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
dahlstrom-g/intellij-community
platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/ImlReplaceBySourceTest.kt
3
6440
// 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 import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.rules.ProjectModelRule import com.intellij.testFramework.rules.TempDirectory import com.intellij.workspaceModel.ide.impl.jps.serialization.CachingJpsFileContentReader import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsProjectEntitiesLoader import com.intellij.workspaceModel.ide.impl.jps.serialization.TestErrorReporter import com.intellij.workspaceModel.ide.impl.jps.serialization.asConfigLocation import com.intellij.workspaceModel.storage.EntityChange import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.api.JavaSourceRootEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.SourceRootEntity import com.intellij.workspaceModel.storage.checkConsistency import com.intellij.workspaceModel.storage.impl.url.toVirtualFileUrl import com.intellij.workspaceModel.storage.toBuilder import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jetbrains.jps.model.serialization.PathMacroUtil import org.junit.* import java.io.File class ImlReplaceBySourceTest { @Rule @JvmField val projectModel = ProjectModelRule(true) private lateinit var virtualFileManager: VirtualFileUrlManager @Before fun setUp() { virtualFileManager = VirtualFileUrlManager.getInstance(projectModel.project) } @Test fun sampleProject() { val projectDir = File(PathManagerEx.getCommunityHomePath(), "jps/model-serialization/testData/sampleProject") replaceBySourceFullReplace(projectDir) } @Test fun communityProject() { val projectDir = File(PathManagerEx.getCommunityHomePath()) replaceBySourceFullReplace(projectDir) } @Test fun addSourceRootToModule() { val moduleFile = temp.newFile("a.iml") moduleFile.writeText(""" <module type="JAVA_MODULE" version="4"> <component name="NewModuleRootManager" inherit-compiler-output="true"> <exclude-output /> <content url="file://${'$'}MODULE_DIR${'$'}"> <sourceFolder url="file://${'$'}MODULE_DIR${'$'}/src" isTestSource="false" /> <sourceFolder url="file://${'$'}MODULE_DIR${'$'}/testSrc" isTestSource="true" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="kotlin-stdlib-jdk8" level="project" /> </component> </module> """.trimIndent()) val projectDir = temp.root.toVirtualFileUrl(virtualFileManager) val configLocation = JpsProjectConfigLocation.DirectoryBased(projectDir, projectDir.append(PathMacroUtil.DIRECTORY_STORE_NAME)) var builder = MutableEntityStorage.create() JpsProjectEntitiesLoader.loadModule(moduleFile.toPath(), configLocation, builder, TestErrorReporter, virtualFileManager) moduleFile.writeText(""" <module type="JAVA_MODULE" version="4"> <component name="NewModuleRootManager" inherit-compiler-output="true"> <exclude-output /> <content url="file://${'$'}MODULE_DIR${'$'}"> <sourceFolder url="file://${'$'}MODULE_DIR${'$'}/src" isTestSource="false" /> <sourceFolder url="file://${'$'}MODULE_DIR${'$'}/src2" generated="true" /> <sourceFolder url="file://${'$'}MODULE_DIR${'$'}/testSrc" isTestSource="true" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> </component> </module> """.trimIndent()) val replaceWith = MutableEntityStorage.create() val source = builder.entities(ModuleEntity::class.java).first().entitySource as JpsFileEntitySource.FileInDirectory JpsProjectEntitiesLoader.loadModule(moduleFile.toPath(), source, configLocation, replaceWith, TestErrorReporter, virtualFileManager) val before = builder.toSnapshot() builder = before.toBuilder() builder.replaceBySource({ true }, replaceWith.toSnapshot()) val changes = builder.collectChanges(before).values.flatten() Assert.assertEquals(5, changes.size) val moduleChange = changes.filterIsInstance<EntityChange.Replaced<ModuleEntity>>().single() Assert.assertEquals(3, moduleChange.oldEntity.dependencies.size) Assert.assertEquals(2, moduleChange.newEntity.dependencies.size) // Changes 1 & 2 handle source roots ordering [ModuleSerializersFactory.SourceRootOrderEntry] @Suppress("USELESS_IS_CHECK") val sourceRootChange = changes.filterIsInstance<EntityChange.Added<SourceRootEntity>>().single { it.entity is SourceRootEntity } @Suppress("USELESS_IS_CHECK") val javaSourceRootChange = changes.filterIsInstance<EntityChange.Added<JavaSourceRootEntity>>().single { it.entity is JavaSourceRootEntity } Assert.assertEquals(File(temp.root, "src2").toVirtualFileUrl(virtualFileManager).url, sourceRootChange.entity.url.url) Assert.assertEquals(true, javaSourceRootChange.entity.generated) } private fun replaceBySourceFullReplace(projectFile: File) { var storageBuilder1 = MutableEntityStorage.create() val data = com.intellij.workspaceModel.ide.impl.jps.serialization.loadProject(projectFile.asConfigLocation(virtualFileManager), storageBuilder1, virtualFileManager) val storageBuilder2 = MutableEntityStorage.create() val reader = CachingJpsFileContentReader(projectFile.asConfigLocation(virtualFileManager)) data.loadAll(reader, storageBuilder2, TestErrorReporter, null) val before = storageBuilder1.toSnapshot() storageBuilder1 = before.toBuilder() storageBuilder1.checkConsistency() storageBuilder1.replaceBySource(sourceFilter = { true }, replaceWith = storageBuilder2.toSnapshot()) storageBuilder1.checkConsistency() val changes = storageBuilder1.collectChanges(before) Assert.assertTrue(changes.toString(), changes.isEmpty()) } @Rule @JvmField val temp = TempDirectory() companion object { @JvmField @ClassRule val appRule = ApplicationRule() } }
apache-2.0
0e734a165b8621f98921551e5d5d4dd7
45
144
0.742547
5
false
true
false
false
androidx/androidx
compose/ui/ui-text/src/test/java/androidx/compose/ui/text/input/PasswordVisualTransformationTest.kt
3
2123
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.input import androidx.compose.ui.text.AnnotatedString import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class PasswordVisualTransformationTest { @Test fun check_visual_output_is_masked_with_asterisk() { val transformation = PasswordVisualTransformation(mask = '*') val text = AnnotatedString("12345") val transformedText = transformation.filter(text) val visualText = transformedText.text val offsetMapping = transformedText.offsetMapping assertThat(visualText.text).isEqualTo("*****") for (i in 0..visualText.text.length) { assertThat(offsetMapping.originalToTransformed(i)).isEqualTo(i) assertThat(offsetMapping.transformedToOriginal(i)).isEqualTo(i) } } @Test fun check_visual_output_is_masked_with_default() { val filter = PasswordVisualTransformation() val text = AnnotatedString("1234567890") val transformedText = filter.filter(text) val visualText = transformedText.text val offsetMapping = transformedText.offsetMapping assertThat(visualText.text).isEqualTo("\u2022".repeat(10)) for (i in 0..visualText.text.length) { assertThat(offsetMapping.originalToTransformed(i)).isEqualTo(i) assertThat(offsetMapping.transformedToOriginal(i)).isEqualTo(i) } } }
apache-2.0
84690cb76017d1f65dd75e4fdbb2ae2a
36.928571
75
0.7122
4.35041
false
true
false
false
androidx/androidx
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/window/PopupLayoutTest.kt
3
11254
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.window import android.view.View import android.view.ViewGroup import android.view.WindowManager import androidx.compose.runtime.remember import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.layout.AlignmentLine import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.platform.LocalView import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection 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 import java.util.UUID /** * Tests for the internal [PopupLayout] view used by [Popup]. * When adding new tests, consider writing the tests against the [Popup] composable directly first, * since that's the public API, and only adding tests here if the tests need to interact in ways * that aren't easily supported by the compose test APIs. */ @MediumTest @RunWith(AndroidJUnit4::class) class PopupLayoutTest { @get:Rule val rule = createComposeRule() @Test fun canCalculatePosition_onlyWhenSizeAndCoordinatesAreAvailable() { val layout = createPopupLayout() assertThat(layout.canCalculatePosition).isFalse() // Only size available. layout.popupContentSize = IntSize.Zero assertThat(layout.canCalculatePosition).isFalse() // Only coordinates available. layout.popupContentSize = null layout.updateParentLayoutCoordinates(NoopLayoutCoordinates) assertThat(layout.canCalculatePosition).isFalse() // Everything available. layout.popupContentSize = IntSize.Zero assertThat(layout.canCalculatePosition).isTrue() } @Test fun positionUpdated_whenCoordinatesUpdated() { val coordinates = MutableLayoutCoordinates() val layout = createPopupLayout( positionProvider = object : PopupPositionProvider { override fun calculatePosition( anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize ): IntOffset = anchorBounds.topLeft }, ) layout.popupContentSize = IntSize.Zero assertThat(layout.params.x).isEqualTo(0) assertThat(layout.params.y).isEqualTo(0) coordinates.windowOffset = Offset(50f, 50f) layout.updateParentLayoutCoordinates(coordinates) assertThat(layout.params.x).isEqualTo(50) assertThat(layout.params.y).isEqualTo(50) } @Test fun positionNotUpdated_whenCoordinatesUpdated_withSameParentBounds() { var paramUpdateCount = 0 val layout = createPopupLayout( positionProvider = object : PopupPositionProvider { override fun calculatePosition( anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize ): IntOffset = anchorBounds.topLeft }, popupLayoutHelper = object : NoopPopupLayoutHelper() { override fun updateViewLayout( windowManager: WindowManager, popupView: View, params: ViewGroup.LayoutParams ) { paramUpdateCount++ } } ) // Set size before coordinates to match the order that the compose runtime uses. layout.popupContentSize = IntSize.Zero layout.updateParentLayoutCoordinates(MutableLayoutCoordinates()) assertThat(paramUpdateCount).isEqualTo(1) // Different coordinates object but with the same values, so shouldn't trigger a position // update. layout.updateParentLayoutCoordinates(MutableLayoutCoordinates()) assertThat(paramUpdateCount).isEqualTo(1) } @Test fun positionNotUpdated_onParentBoundsUpdateRequested_withSameParentBounds() { var paramUpdateCount = 0 val layout = createPopupLayout( positionProvider = object : PopupPositionProvider { override fun calculatePosition( anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize ): IntOffset = anchorBounds.topLeft }, popupLayoutHelper = object : NoopPopupLayoutHelper() { override fun updateViewLayout( windowManager: WindowManager, popupView: View, params: ViewGroup.LayoutParams ) { paramUpdateCount++ } } ) // Set size before coordinates to match the order that the compose runtime uses. layout.popupContentSize = IntSize.Zero layout.updateParentLayoutCoordinates(MutableLayoutCoordinates()) assertThat(paramUpdateCount).isEqualTo(1) layout.updateParentBounds() assertThat(paramUpdateCount).isEqualTo(1) } @Test fun positionUpdated_onParentBoundsUpdateRequested_withDifferentParentBounds() { var paramUpdateCount = 0 val coordinates = MutableLayoutCoordinates() val layout = createPopupLayout( positionProvider = object : PopupPositionProvider { override fun calculatePosition( anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize ): IntOffset = anchorBounds.topLeft }, popupLayoutHelper = object : NoopPopupLayoutHelper() { override fun updateViewLayout( windowManager: WindowManager, popupView: View, params: ViewGroup.LayoutParams ) { paramUpdateCount++ } } ) // Set size before coordinates to match the order that the compose runtime uses. layout.popupContentSize = IntSize.Zero layout.updateParentLayoutCoordinates(coordinates) assertThat(layout.params.x).isEqualTo(0) assertThat(layout.params.y).isEqualTo(0) coordinates.windowOffset = Offset(50f, 50f) layout.updateParentBounds() assertThat(layout.params.x).isEqualTo(50) assertThat(layout.params.y).isEqualTo(50) } private fun createPopupLayout( onDismissRequest: (() -> Unit)? = null, properties: PopupProperties = PopupProperties(), density: Density = rule.density, positionProvider: PopupPositionProvider = ZeroPositionProvider, popupLayoutHelper: PopupLayoutHelper = NoopPopupLayoutHelper() ): PopupLayout { lateinit var layout: PopupLayout rule.setContent { val view = LocalView.current remember { PopupLayout( onDismissRequest = onDismissRequest, properties = properties, testTag = "test popup", composeView = view, density = density, initialPositionProvider = positionProvider, popupId = UUID.randomUUID(), popupLayoutHelper = popupLayoutHelper ).also { layout = it } } } return rule.runOnIdle { layout } } private companion object { val ZeroPositionProvider = object : PopupPositionProvider { override fun calculatePosition( anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize ): IntOffset = IntOffset.Zero } val NoopLayoutCoordinates: LayoutCoordinates = MutableLayoutCoordinates() /** * An implementation of [LayoutCoordinates] that allows explicitly setting values but only * supports the minimum required subset of operations that [PopupLayout] uses. */ private class MutableLayoutCoordinates : LayoutCoordinates { override var size: IntSize = IntSize.Zero override val providedAlignmentLines: Set<AlignmentLine> = emptySet() override var parentLayoutCoordinates: LayoutCoordinates? = null override var parentCoordinates: LayoutCoordinates? = null override var isAttached: Boolean = false var windowOffset: Offset = Offset.Zero override fun windowToLocal(relativeToWindow: Offset): Offset = relativeToWindow - windowOffset override fun localToWindow(relativeToLocal: Offset): Offset = windowOffset + relativeToLocal override fun localToRoot(relativeToLocal: Offset): Offset = throw UnsupportedOperationException() override fun localPositionOf( sourceCoordinates: LayoutCoordinates, relativeToSource: Offset ): Offset = throw UnsupportedOperationException() override fun localBoundingBoxOf( sourceCoordinates: LayoutCoordinates, clipBounds: Boolean ): Rect = throw UnsupportedOperationException() override fun get(alignmentLine: AlignmentLine): Int = throw UnsupportedOperationException() } private open class NoopPopupLayoutHelper : PopupLayoutHelper { override fun getWindowVisibleDisplayFrame( composeView: View, outRect: android.graphics.Rect ) { // do nothing } override fun setGestureExclusionRects(composeView: View, width: Int, height: Int) { // do nothing } override fun updateViewLayout( windowManager: WindowManager, popupView: View, params: ViewGroup.LayoutParams ) { // do nothing } } } }
apache-2.0
1b6b3a8b67b18e27b77381de8f9ffe45
36.264901
99
0.630709
5.780175
false
true
false
false
androidx/androidx
compose/ui/ui-text/src/test/java/androidx/compose/ui/text/AnnotatedStringBuilderTest.kt
3
41128
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString.Range import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.em import androidx.compose.ui.unit.sp import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class AnnotatedStringBuilderTest { @Test fun defaultConstructor() { val annotatedString = AnnotatedString.Builder().toAnnotatedString() assertThat(annotatedString.text).isEmpty() assertThat(annotatedString.spanStyles).isEmpty() assertThat(annotatedString.paragraphStyles).isEmpty() } @Test fun constructorWithString() { val text = "a" val annotatedString = AnnotatedString.Builder(text).toAnnotatedString() assertThat(annotatedString.text).isEqualTo(text) assertThat(annotatedString.spanStyles).isEmpty() assertThat(annotatedString.paragraphStyles).isEmpty() } @Test fun constructorWithAnnotatedString_hasSameAnnotatedStringAttributes() { val text = createAnnotatedString(text = "a") val annotatedString = AnnotatedString.Builder(text).toAnnotatedString() assertThat(annotatedString.text).isEqualTo(text.text) assertThat(annotatedString.spanStyles).isEqualTo(text.spanStyles) assertThat(annotatedString.paragraphStyles).isEqualTo(text.paragraphStyles) } @Test fun addStyle_withSpanStyle_addsStyle() { val style = SpanStyle(color = Color.Red) val range = TextRange(0, 1) val annotatedString = with(AnnotatedString.Builder("ab")) { addStyle(style, range.start, range.end) toAnnotatedString() } val expectedSpanStyles = listOf( Range(style, range.start, range.end) ) assertThat(annotatedString.paragraphStyles).isEmpty() assertThat(annotatedString.spanStyles).isEqualTo(expectedSpanStyles) } @Test fun addStyle_withParagraphStyle_addsStyle() { val style = ParagraphStyle(lineHeight = 30.sp) val range = TextRange(0, 1) val annotatedString = with(AnnotatedString.Builder("ab")) { addStyle(style, range.start, range.end) toAnnotatedString() } val expectedParagraphStyles = listOf( Range(style, range.start, range.end) ) assertThat(annotatedString.spanStyles).isEmpty() assertThat(annotatedString.paragraphStyles).isEqualTo(expectedParagraphStyles) } @Test fun append_withString_appendsTheText() { val text = "a" val appendedText = "b" val annotatedString = with(AnnotatedString.Builder(text)) { append(appendedText) toAnnotatedString() } val expectedString = "$text$appendedText" assertThat(annotatedString.text).isEqualTo(expectedString) assertThat(annotatedString.spanStyles).isEmpty() assertThat(annotatedString.paragraphStyles).isEmpty() } @Test fun append_withString_andMultipleCalls_appendsAllOfTheText() { val annotatedString = with(AnnotatedString.Builder("a")) { append("b") append("c") toAnnotatedString() } assertThat(annotatedString.text).isEqualTo("abc") } @Test fun append_withAnnotatedString_appendsTheText() { val color = Color.Red val text = "a" val lineHeight = 20.sp val annotatedString = createAnnotatedString( text = text, color = color, lineHeight = lineHeight ) val appendedColor = Color.Blue val appendedText = "b" val appendedLineHeight = 30.sp val appendedAnnotatedString = createAnnotatedString( text = appendedText, color = appendedColor, lineHeight = appendedLineHeight ) val buildResult = with(AnnotatedString.Builder(annotatedString)) { append(appendedAnnotatedString) toAnnotatedString() } val expectedString = "$text$appendedText" val expectedSpanStyles = listOf( Range( item = SpanStyle(color), start = 0, end = text.length ), Range( item = SpanStyle(appendedColor), start = text.length, end = expectedString.length ) ) val expectedParagraphStyles = listOf( Range( item = ParagraphStyle(lineHeight = lineHeight), start = 0, end = text.length ), Range( item = ParagraphStyle(lineHeight = appendedLineHeight), start = text.length, end = expectedString.length ) ) assertThat(buildResult.text).isEqualTo(expectedString) assertThat(buildResult.spanStyles).isEqualTo(expectedSpanStyles) assertThat(buildResult.paragraphStyles).isEqualTo(expectedParagraphStyles) } @Test fun append_withAnnotatedStringAndRange_appendsTheText() { val text = "a" val annotatedString = AnnotatedString( text = text, spanStyles = listOf( text.inclusiveRangeOf('a', 'a', item = SpanStyle(color = Color.Red)) ), paragraphStyles = listOf( text.inclusiveRangeOf('a', 'a', item = ParagraphStyle(lineHeight = 20.sp)) ), annotations = listOf( text.inclusiveRangeOf('a', 'a', item = "prefix", tag = "prefixTag") ) ) // We want to test the cross product of the following cases: // - Range beginning at start, ending at end-1, completely overlapping [start,end), and // completely inside (start, end-1). // - SpanStyle, ParagraphStyle, annotation val appendedText = "bcdef" val appendedSpanStyles = listOf( appendedText.inclusiveRangeOf('b', 'f', item = SpanStyle(color = Color.Blue)), appendedText.inclusiveRangeOf('c', 'f', item = SpanStyle(color = Color.Green)), appendedText.inclusiveRangeOf('b', 'e', item = SpanStyle(color = Color.Yellow)), appendedText.inclusiveRangeOf('c', 'e', item = SpanStyle(color = Color.Magenta)), ) // Paragraph styles can't overlap. val appendedParagraphStyles = listOf( appendedText.inclusiveRangeOf('b', 'b', item = ParagraphStyle(lineHeight = 30.sp)), appendedText.inclusiveRangeOf('c', 'c', item = ParagraphStyle(lineHeight = 40.sp)), appendedText.inclusiveRangeOf('d', 'd', item = ParagraphStyle(lineHeight = 50.sp)), appendedText.inclusiveRangeOf('e', 'e', item = ParagraphStyle(lineHeight = 60.sp)), appendedText.inclusiveRangeOf('f', 'f', item = ParagraphStyle(lineHeight = 70.sp)), ) val appendedAnnotations = listOf( appendedText.inclusiveRangeOf('b', 'f', item = 1, tag = "tag1"), appendedText.inclusiveRangeOf('c', 'f', item = 2, tag = "tag2"), appendedText.inclusiveRangeOf('b', 'e', item = 3, tag = "tag3"), appendedText.inclusiveRangeOf('c', 'e', item = 4, tag = "tag4"), ) val appendedAnnotatedString = AnnotatedString( text = appendedText, spanStyles = appendedSpanStyles, paragraphStyles = appendedParagraphStyles, annotations = appendedAnnotations ) val buildResult = with(AnnotatedString.Builder(annotatedString)) { // Append everything but the first and last characters of the appended string. append( appendedAnnotatedString, start = appendedText.indexOf('c'), end = appendedText.indexOf('e') + 1 ) toAnnotatedString() } val expectedString = "acde" val expectedSpanStyles = listOf( expectedString.inclusiveRangeOf('a', 'a', item = SpanStyle(color = Color.Red)), expectedString.inclusiveRangeOf('c', 'e', item = SpanStyle(color = Color.Blue)), expectedString.inclusiveRangeOf('c', 'e', item = SpanStyle(color = Color.Green)), expectedString.inclusiveRangeOf('c', 'e', item = SpanStyle(color = Color.Yellow)), expectedString.inclusiveRangeOf('c', 'e', item = SpanStyle(color = Color.Magenta)), ) val expectedParagraphStyles = listOf( expectedString.inclusiveRangeOf('a', 'a', item = ParagraphStyle(lineHeight = 20.sp)), expectedString.inclusiveRangeOf('c', 'c', item = ParagraphStyle(lineHeight = 40.sp)), expectedString.inclusiveRangeOf('d', 'd', item = ParagraphStyle(lineHeight = 50.sp)), expectedString.inclusiveRangeOf('e', 'e', item = ParagraphStyle(lineHeight = 60.sp)), ) val expectedAnnotations = listOf( expectedString.inclusiveRangeOf('a', 'a', item = "prefix", tag = "prefixTag"), expectedString.inclusiveRangeOf('c', 'e', item = 1, tag = "tag1"), expectedString.inclusiveRangeOf('c', 'e', item = 2, tag = "tag2"), expectedString.inclusiveRangeOf('c', 'e', item = 3, tag = "tag3"), expectedString.inclusiveRangeOf('c', 'e', item = 4, tag = "tag4"), ) assertThat(buildResult.text).isEqualTo(expectedString) assertThat(buildResult.spanStyles).isEqualTo(expectedSpanStyles) assertThat(buildResult.paragraphStyles).isEqualTo(expectedParagraphStyles) assertThat(buildResult.annotations).isEqualTo(expectedAnnotations) } @Test fun append_withCharSequence_appendsTheText_whenAnnotatedString() { val color = Color.Red val text = "a" val lineHeight = 20.sp val annotatedString = createAnnotatedString( text = text, color = color, lineHeight = lineHeight ) val appendedColor = Color.Blue val appendedText = "b" val appendedLineHeight = 30.sp val appendedAnnotatedString = createAnnotatedString( text = appendedText, color = appendedColor, lineHeight = appendedLineHeight ) val buildResult = with(AnnotatedString.Builder(annotatedString)) { // Cast forces dispatch to the more general method, using the return value ensures // the right method was selected. append(appendedAnnotatedString as CharSequence) .toAnnotatedString() } val expectedString = "$text$appendedText" val expectedSpanStyles = listOf( Range( item = SpanStyle(color), start = 0, end = text.length ), Range( item = SpanStyle(appendedColor), start = text.length, end = expectedString.length ) ) val expectedParagraphStyles = listOf( Range( item = ParagraphStyle(lineHeight = lineHeight), start = 0, end = text.length ), Range( item = ParagraphStyle(lineHeight = appendedLineHeight), start = text.length, end = expectedString.length ) ) assertThat(buildResult.text).isEqualTo(expectedString) assertThat(buildResult.spanStyles).isEqualTo(expectedSpanStyles) assertThat(buildResult.paragraphStyles).isEqualTo(expectedParagraphStyles) } @Test fun append_withCharSequence_appendsTheText_whenNotAnnotatedString() { val text = "a" val appendedText = object : CharSequence by "bc" {} val annotatedString = with(AnnotatedString.Builder(text)) { append(appendedText) toAnnotatedString() } val expectedString = "abc" assertThat(annotatedString.text).isEqualTo(expectedString) assertThat(annotatedString.spanStyles).isEmpty() assertThat(annotatedString.paragraphStyles).isEmpty() } // The edge cases for range-based AnnotatedString append are tested in depth by other tests that // just call the append(AnnotatedString, Int, Int) method – the CharSequence overload just // delegates to that, so this test is much more basic. @OptIn(ExperimentalTextApi::class) @Test fun append_withCharSequenceAndRange_appendsTheText_whenAnnotatedString() { val color = Color.Red val text = "a" val lineHeight = 20.sp val annotatedString = createAnnotatedString( text = text, color = color, lineHeight = lineHeight ) // b-g will have a style span. // c-f will have a paragraph span. // de will have an annotation. val appendedText = "b(c(de)f)g" val appendedColor = Color.Blue val appendedLineHeight = 30.sp val appendedAnnotationTag = "tag" val appendedAnnotation = "annotation" val appendedAnnotatedString = buildAnnotatedString { withStyle(SpanStyle(color = appendedColor)) { append("b(") withStyle(ParagraphStyle(lineHeight = appendedLineHeight)) { append("c(") withAnnotation(appendedAnnotationTag, appendedAnnotation) { append("de") } append(")f") } append(")g") } } val buildResult = with(AnnotatedString.Builder(annotatedString)) { // Cast forces dispatch to the more general method, using the return value ensures // the right method was selected. append( appendedAnnotatedString as CharSequence, start = appendedText.indexOf('c'), end = appendedText.indexOf('f') + 1 ).toAnnotatedString() } val expectedString = "ac(de)f" val expectedSpanStyles = listOf( Range( item = SpanStyle(color), start = 0, end = text.length ), Range( item = SpanStyle(appendedColor), start = text.length, end = expectedString.length ) ) val expectedParagraphStyles = listOf( Range( item = ParagraphStyle(lineHeight = lineHeight), start = 0, end = text.length ), Range( item = ParagraphStyle(lineHeight = appendedLineHeight), start = text.length, end = expectedString.length ) ) val expectedAnnotations = listOf( Range( tag = appendedAnnotationTag, item = appendedAnnotation, start = expectedString.indexOf('d'), end = expectedString.indexOf('e') + 1 ) ) assertThat(buildResult.text).isEqualTo(expectedString) assertThat(buildResult.spanStyles).isEqualTo(expectedSpanStyles) assertThat(buildResult.paragraphStyles).isEqualTo(expectedParagraphStyles) assertThat(buildResult.annotations).isEqualTo(expectedAnnotations) } @Test fun append_withCharSequenceAndRange_appendsTheText_whenNotAnnotatedString() { val text = "a" val appendedText = object : CharSequence by "bcde" {} val annotatedString = with(AnnotatedString.Builder(text)) { append(appendedText, 1, 3) toAnnotatedString() } val expectedString = "acd" assertThat(annotatedString.text).isEqualTo(expectedString) assertThat(annotatedString.spanStyles).isEmpty() assertThat(annotatedString.paragraphStyles).isEmpty() } @Test fun pushStyle() { val text = "Test" val style = SpanStyle(color = Color.Red) val buildResult = AnnotatedString.Builder().apply { pushStyle(style) append(text) pop() }.toAnnotatedString() assertThat(buildResult.text).isEqualTo(text) assertThat(buildResult.spanStyles).hasSize(1) assertThat(buildResult.spanStyles[0].item).isEqualTo(style) assertThat(buildResult.spanStyles[0].start).isEqualTo(0) assertThat(buildResult.spanStyles[0].end).isEqualTo(buildResult.length) } @Test fun pushStyle_without_pop() { val styles = arrayOf( SpanStyle(color = Color.Red), SpanStyle(fontStyle = FontStyle.Italic), SpanStyle(fontWeight = FontWeight.Bold) ) val buildResult = with(AnnotatedString.Builder()) { styles.forEachIndexed { index, spanStyle -> // pop is intentionally not called here pushStyle(spanStyle) append("Style$index") } toAnnotatedString() } assertThat(buildResult.text).isEqualTo("Style0Style1Style2") assertThat(buildResult.spanStyles).hasSize(3) styles.forEachIndexed { index, spanStyle -> assertThat(buildResult.spanStyles[index].item).isEqualTo(spanStyle) assertThat(buildResult.spanStyles[index].end).isEqualTo(buildResult.length) } assertThat(buildResult.spanStyles[0].start).isEqualTo(0) assertThat(buildResult.spanStyles[1].start).isEqualTo("Style0".length) assertThat(buildResult.spanStyles[2].start).isEqualTo("Style0Style1".length) } @Test fun pushStyle_with_multiple_styles() { val spanStyle1 = SpanStyle(color = Color.Red) val spanStyle2 = SpanStyle(fontStyle = FontStyle.Italic) val buildResult = with(AnnotatedString.Builder()) { pushStyle(spanStyle1) append("Test") pushStyle(spanStyle2) append(" me") pop() pop() toAnnotatedString() } assertThat(buildResult.text).isEqualTo("Test me") assertThat(buildResult.spanStyles).hasSize(2) assertThat(buildResult.spanStyles[0].item).isEqualTo(spanStyle1) assertThat(buildResult.spanStyles[0].start).isEqualTo(0) assertThat(buildResult.spanStyles[0].end).isEqualTo(buildResult.length) assertThat(buildResult.spanStyles[1].item).isEqualTo(spanStyle2) assertThat(buildResult.spanStyles[1].start).isEqualTo("Test".length) assertThat(buildResult.spanStyles[1].end).isEqualTo(buildResult.length) } @Test fun pushStyle_with_multiple_styles_on_top_of_each_other() { val styles = arrayOf( SpanStyle(color = Color.Red), SpanStyle(fontStyle = FontStyle.Italic), SpanStyle(fontWeight = FontWeight.Bold) ) val buildResult = with(AnnotatedString.Builder()) { styles.forEach { spanStyle -> // pop is intentionally not called here pushStyle(spanStyle) } toAnnotatedString() } assertThat(buildResult.text).isEmpty() assertThat(buildResult.spanStyles).hasSize(3) styles.forEachIndexed { index, spanStyle -> assertThat(buildResult.spanStyles[index].item).isEqualTo(spanStyle) assertThat(buildResult.spanStyles[index].start).isEqualTo(buildResult.length) assertThat(buildResult.spanStyles[index].end).isEqualTo(buildResult.length) } } @Test fun pushStyle_with_multiple_stacks_should_construct_styles_in_the_same_order() { val styles = arrayOf( SpanStyle(color = Color.Red), SpanStyle(fontStyle = FontStyle.Italic), SpanStyle(fontWeight = FontWeight.Bold), SpanStyle(letterSpacing = 1.2.em) ) val buildResult = with(AnnotatedString.Builder()) { pushStyle(styles[0]) append("layer1-1") pushStyle(styles[1]) append("layer2-1") pushStyle(styles[2]) append("layer3-1") pop() pushStyle(styles[3]) append("layer3-2") pop() append("layer2-2") pop() append("layer1-2") toAnnotatedString() } assertThat(buildResult.spanStyles).hasSize(4) styles.forEachIndexed { index, spanStyle -> assertThat(buildResult.spanStyles[index].item).isEqualTo(spanStyle) } } @Test fun pushStyle_with_multiple_nested_styles_should_return_styles_in_same_order() { val styles = arrayOf( SpanStyle(color = Color.Red), SpanStyle(fontStyle = FontStyle.Italic), SpanStyle(fontWeight = FontWeight.Bold), SpanStyle(letterSpacing = 1.2.em) ) val buildResult = with(AnnotatedString.Builder()) { pushStyle(styles[0]) append("layer1-1") pushStyle(styles[1]) append("layer2-1") pop() pushStyle(styles[2]) append("layer2-2") pushStyle(styles[3]) append("layer3-1") pop() append("layer2-3") pop() append("layer1-2") pop() toAnnotatedString() } assertThat(buildResult.spanStyles).hasSize(4) styles.forEachIndexed { index, spanStyle -> assertThat(buildResult.spanStyles[index].item).isEqualTo(spanStyle) } } @Test(expected = IllegalStateException::class) fun pop_when_empty_does_not_throw_exception() { AnnotatedString.Builder().pop() } @Test fun pop_in_the_middle() { val spanStyle1 = SpanStyle(color = Color.Red) val spanStyle2 = SpanStyle(fontStyle = FontStyle.Italic) val buildResult = with(AnnotatedString.Builder()) { append("Style0") pushStyle(spanStyle1) append("Style1") pop() pushStyle(spanStyle2) append("Style2") pop() append("Style3") toAnnotatedString() } assertThat(buildResult.text).isEqualTo("Style0Style1Style2Style3") assertThat(buildResult.spanStyles).hasSize(2) // the order is first applied is in the second assertThat(buildResult.spanStyles[0].item).isEqualTo((spanStyle1)) assertThat(buildResult.spanStyles[0].start).isEqualTo(("Style0".length)) assertThat(buildResult.spanStyles[0].end).isEqualTo(("Style0Style1".length)) assertThat(buildResult.spanStyles[1].item).isEqualTo((spanStyle2)) assertThat(buildResult.spanStyles[1].start).isEqualTo(("Style0Style1".length)) assertThat(buildResult.spanStyles[1].end).isEqualTo(("Style0Style1Style2".length)) } @Test fun push_increments_the_style_index() { val style = SpanStyle(color = Color.Red) with(AnnotatedString.Builder()) { val styleIndex0 = pushStyle(style) val styleIndex1 = pushStyle(style) val styleIndex2 = pushStyle(style) assertThat(styleIndex0).isEqualTo(0) assertThat(styleIndex1).isEqualTo(1) assertThat(styleIndex2).isEqualTo(2) } } @Test fun push_reduces_the_style_index_after_pop() { val spanStyle = SpanStyle(color = Color.Red) val paragraphStyle = ParagraphStyle(lineHeight = 18.sp) with(AnnotatedString.Builder()) { val styleIndex0 = pushStyle(spanStyle) val styleIndex1 = pushStyle(spanStyle) assertThat(styleIndex0).isEqualTo(0) assertThat(styleIndex1).isEqualTo(1) // a pop should reduce the next index to one pop() val paragraphStyleIndex = pushStyle(paragraphStyle) assertThat(paragraphStyleIndex).isEqualTo(1) } } @Test(expected = IllegalStateException::class) fun pop_until_throws_exception_for_invalid_index() { val style = SpanStyle(color = Color.Red) with(AnnotatedString.Builder()) { val styleIndex = pushStyle(style) // should throw exception pop(styleIndex + 1) } } @Test fun pop_until_index_pops_correctly() { val style = SpanStyle(color = Color.Red) with(AnnotatedString.Builder()) { pushStyle(style) // store the index of second push val styleIndex = pushStyle(style) pushStyle(style) // pop up to and including styleIndex pop(styleIndex) // push again to get a new index to compare val newStyleIndex = pushStyle(style) assertThat(newStyleIndex).isEqualTo(styleIndex) } } @Test fun withStyle_applies_style_to_block() { val style = SpanStyle(color = Color.Red) val buildResult = with(AnnotatedString.Builder()) { withStyle(style) { append("Style") } toAnnotatedString() } assertThat(buildResult.paragraphStyles).isEmpty() assertThat(buildResult.spanStyles).isEqualTo( listOf(Range(style, 0, buildResult.length)) ) } @Test fun withStyle_with_paragraphStyle_applies_style_to_block() { val style = ParagraphStyle(lineHeight = 18.sp) val buildResult = with(AnnotatedString.Builder()) { withStyle(style) { append("Style") } toAnnotatedString() } assertThat(buildResult.spanStyles).isEmpty() assertThat(buildResult.paragraphStyles).isEqualTo( listOf(Range(style, 0, buildResult.length)) ) } @Test fun append_char_appends() { val buildResult = with(AnnotatedString.Builder("a")) { append('b') append('c') toAnnotatedString() } assertThat(buildResult).isEqualTo(AnnotatedString("abc")) } @Test fun builderLambda() { val text1 = "Hello" val text2 = "World" val spanStyle1 = SpanStyle(color = Color.Red) val spanStyle2 = SpanStyle(color = Color.Blue) val paragraphStyle1 = ParagraphStyle(textAlign = TextAlign.Right) val paragraphStyle2 = ParagraphStyle(textAlign = TextAlign.Right) val buildResult = buildAnnotatedString { withStyle(paragraphStyle1) { withStyle(spanStyle1) { append(text1) } } append(" ") pushStyle(paragraphStyle2) pushStyle(spanStyle2) append(text2) pop() } val expectedString = "$text1 $text2" val expectedSpanStyles = listOf( Range(spanStyle1, 0, text1.length), Range(spanStyle2, text1.length + 1, expectedString.length) ) val expectedParagraphStyles = listOf( Range(paragraphStyle1, 0, text1.length), Range(paragraphStyle2, text1.length + 1, expectedString.length) ) assertThat(buildResult.text).isEqualTo(expectedString) assertThat(buildResult.spanStyles).isEqualTo(expectedSpanStyles) assertThat(buildResult.paragraphStyles).isEqualTo(expectedParagraphStyles) } @Test fun toAnnotatedString_calling_twice_creates_equal_annotated_strings() { val builder = AnnotatedString.Builder().apply { // pushed styles not popped on purpose pushStyle(SpanStyle(color = Color.Red)) append("Hello") pushStyle(SpanStyle(color = Color.Blue)) append("World") } assertThat(builder.toAnnotatedString()).isEqualTo(builder.toAnnotatedString()) } @Test fun can_call_other_functions_after_toAnnotatedString() { val builder = AnnotatedString.Builder().apply { // pushed styles not popped on purpose pushStyle(SpanStyle(fontSize = 12.sp)) append("Hello") pushStyle(SpanStyle(fontSize = 16.sp)) append("World") } val buildResult1 = builder.toAnnotatedString() val buildResult2 = with(builder) { pop() pop() pushStyle(SpanStyle(fontSize = 18.sp)) append("!") toAnnotatedString() } // buildResult2 should be the same as creating a new AnnotatedString based on the first // result and appending the same values val expectedResult = with(AnnotatedString.Builder(buildResult1)) { withStyle(SpanStyle(fontSize = 18.sp)) { append("!") } toAnnotatedString() } assertThat(buildResult2).isEqualTo(expectedResult) } @Test fun pushAnnotation() { val text = "Test" val annotation = "Annotation" val tag = "tag" val buildResult = AnnotatedString.Builder().apply { pushStringAnnotation(tag, annotation) append(text) pop() }.toAnnotatedString() assertThat(buildResult.text).isEqualTo(text) val stringAnnotations = buildResult.getStringAnnotations(tag, 0, text.length) assertThat(stringAnnotations).hasSize(1) assertThat(stringAnnotations.first()).isEqualTo( Range(annotation, 0, text.length, tag) ) } @Test fun pushAnnotation_multiple_nested() { val annotation1 = "Annotation1" val annotation2 = "Annotation2" val tag = "tag" val buildResult = AnnotatedString.Builder().apply { pushStringAnnotation(tag, annotation1) append("Hello") pushStringAnnotation(tag, annotation2) append("world") pop() append("!") pop() }.toAnnotatedString() // The final result is Helloworld! // [ ] // [ ] assertThat(buildResult.text).isEqualTo("Helloworld!") assertThat(buildResult.getStringAnnotations(tag, 0, 11)).hasSize(2) assertThat(buildResult.getStringAnnotations(tag, 0, 5)).hasSize(1) assertThat(buildResult.getStringAnnotations(tag, 5, 10)).hasSize(2) assertThat(buildResult.getStringAnnotations(tag, 10, 11)).hasSize(1) val annotations = buildResult.getStringAnnotations(tag, 0, 11) assertThat(annotations[0]).isEqualTo( Range(annotation1, 0, 11, tag) ) assertThat(annotations[1]).isEqualTo( Range(annotation2, 5, 10, tag) ) } @Test fun pushAnnotation_multiple_differentTag() { val annotation1 = "Annotation1" val annotation2 = "Annotation2" val tag1 = "tag1" val tag2 = "tag2" val buildResult = AnnotatedString.Builder().apply { pushStringAnnotation(tag1, annotation1) append("Hello") pushStringAnnotation(tag2, annotation2) append("world") pop() append("!") pop() }.toAnnotatedString() // The final result is Helloworld! // [ ] // [ ] assertThat(buildResult.text).isEqualTo("Helloworld!") assertThat(buildResult.getStringAnnotations(tag1, 0, 11)).hasSize(1) assertThat(buildResult.getStringAnnotations(tag1, 0, 5)).hasSize(1) assertThat(buildResult.getStringAnnotations(tag1, 5, 10)).hasSize(1) assertThat(buildResult.getStringAnnotations(tag1, 5, 10).first()) .isEqualTo(Range(annotation1, 0, 11, tag1)) assertThat(buildResult.getStringAnnotations(tag2, 5, 10)).hasSize(1) assertThat(buildResult.getStringAnnotations(tag2, 5, 10).first()) .isEqualTo(Range(annotation2, 5, 10, tag2)) assertThat(buildResult.getStringAnnotations(tag2, 10, 11)).hasSize(0) } @Test fun getAnnotation() { val annotation = "Annotation" val tag = "tag" val buildResult = AnnotatedString.Builder().apply { append("Hello") pushStringAnnotation(tag, annotation) append("World") pop() append("Hello") pushStringAnnotation(tag, annotation) pop() append("World") }.toAnnotatedString() // The final result is: HelloWorldHelloWorld // [ ] // [] assertThat(buildResult.getStringAnnotations(tag, 0, 5)).hasSize(0) assertThat(buildResult.getStringAnnotations(tag, 0, 6)).hasSize(1) assertThat(buildResult.getStringAnnotations(tag, 6, 6)).hasSize(1) assertThat(buildResult.getStringAnnotations(tag, 10, 10)).hasSize(0) assertThat(buildResult.getStringAnnotations(tag, 8, 13)).hasSize(1) assertThat(buildResult.getStringAnnotations(tag, 15, 15)).hasSize(1) assertThat(buildResult.getStringAnnotations(tag, 10, 15)).hasSize(0) assertThat(buildResult.getStringAnnotations(tag, 15, 20)).hasSize(1) } @Test fun getAnnotation_withoutTag_multipleAnnotations() { val annotation1 = "Annotation1" val annotation2 = "Annotation2" val tag1 = "tag1" val tag2 = "tag2" val buildResult = AnnotatedString.Builder().apply { pushStringAnnotation(tag1, annotation1) append("Hello") pushStringAnnotation(tag2, annotation2) append("world") pop() append("!") pop() }.toAnnotatedString() // The final result is Helloworld! // [ ] // [ ] assertThat(buildResult.getStringAnnotations(0, 5)).isEqualTo( listOf(Range(annotation1, 0, 11, tag1)) ) assertThat(buildResult.getStringAnnotations(5, 6)).isEqualTo( listOf( Range(annotation1, 0, 11, tag1), Range(annotation2, 5, 10, tag2) ) ) assertThat(buildResult.getStringAnnotations(10, 11)).isEqualTo( listOf(Range(annotation1, 0, 11, tag1)) ) } @Test fun getAnnotation_separates_ttsAnnotation_and_stringAnnotation() { val annotation1 = VerbatimTtsAnnotation("abc") val annotation2 = "annotation" val tag = "tag" val buildResult = AnnotatedString.Builder().apply { pushTtsAnnotation(annotation1) append("Hello") pushStringAnnotation(tag, annotation2) append("world") pop() append("!") pop() }.toAnnotatedString() // The final result is Helloworld! // [ ] TtsAnnotation // [ ] Range<String> assertThat(buildResult.getTtsAnnotations(0, 5)).isEqualTo( listOf(Range(annotation1, 0, 11, "")) ) assertThat(buildResult.getTtsAnnotations(5, 6)).isEqualTo( listOf(Range(annotation1, 0, 11, "")) ) assertThat(buildResult.getStringAnnotations(0, 5)).isEmpty() assertThat(buildResult.getStringAnnotations(5, 6)).isEqualTo( listOf(Range(annotation2, 5, 10, tag)) ) assertThat(buildResult.getStringAnnotations(10, 11)).isEmpty() } @Test fun getAnnotation_withTag_withTtsAnnotation_withStringAnnotation() { val annotation1 = VerbatimTtsAnnotation("abc") val annotation2 = "annotation" val tag = "tag" val buildResult = AnnotatedString.Builder().apply { pushTtsAnnotation(annotation1) append("Hello") pushStringAnnotation(tag, annotation2) append("world") pop() append("!") pop() }.toAnnotatedString() // The final result is Helloworld! // [ ] TtsAnnotation // [ ] Range<String> assertThat(buildResult.getStringAnnotations(tag, 0, 5)).isEmpty() assertThat(buildResult.getStringAnnotations(tag, 5, 6)).isEqualTo( listOf(Range(annotation2, 5, 10, tag)) ) // The tag doesn't match, return empty list. assertThat(buildResult.getStringAnnotations("tag1", 5, 6)).isEmpty() assertThat(buildResult.getStringAnnotations(tag, 10, 11)).isEmpty() } @OptIn(ExperimentalTextApi::class) @Test fun getAnnotation_separates_urlAnnotation_and_stringAnnotation() { val annotation1 = UrlAnnotation("abc") val annotation2 = "annotation" val tag = "tag" val buildResult = AnnotatedString.Builder().apply { pushUrlAnnotation(annotation1) append("Hello") pushStringAnnotation(tag, annotation2) append("world") pop() append("!") pop() }.toAnnotatedString() // The final result is Helloworld! // [ ] UrlAnnotation // [ ] Range<String> assertThat(buildResult.getUrlAnnotations(0, 5)).isEqualTo( listOf(Range(annotation1, 0, 11, "")) ) assertThat(buildResult.getUrlAnnotations(5, 6)).isEqualTo( listOf(Range(annotation1, 0, 11, "")) ) assertThat(buildResult.getStringAnnotations(0, 5)).isEmpty() assertThat(buildResult.getStringAnnotations(5, 6)).isEqualTo( listOf(Range(annotation2, 5, 10, tag)) ) assertThat(buildResult.getStringAnnotations(10, 11)).isEmpty() } @OptIn(ExperimentalTextApi::class) @Test fun getAnnotation_withTag_withUrlAnnotation_withStringAnnotation() { val annotation1 = UrlAnnotation("abc") val annotation2 = "annotation" val tag = "tag" val buildResult = AnnotatedString.Builder().apply { pushUrlAnnotation(annotation1) append("Hello") pushStringAnnotation(tag, annotation2) append("world") pop() append("!") pop() }.toAnnotatedString() // The final result is Helloworld! // [ ] UrlAnnotation // [ ] Range<String> assertThat(buildResult.getStringAnnotations(tag, 0, 5)).isEmpty() assertThat(buildResult.getStringAnnotations(tag, 5, 6)).isEqualTo( listOf(Range(annotation2, 5, 10, tag)) ) // The tag doesn't match, return empty list. assertThat(buildResult.getStringAnnotations("tag1", 5, 6)).isEmpty() assertThat(buildResult.getStringAnnotations(tag, 10, 11)).isEmpty() } private fun createAnnotatedString( text: String, color: Color = Color.Red, lineHeight: TextUnit = 20.sp ): AnnotatedString { return AnnotatedString( text = text, spanStyles = listOf( Range( item = SpanStyle(color), start = 0, end = text.length ) ), paragraphStyles = listOf( Range( item = ParagraphStyle(lineHeight = lineHeight), start = 0, end = text.length ) ) ) } /** * Returns a [Range] from the index of [start] to the index of [end], both inclusive. */ private fun <T> String.inclusiveRangeOf( start: Char, end: Char, item: T, tag: String = "" ) = Range( tag = tag, item = item, start = indexOf(start), end = indexOf(end) + 1 ) }
apache-2.0
ad37b970f7b114858b6dcf77418f94ff
35.171504
100
0.589335
4.882004
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/checker/regression/DoubleDefine.fir.kt
10
1784
// RUNTIME import java.util.* import java.io.* fun takeFirst(expr: StringBuilder): Char { val c = expr.get(0) expr.deleteCharAt(0) return c } fun evaluateArg(expr: CharSequence, numbers: ArrayList<Int>): Int { if (expr.length == 0) throw Exception("Syntax error: Character expected"); val c = takeFirst(<error descr="[ARGUMENT_TYPE_MISMATCH] Argument type mismatch: actual type is kotlin/CharSequence but kotlin/text/StringBuilder was expected">expr</error>) if (c >= '0' && c <= '9') { val n = c - '0' if (!numbers.contains(n)) throw Exception("You used incorrect number: " + n) numbers.remove(n) return n } throw Exception("Syntax error: Unrecognized character " + c) } fun evaluateAdd(expr: StringBuilder, numbers: ArrayList<Int>): Int { val lhs = evaluateArg(expr, numbers) if (expr.length > 0) { } return lhs } fun evaluate(expr: StringBuilder, numbers: ArrayList<Int>): Int { val lhs = evaluateAdd(expr, numbers) if (expr.length > 0) { val c = expr.get(0) expr.deleteCharAt(0) } return lhs } fun main(args: Array<String>) { System.out.println("24 game") val numbers = ArrayList<Int>(4) val rnd = Random(); val prompt = StringBuilder() for(i in 0..3) { val n = rnd.nextInt(9) + 1 numbers.add(n) if (i > 0) prompt.append(" "); prompt.append(n) } System.out.println("Your numbers: " + prompt) System.out.println("Enter your expression:") val reader = BufferedReader(InputStreamReader(System.`in`)) val expr = StringBuilder(reader.readLine()!!) try { val result = evaluate(expr, numbers) if (result != 24) System.out.println("Sorry, that's " + result) else System.out.println("You won!"); } catch(e: Throwable) { System.out.println(e.message) } }
apache-2.0
f7c512d92c731c44b35dbe0b52a24eb8
26.030303
175
0.654709
3.43738
false
false
false
false
GunoH/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/components/InlayTablePage.kt
3
10804
/* * 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.plugins.notebooks.visualization.r.inlays.components import com.intellij.icons.AllIcons import com.intellij.ide.CopyProvider import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.* import com.intellij.openapi.fileChooser.FileChooserFactory import com.intellij.openapi.fileChooser.FileSaverDescriptor import com.intellij.openapi.fileChooser.FileSaverDialog import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.DumbAwareToggleAction import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.ui.IdeBorderFactory import com.intellij.ui.SideBorder import com.intellij.ui.components.JBScrollPane import com.intellij.ui.table.JBTable import com.intellij.util.ui.TextTransferable import org.jetbrains.plugins.notebooks.visualization.VisualisationIcons import org.jetbrains.plugins.notebooks.visualization.r.VisualizationBundle import org.jetbrains.plugins.notebooks.visualization.r.inlays.ClipboardUtils import org.jetbrains.plugins.notebooks.visualization.r.inlays.dataframe.DataFrame import org.jetbrains.plugins.notebooks.visualization.r.inlays.dataframe.columns.DoubleType import org.jetbrains.plugins.notebooks.visualization.r.inlays.dataframe.columns.IntType import org.jetbrains.plugins.notebooks.visualization.r.inlays.table.* import org.jetbrains.plugins.notebooks.visualization.r.inlays.table.filters.gui.TableFilterHeader import org.jetbrains.plugins.notebooks.visualization.r.inlays.table.paging.TablePaginator import org.jetbrains.plugins.notebooks.visualization.r.ui.MaterialTable import org.jetbrains.plugins.notebooks.visualization.r.ui.MaterialTableUtils import java.awt.BorderLayout import java.awt.Event import java.awt.event.ActionEvent import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import java.io.BufferedWriter import java.io.File import java.util.Arrays.asList import javax.swing.* import javax.swing.table.TableRowSorter /** * Table page of notebook inlay component. Hold and serve table. * By default table has a context menu with "copy selection" action and toolbar with action "Save as tsv". */ class InlayTablePage : JPanel(BorderLayout()), ToolBarProvider { var onChange: (() -> Unit)? = null private val table = MaterialTable() val scrollPane = JBScrollPane(table) private var filterHeader: TableFilterHeader? = null private var paginator: TablePaginator? = null val preferredHeight: Int get() { return table.preferredSize.height } class TableCopyProvider(private val table: JBTable) : CopyProvider { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT override fun performCopy(dataContext: DataContext) { val copySelectedToString: CharSequence = ClipboardUtils.copySelectedToString(table) CopyPasteManager.getInstance().setContents(TextTransferable(copySelectedToString)) } override fun isCopyEnabled(dataContext: DataContext): Boolean { return table.selectedRowCount > 0 } override fun isCopyVisible(dataContext: DataContext): Boolean { return true } } init { // Disposer.register(parent, disposable) table.putClientProperty("AuxEditorComponent", true) scrollPane.border = IdeBorderFactory.createBorder(SideBorder.RIGHT) scrollPane.viewportBorder = IdeBorderFactory.createBorder(SideBorder.BOTTOM or SideBorder.LEFT or SideBorder.RIGHT) setupTablePopupMenu(table) // setupCopySelectedAction(table) setupSelectAllAction(table) table.addKeyListener(object : KeyAdapter() { override fun keyPressed(e: KeyEvent) { if (filterHeader == null && e.keyChar.isLetterOrDigit()) { addTableFilterHeader() } } }) DataManager.registerDataProvider(table) { dataId -> if (PlatformDataKeys.COPY_PROVIDER.`is`(dataId)) TableCopyProvider(table) else null } add(scrollPane, BorderLayout.CENTER) } private fun setupTablePopupMenu(table: JTable) { val copyAll = JMenuItem(VisualizationBundle.message("inlay.table.copy.all")) copyAll.addActionListener { ClipboardUtils.copyAllToClipboard(table) } val copySelected = JMenuItem(VisualizationBundle.message("inlay.table.copy.selected")) copySelected.addActionListener { ClipboardUtils.copySelectedToClipboard(table) } val popupMenu = JPopupMenu() popupMenu.add(copyAll) popupMenu.add(copySelected) table.componentPopupMenu = popupMenu } private fun setupSelectAllAction(table: JTable) { val actionName = VisualizationBundle.message("action.name.table.select.all") val action = object : AbstractAction(actionName) { override fun actionPerformed(e: ActionEvent) { table.setRowSelectionInterval(0, table.rowCount - 1) table.setColumnSelectionInterval(0, table.columnCount - 1) } } table.actionMap.put(actionName, action) table.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK), actionName) } private inner class NumberComparator<T : Comparable<*>> : Comparator<T> { override fun compare(o1: T, o2: T): Int { return compareValues(o1, o2) } } /** * Sets the data frame for displaying in table. * also setups tableRowSorter with natural comparators for Int and double columns */ fun setDataFrame(dataFrame: DataFrame) { table.columnModel = DataFrameColumnModel(dataFrame) table.model = DataFrameTableModel(dataFrame) for (i in dataFrame.getColumns().indices) { table.columnModel.getColumn(i).cellRenderer = when { dataFrame[i].type == IntType -> IntegerTableCellRenderer() dataFrame[i].type == DoubleType -> DoubleTableCellRenderer() else -> StringTableCellRenderer() } } MaterialTableUtils.fitColumnsWidth(table) val tableRowSorter = TableRowSorter(table.model) tableRowSorter.sortsOnUpdates = true for ((i, column) in dataFrame.getColumns().withIndex()) { if (column.type is IntType) { tableRowSorter.setComparator(i, NumberComparator<Int>()) } else if (column.type is DoubleType) { tableRowSorter.setComparator(i, NumberComparator<Double>()) } } table.rowSorter = tableRowSorter } private fun addTableFilterHeader() { filterHeader = TableFilterHeader() filterHeader!!.table = table } override fun createActions(): List<AnAction> { val actionSaveAsCsv = object : DumbAwareAction(VisualizationBundle.message("inlay.table.export.as.text"), VisualizationBundle.message("inlay.table.export.as.description"), AllIcons.ToolbarDecorator.Export) { override fun actionPerformed(e: AnActionEvent) { saveAsCsv(e.project ?: return) } } val filterTable = object : DumbAwareToggleAction(VisualizationBundle.message("inlay.table.filter.text"), VisualizationBundle.message("inlay.table.filter.description"), AllIcons.Actions.Find) { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT override fun isSelected(e: AnActionEvent): Boolean { return filterHeader != null } override fun setSelected(e: AnActionEvent, state: Boolean) { if (state) { addTableFilterHeader() } else { filterHeader?.table = null filterHeader = null } } } val paginateTable = object : DumbAwareToggleAction(VisualizationBundle.message("inlay.table.pagination.text"), VisualizationBundle.message("inlay.table.pagination.description"), VisualisationIcons.Table.Pagination) { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT override fun isSelected(e: AnActionEvent): Boolean { return paginator != null } override fun setSelected(e: AnActionEvent, state: Boolean) { if (state) { paginator = TablePaginator() paginator!!.table = table } else { paginator?.table = null paginator = null } } } return asList(actionSaveAsCsv, filterTable, paginateTable) } /** Save the file as tsv (tab separated values) via intellij SaveFileDialog. */ private fun saveAsCsv(project: Project) { val descriptor = FileSaverDescriptor(VisualizationBundle.message("inlay.table.export.as.csv.text"), VisualizationBundle.message("inlay.table.export.as.csv.description"), "csv", "tsv") val chooser: FileSaverDialog = FileChooserFactory.getInstance().createSaveFileDialog(descriptor, this) val basePath = project.basePath ?: return val virtualBaseDir = LocalFileSystem.getInstance().findFileByIoFile(File(basePath)) val fileWrapper = chooser.save(virtualBaseDir, "table.csv") ?: return fun saveSelection(out: BufferedWriter, cellBreak: String) { val selectedColumnCount = table.selectedColumnCount val selectedRowCount = table.selectedRowCount val selectedRows = table.selectedRows val selectedColumns = table.selectedColumns for (i in 0 until selectedRowCount) { for (j in 0 until selectedColumnCount) { out.write(ClipboardUtils.escape(table.getValueAt(selectedRows[i], selectedColumns[j]))) if (j < selectedColumnCount - 1) { out.write(cellBreak) } } if (i < table.rowCount - 1) { out.append(ClipboardUtils.LINE_BREAK) } } } fun saveAll(out: BufferedWriter, cellBreak: String) { for (i in 0 until table.rowCount) { for (j in 0 until table.columnCount) { out.write(ClipboardUtils.escape(table.getValueAt(i, j))) if (j < table.columnCount - 1) { out.write(cellBreak) } } if (i < table.rowCount - 1) { out.append(ClipboardUtils.LINE_BREAK) } } } fileWrapper.file.bufferedWriter().use { out -> val cellBreak = if (fileWrapper.file.extension == "csv") ";" else "\t" if (table.selectedColumnCount == 0 || table.selectedRowCount == 0) { saveAll(out, cellBreak) } else { saveSelection(out, cellBreak) } } } }
apache-2.0
db3663caa84c4adc68a0dc232b342a40
36.648084
140
0.698167
4.603323
false
false
false
false
GunoH/intellij-community
plugins/devkit/devkit-core/src/actions/updateFromSources/UpdateIdeFromSourcesAction.kt
2
23319
// 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.idea.devkit.actions.updateFromSources import com.intellij.CommonBundle import com.intellij.execution.configurations.JavaParameters import com.intellij.execution.process.* import com.intellij.ide.plugins.PluginInstaller import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.PluginNode import com.intellij.ide.plugins.marketplace.MarketplaceRequests import com.intellij.notification.* import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.roots.OrderEnumerator import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.NioFiles import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.task.ProjectTaskManager import com.intellij.testFramework.LightVirtualFile import com.intellij.util.Restarter import com.intellij.util.TimeoutUtil import com.intellij.util.io.inputStream import com.intellij.util.io.isDirectory import com.intellij.util.io.isFile import org.jetbrains.annotations.NonNls import org.jetbrains.idea.devkit.DevKitBundle import org.jetbrains.idea.devkit.util.PsiUtil import java.io.File import java.nio.file.Files import java.nio.file.Path import java.util.* import kotlin.io.path.name private val LOG = logger<UpdateIdeFromSourcesAction>() private val notificationGroup by lazy { NotificationGroupManager.getInstance().getNotificationGroup("Update from Sources") } internal open class UpdateIdeFromSourcesAction @JvmOverloads constructor(private val forceShowSettings: Boolean = false) : AnAction(if (forceShowSettings) DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.show.settings.text") else DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.text"), DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.description"), null), DumbAware { override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return if (forceShowSettings || UpdateFromSourcesSettings.getState().showSettings) { val oldWorkIdePath = UpdateFromSourcesSettings.getState().actualIdePath val ok = UpdateFromSourcesDialog(project, forceShowSettings).showAndGet() if (!ok) { return } val updatedState = UpdateFromSourcesSettings.getState() if (oldWorkIdePath != updatedState.actualIdePath) { updatedState.workIdePathsHistory.remove(oldWorkIdePath) updatedState.workIdePathsHistory.remove(updatedState.actualIdePath) updatedState.workIdePathsHistory.add(0, updatedState.actualIdePath) updatedState.workIdePathsHistory.add(0, oldWorkIdePath) } } fun error(@NlsContexts.DialogMessage message : String) { Messages.showErrorDialog(project, message, CommonBundle.getErrorTitle()) } val state = UpdateFromSourcesSettings.getState() val devIdeaHome = project.basePath ?: return val workIdeHome = state.actualIdePath val restartAutomatically = state.restartAutomatically if (!ApplicationManager.getApplication().isRestartCapable && FileUtil.pathsEqual(workIdeHome, PathManager.getHomePath())) { return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.ide.cannot.restart")) } val notIdeHomeMessage = checkIdeHome(workIdeHome) if (notIdeHomeMessage != null) { return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.work.home.not.valid.ide.home", workIdeHome, notIdeHomeMessage)) } if (FileUtil.isAncestor(workIdeHome, PathManager.getConfigPath(), false)) { return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.config.or.system.directory.under.home", workIdeHome, PathManager.PROPERTY_CONFIG_PATH)) } if (FileUtil.isAncestor(workIdeHome, PathManager.getSystemPath(), false)) { return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.config.or.system.directory.under.home", workIdeHome, PathManager.PROPERTY_SYSTEM_PATH)) } val bundledPluginDirsToSkip: List<String> val nonBundledPluginDirsToInclude: List<String> val buildEnabledPluginsOnly = !state.buildDisabledPlugins if (buildEnabledPluginsOnly) { val pluginDirectoriesToSkip = LinkedHashSet(state.pluginDirectoriesForDisabledPlugins) pluginDirectoriesToSkip.removeAll( PluginManagerCore.getLoadedPlugins().asSequence() .filter { it.isBundled } .map { it.pluginPath } .filter { it.isDirectory() } .map { it.name } .toHashSet() ) PluginManagerCore.getPlugins() .filter { it.isBundled && !it.isEnabled } .map { it.pluginPath } .filter { it.isDirectory() } .mapTo(pluginDirectoriesToSkip) { it.name } val list = pluginDirectoriesToSkip.toMutableList() state.pluginDirectoriesForDisabledPlugins = list bundledPluginDirsToSkip = list nonBundledPluginDirsToInclude = PluginManagerCore.getPlugins() .asSequence() .filter { !it.isBundled && it.isEnabled } .map { it.pluginPath } .filter { it.isDirectory() } .map { it.name } .toList() } else { bundledPluginDirsToSkip = emptyList() nonBundledPluginDirsToInclude = emptyList() } val deployDir = "$devIdeaHome/out/deploy" // NON-NLS val distRelativePath = "dist" // NON-NLS val backupDir = "$devIdeaHome/out/backup-before-update-from-sources" // NON-NLS val params = createScriptJavaParameters(project = project, deployDir = deployDir, distRelativePath = distRelativePath, buildEnabledPluginsOnly = buildEnabledPluginsOnly, bundledPluginDirsToSkip = bundledPluginDirsToSkip, nonBundledPluginDirsToInclude = nonBundledPluginDirsToInclude) ?: return val taskManager = ProjectTaskManager.getInstance(project) taskManager .run(taskManager.createModulesBuildTask(ModuleManager.getInstance(project).modules, true, true, true, false)) .onSuccess { if (!it.isAborted && !it.hasErrors()) { runUpdateScript(params, project, workIdeHome, deployDir, distRelativePath, backupDir, restartAutomatically) } } } private fun checkIdeHome(workIdeHome: String): String? { val homeDir = Path.of(workIdeHome) if (Files.notExists(homeDir)) { return null } if (!Files.isDirectory(homeDir)) { return DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.work.home.not.valid.ide.home.not.directory") } val buildTxt = if (SystemInfo.isMac) "Resources/build.txt" else "build.txt" // NON-NLS for (name in listOf("bin", buildTxt)) { if (Files.notExists(homeDir.resolve(name))) { return DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.work.home.not.valid.ide.home.not.exists", name) } } return null } private fun runUpdateScript(params: JavaParameters, project: Project, workIdeHome: String, deployDirPath: String, distRelativePath: String, backupDir: String, restartAutomatically: Boolean) { val builtDistPath = "$deployDirPath/$distRelativePath" object : Task.Backgroundable(project, DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.title"), true) { override fun run(indicator: ProgressIndicator) { indicator.text = DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.progress.text") backupImportantFilesIfNeeded(workIdeHome, backupDir, indicator) indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.progress.delete", builtDistPath) NioFiles.deleteRecursively(Path.of(builtDistPath)) indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.progress.start.script", ULTIMATE_UPDATE_FROM_SOURCES_BUILD_TARGET) val commandLine = params.toCommandLine() commandLine.isRedirectErrorStream = true val scriptHandler = OSProcessHandler(commandLine) val output = Collections.synchronizedList(ArrayList<@NlsSafe String>()) scriptHandler.addProcessListener(object : ProcessListener { override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) { output.add(event.text) if (outputType == ProcessOutputTypes.STDOUT) { indicator.text2 = event.text } } override fun processTerminated(event: ProcessEvent) { if (indicator.isCanceled) { return } if (event.exitCode != 0) { notificationGroup.createNotification(title = DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.failed.title"), content = DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.failed.content", event.exitCode), type = NotificationType.ERROR) .addAction(NotificationAction.createSimple(DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.action.view.output")) { FileEditorManager.getInstance(project).openFile(LightVirtualFile("output.txt", output.joinToString("")), true) }) .addAction(NotificationAction.createSimple(DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.action.view.debug.log")) { val logFile = LocalFileSystem.getInstance().refreshAndFindFileByPath("$deployDirPath/log/debug.log") ?: return@createSimple // NON-NLS logFile.refresh(true, false) FileEditorManager.getInstance(project).openFile(logFile, true) }) .notify(project) return } if (!FileUtil.pathsEqual(workIdeHome, PathManager.getHomePath())) { startCopyingFiles(builtDistPath, workIdeHome, project) return } val command = generateUpdateCommand(builtDistPath, workIdeHome) if (restartAutomatically) { ApplicationManager.getApplication().invokeLater { scheduleRestart(command, deployDirPath, project) } } else { showRestartNotification(command, deployDirPath, project) } } }) scriptHandler.startNotify() while (!scriptHandler.isProcessTerminated) { scriptHandler.waitFor(300) indicator.checkCanceled() } } }.queue() } private fun showRestartNotification(command: Array<String>, deployDirPath: String, project: Project) { notificationGroup .createNotification(DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.success.title"), DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.success.content"), NotificationType.INFORMATION) .setListener(NotificationListener { _, _ -> restartWithCommand(command, deployDirPath) }) .notify(project) } private fun scheduleRestart(command: Array<String>, deployDirPath: String, project: Project) { object : Task.Modal(project, DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.success.title"), true) { override fun run(indicator: ProgressIndicator) { indicator.isIndeterminate = false var progress = 0 for (i in 10 downTo 1) { indicator.text = DevKitBundle.message( "action.UpdateIdeFromSourcesAction.progress.text.new.installation.prepared.ide.will.restart", i) repeat(10) { indicator.fraction = 0.01 * progress++ indicator.checkCanceled() TimeoutUtil.sleep(100) } } restartWithCommand(command, deployDirPath) } override fun onCancel() { showRestartNotification(command, deployDirPath, project) } }.setCancelText(DevKitBundle.message("action.UpdateIdeFromSourcesAction.button.postpone")).queue() } private fun backupImportantFilesIfNeeded(workIdeHome: String, backupDirPath: String, indicator: ProgressIndicator) { val backupDir = Path.of(backupDirPath) if (Files.exists(backupDir)) { LOG.debug("$backupDir already exists, skipping backup") return } LOG.debug("Backing up files from $workIdeHome to $backupDir") indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.backup.progress.text") Files.createDirectories(backupDir) File(workIdeHome, "bin").listFiles() ?.filter { it.name !in safeToDeleteFilesInBin && it.extension !in safeToDeleteExtensions } ?.forEach { FileUtil.copy(it, backupDir.resolve("bin/${it.name}").toFile()) } File(workIdeHome).listFiles() ?.filter { it.name !in safeToDeleteFilesInHome } ?.forEach { FileUtil.copyFileOrDir(it, backupDir.resolve(it.name).toFile()) } } private fun startCopyingFiles(builtDistPath: String, workIdeHome: String, project: Project) { object : Task.Backgroundable(project, DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.title"), true) { override fun run(indicator: ProgressIndicator) { indicator.text = DevKitBundle.message("action.UpdateIdeFromSourcesAction.copy.progress.text") indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.copy.delete.old.files.text") FileUtil.delete(File(workIdeHome)) indicator.checkCanceled() indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.copy.copy.new.files.text") FileUtil.copyDir(File(builtDistPath), File(workIdeHome)) indicator.checkCanceled() Notification("Update from Sources", DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.title"), DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.content", workIdeHome), NotificationType.INFORMATION).notify(project) } }.queue() } private fun generateUpdateCommand(builtDistPath: String, workIdeHome: String): Array<String> { if (SystemInfo.isWindows) { val restartLogFile = File(PathManager.getLogPath(), "update-from-sources.log") val updateScript = FileUtil.createTempFile("update", ".cmd", false) val workHomePath = File(workIdeHome).absolutePath /* deletion of the IDE files may fail to delete some executable files because they are still used by the IDE process, so the script wait for some time and try to delete again; 'ping' command is used instead of 'timeout' because the latter doesn't work from batch files; removal of the script file is performed in separate process to avoid errors while executing the script */ FileUtil.writeToFile(updateScript, """ @echo off SET count=20 SET time_to_wait=1 :DELETE_DIR RMDIR /Q /S "$workHomePath" IF EXIST "$workHomePath" ( IF %count% GEQ 0 ( ECHO "$workHomePath" still exists, wait %time_to_wait%s and try delete again SET /A time_to_wait=%time_to_wait%+1 PING 127.0.0.1 -n %time_to_wait% >NUL SET /A count=%count%-1 ECHO %count% attempts remain GOTO DELETE_DIR ) ECHO Failed to delete "$workHomePath", IDE wasn't updated. You may delete it manually and copy files from "${File(builtDistPath).absolutePath}" by hand GOTO CLEANUP_AND_EXIT ) XCOPY "${File(builtDistPath).absolutePath}" "$workHomePath"\ /Q /E /Y :CLEANUP_AND_EXIT START /b "" cmd /c DEL /Q /F "${updateScript.absolutePath}" & EXIT /b """.trimIndent()) return arrayOf("cmd", "/c", updateScript.absolutePath, ">${restartLogFile.absolutePath}", "2>&1") } val command = arrayOf( "rm -rf \"$workIdeHome\"/*", "cp -R \"$builtDistPath\"/* \"$workIdeHome\"" ) return arrayOf("/bin/sh", "-c", command.joinToString(" && ")) } private fun restartWithCommand(command: Array<String>, deployDirPath: String) { val pluginsDir = Path.of(deployDirPath) .resolve("artifacts/${ApplicationInfo.getInstance().build.productCode}-plugins") val nonBundledPluginsPaths = lazy { nonBundledPluginsPaths() } readPluginsDir(pluginsDir).forEach { newPluginNode -> updateNonBundledPlugin(newPluginNode, pluginsDir) { nonBundledPluginsPaths.value[it] } } Restarter.doNotLockInstallFolderOnRestart() (ApplicationManagerEx.getApplicationEx() as ApplicationImpl).restart( ApplicationEx.FORCE_EXIT or ApplicationEx.EXIT_CONFIRMED or ApplicationEx.SAVE, command, ) } private fun readPluginsDir(pluginsDirPath: Path): List<PluginNode> { val pluginsXml = pluginsDirPath.resolve("plugins.xml") if (!pluginsXml.isFile()) { LOG.warn("Cannot read non-bundled plugins from $pluginsXml, they won't be updated") return emptyList() } return try { pluginsXml.inputStream().use { MarketplaceRequests.parsePluginList(it) } } catch (e: Exception) { LOG.error("Failed to parse $pluginsXml", e) emptyList() } } private fun nonBundledPluginsPaths(): Map<PluginId, Path> { return PluginManagerCore.getLoadedPlugins() .asSequence() .filterNot { it.isBundled } .associate { it.pluginId to it.pluginPath } .also { LOG.debug("Existing custom plugins: $it") } } private fun updateNonBundledPlugin( newDescriptor: PluginNode, pluginsDir: Path, oldPluginPathProvider: (PluginId) -> Path?, ) { assert(!newDescriptor.isBundled) val oldPluginPath = oldPluginPathProvider(newDescriptor.pluginId) ?: return val newPluginPath = pluginsDir.resolve(newDescriptor.downloadUrl) .also { LOG.debug("Adding update command: $oldPluginPath to $it") } PluginInstaller.installAfterRestart( newDescriptor, newPluginPath, oldPluginPath, false, ) } private fun createScriptJavaParameters(project: Project, deployDir: String, @Suppress("SameParameterValue") distRelativePath: String, buildEnabledPluginsOnly: Boolean, bundledPluginDirsToSkip: List<String>, nonBundledPluginDirsToInclude: List<String>): JavaParameters? { val sdk = ProjectRootManager.getInstance(project).projectSdk if (sdk == null) { LOG.warn("Project SDK is not defined") return null } val params = JavaParameters() params.isUseClasspathJar = true params.setDefaultCharset(project) params.jdk = sdk params.mainClass = ULTIMATE_UPDATE_FROM_SOURCES_BUILD_TARGET params.programParametersList.add("--classpath") val buildScriptsModuleName = "intellij.idea.ultimate.build" val buildScriptsModule = ModuleManager.getInstance(project).findModuleByName(buildScriptsModuleName) if (buildScriptsModule == null) { LOG.warn("Build scripts module $buildScriptsModuleName is not found in the project") return null } val classpath = OrderEnumerator.orderEntries(buildScriptsModule) .recursively().withoutSdk().runtimeOnly().productionOnly().classes().pathsList.pathList params.classPath.addAll(classpath) params.vmParametersList.add("-D$includeBinAndRuntimeProperty=true") params.vmParametersList.add("-Dintellij.build.bundled.jre.prefix=jbrsdk_jcef-") if (buildEnabledPluginsOnly) { if (bundledPluginDirsToSkip.isNotEmpty()) { params.vmParametersList.add("-Dintellij.build.bundled.plugin.dirs.to.skip=${bundledPluginDirsToSkip.joinToString(",")}") } val nonBundled = if (nonBundledPluginDirsToInclude.isNotEmpty()) nonBundledPluginDirsToInclude.joinToString(",") else "none" params.vmParametersList.add("-Dintellij.build.non.bundled.plugin.dirs.to.include=$nonBundled") } if (!buildEnabledPluginsOnly || nonBundledPluginDirsToInclude.isNotEmpty()) { params.vmParametersList.add("-Dintellij.build.local.plugins.repository=true") } params.vmParametersList.add("-Dintellij.build.output.root=$deployDir") params.vmParametersList.add("-DdistOutputRelativePath=$distRelativePath") return params } override fun update(e: AnActionEvent) { val project = e.project e.presentation.isEnabledAndVisible = project != null && PsiUtil.isIdeaProject(project) } } private const val includeBinAndRuntimeProperty = "intellij.build.generate.bin.and.runtime.for.unpacked.dist" internal class UpdateIdeFromSourcesSettingsAction : UpdateIdeFromSourcesAction(true) @NonNls private val safeToDeleteFilesInHome = setOf( "bin", "help", "jre", "jre64", "jbr", "lib", "license", "plugins", "redist", "MacOS", "Resources", "build.txt", "product-info.json", "Install-Linux-tar.txt", "Install-Windows-zip.txt", "ipr.reg" ) @NonNls private val safeToDeleteFilesInBin = setOf( "append.bat", "appletviewer.policy", "format.sh", "format.bat", "fsnotifier", "fsnotifier64", "inspect.bat", "inspect.sh", "restarter", "icons", /* "idea.properties", "idea.sh", "idea.bat", "idea.exe.vmoptions", "idea64.exe.vmoptions", "idea.vmoptions", "idea64.vmoptions", "log.xml", */ ) @NonNls private val safeToDeleteExtensions = setOf("exe", "dll", "dylib", "so", "ico", "svg", "png", "py") private const val ULTIMATE_UPDATE_FROM_SOURCES_BUILD_TARGET = "UltimateUpdateFromSourcesBuildTarget"
apache-2.0
7f4c0ffccccc20d63882ebbbf46ed23e
44.45614
213
0.692911
4.969949
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/refactoring/ui/RefactoringDialogUsageCollector.kt
10
1444
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.ui import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.project.Project class RefactoringDialogUsageCollector : CounterUsagesCollector() { companion object { private val GROUP = EventLogGroup("refactoring.dialog", 3) private val SELECTED = EventFields.Boolean("selected") private val CLASS_NAME = EventFields.Class("class_name") private val OPEN_IN_EDITOR_SAVED = GROUP.registerVarargEvent("open.in.editor.saved", SELECTED, CLASS_NAME, EventFields.PluginInfo) private val OPEN_IN_EDITOR_SHOWN = GROUP.registerVarargEvent("open.in.editor.shown", SELECTED, CLASS_NAME, EventFields.PluginInfo) @JvmStatic fun logOpenInEditorSaved(project: Project, selected: Boolean, clazz: Class<*>) { OPEN_IN_EDITOR_SAVED.log(project, SELECTED.with(selected), CLASS_NAME.with(clazz)) } @JvmStatic fun logOpenInEditorShown(project: Project, selected: Boolean, clazz: Class<*>) { OPEN_IN_EDITOR_SHOWN.log(project, SELECTED.with(selected), CLASS_NAME.with(clazz)) } } override fun getGroup(): EventLogGroup { return GROUP } }
apache-2.0
224f5b1ba0995b84d9254912bdf990a2
40.285714
140
0.762465
4.247059
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/PanelImpl.kt
2
12512
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.builder.impl import com.intellij.openapi.ui.OnePixelDivider import com.intellij.openapi.util.NlsContexts import com.intellij.ui.SeparatorComponent import com.intellij.ui.TitledSeparator import com.intellij.ui.components.JBLabel import com.intellij.ui.components.Label import com.intellij.ui.dsl.UiDslException import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.builder.Row import com.intellij.ui.dsl.builder.SpacingConfiguration import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import com.intellij.ui.layout.* import org.jetbrains.annotations.ApiStatus import java.awt.Color import javax.swing.JComponent import javax.swing.JLabel @ApiStatus.Internal internal class PanelImpl(private val dialogPanelConfig: DialogPanelConfig, var spacingConfiguration: SpacingConfiguration, private val parent: RowImpl?) : CellBaseImpl<Panel>(), Panel { val rows: List<RowImpl> get() = _rows private var panelContext = PanelContext() private val _rows = mutableListOf<RowImpl>() private var visible = true private var enabled = true override fun row(label: String, init: Row.() -> Unit): RowImpl { if (label.isEmpty()) { val result = RowImpl(dialogPanelConfig, panelContext, this, RowLayout.LABEL_ALIGNED) result.cell() result.init() _rows.add(result) return result } else { return row(Label(label), init) } } override fun row(label: JLabel?, init: Row.() -> Unit): RowImpl { val result: RowImpl if (label == null) { result = RowImpl(dialogPanelConfig, panelContext, this, RowLayout.INDEPENDENT) } else { label.putClientProperty(DslComponentProperty.ROW_LABEL, true) result = RowImpl(dialogPanelConfig, panelContext, this, RowLayout.LABEL_ALIGNED) result.cell(label) } result.init() _rows.add(result) if (label != null && result.cells.size > 1) { labelCell(label, result.cells[1]) } return result } override fun twoColumnsRow(column1: (Row.() -> Unit)?, column2: (Row.() -> Unit)?): Row { if (column1 == null && column2 == null) { throw UiDslException("Both columns cannot be null") } return row { panel { row { if (column1 == null) { cell() } else { column1() } } }.gap(RightGap.COLUMNS) panel { row { if (column2 == null) { cell() } else { column2() } } } }.layout(RowLayout.PARENT_GRID) } override fun threeColumnsRow(column1: (Row.() -> Unit)?, column2: (Row.() -> Unit)?, column3: (Row.() -> Unit)?): Row { if (column1 == null && column2 == null && column3 == null) { throw UiDslException("All columns cannot be null") } return row { panel { row { if (column1 == null) { cell() } else { column1() } } }.gap(RightGap.COLUMNS) panel { row { if (column2 == null) { cell() } else { column2() } } }.gap(RightGap.COLUMNS) panel { row { if (column3 == null) { cell() } else { column3() } } } }.layout(RowLayout.PARENT_GRID) } @Suppress("OVERRIDE_DEPRECATION") override fun separator(@NlsContexts.Separator title: String?, background: Color?): Row { return createSeparatorRow(title) } override fun separator(background: Color?): Row { return createSeparatorRow(null, background) } override fun panel(init: Panel.() -> Unit): PanelImpl { lateinit var result: PanelImpl row { result = panel(init).align(AlignY.FILL) as PanelImpl } return result } override fun rowsRange(init: Panel.() -> Unit): RowsRangeImpl { val result = RowsRangeImpl(this, _rows.size) this.init() result.endIndex = _rows.size - 1 return result } override fun group(title: String?, indent: Boolean, init: Panel.() -> Unit): RowImpl { return groupImpl(toSeparatorLabel(title), indent, init) } override fun group(title: JBLabel, indent: Boolean, init: Panel.() -> Unit): RowImpl { return groupImpl(title, indent, init) } private fun groupImpl(title: JBLabel?, indent: Boolean, init: Panel.() -> Unit): RowImpl { val result = row { panel { createSeparatorRow(title) if (indent) { indent(init) } else { init() } }.align(AlignY.FILL) } result.internalTopGap = spacingConfiguration.verticalMediumGap result.internalBottomGap = spacingConfiguration.verticalMediumGap return result } @Suppress("OVERRIDE_DEPRECATION") override fun group(title: String?, indent: Boolean, topGroupGap: Boolean?, bottomGroupGap: Boolean?, init: Panel.() -> Unit): Panel { lateinit var result: Panel val row = row { result = panel { createSeparatorRow(title) } } if (indent) { result.indent(init) } else { result.init() } setTopGroupGap(row, topGroupGap) setBottomGroupGap(row, bottomGroupGap) return result } override fun groupRowsRange(title: String?, indent: Boolean, topGroupGap: Boolean?, bottomGroupGap: Boolean?, init: Panel.() -> Unit): RowsRangeImpl { val result = RowsRangeImpl(this, _rows.size) createSeparatorRow(title) if (indent) { indent(init) } else { init() } result.endIndex = _rows.size - 1 setTopGroupGap(rows[result.startIndex], topGroupGap) setBottomGroupGap(rows[result.endIndex], bottomGroupGap) return result } override fun collapsibleGroup(title: String, indent: Boolean, init: Panel.() -> Unit): CollapsibleRowImpl { val result = CollapsibleRowImpl(dialogPanelConfig, panelContext, this, title) { if (indent) { indent(init) } else { init() } } result.expanded = false result.internalTopGap = spacingConfiguration.verticalMediumGap result.internalBottomGap = spacingConfiguration.verticalMediumGap _rows.add(result) return result } @Deprecated("Use buttonsGroup(...) instead") @ApiStatus.ScheduledForRemoval override fun <T> buttonGroup(binding: PropertyBinding<T>, type: Class<T>, title: String?, indent: Boolean, init: Panel.() -> Unit) { buttonsGroup(title, indent, init) .bind(MutableProperty(binding.get, binding.set), type) } override fun buttonsGroup(title: String?, indent: Boolean, init: Panel.() -> Unit): ButtonsGroupImpl { val result = ButtonsGroupImpl(this, _rows.size) dialogPanelConfig.context.addButtonsGroup(result) try { if (title != null) { val row = row { @Suppress("DialogTitleCapitalization") label(title) .applyToComponent { putClientProperty(DslComponentProperty.NO_BOTTOM_GAP, true) } } row.internalBottomGap = spacingConfiguration.buttonGroupHeaderBottomGap } if (indent) { indent(init) } else { init() } } finally { dialogPanelConfig.context.removeLastButtonsGroup() } result.endIndex = _rows.size - 1 return result } override fun onApply(callback: () -> Unit): PanelImpl { dialogPanelConfig.applyCallbacks.register(null, callback) return this } override fun onReset(callback: () -> Unit): PanelImpl { dialogPanelConfig.resetCallbacks.register(null, callback) return this } override fun onIsModified(callback: () -> Boolean): PanelImpl { dialogPanelConfig.isModifiedCallbacks.register(null, callback) return this } override fun customizeSpacingConfiguration(spacingConfiguration: SpacingConfiguration, init: Panel.() -> Unit) { this.spacingConfiguration = spacingConfiguration this.init() } override fun customize(customGaps: Gaps): PanelImpl { super.customize(customGaps) return this } override fun enabled(isEnabled: Boolean): PanelImpl { enabled = isEnabled if (parent == null || parent.isEnabled()) { doEnabled(enabled, _rows.indices) } return this } override fun enabledFromParent(parentEnabled: Boolean) { enabledFromParent(parentEnabled, _rows.indices) } fun enabledFromParent(parentEnabled: Boolean, range: IntRange) { doEnabled(parentEnabled && enabled, range) } fun isEnabled(): Boolean { return enabled && (parent == null || parent.isEnabled()) } override fun enabledIf(predicate: ComponentPredicate): PanelImpl { super.enabledIf(predicate) return this } override fun visible(isVisible: Boolean): PanelImpl { visible = isVisible if (parent == null || parent.isVisible()) { doVisible(visible, _rows.indices) } return this } override fun visibleIf(predicate: ComponentPredicate): Panel { super.visibleIf(predicate) return this } override fun visibleFromParent(parentVisible: Boolean) { visibleFromParent(parentVisible, _rows.indices) } fun visibleFromParent(parentVisible: Boolean, range: IntRange) { doVisible(parentVisible && visible, range) } fun isVisible(): Boolean { return visible && (parent == null || parent.isVisible()) } @Deprecated("Use align method instead") override fun horizontalAlign(horizontalAlign: HorizontalAlign): PanelImpl { super.horizontalAlign(horizontalAlign) return this } @Deprecated("Use align method instead") override fun verticalAlign(verticalAlign: VerticalAlign): PanelImpl { super.verticalAlign(verticalAlign) return this } override fun align(align: Align): PanelImpl { super.align(align) return this } override fun resizableColumn(): PanelImpl { super.resizableColumn() return this } override fun gap(rightGap: RightGap): PanelImpl { super.gap(rightGap) return this } override fun indent(init: Panel.() -> Unit): RowsRangeImpl { val result = RowsRangeImpl(this, _rows.size) val prevPanelContext = panelContext panelContext = panelContext.copy(indentCount = prevPanelContext.indentCount + 1) try { this.init() } finally { panelContext = prevPanelContext } result.endIndex = _rows.size - 1 return result } private fun doEnabled(isEnabled: Boolean, range: IntRange) { for (i in range) { _rows[i].enabledFromParent(isEnabled) } } private fun doVisible(isVisible: Boolean, range: IntRange) { for (i in range) { _rows[i].visibleFromParent(isVisible) } } private fun setTopGroupGap(row: RowImpl, topGap: Boolean?) { if (topGap == null) { row.internalTopGap = spacingConfiguration.verticalMediumGap } else { row.topGap(if (topGap) TopGap.MEDIUM else TopGap.NONE) } } private fun setBottomGroupGap(row: RowImpl, bottomGap: Boolean?) { if (bottomGap == null) { row.internalBottomGap = spacingConfiguration.verticalMediumGap } else { row.bottomGap(if (bottomGap) BottomGap.MEDIUM else BottomGap.NONE) } } } internal data class PanelContext( /** * Number of [SpacingConfiguration.horizontalIndent] indents before each row in the panel */ val indentCount: Int = 0 ) private fun Panel.createSeparatorRow(@NlsContexts.Separator title: String?): Row { return createSeparatorRow(toSeparatorLabel(title)) } private fun Panel.createSeparatorRow(title: JBLabel?, background: Color? = null): Row { val separator: JComponent if (title == null) { separator = SeparatorComponent(0, background ?: OnePixelDivider.BACKGROUND, null) } else { separator = object : TitledSeparator(title.text) { override fun createLabel(): JBLabel { return title } } separator.border = null } return row { cell(separator) .align(AlignX.FILL) } } private fun toSeparatorLabel(@NlsContexts.Separator title: String?): JBLabel? { @Suppress("DialogTitleCapitalization") return if (title == null) null else JBLabel(title) }
apache-2.0
6506e4820be87d335f89880aff5d3ad3
26.143167
158
0.649536
4.286399
false
true
false
false
GunoH/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/buildSystem/MavenPlugin.kt
4
3635
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.PluginSettingsOwner import org.jetbrains.kotlin.tools.projectWizard.core.asSuccess import org.jetbrains.kotlin.tools.projectWizard.core.checker import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.RootFileModuleStructureIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.ModulesDependencyMavenIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.maven.PluginRepositoryMavenIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.withIrs import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.MavenPrinter import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.updateBuildFiles class MavenPlugin(context: Context) : BuildSystemPlugin(context) { override val path = pluginPath companion object : PluginSettingsOwner() { override val pluginPath = "buildSystem.maven" private val isMaven = checker { type.settingValue == BuildSystemType.Maven } val createSettingsFileTask by pipelineTask(GenerationPhase.PROJECT_GENERATION) { runAfter(KotlinPlugin.createModules) runBefore(createModules) isAvailable = isMaven withAction { buildFiles.update { buildFiles -> if (buildFiles.size == 1) return@update buildFiles.asSuccess() buildFiles.map { buildFile -> when (val structure = buildFile.modules) { is RootFileModuleStructureIR -> { val dependencies = allModulesPaths.map { path -> path.joinToString(separator = "/") } buildFile.copy(modules = structure.withIrs(ModulesDependencyMavenIR(dependencies))) } else -> buildFile } }.asSuccess() } } } val addBuildSystemPluginRepositories by pipelineTask(GenerationPhase.PROJECT_GENERATION) { runAfter(KotlinPlugin.createPluginRepositories) runBefore(createModules) isAvailable = isMaven withAction { val repositories = getPluginRepositoriesWithDefaultOnes() updateBuildFiles { buildFile -> buildFile.withIrs(repositories.map(::PluginRepositoryMavenIR)).asSuccess() } } } val addBuildSystemData by addBuildSystemData( BuildSystemData( type = BuildSystemType.Maven, buildFileData = BuildFileData( createPrinter = { MavenPrinter() }, buildFileName = "pom.xml" ) ) ) } override val pipelineTasks: List<PipelineTask> = super.pipelineTasks + listOf( createSettingsFileTask, addBuildSystemPluginRepositories, addBuildSystemData ) }
apache-2.0
7b71208ac051504d92d2e19e05428370
44.45
158
0.642091
5.724409
false
false
false
false
TeamNewPipe/NewPipe
app/src/main/java/org/schabi/newpipe/views/player/CircleClipTapView.kt
2
2200
package org.schabi.newpipe.views.player import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import android.util.AttributeSet import android.view.View class CircleClipTapView(context: Context?, attrs: AttributeSet) : View(context, attrs) { private var backgroundPaint = Paint() private var widthPx = 0 private var heightPx = 0 // Background private var shapePath = Path() private var arcSize: Float = 80f private var isLeft = true init { requireNotNull(context) { "Context is null." } backgroundPaint.apply { style = Paint.Style.FILL isAntiAlias = true color = 0x30000000 } val dm = context.resources.displayMetrics widthPx = dm.widthPixels heightPx = dm.heightPixels updatePathShape() } fun updateArcSize(baseView: View) { val newArcSize = baseView.height / 11.4f if (arcSize != newArcSize) { arcSize = newArcSize updatePathShape() } } fun updatePosition(newIsLeft: Boolean) { if (isLeft != newIsLeft) { isLeft = newIsLeft updatePathShape() } } private fun updatePathShape() { val halfWidth = widthPx * 0.5f shapePath.reset() val w = if (isLeft) 0f else widthPx.toFloat() val f = if (isLeft) 1 else -1 shapePath.moveTo(w, 0f) shapePath.lineTo(f * (halfWidth - arcSize) + w, 0f) shapePath.quadTo( f * (halfWidth + arcSize) + w, heightPx.toFloat() / 2, f * (halfWidth - arcSize) + w, heightPx.toFloat() ) shapePath.lineTo(w, heightPx.toFloat()) shapePath.close() invalidate() } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) widthPx = w heightPx = h updatePathShape() } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) canvas?.clipPath(shapePath) canvas?.drawPath(shapePath, backgroundPaint) } }
gpl-3.0
2fb354d9786784a8241d52e65fa94e7f
23.719101
88
0.593636
4.305284
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ObjectLiteralToLambdaIntention.kt
1
9962
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.canMoveLambdaOutsideParentheses import org.jetbrains.kotlin.idea.core.moveFunctionLiteralOutsideParentheses import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.inspections.RedundantSamConstructorInspection import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.sam.JavaSingleAbstractMethodUtils import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.types.KotlinType @Suppress("DEPRECATION") class ObjectLiteralToLambdaInspection : IntentionBasedInspection<KtObjectLiteralExpression>(ObjectLiteralToLambdaIntention::class) { override fun problemHighlightType(element: KtObjectLiteralExpression): ProblemHighlightType { val (_, baseType, singleFunction) = extractData(element) ?: return super.problemHighlightType(element) val bodyBlock = singleFunction.bodyBlockExpression val lastStatement = bodyBlock?.statements?.lastOrNull() if (bodyBlock?.anyDescendantOfType<KtReturnExpression> { it != lastStatement } == true) return ProblemHighlightType.INFORMATION val valueArgument = element.parent as? KtValueArgument val call = valueArgument?.getStrictParentOfType<KtCallExpression>() if (call != null) { val argumentMatch = call.resolveToCall()?.getArgumentMapping(valueArgument) as? ArgumentMatch if (baseType.constructor != argumentMatch?.valueParameter?.type?.constructor) return ProblemHighlightType.INFORMATION } return super.problemHighlightType(element) } } class ObjectLiteralToLambdaIntention : SelfTargetingRangeIntention<KtObjectLiteralExpression>( KtObjectLiteralExpression::class.java, KotlinBundle.lazyMessage("convert.to.lambda"), KotlinBundle.lazyMessage("convert.object.literal.to.lambda") ) { override fun applicabilityRange(element: KtObjectLiteralExpression): TextRange? { val (baseTypeRef, baseType, singleFunction) = extractData(element) ?: return null if (!JavaSingleAbstractMethodUtils.isSamType(baseType)) return null val functionDescriptor = singleFunction.resolveToDescriptorIfAny(BodyResolveMode.FULL) ?: return null val overridden = functionDescriptor.overriddenDescriptors.singleOrNull() ?: return null if (overridden.modality != Modality.ABSTRACT) return null if (!singleFunction.hasBody()) return null if (singleFunction.valueParameters.any { it.name == null }) return null val bodyExpression = singleFunction.bodyExpression!! val context = bodyExpression.analyze() val containingDeclaration = functionDescriptor.containingDeclaration // this-reference if (bodyExpression.anyDescendantOfType<KtThisExpression> { thisReference -> context[BindingContext.REFERENCE_TARGET, thisReference.instanceReference] == containingDeclaration } ) return null // Recursive call, skip labels if (ReferencesSearch.search(singleFunction, LocalSearchScope(bodyExpression)).any { it.element !is KtLabelReferenceExpression }) { return null } fun ReceiverValue?.isImplicitClassFor(descriptor: DeclarationDescriptor) = this is ImplicitClassReceiver && classDescriptor == descriptor if (bodyExpression.anyDescendantOfType<KtExpression> { expression -> val resolvedCall = expression.getResolvedCall(context) resolvedCall?.let { it.dispatchReceiver.isImplicitClassFor(containingDeclaration) || it.extensionReceiver .isImplicitClassFor(containingDeclaration) } == true } ) return null return TextRange(element.objectDeclaration.getObjectKeyword()!!.startOffset, baseTypeRef.endOffset) } override fun applyTo(element: KtObjectLiteralExpression, editor: Editor?) { val (_, baseType, singleFunction) = extractData(element)!! val commentSaver = CommentSaver(element) val returnSaver = ReturnSaver(singleFunction) val body = singleFunction.bodyExpression!! val factory = KtPsiFactory(element) val newExpression = factory.buildExpression { appendFixedText(IdeDescriptorRenderers.SOURCE_CODE.renderType(baseType)) appendFixedText("{") val parameters = singleFunction.valueParameters val needParameters = parameters.count() > 1 || parameters.any { parameter -> ReferencesSearch.search(parameter, LocalSearchScope(body)).any() } if (needParameters) { parameters.forEachIndexed { index, parameter -> if (index > 0) { appendFixedText(",") } appendName(parameter.nameAsSafeName) } appendFixedText("->") } val lastCommentOwner = if (singleFunction.hasBlockBody()) { val contentRange = (body as KtBlockExpression).contentRange() appendChildRange(contentRange) contentRange.last } else { appendExpression(body) body } if (lastCommentOwner?.anyDescendantOfType<PsiComment> { it.tokenType == KtTokens.EOL_COMMENT } == true) { appendFixedText("\n") } appendFixedText("}") } val replaced = runWriteActionIfPhysical(element) { element.replaced(newExpression) } val pointerToReplaced = replaced.createSmartPointer() val callee = replaced.callee val callExpression = callee.parent as KtCallExpression val functionLiteral = callExpression.lambdaArguments.single().getLambdaExpression()!! val returnLabel = callee.getReferencedNameAsName() runWriteActionIfPhysical(element) { returnSaver.restore(functionLiteral, returnLabel) } val parentCall = ((replaced.parent as? KtValueArgument) ?.parent as? KtValueArgumentList) ?.parent as? KtCallExpression if (parentCall != null && RedundantSamConstructorInspection.samConstructorCallsToBeConverted(parentCall) .singleOrNull() == callExpression ) { runWriteActionIfPhysical(element) { commentSaver.restore(replaced, forceAdjustIndent = true/* by some reason lambda body is sometimes not properly indented */) } RedundantSamConstructorInspection.replaceSamConstructorCall(callExpression) if (parentCall.canMoveLambdaOutsideParentheses()) runWriteActionIfPhysical(element) { parentCall.moveFunctionLiteralOutsideParentheses() } } else { runWriteActionIfPhysical(element) { commentSaver.restore(replaced, forceAdjustIndent = true/* by some reason lambda body is sometimes not properly indented */) } pointerToReplaced.element?.let { replacedByPointer -> val endOffset = (replacedByPointer.callee.parent as? KtCallExpression)?.typeArgumentList?.endOffset ?: replacedByPointer.callee.endOffset ShortenReferences.DEFAULT.process(replacedByPointer.containingKtFile, replacedByPointer.startOffset, endOffset) } } } private val KtExpression.callee get() = getCalleeExpressionIfAny() as KtNameReferenceExpression } private data class Data( val baseTypeRef: KtTypeReference, val baseType: KotlinType, val singleFunction: KtNamedFunction ) private fun extractData(element: KtObjectLiteralExpression): Data? { val objectDeclaration = element.objectDeclaration val singleFunction = objectDeclaration.declarations.singleOrNull() as? KtNamedFunction ?: return null if (!singleFunction.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return null val delegationSpecifier = objectDeclaration.superTypeListEntries.singleOrNull() ?: return null val typeRef = delegationSpecifier.typeReference ?: return null val bindingContext = typeRef.analyze(BodyResolveMode.PARTIAL) val baseType = bindingContext[BindingContext.TYPE, typeRef] ?: return null return Data(typeRef, baseType, singleFunction) }
apache-2.0
af967c825c4b64c62cb8ffde48c867c9
47.130435
158
0.722546
5.653802
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/lang/documentation/ide/ui/SearchModel.kt
2
6772
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("DuplicatedCode") // extracted from org.jetbrains.r.rendering.toolwindow.RDocumentationComponent package com.intellij.lang.documentation.ide.ui import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.application.ApplicationBundle import com.intellij.openapi.application.EDT import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.DocumentAdapter import com.intellij.ui.LightColors import com.intellij.ui.SearchTextField import com.intellij.util.ui.JBUI import com.intellij.util.ui.NamedColorUtil import com.intellij.util.ui.UIUtil import com.intellij.util.ui.addPropertyChangeListener import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import java.awt.Point import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import javax.swing.JEditorPane import javax.swing.JLabel import javax.swing.SwingConstants import javax.swing.event.DocumentEvent import kotlin.math.abs internal class SearchModel(ui: DocumentationUI) : Disposable { private val editorPane: JEditorPane = ui.editorPane private val cs = CoroutineScope(Dispatchers.EDT) val searchField = SearchTextField() val matchLabel: JLabel = JLabel().also { label -> // adapted from com.intellij.find.editorHeaderActions.StatusTextAction label.font = JBUI.Fonts.toolbarFont() label.text = "9888 results" //NON-NLS label.preferredSize = label.preferredSize label.text = null label.horizontalAlignment = SwingConstants.RIGHT } init { searchField.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { val pattern = searchField.text setPattern(pattern) near() } }) searchField.addKeyboardListener(object : KeyAdapter() { override fun keyReleased(e: KeyEvent) { if (e.keyCode == KeyEvent.VK_ENTER && hasNext) { next() } } }) cs.launch { ui.contentUpdates.collect { updateIndices() updateHighlighting() } } editorPane.addPropertyChangeListener(parent = this, "highlighter") { updateHighlighting() } } private var pattern: String = "" private val indices = ArrayList<Int>() private var currentSelection = 0 private val tagHandles = ArrayList<() -> Unit>() override fun dispose() { cs.cancel("SearchModel disposal") pattern = "" indices.clear() currentSelection = -1 removeHighlights() } fun createNavigationActions(): List<AnAction> = listOf( object : DumbAwareAction() { init { ActionUtil.copyFrom(this, IdeActions.ACTION_PREVIOUS_OCCURENCE) } override fun update(e: AnActionEvent) { e.presentation.isEnabled = hasPrev } override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun actionPerformed(e: AnActionEvent) = prev() }, object : DumbAwareAction() { init { ActionUtil.copyFrom(this, IdeActions.ACTION_NEXT_OCCURENCE) } override fun actionPerformed(e: AnActionEvent) = next() override fun update(e: AnActionEvent) { e.presentation.isEnabled = hasNext } override fun getActionUpdateThread() = ActionUpdateThread.BGT }, ) private fun setPattern(pattern: String) { if (this.pattern == pattern) return this.pattern = pattern updateIndices() updateHighlighting() } private val hasNext: Boolean get() = currentSelection + 1 < indices.size private val hasPrev: Boolean get() = currentSelection - 1 >= 0 private fun next() { check(hasNext) { "Doesn't have next element" } currentSelection += 1 updateHighlighting() updateMatchLabel() scroll() } private fun prev() { check(hasPrev) { "Doesn't have prev element" } currentSelection -= 1 updateHighlighting() updateMatchLabel() scroll() } private fun near() { val visibleRect = editorPane.visibleRect val visibleRestCenter = Point(visibleRect.centerX.toInt(), visibleRect.centerY.toInt()) val currentOffset = editorPane.viewToModel2D(visibleRestCenter) val nearestSelection = indices.minByOrNull { abs(it - currentOffset) } ?: return currentSelection = indices.indexOf(nearestSelection) updateHighlighting() updateMatchLabel() scroll() } private fun scroll() { val viewRectangle = editorPane.modelToView(indices[currentSelection]) editorPane.scrollRectToVisible(viewRectangle) } private fun updateIndices() { indices.clear() currentSelection = 0 if (pattern.isNotEmpty()) { val text = editorPane.document.getText(0, editorPane.document.length) var index = 0 while (index < text.length) { index = StringUtil.indexOfIgnoreCase(text, pattern, index) if (index == -1) break indices.add(index) index += pattern.length } } updateMatchLabel() } private fun updateMatchLabel() { matchLabel.foreground = UIUtil.getLabelForeground() matchLabel.font = JBUI.Fonts.toolbarFont() val matches = indices.size val cursorIndex = currentSelection + 1 if (pattern.isEmpty()) { searchField.textEditor.background = UIUtil.getTextFieldBackground() matchLabel.text = "" } else if (matches > 0) { searchField.textEditor.background = UIUtil.getTextFieldBackground() matchLabel.text = ApplicationBundle.message("editorsearch.current.cursor.position", cursorIndex, matches) } else { searchField.textEditor.background = LightColors.RED matchLabel.foreground = NamedColorUtil.getErrorForeground() matchLabel.text = ApplicationBundle.message("editorsearch.matches", matches) } } private fun removeHighlights() { for (tagHandle in tagHandles) { tagHandle() } tagHandles.clear() } private fun updateHighlighting() { removeHighlights() val highlighter = editorPane.highlighter ?: return editorPane.invalidate() editorPane.repaint() for (index in indices) { val tag = highlighter.addHighlight(index, index + pattern.length, SearchHighlighterPainter(indices[currentSelection] == index)) tagHandles.add { highlighter.removeHighlight(tag) } } } }
apache-2.0
99ba0adc82bd72ad2ad1a39104ac229e
29.781818
133
0.711902
4.523714
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/NewKotlinFileAction.kt
1
12756
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.actions import com.intellij.ide.actions.* import com.intellij.ide.fileTemplates.FileTemplate import com.intellij.ide.fileTemplates.FileTemplateManager import com.intellij.ide.fileTemplates.actions.AttributesDefaults import com.intellij.ide.fileTemplates.ui.CreateFromTemplateDialog import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.ui.InputValidatorEx import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import com.intellij.util.IncorrectOperationException import org.jetbrains.annotations.TestOnly import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.configuration.ConfigureKotlinStatus import org.jetbrains.kotlin.idea.configuration.KotlinProjectConfigurator import org.jetbrains.kotlin.idea.configuration.toModuleGroup import org.jetbrains.kotlin.idea.project.getLanguageVersionSettings import org.jetbrains.kotlin.idea.statistics.KotlinCreateFileFUSCollector import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.parsing.KotlinParserDefinition.Companion.STD_SCRIPT_SUFFIX import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.psiUtil.startOffset import java.util.* class NewKotlinFileAction : CreateFileFromTemplateAction( KotlinBundle.message("action.new.file.text"), KotlinBundle.message("action.new.file.description"), KotlinFileType.INSTANCE.icon ) { override fun postProcess(createdElement: PsiFile, templateName: String?, customProperties: Map<String, String>?) { super.postProcess(createdElement, templateName, customProperties) val module = ModuleUtilCore.findModuleForPsiElement(createdElement) if (createdElement is KtFile) { if (module != null) { for (hook in NewKotlinFileHook.EP_NAME.extensions) { hook.postProcess(createdElement, module) } } val ktClass = createdElement.declarations.singleOrNull() as? KtNamedDeclaration if (ktClass != null) { if (ktClass is KtClass && ktClass.isData()) { val primaryConstructor = ktClass.primaryConstructor if (primaryConstructor != null) { createdElement.editor()?.caretModel?.moveToOffset(primaryConstructor.startOffset + 1) return } } CreateFromTemplateAction.moveCaretAfterNameIdentifier(ktClass) } else { val editor = createdElement.editor() ?: return val lineCount = editor.document.lineCount if (lineCount > 0) { editor.caretModel.moveToLogicalPosition(LogicalPosition(lineCount - 1, 0)) } } } } private fun KtFile.editor() = FileEditorManager.getInstance(this.project).selectedTextEditor?.takeIf { it.document == this.viewProvider.document } override fun buildDialog(project: Project, directory: PsiDirectory, builder: CreateFileFromTemplateDialog.Builder) { builder.setTitle(KotlinBundle.message("action.new.file.dialog.title")) .addKind( KotlinBundle.message("action.new.file.dialog.class.title"), KotlinIcons.CLASS, "Kotlin Class" ) .addKind( KotlinBundle.message("action.new.file.dialog.file.title"), KotlinFileType.INSTANCE.icon, "Kotlin File" ) .addKind( KotlinBundle.message("action.new.file.dialog.interface.title"), KotlinIcons.INTERFACE, "Kotlin Interface" ) if (project.getLanguageVersionSettings().supportsFeature(LanguageFeature.SealedInterfaces)) { builder.addKind( KotlinBundle.message("action.new.file.dialog.sealed.interface.title"), KotlinIcons.INTERFACE, "Kotlin Sealed Interface" ) } builder.addKind( KotlinBundle.message("action.new.file.dialog.data.class.title"), KotlinIcons.CLASS, "Kotlin Data Class" ) .addKind( KotlinBundle.message("action.new.file.dialog.enum.title"), KotlinIcons.ENUM, "Kotlin Enum" ) .addKind( KotlinBundle.message("action.new.file.dialog.sealed.class.title"), KotlinIcons.CLASS, "Kotlin Sealed Class" ) .addKind( KotlinBundle.message("action.new.file.dialog.annotation.title"), KotlinIcons.ANNOTATION, "Kotlin Annotation" ) .addKind( KotlinBundle.message("action.new.file.dialog.object.title"), KotlinIcons.OBJECT, "Kotlin Object" ) builder.setValidator(NameValidator) } override fun getActionName(directory: PsiDirectory, newName: String, templateName: String): String = KotlinBundle.message("action.new.file.text") override fun isAvailable(dataContext: DataContext): Boolean { if (super.isAvailable(dataContext)) { val ideView = LangDataKeys.IDE_VIEW.getData(dataContext)!! val project = PlatformDataKeys.PROJECT.getData(dataContext)!! val projectFileIndex = ProjectRootManager.getInstance(project).fileIndex return ideView.directories.any { projectFileIndex.isInSourceContent(it.virtualFile) || CreateTemplateInPackageAction.isInContentRoot(it.virtualFile, projectFileIndex) } } return false } override fun hashCode(): Int = 0 override fun equals(other: Any?): Boolean = other is NewKotlinFileAction override fun startInWriteAction() = false override fun createFileFromTemplate(name: String, template: FileTemplate, dir: PsiDirectory) = createFileFromTemplateWithStat(name, template, dir) companion object { private object NameValidator : InputValidatorEx { override fun getErrorText(inputString: String): String? { if (inputString.trim().isEmpty()) { return KotlinBundle.message("action.new.file.error.empty.name") } val parts: List<String> = inputString.split(*FQNAME_SEPARATORS) if (parts.any { it.trim().isEmpty() }) { return KotlinBundle.message("action.new.file.error.empty.name.part") } return null } override fun checkInput(inputString: String): Boolean = true override fun canClose(inputString: String): Boolean = getErrorText(inputString) == null } @get:TestOnly val nameValidator: InputValidatorEx get() = NameValidator private fun findOrCreateTarget(dir: PsiDirectory, name: String, directorySeparators: CharArray): Pair<String, PsiDirectory> { var className = removeKotlinExtensionIfPresent(name) var targetDir = dir for (splitChar in directorySeparators) { if (splitChar in className) { val names = className.trim().split(splitChar) for (dirName in names.dropLast(1)) { targetDir = targetDir.findSubdirectory(dirName) ?: runWriteAction { targetDir.createSubdirectory(dirName) } } className = names.last() break } } return Pair(className, targetDir) } private fun removeKotlinExtensionIfPresent(name: String): String = when { name.endsWith(".$KOTLIN_WORKSHEET_EXTENSION") -> name.removeSuffix(".$KOTLIN_WORKSHEET_EXTENSION") name.endsWith(".$STD_SCRIPT_SUFFIX") -> name.removeSuffix(".$STD_SCRIPT_SUFFIX") name.endsWith(".${KotlinFileType.EXTENSION}") -> name.removeSuffix(".${KotlinFileType.EXTENSION}") else -> name } private fun createFromTemplate(dir: PsiDirectory, className: String, template: FileTemplate): PsiFile? { val project = dir.project val defaultProperties = FileTemplateManager.getInstance(project).defaultProperties val properties = Properties(defaultProperties) val element = try { CreateFromTemplateDialog( project, dir, template, AttributesDefaults(className).withFixedName(true), properties ).create() } catch (e: IncorrectOperationException) { throw e } catch (e: Exception) { LOG.error(e) return null } return element?.containingFile } private val FILE_SEPARATORS = charArrayOf('/', '\\') private val FQNAME_SEPARATORS = charArrayOf('/', '\\', '.') fun createFileFromTemplateWithStat(name: String, template: FileTemplate, dir: PsiDirectory): PsiFile? { KotlinCreateFileFUSCollector.logFileTemplate(template.name) return createFileFromTemplate(name, template, dir) } fun createFileFromTemplate(name: String, template: FileTemplate, dir: PsiDirectory): PsiFile? { val directorySeparators = when (template.name) { "Kotlin File" -> FILE_SEPARATORS else -> FQNAME_SEPARATORS } val (className, targetDir) = findOrCreateTarget(dir, name, directorySeparators) val service = DumbService.getInstance(dir.project) service.isAlternativeResolveEnabled = true try { val adjustedDir = CreateTemplateInPackageAction.adjustDirectory(targetDir, JavaModuleSourceRootTypes.SOURCES) val psiFile = createFromTemplate(adjustedDir, className, template) if (psiFile is KtFile) { val singleClass = psiFile.declarations.singleOrNull() as? KtClass if (singleClass != null && !singleClass.isEnum() && !singleClass.isInterface() && name.contains("Abstract")) { runWriteAction { singleClass.addModifier(KtTokens.ABSTRACT_KEYWORD) } } } JavaCreateTemplateInPackageAction.setupJdk(adjustedDir, psiFile) val module = ModuleUtil.findModuleForFile(psiFile) val configurator = KotlinProjectConfigurator.EP_NAME.extensions.firstOrNull() if (module != null && configurator != null) { DumbService.getInstance(module.project).runWhenSmart { if (configurator.getStatus(module.toModuleGroup()) == ConfigureKotlinStatus.CAN_BE_CONFIGURED) { configurator.configure(module.project, emptyList()) } } } return psiFile } finally { service.isAlternativeResolveEnabled = false } } } } abstract class NewKotlinFileHook { companion object { val EP_NAME: ExtensionPointName<NewKotlinFileHook> = ExtensionPointName.create<NewKotlinFileHook>("org.jetbrains.kotlin.newFileHook") } abstract fun postProcess(createdElement: KtFile, module: Module) }
apache-2.0
252375e10904de6a225d1172cfaf5a7c
42.240678
158
0.635701
5.402795
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/substring/ReplaceSubstringWithIndexingOperationInspection.kt
2
2381
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.substring import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.psi.KtConstantExpression import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator class ReplaceSubstringWithIndexingOperationInspection : ReplaceSubstringInspection() { override fun inspectionText(element: KtDotQualifiedExpression): String = KotlinBundle.message("inspection.replace.substring.with.indexing.operation.display.name") override val defaultFixText: String get() = KotlinBundle.message("replace.substring.call.with.indexing.operation.call") override val isAlwaysStable: Boolean = true override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) { val expression = element.callExpression?.valueArguments?.firstOrNull()?.getArgumentExpression() ?: return element.replaceWith("$0[$1]", expression) } override fun isApplicableInner(element: KtDotQualifiedExpression): Boolean { val arguments = element.callExpression?.valueArguments ?: return false if (arguments.size != 2) return false val arg1 = element.getValueArgument(0) ?: return false val arg2 = element.getValueArgument(1) ?: return false return arg1 + 1 == arg2 } private fun KtDotQualifiedExpression.getValueArgument(index: Int): Int? { val bindingContext = analyze() val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return null val expression = resolvedCall.call.valueArguments[index].getArgumentExpression() as? KtConstantExpression ?: return null val constant = ConstantExpressionEvaluator.getConstant(expression, bindingContext) ?: return null val constantType = bindingContext.getType(expression) ?: return null return constant.getValue(constantType) as? Int } }
apache-2.0
dcca5602271c6deb70677b72455446f7
53.136364
158
0.773625
5.087607
false
false
false
false
smmribeiro/intellij-community
plugins/devkit/devkit-core/src/inspections/missingApi/resolve/IdeExternalAnnotationsLocationProvider.kt
4
1881
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.inspections.missingApi.resolve import com.intellij.codeInsight.externalAnnotation.location.AnnotationsLocation import com.intellij.codeInsight.externalAnnotation.location.AnnotationsLocationProvider import com.intellij.openapi.project.Project import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.BuildNumber /** * Provides coordinates of external annotations artifacts for IntelliJ SDK. */ internal class IdeExternalAnnotationsLocationProvider : AnnotationsLocationProvider { override fun getLocations( project: Project, library: Library, artifactId: String?, groupId: String?, version: String? ): Collection<AnnotationsLocation> { if (groupId == null || artifactId == null || version == null) { return emptyList() } val libraries = LibrariesWithIntellijClassesSetting.getInstance(project).intellijApiContainingLibraries if (libraries.any { it.groupId == groupId && it.artifactId == artifactId }) { return getAnnotationsLocations(version) } return emptyList() } @Suppress("HardCodedStringLiteral") private fun getAnnotationsLocations(ideVersion: String): List<AnnotationsLocation> { val annotationsVersion = if (ideVersion.endsWith("-SNAPSHOT")) { ideVersion } else { val ideBuildNumber = BuildNumber.fromStringOrNull(ideVersion) ?: return emptyList() "${ideBuildNumber.baselineVersion}.999999" } return listOf(AnnotationsLocation( "com.jetbrains.intellij.idea", "ideaIU", annotationsVersion, PublicIntelliJSdkExternalAnnotationsRepository.RELEASES_REPO_URL, PublicIntelliJSdkExternalAnnotationsRepository.SNAPSHOTS_REPO_URL )) } }
apache-2.0
4b103494e2ad73209180c69149b4c7a5
38.1875
140
0.758107
5.00266
false
false
false
false
anastr/SpeedView
speedviewlib/src/main/java/com/github/anastr/speedviewlib/RaySpeedometer.kt
1
8175
package com.github.anastr.speedviewlib import android.content.Context import android.graphics.BlurMaskFilter import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import android.os.Build import android.util.AttributeSet import com.github.anastr.speedviewlib.components.indicators.Indicator /** * this Library build By Anas Altair * see it on [GitHub](https://github.com/anastr/SpeedView) */ open class RaySpeedometer @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, ) : Speedometer(context, attrs, defStyleAttr) { private val markPath = Path() private val ray1Path = Path() private val ray2Path = Path() private val rayMarkPaint = Paint(Paint.ANTI_ALIAS_FLAG) private val activeMarkPaint = Paint(Paint.ANTI_ALIAS_FLAG) private val speedBackgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG) private val rayPaint = Paint(Paint.ANTI_ALIAS_FLAG) private var withEffects = true private var degreeBetweenMark = 5 var isWithEffects: Boolean get() = withEffects set(withEffects) { this.withEffects = withEffects if (isInEditMode) return indicator.withEffects(withEffects) if (withEffects) { rayPaint.maskFilter = BlurMaskFilter(3f, BlurMaskFilter.Blur.SOLID) activeMarkPaint.maskFilter = BlurMaskFilter(5f, BlurMaskFilter.Blur.SOLID) speedBackgroundPaint.maskFilter = BlurMaskFilter(8f, BlurMaskFilter.Blur.SOLID) } else { rayPaint.maskFilter = null activeMarkPaint.maskFilter = null speedBackgroundPaint.maskFilter = null } invalidateGauge() } var speedBackgroundColor: Int get() = speedBackgroundPaint.color set(speedBackgroundColor) { speedBackgroundPaint.color = speedBackgroundColor invalidateGauge() } var rayMarkWidth: Float get() = rayMarkPaint.strokeWidth set(markRayWidth) { rayMarkPaint.strokeWidth = markRayWidth activeMarkPaint.strokeWidth = markRayWidth if (isAttachedToWindow) invalidate() } var rayColor: Int get() = rayPaint.color set(rayColor) { rayPaint.color = rayColor invalidateGauge() } // /** // * this Speedometer doesn't use this method. // * @return `Color.TRANSPARENT` always. // */ // override var indicatorColor: Int // @Deprecated("") // get() = 0 // @Deprecated("") // set(indicatorColor) { // } init { init() initAttributeSet(context, attrs) } override fun defaultGaugeValues() { super.textColor = 0xFFFFFFFF.toInt() } override fun defaultSpeedometerValues() { super.backgroundCircleColor = 0xff212121.toInt() super.markColor = 0xFF000000.toInt() } private fun initAttributeSet(context: Context, attrs: AttributeSet?) { if (attrs == null) return val a = context.theme.obtainStyledAttributes(attrs, R.styleable.RaySpeedometer, 0, 0) rayPaint.color = a.getColor(R.styleable.RaySpeedometer_sv_rayColor, rayPaint.color) val degreeBetweenMark = a.getInt(R.styleable.RaySpeedometer_sv_degreeBetweenMark, this.degreeBetweenMark) val rayMarkWidth = a.getDimension(R.styleable.RaySpeedometer_sv_rayMarkWidth, rayMarkPaint.strokeWidth) rayMarkPaint.strokeWidth = rayMarkWidth activeMarkPaint.strokeWidth = rayMarkWidth speedBackgroundPaint.color = a.getColor(R.styleable.RaySpeedometer_sv_speedBackgroundColor, speedBackgroundPaint.color) withEffects = a.getBoolean(R.styleable.RaySpeedometer_sv_withEffects, withEffects) a.recycle() isWithEffects = withEffects if (degreeBetweenMark in 1..20) this.degreeBetweenMark = degreeBetweenMark } private fun init() { rayMarkPaint.style = Paint.Style.STROKE rayMarkPaint.strokeWidth = dpTOpx(3f) activeMarkPaint.style = Paint.Style.STROKE activeMarkPaint.strokeWidth = dpTOpx(3f) rayPaint.style = Paint.Style.STROKE rayPaint.strokeWidth = dpTOpx(1.8f) rayPaint.color = 0xFFFFFFFF.toInt() speedBackgroundPaint.color = 0xFFFFFFFF.toInt() if (Build.VERSION.SDK_INT >= 11) setLayerType(LAYER_TYPE_SOFTWARE, null) isWithEffects = withEffects } override fun onSizeChanged(w: Int, h: Int, oldW: Int, oldH: Int) { super.onSizeChanged(w, h, oldW, oldH) updateMarkPath() updateBackgroundBitmap() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.save() canvas.rotate(getStartDegree() + 90f, size * .5f, size * .5f) var i = getStartDegree() while (i < getEndDegree()) { if (degree <= i) { rayMarkPaint.color = markColor canvas.drawPath(markPath, rayMarkPaint) canvas.rotate(degreeBetweenMark.toFloat(), size * .5f, size * .5f) i += degreeBetweenMark continue } if (currentSection != null) activeMarkPaint.color = currentSection!!.color else activeMarkPaint.color = 0 // transparent color canvas.drawPath(markPath, activeMarkPaint) canvas.rotate(degreeBetweenMark.toFloat(), size * .5f, size / 2f) i += degreeBetweenMark } canvas.restore() val speedBackgroundRect = getSpeedUnitTextBounds() speedBackgroundRect.left -= 2f speedBackgroundRect.right += 2f speedBackgroundRect.bottom += 2f canvas.drawRect(speedBackgroundRect, speedBackgroundPaint) drawSpeedUnitText(canvas) drawIndicator(canvas) drawNotes(canvas) } override fun updateBackgroundBitmap() { val c = createBackgroundBitmapCanvas() updateMarkPath() ray1Path.reset() ray1Path.moveTo(size / 2f, size / 2f) ray1Path.lineTo(size / 2f, sizePa / 3.2f + padding) ray1Path.moveTo(size / 2f, sizePa / 3.2f + padding) ray1Path.lineTo(size / 2.2f, sizePa / 3f + padding) ray1Path.moveTo(size / 2.2f, sizePa / 3f + padding) ray1Path.lineTo(size / 2.1f, sizePa / 4.5f + padding) ray2Path.reset() ray2Path.moveTo(size / 2f, size / 2f) ray2Path.lineTo(size / 2f, sizePa / 3.2f + padding) ray2Path.moveTo(size / 2f, sizePa / 3.2f + padding) ray2Path.lineTo(size / 2.2f, sizePa / 3.8f + padding) ray2Path.moveTo(size / 2f, sizePa / 3.2f + padding) ray2Path.lineTo(size / 1.8f, sizePa / 3.8f + padding) c.save() for (i in 0..5) { c.rotate(58f, size * .5f, size * .5f) if (i % 2 == 0) c.drawPath(ray1Path, rayPaint) else c.drawPath(ray2Path, rayPaint) } c.restore() drawMarks(c) if (tickNumber > 0) drawTicks(c) else drawDefMinMaxSpeedPosition(c) } private fun updateMarkPath() { markPath.reset() markPath.moveTo(size * .5f, padding.toFloat()) markPath.lineTo(size * .5f, speedometerWidth + padding) } override fun setIndicator(indicator: Indicator.Indicators) { super.setIndicator(indicator) this.indicator.withEffects(withEffects) } fun getDegreeBetweenMark(): Int { return degreeBetweenMark } /** * The spacing between the marks * * it should be between (0-20] ,else well be ignore. * * @param degreeBetweenMark degree between two marks. */ fun setDegreeBetweenMark(degreeBetweenMark: Int) { if (degreeBetweenMark <= 0 || degreeBetweenMark > 20) return this.degreeBetweenMark = degreeBetweenMark if (isAttachedToWindow) invalidate() } }
apache-2.0
4104b4985cc982e4778a7cd52375442f
32.367347
127
0.62104
4.114243
false
false
false
false
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/manager/appanalysis/AppResourceManager.kt
1
2683
package sk.styk.martin.apkanalyzer.manager.appanalysis import sk.styk.martin.apkanalyzer.model.detail.FileData import sk.styk.martin.apkanalyzer.model.detail.ResourceData import java.util.* import javax.inject.Inject class AppResourceManager @Inject constructor() { fun get(fileData: FileData): ResourceData { var numJpg = 0 var numGif = 0 var numPng = 0 var numXml = 0 var numNinePatchPng = 0 var unspecifiedDpi = 0 var ldpi = 0 var mdpi = 0 var hdpi = 0 var xhdpi = 0 var xxhdpi = 0 var xxxhdpi = 0 var nodpi = 0 var tvdpi = 0 val differentDrawables = HashSet<String>() val differentLayouts = HashSet<String>() fileData.drawableHashes.forEach { val name = it.path // eliminate duplicities differentDrawables.add(it.fileName) when { name.endsWith(".jpg") -> numJpg++ name.endsWith(".gif") -> numGif++ name.endsWith(".9.png") -> numNinePatchPng++ name.endsWith(".png") -> numPng++ name.endsWith(".xml") -> numXml++ } when { name.contains("ldpi") -> ldpi++ name.contains("mdpi") -> mdpi++ name.contains("xxxhdpi") -> xxxhdpi++ name.contains("xxhdpi") -> xxhdpi++ name.contains("xhdpi") -> xhdpi++ name.contains("hdpi") -> hdpi++ name.contains("nodpi") -> nodpi++ name.contains("tvdpi") -> tvdpi++ else -> unspecifiedDpi++ } } // just adding it to set to eliminate duplicities fileData.layoutHashes.forEach { differentLayouts.add(it.fileName) } return ResourceData( pngDrawables = numPng, ninePatchDrawables = numNinePatchPng, jpgDrawables = numJpg, gifDrawables = numGif, xmlDrawables = numXml, drawables = fileData.drawableHashes.size, differentDrawables = differentDrawables.size, ldpiDrawables = ldpi, mdpiDrawables = mdpi, hdpiDrawables = hdpi, xhdpiDrawables = xhdpi, xxhdpiDrawables = xxhdpi, xxxhdpiDrawables = xxxhdpi, nodpiDrawables = nodpi, tvdpiDrawables = tvdpi, unspecifiedDpiDrawables = unspecifiedDpi, layouts = fileData.layoutHashes.size, differentLayouts = differentLayouts.size) } }
gpl-3.0
2684a980e1788b998ed0718673fba27f
32.5375
75
0.534104
4.471667
false
false
false
false
sksamuel/ktest
kotest-common/src/jvmMain/kotlin/io/kotest/mpp/stacktraces.kt
1
877
@file:JvmName("stacktracesjvm") package io.kotest.mpp actual val stacktraces: StackTraces = object : StackTraces { override fun throwableLocation(t: Throwable): String? { return throwableLocation(t, 1)?.firstOrNull() } override fun throwableLocation(t: Throwable, n: Int): List<String>? { return (t.cause ?: t).stackTrace?.dropWhile { it.className.startsWith("io.kotest") }?.take(n)?.map { it.toString() } ?: emptyList() } override fun <T : Throwable> cleanStackTrace(throwable: T): T { if (shouldRemoveKotestElementsFromStacktrace) { throwable.stackTrace = UserStackTraceConverter.getUserStacktrace(throwable.stackTrace) } return throwable } override fun root(throwable: Throwable): Throwable { val cause = throwable.cause return if (cause == null) throwable else root(cause) } }
mit
7918fb012d607645ee912fb0c892b51a
30.321429
95
0.67959
4.236715
false
true
false
false
drmashu/koshop
src/main/kotlin/io/github/drmashu/koshop/model/Item.kt
1
1131
package io.github.drmashu.koshop.model import com.fasterxml.jackson.annotation.JsonIgnore import org.seasar.doma.Entity import org.seasar.doma.Transient import org.seasar.doma.Id import org.seasar.doma.jdbc.entity.NamingType import java.math.BigDecimal import java.sql.Blob /** * Created by NAGASAWA Takahiro on 2015/09/26. */ @Entity(naming = NamingType.SNAKE_UPPER_CASE) public class Item { @Id public var id: String? = null public var name: String? = null public var price: BigDecimal? = null public var description: String? = null @Transient public var images: MutableList<ItemImage>? = null } /** * */ @Entity(naming = NamingType.SNAKE_UPPER_CASE) public class Items { @Id public var uid: String? = null @Id public var itemId: String? = null public var count: Int? = null @Transient public var item: Item? = null } /** * */ @Entity(naming = NamingType.SNAKE_UPPER_CASE) public class ItemImage { @Id public var itemId: String? = null @Id public var index: Byte? = null @JsonIgnore public var image: Blob? = null public var contentType: String? = null }
apache-2.0
153902c22519bef8da3fd393002e18ae
23.586957
53
0.701149
3.458716
false
false
false
false
sg26565/hott-transmitter-config
mz32-Downloader/src/main/kotlin/de/treichels/hott/mz32/mz32.kt
1
14717
package de.treichels.hott.mz32 import de.treichels.hott.model.enums.TransmitterType import de.treichels.hott.model.firmware.Firmware import de.treichels.hott.model.firmware.getFirmware import de.treichels.hott.ui.CallbackAdapter import de.treichels.hott.ui.ExceptionDialog import de.treichels.hott.util.hash import de.treichels.lzma.canCompress import de.treichels.lzma.uncompress import tornadofx.* import java.io.File import java.nio.file.FileSystems import java.nio.file.Files import java.nio.file.StandardCopyOption import java.text.MessageFormat import java.util.* import java.util.concurrent.CancellationException import java.util.concurrent.CountDownLatch import java.util.logging.Logger import java.util.regex.Pattern class Mz32(private val rootDir: File) { private val cfgFile = CfgFile.load(File(rootDir, GRAUPNER_DISK_CFG)) private val md5 = MD5Sum(rootDir) @Suppress("MemberVisibilityCanBePrivate") val productName: String = cfgFile["Product name"]!! @Suppress("MemberVisibilityCanBePrivate") val productCode: Int = cfgFile["Product code"]!!.toInt() @Suppress("MemberVisibilityCanBePrivate") val productVersion: Float = cfgFile["Product ver."]!!.toFloat() / 1000 @Suppress("unused") val rfidNumber: String = cfgFile["RFID number"]!! @Suppress("MemberVisibilityCanBePrivate") val updatePath: String = cfgFile["Update path"]!! //val userPath = cfgFile["User path"]!!.split(';').filter { !it.isBlank() } //val langPath = cfgFile["Lang path"]!!.split(';').filter { !it.isBlank() } //val langUser = cfgFile["Lang User"]!!.split(';').filter { !it.isBlank() }.map { "^" + it.replace("*", "[^/]*") + ".*$" }.map { Regex(it) } private val messages = ResourceBundle.getBundle(Mz32Downloader::class.java.canonicalName) private val remotePath = "/Firmware/${TransmitterType.category}/$productCode" fun scan(task: FXTask<*>, languages: List<Language>) { md5.clear() md5.scan(task, languages) md5.save() } fun update( task: FXTask<*>, languages: List<Language>, updateResources: Boolean = true, updateHelpPages: Boolean = true, updateVoiceFiles: Boolean = true, updateManuals: Boolean = true, updateFirmware: Boolean = true ) { if (task.isCancelled) return try { task.updateProgress(0.0, 1.0) val (latestFirmware, latestResources) = findLatest(task) md5.load() task.updateProgress(0.0, 1.0) if (updateResources) updateResources( task, languages, latestResources, updateHelpPages, updateVoiceFiles, updateManuals ) task.updateProgress(0.0, 1.0) if (updateFirmware) TransmitterType.forProductCode(productCode).getFirmware() .firstOrNull { it.name == latestFirmware }?.apply { updateFirmware(task, this) } md5.save() } catch (e: CancellationException) { task.print(messages["cancelled"]) } catch (e: Exception) { task.print(MessageFormat.format(messages["failed"], e)) showError(e) } if (task.isCancelled) task.print(messages["download_cancelled"]) else task.print(messages["all_done"]) } private fun findLatest(task: FXTask<*>) = Firmware.download(CallbackAdapter(task), "$remotePath/latest.txt") { inputStream, _ -> task.print(messages["checking_online"]) val cfg = CfgFile.load(inputStream) task.print(messages["ok"]) Pair(cfg["firmware"]!!, cfg["resources"]!!) } private fun updateResources( task: FXTask<*>, languages: List<Language>, firmware: String, updateHelpPages: Boolean = true, updateVoiceFiles: Boolean = true, updateManuals: Boolean = true ) { if (task.isCancelled) return task.print(MessageFormat.format(messages["found_resources"], firmware)) val remoteRoot = "$remotePath/$firmware" // process remote md5sum.txt val remoteMd5 = MD5Sum().apply { task.print("$remoteRoot/md5sum.txt\n") task.print(messages["downloading.remote.md5sum.txt.from.server"]) Firmware.download(CallbackAdapter(task), "$remoteRoot/md5sum.txt") { inputStream, _ -> load(inputStream) } task.print(messages["ok"]) if (task.isCancelled) return task.print(messages["checking_resource_files"]) entries.forEachIndexed { index, entry -> if (task.isCancelled) return val path = Path(entry.key) val hash = entry.value when { path.isHelp -> if (updateHelpPages && languages.contains(path.language)) updateFileOnline( task, remoteRoot, path, hash ) path.isVoice -> if (updateVoiceFiles && languages.contains(path.language)) updateFileOnline( task, remoteRoot, path, hash ) path.isManual -> if (updateManuals && languages.contains(path.language)) updateFileOnline( task, remoteRoot, path, hash ) else -> updateFileOnline(task, remoteRoot, path, hash) } task.updateProgress(index.toLong(), size.toLong()) } } if (task.isCancelled) return // check for obsolete local md5 entries and files val files = rootDir.walk().iterator().asSequence() // ignore directories .filter { it.isFile } // get the relative path .map { "/${it.relativeTo(rootDir).path}" } // convert path separators on Windows .map { it.replace(File.separatorChar, '/') } // collect to a mutable set .toMutableSet() // add keys from md5sum.txt files.addAll(md5.keys) // keep entries in remote md5sum.txt files.removeIf { remoteMd5.keys.contains(it.toLowerCase()) } val toBeDeleted = files.asSequence() // convert to path .map { Path(it) } .filter { it.isAutoDelete } // keep protected entries .filterNot { it.isProtected } // keep help pages unless updateHelpPages was selected .filterNot { it.isHelp && !updateHelpPages } // keep voice files unless updateVoiceFiles was selected .filterNot { it.isVoice && !updateVoiceFiles } // keep voice files unless updateManuals was selected .filterNot { it.isManual && !updateManuals } // convert to string .map { it.value }.toMutableList() // special handling of /System/Revision_rXXXX.txt toBeDeleted += files.asSequence() .filter { revisions.matcher(it).matches() } .filterNot { remoteMd5.containsKey(it) } toBeDeleted.sorted().forEach { // delete remaining entries task.print(MessageFormat.format(messages["removing_obsolete_file"], it)) File(rootDir, it).apply { if (exists()) delete() } md5.remove(it) } task.print(messages["done"]) // delete VoiceList.lst in each language folder if (updateVoiceFiles) languages.map { "/Voice/${it.name}/VoiceList.lst" }.forEach { File(rootDir, it).delete() } } private fun updateFileOnline(task: FXTask<*>, root: String, path: Path, remoteHash: Hash) { if (task.isCancelled) return val filePath = path.value log.fine(MessageFormat.format(messages["remote_file"], root, filePath, remoteHash)) // local file on transmitter val file = File(rootDir, filePath).apply { parentFile.mkdirs() } val fileExists = file.exists() // local file size val fileSize = file.length() // local hash according to local md5sum.txt var localHash = md5[filePath] // local size according to local md5sum.txt val localSize = localHash?.size ?: 0L // remote size according to remote md5sum.txt val remoteSize = remoteHash.size // re-calculate missing or invalid hash if file exists and has same size as remote if (fileExists && fileSize == remoteSize && (localHash == null || localSize != fileSize)) { if (localHash == null) task.print(MessageFormat.format(messages["missing_checksum"], file)) else task.print(MessageFormat.format(messages["stale_checksum"], file)) localHash = Hash(fileSize, file.hash()) md5[filePath] = localHash task.print(messages["ok"]) } log.fine("Local file: ${file.absolutePath} (${if (file.exists()) "$fileSize Bytes" else "missing"}), $localHash") // if target file does not exist or has different size as remote or has different remoteHash if (!fileExists || (fileSize != remoteSize || remoteHash != localHash) && !path.isUser && !path.isLangUser) { when { !fileExists -> task.print(MessageFormat.format(messages["new_file"], file)) fileSize != remoteSize -> task.print( MessageFormat.format( messages["size_mismatch"], file ) ) remoteHash != localHash -> task.print( MessageFormat.format( messages["checksum_mismatch"], file ) ) } // download into temporary file val tempFile = File(file.parent, "${file.name}.tmp") val callback = CallbackAdapter(task) try { if (canCompress(file.extension)) Firmware.download(callback, "$root$filePath.lzma") { inputStream, _ -> uncompress( inputStream, tempFile.outputStream() ) } else Firmware.download(callback, "$root$filePath", tempFile) // replace target file only after successfull download Files.move( tempFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ) md5[filePath] = remoteHash task.print("ok\n") } catch (e: Exception) { task.print(MessageFormat.format(messages["failed"], e)) } finally { if (tempFile.exists()) tempFile.delete() } } } private fun showError(e: Exception) { val latch = CountDownLatch(1) runLater { ExceptionDialog(e).showAndWait() latch.countDown() } latch.await() } private fun updateFirmware(task: FXTask<*>, firmware: Firmware<TransmitterType>) { if (task.isCancelled) return val fileName = firmware.name val filePath = "$updatePath/$fileName" val file = File(rootDir, filePath) val fileSize = file.length() val firmwareSize = firmware.size task.print(MessageFormat.format(messages["found_firmware"], fileName)) if (!file.exists() || fileSize != firmwareSize) { // download into temporary file val tempFile = File(file.parent, "${file.name}.tmp") task.print(MessageFormat.format(messages["downloading_from_server"], file)) val hash = Firmware.download(CallbackAdapter(task), "$remotePath/$fileName", tempFile) // replace target file only after successfull download Files.move( tempFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ) md5[filePath] = Hash(firmwareSize, hash) task.print("ok\n") } else { task.print(MessageFormat.format(messages["uptodate"], file)) } md5.save() task.print(messages["done"]) } override fun toString(): String = "$rootDir ($productName [$productCode] v$productVersion)" companion object { private const val GRAUPNER_DISK_CFG = "/GraupnerDisk.cfg" private val revisions = Pattern.compile("/System/Revision_r[0-9]*\\.txt") private val log = Logger.getLogger(this::class.qualifiedName) fun find(): List<Mz32> { // File roots val canditates = File.listRoots().toMutableSet() // FileSystem roots try { canditates.addAll(FileSystems.getDefault().rootDirectories.map { it.toFile() }) } catch (e: Exception) { // ignore } // /proc/mounts try { val procMounts = File("/proc/mounts") if (procMounts.exists()) canditates.addAll(procMounts.readLines().map { File(it.split(" ")[1]) }) } catch (e: Exception) { // ignore } // mount command try { Runtime.getRuntime().exec("mount").apply { waitFor() if (exitValue() == 0) canditates.addAll(inputStream.reader().readLines().map { val path = it.substringAfter(" on ").substringBeforeLast(" (").trim() File(path) }) } } catch (e: Exception) { // ignore } return canditates.mapNotNull { try { Mz32(it) } catch (e: Exception) { null } } } } } internal fun FXTask<*>.print(newMessage: String) { runLater { updateMessage(newMessage) } }
lgpl-3.0
95e1064dddcfd4ad2f2670f3731c772a
34.377404
144
0.547054
4.845901
false
false
false
false
sg26565/hott-transmitter-config
HoTT-Serial/src/main/kotlin/de/treichels/hott/serial/ModelInfo.kt
1
1704
/** * HoTT Transmitter Config Copyright (C) 2013 Oliver Treichel * * 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:></http:>//www.gnu.org/licenses/>. */ package de.treichels.hott.serial import de.treichels.hott.model.enums.ModelType import de.treichels.hott.model.enums.ReceiverClass import de.treichels.hott.model.enums.TransmitterType import java.io.Serializable /** * @author Oliver Treichel &lt;[email protected]&gt; */ data class ModelInfo( val modelNumber: Int, val modelName: String, val modelInfo: String, val modelType: ModelType, val transmitterType: TransmitterType=TransmitterType.Unknown, val receiverClass: ReceiverClass = ReceiverClass.Unknown, val usedHours: Int = 0, val usedMinutes: Int = 0 ) : Serializable { override fun toString(): String { return String.format( "ModelInfo [modelNumber=%s, modelName=%s, modelInfo=%s, modelType=%s, transmitterType=%s, receiverClass=%s, usedHours=%s, usedMinutes=%s]", modelNumber, modelName, modelInfo, modelType, transmitterType, receiverClass, usedHours, usedMinutes) } }
lgpl-3.0
a422dab9907e318a451846488263371d
43.842105
160
0.723592
4.324873
false
false
false
false
aosp-mirror/platform_frameworks_support
room/compiler/src/test/kotlin/androidx/room/processor/FieldProcessorTest.kt
1
16484
/* * Copyright (C) 2016 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.room.processor import androidx.room.Entity import androidx.room.parser.Collate import androidx.room.parser.SQLTypeAffinity import androidx.room.solver.types.ColumnTypeAdapter import androidx.room.testing.TestInvocation import androidx.room.testing.TestProcessor import androidx.room.vo.Field import com.google.auto.common.MoreElements import com.google.auto.common.MoreTypes import com.google.common.truth.Truth import com.google.testing.compile.CompileTester import com.google.testing.compile.JavaFileObjects import com.google.testing.compile.JavaSourcesSubjectFactory import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.mockito.Mockito.mock import simpleRun import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror @Suppress("HasPlatformType") @RunWith(JUnit4::class) class FieldProcessorTest { companion object { const val ENTITY_PREFIX = """ package foo.bar; import androidx.room.*; @Entity abstract class MyEntity { """ const val ENTITY_SUFFIX = "}" val ALL_PRIMITIVES = arrayListOf( TypeKind.INT, TypeKind.BYTE, TypeKind.SHORT, TypeKind.LONG, TypeKind.CHAR, TypeKind.FLOAT, TypeKind.DOUBLE) val ARRAY_CONVERTER = JavaFileObjects.forSourceLines("foo.bar.MyConverter", """ package foo.bar; import androidx.room.*; public class MyConverter { ${ALL_PRIMITIVES.joinToString("\n") { val arrayDef = "${it.name.toLowerCase()}[]" "@TypeConverter public static String" + " arrayIntoString($arrayDef input) { return null;}" + "@TypeConverter public static $arrayDef" + " stringIntoArray${it.name}(String input) { return null;}" }} ${ALL_PRIMITIVES.joinToString("\n") { val arrayDef = "${it.box()}[]" "@TypeConverter public static String" + " arrayIntoString($arrayDef input) { return null;}" + "@TypeConverter public static $arrayDef" + " stringIntoArray${it.name}Boxed(String input) { return null;}" }} } """) private fun TypeKind.box(): String { return "java.lang." + when (this) { TypeKind.INT -> "Integer" TypeKind.CHAR -> "Character" else -> this.name.toLowerCase().capitalize() } } // these 2 box methods are ugly but makes tests nicer and they are private private fun TypeKind.typeMirror(invocation: TestInvocation): TypeMirror { return invocation.processingEnv.typeUtils.getPrimitiveType(this) } private fun TypeKind.affinity(): SQLTypeAffinity { return when (this) { TypeKind.FLOAT, TypeKind.DOUBLE -> SQLTypeAffinity.REAL else -> SQLTypeAffinity.INTEGER } } private fun TypeKind.box(invocation: TestInvocation): TypeMirror { return invocation.processingEnv.elementUtils.getTypeElement(box()).asType() } } @Test fun primitives() { ALL_PRIMITIVES.forEach { primitive -> singleEntity("${primitive.name.toLowerCase()} x;") { field, invocation -> assertThat(field, `is`( Field(name = "x", type = primitive.typeMirror(invocation), element = field.element, affinity = primitive.affinity() ))) }.compilesWithoutError() } } @Test fun boxed() { ALL_PRIMITIVES.forEach { primitive -> singleEntity("${primitive.box()} y;") { field, invocation -> assertThat(field, `is`( Field(name = "y", type = primitive.box(invocation), element = field.element, affinity = primitive.affinity()))) }.compilesWithoutError() } } @Test fun columnName() { singleEntity(""" @ColumnInfo(name = "foo") @PrimaryKey int x; """) { field, invocation -> assertThat(field, `is`( Field(name = "x", type = TypeKind.INT.typeMirror(invocation), element = field.element, columnName = "foo", affinity = SQLTypeAffinity.INTEGER))) }.compilesWithoutError() } @Test fun indexed() { singleEntity(""" @ColumnInfo(name = "foo", index = true) int x; """) { field, invocation -> assertThat(field, `is`( Field(name = "x", type = TypeKind.INT.typeMirror(invocation), element = field.element, columnName = "foo", affinity = SQLTypeAffinity.INTEGER, indexed = true))) }.compilesWithoutError() } @Test fun emptyColumnName() { singleEntity(""" @ColumnInfo(name = "") int x; """) { _, _ -> }.failsToCompile().withErrorContaining(ProcessorErrors.COLUMN_NAME_CANNOT_BE_EMPTY) } @Test fun byteArrayWithEnforcedType() { singleEntity("@TypeConverters(foo.bar.MyConverter.class)" + "@ColumnInfo(typeAffinity = ColumnInfo.TEXT) byte[] arr;") { field, invocation -> assertThat(field, `is`(Field(name = "arr", type = invocation.processingEnv.typeUtils.getArrayType( TypeKind.BYTE.typeMirror(invocation)), element = field.element, affinity = SQLTypeAffinity.TEXT))) assertThat((field.cursorValueReader as? ColumnTypeAdapter)?.typeAffinity, `is`(SQLTypeAffinity.TEXT)) }.compilesWithoutError() } @Test fun primitiveArray() { ALL_PRIMITIVES.forEach { primitive -> singleEntity("@TypeConverters(foo.bar.MyConverter.class) " + "${primitive.toString().toLowerCase()}[] arr;") { field, invocation -> assertThat(field, `is`( Field(name = "arr", type = invocation.processingEnv.typeUtils.getArrayType( primitive.typeMirror(invocation)), element = field.element, affinity = if (primitive == TypeKind.BYTE) { SQLTypeAffinity.BLOB } else { SQLTypeAffinity.TEXT }))) }.compilesWithoutError() } } @Test fun boxedArray() { ALL_PRIMITIVES.forEach { primitive -> singleEntity("@TypeConverters(foo.bar.MyConverter.class) " + "${primitive.box()}[] arr;") { field, invocation -> assertThat(field, `is`( Field(name = "arr", type = invocation.processingEnv.typeUtils.getArrayType( primitive.box(invocation)), element = field.element, affinity = SQLTypeAffinity.TEXT))) }.compilesWithoutError() } } @Test fun generic() { singleEntity(""" static class BaseClass<T> { T item; } @Entity static class Extending extends BaseClass<java.lang.Integer> { } """) { field, invocation -> assertThat(field, `is`(Field(name = "item", type = TypeKind.INT.box(invocation), element = field.element, affinity = SQLTypeAffinity.INTEGER))) }.compilesWithoutError() } @Test fun unboundGeneric() { singleEntity(""" @Entity static class BaseClass<T> { T item; } """) { _, _ -> }.failsToCompile() .withErrorContaining(ProcessorErrors.CANNOT_USE_UNBOUND_GENERICS_IN_ENTITY_FIELDS) } @Test fun nameVariations() { simpleRun { assertThat(Field(mock(Element::class.java), "x", TypeKind.INT.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("x"))) assertThat(Field(mock(Element::class.java), "x", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("x"))) assertThat(Field(mock(Element::class.java), "xAll", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER) .nameWithVariations, `is`(arrayListOf("xAll"))) } } @Test fun nameVariations_is() { val elm = mock(Element::class.java) simpleRun { assertThat(Field(elm, "isX", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("isX", "x"))) assertThat(Field(elm, "isX", TypeKind.INT.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("isX"))) assertThat(Field(elm, "is", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("is"))) assertThat(Field(elm, "isAllItems", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("isAllItems", "allItems"))) } } @Test fun nameVariations_has() { val elm = mock(Element::class.java) simpleRun { assertThat(Field(elm, "hasX", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("hasX", "x"))) assertThat(Field(elm, "hasX", TypeKind.INT.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("hasX"))) assertThat(Field(elm, "has", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("has"))) assertThat(Field(elm, "hasAllItems", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("hasAllItems", "allItems"))) } } @Test fun nameVariations_m() { val elm = mock(Element::class.java) simpleRun { assertThat(Field(elm, "mall", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("mall"))) assertThat(Field(elm, "mallVars", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("mallVars"))) assertThat(Field(elm, "mAll", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("mAll", "all"))) assertThat(Field(elm, "m", TypeKind.INT.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("m"))) assertThat(Field(elm, "mallItems", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("mallItems"))) assertThat(Field(elm, "mAllItems", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("mAllItems", "allItems"))) } } @Test fun nameVariations_underscore() { val elm = mock(Element::class.java) simpleRun { assertThat(Field(elm, "_all", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("_all", "all"))) assertThat(Field(elm, "_", TypeKind.INT.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("_"))) assertThat(Field(elm, "_allItems", TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("_allItems", "allItems"))) } } @Test fun collate() { Collate.values().forEach { collate -> singleEntity(""" @PrimaryKey @ColumnInfo(collate = ColumnInfo.${collate.name}) String code; """) { field, invocation -> assertThat(field, `is`( Field(name = "code", type = invocation.context.COMMON_TYPES.STRING, element = field.element, columnName = "code", collate = collate, affinity = SQLTypeAffinity.TEXT))) }.compilesWithoutError() } } fun singleEntity(vararg input: String, handler: (Field, invocation: TestInvocation) -> Unit): CompileTester { return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources()) .that(listOf(JavaFileObjects.forSourceString("foo.bar.MyEntity", ENTITY_PREFIX + input.joinToString("\n") + ENTITY_SUFFIX ), ARRAY_CONVERTER)) .processedWith(TestProcessor.builder() .forAnnotations(androidx.room.Entity::class) .nextRunHandler { invocation -> val (owner, field) = invocation.roundEnv .getElementsAnnotatedWith(Entity::class.java) .map { Pair(it, invocation.processingEnv.elementUtils .getAllMembers(MoreElements.asType(it)) .firstOrNull { it.kind == ElementKind.FIELD }) } .first { it.second != null } val entityContext = EntityProcessor(invocation.context, MoreElements.asType(owner)) .context val parser = FieldProcessor( baseContext = entityContext, containing = MoreTypes.asDeclared(owner.asType()), element = field!!, bindingScope = FieldProcessor.BindingScope.TWO_WAY, fieldParent = null) handler(parser.process(), invocation) true } .build()) } }
apache-2.0
7b1484d68ab558e5d18673bcbe635a81
41.927083
99
0.52554
5.418803
false
true
false
false
google/intellij-gn-plugin
src/main/java/com/google/idea/gn/psi/TemplateFunction.kt
1
5141
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package com.google.idea.gn.psi import com.google.idea.gn.GnKeys import com.google.idea.gn.completion.CompletionIdentifier import com.google.idea.gn.psi.builtin.BuiltinVariable import com.google.idea.gn.psi.builtin.ForwardVariablesFrom import com.google.idea.gn.psi.builtin.Template import com.google.idea.gn.psi.scope.BlockScope import com.google.idea.gn.psi.scope.BuiltinScope import com.google.idea.gn.psi.scope.Scope import com.google.idea.gn.psi.scope.TemplateScope import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.parentsOfType class TemplateFunction(override val identifierName: String, val declaration: GnCall, val declarationScope: Scope) : Function { override fun execute(call: GnCall, targetScope: Scope): GnValue? { // Prevent recurring forever. if (PsiTreeUtil.isAncestor(declaration, call, false)) { return null } val declarationBlock = declaration.block ?: return null val executionScope: BlockScope = TemplateScope(declarationScope, targetScope.callSite ?: call) executionScope.addVariable( Variable(Template.TARGET_NAME, GnPsiUtil.evaluateFirst(call.exprList, targetScope))) call.block?.let { callBlock -> val innerScope: Scope = BlockScope(targetScope) Visitor(innerScope).visitBlock(callBlock) innerScope.consolidateVariables()?.let { executionScope .addVariable(Variable(BuiltinVariable.INVOKER.identifierName, GnValue(it))) } } Visitor(BlockScope(executionScope)).visitBlock(declarationBlock) return null } fun buildDummyInvokeScope(): Scope { val scope = BlockScope(declarationScope) scope.addVariable(Variable(Template.TARGET_NAME, GnValue("dummy"))) // TODO allow any variables to come from invoker. scope.addVariable(Variable(BuiltinVariable.INVOKER.identifierName)) return scope } override val variables: Map<String, FunctionVariable> by lazy { gatherInvokerVariables() ?: emptyMap() } override val identifierType: CompletionIdentifier.IdentifierType get() = CompletionIdentifier.IdentifierType.TEMPLATE override val isBuiltin: Boolean get() = false private fun gatherInvokerVariables(): Map<String, FunctionVariable>? { val block = declaration.block ?: return null val variables = mutableMapOf<String, FunctionVariable>() block.accept(Visitor(BlockScope(declarationScope), object : Visitor.VisitorDelegate() { fun visitForwardVariables(call: GnCall) { val exprList = call.exprList.exprList if (exprList.size < 2) { return } if (!exprList[0].textMatches(BuiltinVariable.INVOKER.identifierName)) { return } // We're evaluating on built-in scope assuming that variables are usually set as literals. val forward = GnPsiUtil.evaluate(exprList[1], BuiltinScope) forward?.list?.let { vars -> val varMap = vars.mapNotNull { it.string?.let { s -> Pair(s, TemplateVariable(s)) } } variables.putAll(varMap) return } forward?.string?.let { star -> if (star == ForwardVariablesFrom.STAR) { val parent = call.parent.parentsOfType(GnCall::class.java).firstOrNull() ?: return if (parent != declaration) { // Forward all variables from the resolved function. parent.getUserData(GnKeys.CALL_RESOLVED_FUNCTION)?.let { f -> variables.putAll(f.variables) } } } return } } override fun resolveCall(call: GnCall, function: Function?): Visitor.CallAction = when (function) { is Template -> Visitor.CallAction.EXECUTE is ForwardVariablesFrom -> { visitForwardVariables(call) Visitor.CallAction.SKIP } else -> Visitor.CallAction.VISIT_BLOCK } override fun shouldExecuteExpr(expr: GnExpr): Boolean { expr.accept(object : PsiElementVisitor() { override fun visitElement(element: PsiElement) { if (element !is GnScopeAccess) { element.acceptChildren(this) return } if (element.idList.size < 2) { return } val first = element.idList[0] if (!first.textMatches(BuiltinVariable.INVOKER.identifierName)) { return } val second = element.idList[1].text variables[second] = TemplateVariable(second) } }) // We allow block expressions to be evaluated, since we can have variable // forwarding happening in there. return (expr is GnPrimaryExpr && expr.block != null) } override val observeConditions: Boolean get() = false })) return variables } }
bsd-3-clause
1f3fa5b4951e4a997ca77288a2ec7966
34.701389
126
0.659599
4.581996
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/util/AgendaUtils.kt
1
2385
package com.orgzly.android.util import com.orgzly.android.ui.notes.query.agenda.AgendaItems.ExpandableOrgRange import com.orgzly.org.datetime.* import org.joda.time.DateTime import java.util.* object AgendaUtils { data class ExpandedOrgRange(val isOverdueToday: Boolean, val expanded: Set<DateTime>) fun expandOrgDateTime(expandable: ExpandableOrgRange, now: DateTime, days: Int): ExpandedOrgRange { val today = now.withTimeAtStartOfDay() // Only unique values val result: MutableSet<DateTime> = LinkedHashSet() var rangeStart = expandable.range.startTime val rangeEnd = expandable.range.endTime // Check if overdue var isOverdueToday = false if (expandable.canBeOverdueToday) { val nowCal = today.toGregorianCalendar() if (rangeStart.calendar.before(nowCal)) { isOverdueToday = true } } var to = today.plusDays(days).withTimeAtStartOfDay() if (rangeEnd == null) { result.addAll(OrgDateTimeUtils.getTimesInInterval( rangeStart, today, to, 0, true, expandable.warningPeriod, 0)) } else { // a time range if (to.isAfter(rangeEnd.calendar.timeInMillis)) { to = DateTime(rangeEnd.calendar).withTimeAtStartOfDay().plusDays(1) } // If start time has no repeater, use a daily repeater if (!rangeStart.hasRepeater()) { val start = DateTime(rangeStart.calendar) val repeater = OrgRepeater(OrgRepeater.Type.CATCH_UP, 1, OrgInterval.Unit.DAY) rangeStart = buildOrgDateTimeFromDate(start, repeater) } result.addAll(OrgDateTimeUtils.getTimesInInterval( rangeStart, today, to, 0, true, expandable.warningPeriod, 0)) } return ExpandedOrgRange(isOverdueToday, TreeSet(result)) } private fun buildOrgDateTimeFromDate(date: DateTime, repeater: OrgRepeater?): OrgDateTime { return OrgDateTime.Builder().apply { setYear(date.year) setMonth(date.monthOfYear - 1) setDay(date.dayOfMonth) setHour(date.hourOfDay) setMinute(date.minuteOfHour) if (repeater != null) { setRepeater(repeater) } }.build() } }
gpl-3.0
e27ea7c977efa4eeead770ee5646000e
33.085714
103
0.623899
4.595376
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/manager/ActionIconManager.kt
1
20775
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.legacy.action.manager import android.graphics.drawable.Drawable import android.widget.Toast import jp.hazuki.yuzubrowser.bookmark.repository.BookmarkManager import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.legacy.action.Action import jp.hazuki.yuzubrowser.legacy.action.SingleAction import jp.hazuki.yuzubrowser.legacy.action.item.CustomSingleAction import jp.hazuki.yuzubrowser.legacy.action.item.WebScrollSingleAction import jp.hazuki.yuzubrowser.legacy.action.item.startactivity.StartActivitySingleAction import jp.hazuki.yuzubrowser.legacy.browser.BrowserInfo import jp.hazuki.yuzubrowser.legacy.utils.graphics.SimpleLayerDrawable import jp.hazuki.yuzubrowser.legacy.utils.graphics.TabListActionTextDrawable import jp.hazuki.yuzubrowser.ui.settings.AppPrefs class ActionIconManager(val info: BrowserInfo) { operator fun get(action: Action): Drawable? { return if (action.isEmpty()) null else get(action[0]) } operator fun get(action: SingleAction): Drawable? { when (action.id) { SingleAction.GO_BACK -> { val tab = info.currentTabData ?: return null return if (tab.mWebView.canGoBack()) info.resourcesByInfo.getDrawable(R.drawable.ic_arrow_back_white_24dp, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_arrow_back_disable_white_24dp, info.themeByInfo) } SingleAction.GO_FORWARD -> { val tab = info.currentTabData ?: return null return if (tab.mWebView.canGoForward()) info.resourcesByInfo.getDrawable(R.drawable.ic_arrow_forward_white_24dp, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_arrow_forward_disable_white_24dp, info.themeByInfo) } SingleAction.WEB_RELOAD_STOP -> { val tab = info.currentTabData ?: return null return if (tab.isInPageLoad) info.resourcesByInfo.getDrawable(R.drawable.ic_clear_white_24dp, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_refresh_white_24px, info.themeByInfo) } SingleAction.WEB_RELOAD -> return info.resourcesByInfo.getDrawable(R.drawable.ic_refresh_white_24px, info.themeByInfo) SingleAction.WEB_STOP -> return info.resourcesByInfo.getDrawable(R.drawable.ic_clear_white_24dp, info.themeByInfo) SingleAction.GO_HOME -> return info.resourcesByInfo.getDrawable(R.drawable.ic_home_white_24dp, info.themeByInfo) SingleAction.ZOOM_IN -> return info.resourcesByInfo.getDrawable(R.drawable.ic_zoom_in_white_24dp, info.themeByInfo) SingleAction.ZOOM_OUT -> return info.resourcesByInfo.getDrawable(R.drawable.ic_zoom_out_white_24dp, info.themeByInfo) SingleAction.PAGE_UP -> return info.resourcesByInfo.getDrawable(R.drawable.ic_arrow_upward_white_24dp, info.themeByInfo) SingleAction.PAGE_DOWN -> return info.resourcesByInfo.getDrawable(R.drawable.ic_arrow_downward_white_24dp, info.themeByInfo) SingleAction.PAGE_TOP -> return info.resourcesByInfo.getDrawable(R.drawable.ic_keyboard_arrow_up_black_24dp, info.themeByInfo) SingleAction.PAGE_BOTTOM -> return info.resourcesByInfo.getDrawable(R.drawable.ic_keyboard_arrow_down_black_24dp, info.themeByInfo) SingleAction.PAGE_SCROLL -> { val id = (action as WebScrollSingleAction).iconResourceId return if (id > 0) info.resourcesByInfo.getDrawable(action.iconResourceId, info.themeByInfo) else null } SingleAction.PAGE_FAST_SCROLL -> return info.resourcesByInfo.getDrawable(R.drawable.ic_scroll_white_24dp, info.themeByInfo) SingleAction.PAGE_AUTO_SCROLL -> return info.resourcesByInfo.getDrawable(R.drawable.ic_play_arrow_white_24dp, info.themeByInfo) SingleAction.FOCUS_UP -> return info.resourcesByInfo.getDrawable(R.drawable.ic_label_up_white_24px, info.themeByInfo) SingleAction.FOCUS_DOWN -> return info.resourcesByInfo.getDrawable(R.drawable.ic_label_down_white_24px, info.themeByInfo) SingleAction.FOCUS_LEFT -> return info.resourcesByInfo.getDrawable(R.drawable.ic_label_left_white_24px, info.themeByInfo) SingleAction.FOCUS_RIGHT -> return info.resourcesByInfo.getDrawable(R.drawable.ic_label_right_white_24px, info.themeByInfo) SingleAction.FOCUS_CLICK -> return info.resourcesByInfo.getDrawable(R.drawable.ic_fiber_manual_record_white_24dp, info.themeByInfo) SingleAction.TOGGLE_JS -> { val tab = info.currentTabData ?: return null return if (tab.mWebView.webSettings.javaScriptEnabled) info.resourcesByInfo.getDrawable(R.drawable.ic_memory_white_24dp, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_memory_white_disable_24px, info.themeByInfo) } SingleAction.TOGGLE_IMAGE -> { val tab = info.currentTabData ?: return null return if (tab.mWebView.webSettings.loadsImagesAutomatically) info.resourcesByInfo.getDrawable(R.drawable.ic_crop_original_white_24px, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_crop_original_disable_white_24px, info.themeByInfo) } SingleAction.TOGGLE_COOKIE -> { val tab = info.currentTabData ?: return null return if (tab.isEnableCookie) info.resourcesByInfo.getDrawable(R.drawable.ic_cookie_24dp, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_cookie_disable_24dp, info.themeByInfo) } SingleAction.TOGGLE_USERJS -> { return if (info.isEnableUserScript) info.resourcesByInfo.getDrawable(R.drawable.ic_memory_white_24dp, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_memory_white_disable_24px, info.themeByInfo) } SingleAction.TOGGLE_NAV_LOCK -> { val tab = info.currentTabData ?: return null return if (tab.isNavLock) info.resourcesByInfo.getDrawable(R.drawable.ic_lock_outline_white_24px, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_lock_open_white_24px, info.themeByInfo) } SingleAction.PAGE_INFO -> return info.resourcesByInfo.getDrawable(R.drawable.ic_info_white_24dp, info.themeByInfo) SingleAction.COPY_URL -> return info.resourcesByInfo.getDrawable(R.drawable.ic_mode_edit_white_24dp, info.themeByInfo) SingleAction.COPY_TITLE -> return info.resourcesByInfo.getDrawable(R.drawable.ic_mode_edit_white_24dp, info.themeByInfo) SingleAction.COPY_TITLE_URL -> return info.resourcesByInfo.getDrawable(R.drawable.ic_mode_edit_white_24dp, info.themeByInfo) SingleAction.TAB_HISTORY -> return info.resourcesByInfo.getDrawable(R.drawable.ic_undo_white_24dp, info.themeByInfo) SingleAction.MOUSE_POINTER -> return info.resourcesByInfo.getDrawable(R.drawable.ic_mouse_white_24dp, info.themeByInfo) SingleAction.FIND_ON_PAGE -> return info.resourcesByInfo.getDrawable(R.drawable.ic_find_in_page_white_24px, info.themeByInfo) SingleAction.SAVE_SCREENSHOT -> return info.resourcesByInfo.getDrawable(R.drawable.ic_photo_white_24dp, info.themeByInfo) SingleAction.SHARE_SCREENSHOT -> return info.resourcesByInfo.getDrawable(R.drawable.ic_photo_white_24dp, info.themeByInfo) SingleAction.SAVE_PAGE -> return info.resourcesByInfo.getDrawable(R.drawable.ic_save_white_24dp, info.themeByInfo) SingleAction.OPEN_URL -> return info.resourcesByInfo.getDrawable(R.drawable.ic_book_white_24dp, info.themeByInfo) SingleAction.TRANSLATE_PAGE -> return info.resourcesByInfo.getDrawable(R.drawable.ic_g_translate_white_24px, info.themeByInfo) SingleAction.NEW_TAB -> return info.resourcesByInfo.getDrawable(R.drawable.ic_add_box_white_24dp, info.themeByInfo) SingleAction.CLOSE_TAB -> return info.resourcesByInfo.getDrawable(R.drawable.ic_minas_box_white_24dp, info.themeByInfo) SingleAction.CLOSE_ALL -> return info.resourcesByInfo.getDrawable(R.drawable.ic_minas_box_white_24dp, info.themeByInfo) SingleAction.CLOSE_AUTO_SELECT -> return info.resourcesByInfo.getDrawable(R.drawable.ic_minas_box_white_24dp, info.themeByInfo) SingleAction.CLOSE_OTHERS -> return info.resourcesByInfo.getDrawable(R.drawable.ic_minas_box_white_24dp, info.themeByInfo) SingleAction.LEFT_TAB -> return info.resourcesByInfo.getDrawable(R.drawable.ic_chevron_left_white_24dp, info.themeByInfo) SingleAction.RIGHT_TAB -> return info.resourcesByInfo.getDrawable(R.drawable.ic_chevron_right_white_24dp, info.themeByInfo) SingleAction.SWAP_LEFT_TAB -> return info.resourcesByInfo.getDrawable(R.drawable.ic_fast_rewind_white_24dp, info.themeByInfo) SingleAction.SWAP_RIGHT_TAB -> return info.resourcesByInfo.getDrawable(R.drawable.ic_fast_forward_white_24dp, info.themeByInfo) SingleAction.TAB_LIST -> { val base = info.resourcesByInfo.getDrawable(R.drawable.ic_tab_white_24dp, info.themeByInfo) val text = TabListActionTextDrawable(info.applicationContextInfo, info.tabSize) return SimpleLayerDrawable(base, text) } SingleAction.CLOSE_ALL_LEFT -> return info.resourcesByInfo.getDrawable(R.drawable.ic_skip_previous_white_24dp, info.themeByInfo) SingleAction.CLOSE_ALL_RIGHT -> return info.resourcesByInfo.getDrawable(R.drawable.ic_skip_next_white_24dp, info.themeByInfo) SingleAction.RESTORE_TAB -> return info.resourcesByInfo.getDrawable(R.drawable.ic_redo_white_24dp, info.themeByInfo) SingleAction.REPLICATE_TAB -> return info.resourcesByInfo.getDrawable(R.drawable.ic_content_copy_white_24dp, info.themeByInfo) SingleAction.SHOW_SEARCHBOX -> return info.resourcesByInfo.getDrawable(R.drawable.ic_search_white_24dp, info.themeByInfo) SingleAction.PASTE_SEARCHBOX -> return info.resourcesByInfo.getDrawable(R.drawable.ic_content_paste_white_24dp, info.themeByInfo) SingleAction.PASTE_GO -> return info.resourcesByInfo.getDrawable(R.drawable.ic_content_paste_white_24dp, info.themeByInfo) SingleAction.SHOW_BOOKMARK -> return info.resourcesByInfo.getDrawable(R.drawable.ic_collections_bookmark_white_24dp, info.themeByInfo) SingleAction.SHOW_HISTORY -> return info.resourcesByInfo.getDrawable(R.drawable.ic_history_white_24dp, info.themeByInfo) SingleAction.SHOW_DOWNLOADS -> return info.resourcesByInfo.getDrawable(R.drawable.ic_file_download_white_24dp, info.themeByInfo) SingleAction.SHOW_SETTINGS -> return info.resourcesByInfo.getDrawable(R.drawable.ic_settings_white_24dp, info.themeByInfo) SingleAction.OPEN_SPEED_DIAL -> return info.resourcesByInfo.getDrawable(R.drawable.ic_speed_dial_white_24dp, info.themeByInfo) SingleAction.ADD_BOOKMARK -> { val tab = info.currentTabData ?: return null return if (BookmarkManager.getInstance(info.applicationContextInfo).isBookmarked(tab.url)) info.resourcesByInfo.getDrawable(R.drawable.ic_star_white_24px, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_star_border_white_24px, info.themeByInfo) } SingleAction.ADD_SPEED_DIAL -> return info.resourcesByInfo.getDrawable(R.drawable.ic_speed_dial_add_white_24dp, info.themeByInfo) SingleAction.ADD_PATTERN -> return info.resourcesByInfo.getDrawable(R.drawable.ic_pattern_add_white_24dp, info.themeByInfo) SingleAction.ADD_TO_HOME -> return info.resourcesByInfo.getDrawable(R.drawable.ic_add_to_home_white_24dp, info.themeByInfo) SingleAction.SUB_GESTURE -> return info.resourcesByInfo.getDrawable(R.drawable.ic_gesture_white_24dp, info.themeByInfo) SingleAction.CLEAR_DATA -> return info.resourcesByInfo.getDrawable(R.drawable.ic_delete_sweep_white_24px, info.themeByInfo) SingleAction.SHOW_PROXY_SETTING -> return info.resourcesByInfo.getDrawable(R.drawable.ic_import_export_white_24dp, info.themeByInfo) SingleAction.ORIENTATION_SETTING -> return info.resourcesByInfo.getDrawable(R.drawable.ic_stay_current_portrait_white_24dp, info.themeByInfo) SingleAction.OPEN_LINK_SETTING -> return info.resourcesByInfo.getDrawable(R.drawable.ic_link_white_24dp, info.themeByInfo) SingleAction.USERAGENT_SETTING -> return info.resourcesByInfo.getDrawable(R.drawable.ic_group_white_24dp, info.themeByInfo) SingleAction.TEXTSIZE_SETTING -> return info.resourcesByInfo.getDrawable(R.drawable.ic_format_size_white_24dp, info.themeByInfo) SingleAction.USERJS_SETTING -> return info.resourcesByInfo.getDrawable(R.drawable.ic_memory_white_24dp, info.themeByInfo) SingleAction.WEB_ENCODE_SETTING -> return info.resourcesByInfo.getDrawable(R.drawable.ic_format_shapes_white_24dp, info.themeByInfo) SingleAction.DEFALUT_USERAGENT_SETTING -> return info.resourcesByInfo.getDrawable(R.drawable.ic_group_white_24dp, info.themeByInfo) SingleAction.RENDER_SETTING, SingleAction.RENDER_ALL_SETTING -> return info.resourcesByInfo.getDrawable(R.drawable.ic_blur_linear_white_24dp, info.themeByInfo) SingleAction.TOGGLE_VISIBLE_TAB -> return info.resourcesByInfo.getDrawable(R.drawable.ic_remove_red_eye_white_24dp, info.themeByInfo) SingleAction.TOGGLE_VISIBLE_URL -> return info.resourcesByInfo.getDrawable(R.drawable.ic_remove_red_eye_white_24dp, info.themeByInfo) SingleAction.TOGGLE_VISIBLE_PROGRESS -> return info.resourcesByInfo.getDrawable(R.drawable.ic_remove_red_eye_white_24dp, info.themeByInfo) SingleAction.TOGGLE_VISIBLE_CUSTOM -> return info.resourcesByInfo.getDrawable(R.drawable.ic_remove_red_eye_white_24dp, info.themeByInfo) SingleAction.TOGGLE_WEB_TITLEBAR -> return info.resourcesByInfo.getDrawable(R.drawable.ic_web_asset_white_24dp, info.themeByInfo) SingleAction.TOGGLE_WEB_GESTURE -> { return if (info.isEnableGesture) info.resourcesByInfo.getDrawable(R.drawable.ic_gesture_white_24dp, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_gesture_white_disable_24px, info.themeByInfo) } SingleAction.TOGGLE_FLICK -> { return if (AppPrefs.flick_enable.get()) info.resourcesByInfo.getDrawable(R.drawable.ic_gesture_white_24dp, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_gesture_white_disable_24px, info.themeByInfo) } SingleAction.TOGGLE_QUICK_CONTROL -> { return if (info.isEnableQuickControl) info.resourcesByInfo.getDrawable(R.drawable.ic_pie_chart_outlined_white_24px, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_pie_chart_outlined_disable_white_24px, info.themeByInfo) } SingleAction.TOGGLE_MULTI_FINGER_GESTURE -> { return if (info.isEnableMultiFingerGesture) info.resourcesByInfo.getDrawable(R.drawable.ic_gesture_white_24dp, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_gesture_white_disable_24px, info.themeByInfo) } SingleAction.TOGGLE_AD_BLOCK -> { return if (info.isEnableAdBlock) info.resourcesByInfo.getDrawable(R.drawable.ic_ad_block_enable_white_24dp, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_ad_block_disable_white_24dp, info.themeByInfo) } SingleAction.OPEN_BLACK_LIST -> return info.resourcesByInfo.getDrawable(R.drawable.ic_open_ad_block_black_24dp, info.themeByInfo) SingleAction.OPEN_WHITE_LIST -> return info.resourcesByInfo.getDrawable(R.drawable.ic_open_ad_block_white_24dp, info.themeByInfo) SingleAction.OPEN_WHITE_PATE_LIST -> return info.resourcesByInfo.getDrawable(R.drawable.ic_open_ad_block_white_page_24dp, info.themeByInfo) SingleAction.ADD_WHITE_LIST_PAGE -> return info.resourcesByInfo.getDrawable(R.drawable.ic_add_white_page_24dp, info.themeByInfo) SingleAction.SHARE_WEB -> return info.resourcesByInfo.getDrawable(R.drawable.ic_share_white_24dp, info.themeByInfo) SingleAction.OPEN_OTHER -> return info.resourcesByInfo.getDrawable(R.drawable.ic_public_white_24dp, info.themeByInfo) SingleAction.START_ACTIVITY -> return (action as StartActivitySingleAction).getIconDrawable(info.applicationContextInfo) SingleAction.TOGGLE_FULL_SCREEN -> return info.resourcesByInfo.getDrawable(R.drawable.ic_fullscreen_white_24dp, info.themeByInfo) SingleAction.OPEN_OPTIONS_MENU -> return info.resourcesByInfo.getDrawable(R.drawable.ic_more_vert_white_24dp, info.themeByInfo) SingleAction.CUSTOM_MENU -> return info.resourcesByInfo.getDrawable(R.drawable.ic_more_vert_white_24dp, info.themeByInfo) SingleAction.FINISH -> return info.resourcesByInfo.getDrawable(R.drawable.ic_power_settings_white_24dp, info.themeByInfo) SingleAction.MINIMIZE -> return info.resourcesByInfo.getDrawable(R.drawable.ic_fullscreen_exit_white_24dp, info.themeByInfo) SingleAction.CUSTOM_ACTION -> return get((action as CustomSingleAction).action) SingleAction.VIBRATION -> return null SingleAction.TOAST -> return null SingleAction.PRIVATE -> return if (info.isPrivateMode) info.resourcesByInfo.getDrawable(R.drawable.ic_private_white_24dp, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_private_white_disable_24dp, info.themeByInfo) SingleAction.VIEW_SOURCE -> return info.resourcesByInfo.getDrawable(R.drawable.ic_view_source_white_24dp, info.themeByInfo) SingleAction.PRINT -> return info.resourcesByInfo.getDrawable(R.drawable.ic_print_white_24dp, info.themeByInfo) SingleAction.TAB_PINNING -> { val tab = info.currentTabData ?: return null return if (tab.isPinning) info.resourcesByInfo.getDrawable(R.drawable.ic_pin_24dp, info.themeByInfo) else info.resourcesByInfo.getDrawable(R.drawable.ic_pin_disable_24dp, info.themeByInfo) } SingleAction.ALL_ACTION -> return info.resourcesByInfo.getDrawable(R.drawable.ic_list_white_24dp, info.themeByInfo) SingleAction.READER_MODE -> return info.resourcesByInfo.getDrawable(R.drawable.ic_chrome_reader_mode_white_24dp, info.themeByInfo) SingleAction.READ_IT_LATER -> return info.resourcesByInfo.getDrawable(R.drawable.ic_watch_later_white_24dp, info.themeByInfo) SingleAction.READ_IT_LATER_LIST -> return info.resourcesByInfo.getDrawable(R.drawable.ic_read_it_list_white_24px, info.themeByInfo) SingleAction.WEB_THEME -> return info.resourcesByInfo.getDrawable(R.drawable.ic_baseline_dark_mode_24, info.themeByInfo) else -> { Toast.makeText(info.applicationContextInfo, "Unknown action:" + action.id, Toast.LENGTH_LONG).show() return null } } } }
apache-2.0
559e141dd3f44aef03862ea8a56cd24e
80.791339
171
0.703779
4.218274
false
false
false
false
seventhroot/elysium
bukkit/rpk-crafting-skill-bukkit/src/main/kotlin/com/rpkit/craftingskill/bukkit/listener/BlockBreakListener.kt
1
4273
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.craftingskill.bukkit.listener import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.core.bukkit.util.addLore import com.rpkit.craftingskill.bukkit.RPKCraftingSkillBukkit import com.rpkit.craftingskill.bukkit.craftingskill.RPKCraftingAction import com.rpkit.craftingskill.bukkit.craftingskill.RPKCraftingSkillProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import org.bukkit.GameMode import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.block.BlockBreakEvent import org.bukkit.inventory.ItemStack import kotlin.math.min import kotlin.math.roundToInt import kotlin.random.Random class BlockBreakListener(private val plugin: RPKCraftingSkillBukkit): Listener { @EventHandler fun onBlockBreak(event: BlockBreakEvent) { val bukkitPlayer = event.player if (bukkitPlayer.gameMode == GameMode.CREATIVE || bukkitPlayer.gameMode == GameMode.SPECTATOR) return val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val craftingSkillProvider = plugin.core.serviceManager.getServiceProvider(RPKCraftingSkillProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer) if (minecraftProfile == null) { event.isDropItems = false return } val character = characterProvider.getActiveCharacter(minecraftProfile) if (character == null) { event.isDropItems = false return } val itemsToDrop = mutableListOf<ItemStack>() for (item in event.block.getDrops(event.player.inventory.itemInMainHand)) { val material = item.type val craftingSkill = craftingSkillProvider.getCraftingExperience(character, RPKCraftingAction.MINE, material) val quality = craftingSkillProvider.getQualityFor(RPKCraftingAction.MINE, material, craftingSkill) val amount = craftingSkillProvider.getAmountFor(RPKCraftingAction.MINE, material, craftingSkill) if (quality != null) { item.addLore(quality.lore) } if (amount > 1) { item.amount = amount.roundToInt() itemsToDrop.add(item) } else if (amount < 1) { val random = Random.nextDouble() if (random <= amount) { item.amount = 1 itemsToDrop.add(item) } } else { itemsToDrop.add(item) } val maxExperience = plugin.config.getConfigurationSection("mining.$material") ?.getKeys(false) ?.map(String::toInt) ?.max() ?: 0 if (maxExperience != 0 && craftingSkill < maxExperience) { val totalExperience = min(craftingSkill + item.amount, maxExperience) craftingSkillProvider.setCraftingExperience(character, RPKCraftingAction.MINE, material, totalExperience) event.player.sendMessage(plugin.messages["mine-experience", mapOf( Pair("total-experience", totalExperience.toString()), Pair("received-experience", item.amount.toString()) )]) } } event.isDropItems = false for (item in itemsToDrop) { event.block.world.dropItemNaturally(event.block.location, item) } } }
apache-2.0
e21221eee016a8dd7972e73b0f440998
43.989474
121
0.673063
5.074822
false
false
false
false
Kotlin/kotlinx.dom
src/main/kotlin/Classes.kt
1
1753
package kotlinx.dom import org.w3c.dom.* import java.util.* /** Returns true if the element has the given CSS class style in its 'class' attribute */ fun Element.hasClass(cssClass: String): Boolean = classes.matches("""(^|.*\s+)$cssClass($|\s+.*)""".toRegex()) /** * Adds CSS class to element. Has no effect if all specified classes are already in class attribute of the element * * @return true if at least one class has been added */ fun Element.addClass(vararg cssClasses: String): Boolean { val missingClasses = cssClasses.filterNot { hasClass(it) } if (missingClasses.isNotEmpty()) { val presentClasses = classes.trim() classes = buildString { append(presentClasses) if (!presentClasses.isEmpty()) { append(" ") } missingClasses.joinTo(this, " ") } return true } return false } /** * Removes all [cssClasses] from element. Has no effect if all specified classes are missing in class attribute of the element * * @return true if at least one class has been removed */ fun Element.removeClass(vararg cssClasses: String): Boolean { if (cssClasses.any { hasClass(it) }) { val toBeRemoved = cssClasses.toSet() classes = classes.trim().split("\\s+".toRegex()).filter { it !in toBeRemoved }.joinToString(" ") return true } return false } var Element.classes: String get() = this.getAttribute("class") ?: "" set(value) { this.setAttribute("class", value) } var Element.classSet: Set<String> get() { return this.className.split("""\s+""".toRegex()).filter { it.isNotEmpty() }.toSet() } set(value) { this.className = value.joinToString(" ") }
apache-2.0
5345f42efb54e524bb9b236136abb36c
29.241379
126
0.630918
4.115023
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/problem/util/ParserDtoUtil.kt
1
13782
package org.evomaster.core.problem.util import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import org.evomaster.client.java.controller.api.dto.SutInfoDto import org.evomaster.core.Lazy import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.problem.rest.RestActionBuilderV3 import org.evomaster.core.search.gene.BooleanGene import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.ObjectGene import org.evomaster.core.search.gene.SeededGene import org.evomaster.core.search.gene.collection.* import org.evomaster.core.search.gene.datetime.DateTimeGene import org.evomaster.core.search.gene.numeric.* import org.evomaster.core.search.gene.optional.FlexibleGene import org.evomaster.core.search.gene.optional.NullableGene import org.evomaster.core.search.gene.optional.OptionalGene import org.evomaster.core.search.gene.placeholder.CycleObjectGene import org.evomaster.core.search.gene.regex.RegexGene import org.evomaster.core.search.gene.string.NumericStringGene import org.evomaster.core.search.gene.string.StringGene import org.slf4j.Logger import org.slf4j.LoggerFactory object ParserDtoUtil { private val objectMapper = ObjectMapper() private val log: Logger = LoggerFactory.getLogger(ParserDtoUtil::class.java) fun getJsonNodeFromText(text: String) : JsonNode?{ return try { objectMapper.readTree(text) }catch (e: Exception){ null } } /** * get or parse schema of dto classes from [infoDto] as gene * @return a map of dto class name to corresponding gene */ fun getOrParseDtoWithSutInfo(infoDto: SutInfoDto) : Map<String, Gene>{ /* need to get all for handling `ref` */ val names = infoDto.unitsInfoDto?.parsedDtos?.keys?.toList()?:return emptyMap() val schemas = names.map { infoDto.unitsInfoDto.parsedDtos[it]!! } //TODO need to check: referType is same with the name? val genes = RestActionBuilderV3.createObjectGeneForDTOs(names, schemas, names) Lazy.assert { names.size == genes.size } return names.mapIndexed { index, s -> s to genes[index] }.toMap() } /** * parse gene based on json node */ fun parseJsonNodeAsGene(name: String, jsonNode: JsonNode): Gene{ return parseJsonNodeAsGene(name, jsonNode, null) ?:throw IllegalStateException("Fail to parse the given json node: ${jsonNode.toPrettyString()}") } /** * parse gene based on json node and optionally employ given [objectGeneCluster] to parse object gene */ fun parseJsonNodeAsGene(name: String, jsonNode: JsonNode, objectGeneCluster: Map<String, Gene>?): Gene?{ return when{ jsonNode.isBoolean -> BooleanGene(name, jsonNode.booleanValue()) jsonNode.isBigDecimal -> BigDecimalGene(name, jsonNode.decimalValue()) jsonNode.isDouble -> DoubleGene(name, jsonNode.doubleValue()) jsonNode.isFloat -> FloatGene(name, jsonNode.floatValue()) jsonNode.isInt -> IntegerGene(name, jsonNode.intValue()) jsonNode.isLong -> LongGene(name, jsonNode.longValue()) jsonNode.isShort -> IntegerGene(name, jsonNode.shortValue().toInt(), min = Short.MIN_VALUE.toInt(), max = Short.MAX_VALUE.toInt()) jsonNode.isTextual -> { StringGene(name, jsonNode.textValue()) } jsonNode.isArray -> { val elements = jsonNode.map { parseJsonNodeAsGene(name + "_item", it, objectGeneCluster) } if (elements.any { it == null }) return null if (elements.isNotEmpty()){ val template = if (elements.any { ParamUtil.getValueGene(it!!) is ObjectGene }) elements.maxByOrNull { (ParamUtil.getValueGene(it!!) as? ObjectGene)?.fields?.size ?: -1 }!! else elements.first() ArrayGene(name, template = template!!.copy()) } else ArrayGene(name, template = StringGene(name + "_item")) } jsonNode.isObject ->{ if (objectGeneCluster == null){ inferGeneBasedOnJsonNode(name, jsonNode, objectGeneCluster)?: return null }else { (findAndCopyExtractedObjectDto(jsonNode, objectGeneCluster) ?: inferGeneBasedOnJsonNode(name, jsonNode, objectGeneCluster))?:return null } } jsonNode.isNull -> { Lazy.assert { objectGeneCluster == null } // TODO change it to NullGene later return NullableGene(name, StringGene(name)).also { it.isPresent = false } } else -> throw IllegalStateException("Not support to parse json object with the type ${jsonNode.nodeType.name}") } } private fun inferGeneBasedOnJsonNode(name: String, jsonNode : JsonNode, objectGeneCluster: Map<String, Gene>?) : Gene?{ if (jsonNode.size() == 0) return FixedMapGene(name, StringGene("key"), StringGene("value")) val values = jsonNode.fields().asSequence().map { parseJsonNodeAsGene(it.key, it.value, objectGeneCluster) }.toMutableList() if (values.any { it == null }) return null // val groupedValues = values.filterNotNull().groupBy { g-> // val v = ParamUtil.getValueGene(g) // if (v is ObjectGene) v.refType?:(v.fields.joinToString("-") { f->f.name }) else v::class.java.name // } return FlexibleMapGene(name, StringGene("key"), values.first()!!.copy()) } private fun findAndCopyExtractedObjectDto(node: JsonNode, objectGeneMap: Map<String, Gene>) : ObjectGene? { return objectGeneMap.values.filterIsInstance<ObjectGene>().firstOrNull { o-> var all = true node.fields().forEach { f -> all = all && o.fields.any { of -> of.name.equals(f.key, ignoreCase = true) } } all }?.copy() as? ObjectGene } /** * wrap the given [gene] with OptionalGene if the gene is not */ fun wrapWithOptionalGene(gene: Gene, isOptional: Boolean): Gene{ return if (isOptional && gene !is OptionalGene) OptionalGene(gene.name, gene) else gene } /** * set value of gene based on [stringValue] with json format */ fun setGeneBasedOnString(gene: Gene, stringValue: String?){ val valueGene = ParamUtil.getValueGene(gene) if (stringValue != null){ when(valueGene){ is IntegerGene -> valueGene.setValueWithRawString(stringValue) is DoubleGene -> valueGene.setValueWithRawString(stringValue) is FloatGene -> valueGene.setValueWithRawString(stringValue) is BooleanGene -> valueGene.setValueWithRawString(stringValue) is StringGene -> valueGene.value = stringValue is BigDecimalGene -> valueGene.setValueWithRawString(stringValue) is BigIntegerGene -> valueGene.setValueWithRawString(stringValue) is NumericStringGene -> valueGene.number.setValueWithRawString(stringValue) is RegexGene -> { // TODO set value based on RegexGene LoggingUtil.uniqueWarn(log, "do not handle setGeneBasedOnString with stringValue($stringValue) for Regex") } is LongGene -> valueGene.setValueWithRawString(stringValue) is EnumGene<*> -> valueGene.setValueWithRawString(stringValue) is SeededGene<*> -> { valueGene.employSeeded = false setGeneBasedOnString(valueGene.gene as Gene, stringValue) } is PairGene<*, *> -> { throw IllegalStateException("should not really happen since this gene is only") } is DateTimeGene ->{ // TODO LoggingUtil.uniqueWarn(log, "do not handle setGeneBasedOnString with stringValue($stringValue) for DateTimeGene") } is ArrayGene<*> -> { val template = valueGene.template val node = objectMapper.readTree(stringValue) if (node.isArray){ node.run { if (valueGene.maxSize!=null && valueGene.maxSize!! < size()){ log.warn("ArrayGene: responses have more elements than it allows, i.e., max is ${valueGene.maxSize} but the actual is ${size()}") this.filterIndexed { index, _ -> index < valueGene.maxSize!!} }else this }.forEach { p-> val copy = template.copy() // TODO need to handle cycle object gene in responses if (copy !is CycleObjectGene){ setGeneBasedOnString(copy, getTextForStringGene(copy, p)) valueGene.addElement(copy) } } }else{ throw IllegalStateException("stringValue ($stringValue) is not Array") } } is FixedMapGene<*, *> ->{ val template = valueGene.template val node = objectMapper.readTree(stringValue) if (node.isObject){ node.fields().asSequence().forEachIndexed {index, p-> if (valueGene.maxSize!=null && index >= valueGene.maxSize ){ log.warn("MapGene: responses have more elements than it allows, i.e., max is ${valueGene.maxSize} but the actual is ${node.size()}") }else{ val copy = template.copy() as PairGene<*, *> // setGeneBasedOnString(copy, p.toPrettyString()) setGeneBasedOnString(copy.first, p.key) setGeneBasedOnString(copy.second, getTextForStringGene(copy.second, p.value)) valueGene.addElement(copy) } } }else{ throw IllegalStateException("stringValue ($stringValue) is not Object or Map") } } is FlexibleMapGene<*> -> { val template = valueGene.template val node = objectMapper.readTree(stringValue) if (node.isObject){ node.fields().asSequence().forEachIndexed {index, p-> if (valueGene.maxSize!=null && index >= valueGene.maxSize ){ log.warn("MapGene: responses have more elements than it allows, i.e., max is ${valueGene.maxSize} but the actual is ${node.size()}") }else{ val copy = template.copy() as PairGene<*, FlexibleGene> setGeneBasedOnString(copy.first, p.key) val fvalueGene = parseJsonNodeAsGene("flexibleValue", p.value) copy.second.replaceGeneTo(fvalueGene) setGeneBasedOnString(fvalueGene, getTextForStringGene(fvalueGene, p.value)) valueGene.addElement(copy) } } }else{ throw IllegalStateException("stringValue ($stringValue) is not Object") } } is ObjectGene -> { val node = objectMapper.readTree(stringValue) if (node.isObject){ valueGene.fields.forEach { f-> val pdto = node.fields().asSequence().find { it.key == f.name } //?:throw IllegalStateException("could not find the field (${f.name}) in ParamDto") if (pdto == null && f is OptionalGene) f.isActive = false else if (pdto != null) setGeneBasedOnString(f, getTextForStringGene(f, pdto.value)) else throw IllegalStateException("could not set value for the field (${f.name})") } }else{ throw IllegalStateException("stringValue ($stringValue) is not Object") } } is CycleObjectGene ->{ LoggingUtil.uniqueWarn(log, "NOT support to handle cycle object with more than 2 depth") } else -> throw IllegalStateException("Not support setGeneBasedOnParamDto with gene ${gene::class.java.simpleName} and stringValue ($stringValue)") } }else{ if (gene is OptionalGene) gene.isActive = false else log.warn("could not set null for ${gene.name} with type (${gene::class.java.simpleName})") } } private fun getTextForStringGene(gene: Gene, node: JsonNode) : String{ if (ParamUtil.getValueGene(gene) is StringGene && node.isTextual) return node.asText() return node.toPrettyString() } }
lgpl-3.0
04bedffd512605ade4a52f80e328f6fb
49.12
164
0.562618
5.136787
false
false
false
false
AndroidX/constraintlayout
projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/MotionDemo.kt
2
4476
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.constraintlayout import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layoutId import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.constraintlayout.compose.MotionLayout import androidx.constraintlayout.compose.MotionLayoutDebugFlags import androidx.constraintlayout.compose.MotionScene import java.util.* @Preview(group = "motion_1") @Composable public fun MotionDemo() { var animateToEnd by remember { mutableStateOf(false) } val progress by animateFloatAsState( targetValue = if (animateToEnd) 1f else 0f, animationSpec = tween(6000) ) Column(modifier = Modifier.background(Color.White)) { val scene1 = MotionScene( """ { Header: { name: 'motion26' }, ConstraintSets: { // END STATE start: { id1: { width: 40, height: 40, start: ['parent', 'start', 16], bottom: ['parent', 'bottom', 16] }, id2: { width: 40, height: 40, start: ['parent', 'start', 16], bottom: ['parent', 'bottom', 16], alpha: 0 }, id3: { width: 40, height: 40, start: ['parent', 'start', 16], bottom: ['parent', 'bottom', 16], alpha: 1 } }, // END STATE end: { id1: { width: 40, height: 40, end: ['parent', 'end', 16], top: ['parent', 'top', 16], rotationX: 180 }, id2: { width: 40, height: 40, end: ['parent', 'end', 16], top: ['parent', 'top', 16], rotationX: 180, alpha: 1 }, id3: { width: 40, height: 40, end: ['parent', 'end', 16], top: ['parent', 'top', 16], rotationX: 180, alpha: 0 } } }, Transitions: { default: { from: 'start', to: 'end', pathMotionArc: 'startHorizontal', KeyFrames: { KeyPositions: [ { target: ['id1'], frames: [25, 50, 75], percentX: [0.2, 0.5, 0.8], percentY: [0.2, 0.2, 0.8] } ], KeyAttributes: [ { target: ['id2'], frames: [0, 50, 51, 99], alpha: [0, 0, 1, 1] }, { target: ['id3'], frames: [1, 50, 51, 99], alpha: [1, 1, 0, 0] } ] } } } } """ ) MotionLayout( modifier = Modifier.fillMaxWidth().height(400.dp), motionScene = scene1, debug = EnumSet.of(MotionLayoutDebugFlags.SHOW_ALL), progress = progress ) { Box(modifier = Modifier.layoutId("id1").background(Color.Red)) Box(modifier = Modifier.layoutId("id2").background(Color.Blue)) Box(modifier = Modifier.layoutId("id3").background(Color.Green)) } Button( onClick = { animateToEnd = !animateToEnd }, modifier = Modifier.fillMaxWidth().padding(3.dp) ) { Text(text = "Run") } } }
apache-2.0
3655782fc5ec129c2632096d1c0d1a7a
27.150943
76
0.597185
4.017953
false
false
false
false
Restioson/kettle-engine
core/src/main/kotlin/io/github/restioson/kettle/entity/ComponentMappers.kt
1
1574
package io.github.restioson.kettle.entity import com.badlogic.ashley.core.ComponentMapper import io.github.restioson.kettle.entity.component.AssetLocationComponent import io.github.restioson.kettle.entity.component.BitmapFontComponent import io.github.restioson.kettle.entity.component.BodyComponent import io.github.restioson.kettle.entity.component.GraphicsComponent import io.github.restioson.kettle.entity.component.HealthComponent import io.github.restioson.kettle.entity.component.MusicComponent import io.github.restioson.kettle.entity.component.PixmapComponent import io.github.restioson.kettle.entity.component.SoundComponent /** * Object which stores Ashley ComponentMappers */ object ComponentMappers { val ASSET_LOCATION: ComponentMapper<AssetLocationComponent> = ComponentMapper.getFor(AssetLocationComponent::class.java) val GRAPHICS: ComponentMapper<GraphicsComponent> = ComponentMapper.getFor(GraphicsComponent::class.java) val BODY: ComponentMapper<BodyComponent> = ComponentMapper.getFor(BodyComponent::class.java) val HEALTH: ComponentMapper<HealthComponent> = ComponentMapper.getFor(HealthComponent::class.java) val SOUND: ComponentMapper<SoundComponent> = ComponentMapper.getFor(SoundComponent::class.java) val MUSIC: ComponentMapper<MusicComponent> = ComponentMapper.getFor(MusicComponent::class.java) val PIXMAP: ComponentMapper<PixmapComponent> = ComponentMapper.getFor(PixmapComponent::class.java) val BITMAP_FONT: ComponentMapper<BitmapFontComponent> = ComponentMapper.getFor(BitmapFontComponent::class.java) }
apache-2.0
db40c349759b78c5b5d2ff7dc1fe8193
57.333333
124
0.837992
4.536023
false
false
false
false
commons-app/apps-android-commons
app/src/main/java/fr/free/nrw/commons/explore/media/MediaConverter.kt
5
3668
package fr.free.nrw.commons.explore.media import fr.free.nrw.commons.Media import fr.free.nrw.commons.location.LatLng import fr.free.nrw.commons.upload.structure.depictions.get import fr.free.nrw.commons.utils.CommonsDateUtil import fr.free.nrw.commons.utils.MediaDataExtractorUtil import fr.free.nrw.commons.wikidata.WikidataProperties import org.apache.commons.lang3.StringUtils import org.wikipedia.dataclient.mwapi.MwQueryPage import org.wikipedia.gallery.ExtMetadata import org.wikipedia.gallery.ImageInfo import org.wikipedia.wikidata.DataValue import org.wikipedia.wikidata.Entities import java.text.ParseException import java.util.* import javax.inject.Inject class MediaConverter @Inject constructor() { fun convert(page: MwQueryPage, entity: Entities.Entity, imageInfo: ImageInfo): Media { val metadata = imageInfo.metadata requireNotNull(metadata) { "No metadata" } // Stores mapping of title attribute to hidden attribute of each category val myMap = mutableMapOf<String, Boolean>() page.categories()?.forEach { myMap[it.title()] = (it.hidden()) } return Media( page.pageId().toString(), imageInfo.thumbUrl.takeIf { it.isNotBlank() } ?: imageInfo.originalUrl, imageInfo.originalUrl, page.title(), metadata.imageDescription(), safeParseDate(metadata.dateTime()), metadata.licenseShortName(), metadata.prefixedLicenseUrl, getAuthor(metadata), imageInfo.user, MediaDataExtractorUtil.extractCategoriesFromList(metadata.categories), metadata.latLng, entity.labels().mapValues { it.value.value() }, entity.descriptions().mapValues { it.value.value() }, entity.depictionIds(), myMap ) } /** * Creating Media object from MWQueryPage. * Earlier only basic details were set for the media object but going forward, * a full media object(with categories, descriptions, coordinates etc) can be constructed using this method * * @param page response from the API * @return Media object */ private fun safeParseDate(dateStr: String): Date? { return try { CommonsDateUtil.getMediaSimpleDateFormat().parse(dateStr) } catch (e: ParseException) { null } } /** * This method extracts the Commons Username from the artist HTML information * @param metadata * @return */ private fun getAuthor(metadata: ExtMetadata): String? { return try { val authorHtml = metadata.artist() val anchorStartTagTerminalChars = "\">" val anchorCloseTag = "</a>" return authorHtml.substring( authorHtml.indexOf(anchorStartTagTerminalChars) + anchorStartTagTerminalChars .length, authorHtml.indexOf(anchorCloseTag) ) } catch (ex: java.lang.Exception) { "" } } } private fun Entities.Entity.depictionIds() = this[WikidataProperties.DEPICTS]?.mapNotNull { (it.mainSnak.dataValue as? DataValue.EntityId)?.value?.id } ?: emptyList() private val ExtMetadata.prefixedLicenseUrl: String get() = licenseUrl().let { if (!it.startsWith("http://") && !it.startsWith("https://")) "https://$it" else it } private val ExtMetadata.latLng: LatLng? get() = if (!StringUtils.isBlank(gpsLatitude) && !StringUtils.isBlank(gpsLongitude)) LatLng(gpsLatitude.toDouble(), gpsLongitude.toDouble(), 0.0f) else null
apache-2.0
a31b7b40d344c0e4e58b86d48efea06e
34.960784
111
0.65458
4.602258
false
false
false
false
t-yoshi/peca-android
libpeercast/src/main/java/org/peercast/core/lib/rpc/ChannelStatus.kt
1
860
package org.peercast.core.lib.rpc import android.os.Parcelable import kotlinx.parcelize.Parcelize import kotlinx.serialization.Serializable import org.peercast.core.lib.rpc.io.MaybeNull /** * 特定のチャンネルの情報。 * @author (c) 2019, T Yoshizawa * @licenses Dual licensed under the MIT or GPL licenses. */ @Parcelize @Serializable data class ChannelStatus internal constructor( val status: ConnectionStatus, val source: String, val uptime: Int, @MaybeNull val localRelays: Int = 0, @MaybeNull val localDirects: Int = 0, @MaybeNull val totalRelays: Int = 0, @MaybeNull val totalDirects: Int = 0, @MaybeNull val isBroadcasting: Boolean = false, @MaybeNull val isRelayFull: Boolean = false, @MaybeNull val isDirectFull: Boolean = false, @MaybeNull val isReceiving: Boolean = false, ) : Parcelable
gpl-3.0
22c63965ee1669258dfa52bfda6354b2
28.857143
57
0.73445
3.666667
false
false
false
false
android/user-interface-samples
AppWidget/app/src/main/java/com/example/android/appwidget/glance/image/ImageGlanceWidget.kt
1
7713
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.appwidget.glance.image import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import android.net.Uri import android.util.Log import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.net.toUri import androidx.datastore.preferences.core.stringPreferencesKey import androidx.glance.GlanceId import androidx.glance.GlanceModifier import androidx.glance.Image import androidx.glance.ImageProvider import androidx.glance.LocalContext import androidx.glance.LocalGlanceId import androidx.glance.LocalSize import androidx.glance.action.ActionParameters import androidx.glance.action.clickable import androidx.glance.appwidget.CircularProgressIndicator import androidx.glance.appwidget.GlanceAppWidget import androidx.glance.appwidget.GlanceAppWidgetManager import androidx.glance.appwidget.GlanceAppWidgetReceiver import androidx.glance.appwidget.ImageProvider import androidx.glance.appwidget.SizeMode import androidx.glance.appwidget.action.ActionCallback import androidx.glance.appwidget.action.actionRunCallback import androidx.glance.appwidget.action.actionStartActivity import androidx.glance.appwidget.appWidgetBackground import androidx.glance.appwidget.state.updateAppWidgetState import androidx.glance.background import androidx.glance.currentState import androidx.glance.layout.Alignment import androidx.glance.layout.Box import androidx.glance.layout.ContentScale import androidx.glance.layout.fillMaxSize import androidx.glance.layout.fillMaxWidth import androidx.glance.layout.padding import androidx.glance.text.FontStyle import androidx.glance.text.Text import androidx.glance.text.TextAlign import androidx.glance.text.TextDecoration import androidx.glance.text.TextStyle import com.example.android.appwidget.glance.GlanceTheme import com.example.android.appwidget.glance.appWidgetBackgroundCornerRadius import com.example.android.appwidget.glance.toPx /** * Sample showcasing how to load images using WorkManager and Coil. */ class ImageGlanceWidget : GlanceAppWidget() { companion object { val sourceKey = stringPreferencesKey("image_source") val sourceUrlKey = stringPreferencesKey("image_source_url") fun getImageKey(size: DpSize) = getImageKey(size.width.value.toPx, size.height.value.toPx) fun getImageKey(width: Float, height: Float) = stringPreferencesKey( "uri-$width-$height" ) } override val sizeMode: SizeMode = SizeMode.Exact @Composable override fun Content() { val context = LocalContext.current val size = LocalSize.current val imagePath = currentState(getImageKey(size)) GlanceTheme { Box( modifier = GlanceModifier .fillMaxSize() .appWidgetBackground() .background(GlanceTheme.colors.background) .appWidgetBackgroundCornerRadius(), contentAlignment = if (imagePath == null) { Alignment.Center } else { Alignment.BottomEnd } ) { if (imagePath != null) { Image( provider = getImageProvider(imagePath), contentDescription = null, contentScale = ContentScale.FillBounds, modifier = GlanceModifier .fillMaxSize() .clickable(actionRunCallback<RefreshAction>()) ) Text( text = "Source: ${currentState(sourceKey)}", style = TextStyle( color = GlanceTheme.colors.onPrimary, fontSize = 12.sp, fontStyle = FontStyle.Italic, textAlign = TextAlign.End, textDecoration = TextDecoration.Underline ), modifier = GlanceModifier .fillMaxWidth() .padding(8.dp) .background(GlanceTheme.colors.primary) .clickable( actionStartActivity( Intent( Intent.ACTION_VIEW, Uri.parse(currentState(sourceUrlKey)) ) ) ) ) } else { CircularProgressIndicator() // Enqueue the worker after the composition is completed using the glanceId as // tag so we can cancel all jobs in case the widget instance is deleted val glanceId = LocalGlanceId.current SideEffect { ImageWorker.enqueue(context, size, glanceId) } } } } } /** * Called when the widget instance is deleted. We can then clean up any ongoing task. */ override suspend fun onDelete(context: Context, glanceId: GlanceId) { super.onDelete(context, glanceId) ImageWorker.cancel(context, glanceId) } /** * Create an ImageProvider using an URI if it's a "content://" type, otherwise load * the bitmap from the cache file * * Note: When using bitmaps directly your might reach the memory limit for RemoteViews. * If you do reach the memory limit, you'll need to generate a URI granting permissions * to the launcher. * * More info: * https://developer.android.com/training/secure-file-sharing/share-file#GrantPermissions */ private fun getImageProvider(path: String): ImageProvider { if (path.startsWith("content://")) { return ImageProvider(path.toUri()) } val bitmap = BitmapFactory.decodeFile(path) return ImageProvider(bitmap) } } class RefreshAction : ActionCallback { override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) { // Clear the state to show loading screen updateAppWidgetState(context, glanceId) { prefs -> prefs.clear() } ImageGlanceWidget().update(context, glanceId) // Enqueue a job for each size the widget can be shown in the current state // (i.e landscape/portrait) GlanceAppWidgetManager(context).getAppWidgetSizes(glanceId).forEach { size -> ImageWorker.enqueue(context, size, glanceId, force = true) } } } class ImageGlanceWidgetReceiver : GlanceAppWidgetReceiver() { override val glanceAppWidget: GlanceAppWidget = ImageGlanceWidget() }
apache-2.0
a5a3dceb56c6e6dd082327c8fbd1b132
38.558974
103
0.640347
5.290123
false
false
false
false
etesync/android
app/src/main/java/com/etesync/syncadapter/ui/DeleteCollectionFragment.kt
1
5918
/* * Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering). * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html */ package com.etesync.syncadapter.ui import android.accounts.Account import android.app.Dialog import android.app.ProgressDialog import android.content.Context import android.os.Bundle import android.text.TextUtils import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import androidx.loader.app.LoaderManager import androidx.loader.content.AsyncTaskLoader import androidx.loader.content.Loader import com.etesync.syncadapter.* import com.etesync.journalmanager.Crypto import com.etesync.journalmanager.Exceptions import com.etesync.journalmanager.JournalManager import com.etesync.syncadapter.model.CollectionInfo import com.etesync.syncadapter.model.JournalEntity import okhttp3.HttpUrl.Companion.toHttpUrlOrNull class DeleteCollectionFragment : DialogFragment(), LoaderManager.LoaderCallbacks<Exception> { protected lateinit var account: Account protected lateinit var collectionInfo: CollectionInfo override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) loaderManager.initLoader(0, arguments, this) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val progress = ProgressDialog(context) progress.setTitle(R.string.delete_collection_deleting_collection) progress.setMessage(getString(R.string.please_wait)) progress.isIndeterminate = true progress.setCanceledOnTouchOutside(false) isCancelable = false return progress } override fun onCreateLoader(id: Int, args: Bundle?): Loader<Exception> { account = args!!.getParcelable(ARG_ACCOUNT)!! collectionInfo = args.getSerializable(ARG_COLLECTION_INFO) as CollectionInfo return DeleteCollectionLoader(context!!, account, collectionInfo) } override fun onLoadFinished(loader: Loader<Exception>, exception: Exception?) { dismissAllowingStateLoss() if (exception != null) fragmentManager!!.beginTransaction() .add(ExceptionInfoFragment.newInstance(exception, account), null) .commitAllowingStateLoss() else { val activity = activity if (activity is Refreshable) (activity as Refreshable).refresh() else if (activity is EditCollectionActivity) activity.finish() } } override fun onLoaderReset(loader: Loader<Exception>) {} protected class DeleteCollectionLoader(context: Context, internal val account: Account, internal val collectionInfo: CollectionInfo) : AsyncTaskLoader<Exception>(context) { override fun onStartLoading() { forceLoad() } override fun loadInBackground(): Exception? { try { // delete collection locally val data = (context.applicationContext as App).data val settings = AccountSettings(context, account) val principal = settings.uri?.toHttpUrlOrNull() val httpClient = HttpClient.Builder(context, settings).build().okHttpClient val journalManager = JournalManager(httpClient, principal!!) val crypto = Crypto.CryptoManager(collectionInfo.version, settings.password(), collectionInfo.uid!!) journalManager.delete(JournalManager.Journal(crypto, collectionInfo.toJson(), collectionInfo.uid!!)) val journalEntity = JournalEntity.fetch(data, collectionInfo.getServiceEntity(data), collectionInfo.uid) journalEntity!!.isDeleted = true data.update(journalEntity) return null } catch (e: Exceptions.HttpException) { return e } catch (e: Exceptions.IntegrityException) { return e } catch (e: Exceptions.GenericCryptoException) { return e } catch (e: InvalidAccountException) { return e } } } class ConfirmDeleteCollectionFragment : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val collectionInfo = arguments!!.getSerializable(ARG_COLLECTION_INFO) as CollectionInfo val name = if (TextUtils.isEmpty(collectionInfo.displayName)) collectionInfo.uid else collectionInfo.displayName return AlertDialog.Builder(context!!) .setTitle(R.string.delete_collection_confirm_title) .setMessage(getString(R.string.delete_collection_confirm_warning, name)) .setPositiveButton(android.R.string.yes) { dialog, _ -> val frag = DeleteCollectionFragment() frag.arguments = arguments frag.show(fragmentManager!!, null) } .setNegativeButton(android.R.string.no) { _, _ -> dismiss() } .create() } companion object { fun newInstance(account: Account, collectionInfo: CollectionInfo): ConfirmDeleteCollectionFragment { val frag = ConfirmDeleteCollectionFragment() val args = Bundle(2) args.putParcelable(ARG_ACCOUNT, account) args.putSerializable(ARG_COLLECTION_INFO, collectionInfo) frag.arguments = args return frag } } } companion object { protected val ARG_ACCOUNT = "account" protected val ARG_COLLECTION_INFO = "collectionInfo" } }
gpl-3.0
edb5f58f304b42a795064deb7bbfa8a3
38.172185
176
0.660693
5.396898
false
false
false
false
mfklauberg/projetosacademicosfurb
compiladores/core/src/test/kotlin/ui/utils/Resources.kt
1
1224
package ui.utils import javafx.scene.image.Image import java.net.URI import java.nio.file.Paths /** * FURB - Bacharelado em Ciências da Computação * Compiladores - Interface * * Fábio Luiz Fischer & Matheus Felipe Klauberg **/ object Resources { val newFile: Image = Image(Paths.get("res/icon/gallery/new.png").toRealPath().toUri().toString()) val openFile: Image = Image(Paths.get("res/icon/gallery/open.png").toRealPath().toUri().toString()) val saveFile: Image = Image(Paths.get("res/icon/gallery/save.png").toRealPath().toUri().toString()) val copyText: Image = Image(Paths.get("res/icon/gallery/copy.png").toRealPath().toUri().toString()) val pasteText: Image = Image(Paths.get("res/icon/gallery/paste.png").toRealPath().toUri().toString()) val cutText: Image = Image(Paths.get("res/icon/gallery/cut.png").toRealPath().toUri().toString()) val buildProject: Image = Image(Paths.get("res/icon/gallery/build.png").toRealPath().toUri().toString()) val appTeam: Image = Image(Paths.get("res/icon/gallery/team.png").toRealPath().toUri().toString()) fun getStyleSheets():List<URI> { return listOf(Paths.get("res/style/text-area.css").toRealPath().toUri()) } }
mit
08b2770e738048a763851411ec1cb1d4
44.222222
108
0.69918
3.456091
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CatalogueController.kt
2
8165
package eu.kanade.tachiyomi.ui.catalogue import android.Manifest.permission.WRITE_EXTERNAL_STORAGE import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.SearchView import android.view.* import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.ControllerChangeType import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.FadeChangeHandler import com.jakewharton.rxbinding.support.v7.widget.queryTextChangeEvents import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.IFlexible import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.source.CatalogueSource import eu.kanade.tachiyomi.source.online.LoginSource import eu.kanade.tachiyomi.ui.base.controller.NucleusController import eu.kanade.tachiyomi.ui.base.controller.requestPermissionsSafe import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction import eu.kanade.tachiyomi.ui.catalogue.browse.BrowseCatalogueController import eu.kanade.tachiyomi.ui.catalogue.global_search.CatalogueSearchController import eu.kanade.tachiyomi.ui.catalogue.latest.LatestUpdatesController import eu.kanade.tachiyomi.ui.setting.SettingsSourcesController import eu.kanade.tachiyomi.widget.preference.SourceLoginDialog import kotlinx.android.synthetic.main.catalogue_main_controller.* import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * This controller shows and manages the different catalogues enabled by the user. * This controller should only handle UI actions, IO actions should be done by [CataloguePresenter] * [SourceLoginDialog.Listener] refreshes the adapter on successful login of catalogues. * [CatalogueAdapter.OnBrowseClickListener] call function data on browse item click. * [CatalogueAdapter.OnLatestClickListener] call function data on latest item click */ class CatalogueController : NucleusController<CataloguePresenter>(), SourceLoginDialog.Listener, FlexibleAdapter.OnItemClickListener, CatalogueAdapter.OnBrowseClickListener, CatalogueAdapter.OnLatestClickListener { /** * Application preferences. */ private val preferences: PreferencesHelper = Injekt.get() /** * Adapter containing sources. */ private var adapter: CatalogueAdapter? = null /** * Called when controller is initialized. */ init { // Enable the option menu setHasOptionsMenu(true) } /** * Set the title of controller. * * @return title. */ override fun getTitle(): String? { return applicationContext?.getString(R.string.label_catalogues) } /** * Create the [CataloguePresenter] used in controller. * * @return instance of [CataloguePresenter] */ override fun createPresenter(): CataloguePresenter { return CataloguePresenter() } /** * Initiate the view with [R.layout.catalogue_main_controller]. * * @param inflater used to load the layout xml. * @param container containing parent views. * @return inflated view. */ override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View { return inflater.inflate(R.layout.catalogue_main_controller, container, false) } /** * Called when the view is created * * @param view view of controller */ override fun onViewCreated(view: View) { super.onViewCreated(view) adapter = CatalogueAdapter(this) // Create recycler and set adapter. recycler.layoutManager = LinearLayoutManager(view.context) recycler.adapter = adapter recycler.addItemDecoration(SourceDividerItemDecoration(view.context)) requestPermissionsSafe(arrayOf(WRITE_EXTERNAL_STORAGE), 301) } override fun onDestroyView(view: View) { adapter = null super.onDestroyView(view) } override fun onChangeStarted(handler: ControllerChangeHandler, type: ControllerChangeType) { super.onChangeStarted(handler, type) if (!type.isPush && handler is SettingsSourcesFadeChangeHandler) { presenter.updateSources() } } /** * Called when login dialog is closed, refreshes the adapter. * * @param source clicked item containing source information. */ override fun loginDialogClosed(source: LoginSource) { if (source.isLogged()) { adapter?.clear() presenter.loadSources() } } /** * Called when item is clicked */ override fun onItemClick(position: Int): Boolean { val item = adapter?.getItem(position) as? SourceItem ?: return false val source = item.source if (source is LoginSource && !source.isLogged()) { val dialog = SourceLoginDialog(source) dialog.targetController = this dialog.showDialog(router) } else { // Open the catalogue view. openCatalogue(source, BrowseCatalogueController(source)) } return false } /** * Called when browse is clicked in [CatalogueAdapter] */ override fun onBrowseClick(position: Int) { onItemClick(position) } /** * Called when latest is clicked in [CatalogueAdapter] */ override fun onLatestClick(position: Int) { val item = adapter?.getItem(position) as? SourceItem ?: return openCatalogue(item.source, LatestUpdatesController(item.source)) } /** * Opens a catalogue with the given controller. */ private fun openCatalogue(source: CatalogueSource, controller: BrowseCatalogueController) { preferences.lastUsedCatalogueSource().set(source.id) router.pushController(controller.withFadeTransaction()) } /** * Adds items to the options menu. * * @param menu menu containing options. * @param inflater used to load the menu xml. */ override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { // Inflate menu inflater.inflate(R.menu.catalogue_main, menu) // Initialize search option. val searchItem = menu.findItem(R.id.action_search) val searchView = searchItem.actionView as SearchView // Change hint to show global search. searchView.queryHint = applicationContext?.getString(R.string.action_global_search_hint) // Create query listener which opens the global search view. searchView.queryTextChangeEvents() .filter { it.isSubmitted } .subscribeUntilDestroy { performGlobalSearch(it.queryText().toString()) } } fun performGlobalSearch(query: String){ router.pushController(CatalogueSearchController(query).withFadeTransaction()) } /** * Called when an option menu item has been selected by the user. * * @param item The selected item. * @return True if this event has been consumed, false if it has not. */ override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { // Initialize option to open catalogue settings. R.id.action_settings -> { router.pushController((RouterTransaction.with(SettingsSourcesController())) .popChangeHandler(SettingsSourcesFadeChangeHandler()) .pushChangeHandler(FadeChangeHandler())) } else -> return super.onOptionsItemSelected(item) } return true } /** * Called to update adapter containing sources. */ fun setSources(sources: List<IFlexible<*>>) { adapter?.updateDataSet(sources) } /** * Called to set the last used catalogue at the top of the view. */ fun setLastUsedSource(item: SourceItem?) { adapter?.removeAllScrollableHeaders() if (item != null) { adapter?.addScrollableHeader(item) } } class SettingsSourcesFadeChangeHandler : FadeChangeHandler() }
apache-2.0
65b40f62e872cd6cbc5d9f69d0acf863
33.601695
99
0.689406
4.930556
false
false
false
false
peterholak/mogul
native/src/mogul/microdom/Node.kt
2
5758
package mogul.microdom import mogul.microdom.ObservableList.Change.* import mogul.platform.* sealed class Node { var parent: Container? = null; internal set abstract var style: Style open var hoverStyle: Style? = null open var mouseDownStyle: Style? = null abstract var events: Events abstract fun draw(cairo: Cairo) var topLeft: Position? = null var cachedLayoutSize: Size? = null var state = NodeState() /** Returns what the size of the content would be, if not affected by width/height style attributes. */ abstract fun defaultInnerSize(cairo: Cairo): Size fun effectiveStyle(): Style { var result = style if (state.hover && hoverStyle != null) result += hoverStyle!! if (state.mouseDown && mouseDownStyle != null) result += mouseDownStyle!! return result } fun fireEvent(event: Event) { events.map[event.type]?.forEach { it.invoke(event) } } /** Returns the actual size of content, after width/height style attributes, padding, and borders are taken into account. */ fun innerSize(cairo: Cairo): Size { val default by lazy { defaultInnerSize(cairo) } val shrunk by lazy { layoutSize(cairo) - style.padding - style.margin - style.border?.width } return Size( if (style.width == null) default.width else shrunk.width, if (style.height == null) default.height else shrunk.height ) } /** Returns the full size of the element, including the padding, border and margins. */ fun layoutSize(cairo: Cairo): Size { val defaultSize by lazy { defaultInnerSize(cairo) + style.padding + style.border?.width } return Size( style.width ?: defaultSize.width, style.height ?: defaultSize.height ) + style.margin } open fun populateLayoutSize(cairo: Cairo) { // could be optimized, same things are calculated twice cachedLayoutSize = layoutSize(cairo) } fun boundingRectangle(): Rectangle? = topLeft?.let { // TODO: fix this layout nonsense Rectangle(it - style.padding?.topLeft, cachedLayoutSize!! - Size(style.margin?.left ?: 0, 0)) } fun replaceWith(newChild: Node) { if (parent !is Container) { throw UnsupportedOperationException("replaceWith cannot be called on root node! (parent of node must be a Container).") }else{ (parent as Container).replaceChild(this, newChild) } } } // TODO: this doesn't really notify on all operations yet, so that needs to be fixed class ObservableList<T>(private val list: MutableList<T> = mutableListOf()): MutableList<T> by list { val listeners = mutableListOf<(change: Change<T>) -> Unit>() private fun notifyListeners(change: Change<T>) { listeners.forEach { it.invoke(change) }} @Suppress("unused") sealed class Change<T> { class Added<T>(val elements: Collection<T>) : Change<T>() class Removed<T>(val elements: Collection<T>) : Change<T>() } override fun add(element: T) = list.add(element).also { notifyListeners(Added(listOf(element))) } override fun add(index: Int, element: T) = list.add(index, element).also { notifyListeners(Added(listOf(element))) } override fun addAll(elements: Collection<T>) = list.addAll(elements).also { notifyListeners(Added(elements)) } override fun addAll(index: Int, elements: Collection<T>) = list.addAll(index, elements).also { notifyListeners(Added(elements)) } override fun remove(element: T) = list.remove(element).also { notifyListeners(Removed(listOf(element))) } override fun removeAt(index: Int) = list.removeAt(index).also { notifyListeners(Removed(listOf(it))) } override fun removeAll(elements: Collection<T>) = list.removeAll(elements).also { notifyListeners(Removed(elements)) } // This could be pretty inefficient and maybe pointless (right now its only used for setting parent to null) override fun clear() = list.also { notifyListeners(Removed(it)) }.clear() // Maybe the Removed should be called as well, or it should be a different Change type, but for now I don't need it override fun set(index: Int, element: T) = list.set(index, element).also { notifyListeners(Removed(listOf(it))) }.also{ notifyListeners(Added(listOf(element))) } } class NodeNotFoundException : Exception() abstract class Container(initialChildren: List<Node>) : Node() { val children: ObservableList<Node> = ObservableList() init { children.listeners.add { change -> when (change) { is Added -> change.elements.forEach { if (it.parent != null) { // TODO Not thread safe it.parent!!.children.remove(it) } it.parent = this } // Is there any point to this? is Removed -> change.elements.forEach { it.parent = null } } } children.addAll(initialChildren) } override fun populateLayoutSize(cairo: Cairo) { super.populateLayoutSize(cairo) children.forEach { it.populateLayoutSize(cairo) } } internal fun replaceChild(old: Node, new: Node) { val position = children.indexOf(old) if (position == -1) throw NodeNotFoundException() children[position] = new } } abstract class Leaf : Node() /** This could be optimized by having the state represented with bitfields */ data class NodeState( val hover: Boolean = false, val mouseDown: Boolean = false ) val initialNodeState = NodeState(false, false)
mit
27f60a2248875ec542641522c572e1d9
36.888158
131
0.643105
4.405509
false
false
false
false
cliffano/swaggy-jenkins
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/FavoriteImpllinks.kt
1
908
package org.openapitools.model import java.util.Objects import com.fasterxml.jackson.annotation.JsonProperty import org.openapitools.model.Link import javax.validation.constraints.DecimalMax import javax.validation.constraints.DecimalMin import javax.validation.constraints.Email import javax.validation.constraints.Max import javax.validation.constraints.Min import javax.validation.constraints.NotNull import javax.validation.constraints.Pattern import javax.validation.constraints.Size import javax.validation.Valid import io.swagger.v3.oas.annotations.media.Schema /** * * @param self * @param propertyClass */ data class FavoriteImpllinks( @field:Valid @Schema(example = "null", description = "") @field:JsonProperty("self") val self: Link? = null, @Schema(example = "null", description = "") @field:JsonProperty("_class") val propertyClass: kotlin.String? = null ) { }
mit
f7a3dcbc010a9bd004b1ed3019827608
26.515152
74
0.778634
4.108597
false
false
false
false
mikegehard/kotlinArchiveChannel
src/main/kotlin/io/github/mikegehard/slack/SlackMessage.kt
1
1141
package io.github.mikegehard.slack import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.fasterxml.jackson.databind.deser.std.StdDeserializer import java.time.Instant // You need the custom deserializer because the Slack API returns // this timestamp as a string value that contains a float. // Example "ts": "123.12345" @JsonDeserialize(using = SlackMessageDeserializer::class) data class SlackMessage( val timestamp: Instant ) class SlackMessageDeserializer : StdDeserializer<SlackMessage>(SlackMessage::class.java) { override fun deserialize(jp: JsonParser, ctxt: DeserializationContext?): SlackMessage { val node: JsonNode = jp.codec.readTree(jp) val parts = node.get("ts").textValue().split(".") return if (parts.size == 2) { SlackMessage(Instant.ofEpochSecond(parts[0].toLong(), parts[1].toLong() * 10000)) } else { SlackMessage(Instant.ofEpochSecond(parts[0].toLong())) } } }
mit
77cb21c4e83b094b31a64faf2299784a
39.75
93
0.738826
4.289474
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/cargo/runconfig/filters/RsBacktraceFilter.kt
3
5468
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.runconfig.filters import com.intellij.execution.filters.Filter import com.intellij.execution.filters.OpenFileHyperlinkInfo import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import org.rust.cargo.project.workspace.CargoWorkspace import org.rust.cargo.project.workspace.PackageOrigin import org.rust.cargo.runconfig.filters.RegexpFileLinkFilter.Companion.FILE_POSITION_RE import org.rust.lang.core.resolve.resolveStringPath import java.util.* import java.util.regex.Pattern /** * Adds features to stack backtraces: * - Wrap function calls into hyperlinks to source code. * - Turn source code links into hyperlinks. * - Dims function hash codes to reduce noise. */ class RsBacktraceFilter( project: Project, cargoProjectDir: VirtualFile, workspace: CargoWorkspace? ) : Filter { private val sourceLinkFilter = RegexpFileLinkFilter(project, cargoProjectDir, "\\s+at $FILE_POSITION_RE") private val backtraceItemFilter = RsBacktraceItemFilter(project, workspace) override fun applyFilter(line: String, entireLength: Int): Filter.Result? { return backtraceItemFilter.applyFilter(line, entireLength) ?: sourceLinkFilter.applyFilter(line, entireLength) } } /** * Adds hyperlinks to function names in backtraces */ private class RsBacktraceItemFilter( val project: Project, val workspace: CargoWorkspace? ) : Filter { private val pattern = Pattern.compile("^(\\s*\\d+:\\s+(?:0x[a-f0-9]+ - )?)(.+?)(::h[0-9a-f]+)?$")!! private val docManager = PsiDocumentManager.getInstance(project) override fun applyFilter(line: String, entireLength: Int): Filter.Result? { val matcher = pattern.matcher(line) if (!matcher.find()) return null val header = matcher.group(1) val funcName = matcher.group(2) val funcHash = matcher.group(3) val normFuncName = funcName.normalize() val resultItems = ArrayList<Filter.ResultItem>(2) // Add hyperlink to the function name val funcStart = entireLength - line.length + header.length val funcEnd = funcStart + funcName.length if (SKIP_PREFIXES.none { normFuncName.startsWith(it) }) { extractFnHyperlink(normFuncName, funcStart, funcEnd)?.let { resultItems.add(it) } } // Dim the hashcode if (funcHash != null) { resultItems.add(Filter.ResultItem(funcEnd, funcEnd + funcHash.length, null, DIMMED_TEXT)) } return Filter.Result(resultItems) } private fun extractFnHyperlink(funcName: String, start: Int, end: Int): Filter.ResultItem? { val workspace = workspace ?: return null val (element, pkg) = resolveStringPath(funcName, workspace, project) ?: return null val funcFile = element.containingFile val doc = docManager.getDocument(funcFile) ?: return null val link = OpenFileHyperlinkInfo(project, funcFile.virtualFile, doc.getLineNumber(element.textOffset)) return Filter.ResultItem(start, end, link, pkg.origin != PackageOrigin.WORKSPACE) } /** * Normalizes function path: * - Removes angle brackets from the element path, including enclosed contents when necessary. * - Removes closure markers. * Examples: * - <core::option::Option<T>>::unwrap -> core::option::Option::unwrap * - std::panicking::default_hook::{{closure}} -> std::panicking::default_hook */ private fun String.normalize(): String { var str = this while (str.endsWith("::{{closure}}")) { str = str.substringBeforeLast("::") } while (true) { val range = str.findAngleBrackets() ?: break val idx = str.indexOf("::", range.start + 1) str = if (idx < 0 || idx > range.endInclusive) { str.removeRange(range) } else { str.removeRange(IntRange(range.endInclusive, range.endInclusive)) .removeRange(IntRange(range.start, range.start)) } } return str } /** * Finds the range of the first matching angle brackets within the string. */ private fun String.findAngleBrackets(): IntRange? { var start = -1 var counter = 0 loop@ for ((index, char) in this.withIndex()) { when (char) { '<' -> { if (start < 0) { start = index } counter += 1 } '>' -> counter -= 1 else -> continue@loop } if (counter == 0) { return IntRange(start, index) } } return null } private companion object { val DIMMED_TEXT = EditorColorsManager.getInstance().globalScheme .getAttributes(TextAttributesKey.createTextAttributesKey("org.rust.DIMMED_TEXT"))!! val SKIP_PREFIXES = arrayOf( "std::rt::lang_start", "std::panicking", "std::sys::backtrace", "std::sys::imp::backtrace", "core::panicking") } }
mit
c7afb8fed32f3111b4bde0cb9598f236
36.452055
110
0.633687
4.367412
false
false
false
false
google/horologist
auth-composables/src/main/java/com/google/android/horologist/auth/composables/screens/CheckYourPhoneScreen.kt
1
4739
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.auth.composables.screens import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.SecurityUpdateGood import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.wear.compose.material.CircularProgressIndicator import androidx.wear.compose.material.Icon import androidx.wear.compose.material.Text import com.google.android.horologist.auth.composables.ExperimentalHorologistAuthComposablesApi import com.google.android.horologist.auth.composables.R import com.google.android.horologist.base.ui.util.DECORATIVE_ELEMENT_CONTENT_DESCRIPTION private val indicatorPadding = 8.dp private val iconSize = 48.dp private val progressBarStrokeWidth = 4.dp @ExperimentalHorologistAuthComposablesApi @Composable public fun CheckYourPhoneScreen( modifier: Modifier = Modifier ) { Box( modifier = modifier.fillMaxSize() ) { Text( text = stringResource(id = R.string.horologist_check_your_phone_title), modifier = Modifier .fillMaxWidth() .align(Alignment.Center), textAlign = TextAlign.Center ) Box( modifier = modifier .padding(bottom = 20.dp) .align(Alignment.BottomCenter) .size(iconSize) .clip(CircleShape) ) { CircularProgressIndicator( modifier = modifier .size(iconSize - progressBarStrokeWidth + indicatorPadding), strokeWidth = progressBarStrokeWidth ) Icon( imageVector = Icons.Default.SecurityUpdateGood, contentDescription = DECORATIVE_ELEMENT_CONTENT_DESCRIPTION, modifier = Modifier .align(Alignment.Center) .size(iconSize - indicatorPadding - 8.dp) .clip(CircleShape) ) } } } @ExperimentalHorologistAuthComposablesApi @Composable public fun CheckYourPhoneScreen( modifier: Modifier = Modifier, message: String ) { Column( modifier = modifier.fillMaxSize() ) { Text( text = stringResource(id = R.string.horologist_check_your_phone_title), modifier = Modifier .padding(top = 60.dp) .fillMaxWidth() .align(Alignment.CenterHorizontally), textAlign = TextAlign.Center ) Text( text = message, modifier = Modifier .padding(top = 20.dp) .fillMaxWidth() .align(Alignment.CenterHorizontally), textAlign = TextAlign.Center ) Box( modifier = modifier .padding(vertical = 20.dp) .fillMaxWidth() .size(iconSize) .clip(CircleShape), contentAlignment = Alignment.Center ) { CircularProgressIndicator( modifier = modifier .size(iconSize - progressBarStrokeWidth + indicatorPadding), strokeWidth = progressBarStrokeWidth ) Icon( imageVector = Icons.Default.SecurityUpdateGood, contentDescription = DECORATIVE_ELEMENT_CONTENT_DESCRIPTION, modifier = Modifier .size(iconSize - indicatorPadding - 8.dp) .clip(CircleShape) ) } } }
apache-2.0
580f687dca7870e5d2e7247c886d3b52
34.103704
94
0.646339
5.014815
false
false
false
false
egenvall/TravelPlanner
app/src/main/java/com/egenvall/travelplanner/model/VtModels.kt
1
1541
package com.egenvall.travelplanner.model data class AccessToken(val scope : String ="", val expires_in : Int = -1, val token_type : String = "", val access_token : String = "") data class VtResponseModel( val LocationList : LocationList) data class LocationList( val errorText : String?, val error : String?, val StopLocation: List<StopLocation>? = listOf<StopLocation>(), val CoordLocation: List<CoordLocation>? = listOf<CoordLocation>() ) data class StopLocation( val id : String = "id", val type : String = "STOP", val lat : Double = 0.0, val lon : Double = 0.0, val idx : String = "idx", val name : String = "Stopname") data class CoordLocation( val type : String = "ADR", val lon : Double = 0.0, val lat : Double = 0.0, val idx : String ="idx", val name : String ="Coordname") data class TripResponseModel(val TripList : TripList) data class TripList(val error : String?, val errorText: String?, val Trip : List<Trip>) data class Trip(val Leg : List<Leg>, val type : String) data class Leg (val Origin : TripEndpoint, val Destination : TripEndpoint, val fgColor : String, val direction : String, val name : String, val sname : String, val type : String) data class TripEndpoint(val id : String?, val routeIdx : String?, val track : String?, val name : String, val time : String, val type : String, val directtime : String?, val rtTime : String?)
apache-2.0
98f11adaa134afa2c6e8625d0df0569e
58.269231
178
0.625568
4.044619
false
false
false
false
icarumbas/bagel
core/src/ru/icarumbas/bagel/engine/systems/physics/AwakeSystem.kt
1
1304
package ru.icarumbas.bagel.engine.systems.physics import com.badlogic.ashley.core.Entity import com.badlogic.ashley.core.Family import com.badlogic.ashley.systems.IteratingSystem import ru.icarumbas.bagel.engine.components.other.RoomIdComponent import ru.icarumbas.bagel.engine.components.physics.BodyComponent import ru.icarumbas.bagel.engine.components.physics.StaticComponent import ru.icarumbas.bagel.engine.world.RoomWorld import ru.icarumbas.bagel.utils.body import ru.icarumbas.bagel.utils.inActive import ru.icarumbas.bagel.utils.roomId import ru.icarumbas.bagel.utils.statik class AwakeSystem( private val rm: RoomWorld ) : IteratingSystem(Family.all(BodyComponent::class.java).one(RoomIdComponent::class.java, StaticComponent::class.java).get()) { private var lastMapId = -1 override fun update(deltaTime: Float) { if (lastMapId != rm.currentMapId) { super.update(deltaTime) lastMapId = rm.currentMapId } } override fun processEntity(entity: Entity, deltaTime: Float) { if (statik.has(entity)) body[entity].body.isActive = statik[entity].mapPath == rm.getMapPath() if (roomId.has(entity) && !inActive.has(entity)) body[entity].body.isActive = roomId[entity].id == rm.currentMapId } }
apache-2.0
55eb6418cf4e48ac4e29448cf3d14c98
32.435897
128
0.739264
3.824047
false
false
false
false
Kotlin/dokka
kotlin-analysis/src/main/kotlin/org/jetbrains/dokka/analysis/DRIFactory.kt
1
2933
package org.jetbrains.dokka.analysis import com.intellij.psi.* import org.jetbrains.dokka.links.* import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.EnumEntrySyntheticClassDescriptor import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.resolve.descriptorUtil.parentsWithSelf import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.safeAs fun DRI.Companion.from(descriptor: DeclarationDescriptor) = descriptor.parentsWithSelf.run { val parameter = firstIsInstanceOrNull<ValueParameterDescriptor>() val callable = parameter?.containingDeclaration ?: firstIsInstanceOrNull() DRI( packageName = firstIsInstanceOrNull<PackageFragmentDescriptor>()?.fqName?.asString() ?: "", classNames = (filterIsInstance<ClassDescriptor>() + filterIsInstance<TypeAliasDescriptor>()).toList() .takeIf { it.isNotEmpty() } ?.asReversed() ?.joinToString(separator = ".") { it.name.asString() }, callable = callable?.let { Callable.from(it) }, target = DriTarget.from(parameter ?: descriptor), extra = if (descriptor is EnumEntrySyntheticClassDescriptor || descriptor.safeAs<ClassDescriptor>()?.kind == ClassKind.ENUM_ENTRY) DRIExtraContainer().also { it[EnumEntryDRIExtra] = EnumEntryDRIExtra }.encode() else null ) } fun DRI.Companion.from(psi: PsiElement) = psi.parentsWithSelf.run { val psiMethod = firstIsInstanceOrNull<PsiMethod>() val psiField = firstIsInstanceOrNull<PsiField>() val classes = filterIsInstance<PsiClass>().filterNot { it is PsiTypeParameter } .toList() // We only want exact PsiClass types, not PsiTypeParameter subtype val additionalClasses = if (psi is PsiEnumConstant) listOfNotNull(psiField?.name) else emptyList() DRI( packageName = classes.lastOrNull()?.qualifiedName?.substringBeforeLast('.', "") ?: "", classNames = (additionalClasses + classes.mapNotNull { it.name }).takeIf { it.isNotEmpty() } ?.asReversed()?.joinToString("."), // The fallback strategy test whether psi is not `PsiEnumConstant`. The reason behind this is that // we need unified DRI for both Java and Kotlin enums, so we can link them properly and treat them alike. // To achieve that, we append enum name to classNames list and leave the callable part set to null. For Kotlin enums // it is by default, while for Java enums we have to explicitly test for that in this `takeUnless` condition. callable = psiMethod?.let { Callable.from(it) } ?: psiField?.takeUnless { psi is PsiEnumConstant }?.let { Callable.from(it) }, target = DriTarget.from(psi), extra = if (psi is PsiEnumConstant) DRIExtraContainer().also { it[EnumEntryDRIExtra] = EnumEntryDRIExtra }.encode() else null ) }
apache-2.0
f1d6e1ba8d79b60867301c4a0a9af36f
57.66
138
0.71599
4.93771
false
false
false
false
googlecodelabs/android-testing
app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source/remote/TasksRemoteDataSource.kt
1
4409
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.data.source.remote import android.annotation.SuppressLint import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.map import com.example.android.architecture.blueprints.todoapp.data.Result import com.example.android.architecture.blueprints.todoapp.data.Result.Error import com.example.android.architecture.blueprints.todoapp.data.Result.Success import com.example.android.architecture.blueprints.todoapp.data.Task import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource import kotlinx.coroutines.delay /** * Implementation of the data source that adds a latency simulating network. */ object TasksRemoteDataSource : TasksDataSource { private const val SERVICE_LATENCY_IN_MILLIS = 2000L private var TASKS_SERVICE_DATA = LinkedHashMap<String, Task>(2) init { addTask("Build tower in Pisa", "Ground looks good, no foundation work required.") addTask("Finish bridge in Tacoma", "Found awesome girders at half the cost!") } private val observableTasks = MutableLiveData<Result<List<Task>>>() @SuppressLint("NullSafeMutableLiveData") override suspend fun refreshTasks() { observableTasks.value = getTasks() } override suspend fun refreshTask(taskId: String) { refreshTasks() } override fun observeTasks(): LiveData<Result<List<Task>>> { return observableTasks } override fun observeTask(taskId: String): LiveData<Result<Task>> { return observableTasks.map { tasks -> when (tasks) { is Result.Loading -> Result.Loading is Error -> Error(tasks.exception) is Success -> { val task = tasks.data.firstOrNull() { it.id == taskId } ?: return@map Error(Exception("Not found")) Success(task) } } } } override suspend fun getTasks(): Result<List<Task>> { // Simulate network by delaying the execution. val tasks = TASKS_SERVICE_DATA.values.toList() delay(SERVICE_LATENCY_IN_MILLIS) return Success(tasks) } override suspend fun getTask(taskId: String): Result<Task> { // Simulate network by delaying the execution. delay(SERVICE_LATENCY_IN_MILLIS) TASKS_SERVICE_DATA[taskId]?.let { return Success(it) } return Error(Exception("Task not found")) } private fun addTask(title: String, description: String) { val newTask = Task(title, description) TASKS_SERVICE_DATA[newTask.id] = newTask } override suspend fun saveTask(task: Task) { TASKS_SERVICE_DATA[task.id] = task } override suspend fun completeTask(task: Task) { val completedTask = Task(task.title, task.description, true, task.id) TASKS_SERVICE_DATA[task.id] = completedTask } override suspend fun completeTask(taskId: String) { // Not required for the remote data source } override suspend fun activateTask(task: Task) { val activeTask = Task(task.title, task.description, false, task.id) TASKS_SERVICE_DATA[task.id] = activeTask } override suspend fun activateTask(taskId: String) { // Not required for the remote data source } override suspend fun clearCompletedTasks() { TASKS_SERVICE_DATA = TASKS_SERVICE_DATA.filterValues { !it.isCompleted } as LinkedHashMap<String, Task> } override suspend fun deleteAllTasks() { TASKS_SERVICE_DATA.clear() } override suspend fun deleteTask(taskId: String) { TASKS_SERVICE_DATA.remove(taskId) } }
apache-2.0
3c0c7b88f6d41c61ae096e3e5bb95f56
33.445313
89
0.677024
4.404595
false
false
false
false
Commit451/LabCoat
app/src/main/java/com/commit451/gitlab/model/api/Issue.kt
2
1550
package com.commit451.gitlab.model.api import android.os.Parcelable import androidx.annotation.StringDef import com.squareup.moshi.Json import kotlinx.android.parcel.Parcelize import java.util.Date @Parcelize data class Issue( @Json(name = "id") var id: Long = 0, @Json(name = "iid") var iid: Long = 0, @Json(name = "project_id") var projectId: Long = 0, @Json(name = "title") var title: String? = null, @Json(name = "description") var description: String? = null, @Json(name = "state") @State @get:State var state: String? = null, @Json(name = "created_at") var createdAt: Date? = null, @Json(name = "updated_at") var updatedAt: Date? = null, @Json(name = "labels") var labels: List<String>? = null, @Json(name = "milestone") var milestone: Milestone? = null, @Json(name = "assignee") var assignee: User? = null, @Json(name = "author") var author: User? = null, @Json(name = "confidential") var isConfidential: Boolean = false ) : Parcelable { companion object { const val STATE_REOPEN = "reopen" const val STATE_CLOSE = "close" const val STATE_OPENED = "opened" const val STATE_REOPENED = "reopened" const val STATE_CLOSED = "closed" } @StringDef(STATE_REOPEN, STATE_CLOSE) @Retention(AnnotationRetention.SOURCE) annotation class EditState @StringDef(STATE_OPENED, STATE_REOPENED, STATE_CLOSED) @Retention(AnnotationRetention.SOURCE) annotation class State }
apache-2.0
e479b669534063718db3095e9eee471a
26.678571
58
0.640645
3.613054
false
false
false
false
Jire/Strukt
src/jmh/kotlin/org/jire/strukt/benchmarks/Free.kt
1
1442
/* * Copyright 2020 Thomas Nappo (Jire) * * 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.jire.strukt.benchmarks import it.unimi.dsi.fastutil.longs.LongArrayList import it.unimi.dsi.fastutil.longs.LongList import org.jire.strukt.Strukts import org.openjdk.jmh.annotations.* import java.util.concurrent.TimeUnit @BenchmarkMode(Mode.SingleShotTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @State(Scope.Benchmark) @Fork(value = 1, jvmArgsAppend = ["-Xmx16g", "-Xms16g"]) @Warmup(iterations = 0) @Measurement(iterations = 1) abstract class Free(val strukts: Strukts) { private val addresses: LongList = LongArrayList(CAPACITY.toInt()) @Setup fun setup() { for (i in 1..CAPACITY) { addresses.add(strukts.allocate()) } } @Benchmark fun free() { val it = addresses.listIterator() while (it.hasNext()) { val address = it.nextLong() strukts.free(address) } } }
apache-2.0
b7312598e8709971f8cdfa3dad8e81e0
27.294118
78
0.717753
3.542998
false
false
false
false
ntemplon/legends-of-omterra
core/src/com/jupiter/europa/scene2d/ui/AttributeSelector.kt
1
2171
/* * The MIT License * * Copyright 2015 Nathan Templon. * * 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.jupiter.europa.scene2d.ui import com.jupiter.europa.entity.stats.AttributeSet import com.jupiter.europa.entity.stats.AttributeSet.Attributes /** * @author Nathan Templon */ public class AttributeSelector @jvmOverloads constructor(maxSelection: Int, style: MultipleNumberSelector.MultipleNumberSelectorStyle, columns: Int = 1) : MultipleNumberSelector(maxSelection, style, AttributeSelector.ATTRIBUTE_NAMES, columns) { // Properties public fun getAttributes(): AttributeSet { val set = AttributeSet() val values: Map<String, Int> = this.getValues() for ((name, value) in values) { val attribute = Attributes.getByDisplayName(name) if (attribute != null) { set.setAttribute(attribute, value) } } return set } companion object { // Constants public val ATTRIBUTE_NAMES: List<String> = AttributeSet.PRIMARY_ATTRIBUTES.map { attr -> attr.displayName }.toList() } }
mit
a72cb07afbbce11116244b0d3a49db5d
34.016129
121
0.713496
4.599576
false
false
false
false
jpmoreto/play-with-robots
android/app/src/main/java/jpm/android/robot/Robot.kt
1
3168
package jpm.android.robot import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import kotlin.reflect.KClass object Robot { data class SensorInfo<T: Number>(val name: String, val unit: String, val unitShortName: String, val toUnits: Double, val dataCls: KClass<T>) { fun convert(from: T) = from.toDouble() * toUnits } val ACC_SENSOR = 0 val GYRO_SENSOR = 1 val CMP_SENSOR = 2 val US_SENSOR = 3 val TEMP_SENSOR = 4 val ROT_SENSOR = 5 val sensorsInfo = arrayOf( SensorInfo("Acc", "g","g", 1.0/200.0, Int::class), SensorInfo("Gyro", "radian/second", "r/s", 1.0/200.0, Int::class), SensorInfo("Cmp", "degree", "º", 1.0/200.0, Int::class), SensorInfo("US", "meter", "m", 1.0, Int::class), SensorInfo("Temp", "degree", "º", 1.0, Int::class), SensorInfo("Rot", "meter", "m", 2 * Math.PI * RobotDimensions.wheelRadius / 100.0, Int::class) ) private val robot = Path() fun getRobot(deltaX: Float, deltaY: Float, scale: Float): Path { fun toScale(value: Float) = scale * value val halfRobotWith = toScale(RobotDimensions.bodyWidth.toFloat()) / 2.0f val halfRobotLength = toScale(RobotDimensions.robotRectLength.toFloat()) / 2.0f val deltaXMinusHalfRobotWith = deltaX - halfRobotWith val deltaXPlusHalfRobotWith = deltaX + halfRobotWith val deltaYMinusHalfRobotLength = deltaY - halfRobotLength val deltaYPlusHalfRobotLength = deltaY + halfRobotLength robot.rewind() robot.moveTo(deltaXMinusHalfRobotWith, deltaYMinusHalfRobotLength) robot.lineTo(deltaXMinusHalfRobotWith, deltaYPlusHalfRobotLength) robot.arcTo( deltaXMinusHalfRobotWith, deltaYPlusHalfRobotLength - halfRobotWith, deltaXPlusHalfRobotWith, deltaYPlusHalfRobotLength + halfRobotWith, -180f,-180f,true) robot.lineTo(deltaXPlusHalfRobotWith, deltaYMinusHalfRobotLength) robot.arcTo( deltaXMinusHalfRobotWith, deltaYMinusHalfRobotLength - halfRobotWith, deltaXPlusHalfRobotWith, deltaYMinusHalfRobotLength + halfRobotWith, 0f,-180f,true) return robot } /* angles in android: http://www.cumulations.com/blogs/5/Understanding-Sweep-angle-in-drawArc-method-of-android rotate positive clockwise and 0 degrees is 3 hours (like trigonometric circle) */ fun drawUsRead(deltaX: Float, deltaY: Float, scale: Float, sensorNum: Int, distance: Int, paint: Paint, canvas: Canvas) { fun toScale(value: Double) = scale * value.toFloat() val s = RobotDimensions.sonarSensors[sensorNum] canvas.drawArc( deltaX + toScale(s.x) - distance, deltaY - toScale(s.y) - distance, deltaX + toScale(s.x) + distance, deltaY - toScale(s.y) + distance, RobotDimensions.sonarSensors[sensorNum].angleDeg + 270f - RobotDimensions.sonarAngle / 2f, RobotDimensions.sonarAngle.toFloat(), true,paint) } }
mit
c099c61f2050edd94b2419811f86aceb
39.589744
146
0.647189
3.80072
false
false
false
false
http4k/http4k
http4k-format/core/src/main/kotlin/org/http4k/format/AutoMarshalling.kt
1
1591
package org.http4k.format import org.http4k.core.HttpMessage import org.http4k.core.Request import org.http4k.lens.BiDiLensSpec import org.http4k.lens.ParamMeta.ObjectParam import java.io.InputStream import kotlin.reflect.KClass /** * Common base type for all format libraries which can convert directly from String -> Classes */ abstract class AutoMarshalling { abstract fun <T : Any> asA(input: String, target: KClass<T>): T abstract fun <T : Any> asA(input: InputStream, target: KClass<T>): T @JvmName("streamAsA") inline fun <reified T : Any> asA(input: InputStream): T = asA(input, T::class) @JvmName("stringAsA") inline fun <reified T : Any> asA(input: String): T = asA(input, T::class) @JvmName("stringAsA") fun <T : Any> String.asA(target: KClass<T>): T = asA(this, target) abstract fun asFormatString(input: Any): String fun asInputStream(input: Any): InputStream = asFormatString(input).byteInputStream() /** * Conversion happens by converting the base object into JSON and then out again */ inline fun <IN : Any, reified OUT : Any> convert(input: IN): OUT = asA(asFormatString(input)) @JvmName("autoRequest") inline fun <reified OUT : Any> BiDiLensSpec<Request, String>.auto() = autoLens<Request, OUT>(this) inline fun <reified OUT : Any> BiDiLensSpec<HttpMessage, String>.auto() = autoLens<HttpMessage, OUT>(this) inline fun <reified IN : Any, reified OUT : Any> autoLens(lens: BiDiLensSpec<IN, String>) = lens.mapWithNewMeta({ asA<OUT>(it) }, { asFormatString(it) }, ObjectParam) }
apache-2.0
0f4317ed139b2ec582d3329c42aea685
36
110
0.700189
3.63242
false
false
false
false
openMF/android-client
mifosng-android/src/main/java/com/mifos/mifosxdroid/adapters/DataTableAdapter.kt
1
1583
package com.mifos.mifosxdroid.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.mifos.mifosxdroid.R import com.mifos.objects.noncore.DataTable class DataTableAdapter( val onDateTableClick: (DataTable) -> Unit ) : RecyclerView.Adapter<DataTableAdapter.ViewHolder>() { var dataTables: List<DataTable> = ArrayList() set(value) { field = value notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val viewHolder = ViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.item_data_table, parent, false) ) viewHolder.itemView.setOnClickListener { if(viewHolder.adapterPosition != RecyclerView.NO_POSITION) onDateTableClick(dataTables[viewHolder.adapterPosition]) } return viewHolder } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val dataTable = dataTables[position] holder.tvDataTableName.text = dataTable.registeredTableName } override fun getItemCount() = dataTables.size fun getItem(position: Int): DataTable { return dataTables[position] } override fun getItemId(i: Int): Long { return 0 } class ViewHolder(v: View) : RecyclerView.ViewHolder(v) { val tvDataTableName: TextView = v.findViewById(R.id.tv_data_table_name) } }
mpl-2.0
79a2be4477ac023abe2efa70df4c074d
30.039216
83
0.687934
4.61516
false
false
false
false
tfcbandgeek/SmartReminders-android
app/src/main/java/jgappsandgames/smartreminderslite/sort/WeekActivity.kt
1
3129
package jgappsandgames.smartreminderslite.sort // Java import java.util.Calendar // Android OS import android.app.Activity import android.os.Bundle // View import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity // App import jgappsandgames.smartreminderslite.R import jgappsandgames.smartreminderslite.adapter.TaskAdapter // Save import jgappsandgames.smartreminderssave.MasterManager import jgappsandgames.smartreminderssave.date.DateManager // KotlinX import kotlinx.android.synthetic.main.activity_date.* // App import jgappsandgames.smartreminderslite.utility.* /** * WeekActivity * Created by joshua on 1/19/2018. */ class WeekActivity: AppCompatActivity(), TaskAdapter.OnTaskChangedListener { // Data ---------------------------------------------------------------------------------------- private var weekActive: Int = 0 // LifeCycle Methods --------------------------------------------------------------------------- override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_date) // First Run loadClass(this) // Set Title setTitle() // Set Click Listeners date_previous.setOnClickListener { weekActive-- if (weekActive < 0) weekActive = 0 date_tasks.adapter = TaskAdapter(this, this, TaskAdapter.swapTasks(DateManager.getWeekTasks(weekActive)), "") setTitle() } date_next.setOnClickListener { weekActive++ date_tasks.adapter = TaskAdapter(this, this, TaskAdapter.swapTasks(DateManager.getWeekTasks(weekActive)), "") setTitle() } } override fun onResume() { super.onResume() DateManager.create() date_tasks.adapter = TaskAdapter(this, this, TaskAdapter.swapTasks(DateManager.getWeekTasks(weekActive)), "") } override fun onPause() { super.onPause() save() } // Menu ---------------------------------------------------------------------------------------- override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_auxilary, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean = onOptionsItemSelected(this, item, object: Save { override fun save() = [email protected]() }) // Task Changed Listener ----------------------------------------------------------------------- override fun onTaskChanged() = onResume() // Private Class Methods ----------------------------------------------------------------------- private fun setTitle() { val start = DateManager.getWeek(weekActive).getStart() val end = DateManager.getWeek(weekActive).getEnd() title = (start.get(Calendar.MONTH) + 1).toString() + "/" + start.get(Calendar.DAY_OF_MONTH).toString() + " - " + (end.get(Calendar.MONTH) + 1).toString() + "/" + end.get(Calendar.DAY_OF_MONTH).toString() } fun save() = MasterManager.save() }
apache-2.0
e7805cb91bb2e863607aa8d25159391f
31.947368
164
0.588367
4.998403
false
false
false
false
IntershopCommunicationsAG/scmversion-gradle-plugin
src/main/kotlin/com/intershop/gradle/scm/task/CreateBranch.kt
1
3233
/* * Copyright 2020 Intershop Communications AG. * * 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.intershop.gradle.scm.task import com.intershop.gradle.scm.extension.ScmExtension import com.intershop.gradle.scm.utils.BranchType import org.gradle.api.GradleException import org.gradle.api.tasks.Input import org.gradle.api.tasks.Optional import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.options.Option /** * This is the implementation of Gradle * task to create the "next" branch. */ open class CreateBranch: AbstractDryRunTask() { private var featureName: String = "" init { outputs.upToDateWhen { false } description = "Creates an SCM branch With a specific version from the working copy" } /** * This will configure the feature extension of a branch. * It is a command line option of this task. * * @property feature */ @set:Option(option = "feature", description = "Feature extension for version tasks.") @get:Optional @get:Input var feature: String get() = featureName set(value) { featureName = value } /** * Implementation of the task action. */ @Throws(GradleException::class) @TaskAction fun branch() { val versionConfig = project.extensions.getByType(ScmExtension::class.java).version val versionService = versionConfig.versionService if(versionService.localService.branchType == BranchType.TAG) { throw GradleException("It is not possible to create a branch from an tag! " + "Please check your working copy and workflow.") } var version = versionService.preVersion var isFeatureBranch = false if(featureName.isNotEmpty()) { version = version.setBranchMetadata(featureName) isFeatureBranch = true } if(! dryRun) { try { versionService.createBranch(version.toStringFor(versionConfig.patternDigits), isFeatureBranch) } catch (ex: Exception) { throw GradleException("It is not possible to create a branch on the SCM! (${ex.message})") } println(""" |---------------------------------------------- | Branch created: $version |----------------------------------------------""".trimMargin()) } else { println(""" |---------------------------------------------- | DryRun: Branch would be created: | Branch: $version |----------------------------------------------""".trimMargin()) } } }
apache-2.0
e90022cdf7ea876c7a37310474fc6960
31.989796
110
0.598515
4.78963
false
false
false
false
ligi/PlugHub
app/src/main/java/org/ligi/plughub/MainActivity.kt
1
2758
package org.ligi.plughub import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.SwitchCompat import android.text.method.LinkMovementMethod import android.widget.EditText import android.widget.TextView import org.jetbrains.anko.* public class MainActivity : AppCompatActivity() { val cfg = EdiMaxConfig() val comm = EdiMaxCommunicator(cfg) var switch: SwitchCompat? = null var powerState: TextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) createUI() getDataCall() } private fun getDataCall() { comm.executeCommand(EdiMaxCommands.CMD_GET_STATE, { param -> runOnUiThread { if (param != null) { switch!!.setChecked((EdiMaxCommands.unwrapPowerState(param) == "ON")) } comm.executeCommand(EdiMaxCommands.CMD_GET_POWER, { response -> runOnUiThread { if (response != null) { powerState!!.setText(EdiMaxCommands.unwrapNowCurrent(response) + "A " + EdiMaxCommands.unwrapNowPower(response) + "W") } getDataCall() } }) } }) } private fun createUI() { verticalLayout() { textView("Only works with EdiMax plugs at the moment").setMovementMethod(LinkMovementMethod()) linearLayout { editText { setText(cfg.host) extractText { text -> cfg.host = text } } textView(":") editText { setText(cfg.port.toString()) extractText { text -> cfg.port = Integer.valueOf(text) } } } editText { setText(cfg.pass) extractText { text -> cfg.pass = text } } switch = switchCompatSupport() { onCheckedChange { compoundButton, b -> comm.executeCommand(if (b) EdiMaxCommands.CMD_ON else EdiMaxCommands.CMD_OFF, {}) } setText("Switch") } powerState = textView() }.setPadding(dip(16), dip(16), dip(16), dip(16)) } private fun EditText.extractText(function: (param: String) -> Unit) { textChangedListener { onTextChanged { text, start, before, count -> function(text.toString()) } } } }
gpl-3.0
a8ac6dbf8afc7748f8e29a25ebf074f6
28.978261
146
0.506889
5.145522
false
false
false
false
fossasia/open-event-android
app/src/main/java/org/fossasia/openevent/general/order/OrdersUnderUserFragment.kt
1
10478
package org.fossasia.openevent.general.order import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible import androidx.core.widget.NestedScrollView import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.Navigation.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.content_no_internet.view.noInternetCard import kotlinx.android.synthetic.main.dialog_filter_order.view.completedOrdersCheckBox import kotlinx.android.synthetic.main.dialog_filter_order.view.dateRadioButton import kotlinx.android.synthetic.main.dialog_filter_order.view.orderStatusRadioButton import kotlinx.android.synthetic.main.dialog_filter_order.view.pendingOrdersCheckBox import kotlinx.android.synthetic.main.dialog_filter_order.view.placedOrdersCheckBox import kotlinx.android.synthetic.main.fragment_orders_under_user.view.filter import kotlinx.android.synthetic.main.fragment_orders_under_user.view.filterToolbar import kotlinx.android.synthetic.main.fragment_orders_under_user.view.findMyTickets import kotlinx.android.synthetic.main.fragment_orders_under_user.view.noTicketsScreen import kotlinx.android.synthetic.main.fragment_orders_under_user.view.ordersRecycler import kotlinx.android.synthetic.main.fragment_orders_under_user.view.pastEvent import kotlinx.android.synthetic.main.fragment_orders_under_user.view.scrollView import kotlinx.android.synthetic.main.fragment_orders_under_user.view.shimmerSearch import kotlinx.android.synthetic.main.fragment_orders_under_user.view.swipeRefresh import kotlinx.android.synthetic.main.fragment_orders_under_user.view.ticketsNumber import kotlinx.android.synthetic.main.fragment_orders_under_user.view.ticketsTitle import kotlinx.android.synthetic.main.fragment_orders_under_user.view.toolbarLayout import org.fossasia.openevent.general.BottomIconDoubleClick import org.fossasia.openevent.general.R import org.fossasia.openevent.general.utils.Utils import org.fossasia.openevent.general.utils.Utils.setToolbar import org.fossasia.openevent.general.utils.extensions.hideWithFading import org.fossasia.openevent.general.utils.extensions.nonNull import org.fossasia.openevent.general.utils.extensions.showWithFading import org.jetbrains.anko.design.longSnackbar import org.koin.androidx.viewmodel.ext.android.viewModel const val ORDERS_FRAGMENT = "ordersFragment" class OrdersUnderUserFragment : Fragment(), BottomIconDoubleClick { private lateinit var rootView: View private val ordersUnderUserVM by viewModel<OrdersUnderUserViewModel>() private val ordersPagedListAdapter = OrdersPagedListAdapter() override fun onStart() { super.onStart() if (!ordersUnderUserVM.isLoggedIn()) { redirectToLogin() } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { rootView = inflater.inflate(R.layout.fragment_orders_under_user, container, false) setToolbar(activity, show = false) ordersPagedListAdapter.setShowExpired(false) rootView.ordersRecycler.adapter = ordersPagedListAdapter rootView.ordersRecycler.isNestedScrollingEnabled = false val linearLayoutManager = LinearLayoutManager(context) linearLayoutManager.orientation = RecyclerView.VERTICAL rootView.ordersRecycler.layoutManager = linearLayoutManager ordersUnderUserVM.connection .nonNull() .observe(viewLifecycleOwner, Observer { isConnected -> if (!isConnected) { showNoInternetScreen(true) } else { val currentItems = ordersUnderUserVM.eventAndOrderPaged.value if (currentItems != null) { showNoInternetScreen(false) showNoTicketsScreen(currentItems.size == 0) ordersPagedListAdapter.submitList(currentItems) } else { ordersUnderUserVM.getOrdersAndEventsOfUser(showExpired = false, fromDb = true) } } }) ordersUnderUserVM.numOfTickets .nonNull() .observe(viewLifecycleOwner, Observer { rootView.ticketsNumber.text = resources.getQuantityString(R.plurals.numOfOrders, it, it) showNoTicketsScreen(it == 0 && !rootView.shimmerSearch.isVisible) }) ordersUnderUserVM.showShimmerResults .nonNull() .observe(viewLifecycleOwner, Observer { if (it) { rootView.shimmerSearch.startShimmer() showNoTicketsScreen(false) showNoInternetScreen(false) } else { rootView.shimmerSearch.stopShimmer() rootView.swipeRefresh.isRefreshing = false } rootView.shimmerSearch.isVisible = it }) ordersUnderUserVM.message .nonNull() .observe(viewLifecycleOwner, Observer { rootView.longSnackbar(it) }) ordersUnderUserVM.eventAndOrderPaged .nonNull() .observe(viewLifecycleOwner, Observer { ordersPagedListAdapter.submitList(it) }) rootView.swipeRefresh.setColorSchemeColors(Color.BLUE) rootView.swipeRefresh.setOnRefreshListener { if (ordersUnderUserVM.isConnected()) { ordersUnderUserVM.clearOrders() ordersUnderUserVM.getOrdersAndEventsOfUser(showExpired = false, fromDb = false) } else { rootView.swipeRefresh.isRefreshing = false } } return rootView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val recyclerViewClickListener = object : OrdersPagedListAdapter.OrderClickListener { override fun onClick(eventID: Long, orderIdentifier: String, orderId: Long) { findNavController(rootView).navigate(OrdersUnderUserFragmentDirections .actionOrderUserToOrderDetails(eventID, orderIdentifier, orderId)) } } ordersPagedListAdapter.setListener(recyclerViewClickListener) rootView.pastEvent.setOnClickListener { findNavController(rootView).navigate(OrdersUnderUserFragmentDirections.actionOrderUserToOrderExpired()) } rootView.findMyTickets.setOnClickListener { Utils.openUrl(requireContext(), resources.getString(R.string.ticket_issues_url)) } rootView.scrollView.setOnScrollChangeListener { _: NestedScrollView?, _: Int, scrollY: Int, _: Int, _: Int -> if (scrollY > rootView.ticketsTitle.y && !rootView.toolbarLayout.isVisible) { rootView.toolbarLayout.showWithFading() } else if (scrollY < rootView.ticketsTitle.y && rootView.toolbarLayout.isVisible) { rootView.toolbarLayout.hideWithFading() } } rootView.filter.setOnClickListener { showFilterDialog() } rootView.filterToolbar.setOnClickListener { showFilterDialog() } } private fun showFilterDialog() { val filterLayout = layoutInflater.inflate(R.layout.dialog_filter_order, null) filterLayout.completedOrdersCheckBox.isChecked = ordersUnderUserVM.filter.isShowingCompletedOrders filterLayout.pendingOrdersCheckBox.isChecked = ordersUnderUserVM.filter.isShowingPendingOrders filterLayout.placedOrdersCheckBox.isChecked = ordersUnderUserVM.filter.isShowingPlacedOrders if (ordersUnderUserVM.filter.isSortingOrdersByDate) filterLayout.dateRadioButton.isChecked = true else filterLayout.orderStatusRadioButton.isChecked = true AlertDialog.Builder(requireContext()) .setView(filterLayout) .setNegativeButton(getString(R.string.cancel)) { dialog, _ -> dialog.cancel() }.setPositiveButton(getString(R.string.apply)) { _, _ -> ordersUnderUserVM.filter.isShowingCompletedOrders = filterLayout.completedOrdersCheckBox.isChecked ordersUnderUserVM.filter.isShowingPendingOrders = filterLayout.pendingOrdersCheckBox.isChecked ordersUnderUserVM.filter.isShowingPlacedOrders = filterLayout.placedOrdersCheckBox.isChecked ordersUnderUserVM.filter.isSortingOrdersByDate = filterLayout.dateRadioButton.isChecked applyFilter() }.create().show() } private fun applyFilter() { ordersUnderUserVM.clearOrders() ordersPagedListAdapter.clear() if (ordersUnderUserVM.isConnected()) { ordersUnderUserVM.getOrdersAndEventsOfUser(showExpired = false, fromDb = false) } else { showNoInternetScreen(true) } } override fun onDestroyView() { super.onDestroyView() rootView.swipeRefresh.setOnRefreshListener(null) ordersPagedListAdapter.setListener(null) } private fun showNoTicketsScreen(show: Boolean) { rootView.noTicketsScreen.isVisible = show } private fun redirectToLogin() { findNavController(rootView).navigate(OrdersUnderUserFragmentDirections .actionOrderUserToAuth(getString(R.string.log_in_first), ORDERS_FRAGMENT)) } private fun showNoInternetScreen(show: Boolean) { if (show) { rootView.shimmerSearch.isVisible = false showNoTicketsScreen(false) ordersPagedListAdapter.clear() } rootView.noInternetCard.isVisible = show } override fun doubleClick() = rootView.scrollView.smoothScrollTo(0, 0) override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { activity?.onBackPressed() true } else -> super.onOptionsItemSelected(item) } } }
apache-2.0
317b7163726aa93525d1a0b5824bd433
42.841004
117
0.695934
4.996662
false
false
false
false
dafi/commonutils
app/src/main/java/com/ternaryop/utils/network/UriUtils.kt
1
6539
package com.ternaryop.utils.network import android.content.ContentUris import android.content.Context import android.net.Uri import android.os.Build import android.os.Environment import android.provider.DocumentsContract import android.provider.MediaStore import android.util.Pair import java.io.UnsupportedEncodingException import java.net.URI import java.net.URISyntaxException import java.net.URLEncoder /** * Created by dave on 25/04/14. * Helper class to work with Uri */ const val RESOLVE_URL_RETRY_COUNT = 20 /** * Method for return file path of Gallery image * * @param context * @return path of the selected image file from gallery */ fun Uri.getPath(context: Context): String? { //check here to KITKAT or new version val isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, this)) { // ExternalStorageProvider if (isExternalStorageDocument) { val docId = DocumentsContract.getDocumentId(this) val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val type = split[0] if ("primary".equals(type, ignoreCase = true)) { return Environment.getExternalStorageDirectory().toString() + "/" + split[1] } } else if (isDownloadsDocument) { // DownloadsProvider val id = DocumentsContract.getDocumentId(this) val contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id)) return contentUri.getDataColumn(context, null, null) } else if (isMediaDocument) { // MediaProvider val docId = DocumentsContract.getDocumentId(this) val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val type = split[0] val contentUri: Uri? = when (type) { "image" -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI "video" -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI "audio" -> MediaStore.Audio.Media.EXTERNAL_CONTENT_URI else -> null } val selection = "_id=?" val selectionArgs = arrayOf(split[1]) return contentUri.getDataColumn(context, selection, selectionArgs) } } else if ("content".equals(scheme, ignoreCase = true)) { // MediaStore (and general) // Return the remote address return if (isGooglePhotosUri) lastPathSegment else getDataColumn(context, null, null) } else if ("file".equals(scheme, ignoreCase = true)) { // File return path } return null } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context The context. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ fun Uri?.getDataColumn(context: Context, selection: String?, selectionArgs: Array<String>?): String? { if (this == null) return null val projection = arrayOf(MediaStore.Images.Media.DATA) return context.contentResolver.query(this, projection, selection, selectionArgs, null)?.use { cursor -> if (cursor.moveToFirst()) { cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)) } else { null } } } /** * @return Whether the Uri authority is ExternalStorageProvider. */ inline val Uri.isExternalStorageDocument: Boolean get() = "com.android.externalstorage.documents" == authority /** * @return Whether the Uri authority is DownloadsProvider. */ inline val Uri.isDownloadsDocument: Boolean get() = "com.android.providers.downloads.documents" == authority /** * @return Whether the Uri authority is MediaProvider. */ inline val Uri.isMediaDocument: Boolean get() = "com.android.providers.media.documents" == authority /** * @return Whether the Uri authority is Google Photos. */ inline val Uri.isGooglePhotosUri: Boolean get() = "com.google.android.apps.photos.content" == authority fun Uri.getRealPathAndMimeFromUri(context: Context): Pair<String, String>? { val proj = arrayOf(MediaStore.Images.Media.MIME_TYPE) return context.contentResolver.query(this, proj, null, null, null)?.use { cursor -> cursor.moveToFirst() Pair.create(getPath(context), cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.MIME_TYPE))) } } object UriUtils { /** * URI doesn't encode invalid characters, so we do it * For example the url http://my.com/hello\u00a0-world.jpg is fixed into * http://my.com/hello%C2%A0-world.jpg * @param uriString the url to convert to URI * @param enc the encoding to use * @param retryCount how many times must retry before throw exception * @return the fixed url * @throws URISyntaxException unable to encode the illegal characters * @throws UnsupportedEncodingException unable to encode the url */ fun encodeIllegalChar(uriString: String, enc: String, retryCount: Int = RESOLVE_URL_RETRY_COUNT): URI { var count = retryCount var uriStr = uriString while (true) { try { return URI(uriStr) } catch (e: URISyntaxException) { val reason = e.reason if (reason == null || !(reason.contains("in path") || reason.contains("in query") || reason.contains("in fragment"))) { throw e } if (0 > count--) { throw e } val input = e.input val idx = e.index val illChar = input[idx].toString() uriStr = input.replace(illChar, URLEncoder.encode(illChar, enc)) } } } fun resolveRelativeURL(baseURL: String?, link: String): String { val uri = encodeIllegalChar(link, "UTF-8") return when { uri.isAbsolute -> uri.toString() baseURL != null -> encodeIllegalChar(baseURL, "UTF-8").resolve(uri).toString() else -> throw IllegalArgumentException("baseUrl is null") } } }
mit
22b8fbed75981204ef286d301585db66
35.735955
117
0.637406
4.484911
false
false
false
false
kropp/intellij-makefile
src/main/kotlin/name/kropp/intellij/makefile/MakefileShellLanguageInjector.kt
1
1967
package name.kropp.intellij.makefile import com.intellij.lang.* import com.intellij.lang.injection.* import com.intellij.openapi.util.* import com.intellij.psi.* import name.kropp.intellij.makefile.psi.* import kotlin.math.* private const val SHELL_LANGUAGE_ID = "Shell Script" private val SHELL_LANGUAGE = Language.findLanguageByID(SHELL_LANGUAGE_ID) class MakefileShellLanguageInjector : MultiHostInjector { override fun elementsToInjectIn(): MutableList<out Class<out PsiElement>> { return mutableListOf(MakefileRecipe::class.java, MakefileFunction::class.java, MakefileSubstitution::class.java) } private fun isTab(c: Char): Boolean = c == '\t' override fun getLanguagesToInject(registrar: MultiHostRegistrar, context: PsiElement) { if (SHELL_LANGUAGE == null) return val rangesToInject = when (context) { is MakefileRecipe -> { context.children.filterIsInstance<MakefileCommand>().map { val tabs = it.text.takeWhile(::isTab).count() val firstSymbol = it.text.dropWhile(::isTab).firstOrNull() val silent = if (firstSymbol == '@' || firstSymbol == '-') 1 else 0 TextRange.create(it.textRangeInParent.startOffset + tabs + silent, min(it.textRangeInParent.endOffset, context.textLength)) } } is MakefileFunction -> { if (context.functionName.textMatches("shell")) { context.children.filterIsInstance<MakefileFunctionParam>().map { it.textRangeInParent } } else { emptyList() } } is MakefileSubstitution -> { if (context.textLength > 2) { listOf(TextRange(1, context.textLength - 1)) } else emptyList() } else -> emptyList() } if (rangesToInject.any()) { registrar.startInjecting(SHELL_LANGUAGE) rangesToInject.forEach { registrar.addPlace(null, null, context as PsiLanguageInjectionHost, it) } registrar.doneInjecting() } } }
mit
32c64563b7286d2e1f4d1ea6b2d42e30
34.781818
133
0.678699
4.390625
false
false
false
false
nicorsm/S3-16-simone
app/src/main/java/app/simone/multiplayer/controller/NearbyGameController.kt
2
3871
package app.simone.multiplayer.controller import app.simone.multiplayer.model.FacebookUser import app.simone.multiplayer.view.nearby.WaitingRoomActivity import app.simone.shared.utils.Constants import com.facebook.Profile import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import java.util.* /** * Controller containing useful functions for communicating with Firebase about the Nearby multiplayer. * @author Nicola Giancecchi */ class NearbyGameController { companion object { const val USERS_REF = "users" const val MATCHES_REF = "matches" const val TAKEN = "taken" const val TOKEN = "token" const val STARTED = "started" } val db = FirebaseDatabase.getInstance() /** * Updates Firebase Cloud Notifications token * @param token notification token, as provided by FCM * @param fbid Facebook ID of the user linked to the token */ fun updateToken(token: String, fbid: String) { db.getReference(USERS_REF).child(fbid).child(TOKEN).setValue(token) } /** * Updates the online profile of the user. */ fun updateUserData(){ if(FacebookManagerActor.isLoggedIn()){ val profile = Profile.getCurrentProfile() val userNode = db.getReference(USERS_REF).child(profile.id) userNode.child(FacebookUser.kNAME).setValue(profile.name) val profileUri = profile.getProfilePictureUri(Constants.FB_IMAGE_PICTURE_SIZE,Constants.FB_IMAGE_PICTURE_SIZE) userNode.child(FacebookUser.kPICTURE).setValue(profileUri.toString()) } } /** * Creates a node on the Realtime Database to start a new match * @param userIDs a list of strings containing the Facebook IDs of the participating users. * @param playerID the Facebook ID of the current player. */ fun createMatch(userIDs: List<String>, playerID: String): String { val matchName = UUID.randomUUID().toString() val users = HashMap<String,Any>() for (userID in userIDs) { val value = HashMap<String,Boolean>() value["taken"] = (userID == playerID) users[userID] = value } db.getReference(MATCHES_REF).child(matchName).child(USERS_REF).setValue(users) return matchName } /** * Observes current players and updates the list when data changes. * @param match the ID of the match to observe * @param activity the activity to be attached. */ fun getAndListenForNewPlayers(match: String, activity: WaitingRoomActivity) { val ref = db.getReference(MATCHES_REF).child(match) val adapter = FirebaseListAdapterFactory.getWaitingRoomAdapter(ref, activity) activity.listView?.adapter = adapter var activityStarted = false ref.addValueEventListener(object: ValueEventListener { override fun onCancelled(p0: DatabaseError?) { } override fun onDataChange(p0: DataSnapshot?) { val started = p0?.child(STARTED) val users = p0?.child(USERS_REF) if(users?.children?.filter { it.child(TAKEN).value == false }?.count() == 0 && !activityStarted){ activity.startGameActivity(match) activityStarted = true } } }) } /** * A call to Database made when the user accepts an invite to a match * @param user Facebook ID of the user * @param match ID of the match */ fun acceptInvite(user: String, match: String) { db.getReference(MATCHES_REF).child(match).child(USERS_REF).child(user).child(TAKEN).setValue(true) } }
mit
329f5de5f4c0016b47272e7e583084dc
35.186916
122
0.657195
4.449425
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/inspections/latex/typesetting/spacing/LatexEllipsisInspection.kt
1
3104
package nl.hannahsten.texifyidea.inspections.latex.typesetting.spacing import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.refactoring.suggested.startOffset import nl.hannahsten.texifyidea.inspections.InsightGroup import nl.hannahsten.texifyidea.inspections.TexifyInspectionBase import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.AMSMATH import nl.hannahsten.texifyidea.psi.LatexNormalText import nl.hannahsten.texifyidea.util.* import nl.hannahsten.texifyidea.util.magic.PatternMagic /** * @author Sten Wessel */ open class LatexEllipsisInspection : TexifyInspectionBase() { override val inspectionGroup = InsightGroup.LATEX override fun getDisplayName() = "Ellipsis with ... instead of \\ldots or \\dots" override val inspectionId = "Ellipsis" override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): MutableList<ProblemDescriptor> { val descriptors = descriptorList() val texts = file.childrenOfType(LatexNormalText::class) for (text in texts) { ProgressManager.checkCanceled() for (match in PatternMagic.ellipsis.findAll(text.text)) { // Ignore the inspection when the ellipsis is inside a comment. if (file.findElementAt(match.range.first + text.startOffset)?.isComment() == true) { continue } descriptors.add( manager.createProblemDescriptor( text, match.range.toTextRange(), "Ellipsis with ... instead of command", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOntheFly, InsertEllipsisCommandFix(text.inMathContext()) ) ) } } return descriptors } /** * @author Sten Wessel */ private class InsertEllipsisCommandFix(val inMathMode: Boolean) : LocalQuickFix { override fun getFamilyName() = "Convert to ${if (inMathMode) "\\dots (amsmath package)" else "\\ldots"}" override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement val file = element.containingFile val document = PsiDocumentManager.getInstance(project).getDocument(file) ?: return val range = descriptor.textRangeInElement.shiftRight(element.textOffset) document.replaceString(range.startOffset, range.endOffset, if (inMathMode) "\\dots" else "\\ldots") if (inMathMode && AMSMATH !in file.includedPackages()) { file.insertUsepackage(AMSMATH) } } } }
mit
8a7d2a30c31b7b1b1d3f590b4420052e
38.291139
126
0.672358
5.18197
false
false
false
false
KotlinKit/Reactant
Core/src/main/kotlin/org/brightify/reactant/autolayout/AutoLayout.kt
1
9401
package org.brightify.reactant.autolayout import android.content.Context import android.util.AttributeSet import android.util.Log import android.view.View import android.view.ViewGroup import org.brightify.reactant.autolayout.internal.AutoLayoutConstraints import org.brightify.reactant.autolayout.internal.ConstraintManager import org.brightify.reactant.autolayout.internal.util.isAlmostZero import org.brightify.reactant.autolayout.util.description import org.brightify.reactant.autolayout.util.forEachChild import org.brightify.reactant.autolayout.util.snp import org.brightify.reactant.core.util.assignId import org.brightify.reactant.core.util.onChange import kotlin.math.min import kotlin.math.roundToInt /** * @author <a href="mailto:[email protected]">Filip Dolnik</a> */ open class AutoLayout @JvmOverloads constructor(context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0) : ViewGroup(context, attrs, defStyleAttr, defStyleRes) { var measureTime: Boolean by onChange(false) { _, _, _ -> (parent as? AutoLayout)?.measureTime = measureTime forEachChild { if (it is AutoLayout) { it.measureTime = measureTime } } } internal var constraintManager = ConstraintManager() private set private val autoLayoutConstraints: AutoLayoutConstraints get() = constraintManager.viewConstraints[this]?.autoLayoutConstraints ?: throw IllegalStateException( "Missing AutoLayoutConstraints.") private val density: Double get() = resources.displayMetrics.density.toDouble() init { assignId() constraintManager.addManagedView(this) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { val offsetTop = constraintManager.getValueForVariable(snp.top) val offsetLeft = constraintManager.getValueForVariable(snp.left) forEachChild { it.layout( getChildPosition(it.snp.left, offsetLeft), getChildPosition(it.snp.top, offsetTop), getChildPosition(it.snp.right, offsetLeft), getChildPosition(it.snp.bottom, offsetTop) ) } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { if (parent is AutoLayout) { setMeasuredSize(widthMeasureSpec, heightMeasureSpec) measureRealSizes() } else { val begin = System.nanoTime() initializeAutoLayoutConstraints(widthMeasureSpec, heightMeasureSpec) constraintManager.updateIntrinsicSizeNecessityDecider() updateVisibility() requestLayoutRecursive(this) measureIntrinsicSizes() setMeasuredSize(widthMeasureSpec, heightMeasureSpec) measureIntrinsicHeights() if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY || MeasureSpec.getMode( heightMeasureSpec) != MeasureSpec.EXACTLY) { setMeasuredSize(widthMeasureSpec, heightMeasureSpec) } measureRealSizes() if (measureTime) { val time = (System.nanoTime() - begin) / 1e9 val wMode = MeasureSpec.getMode(widthMeasureSpec) shr 30 val wSize = MeasureSpec.getSize(widthMeasureSpec) val hMode = MeasureSpec.getMode(heightMeasureSpec) shr 30 val hSize = MeasureSpec.getSize(heightMeasureSpec) Log.d("AutoLayout.onMeasure", "($description) Took $time s totally where width: $wMode / $wSize and height: $hMode / $hSize " + "constraint count: ${constraintManager.allConstraints.size}.\n\n") } } } override fun shouldDelayChildPressedState() = false override fun onViewAdded(child: View?) { super.onViewAdded(child) child?.let { it.assignId() if (child is AutoLayout) { constraintManager.join(child.constraintManager) setConstraintManagerRecursive(child, constraintManager) child.autoLayoutConstraints.setActive(false) measureTime = measureTime or child.measureTime child.measureTime = measureTime } else { constraintManager.addManagedView(child) } } } override fun onViewRemoved(child: View?) { super.onViewRemoved(child) child?.let { if (child is AutoLayout) { setConstraintManagerRecursive(child, constraintManager.split(child)) child.autoLayoutConstraints.setActive(true) } else { constraintManager.removeManagedView(child) } } } private fun initializeAutoLayoutConstraints(widthMeasureSpec: Int, heightMeasureSpec: Int) { autoLayoutConstraints.widthIsAtMost = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.UNSPECIFIED) { autoLayoutConstraints.width = -1.0 } else { autoLayoutConstraints.width = MeasureSpec.getSize(widthMeasureSpec).toDp() } autoLayoutConstraints.heightIsAtMost = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) { autoLayoutConstraints.height = -1.0 } else { autoLayoutConstraints.height = MeasureSpec.getSize(heightMeasureSpec).toDp() } } private fun updateVisibility() { constraintManager.getVisibilityManager(this).visibility = visibility forEachChild { if (it is AutoLayout) { it.updateVisibility() } else { constraintManager.getVisibilityManager(it).visibility = it.visibility } } } private fun measureIntrinsicSizes() { forEachChild { if (it is AutoLayout) { it.measureIntrinsicSizes() } else if (constraintManager.getIntrinsicSizeManager(it) != null) { val needsWidth = constraintManager.needsIntrinsicWidth(it) val needsHeight = constraintManager.needsIntrinsicHeight(it) if (needsWidth || needsHeight) { it.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED) } it.snp.intrinsicWidth = if (needsWidth) it.measuredWidth.toDp() else -1.0 it.snp.intrinsicHeight = if (needsHeight) it.measuredHeight.toDp() else -1.0 } } } private fun measureIntrinsicHeights() { forEachChild { if (it is AutoLayout) { it.measureIntrinsicHeights() } else if (constraintManager.needsIntrinsicHeight(it) && !(constraintManager.getValueForVariable(it.snp.width) - it.snp.intrinsicWidth).isAlmostZero) { it.measure(MeasureSpec.makeMeasureSpec(constraintManager.getValueForVariable(it.snp.width).toPx(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)) val measuredHeight = it.measuredHeight.toDp() if (!(it.snp.intrinsicHeight - measuredHeight).isAlmostZero) { it.snp.intrinsicHeight = measuredHeight } } } } private fun measureRealSizes() { forEachChild { it.measure(MeasureSpec.makeMeasureSpec(constraintManager.getValueForVariable(it.snp.width).toPx(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(constraintManager.getValueForVariable(it.snp.height).toPx(), MeasureSpec.EXACTLY)) } } private fun getChildPosition(variable: ConstraintVariable, offset: Double): Int = (constraintManager.getValueForVariable( variable) - offset).toPx() private fun setMeasuredSize(widthMeasureSpec: Int, heightMeasureSpec: Int) { fun getMeasuredSize(measureSpec: Int, currentSize: ConstraintVariable): Int { return when (MeasureSpec.getMode(measureSpec)) { MeasureSpec.EXACTLY -> MeasureSpec.getSize(measureSpec) MeasureSpec.UNSPECIFIED -> constraintManager.getValueForVariable(currentSize).toPx() else -> min(MeasureSpec.getSize(measureSpec), constraintManager.getValueForVariable(currentSize).toPx()) } } setMeasuredDimension(getMeasuredSize(widthMeasureSpec, snp.width), getMeasuredSize(heightMeasureSpec, snp.height)) } private fun setConstraintManagerRecursive(view: AutoLayout, constraintManager: ConstraintManager) { view.constraintManager = constraintManager view.forEachChild { if (it is AutoLayout) { setConstraintManagerRecursive(it, constraintManager) } } } private fun requestLayoutRecursive(view: View) { view.requestLayout() (view as? AutoLayout)?.forEachChild { requestLayoutRecursive(it) } } private fun Double.toPx(): Int = (this * density).roundToInt() private fun Int.toDp(): Double = this / density }
mit
fb1dc9249c089acf7d491fdffa2645be
39.69697
197
0.64291
5.20831
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/editor/typedhandlers/LatexEnterBetweenBracesHandler.kt
1
2225
package nl.hannahsten.texifyidea.editor.typedhandlers import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.actionSystem.EditorActionHandler import com.intellij.openapi.util.Ref import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.util.IncorrectOperationException import nl.hannahsten.texifyidea.file.LatexFile import nl.hannahsten.texifyidea.psi.LatexTypes /** * In the situation \[<caret>\], when pressing enter the caret * should end up with the correct indent. * * @author Sten Wessel */ class LatexEnterBetweenBracesHandler : EnterHandlerDelegateAdapter() { override fun preprocessEnter(file: PsiFile, editor: Editor, caretOffset: Ref<Int>, caretAdvance: Ref<Int>, dataContext: DataContext, originalHandler: EditorActionHandler?): EnterHandlerDelegate.Result { if (file !is LatexFile) { return EnterHandlerDelegate.Result.Continue } val offset = caretOffset.get() val before = file.findElementAt(offset - 1) val after = file.findElementAt(offset + 1) if (before == null || after == null) { return EnterHandlerDelegate.Result.Continue } if (before.node.elementType === LatexTypes.DISPLAY_MATH_START && after.node.elementType === LatexTypes.DISPLAY_MATH_END) { originalHandler!!.execute(editor, editor.caretModel.currentCaret, dataContext) PsiDocumentManager.getInstance(file.getProject()).commitDocument(editor.document) try { CodeStyleManager.getInstance(file.getProject()).adjustLineIndent(file, editor.caretModel.offset) } catch (e: IncorrectOperationException) { Logger.getInstance(javaClass).error(e) } return EnterHandlerDelegate.Result.DefaultForceIndent } return EnterHandlerDelegate.Result.Continue } }
mit
93271f9ec196406f7fa189d5da696b48
40.981132
206
0.736629
4.922566
false
false
false
false
android/android-studio-poet
aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/project/GradlewGenerator.kt
1
3641
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.androidstudiopoet.generators.project import com.google.androidstudiopoet.models.ProjectBlueprint import com.google.androidstudiopoet.utils.joinPath import com.google.androidstudiopoet.writers.GithubDownloader import java.io.File import java.io.FileInputStream import java.nio.file.Files import java.nio.file.StandardCopyOption object GradlewGenerator { private val ref = "master" fun generateGradleW(root: String, projectBlueprint: ProjectBlueprint) { val gradlew = "gradlew" val gradlewbat = "gradlew.bat" if (!File(getAssetsFolderPath()).exists() || !File(getAssetsFolderPath(), gradlew).exists() || !File(getAssetsFolderPath(), gradlewbat).exists() || !File(getAssetsFolderPath(), "gradle/wrapper").exists() ) { println("AS Poet needs network access to download gradle files from Github " + "\nhttps://github.com/android/android-studio-poet/tree/master/resources/gradle-assets?ref=$ref " + "\nplease copy/paste the gradle folder directly to the generated root folder") return } val gradleWFile = File(root, gradlew).toPath() Files.copy(FileInputStream(File(getAssetsFolderPath(), gradlew)), gradleWFile, StandardCopyOption.REPLACE_EXISTING) Files.copy(FileInputStream(File(getAssetsFolderPath(), gradlewbat)), File(root, gradlewbat).toPath(), StandardCopyOption.REPLACE_EXISTING) Runtime.getRuntime().exec("chmod u+x " + gradleWFile) val gradleFolder = File(root, "gradle") gradleFolder.mkdir() val gradleWrapperFolder = File(gradleFolder, "wrapper") gradleWrapperFolder.mkdir() val sourceFolder = File(getAssetsFolderPath(), "gradle/wrapper") val gradleWrapperJar = "gradle-wrapper.jar" val gradleWrapperProperties = "gradle-wrapper.properties" Files.copy(FileInputStream(File(sourceFolder, gradleWrapperJar)), File(gradleWrapperFolder, gradleWrapperJar).toPath(), StandardCopyOption.REPLACE_EXISTING) File(gradleWrapperFolder, gradleWrapperProperties). writeText(gradleWrapper(projectBlueprint.gradleVersion)) } private fun getAssetsFolderPath(): String { var assetsFolder: String = System.getProperty("user.home") .joinPath(".aspoet") .joinPath("gradle-assets") if (!File(assetsFolder).exists()) { GithubDownloader().downloadDir( "https://api.github.com/repos/android/" + "android-studio-poet/contents/resources/gradle-assets?ref=$ref", assetsFolder) } return assetsFolder } private fun gradleWrapper(gradleVersion: String) = """ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-$gradleVersion-bin.zip """ }
apache-2.0
7c9818bd320451ce24b8fed412323ec8
37.326316
146
0.688822
4.71022
false
false
false
false
crunchersaspire/worshipsongs-android
app/src/main/java/org/worshipsongs/fragment/TopicsFragment.kt
3
6269
package org.worshipsongs.fragment import android.app.SearchManager import android.content.Context import android.content.Intent import android.graphics.Color import android.graphics.PorterDuff import android.os.Bundle import android.os.Parcelable import android.view.* import android.widget.ImageView import android.widget.ListView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import org.worshipsongs.CommonConstants import org.worshipsongs.R import org.worshipsongs.activity.SongListActivity import org.worshipsongs.adapter.TitleAdapter import org.worshipsongs.domain.Topics import org.worshipsongs.domain.Type import org.worshipsongs.listener.SongContentViewListener import org.worshipsongs.registry.ITabFragment import org.worshipsongs.service.TopicService import org.worshipsongs.service.UserPreferenceSettingService import org.worshipsongs.utils.CommonUtils /** * @author: Madasamy * @since: 3.x */ class TopicsFragment : AbstractTabFragment(), TitleAdapter.TitleAdapterListener<Topics>, ITabFragment { private var state: Parcelable? = null private var topicsService: TopicService? = null private var topicsList: List<Topics>? = null private var topicsListView: ListView? = null private var titleAdapter: TitleAdapter<Topics>? = null private val userPreferenceSettingService = UserPreferenceSettingService() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { state = savedInstanceState.getParcelable(STATE_KEY) } setHasOptionsMenu(true) initSetUp() } private fun initSetUp() { topicsService = TopicService(activity!!.applicationContext) topicsList = topicsService!!.findAll() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.songs_layout, container, false) as View setListView(view) return view } private fun setListView(view: View) { topicsListView = view.findViewById<View>(R.id.song_list_view) as ListView titleAdapter = TitleAdapter((activity as AppCompatActivity?)!!, R.layout.songs_layout) titleAdapter!!.setTitleAdapterListener(this) titleAdapter!!.addObjects(topicsService!!.filteredTopics("", topicsList!!)) topicsListView!!.adapter = titleAdapter } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.action_bar_menu, menu) val searchManager = activity!!.getSystemService(Context.SEARCH_SERVICE) as SearchManager val searchView = menu!!.findItem(R.id.menu_search).actionView as SearchView searchView.setSearchableInfo(searchManager.getSearchableInfo(activity!!.componentName)) searchView.maxWidth = Integer.MAX_VALUE searchView.queryHint = getString(R.string.action_search) val image = searchView.findViewById<View>(R.id.search_close_btn) as ImageView val drawable = image.drawable drawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { titleAdapter!!.addObjects(topicsService!!.filteredTopics(query, topicsList!!)) return true } override fun onQueryTextChange(newText: String): Boolean { titleAdapter!!.addObjects(topicsService!!.filteredTopics(newText, topicsList!!)) return true } }) menu.getItem(0).isVisible = false super.onCreateOptionsMenu(menu, inflater) } override fun onSaveInstanceState(outState: Bundle) { if (this.isAdded && topicsListView != null) { outState.putParcelable(STATE_KEY, topicsListView!!.onSaveInstanceState()) } super.onSaveInstanceState(outState) } override fun onResume() { super.onResume() if (state != null) { topicsListView!!.onRestoreInstanceState(state) } else { titleAdapter!!.addObjects(topicsService!!.filteredTopics("", topicsList!!)) } } override fun onPause() { state = topicsListView!!.onSaveInstanceState() super.onPause() } override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) if (isVisibleToUser && topicsList != null) { CommonUtils.hideKeyboard(activity) } } private fun getTopicsName(topics: Topics): String { return if (userPreferenceSettingService.isTamil) topics.tamilName!! else topics.defaultName!! } override fun setViews(objects: Map<String, Any>, topics: Topics?) { val textView = objects[CommonConstants.TITLE_KEY] as TextView? textView!!.text = getTopicsName(topics!!) textView.setOnClickListener(getOnClickListener(topics)) setCountView((objects[CommonConstants.SUBTITLE_KEY] as TextView?)!!, topics.noOfSongs.toString()) } private fun getOnClickListener(topics: Topics): View.OnClickListener { return View.OnClickListener { val intent = Intent(context, SongListActivity::class.java) intent.putExtra(CommonConstants.TYPE, Type.TOPICS.name) intent.putExtra(CommonConstants.TITLE_KEY, getTopicsName(topics)) intent.putExtra(CommonConstants.ID, topics.id) startActivity(intent) } } override fun defaultSortOrder(): Int { return 2 } override val title: String get() { return "categories" } override fun checked(): Boolean { return true } override fun setListenerAndBundle(songContentViewListener: SongContentViewListener?, bundle: Bundle) { // Do nothing } companion object { private val STATE_KEY = "listViewState" } }
gpl-3.0
8cd4e313d7c0405ce4ae313de77c56b4
31.651042
114
0.683682
4.987271
false
false
false
false
PaulWoitaschek/Voice
bookOverview/src/main/kotlin/voice/bookOverview/views/BookFolderIcon.kt
1
803
package voice.bookOverview.views import androidx.compose.foundation.layout.Box import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Book import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import voice.bookOverview.R @Composable internal fun BookFolderIcon( withHint: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, ) { Box { IconButton(modifier = modifier, onClick = onClick) { Icon( imageVector = Icons.Outlined.Book, contentDescription = stringResource(R.string.audiobook_folders_title), ) } if (withHint) { AddBookHint() } } }
gpl-3.0
e019cda8e7b379368785be5359830807
25.766667
78
0.749689
4.096939
false
false
false
false
colriot/anko
dsl/testData/functional/common/SqlParserHelpersTest.kt
1
14476
public fun <T1, R> rowParser(parser: (T1) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 1) throw SQLiteException("Invalid row: 1 column required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1) } } } public fun <T1, T2, R> rowParser(parser: (T1, T2) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 2) throw SQLiteException("Invalid row: 2 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2) } } } public fun <T1, T2, T3, R> rowParser(parser: (T1, T2, T3) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 3) throw SQLiteException("Invalid row: 3 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3) } } } public fun <T1, T2, T3, T4, R> rowParser(parser: (T1, T2, T3, T4) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 4) throw SQLiteException("Invalid row: 4 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4) } } } public fun <T1, T2, T3, T4, T5, R> rowParser(parser: (T1, T2, T3, T4, T5) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 5) throw SQLiteException("Invalid row: 5 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5) } } } public fun <T1, T2, T3, T4, T5, T6, R> rowParser(parser: (T1, T2, T3, T4, T5, T6) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 6) throw SQLiteException("Invalid row: 6 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6) } } } public fun <T1, T2, T3, T4, T5, T6, T7, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 7) throw SQLiteException("Invalid row: 7 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 8) throw SQLiteException("Invalid row: 8 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 9) throw SQLiteException("Invalid row: 9 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 10) throw SQLiteException("Invalid row: 10 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 11) throw SQLiteException("Invalid row: 11 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 12) throw SQLiteException("Invalid row: 12 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 13) throw SQLiteException("Invalid row: 13 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 14) throw SQLiteException("Invalid row: 14 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 15) throw SQLiteException("Invalid row: 15 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 16) throw SQLiteException("Invalid row: 16 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 17) throw SQLiteException("Invalid row: 17 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16, columns[16] as T17) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 18) throw SQLiteException("Invalid row: 18 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16, columns[16] as T17, columns[17] as T18) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 19) throw SQLiteException("Invalid row: 19 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16, columns[16] as T17, columns[17] as T18, columns[18] as T19) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 20) throw SQLiteException("Invalid row: 20 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16, columns[16] as T17, columns[17] as T18, columns[18] as T19, columns[19] as T20) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 21) throw SQLiteException("Invalid row: 21 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16, columns[16] as T17, columns[17] as T18, columns[18] as T19, columns[19] as T20, columns[20] as T21) } } } public fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22) -> R): RowParser<R> { return object : RowParser<R> { override fun parseRow(columns: Array<Any>): R { if (columns.size() != 22) throw SQLiteException("Invalid row: 22 columns required") @Suppress("UNCHECKED_CAST") return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16, columns[16] as T17, columns[17] as T18, columns[18] as T19, columns[19] as T20, columns[20] as T21, columns[21] as T22) } } }
apache-2.0
150e9b2acad6261baa91e4850c657bcc
59.070539
446
0.588284
2.664948
false
false
false
false
detunized/UnfuckJs
src/net/detunized/unfuckjs/ConvertBooleanToIf.kt
1
1138
package net.detunized.unfuckjs import com.intellij.lang.javascript.psi.JSBinaryExpression import com.intellij.lang.javascript.psi.JSStatement import com.intellij.lang.javascript.psi.JSExpressionStatement import org.intellij.idea.lang.javascript.psiutil.JSElementFactory abstract class ConvertBooleanToIf(val operator: String): StatementIntentionAction() { override val name = "Convert ${operator} to if" abstract fun getCondition(expression: JSBinaryExpression): String abstract fun getThen(expression: JSBinaryExpression): String override fun invoke(statement: JSStatement) { val e = (statement as JSExpressionStatement).getExpression() as JSBinaryExpression JSElementFactory.replaceStatement( statement, "if (${getCondition(e)}) { ${getThen(e)}; }" ) } override fun isAvailable(statement: JSStatement): Boolean { if (statement is JSExpressionStatement) { val e = statement.getExpression() if (e is JSBinaryExpression && getOperatorText(e) == operator) return true } return false } }
mit
d0c92a35f1a3998d1d9c08c8b8892e12
36.933333
90
0.702109
4.761506
false
false
false
false
BjoernPetersen/JMusicBot
src/main/kotlin/net/bjoernpetersen/musicbot/internal/player/PlayerHistoryImpl.kt
1
1054
package net.bjoernpetersen.musicbot.internal.player import net.bjoernpetersen.musicbot.api.player.PlayState import net.bjoernpetersen.musicbot.api.player.SongEntry import net.bjoernpetersen.musicbot.spi.player.Player import net.bjoernpetersen.musicbot.spi.player.PlayerHistory import java.util.LinkedList import javax.inject.Inject internal class PlayerHistoryImpl @Inject private constructor(player: Player) : PlayerHistory { private val history = LinkedList<SongEntry>() init { player.addListener { _, new -> if (new is PlayState) { val entry = new.entry if (history.lastOrNull() != entry) { if (history.size == MAX_SIZE) history.poll() history.add(entry) } } } } override fun getHistory(limit: Int): List<SongEntry> { return if (history.size > limit) history.subList(history.size - limit, history.size) else history } companion object { const val MAX_SIZE = 40 } }
mit
c05494075ee3cf8b5905c34b9cdf0171
30
94
0.64611
4.466102
false
false
false
false
nemerosa/ontrack
ontrack-extension-github/src/test/java/net/nemerosa/ontrack/extension/github/ingestion/processing/events/PushIngestionEventProcessorTest.kt
1
6076
package net.nemerosa.ontrack.extension.github.ingestion.processing.events import io.mockk.every import io.mockk.mockk import net.nemerosa.ontrack.extension.github.ingestion.IngestionHookFixtures import net.nemerosa.ontrack.extension.github.ingestion.processing.IngestionEventPreprocessingCheck import net.nemerosa.ontrack.extension.github.ingestion.processing.IngestionEventProcessingResult import net.nemerosa.ontrack.extension.github.ingestion.processing.IngestionEventProcessingResultDetails import net.nemerosa.ontrack.extension.github.ingestion.processing.model.Commit import net.nemerosa.ontrack.extension.github.ingestion.processing.push.PushPayload import net.nemerosa.ontrack.extension.github.ingestion.processing.push.PushPayloadListener import net.nemerosa.ontrack.extension.github.ingestion.processing.push.PushPayloadListenerCheck import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import kotlin.test.assertEquals class PushIngestionEventProcessorTest { private lateinit var processor: PushIngestionEventProcessor private val processedPaths = mutableSetOf<String>() @BeforeEach fun before() { processedPaths.clear() val listenerOnPath1 = mockk<PushPayloadListener>() every { listenerOnPath1.preProcessCheck(any()) } answers { val payload: PushPayload = args[0] as PushPayload if (payload.isAddedOrModified("path/1")) { PushPayloadListenerCheck.TO_BE_PROCESSED } else { PushPayloadListenerCheck.IGNORED } } every { listenerOnPath1.process(any(), any()) } answers { processedPaths += "path/1" IngestionEventProcessingResultDetails.processed() } val listenerOnPath2 = mockk<PushPayloadListener>() every { listenerOnPath2.preProcessCheck(any()) } answers { val payload: PushPayload = args[0] as PushPayload if (payload.isAddedOrModified("path/2")) { PushPayloadListenerCheck.TO_BE_PROCESSED } else { PushPayloadListenerCheck.IGNORED } } every { listenerOnPath2.process(any(), any()) } answers { processedPaths += "path/2" IngestionEventProcessingResultDetails.processed() } processor = PushIngestionEventProcessor( structureService = mockk(), pushPayloadListeners = listOf( listenerOnPath1, listenerOnPath2, ) ) } @Test fun `Payload source for a tag`() { val payload = IngestionHookFixtures.samplePushPayload( ref = "refs/tags/1.0.0" ) assertEquals( "1.0.0", processor.getPayloadSource(payload) ) } @Test fun `Payload source for a branch`() { val payload = IngestionHookFixtures.samplePushPayload( ref = "refs/heads/main", id = "1234567", ) assertEquals( "main@1234567", processor.getPayloadSource(payload) ) } @Test fun `Path 1 pushed`() { val payload = payload("path/1") assertEquals( IngestionEventPreprocessingCheck.TO_BE_PROCESSED, processor.preProcessingCheck(payload) ) assertEquals( IngestionEventProcessingResult.PROCESSED, processor.process(payload, null).result ) assertEquals( setOf("path/1"), processedPaths ) } @Test fun `Path 1 and other pushed`() { val payload = payload("path/1", "path/other") assertEquals( IngestionEventPreprocessingCheck.TO_BE_PROCESSED, processor.preProcessingCheck(payload) ) assertEquals( IngestionEventProcessingResult.PROCESSED, processor.process(payload, null).result ) assertEquals( setOf("path/1"), processedPaths ) } @Test fun `Path 2 pushed`() { val payload = payload("path/2") assertEquals( IngestionEventPreprocessingCheck.TO_BE_PROCESSED, processor.preProcessingCheck(payload) ) assertEquals( IngestionEventProcessingResult.PROCESSED, processor.process(payload, null).result ) assertEquals( setOf("path/2"), processedPaths ) } @Test fun `Path 1 and 2 pushed`() { val payload = payload("path/1", "path/2") assertEquals( IngestionEventPreprocessingCheck.TO_BE_PROCESSED, processor.preProcessingCheck(payload) ) assertEquals( IngestionEventProcessingResult.PROCESSED, processor.process(payload, null).result ) assertEquals( setOf("path/1", "path/2"), processedPaths ) } @Test fun `Neither path 1 and 2 pushed`() { val payload = payload("path/other", "other") assertEquals( IngestionEventPreprocessingCheck.IGNORED, processor.preProcessingCheck(payload) ) assertEquals( IngestionEventProcessingResult.IGNORED, processor.process(payload, null).result ) assertEquals( emptySet(), processedPaths ) } private fun payload( vararg paths: String, ) = PushPayload( repository = IngestionHookFixtures.sampleRepository(), ref = "refs/heads/${IngestionHookFixtures.sampleBranch}", commits = listOf( Commit( id = "commit", message = "Commit", author = IngestionHookFixtures.sampleAuthor(), added = paths.toList(), modified = emptyList(), removed = emptyList(), ), ) ) }
mit
d75515477e495cac11fe62fd4898c18a
29.847716
103
0.600395
4.988506
false
true
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/formatter/blocks/SyntheticRsFmtBlock.kt
1
2119
package org.rust.ide.formatter.blocks import com.intellij.formatting.* import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import org.rust.ide.formatter.RsFmtContext import org.rust.ide.formatter.impl.computeSpacing /** * Synthetic formatting block wraps a subsequence of sub blocks * and presents itself as one of the members of this subsequence. */ class SyntheticRsFmtBlock( val representative: ASTBlock? = null, private val subBlocks: List<Block>, private val alignment: Alignment? = null, private val indent: Indent? = null, private val wrap: Wrap? = null, val ctx: RsFmtContext ) : ASTBlock { init { assert(subBlocks.isNotEmpty()) { "tried to build empty synthetic block" } } private val textRange = TextRange( subBlocks.first().textRange.startOffset, subBlocks.last().textRange.endOffset) override fun getTextRange(): TextRange = textRange override fun getNode(): ASTNode? = representative?.node override fun getAlignment(): Alignment? = alignment ?: representative?.alignment override fun getIndent(): Indent? = indent ?: representative?.indent override fun getWrap(): Wrap? = wrap ?: representative?.wrap override fun getSubBlocks(): List<Block> = subBlocks override fun getChildAttributes(newChildIndex: Int): ChildAttributes = ChildAttributes(indent, null) override fun getSpacing(child1: Block?, child2: Block): Spacing? = computeSpacing(child1, child2, ctx) override fun isLeaf(): Boolean = false override fun isIncomplete(): Boolean = subBlocks.last().isIncomplete override fun toString(): String { val text = findFirstNonSyntheticChild()?.psi?.containingFile?.text?.let { textRange.subSequence(it) } ?: "<rust synthetic>" return "$text $textRange" } private fun findFirstNonSyntheticChild(): ASTNode? { val child = subBlocks.first() return when (child) { is SyntheticRsFmtBlock -> child.findFirstNonSyntheticChild() is ASTBlock -> child.node else -> null } } }
mit
d00ed6d647e4d2dccd3a3432d14a105d
34.316667
109
0.696083
4.626638
false
false
false
false
enolive/exercism
kotlin/sieve/src/main/kotlin/Sieve.kt
1
419
object Sieve { private val start = 2 fun primesUpTo(limit: Int): List<Int> = (start..limit).filter { it.isPrime() } private fun Int.isPrime(): Boolean = (start..highestPossiblePrime()) .none { isDivisibleBy(it) } private fun Int.highestPossiblePrime() = Math.sqrt(this.toDouble()).toInt() private fun Int.isDivisibleBy(it: Int) = this % it == 0 }
mit
7060359dedb4e76fbfb198872a8bdead
23.647059
79
0.589499
3.809091
false
false
false
false
DankBots/Mega-Gnar
src/main/kotlin/gg/octave/bot/commands/music/dj/Restart.kt
1
922
package gg.octave.bot.commands.music.dj import gg.octave.bot.commands.music.embedTitle import gg.octave.bot.entities.framework.CheckVoiceState import gg.octave.bot.entities.framework.DJ import gg.octave.bot.entities.framework.MusicCog import gg.octave.bot.utils.extensions.manager import me.devoxin.flight.api.Context import me.devoxin.flight.api.annotations.Command class Restart : MusicCog { override fun sameChannel() = true override fun requirePlayer() = true @DJ @CheckVoiceState @Command(aliases = ["replay"], description = "Restart the current song.") fun restart(ctx: Context) { val manager = ctx.manager val track = manager.player.playingTrack ?: manager.scheduler.lastTrack ?: return ctx.send("No track has been previously started.") ctx.send("Restarting track: `${track.info.embedTitle}`.") manager.player.playTrack(track.makeClone()) } }
mit
0fe86129b48efd55ef8c536cd3ad4a33
33.185185
78
0.73102
3.957082
false
false
false
false
goodwinnk/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/application/impl/AppUIExecutorTest.kt
1
12938
// 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.openapi.application.impl import com.intellij.openapi.Disposable import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState 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.ui.UIUtil import kotlinx.coroutines.experimental.* import kotlinx.coroutines.experimental.channels.Channel import java.util.concurrent.LinkedBlockingQueue import javax.swing.SwingUtilities /** * @author eldar */ class AppUIExecutorTest : LightPlatformTestCase() { override fun runInDispatchThread() = false override fun invokeTestRunnable(runnable: Runnable) { SwingUtilities.invokeLater(runnable) UIUtil.dispatchAllInvocationEvents() } private fun Deferred<Unit>.joinNonBlocking() { var countDown = 300 object : Runnable { override fun run() { if (isCompleted) { getCompleted() } else { if (countDown-- <= 0) fail("Too many EDT reschedules") SwingUtilities.invokeLater(this) } } }.run() } fun `test coroutine onUiThread`() { val executor = AppUIExecutor.onUiThread(ModalityState.any()) async((executor as AppUIExecutorEx).createJobContext()) { 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) async(Unconfined) { queue.add("start") launch((executor as AppUIExecutorEx).createJobContext(coroutineContext)) { 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} because of ${e.cause?.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 because of DisposedException", "end") }.joinNonBlocking() } private fun createDocument(): Document { val file = PsiFileFactory.getInstance(getProject()).createFileFromText("a.txt", PlainTextFileType.INSTANCE, "") return file.viewProvider.document!! } fun `test withDocumentsCommitted`() { val executor = AppUIExecutor.onUiThread(ModalityState.NON_MODAL) .inWriteAction() .withDocumentsCommitted(getProject()) val transactionExecutor = AppUIExecutor.onUiThread(ModalityState.NON_MODAL) .inTransaction(getProject()) .inWriteAction() async(Unconfined) { val pdm = PsiDocumentManager.getInstance(getProject()) val commitChannel = Channel<Unit>() val job = launch((executor as AppUIExecutorEx).createJobContext(coroutineContext)) { commitChannel.receive() assertFalse(pdm.hasUncommitedDocuments()) val document = createDocument() document.insertString(0, "a") assertTrue(pdm.hasUncommitedDocuments()) commitChannel.receive() assertFalse(pdm.hasUncommitedDocuments()) assertEquals("a", document.text) document.insertString(1, "b") assertTrue(pdm.hasUncommitedDocuments()) commitChannel.receive() assertFalse(pdm.hasUncommitedDocuments()) assertEquals("ab", document.text) commitChannel.close() } launch((transactionExecutor as AppUIExecutorEx).createJobContext(coroutineContext, job)) { while (true) { pdm.commitAllDocuments() commitChannel.send(Unit) } }.join() coroutineContext.cancelChildren() }.joinNonBlocking() } fun `test custom simple constraints`() { var scheduled = false val executor = (AppUIExecutor.onUiThread() as AppUIExecutorEx) .withConstraint(object : AsyncExecution.SimpleContextConstraint { override val isCorrectContext: Boolean get() = scheduled override fun schedule(runnable: Runnable) { scheduled = true runnable.run() scheduled = false } override fun toString() = "test" }) async(executor.createJobContext()) { 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() as AppUIExecutorEx) .withConstraint(object : AsyncExecution.ExpirableContextConstraint { override val expirable = disposable override val isCorrectContext: Boolean get() = scheduled override fun scheduleExpirable(runnable: Runnable) { if (Disposer.isDisposed(disposable)) { queue.add("refuse to run already disposed") return } scheduled = true runnable.run() scheduled = false } override fun toString() = "test" }) queue.add("start") async(Unconfined) { launch(executor.createJobContext()) { 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} because of ${e.cause?.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 because of DisposedException", "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 as AppUIExecutorEx) .withConstraint(object : AsyncExecution.ExpirableContextConstraint { override val expirable = disposable override val isCorrectContext: Boolean get() = scheduled override fun scheduleExpirable(runnable: Runnable) { if (Disposer.isDisposed(disposable)) { queue.add("refuse to run already disposed") return } scheduled = true runnable.run() scheduled = false } override fun toString() = "test" }) async(Unconfined) { queue.add("start") val channel = Channel<Unit>() val job = launch(executor.createJobContext(coroutineContext)) { 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} because of ${e.cause?.javaClass?.simpleName}") throw e } queue.add("coroutine end") channel.close() } launch(uiExecutor.createJobContext(coroutineContext, parent = 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", "coroutine start", "before yield", "disposing", "disposable.beforeTreeDispose()", "coroutine yield caught JobCancellationException because of DisposedException", "disposable.dispose()", "end") }.joinNonBlocking() } fun `test custom expirable constraints disposed during dispatching`() { val queue = LinkedBlockingQueue<String>() var scheduled = false var shouldDisposeOnDispatch = 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 as AppUIExecutorEx) .withConstraint(object : AsyncExecution.ExpirableContextConstraint { override val expirable = disposable override val isCorrectContext: Boolean get() = scheduled override fun scheduleExpirable(runnable: Runnable) { if (shouldDisposeOnDispatch) { queue.add("disposing") Disposer.dispose(disposable) } if (Disposer.isDisposed(disposable)) { queue.add("refuse to run already disposed") return } scheduled = true runnable.run() scheduled = false } override fun toString() = "test" }) async(Unconfined) { queue.add("start") val channel = Channel<Unit>() val job = launch(executor.createJobContext(coroutineContext)) { queue.add("coroutine start") assertTrue(scheduled) channel.receive() assertTrue(scheduled) try { shouldDisposeOnDispatch = true queue.add("before receive") channel.receive() queue.add("after receive disposed") yield() queue.add("after yield disposed") } catch (e: Throwable) { queue.add("coroutine yield caught ${e.javaClass.simpleName} because of ${e.cause?.javaClass?.simpleName}") throw e } queue.add("coroutine end") channel.close() } launch(uiExecutor.createJobContext(coroutineContext, parent = job)) { try { while (true) { channel.send(Unit) } } catch (e: Throwable) { throw e } } job.join() queue.add("end") assertOrderedEquals(queue, "start", "coroutine start", "before receive", "disposing", "disposable.beforeTreeDispose()", "disposable.dispose()", "refuse to run already disposed", "after receive disposed", // channel.receive() is atomic "coroutine yield caught JobCancellationException because of DisposedException", "end") }.joinNonBlocking() } }
apache-2.0
4f60fad87f5b557b14e4d53801b464a6
30.329298
140
0.603107
5.225363
false
false
false
false
mockk/mockk
modules/mockk/src/commonMain/kotlin/io/mockk/MockK.kt
1
21124
@file:Suppress("NOTHING_TO_INLINE") package io.mockk import kotlin.reflect.KClass /** * Builds a new mock for specified class. * * A mock is a fake version of a class that replaces all the methods with fake implementations. * * By default, every method that you wish to mock should be stubbed using [every]. * Otherwise, it will throw when called so you know if you forgot to mock a method. * If [relaxed] or [relaxUnitFun] is set to true, methods will automatically be stubbed. * * @param name mock name * @param relaxed allows creation with no specific behaviour. Unstubbed methods will not throw. * @param moreInterfaces additional interfaces for this mockk to implement, in addition to the specified class. * @param relaxUnitFun allows creation with no specific behaviour for Unit function. * Unstubbed methods that return [Unit] will not throw, while other methods will still throw unless they are stubbed. * @param block block to execute after mock is created with mock as a receiver. Similar to using [apply] on the mock object. * * @sample * interface Navigator { * val currentLocation: String * fun navigateTo(newLocation: String): Unit * } * * val navigator = mockk<Navigator>() * every { navigator.currentLocation } returns "Home" * * println(navigator.currentLocation) // prints "Home" * navigator.navigateTo("Store") // throws an error */ inline fun <reified T : Any> mockk( name: String? = null, relaxed: Boolean = false, vararg moreInterfaces: KClass<*>, relaxUnitFun: Boolean = false, block: T.() -> Unit = {} ): T = MockK.useImpl { MockKDsl.internalMockk( name, relaxed, *moreInterfaces, relaxUnitFun = relaxUnitFun, block = block ) } /** * Builds a new spy for specified class. Initializes object via default constructor. * * A spy is a special kind of [mockk] that enables a mix of mocked behaviour and real behaviour. * A part of the behaviour may be mocked using [every], but any non-mocked behaviour will call the original method. * * @param name spyk name * @param moreInterfaces additional interfaces for this spyk to implement, in addition to the specified class. * @param recordPrivateCalls allows this spyk to record any private calls, enabling a verification. * @param block block to execute after spyk is created with spyk as a receiver. Similar to using [apply] on the spyk object. */ inline fun <reified T : Any> spyk( name: String? = null, vararg moreInterfaces: KClass<*>, recordPrivateCalls: Boolean = false, block: T.() -> Unit = {} ): T = MockK.useImpl { MockKDsl.internalSpyk( name, *moreInterfaces, recordPrivateCalls = recordPrivateCalls, block = block ) } /** * Builds a new spy for specified class, copying fields from [objToCopy]. * * A spy is a special kind of [mockk] that enables a mix of mocked behaviour and real behaviour. * A part of the behaviour may be mocked using [every], but any non-mocked behaviour will call the original method. * * @param name spyk name * @param moreInterfaces additional interfaces for this spyk to implement, in addition to the specified class. * @param recordPrivateCalls allows this spyk to record any private calls, enabling a verification. * @param block block to execute after spyk is created with spyk as a receiver. Similar to using [apply] on the spyk object. */ inline fun <reified T : Any> spyk( objToCopy: T, name: String? = null, vararg moreInterfaces: KClass<*>, recordPrivateCalls: Boolean = false, block: T.() -> Unit = {} ): T = MockK.useImpl { MockKDsl.internalSpyk( objToCopy, name, *moreInterfaces, recordPrivateCalls = recordPrivateCalls, block = block ) } /** * Creates new capturing slot. * * Slots allow you to capture what arguments a mocked method is called with. * When mocking a method using [every], pass the slot wrapped with the [MockKMatcherScope.capture] function in place of a method argument or [MockKMatcherScope.any]. * * @sample * interface FileNetwork { * fun download(name: String): File * } * * val network = mockk<FileNetwork>() * val slot = slot<String>() * * every { network.download(capture(slot)) } returns mockk() * * network.download("testfile") * // slot.captured is now "testfile" */ inline fun <reified T : Any> slot() = MockK.useImpl { MockKDsl.internalSlot<T>() } /** * Starts a block of stubbing. Part of DSL. * * Used to define what behaviour is going to be mocked. * * @sample * interface Navigator { * val currentLocation: String * } * * val navigator = mockk<Navigator>() * every { navigator.currentLocation } returns "Home" * * println(navigator.currentLocation) // prints "Home" * @see [coEvery] Coroutine version. */ fun <T> every(stubBlock: MockKMatcherScope.() -> T): MockKStubScope<T, T> = MockK.useImpl { MockKDsl.internalEvery(stubBlock) } /** * Stub block to return Unit result. Part of DSL. * * Used to define what behaviour is going to be mocked. * Acts as a shortcut for `every { ... } returns Unit`. * * @see [every] * @see [coJustRun] Coroutine version. * @sample * every { logger.log(any()) } returns Unit * every { logger.log(any()) } just Runs * justRun { logger.log(any()) } */ fun justRun(stubBlock: MockKMatcherScope.() -> Unit) = every(stubBlock) just Runs /** * Starts a block of stubbing for coroutines. Part of DSL. * Similar to [every], but works with suspend functions. * * Used to define what behaviour is going to be mocked. * @see [every] */ fun <T> coEvery(stubBlock: suspend MockKMatcherScope.() -> T): MockKStubScope<T, T> = MockK.useImpl { MockKDsl.internalCoEvery(stubBlock) } /** * Stub block to return Unit result as a coroutine block. Part of DSL. * Similar to [justRun], but works with suspend functions. * * Used to define what behaviour is going to be mocked. * Acts as a shortcut for `coEvery { ... } returns Unit`. * @see [justRun] */ fun coJustRun(stubBlock: suspend MockKMatcherScope.() -> Unit) = coEvery(stubBlock) just Runs /** * Stub block to never return. Part of DSL. * * Used to define what behaviour is going to be mocked. * @see [coJustRun] */ fun coJustAwait(stubBlock: suspend MockKMatcherScope.() -> Unit) = coEvery(stubBlock) just Awaits /** * Verifies that calls were made in the past. Part of DSL. * * @param ordering how the verification should be ordered * @param inverse when true, the verification will check that the behaviour specified did **not** happen * @param atLeast verifies that the behaviour happened at least [atLeast] times * @param atMost verifies that the behaviour happened at most [atMost] times * @param exactly verifies that the behaviour happened exactly [exactly] times. Use -1 to disable * @param timeout timeout value in milliseconds. Will wait until one of two following states: either verification is * passed or timeout is reached. * @param verifyBlock code block containing at least 1 call to verify * * @sample * val navigator = mockk<Navigator>(relaxed = true) * * navigator.navigateTo("Park") * verify { navigator.navigateTo(any()) } * @see [coVerify] Coroutine version */ fun verify( ordering: Ordering = Ordering.UNORDERED, inverse: Boolean = false, atLeast: Int = 1, atMost: Int = Int.MAX_VALUE, exactly: Int = -1, timeout: Long = 0, verifyBlock: MockKVerificationScope.() -> Unit ) = MockK.useImpl { MockKDsl.internalVerify(ordering, inverse, atLeast, atMost, exactly, timeout, verifyBlock) } /** * Verifies that calls were made inside a coroutine. * * @param ordering how the verification should be ordered * @param inverse when true, the verification will check that the behaviour specified did **not** happen * @param atLeast verifies that the behaviour happened at least [atLeast] times * @param atMost verifies that the behaviour happened at most [atMost] times * @param exactly verifies that the behaviour happened exactly [exactly] times. Use -1 to disable * @param timeout timeout value in milliseconds. Will wait until one of two following states: either verification is * passed or timeout is reached. * @param verifyBlock code block containing at least 1 call to verify * * @see [verify] */ fun coVerify( ordering: Ordering = Ordering.UNORDERED, inverse: Boolean = false, atLeast: Int = 1, atMost: Int = Int.MAX_VALUE, exactly: Int = -1, timeout: Long = 0, verifyBlock: suspend MockKVerificationScope.() -> Unit ) = MockK.useImpl { MockKDsl.internalCoVerify( ordering, inverse, atLeast, atMost, exactly, timeout, verifyBlock ) } /** * Verifies that all calls inside [verifyBlock] happened. **Does not** verify any order. * * If ordering is important, use [verifyOrder]. * * @see coVerifyAll Coroutine version * @see verify * @see verifyOrder * @see verifySequence * * @param inverse when true, the verification will check that the behaviour specified did **not** happen */ fun verifyAll( inverse: Boolean = false, verifyBlock: MockKVerificationScope.() -> Unit ) = MockK.useImpl { MockKDsl.internalVerifyAll(inverse, verifyBlock) } /** * Verifies that all calls inside [verifyBlock] happened, checking that they happened in the order declared. * * @see coVerifyOrder Coroutine version * @see verify * @see verifyAll * @see verifySequence * * @param inverse when true, the verification will check that the behaviour specified did **not** happen */ fun verifyOrder( inverse: Boolean = false, verifyBlock: MockKVerificationScope.() -> Unit ) = MockK.useImpl { MockKDsl.internalVerifyOrder(inverse, verifyBlock) } /** * Verifies that all calls inside [verifyBlock] happened, and no other call was made to those mocks * * @see coVerifySequence Coroutine version * @see verify * @see verifyOrder * @see verifyAll * * @param inverse when true, the verification will check that the behaviour specified did **not** happen */ fun verifySequence( inverse: Boolean = false, verifyBlock: MockKVerificationScope.() -> Unit ) = MockK.useImpl { MockKDsl.internalVerifySequence(inverse, verifyBlock) } /** * Verifies that all calls inside [verifyBlock] happened. **Does not** verify any order. Coroutine version * * If ordering is important, use [coVerifyOrder] * * @see verifyAll * @see coVerify * @see coVerifyOrder * @see coVerifySequence * * @param inverse when true, the verification will check that the behaviour specified did **not** happen */ fun coVerifyAll( inverse: Boolean = false, verifyBlock: suspend MockKVerificationScope.() -> Unit ) = MockK.useImpl { MockKDsl.internalCoVerifyAll(inverse, verifyBlock) } /** * Verifies that all calls inside [verifyBlock] happened, checking that they happened in the order declared. * Coroutine version. * * @see verifyOrder * @see coVerify * @see coVerifyAll * @see coVerifySequence * * @param inverse when true, the verification will check that the behaviour specified did **not** happen */ fun coVerifyOrder( inverse: Boolean = false, verifyBlock: suspend MockKVerificationScope.() -> Unit ) = MockK.useImpl { MockKDsl.internalCoVerifyOrder(inverse, verifyBlock) } /** * Verifies that all calls inside [verifyBlock] happened, and no other call was made to those mocks. * Coroutine version. * * @see verifySequence * @see coVerify * @see coVerifyOrder * @see coVerifyAll * * @param inverse when true, the verification will check that the behaviour specified did **not** happen */ fun coVerifySequence( inverse: Boolean = false, verifyBlock: suspend MockKVerificationScope.() -> Unit ) = MockK.useImpl { MockKDsl.internalCoVerifySequence(inverse, verifyBlock) } /** * Exclude calls from recording * * @param current if current recorded calls should be filtered out * @see [coExcludeRecords] Coroutine version. */ fun excludeRecords( current: Boolean = true, excludeBlock: MockKMatcherScope.() -> Unit ) = MockK.useImpl { MockKDsl.internalExcludeRecords(current, excludeBlock) } /** * Exclude calls from recording for a suspend block * * @param current if current recorded calls should be filtered out * @see [excludeRecords] */ fun coExcludeRecords( current: Boolean = true, excludeBlock: suspend MockKMatcherScope.() -> Unit ) = MockK.useImpl { MockKDsl.internalCoExcludeRecords(current, excludeBlock) } /** * Checks if all recorded calls were verified. */ fun confirmVerified(vararg mocks: Any) = MockK.useImpl { MockKDsl.internalConfirmVerified(*mocks) } /** * Checks if all recorded calls are necessary. */ fun checkUnnecessaryStub(vararg mocks: Any) = MockK.useImpl { MockKDsl.internalCheckUnnecessaryStub(*mocks) } /** * Resets information associated with specified mocks. * To clear all mocks use clearAllMocks. */ fun clearMocks( firstMock: Any, vararg mocks: Any, answers: Boolean = true, recordedCalls: Boolean = true, childMocks: Boolean = true, verificationMarks: Boolean = true, exclusionRules: Boolean = true ) = MockK.useImpl { MockKDsl.internalClearMocks( firstMock = firstMock, mocks = mocks, answers = answers, recordedCalls = recordedCalls, childMocks = childMocks, verificationMarks = verificationMarks, exclusionRules = exclusionRules ) } /** * Registers instance factory and returns object able to do deregistration. */ inline fun <reified T : Any> registerInstanceFactory(noinline instanceFactory: () -> T): Deregisterable = MockK.useImpl { MockKDsl.internalRegisterInstanceFactory(instanceFactory) } /** * Executes block of code with registering and unregistering instance factory. */ inline fun <reified T : Any, R> withInstanceFactory(noinline instanceFactory: () -> T, block: () -> R): R = MockK.useImpl { MockKDsl.internalWithInstanceFactory(instanceFactory, block) } /** * Builds a mock for an arbitrary class */ inline fun <T : Any> mockkClass( type: KClass<T>, name: String? = null, relaxed: Boolean = false, vararg moreInterfaces: KClass<*>, relaxUnitFun: Boolean = false, block: T.() -> Unit = {} ): T = MockK.useImpl { MockKDsl.internalMockkClass( type, name, relaxed, *moreInterfaces, relaxUnitFun = relaxUnitFun, block = block ) } /** * Builds an Object mock. Any mocks of this exact object are cancelled before it's mocked. * * This lets you mock object methods with [every]. * * @sample * object CalculatorObject { * fun add(a: Int, b: Int) = a + b * } * * mockkObject(CalculatorObject) * every { ObjBeingMocked.add(1, 2) } returns 55 * * @see [unmockkObject] To manually cancel mock */ inline fun mockkObject(vararg objects: Any, recordPrivateCalls: Boolean = false) = MockK.useImpl { MockKDsl.internalMockkObject(*objects, recordPrivateCalls = recordPrivateCalls) } /** * Cancel object mocks. */ inline fun unmockkObject(vararg objects: Any) = MockK.useImpl { MockKDsl.internalUnmockkObject(*objects) } /** * Builds a static mock and unmocks it after the block has been executed. */ inline fun mockkObject(vararg objects: Any, recordPrivateCalls: Boolean = false, block: () -> Unit) { mockkObject(*objects, recordPrivateCalls = recordPrivateCalls) try { block() } finally { unmockkObject(*objects) } } /** * Builds a static mock. Any mocks of this exact class are cancelled before it's mocked * * @see [unmockkStatic] To manually cancel mock */ inline fun mockkStatic(vararg classes: KClass<*>) = MockK.useImpl { MockKDsl.internalMockkStatic(*classes) } /** * Builds a static mock. Old static mocks of same classes are cancelled before. * * @see [unmockkStatic] To manually cancel mock */ inline fun mockkStatic(vararg classes: String) = MockK.useImpl { MockKDsl.internalMockkStatic(*classes.map { InternalPlatformDsl.classForName(it) as KClass<*> }.toTypedArray()) } /** * Cancel static mocks. */ inline fun clearStaticMockk( vararg classes: KClass<*>, answers: Boolean = true, recordedCalls: Boolean = true, childMocks: Boolean = true ) = MockK.useImpl { MockKDsl.internalClearStaticMockk( *classes, answers = answers, recordedCalls = recordedCalls, childMocks = childMocks ) } /** * Cancel static mocks. */ inline fun unmockkStatic(vararg classes: KClass<*>) = MockK.useImpl { MockKDsl.internalUnmockkStatic(*classes) } /** * Cancel static mocks. */ inline fun unmockkStatic(vararg classes: String) = MockK.useImpl { MockKDsl.internalUnmockkStatic(*classes.map { InternalPlatformDsl.classForName(it) as KClass<*> }.toTypedArray()) } /** * Builds a static mock and unmocks it after the block has been executed. */ inline fun mockkStatic(vararg classes: KClass<*>, block: () -> Unit) { mockkStatic(*classes) try { block() } finally { unmockkStatic(*classes) } } /** * Builds a static mock and unmocks it after the block has been executed. */ inline fun mockkStatic(vararg classes: String, block: () -> Unit) { mockkStatic(*classes) try { block() } finally { unmockkStatic(*classes) } } /** * Builds a constructor mock. Old constructor mocks of same classes are cancelled before. * * Once used, every constructor of the given class will start returning a singleton that can be mocked. * Rather than building a new instance every time the constructor is called, * MockK generates a singleton and always returns the same instance. * This will apply to all constructors for a given class, there is no way to distinguish between them. * * @see [unmockkConstructor] To manually cancel mock * @sample * class ClassToTest { * private val log = Logger() * } * * mockkConstructor(Logger::class) * // ClassToTest.log will now use a mock instance */ inline fun mockkConstructor( vararg classes: KClass<*>, recordPrivateCalls: Boolean = false, localToThread: Boolean = false ) = MockK.useImpl { MockKDsl.internalMockkConstructor( *classes, recordPrivateCalls = recordPrivateCalls, localToThread = localToThread ) } /** * Cancel constructor mocks. */ inline fun unmockkConstructor(vararg classes: KClass<*>) = MockK.useImpl { MockKDsl.internalUnmockkConstructor(*classes) } /** * Builds a constructor mock and unmocks it after the block has been executed. */ inline fun mockkConstructor( vararg classes: KClass<*>, recordPrivateCalls: Boolean = false, localToThread: Boolean = false, block: () -> Unit ) { mockkConstructor(*classes, recordPrivateCalls = recordPrivateCalls, localToThread = localToThread) try { block() } finally { unmockkConstructor(*classes) } } /** * Clears constructor mock. */ inline fun clearConstructorMockk( vararg classes: KClass<*>, answers: Boolean = true, recordedCalls: Boolean = true, childMocks: Boolean = true ) = MockK.useImpl { MockKDsl.internalClearConstructorMockk( *classes, answers = answers, recordedCalls = recordedCalls, childMocks = childMocks ) } /** * Cancels object, static and constructor mocks. */ inline fun unmockkAll() = MockK.useImpl { MockKDsl.internalUnmockkAll() } /** * Clears all regular, object, static and constructor mocks. */ inline fun clearAllMocks( answers: Boolean = true, recordedCalls: Boolean = true, childMocks: Boolean = true, regularMocks: Boolean = true, objectMocks: Boolean = true, staticMocks: Boolean = true, constructorMocks: Boolean = true ) = MockK.useImpl { MockKDsl.internalClearAllMocks( answers, recordedCalls, childMocks, regularMocks, objectMocks, staticMocks, constructorMocks ) } /** * Checks if provided mock is mock of certain type */ fun isMockKMock( mock: Any, regular: Boolean = true, spy: Boolean = false, objectMock: Boolean = false, staticMock: Boolean = false, constructorMock: Boolean = false ) = MockK.useImpl { MockKDsl.internalIsMockKMock( mock, regular, spy, objectMock, staticMock, constructorMock ) } object MockKAnnotations { /** * Initializes properties annotated with @MockK, @RelaxedMockK, @Slot and @SpyK in provided object. */ inline fun init( vararg obj: Any, overrideRecordPrivateCalls: Boolean = false, relaxUnitFun: Boolean = false, relaxed: Boolean = false ) = MockK.useImpl { MockKDsl.internalInitAnnotatedMocks( obj.toList(), overrideRecordPrivateCalls, relaxUnitFun, relaxed ) } } expect object MockK { inline fun <T> useImpl(block: () -> T): T }
apache-2.0
25836fa1854529475a90a9dd261fca34
28.338889
165
0.690589
4.124976
false
false
false
false
samtstern/quickstart-android
mlkit/app/src/main/java/com/google/firebase/samples/apps/mlkit/kotlin/cloudtextrecognition/CloudTextRecognitionProcessor.kt
1
2084
package com.google.firebase.samples.apps.mlkit.kotlin.cloudtextrecognition import android.graphics.Bitmap import android.util.Log import com.google.android.gms.tasks.Task import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.common.FirebaseVisionImage import com.google.firebase.ml.vision.text.FirebaseVisionText import com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer import com.google.firebase.samples.apps.mlkit.common.FrameMetadata import com.google.firebase.samples.apps.mlkit.common.GraphicOverlay import com.google.firebase.samples.apps.mlkit.kotlin.VisionProcessorBase /** * Processor for the cloud text detector demo. */ class CloudTextRecognitionProcessor : VisionProcessorBase<FirebaseVisionText>() { private val detector: FirebaseVisionTextRecognizer = FirebaseVision.getInstance().cloudTextRecognizer override fun detectInImage(image: FirebaseVisionImage): Task<FirebaseVisionText> { return detector.processImage(image) } override fun onSuccess( originalCameraImage: Bitmap?, results: FirebaseVisionText, frameMetadata: FrameMetadata, graphicOverlay: GraphicOverlay ) { graphicOverlay.clear() if (results == null) { return // TODO: investigate why this is needed } val blocks = results.textBlocks for (i in blocks.indices) { val lines = blocks[i].lines for (j in lines.indices) { val elements = lines[j].elements for (l in elements.indices) { val cloudTextGraphic = CloudTextGraphic( graphicOverlay, elements[l] ) graphicOverlay.add(cloudTextGraphic) graphicOverlay.postInvalidate() } } } } override fun onFailure(e: Exception) { Log.w(TAG, "Cloud Text detection failed.$e") } companion object { private const val TAG = "CloudTextRecProc" } }
apache-2.0
97b7365833901872d12f47decec92d60
33.733333
105
0.668906
4.903529
false
false
false
false
android/health-samples
health-connect/HealthConnectSample/app/src/main/java/com/example/healthconnectsample/presentation/screen/exercisesessiondetail/ExerciseSessionDetailScreen.kt
1
9329
/* * 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.healthconnectsample.presentation.screen.exercisesessiondetail import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.health.connect.client.permission.HealthPermission import androidx.health.connect.client.records.ExerciseSessionRecord import androidx.health.connect.client.records.HeartRateRecord import androidx.health.connect.client.records.SpeedRecord import androidx.health.connect.client.units.Energy import androidx.health.connect.client.units.Length import androidx.health.connect.client.units.Velocity import com.example.healthconnectsample.R import com.example.healthconnectsample.data.ExerciseSessionData import com.example.healthconnectsample.data.formatTime import com.example.healthconnectsample.presentation.component.ExerciseSessionDetailsMinMaxAvg import com.example.healthconnectsample.presentation.component.heartRateSeries import com.example.healthconnectsample.presentation.component.sessionDetailsItem import com.example.healthconnectsample.presentation.component.speedSeries import com.example.healthconnectsample.presentation.theme.HealthConnectTheme import java.time.Duration import java.time.ZonedDateTime import java.util.UUID import kotlin.random.Random /** * Shows a details of a given [ExerciseSessionRecord], including aggregates and underlying raw data. */ @Composable fun ExerciseSessionDetailScreen( permissions: Set<HealthPermission>, permissionsGranted: Boolean, sessionMetrics: ExerciseSessionData, uiState: ExerciseSessionDetailViewModel.UiState, onError: (Throwable?) -> Unit = {}, onPermissionsResult: () -> Unit = {}, onPermissionsLaunch: (Set<HealthPermission>) -> Unit = {} ) { // Remember the last error ID, such that it is possible to avoid re-launching the error // notification for the same error when the screen is recomposed, or configuration changes etc. val errorId = rememberSaveable { mutableStateOf(UUID.randomUUID()) } LaunchedEffect(uiState) { // If the initial data load has not taken place, attempt to load the data. if (uiState is ExerciseSessionDetailViewModel.UiState.Uninitialized) { onPermissionsResult() } // The [ExerciseSessionDetailViewModel.UiState] provides details of whether the last action // was a success or resulted in an error. Where an error occurred, for example in reading // and writing to Health Connect, the user is notified, and where the error is one that can // be recovered from, an attempt to do so is made. if (uiState is ExerciseSessionDetailViewModel.UiState.Error && errorId.value != uiState.uuid ) { onError(uiState.exception) errorId.value = uiState.uuid } } if (uiState != ExerciseSessionDetailViewModel.UiState.Uninitialized) { LazyColumn( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally ) { if (!permissionsGranted) { item { Button( onClick = { onPermissionsLaunch(permissions) } ) { Text(text = stringResource(R.string.permissions_button_label)) } } } else { sessionDetailsItem(labelId = R.string.total_active_duration) { val activeDuration = sessionMetrics.totalActiveTime ?: Duration.ZERO Text(activeDuration.formatTime()) } sessionDetailsItem(labelId = R.string.total_steps) { Text(sessionMetrics.totalSteps?.toString() ?: "0") } sessionDetailsItem(labelId = R.string.total_distance) { Text(sessionMetrics.totalDistance?.toString() ?: "0.0") } sessionDetailsItem(labelId = R.string.total_energy) { Text(sessionMetrics.totalEnergyBurned?.inCalories.toString()) } sessionDetailsItem(labelId = R.string.speed_stats) { ExerciseSessionDetailsMinMaxAvg( sessionMetrics.minSpeed?.inMetersPerSecond.let { String.format( "%.1f", it ) }, sessionMetrics.maxSpeed?.inMetersPerSecond.let { String.format( "%.1f", it ) }, sessionMetrics.avgSpeed?.inMetersPerSecond.let { String.format("%.1f", it) } ) } speedSeries( labelId = R.string.speed_series, series = sessionMetrics.speedRecord ) sessionDetailsItem(labelId = R.string.hr_stats) { ExerciseSessionDetailsMinMaxAvg( sessionMetrics.minHeartRate?.toString() ?: stringResource(id = R.string.not_available_abbrev), sessionMetrics.maxHeartRate?.toString() ?: stringResource(id = R.string.not_available_abbrev), sessionMetrics.avgHeartRate?.toString() ?: stringResource(id = R.string.not_available_abbrev) ) } heartRateSeries( labelId = R.string.hr_series, series = sessionMetrics.heartRateSeries ) } } } } @Preview @Composable fun ExerciseSessionScreenPreview() { HealthConnectTheme { val uid = UUID.randomUUID().toString() val sessionMetrics = ExerciseSessionData( uid = uid, totalSteps = 5152, totalDistance = Length.meters(11923.4), totalEnergyBurned = Energy.calories(1131.2), minHeartRate = 55, maxHeartRate = 103, avgHeartRate = 77, heartRateSeries = generateHeartRateSeries(), minSpeed = Velocity.metersPerSecond(2.5), maxSpeed = Velocity.metersPerSecond(3.1), avgSpeed = Velocity.metersPerSecond(2.8), speedRecord = generateSpeedData(), ) ExerciseSessionDetailScreen( permissions = setOf(), permissionsGranted = true, sessionMetrics = sessionMetrics, uiState = ExerciseSessionDetailViewModel.UiState.Done ) } } private fun generateSpeedData(): List<SpeedRecord> { val data = mutableListOf<SpeedRecord.Sample>() val end = ZonedDateTime.now() var time = ZonedDateTime.now() for (index in 1..10) { time = end.minusMinutes(index.toLong()) data.add( SpeedRecord.Sample( time = time.toInstant(), speed = Velocity.metersPerSecond((Random.nextDouble(1.0, 5.0))) ) ) } return listOf( SpeedRecord( startTime = time.toInstant(), startZoneOffset = time.offset, endTime = end.toInstant(), endZoneOffset = end.offset, samples = data ) ) } private fun generateHeartRateSeries(): List<HeartRateRecord> { val data = mutableListOf<HeartRateRecord.Sample>() val end = ZonedDateTime.now() var time = ZonedDateTime.now() for (index in 1..10) { time = end.minusMinutes(index.toLong()) data.add( HeartRateRecord.Sample( time = time.toInstant(), beatsPerMinute = Random.nextLong(55, 180) ) ) } return listOf( HeartRateRecord( startTime = time.toInstant(), startZoneOffset = time.offset, endTime = end.toInstant(), endZoneOffset = end.offset, samples = data ) ) }
apache-2.0
82cb37861da76d850893284cd2f8a497
39.56087
100
0.621503
5.154144
false
false
false
false
Endran/KotlinExample
Sources/SpekExample/app/src/test/java/nl/endran/spekexample/JavaKitchenTest.kt
1
3725
package nl.endran.spekexample import org.assertj.core.api.Assertions import org.jetbrains.spek.api.Spek class JavaKitchenTest : Spek() { val bacon = "Bacon" val chicken = "Chicken" val fish = "Fish" init { given("a JavaKitchen without chefs") { val javaKitchen = JavaKitchen(emptyList()) on("asking the list of available dishes") { val availableDishes = javaKitchen.availableDishes it("should return an empty list") { Assertions.assertThat(availableDishes).isEmpty() } } } val baconSpeciality = listOf(bacon) given("a JavaKitchen with 2 chefs that both have $baconSpeciality as a speciality") { val javaKitchen = JavaKitchen(listOf( Chef(baconSpeciality), Chef(baconSpeciality))) on("asking the list of available dishes") { val availableDishes = javaKitchen.availableDishes it("should contain $bacon") { Assertions.assertThat(availableDishes).contains(bacon) } } on("requesting the preparation time for $bacon") { val preparationTime = javaKitchen.calculatePreparationTime(bacon) it("should take ${JavaKitchen.NORMAL_PREPARATION_TIME} minutes") { Assertions.assertThat(preparationTime).isEqualTo(JavaKitchen.NORMAL_PREPARATION_TIME) } } } val baconAndChickenSpeciality = listOf(bacon, chicken) val baconFishAndChickenSpeciality = listOf(bacon, fish, chicken) given("a JavaKitchen with a chef with $baconAndChickenSpeciality, a chef with $baconSpeciality and a chef with $baconFishAndChickenSpeciality") { val javaKitchen = JavaKitchen(listOf( Chef(baconAndChickenSpeciality), Chef(baconSpeciality), Chef(baconFishAndChickenSpeciality))) on("asking the list of available dishes") { val availableDishes = javaKitchen.availableDishes it("should return not return empty list") { Assertions.assertThat(availableDishes).isNotEmpty() } it("should resemble $baconAndChickenSpeciality") { Assertions.assertThat(availableDishes).containsAll(baconAndChickenSpeciality) } } on("requesting the preparation time for $bacon") { val preparationTime = javaKitchen.calculatePreparationTime(bacon) it("should take ${JavaKitchen.FAST_PREPARATION_TIME} minutes") { Assertions.assertThat(preparationTime).isEqualTo(JavaKitchen.FAST_PREPARATION_TIME) } } on("requesting the preparation time for $chicken") { val preparationTime = javaKitchen.calculatePreparationTime(chicken) it("should take ${JavaKitchen.NORMAL_PREPARATION_TIME} minutes") { Assertions.assertThat(preparationTime).isEqualTo(JavaKitchen.NORMAL_PREPARATION_TIME) } } on("requesting the preparation time for $fish") { var exception: RuntimeException? = null try { javaKitchen.calculatePreparationTime(fish) } catch (e: RuntimeException) { exception = e } it("should have thrown an exception") { Assertions.assertThat(exception).isNotNull() } } } } }
apache-2.0
ef9190d17d9dbab6c1b0005f7f6f1ec8
37.010204
153
0.576644
4.445107
false
false
false
false
ice1000/OI-codes
codewars/authoring/kotlin/AISO.kt
1
8086
import java.util.* import java.util.stream.Collectors import java.util.stream.Stream /* * so, when are two type, `a` and `b`, considered equal? * a definition might be, it is possible to go from `a` to `b`, * and from `b` to `a`. * Going a roundway trip should leave you the same value. * Unfortunately it is virtually impossible to test this in Haskell. * This is called ISO. * <p> * ISO can also be simulated in Java. * <p> * Created by ice1000 on 17-6-19. */ abstract class ISO<A, B> { /** go backward */ abstract fun bw(b: B): A /** go forward */ abstract fun fw(a: A): B } abstract class Either<out L, out R> { abstract fun <T> pm(lt: (L) -> T, rt: (R) -> T): T } fun <L, R> left(l: L): Either<L, R> = object : Either<L, R>() { override fun <T> pm(lt: (L) -> T, rt: (R) -> T): T = lt(l) override fun equals(other: Any?) = (other as Either<*, *>).pm({ l == it }, { false }) override fun toString() = "left: $l" } fun <L, R> right(r: R): Either<L, R> = object : Either<L, R>() { override fun <T> pm(lt: (L) -> T, rt: (R) -> T): T = rt(r) override fun equals(other: Any?) = (other as Either<*, *>).pm({ false }, { r == it }) override fun toString() = "right: $r" } private fun <T> Nothing.absurd(): T = this private inline fun <A, B> iso(crossinline forward: (A) -> B, crossinline backward: (B) -> A): ISO<A, B> = object : ISO<A, B>() { override fun bw(b: B): A = backward(b) override fun fw(a: A): B = forward(a) } /* given ISO a b, we can go from a to b */ fun <A, B> subStL(iso: ISO<A, B>): (A) -> B = iso::fw /* and vise versa */ fun <A, B> subStR(iso: ISO<A, B>): (B) -> A = iso::bw /* There can be more than one ISO a b */ fun isoBool(): ISO<Boolean, Boolean> = refl() fun isoBoolNot(): ISO<Boolean, Boolean> = iso(Boolean::not, Boolean::not) /* isomorphism is reflexive */ fun <A> refl(): ISO<A, A> = iso({ it }, { it }) /* isomorphism is symmetric */ fun <A, B> symm(iso: ISO<B, A>): ISO<A, B> = iso(iso::bw, iso::fw) /* isomorphism is transitive */ fun <A, B, C> trans(ab: ISO<A, B>, bc: ISO<B, C>): ISO<A, C> = iso({ bc.fw(ab.fw(it)) }, { ab.bw(bc.bw(it)) }) /* We can combine isomorphism */ fun <A, B, C, D> isoPair(ab: ISO<A, B>, cd: ISO<C, D>): ISO<Pair<A, C>, Pair<B, D>> = iso({ (a, c) -> ab.fw(a) to cd.fw(c) }, { (b, d) -> ab.bw(b) to cd.bw(d) }) fun <A, B> isoStream(iso: ISO<A, B>): ISO<Stream<A>, Stream<B>> = iso({ it.map(iso::fw) }, { it.map(iso::bw) }) fun <A, B> isoOptional(iso: ISO<A, B>): ISO<Optional<A>, Optional<B>> = iso({ it.map(iso::fw) }, { it.map(iso::bw) }) fun <A, B, C, D> isoEither(ab: ISO<A, B>, cd: ISO<C, D>): ISO<Either<A, C>, Either<B, D>> = iso({ it.pm({ left(ab.fw(it)) }, { right(cd.fw(it)) }) }, { it.pm({ left(ab.bw(it)) }, { right(cd.bw(it)) }) }) /* * Going another way is hard (and is generally impossible) * Remember, for all valid ISO, converting and converting back * is the same as the original value. * You need this to prove some case are impossible. */ fun <A, B> isoUnOptional(iso: ISO<Optional<A>, Optional<B>>): ISO<A, B> = iso({ iso.fw(Optional.of(it)).orElseGet { iso.fw(Optional.empty()).get() } }, { iso.bw(Optional.of(it)).orElseGet { iso.bw(Optional.empty()).get() } }) // We cannot have // isoUnEither :: // ISO (Either a b) (Either c d) -> ISO a c -> ISO b d. // Note that we have fun isoEU(): ISO<Either<Stream<Unit>, Unit>, Either<Stream<Unit>, Nothing>> = iso({ it.pm({ left(Stream.concat(Stream.of(Unit), it)) }, { left(Stream.empty()) }) }, { it.pm({ it.collect(Collectors.toList()).let { if (it.isEmpty()) right(Unit) else left(Stream.generate { Unit }.limit(it.size - 1L)) } }, { it.absurd() }) }) // where (), the empty Pair, has 1 value, and Void has 0 value // If we have isoUnEither, // We have ISO () Void by calling isoUnEither isoEU // That is impossible, since we can get a Void by // substL on ISO () Void // So it is impossible to have isoUnEither fun <A, B, C, D> isoFunc(ab: ISO<A, B>, cd: ISO<C, D>): ISO<(A) -> C, (B) -> D> = iso({ ac -> { cd.fw(ac(ab.bw(it))) } }, { bd -> { cd.bw(bd(ab.fw(it))) } }) /* And we have isomorphism on isomorphism! */ fun <A, B> isoSymm(): ISO<ISO<A, B>, ISO<B, A>> = iso(::symm, ::symm) // ------------------------------- /** a = b -> c = d -> a * c = b * d */ fun <A, B, C, D> isoProd(ab: ISO<A, B>, cd: ISO<C, D>): ISO<Pair<A, C>, Pair<B, D>> = isoPair(ab, cd) /** a = b -> c = d -> a + c = b + d */ fun <A, B, C, D> isoPlus(ab: ISO<A, B>, cd: ISO<C, D>): ISO<Either<A, C>, Either<B, D>> = isoEither(ab, cd) /** a = b -> S a = S b */ fun <A, B> isoS(iso: ISO<A, B>): ISO<Optional<A>, Optional<B>> = isoOptional(iso) /** a = b -> c = d -> c ^ a = d ^ b */ fun <A, B, C, D> isoPow(ab: ISO<A, B>, cd: ISO<C, D>): ISO<(A) -> C, (B) -> D> = isoFunc(ab, cd) /** a + b = b + a */ fun <A, B> plusComm(): ISO<Either<A, B>, Either<B, A>> = iso({ it.pm({ right(it) }, { left(it) }) }, { it.pm({ right(it) }, { left(it) }) }) /** a + b + c = a + (b + c) */ fun <A, B, C> plusAssoc(): ISO<Either<Either<A, B>, C>, Either<A, Either<B, C>>> = iso({ abc -> abc.pm({ ab -> ab.pm(::left, { b -> right(left(b)) }) }) { c -> right(right(c)) } }, { abc -> abc.pm({ a -> left(left(a)) }) { bc -> bc.pm({ b -> left(right(b)) }, ::right) } }) /** a * b = b * a */ fun <A, B> multComm(): ISO<Pair<A, B>, Pair<B, A>> = iso({ (a, b) -> b to a }, { (b, a) -> a to b }) /** a * b * c = a * (b * c) */ fun <A, B, C> multAssoc(): ISO<Pair<Pair<A, B>, C>, Pair<A, Pair<B, C>>> = iso({ (pair, c) -> Pair(pair.first, pair.second to c) }, { (a, pair) -> Pair(a to pair.first, pair.second) }) /** a * (b + c) = a * b + a * c */ fun <A, B, C> dist(): ISO<Pair<A, Either<B, C>>, Either<Pair<A, B>, Pair<A, C>>> = iso({ (a, e) -> e.pm({ b -> left(a to b) }, { c -> right(a to c) }) }, { e -> e.pm({ (a, b) -> a to left(b) }, { (a, c) -> a to right(c) }) }) /** (c ^ b) ^ a = c ^ (a * b) */ fun <A, B, C> curryISO(): ISO<(A) -> (B) -> C, (Pair<A, B>) -> C> = iso({ a -> { (a, b) -> a(a)(b) } }) { ab -> { a -> { b -> ab(a to b) } } } /** * 1 = S O (we are using peano arithmetic) * https://en.wikipedia.org/wiki/Peano_axioms */ fun one(): ISO<Unit, Optional<Nothing>> = iso({ Optional.empty() }, { Unit }) /** 2 = S (S O) */ fun two(): ISO<Boolean, Optional<Optional<Void>>> = iso({ b -> if (b) Optional.of(Optional.empty()) else Optional.empty() }, { it.isPresent }) /** 0 + b = b */ fun <B> plusO(): ISO<Either<Nothing, B>, B> = iso({ a -> a.pm({ it.absurd() }, { b -> b }) }, ::right) /* S a + b = S (a + b) */ fun <A, B> plusS(): ISO<Either<Optional<A>, B>, Optional<Either<A, B>>> = iso({ oab -> oab.pm({ oa -> oa.map { a -> Optional.of(left<A, B>(a)) }.orElseGet { Optional.empty() } }) { b -> Optional.of(right(b)) } }, { oab -> oab.map { ab -> ab.pm({ a -> left<Optional<A>, B>(Optional.of(a)) }, ::right) }.orElseGet { left(Optional.empty()) } }) /* 1 + b = S b */ fun <B> plusSO(): ISO<Either<Unit, B>, Optional<B>> = trans(isoPlus(one(), refl<B>()), trans(plusS(), isoS(plusO<B>()))) /** 0 * a = 0 */ fun <A> multO(): ISO<Pair<Nothing, A>, Nothing> = iso({ (no) -> no }) { a -> a.absurd() } /* S a * b = b + a * b */ fun <A, B> multS(): ISO<Pair<Optional<A>, B>, Either<B, Pair<A, B>>> = iso({ (o, b) -> o.map({ a -> right<B, Pair<A, B>>(a to b) }).orElseGet({ left(b) }) }, { bab -> bab.pm({ b -> Pair(Optional.empty(), b) }, { (a, b) -> Pair(Optional.of(a), b) }) }) /** S a * b = b + a * b */ fun <B> multSO(): ISO<Pair<Unit, B>, B> = trans(isoProd(one(), refl<B>()), trans(multS(), trans(isoPlus(refl<B>(), multO<B>()), trans(plusComm(), plusO())))) /** a ^ 0 = 1 */ fun <A> powO(): ISO<(Nothing) -> A, Unit> = iso({ Unit }, { { no: Nothing -> no.absurd() } }) /** a ^ (S b) = a * (a ^ b) */ fun <A, B> powS(): ISO<(Optional<B>) -> A, Pair<A, (B) -> A>> = iso({ f -> Pair(f(Optional.empty()), { o -> f(Optional.of(o)) }) }, { (a, b) -> { p -> p.map(b).orElseGet({ a }) } }) /** * a ^ 1 = a * Go the hard way (like multSO, plusSO) * to prove that you really get what is going on! */ fun <A> powSO(): ISO<(Unit) -> A, A> = iso({ f -> f(Unit) }, { a -> { a } })
agpl-3.0
454d4cc14b887ad2e6c9b8ac7e6f9efa
41.557895
192
0.528568
2.457004
false
false
false
false
AndroidX/androidx
room/room-compiler/src/main/kotlin/androidx/room/ext/xtype_ext.kt
3
4156
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.ext import androidx.room.compiler.codegen.XTypeName import androidx.room.compiler.processing.XType import androidx.room.compiler.processing.isArray import androidx.room.compiler.processing.isByte import androidx.room.compiler.processing.isEnum import androidx.room.compiler.processing.isKotlinUnit import androidx.room.compiler.processing.isVoid import androidx.room.compiler.processing.isVoidObject /** * Returns `true` if this type is not the `void` type. */ fun XType.isNotVoid() = !isVoid() /** * Returns `true` if this does not represent a [Void] type. */ fun XType.isNotVoidObject() = !isVoidObject() /** * Returns `true` if this type does not represent a [Unit] type. */ fun XType.isNotKotlinUnit() = !isKotlinUnit() /** * Returns `true` if this type represents a valid resolvable type. */ fun XType.isNotError() = !isError() /** * Returns `true` if this is not the None type. */ fun XType.isNotNone() = !isNone() /** * Returns `true` if this is not `byte` type. */ fun XType.isNotByte() = !isByte() /** * Returns `true` if this is a `ByteBuffer` type. */ fun XType.isByteBuffer() = asTypeName().equalsIgnoreNullability(CommonTypeNames.BYTE_BUFFER) /** * Returns `true` if this represents a `UUID` type. */ fun XType.isUUID() = asTypeName().equalsIgnoreNullability(CommonTypeNames.UUID) /** * Checks if the class of the provided type has the equals() and hashCode() methods declared. * * Certain Room types and database primitive types are considered to implements equals and * hashcode. * * If they are not found at the current class level, the method recursively moves on to the * super class level and continues to look for these declared methods. */ fun XType.implementsEqualsAndHashcode(): Boolean { if (this.isSupportedMapTypeArg()) return true val typeElement = this.typeElement ?: return false if (typeElement.asClassName().equalsIgnoreNullability(XTypeName.ANY_OBJECT)) { return false } if (typeElement.isDataClass()) { return true } val hasEquals = typeElement.getDeclaredMethods().any { it.jvmName == "equals" && it.returnType.asTypeName() == XTypeName.PRIMITIVE_BOOLEAN && it.parameters.count() == 1 && it.parameters[0].type.asTypeName().equalsIgnoreNullability(XTypeName.ANY_OBJECT) } val hasHashCode = typeElement.getDeclaredMethods().any { it.jvmName == "hashCode" && it.returnType.asTypeName() == XTypeName.PRIMITIVE_INT && it.parameters.count() == 0 } if (hasEquals && hasHashCode) return true return typeElement.superClass?.implementsEqualsAndHashcode() ?: false } /** * Checks if the class of the provided type is one of the types supported in Dao functions with a * Map or Multimap return type. */ fun XType.isSupportedMapTypeArg(): Boolean { if (this.asTypeName().isPrimitive) return true if (this.asTypeName().isBoxedPrimitive) return true if (this.asTypeName().equalsIgnoreNullability(CommonTypeNames.STRING)) return true if (this.isTypeOf(ByteArray::class)) return true if (this.isArray() && this.isByte()) return true val typeElement = this.typeElement ?: return false if (typeElement.isEnum()) return true return false } /** * Returns `true` if this is a [List] */ fun XType.isList(): Boolean = isTypeOf(List::class) /** * Returns true if this is a [List] or [Set]. */ fun XType.isCollection(): Boolean { return isTypeOf(List::class) || isTypeOf(Set::class) }
apache-2.0
99e6d91ca40a794b77c0257062a65e89
30.969231
97
0.710298
4.078508
false
false
false
false
Eifelschaf/svbrockscheid
app/src/main/java/de/kleinelamas/svbrockscheid/TeamAdapter.kt
1
3954
package de.kleinelamas.svbrockscheid import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import de.kleinelamas.svbrockscheid.connection.ApiClient import de.kleinelamas.svbrockscheid.databinding.ListItemPlayerBinding import de.kleinelamas.svbrockscheid.glide.GlideApp import de.kleinelamas.svbrockscheid.model.Player import de.kleinelamas.svbrockscheid.model.TeamHolder import javax.inject.Inject /** * @author Matthias Kutscheid */ class TeamAdapter(private val selectionListener: SelectionListener) : RecyclerView.Adapter<ViewHolder>() { interface SelectionListener { fun onPlayerSelected(player: Player, view: View) } init { SVBApp.component.inject(this) } @Inject lateinit var apiClient: ApiClient var teamHolder: TeamHolder? = null set(value) { field = value notifyDataSetChanged() } override fun getItemCount(): Int { var count = 0 teamHolder?.let { it.getTorhueter()?.let { count += it.size } it.getAbwehr()?.let { count += it.size } it.getMittelfeld()?.let { count += it.size } it.getAngriff()?.let { count += it.size } it.getTrainer()?.let { count += it.size } } return count } private fun getItem(position: Int): PlayerData? { var remainingPosition = position var player: Player? = null var playerPosition: String? = null // find the correct player teamHolder?.let { holder: TeamHolder -> val calculatePositionOrReturn: (Array<Player>) -> Unit = { players -> if (remainingPosition > -1) { if (remainingPosition < players.size) { player = players[remainingPosition] } remainingPosition -= players.size } } playerPosition = "Torhüter" holder.getTorhueter()?.let(calculatePositionOrReturn) if (remainingPosition > -1) { playerPosition = "Abwehr" } holder.getAbwehr()?.let(calculatePositionOrReturn) if (remainingPosition > -1) { playerPosition = "Mittelfeld" } holder.getMittelfeld()?.let(calculatePositionOrReturn) if (remainingPosition > -1) { playerPosition = "Angriff" } holder.getAngriff()?.let(calculatePositionOrReturn) if (remainingPosition > -1) { playerPosition = "Trainer" } holder.getTrainer()?.let(calculatePositionOrReturn) } player?.let { playerPosition?.let { playerPosition -> return PlayerData(it, playerPosition) } } return null } override fun onBindViewHolder(holder: ViewHolder, position: Int) { getItem(position)?.let { (player, position) -> holder.binding.player = player holder.binding.position = position holder.binding.root.setOnClickListener { selectionListener.onPlayerSelected(player, it) } GlideApp.with(holder.itemView).load(BuildDependentConstants.URL + "bilder/team/" + player.bild).placeholder(R.drawable.ic_player).into(holder.binding.image) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(ListItemPlayerBinding.inflate(LayoutInflater.from(parent.context), parent, false)) } } class ViewHolder(val binding: ListItemPlayerBinding) : RecyclerView.ViewHolder(binding.root) { init { binding.image.layoutParams.width = binding.image.context.resources.displayMetrics.widthPixels / 2 } } private data class PlayerData(val player: Player, val position: String)
apache-2.0
e7573ed4f2b2f5343e6919c3b230f83a
34.621622
168
0.621553
4.791515
false
false
false
false
AndroidX/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/FabSecondaryTokens.kt
3
1749
/* * 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. */ // VERSION: v0_103 // GENERATED CODE - DO NOT MODIFY BY HAND package androidx.compose.material3.tokens import androidx.compose.ui.unit.dp internal object FabSecondaryTokens { val ContainerColor = ColorSchemeKeyTokens.SecondaryContainer val ContainerElevation = ElevationTokens.Level3 val ContainerHeight = 56.0.dp val ContainerShape = ShapeKeyTokens.CornerLarge val ContainerWidth = 56.0.dp val FocusContainerElevation = ElevationTokens.Level3 val FocusIconColor = ColorSchemeKeyTokens.OnSecondaryContainer val HoverContainerElevation = ElevationTokens.Level4 val HoverIconColor = ColorSchemeKeyTokens.OnSecondaryContainer val IconColor = ColorSchemeKeyTokens.OnSecondaryContainer val IconSize = 24.0.dp val LoweredContainerElevation = ElevationTokens.Level1 val LoweredFocusContainerElevation = ElevationTokens.Level1 val LoweredHoverContainerElevation = ElevationTokens.Level2 val LoweredPressedContainerElevation = ElevationTokens.Level1 val PressedContainerElevation = ElevationTokens.Level3 val PressedIconColor = ColorSchemeKeyTokens.OnSecondaryContainer }
apache-2.0
f1bbcf33c596c8a9d66e0cc12daf50ff
41.682927
75
0.787307
4.982906
false
false
false
false
mvarnagiris/expensius
app/src/main/kotlin/com/mvcoding/expensius/feature/tag/TagsModule.kt
1
4055
/* * Copyright (C) 2017 Mantas Varnagiris. * * 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. */ package com.mvcoding.expensius.feature.tag import android.app.Activity import android.view.View import com.memoizrlabs.ShankModule import com.memoizrlabs.shankkotlin.provideGlobalSingleton import com.memoizrlabs.shankkotlin.provideNew import com.memoizrlabs.shankkotlin.provideSingletonFor import com.memoizrlabs.shankkotlin.registerFactory import com.mvcoding.expensius.feature.ModelDisplayType import com.mvcoding.expensius.feature.ModelDisplayType.VIEW_ARCHIVED import com.mvcoding.expensius.feature.ModelDisplayType.VIEW_NOT_ARCHIVED import com.mvcoding.expensius.model.Tag import com.mvcoding.expensius.provideAppUserIdSource import com.mvcoding.expensius.provideAppUserSource import com.mvcoding.expensius.provideFirebaseTagsService import com.mvcoding.expensius.provideRxSchedulers import memoizrlabs.com.shankandroid.withActivityScope import memoizrlabs.com.shankandroid.withThisScope class TagsModule : ShankModule { override fun registerFactories() { createTagsWriter() tagsSource() allTagsSource() notArchivedTagsSource() tagsWriter() tagsPresenter() tagPresenter() quickTagsPresenter() } private fun createTagsWriter() = registerFactory(CreateTagsWriter::class) { -> CreateTagsWriter(provideAppUserSource()) { userId, createTags -> provideFirebaseTagsService().createTags(userId, createTags) } } private fun tagsSource() = registerFactory(TagsSource::class) { modelDisplayType: ModelDisplayType -> TagsSource(provideAppUserIdSource()) { if (modelDisplayType == VIEW_ARCHIVED) provideFirebaseTagsService().getArchivedTags(it) else provideFirebaseTagsService().getTags(it) } } private fun allTagsSource() = registerFactory(AllTagsSource::class) { -> AllTagsSource(provideTagsSource(VIEW_NOT_ARCHIVED), provideTagsSource(VIEW_ARCHIVED)) } private fun notArchivedTagsSource() = registerFactory(NotArchivedTagsSource::class) { -> NotArchivedTagsSource(provideAllTagsSource()) } private fun tagsWriter() = registerFactory(TagsWriter::class) { -> TagsWriter(provideAppUserSource()) { userId, tags -> provideFirebaseTagsService().updateTags(userId, tags) } } private fun tagsPresenter() = registerFactory(TagsPresenter::class) { modelDisplayType: ModelDisplayType -> TagsPresenter(modelDisplayType, provideTagsSource(modelDisplayType), provideTagsWriter(), provideRxSchedulers()) } private fun tagPresenter() = registerFactory(TagPresenter::class) { tag: Tag -> TagPresenter(tag, provideCreateTagsWriter(), provideTagsWriter()) } private fun quickTagsPresenter() = registerFactory(QuickTagsPresenter::class) { -> QuickTagsPresenter(provideNotArchivedTagsSource(), provideRxSchedulers()) } } fun provideCreateTagsWriter() = provideNew<CreateTagsWriter>() fun provideTagsWriter() = provideNew<TagsWriter>() fun provideTagsSource(modelDisplayType: ModelDisplayType) = provideGlobalSingleton<TagsSource>(modelDisplayType) fun provideAllTagsSource() = provideNew<AllTagsSource>() fun provideNotArchivedTagsSource() = provideNew<NotArchivedTagsSource>() fun Activity.provideTagsPresenter(modelDisplayType: ModelDisplayType) = withThisScope.provideSingletonFor<TagsPresenter>(modelDisplayType) fun View.provideQuickTagsPresenter() = withActivityScope.provideSingletonFor<QuickTagsPresenter>() fun Activity.provideTagPresenter(tag: Tag) = withThisScope.provideSingletonFor<TagPresenter>(tag)
gpl-3.0
0b427539c362340e71a0b9299eb15fce
47.855422
164
0.782244
4.597506
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/intentions/AddCurlyBracesIntention.kt
3
2812
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsPath import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.RsUseItem import org.rust.lang.core.psi.RsUseSpeck import org.rust.lang.core.psi.ext.ancestorStrict import org.rust.lang.core.psi.ext.isStarImport import org.rust.lang.core.psi.ext.startOffset /** * Adds curly braces to singleton imports, changing from this * * ``` * import std::mem; * ``` * * to this: * * ``` * import std::{mem}; * ``` */ class AddCurlyBracesIntention : RsElementBaseIntentionAction<AddCurlyBracesIntention.Context>() { override fun getText() = "Add curly braces" override fun getFamilyName() = text class Context( val useSpeck: RsUseSpeck, val path: RsPath, val semicolon: PsiElement ) override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? { val useItem = element.ancestorStrict<RsUseItem>() ?: return null val semicolon = useItem.semicolon ?: return null val useSpeck = useItem.useSpeck ?: return null val path = useSpeck.path ?: return null if (useSpeck.useGroup != null || useSpeck.isStarImport) return null return Context(useSpeck, path, semicolon) } override fun invoke(project: Project, editor: Editor, ctx: Context) { val identifier = ctx.path.referenceNameElement?.text ?: "" // Create a new use item that contains a glob list that we can use. // Then extract from it the glob list and the double colon. val newUseSpeck = RsPsiFactory(project).createUseSpeck("dummy::{$identifier}") val newGroup = newUseSpeck.useGroup ?: return val newColonColon = newUseSpeck.coloncolon ?: return val alias = ctx.useSpeck.alias // If there was an alias before, insert it into the new glob item if (alias != null) { val newGlobItem = newGroup.children[0] newGlobItem.addAfter(alias, newGlobItem.lastChild) } // Remove the identifier from the path by replacing it with its subpath val qualifier = ctx.path.path if (qualifier != null) { ctx.path.replace(qualifier) } else { ctx.path.delete() } // Delete the alias of the identifier, if any alias?.delete() // Insert the double colon and glob list into the use item ctx.useSpeck.add(newColonColon) ctx.useSpeck.add(newGroup) editor.caretModel.moveToOffset(ctx.semicolon.startOffset - 1) } }
mit
c267c4ff51a9eac51090f7cb04fc7f82
32.082353
105
0.671408
4.280061
false
false
false
false
googlecast/CastAndroidTvReceiver
app-kotlin/src/main/kotlin/com/google/sample/cast/atvreceiver/presenter/CardPresenter.kt
1
4069
/** * Copyright 2022 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.sample.cast.atvreceiver.presenter import android.graphics.drawable.Drawable import android.util.Log import android.view.View import androidx.leanback.widget.Presenter import android.view.ViewGroup import androidx.core.content.ContextCompat import com.google.sample.cast.atvreceiver.R import androidx.leanback.widget.ImageCardView import com.bumptech.glide.Glide import com.google.sample.cast.atvreceiver.data.Movie /** * A CardPresenter is used to generate Views and bind Objects to them on demand. * It contains an Image CardView */ class CardPresenter : Presenter() { private var mDefaultCardImage: Drawable? = null override fun onCreateViewHolder(parent: ViewGroup): ViewHolder { Log.d(TAG, "onCreateViewHolder") sDefaultBackgroundColor = ContextCompat.getColor(parent.context, R.color.default_background) sSelectedBackgroundColor = ContextCompat.getColor(parent.context, R.color.selected_background) /* * This template uses a default image in res/drawable, but the general case for Android TV * will require your resources in xhdpi. For more information, see * https://developer.android.com/training/tv/start/layouts.html#density-resources */ mDefaultCardImage = ContextCompat.getDrawable(parent.context, R.drawable.movie) val cardView: ImageCardView = object : ImageCardView(parent.context) { override fun setSelected(selected: Boolean) { updateCardBackgroundColor(this, selected) super.setSelected(selected) } } cardView.isFocusable = true cardView.isFocusableInTouchMode = true updateCardBackgroundColor(cardView, false) return ViewHolder(cardView) } override fun onBindViewHolder(viewHolder: ViewHolder, item: Any) { val movie = item as Movie val cardView = viewHolder.view as ImageCardView Log.d(TAG, "onBindViewHolder") if (movie.cardImageUrl != null) { cardView.titleText = movie.title cardView.contentText = movie.studio cardView.setMainImageDimensions(CARD_WIDTH, CARD_HEIGHT) Glide.with(viewHolder.view.context) .load(movie.cardImageUrl) .centerCrop() .error(mDefaultCardImage) .into(cardView.mainImageView) } } override fun onUnbindViewHolder(viewHolder: ViewHolder) { Log.d(TAG, "onUnbindViewHolder") val cardView = viewHolder.view as ImageCardView // Remove references to images so that the garbage collector can free up memory cardView.badgeImage = null cardView.mainImage = null } companion object { private const val TAG = "CardPresenter" private const val CARD_WIDTH = 313 private const val CARD_HEIGHT = 176 private var sSelectedBackgroundColor = 0 private var sDefaultBackgroundColor = 0 private fun updateCardBackgroundColor(view: ImageCardView, selected: Boolean) { val color = if (selected) sSelectedBackgroundColor else sDefaultBackgroundColor // Both background colors should be set because the view's background is temporarily visible // during animations. view.setBackgroundColor(color) view.findViewById<View>(R.id.info_field).setBackgroundColor(color) } } }
apache-2.0
49aa65e9a123d59912679050cca67d7a
41.842105
104
0.695257
4.82109
false
false
false
false
jvalduvieco/blok
apps/Api/src/test/kotlin/com/blok/Common/Infrastructure/HTTP/CommandRequestHandlerTest.kt
1
1484
package com.blok.Common.Infrastructure.HTTP import com.blok.Answer import com.blok.CommandRequestHandler import com.blok.common.Bus.CommandBus import com.blok.common.Bus.SynchronousCommandBus import com.blok.handlers.RequestPayload.NoPayload import com.blok.model.PostId import com.blok.model.PostRepository import org.junit.Assert.assertEquals import org.junit.Test class OkController(bus: CommandBus) : CommandRequestHandler<NoPayload>(NoPayload::class.java, bus) { override fun processImpl(value: NoPayload, urlParams: Map<String, String>, shouldReturnHtml: Boolean): Answer { return Answer.ok() } } class PostNotFoundController(bus: CommandBus) : CommandRequestHandler<NoPayload>(NoPayload::class.java, bus) { override fun processImpl(value: NoPayload, urlParams: Map<String, String>, shouldReturnHtml: Boolean): Answer { throw PostRepository.PostNotFound(PostId()) return Answer.ok() } } class CommandRequestHandlerTest { private val commandBus: CommandBus = SynchronousCommandBus() @Test fun requestHandlerReturnsAnswer() { val controller = OkController(commandBus) val answer = controller.process(NoPayload(), hashMapOf(), false) assertEquals(200, answer.code) } @Test fun NotFoundExceptionAnswers404() { val controller = PostNotFoundController(commandBus) val answer = controller.process(NoPayload(), hashMapOf(), false) assertEquals(404, answer.code) } }
mit
e32439f936f0c8204f2543362a084dc9
36.1
115
0.746631
4.313953
false
true
false
false
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt
1
1369
package com.baeldung.sorting import kotlin.comparisons.* fun sortMethodUsage() { val sortedValues = mutableListOf(1, 2, 7, 6, 5, 6) sortedValues.sort() println(sortedValues) } fun sortByMethodUsage() { val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e") sortedValues.sortBy { it.second } println(sortedValues) } fun sortWithMethodUsage() { val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e") sortedValues.sortWith(compareBy({it.second}, {it.first})) println(sortedValues) } fun <T : kotlin.Comparable<T>> getSimpleComparator() : Comparator<T> { val ascComparator = naturalOrder<T>() return ascComparator } fun getComplexComparator() { val complexComparator = compareBy<Pair<Int, String>>({it.first}, {it.second}) } fun nullHandlingUsage() { val sortedValues = mutableListOf(1 to "a", 2 to null, 7 to "c", 6 to "d", 5 to "c", 6 to "e") sortedValues.sortWith(nullsLast(compareBy { it.second })) println(sortedValues) } fun extendedComparatorUsage() { val students = mutableListOf(21 to "Helen", 21 to "Tom", 20 to "Jim") val ageComparator = compareBy<Pair<Int, String?>> {it.first} val ageAndNameComparator = ageComparator.thenByDescending {it.second} println(students.sortedWith(ageAndNameComparator)) }
gpl-3.0
b90df23a983c9f687bf7b2b9bf6131a0
30.136364
97
0.680058
3.397022
false
false
false
false
EventFahrplan/EventFahrplan
app/src/main/java/nerd/tuxmobil/fahrplan/congress/sharing/models/SessionExport.kt
1
1402
package nerd.tuxmobil.fahrplan.congress.sharing.models import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import nerd.tuxmobil.fahrplan.congress.models.Session @JsonClass(generateAdapter = true) data class SessionExport( @Json(name = "lecture_id") // Keep "lecture_id" key for Chaosflix export. var sessionId: String, var title: String, var subtitle: String = "", var day: Int = 0, var room: String? = null, var slug: String? = null, var url: String? = null, var speakers: String? = null, var track: String? = null, var type: String? = null, var lang: String? = null, var abstract: String, var description: String = "", var links: String? = null, var date: String? = null ) { constructor(session: Session) : this( sessionId = session.sessionId, title = session.title, subtitle = session.subtitle, day = session.day, room = session.room, slug = session.slug, url = session.url, speakers = session.speakers.joinToString(";"), track = session.track, type = session.lang, lang = session.abstractt, abstract = session.description, description = session.links, links = session.date ) }
apache-2.0
db816d864c828e65dc212c0faea80897
32.380952
81
0.577033
4.367601
false
false
false
false
fumoffu/jaydeer-game
src/main/kotlin/fr/jaydeer/dice/dto/DiceType.kt
1
452
package fr.jaydeer.dice.dto import com.fasterxml.jackson.annotation.JsonValue enum class DiceType(val id: String) { N_SIDE(Id.N_SIDE), CUSTOM(Id.CUSTOM); @JsonValue override fun toString(): String { return id } companion object { fun forValue(id: String): DiceType = DiceType.values().first { it.id == id } } object Id { const val N_SIDE = "nSide" const val CUSTOM = "custom" } }
gpl-3.0
a7ef778328322114fcea8a19b0ba44e6
19.590909
84
0.610619
3.645161
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/reference/LuaNameReference.kt
2
2181
/* * Copyright (c) 2017. tangzx([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 com.tang.intellij.lua.reference import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiReferenceBase import com.intellij.util.IncorrectOperationException import com.tang.intellij.lua.psi.LuaElementFactory import com.tang.intellij.lua.psi.LuaNameExpr import com.tang.intellij.lua.psi.resolve import com.tang.intellij.lua.search.SearchContext /** * * Created by tangzx on 2016/11/26. */ class LuaNameReference internal constructor(element: LuaNameExpr) : PsiReferenceBase<LuaNameExpr>(element), LuaReference { private val id: PsiElement = element.id override fun getRangeInElement(): TextRange { val start = id.textOffset - myElement.textOffset return TextRange(start, start + id.textLength) } @Throws(IncorrectOperationException::class) override fun handleElementRename(newElementName: String): PsiElement { val newId = LuaElementFactory.createIdentifier(myElement.project, newElementName) id.replace(newId) return newId } override fun resolve(): PsiElement? { return resolve(SearchContext.get(myElement.project)) } override fun resolve(context: SearchContext): PsiElement? { val resolve = resolve(myElement, context) return if (resolve === myElement) null else resolve } override fun isReferenceTo(element: PsiElement): Boolean { return myElement.manager.areElementsEquivalent(element, resolve()) } override fun getVariants(): Array<Any> { return emptyArray() } }
apache-2.0
71c653f019526927672266047b03aaf5
33.619048
122
0.736359
4.460123
false
false
false
false
WillowChat/Hopper
src/main/kotlin/chat/willow/hopper/connections/HopperConnections.kt
1
5465
package chat.willow.hopper.connections import chat.willow.hopper.auth.IIdentifierGenerator import chat.willow.hopper.auth.nextUniqueId import chat.willow.hopper.logging.loggerFor import chat.willow.warren.IWarrenClient import chat.willow.warren.WarrenClient import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.thread import kotlin.concurrent.withLock interface IHopperConnections { fun create(host: String, port: Int, tls: Boolean, nick: String): HopperConnection? fun track(connection: HopperConnection) fun remove(id: String) fun all(): Set<HopperConnection> fun start(id: String) fun stop(id: String) operator fun get(id: String): HopperConnection? operator fun minusAssign(id: String) operator fun contains(id: String): Boolean } data class HopperConnection(val id: String, val info: HopperConnectionInfo) data class HopperConnectionInfo(val host: String, val port: Int, val tls: Boolean, val nick: String) enum class HopperConnectionState { STARTED, STOPPED } data class HopperBuffer(val id: String, val events: List<HopperBufferEvent<*>>) // todo: think about storage and retrieval by id, date/time data class HopperBufferEvent<out T>(val id: String, val type: String, val payload: T) // todo: metadata class HopperConnections(private val generator: IIdentifierGenerator) : IHopperConnections { private val LOGGER = loggerFor<HopperConnections>() private val connectionLocks = ConcurrentHashMap<String, ReentrantLock>() private val connections = ConcurrentHashMap<String, HopperConnection>() private val warrens = mutableMapOf<String, IWarrenClient>() private val states = mutableMapOf<String, HopperConnectionState>() private val threads = mutableMapOf<String, Thread>() override fun get(id: String): HopperConnection? { return connectionLocks[id]?.withLock { connections[id] } } override fun minusAssign(id: String) { val connection = connections[id] ?: return val lock = connectionLocks[id] ?: return lock.withLock { stop(connection.id) connections.remove(id) warrens.remove(id) states.remove(id) threads.remove(id) } } override fun contains(id: String): Boolean { return connections.containsKey(id) } override fun all(): Set<HopperConnection> { return connections.values.toSet() } override fun create(host: String, port: Int, tls: Boolean, nick: String): HopperConnection? { val id = nextUniqueId(generator, connections) val info = HopperConnectionInfo(host, port, tls, nick) return HopperConnection(id, info) } override fun track(connection: HopperConnection) { val lock = ReentrantLock() connectionLocks[connection.id] = lock lock.withLock { connections += connection.id to connection val client = constructWarrenClient(connection.info) client.events.onAny { LOGGER.info("event for ${connection.id}: $it") } warrens += connection.id to client states += connection.id to HopperConnectionState.STOPPED connection } } override fun remove(id: String) { // todo: clean up bad state if found val lock = connectionLocks[id] ?: return lock.withLock { connections.remove(id) warrens.remove(id) states.remove(id) } } private fun constructWarrenClient(info: HopperConnectionInfo): IWarrenClient { return WarrenClient.build { server(server = info.host) { useTLS = info.tls port = info.port channel("#botdev") } user(info.nick) } } override fun start(id: String) { val lock = connectionLocks[id] ?: return val thread = lock.withLock { val state = states[id] ?: return val warren = warrens[id] ?: return // todo: handle bad state if (state == HopperConnectionState.STARTED) { return } val thread = thread(start = false, name = "Warren thread for $id") { this.states[id] = HopperConnectionState.STARTED LOGGER.info("Warren starting for $id") warren.start() LOGGER.info("Warren ended for $id") stop(id) } thread.setUncaughtExceptionHandler { _, exception -> LOGGER.warn("uncaught exception for Warren $id: $exception") stop(id) } threads[id] = thread thread } thread.start() } override fun stop(id: String) { val lock = connectionLocks[id] ?: return lock.withLock { val state = states[id] ?: return val thread = threads[id] ?: return val connection = connections[id] ?: return if (state == HopperConnectionState.STOPPED) { return } LOGGER.info("stopping Warren by interrupting: $id") thread.interrupt() thread.join(1000) warrens[id] = constructWarrenClient(connection.info) states[id] = HopperConnectionState.STOPPED } } }
isc
744fb5d15061a61f614523c11d78ddb5
29.198895
139
0.622873
4.557965
false
false
false
false
tingyik90/snackprogressbar
lib/src/main/java/com/tingyik90/snackprogressbar/SnackProgressBarCore.kt
1
16357
package com.tingyik90.snackprogressbar import android.annotation.SuppressLint import android.os.Build import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.annotation.IntRange import androidx.annotation.Keep import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.content.ContextCompat import com.google.android.material.snackbar.BaseTransientBottomBar import com.tingyik90.snackprogressbar.SnackProgressBar.Companion.TYPE_CIRCULAR import com.tingyik90.snackprogressbar.SnackProgressBar.Companion.TYPE_HORIZONTAL import com.tingyik90.snackprogressbar.SnackProgressBar.Companion.TYPE_NORMAL /** * Core class constructing the SnackProgressBar. * * @constructor Create a SnackProgressBarCore. * @param parentView View to hold the SnackProgressBarLayout. * @param snackProgressBarLayout [SnackProgressBarLayout] to be displayed. * @param overlayLayout OverlayLayout to be displayed. * @param showDuration Duration to show the SnackProgressBarLayout. * @param snackProgressBar [SnackProgressBar] which is attached to the SnackProgressBarLayout. */ @Keep internal class SnackProgressBarCore private constructor( private val parentView: ViewGroup, val snackProgressBarLayout: SnackProgressBarLayout, val overlayLayout: FrameLayout, private var showDuration: Int, private var snackProgressBar: SnackProgressBar ) : BaseTransientBottomBar<SnackProgressBarCore>(parentView, snackProgressBarLayout, snackProgressBarLayout) { /* variables */ // Duration as per SnackbarManager private val shortDurationMillis = 1500 private val longDurationMillis = 2750 private val handler = Handler() private val runnable = Runnable { dismiss() } private var isActionClicked = false /* companion object */ @Keep companion object { /** * Prepares SnackProgressBarCore. * * @param parentView View to hold the SnackProgressBar, prepared by SnackProgressBarManager * @param snackProgressBar SnackProgressBar to be shown. * @param showDuration Duration to show the SnackProgressBar. * @param viewsToMove View to be animated along with the SnackProgressBar. */ internal fun make( parentView: ViewGroup, snackProgressBar: SnackProgressBar, showDuration: Int, viewsToMove: Array<View>? ): SnackProgressBarCore { // Get inflater from parent val inflater = LayoutInflater.from(parentView.context) // Add overlayLayout as background val overlayLayout = inflater.inflate(R.layout.overlay, parentView, false) as FrameLayout // Starting v6.0, assign unique view id to overlayLayout. // There has been cases where overlayLayout is not correctly removed when the first (with overLay) // and second (without overLay) snackProgressBar are updated too quickly. This maybe due to removing the // incorrect child from parent view. if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) { overlayLayout.id = View.generateViewId() } parentView.addView(overlayLayout) // Inflate SnackProgressBarLayout and pass viewsToMove val snackProgressBarLayout = inflater.inflate( R.layout.snackprogressbar, parentView, false ) as SnackProgressBarLayout snackProgressBarLayout.setViewsToMove(viewsToMove) // Create SnackProgressBarCore val snackProgressBarCore = SnackProgressBarCore( parentView, snackProgressBarLayout, overlayLayout, showDuration, snackProgressBar ) snackProgressBarCore.behavior = SwipeBehavior() snackProgressBarCore.updateTo(snackProgressBar) return snackProgressBarCore } } /** * Gets the show duration. */ internal fun getShowDuration(): Int { return showDuration } /** * Gets the attached snackProgressBar. */ internal fun getSnackProgressBar(): SnackProgressBar { return snackProgressBar } /** * Updates the SnackProgressBar without dismissing it to the new SnackProgressBar. * * @param snackProgressBar SnackProgressBar to be updated to. */ internal fun updateTo(snackProgressBar: SnackProgressBar) { this.snackProgressBar = snackProgressBar setType() setIcon() setAction() showProgressPercentage() setProgressMax() setSwipeToDismiss() setMessage() // only toggle overlayLayout visibility if already shown if (isShown) { showOverlayLayout() } } /** * Updates the color and alpha of overlayLayout. * * @param overlayColor R.color id. * @param overlayLayoutAlpha Alpha between 0f to 1f. Default = 0.8f. */ internal fun setOverlayLayout(overlayColor: Int, overlayLayoutAlpha: Float): SnackProgressBarCore { overlayLayout.setBackgroundColor(ContextCompat.getColor(context, overlayColor)) overlayLayout.alpha = overlayLayoutAlpha return this } /** * Sets whether to use rounded corner background for SnackProgressBar according to new Material Design. * Note that the background cannot be changed after being shown. * * @param useRoundedCornerBackground Whether to use rounded corner background for SnackProgressBar. */ internal fun useRoundedCornerBackground(useRoundedCornerBackground: Boolean): SnackProgressBarCore { snackProgressBarLayout.useRoundedCornerBackground(useRoundedCornerBackground) return this } /** * Updates the color of the layout. * * @param backgroundColor R.color id. * @param messageTextColor R.color id. * @param actionTextColor R.color id. * @param progressBarColor R.color id. * @param progressTextColor R.color id. */ internal fun setColor( backgroundColor: Int, messageTextColor: Int, actionTextColor: Int, progressBarColor: Int, progressTextColor: Int ): SnackProgressBarCore { snackProgressBarLayout.setColor( backgroundColor, messageTextColor, actionTextColor, progressBarColor, progressTextColor ) return this } /** * Sets the text size of SnackProgressBar. * * @param px Font size in pixels. */ internal fun setTextSize(px: Float): SnackProgressBarCore { snackProgressBarLayout.setTextSize(px) return this } /** * Sets the max lines for message. * * @param maxLines Number of lines. */ internal fun setMaxLines(maxLines: Int): SnackProgressBarCore { snackProgressBarLayout.setMaxLines(maxLines) return this } /** * Sets the progress for SnackProgressBar. * * @param progress Progress of the ProgressBar. */ internal fun setProgress(@IntRange(from = 0) progress: Int): SnackProgressBarCore { val progressBar = when (snackProgressBar.getType()) { TYPE_HORIZONTAL -> snackProgressBarLayout.horizontalProgressBar TYPE_CIRCULAR -> snackProgressBarLayout.circularDeterminateProgressBar else -> null } if (progressBar != null) { progressBar.progress = progress val progress100 = (progress.toFloat() / progressBar.max * 100).toInt() var progressString = progress100.toString() snackProgressBarLayout.progressTextCircular.text = progressString // Include % for progressText progressString += "%" snackProgressBarLayout.progressText.text = progressString } return this } /** * Show the SnackProgressBar */ override fun show() { // Show overLayLayout showOverlayLayout() // Use default SnackManager if it is CoordinatorLayout if (parentView is CoordinatorLayout) { duration = showDuration } // Else, set up own handler for dismiss countdown else { setOnBarTouchListener() // Disable SnackManager by stopping countdown duration = LENGTH_INDEFINITE // Assign the actual showDuration if dismiss is required if (showDuration != LENGTH_INDEFINITE) { when (showDuration) { LENGTH_SHORT -> showDuration = shortDurationMillis LENGTH_LONG -> showDuration = longDurationMillis } handler.postDelayed(runnable, showDuration.toLong()) } } super.show() } /** * Sets the layout based on SnackProgressBar type. * Note: Layout positioning for action is handled by [SnackProgressBarLayout] */ private fun setType(): SnackProgressBarCore { // Update view when (snackProgressBar.getType()) { TYPE_NORMAL -> { snackProgressBarLayout.horizontalProgressBar.visibility = View.GONE snackProgressBarLayout.circularDeterminateProgressBar.visibility = View.GONE snackProgressBarLayout.circularIndeterminateProgressBar.visibility = View.GONE } TYPE_HORIZONTAL -> { snackProgressBarLayout.horizontalProgressBar.visibility = View.VISIBLE snackProgressBarLayout.circularDeterminateProgressBar.visibility = View.GONE snackProgressBarLayout.circularIndeterminateProgressBar.visibility = View.GONE snackProgressBarLayout.horizontalProgressBar.isIndeterminate = snackProgressBar.isIndeterminate() } TYPE_CIRCULAR -> { snackProgressBarLayout.horizontalProgressBar.visibility = View.GONE if (snackProgressBar.isIndeterminate()) { snackProgressBarLayout.circularDeterminateProgressBar.visibility = View.GONE snackProgressBarLayout.circularIndeterminateProgressBar.visibility = View.VISIBLE } else { snackProgressBarLayout.circularDeterminateProgressBar.visibility = View.VISIBLE snackProgressBarLayout.circularIndeterminateProgressBar.visibility = View.GONE } } } return this } /** * Sets the icon of SnackProgressBar. */ private fun setIcon(): SnackProgressBarCore { val iconBitmap = snackProgressBar.getIconBitmap() val iconResId = snackProgressBar.getIconResource() when { iconBitmap != null -> { snackProgressBarLayout.iconImage.setImageBitmap(iconBitmap) snackProgressBarLayout.iconImage.visibility = View.VISIBLE } iconResId != SnackProgressBar.DEFAULT_ICON_RES_ID -> { snackProgressBarLayout.iconImage.setImageResource(iconResId) snackProgressBarLayout.iconImage.visibility = View.VISIBLE } else -> snackProgressBarLayout.iconImage.visibility = View.GONE } return this } /** * Sets the action to be displayed. */ @SuppressLint("DefaultLocale") private fun setAction(): SnackProgressBarCore { val action = snackProgressBar.getAction() val onActionClickListener = snackProgressBar.getOnActionClickListener() // Set the text snackProgressBarLayout.actionText.text = action.toUpperCase() snackProgressBarLayout.actionNextLineText.text = action.toUpperCase() // Set the onClickListener val onClickListener = View.OnClickListener { // To prevent multiple clicks on action if (!isActionClicked) { isActionClicked = true // Remove the dismiss callback to avoid calling it twice handler.removeCallbacks(runnable) onActionClickListener?.onActionClick() dismiss() } } snackProgressBarLayout.actionText.setOnClickListener(onClickListener) snackProgressBarLayout.actionNextLineText.setOnClickListener(onClickListener) return this } /** * Sets whether to show progressText. */ private fun showProgressPercentage(): SnackProgressBarCore { if (snackProgressBar.isShowProgressPercentage()) { if (snackProgressBar.getType() == TYPE_CIRCULAR) { snackProgressBarLayout.progressText.visibility = View.GONE snackProgressBarLayout.progressTextCircular.visibility = View.VISIBLE } else { snackProgressBarLayout.progressText.visibility = View.VISIBLE snackProgressBarLayout.progressTextCircular.visibility = View.GONE } } else { snackProgressBarLayout.progressText.visibility = View.GONE snackProgressBarLayout.progressTextCircular.visibility = View.GONE } return this } /** * Sets the max progress for progressBar. */ private fun setProgressMax(): SnackProgressBarCore { snackProgressBarLayout.horizontalProgressBar.max = snackProgressBar.getProgressMax() snackProgressBarLayout.circularDeterminateProgressBar.max = snackProgressBar.getProgressMax() return this } /** * Sets whether user can swipe to dismiss. */ private fun setSwipeToDismiss(): SnackProgressBarCore { (behavior as SwipeBehavior).canSwipe = snackProgressBar.isSwipeToDismiss() snackProgressBarLayout.setSwipeToDismiss(snackProgressBar.isSwipeToDismiss()) return this } /** * Sets the message of SnackProgressBar. */ private fun setMessage(): SnackProgressBarCore { snackProgressBarLayout.messageText.text = snackProgressBar.getMessage() return this } /** * Shows the overlayLayout based on whether user input is allowed. */ private fun showOverlayLayout(): SnackProgressBarCore { if (!snackProgressBar.isAllowUserInput()) { overlayLayout.visibility = View.VISIBLE } else { overlayLayout.visibility = View.GONE } return this } /** * Removes the overlayLayout */ internal fun removeOverlayLayout() { parentView.removeView(overlayLayout) } /** * Registers a callback to be invoked when the SnackProgressBar is touched. * This is only applicable when swipe to dismiss behaviour is true and CoordinatorLayout is not used. */ private fun setOnBarTouchListener() { snackProgressBarLayout.setOnBarTouchListener(object : SnackProgressBarLayout.OnBarTouchListener { override fun onTouch(event: Int) { when (event) { SnackProgressBarLayout.ACTION_DOWN -> // When user touched the SnackProgressBar, stop the dismiss countdown handler.removeCallbacks(runnable) SnackProgressBarLayout.SWIPE_OUT -> // Once the SnackProgressBar is swiped out, dismiss after animation ends handler.postDelayed(runnable, SnackProgressBarLayout.ANIMATION_DURATION) SnackProgressBarLayout.SWIPE_IN -> // Once the SnackProgressBar is swiped in, resume dismiss countdown if (showDuration != SnackProgressBarManager.LENGTH_INDEFINITE) { handler.postDelayed(runnable, showDuration.toLong()) } } } }) } /** * Custom behavior to toggle swipeToDismiss in [CoordinatorLayout]. */ private class SwipeBehavior : Behavior() { var canSwipe = true override fun canSwipeDismissView(child: View): Boolean { return super.canSwipeDismissView(child) && canSwipe } } }
apache-2.0
eadbf3d20310633e2d3c29e66f4f42d3
37.309133
116
0.651831
5.505554
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/codegen/branching/advanced_when2.kt
1
268
fun advanced_when2(i: Int): Int { var value = 1 when (i) { 10 -> {val v = 42; value = v} 11 -> {val v = 43; value = v} 12 -> {val v = 44; value = v} } return value } fun main(args: Array<String>) { if (advanced_when2(10) != 42) throw Error() }
apache-2.0
1f63a5419d45c2254a2f691ce9b6368e
18.142857
45
0.526119
2.68
false
false
false
false
edsilfer/android-kotlin-support
kotlin-support/src/main/java/br/com/edsilfer/kotlin_support/service/keyboard/EnhancedTextWatcher.kt
1
816
package br.com.edsilfer.kotlin_support.service.keyboard import android.text.Editable import android.text.TextWatcher import android.widget.EditText /** * Created by User on 03/12/2016. */ abstract class EnhancedTextWatcher(val mInput: EditText) : TextWatcher { private var snapshot = "" override fun afterTextChanged(sequence: Editable?) { } override fun beforeTextChanged(sequence: CharSequence?, start: Int, count: Int, after: Int) { snapshot = mInput.text.toString() } override fun onTextChanged(sequence: CharSequence?, start: Int, previousLength: Int, count: Int) { onTextChanged(start, count == 0, if (count == 0 && start < snapshot.length) snapshot[start] else ' ') } abstract fun onTextChanged(cursor: Int, isBackspace: Boolean, deletedChar: Char) }
apache-2.0
5f6f64c8674a951a2497fbc3e8aee58f
29.222222
109
0.71201
4.163265
false
false
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/DrainBow.kt
1
1392
package nl.sugcube.dirtyarrows.bow.ability import nl.sugcube.dirtyarrows.DirtyArrows import nl.sugcube.dirtyarrows.bow.BowAbility import nl.sugcube.dirtyarrows.bow.DefaultBow import nl.sugcube.dirtyarrows.util.showHealParticle import org.bukkit.attribute.Attribute import org.bukkit.entity.Arrow import org.bukkit.entity.LivingEntity import org.bukkit.entity.Player import org.bukkit.event.entity.ProjectileHitEvent import kotlin.math.abs import kotlin.math.min /** * Regain 1 heart of health per hit on a different entity. * * @author SugarCaney */ open class DrainBow(plugin: DirtyArrows) : BowAbility( plugin = plugin, type = DefaultBow.DRAINING, canShootInProtectedRegions = true, description = "Gain health back every hit." ) { /** * The amount of health points to heal on every hit. 1 point = half a heart. */ val healthPointsToHeal = config.getInt("$node.health-points") override fun land(arrow: Arrow, player: Player, event: ProjectileHitEvent) { val target = event.hitEntity as? LivingEntity ?: return if (target == player) return val maxHealth = player.getAttribute(Attribute.GENERIC_MAX_HEALTH)?.value ?: return player.health = min(maxHealth, player.health + healthPointsToHeal) repeat(abs(healthPointsToHeal)) { player.location.showHealParticle(1) } } }
gpl-3.0
324b790ce011c0df5a8b08ebd1abd7ab
32.166667
90
0.721983
4.142857
false
false
false
false
edsilfer/android-kotlin-support
kotlin-support/src/main/java/br/com/edsilfer/kotlin_support/service/communication/EmailManager.kt
1
4730
package br.com.edsilfer.kotlin_support.service.communication /** * Created by efernandes on 06/12/16. */ import android.util.Log import br.com.edsilfer.kotlin_support.model.Email import br.com.edsilfer.kotlin_support.model.Sender import java.io.File import java.security.Security import java.util.* import javax.activation.DataHandler import javax.activation.FileDataSource import javax.mail.* import javax.mail.internet.InternetAddress import javax.mail.internet.MimeBodyPart import javax.mail.internet.MimeMessage import javax.mail.internet.MimeMultipart class EmailManager(val sender: Sender) : javax.mail.Authenticator() { companion object { val ARG_CONTENT_TYPE = "application/octet-stream" val ARG_NAME = "ByteArrayDataSource" val ARG_TYPE_TEXT_PLAIN = "text/plain" val PROP_MAIL_TRANSPORT_PROTOCOL = "mail.transport.protocol" val PROP_MAIL_SMTP_HOST = "mail.host" val PROP_MAIL_SMTP_AUTH = "mail.smtp.auth" val PROP_MAIL_SMTP_PORT = "mail.smtp.port" val PROP_MAIL_SMTP_SOCKET_FACTORY_PORT = "mail.smtp.socketFactory.port" val PROP_MAIL_SMTP_SOCKET_FACTORY_CLASS = "mail.smtp.socketFactory.class" val PROP_MAIL_SMTP_SOCKET_FACTORY_FALLBACK = "mail.smtp.socketFactory.fallback" val PROP_MAIL_SMTP_QUIT_WAIT = "mail.smtp.quitwait" val VALUE_MAIL_TRANSPORT_PROTOCOL = "smtp" val VALUE_MAIL_SMTP_HOST = "smtp.gmail.com" val VALUE_MAIL_SMTP_AUTH = "true" val VALUE_MAIL_SMTP_PORT = "465" val VALUE_MAIL_SMTP_SOCKET_FACTORY_PORT = "465" val VALUE_MAIL_SMTP_SOCKET_FACTORY_CLASS = "javax.net.ssl.SSLSocketFactory" val VALUE_MAIL_SMTP_SOCKET_FACTORY_FALLBACK = "false" val VALUE_MAIL_SMTP_QUIT_WAIT = "false" init { Security.addProvider(JSSEProvider()) } } private val session: Session init { val props = Properties() props.setProperty(PROP_MAIL_TRANSPORT_PROTOCOL, VALUE_MAIL_TRANSPORT_PROTOCOL) props.setProperty(PROP_MAIL_SMTP_HOST, VALUE_MAIL_SMTP_HOST) props.put(PROP_MAIL_SMTP_AUTH, VALUE_MAIL_SMTP_AUTH) props.put(PROP_MAIL_SMTP_PORT, VALUE_MAIL_SMTP_PORT) props.put(PROP_MAIL_SMTP_SOCKET_FACTORY_PORT, VALUE_MAIL_SMTP_SOCKET_FACTORY_PORT) props.put(PROP_MAIL_SMTP_SOCKET_FACTORY_CLASS, VALUE_MAIL_SMTP_SOCKET_FACTORY_CLASS) props.put(PROP_MAIL_SMTP_SOCKET_FACTORY_FALLBACK, VALUE_MAIL_SMTP_SOCKET_FACTORY_FALLBACK) props.setProperty(PROP_MAIL_SMTP_QUIT_WAIT, VALUE_MAIL_SMTP_QUIT_WAIT) session = Session.getDefaultInstance(props, this) } override fun getPasswordAuthentication(): PasswordAuthentication { return PasswordAuthentication(sender.email, sender.password) } @Synchronized @Throws(Exception::class) fun sendMail(email: Email) { try { val message = MimeMessage(session) message.sender = InternetAddress(sender.email) message.subject = email.subject message.setContent(getContent(email.attachments, email.body)) setRecipients(email, message) Transport.send(message) Log.i("EmailManager", "E-mail sent to ${email.getRecipients()} successfully") } catch (e: Exception) { Log.e("EmailManager", "Error attempting to send e-mail. Message: ${e.message}") } } private fun setRecipients(email: Email, message: MimeMessage) { if (email.recipients.size > 1) { message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email.getRecipients())) } else { message.setRecipient(Message.RecipientType.TO, InternetAddress(email.getRecipients())) } } private fun getContent(files: Array<File>, textContent: String = ""): Multipart { val multipart: Multipart = MimeMultipart() addTextContent(multipart, textContent) addAttachments(files, multipart) return multipart } private fun addAttachments(files: Array<File>, multipart: Multipart) { for (f in files) { val messageBodyPart = MimeBodyPart() Log.i("EmailManager", "Attaching: ${f.absolutePath}...") val source = FileDataSource(f.absolutePath) messageBodyPart.dataHandler = DataHandler(source) messageBodyPart.fileName = f.name multipart.addBodyPart(messageBodyPart) } } private fun addTextContent(multipart: Multipart, textContent: String) { if (textContent.isNotBlank()) { val bodyPart = MimeBodyPart() bodyPart.setText(textContent) multipart.addBodyPart(bodyPart) } } }
apache-2.0
6cacfcd5d3380c01dee47e55a53ba61f
37.778689
105
0.672516
3.935108
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/User.kt
1
330
package eu.kanade.tachiyomi.data.track.bangumi import kotlinx.serialization.Serializable @Serializable data class User( val avatar: Avatar? = Avatar(), val id: Int? = 0, val nickname: String? = "", val sign: String? = "", val url: String? = "", val usergroup: Int? = 0, val username: String? = "", )
apache-2.0
679e26488ec8264dd1e4dac6ddc03395
22.571429
46
0.630303
3.548387
false
false
false
false
hurricup/intellij-community
platform/configuration-store-impl/testSrc/MockStreamProvider.kt
1
1524
package com.intellij.configurationStore import com.intellij.openapi.components.RoamingType import com.intellij.util.* import java.io.InputStream import java.nio.file.NoSuchFileException import java.nio.file.Path class MockStreamProvider(private val dir: Path) : StreamProvider { override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { dir.resolve(fileSpec).write(content, 0, size) } override fun read(fileSpec: String, roamingType: RoamingType): InputStream? { val file = dir.resolve(fileSpec) try { return file.inputStream() } catch (e: NoSuchFileException) { return null } } override fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean) { dir.resolve(path).directoryStreamIfExists({ filter(it.fileName.toString()) }) { for (file in it) { val attributes = file.basicAttributesIfExists() if (attributes == null || attributes.isDirectory || file.isHidden()) { continue } // we ignore empty files as well - delete if corrupted if (attributes.size() == 0L) { file.delete() continue } if (!file.inputStream().use { processor(file.fileName.toString(), it, false) }) { break } } } } override fun delete(fileSpec: String, roamingType: RoamingType) { dir.resolve(fileSpec).delete() } }
apache-2.0
4f29fe16ddb40193cc3ab72ecee282fa
30.75
184
0.665354
4.391931
false
false
false
false
abigpotostew/easypolitics
db/src/main/kotlin/bz/stewart/bracken/db/args/AbstractClientArgs.kt
1
1134
package bz.stewart.bracken.db.args import com.xenomachina.argparser.ArgParser import com.xenomachina.argparser.default abstract class AbstractClientArgs(parser: ArgParser) : ClientConnectionArgs { override val dbName: String by parser.storing("-b", "--database", help = "Name of db to write to.") override val hostname: String? by parser.storing("--host", help = "Hostname for a remote db connection.").default( null) override val port: String? by parser.storing("--port", help = "Port for a remote db connection.").default(null) override val username: String? by parser.storing("-u", "--user", help = "Username for db authentication.").default( null) override val password: String? by parser.storing("-p", "--pass", help = "Password for db authentication.").default( null) fun hasValidClientArgs():Boolean{ return (this.hostname == null || (this.hostname != null && this.username != null && this.password != null)) } fun getInvalidClientArgsMessage():String{ return "Username (-u) and password (-p) are required when specifying the host (--host)" } }
apache-2.0
3f7a8454bb065fdb878568b91c25ce5e
44.36
119
0.686067
4.247191
false
false
false
false
Maccimo/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/model/psi/labels/LinkLabelSymbol.kt
1
3348
package org.intellij.plugins.markdown.model.psi.labels import com.intellij.find.usages.api.SearchTarget import com.intellij.find.usages.api.UsageHandler import com.intellij.model.Pointer import com.intellij.navigation.* import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import com.intellij.psi.SmartPointerManager import com.intellij.psi.SmartPsiFileRange import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.psi.util.parentOfType import com.intellij.refactoring.rename.api.RenameTarget import com.intellij.refactoring.suggested.startOffset import org.intellij.plugins.markdown.MarkdownIcons import org.intellij.plugins.markdown.lang.psi.impl.MarkdownLinkDefinition import org.intellij.plugins.markdown.lang.psi.impl.MarkdownLinkLabel import org.intellij.plugins.markdown.model.psi.MarkdownSymbolWithUsages import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal data class LinkLabelSymbol( override val file: PsiFile, override val range: TextRange, val text: String ): MarkdownSymbolWithUsages, SearchTarget, RenameTarget, NavigatableSymbol, NavigationTarget { override fun createPointer(): Pointer<out LinkLabelSymbol> { val project = file.project val base = SmartPointerManager.getInstance(project).createSmartPsiFileRangePointer(file, range) return LinkLabelPointer(base, text) } private class LinkLabelPointer(private val base: SmartPsiFileRange, private val text: String): Pointer<LinkLabelSymbol> { override fun dereference(): LinkLabelSymbol? { val file = base.containingFile ?: return null val range = base.range ?: return null return LinkLabelSymbol(file, TextRange.create(range), text) } } override val targetName: String get() = text override val maximalSearchScope: SearchScope? get() = GlobalSearchScope.fileScope(file) override val presentation: TargetPresentation get() = targetPresentation override val usageHandler: UsageHandler<*> get() = UsageHandler.createEmptyUsageHandler(text) override val searchText: String get() = text override fun getTargetPresentation(): TargetPresentation { return TargetPresentation.builder(text).icon(MarkdownIcons.EditorActions.Link).presentation() } override fun navigationRequest(): NavigationRequest? { val virtualFile = file.virtualFile?.takeIf { it.isValid } ?: return null return NavigationService.instance().sourceNavigationRequest(virtualFile, range.startOffset) } override fun getNavigationTargets(project: Project): Collection<NavigationTarget> { return listOf(this) } companion object { fun createPointer(label: MarkdownLinkLabel): Pointer<LinkLabelSymbol>? { val text = label.text val rangeInElement = TextRange(0, text.length) val absoluteRange = rangeInElement.shiftRight(label.startOffset) val textInElement = rangeInElement.substring(text) val file = label.containingFile val project = file.project val base = SmartPointerManager.getInstance(project).createSmartPsiFileRangePointer(file, absoluteRange) return LinkLabelPointer(base, textInElement) } val MarkdownLinkLabel.isDeclaration: Boolean get() = parentOfType<MarkdownLinkDefinition>() != null } }
apache-2.0
0a6d11256128ee15496f33807220c0b5
37.930233
123
0.784648
4.662953
false
false
false
false
ThoseGrapefruits/intellij-rust
src/test/kotlin/org/rust/lang/documentation/RustDocumentationProviderTest.kt
1
1096
package org.rust.lang.documentation import com.intellij.codeInsight.documentation.DocumentationManager import com.intellij.openapi.util.io.FileUtil import org.assertj.core.api.Assertions.assertThat import org.rust.lang.RustTestCase import java.io.File class RustDocumentationProviderTest : RustTestCase() { override fun getTestDataPath() = "src/test/resources/org/rust/lang/documentation/fixtures" private fun doTest(expected: String) { myFixture.configureByFile(fileName) val originalElement = myFixture.elementAtCaret val element = DocumentationManager.getInstance(project).findTargetElement(myFixture.editor, myFixture.file) val doc = RustDocumentationProvider().getQuickNavigateInfo(element, originalElement) assertThat(doc).isEqualTo(expected); } private fun doFileTest() { val text = FileUtil.loadFile(File(testDataPath + "/" + fileName.replace(".rs", ".html"))).trim() doTest(text) } fun testVariable1() = doFileTest() fun testVariable2() = doFileTest() fun testNestedFunction() = doFileTest() }
mit
0b5cc272b1d8ddf4382291d03973b5e2
38.142857
115
0.742701
4.624473
false
true
false
false