repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
GunoH/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/dataframe/ColumnUtils.kt | 9 | 1379 | /*
* 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.dataframe
import org.jetbrains.plugins.notebooks.visualization.r.inlays.dataframe.columns.Column
class ColumnUtils {
companion object {
/**
* Checks that the Number is ordered (does not matters ascendant or descendant). Applicable only for numerical columns.
* Column contains only null values will be ordered.
*/
fun isColumnOrdered(column: Column<out Number>): Boolean {
if(column.size < 2) {
return true
}
var prev = -1
var order: Boolean? = null
for (i in 0 until column.size) {
if(column.isNull(i))
continue
if(prev==-1) {
prev = i
continue
}
if(order == null) {
order = column[prev].toDouble() <= column[i].toDouble()
} else {
if (order != column[prev].toDouble() <= column[i].toDouble()) {
return false
}
}
prev = i
}
return true
}
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/compiler-plugins/compiler-plugin-support/common/src/org/jetbrains/kotlin/idea/compilerPlugin/idePluginUtils.kt | 4 | 2803 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.compilerPlugin
import com.intellij.openapi.module.Module
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.facet.getInstance
import org.jetbrains.kotlin.idea.macros.KOTLIN_BUNDLED
import java.io.File
fun Module.getSpecialAnnotations(prefix: String): List<String> =
KotlinCommonCompilerArgumentsHolder.getInstance(this).pluginOptions
?.filter { it.startsWith(prefix) }
?.map { it.substring(prefix.length) }
?: emptyList()
class CompilerPluginSetup(val options: List<PluginOption>, val classpath: List<String>) {
class PluginOption(val key: String, val value: String)
}
fun File.toJpsVersionAgnosticKotlinBundledPath(): String {
val kotlincDirectory = KotlinPluginLayout.kotlinc
require(this.startsWith(kotlincDirectory)) { "$this should start with ${kotlincDirectory}" }
return "\$$KOTLIN_BUNDLED\$/${this.relativeTo(kotlincDirectory)}"
}
fun modifyCompilerArgumentsForPlugin(
facet: KotlinFacet,
setup: CompilerPluginSetup?,
compilerPluginId: String,
pluginName: String
) {
val facetSettings = facet.configuration.settings
// investigate why copyBean() sometimes throws exceptions
val commonArguments = facetSettings.compilerArguments ?: CommonCompilerArguments.DummyImpl()
/** See [CommonCompilerArguments.PLUGIN_OPTION_FORMAT] **/
val newOptionsForPlugin = setup?.options?.map { "plugin:$compilerPluginId:${it.key}=${it.value}" } ?: emptyList()
val oldAllPluginOptions =
(commonArguments.pluginOptions ?: emptyArray()).filterTo(mutableListOf()) { !it.startsWith("plugin:$compilerPluginId:") }
val newAllPluginOptions = oldAllPluginOptions + newOptionsForPlugin
val oldPluginClasspaths = (commonArguments.pluginClasspaths ?: emptyArray()).filterTo(mutableListOf()) {
val lastIndexOfFile = it.lastIndexOfAny(charArrayOf('/', File.separatorChar))
if (lastIndexOfFile < 0) {
return@filterTo true
}
!it.drop(lastIndexOfFile + 1).matches("(kotlin-)?(maven-)?$pluginName-.*\\.jar".toRegex())
}
val newPluginClasspaths = oldPluginClasspaths + (setup?.classpath ?: emptyList())
commonArguments.pluginOptions = newAllPluginOptions.toTypedArray()
commonArguments.pluginClasspaths = newPluginClasspaths.toTypedArray()
facetSettings.compilerArguments = commonArguments
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/surroundWith/if/moveDeclarationsOut/val/valWithTypeWithInitializer.kt | 13 | 62 | fun foo() {
<caret>val a: String = "aaa"
a.charAt(1)
}
| apache-2.0 |
GunoH/intellij-community | java/execution/impl/src/com/intellij/execution/scratch/JavaScratchConfigurationOptions.kt | 7 | 483 | // 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.execution.scratch
import com.intellij.execution.application.JvmMainMethodRunConfigurationOptions
import com.intellij.util.xmlb.annotations.OptionTag
open class JavaScratchConfigurationOptions: JvmMainMethodRunConfigurationOptions() {
@get:OptionTag("SCRATCH_FILE_URL")
open var scratchFileUrl: String? by string()
} | apache-2.0 |
andrsim66/Timetable-Kotlin | app/src/main/java/com/sevenander/timetable/viewTimetable/adapter/LessonPagerAdapter.kt | 1 | 922 | package com.sevenander.timetable.viewTimetable.adapter
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.view.PagerAdapter
import com.sevenander.timetable.viewTimetable.LessonListFragment
/**
* Created by andrii on 6/1/17.
*/
class LessonPagerAdapter(fragmentManager: FragmentManager, private var titles: Array<String?>) :
FragmentStatePagerAdapter(fragmentManager) {
override fun getItem(position: Int): Fragment {
return LessonListFragment.newInstance(getPageTitle(position).toString())
}
override fun getCount(): Int {
return titles.size
}
override fun getPageTitle(position: Int): CharSequence {
return titles[position].orEmpty()
}
override fun getItemPosition(`object`: Any?): Int {
return PagerAdapter.POSITION_NONE
}
} | mit |
jk1/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/MenuFixture.kt | 1 | 5209 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.fixtures
import com.intellij.openapi.util.Ref
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.testGuiFramework.framework.GuiTestUtil
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.typeMatcher
import org.fest.assertions.Assertions.assertThat
import org.fest.swing.core.GenericTypeMatcher
import org.fest.swing.core.Robot
import org.fest.swing.timing.Condition
import org.fest.swing.timing.Pause
import org.fest.swing.timing.Timeout
import org.fest.util.Lists.newArrayList
import org.junit.Assert.assertNotNull
import java.awt.Container
import java.util.*
import java.util.concurrent.TimeUnit
import javax.swing.JMenuItem
import javax.swing.JPopupMenu
class MenuFixture internal constructor(private val myRobot: Robot, private val myContainer: IdeFrameImpl) {
/**
* Invokes an action by menu path
*
* @param path the series of menu names, e.g. ["][]
*/
fun invokeMenuPath(vararg path: String) {
getMenuItemFixture(*path).click()
}
fun getMenuItemFixture(vararg path: String): MenuItemFixture {
return MenuItemFixture(MenuItemFixture::class.java, myRobot, findActionMenuItem(false, *path))
}
fun getMenuItemFixtureByRegex(vararg path: String): MenuItemFixture {
return MenuItemFixture(MenuItemFixture::class.java, myRobot, findActionMenuItem(true, *path))
}
/**
* Invokes an action by menu path (where each segment is a regular expression). This is particularly
* useful when the menu items can change dynamically, such as the labels of Undo actions, Run actions,
* etc.
*
* @param path the series of menu name regular expressions, e.g. ["][]
*/
fun invokeMenuPathRegex(vararg path: String) {
getMenuItemFixtureByRegex(*path).click()
}
private fun findActionMenuItem(pathIsRegex: Boolean, vararg path: String): JMenuItem {
assertThat(path).isNotEmpty
val segmentCount = path.size
// We keep the list of previously found pop-up menus, so we don't look for menu items in the same pop-up more than once.
val previouslyFoundPopups = ArrayList<JPopupMenu>()
var root: Container = myContainer
for (i in 0 until segmentCount) {
val segment = path[i]
assertNotNull(root)
val menuItem: JMenuItem = getMenuItem(root, pathIsRegex, segment, 2L)
if (root is JPopupMenu) {
previouslyFoundPopups.add(root)
}
if (i < segmentCount - 1) {
val showingPopupMenus = findShowingPopupMenus(getCountOfShowing(previouslyFoundPopups) + 1)
myRobot.click(menuItem)
showingPopupMenus.removeAll(previouslyFoundPopups)
assertThat(showingPopupMenus).hasSize(1)
root = showingPopupMenus[0]
continue
}
return menuItem
}
throw AssertionError("Menu item with path " + Arrays.toString(path) + " should have been found already")
}
private fun menuItemMatcher(pathIsRegex: Boolean,
segment: String): GenericTypeMatcher<JMenuItem> {
return typeMatcher(JMenuItem::class.java, {
if (pathIsRegex) it.text.matches(segment.toRegex())
else segment == it.text
})
}
private fun getMenuItem(root: Container, pathIsRegex: Boolean, segment: String): JMenuItem {
return myRobot.finder().find(root, menuItemMatcher(pathIsRegex, segment))
}
private fun getMenuItem(root: Container, pathIsRegex: Boolean, segment: String, timeoutInSeconds: Long): JMenuItem {
return GuiTestUtil.waitUntilFound(myRobot, root, menuItemMatcher(pathIsRegex, segment), Timeout.timeout(timeoutInSeconds, TimeUnit.SECONDS))
}
private fun getCountOfShowing(previouslyFoundPopups: List<JPopupMenu>): Int {
return previouslyFoundPopups.stream().filter { popupMenu -> popupMenu.isShowing }.count().toInt()
}
private fun findShowingPopupMenus(expectedCount: Int): MutableList<JPopupMenu> {
val ref = Ref<MutableList<JPopupMenu>>()
Pause.pause(object : Condition("waiting for $expectedCount JPopupMenus to show up") {
override fun test(): Boolean {
val popupMenus = newArrayList(myRobot.finder().findAll(typeMatcher(JPopupMenu::class.java, { it.isShowing })))
val allFound = popupMenus.size == expectedCount
if (allFound)
ref.set(popupMenus)
return allFound
}
})
val popupMenus = ref.get()
assertThat(popupMenus).isNotNull.hasSize(expectedCount)
return popupMenus
}
class MenuItemFixture(selfType: Class<MenuItemFixture>, robot: Robot, target: JMenuItem) : JComponentFixture<MenuItemFixture, JMenuItem>(
selfType, robot, target)
}
| apache-2.0 |
andrewoma/dexx | kollection/src/test/kotlin/com/github/andrewoma/dexx/kollection/ImmutableSetTest.kt | 1 | 1698 | /*
* Copyright (c) 2015 Andrew O'Malley
*
* 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.github.andrewoma.dexx.kollection
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class ImmutableSetTest : AbstractImmutableSetTest() {
override fun <E : Comparable<E>> set(vararg elements: E) = immutableSetOf(*elements)
@Test fun `should be produce a readable toString`() {
assertThat(set(1, 2, 3).toString()).isEqualTo("ImmutableSet(1, 2, 3)")
}
@Test fun `should allow construction from sequences`() {
assertThat(listOf(1, 2, 3).asSequence().toImmutableSet()).isEqualTo(immutableSetOf(1, 2, 3))
}
}
| mit |
marius-m/wt4 | models/src/main/java/lt/markmerkk/entities/Ticket.kt | 1 | 2727 | package lt.markmerkk.entities
import lt.markmerkk.Const
data class Ticket(
val id: Long = Const.NO_ID,
val code: TicketCode = TicketCode.asEmpty(),
val description: String = "",
val parentId: Long = Const.NO_ID, // todo up of removal
val status: String,
val assigneeName: String,
val reporterName: String,
val isWatching: Boolean,
val parentCode: TicketCode,
val remoteData: RemoteData? = null
) {
fun clearStatus(): Ticket {
return Ticket(
id = id,
code = code,
description = description,
parentId = parentId,
status = "",
assigneeName = assigneeName,
reporterName = reporterName,
isWatching = isWatching,
parentCode = parentCode,
remoteData = remoteData
)
}
companion object {
fun new(
code: String,
description: String,
remoteData: RemoteData?
): Ticket {
return Ticket(
code = TicketCode.new(code),
description = description,
status = "",
parentCode = TicketCode.asEmpty(),
assigneeName = "",
reporterName = "",
isWatching = false,
remoteData = remoteData
)
}
fun fromRemoteData(
code: String,
description: String,
status: String,
assigneeName: String,
reporterName: String,
isWatching: Boolean,
parentCode: String,
remoteData: RemoteData?
): Ticket {
return Ticket(
code = TicketCode.new(code),
description = description,
status = status,
assigneeName = assigneeName,
reporterName = reporterName,
isWatching = isWatching,
parentCode = TicketCode.new(parentCode),
remoteData = remoteData
)
}
}
}
fun Ticket.markAsError(
errorMessage: String
): Ticket {
return Ticket(
id = id,
code = code,
description = description,
parentId = parentId,
status = status,
assigneeName = assigneeName,
reporterName = reporterName,
isWatching = isWatching,
parentCode = parentCode,
remoteData = remoteData.markAsError(errorMessage)
)
}
| apache-2.0 |
evanchooly/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/MavenId.kt | 1 | 3004 | package com.beust.kobalt.maven
import com.beust.kobalt.api.Kobalt
import org.eclipse.aether.artifact.DefaultArtifact
/**
* Encapsulate a Maven id captured in one string, as used by Gradle or Ivy, e.g. "org.testng:testng:6.9.9".
* These id's are somewhat painful to manipulate because on top of containing groupId, artifactId
* and version, they also accept an optional packaging (e.g. "aar") and qualifier (e.g. "no_aop").
* Determining which is which in an untyped string separated by colons is not clearly defined so
* this class does a best attempt at deconstructing an id but there's surely room for improvement.
*
* This class accepts a versionless id, which needs to end with a :, e.g. "com.beust:jcommander:" (which
* usually means "latest version") but it doesn't handle version ranges yet.
*/
class MavenId private constructor(val groupId: String, val artifactId: String, val packaging: String?,
val classifier: String?, val version: String?) {
companion object {
fun isMavenId(id: String) = with(id.split(":")) {
size >= 3 && size <= 5
}
fun isRangedVersion(s: String): Boolean {
return s.first() in listOf('[', '(') && s.last() in listOf(']', ')')
}
/**
* Similar to create(MavenId) but don't run IMavenIdInterceptors.
*/
fun createNoInterceptors(id: String) : MavenId = DefaultArtifact(id).run {
MavenId(groupId, artifactId, extension, classifier, version)
}
fun toKobaltId(id: String) = if (id.endsWith(":")) id + "(0,]" else id
/**
* The main entry point to create Maven Id's. Id's created by this function
* will run through IMavenIdInterceptors.
*/
fun create(originalId: String) : MavenId {
val id = toKobaltId(originalId)
var originalMavenId = createNoInterceptors(id)
var interceptedMavenId = originalMavenId
val interceptors = Kobalt.context?.pluginInfo?.mavenIdInterceptors
if (interceptors != null) {
interceptedMavenId = interceptors.fold(originalMavenId, {
id, interceptor -> interceptor.intercept(id) })
}
return interceptedMavenId
}
fun create(groupId: String, artifactId: String, packaging: String?, classifier: String?, version: String?) =
create(toId(groupId, artifactId, packaging, classifier, version))
fun toId(groupId: String, artifactId: String, packaging: String? = null, classifier: String? = null, version: String?) =
"$groupId:$artifactId" +
(if (packaging != null && packaging != "") ":$packaging" else "") +
(if (classifier != null && classifier != "") ":$classifier" else "") +
":$version"
}
val hasVersion = version != null
val toId = MavenId.toId(groupId, artifactId, packaging, classifier, version)
}
| apache-2.0 |
chiclaim/android-sample | language-kotlin/kotlin-sample/coroutine-in-action/src/main/kotlin/com/chiclaim/coroutine/basic/example-cancel-05.kt | 1 | 1071 |
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
} finally {
withContext(NonCancellable) {
println("I'm running finally")
delay(1000L)
println("And I've just delayed for 1 sec because I'm non-cancellable")
}
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancelAndJoin() // cancels the job and waits for its completion
println("main: Now I can quit.")
}
/*
官方是说如果在finally调用suspend函数会抛出异常CancellationException,所以需要放在withContext(NonCancellable)中
//todo ?? 经过测试,把withContext(NonCancellable)注释不会抛出异常
I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
main: I'm tired of waiting!
I'm running finally
And I've just delayed for 1 sec because I'm non-cancellable
main: Now I can quit.
*/ | apache-2.0 |
DarrenAtherton49/droid-community-app | app/src/main/kotlin/com/darrenatherton/droidcommunity/common/injection/module/SubscriptionDrawerModule.kt | 1 | 127 | package com.darrenatherton.droidcommunity.common.injection.module
import dagger.Module
@Module
class SubscriptionDrawerModule | mit |
Doctoror/ParticleConstellationsLiveWallpaper | app/src/test/java/com/doctoror/particleswallpaper/framework/opengl/GlUncaughtExceptionHandlerTest.kt | 1 | 2610 | /*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.doctoror.particleswallpaper.framework.opengl
import org.junit.Test
import org.mockito.kotlin.*
class GlUncaughtExceptionHandlerTest {
private val knownOpenglIssuesHandler: KnownOpenglIssuesHandler = mock()
private val wrapped: Thread.UncaughtExceptionHandler = mock()
private val underTest =
GlUncaughtExceptionHandler(
knownOpenglIssuesHandler,
wrapped
)
@Test
fun doesNotForwardNullToKnownOpenglIssuesHandler() {
underTest.uncaughtException(Thread.currentThread(), null)
verify(knownOpenglIssuesHandler, never()).handleUncaughtException(anyOrNull())
}
@Test
fun alwaysForwardsNullToWrapped() {
underTest.uncaughtException(Thread.currentThread(), null)
verify(knownOpenglIssuesHandler, never()).handleUncaughtException(anyOrNull())
verify(wrapped).uncaughtException(Thread.currentThread(), null)
}
@Test
fun forwardsThrowableToKnownOpenglIssuesHandler() {
val throwable = Exception()
underTest.uncaughtException(Thread.currentThread(), throwable)
verify(knownOpenglIssuesHandler).handleUncaughtException(throwable)
}
@Test
fun forwardsThrowableToWrappedIfKnownOpenglIssuesHandlerDidNotHandle() {
val throwable = Exception()
underTest.uncaughtException(Thread.currentThread(), throwable)
verify(knownOpenglIssuesHandler).handleUncaughtException(throwable)
verify(wrapped).uncaughtException(Thread.currentThread(), throwable)
}
@Test
fun doesNotForwardThrowableToWrappedIfKnownOpenglIssuesHandlerHandled() {
val throwable = Exception()
whenever(knownOpenglIssuesHandler.handleUncaughtException(anyOrNull())).thenReturn(true)
underTest.uncaughtException(Thread.currentThread(), throwable)
verify(knownOpenglIssuesHandler).handleUncaughtException(throwable)
verify(wrapped, never()).uncaughtException(anyOrNull(), anyOrNull())
}
}
| apache-2.0 |
FountainMC/FountainAPI | src/main/kotlin/org/fountainmc/api/world/block/plants/Leaves.kt | 1 | 343 | package org.fountainmc.api.world.block.plants
interface Leaves : Plant {
/**
* Return if the leaves can decay
* @return if able to decay
*/
fun canDecay(): Boolean
val type: LeafType
enum class LeafType {
OAK,
SPRUCE,
BIRCH,
JUNGLE,
ACACIA,
DARK_OAK
}
}
| mit |
eyyoung/idea-plugin-custom-ui-panel | src/main/kotlin/com/nd/sdp/common/model/Widget.kt | 1 | 712 | package com.nd.sdp.common.model
/**
* 控件Bean
* Created by Young on 2017/7/3.
*/
class Widget {
var name: String? = null
var repository: String? = null
var readme: String? = null
var more: String? = null
var image: String? = null
var imageWiki: String? = null
var category: String? = null
var xml: String? = null
var java: String? = null
var defaultType: String? = null
var dependency: Dependency? = null
var wiki: String? = null
var dependencies: Dependencies? = null
override fun toString(): String {
return if (name == null) "" else name!!
}
fun getSearchInfo(): String {
return name + readme + more + category
}
}
| mit |
code-disaster/lwjgl3 | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_gpu_shader_fp64.kt | 4 | 9038 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val ARB_gpu_shader_fp64 = "ARBGPUShaderFP64".nativeClassGL("ARB_gpu_shader_fp64") {
documentation =
"""
Native bindings to the $registryLink extension.
This extension allows GLSL shaders to use double-precision floating-point data types, including vectors and matrices of doubles. Doubles may be used as
inputs, outputs, and uniforms.
The shading language supports various arithmetic and comparison operators on double-precision scalar, vector, and matrix types, and provides a set of
built-in functions including:
${ul(
"square roots and inverse square roots;",
"fused floating-point multiply-add operations;",
"""
splitting a floating-point number into a significand and exponent (frexp), or building a floating-point number from a significand and exponent
(ldexp);
""",
"""
absolute value, sign tests, various functions to round to an integer value, modulus, minimum, maximum, clamping, blending two values, step
functions, and testing for infinity and NaN values;
""",
"packing and unpacking doubles into a pair of 32-bit unsigned integers;",
"matrix component-wise multiplication, and computation of outer products, transposes, determinants, and inverses; and",
"vector relational functions."
)}
Double-precision versions of angle, trigonometry, and exponential functions are not supported.
Implicit conversions are supported from integer and single-precision floating-point values to doubles, and this extension uses the relaxed function
overloading rules specified by the ARB_gpu_shader5 extension to resolve ambiguities.
This extension provides API functions for specifying double-precision uniforms in the default uniform block, including functions similar to the uniform
functions added by ${EXT_direct_state_access.link} (if supported).
This extension provides an "LF" suffix for specifying double-precision constants. Floating-point constants without a suffix in GLSL are treated as
single-precision values for backward compatibility with versions not supporting doubles; similar constants are treated as double-precision values in the
"C" programming language.
This extension does not support interpolation of double-precision values; doubles used as fragment shader inputs must be qualified as "flat".
Additionally, this extension does not allow vertex attributes with 64-bit components. That support is added separately by
${registryLinkTo("EXT", "vertex_attrib_64bit")}.
Requires ${GL32.link} and GLSL 1.50. ${GL40.promoted}
"""
IntConstant(
"Returned in the {@code type} parameter of GetActiveUniform, and GetTransformFeedbackVarying.",
"DOUBLE_VEC2"..0x8FFC,
"DOUBLE_VEC3"..0x8FFD,
"DOUBLE_VEC4"..0x8FFE,
"DOUBLE_MAT2"..0x8F46,
"DOUBLE_MAT3"..0x8F47,
"DOUBLE_MAT4"..0x8F48,
"DOUBLE_MAT2x3"..0x8F49,
"DOUBLE_MAT2x4"..0x8F4A,
"DOUBLE_MAT3x2"..0x8F4B,
"DOUBLE_MAT3x4"..0x8F4C,
"DOUBLE_MAT4x2"..0x8F4D,
"DOUBLE_MAT4x3"..0x8F4E
)
reuse(GL40C, "Uniform1d")
reuse(GL40C, "Uniform2d")
reuse(GL40C, "Uniform3d")
reuse(GL40C, "Uniform4d")
reuse(GL40C, "Uniform1dv")
reuse(GL40C, "Uniform2dv")
reuse(GL40C, "Uniform3dv")
reuse(GL40C, "Uniform4dv")
reuse(GL40C, "UniformMatrix2dv")
reuse(GL40C, "UniformMatrix3dv")
reuse(GL40C, "UniformMatrix4dv")
reuse(GL40C, "UniformMatrix2x3dv")
reuse(GL40C, "UniformMatrix2x4dv")
reuse(GL40C, "UniformMatrix3x2dv")
reuse(GL40C, "UniformMatrix3x4dv")
reuse(GL40C, "UniformMatrix4x2dv")
reuse(GL40C, "UniformMatrix4x3dv")
reuse(GL40C, "GetUniformdv")
val program = GLuint("program", "the program object to update")
var src = GL40C["Uniform1d"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniform1dEXT",
"DSA version of #Uniform1d().",
program,
src["location"],
src["x"]
)
src = GL40C["Uniform2d"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniform2dEXT",
"DSA version of #Uniform2d().",
program,
src["location"],
src["x"],
src["y"]
)
src = GL40C["Uniform3d"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniform3dEXT",
"DSA version of #Uniform3d().",
program,
src["location"],
src["x"],
src["y"],
src["z"]
)
src = GL40C["Uniform4d"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniform4dEXT",
"DSA version of #Uniform4d().",
program,
src["location"],
src["x"],
src["y"],
src["z"],
src["w"]
)
src = GL40C["Uniform1dv"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniform1dvEXT",
"DSA version of #Uniform1dv().",
program,
src["location"],
src["count"],
src["value"]
)
src = GL40C["Uniform2dv"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniform2dvEXT",
"DSA version of #Uniform2dv().",
program,
src["location"],
src["count"],
src["value"]
)
src = GL40C["Uniform3dv"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniform3dvEXT",
"DSA version of #Uniform3dv().",
program,
src["location"],
src["count"],
src["value"]
)
src = GL40C["Uniform4dv"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniform4dvEXT",
"DSA version of #Uniform4dv().",
program,
src["location"],
src["count"],
src["value"]
)
src = GL40C["UniformMatrix2dv"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniformMatrix2dvEXT",
"DSA version of #UniformMatrix2dv().",
program,
src["location"],
src["count"],
src["transpose"],
src["value"]
)
src = GL40C["UniformMatrix3dv"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniformMatrix3dvEXT",
"DSA version of #UniformMatrix3dv().",
program,
src["location"],
src["count"],
src["transpose"],
src["value"]
)
src = GL40C["UniformMatrix4dv"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniformMatrix4dvEXT",
"DSA version of #UniformMatrix4dv().",
program,
src["location"],
src["count"],
src["transpose"],
src["value"]
)
src = GL40C["UniformMatrix2x3dv"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniformMatrix2x3dvEXT",
"DSA version of #UniformMatrix2x3dv().",
program,
src["location"],
src["count"],
src["transpose"],
src["value"]
)
src = GL40C["UniformMatrix2x4dv"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniformMatrix2x4dvEXT",
"DSA version of #UniformMatrix2x4dv().",
program,
src["location"],
src["count"],
src["transpose"],
src["value"]
)
src = GL40C["UniformMatrix3x2dv"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniformMatrix3x2dvEXT",
"DSA version of #UniformMatrix3x2dv().",
program,
src["location"],
src["count"],
src["transpose"],
src["value"]
)
src = GL40C["UniformMatrix3x4dv"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniformMatrix3x4dvEXT",
"DSA version of #UniformMatrix3x4dv().",
program,
src["location"],
src["count"],
src["transpose"],
src["value"]
)
src = GL40C["UniformMatrix4x2dv"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniformMatrix4x2dvEXT",
"DSA version of #UniformMatrix4x2dv().",
program,
src["location"],
src["count"],
src["transpose"],
src["value"]
)
src = GL40C["UniformMatrix4x3dv"]
IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void(
"ProgramUniformMatrix4x3dvEXT",
"DSA version of #UniformMatrix4x3dv().",
program,
src["location"],
src["count"],
src["transpose"],
src["value"]
)
} | bsd-3-clause |
aerisweather/AerisAndroidSDK | Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/view/locations/LocationSearchActivity.kt | 1 | 10026 | package com.example.demoaerisproject.view.locations
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.Observer
import com.aerisweather.aeris.response.PlacesResponse
import com.example.demoaerisproject.R
import com.example.demoaerisproject.data.room.MyPlace
import com.example.demoaerisproject.view.BaseActivity
import com.example.demoaerisproject.view.ComposeSnackbar
import com.example.demoaerisproject.view.ComposeSpinner
import dagger.hilt.android.AndroidEntryPoint
import java.util.*
@AndroidEntryPoint
class LocationSearchActivity : BaseActivity() {
private val viewModel: LocationSearchViewModel by viewModels()
private val DEBOUNCE_LIMIT = 1500L // seconds
private var outlineTextValue: String = ""
override fun onCreate(savedInstanceState: Bundle?) {
setContent {
Box(
Modifier
.fillMaxSize()
.background(Color.Black)
.testTag("init_black_box")
)
}
actionBarTitle = resources.getString(R.string.activity_search)
super.onCreate(savedInstanceState)
}
override fun onResume() {
super.onResume()
viewModel.event.observe(this, Observer(::onViewModelEvent))
}
private fun onViewModelEvent(event: SearchEvent) {
setContent {
when (event) {
is SearchEvent.Success -> {
Render(event)
}
is SearchEvent.InProgress -> {
Render()
ComposeSpinner()
}
is SearchEvent.Error -> {
Render()
ComposeSnackbar(event.msg)
}
}
}
}
@Composable
private fun Render(event: SearchEvent.Success? = null) {
Column(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp, 10.dp, 10.dp, 10.dp)
) {
val focusRequester = remember { FocusRequester() }
val editTextString = remember {
mutableStateOf(
TextFieldValue(
text = outlineTextValue,
selection = TextRange(outlineTextValue.length)
)
)
}
var timer: Timer? = null
val debounce: (str: String) -> Unit = {
timer = Timer()
timer?.apply {
schedule(
object : TimerTask() {
override fun run() {
viewModel.search(it)
cancel()
}
},
DEBOUNCE_LIMIT, 5000
)
}
}
OutlinedTextField(
value = editTextString.value,
label = {
Text(
text = stringResource(id = R.string.text_input),
style = TextStyle(color = Color.Gray)
)
},
onValueChange = {
editTextString.value = it
if (outlineTextValue != it.text) {
timer?.cancel()
debounce(it.text)
outlineTextValue = it.text
}
},
colors = TextFieldDefaults.outlinedTextFieldColors(
textColor = Color.White,
focusedBorderColor = Color.Gray,
unfocusedBorderColor = Color.Gray
),
modifier = Modifier
.testTag("search_text")
.focusRequester(focusRequester)
)
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.CenterEnd
) {
IconButton(onClick = {
viewModel.search(outlineTextValue)
}) {
Icon(
painterResource(id = R.drawable.ic_search),
contentDescription = resources.getString(R.string.activity_search),
tint = Color.White,
modifier = Modifier.padding(0.dp, 10.dp, 10.dp, 0.dp),
)
}
}
}
if (event?.response?.isNotEmpty() == true) {
LazyColumn(
contentPadding = PaddingValues(
horizontal = 16.dp, vertical = 8.dp
)
) {
items(
items = event.response,
itemContent = {
ComposeListPlace(place = it)
})
}
}
}
}
@Composable
private fun ComposeListPlace(place: PlacesResponse) {
val openDialog = remember { mutableStateOf(false) }
Card(
Modifier
.padding(horizontal = 5.dp, vertical = 5.dp)
.fillMaxWidth()
.background(Color.Black)
.clickable {
openDialog.value = true
},
shape = RoundedCornerShape(corner = CornerSize(8.dp))
) {
Column(
modifier = Modifier
.fillMaxWidth()
.background(Color.Black)
) {
place.place.apply {
Text(
text = resources.getString(
R.string.city_state_country,
name ?: city, state, country
),
color = Color.White,
fontSize = 18.sp,
modifier = Modifier.padding(10.dp)
)
}
Divider(color = Color(0xFF808080), thickness = 1.dp)
}
}
if (openDialog.value) {
AlertDialog(onDismissRequest = { openDialog.value = false },
properties = DialogProperties(
dismissOnClickOutside = true,
dismissOnBackPress = true
),
title = { Text(resources.getString(R.string.alert_dlg_confirm_title)) },
text = { Text(resources.getString(R.string.alert_dlg_confirm_desc)) },
confirmButton = {
Button(onClick = {
onDlgConfirm(place)
openDialog.value = false
}) {
Text(text = resources.getString(R.string.alert_dlg_yes))
}
},
dismissButton = {
Button(onClick = {
openDialog.value = false
}) {
Text(text = resources.getString(R.string.alert_dlg_cancel))
}
}
)
}
}
var onDlgConfirm: (myPlace: PlacesResponse?) -> Unit = {
it?.apply {
viewModel.addLocation(
myPlace = MyPlace(
place.name ?: place.city,
place.state,
place.country,
true,
location.lat,
location.lon
)
)
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.menu_search, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menuLocateMe -> {
viewModel.locateMe()
return true
}
R.id.menuMyLocs -> {
startActivity(Intent(this, MyLocsActivity::class.java))
return true
}
}
return super.onOptionsItemSelected(item)
}
} | mit |
senyuyuan/Gluttony | gluttony-realm/src/main/java/sen/yuan/dao/gluttony_realm/realm_save.kt | 1 | 1263 | package sen.yuan.dao.gluttony_realm
import io.realm.RealmObject
/**
* Created by Administrator on 2016/11/23.
*/
/**
* @return 托管状态 的 model
* */
fun <T : RealmObject> T.save(): T {
val mClassAnnotations = this.javaClass.kotlin.annotations
var managedData: T = this
Gluttony.realm.executeTransaction {
// var person = DynamicRealm.getInstance(RealmConfiguration.Builder().build()).createObject("person")
if (mClassAnnotations.firstOrNull { it is Singleton } != null) {
it.delete(this.javaClass)
}
managedData = it.copyToRealm(this@save)
}
return managedData
}
//
///**
// * 对单例模式数据的支持:寻找
// *
// * 注意:必须有@Singleton注解的Int字段
// * */
//inline fun <reified T : RealmObject> T.saveSingleton(): T? {
// var managedData: T = this
// Gluttony.realm.executeTransaction {
// managedData = it.copyToRealm(this@saveSingleton)
// }
// return managedData
//}
/**
* @return 托管状态 的 model
* */
inline fun <reified T : RealmObject> T.updateOrSave(): T {
var managedData: T = this
Gluttony.realm.executeTransaction {
managedData = it.copyToRealmOrUpdate(this@updateOrSave)
}
return managedData
} | apache-2.0 |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/attribute/Slot.kt | 1 | 1840 | /*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.attribute
import com.mcmoonlake.api.Valuable
/**
* ## Slot (槽位)
*
* * Enumeration can be used for attribute item stack modifier takes effect in which slot.
* * 枚举可用于属性物品修改器的生效槽位.
*
* @see [AttributeItemModifier]
* @author lgou2w
* @since 2.0
*/
enum class Slot(
/**
* * Enum type name.
* * 枚举类型名称.
*/
val type: String
) : Valuable<String> {
/**
* * Attribute Slot: Main hand
* * 属性部位: 主手
*/
MAIN_HAND("mainhand"),
/**
* * Attribute Slot: Off hand
* * 属性部位: 副手
*/
OFF_HAND("offhand"),
/**
* * Attribute Slot: Head
* * 属性部位: 头
*/
HEAD("head"),
/**
* * Attribute Slot: Legs
* * 属性部位: 腿
*/
LEGS("legs"),
/**
* * Attribute Slot: Chest
* * 属性部位: 胸
*/
CHEST("chest"),
/**
* * Attribute Slot: Feet
* * 属性部位: 脚
*/
FEET("feet"),
;
override fun value(): String
= type
}
| gpl-3.0 |
nadraliev/DsrWeatherApp | app/src/main/java/soutvoid/com/DsrWeatherApp/domain/triggers/RealmLong.kt | 1 | 351 | package soutvoid.com.DsrWeatherApp.domain.triggers
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import soutvoid.com.DsrWeatherApp.ui.util.getRandomString
import java.io.Serializable
open class RealmLong(
var value: Long = 0,
@PrimaryKey
var id: String = getRandomString()
) : RealmObject(), Serializable | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/hierarchy/class/sub/ObjectFromClass/main.kt | 13 | 345 | open class <caret>A
object B: A()
class MyClass(a: A = run { object: A() {} }) {
init {
object C: A()
}
fun foo(a: A = run { object: A() {} }) {
object D: A()
}
val t = object {
object F: A()
}
}
val bar: Int
get() {
object E: A()
return 0
}
val x = object: A() {
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/moveMemberToCompanionObject/simple.kt | 13 | 81 | // "Move to companion object" "true"
class Test {
<caret>const val foo = ""
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/copyPaste/imports/TopLevelProperty.expected.kt | 13 | 50 | package to
import a.b
import a.c
fun f() = c + b | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/compiler-plugins/parcelize/common/src/org/jetbrains/kotlin/idea/compilerPlugin/parcelize/KotlinParcelizeBundle.kt | 7 | 654 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.compilerPlugin.parcelize
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.kotlin.util.AbstractKotlinBundle
@NonNls
private const val BUNDLE = "messages.KotlinParcelizeBundle"
object KotlinParcelizeBundle : AbstractKotlinBundle(BUNDLE) {
@Nls
@JvmStatic
fun message(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String =
getMessage(key, *params)
}
| apache-2.0 |
mctoyama/PixelServer | src/main/kotlin/org/pixelndice/table/pixelserver/connection/main/state04joingame/State05WaitingQueryGame.kt | 1 | 3209 | package org.pixelndice.table.pixelserver.connection.main.state04joingame
import com.google.common.base.Throwables
import org.apache.logging.log4j.LogManager
import org.hibernate.Session
import org.pixelndice.table.pixelprotocol.Protobuf
import org.pixelndice.table.pixelserver.connection.main.Context
import org.pixelndice.table.pixelserver.connection.main.State
import org.pixelndice.table.pixelserver.connection.main.State03JoinOrHostGame
import org.pixelndice.table.pixelserver.sessionFactory
import org.pixelndice.table.pixelserverhibernate.Game
import org.pixelndice.table.pixelserverhibernate.RPGGameSystem
private val logger = LogManager.getLogger(State05WaitingQueryGame::class.java)
class State05WaitingQueryGame: State {
override fun process(ctx: Context) {
// one get operation
val p = ctx.channel.packet
val resp = Protobuf.Packet.newBuilder()
if (p != null) {
if (p.payloadCase == Protobuf.Packet.PayloadCase.QUERYGAME) {
var session: Session? = null
try {
session = sessionFactory.openSession()
val query = session.createNamedQuery("gameByUUID", Game::class.java)
query.setParameter("uuid", p.queryGame.uuid)
val list = query.list()
if (list.isEmpty()) {
val notFound = Protobuf.GameNotFound.newBuilder()
resp.gameNotFound = notFound.build()
ctx.channel.packet = resp.build()
} else {
val gameFound = list.get(0)
val gameByUUID = Protobuf.GameByUUID.newBuilder()
val game = Protobuf.Game.newBuilder()
game.uuid = p.queryGame.uuid
val gm = Protobuf.Account.newBuilder()
gm.id = gameFound.gm!!.id!!
gm.email = gameFound.gm!!.email
gm.name = gameFound.gm!!.name
game.gm = gm.build()
game.campaign = gameFound.campaign
game.rpgGameSystem = RPGGameSystem.toProtobuf(gameFound.rpgGameSystem)
game.hostname = gameFound.hostname
game.port = gameFound.port
gameByUUID.game = game.build()
resp.gameByUuid = gameByUUID.build()
ctx.channel.packet = resp.build()
}
ctx.state = State03JoinOrHostGame()
}catch (e: Exception){
logger.fatal("Hibernate fatal error!")
logger.fatal(Throwables.getStackTraceAsString(e))
}finally {
session?.close()
}
}else{
logger.error("Expecting QueryGame. Instead Received: $p")
val rend = Protobuf.EndWithError.newBuilder()
rend.reason = "key.expectingquerygame"
resp.setEndWithError(rend)
ctx.channel.packet = resp.build()
}
}
}
} | bsd-2-clause |
flesire/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/labels/LabelFormatException.kt | 2 | 174 | package net.nemerosa.ontrack.model.labels
import net.nemerosa.ontrack.model.exceptions.InputException
class LabelFormatException(message: String) : InputException(message)
| mit |
airbnb/epoxy | epoxy-composesample/src/main/java/com/airbnb/epoxy/compose/sample/ComposableInteropActivity.kt | 1 | 2451 | package com.airbnb.epoxy.compose.sample
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Divider
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.airbnb.epoxy.EpoxyRecyclerView
import com.airbnb.epoxy.composableInterop
import com.airbnb.epoxy.compose.sample.epoxyviews.headerView
class ComposableInteropActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_composable_interop)
val recyclerView: EpoxyRecyclerView = findViewById(R.id.epoxy_recycler_view)
recyclerView.withModels {
headerView {
id("header")
title("Testing Composable in Epoxy")
}
for (i in 0..100) {
composableInterop(id = "compose_text_$i") {
ShowCaption("Caption coming from composable")
}
composableInterop(id = "news_$i") {
NewsStory()
}
}
}
}
}
@Composable
@Preview
fun NewsStory() {
Column(
modifier = Modifier.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Image(
painter = painterResource(id = R.drawable.header),
contentDescription = null
)
ShowCaption("Above Image and below text are coming from Compose in Epoxy")
ShowCaption("Davenport, California")
ShowCaption("December 2021")
Divider(
color = Color(0x859797CF),
thickness = 2.dp,
modifier = Modifier.padding(top = 16.dp)
)
}
}
@Composable
fun ShowCaption(text: String) {
Text(
text,
textAlign = TextAlign.Center,
modifier = Modifier
.padding(4.dp)
.fillMaxWidth()
)
}
| apache-2.0 |
BreakOutEvent/breakout-backend | src/main/java/backend/model/posting/PostingRepository.kt | 1 | 1577 | package backend.model.posting
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.CrudRepository
import org.springframework.data.repository.query.Param
interface PostingRepository : CrudRepository<Posting, Long> {
fun findById(id: Long): Posting
@Query("select p from Posting p inner join p.hashtags h where h.value = :hashtag order by p.id desc")
fun findByHashtag(@Param("hashtag") hashtag: String, pageable: Pageable): List<Posting>
fun findAllByOrderByIdDesc(pageable: Pageable): List<Posting>
fun findByTeamEventIdInOrderByIdDesc(eventIdList: List<Long>, pageable: Pageable): List<Posting>
@Query("select p from Posting p where p.reported = true")
fun findReported(): List<Posting>
fun findAllByUserId(userId: Long): List<Posting>
@Query("select distinct p from Posting p inner join p.comments c where c.user.id = :userId")
fun findAllCommentedByUser(@Param("userId") userId: Long): List<Posting>
@Query("select p from Posting p inner join p.likes l where l.user.id = :userId")
fun findAllLikedByUser(@Param("userId") userId: Long): List<Posting>
@Query("select p from Posting p where p.challenge = :challengeId")
fun findAllByChallengeId(@Param("challengeId") challengeId: Long): List<Posting>
@Query("""
select *
from posting
where team_id = :id
order by id desc
limit 1
""", nativeQuery = true)
fun findLastPostingByTeamId(@Param("id") id: Long): Posting?
}
| agpl-3.0 |
paplorinc/intellij-community | python/src/com/jetbrains/python/testing/PyUnitTest.kt | 6 | 4246 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.testing
import com.intellij.execution.Executor
import com.intellij.execution.configurations.RunProfileState
import com.intellij.execution.configurations.RuntimeConfigurationWarning
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.options.SettingsEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.jetbrains.python.PyNames
import com.jetbrains.python.PythonHelper
import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant
/**
* unittest
*/
class PyUnitTestSettingsEditor(configuration: PyAbstractTestConfiguration) :
PyAbstractTestSettingsEditor(
PyTestSharedForm.create(configuration,
PyTestSharedForm.CustomOption(PyUnitTestConfiguration::pattern.name, PyRunTargetVariant.PATH)
))
class PyUnitTestExecutionEnvironment(configuration: PyUnitTestConfiguration, environment: ExecutionEnvironment) :
PyTestExecutionEnvironment<PyUnitTestConfiguration>(configuration, environment) {
override fun getRunner(): PythonHelper =
// different runner is used for setup.py
if (configuration.isSetupPyBased()) {
PythonHelper.SETUPPY
}
else {
PythonHelper.UNITTEST
}
}
class PyUnitTestConfiguration(project: Project, factory: PyUnitTestFactory) :
PyAbstractTestConfiguration(project, factory,
PythonTestConfigurationsModel.PYTHONS_UNITTEST_NAME) { // Bare functions not supported in unittest: classes only
@ConfigField
var pattern: String? = null
override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState? =
PyUnitTestExecutionEnvironment(this, environment)
override fun createConfigurationEditor(): SettingsEditor<PyAbstractTestConfiguration> =
PyUnitTestSettingsEditor(this)
override fun getCustomRawArgumentsString(forRerun: Boolean): String {
// Pattern can only be used with folders ("all in folder" in legacy terms)
if ((!pattern.isNullOrEmpty()) && target.targetType != PyRunTargetVariant.CUSTOM) {
val path = LocalFileSystem.getInstance().findFileByPath(target.target) ?: return ""
// "Pattern" works only for "discovery" mode and for "rerun" we are using "python" targets ("concrete" tests)
return if (path.isDirectory && !forRerun) "-p $pattern" else ""
}
else {
return ""
}
}
/**
* @return configuration should use runner for setup.py
*/
internal fun isSetupPyBased(): Boolean {
val setupPy = target.targetType == PyRunTargetVariant.PATH && target.target.endsWith(PyNames.SETUP_DOT_PY)
return setupPy
}
// setup.py runner is not id-based
override fun isIdTestBased(): Boolean = !isSetupPyBased()
override fun checkConfiguration() {
super.checkConfiguration()
if (target.targetType == PyRunTargetVariant.PATH && target.target.endsWith(".py") && !pattern.isNullOrEmpty()) {
throw RuntimeConfigurationWarning("Pattern can only be used to match files in folder. Can't use pattern for file.")
}
}
override fun isFrameworkInstalled(): Boolean = true //Unittest is always available
// Unittest does not support filesystem path. It needs qname resolvable against root or working directory
override fun shouldSeparateTargetPath() = false
}
object PyUnitTestFactory : PyAbstractTestFactory<PyUnitTestConfiguration>() {
override fun createTemplateConfiguration(project: Project): PyUnitTestConfiguration = PyUnitTestConfiguration(project, this)
override fun getName(): String = PythonTestConfigurationsModel.PYTHONS_UNITTEST_NAME
} | apache-2.0 |
paplorinc/intellij-community | java/java-tests/testSrc/com/intellij/copyright/JavaCopyrightTest.kt | 6 | 1704 | // 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.copyright
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase
import com.maddyhome.idea.copyright.CopyrightProfile
import com.maddyhome.idea.copyright.psi.UpdateCopyrightFactory
class JavaCopyrightTest : LightPlatformCodeInsightFixtureTestCase() {
fun testMultipleCopyrightsInOneFile() {
myFixture.configureByText(JavaFileType.INSTANCE,
"""
/**
* Copyright JetBrains
*/
/**
* Copyright empty
*/
class A {}
""")
updateCopyright()
myFixture.checkResult("""
/*
* Copyright text
* copyright text
*/
/**
* Copyright empty
*/
class A {}
""")
}
fun testMultipleCopyrightsInOneFileOneRemoved() {
myFixture.configureByText(JavaFileType.INSTANCE,
"""
/*
* Copyright JetBrains
* second line
*/
/*
* Copyright JetBrains
*/
public class A {}
""")
updateCopyright()
myFixture.checkResult("""
/*
* Copyright text
* copyright text
*/
public class A {}
""")
}
@Throws(Exception::class)
private fun updateCopyright() {
val options = CopyrightProfile()
options.notice = "Copyright text\ncopyright text"
options.keyword = "Copyright"
options.allowReplaceRegexp = "JetBrains"
val updateCopyright = UpdateCopyrightFactory.createUpdateCopyright(myFixture.project, myFixture.module,
myFixture.file, options)
updateCopyright!!.prepare()
updateCopyright.complete()
}
} | apache-2.0 |
BreakOutEvent/breakout-backend | src/main/java/backend/controller/ActivationController.kt | 1 | 1406 | package backend.controller
import backend.controller.exceptions.NotFoundException
import backend.model.user.UserService
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/activation")
class ActivationController(private val userService: UserService) {
/**
* POST /activation/user?={token}
* Activates account with given token
*/
@PostMapping("user")
fun activateAccount(@RequestParam token: String): Map<String, String> {
val user = userService.getUserByActivationToken(token) ?: throw NotFoundException("No user with token $token")
userService.activate(user, token)
return mapOf("message" to "success")
}
/**
* POST /activation/email?={token}
* Confirms email change with given token
*/
@PostMapping("email")
fun confirmEmail(@RequestParam token: String): Map<String, String> {
val user = userService.getUserByChangeEmailToken(token)
?: throw NotFoundException("No user with change email token $token")
userService.confirmChangeEmail(user, token)
return mapOf("message" to "success")
}
}
| agpl-3.0 |
nibarius/opera-park-android | app/src/main/java/se/barsk/park/analytics/Analytics.kt | 1 | 654 | package se.barsk.park.analytics
import android.content.Context
import com.google.firebase.analytics.FirebaseAnalytics
import se.barsk.park.ParkApp
/**
* Object for handling all analytics reporting.
*/
class Analytics(context: Context) {
private val fa: FirebaseAnalytics = FirebaseAnalytics.getInstance(context)
fun optOutToggled() = updateOptOutState()
fun logEvent(event: AnalyticsEvent) = fa.logEvent(event.name, event.parameters)
fun setProperty(property: String, value: String) = fa.setUserProperty(property, value)
private fun updateOptOutState() = fa.setAnalyticsCollectionEnabled(ParkApp.storageManager.statsEnabled())
} | mit |
jaredsburrows/android-gif-example | app/src/androidTest/java/com/burrowsapps/gif/search/ui/giflist/GifScreenTest.kt | 1 | 7346 | package com.burrowsapps.gif.search.ui.giflist
import android.content.Context
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onAllNodesWithContentDescription
import androidx.compose.ui.test.onFirst
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextInput
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.burrowsapps.gif.search.MainActivity
import com.burrowsapps.gif.search.R
import com.burrowsapps.gif.search.test.TestFileUtils.MOCK_SERVER_PORT
import com.burrowsapps.gif.search.test.TestFileUtils.getMockGifResponse
import com.burrowsapps.gif.search.test.TestFileUtils.getMockResponse
import com.burrowsapps.gif.search.test.TestFileUtils.getMockWebpResponse
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import dagger.hilt.android.testing.HiltTestApplication
import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import java.net.HttpURLConnection.HTTP_NOT_FOUND
import javax.inject.Inject
@HiltAndroidTest
@Config(application = HiltTestApplication::class)
@RunWith(AndroidJUnit4::class)
class GifScreenTest {
@get:Rule(order = 0)
internal val hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1)
internal var composeTestRule = createAndroidComposeRule<MainActivity>()
@Inject @ApplicationContext internal lateinit var context: Context
private val server = MockWebServer()
@Before
fun setUp() {
hiltRule.inject()
server.apply {
dispatcher = object : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse {
request.path.orEmpty().apply {
return when {
contains(other = "v1/trending") -> getMockResponse(fileName = "/trending_results.json")
contains(other = "v1/search") -> getMockResponse(fileName = "/search_results.json")
endsWith(suffix = ".png") -> getMockWebpResponse(fileName = "/ic_launcher.webp")
endsWith(suffix = ".gif") -> getMockGifResponse(fileName = "/android.gif")
else -> MockResponse().setResponseCode(code = HTTP_NOT_FOUND)
}
}
}
}
start(MOCK_SERVER_PORT)
}
}
@After
fun tearDown() {
server.shutdown()
}
@Test
fun testGifActivityTitleIsShowing() {
composeTestRule.onNodeWithText(text = context.getString(R.string.gif_screen_title))
.assertIsDisplayed()
}
@Test
fun testLicenseMenuOpensLicenseScreen() {
composeTestRule.onNodeWithContentDescription(label = context.getString(R.string.menu_more))
.performClick()
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = context.getString(R.string.license_screen_title))
.performClick()
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = context.getString(R.string.license_screen_title))
.assertIsDisplayed()
}
@Test
fun testGoBackViaHardwareBackButton() {
composeTestRule.onNodeWithText(text = context.getString(R.string.gif_screen_title))
.assertIsDisplayed()
composeTestRule.runOnUiThread {
composeTestRule.activity.onBackPressedDispatcher.onBackPressed()
}
composeTestRule.waitForIdle()
// TODO: assert back
}
@Test
fun testOpensLicenseScreenAndGoBack() {
composeTestRule.onNodeWithContentDescription(label = context.getString(R.string.menu_more))
.performClick()
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = context.getString(R.string.license_screen_title))
.performClick()
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = context.getString(R.string.license_screen_title))
.assertIsDisplayed()
composeTestRule.runOnUiThread {
composeTestRule.activity.onBackPressedDispatcher.onBackPressed()
}
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = context.getString(R.string.gif_screen_title))
.assertIsDisplayed()
}
@Test
fun testTrendingThenClickOpenDialog() {
composeTestRule.onAllNodesWithContentDescription(label = context.getString(R.string.gif_image))
.onFirst().performClick()
composeTestRule.waitForIdle()
// TODO
// composeTestRule.onNode(isDialog()).assertIsDisplayed()
// composeTestRule.onNodeWithText(text = context.getString(R.string.copy_url))
// .assertIsDisplayed()
}
@Test
fun testSearchAndGoBackViaHardwareBackButton() {
composeTestRule.onNodeWithContentDescription(label = context.getString(R.string.menu_search))
.performClick()
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = context.getString(R.string.search_gifs)).performClick()
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = context.getString(R.string.search_gifs))
.performTextInput("hello")
composeTestRule.waitForIdle()
composeTestRule.runOnUiThread {
composeTestRule.activity.onBackPressedDispatcher.onBackPressed()
composeTestRule.activity.onBackPressedDispatcher.onBackPressed()
}
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = context.getString(R.string.gif_screen_title))
.assertIsDisplayed()
}
@Test
fun testSearchAndClickClear() {
composeTestRule.onNodeWithContentDescription(label = context.getString(R.string.menu_search))
.performClick()
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = context.getString(R.string.search_gifs)).performClick()
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = context.getString(R.string.search_gifs))
.performTextInput("hello")
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = "hello").assertIsDisplayed()
composeTestRule.onNodeWithContentDescription(label = context.getString(R.string.menu_close))
.performClick()
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = "hello").assertDoesNotExist()
}
@Test
fun testSearchAndClickBackButtonClear() {
composeTestRule.onNodeWithContentDescription(label = context.getString(R.string.menu_search))
.performClick()
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = context.getString(R.string.search_gifs)).performClick()
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = context.getString(R.string.search_gifs))
.performTextInput("hello")
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = "hello").assertIsDisplayed()
composeTestRule.onNodeWithContentDescription(label = context.getString(R.string.menu_back))
.performClick()
composeTestRule.waitForIdle()
composeTestRule.onNodeWithText(text = "hello").assertDoesNotExist()
}
}
| apache-2.0 |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureHandler.kt | 2 | 11452 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.changeSignature
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMethod
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.parentOfType
import com.intellij.refactoring.HelpID
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.changeSignature.ChangeSignatureHandler
import com.intellij.refactoring.changeSignature.ChangeSignatureUtil
import com.intellij.refactoring.util.CommonRefactoringUtil
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.surroundWith.KotlinSurrounderUtils
import org.jetbrains.kotlin.idea.intentions.isInvokeOperator
import org.jetbrains.kotlin.idea.util.expectedDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
class KotlinChangeSignatureHandler : ChangeSignatureHandler {
override fun findTargetMember(element: PsiElement) = findTargetForRefactoring(element)
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext) {
editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE)
val element = findTargetMember(file, editor) ?: CommonDataKeys.PSI_ELEMENT.getData(dataContext) ?: return
val elementAtCaret = file.findElementAt(editor.caretModel.offset) ?: return
if (element !is KtElement)
throw KotlinExceptionWithAttachments("This handler must be invoked for Kotlin elements only: ${element::class.java}")
.withAttachment("element", element)
invokeChangeSignature(element, elementAtCaret, project, editor)
}
override fun invoke(project: Project, elements: Array<PsiElement>, dataContext: DataContext?) {
val element = elements.singleOrNull()?.unwrapped ?: return
if (element !is KtElement) {
throw KotlinExceptionWithAttachments("This handler must be invoked for Kotlin elements only: ${element::class.java}")
.withAttachment("element", element)
}
val editor = dataContext?.let { CommonDataKeys.EDITOR.getData(it) }
invokeChangeSignature(element, element, project, editor)
}
override fun getTargetNotFoundMessage() = KotlinBundle.message("error.wrong.caret.position.function.or.constructor.name")
companion object {
fun findTargetForRefactoring(element: PsiElement): PsiElement? {
val elementParent = element.parent
if ((elementParent is KtNamedFunction || elementParent is KtClass || elementParent is KtProperty) &&
(elementParent as KtNamedDeclaration).nameIdentifier === element
) return elementParent
if (elementParent is KtParameter &&
elementParent.hasValOrVar() &&
elementParent.parentOfType<KtPrimaryConstructor>()?.valueParameterList === elementParent.parent
) return elementParent
if (elementParent is KtProperty && elementParent.valOrVarKeyword === element) return elementParent
if (elementParent is KtConstructor<*> && elementParent.getConstructorKeyword() === element) return elementParent
element.parentOfType<KtParameterList>()?.let { parameterList ->
return PsiTreeUtil.getParentOfType(parameterList, KtFunction::class.java, KtProperty::class.java, KtClass::class.java)
}
element.parentOfType<KtTypeParameterList>()?.let { typeParameterList ->
return PsiTreeUtil.getParentOfType(typeParameterList, KtFunction::class.java, KtProperty::class.java, KtClass::class.java)
}
val call: KtCallElement? = PsiTreeUtil.getParentOfType(
element,
KtCallExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtConstructorDelegationCall::class.java
)
val calleeExpr = call?.let {
val callee = it.calleeExpression
(callee as? KtConstructorCalleeExpression)?.constructorReferenceExpression ?: callee
} ?: element.parentOfType<KtSimpleNameExpression>()
if (calleeExpr is KtSimpleNameExpression || calleeExpr is KtConstructorDelegationReferenceExpression) {
val bindingContext = element.parentOfType<KtElement>()?.analyze(BodyResolveMode.FULL) ?: return null
if (call?.getResolvedCall(bindingContext)?.resultingDescriptor?.isInvokeOperator == true) return call
val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, calleeExpr as KtReferenceExpression]
if (descriptor is ClassDescriptor || descriptor is CallableDescriptor) return calleeExpr
}
return null
}
fun invokeChangeSignature(element: KtElement, context: PsiElement, project: Project, editor: Editor?) {
val bindingContext = element.analyze(BodyResolveMode.FULL)
val callableDescriptor = findDescriptor(element, project, editor, bindingContext) ?: return
if (callableDescriptor is DeserializedDescriptor) {
return CommonRefactoringUtil.showErrorHint(
project,
editor,
KotlinBundle.message("error.hint.the.read.only.declaration.cannot.be.changed"),
RefactoringBundle.message("changeSignature.refactoring.name"),
"refactoring.changeSignature",
)
}
if (callableDescriptor is JavaCallableMemberDescriptor) {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, callableDescriptor)
if (declaration is PsiClass) {
val message = RefactoringBundle.getCannotRefactorMessage(
RefactoringBundle.message("error.wrong.caret.position.method.or.class.name")
)
CommonRefactoringUtil.showErrorHint(
project,
editor,
message,
RefactoringBundle.message("changeSignature.refactoring.name"),
"refactoring.changeSignature",
)
return
}
assert(declaration is PsiMethod) { "PsiMethod expected: $callableDescriptor" }
ChangeSignatureUtil.invokeChangeSignatureOn(declaration as PsiMethod, project)
return
}
if (callableDescriptor.isDynamic()) {
if (editor != null) {
KotlinSurrounderUtils.showErrorHint(
project,
editor,
KotlinBundle.message("message.change.signature.is.not.applicable.to.dynamically.invoked.functions"),
RefactoringBundle.message("changeSignature.refactoring.name"),
null
)
}
return
}
runChangeSignature(project, editor, callableDescriptor, KotlinChangeSignatureConfiguration.Empty, context, null)
}
private fun getDescriptor(bindingContext: BindingContext, element: PsiElement): DeclarationDescriptor? {
val descriptor = when {
element is KtParameter && element.hasValOrVar() -> bindingContext[BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, element]
element is KtReferenceExpression -> bindingContext[BindingContext.REFERENCE_TARGET, element]
element is KtCallExpression -> element.getResolvedCall(bindingContext)?.resultingDescriptor
else -> bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, element]
}
return if (descriptor is ClassDescriptor) descriptor.unsubstitutedPrimaryConstructor else descriptor
}
fun findDescriptor(element: PsiElement, project: Project, editor: Editor?, bindingContext: BindingContext): CallableDescriptor? {
if (!CommonRefactoringUtil.checkReadOnlyStatus(project, element)) return null
var descriptor = getDescriptor(bindingContext, element)
if (descriptor is MemberDescriptor && descriptor.isActual) {
descriptor = descriptor.expectedDescriptor() ?: descriptor
}
return when (descriptor) {
is PropertyDescriptor -> descriptor
is FunctionDescriptor -> {
if (descriptor.valueParameters.any { it.varargElementType != null }) {
val message = KotlinBundle.message("error.cant.refactor.vararg.functions")
CommonRefactoringUtil.showErrorHint(
project,
editor,
message,
RefactoringBundle.message("changeSignature.refactoring.name"),
HelpID.CHANGE_SIGNATURE
)
return null
}
if (descriptor.kind === SYNTHESIZED) {
val message = KotlinBundle.message("cannot.refactor.synthesized.function", descriptor.name)
CommonRefactoringUtil.showErrorHint(
project,
editor,
message,
RefactoringBundle.message("changeSignature.refactoring.name"),
HelpID.CHANGE_SIGNATURE
)
return null
}
descriptor
}
else -> {
val message = RefactoringBundle.getCannotRefactorMessage(
KotlinBundle.message("error.wrong.caret.position.function.or.constructor.name")
)
CommonRefactoringUtil.showErrorHint(
project,
editor,
message,
RefactoringBundle.message("changeSignature.refactoring.name"),
HelpID.CHANGE_SIGNATURE
)
null
}
}
}
}
}
| apache-2.0 |
Virtlink/aesi | paplj/src/main/kotlin/com/virtlink/paplj/terms/AndTerm.kt | 1 | 1579 | package com.virtlink.paplj.terms
import com.virtlink.terms.*
// GENERATED: This file is generated, do not modify.
/**
* The AndTerm term.
*/
@Suppress("UNCHECKED_CAST")
class AndTerm(
override val lhs: ExprTerm,
override val rhs: ExprTerm)
: Term(), BinOpTerm {
companion object {
/**
* Gets the constructor of this term.
*/
val constructor = TermConstructorOfT("AndTerm", 2, { create(it) })
/**
* Creates a new term from the specified list of child terms.
*
* @param children The list of child terms.
* @return The created term.
*/
@JvmStatic fun create(children: List<ITerm>): AndTerm {
if (children.size != constructor.arity) {
throw IllegalArgumentException("children must be ${constructor.arity} in length")
}
val lhs = children[0] as ExprTerm
val rhs = children[1] as ExprTerm
return AndTerm(lhs, rhs)
}
}
override val constructor: ITermConstructor
get() = Companion.constructor
override val children: List<ITerm> by lazy { ChildrenList() }
private inner class ChildrenList: AbstractList<ITerm>() {
override val size: Int
get() = AndTerm.constructor.arity
override fun get(index: Int): ITerm
= when (index) {
0 -> [email protected]
1 -> [email protected]
else -> throw IndexOutOfBoundsException()
}
}
}
| apache-2.0 |
indianpoptart/RadioControl | OldCode/rootChecker-jun2021.kt | 1 | 1989 | //Check for root first
if (!rootCheck()) {
Log.d("RadioControl-Main","NotRooted")
//toggle.isEnabled = false
toggle.isChecked = false //Uncheck toggle
statusText.setText(R.string.noRoot) //Sets the status text to no root
statusText.setTextColor(ContextCompat.getColor(applicationContext, R.color.status_no_root)) //Sets text to deactivated (RED) color
//Drawer icon
carrierIcon = IconicsDrawable(this, GoogleMaterial.Icon.gmd_error_outline).apply {
colorInt = Color.RED
}
carrierName = "Not Rooted"
}
else{
Log.d("RadioControl-Main","RootedIGuess")
toggle.isChecked = true
//Preference handling
editor.putInt(getString(R.string.preference_app_active), 1)
//UI Handling
statusText.setText(R.string.showEnabled) //Sets the status text to enabled
statusText.setTextColor(ContextCompat.getColor(applicationContext, R.color.status_activated))
carrierIcon = IconicsDrawable(this, GoogleMaterial.Icon.gmd_check_circle).apply {
colorInt = Color.GREEN
}
carrierName = "Rooted"
//Service initialization
applicationContext.startService(bgj)
//Alarm scheduling
alarmUtil.scheduleAlarm(applicationContext)
//Checks if workmode is enabled and starts the Persistence Service, otherwise it registers the broadcast receivers
if (getPrefs.getBoolean(getString(R.string.preference_work_mode), true)) {
val i = Intent(applicationContext, PersistenceService::class.java)
if (Build.VERSION.SDK_INT >= 26) {
applicationContext.startForegroundService(i)
} else {
applicationContext.startService(i)
}
Log.d("RadioControl-Main", "persist Service launched")
} else {
registerForBroadcasts(applicationContext)
}
//Checks if background optimization is enabled and schedules a job
if (getPrefs.getBoolean(getString(R.string.key_preference_settings_battery_opimization), false)) {
scheduleJob()
}
} | gpl-3.0 |
apollographql/apollo-android | apollo-api/src/commonMain/kotlin/com/apollographql/apollo3/api/test/TestResolver.kt | 1 | 4122 | package com.apollographql.apollo3.api.test
import com.apollographql.apollo3.annotations.ApolloExperimental
import com.apollographql.apollo3.annotations.ApolloInternal
import com.apollographql.apollo3.api.CompiledListType
import com.apollographql.apollo3.api.CompiledNamedType
import com.apollographql.apollo3.api.CompiledNotNullType
import com.apollographql.apollo3.api.CompiledType
import com.apollographql.apollo3.api.CustomScalarType
import kotlin.native.concurrent.ThreadLocal
/**
* Implement [TestResolver] to generate fake data during tests.
*/
@ApolloExperimental
interface TestResolver {
/**
* Resolve the given field
*
* @param responseName the name of the field as seen in the json
* @param compiledType the GraphQL type of the field
* @param ctors if [compiledType] is a composite type or any non-null or list combination of a composite type,
* ctors contain a list of constructors for the possible shapes
*
* @return T the Kotlin value for the field. Can be Int, Double, String, List<Any?> or Map<String, Any?> or null
*/
fun <T> resolve(responseName: String, compiledType: CompiledType, ctors: Array<out () -> Map<String, Any?>>?): T
}
@ApolloExperimental
open class DefaultTestResolver : TestResolver {
private val MAX_STACK_SIZE = 256
private val stack = Array<Any>(MAX_STACK_SIZE) { 0 }
private var stackSize = 0
private var intCounter = 0
private var floatCounter = 0.5
private var compositeCounter = 0
private var booleanCounter = false
open fun resolveListSize(path: List<Any>): Int {
return 3
}
open fun resolveInt(path: List<Any>): Int {
return intCounter++
}
open fun resolveString(path: List<Any>): String {
return path.subList(path.indexOfLast { it is String }, path.size).joinToString("")
}
open fun resolveFloat(path: List<Any>): Double {
return floatCounter++
}
open fun resolveBoolean(path: List<Any>): Boolean {
return booleanCounter.also {
booleanCounter = !booleanCounter
}
}
open fun resolveComposite(path: List<Any>, ctors: Array<out () -> Map<String, Any?>>): Map<String, Any?> {
return ctors[(compositeCounter++) % ctors.size]()
}
open fun resolveCustomScalar(path: List<Any>): String {
error("Cannot resolve custom scalar at $path")
}
private fun push(v: Any) {
check(stackSize < MAX_STACK_SIZE) {
"Nesting too deep at ${stack.joinToString(".")}"
}
stack[stackSize++] = v
}
private fun pop() {
stackSize--
stack[stackSize] = 0 // Allow garbage collection
}
private fun <T> resolveInternal(responseName: String, compiledType: CompiledType, ctors: Array<out () -> Map<String, Any?>>?): T {
val path = stack.take(stackSize).toList()
@Suppress("UNCHECKED_CAST")
return when (compiledType) {
is CompiledNotNullType -> resolve(responseName, compiledType.ofType, ctors)
is CompiledListType -> {
0.until(resolveListSize(path)).map { i ->
push(i)
resolveInternal<Any>(responseName, compiledType.ofType, ctors).also {
pop()
}
}
}
is CustomScalarType -> {
resolveCustomScalar(path)
}
is CompiledNamedType -> {
when (compiledType.name) {
"Int" -> resolveInt(path)
"Float" -> resolveFloat(path)
"Boolean" -> resolveBoolean(path)
"String" -> resolveString(path)
"ID" -> resolveString(path)
else -> {
resolveComposite(path, ctors ?: error("no ctors for $responseName"))
}
}
}
} as T
}
override fun <T> resolve(responseName: String, compiledType: CompiledType, ctors: Array<out () -> Map<String, Any?>>?): T {
push(responseName)
return resolveInternal<T>(responseName, compiledType, ctors).also {
pop()
}
}
}
@ThreadLocal
@ApolloExperimental
internal var currentTestResolver: TestResolver? = null
@ApolloExperimental
fun <T> withTestResolver(testResolver: TestResolver, block: () -> T): T {
currentTestResolver = testResolver
return block().also {
currentTestResolver = null
}
}
| mit |
google/iosched | shared/src/main/java/com/google/samples/apps/iosched/shared/domain/settings/GetNotificationsSettingUseCase.kt | 1 | 1343 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.domain.settings
import com.google.samples.apps.iosched.shared.data.prefs.PreferenceStorage
import com.google.samples.apps.iosched.shared.di.IoDispatcher
import com.google.samples.apps.iosched.shared.domain.UseCase
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.first
import javax.inject.Inject
class GetNotificationsSettingUseCase @Inject constructor(
private val preferenceStorage: PreferenceStorage,
@IoDispatcher dispatcher: CoroutineDispatcher
) : UseCase<Unit, Boolean>(dispatcher) {
// TODO use preferToReceiveNotifications as flow
override suspend fun execute(parameters: Unit) =
preferenceStorage.preferToReceiveNotifications.first()
}
| apache-2.0 |
sheaam30/setlist | app/src/test/java/setlist/shea/setlist/TestApp.kt | 1 | 641 | package setlist.shea.setlist
import dagger.android.AndroidInjector
import dagger.android.DaggerApplication
import setlist.shea.domain.di.RoomModule
import setlist.shea.setlist.di.ApplicationModule
import setlist.shea.setlist.di.DaggerApplicationComponent
/**
* Created by Adam on 10/14/2017.
*/
class TestApp : SetListApp() {
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerApplicationComponent
.builder()
.application(this)
.room(RoomModule())
.applicationModule(ApplicationModule())
.build()
}
} | apache-2.0 |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/remote/rating/model/RatingRequest.kt | 2 | 271 | package org.stepik.android.remote.rating.model
import com.google.gson.annotations.SerializedName
class RatingRequest(
@SerializedName("exp")
val exp: Long,
@SerializedName("course")
val course: Long,
@SerializedName("token")
val token: String?
) | apache-2.0 |
allotria/intellij-community | java/java-impl/src/com/intellij/codeInsight/daemon/problems/MemberType.kt | 4 | 806 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.daemon.problems
import com.intellij.psi.*
internal enum class MemberType {
METHOD,
CLASS,
FIELD,
ENUM_CONSTANT;
companion object {
internal fun create(psiMember: PsiMember): MemberType? =
when (psiMember) {
is PsiMethod -> METHOD
is PsiClass -> CLASS
is PsiField -> FIELD
is PsiEnumConstant -> ENUM_CONSTANT
else -> null
}
internal fun create(member: Member): MemberType =
when (member) {
is Member.Method -> METHOD
is Member.Class -> CLASS
is Member.Field -> FIELD
is Member.EnumConstant -> ENUM_CONSTANT
}
}
} | apache-2.0 |
allotria/intellij-community | platform/platform-impl/src/com/intellij/internal/ui/AnimationPanelTestAction.kt | 3 | 20032 | package com.intellij.internal.ui
import com.intellij.icons.AllIcons
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CustomShortcutSet
import com.intellij.openapi.application.ex.ClipboardUtil
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.Disposer
import com.intellij.ui.*
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.JBTextArea
import com.intellij.ui.components.fields.ExpandableTextField
import com.intellij.ui.components.fields.ExtendableTextComponent
import com.intellij.ui.components.panels.HorizontalLayout
import com.intellij.ui.components.panels.OpaquePanel
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.ui.components.panels.Wrapper
import com.intellij.ui.layout.*
import com.intellij.util.animation.*
import com.intellij.util.animation.components.BezierPainter
import com.intellij.util.ui.EmptyIcon
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.awt.geom.Point2D
import java.lang.Math.PI
import java.text.NumberFormat
import java.util.function.Consumer
import javax.swing.Action
import javax.swing.JButton
import javax.swing.JComponent
import javax.swing.SwingConstants
import javax.swing.border.CompoundBorder
import kotlin.math.absoluteValue
import kotlin.math.pow
import kotlin.math.roundToInt
@Suppress("HardCodedStringLiteral")
class AnimationPanelTestAction : DumbAwareAction("Show Animation Panel") {
private class DemoPanel(val disposable: Disposable, val bezier: () -> Easing) : BorderLayoutPanel() {
val textArea: JBTextArea
init {
preferredSize = Dimension(600, 300)
border = JBUI.Borders.emptyLeft(12)
textArea = JBTextArea()
createScrollPaneWithAnimatedActions(textArea)
}
fun load() {
loadStage1()
}
private fun loadStage1() {
val baseColor = UIUtil.getTextFieldForeground()
val showDemoBtn = JButton("Click to start a demo", AllIcons.Process.Step_1).also {
it.border = JBUI.Borders.customLine(baseColor, 1)
it.isContentAreaFilled = false
it.isOpaque = true
}
val showTestPageLnk = ActionLink("or load the testing page")
addToCenter(OpaquePanel(VerticalLayout(15, SwingConstants.CENTER)).also {
it.add(showDemoBtn, VerticalLayout.CENTER)
it.add(showTestPageLnk, VerticalLayout.CENTER)
})
val icons = arrayOf(AllIcons.Process.Step_1, AllIcons.Process.Step_2, AllIcons.Process.Step_3,
AllIcons.Process.Step_4, AllIcons.Process.Step_5, AllIcons.Process.Step_6,
AllIcons.Process.Step_7, AllIcons.Process.Step_8)
val iconAnimator = JBAnimator(disposable).apply {
period = 60
isCyclic = true
type = JBAnimator.Type.EACH_FRAME
ignorePowerSaveMode()
}
iconAnimator.animate(animation(icons, showDemoBtn::setIcon).apply {
duration = iconAnimator.period * icons.size
})
val fadeOutElements = listOf(
transparent(baseColor) {
showDemoBtn.foreground = it
showDemoBtn.border = JBUI.Borders.customLine(it, 1)
},
animation {
val array = showDemoBtn.text.toCharArray()
array.shuffle()
showDemoBtn.text = String(array)
},
transparent(showTestPageLnk.foreground, showTestPageLnk::setForeground).apply {
runWhenScheduled {
showDemoBtn.icon = EmptyIcon.ICON_16
showDemoBtn.isOpaque = false
showDemoBtn.repaint()
Disposer.dispose(iconAnimator)
}
runWhenExpired {
removeAll()
revalidate()
repaint()
}
}
)
showDemoBtn.addActionListener {
animate {
fadeOutElements + animation().runWhenExpired {
loadStage2()
}
}
}
showTestPageLnk.addActionListener {
animate {
fadeOutElements + animation().runWhenExpired {
loadTestPage()
}
}
}
showDemoBtn.addMouseListener(object : MouseAdapter() {
private val consumers = arrayOf(
consumer(DoubleColorFunction(showDemoBtn.background, showDemoBtn.foreground), showDemoBtn::setBackground),
consumer(DoubleColorFunction(showDemoBtn.foreground, showDemoBtn.background), showDemoBtn::setForeground),
)
val animator = JBAnimator()
val statefulEasing = CubicBezierEasing(0.215, 0.61, 0.355, 1.0).stateful()
override fun mouseEntered(e: MouseEvent) {
animator.animate(Animation(*consumers).apply {
duration = 500
easing = statefulEasing.coerceIn(statefulEasing.value, 1.0)
duration = (duration * (1.0 - statefulEasing.value)).roundToInt()
})
}
override fun mouseExited(e: MouseEvent) {
animator.animate(Animation(*consumers).apply {
delay = 50
duration = 450
easing = statefulEasing.coerceIn(0.0, statefulEasing.value).reverse()
duration = (duration * statefulEasing.value).roundToInt()
})
}
})
}
private fun loadStage2() {
val clicks = 2
val buttonDemo = SpringButtonPanel("Here!", Rectangle(width / 2 - 50, 10, 100, 40), clicks) {
[email protected](it)
loadStage3()
}
addToCenter(buttonDemo)
val scroller = ComponentUtil.getScrollPane(textArea) ?: error("text area has no scroll pane")
if (scroller.parent == null) {
textArea.text = """
Hello!
Click the button ${clicks + 1} times.
""".trimIndent()
scroller.preferredSize = Dimension([email protected], 0)
addToTop(scroller)
}
JBAnimator().animate(let {
val to = Dimension([email protected], 100)
animation(scroller.preferredSize, to, scroller::setPreferredSize)
.setEasing(bezier())
.runWhenUpdated {
revalidate()
repaint()
}
})
}
private fun loadStage3() {
val scroller = ComponentUtil.getScrollPane(textArea) ?: error("text area has no scroll pane")
if (scroller.parent == null) {
textArea.text = "Good start!"
scroller.preferredSize = Dimension([email protected], 0)
addToTop(scroller)
}
val oopsText = "Oops... Everything is gone"
val sorryText = """
$oopsText
To check page scroll options insert a text
and press UP or DOWN key.
These values are funny:
0.34, 1.56, 0.64, 1
""".trimIndent()
animate {
type = JBAnimator.Type.EACH_FRAME
makeSequent(
animation(scroller.preferredSize, size, scroller::setPreferredSize).apply {
duration = 500
delay = 500
easing = bezier()
runWhenUpdated {
revalidate()
repaint()
}
},
animation(textArea.text, oopsText, textArea::setText).apply {
duration = ((textArea.text.length + oopsText.length) * 20).coerceAtMost(5_000)
delay = 200
},
animation(oopsText, sorryText, textArea::setText).apply {
duration = ((oopsText.length + sorryText.length) * 20).coerceAtMost(7_500)
delay = 1000
},
animation(size, Dimension(width, height - 30), scroller::setPreferredSize).apply {
delay = 2_500
easing = bezier()
runWhenUpdated {
revalidate()
repaint()
}
runWhenExpired {
val link = ActionLink("Got it! Now, open the test panel") { loadTestPage() }
val foreground = link.foreground
val transparent = ColorUtil.withAlpha(link.foreground, 0.0)
link.foreground = transparent
addToBottom(Wrapper(FlowLayout(), link))
animate(transparent(foreground, link::setForeground).apply {
easing = easing.reverse()
})
}
}
)
}
}
private fun loadTestPage() = hideAllComponentsAndRun {
val linear = FillPanel("Linear")
val custom = FillPanel("Custom")
val content = Wrapper(HorizontalLayout(40)).apply {
border = JBUI.Borders.empty(0, 40)
add(custom, HorizontalLayout.CENTER)
add(linear, HorizontalLayout.CENTER)
}
addToCenter(content)
val animations = listOf(
animation(custom::value::set),
animation(linear::value::set),
animation().runWhenUpdated {
content.repaint()
}
)
val fillers = JBAnimator(disposable)
addToLeft(AnimationSettings { options ->
fillers.period = options.period
fillers.isCyclic = options.cyclic
fillers.type = options.type
animations[0].easing = bezier()
animations[1].easing = Easing.LINEAR
animations.forEach { animation ->
animation.duration = options.duration
animation.delay = options.delay
animation.easing = animation.easing.coerceIn(
options.coerceMin / 100.0,
options.coerceMax / 100.0
)
if (options.inverse) {
animation.easing = animation.easing.invert()
}
if (options.reverse) {
animation.easing = animation.easing.reverse()
}
if (options.mirror) {
animation.easing = animation.easing.mirror()
}
}
fillers.animate(animations)
})
revalidate()
}
private fun hideAllComponentsAndRun(afterFinish: () -> Unit) {
val remover = mutableListOf<Animation>()
val scroller = ComponentUtil.getScrollPane(textArea)
components.forEach { comp ->
if (scroller === comp) {
remover += animation(comp.preferredSize, Dimension(comp.width, 0), comp::setPreferredSize)
.setEasing(bezier())
.runWhenUpdated {
revalidate()
repaint()
}
remover += animation(textArea.text, "", textArea::setText).setEasing { x ->
1 - (1 - x).pow(4.0)
}
remover += transparent(textArea.foreground, textArea::setForeground)
}
else if (comp is Wrapper && comp.targetComponent is ActionLink) {
val link = comp.targetComponent as ActionLink
remover += transparent(link.foreground, link::setForeground)
}
}
remover += animation().runWhenExpired {
removeAll()
afterFinish()
}
remover.forEach {
it.duration = 800
}
animate { remover }
}
private fun createScrollPaneWithAnimatedActions(textArea: JBTextArea): JBScrollPane {
val pane = JBScrollPane(textArea)
val commonAnimator = JBAnimator(disposable)
create("Scroll Down") {
val from: Int = pane.verticalScrollBar.value
val to: Int = from + pane.visibleRect.height
commonAnimator.animate(
animation(from, to, pane.verticalScrollBar::setValue)
.setDuration(350)
.setEasing(bezier())
)
}.registerCustomShortcutSet(CustomShortcutSet.fromString("DOWN"), pane)
create("Scroll Up") {
val from: Int = pane.verticalScrollBar.value
val to: Int = from - pane.visibleRect.height
commonAnimator.animate(
animation(from, to, pane.verticalScrollBar::setValue)
.setDuration(350)
.setEasing(bezier())
)
}.registerCustomShortcutSet(CustomShortcutSet.fromString("UP"), pane)
return pane
}
}
class Options {
var period: Int = 10
var duration: Int = 1000
var delay: Int = 0
var cyclic: Boolean = false
var reverse: Boolean = false
var inverse: Boolean = false
var mirror: Boolean = false
var coerceMin: Int = 0
var coerceMax: Int = 100
var type: JBAnimator.Type = JBAnimator.Type.IN_TIME
}
private class AnimationSettings(val onStart: (Options) -> Unit) : BorderLayoutPanel() {
private val options = Options()
init {
val panel = panel {
row("Duration:") {
spinner(options::duration, 0, 5000, 50)
}
row("Period:") {
spinner(options::period, 5, 1000, 5)
}
row("Delay:") {
spinner(options::delay, 0, 5000, 100)
}
row {
checkBox("Cyclic", options::cyclic)
}
row {
checkBox("Reverse", options::reverse)
}
row {
checkBox("Inverse", options::inverse)
}
row {
checkBox("Mirror", options::mirror)
}
row("Coerce (%)") {
spinner(options::coerceMin, 0, 100, 5)
spinner(options::coerceMax, 0, 100, 5)
}
row {
comboBox(EnumComboBoxModel(JBAnimator.Type::class.java), options::type, listCellRenderer { value, _, _ ->
text = value.toString().split("_").joinToString(" ") {
it.toLowerCase().capitalize()
}
})
}
}
addToCenter(panel)
addToBottom(JButton("Start Animation").apply {
addActionListener {
panel.apply()
onStart(options)
}
})
}
}
private class FillPanel(val description: String) : JComponent() {
var value: Double = 1.0
init {
background = JBColor(0xC2D6F6, 0x455563)
preferredSize = Dimension(40, 0)
border = JBUI.Borders.empty(40, 5, 40, 0)
}
override fun paintComponent(g: Graphics) {
val g2d = g as Graphics2D
val insets = insets
val bounds = g2d.clipBounds.apply {
height -= insets.top + insets.bottom
y += insets.top
}
val fillHeight = (bounds.height * value).roundToInt()
val fillY = bounds.y + bounds.height - fillHeight.coerceAtLeast(0)
g2d.color = background
g2d.fillRect(bounds.x, fillY, bounds.width, fillHeight.absoluteValue)
g2d.color = UIUtil.getPanelBackground()
g2d.stroke = BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0f, floatArrayOf(3f), 0f)
g2d.drawLine(bounds.x, bounds.y, bounds.x + bounds.width, bounds.y)
g2d.drawLine(bounds.x, bounds.y + bounds.height, bounds.x + bounds.width, bounds.y + bounds.height)
val textX = bounds.width
val textY = bounds.y + bounds.height
g2d.color = UIUtil.getPanelBackground()
g2d.font = g2d.font.deriveFont(30f).deriveFont(Font.BOLD)
g2d.rotate(-PI / 2, textX.toDouble(), textY.toDouble())
g2d.drawString(description, textX, textY)
}
}
private class BezierEasingPanel : BorderLayoutPanel() {
private val painter = BezierPainter(0.215, 0.61, 0.355, 1.0).also(this::addToCenter).apply {
border = JBUI.Borders.empty(25)
}
private val display = ExpandableTextField().also(this::addToTop).apply {
isEditable = false
text = getControlPoints(painter).joinToString(transform = format::format)
border = JBUI.Borders.empty(1)
}
init {
border = JBUI.Borders.customLine(UIUtil.getBoundsColor(), 1)
painter.addPropertyChangeListener { e ->
if (e.propertyName.endsWith("ControlPoint")) {
display.text = getControlPoints(painter).joinToString(transform = format::format)
}
}
display.setExtensions(
ExtendableTextComponent.Extension.create(AllIcons.General.Reset, "Reset") {
setControlPoints(painter, listOf(0.215, 0.61, 0.355, 1.0))
},
ExtendableTextComponent.Extension.create(AllIcons.Actions.MenuPaste, "Paste from Clipboard") {
try {
ClipboardUtil.getTextInClipboard()?.let {
setControlPoints(painter, parseControlPoints(it))
}
}
catch (ignore: NumberFormatException) {
animate {
listOf(animation(UIUtil.getErrorForeground(), UIUtil.getTextFieldForeground(), display::setForeground).apply {
duration = 800
easing = Easing { x -> x * x * x }
})
}
}
})
}
fun getEasing() = painter.getEasing()
private fun getControlPoints(bezierPainter: BezierPainter): List<Double> = listOf(
bezierPainter.firstControlPoint.x, bezierPainter.firstControlPoint.y,
bezierPainter.secondControlPoint.x, bezierPainter.secondControlPoint.y,
)
private fun setControlPoints(bezierPainter: BezierPainter, values: List<Double>) {
bezierPainter.firstControlPoint = Point2D.Double(values[0], values[1])
bezierPainter.secondControlPoint = Point2D.Double(values[2], values[3])
}
@Throws(java.lang.NumberFormatException::class)
private fun parseControlPoints(value: String): List<Double> = value.split(",").also {
if (it.size != 4) throw NumberFormatException("Cannot parse $value;")
}.map { it.trim().toDouble() }
companion object {
private val format = NumberFormat.getNumberInstance()
}
}
private class SpringButtonPanel(text: String, start: Rectangle, val until: Int, val onFinish: Consumer<SpringButtonPanel>) : Wrapper() {
val button = JButton(text)
val animator = JBAnimator().apply {
period = 5
type = JBAnimator.Type.IN_TIME
}
val easing = Easing { x -> 1 + 2.7 * (x - 1).pow(3.0) + 1.7 * (x - 1).pow(2.0) }
var turns = 0
init {
button.bounds = start
button.addActionListener {
if (turns >= until) {
flyAway()
} else {
jump()
turns++
}
}
layout = null
add(button)
}
private fun flyAway() {
animator.animate(
animation(button.bounds, Rectangle(width / 2, 0, 0, 0), button::setBounds).apply {
duration = 350
easing = [email protected]
runWhenExpired {
onFinish.accept(this@SpringButtonPanel)
}
}
)
}
private fun jump() {
animator.animate(
animation(button.bounds, generateBounds(), button::setBounds).apply {
duration = 350
easing = [email protected]
}
)
}
private fun generateBounds(): Rectangle {
val size = bounds
val x = (Math.random() * size.width / 2).toInt()
val y = (Math.random() * size.height / 2).toInt()
val width = (Math.random() * (size.width - x)).coerceAtLeast(100.0).toInt()
val height = (Math.random() * (size.height - y)).coerceAtLeast(24.0).toInt()
return Rectangle(x, y, width, height)
}
}
override fun actionPerformed(e: AnActionEvent) {
object : DialogWrapper(e.project) {
val bezier = BezierEasingPanel()
val demo = DemoPanel(disposable, bezier::getEasing)
init {
title = "Animation Panel Test Action"
bezier.border = CompoundBorder(JBUI.Borders.emptyRight(12), bezier.border)
setResizable(true)
init()
window.addWindowListener(object : WindowAdapter() {
override fun windowOpened(e: WindowEvent?) {
demo.load()
window.removeWindowListener(this)
}
})
}
override fun createCenterPanel() = OnePixelSplitter(false, .3f).also { ops ->
ops.firstComponent = bezier
ops.secondComponent = demo
}
override fun createActions() = emptyArray<Action>()
}.show()
}
} | apache-2.0 |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/database/model/UClient.kt | 1 | 4152 | /*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.database.model
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.parcelize.Parcelize
import org.monora.uprotocol.core.protocol.Client
import org.monora.uprotocol.core.protocol.ClientType
import java.io.FileInputStream
import java.security.cert.X509Certificate
@Parcelize
@Entity(tableName = "client")
data class UClient(
@PrimaryKey
var uid: String,
var nickname: String,
var manufacturer: String,
var product: String,
var type: ClientType,
var versionName: String,
var versionCode: Int,
var protocolVersion: Int,
var protocolVersionMin: Int,
var revisionOfPicture: Long,
var lastUsageTime: Long = System.currentTimeMillis(),
var blocked: Boolean = false,
var local: Boolean = false,
var trusted: Boolean = false,
var certificate: X509Certificate? = null,
) : Client, Parcelable {
override fun getClientCertificate(): X509Certificate? = certificate
override fun getClientLastUsageTime(): Long = lastUsageTime
override fun getClientManufacturer(): String = manufacturer
override fun getClientNickname(): String = nickname
override fun getClientProduct(): String = product
override fun getClientProtocolVersion(): Int = protocolVersion
override fun getClientProtocolVersionMin(): Int = protocolVersionMin
override fun getClientType(): ClientType = type
override fun getClientUid(): String = uid
override fun getClientVersionCode(): Int = versionCode
override fun getClientVersionName(): String = versionName
override fun getClientRevisionOfPicture(): Long = revisionOfPicture
override fun isClientBlocked(): Boolean = blocked
override fun isClientLocal(): Boolean = local
override fun isClientTrusted(): Boolean = trusted
override fun setClientBlocked(blocked: Boolean) {
this.blocked = blocked
}
override fun setClientCertificate(certificate: X509Certificate?) {
this.certificate = certificate
}
override fun setClientLastUsageTime(lastUsageTime: Long) {
this.lastUsageTime = lastUsageTime
}
override fun setClientLocal(local: Boolean) {
this.local = local
}
override fun setClientManufacturer(manufacturer: String) {
this.manufacturer = manufacturer
}
override fun setClientNickname(nickname: String) {
this.nickname = nickname
}
override fun setClientProduct(product: String) {
this.product = product
}
override fun setClientProtocolVersion(protocolVersion: Int) {
this.protocolVersion = protocolVersion
}
override fun setClientProtocolVersionMin(protocolVersionMin: Int) {
this.protocolVersionMin = protocolVersionMin
}
override fun setClientRevisionOfPicture(revision: Long) {
this.revisionOfPicture = revision
}
override fun setClientTrusted(trusted: Boolean) {
this.trusted = trusted
}
override fun setClientType(type: ClientType) {
this.type = type
}
override fun setClientUid(uid: String) {
this.uid = uid
}
override fun setClientVersionCode(versionCode: Int) {
this.versionCode = versionCode
}
override fun setClientVersionName(versionName: String) {
this.versionName = versionName
}
}
| gpl-2.0 |
notsyncing/cowherd | cowherd-flex/src/main/kotlin/io/github/notsyncing/cowherd/flex/CowherdScriptManager.kt | 1 | 8815 | package io.github.notsyncing.cowherd.flex
import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner
import io.github.notsyncing.cowherd.models.ActionMethodInfo
import io.github.notsyncing.cowherd.models.RouteInfo
import io.github.notsyncing.cowherd.routing.RouteManager
import io.vertx.core.http.HttpMethod
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.io.Reader
import java.nio.file.*
import java.util.concurrent.Executors
import java.util.logging.Logger
import kotlin.concurrent.thread
import kotlin.reflect.jvm.javaMethod
import kotlin.reflect.jvm.reflect
object CowherdScriptManager {
private const val SCRIPT_EXT = ".cf.kts"
const val TAG_SCRIPT_PATH = "cowherd.flex.route_tag.script_path"
const val TAG_FUNCTION = "cowherd.flex.route_tag.function"
const val TAG_FUNCTION_CLASS = "cowherd.flex.route_tag.function_class"
const val TAG_REAL_FUNCTION = "cowherd.flex.route_tag.real_function"
const val TAG_HTTP_METHOD = "cowherd.flex.route_tag.http_method"
private lateinit var engine: CowherdScriptEngine
private val searchPaths = mutableListOf("$")
var ignoreClasspathScripts = false
private lateinit var watcher: WatchService
private lateinit var watchingThread: Thread
private val watchingPaths = mutableMapOf<WatchKey, Path>()
private var watching = true
private var currentScriptPath: String = ""
private var isInit = true
private val reloadThread = Executors.newSingleThreadExecutor {
Thread(it).apply {
this.name = "cowherd.flex.reloader"
this.isDaemon = true
}
}
private val logger = Logger.getLogger(javaClass.simpleName)
fun addSearchPath(p: Path) {
addSearchPath(p.toAbsolutePath().normalize().toString())
}
fun addSearchPath(p: String) {
if (searchPaths.contains(p)) {
logger.warning("Script search paths already contain $p, will skip adding it.")
return
}
searchPaths.add(p)
if (!isInit) {
loadAndWatchScriptsFromDirectory(p)
}
}
fun init() {
isInit = true
engine = KotlinScriptEngine()
watcher = FileSystems.getDefault().newWatchService()
watching = true
watchingThread = thread(name = "cowherd.flex.watcher", isDaemon = true, block = this::watcherThread)
loadAllScripts()
isInit = false
}
private fun evalScript(reader: Reader, path: String) {
reader.use {
currentScriptPath = path
engine.eval(it)
currentScriptPath = ""
}
}
private fun evalScript(inputStream: InputStream, path: String) {
evalScript(InputStreamReader(inputStream), path)
}
private fun evalScript(file: Path) {
val path = file.toAbsolutePath().normalize().toString()
currentScriptPath = path
engine.loadScript(file)
currentScriptPath = ""
}
private fun loadAndWatchScriptsFromDirectory(path: String) {
val p = Paths.get(path)
var counter = 0
Files.list(p)
.filter { it.fileName.toString().endsWith(SCRIPT_EXT) }
.forEach { f ->
logger.info("Loading script $f")
evalScript(f)
counter++
}
val watchKey = p.register(watcher, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY)
watchingPaths[watchKey] = p
logger.info("Loaded $counter scripts from $path and added them to the watching list.")
}
private fun loadAllScripts() {
watchingPaths.keys.forEach { it.cancel() }
watchingPaths.clear()
for (path in searchPaths) {
if (path == "$") {
if (ignoreClasspathScripts) {
continue
}
val regex = "^(.*?)${SCRIPT_EXT.replace(".", "\\.")}$"
FastClasspathScanner()
.matchFilenamePattern(regex) { relativePath: String, inputStream, _ ->
InputStreamReader(inputStream).use {
logger.info("Loading script $relativePath from classpath")
evalScript(it, relativePath)
}
}
.scan()
} else {
loadAndWatchScriptsFromDirectory(path)
}
}
}
fun registerAction(method: HttpMethod, route: String, code: Function<*>) {
if (RouteManager.containsRoute(RouteInfo(route))) {
logger.warning("Route map already contains an action with route $route, the previous one " +
"will be overwritten!")
}
val routeInfo = RouteInfo(route)
routeInfo.isFastRoute = true
routeInfo.setTag(TAG_SCRIPT_PATH, currentScriptPath)
routeInfo.setTag(TAG_FUNCTION, code.reflect())
routeInfo.setTag(TAG_FUNCTION_CLASS, code)
routeInfo.setTag(TAG_REAL_FUNCTION, code.javaClass.methods.firstOrNull { it.name == "invoke" }
?.apply { this.isAccessible = true })
routeInfo.setTag(TAG_HTTP_METHOD, method)
RouteManager.addRoute(routeInfo, ActionMethodInfo(ScriptActionInvoker::invokeAction.javaMethod))
}
fun destroy() {
watching = false
watcher.close()
watchingThread.interrupt()
RouteManager.removeRouteIf { routeInfo, _ -> routeInfo.hasTag(TAG_SCRIPT_PATH) }
}
fun reset() {
searchPaths.clear()
searchPaths.add("$")
watchingPaths.keys.forEach { it.cancel() }
watchingPaths.clear()
ignoreClasspathScripts = false
}
private fun updateActions(scriptFile: Path, type: WatchEvent.Kind<*>) {
val iter = RouteManager.getRoutes().entries.iterator()
val scriptFilePathStr = scriptFile.toString()
if ((type == StandardWatchEventKinds.ENTRY_MODIFY) || (type == StandardWatchEventKinds.ENTRY_DELETE)) {
while (iter.hasNext()) {
val (info, _) = iter.next()
val path = info.getTag(TAG_SCRIPT_PATH) as String?
if (path == null) {
continue
}
if (Files.isDirectory(scriptFile)) {
if (Paths.get(path).startsWith(scriptFile)) {
iter.remove()
}
} else {
if (path == scriptFilePathStr) {
iter.remove()
}
}
}
}
if (type != StandardWatchEventKinds.ENTRY_DELETE) {
evalScript(scriptFile)
}
logger.info("Script file $scriptFile updated, type $type.")
}
private fun watcherThread() {
while (watching) {
val key: WatchKey
try {
key = watcher.take()
} catch (x: InterruptedException) {
continue
} catch (x: ClosedWatchServiceException) {
if (!watching) {
continue
}
throw x
}
for (event in key.pollEvents()) {
val kind = event.kind()
if (kind == StandardWatchEventKinds.OVERFLOW) {
logger.warning("Script watcher overflow, at ${watchingPaths[key]}")
continue
}
val ev = event as WatchEvent<Path>
val filename = ev.context()
if (!filename.toString().endsWith(SCRIPT_EXT)) {
continue
}
val dir = watchingPaths[key]
if (dir == null) {
logger.warning("We are notified by a path not in the watching list, filename: $filename")
continue
}
try {
val fullPath = dir.resolve(filename)
reloadThread.submit {
try {
updateActions(fullPath, kind)
} catch (e: Exception) {
logger.warning("An exception occured when reloading script $fullPath: ${e.message}")
e.printStackTrace()
}
}
} catch (x: IOException) {
x.printStackTrace()
continue
}
}
val valid = key.reset()
if (!valid) {
continue
}
}
}
} | gpl-3.0 |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/src/internal/ConcurrentLinkedList.kt | 1 | 9055 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlin.jvm.*
import kotlin.native.concurrent.SharedImmutable
/**
* Returns the first segment `s` with `s.id >= id` or `CLOSED`
* if all the segments in this linked list have lower `id`, and the list is closed for further segment additions.
*/
private inline fun <S : Segment<S>> S.findSegmentInternal(
id: Long,
createNewSegment: (id: Long, prev: S?) -> S
): SegmentOrClosed<S> {
/*
Go through `next` references and add new segments if needed, similarly to the `push` in the Michael-Scott
queue algorithm. The only difference is that "CAS failure" means that the required segment has already been
added, so the algorithm just uses it. This way, only one segment with each id can be added.
*/
var cur: S = this
while (cur.id < id || cur.removed) {
val next = cur.nextOrIfClosed { return SegmentOrClosed(CLOSED) }
if (next != null) { // there is a next node -- move there
cur = next
continue
}
val newTail = createNewSegment(cur.id + 1, cur)
if (cur.trySetNext(newTail)) { // successfully added new node -- move there
if (cur.removed) cur.remove()
cur = newTail
}
}
return SegmentOrClosed(cur)
}
/**
* Returns `false` if the segment `to` is logically removed, `true` on a successful update.
*/
@Suppress("NOTHING_TO_INLINE") // Must be inline because it is an AtomicRef extension
private inline fun <S : Segment<S>> AtomicRef<S>.moveForward(to: S): Boolean = loop { cur ->
if (cur.id >= to.id) return true
if (!to.tryIncPointers()) return false
if (compareAndSet(cur, to)) { // the segment is moved
if (cur.decPointers()) cur.remove()
return true
}
if (to.decPointers()) to.remove() // undo tryIncPointers
}
/**
* Tries to find a segment with the specified [id] following by next references from the
* [startFrom] segment and creating new ones if needed. The typical use-case is reading this `AtomicRef` values,
* doing some synchronization, and invoking this function to find the required segment and update the pointer.
* At the same time, [Segment.cleanPrev] should also be invoked if the previous segments are no longer needed
* (e.g., queues should use it in dequeue operations).
*
* Since segments can be removed from the list, or it can be closed for further segment additions.
* Returns the segment `s` with `s.id >= id` or `CLOSED` if all the segments in this linked list have lower `id`,
* and the list is closed.
*/
internal inline fun <S : Segment<S>> AtomicRef<S>.findSegmentAndMoveForward(
id: Long,
startFrom: S,
createNewSegment: (id: Long, prev: S?) -> S
): SegmentOrClosed<S> {
while (true) {
val s = startFrom.findSegmentInternal(id, createNewSegment)
if (s.isClosed || moveForward(s.segment)) return s
}
}
/**
* Closes this linked list of nodes by forbidding adding new ones,
* returns the last node in the list.
*/
internal fun <N : ConcurrentLinkedListNode<N>> N.close(): N {
var cur: N = this
while (true) {
val next = cur.nextOrIfClosed { return cur }
if (next === null) {
if (cur.markAsClosed()) return cur
} else {
cur = next
}
}
}
internal abstract class ConcurrentLinkedListNode<N : ConcurrentLinkedListNode<N>>(prev: N?) {
// Pointer to the next node, updates similarly to the Michael-Scott queue algorithm.
private val _next = atomic<Any?>(null)
// Pointer to the previous node, updates in [remove] function.
private val _prev = atomic(prev)
private val nextOrClosed get() = _next.value
/**
* Returns the next segment or `null` of the one does not exist,
* and invokes [onClosedAction] if this segment is marked as closed.
*/
@Suppress("UNCHECKED_CAST")
inline fun nextOrIfClosed(onClosedAction: () -> Nothing): N? = nextOrClosed.let {
if (it === CLOSED) {
onClosedAction()
} else {
it as N?
}
}
val next: N? get() = nextOrIfClosed { return null }
/**
* Tries to set the next segment if it is not specified and this segment is not marked as closed.
*/
fun trySetNext(value: N): Boolean = _next.compareAndSet(null, value)
/**
* Checks whether this node is the physical tail of the current linked list.
*/
val isTail: Boolean get() = next == null
val prev: N? get() = _prev.value
/**
* Cleans the pointer to the previous node.
*/
fun cleanPrev() { _prev.lazySet(null) }
/**
* Tries to mark the linked list as closed by forbidding adding new nodes after this one.
*/
fun markAsClosed() = _next.compareAndSet(null, CLOSED)
/**
* This property indicates whether the current node is logically removed.
* The expected use-case is removing the node logically (so that [removed] becomes true),
* and invoking [remove] after that. Note that this implementation relies on the contract
* that the physical tail cannot be logically removed. Please, do not break this contract;
* otherwise, memory leaks and unexpected behavior can occur.
*/
abstract val removed: Boolean
/**
* Removes this node physically from this linked list. The node should be
* logically removed (so [removed] returns `true`) at the point of invocation.
*/
fun remove() {
assert { removed } // The node should be logically removed at first.
assert { !isTail } // The physical tail cannot be removed.
while (true) {
// Read `next` and `prev` pointers ignoring logically removed nodes.
val prev = leftmostAliveNode
val next = rightmostAliveNode
// Link `next` and `prev`.
next._prev.value = prev
if (prev !== null) prev._next.value = next
// Checks that prev and next are still alive.
if (next.removed) continue
if (prev !== null && prev.removed) continue
// This node is removed.
return
}
}
private val leftmostAliveNode: N? get() {
var cur = prev
while (cur !== null && cur.removed)
cur = cur._prev.value
return cur
}
private val rightmostAliveNode: N get() {
assert { !isTail } // Should not be invoked on the tail node
var cur = next!!
while (cur.removed)
cur = cur.next!!
return cur
}
}
/**
* Each segment in the list has a unique id and is created by the provided to [findSegmentAndMoveForward] method.
* Essentially, this is a node in the Michael-Scott queue algorithm,
* but with maintaining [prev] pointer for efficient [remove] implementation.
*/
internal abstract class Segment<S : Segment<S>>(val id: Long, prev: S?, pointers: Int): ConcurrentLinkedListNode<S>(prev) {
/**
* This property should return the maximal number of slots in this segment,
* it is used to define whether the segment is logically removed.
*/
abstract val maxSlots: Int
/**
* Numbers of cleaned slots (the lowest bits) and AtomicRef pointers to this segment (the highest bits)
*/
private val cleanedAndPointers = atomic(pointers shl POINTERS_SHIFT)
/**
* The segment is considered as removed if all the slots are cleaned.
* There are no pointers to this segment from outside, and
* it is not a physical tail in the linked list of segments.
*/
override val removed get() = cleanedAndPointers.value == maxSlots && !isTail
// increments the number of pointers if this segment is not logically removed.
internal fun tryIncPointers() = cleanedAndPointers.addConditionally(1 shl POINTERS_SHIFT) { it != maxSlots || isTail }
// returns `true` if this segment is logically removed after the decrement.
internal fun decPointers() = cleanedAndPointers.addAndGet(-(1 shl POINTERS_SHIFT)) == maxSlots && !isTail
/**
* Invoked on each slot clean-up; should not be invoked twice for the same slot.
*/
fun onSlotCleaned() {
if (cleanedAndPointers.incrementAndGet() == maxSlots && !isTail) remove()
}
}
private inline fun AtomicInt.addConditionally(delta: Int, condition: (cur: Int) -> Boolean): Boolean {
while (true) {
val cur = this.value
if (!condition(cur)) return false
if (this.compareAndSet(cur, cur + delta)) return true
}
}
@JvmInline
internal value class SegmentOrClosed<S : Segment<S>>(private val value: Any?) {
val isClosed: Boolean get() = value === CLOSED
@Suppress("UNCHECKED_CAST")
val segment: S get() = if (value === CLOSED) error("Does not contain segment") else value as S
}
private const val POINTERS_SHIFT = 16
@SharedImmutable
private val CLOSED = Symbol("CLOSED")
| apache-2.0 |
googlemaps/android-places-ktx | places-ktx/src/test/java/com/google/android/libraries/places/ktx/model/PhotoMetadataTest.kt | 1 | 1436 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.places.ktx.model
import com.google.android.libraries.places.ktx.api.model.photoMetadata
import org.junit.Assert.assertEquals
import org.junit.Test
internal class PhotoMetadataTest {
@Test
fun testBuilderNoActions() {
val photoMetadata = photoMetadata("reference")
assertEquals("", photoMetadata.attributions)
assertEquals(0, photoMetadata.height)
assertEquals(0, photoMetadata.width)
}
@Test
fun testBuilderWithActions() {
val photoMetadata = photoMetadata("reference") {
setAttributions("attributions")
setWidth(100)
setHeight(100)
}
assertEquals("attributions", photoMetadata.attributions)
assertEquals(100, photoMetadata.height)
assertEquals(100, photoMetadata.width)
}
} | apache-2.0 |
flamurey/koltin-func | src/main/kotlin/com/flamurey/kfunc/core/Either.kt | 1 | 2264 | package com.flamurey.kfunc.core
sealed class Either<out A, out B> : Monad<B> {
class Left<out A>(val value: A) : Either<A, Nothing>() {
override fun get(): Nothing {
throw UnsupportedOperationException()
}
override fun isPresent(): Boolean = false
override fun <B> map(f: (Nothing) -> B): Either<A, B> = this
override fun <B> flatMap(f: (Nothing) -> Monad<B>): Either<A, B> = this
}
class Right<out B>(val value: B) : Either<Nothing, B>() {
override fun get(): B = value
override fun isPresent(): Boolean = true
override fun <C> map(f: (B) -> C): Either<Nothing, C> = Right(f(value))
override fun <C> flatMap(f: (B) -> Monad<C>): Either<Monad<C>, C> {
val m = f(value)
return when (m) {
is Right<C> -> m
else ->
if (m.isPresent()) Right(m.get())
else Left(m)
}
}
}
fun apply(success: (B) -> Unit, fail: (A) -> Unit) : Unit =
when (this) {
is Either.Left<A> -> fail(value)
is Either.Right<B> -> success(value)
}
companion object {
fun <A, B> fail(error: A): Either<A, B> = Left(error)
fun <A, B> success(result: B): Either<A, B> = Right(result)
}
}
fun <A, B, C> Either<A, B>.flatMap(f: (B) -> Either<A, C>): Either<A, C> =
when (this) {
is Either.Left<A> -> this
is Either.Right<B> -> f(value)
}
fun <E, A, B, C> Either<E, A>.map2(other: Either<E, B>, f: (A, B) -> C): Either<E, C> =
when (this) {
is Either.Left<E> -> this
is Either.Right<A> -> when (other) {
is Either.Left<E> -> other
is Either.Right<B> -> Either.Right(f(this.value, other.value))
}
}
fun <A, B> Either<A, B>.getOrElse(other: B): B =
when (this) {
is Either.Right<B> -> value
else -> other
}
fun <A, B> Either<A, B>.orElse(other: B): Either<A, B> =
when (this) {
is Either.Right<B> -> this
else -> Either.Right(other)
}
fun <A> tryDo(f: () -> A): Either<Exception, A> =
try {
Either.Right(f())
} catch (e: Exception) {
Either.Left(e)
}
fun <A, B> Either<Monad<A>, Monad<B>>.codistribute(): Monad<Either<A, B>> =
when (this) {
is Either.Left<Monad<A>> -> value.map { Either.Left(it) }
is Either.Right<Monad<B>> -> value.map { Either.Right(it) }
}
| mit |
zdary/intellij-community | platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/library/ProjectLibraryTableBridgeImpl.kt | 2 | 10405 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.legacyBridge.library
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.roots.libraries.LibraryTablePresentation
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.util.Disposer
import com.intellij.projectModel.ProjectModelBundle
import com.intellij.util.EventDispatcher
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.ide.impl.executeOrQueueOnDispatchThread
import com.intellij.workspaceModel.ide.impl.jps.serialization.getLegacyLibraryName
import com.intellij.workspaceModel.ide.legacyBridge.ProjectLibraryTableBridge
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryId
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryTableId
internal class ProjectLibraryTableBridgeImpl(
private val parentProject: Project
) : ProjectLibraryTableBridge, Disposable {
private val LOG = Logger.getInstance(javaClass)
private val entityStorage: VersionedEntityStorage = WorkspaceModel.getInstance(parentProject).entityStorage
private val dispatcher = EventDispatcher.create(LibraryTable.Listener::class.java)
private val libraryArrayValue = CachedValue<Array<Library>> { storage ->
storage.entities(LibraryEntity::class.java).filter { it.tableId == LibraryTableId.ProjectLibraryTableId }
.mapNotNull { storage.libraryMap.getDataByEntity(it) }
.toList().toTypedArray()
}
init {
val messageBusConnection = project.messageBus.connect(this)
WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(messageBusConnection, object : WorkspaceModelChangeListener {
override fun beforeChanged(event: VersionedStorageChange) {
val changes = event.getChanges(LibraryEntity::class.java).filterProjectLibraryChanges()
.filterIsInstance<EntityChange.Removed<LibraryEntity>>()
if (changes.isEmpty()) return
executeOrQueueOnDispatchThread {
for (change in changes) {
val library = event.storageBefore.libraryMap.getDataByEntity(change.entity)
LOG.debug { "Fire 'beforeLibraryRemoved' event for ${change.entity.name}, library = $library" }
if (library != null) {
dispatcher.multicaster.beforeLibraryRemoved(library)
}
}
}
}
override fun changed(event: VersionedStorageChange) {
val changes = event.getChanges(LibraryEntity::class.java).filterProjectLibraryChanges()
if (changes.isEmpty()) return
executeOrQueueOnDispatchThread {
for (change in changes) {
LOG.debug { "Process library change $change" }
when (change) {
is EntityChange.Added -> {
val alreadyCreatedLibrary = event.storageAfter.libraryMap.getDataByEntity(change.entity) as LibraryBridgeImpl?
val library = if (alreadyCreatedLibrary != null) {
alreadyCreatedLibrary.entityStorage = entityStorage
alreadyCreatedLibrary
}
else {
var newLibrary: LibraryBridge? = null
WorkspaceModel.getInstance(project).updateProjectModelSilent {
newLibrary = it.mutableLibraryMap.getOrPutDataByEntity(change.entity) {
LibraryBridgeImpl(
libraryTable = this@ProjectLibraryTableBridgeImpl,
project = project,
initialId = change.entity.persistentId(),
initialEntityStorage = entityStorage,
targetBuilder = null
)
}
}
newLibrary!!
}
dispatcher.multicaster.afterLibraryAdded(library)
}
is EntityChange.Removed -> {
val library = event.storageBefore.libraryMap.getDataByEntity(change.entity)
if (library != null) {
// TODO There won't be any content in libraryImpl as EntityStore's current was already changed
dispatcher.multicaster.afterLibraryRemoved(library)
Disposer.dispose(library)
}
}
is EntityChange.Replaced -> {
val idBefore = change.oldEntity.persistentId()
val idAfter = change.newEntity.persistentId()
if (idBefore != idAfter) {
val library = event.storageBefore.libraryMap.getDataByEntity(change.oldEntity) as? LibraryBridgeImpl
if (library != null) {
library.entityId = idAfter
dispatcher.multicaster.afterLibraryRenamed(library, getLegacyLibraryName(idBefore))
}
}
}
}
}
}
}
})
}
internal fun loadLibraries() {
val storage = entityStorage.current
val libraries = storage
.entities(LibraryEntity::class.java)
.filter { it.tableId is LibraryTableId.ProjectLibraryTableId }
.filter { storage.libraryMap.getDataByEntity(it) == null }
.map { libraryEntity ->
Pair(libraryEntity, LibraryBridgeImpl(
libraryTable = this@ProjectLibraryTableBridgeImpl,
project = project,
initialId = libraryEntity.persistentId(),
initialEntityStorage = entityStorage,
targetBuilder = null
))
}
.toList()
LOG.debug("Initial load of project-level libraries")
if (libraries.isNotEmpty()) {
WorkspaceModel.getInstance(project).updateProjectModelSilent {
libraries.forEach { (entity, library) ->
it.mutableLibraryMap.addIfAbsent(entity, library)
}
}
libraries.forEach { (_, library) ->
dispatcher.multicaster.afterLibraryAdded(library)
}
}
}
override fun getProject(): Project = parentProject
override fun getLibraries(): Array<Library> = entityStorage.cachedValue(libraryArrayValue)
override fun createLibrary(): Library = createLibrary(null)
override fun createLibrary(name: String?): Library {
if (name == null) error("Creating unnamed project libraries is unsupported")
if (getLibraryByName(name) != null) {
error("Project library named $name already exists")
}
val modifiableModel = modifiableModel
modifiableModel.createLibrary(name)
modifiableModel.commit()
val newLibrary = getLibraryByName(name)
if (newLibrary == null) {
error("Library $name was not created")
}
return newLibrary
}
override fun removeLibrary(library: Library) {
val modifiableModel = modifiableModel
modifiableModel.removeLibrary(library)
modifiableModel.commit()
}
override fun getLibraryIterator(): Iterator<Library> = libraries.iterator()
override fun getLibraryByName(name: String): Library? {
val entity = entityStorage.current.resolve(LibraryId(name, LibraryTableId.ProjectLibraryTableId)) ?: return null
return entityStorage.current.libraryMap.getDataByEntity(entity)
}
override fun getTableLevel(): String = LibraryTablesRegistrar.PROJECT_LEVEL
override fun getPresentation(): LibraryTablePresentation = PROJECT_LIBRARY_TABLE_PRESENTATION
override fun getModifiableModel(): LibraryTable.ModifiableModel =
ProjectModifiableLibraryTableBridgeImpl(
libraryTable = this,
project = project,
originalStorage = entityStorage.current
)
override fun getModifiableModel(diff: WorkspaceEntityStorageBuilder): LibraryTable.ModifiableModel =
ProjectModifiableLibraryTableBridgeImpl(
libraryTable = this,
project = project,
originalStorage = entityStorage.current,
diff = diff,
cacheStorageResult = false
)
override fun addListener(listener: LibraryTable.Listener) = dispatcher.addListener(listener)
override fun addListener(listener: LibraryTable.Listener, parentDisposable: Disposable) =
dispatcher.addListener(listener, parentDisposable)
override fun removeListener(listener: LibraryTable.Listener) = dispatcher.removeListener(listener)
override fun dispose() {
for (library in libraries) {
Disposer.dispose(library)
}
}
companion object {
private fun List<EntityChange<LibraryEntity>>.filterProjectLibraryChanges() =
filter {
when (it) {
is EntityChange.Added -> it.entity.tableId is LibraryTableId.ProjectLibraryTableId
is EntityChange.Removed -> it.entity.tableId is LibraryTableId.ProjectLibraryTableId
is EntityChange.Replaced -> it.oldEntity.tableId is LibraryTableId.ProjectLibraryTableId
}
}
internal val PROJECT_LIBRARY_TABLE_PRESENTATION = object : LibraryTablePresentation() {
override fun getDisplayName(plural: Boolean) = ProjectModelBundle.message("project.library.display.name", if (plural) 2 else 1)
override fun getDescription() = ProjectModelBundle.message("libraries.node.text.project")
override fun getLibraryTableEditorTitle() = ProjectModelBundle.message("library.configure.project.title")
}
private const val LIBRARY_BRIDGE_MAPPING_ID = "intellij.libraries.bridge"
internal val WorkspaceEntityStorage.libraryMap: ExternalEntityMapping<LibraryBridge>
get() = getExternalMapping(LIBRARY_BRIDGE_MAPPING_ID)
internal val WorkspaceEntityStorageDiffBuilder.mutableLibraryMap: MutableExternalEntityMapping<LibraryBridge>
get() = getMutableExternalMapping(LIBRARY_BRIDGE_MAPPING_ID)
internal fun WorkspaceEntityStorage.findLibraryEntity(library: LibraryBridge) =
libraryMap.getEntities(library).firstOrNull() as LibraryEntity?
}
}
| apache-2.0 |
code-helix/slatekit | src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Args.kt | 1 | 5174 | /**
<slate_header>
author: Kishore Reddy
url: www.github.com/code-helix/slatekit
copyright: 2015 Kishore Reddy
license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md
desc: A tool-kit, utility library and server-backend
usage: Please refer to license on github for more info.
</slate_header>
*/
package slatekit.examples
//<doc:import_required>
import slatekit.common.args.Args
import slatekit.common.args.ArgsSchema
//</doc:import_required>
//<doc:import_examples>
import slatekit.results.Success
import slatekit.results.Try
import slatekit.results.getOrElse
//</doc:import_examples>
class Example_Args : Command("args") {
override fun execute(request: CommandRequest) : Try<Any>
{
//<doc:examples>
// Example:
// Given on the the command line:
// -log.level=info -env=dev -text='hello world'
showResults( Args.parse( "-log.level=info -env=dev -text='hello world'") )
// CASE 1: Parse using an action prefixed to the arguments
showResults( Args.parse( "service.action -log.level=info -env=dev -text='hello world'", hasAction = true) )
// CASE 2: Custom prefix and sep e.g. "!" and separator ":"
showResults( Args.parse( "!env=dev !text='hello word' !batch:10 ", prefix = "!", sep = ":") )
// CASE 3a: Check for action/method call in the beginning
val args = Args.parse( "manage.movies.createSample -title='Dark Knight' -date='2013-07-18'", hasAction = true )
showResults( args )
args.onSuccess { args ->
args.getString("title")
args.getLocalDate("date")
}
// CASE 3c: Check for only action name in the beginning.
showResults( Args.parse( "method", prefix = "-", sep = "=", hasAction = true ) )
// CASE 4: No args
showResults( Args.parse( "service.method", prefix = "-", sep = "=", hasAction = true ) )
// CASE 5a: Help request ( "?", "help")
showResults( Args.parse( "?" ) )
// CASE 5b: Help request with method call ( "method.action" ? )
showResults( Args.parse( "service.method help" , hasAction = true ) )
// CASE 6: Version request ( "ver", "version" )
showResults( Args.parse( "version" ) )
// CASE 7: Exit request
showResults( Args.parse( "exit" ) )
// CASE 8: Build up the schema
val schema = ArgsSchema().text("env", "env").flag("log", "log").number("level", "level")
print(schema)
//</doc:examples>
return Success("")
}
//<doc:examples_support>
fun showResults(result:Try<Args>) {
println("RESULTS:")
if(!result.success) {
println("Error parsing args : " + result.desc)
return
}
val args = result.getOrElse { Args.empty() }
println("action : " + args.action)
if(!args.parts.isEmpty()) {
print("parts : ")
var parts = ""
args.parts.forEach{ item -> parts += (item + " ") }
println( parts )
}
println("prefix : '" + args.prefix + "'")
println("separator: '" + args.separator + "'")
println("named : " + args.named.size )
if(!args.named.isEmpty()) {
args.named.forEach { pair ->
println("\t" + pair.key + " " + args.separator + " " + pair.value)
}
}
println("index : " + args.positional.size)
if(!args.positional.isEmpty()) { args.positional.forEach{ item -> println( "\t" + item) } }
if(args.isHelp) println("help")
if(args.isEmpty) println("empty")
if(args.isVersion)println("version")
println()
println()
}
//</doc:examples_support>
/*
//<doc:output>
{{< highlight bat >}}
RESULTS:
action :
prefix : '-'
separator: ':'
named : 3
text : hello world
batch : 10
env : dev
index : 0
RESULTS:
action :
prefix : '!'
separator: '='
named : 3
text = hello word
batch = 10
env = dev
index : 0
RESULTS:
action : area.service.method
parts : area service method
prefix : '-'
separator: '='
named : 3
text = hello word
batch = 10
env = dev
index : 0
RESULTS:
action : service.method
parts : service method
prefix : '-'
separator: '='
named : 3
text = hello word
batch = 10
env = dev
index : 0
RESULTS:
action : method
parts : method
prefix : '-'
separator: '='
named : 0
index : 0
empty
RESULTS:
action : service.method
parts : service method
prefix : '-'
separator: '='
named : 0
index : 0
empty
RESULTS:
action :
prefix : '-'
separator: ':'
named : 0
index : 1
?
help
RESULTS:
action : service.method.help
parts : service method help
prefix : '-'
separator: ':'
named : 0
index : 0
empty
RESULTS:
action :
prefix : '-'
separator: ':'
named : 0
index : 1
version
version
RESULTS:
action :
prefix : '-'
separator: ':'
named : 0
index : 1
{{< /highlight >}}
//</doc:output>
*/
/**
* Sample class to show storing of the command line options.
*
* @param env
* @param text
* @param batch
*/
class SampleOptions(val env:String, val text:String, val batch:Int)
}
| apache-2.0 |
code-helix/slatekit | src/lib/kotlin/slatekit-notifications/src/main/kotlin/slatekit/notifications/email/EmailMessage.kt | 1 | 499 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.notifications.email
data class EmailMessage(
val to: String,
val subject: String,
val body: String,
val html: Boolean
)
| apache-2.0 |
HTWDD/HTWDresden | app/src/main/java/de/htwdd/htwdresden/interfaces/Swipeable.kt | 1 | 59 | package de.htwdd.htwdresden.interfaces
interface Swipeable | mit |
leafclick/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/update/RefreshVFsSynchronously.kt | 1 | 4755 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.update
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangesUtil.CASE_SENSITIVE_FILE_PATH_HASHING_STRATEGY
import com.intellij.openapi.vcs.changes.ContentRevision
import com.intellij.openapi.vcs.update.UpdateFilesHelper.iterateFileGroupFilesDeletedOnServerFirst
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil.markDirtyAndRefresh
import com.intellij.openapi.vfs.VirtualFile
import java.io.File
interface FilePathChange {
val beforePath: FilePath?
val afterPath: FilePath?
}
object RefreshVFsSynchronously {
@JvmStatic
fun updateAllChanged(updatedFiles: UpdatedFiles) {
val collector = FilesCollector()
iterateFileGroupFilesDeletedOnServerFirst(updatedFiles, collector)
refreshDeletedFiles(collector.deletedFiles)
refreshFiles(collector.files)
}
@JvmStatic
fun refreshFiles(files: Collection<File>) {
val toRefresh = files.mapNotNullTo(mutableSetOf()) { findValidParent(it) }
markDirtyAndRefresh(false, false, false, *toRefresh.toTypedArray())
}
private fun refreshDeletedFiles(files: Collection<File>) {
val toRefresh = files.mapNotNullTo(mutableSetOf()) { findValidParent(it.parentFile) }
markDirtyAndRefresh(false, true, false, *toRefresh.toTypedArray())
}
private fun findValidParent(file: File?): VirtualFile? =
generateSequence(file) { it.parentFile }
.mapNotNull { LocalFileSystem.getInstance().findFileByIoFile(it) }
.firstOrNull { it.isValid }
@JvmStatic
fun updateChangesForRollback(changes: List<Change>) = refresh(changes, REVERSED_CHANGE_WRAPPER)
@JvmStatic
fun updateChanges(changes: Collection<Change>) = refresh(changes, CHANGE_WRAPPER)
fun refresh(changes: Collection<FilePathChange>, isRollback: Boolean = false) =
refresh(changes, if (isRollback) REVERSED_FILE_PATH_CHANGE_WRAPPER else FILE_PATH_CHANGE_WRAPPER)
private fun <T> refresh(changes: Collection<T>, wrapper: Wrapper<T>) {
val files = mutableSetOf<File>()
val deletedFiles = mutableSetOf<File>()
changes.forEach { change ->
val beforePath = wrapper.getBeforePath(change)
val afterPath = wrapper.getAfterPath(change)
beforePath?.let {
(if (wrapper.isBeforePathDeleted(change)) deletedFiles else files) += it.ioFile
}
afterPath?.let {
if (it != beforePath) files += it.ioFile
}
}
refreshFiles(files)
refreshDeletedFiles(deletedFiles)
}
}
private val CHANGE_WRAPPER = ChangeWrapper(false)
private val REVERSED_CHANGE_WRAPPER = ChangeWrapper(true)
private val FILE_PATH_CHANGE_WRAPPER = FilePathChangeWrapper(false)
private val REVERSED_FILE_PATH_CHANGE_WRAPPER = FilePathChangeWrapper(true)
private class ChangeWrapper(private val isReversed: Boolean) : Wrapper<Change> {
private fun getBeforeRevision(change: Change): ContentRevision? = change.run { if (isReversed) afterRevision else beforeRevision }
private fun getAfterRevision(change: Change): ContentRevision? = change.run { if (isReversed) beforeRevision else afterRevision }
override fun getBeforePath(change: Change): FilePath? = getBeforeRevision(change)?.file
override fun getAfterPath(change: Change): FilePath? = getAfterRevision(change)?.file
override fun isBeforePathDeleted(change: Change): Boolean =
change.run { getAfterRevision(this) == null || isMoved || isRenamed || isIsReplaced }
}
private class FilePathChangeWrapper(private val isReversed: Boolean) : Wrapper<FilePathChange> {
override fun getBeforePath(change: FilePathChange): FilePath? = change.run { if (isReversed) afterPath else beforePath }
override fun getAfterPath(change: FilePathChange): FilePath? = change.run { if (isReversed) beforePath else afterPath }
override fun isBeforePathDeleted(change: FilePathChange): Boolean =
change.let { getAfterPath(it) == null || !CASE_SENSITIVE_FILE_PATH_HASHING_STRATEGY.equals(getBeforePath(it), getAfterPath(it)) }
}
private interface Wrapper<T> {
fun getBeforePath(change: T): FilePath?
fun getAfterPath(change: T): FilePath?
fun isBeforePathDeleted(change: T): Boolean
}
private class FilesCollector : UpdateFilesHelper.Callback {
val files = mutableSetOf<File>()
val deletedFiles = mutableSetOf<File>()
override fun onFile(filePath: String, groupId: String) {
val file = File(filePath)
if (FileGroup.REMOVED_FROM_REPOSITORY_ID == groupId || FileGroup.MERGED_WITH_TREE_CONFLICT.endsWith(groupId)) {
deletedFiles.add(file)
}
else {
files.add(file)
}
}
} | apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/defaultValues/lambdaInlining/simpleErasedStaticInstance.kt | 1 | 323 | // FILE: 1.kt
// LANGUAGE_VERSION: 1.2
// SKIP_INLINE_CHECK_IN: inlineFun$default
package test
inline fun inlineFun(lambda: () -> Any = { "OK" as Any }): Any {
return lambda()
}
// FILE: 2.kt
// CHECK_CONTAINS_NO_CALLS: box except=throwCCE;isType
import test.*
fun box(): String {
return inlineFun() as String
} | apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/extensionFunctions/kt1776.kt | 2 | 308 | interface Expr {
public fun ttFun() : Int = 12
}
class Num(val value : Int) : Expr
fun Expr.sometest() : Int {
if (this is Num) {
value
return value
}
return 0;
}
fun box() : String {
if (Num(11).sometest() != 11) return "fail ${Num(11).sometest()}"
return "OK"
} | apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/classLiteral/bound/simple.kt | 2 | 167 | // IGNORE_BACKEND: NATIVE
fun box(): String {
val x: CharSequence = ""
val klass = x::class
return if (klass == String::class) "OK" else "Fail: $klass"
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/parameterInfo/functionCall/Conflicting.kt | 13 | 548 | // Possible parameter info, for index, lambda and arguments.
// Test is flaky without the fix. In IDEA there's a blinking without the fix with different popups.
fun foo(a: A) {
a.subscribe(object : L {
override fun on() {
withLambda {
<caret>arrayOf(1)[0]
}
}
})
}
fun withLambda(a: (Int) -> Unit) {}
interface L {
fun on()
}
class A {
fun subscribe(listener: L) {}
}
/*
Text: (<highlight>a: (Int) -> Unit</highlight>), Disabled: false, Strikeout: false, Green: true
*/
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/addJvmNameAnnotation/topLevel.kt | 4 | 273 | // "Add '@JvmName' annotation" "true"
// WITH_STDLIB
fun <caret>bar(foo: List<String>): String {
return "1"
}
fun bar(foo: List<Int>): String {
return "2"
}
fun bar1(foo: List<Int>): String {
return "3"
}
fun bar2(foo: List<Int>): String {
return "4"
}
| apache-2.0 |
smmribeiro/intellij-community | platform/lang-api/src/com/intellij/ide/bookmark/BookmarkType.kt | 1 | 5348 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.bookmark
import com.intellij.ide.ui.UISettings
import com.intellij.lang.LangBundle
import com.intellij.openapi.editor.colors.EditorColorsUtil
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.ui.RegionPainter
import com.intellij.ui.IconWrapperWithToolTip
import com.intellij.ui.JBColor
import com.intellij.ui.paint.RectanglePainter
import com.intellij.util.ui.RegionPaintIcon
import java.awt.Component
import java.awt.Graphics2D
import java.awt.RenderingHints
import java.awt.geom.Path2D
import javax.swing.Icon
enum class BookmarkType(val mnemonic: Char, private val painter: RegionPainter<Component?>) {
DIGIT_1('1'), DIGIT_2('2'), DIGIT_3('3'), DIGIT_4('4'), DIGIT_5('5'),
DIGIT_6('6'), DIGIT_7('7'), DIGIT_8('8'), DIGIT_9('9'), DIGIT_0('0'),
LETTER_A('A'), LETTER_B('B'), LETTER_C('C'), LETTER_D('D'),
LETTER_E('E'), LETTER_F('F'), LETTER_G('G'), LETTER_H('H'),
LETTER_I('I'), LETTER_J('J'), LETTER_K('K'), LETTER_L('L'),
LETTER_M('M'), LETTER_N('N'), LETTER_O('O'), LETTER_P('P'),
LETTER_Q('Q'), LETTER_R('R'), LETTER_S('S'), LETTER_T('T'),
LETTER_U('U'), LETTER_V('V'), LETTER_W('W'),
LETTER_X('X'), LETTER_Y('Y'), LETTER_Z('Z'),
DEFAULT(0.toChar(), BookmarkPainter());
constructor(mnemonic: Char) : this(mnemonic, MnemonicPainter(mnemonic.toString()))
val icon by lazy { createIcon(16, 1) }
val gutterIcon by lazy { createIcon(12, 0) }
private fun createIcon(size: Int, insets: Int): Icon = IconWrapperWithToolTip(
RegionPaintIcon(size, size, insets, painter).withIconPreScaled(false),
LangBundle.messagePointer("tooltip.bookmarked"))
companion object {
@JvmStatic
fun get(mnemonic: Char) = values().firstOrNull { it.mnemonic == mnemonic } ?: DEFAULT
}
}
private val BOOKMARK_ICON_BACKGROUND = EditorColorsUtil.createColorKey("Bookmark.iconBackground", JBColor(0xF7C777, 0xAA8542))
private class BookmarkPainter : RegionPainter<Component?> {
override fun toString() = "BookmarkIcon"
override fun hashCode() = toString().hashCode()
override fun equals(other: Any?) = other === this || other is BookmarkPainter
override fun paint(g: Graphics2D, x: Int, y: Int, width: Int, height: Int, c: Component?) {
val background = EditorColorsUtil.getColor(c, BOOKMARK_ICON_BACKGROUND)
if (background != null) {
val xL = width / 6f
val xR = width - xL
val xC = width / 2f
val yT = height / 24f
val yB = height - yT
val yC = yB + xL - xC
val path = Path2D.Float()
path.moveTo(x + xL, y + yT)
path.lineTo(x + xL, y + yB)
path.lineTo(x + xC, y + yC)
path.lineTo(x + xR, y + yB)
path.lineTo(x + xR, y + yT)
path.closePath()
g.paint = background
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g.fill(path)
}
}
}
private val MNEMONIC_ICON_FOREGROUND = EditorColorsUtil.createColorKey("Bookmark.Mnemonic.iconForeground", JBColor(0x000000, 0xBBBBBB))
private val MNEMONIC_ICON_BACKGROUND = EditorColorsUtil.createColorKey("Bookmark.Mnemonic.iconBackground", JBColor(0xFEF7EC, 0x5B5341))
private val MNEMONIC_ICON_BORDER_COLOR = EditorColorsUtil.createColorKey("Bookmark.Mnemonic.iconBorderColor", JBColor(0xF4AF3D, 0xD9A343))
private class MnemonicPainter(val mnemonic: String) : RegionPainter<Component?> {
override fun toString() = "BookmarkMnemonicIcon:$mnemonic"
override fun hashCode() = mnemonic.hashCode()
override fun equals(other: Any?): Boolean {
if (other === this) return true
val painter = other as? MnemonicPainter ?: return false
return painter.mnemonic == mnemonic
}
override fun paint(g: Graphics2D, x: Int, y: Int, width: Int, height: Int, c: Component?) {
val foreground = EditorColorsUtil.getColor(c, MNEMONIC_ICON_FOREGROUND)
val background = EditorColorsUtil.getColor(c, MNEMONIC_ICON_BACKGROUND)
val borderColor = EditorColorsUtil.getColor(c, MNEMONIC_ICON_BORDER_COLOR)
val divisor = Registry.intValue("ide.mnemonic.icon.round", 0)
val round = if (divisor > 0) width.coerceAtLeast(height) / divisor else null
if (background != null) {
g.paint = background
RectanglePainter.FILL.paint(g, x, y, width, height, round)
}
if (foreground != null) {
g.paint = foreground
UISettings.setupAntialiasing(g)
val frc = g.fontRenderContext
val font = EditorFontType.PLAIN.globalFont
val size1 = .8f * height
val vector1 = font.deriveFont(size1).createGlyphVector(frc, mnemonic)
val bounds1 = vector1.visualBounds
val size2 = .8f * size1 * size1 / bounds1.height.toFloat()
val vector2 = font.deriveFont(size2).createGlyphVector(frc, mnemonic)
val bounds2 = vector2.visualBounds
val dx = x - bounds2.x + .5 * (width - bounds2.width)
val dy = y - bounds2.y + .5 * (height - bounds2.height)
g.drawGlyphVector(vector2, dx.toFloat(), dy.toFloat())
}
if (borderColor != null && borderColor != background) {
g.paint = borderColor
RectanglePainter.DRAW.paint(g, x, y, width, height, round)
}
}
}
| apache-2.0 |
smmribeiro/intellij-community | jvm/jvm-analysis-kotlin-tests/testData/codeInspection/nonNls/LiteralsInNonNlsClass.kt | 19 | 323 | import org.jetbrains.annotations.NonNls
@NonNls
class LiteralsInNonNlsClass {
var field = "field"
fun method(param: String = "paramDefaultValue"): String {
field = "field"
val variable = "var"
variable.plus("plus")
variable == "equalityOperator"
variable.equals("equals")
return "return"
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/addImport/DropExplicitImports2.dependency.kt | 13 | 84 | package dependency
fun function(){}
val property: Int = 0
class Class1
class Class2 | apache-2.0 |
smmribeiro/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/notification/GrazieNotificationComponent.kt | 7 | 567 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.grazie.ide.notification
import com.intellij.grazie.GrazieConfig
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
private class GrazieNotificationComponent : StartupActivity.Background {
override fun runActivity(project: Project) {
if (GrazieConfig.get().hasMissedLanguages()) {
GrazieToastNotifications.showMissedLanguages(project)
}
}
}
| apache-2.0 |
smmribeiro/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/dataLoader.kt | 9 | 1084 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.plugins
import com.intellij.util.lang.ZipFilePool
import org.jetbrains.annotations.ApiStatus
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
@ApiStatus.Internal
interface DataLoader {
val pool: ZipFilePool?
val emptyDescriptorIfCannotResolve: Boolean
get() = false
fun isExcludedFromSubSearch(jarFile: Path): Boolean = false
fun load(path: String): InputStream?
override fun toString(): String
}
@ApiStatus.Internal
class LocalFsDataLoader(val basePath: Path) : DataLoader {
override val pool: ZipFilePool?
get() = ZipFilePool.POOL
override val emptyDescriptorIfCannotResolve: Boolean
get() = true
override fun load(path: String): InputStream? {
return try {
Files.newInputStream(basePath.resolve(path))
}
catch (e: NoSuchFileException) {
null
}
}
override fun toString() = basePath.toString()
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/completion/tests/testData/handlers/multifile/JetClassCompletionImport-2.kt | 13 | 34 | package forimport
class TTTest {} | apache-2.0 |
smmribeiro/intellij-community | plugins/gradle/native/tooling/testSources/org/jetbrains/plugins/gradle/nativeplatform/tooling/model/DeterminedEntityGenerator.kt | 13 | 965 | // 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.gradle.nativeplatform.tooling.model
import java.util.*
import kotlin.collections.LinkedHashSet
class DeterminedEntityGenerator {
private val alphaNum = ('a'..'z') + ('A'..'Z') + ('0'..'9')
private val strings = LinkedHashSet<String>()
private val random = Random(0)
fun nextInt(lower: Int, upper: Int) =
random.nextInt(upper - lower) + lower
fun nextBoolean() = random.nextBoolean()
fun nextString(length: Int) = (1..length)
.map { random.nextInt(alphaNum.size) }
.map(alphaNum::get)
.joinToString("")
tailrec fun nextUString(minLength: Int): String {
repeat(100) {
val string = nextString(minLength)
if (!strings.contains(string)) {
strings.add(string)
return string
}
}
return nextUString(minLength + 1)
}
} | apache-2.0 |
smmribeiro/intellij-community | platform/vcs-log/graph/test/com/intellij/vcs/log/graph/impl/print/PrintElementGeneratorTest.kt | 22 | 3879 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.graph.impl.print
import com.intellij.util.NotNullFunction
import com.intellij.vcs.log.graph.AbstractTestWithTwoTextFile
import com.intellij.vcs.log.graph.api.elements.GraphEdge
import com.intellij.vcs.log.graph.api.elements.GraphElement
import com.intellij.vcs.log.graph.api.elements.GraphNode
import com.intellij.vcs.log.graph.api.printer.PrintElementManager
import com.intellij.vcs.log.graph.asString
import com.intellij.vcs.log.graph.impl.permanent.GraphLayoutBuilder
import com.intellij.vcs.log.graph.impl.print.elements.PrintElementWithGraphElement
import com.intellij.vcs.log.graph.parser.LinearGraphParser
import com.intellij.vcs.log.graph.utils.LinearGraphUtils
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.*
open class PrintElementGeneratorTest : AbstractTestWithTwoTextFile("elementGenerator") {
class TestPrintElementManager(private val myGraphElementComparator: Comparator<GraphElement>) : PrintElementManager {
override fun isSelected(printElement: PrintElementWithGraphElement): Boolean {
return false
}
override fun getColorId(element: GraphElement): Int {
if (element is GraphNode) {
return element.nodeIndex
}
if (element is GraphEdge) {
val normalEdge = LinearGraphUtils.asNormalEdge(element)
if (normalEdge != null) return normalEdge.up + normalEdge.down
return LinearGraphUtils.getNotNullNodeIndex(element)
}
throw IllegalStateException("Incorrect graph element type: " + element)
}
override fun getGraphElementComparator(): Comparator<GraphElement> {
return myGraphElementComparator
}
}
override fun runTest(`in`: String, out: String) {
runTest(`in`, out, 7, 2, 10)
}
private fun runTest(`in`: String, out: String, longEdgeSize: Int, visiblePartSize: Int, edgeWithArrowSize: Int) {
val graph = LinearGraphParser.parse(`in`)
val graphLayout = GraphLayoutBuilder.build(graph) { o1, o2 -> o1.compareTo(o2) }
val graphElementComparator = GraphElementComparatorByLayoutIndex(
NotNullFunction<Int, Int> { nodeIndex -> graphLayout.getLayoutIndex(nodeIndex!!) }
)
val elementManager = TestPrintElementManager(graphElementComparator)
val printElementGenerator = PrintElementGeneratorImpl(graph, elementManager, longEdgeSize, visiblePartSize, edgeWithArrowSize)
val actual = printElementGenerator.asString(graph.nodesCount())
assertEquals(out, actual)
}
@Test
fun oneNode() {
doTest("oneNode")
}
@Test
fun manyNodes() {
doTest("manyNodes")
}
@Test
fun longEdges() {
doTest("longEdges")
}
@Test
fun specialElements() {
doTest("specialElements")
}
// oneUpOneDown tests were created in order to investigate some arrow behavior in upsource
@Test
fun oneUpOneDown1() {
val testName = "oneUpOneDown1"
runTest(loadText(testName + AbstractTestWithTwoTextFile.IN_POSTFIX), loadText(testName + AbstractTestWithTwoTextFile.OUT_POSTFIX), 7, 1,
10)
}
@Test
fun oneUpOneDown2() {
val testName = "oneUpOneDown2"
runTest(loadText(testName + AbstractTestWithTwoTextFile.IN_POSTFIX), loadText(testName + AbstractTestWithTwoTextFile.OUT_POSTFIX), 10,
1, 10)
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/function/funVarargAndNormalParam.kt | 4 | 79 | <warning descr="SSR">fun x(vararg y: Int, z: Int) { println(y + z) }</warning>
| apache-2.0 |
fabmax/kool | kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/gl/ShaderGeneratorImplGL.kt | 1 | 9414 | package de.fabmax.kool.platform.gl
import de.fabmax.kool.KoolContext
import de.fabmax.kool.pipeline.*
import de.fabmax.kool.pipeline.shadermodel.CodeGenerator
import de.fabmax.kool.pipeline.shadermodel.ShaderGenerator
import de.fabmax.kool.pipeline.shadermodel.ShaderGraph
import de.fabmax.kool.pipeline.shadermodel.ShaderModel
class ShaderGeneratorImplGL : ShaderGenerator() {
override fun generateShader(model: ShaderModel, pipelineLayout: Pipeline.Layout, ctx: KoolContext): ShaderCode {
val (vs, fs) = generateCode(model, pipelineLayout)
return ShaderCode(ShaderCode.GlCode(vs, fs))
}
private fun generateCode(model: ShaderModel, pipelineLayout: Pipeline.Layout): Pair<String, String> {
val vertShader = generateVertexShaderCode(model, pipelineLayout)
val fragShader = generateFragmentShaderCode(model, pipelineLayout)
if (model.dumpCode) {
println("Vertex shader:\n$vertShader")
println("Fragment shader:\n$fragShader")
}
return vertShader to fragShader
}
private fun generateVertexShaderCode(model: ShaderModel, pipelineLayout: Pipeline.Layout): String {
val codeGen = CodeGen()
model.vertexStageGraph.generateCode(codeGen)
return """
#version 300 es
${model.infoStr()}
// descriptor layout / uniforms ${generateDescriptorBindings(pipelineLayout, ShaderStage.VERTEX_SHADER)}
// vertex attributes ${generateAttributeBindings(pipelineLayout)}
// outputs ${model.vertexStageGraph.generateStageOutputs()}
// functions
${codeGen.generateFunctions()}
void main() {
${codeGen.generateMain()}
gl_Position = ${model.vertexStageGraph.positionOutput.variable.ref4f()};
}
""".trimIndent()
}
private fun generateFragmentShaderCode(model: ShaderModel, pipelineLayout: Pipeline.Layout): String {
val codeGen = CodeGen()
model.fragmentStageGraph.generateCode(codeGen)
return """
#version 300 es
precision highp float;
precision highp sampler2DShadow;
${model.infoStr()}
// descriptor layout / uniforms ${generateDescriptorBindings(pipelineLayout, ShaderStage.FRAGMENT_SHADER)}
// inputs ${model.fragmentStageGraph.generateStageInputs()}
// functions
${codeGen.generateFunctions()}
void main() {
${codeGen.generateMain()}
}
""".trimIndent()
}
private fun ShaderModel.infoStr(): String {
return modelName.lines().joinToString { "// $it\n"}
}
private fun generateDescriptorBindings(pipelineLayout: Pipeline.Layout, stage: ShaderStage): String {
val srcBuilder = StringBuilder("\n")
pipelineLayout.descriptorSets.forEach { set ->
set.descriptors.forEach { desc ->
if (desc.stages.contains(stage)) {
when (desc) {
is UniformBuffer -> srcBuilder.append(generateUniformBuffer(desc))
is TextureSampler1d -> srcBuilder.append(generateTextureSampler1d(desc))
is TextureSampler2d -> srcBuilder.append(generateTextureSampler2d(desc))
is TextureSampler3d -> srcBuilder.append(generateTextureSampler3d(desc))
is TextureSamplerCube -> srcBuilder.append(generateTextureSamplerCube(desc))
}
}
}
}
// WebGL doesn't have an equivalent for push constants, generate standard uniforms instead
val pushConstants = pipelineLayout.pushConstantRanges.filter { it.stages.contains(stage) }
if (pushConstants.isNotEmpty()) {
pipelineLayout.pushConstantRanges.forEach { pcr ->
pcr.pushConstants.forEach { u ->
srcBuilder.appendln("uniform ${u.declare()};")
}
}
}
return srcBuilder.toString()
}
private fun generateUniformBuffer(desc: UniformBuffer): String {
// fixme: implement support for UBOs (supported by WebGL2), for now individual uniforms are used
val srcBuilder = StringBuilder()
desc.uniforms.forEach { u ->
srcBuilder.appendln("uniform ${u.declare()};")
}
return srcBuilder.toString()
}
private fun generateTextureSampler1d(desc: TextureSampler1d): String {
val arraySuffix = if (desc.arraySize > 1) { "[${desc.arraySize}]" } else { "" }
return "uniform sampler2D ${desc.name}$arraySuffix;\n"
}
private fun generateTextureSampler2d(desc: TextureSampler2d): String {
val samplerType = if (desc.isDepthSampler) "sampler2DShadow" else "sampler2D"
val arraySuffix = if (desc.arraySize > 1) { "[${desc.arraySize}]" } else { "" }
return "uniform $samplerType ${desc.name}$arraySuffix;\n"
}
private fun generateTextureSampler3d(desc: TextureSampler3d): String {
val arraySuffix = if (desc.arraySize > 1) { "[${desc.arraySize}]" } else { "" }
return "uniform sampler3D ${desc.name}$arraySuffix;\n"
}
private fun generateTextureSamplerCube(desc: TextureSamplerCube): String {
val samplerType = if (desc.isDepthSampler) "samplerCubeShadow" else "samplerCube"
val arraySuffix = if (desc.arraySize > 1) { "[${desc.arraySize}]" } else { "" }
return "uniform $samplerType ${desc.name}$arraySuffix;\n"
}
private fun generateAttributeBindings(pipelineLayout: Pipeline.Layout): String {
val srcBuilder = StringBuilder("\n")
pipelineLayout.vertices.bindings.forEach { binding ->
binding.vertexAttributes.forEach { attr ->
srcBuilder.appendln("layout(location=${attr.location}) in ${attr.type.glslType} ${attr.name};")
}
}
return srcBuilder.toString()
}
private fun ShaderGraph.generateStageInputs(): String {
val srcBuilder = StringBuilder("\n")
inputs.forEach {
val flat = if (it.isFlat) "flat" else ""
srcBuilder.appendln("$flat in ${it.variable.glslType()} ${it.variable.name};")
}
return srcBuilder.toString()
}
private fun ShaderGraph.generateStageOutputs(): String {
val srcBuilder = StringBuilder("\n")
outputs.forEach {
val flat = if (it.isFlat) "flat" else ""
srcBuilder.appendln("$flat out ${it.variable.glslType()} ${it.variable.name};")
}
return srcBuilder.toString()
}
private fun StringBuilder.appendln(line: String) = append("$line\n")
private fun Uniform<*>.declare(): String {
return when (this) {
is Uniform1f -> "float $name"
is Uniform2f -> "vec2 $name"
is Uniform3f -> "vec3 $name"
is Uniform4f -> "vec4 $name"
is UniformColor -> "vec4 $name"
is Uniform1fv -> "float $name[$length]"
is Uniform2fv -> "vec2 $name[$length]"
is Uniform3fv -> "vec3 $name[$length]"
is Uniform4fv -> "vec4 $name[$length]"
is UniformMat3f -> "mat3 $name"
is UniformMat3fv -> "mat3 $name[$length"
is UniformMat4f -> "mat4 $name"
is UniformMat4fv -> "mat4 $name[$length]"
is Uniform1i -> "int $name"
is Uniform2i -> "ivec2 $name"
is Uniform3i -> "ivec3 $name"
is Uniform4i -> "ivec4 $name"
is Uniform1iv -> "int $name[$length]"
is Uniform2iv -> "ivec2 $name[$length]"
is Uniform3iv -> "ivec3 $name[$length]"
is Uniform4iv -> "ivec4 $name[$length]"
}
}
private class CodeGen : CodeGenerator {
val functions = mutableMapOf<String, String>()
val mainCode = mutableListOf<String>()
override fun appendFunction(name: String, glslCode: String) {
functions[name] = glslCode
}
override fun appendMain(glslCode: String) {
mainCode += glslCode
}
override fun sampleTexture1d(texName: String, texCoords: String, lod: String?) =
sampleTexture(texName, "vec2($texCoords, 0.0)", lod)
override fun sampleTexture2d(texName: String, texCoords: String, lod: String?) =
sampleTexture(texName, texCoords, lod)
override fun sampleTexture2dDepth(texName: String, texCoords: String): String {
return "textureProj($texName, $texCoords)"
}
override fun sampleTexture3d(texName: String, texCoords: String, lod: String?) =
sampleTexture(texName, texCoords, lod)
override fun sampleTextureCube(texName: String, texCoords: String, lod: String?) =
sampleTexture(texName, texCoords, lod)
fun generateFunctions(): String = functions.values.joinToString("\n")
fun generateMain(): String = mainCode.joinToString("\n")
private fun sampleTexture(texName: String, texCoords: String, lod: String?): String {
return if (lod == null) {
"texture($texName, $texCoords)"
} else {
"textureLod($texName, $texCoords, $lod)"
}
}
}
} | apache-2.0 |
Flank/flank | flank-scripts/src/main/kotlin/flank/scripts/ops/assemble/android/BuildMultiModulesApks.kt | 1 | 968 | package flank.scripts.ops.assemble.android
import flank.common.androidTestProjectsPath
import flank.common.flankFixturesTmpPath
import flank.scripts.utils.createGradleCommand
import flank.scripts.utils.runCommand
import java.nio.file.Paths
fun AndroidBuildConfiguration.buildMultiModulesApks() {
if (artifacts.canExecute("buildMultiModulesApks").not()) return
createGradleCommand(
workingDir = androidTestProjectsPath,
options = listOf(
"-p", androidTestProjectsPath,
":multi-modules:multiapp:assemble"
) + (1..20).map { ":multi-modules:testModule$it:assembleAndroidTest" }
).runCommand()
if (copy) copyMultiModulesApks()
}
private fun copyMultiModulesApks() {
val outputDir = Paths.get(flankFixturesTmpPath, "apk", "multi-modules").toString()
Paths.get(androidTestProjectsPath, "multi-modules").toFile().findApks()
.forEach { it.copyApkToDirectory(Paths.get(outputDir, it.name)) }
}
| apache-2.0 |
fabmax/kool | kool-physics/src/jvmMain/kotlin/de/fabmax/kool/physics/joints/Joint.kt | 1 | 770 | package de.fabmax.kool.physics.joints
import de.fabmax.kool.physics.Releasable
import physx.extensions.PxJoint
import physx.physics.PxConstraintFlagEnum
actual abstract class Joint : Releasable {
abstract val pxJoint: PxJoint
actual val isBroken: Boolean
get() = pxJoint.constraintFlags.isSet(PxConstraintFlagEnum.eBROKEN)
actual var debugVisualize: Boolean = false
set(value) = if ( value ) {
pxJoint.constraintFlags.set(PxConstraintFlagEnum.eVISUALIZATION)
} else {
pxJoint.constraintFlags.clear(PxConstraintFlagEnum.eVISUALIZATION)
}
actual fun setBreakForce(force: Float, torque: Float) = pxJoint.setBreakForce(force, torque)
override fun release() {
pxJoint.release()
}
} | apache-2.0 |
stepstone-tech/android-material-app-rating | app-rating/src/main/java/com/stepstone/apprating/AppRatingDialogFragment.kt | 1 | 6940 | /*
Copyright 2017 StepStone Services
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.stepstone.apprating
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.DialogFragment
import androidx.appcompat.app.AlertDialog
import android.text.TextUtils
import com.stepstone.apprating.extensions.applyIfNotZero
import com.stepstone.apprating.listener.RatingDialogListener
/**
* This class represents rating dialog created by [com.stepstone.apprating.AppRatingDialog.Builder].
* @see AppRatingDialog
*/
class AppRatingDialogFragment : DialogFragment() {
private var listener: RatingDialogListener? = null
get() {
if (host is RatingDialogListener) {
return host as RatingDialogListener
}
return targetFragment as RatingDialogListener?
}
private lateinit var data: AppRatingDialog.Builder.Data
private lateinit var alertDialog: AlertDialog
private lateinit var dialogView: AppRatingDialogView
private val title by lazy { data.title.resolveText(resources) }
private val description by lazy { data.description.resolveText(resources) }
private val defaultComment by lazy { data.defaultComment.resolveText(resources) }
private val hint by lazy { data.hint.resolveText(resources) }
private val positiveButtonText by lazy { data.positiveButtonText.resolveText(resources) }
private val neutralButtonText by lazy { data.neutralButtonText.resolveText(resources) }
private val negativeButtonText by lazy { data.negativeButtonText.resolveText(resources) }
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return setupAlertDialog(activity!!)
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putFloat(CURRENT_RATE_NUMBER, dialogView.rateNumber)
super.onSaveInstanceState(outState)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val rateNumber: Float? = savedInstanceState?.getFloat(CURRENT_RATE_NUMBER)
if (rateNumber != null) {
dialogView.setDefaultRating(rateNumber.toInt())
}
}
private fun setupAlertDialog(context: Context): AlertDialog {
dialogView = AppRatingDialogView(context)
val builder = AlertDialog.Builder(activity!!)
data = arguments?.getSerializable(DIALOG_DATA) as AppRatingDialog.Builder.Data
setupPositiveButton(dialogView, builder)
setupNegativeButton(builder)
setupNeutralButton(builder)
setupTitleAndContentMessages(dialogView)
setupHint(dialogView)
setupColors(dialogView)
setupInputBox()
setupRatingBar()
builder.setView(dialogView)
alertDialog = builder.create()
setupAnimation()
setupCancelable()
return alertDialog
}
private fun setupRatingBar() {
dialogView.setNumberOfStars(data.numberOfStars)
val isEmpty = data.noteDescriptions?.isEmpty() ?: true
if (!isEmpty) {
dialogView.setNoteDescriptions(data.noteDescriptions!!)
}
dialogView.setDefaultRating(data.defaultRating)
}
private fun setupInputBox() {
dialogView.setCommentInputEnabled(data.commentInputEnabled)
}
private fun setupCancelable() {
data.cancelable?.let { isCancelable = it }
data.canceledOnTouchOutside?.let { alertDialog.setCanceledOnTouchOutside(it) }
}
private fun setupAnimation() {
if (data.windowAnimationResId != 0) {
alertDialog.window.attributes.windowAnimations = data.windowAnimationResId
}
}
private fun setupColors(dialogView: AppRatingDialogView) {
data.titleTextColorResId.applyIfNotZero {
dialogView.setTitleTextColor(this)
}
data.descriptionTextColorResId.applyIfNotZero {
dialogView.setDescriptionTextColor(this)
}
data.commentTextColorResId.applyIfNotZero {
dialogView.setEditTextColor(this)
}
data.commentBackgroundColorResId.applyIfNotZero {
dialogView.setEditBackgroundColor(this)
}
data.hintTextColorResId.applyIfNotZero {
dialogView.setHintColor(this)
}
data.starColorResId.applyIfNotZero {
dialogView.setStarColor(this)
}
data.noteDescriptionTextColor.applyIfNotZero {
dialogView.setNoteDescriptionTextColor(this)
}
}
private fun setupTitleAndContentMessages(dialogView: AppRatingDialogView) {
if (!title.isNullOrEmpty()) {
dialogView.setTitleText(title!!)
}
if (!description.isNullOrEmpty()) {
dialogView.setDescriptionText(description!!)
}
if (!defaultComment.isNullOrEmpty()) {
dialogView.setDefaultComment(defaultComment!!)
}
}
private fun setupHint(dialogView: AppRatingDialogView) {
if (!TextUtils.isEmpty(hint)) {
dialogView.setHint(hint!!)
}
}
private fun setupNegativeButton(builder: AlertDialog.Builder) {
if (!TextUtils.isEmpty(negativeButtonText)) {
builder.setNegativeButton(negativeButtonText) { _, _ ->
listener?.onNegativeButtonClicked()
}
}
}
private fun setupPositiveButton(dialogView: AppRatingDialogView, builder: AlertDialog.Builder) {
if (!TextUtils.isEmpty(positiveButtonText)) {
builder.setPositiveButton(positiveButtonText) { _, _ ->
val rateNumber = dialogView.rateNumber.toInt()
val comment = dialogView.comment
listener?.onPositiveButtonClicked(rateNumber, comment)
}
}
}
private fun setupNeutralButton(builder: AlertDialog.Builder) {
if (!TextUtils.isEmpty(neutralButtonText)) {
builder.setNeutralButton(neutralButtonText) { _, _ ->
listener?.onNeutralButtonClicked()
}
}
}
companion object {
fun newInstance(data: AppRatingDialog.Builder.Data): AppRatingDialogFragment {
val fragment = AppRatingDialogFragment()
val bundle = Bundle()
bundle.putSerializable(DIALOG_DATA, data)
fragment.arguments = bundle
return fragment
}
}
}
| apache-2.0 |
jotomo/AndroidAPS | dana/src/main/java/info/nightscout/androidaps/dana/DanaPumpInterface.kt | 1 | 95 | package info.nightscout.androidaps.dana
interface DanaPumpInterface {
fun clearPairing()
} | agpl-3.0 |
jotomo/AndroidAPS | danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusTime_k.kt | 1 | 2415 | package info.nightscout.androidaps.danaRKorean.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.danar.R
import info.nightscout.androidaps.danar.comm.MessageBase
import info.nightscout.androidaps.events.EventRebuildTabs
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
class MsgInitConnStatusTime_k(
injector: HasAndroidInjector
) : MessageBase(injector) {
init {
SetCommand(0x0301)
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(bytes: ByteArray) {
if (bytes.size - 10 < 10) {
val notification = Notification(Notification.WRONG_DRIVER, resourceHelper.gs(R.string.pumpdrivercorrected), Notification.NORMAL)
rxBus.send(EventNewNotification(notification))
danaRKoreanPlugin.disconnect("Wrong Model")
aapsLogger.debug(LTag.PUMPCOMM, "Wrong model selected. Switching to export DanaR")
danaRKoreanPlugin.setPluginEnabled(PluginType.PUMP, false)
danaRKoreanPlugin.setFragmentVisible(PluginType.PUMP, false)
danaRPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRPlugin.setFragmentVisible(PluginType.PUMP, true)
danaPump.reset() // mark not initialized
//If profile coming from pump, switch it as well
configBuilder.storeSettings("ChangingKoreanDanaDriver")
rxBus.send(EventRebuildTabs())
commandQueue.readStatus("PumpDriverChange", null) // force new connection
return
}
val time = dateTimeSecFromBuff(bytes, 0)
val versionCode1 = intFromBuff(bytes, 6, 1)
val versionCode2 = intFromBuff(bytes, 7, 1)
val versionCode3 = intFromBuff(bytes, 8, 1)
val versionCode4 = intFromBuff(bytes, 9, 1)
aapsLogger.debug(LTag.PUMPCOMM, "Pump time: " + dateUtil.dateAndTimeString(time))
aapsLogger.debug(LTag.PUMPCOMM, "Version code1: $versionCode1")
aapsLogger.debug(LTag.PUMPCOMM, "Version code2: $versionCode2")
aapsLogger.debug(LTag.PUMPCOMM, "Version code3: $versionCode3")
aapsLogger.debug(LTag.PUMPCOMM, "Version code4: $versionCode4")
}
} | agpl-3.0 |
mdaniel/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantCompanionReference/sameNameLocalVariable2.kt | 13 | 157 | // PROBLEM: none
class Test {
companion object {
val localVar = 1
}
fun test(localVar: Int) {
<caret>Companion.localVar
}
} | apache-2.0 |
mdaniel/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/list/search/ReviewListSearchPanelViewModel.kt | 1 | 466 | // 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.collaboration.ui.codereview.list.search
import kotlinx.coroutines.flow.MutableStateFlow
interface ReviewListSearchPanelViewModel<S : ReviewListSearchValue> {
val searchState: MutableStateFlow<S>
val queryState: MutableStateFlow<String?>
val emptySearch: S
val defaultSearch: S
fun getSearchHistory(): List<S>
} | apache-2.0 |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/duplicateUtil.kt | 1 | 4553 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine
import com.intellij.codeInsight.folding.CodeFoldingManager
import com.intellij.codeInsight.highlighting.HighlightManager
import com.intellij.find.FindManager
import com.intellij.java.refactoring.JavaRefactoringBundle
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.markup.RangeHighlighter
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.refactoring.util.duplicates.MethodDuplicatesHandler
import com.intellij.ui.ReplacePromptDialog
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange
import org.jetbrains.kotlin.idea.refactoring.introduce.getPhysicalTextRange
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
fun KotlinPsiRange.highlight(project: Project, editor: Editor): RangeHighlighter? {
val textRange = getPhysicalTextRange()
val highlighters = ArrayList<RangeHighlighter>()
HighlightManager.getInstance(project).addRangeHighlight(
editor, textRange.startOffset, textRange.endOffset, EditorColors.SEARCH_RESULT_ATTRIBUTES, true, highlighters
)
return highlighters.firstOrNull()
}
fun KotlinPsiRange.preview(project: Project, editor: Editor): RangeHighlighter? {
val highlight = highlight(project, editor) ?: return null
val startOffset = getPhysicalTextRange().startOffset
val foldedRegions = CodeFoldingManager.getInstance(project)
.getFoldRegionsAtOffset(editor, startOffset)
.filter { !it.isExpanded }
if (!foldedRegions.isEmpty()) {
editor.foldingModel.runBatchFoldingOperation {
foldedRegions.forEach { it.isExpanded = true }
}
}
editor.scrollingModel.scrollTo(editor.offsetToLogicalPosition(startOffset), ScrollType.MAKE_VISIBLE)
return highlight
}
fun processDuplicates(
duplicateReplacers: Map<KotlinPsiRange, () -> Unit>,
project: Project,
editor: Editor,
scopeDescription: String = "this file",
usageDescription: String = "a usage of extracted declaration"
) {
val size = duplicateReplacers.size
if (size == 0) return
if (size == 1) {
duplicateReplacers.keys.first().preview(project, editor)
}
val answer = if (isUnitTestMode()) {
Messages.YES
} else {
Messages.showYesNoDialog(
project,
KotlinBundle.message("0.has.detected.1.code.fragments.in.2.that.can.be.replaced.with.3",
ApplicationNamesInfo.getInstance().productName,
duplicateReplacers.size,
scopeDescription,
usageDescription
),
KotlinBundle.message("text.process.duplicates"),
Messages.getQuestionIcon()
)
}
if (answer != Messages.YES) {
return
}
var showAll = false
duplicateReplacersLoop@
for ((i, entry) in duplicateReplacers.entries.withIndex()) {
val (pattern, replacer) = entry
if (!pattern.isValid) continue
val highlighter = pattern.preview(project, editor)
if (!isUnitTestMode()) {
if (size > 1 && !showAll) {
val promptDialog = ReplacePromptDialog(false, JavaRefactoringBundle.message("process.duplicates.title", i + 1, size), project)
promptDialog.show()
when (promptDialog.exitCode) {
FindManager.PromptResult.ALL -> showAll = true
FindManager.PromptResult.SKIP -> continue@duplicateReplacersLoop
FindManager.PromptResult.CANCEL -> return
}
}
}
highlighter?.let { HighlightManager.getInstance(project).removeSegmentHighlighter(editor, it) }
project.executeWriteCommand(MethodDuplicatesHandler.getRefactoringName(), replacer)
}
}
fun processDuplicatesSilently(duplicateReplacers: Map<KotlinPsiRange, () -> Unit>, project: Project) {
project.executeWriteCommand(MethodDuplicatesHandler.getRefactoringName()) {
duplicateReplacers.values.forEach { it() }
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/intentions/IntentionDescriptionTest.kt | 1 | 2714 | // 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.codeInsight.intention.IntentionActionBean
import com.intellij.codeInsight.intention.impl.config.IntentionManagerImpl
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.testFramework.UsefulTestCase
import org.jetbrains.kotlin.idea.KotlinPluginUtil
import org.jetbrains.kotlin.test.KotlinRoot
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
@RunWith(JUnit38ClassRunner::class)
class IntentionDescriptionTest : LightPlatformTestCase() {
private val necessaryNormalNames = listOf("description.html", "before.kt.template", "after.kt.template")
private val necessaryXmlNames = listOf("description.html", "before.xml.template", "after.xml.template")
private val necessaryMavenNames = listOf("description.html")
fun testDescriptionsAndShortNames() {
val intentionTools = loadKotlinIntentions()
val errors = StringBuilder()
for (tool in intentionTools) {
val className = tool.className
val shortName = className.substringAfterLast(".").replace("$", "")
val directory = KotlinRoot.DIR.resolve("idea/resources-en/intentionDescriptions/$shortName")
if (!directory.exists() || !directory.isDirectory) {
if (tool.categories != null) {
errors.append("No description directory for intention '").append(className).append("'\n")
}
} else {
val necessaryNames = when {
shortName.isMavenIntentionName() -> necessaryMavenNames
shortName.isXmlIntentionName() -> necessaryXmlNames
else -> necessaryNormalNames
}
for (fileName in necessaryNames) {
val file = directory.resolve(fileName)
if (!file.exists() || !file.isFile) {
errors.append("No description file $fileName for intention '").append(className).append("'\n")
}
}
}
}
UsefulTestCase.assertEmpty(errors.toString())
}
private fun String.isMavenIntentionName() = startsWith("MavenPlugin")
private fun String.isXmlIntentionName() = startsWith("Add") && endsWith("ToManifest")
private fun loadKotlinIntentions(): List<IntentionActionBean> = IntentionManagerImpl.EP_INTENTION_ACTIONS.extensions.filter {
it.pluginDescriptor.pluginId == KotlinPluginUtil.KOTLIN_PLUGIN_ID
}
} | apache-2.0 |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/search/SearchFragment.kt | 1 | 2440 | package io.github.feelfreelinux.wykopmobilny.ui.modules.search
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.base.BaseActivity
import io.github.feelfreelinux.wykopmobilny.base.BaseFragment
import io.github.feelfreelinux.wykopmobilny.utils.hideKeyboard
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.activity_search.*
class SearchFragment : BaseFragment() {
companion object {
fun newInstance() = SearchFragment()
}
val querySubject by lazy { PublishSubject.create<String>() }
private lateinit var viewPagerAdapter: SearchPagerAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
setHasOptionsMenu(true)
return inflater.inflate(R.layout.activity_search, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewPagerAdapter = SearchPagerAdapter(resources, childFragmentManager)
pager.adapter = viewPagerAdapter
pager.offscreenPageLimit = 3
tabLayout.setupWithViewPager(pager)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
(activity as BaseActivity).supportActionBar?.setTitle(R.string.search)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
menu.clear()
inflater.inflate(R.menu.search_menu, menu)
val item = menu.findItem(R.id.action_search)
item.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM or MenuItem.SHOW_AS_ACTION_WITH_TEXT)
val searchView = item.actionView as SearchView
val historyDb = HistorySuggestionListener(context!!, {
querySubject.onNext(it)
activity?.hideKeyboard()
}, searchView)
with(searchView) {
setOnQueryTextListener(historyDb)
setOnSuggestionListener(historyDb)
setIconifiedByDefault(false)
isIconified = false
}
}
} | mit |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParameters/EmptyArgumentInThisAsConstructor2.kt | 12 | 131 | class A(a: Int) {
constructor() : this(<caret>)
}
// SET_TRUE: ALIGN_MULTILINE_METHOD_BRACKETS
// IGNORE_FORMATTER
// KT-39459 | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/splitIf/keepComments/withOR.kt | 4 | 146 | fun <T> doSomething(a: T) {}
fun foo(p: Int) {
<caret>if (p < 0 /* p < 0 */ || p > 100 /* too much */) {
doSomething("test")
}
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/primitiveArray/filterFirst.kt | 4 | 123 | // WITH_RUNTIME
fun test() {
val array: IntArray = intArrayOf(0, 1, 2, 3)
array.<caret>filter { it > 0 }.first()
} | apache-2.0 |
idea4bsd/idea4bsd | platform/script-debugger/debugger-ui/src/ScopeVariablesGroup.kt | 5 | 4386 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.xdebugger.XDebuggerBundle
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XValueChildrenList
import com.intellij.xdebugger.frame.XValueGroup
import org.jetbrains.concurrency.done
import org.jetbrains.concurrency.rejected
import org.jetbrains.concurrency.thenAsyncAccept
class ScopeVariablesGroup(val scope: Scope, parentContext: VariableContext, callFrame: CallFrame?) : XValueGroup(scope.createScopeNodeName()) {
private val context = createVariableContext(scope, parentContext, callFrame)
private val callFrame = if (scope.type == Scope.Type.LOCAL) callFrame else null
override fun isAutoExpand() = scope.type == Scope.Type.LOCAL || scope.type == Scope.Type.CATCH
override fun getComment(): String? {
val className = scope.description
return if ("Object" == className) null else className
}
override fun computeChildren(node: XCompositeNode) {
val promise = processScopeVariables(scope, node, context, callFrame == null)
if (callFrame == null) {
return
}
promise
.done(node) {
context.memberFilter
.thenAsyncAccept(node) {
if (it.hasNameMappings()) {
it.sourceNameToRaw(RECEIVER_NAME)?.let {
return@thenAsyncAccept callFrame.evaluateContext.evaluate(it)
.done(node) {
VariableImpl(RECEIVER_NAME, it.value, null)
node.addChildren(XValueChildrenList.singleton(VariableView(VariableImpl(RECEIVER_NAME, it.value, null), context)), true)
}
}
}
context.viewSupport.computeReceiverVariable(context, callFrame, node)
}
.rejected(node) {
context.viewSupport.computeReceiverVariable(context, callFrame, node)
}
}
}
}
fun createAndAddScopeList(node: XCompositeNode, scopes: List<Scope>, context: VariableContext, callFrame: CallFrame?) {
val list = XValueChildrenList(scopes.size)
for (scope in scopes) {
list.addTopGroup(ScopeVariablesGroup(scope, context, callFrame))
}
node.addChildren(list, true)
}
fun createVariableContext(scope: Scope, parentContext: VariableContext, callFrame: CallFrame?): VariableContext {
if (callFrame == null || scope.type == Scope.Type.LIBRARY) {
// functions scopes - we can watch variables only from global scope
return ParentlessVariableContext(parentContext, scope, scope.type == Scope.Type.GLOBAL)
}
else {
return VariableContextWrapper(parentContext, scope)
}
}
private class ParentlessVariableContext(parentContext: VariableContext, scope: Scope, private val watchableAsEvaluationExpression: Boolean) : VariableContextWrapper(parentContext, scope) {
override fun watchableAsEvaluationExpression() = watchableAsEvaluationExpression
}
private fun Scope.createScopeNodeName(): String {
when (type) {
Scope.Type.GLOBAL -> return XDebuggerBundle.message("scope.global")
Scope.Type.LOCAL -> return XDebuggerBundle.message("scope.local")
Scope.Type.WITH -> return XDebuggerBundle.message("scope.with")
Scope.Type.CLOSURE -> return XDebuggerBundle.message("scope.closure")
Scope.Type.CATCH -> return XDebuggerBundle.message("scope.catch")
Scope.Type.LIBRARY -> return XDebuggerBundle.message("scope.library")
Scope.Type.INSTANCE -> return XDebuggerBundle.message("scope.instance")
Scope.Type.CLASS -> return XDebuggerBundle.message("scope.class")
Scope.Type.BLOCK -> return XDebuggerBundle.message("scope.block")
Scope.Type.SCRIPT -> return XDebuggerBundle.message("scope.script")
Scope.Type.UNKNOWN -> return XDebuggerBundle.message("scope.unknown")
else -> throw IllegalArgumentException(type.name)
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/basic/inlineReified2.kt | 4 | 132 | // WITH_RUNTIME
inline fun <reified T : CharSequence, reified U, X> foo() {
<selection>listOf(T::class, U::class)</selection>
} | apache-2.0 |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/preferences/SettingsPreferences.kt | 1 | 3339 | package io.github.feelfreelinux.wykopmobilny.utils.preferences
import android.content.Context
interface SettingsPreferencesApi {
var notificationsSchedulerDelay: String?
var hotEntriesScreen: String?
var defaultScreen: String?
var linkImagePosition: String?
var linkShowImage: Boolean
var linkSimpleList: Boolean
var linkShowAuthor: Boolean
var showAdultContent: Boolean
var hideNsfw: Boolean
var useDarkTheme: Boolean
var useAmoledTheme: Boolean
var showNotifications: Boolean
var piggyBackPushNotifications: Boolean
var showMinifiedImages: Boolean
var cutLongEntries: Boolean
var cutImages: Boolean
var openSpoilersDialog: Boolean
var hideLowRangeAuthors: Boolean
var hideContentWithoutTags: Boolean
var cutImageProportion: Int
var fontSize: String?
var hideLinkCommentsByDefault: Boolean
var hideBlacklistedViews: Boolean
var enableYoutubePlayer: Boolean
var enableEmbedPlayer: Boolean
var useBuiltInBrowser: Boolean
var groupNotifications: Boolean
var disableExitConfirmation: Boolean
var dialogShown: Boolean
}
class SettingsPreferences(context: Context) : Preferences(context, true), SettingsPreferencesApi {
override var notificationsSchedulerDelay by stringPref(defaultValue = "15")
override var showAdultContent by booleanPref(defaultValue = false)
override var hideNsfw: Boolean by booleanPref(defaultValue = true)
override var hideLowRangeAuthors: Boolean by booleanPref(defaultValue = false)
override var hideContentWithoutTags: Boolean by booleanPref(defaultValue = false)
override var hotEntriesScreen by stringPref(defaultValue = "newest")
override var defaultScreen by stringPref(defaultValue = "mainpage")
override var fontSize by stringPref(defaultValue = "normal")
override var linkImagePosition by stringPref(defaultValue = "left")
override var linkShowImage by booleanPref(defaultValue = true)
override var linkSimpleList by booleanPref(defaultValue = false)
override var linkShowAuthor by booleanPref(defaultValue = false)
override var useDarkTheme by booleanPref(defaultValue = false)
override var useAmoledTheme by booleanPref(defaultValue = false)
override var showMinifiedImages by booleanPref(defaultValue = false)
override var piggyBackPushNotifications by booleanPref(defaultValue = false)
override var cutLongEntries by booleanPref(defaultValue = true)
override var cutImages by booleanPref(defaultValue = true)
override var cutImageProportion by intPref(defaultValue = 60)
override var openSpoilersDialog by booleanPref(defaultValue = true)
override var showNotifications by booleanPref(defaultValue = true)
override var hideLinkCommentsByDefault by booleanPref(defaultValue = false)
override var hideBlacklistedViews: Boolean by booleanPref(defaultValue = false)
override var enableEmbedPlayer by booleanPref(defaultValue = true)
override var enableYoutubePlayer by booleanPref(defaultValue = true)
override var useBuiltInBrowser by booleanPref(defaultValue = true)
override var groupNotifications by booleanPref(defaultValue = true)
override var disableExitConfirmation by booleanPref(defaultValue = false)
override var dialogShown by booleanPref(defaultValue = false)
} | mit |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/multiModule/multiplatform/custom/buildError2Levels/pJvm_fg.kt | 10 | 44 | actual fun f() = Unit
actual fun g() = Unit | apache-2.0 |
siosio/intellij-community | plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/asJava/fields/FirLightFieldEnumEntry.kt | 2 | 3433 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.asJava
import com.intellij.psi.*
import org.jetbrains.kotlin.asJava.builder.LightMemberOrigin
import org.jetbrains.kotlin.asJava.classes.*
import org.jetbrains.kotlin.asJava.elements.FirLightIdentifier
import org.jetbrains.kotlin.fir.declarations.FirResolvePhase
import org.jetbrains.kotlin.idea.asJava.*
import org.jetbrains.kotlin.idea.frontend.api.isValid
import org.jetbrains.kotlin.idea.frontend.api.symbols.KtEnumEntrySymbol
import org.jetbrains.kotlin.idea.util.ifTrue
import org.jetbrains.kotlin.psi.KtEnumEntry
internal class FirLightFieldForEnumEntry(
private val enumEntrySymbol: KtEnumEntrySymbol,
containingClass: FirLightClassForSymbol,
override val lightMemberOrigin: LightMemberOrigin?
) : FirLightField(containingClass, lightMemberOrigin), PsiEnumConstant {
private val _modifierList by lazyPub {
FirLightClassModifierList(
containingDeclaration = this@FirLightFieldForEnumEntry,
modifiers = setOf(PsiModifier.STATIC, PsiModifier.FINAL, PsiModifier.PUBLIC),
annotations = emptyList()
)
}
override fun getModifierList(): PsiModifierList = _modifierList
override val kotlinOrigin: KtEnumEntry? = enumEntrySymbol.psi as? KtEnumEntry
override fun isDeprecated(): Boolean = false
//TODO Make with KtSymbols
private val hasBody: Boolean get() = kotlinOrigin?.let { it.body != null } ?: true
private val _initializingClass: PsiEnumConstantInitializer? by lazyPub {
hasBody.ifTrue {
FirLightClassForEnumEntry(
enumEntrySymbol = enumEntrySymbol,
enumConstant = this@FirLightFieldForEnumEntry,
enumClass = containingClass,
manager = manager
)
}
}
override fun getInitializingClass(): PsiEnumConstantInitializer? = _initializingClass
override fun getOrCreateInitializingClass(): PsiEnumConstantInitializer =
_initializingClass ?: cannotModify()
override fun getArgumentList(): PsiExpressionList? = null
override fun resolveMethod(): PsiMethod? = null
override fun resolveConstructor(): PsiMethod? = null
override fun resolveMethodGenerics(): JavaResolveResult = JavaResolveResult.EMPTY
override fun hasInitializer() = true
override fun computeConstantValue(visitedVars: MutableSet<PsiVariable>?) = this
override fun getName(): String = enumEntrySymbol.name.asString()
private val _type: PsiType by lazyPub {
enumEntrySymbol.annotatedType.asPsiType(enumEntrySymbol, this@FirLightFieldForEnumEntry, FirResolvePhase.TYPES)
}
override fun getType(): PsiType = _type
override fun getInitializer(): PsiExpression? = null
override fun hashCode(): Int = enumEntrySymbol.hashCode()
private val _identifier: PsiIdentifier by lazyPub {
FirLightIdentifier(this, enumEntrySymbol)
}
override fun getNameIdentifier(): PsiIdentifier = _identifier
override fun isValid(): Boolean = super.isValid() && enumEntrySymbol.isValid()
override fun equals(other: Any?): Boolean =
other is FirLightFieldForEnumEntry &&
enumEntrySymbol == other.enumEntrySymbol
} | apache-2.0 |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameOnSecondaryConstructorHandler.kt | 5 | 2129 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.rename.RenameHandler
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.psi.*
class RenameOnSecondaryConstructorHandler : RenameHandler {
override fun isAvailableOnDataContext(dataContext: DataContext): Boolean {
val editor = CommonDataKeys.EDITOR.getData(dataContext) ?: return false
val file = CommonDataKeys.PSI_FILE.getData(dataContext) ?: return false
val element = PsiTreeUtil.findElementOfClassAtOffsetWithStopSet(
file,
editor.caretModel.offset,
KtSecondaryConstructor::class.java,
false,
KtBlockExpression::class.java,
KtValueArgumentList::class.java,
KtParameterList::class.java,
KtConstructorDelegationCall::class.java
)
return element != null
}
override fun isRenaming(dataContext: DataContext): Boolean = isAvailableOnDataContext(dataContext)
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) {
CodeInsightUtils.showErrorHint(
project,
editor,
KotlinBundle.message("text.rename.is.not.applicable.to.secondary.constructors"),
RefactoringBundle.message("rename.title"),
null
)
}
override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) {
// Do nothing: this method is called not from editor
}
}
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/KotlinDescriptorTestCaseWithStepping.kt | 1 | 16415 | // 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.debugger.test
import com.intellij.debugger.actions.MethodSmartStepTarget
import com.intellij.debugger.actions.SmartStepTarget
import com.intellij.debugger.engine.BasicStepMethodFilter
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.MethodFilter
import com.intellij.debugger.engine.SuspendContextImpl
import com.intellij.debugger.engine.evaluation.EvaluateException
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.engine.events.SuspendContextCommandImpl
import com.intellij.debugger.engine.managerThread.DebuggerCommand
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.debugger.impl.JvmSteppingCommandProvider
import com.intellij.debugger.impl.PositionUtil
import com.intellij.execution.configurations.JavaParameters
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.jarRepository.JarRepositoryManager
import com.intellij.jarRepository.RemoteRepositoryDescription
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.roots.libraries.ui.OrderRoot
import com.intellij.psi.PsiElement
import com.intellij.testFramework.runInEdtAndWait
import com.intellij.xdebugger.XDebuggerTestUtil
import com.intellij.xdebugger.frame.XStackFrame
import junit.framework.AssertionFailedError
import org.jetbrains.idea.maven.aether.ArtifactKind
import org.jetbrains.jps.model.library.JpsMavenRepositoryLibraryDescriptor
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils.getTopmostElementAtOffset
import org.jetbrains.kotlin.idea.debugger.KotlinPositionManager
import org.jetbrains.kotlin.idea.debugger.stackFrame.KotlinStackFrame
import org.jetbrains.kotlin.idea.debugger.stepping.KotlinSteppingCommandProvider
import org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto.KotlinSmartStepIntoHandler
import org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto.KotlinSmartStepTarget
import org.jetbrains.kotlin.idea.debugger.test.util.KotlinOutputChecker
import org.jetbrains.kotlin.idea.debugger.test.util.SteppingInstruction
import org.jetbrains.kotlin.idea.debugger.test.util.SteppingInstructionKind
import org.jetbrains.kotlin.idea.debugger.test.util.render
import org.jetbrains.kotlin.idea.test.ConfigLibraryUtil
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils.isIgnoredTarget
import org.jetbrains.kotlin.idea.test.KotlinBaseTest
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtTreeVisitorVoid
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.test.InTextDirectivesUtils
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance
import java.io.ByteArrayOutputStream
import java.io.PrintStream
import java.nio.charset.StandardCharsets
abstract class KotlinDescriptorTestCaseWithStepping : KotlinDescriptorTestCase() {
companion object {
//language=RegExp
const val MAVEN_DEPENDENCY_REGEX = """maven\(([a-zA-Z0-9_\-.]+):([a-zA-Z0-9_\-.]+):([a-zA-Z0-9_\-.]+)\)"""
}
private val dp: DebugProcessImpl
get() = debugProcess ?: throw AssertionError("createLocalProcess() should be called before getDebugProcess()")
@Volatile
private var myEvaluationContext: EvaluationContextImpl? = null
val evaluationContext get() = myEvaluationContext!!
@Volatile
private var myDebuggerContext: DebuggerContextImpl? = null
protected open val debuggerContext get() = myDebuggerContext!!
@Volatile
private var myCommandProvider: KotlinSteppingCommandProvider? = null
private val commandProvider get() = myCommandProvider!!
private val classPath = mutableListOf<String>()
private val thrownExceptions = mutableListOf<Throwable>()
private fun initContexts(suspendContext: SuspendContextImpl) {
myEvaluationContext = createEvaluationContext(suspendContext)
myDebuggerContext = createDebuggerContext(suspendContext)
myCommandProvider = JvmSteppingCommandProvider.EP_NAME.extensions.firstIsInstance<KotlinSteppingCommandProvider>()
}
private fun SuspendContextImpl.getKotlinStackFrames(): List<KotlinStackFrame> {
val proxy = frameProxy ?: return emptyList()
if (myInProgress) {
val positionManager = KotlinPositionManager(debugProcess)
return positionManager.createStackFrames(
proxy, debugProcess, proxy.location()
).filterIsInstance<KotlinStackFrame>()
}
return emptyList()
}
override fun createEvaluationContext(suspendContext: SuspendContextImpl): EvaluationContextImpl? {
return try {
val proxy = suspendContext.getKotlinStackFrames().firstOrNull()?.stackFrameProxy ?: suspendContext.frameProxy
assertNotNull(proxy)
EvaluationContextImpl(suspendContext, proxy, proxy?.thisObject())
} catch (e: EvaluateException) {
error(e)
null
}
}
internal fun process(instructions: List<SteppingInstruction>) {
instructions.forEach(this::process)
}
internal fun doOnBreakpoint(action: SuspendContextImpl.() -> Unit) {
super.onBreakpoint {
try {
initContexts(it)
it.printContext()
it.action()
} catch (e: AssertionError) {
throw e
} catch (e: Throwable) {
e.printStackTrace()
resume(it)
}
}
}
internal fun finish() {
doOnBreakpoint {
resume(this)
}
}
private fun SuspendContextImpl.doStepInto(ignoreFilters: Boolean, smartStepFilter: MethodFilter?) {
val stepIntoCommand =
runReadAction { commandProvider.getStepIntoCommand(this, ignoreFilters, smartStepFilter) }
?: dp.createStepIntoCommand(this, ignoreFilters, smartStepFilter)
dp.managerThread.schedule(stepIntoCommand)
}
private fun SuspendContextImpl.doStepOut() {
val stepOutCommand = runReadAction { commandProvider.getStepOutCommand(this, debuggerContext) }
?: dp.createStepOutCommand(this)
dp.managerThread.schedule(stepOutCommand)
}
override fun tearDown() {
super.tearDown()
classPath.clear()
}
private fun SuspendContextImpl.doStepOver(ignoreBreakpoints: Boolean = false) {
val stepOverCommand = runReadAction {
val sourcePosition = debuggerContext.sourcePosition
commandProvider.getStepOverCommand(this, ignoreBreakpoints, sourcePosition)
} ?: dp.createStepOverCommand(this, ignoreBreakpoints)
dp.managerThread.schedule(stepOverCommand)
}
private fun process(instruction: SteppingInstruction) {
fun loop(count: Int, block: SuspendContextImpl.() -> Unit) {
repeat(count) {
doOnBreakpoint(block)
}
}
when (instruction.kind) {
SteppingInstructionKind.StepInto -> loop(instruction.arg) { doStepInto(false, null) }
SteppingInstructionKind.StepOut -> loop(instruction.arg) { doStepOut() }
SteppingInstructionKind.StepOver -> loop(instruction.arg) { doStepOver() }
SteppingInstructionKind.ForceStepOver -> loop(instruction.arg) { doStepOver(ignoreBreakpoints = true) }
SteppingInstructionKind.SmartStepInto -> loop(instruction.arg) { doSmartStepInto() }
SteppingInstructionKind.SmartStepIntoByIndex -> doOnBreakpoint { doSmartStepInto(instruction.arg) }
SteppingInstructionKind.Resume -> loop(instruction.arg) { resume(this) }
SteppingInstructionKind.SmartStepTargetsExpectedNumber ->
doOnBreakpoint {
checkNumberOfSmartStepTargets(instruction.arg)
resume(this)
}
}
}
private fun checkNumberOfSmartStepTargets(expectedNumber: Int) {
val smartStepFilters = createSmartStepIntoFilters()
try {
assertEquals(
"Actual and expected numbers of smart step targets do not match",
expectedNumber,
smartStepFilters.size
)
} catch (ex: AssertionFailedError) {
thrownExceptions.add(ex)
}
}
private fun SuspendContextImpl.doSmartStepInto(chooseFromList: Int = 0) {
this.doSmartStepInto(chooseFromList, false)
}
override fun throwExceptionsIfAny() {
if (thrownExceptions.isNotEmpty()) {
if (!isTestIgnored()) {
throw AssertionError(
"Test failed with exceptions:\n${thrownExceptions.renderStackTraces()}"
)
} else {
(checker as? KotlinOutputChecker)?.threwException = true
}
}
}
private fun List<Throwable>.renderStackTraces(): String {
val outputStream = ByteArrayOutputStream()
PrintStream(outputStream, true, StandardCharsets.UTF_8).use {
for (throwable in this) {
throwable.printStackTrace(it)
}
}
return outputStream.toString(StandardCharsets.UTF_8)
}
protected fun isTestIgnored(): Boolean {
val outputFile = getExpectedOutputFile()
return outputFile.exists() && isIgnoredTarget(targetBackend(), outputFile)
}
private fun SuspendContextImpl.printContext() {
runReadAction {
if (this.frameProxy == null) {
return@runReadAction println("Context thread is null", ProcessOutputTypes.SYSTEM)
}
val sourcePosition = PositionUtil.getSourcePosition(this)
println(sourcePosition?.render() ?: "null", ProcessOutputTypes.SYSTEM)
}
}
private fun SuspendContextImpl.doSmartStepInto(chooseFromList: Int, ignoreFilters: Boolean) {
val filters = createSmartStepIntoFilters()
if (chooseFromList == 0) {
filters.forEach {
doStepInto(ignoreFilters, it)
}
} else {
try {
doStepInto(ignoreFilters, filters[chooseFromList - 1])
} catch (e: IndexOutOfBoundsException) {
val elementText = runReadAction { debuggerContext.sourcePosition.elementAt.getElementTextWithContext() }
throw AssertionError("Couldn't find smart step into command at: \n$elementText", e)
}
}
}
private fun createSmartStepIntoFilters(): List<MethodFilter> {
val position = debuggerContext.sourcePosition
val stepTargets = KotlinSmartStepIntoHandler()
.findStepIntoTargets(position, debuggerSession)
.blockingGet(XDebuggerTestUtil.TIMEOUT_MS)
?: error("Couldn't calculate smart step targets")
return runReadAction {
stepTargets.sortedByPositionInTree().mapNotNull { stepTarget ->
when (stepTarget) {
is KotlinSmartStepTarget -> stepTarget.createMethodFilter()
is MethodSmartStepTarget -> BasicStepMethodFilter(stepTarget.method, stepTarget.getCallingExpressionLines())
else -> null
}
}
}
}
private fun List<SmartStepTarget>.sortedByPositionInTree(): List<SmartStepTarget> {
if (isEmpty()) return emptyList()
val sortedTargets = MutableList(size) { first() }
for ((i, indexInTree) in getIndicesInTree().withIndex()) {
sortedTargets[indexInTree] = get(i)
}
return sortedTargets
}
private fun List<SmartStepTarget>.getIndicesInTree(): List<Int> {
val targetsIndicesInTree = MutableList(size) { 0 }
runReadAction {
val elementAt = debuggerContext.sourcePosition.elementAt
val topmostElement = getTopmostElementAtOffset(elementAt, elementAt.textRange.startOffset)
topmostElement.accept(object : KtTreeVisitorVoid() {
private var elementIndex = 0
override fun visitElement(element: PsiElement) {
for ((i, target) in withIndex()) {
if (element === target.highlightElement) {
targetsIndicesInTree[i] = elementIndex++
break
}
}
super.visitElement(element)
}
})
}
return targetsIndicesInTree
}
protected fun SuspendContextImpl.runActionInSuspendCommand(action: SuspendContextImpl.() -> Unit) {
if (myInProgress) {
action()
} else {
val command = object : SuspendContextCommandImpl(this) {
override fun contextAction(suspendContext: SuspendContextImpl) {
action(suspendContext)
}
}
// Try to execute the action inside a command if we aren't already inside it.
debuggerSession.process.managerThread.invoke(command)
}
}
protected fun processStackFramesOnPooledThread(callback: List<XStackFrame>.() -> Unit) {
val frameProxy = debuggerContext.frameProxy ?: error("Frame proxy is absent")
val debugProcess = debuggerContext.debugProcess ?: error("Debug process is absent")
val nodeManager = debugProcess.xdebugProcess!!.nodeManager
val descriptor = nodeManager.getStackFrameDescriptor(null, frameProxy)
val stackFrames = debugProcess.positionManager.createStackFrames(descriptor)
if (stackFrames.isEmpty()) {
error("Can't create stack frame for $descriptor")
}
ApplicationManager.getApplication().executeOnPooledThread {
stackFrames.callback()
}
}
protected fun countBreakpointsNumber(file: KotlinBaseTest.TestFile) =
InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.content, "//Breakpoint!").size
protected fun SuspendContextImpl.invokeInManagerThread(callback: () -> Unit) {
assert(debugProcess.isAttached)
debugProcess.managerThread.invokeCommand(object : DebuggerCommand {
override fun action() = callback()
override fun commandCancelled() = error(message = "Test was cancelled")
})
}
override fun addMavenDependency(compilerFacility: DebuggerTestCompilerFacility, library: String) {
val regex = Regex(MAVEN_DEPENDENCY_REGEX)
val result = regex.matchEntire(library) ?: return
val (_, groupId: String, artifactId: String, version: String) = result.groupValues
addMavenDependency(compilerFacility, groupId, artifactId, version)
}
override fun createJavaParameters(mainClass: String?): JavaParameters {
val params = super.createJavaParameters(mainClass)
for (entry in classPath) {
params.classPath.add(entry)
}
return params
}
protected fun addMavenDependency(compilerFacility: DebuggerTestCompilerFacility, groupId: String, artifactId: String, version: String) {
val description = JpsMavenRepositoryLibraryDescriptor(groupId, artifactId, version)
val artifacts = loadDependencies(description)
compilerFacility.addDependencies(artifacts.map { it.file.presentableUrl })
addLibraries(artifacts)
}
private fun addLibraries(artifacts: MutableList<OrderRoot>) {
runInEdtAndWait {
ConfigLibraryUtil.addLibrary(module, "ARTIFACTS") {
for (artifact in artifacts) {
classPath.add(artifact.file.presentableUrl) // for sandbox jvm
addRoot(artifact.file, artifact.type)
}
}
}
}
protected fun loadDependencies(
description: JpsMavenRepositoryLibraryDescriptor
): MutableList<OrderRoot> {
return JarRepositoryManager.loadDependenciesSync(
project, description, setOf(ArtifactKind.ARTIFACT),
RemoteRepositoryDescription.DEFAULT_REPOSITORIES, null
) ?: throw AssertionError("Maven Dependency not found: $description")
}
}
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/uast/uast-kotlin/tests/test/org/jetbrains/uast/test/kotlin/comparison/FE1UastResolveApiTest.kt | 4 | 3070 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.test.kotlin.comparison
import com.intellij.testFramework.TestDataPath
import org.jetbrains.kotlin.idea.test.JUnit3RunnerWithInners
import org.jetbrains.kotlin.test.KotlinRoot
import org.jetbrains.kotlin.test.TestMetadata
import org.jetbrains.uast.UFile
import org.jetbrains.uast.test.common.kotlin.UastResolveApiTestBase
import org.jetbrains.uast.test.kotlin.env.AbstractFE1UastTest
import org.junit.runner.RunWith
@RunWith(JUnit3RunnerWithInners::class)
class FE1UastResolveApiTest : AbstractFE1UastTest() {
override fun check(testName: String, file: UFile) {
// Bogus
}
@TestMetadata("uast-kotlin-fir/testData/declaration")
@TestDataPath("/")
@RunWith(JUnit3RunnerWithInners::class)
class Declaration : AbstractFE1UastTest(), UastResolveApiTestBase {
override var testDataDir = KotlinRoot.DIR.resolve("uast/uast-kotlin-fir/testData/declaration")
override val isFirUastPlugin: Boolean = false
override fun check(testName: String, file: UFile) {
// Bogus
}
@TestMetadata("doWhile.kt")
fun testDoWhile() {
doTest("doWhile", ::checkCallbackForDoWhile)
}
@TestMetadata("if.kt")
fun testIf() {
doTest("if", ::checkCallbackForIf)
}
@TestMetadata("retention.kt")
fun testRetention() {
doTest("retention", ::checkCallbackForRetention)
}
}
@TestMetadata("uast-kotlin-fir/testData/type")
@TestDataPath("/")
@RunWith(JUnit3RunnerWithInners::class)
class Type : AbstractFE1UastTest(), UastResolveApiTestBase {
override var testDataDir = KotlinRoot.DIR_PATH.resolve("uast/uast-kotlin-fir/testData/type").toFile()
override val isFirUastPlugin: Boolean = false
override fun check(testName: String, file: UFile) {
// Bogus
}
@TestMetadata("threadSafe.kt")
fun testThreadSafe() {
doTest("threadSafe", ::checkThreadSafe)
}
}
@TestMetadata("uast-kotlin/tests/testData")
@TestDataPath("/")
@RunWith(JUnit3RunnerWithInners::class)
class Legacy : AbstractFE1UastTest(), UastResolveApiTestBase {
override var testDataDir = KotlinRoot.DIR.resolve("uast/uast-kotlin/tests/testData")
override val isFirUastPlugin: Boolean = false
override fun check(testName: String, file: UFile) {
// Bogus
}
@TestMetadata("MethodReference.kt")
fun testMethodReference() {
doTest("MethodReference", ::checkCallbackForMethodReference)
}
@TestMetadata("Imports.kt")
fun testImports() {
doTest("Imports", ::checkCallbackForImports)
}
@TestMetadata("ReceiverFun.kt")
fun testReceiverFun() {
doTest("ReceiverFun", ::checkCallbackForReceiverFun)
}
}
}
| apache-2.0 |
apollographql/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/adapter/ResponseAdapterBuilder.kt | 1 | 983 | package com.apollographql.apollo3.compiler.codegen.kotlin.adapter
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinContext
import com.apollographql.apollo3.compiler.ir.IrModelGroup
import com.squareup.kotlinpoet.TypeSpec
interface ResponseAdapterBuilder {
fun prepare()
fun build(): List<TypeSpec>
companion object {
fun create(
context: KotlinContext,
modelGroup: IrModelGroup,
path: List<String>,
public: Boolean
): ResponseAdapterBuilder = when(modelGroup.models.size) {
0 -> error("Don't know how to create an adapter for a scalar type")
1 -> MonomorphicFieldResponseAdapterBuilder(
context = context,
model = modelGroup.models.first(),
path = path,
public = public
)
else -> PolymorphicFieldResponseAdapterBuilder(
context = context,
modelGroup = modelGroup,
path = path,
public = public
)
}
}
}
| mit |
stoyicker/dinger | data/src/main/kotlin/data/tinder/recommendation/RecommendationSourceModule.kt | 1 | 2326 | package data.tinder.recommendation
import android.content.Context
import com.nytimes.android.external.fs3.FileSystemRecordPersister
import com.nytimes.android.external.fs3.filesystem.FileSystemFactory
import com.nytimes.android.external.store3.base.Fetcher
import com.nytimes.android.external.store3.base.impl.FluentMemoryPolicyBuilder
import com.nytimes.android.external.store3.base.impl.FluentStoreBuilder.Companion.parsedWithKey
import com.nytimes.android.external.store3.base.impl.StalePolicy
import com.nytimes.android.external.store3.base.impl.Store
import com.nytimes.android.external.store3.middleware.moshi.MoshiParserFactory
import com.squareup.moshi.Moshi
import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter
import dagger.Module
import dagger.Provides
import data.crash.CrashReporterModule
import data.network.ParserModule
import data.tinder.TinderApi
import data.tinder.TinderApiModule
import okio.BufferedSource
import reporter.CrashReporter
import java.util.Date
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
import dagger.Lazy as DaggerLazy
@Module(includes = [
ParserModule::class, TinderApiModule::class, CrashReporterModule::class])
internal class RecommendationSourceModule {
@Provides
@Singleton
fun store(context: Context, moshiBuilder: Moshi.Builder, api: TinderApi) =
parsedWithKey<Unit, BufferedSource, RecommendationResponse>(
Fetcher { fetch(api) }) {
parsers = listOf(MoshiParserFactory.createSourceParser(moshiBuilder
.add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe())
.build(),
RecommendationResponse::class.java))
persister = FileSystemRecordPersister.create(
FileSystemFactory.create(context.externalCacheDir!!),
{ it.toString() },
7,
TimeUnit.DAYS)
memoryPolicy = FluentMemoryPolicyBuilder.build {
expireAfterWrite = 30
expireAfterTimeUnit = TimeUnit.MINUTES
}
stalePolicy = StalePolicy.NETWORK_BEFORE_STALE
}
@Provides
@Singleton
fun source(store: DaggerLazy<Store<RecommendationResponse, Unit>>,
crashReporter: CrashReporter) = GetRecommendationSource(store, crashReporter)
private fun fetch(api: TinderApi) = api.getRecommendations().map { it.source() }
}
| mit |
androidx/androidx | compose/material/material/src/androidAndroidTest/kotlin/androidx/compose/material/NavigationRailScreenshotTest.kt | 3 | 9411 | /*
* 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.material
import android.os.Build
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.layout.Box
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.testutils.assertAgainstGolden
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.captureToImage
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import androidx.test.screenshot.AndroidXScreenshotTestRule
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@OptIn(ExperimentalTestApi::class)
class NavigationRailScreenshotTest {
@get:Rule
val composeTestRule = createComposeRule()
@get:Rule
val screenshotRule = AndroidXScreenshotTestRule(GOLDEN_MATERIAL)
@Test
fun lightTheme_defaultColors() {
val interactionSource = MutableInteractionSource()
var scope: CoroutineScope? = null
composeTestRule.setContent {
MaterialTheme(lightColors()) {
scope = rememberCoroutineScope()
DefaultNavigationRail(interactionSource)
}
}
assertNavigationRailMatches(
scope = scope!!,
interactionSource = interactionSource,
interaction = null,
goldenIdentifier = "navigationRail_lightTheme_defaultColors"
)
}
@Test
fun lightTheme_defaultColors_pressed() {
val interactionSource = MutableInteractionSource()
var scope: CoroutineScope? = null
composeTestRule.setContent {
MaterialTheme(lightColors()) {
scope = rememberCoroutineScope()
DefaultNavigationRail(interactionSource)
}
}
assertNavigationRailMatches(
scope = scope!!,
interactionSource = interactionSource,
interaction = PressInteraction.Press(Offset(10f, 10f)),
goldenIdentifier = "navigationRail_lightTheme_defaultColors_pressed"
)
}
@Test
fun darkTheme_defaultColors() {
val interactionSource = MutableInteractionSource()
var scope: CoroutineScope? = null
composeTestRule.setContent {
MaterialTheme(darkColors()) {
scope = rememberCoroutineScope()
DefaultNavigationRail(interactionSource)
}
}
assertNavigationRailMatches(
scope = scope!!,
interactionSource = interactionSource,
interaction = null,
goldenIdentifier = "navigationRail_darkTheme_defaultColors"
)
}
@Test
fun darkTheme_defaultColors_pressed() {
val interactionSource = MutableInteractionSource()
var scope: CoroutineScope? = null
composeTestRule.setContent {
MaterialTheme(darkColors()) {
scope = rememberCoroutineScope()
DefaultNavigationRail(interactionSource)
}
}
assertNavigationRailMatches(
scope = scope!!,
interactionSource = interactionSource,
interaction = PressInteraction.Press(Offset(10f, 10f)),
goldenIdentifier = "navigationRail_darkTheme_defaultColors_pressed"
)
}
@Test
fun lightTheme_defaultColors_withHeaderFab() {
val interactionSource = MutableInteractionSource()
var scope: CoroutineScope? = null
composeTestRule.setContent {
MaterialTheme(lightColors()) {
scope = rememberCoroutineScope()
DefaultNavigationRail(interactionSource, withHeaderFab = true)
}
}
assertNavigationRailMatches(
scope = scope!!,
interactionSource = interactionSource,
interaction = null,
goldenIdentifier = "navigationRail_lightTheme_defaultColors_withFab"
)
}
@Test
fun lightTheme_defaultColors_withHeaderFab_pressed() {
val interactionSource = MutableInteractionSource()
var scope: CoroutineScope? = null
composeTestRule.setContent {
MaterialTheme(lightColors()) {
scope = rememberCoroutineScope()
DefaultNavigationRail(interactionSource, withHeaderFab = true)
}
}
assertNavigationRailMatches(
scope = scope!!,
interactionSource = interactionSource,
interaction = PressInteraction.Press(Offset(10f, 100f)),
goldenIdentifier = "navigationRail_lightTheme_defaultColors_withFab_pressed"
)
}
/**
* Asserts that the NavigationRail matches the screenshot with identifier [goldenIdentifier].
*
* @param scope [CoroutineScope] used to interact with [MutableInteractionSource]
* @param interactionSource the [MutableInteractionSource] used for the first
* NavigationRailItem
* @param interaction the [Interaction] to assert for, or `null` if no [Interaction].
* @param goldenIdentifier the identifier for the corresponding screenshot
*/
private fun assertNavigationRailMatches(
scope: CoroutineScope,
interactionSource: MutableInteractionSource,
interaction: Interaction? = null,
goldenIdentifier: String
) {
if (interaction != null) {
composeTestRule.runOnIdle {
// Start ripple
scope.launch {
interactionSource.emit(interaction)
}
}
composeTestRule.waitForIdle()
// Ripples are drawn on the RenderThread, not the main (UI) thread, so we can't
// properly wait for synchronization. Instead just wait until after the ripples are
// finished animating.
Thread.sleep(300)
}
// Capture and compare screenshots
composeTestRule.onNodeWithTag(Tag)
.captureToImage()
.assertAgainstGolden(screenshotRule, goldenIdentifier)
}
}
/**
* Default colored [NavigationRailItem] with three [NavigationRailItem]s. The first
* [NavigationRailItem] is selected, and the rest are not.
*
* @param interactionSource the [MutableInteractionSource] for the first [NavigationRailItem], to
* control its visual state.
* @param withHeaderFab when true, shows a [FloatingActionButton] as the [NavigationRail] header.
*/
@Composable
private fun DefaultNavigationRail(
interactionSource: MutableInteractionSource,
withHeaderFab: Boolean = false
) {
Box(Modifier.semantics(mergeDescendants = true) {}.testTag(Tag)) {
NavigationRail(
header = if (withHeaderFab) {
{ HeaderFab() }
} else {
null
}
) {
NavigationRailItem(
icon = { Icon(Icons.Filled.Favorite, null) },
label = { Text("Favorites") },
selected = true,
onClick = {},
interactionSource = interactionSource
)
NavigationRailItem(
icon = { Icon(Icons.Filled.Home, null) },
label = { Text("Home") },
selected = false,
onClick = {}
)
NavigationRailItem(
icon = { Icon(Icons.Filled.Search, null) },
label = { Text("Search") },
selected = false,
onClick = {}
)
}
}
}
/**
* Default [FloatingActionButton] to be used along with the [DefaultNavigationRail] when the
* withHeaderFab flag is true.
*/
@Composable
private fun HeaderFab() {
FloatingActionButton(
onClick = { },
) {
Icon(Icons.Filled.Edit, contentDescription = "Edit")
}
}
private const val Tag = "NavigationRail" | apache-2.0 |
androidx/androidx | bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/Bundleable.kt | 3 | 1579 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.bluetooth.core
import android.os.Bundle
import androidx.annotation.RestrictTo
/**
* A class that serializes and stores an object for sending over IPC.
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
interface Bundleable {
/**
* Returns a [Bundle] representing the information stored in this object.
*/
fun toBundle(): Bundle
/**
* Interface for the static `CREATOR` field of [Bundleable] classes.
*/
interface Creator<T : Bundleable> {
/**
* Restores a [Bundleable] instance from a [Bundle] produced by [Bundleable.toBundle].
*
*
* It guarantees the compatibility of [Bundle] representations produced by different
* versions of [Bundleable.toBundle] by providing best default values for missing
* fields. It throws an exception if any essential fields are missing.
*/
fun fromBundle(bundle: Bundle): T
}
} | apache-2.0 |
androidx/androidx | compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/layout/RtlLayoutTest.kt | 3 | 16188 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.layout
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.FixedSize
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.node.Ref
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.runOnUiThreadIR
import androidx.compose.ui.test.TestActivity
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.math.abs
import kotlin.math.roundToInt
@SmallTest
@RunWith(AndroidJUnit4::class)
class RtlLayoutTest {
@Suppress("DEPRECATION")
@get:Rule
val activityTestRule =
androidx.test.rule.ActivityTestRule<TestActivity>(
TestActivity::class.java
)
private lateinit var activity: TestActivity
internal lateinit var density: Density
internal lateinit var countDownLatch: CountDownLatch
internal lateinit var position: Array<Ref<Offset>>
private val size = 100
@Before
fun setup() {
activity = activityTestRule.activity
density = Density(activity)
activity.hasFocusLatch.await(5, TimeUnit.SECONDS)
position = Array(3) { Ref<Offset>() }
countDownLatch = CountDownLatch(3)
}
@Test
fun customLayout_absolutePositioning() = with(density) {
activityTestRule.runOnUiThreadIR {
activity.setContent {
CustomLayout(true, LayoutDirection.Ltr)
}
}
countDownLatch.await(1, TimeUnit.SECONDS)
assertEquals(Offset(0f, 0f), position[0].value)
assertEquals(Offset(size.toFloat(), size.toFloat()), position[1].value)
assertEquals(
Offset(
(size * 2).toFloat(),
(size * 2).toFloat()
),
position[2].value
)
}
@Test
fun customLayout_absolutePositioning_rtl() = with(density) {
activityTestRule.runOnUiThreadIR {
activity.setContent {
CustomLayout(true, LayoutDirection.Rtl)
}
}
countDownLatch.await(1, TimeUnit.SECONDS)
assertEquals(
Offset(0f, 0f),
position[0].value
)
assertEquals(
Offset(
size.toFloat(),
size.toFloat()
),
position[1].value
)
assertEquals(
Offset(
(size * 2).toFloat(),
(size * 2).toFloat()
),
position[2].value
)
}
@Test
fun customLayout_positioning() = with(density) {
activityTestRule.runOnUiThreadIR {
activity.setContent {
CustomLayout(false, LayoutDirection.Ltr)
}
}
countDownLatch.await(1, TimeUnit.SECONDS)
assertEquals(Offset(0f, 0f), position[0].value)
assertEquals(Offset(size.toFloat(), size.toFloat()), position[1].value)
assertEquals(
Offset(
(size * 2).toFloat(),
(size * 2).toFloat()
),
position[2].value
)
}
@Test
fun customLayout_positioning_rtl() = with(density) {
activityTestRule.runOnUiThreadIR {
activity.setContent {
CustomLayout(false, LayoutDirection.Rtl)
}
}
countDownLatch.await(1, TimeUnit.SECONDS)
countDownLatch.await(1, TimeUnit.SECONDS)
assertEquals(
Offset(
(size * 2).toFloat(),
0f
),
position[0].value
)
assertEquals(
Offset(size.toFloat(), size.toFloat()),
position[1].value
)
assertEquals(Offset(0f, (size * 2).toFloat()), position[2].value)
}
@Test
fun customLayout_updatingDirectionCausesRemeasure() {
val direction = mutableStateOf(LayoutDirection.Rtl)
var latch = CountDownLatch(1)
var actualDirection: LayoutDirection? = null
activityTestRule.runOnUiThread {
activity.setContent {
val children = @Composable {
Layout({}) { _, _ ->
actualDirection = layoutDirection
latch.countDown()
layout(100, 100) {}
}
}
CompositionLocalProvider(LocalLayoutDirection provides direction.value) {
Layout(children) { measurables, constraints ->
layout(100, 100) {
measurables.first().measure(constraints).placeRelative(0, 0)
}
}
}
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
assertEquals(LayoutDirection.Rtl, actualDirection)
latch = CountDownLatch(1)
activityTestRule.runOnUiThread { direction.value = LayoutDirection.Ltr }
assertTrue(latch.await(1, TimeUnit.SECONDS))
assertEquals(LayoutDirection.Ltr, actualDirection)
}
@Test
fun testModifiedLayoutDirection_inMeasureScope() {
val latch = CountDownLatch(1)
val resultLayoutDirection = Ref<LayoutDirection>()
activityTestRule.runOnUiThread {
activity.setContent {
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
Layout(content = {}) { _, _ ->
resultLayoutDirection.value = layoutDirection
latch.countDown()
layout(0, 0) {}
}
}
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
assertTrue(LayoutDirection.Rtl == resultLayoutDirection.value)
}
@Test
fun testModifiedLayoutDirection_inIntrinsicsMeasure() {
val latch = CountDownLatch(1)
var resultLayoutDirection: LayoutDirection? = null
activityTestRule.runOnUiThread {
activity.setContent {
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
val measurePolicy = object : MeasurePolicy {
override fun MeasureScope.measure(
measurables: List<Measurable>,
constraints: Constraints
) = layout(0, 0) {}
override fun IntrinsicMeasureScope.minIntrinsicWidth(
measurables: List<IntrinsicMeasurable>,
height: Int
) = 0
override fun IntrinsicMeasureScope.minIntrinsicHeight(
measurables: List<IntrinsicMeasurable>,
width: Int
) = 0
override fun IntrinsicMeasureScope.maxIntrinsicWidth(
measurables: List<IntrinsicMeasurable>,
height: Int
): Int {
resultLayoutDirection = this.layoutDirection
latch.countDown()
return 0
}
override fun IntrinsicMeasureScope.maxIntrinsicHeight(
measurables: List<IntrinsicMeasurable>,
width: Int
) = 0
}
Layout(
content = {},
modifier = Modifier.width(IntrinsicSize.Max),
measurePolicy = measurePolicy
)
}
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
Assert.assertNotNull(resultLayoutDirection)
assertTrue(LayoutDirection.Rtl == resultLayoutDirection)
}
@Test
fun testRestoreLocaleLayoutDirection() {
val latch = CountDownLatch(1)
val resultLayoutDirection = Ref<LayoutDirection>()
activityTestRule.runOnUiThread {
activity.setContent {
val initialLayoutDirection = LocalLayoutDirection.current
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
Box {
CompositionLocalProvider(
LocalLayoutDirection provides initialLayoutDirection
) {
Layout({}) { _, _ ->
resultLayoutDirection.value = layoutDirection
latch.countDown()
layout(0, 0) {}
}
}
}
}
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
assertEquals(LayoutDirection.Ltr, resultLayoutDirection.value)
}
@Test
fun testChildGetsPlacedWithinContainerWithPaddingAndMinimumTouchTarget() {
// copy-pasted from TouchTarget.kt (internal in material module)
class MinimumTouchTargetModifier(val size: DpSize = DpSize(48.dp, 48.dp)) : LayoutModifier {
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
val placeable = measurable.measure(constraints)
val width = maxOf(placeable.width, size.width.roundToPx())
val height = maxOf(placeable.height, size.height.roundToPx())
return layout(width, height) {
val centerX = ((width - placeable.width) / 2f).roundToInt()
val centerY = ((height - placeable.height) / 2f).roundToInt()
placeable.place(centerX, centerY)
}
}
override fun equals(other: Any?): Boolean {
val otherModifier = other as? MinimumTouchTargetModifier ?: return false
return size == otherModifier.size
}
override fun hashCode(): Int = size.hashCode()
}
val latch = CountDownLatch(2)
var outerLC: LayoutCoordinates? = null
var innerLC: LayoutCoordinates? = null
var density: Density? = null
val rowWidth = 200.dp
val outerBoxWidth = 56.dp
val padding = 16.dp
activityTestRule.runOnUiThread {
activity.setContent {
density = LocalDensity.current
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
Row(modifier = Modifier.width(rowWidth)) {
Box(
modifier = Modifier
.onGloballyPositioned {
outerLC = it
latch.countDown()
}
.size(outerBoxWidth)
.background(color = Color.Red)
.padding(horizontal = padding)
.then(MinimumTouchTargetModifier())
) {
Box(
modifier = Modifier
.onGloballyPositioned {
innerLC = it
latch.countDown()
}
.size(30.dp)
.background(color = Color.Gray)
)
}
}
}
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
val (innerOffset, innerWidth) = with(innerLC!!) {
localToWindow(Offset.Zero) to size.width
}
val (outerOffset, outerWidth) = with(outerLC!!) {
localToWindow(Offset.Zero) to size.width
}
assertTrue(innerWidth < outerWidth)
assertTrue(innerOffset.x > outerOffset.x)
assertTrue(innerWidth + innerOffset.x < outerWidth + outerOffset.x)
with(density!!) {
assertEquals(outerOffset.x.roundToInt(), rowWidth.roundToPx() - outerWidth)
val paddingPx = padding.roundToPx()
// OuterBoxLeftEdge_padding-16dp_InnerBoxLeftEdge
assertTrue(abs(outerOffset.x + paddingPx - innerOffset.x) <= 1.0)
// InnerBoxRightEdge_padding-16dp_OuterRightEdge
val outerRightEdge = outerOffset.x + outerWidth
assertTrue(abs(outerRightEdge - paddingPx - (innerOffset.x + innerWidth)) <= 1)
}
}
@Composable
private fun CustomLayout(
absolutePositioning: Boolean,
testLayoutDirection: LayoutDirection
) {
CompositionLocalProvider(LocalLayoutDirection provides testLayoutDirection) {
Layout(
content = {
FixedSize(size, modifier = Modifier.saveLayoutInfo(position[0], countDownLatch))
FixedSize(size, modifier = Modifier.saveLayoutInfo(position[1], countDownLatch))
FixedSize(size, modifier = Modifier.saveLayoutInfo(position[2], countDownLatch))
}
) { measurables, constraints ->
val placeables = measurables.map { it.measure(constraints) }
val width = placeables.fold(0) { sum, p -> sum + p.width }
val height = placeables.fold(0) { sum, p -> sum + p.height }
layout(width, height) {
var x = 0
var y = 0
for (placeable in placeables) {
if (absolutePositioning) {
placeable.place(x, y)
} else {
placeable.placeRelative(x, y)
}
x += placeable.width
y += placeable.height
}
}
}
}
}
private fun Modifier.saveLayoutInfo(
position: Ref<Offset>,
countDownLatch: CountDownLatch
): Modifier = onGloballyPositioned {
position.value = it.localToRoot(Offset(0f, 0f))
countDownLatch.countDown()
}
}
| apache-2.0 |
SimpleMobileTools/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/extensions/List.kt | 1 | 633 | package com.simplemobiletools.commons.extensions
import java.util.*
fun List<String>.getMimeType(): String {
val mimeGroups = HashSet<String>(size)
val subtypes = HashSet<String>(size)
forEach {
val parts = it.getMimeType().split("/")
if (parts.size == 2) {
mimeGroups.add(parts.getOrElse(0) { "" })
subtypes.add(parts.getOrElse(1) { "" })
} else {
return "*/*"
}
}
return when {
subtypes.size == 1 -> "${mimeGroups.first()}/${subtypes.first()}"
mimeGroups.size == 1 -> "${mimeGroups.first()}/*"
else -> "*/*"
}
}
| gpl-3.0 |
kamerok/Orny | app/src/main/kotlin/com/kamer/orny/di/app/features/AddExpenseModule.kt | 1 | 1504 | package com.kamer.orny.di.app.features
import android.arch.lifecycle.ViewModelProviders
import android.support.v4.app.FragmentActivity
import com.kamer.orny.interaction.addexpense.AddExpenseInteractor
import com.kamer.orny.interaction.addexpense.AddExpenseInteractorImpl
import com.kamer.orny.presentation.addexpense.AddExpenseRouter
import com.kamer.orny.presentation.addexpense.AddExpenseRouterImpl
import com.kamer.orny.presentation.addexpense.AddExpenseViewModel
import com.kamer.orny.presentation.addexpense.AddExpenseViewModelImpl
import com.kamer.orny.presentation.core.VMProvider
import com.kamer.orny.utils.createFactory
import dagger.Binds
import dagger.Lazy
import dagger.Module
import dagger.Provides
@Module
abstract class AddExpenseModule {
@Module
companion object {
@JvmStatic
@Provides
fun provideViewModelProvider(lazyViewModel: Lazy<AddExpenseViewModelImpl>): VMProvider<AddExpenseViewModel>
= object : VMProvider<AddExpenseViewModel> {
override fun get(fragmentActivity: FragmentActivity): AddExpenseViewModel =
ViewModelProviders
.of(fragmentActivity, createFactory { lazyViewModel.get() })
.get(AddExpenseViewModelImpl::class.java)
}
}
@Binds
abstract fun bindRouter(router: AddExpenseRouterImpl): AddExpenseRouter
@Binds
abstract fun bindInteractor(interactor: AddExpenseInteractorImpl): AddExpenseInteractor
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/code-insight/inspections-k2/tests/testData/inspectionsLocal/replaceSizeCheckWithIsNotEmpty/string.kt | 2 | 58 | // WITH_STDLIB
fun foo() {
"123".length<caret> != 0
} | apache-2.0 |
GunoH/intellij-community | plugins/devkit/intellij.devkit.git/test/KotlinPluginPrePushHandlerTest.kt | 8 | 7461 | // 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.commit
import com.intellij.mock.MockVirtualFile
import com.intellij.openapi.vfs.VirtualFile
import org.junit.Test
import org.junit.experimental.runners.Enclosed
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameter
import java.nio.file.Paths
import kotlin.io.path.pathString
@RunWith(Enclosed::class)
class KotlinPluginPrePushHandlerTest {
@RunWith(Parameterized::class)
class FilesBelongToPlugin {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun provideTestParameters(): Iterable<List<Pair<String, String>>> {
return listOf(
listOf(ULTIMATE_KOTLIN_PLUGIN to "File.kt"),
listOf(COMMUNITY_KOTLIN_PLUGIN to "File.kt"),
listOf(ULTIMATE_KOTLIN_PLUGIN to "File.kts"),
listOf(COMMUNITY_KOTLIN_PLUGIN to "File.kts"),
listOf(ULTIMATE_KOTLIN_PLUGIN to "File.java"),
listOf(COMMUNITY_KOTLIN_PLUGIN to "File.java"),
listOf(ULTIMATE_KOTLIN_PLUGIN to "File.properties"),
listOf(COMMUNITY_KOTLIN_PLUGIN to "File.properties"),
listOf(ULTIMATE_KOTLIN_PLUGIN to "File.html"),
listOf(COMMUNITY_KOTLIN_PLUGIN to "File.html"),
listOf(ULTIMATE_KOTLIN_PLUGIN to "File.xml"),
listOf(COMMUNITY_KOTLIN_PLUGIN to "File.xml"),
listOf(
COMMUNITY_KOTLIN_PLUGIN to "File.kt",
"not-important-dir-A" to "whatever-file",
"not-important-dir-B" to "whatever-file"
),
listOf(
"not-important-dir-A" to "whatever-file",
COMMUNITY_KOTLIN_PLUGIN to "File.kt",
"not-important-dir-B" to "whatever-file"
),
listOf(
"not-important-dir-A" to "whatever-file",
"not-important-dir-B" to "whatever-file",
COMMUNITY_KOTLIN_PLUGIN to "File.kt"
)
)
}
}
@Parameter
lateinit var files: List<Pair<String, String>>
@Test
fun testThatChecksForFileSet() {
val filesSet = files.map { fileAt(it.first, it.second) }
assert(KotlinPluginPrePushHandler.containKotlinPluginSources(filesSet)) {
"The following set of files doesn't trigger the check: $filesSet"
}
}
}
@RunWith(Parameterized::class)
class FilesDoNotBelongToPlugin {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun provideTestParameters(): Iterable<List<Pair<String, String>>> {
return listOf(
// file path has no kotlin-plugin subdirectory
listOf("not-important-dir" to "File.kt"),
listOf(FLEET_KOTLIN_PLUGIN to "File.kt"),
// kotlin-plugin path contains subdirectories to exclude
listOf("$ULTIMATE_KOTLIN_PLUGIN/test/" to "File.kt"),
listOf("$ULTIMATE_KOTLIN_PLUGIN/testData/" to "File.kt"),
// file extensions to exclude
listOf(COMMUNITY_KOTLIN_PLUGIN to "File.iml"),
listOf(COMMUNITY_KOTLIN_PLUGIN to "File.md"),
// multiple files, none matches
listOf(
"not-important-dir" to "File.kt",
FLEET_KOTLIN_PLUGIN to "File.kt",
"$ULTIMATE_KOTLIN_PLUGIN/test/" to "File.kt",
"$ULTIMATE_KOTLIN_PLUGIN/testData/" to "File.kt",
COMMUNITY_KOTLIN_PLUGIN to "File.iml",
COMMUNITY_KOTLIN_PLUGIN to "File.md"
)
)
}
}
@Parameter
lateinit var files: List<Pair<String, String>>
@Test
fun testThatIgnoresFileSet() {
val filesSet = files.map { fileAt(it.first, it.second) }
assert(!KotlinPluginPrePushHandler.containKotlinPluginSources(filesSet)) {
"The following set of files triggered the check: $filesSet"
}
}
}
@RunWith(Parameterized::class)
class ValidCommitMessages {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun provideTestParameters(): Iterable<String> {
return listOf(
"KTIJ-123",
"(KTIJ-123)",
"[KTIJ-123]",
"{KTIJ-123}",
"'KTIJ-123'",
"`KTIJ-123`",
"\"KTIJ-123\"",
"KTIJ-123 ",
" KTIJ-123",
" KTIJ-123 ",
"KTIJ-123 header",
"Header KTIJ-123",
"Header KTIJ-123 header",
"""
Header KTIJ-123 header
Body-line-1
Body-line-N
""".trimIndent(),
"""
Header KTIJ-123 header
Body-line-1
Body-line-N
^KTIJ-123 fixed
""".trimIndent(),
"""
Header
Body-line-1
Body-line-N
^KTIJ-123 fixed
""".trimIndent(),
"""
Header
Body-line-1
Body-line-N
#KTIJ-123 fixed
""".trimIndent(),
"""
Header
Body-line-1
Body-line-N
Relates to #KTIJ-123
""".trimIndent()
)
}
}
@Parameter
lateinit var commitMessage: String
@Test
fun testThatCommitMessageIsValid() {
assert(KotlinPluginPrePushHandler.commitMessageIsCorrect(commitMessage)) {
"The following commit message was considered invalid: $commitMessage"
}
}
}
@RunWith(Parameterized::class)
class InvalidCommitMessages {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun provideTestParameters(): Iterable<String> {
return listOf(
"",
"KTIJ",
"KTIJ-",
"KTIJ-one",
"KT-123",
"IDEA-123",
"WHATEVER-123",
"Header KTIJ",
"Header KTIJ header",
"""
Header
Body-line-1
Body-line-N
""".trimIndent(),
"""
Header
Body-line-1
Body-line-N
^IDEA-123 fixed
""".trimIndent(),
"""
Header
Body-line-1
Body-line-N
#IDEA-123 fixed
""".trimIndent(),
"""
Header
Body-line-1
Body-line-N
Relates to #IDEA-123
""".trimIndent(),
)
}
}
@Parameter
lateinit var commitMessage: String
@Test
fun testThatCommitMessageIsValid() {
assert(!KotlinPluginPrePushHandler.commitMessageIsCorrect(commitMessage)) {
"The following commit message was considered as valid: $commitMessage"
}
}
}
}
private val tempDir: String = System.getProperty("java.io.tmpdir")
private const val ULTIMATE_KOTLIN_PLUGIN = "plugins/kotlin/package/"
private const val COMMUNITY_KOTLIN_PLUGIN = "community/plugins/kotlin/package/"
private const val FLEET_KOTLIN_PLUGIN = "fleet/plugins/kotlin/package/"
private fun fileAt(dirPath: String, fileName: String): VirtualFile {
val path: String = Paths.get(tempDir, *dirPath.split("/").toTypedArray(), fileName).pathString
return MockVirtualFile(path)
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/fir/testData/quickDoc/EscapeHtmlInsideCodeBlocks.kt | 4 | 628 | /**
* Code block:
* ``` kotlin
* A<T>
* ```
* Code span:
* `<T>` is type parameter
*/
class <caret>A<T>
//INFO: <div class='definition'><pre>class A<T></pre></div><div class='content'><p style='margin-top:0;padding-top:0;'>Code block:</p>
//INFO: <pre><code style='font-size:96%;'>
//INFO: <span style=""><span style="">A<T></span></span>
//INFO: </code></pre><p>Code span: <code style='font-size:96%;'><span style=""><span style=""><T></span></span></code> is type parameter</p></div><table class='sections'></table><div class='bottom'><icon src="file"/> EscapeHtmlInsideCodeBlocks.kt<br/></div>
| apache-2.0 |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/toolWindow/ToolWindowLeftToolbar.kt | 2 | 1205 | // 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.toolWindow
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.impl.AbstractDroppableStripe
import com.intellij.util.ui.JBUI
import java.awt.BorderLayout
import javax.swing.border.Border
internal class ToolWindowLeftToolbar(paneId: String, private val isPrimary: Boolean) : ToolWindowToolbar() {
override val topStripe = StripeV2(this, paneId, ToolWindowAnchor.LEFT)
override val bottomStripe = StripeV2(this, paneId, ToolWindowAnchor.BOTTOM)
init {
init()
}
val moreButton: MoreSquareStripeButton = MoreSquareStripeButton(this)
override fun getStripeFor(anchor: ToolWindowAnchor): AbstractDroppableStripe {
return when (anchor) {
ToolWindowAnchor.LEFT -> topStripe
ToolWindowAnchor.BOTTOM -> bottomStripe
else -> throw IllegalArgumentException("Wrong anchor $anchor")
}
}
override fun createBorder(): Border = JBUI.Borders.customLine(getBorderColor(), 1, 0, 0, 1)
fun initMoreButton() {
if (isPrimary) {
topStripe.parent?.add(moreButton, BorderLayout.CENTER)
}
}
} | apache-2.0 |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/ProjectDataProvider.kt | 2 | 6094 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.jetbrains.packagesearch.intellij.plugin.util.CoroutineLRUCache
import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.logInfo
import com.jetbrains.packagesearch.intellij.plugin.util.logTrace
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import org.jetbrains.idea.packagesearch.api.PackageSearchApiClient
import org.jetbrains.packagesearch.api.v2.ApiPackagesResponse
import org.jetbrains.packagesearch.api.v2.ApiRepository
import org.jetbrains.packagesearch.api.v2.ApiStandardPackage
internal class ProjectDataProvider(
private val apiClient: PackageSearchApiClient,
private val packageCache: CoroutineLRUCache<InstalledDependency, ApiStandardPackage>
) {
suspend fun fetchKnownRepositories(): List<ApiRepository> = apiClient.repositories().repositories
suspend fun doSearch(
searchQuery: String,
filterOptions: FilterOptions
): ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion> {
val repositoryIds = filterOptions.onlyRepositoryIds
return apiClient.packagesByQuery(
searchQuery = searchQuery,
onlyStable = filterOptions.onlyStable,
onlyMpp = filterOptions.onlyKotlinMultiplatform,
repositoryIds = repositoryIds.toList()
)
}
suspend fun fetchInfoFor(installedDependencies: List<InstalledDependency>, traceInfo: TraceInfo): Map<InstalledDependency, ApiStandardPackage> {
if (installedDependencies.isEmpty()) {
return emptyMap()
}
val apiInfoByDependency = fetchInfoFromCacheOrApiFor(installedDependencies, traceInfo)
val (emptyApiInfoByDependency, successfulApiInfoByDependency) =
apiInfoByDependency.partition { (_, v) -> v == null }
if (emptyApiInfoByDependency.isNotEmpty() && emptyApiInfoByDependency.size != installedDependencies.size) {
val failedDependencies = emptyApiInfoByDependency.keys
logInfo(traceInfo, "ProjectDataProvider#fetchInfoFor()") {
"Failed obtaining data for ${failedDependencies.size} dependencies"
}
}
return successfulApiInfoByDependency.filterNotNullValues()
}
private suspend fun fetchInfoFromCacheOrApiFor(
dependencies: List<InstalledDependency>,
traceInfo: TraceInfo
): Map<InstalledDependency, ApiStandardPackage?> {
logDebug(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") {
"Fetching data for ${dependencies.count()} dependencies..."
}
val remoteInfoByDependencyMap = mutableMapOf<InstalledDependency, ApiStandardPackage?>()
val packagesToFetch = mutableListOf<InstalledDependency>()
for (dependency in dependencies) {
val standardV2Package = packageCache.get(dependency)
remoteInfoByDependencyMap[dependency] = standardV2Package
if (standardV2Package == null) {
packagesToFetch += dependency
}
}
if (packagesToFetch.isEmpty()) {
logTrace(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") {
"Found all ${dependencies.count() - packagesToFetch.count()} packages in cache"
}
return remoteInfoByDependencyMap
}
packagesToFetch.asSequence()
.map { dependency -> dependency.coordinatesString }
.distinct()
.sorted()
.also {
logTrace(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") {
"Found ${dependencies.count() - packagesToFetch.count()} packages in cache, still need to fetch ${it.count()} from API"
}
}
.chunked(size = 25)
.asFlow()
.buffer(25)
.map { dependenciesToFetch -> apiClient.packagesByRange(dependenciesToFetch).packages }
.catch {
logDebug(
"${this::class.run { qualifiedName ?: simpleName ?: this }}#fetchedPackages",
it,
) { "Error while retrieving packages" }
emit(emptyList())
}
.toList()
.flatten()
.forEach { v2Package ->
val dependency = InstalledDependency.from(v2Package)
packageCache.put(dependency, v2Package)
remoteInfoByDependencyMap[dependency] = v2Package
}
return remoteInfoByDependencyMap
}
}
private fun <K, V> Map<K, V>.partition(transform: (Map.Entry<K, V>) -> Boolean): Pair<Map<K, V>, Map<K, V>> {
val trueMap = mutableMapOf<K, V>()
val falseMap = mutableMapOf<K, V>()
forEach { if (transform(it)) trueMap[it.key] = it.value else falseMap[it.key] = it.value }
return trueMap to falseMap
}
private fun <K, V> Map<K, V?>.filterNotNullValues() = buildMap<K, V> {
[email protected] { (k, v) -> if (v != null) put(k, v) }
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/hints/types/UnitLocalVariable.kt | 3 | 124 | // MODE: local_variable
fun foo() {
val x =
// indent is the same: declaration & initialization
println("Foo")
} | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.