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 | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/impl/ExternalEntityMappingImplTest.kt | 7 | 1085 | // 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.storage.impl
import com.intellij.workspaceModel.storage.createBuilderFrom
import com.intellij.workspaceModel.storage.createEmptyBuilder
import com.intellij.workspaceModel.storage.entities.test.addSampleEntity
import junit.framework.Assert.assertTrue
import org.junit.Test
class ExternalEntityMappingImplTest {
@Test
fun `mapping mutability test`() {
val initialBuilder = createEmptyBuilder()
val sampleEntity = initialBuilder.addSampleEntity("123")
val mutableMapping = initialBuilder.getMutableExternalMapping<Int>("test.my.mapping")
mutableMapping.addMapping(sampleEntity, 1)
val newBuilder = createBuilderFrom(initialBuilder)
val anotherEntity = initialBuilder.addSampleEntity("321")
mutableMapping.addMapping(anotherEntity, 2)
val anotherMapping = newBuilder.getExternalMapping<Int>("test.my.mapping")
assertTrue(anotherMapping.getEntities(2).isEmpty())
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/springUtils.kt | 4 | 1048 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.wizard.ui
import com.intellij.openapi.util.NlsSafe
import javax.swing.Spring
import javax.swing.SpringLayout
internal operator fun Spring.plus(other: Spring) = Spring.sum(this, other)
internal operator fun Spring.plus(gap: Int) = Spring.sum(this, Spring.constant(gap))
internal operator fun Spring.minus(other: Spring) = this + Spring.minus(other)
internal operator fun Spring.unaryMinus() = Spring.minus(this)
internal operator fun Spring.times(by: Float) = Spring.scale(this, by)
internal fun Int.asSpring() = Spring.constant(this)
internal operator fun SpringLayout.Constraints.get(@NlsSafe edgeName: String) = getConstraint(edgeName)
internal operator fun SpringLayout.Constraints.set(@NlsSafe edgeName: String, spring: Spring) {
setConstraint(edgeName, spring)
}
fun springMin(s1: Spring, s2: Spring) = -Spring.max(-s1, -s2)
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/code-insight/postfix-templates/src/org/jetbrains/kotlin/idea/codeInsight/postfix/KotlinParenthesizedPostfixTemplate.kt | 3 | 795 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight.postfix
import com.intellij.codeInsight.template.postfix.templates.StringBasedPostfixTemplate
import com.intellij.psi.PsiElement
internal class KotlinParenthesizedPostfixTemplate : StringBasedPostfixTemplate {
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor(provider: KotlinPostfixTemplateProvider) : super(
/* name = */ "par",
/* example = */ "(expr)",
/* selector = */ allExpressions(ValuedFilter),
/* provider = */ provider
)
override fun getTemplateString(element: PsiElement) = "(\$expr$)\$END$"
override fun getElementToRemove(expr: PsiElement) = expr
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/UsageReplacementStrategy.kt | 1 | 8095 | // 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.codeInliner
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.util.ModalityUiUtil
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.compareDescriptors
import org.jetbrains.kotlin.idea.core.targetDescriptors
import org.jetbrains.kotlin.idea.intentions.ConvertReferenceToLambdaIntention
import org.jetbrains.kotlin.idea.intentions.SpecifyExplicitLambdaSignatureIntention
import org.jetbrains.kotlin.idea.references.KtSimpleReference
import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope
import org.jetbrains.kotlin.idea.base.util.reformatted
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
interface UsageReplacementStrategy {
fun createReplacer(usage: KtReferenceExpression): (() -> KtElement?)?
companion object {
val KEY = Key<Unit>("UsageReplacementStrategy.replaceUsages")
}
}
private val LOG = Logger.getInstance(UsageReplacementStrategy::class.java)
fun UsageReplacementStrategy.replaceUsagesInWholeProject(
targetPsiElement: PsiElement,
@NlsContexts.DialogTitle progressTitle: String,
@NlsContexts.Command commandName: String,
unwrapSpecialUsages: Boolean = true,
) {
val project = targetPsiElement.project
ProgressManager.getInstance().run(
object : Task.Modal(project, progressTitle, true) {
override fun run(indicator: ProgressIndicator) {
val usages = runReadAction {
val searchScope = KotlinSourceFilterScope.projectSources(GlobalSearchScope.projectScope(project), project)
ReferencesSearch.search(targetPsiElement, searchScope)
.filterIsInstance<KtSimpleReference<KtReferenceExpression>>()
.map { ref -> ref.expression }
}
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL) {
project.executeWriteCommand(commandName) {
[email protected](usages, unwrapSpecialUsages)
}
}
}
})
}
fun UsageReplacementStrategy.replaceUsages(usages: Collection<KtReferenceExpression>, unwrapSpecialUsages: Boolean = true) {
val usagesByFile = usages.groupBy { it.containingFile }
for ((file, usagesInFile) in usagesByFile) {
usagesInFile.forEach { it.putCopyableUserData(UsageReplacementStrategy.KEY, Unit) }
// we should delete imports later to not affect other usages
val importsToDelete = mutableListOf<KtImportDirective>()
var usagesToProcess = usagesInFile
while (usagesToProcess.isNotEmpty()) {
if (processUsages(usagesToProcess, importsToDelete, unwrapSpecialUsages)) break
// some usages may get invalidated we need to find them in the tree
usagesToProcess = file.collectDescendantsOfType { it.getCopyableUserData(UsageReplacementStrategy.KEY) != null }
}
file.forEachDescendantOfType<KtSimpleNameExpression> { it.putCopyableUserData(UsageReplacementStrategy.KEY, null) }
importsToDelete.forEach { it.delete() }
}
}
/**
* @return false if some usages were invalidated
*/
private fun UsageReplacementStrategy.processUsages(
usages: List<KtReferenceExpression>,
importsToDelete: MutableList<KtImportDirective>,
unwrapSpecialUsages: Boolean,
): Boolean {
val sortedUsages = usages.sortedWith { element1, element2 ->
if (element1.parent.textRange.intersects(element2.parent.textRange)) {
compareValuesBy(element2, element1) { it.startOffset }
} else {
compareValuesBy(element1, element2) { it.startOffset }
}
}
var invalidUsagesFound = false
for (usage in sortedUsages) {
try {
if (!usage.isValid) {
invalidUsagesFound = true
continue
}
if (unwrapSpecialUsages) {
val specialUsage = unwrapSpecialUsageOrNull(usage)
if (specialUsage != null) {
createReplacer(specialUsage)?.invoke()
continue
}
}
//TODO: keep the import if we don't know how to replace some of the usages
val importDirective = usage.getStrictParentOfType<KtImportDirective>()
if (importDirective != null) {
if (!importDirective.isAllUnder && importDirective.targetDescriptors().size == 1) {
importsToDelete.add(importDirective)
}
continue
}
createReplacer(usage)?.invoke()?.parent?.parent?.parent?.reformatted(true)
} catch (e: Throwable) {
if (e is ControlFlowException) throw e
LOG.error(e)
}
}
return !invalidUsagesFound
}
fun unwrapSpecialUsageOrNull(
usage: KtReferenceExpression
): KtSimpleNameExpression? {
if (usage !is KtSimpleNameExpression) return null
when (val usageParent = usage.parent) {
is KtCallableReferenceExpression -> {
if (usageParent.callableReference != usage) return null
val (name, descriptor) = usage.nameAndDescriptor
return ConvertReferenceToLambdaIntention.applyTo(usageParent)?.let {
findNewUsage(it, name, descriptor)
}
}
is KtCallElement -> {
for (valueArgument in usageParent.valueArguments.asReversed()) {
val callableReferenceExpression = valueArgument.getArgumentExpression() as? KtCallableReferenceExpression ?: continue
ConvertReferenceToLambdaIntention.applyTo(callableReferenceExpression)
}
val lambdaExpressions = usageParent.valueArguments.mapNotNull { it.getArgumentExpression() as? KtLambdaExpression }
if (lambdaExpressions.isEmpty()) return null
val (name, descriptor) = usage.nameAndDescriptor
val grandParent = usageParent.parent
for (lambdaExpression in lambdaExpressions) {
val functionDescriptor = lambdaExpression.functionLiteral.resolveToDescriptorIfAny() as? FunctionDescriptor ?: continue
if (functionDescriptor.valueParameters.isNotEmpty()) {
SpecifyExplicitLambdaSignatureIntention.applyTo(lambdaExpression)
}
}
return grandParent.safeAs<KtElement>()?.let {
findNewUsage(it, name, descriptor)
}
}
}
return null
}
private val KtSimpleNameExpression.nameAndDescriptor get() = getReferencedName() to resolveToCall()?.candidateDescriptor
private fun findNewUsage(
element: KtElement,
targetName: String?,
targetDescriptor: DeclarationDescriptor?
): KtSimpleNameExpression? = element.findDescendantOfType {
it.getReferencedName() == targetName && compareDescriptors(it.project, targetDescriptor, it.resolveToCall()?.candidateDescriptor)
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/resolve/additionalLazyResolve/anonymousObjectInClassParameterInitializer.kt | 8 | 544 | package test
open class A
class MyClass(
a: A = object: A() {
}
)
//package test
//public open class A defined in test
//public constructor A() defined in test.A
//public final class MyClass defined in test
//public constructor MyClass(a: test.A = ...) defined in test.MyClass
//value-parameter a: test.A = ... defined in test.MyClass.`<init>`
//local final class `<no name provided>` : test.A defined in test.MyClass.`<init>`
//public constructor `<no name provided>`() defined in test.MyClass.`<init>`.`<no name provided>` | apache-2.0 |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/editor/MarkdownEnterHandler.kt | 4 | 5234 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.editor
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate.Result
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import org.intellij.plugins.markdown.injection.MarkdownCodeFenceUtils
import org.intellij.plugins.markdown.lang.formatter.settings.MarkdownCustomCodeStyleSettings
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownBlockQuote
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
import org.intellij.plugins.markdown.util.MarkdownPsiStructureUtil.isTopLevel
import org.intellij.plugins.markdown.util.MarkdownPsiUtil
/**
* Enter handler of Markdown plugin,
*
* It generates blockquotes on `enter`.
* Also it stops indentation when there is >= 2 new lines after text
*/
internal class MarkdownEnterHandler : EnterHandlerDelegateAdapter() {
/**
* During preprocessing indentation can be stopped if there are more than
* two new lines after last element of text in Markdown file.
*
* E.g. it means, that there will be no indent if you will hit enter two times
* after list item on any indent level.
*
* Also, for non-toplevel codefences indentation is implemented via preprocessing.
* The actual reason for it is that injection-based formatting does not work
* correctly in frankenstein-like injection (for example, for codefence inside blockquote)
*/
override fun preprocessEnter(file: PsiFile, editor: Editor, caretOffset: Ref<Int>, caretAdvance: Ref<Int>,
dataContext: DataContext, originalHandler: EditorActionHandler?): Result {
val offset = editor.caretModel.offset
val element = MarkdownPsiUtil.findNonWhiteSpacePrevSibling(file, offset) ?: return Result.Continue
if (!file.isValid || !shouldHandle(editor, dataContext, element)) return Result.Continue
if (shouldAbortIndentation(file, editor, caretOffset.get())) {
EditorModificationUtil.insertStringAtCaret(editor, "\n")
return Result.Stop
}
val fence = MarkdownCodeFenceUtils.getCodeFence(element)
if (fence != null && !fence.isTopLevel()) {
val indent = MarkdownCodeFenceUtils.getIndent(fence) ?: return Result.Continue
EditorModificationUtil.insertStringAtCaret(editor, "\n${indent}")
return Result.Stop
}
return Result.Continue
}
/**
* During post-processing `>` can be added if it is necessary
*/
override fun postProcessEnter(file: PsiFile, editor: Editor, dataContext: DataContext): Result {
val offset = editor.caretModel.offset
val element = MarkdownPsiUtil.findNonWhiteSpacePrevSibling(file, offset) ?: return Result.Continue
if (!file.isValid || !shouldHandle(editor, dataContext, element)) return Result.Continue
processBlockQuote(editor, element)
return Result.Continue
}
private fun processBlockQuote(editor: Editor, element: PsiElement) {
val quote = PsiTreeUtil.getParentOfType(element, MarkdownBlockQuote::class.java) ?: return
val markdown = CodeStyle.getCustomSettings(quote.containingFile, MarkdownCustomCodeStyleSettings::class.java)
var toAdd = ">"
if (markdown.FORCE_ONE_SPACE_AFTER_BLOCKQUOTE_SYMBOL) {
toAdd += " "
}
EditorModificationUtil.insertStringAtCaret(editor, toAdd)
}
/**
* Check if alignment process should not be performed for this offset at all.
*
* Alignment of enter would not be performed if there is >= 2 new lines after
* last text element.
*/
private fun shouldAbortIndentation(file: PsiFile, editor: Editor, offset: Int): Boolean {
//do not stop indentation after two spaces in code fences
if (
file !is MarkdownFile
|| file.findElementAt(offset - 1)?.let { MarkdownCodeFenceUtils.inCodeFence(it.node) } == true
) {
return false
}
val text = editor.document.charsSequence.toString()
var cur = offset - 1
while (cur > 0) {
val char = text.getOrNull(cur)
if (char == null) {
cur--
continue
}
if (char.isWhitespace().not()) {
break
}
if (char == '\n') {
return true
}
cur--
}
return false
}
private fun shouldHandle(editor: Editor, dataContext: DataContext, element: PsiElement): Boolean {
val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return false
if (!editor.document.isWritable) return false
if (InjectedLanguageManager.getInstance(project).getTopLevelFile(element) !is MarkdownFile) return false
return !editor.isViewer
}
} | apache-2.0 |
DeskChan/DeskChan | src/main/kotlin/info/deskchan/MessageData/GUI/ChooseFiles.kt | 2 | 1018 | package info.deskchan.MessageData.GUI
import info.deskchan.core.MessageData
/**
* Open file chooser dialog
*
* <b>Response type</b>: String or List<String>, as specified by @multiple parameter
*
* @property title Dialog title
* @property filters Files filters to use in dialog
* @property initialDirectory Directory to start
* @property initialFilename Initial filename
* @property multiple Select multiple files. False by default
* @property saveDialog Is current dialog is "Save file" type or it "Open file" type
* **/
@MessageData.Tag("gui:choose-file")
@MessageData.RequiresResponse
class ChooseFiles : MessageData {
var title: String? = null
var initialDirectory: String? = null
var initialFilename: String? = null
var multiple: Boolean? = null
var saveDialog: Boolean? = null
var filters: List<Filter>? = null
companion object {
val ResponseFormat: String? = null
}
class Filter(val description: String, val extensions: List<String>) : MessageData
} | lgpl-3.0 |
jk1/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/imports/GroovyFileImports.kt | 2 | 1428 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.imports
import com.intellij.psi.PsiElement
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.PsiScopeProcessor
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement
interface GroovyFileImports {
val file: GroovyFileBase
val starImports: Collection<StarImport>
val staticStarImports: Collection<StaticStarImport>
val allNamedImports: Collection<GroovyNamedImport>
fun processStaticImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean
fun processAllNamedImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean
fun processStaticStarImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean
fun processAllStarImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean
fun processDefaultImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean
fun isImplicit(import: GroovyImport): Boolean
fun findUnnecessaryStatements(): Collection<GrImportStatement>
fun findUnresolvedStatements(names: Collection<String>): Collection<GrImportStatement>
}
| apache-2.0 |
himikof/intellij-rust | src/main/kotlin/org/rust/ide/utils/PresentationUtils.kt | 1 | 8180 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.utils
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
class PresentationInfo(
element: RsNamedElement,
val type: String?,
val name: String,
private val declaration: DeclarationInfo
) {
private val location: String?
init {
location = element.containingFile?.let { " [${it.name}]" }.orEmpty()
}
val typeNameText: String get() = if (type == null) {
name
} else "$type `$name`"
val projectStructureItemText: String get() = "$name${declaration.suffix}"
val projectStructureItemTextWithValue: String get() = "$projectStructureItemText${declaration.value}"
val shortSignatureText = "<b>$name</b>${declaration.suffix.escaped}"
val signatureText: String = "${declaration.prefix}$shortSignatureText"
val quickDocumentationText: String
get() = if (declaration.isAmbiguous && type != null) {
"<i>$type:</i> "
} else {
""
} + "$signatureText${valueText.escaped}$location"
private val valueText: String get() = if (declaration.value.isEmpty()) {
""
} else {
" ${declaration.value}"
}
}
data class DeclarationInfo(
val prefix: String = "",
val suffix: String = "",
val value: String = "",
val isAmbiguous: Boolean = false
)
val RsNamedElement.presentationInfo: PresentationInfo? get() {
val elementName = name ?: return null
val declInfo = when (this) {
is RsFunction -> Pair("function", createDeclarationInfo(this, identifier, false, listOf(whereClause, retType, valueParameterList)))
is RsStructItem -> Pair("struct", createDeclarationInfo(this, identifier, false, if (blockFields != null) listOf(whereClause) else listOf(whereClause, tupleFields)))
is RsFieldDecl -> Pair("field", createDeclarationInfo(this, identifier, false, listOf(typeReference)))
is RsEnumItem -> Pair("enum", createDeclarationInfo(this, identifier, false, listOf(whereClause)))
is RsEnumVariant -> Pair("enum variant", createDeclarationInfo(this, identifier, false, listOf(tupleFields)))
is RsTraitItem -> Pair("trait", createDeclarationInfo(this, identifier, false, listOf(whereClause)))
is RsTypeAlias -> Pair("type alias", createDeclarationInfo(this, identifier, false, listOf(typeReference, typeParamBounds, whereClause), eq))
is RsConstant -> Pair("constant", createDeclarationInfo(this, identifier, false, listOf(expr, typeReference), eq))
is RsSelfParameter -> Pair("parameter", createDeclarationInfo(this, self, false, listOf(typeReference)))
is RsTypeParameter -> Pair("type parameter", createDeclarationInfo(this, identifier, true))
is RsLifetimeDecl -> Pair("lifetime", createDeclarationInfo(this, quoteIdentifier, true))
is RsModItem -> Pair("module", createDeclarationInfo(this, identifier, false))
is RsLabelDecl -> {
val p = parent
when (p) {
is RsLoopExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.loop)))
is RsForExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.expr, p.`in`, p.`for`)))
is RsWhileExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.condition, p.`while`)))
else -> Pair("label", createDeclarationInfo(this, quoteIdentifier, true))
}
}
is RsPatBinding -> {
val patOwner = topLevelPattern.parent
when (patOwner) {
is RsLetDecl -> Pair("variable", createDeclarationInfo(patOwner, identifier, false, listOf(patOwner.typeReference)))
is RsValueParameter -> Pair("value parameter", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.typeReference)))
is RsMatchArm -> Pair("match arm binding", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.patList.lastOrNull())))
is RsCondition -> Pair("condition binding", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.lastChild)))
else -> Pair("binding", createDeclarationInfo(this, identifier, true))
}
}
is RsFile -> {
val mName = modName
if (isCrateRoot) return PresentationInfo(this, "crate", "crate", DeclarationInfo())
else if (mName != null) return PresentationInfo(this, "mod", name.substringBeforeLast(".rs"), DeclarationInfo("mod "))
else Pair("file", DeclarationInfo())
}
else -> Pair(javaClass.simpleName, createDeclarationInfo(this, navigationElement, true))
}
return declInfo.second?.let { PresentationInfo(this, declInfo.first, elementName, it) }
}
val RsDocAndAttributeOwner.presentableQualifiedName: String? get() {
val qName = (this as? RsQualifiedNamedElement)?.qualifiedName
if (qName != null) return qName
if (this is RsMod) return modName
return name
}
private fun createDeclarationInfo(decl: RsCompositeElement, name: PsiElement?, isAmbiguous: Boolean, stopAt: List<PsiElement?> = emptyList(), valueSeparator: PsiElement? = null): DeclarationInfo? {
// Break an element declaration into elements. For example:
//
// pub const Foo: u32 = 100;
// ^^^^^^^^^ signature prefix
// ^^^ name
// ^^^^^ signature suffix
// ^^^^^ value
// ^ end
if (name == null) return null
// Remove leading spaces, comments and attributes
val signatureStart = generateSequence(decl.firstChild) { it.nextSibling }
.dropWhile { it is PsiWhiteSpace || it is PsiComment || it is RsOuterAttr }
.firstOrNull()
?.startOffsetInParent ?: return null
val nameStart = name.offsetIn(decl)
// pick (in order) elements we should stop at
// if they all fail, drop down to the end of the name element
val end = stopAt
.filterNotNull().firstOrNull()
?.let { it.startOffsetInParent + it.textLength }
?: nameStart + name.textLength
val valueStart = valueSeparator?.offsetIn(decl) ?: end
val nameEnd = nameStart + name.textLength
check(signatureStart <= nameStart && nameEnd <= valueStart
&& valueStart <= end && end <= decl.textLength)
val prefix = decl.text.substring(signatureStart, nameStart).escaped
val value = decl.text.substring(valueStart, end)
val suffix = decl.text.substring(nameEnd, end - value.length)
.replace("""\s+""".toRegex(), " ")
.replace("( ", "(")
.replace(" )", ")")
.replace(" ,", ",")
.trimEnd()
return DeclarationInfo(prefix, suffix, value, isAmbiguous)
}
private fun PsiElement.offsetIn(owner: PsiElement): Int =
ancestors.takeWhile { it != owner }.sumBy { it.startOffsetInParent }
val String.escaped: String get() = StringUtil.escapeXml(this)
fun breadcrumbName(e: RsCompositeElement): String? {
fun lastComponentWithoutGenerics(path: RsPath) = path.referenceName
return when (e) {
is RsMacroDefinition -> e.name?.let { "$it!" }
is RsModItem, is RsStructOrEnumItemElement, is RsTraitItem, is RsConstant ->
(e as RsNamedElement).name
is RsImplItem -> {
val typeName = run {
val typeReference = e.typeReference
(typeReference?.typeElement as? RsBaseType)?.path?.let { lastComponentWithoutGenerics(it) }
?: typeReference?.text
?: return null
}
val traitName = e.traitRef?.path?.let { lastComponentWithoutGenerics(it) }
val start = if (traitName != null) "$traitName for" else "impl"
"$start $typeName"
}
is RsFunction -> e.name?.let { "$it()" }
else -> null
}
}
| mit |
ktorio/ktor | ktor-server/ktor-server-core/jvmAndNix/test/io/ktor/server/application/RouteScopedPluginTest.kt | 1 | 20069 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.application
import io.ktor.http.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import io.ktor.util.*
import io.ktor.util.pipeline.*
import kotlin.test.*
@Suppress("DEPRECATION")
class RouteScopedPluginTest {
@Test
fun testPluginInstalledTopLevel(): Unit = withTestApplication {
application.install(TestPlugin)
assertFailsWith<DuplicatePluginException> {
application.routing {
install(TestPlugin)
}
}
}
@Test
fun testPluginInstalledInRoutingScope() = withTestApplication {
val callbackResults = mutableListOf<String>()
application.routing {
route("root-no-plugin") {
route("first-plugin") {
install(TestPlugin) {
name = "foo"
desc = "test plugin"
pipelineCallback = { callbackResults.add(it) }
}
handle {
call.respond(call.receive<String>())
}
route("inner") {
route("new-plugin") {
install(TestPlugin) {
name = "bar"
pipelineCallback = { callbackResults.add(it) }
}
route("inner") {
handle {
call.respond(call.receive<String>())
}
}
handle {
call.respond(call.receive<String>())
}
}
handle {
call.respond(call.receive<String>())
}
}
}
handle {
call.respond(call.receive<String>())
}
}
}
on("making get request to /root-no-plugin") {
val result = handleRequest {
uri = "/root-no-plugin"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should not be invoked") {
assertEquals(0, callbackResults.size)
}
}
on("making get request to /root-no-plugin/first-plugin") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("foo test plugin", callbackResults[0])
callbackResults.clear()
}
}
on("making get request to /root-no-plugin/first-plugin/inner") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin/inner"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("foo test plugin", callbackResults[0])
callbackResults.clear()
}
}
on("making get request to /root-no-plugin/first-plugin/inner/new-plugin") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin/inner/new-plugin"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("bar defaultDesc", callbackResults[0])
callbackResults.clear()
}
}
on("making get request to /root-no-plugin/first-plugin/inner/new-plugin/inner") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin/inner/new-plugin/inner"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("bar defaultDesc", callbackResults[0])
callbackResults.clear()
}
}
}
@Test
fun testPluginDoNotReuseConfig() = withTestApplication {
val callbackResults = mutableListOf<String>()
application.routing {
route("root") {
install(TestPlugin) {
name = "foo"
desc = "test plugin"
pipelineCallback = { callbackResults.add(it) }
}
route("plugin1") {
install(TestPlugin) {
desc = "new desc"
pipelineCallback = { callbackResults.add(it) }
}
handle {
call.respond(call.receive<String>())
}
route("plugin2") {
install(TestPlugin) {
name = "new name"
pipelineCallback = { callbackResults.add(it) }
}
handle {
call.respond(call.receive<String>())
}
}
}
handle {
call.respond(call.receive<String>())
}
}
}
on("making get request to /root") {
val result = handleRequest {
uri = "/root"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("foo test plugin", callbackResults[0])
callbackResults.clear()
}
}
on("making get request to /root/plugin1") {
val result = handleRequest {
uri = "/root/plugin1"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("defaultName new desc", callbackResults[0])
callbackResults.clear()
}
}
on("making get request to /root/plugin1/plugin2") {
val result = handleRequest {
uri = "/root/plugin1/plugin2"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("new name defaultDesc", callbackResults[0])
callbackResults.clear()
}
}
}
@Test
fun testMultiplePluginInstalledAtTheSameRoute(): Unit = withTestApplication {
assertFailsWith<DuplicatePluginException> {
application.routing {
route("root") {
install(TestPlugin)
}
route("root") {
install(TestPlugin)
}
}
}
}
@Test
fun testAllPipelinesPlugin() = withTestApplication {
val callbackResults = mutableListOf<String>()
val receiveCallbackResults = mutableListOf<String>()
val sendCallbackResults = mutableListOf<String>()
val allCallbacks = listOf(callbackResults, receiveCallbackResults, sendCallbackResults)
application.routing {
route("root-no-plugin") {
route("first-plugin") {
install(TestAllPipelinesPlugin) {
name = "foo"
desc = "test plugin"
addCallbacks(callbackResults, receiveCallbackResults, sendCallbackResults)
}
handle {
call.respond(call.receive<String>())
}
route("inner") {
route("new-plugin") {
install(TestAllPipelinesPlugin) {
name = "bar"
addCallbacks(callbackResults, receiveCallbackResults, sendCallbackResults)
}
route("inner") {
handle {
call.respond(call.receive<String>())
}
}
handle {
call.respond(call.receive<String>())
}
}
handle {
call.respond(call.receive<String>())
}
}
}
handle {
call.respond(call.receive<String>())
}
}
}
on("making get request to /root-no-plugin") {
val result = handleRequest {
uri = "/root-no-plugin"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should not be invoked") {
allCallbacks.forEach {
assertEquals(0, it.size)
}
}
}
on("making get request to /root-no-plugin/first-plugin") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
allCallbacks.forEach {
assertEquals(1, it.size)
assertEquals("foo test plugin", it[0])
it.clear()
}
}
}
on("making get request to /root-no-plugin/first-plugin/inner") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin/inner"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
allCallbacks.forEach {
assertEquals(1, it.size)
assertEquals("foo test plugin", it[0])
it.clear()
}
}
}
on("making get request to /root-no-plugin/first-plugin/inner/new-plugin") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin/inner/new-plugin"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
allCallbacks.forEach {
assertEquals(1, it.size)
assertEquals("bar defaultDesc", it[0])
it.clear()
}
}
}
on("making get request to /root-no-plugin/first-plugin/inner/new-plugin/inner") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin/inner/new-plugin/inner"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
allCallbacks.forEach {
assertEquals(1, it.size)
assertEquals("bar defaultDesc", it[0])
it.clear()
}
}
}
}
@Test
fun testCustomPhase() = withTestApplication {
val callbackResults = mutableListOf<String>()
application.routing {
route("root") {
install(TestPluginCustomPhase) {
name = "foo"
desc = "first plugin"
callback = { callbackResults.add(it) }
}
handle {
call.respond(call.receive<String>())
}
route("a") {
install(TestPluginCustomPhase) {
name = "bar"
desc = "second plugin"
callback = { callbackResults.add(it) }
}
handle {
call.respond(call.receive<String>())
}
}
}
}
on("making get request to /root") {
val result = handleRequest {
uri = "/root"
method = HttpMethod.Get
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("second callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("foo first plugin", callbackResults[0])
callbackResults.clear()
}
}
on("making get request to /root/a") {
val result = handleRequest {
uri = "/root/a"
method = HttpMethod.Get
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("second callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("bar second plugin", callbackResults[0])
callbackResults.clear()
}
}
}
private fun TestAllPipelinesPlugin.Config.addCallbacks(
callbackResults: MutableList<String>,
receiveCallbackResults: MutableList<String>,
sendCallbackResults: MutableList<String>
) {
pipelineCallback = { callbackResults.add(it) }
receivePipelineCallback = { receiveCallbackResults.add(it) }
sendPipelineCallback = { sendCallbackResults.add(it) }
}
}
class TestAllPipelinesPlugin private constructor(config: Config) {
private val pipelineCallback = config.pipelineCallback
private val receivePipelineCallback = config.receivePipelineCallback
private val sendPipelineCallback = config.sendPipelineCallback
private val name = config.name
private val desc = config.desc
fun install(pipeline: ApplicationCallPipeline) {
pipeline.intercept(ApplicationCallPipeline.Plugins) {
pipelineCallback("$name $desc")
}
pipeline.receivePipeline.intercept(ApplicationReceivePipeline.Before) {
receivePipelineCallback("$name $desc")
}
pipeline.sendPipeline.intercept(ApplicationSendPipeline.Before) {
sendPipelineCallback("$name $desc")
}
}
@KtorDsl
class Config(
name: String = "defaultName",
desc: String = "defaultDesc",
pipelineCallback: (String) -> Unit = {},
receivePipelineCallback: (String) -> Unit = {},
sendPipelineCallback: (String) -> Unit = {},
) {
var name: String = name
var desc: String = desc
var pipelineCallback = pipelineCallback
var receivePipelineCallback = receivePipelineCallback
var sendPipelineCallback = sendPipelineCallback
}
companion object Plugin : BaseRouteScopedPlugin<Config, TestAllPipelinesPlugin> {
override val key: AttributeKey<TestAllPipelinesPlugin> = AttributeKey("TestPlugin")
override fun install(pipeline: ApplicationCallPipeline, configure: Config.() -> Unit): TestAllPipelinesPlugin {
val config = Config().apply(configure)
val plugin = TestAllPipelinesPlugin(config)
return plugin.apply { install(pipeline) }
}
}
}
class TestPlugin private constructor(config: Config) {
private val pipelineCallback = config.pipelineCallback
private val name = config.name
private val desc = config.desc
fun install(pipeline: ApplicationCallPipeline) {
pipeline.intercept(ApplicationCallPipeline.Fallback) {
pipelineCallback("$name $desc")
}
}
@KtorDsl
class Config(
name: String = "defaultName",
desc: String = "defaultDesc",
pipelineCallback: (String) -> Unit = {}
) {
var name = name
var desc = desc
var pipelineCallback = pipelineCallback
}
companion object Plugin : BaseRouteScopedPlugin<Config, TestPlugin> {
override val key: AttributeKey<TestPlugin> = AttributeKey("TestPlugin")
override fun install(pipeline: ApplicationCallPipeline, configure: Config.() -> Unit): TestPlugin {
val config = Config().apply(configure)
val plugin = TestPlugin(config)
return plugin.apply { install(pipeline) }
}
}
}
class TestPluginCustomPhase private constructor(config: Config) {
private val callback = config.callback
private val name = config.name
private val desc = config.desc
fun install(pipeline: ApplicationCallPipeline) {
val phase = PipelinePhase("new phase")
pipeline.insertPhaseAfter(ApplicationCallPipeline.Plugins, phase)
pipeline.intercept(phase) {
callback("$name $desc")
}
}
@KtorDsl
class Config(
name: String = "defaultName",
desc: String = "defaultDesc",
callback: (String) -> Unit = {},
) {
var name = name
var desc = desc
var callback = callback
}
companion object Plugin : BaseRouteScopedPlugin<Config, TestPluginCustomPhase> {
override val key: AttributeKey<TestPluginCustomPhase> = AttributeKey("TestPlugin")
override fun install(pipeline: ApplicationCallPipeline, configure: Config.() -> Unit): TestPluginCustomPhase {
val config = Config().apply(configure)
val plugin = TestPluginCustomPhase(config)
return plugin.apply { install(pipeline) }
}
}
}
| apache-2.0 |
google/accompanist | sample/src/main/java/com/google/accompanist/sample/MainActivity.kt | 1 | 5098 | /*
* 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
*
* 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.
*/
@file:Suppress("DEPRECATION") // ListActivity
package com.google.accompanist.sample
import android.annotation.SuppressLint
import android.app.ListActivity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ListView
import android.widget.SimpleAdapter
import java.text.Collator
import java.util.ArrayList
import java.util.Collections
import java.util.Comparator
import java.util.HashMap
/**
* A [ListActivity] which automatically populates the list of sample activities in this app
* with the category `com.google.accompanist.sample.SAMPLE_CODE`.
*/
class MainActivity : ListActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
listAdapter = SimpleAdapter(
this,
getData(intent.getStringExtra(EXTRA_PATH)),
android.R.layout.simple_list_item_1,
arrayOf("title"),
intArrayOf(android.R.id.text1)
)
listView.isTextFilterEnabled = true
}
private fun getData(prefix: String?): List<Map<String, Any>> {
val myData = ArrayList<Map<String, Any>>()
val mainIntent = Intent(Intent.ACTION_MAIN, null)
mainIntent.addCategory("com.google.accompanist.sample.SAMPLE_CODE")
@SuppressLint("QueryPermissionsNeeded") // Only querying our own Activities
val list = packageManager.queryIntentActivities(mainIntent, 0)
val prefixPath: Array<String>?
var prefixWithSlash = prefix
if (prefix.isNullOrEmpty()) {
prefixPath = null
} else {
prefixPath = prefix.split("/".toRegex()).toTypedArray()
prefixWithSlash = "$prefix/"
}
val entries = HashMap<String, Boolean>()
list.forEach { info ->
val labelSeq = info.loadLabel(packageManager)
val label = labelSeq?.toString() ?: info.activityInfo.name
if (prefixWithSlash.isNullOrEmpty() || label.startsWith(prefixWithSlash)) {
val labelPath = label.split("/".toRegex()).toTypedArray()
val nextLabel = if (prefixPath == null) labelPath[0] else labelPath[prefixPath.size]
if (prefixPath?.size ?: 0 == labelPath.size - 1) {
addItem(
data = myData,
name = nextLabel,
intent = activityIntent(
info.activityInfo.applicationInfo.packageName,
info.activityInfo.name
)
)
} else {
if (entries[nextLabel] == null) {
addItem(
data = myData,
name = nextLabel,
intent = browseIntent(
if (prefix == "") nextLabel else "$prefix/$nextLabel"
)
)
entries[nextLabel] = true
}
}
}
}
Collections.sort(myData, sDisplayNameComparator)
return myData
}
private fun activityIntent(pkg: String, componentName: String): Intent {
val result = Intent()
result.setClassName(pkg, componentName)
return result
}
private fun browseIntent(path: String): Intent {
val result = Intent()
result.setClass(this, MainActivity::class.java)
result.putExtra(EXTRA_PATH, path)
return result
}
private fun addItem(data: MutableList<Map<String, Any>>, name: String, intent: Intent) {
val temp = mutableMapOf<String, Any>()
temp["title"] = name
temp["intent"] = intent
data += temp
}
override fun onListItemClick(l: ListView, v: View, position: Int, id: Long) {
val map = l.getItemAtPosition(position) as Map<*, *>
val intent = map["intent"] as Intent?
startActivity(intent)
}
companion object {
private const val EXTRA_PATH = "com.example.android.apis.Path"
private val sDisplayNameComparator = object : Comparator<Map<String, Any>> {
private val collator = Collator.getInstance()
override fun compare(map1: Map<String, Any>, map2: Map<String, Any>): Int {
return collator.compare(map1["title"], map2["title"])
}
}
}
}
| apache-2.0 |
google/accompanist | sample/src/main/java/com/google/accompanist/sample/pager/DocsSamples.kt | 1 | 4875 | /*
* 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
*
* 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.
*/
@file:Suppress("UNUSED_ANONYMOUS_PARAMETER")
package com.google.accompanist.sample.pager
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Tab
import androidx.compose.material.TabRow
import androidx.compose.material.TabRowDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.HorizontalPagerIndicator
import com.google.accompanist.pager.VerticalPager
import com.google.accompanist.pager.VerticalPagerIndicator
import com.google.accompanist.pager.pagerTabIndicatorOffset
import com.google.accompanist.pager.rememberPagerState
import kotlinx.coroutines.flow.collect
@OptIn(ExperimentalPagerApi::class)
@Composable
fun HorizontalPagerSample() {
// Display 10 items
HorizontalPager(count = 10) { page ->
// Our page content
Text(
text = "Page: $page",
modifier = Modifier.fillMaxWidth()
)
}
}
@OptIn(ExperimentalPagerApi::class)
@Composable
fun VerticalPagerSample() {
// Display 10 items
VerticalPager(count = 10) { page ->
// Our page content
Text(
text = "Page: $page",
modifier = Modifier.fillMaxWidth()
)
}
}
@OptIn(ExperimentalPagerApi::class)
@Composable
fun HorizontalPagerIndicatorSample() {
val pagerState = rememberPagerState()
Column {
// Display 10 items
HorizontalPager(count = 10) { page ->
// Our page content
Text(
text = "Page: $page",
modifier = Modifier.fillMaxWidth()
)
}
HorizontalPagerIndicator(
pagerState = pagerState,
modifier = Modifier.padding(16.dp),
)
}
}
@OptIn(ExperimentalPagerApi::class)
@Composable
fun VerticalPagerIndicatorSample() {
val pagerState = rememberPagerState()
Row {
// Display 10 items
VerticalPager(
count = 10,
state = pagerState,
) { page ->
// Our page content
Text(
text = "Page: $page",
modifier = Modifier.fillMaxWidth()
)
}
VerticalPagerIndicator(
pagerState = pagerState,
modifier = Modifier.padding(16.dp),
)
}
}
@Suppress("UNUSED_PARAMETER")
object AnalyticsService {
fun sendPageSelectedEvent(page: Int) = Unit
}
@OptIn(ExperimentalPagerApi::class)
@Composable
fun PageChangesSample() {
val pagerState = rememberPagerState()
LaunchedEffect(pagerState) {
// Collect from the a snapshotFlow reading the currentPage
snapshotFlow { pagerState.currentPage }.collect { page ->
AnalyticsService.sendPageSelectedEvent(page)
}
}
VerticalPager(
count = 10,
state = pagerState,
) { page ->
Text(text = "Page: $page")
}
}
@OptIn(ExperimentalPagerApi::class)
@Composable
fun PagerWithTabs(pages: List<String>) {
val pagerState = rememberPagerState()
TabRow(
// Our selected tab is our current page
selectedTabIndex = pagerState.currentPage,
// Override the indicator, using the provided pagerTabIndicatorOffset modifier
indicator = { tabPositions ->
TabRowDefaults.Indicator(
Modifier.pagerTabIndicatorOffset(pagerState, tabPositions)
)
}
) {
// Add tabs for all of our pages
pages.forEachIndexed { index, title ->
Tab(
text = { Text(title) },
selected = pagerState.currentPage == index,
onClick = { /* TODO */ },
)
}
}
HorizontalPager(
count = pages.size,
state = pagerState,
) { page ->
// TODO: page content
}
}
| apache-2.0 |
ForgetAll/GankKotlin | app/src/main/java/com/xiasuhuei321/gankkotlin/util/IntentKey.kt | 1 | 286 | package com.xiasuhuei321.gankkotlin.util
/**
* Created by xiasuhuei321 on 2018/8/25.
* author:luo
* e-mail:[email protected]
*/
object IntentKey {
const val TIME_STAMP = "time_stamp"
const val IMG_URL_ARRAY = "img_url_array"
const val IMG_POSITION = "img_position"
} | apache-2.0 |
harrylefit/EazyBaseMVP | code/app/src/main/java/vn/eazy/base/mvp/example/mvp/presenter/UserPresenter.kt | 1 | 1435 | package vn.eazy.base.mvp.example.mvp.presenter
import android.app.Application
import android.util.Log
import com.trello.rxlifecycle2.android.FragmentEvent
import com.trello.rxlifecycle2.components.support.RxFragment
import com.trello.rxlifecycle2.kotlin.bindUntilEvent
import io.reactivex.functions.Consumer
import vn.eazy.base.mvp.architect.BasePresenter
import vn.eazy.base.mvp.di.scope.ActivityScope
import vn.eazy.base.mvp.example.mvp.contract.UserContract
import vn.eazy.base.mvp.example.mvp.model.entity.User
import vn.eazy.base.mvp.intergration.handler.error.ErrorHandleSubscriber
import vn.eazy.base.mvp.intergration.handler.error.RetryWithDelay
import vn.eazy.base.mvp.intergration.handler.error.RxErrorHandler
import vn.eazy.base.mvp.utils.RxUtils
import javax.inject.Inject
/**
* Created by harryle on 6/18/17.
*/
@ActivityScope
class UserPresenter @Inject
constructor(model: UserContract.Model, view: UserContract.View, handler: RxErrorHandler) : BasePresenter<UserContract.Model, UserContract.View>(model, view, handler) {
override fun useEventBus(): Boolean {
return false
}
fun getUsers() {A
mModel.getUsers()
.retryWhen { errors -> RetryWithDelay(3, 2).apply(errors) }
.compose(RxUtils.applySchedules(mView))
.bindUntilEvent(mView as RxFragment, FragmentEvent.PAUSE)
.subscribe({ Log.d("TAG", it.toString()) })
}
}
| apache-2.0 |
cfieber/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteStageHandler.kt | 1 | 9121 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spectator.api.Registry
import com.netflix.spectator.api.histogram.BucketCounter
import com.netflix.spinnaker.orca.ExecutionStatus
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.events.StageComplete
import com.netflix.spinnaker.orca.ext.afterStages
import com.netflix.spinnaker.orca.ext.failureStatus
import com.netflix.spinnaker.orca.ext.firstAfterStages
import com.netflix.spinnaker.orca.ext.syntheticStages
import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.graph.StageGraphBuilder
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.model.Task
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.q.*
import com.netflix.spinnaker.q.Queue
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.ApplicationEventPublisher
import org.springframework.stereotype.Component
import java.time.Clock
import java.util.concurrent.TimeUnit
@Component
class CompleteStageHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
@Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher,
private val clock: Clock,
override val contextParameterProcessor: ContextParameterProcessor,
private val registry: Registry,
override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory
) : OrcaMessageHandler<CompleteStage>, StageBuilderAware, ExpressionAware {
override fun handle(message: CompleteStage) {
message.withStage { stage ->
if (stage.status in setOf(RUNNING, NOT_STARTED)) {
var status = stage.determineStatus()
try {
if (status in setOf(RUNNING, NOT_STARTED) || (status.isComplete && !status.isHalt)) {
// check to see if this stage has any unplanned synthetic after stages
var afterStages = stage.firstAfterStages()
if (afterStages.isEmpty()) {
stage.planAfterStages()
afterStages = stage.firstAfterStages()
}
if (afterStages.isNotEmpty() && afterStages.any { it.status == NOT_STARTED }) {
afterStages
.filter { it.status == NOT_STARTED }
.forEach { queue.push(StartStage(message, it.id)) }
return@withStage
} else if (status == NOT_STARTED) {
// stage had no synthetic stages or tasks, which is odd but whatever
log.warn("Stage ${stage.id} (${stage.type}) of ${stage.execution.id} had no tasks or synthetic stages!")
status = SKIPPED
}
} else if (status.isFailure) {
if (stage.planOnFailureStages()) {
stage.firstAfterStages().forEach {
queue.push(StartStage(it))
}
return@withStage
}
}
stage.status = status
stage.endTime = clock.millis()
} catch (e: Exception) {
log.error("Failed to construct after stages", e)
stage.status = TERMINAL
stage.endTime = clock.millis()
}
stage.includeExpressionEvaluationSummary()
repository.storeStage(stage)
// When a synthetic stage ends with FAILED_CONTINUE, propagate that status up to the stage's
// parent so that no more of the parent's synthetic children will run.
if (stage.status == FAILED_CONTINUE && stage.syntheticStageOwner != null) {
queue.push(message.copy(stageId = stage.parentStageId!!))
} else if (stage.status in listOf(SUCCEEDED, FAILED_CONTINUE, SKIPPED)) {
stage.startNext()
} else {
queue.push(CancelStage(message))
if (stage.syntheticStageOwner == null) {
log.debug("Stage has no synthetic owner, completing execution (original message: $message)")
queue.push(CompleteExecution(message))
} else {
queue.push(message.copy(stageId = stage.parentStageId!!))
}
}
publisher.publishEvent(StageComplete(this, stage))
trackResult(stage)
}
}
}
// TODO: this should be done out of band by responding to the StageComplete event
private fun trackResult(stage: Stage) {
// We only want to record durations of parent-level stages; not synthetics.
if (stage.parentStageId != null) {
return
}
val id = registry.createId("stage.invocations.duration")
.withTag("status", stage.status.toString())
.withTag("stageType", stage.type)
.let { id ->
// TODO rz - Need to check synthetics for their cloudProvider.
stage.context["cloudProvider"]?.let {
id.withTag("cloudProvider", it.toString())
} ?: id
}
BucketCounter
.get(registry, id, { v -> bucketDuration(v) })
.record((stage.endTime ?: clock.millis()) - (stage.startTime ?: 0))
}
private fun bucketDuration(duration: Long) =
when {
duration > TimeUnit.MINUTES.toMillis(60) -> "gt60m"
duration > TimeUnit.MINUTES.toMillis(30) -> "gt30m"
duration > TimeUnit.MINUTES.toMillis(15) -> "gt15m"
duration > TimeUnit.MINUTES.toMillis(5) -> "gt5m"
else -> "lt5m"
}
override val messageType = CompleteStage::class.java
/**
* Plan any outstanding synthetic after stages.
*/
private fun Stage.planAfterStages() {
var hasPlannedStages = false
builder().buildAfterStages(this) { it: Stage ->
repository.addStage(it)
hasPlannedStages = true
}
if (hasPlannedStages) {
this.execution = repository.retrieve(this.execution.type, this.execution.id)
}
}
/**
* Plan any outstanding synthetic on failure stages.
*/
private fun Stage.planOnFailureStages(): Boolean {
// Avoid planning failure stages if _any_ with the same name are already complete
val previouslyPlannedAfterStageNames = afterStages().filter { it.status.isComplete }.map { it.name }
val graph = StageGraphBuilder.afterStages(this)
builder().onFailureStages(this, graph)
val onFailureStages = graph.build().toList()
onFailureStages.forEachIndexed { index, stage ->
if (index > 0) {
// all on failure stages should be run linearly
graph.connect(onFailureStages.get(index - 1), stage)
}
}
val alreadyPlanned = onFailureStages.any { previouslyPlannedAfterStageNames.contains(it.name) }
return if (alreadyPlanned || onFailureStages.isEmpty()) {
false
} else {
removeNotStartedSynthetics() // should be all synthetics (nothing should have been started!)
appendAfterStages(onFailureStages) {
repository.addStage(it)
}
true
}
}
private fun Stage.removeNotStartedSynthetics() {
syntheticStages()
.filter { it.status == NOT_STARTED }
.forEach { stage ->
execution
.stages
.filter { it.requisiteStageRefIds.contains(stage.id) }
.forEach {
it.requisiteStageRefIds = it.requisiteStageRefIds - stage.id
repository.addStage(it)
}
stage.removeNotStartedSynthetics() // should be all synthetics!
repository.removeStage(execution, stage.id)
}
}
}
private fun Stage.hasPlanningFailure() =
context["beforeStagePlanningFailed"] == true
private fun Stage.determineStatus(): ExecutionStatus {
val syntheticStatuses = syntheticStages().map(Stage::getStatus)
val taskStatuses = tasks.map(Task::getStatus)
val planningStatus = if (hasPlanningFailure()) listOf(failureStatus()) else emptyList()
val allStatuses = syntheticStatuses + taskStatuses + planningStatus
val afterStageStatuses = afterStages().map(Stage::getStatus)
return when {
allStatuses.isEmpty() -> NOT_STARTED
allStatuses.contains(TERMINAL) -> TERMINAL
allStatuses.contains(STOPPED) -> STOPPED
allStatuses.contains(CANCELED) -> CANCELED
allStatuses.contains(FAILED_CONTINUE) -> FAILED_CONTINUE
allStatuses.all { it == SUCCEEDED } -> SUCCEEDED
afterStageStatuses.contains(NOT_STARTED) -> RUNNING // after stages were planned but not run yet
else -> TERMINAL
}
}
| apache-2.0 |
Philip-Trettner/GlmKt | GlmKt/src/glm/vec/Int/IntVec2.kt | 1 | 19684 | package glm
data class IntVec2(val x: Int, val y: Int) {
// Initializes each element by evaluating init from 0 until 1
constructor(init: (Int) -> Int) : this(init(0), init(1))
operator fun get(idx: Int): Int = when (idx) {
0 -> x
1 -> y
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
// Operators
operator fun inc(): IntVec2 = IntVec2(x.inc(), y.inc())
operator fun dec(): IntVec2 = IntVec2(x.dec(), y.dec())
operator fun unaryPlus(): IntVec2 = IntVec2(+x, +y)
operator fun unaryMinus(): IntVec2 = IntVec2(-x, -y)
operator fun plus(rhs: IntVec2): IntVec2 = IntVec2(x + rhs.x, y + rhs.y)
operator fun minus(rhs: IntVec2): IntVec2 = IntVec2(x - rhs.x, y - rhs.y)
operator fun times(rhs: IntVec2): IntVec2 = IntVec2(x * rhs.x, y * rhs.y)
operator fun div(rhs: IntVec2): IntVec2 = IntVec2(x / rhs.x, y / rhs.y)
operator fun rem(rhs: IntVec2): IntVec2 = IntVec2(x % rhs.x, y % rhs.y)
operator fun plus(rhs: Int): IntVec2 = IntVec2(x + rhs, y + rhs)
operator fun minus(rhs: Int): IntVec2 = IntVec2(x - rhs, y - rhs)
operator fun times(rhs: Int): IntVec2 = IntVec2(x * rhs, y * rhs)
operator fun div(rhs: Int): IntVec2 = IntVec2(x / rhs, y / rhs)
operator fun rem(rhs: Int): IntVec2 = IntVec2(x % rhs, y % rhs)
inline fun map(func: (Int) -> Int): IntVec2 = IntVec2(func(x), func(y))
fun toList(): List<Int> = listOf(x, y)
// Predefined vector constants
companion object Constants {
val zero: IntVec2 = IntVec2(0, 0)
val ones: IntVec2 = IntVec2(1, 1)
val unitX: IntVec2 = IntVec2(1, 0)
val unitY: IntVec2 = IntVec2(0, 1)
}
// Conversions to Float
fun toVec(): Vec2 = Vec2(x.toFloat(), y.toFloat())
inline fun toVec(conv: (Int) -> Float): Vec2 = Vec2(conv(x), conv(y))
fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat())
inline fun toVec2(conv: (Int) -> Float): Vec2 = Vec2(conv(x), conv(y))
fun toVec3(z: Float = 0f): Vec3 = Vec3(x.toFloat(), y.toFloat(), z)
inline fun toVec3(z: Float = 0f, conv: (Int) -> Float): Vec3 = Vec3(conv(x), conv(y), z)
fun toVec4(z: Float = 0f, w: Float = 0f): Vec4 = Vec4(x.toFloat(), y.toFloat(), z, w)
inline fun toVec4(z: Float = 0f, w: Float = 0f, conv: (Int) -> Float): Vec4 = Vec4(conv(x), conv(y), z, w)
// Conversions to Float
fun toMutableVec(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat())
inline fun toMutableVec(conv: (Int) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat())
inline fun toMutableVec2(conv: (Int) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
fun toMutableVec3(z: Float = 0f): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z)
inline fun toMutableVec3(z: Float = 0f, conv: (Int) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), z)
fun toMutableVec4(z: Float = 0f, w: Float = 0f): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z, w)
inline fun toMutableVec4(z: Float = 0f, w: Float = 0f, conv: (Int) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), z, w)
// Conversions to Double
fun toDoubleVec(): DoubleVec2 = DoubleVec2(x.toDouble(), y.toDouble())
inline fun toDoubleVec(conv: (Int) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x.toDouble(), y.toDouble())
inline fun toDoubleVec2(conv: (Int) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
fun toDoubleVec3(z: Double = 0.0): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z)
inline fun toDoubleVec3(z: Double = 0.0, conv: (Int) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), z)
fun toDoubleVec4(z: Double = 0.0, w: Double = 0.0): DoubleVec4 = DoubleVec4(x.toDouble(), y.toDouble(), z, w)
inline fun toDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (Int) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), z, w)
// Conversions to Double
fun toMutableDoubleVec(): MutableDoubleVec2 = MutableDoubleVec2(x.toDouble(), y.toDouble())
inline fun toMutableDoubleVec(conv: (Int) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x.toDouble(), y.toDouble())
inline fun toMutableDoubleVec2(conv: (Int) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
fun toMutableDoubleVec3(z: Double = 0.0): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z)
inline fun toMutableDoubleVec3(z: Double = 0.0, conv: (Int) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), z)
fun toMutableDoubleVec4(z: Double = 0.0, w: Double = 0.0): MutableDoubleVec4 = MutableDoubleVec4(x.toDouble(), y.toDouble(), z, w)
inline fun toMutableDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (Int) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), z, w)
// Conversions to Int
fun toIntVec(): IntVec2 = IntVec2(x, y)
inline fun toIntVec(conv: (Int) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
fun toIntVec2(): IntVec2 = IntVec2(x, y)
inline fun toIntVec2(conv: (Int) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
fun toIntVec3(z: Int = 0): IntVec3 = IntVec3(x, y, z)
inline fun toIntVec3(z: Int = 0, conv: (Int) -> Int): IntVec3 = IntVec3(conv(x), conv(y), z)
fun toIntVec4(z: Int = 0, w: Int = 0): IntVec4 = IntVec4(x, y, z, w)
inline fun toIntVec4(z: Int = 0, w: Int = 0, conv: (Int) -> Int): IntVec4 = IntVec4(conv(x), conv(y), z, w)
// Conversions to Int
fun toMutableIntVec(): MutableIntVec2 = MutableIntVec2(x, y)
inline fun toMutableIntVec(conv: (Int) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x, y)
inline fun toMutableIntVec2(conv: (Int) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
fun toMutableIntVec3(z: Int = 0): MutableIntVec3 = MutableIntVec3(x, y, z)
inline fun toMutableIntVec3(z: Int = 0, conv: (Int) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), z)
fun toMutableIntVec4(z: Int = 0, w: Int = 0): MutableIntVec4 = MutableIntVec4(x, y, z, w)
inline fun toMutableIntVec4(z: Int = 0, w: Int = 0, conv: (Int) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), z, w)
// Conversions to Long
fun toLongVec(): LongVec2 = LongVec2(x.toLong(), y.toLong())
inline fun toLongVec(conv: (Int) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong())
inline fun toLongVec2(conv: (Int) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
fun toLongVec3(z: Long = 0L): LongVec3 = LongVec3(x.toLong(), y.toLong(), z)
inline fun toLongVec3(z: Long = 0L, conv: (Int) -> Long): LongVec3 = LongVec3(conv(x), conv(y), z)
fun toLongVec4(z: Long = 0L, w: Long = 0L): LongVec4 = LongVec4(x.toLong(), y.toLong(), z, w)
inline fun toLongVec4(z: Long = 0L, w: Long = 0L, conv: (Int) -> Long): LongVec4 = LongVec4(conv(x), conv(y), z, w)
// Conversions to Long
fun toMutableLongVec(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong())
inline fun toMutableLongVec(conv: (Int) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong())
inline fun toMutableLongVec2(conv: (Int) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
fun toMutableLongVec3(z: Long = 0L): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z)
inline fun toMutableLongVec3(z: Long = 0L, conv: (Int) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), z)
fun toMutableLongVec4(z: Long = 0L, w: Long = 0L): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z, w)
inline fun toMutableLongVec4(z: Long = 0L, w: Long = 0L, conv: (Int) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), z, w)
// Conversions to Short
fun toShortVec(): ShortVec2 = ShortVec2(x.toShort(), y.toShort())
inline fun toShortVec(conv: (Int) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort())
inline fun toShortVec2(conv: (Int) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
fun toShortVec3(z: Short = 0.toShort()): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z)
inline fun toShortVec3(z: Short = 0.toShort(), conv: (Int) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), z)
fun toShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort()): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z, w)
inline fun toShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (Int) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), z, w)
// Conversions to Short
fun toMutableShortVec(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort())
inline fun toMutableShortVec(conv: (Int) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort())
inline fun toMutableShortVec2(conv: (Int) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
fun toMutableShortVec3(z: Short = 0.toShort()): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z)
inline fun toMutableShortVec3(z: Short = 0.toShort(), conv: (Int) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), z)
fun toMutableShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort()): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z, w)
inline fun toMutableShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (Int) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), z, w)
// Conversions to Byte
fun toByteVec(): ByteVec2 = ByteVec2(x.toByte(), y.toByte())
inline fun toByteVec(conv: (Int) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
fun toByteVec2(): ByteVec2 = ByteVec2(x.toByte(), y.toByte())
inline fun toByteVec2(conv: (Int) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
fun toByteVec3(z: Byte = 0.toByte()): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z)
inline fun toByteVec3(z: Byte = 0.toByte(), conv: (Int) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), z)
fun toByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte()): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z, w)
inline fun toByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (Int) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), z, w)
// Conversions to Byte
fun toMutableByteVec(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte())
inline fun toMutableByteVec(conv: (Int) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte())
inline fun toMutableByteVec2(conv: (Int) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
fun toMutableByteVec3(z: Byte = 0.toByte()): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z)
inline fun toMutableByteVec3(z: Byte = 0.toByte(), conv: (Int) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), z)
fun toMutableByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte()): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z, w)
inline fun toMutableByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (Int) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), z, w)
// Conversions to Char
fun toCharVec(): CharVec2 = CharVec2(x.toChar(), y.toChar())
inline fun toCharVec(conv: (Int) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar())
inline fun toCharVec2(conv: (Int) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
fun toCharVec3(z: Char): CharVec3 = CharVec3(x.toChar(), y.toChar(), z)
inline fun toCharVec3(z: Char, conv: (Int) -> Char): CharVec3 = CharVec3(conv(x), conv(y), z)
fun toCharVec4(z: Char, w: Char): CharVec4 = CharVec4(x.toChar(), y.toChar(), z, w)
inline fun toCharVec4(z: Char, w: Char, conv: (Int) -> Char): CharVec4 = CharVec4(conv(x), conv(y), z, w)
// Conversions to Char
fun toMutableCharVec(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar())
inline fun toMutableCharVec(conv: (Int) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar())
inline fun toMutableCharVec2(conv: (Int) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
fun toMutableCharVec3(z: Char): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z)
inline fun toMutableCharVec3(z: Char, conv: (Int) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), z)
fun toMutableCharVec4(z: Char, w: Char): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z, w)
inline fun toMutableCharVec4(z: Char, w: Char, conv: (Int) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), z, w)
// Conversions to Boolean
fun toBoolVec(): BoolVec2 = BoolVec2(x != 0, y != 0)
inline fun toBoolVec(conv: (Int) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0, y != 0)
inline fun toBoolVec2(conv: (Int) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec3(z: Boolean = false): BoolVec3 = BoolVec3(x != 0, y != 0, z)
inline fun toBoolVec3(z: Boolean = false, conv: (Int) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), z)
fun toBoolVec4(z: Boolean = false, w: Boolean = false): BoolVec4 = BoolVec4(x != 0, y != 0, z, w)
inline fun toBoolVec4(z: Boolean = false, w: Boolean = false, conv: (Int) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), z, w)
// Conversions to Boolean
fun toMutableBoolVec(): MutableBoolVec2 = MutableBoolVec2(x != 0, y != 0)
inline fun toMutableBoolVec(conv: (Int) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0, y != 0)
inline fun toMutableBoolVec2(conv: (Int) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec3(z: Boolean = false): MutableBoolVec3 = MutableBoolVec3(x != 0, y != 0, z)
inline fun toMutableBoolVec3(z: Boolean = false, conv: (Int) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), z)
fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != 0, y != 0, z, w)
inline fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false, conv: (Int) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), z, w)
// Conversions to String
fun toStringVec(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec(conv: (Int) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec2(conv: (Int) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec3(z: String = ""): StringVec3 = StringVec3(x.toString(), y.toString(), z)
inline fun toStringVec3(z: String = "", conv: (Int) -> String): StringVec3 = StringVec3(conv(x), conv(y), z)
fun toStringVec4(z: String = "", w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z, w)
inline fun toStringVec4(z: String = "", w: String = "", conv: (Int) -> String): StringVec4 = StringVec4(conv(x), conv(y), z, w)
// Conversions to String
fun toMutableStringVec(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec(conv: (Int) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec2(conv: (Int) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec3(z: String = ""): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z)
inline fun toMutableStringVec3(z: String = "", conv: (Int) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), z)
fun toMutableStringVec4(z: String = "", w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z, w)
inline fun toMutableStringVec4(z: String = "", w: String = "", conv: (Int) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), z, w)
// Conversions to T2
inline fun <T2> toTVec(conv: (Int) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec2(conv: (Int) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec3(z: T2, conv: (Int) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), z)
inline fun <T2> toTVec4(z: T2, w: T2, conv: (Int) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), z, w)
// Conversions to T2
inline fun <T2> toMutableTVec(conv: (Int) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec2(conv: (Int) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec3(z: T2, conv: (Int) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), z)
inline fun <T2> toMutableTVec4(z: T2, w: T2, conv: (Int) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), z, w)
// Allows for swizzling, e.g. v.swizzle.xzx
inner class Swizzle {
val xx: IntVec2 get() = IntVec2(x, x)
val xy: IntVec2 get() = IntVec2(x, y)
val yx: IntVec2 get() = IntVec2(y, x)
val yy: IntVec2 get() = IntVec2(y, y)
val xxx: IntVec3 get() = IntVec3(x, x, x)
val xxy: IntVec3 get() = IntVec3(x, x, y)
val xyx: IntVec3 get() = IntVec3(x, y, x)
val xyy: IntVec3 get() = IntVec3(x, y, y)
val yxx: IntVec3 get() = IntVec3(y, x, x)
val yxy: IntVec3 get() = IntVec3(y, x, y)
val yyx: IntVec3 get() = IntVec3(y, y, x)
val yyy: IntVec3 get() = IntVec3(y, y, y)
val xxxx: IntVec4 get() = IntVec4(x, x, x, x)
val xxxy: IntVec4 get() = IntVec4(x, x, x, y)
val xxyx: IntVec4 get() = IntVec4(x, x, y, x)
val xxyy: IntVec4 get() = IntVec4(x, x, y, y)
val xyxx: IntVec4 get() = IntVec4(x, y, x, x)
val xyxy: IntVec4 get() = IntVec4(x, y, x, y)
val xyyx: IntVec4 get() = IntVec4(x, y, y, x)
val xyyy: IntVec4 get() = IntVec4(x, y, y, y)
val yxxx: IntVec4 get() = IntVec4(y, x, x, x)
val yxxy: IntVec4 get() = IntVec4(y, x, x, y)
val yxyx: IntVec4 get() = IntVec4(y, x, y, x)
val yxyy: IntVec4 get() = IntVec4(y, x, y, y)
val yyxx: IntVec4 get() = IntVec4(y, y, x, x)
val yyxy: IntVec4 get() = IntVec4(y, y, x, y)
val yyyx: IntVec4 get() = IntVec4(y, y, y, x)
val yyyy: IntVec4 get() = IntVec4(y, y, y, y)
}
val swizzle: Swizzle get() = Swizzle()
}
fun vecOf(x: Int, y: Int): IntVec2 = IntVec2(x, y)
operator fun Int.plus(rhs: IntVec2): IntVec2 = IntVec2(this + rhs.x, this + rhs.y)
operator fun Int.minus(rhs: IntVec2): IntVec2 = IntVec2(this - rhs.x, this - rhs.y)
operator fun Int.times(rhs: IntVec2): IntVec2 = IntVec2(this * rhs.x, this * rhs.y)
operator fun Int.div(rhs: IntVec2): IntVec2 = IntVec2(this / rhs.x, this / rhs.y)
operator fun Int.rem(rhs: IntVec2): IntVec2 = IntVec2(this % rhs.x, this % rhs.y)
| mit |
emoji-gen/Emoji-Android | app/src/main/java/moe/pine/emoji/view/setting/TeamListItemView.kt | 1 | 1397 | package moe.pine.emoji.view.setting
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.util.AttributeSet
import android.widget.LinearLayout
import kotlinx.android.synthetic.main.view_setting_team_list_item.view.*
import moe.pine.emoji.fragment.setting.DeleteTeamDialogFragment
import moe.pine.emoji.model.realm.SlackTeam
/**
* View for team list item
* Created by pine on May 14, 2017.
*/
class TeamListItemView : LinearLayout {
var team: SlackTeam? = null
set(value) {
this.text_view_setting_team_domain.text = value?.team.orEmpty()
this.text_view_setting_team_email.text = value?.email.orEmpty()
field = value
}
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onFinishInflate() {
super.onFinishInflate()
this.button_setting_team_delete.setOnClickListener { this.remove() }
}
private fun remove() {
val domain = this.team?.team ?: return
val activity = this.context as? AppCompatActivity
val dialog = DeleteTeamDialogFragment.newInstance(domain)
activity?.supportFragmentManager?.let { dialog.show(it, null) }
}
} | mit |
taskworld/KxAndroid | kxandroid-support-v4/src/main/kotlin/com/taskworld/kxandroid/support/v4/Activities.kt | 1 | 637 | package com.taskworld.kxandroid.support.v4
import android.app.Activity
import android.support.v4.app.ActivityOptionsCompat
import android.view.View
import android.support.v4.util.Pair as PairV4
fun Activity.kx_makeSceneTransitionAnimation(vararg sharedElement: View) =
kx_makeSceneTransitionAnimation(*sharedElement.map { it to if (KxVersion.LOLLIPOP) it.transitionName else "" }.toTypedArray())
fun Activity.kx_makeSceneTransitionAnimation(vararg sharedElements: Pair<View, String>) =
ActivityOptionsCompat.makeSceneTransitionAnimation(this, *sharedElements.map { PairV4.create(it.first, it.second) }.toTypedArray())
| mit |
Flocksserver/Androidkt-CleanArchitecture-Template | app/src/main/java/de/flocksserver/androidkt_cleanarchitecture_template/App.kt | 1 | 924 | package de.flocksserver.androidkt_cleanarchitecture_template
import android.app.Application
import android.content.Context
import de.flocksserver.androidkt_cleanarchitecture_template.di.components.ApplicationComponent
import de.flocksserver.androidkt_cleanarchitecture_template.di.components.DaggerApplicationComponent
import de.flocksserver.androidkt_cleanarchitecture_template.di.modules.ApplicationModule
/**
* Created by marcel on 19.06.17.
*/
open class App : Application() {
val applicationComponent: ApplicationComponent
get() = DaggerApplicationComponent.builder()
.applicationModule(ApplicationModule(this))
.build()
override fun onCreate() {
super.onCreate()
applicationComponent.inject(this)
}
companion object {
operator fun get(context: Context): App {
return context.applicationContext as App
}
}
} | apache-2.0 |
code-disaster/lwjgl3 | modules/generator/src/main/kotlin/org/lwjgl/generator/Structs.kt | 1 | 117108 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.generator
import java.io.*
import java.nio.file.*
private const val STRUCT = "struct"
private val KEYWORDS = JAVA_KEYWORDS + setOf(
// Object
"equals", "getClass", "hashCode", "notify", "notifyAll", "toString", "wait",
// Pointer
"address",
// AutoCloseable
"close",
// NativeResource
"free",
// Struct
"create", "callocStack", "calloc", "isNull", "malloc", "mallocStack", "sizeof"
)
private val BUFFER_KEYWORDS = setOf(
// Iterable
"iterator", "forEach", "spliterator",
// CustomBuffer
"address0", "capacity", "clear", "compact", "duplicate", "flip", "hasRemaining", "limit", "mark", "position", "remaining", "reset", "rewind",
"slice",
// StructBuffer
"apply", "get", "parallelStream", "put", "stream"
)
open class StructMember(
val nativeType: DataType,
val name: String,
val documentation: String,
val bits: Int
) : ModifierTarget<StructMemberModifier>() {
override fun validate(modifier: StructMemberModifier) = modifier.validate(this)
internal var getter: String? = null
fun getter(expression: String): StructMember {
this.getter = expression
return this
}
internal var setter: String? = null
fun setter(expression: String): StructMember {
this.setter = expression
return this
}
fun copyAccessors(member: StructMember): StructMember {
this.getter = member.getter
this.setter = member.setter
return this
}
internal val offsetField
get() = name.uppercase()
internal fun offsetField(parentField: String): String {
return if (parentField.isEmpty())
offsetField
else
"${parentField}_$offsetField"
}
/** hidden if false, contributes to layout only */
internal var public = true
fun private(): StructMember {
public = false
return this
}
/** private + hidden from struct layout javadoc */
internal var virtual = false
fun virtual(): StructMember {
virtual = true
return private()
}
/** mutable if true, even if the parent struct is not mutable */
internal var mutable = false
fun mutable(): StructMember {
mutable = true
return this
}
internal var links: String = ""
internal var linkMode: LinkMode = LinkMode.SINGLE
fun links(links: String, linkMode: LinkMode = LinkMode.SINGLE) {
this.links = links
this.linkMode = linkMode
}
internal open fun copy() = StructMember(nativeType, name, documentation, bits)
}
open class StructMemberArray(
val arrayType: CArrayType<*>,
name: String,
documentation: String,
/** Number of pointer elements that must not be null. */
val validSize: String
) : StructMember(arrayType.elementType, name, documentation, -1) {
val size: String get() = arrayType.size
val primitiveMapping get() = nativeType.let {
if (it is PointerType<*>) PrimitiveMapping.POINTER else it.mapping as PrimitiveMapping
}
override fun copy() = StructMemberArray(arrayType, name, documentation, validSize)
}
private class StructMemberPadding(arrayType: CArrayType<*>, val condition: String?) : StructMemberArray(arrayType, ANONYMOUS, "", arrayType.size)
{
init {
public = false
}
override fun copy(): StructMemberPadding = StructMemberPadding(arrayType, condition)
}
private enum class MultiSetterMode {
NORMAL,
ALTER
}
private enum class AccessMode(val indent: String) {
INSTANCE(t),
FLYWEIGHT("$t$t");
}
class Struct(
module: Module,
className: String,
nativeSubPath: String = "",
/** The native struct name. May be different than className. */
val nativeName: String,
internal val union: Boolean,
/** when true, a declaration is missing, we need to output one. */
private val virtual: Boolean,
/** when false, setters methods will not be generated. */
private val mutable: Boolean,
/** if specified, this struct aliases it. */
private val alias: Struct?,
/** if specified, this struct is a subtype of it. */
internal val parentStruct: Struct?,
/** when true, the struct layout will be built using native code. */
internal val nativeLayout: Boolean,
/** when true, a nested StructBuffer subclass will be generated as well. */
private val generateBuffer: Boolean
) : GeneratorTargetNative(module, className, nativeSubPath) {
companion object {
private val bufferMethodMap = mapOf(
"boolean" to "Byte",
"byte" to "Byte",
"char" to "Char",
"short" to "Short",
"int" to "Int",
"long" to "Long",
"float" to "Float",
"double" to "Double"
)
private const val BUFFER_CAPACITY_PARAM = "capacity"
private val BUFFER_CAPACITY = Parameter(int, BUFFER_CAPACITY_PARAM, "the number of elements in the returned buffer")
// Do not generate deprecated stack allocation methods for structs introduced after 3.2.3.
private val STRUCTS_323 = Files
.readAllLines(Paths.get("modules/generator/src/main/resources/structs3.2.3.txt"))
.toHashSet()
}
/* Output parameter or function result by value */
private var usageOutput = false
/* Input parameter */
private var usageInput = false
/* Function result by reference */
private var usageResultPointer = false
private var static: String? = null
private var pack: String? = null
// TODO: add alignas support to non-struct members if necessary
private var alignas: String? = null
private val customMethods = ArrayList<String>()
private val customMethodsBuffer = ArrayList<String>()
internal val members = ArrayList<StructMember>()
internal fun init(setup: (Struct.() -> Unit)? = null): StructType {
if (setup != null) {
this.setup()
}
if (setup != null || nativeLayout) {
Generator.register(this)
}
return nativeType
}
internal fun copy(className: String, nativeName: String = className, virtual: Boolean = this.virtual): Struct {
val copy = Struct(
module,
className,
nativeSubPath,
nativeName,
union,
virtual,
mutable,
alias,
parentStruct,
nativeLayout,
generateBuffer
)
copy.documentation = documentation
copy.static = static
copy.alignas = alignas
copy.pack = pack
//copy.usageInput = usageInput
//copy.usageOutput = usageOutput
//copy.usageResultPointer = usageResultPointer
copy.customMethods.addAll(customMethods)
copy.customMethodsBuffer.addAll(customMethodsBuffer)
copy.members.addAll(members)
return copy
}
val nativeType get() = StructType(this)
fun setUsageOutput() {
usageOutput = true
}
fun setUsageInput() {
usageInput = true
}
fun setUsageResultPointer() {
usageResultPointer = true
}
fun static(expression: String) {
static = expression
}
fun pack(expression: String) {
pack = expression
}
fun pack(alignment: Int) {
pack = alignment.toString()
}
fun alignas(expression: String) {
alignas = expression
}
fun alignas(alignment: Int) {
alignas = alignment.toString()
}
private val visibleMembers
get() = members.asSequence().filter { it !is StructMemberPadding }
private val publicMembers
get() = members.asSequence().filter { it.public }
private fun mutableMembers(members: Sequence<StructMember> = publicMembers): Sequence<StructMember> = members.let {
if (mutable) it else it.filter { member -> member.mutable }
}
private val settableMembers: Sequence<StructMember> by lazy(LazyThreadSafetyMode.NONE) {
val mutableMembers = mutableMembers()
mutableMembers.filter { !it.has<AutoSizeMember> { !keepSetter(mutableMembers) } }
}
private fun hasMutableMembers(members: Sequence<StructMember> = publicMembers) = this.members.isNotEmpty() && (mutable || mutableMembers(members).any())
operator fun get(name: String): StructMember = members.asSequence().first { it.name == name }
fun StructMember.replace(old: StructMember): StructMember {
members.remove(this)
members[members.indexOf(old)] = this
return this
}
infix fun StructType.copy(member: String) = add(definition[member].copy())
private fun add(member: StructMember): StructMember {
members.add(member)
return member
}
// Plain struct member
operator fun DataType.invoke(name: String, documentation: String) = add(StructMember(this, name, documentation, -1))
// Array struct member
operator fun CArrayType<*>.invoke(name: String, documentation: String, validSize: String = this.size) = add(StructMemberArray(this, name, documentation, validSize))
// Bitfield struct member
operator fun PrimitiveType.invoke(name: String, documentation: String, bits: Int) = add(StructMember(this, name, documentation, bits))
private fun Int.toHexMask() = Integer.toHexString(this)
.uppercase()
.padStart(8, '0')
.let {
"0x${it.substring(0, 2)}_${it.substring(2, 4)}_${it.substring(4, 6)}_${it.substring(6, 8)}"
}
fun StructMember.bitfield(bitfield: Int, bitmask: Int): StructMember {
if (bits != bitmask.countOneBits()) {
this.error("The number of bits set in the specified bitmask (${bitmask.countOneBits()}) does not match the struct member bits ($bits)")
}
val mask = bitmask.toHexMask()
val maskInv = bitmask.inv().toHexMask()
val shift = bitmask.countTrailingZeroBits()
if (shift == 0) {
this.getter("nbitfield$bitfield(struct) & $mask")
this.setter("nbitfield$bitfield(struct, (nbitfield$bitfield(struct) & $maskInv) | (value & $mask))")
} else if (bits + shift == Int.SIZE_BITS) {
this.getter("nbitfield$bitfield(struct) >>> $shift")
this.setter("nbitfield$bitfield(struct, (value << $shift) | (nbitfield$bitfield(struct) & $maskInv))")
} else {
this.getter("(nbitfield$bitfield(struct) & $mask) >>> $shift")
this.setter("nbitfield$bitfield(struct, ((value << $shift) & $mask) | (nbitfield$bitfield(struct) & $maskInv))")
}
return this
}
// Converts a plain member to an array member
operator fun StructMember.get(size: Int, validSize: Int = size) = this[size.toString(), validSize.toString()]
operator fun StructMember.get(size: String, validSize: String = size): StructMemberArray {
[email protected](this)
val nativeType = if (isNestedStructDefinition) {
(this.nativeType as StructType)
.definition.copy(
className = this.name,
nativeName = ANONYMOUS,
virtual = true
)
.nativeType
} else
this.nativeType
return StructMemberArray(nativeType[size], name, documentation, validSize)
.let {
add(it)
it
}
}
// Converts an N-dimensional array to an (N+1)-dimensional array.
operator fun StructMemberArray.get(size: Int, validSize: Int = size) = this[size.toString(), validSize.toString()]
operator fun StructMemberArray.get(size: String, validSize: String): StructMemberArray {
[email protected](this)
return StructMemberArray(arrayType[size], name, documentation, "${this.validSize} * $validSize")
.let {
add(it)
it
}
}
fun padding(size: Int, condition: String? = null) = padding(size.toString(), condition)
fun padding(size: String, condition: String? = null) = add(StructMemberPadding(char[size], condition))
fun PrimitiveType.padding(size: Int, condition: String? = null) = this.padding(size.toString(), condition)
fun PrimitiveType.padding(size: String, condition: String? = null) = add(StructMemberPadding(this[size], condition))
/** Anonymous nested member struct definition. */
fun struct(
mutable: Boolean = this.mutable,
alias: StructType? = null,
parentStruct: StructType? = null,
nativeLayout: Boolean = false,
skipBuffer: Boolean = false,
setup: Struct.() -> Unit
): StructMember {
val struct = Struct(module, ANONYMOUS, nativeSubPath, ANONYMOUS, false, true, mutable, alias?.definition, parentStruct?.definition, nativeLayout, !skipBuffer)
struct.setup()
return StructType(struct).invoke(ANONYMOUS, "")
}
/** Anonymous nested member union definition. */
fun union(
mutable: Boolean = this.mutable,
alias: StructType? = null,
parentStruct: StructType? = null,
nativeLayout: Boolean = false,
skipBuffer: Boolean = false,
setup: Struct.() -> Unit
): StructMember {
val struct = Struct(module, ANONYMOUS, nativeSubPath, ANONYMOUS, true, true, mutable, alias?.definition, parentStruct?.definition, nativeLayout, !skipBuffer)
struct.setup()
return StructType(struct).invoke(ANONYMOUS, "")
}
/** Named nested struct/union. */
operator fun StructMember.invoke(name: String, documentation: String): StructMember {
[email protected](this)
return this.nativeType.invoke(name, documentation)
}
fun customMethod(method: String) {
customMethods.add(method.trim())
}
fun customMethodBuffer(method: String) {
customMethodsBuffer.add(method.trim())
}
private fun PrintWriter.printCustomMethods(customMethods: ArrayList<String>, static: Boolean, indent: String = t) {
customMethods
.filter { it.startsWith("static {") == static }
.forEach {
println("\n$indent$it")
}
}
/** A pointer-to-struct member points to an array of structs, rather than a single struct. */
private val StructMember.isStructBuffer
get() = getReferenceMember<AutoSizeMember>(this.name) != null || this.has<Unsafe>()
/** The nested struct's members are embedded in the parent struct. */
private val StructMember.isNestedStruct
get() = nativeType is StructType && this !is StructMemberArray
/** The nested struct is not defined elsewhere, it's part of the parent struct's definition. */
private val StructMember.isNestedStructDefinition
get() = isNestedStruct && (nativeType as StructType).name === ANONYMOUS
private val StructMember.nestedMembers
get() = (nativeType as StructType).definition.visibleMembers
private val containsUnion: Boolean get() = union || members.any {
it.isNestedStruct && (it.nativeType as StructType).let { type -> type.name === ANONYMOUS && type.definition.containsUnion }
}
private fun StructMember.field(parentMember: String) = if (parentMember.isEmpty())
if (KEYWORDS.contains(name) || (generateBuffer && BUFFER_KEYWORDS.contains(name))) "$name\$" else name
else
"${parentMember}_$name"
private fun StructMember.fieldName(parentMember: String) = if (parentMember.isEmpty())
name
else
"$parentMember.$name"
internal val validations: Sequence<String> by lazy(LazyThreadSafetyMode.NONE) {
if (union)
return@lazy emptySequence<String>()
val validations = ArrayList<String>()
fun MutableList<String>.addPointer(m: StructMember) = this.add("$t${t}long ${m.name} = memGetAddress($STRUCT + $className.${m.offsetField});")
fun MutableList<String>.addCount(m: StructMember) = this.add("$t$t${m.nativeType.javaMethodType} ${m.name} = n${m.name}($STRUCT);")
fun validate(m: StructMember, indent: String, hasPointer: Boolean = false): String {
return if (m.nativeType.hasStructValidation) {
if (m is StructMemberArray) {
"""${
if (hasPointer) "" else "${indent}long ${m.name} = $STRUCT + $className.${m.offsetField};\n"
}${indent}for (int i = 0; i < ${getReferenceMember<AutoSizeMember>(m.name)?.name ?: m.size}; i++) {${
if (m.nativeType is PointerType<*>) {
if (m.validSize == m.size)
"\n$indent check(memGetAddress(${m.name}));"
else
"""
$indent if (i < ${m.validSize}) {
$indent check(memGetAddress(${m.name}));
$indent } else if (memGetAddress(${m.name}) == NULL) {
$indent break;
$indent }"""
} else ""}
$indent ${m.nativeType.javaMethodType}.validate(${m.name});
$indent ${m.name} += POINTER_SIZE;
$indent}"""
} else {
"${if (hasPointer) "" else
"${indent}long ${m.name} = memGetAddress($STRUCT + $className.${m.offsetField});\n" +
"${indent}check(${m.name});\n"
}$indent${getReferenceMember<AutoSizeMember>(m.name).let {
if (it == null)
"${m.nativeType.javaMethodType}.validate(${m.name});"
else
"validate(${m.name}, ${it.name}, ${m.nativeType.javaMethodType}.SIZEOF, ${m.nativeType.javaMethodType}::validate);"}
}"
}
} else
"${indent}check(memGetAddress($STRUCT + $className.${m.offsetField}));"
}
fun validationBlock(condition: String, validations: String): String = "$t${t}if ($condition) {\n$validations\n$t$t}"
mutableMembers().forEach { m ->
if (m.has<AutoSizeMember>()) {
m.get<AutoSizeMember>().let { autoSize ->
val refs = autoSize.members(mutableMembers())
if (autoSize.atLeastOne) {
// TODO: There will be redundancy here when one of the refs is a validateable struct array. But we don't have a case for it yet.
validations.addCount(m)
// if m != 0, make sure one of the auto-sized members is not null
validations.add(
"$t${t}if (${if (autoSize.optional) "\n$t$t$t${m.name} != 0 &&" else "\n$t$t$t${m.name} == 0 || ("}${
refs.map { "\n$t$t${t}memGetAddress($STRUCT + $className.${it.offsetField}) == NULL" }.joinToString(" &&")
}\n$t$t${if (autoSize.optional) "" else ")"}) {\n$t$t${t}throw new NullPointerException(\"At least one of ${refs.map { it.name }.joinToString()} must not be null\");\n$t$t}"
)
} else if (autoSize.optional) {
val refValidations = refs.filter { !it.has(nullable) }.map { ref ->
validate(ref, "$t$t$t")
}.joinToString("\n")
if (refValidations.isEmpty())
return@let
// if m != 0, make sure auto-sized members are not null
validations.add(
validationBlock("${if (refValidations.contains(", ${m.name}")) {
validations.addCount(m)
m.name
} else "n${m.name}($STRUCT)"} != 0", refValidations)
)
} else if (refs.any { it.nativeType.hasStructValidation })
validations.addCount(m)
}
} else if (m.nativeType is StructType && m.nativeType.definition.validations.any()) {
validations.add(
if (m is StructMemberArray)
validate(m, "$t$t")
else
"$t$t${m.nativeType.javaMethodType}.validate($STRUCT + $className.${m.offsetField});"
)
} else if (m.nativeType is PointerType<*> && getReferenceMember<AutoSizeMember>(m.name)?.get<AutoSizeMember>().let { it == null || !it.optional }) {
if (m.nativeType.hasStructValidation) {
validations.add(
if (m.has(nullable)) {
validations.addPointer(m)
validationBlock("${m.name} != NULL", validate(m, "$t$t$t", hasPointer = true))
} else
validate(m, "$t$t")
)
} else if (!m.has(nullable) && m.nativeType !is StructType) {
validations.add(validate(m, "$t$t"))
}
}
}
validations.asSequence()
}
/** Returns a member that has the specified ReferenceModifier with the specified reference. Returns null if no such parameter exists. */
private inline fun <reified T> getReferenceMember(reference: String) where T : StructMemberModifier, T : ReferenceModifier = members.firstOrNull {
it.has<T>(reference)
} // Assumes at most 1 parameter will be found that references the specified parameter
private fun getAutoSizeExpression(reference: String) = members
.filter { it.has<AutoSizeMember>(reference) }
.joinToString(" * ") { it.autoSize }
.run {
if (this.isEmpty())
null
else
this
}
private fun StructMember.getCheckExpression() = if (this.has<Check>())
this.get<Check>().expression.let { expression ->
// if expression is the name of another member, convert to auto-size expression
members.singleOrNull { it.name == expression }?.autoSize ?: expression
}
else
null
private fun PrintWriter.printDocumentation() {
val builder = StringBuilder()
val members = members.filter { it !is StructMemberPadding }
if (documentation != null) {
builder.append(documentation)
if (members.isNotEmpty())
builder.append("\n\n")
}
if (members.isNotEmpty()) {
builder.append("<h3>Layout</h3>\n\n")
builder.append(codeBlock(printStructLayout()))
}
if (builder.isNotEmpty())
println(processDocumentation(builder.toString()).toJavaDoc(indentation = "", see = see, since = since))
}
private val nativeNameQualified get() = (if (union) "union " else "struct ").let { type ->
when {
nativeName.startsWith(type) -> nativeName
nativeName === ANONYMOUS -> type.substring(0, type.length - 1)
else -> "$type$nativeName"
}
}
private fun printStructLayout(indentation: String = "", parent: String = "", parentGetter: String = ""): String {
val memberIndentation = "$indentation "
return """$nativeNameQualified {
${members.asSequence()
.filter { !it.virtual }
.joinToString(";\n$memberIndentation", prefix = memberIndentation, postfix = ";") { member ->
if (member.isNestedStructDefinition || (member is StructMemberArray && member.nativeType is StructType && member.nativeType.name === ANONYMOUS)) {
val struct = (member.nativeType as StructType).definition
val qualifiedClass = if (member.name === ANONYMOUS || struct.className === ANONYMOUS) {
parent
} else {
if (parent.isEmpty()) struct.className else "$parent.${struct.className}"
}
"${struct.printStructLayout(
memberIndentation,
qualifiedClass,
if (member.name === ANONYMOUS || (member is StructMemberArray && member.nativeType.name === ANONYMOUS)) parentGetter else member.field(parentGetter)
)}${if (member.name === ANONYMOUS) "" else " ${member.name.let {
if (member is StructMemberArray)
"{@link $qualifiedClass $it}${member.arrayType.def}"
else
it
}}"}"
} else {
val anonymous = member.name === ANONYMOUS || (member.nativeType is FunctionType && member.nativeType.name.contains("(*)"))
member.nativeType
.let {
when {
it is FunctionType && anonymous -> it.function.nativeType(member.name)
else -> it.name
}
}
.let {
var elementType: NativeType = member.nativeType
while (true) {
if (elementType !is PointerType<*> || elementType.elementType is OpaqueType) {
break
}
elementType = elementType.elementType
}
when {
elementType is FunctionType && anonymous -> it.replace(
"(*${member.name})",
"(*{@link ${elementType.javaMethodType} ${member.name}})"
)
elementType is StructType || elementType is FunctionType -> it.replace(
elementType.name, "{@link ${elementType.javaMethodType} ${elementType.name.let { name ->
if (name.endsWith(" const")) {
"${name.substring(0, name.length - 6)}} const"
} else {
"$name}"
}
}}")
else -> it
}
}
.let {
if (anonymous)
it
else if (!member.public || (member.documentation.isEmpty() && member.links.isEmpty()))
"$it ${member.name}"
else
"$it {@link $parent\\#${member.field(parentGetter).let { link -> if (parent.isEmpty() && link == member.name) link else "$link ${member.name}"}}}"
}
.let {
if (member.bits != -1)
"$it : ${member.bits}"
else if (member is StructMemberArray)
"$it${member.arrayType.def}"
else
it
}
}
}}
$indentation}"""
}
private val StructMember.javadoc: String?
get() = if (documentation.isNotEmpty() || links.isNotEmpty()) {
if (links.isEmpty())
documentation
else
linkMode.appendLinks(
documentation,
if (!links.contains('+')) links else linksFromRegex(links)
)
} else
null
private fun PrintWriter.printSetterJavadoc(accessMode: AccessMode, member: StructMember, indent: String, message: String, getter: String) {
println("$indent/** ${message.replace(
"#member",
if (member.documentation.isEmpty() && member.links.isEmpty())
"{@code ${member.name}}"
else
"{@link ${if (accessMode == AccessMode.INSTANCE) "" else className}#$getter}")} */")
}
private fun PrintWriter.printGetterJavadoc(accessMode: AccessMode, member: StructMember, indent: String, message: String, getter: String, memberName: String) {
val doc = member.javadoc
if (accessMode == AccessMode.INSTANCE) {
if (doc != null) {
println(processDocumentation(doc).toJavaDoc(indentation = indent))
return
}
}
println("$indent/** ${message.replace("#member", if (accessMode == AccessMode.INSTANCE || doc == null) {
"{@code $memberName}"
} else {
"{@link ${[email protected]}#$getter}"
})} */")
}
private fun PrintWriter.printGetterJavadoc(accessMode: AccessMode, member: StructMember, indent: String, message: String, getter: String, memberName: String, vararg parameters: Parameter) {
val doc = member.javadoc
if (accessMode == AccessMode.INSTANCE) {
if (doc != null) {
println(toJavaDoc("", parameters.asSequence(), member.nativeType, doc, null, "", indentation = indent))
return
}
}
println(toJavaDoc(message.replace("#member", if (accessMode == AccessMode.INSTANCE || doc == null) {
"{@code $memberName}"
} else {
"{@link ${[email protected]}#$getter}"
}), parameters.asSequence(), member.nativeType, "", null, "", indentation = indent))
}
private fun StructMember.error(msg: String) {
throw IllegalArgumentException("$msg [${[email protected]}, member: $name]")
}
private fun generateBitfields() {
var bitfieldIndex = 0
var m = 0
while (m < members.size) {
val ref = members[m]
if (ref.bits == -1) {
m++
continue
}
// skip custom bitfields (e.g. Yoga's <Bitfield.h>)
if (0 < m && members[m - 1].virtual) {
var bitsLeft = (members[m - 1].nativeType.mapping as PrimitiveMapping).bytes * 8
while (0 < bitsLeft && m < members.size && members[m].bits != -1) {
bitsLeft -= members[m++].bits
}
continue
}
val typeMapping = (ref.nativeType as PrimitiveType).mapping
val bitsTotal = typeMapping.bytes * 8
var bitsConsumed = 0
var i = m
while (bitsConsumed < bitsTotal && i < members.size) {
val member = members[i]
if (member.bits == -1 || (member.nativeType as PrimitiveType).mapping !== typeMapping || (bitsTotal - bitsConsumed) < member.bits) {
break
}
if (member.getter == null) {
member.bitfield(bitfieldIndex, (-1 ushr (bitsTotal - member.bits)) shl bitsConsumed)
} else {
val getter = member.getter
member.bitfield(bitfieldIndex, (-1 ushr (bitsTotal - member.bits)) shl bitsConsumed)
val newGetter = member.getter
check(getter == newGetter) { "$getter - $newGetter" }
}
bitsConsumed += member.bits
i++
}
members.add(m, StructMember(ref.nativeType, "bitfield${bitfieldIndex++}", "", -1).virtual())
m = i + 1
}
}
private fun validate(mallocable: Boolean) {
if (mallocable) {
members.forEach {
if (it.nativeType is PointerType<*> && it.nativeType.elementType is StructType)
it.nativeType.elementType.definition.setUsageInput()
}
}
members.filter { it.has<AutoSizeMember>() }.forEach {
val autoSize = it.get<AutoSizeMember>()
autoSize.references.forEach { reference ->
val bufferParam = members.firstOrNull { member -> member.name == reference }
if (bufferParam == null)
it.error("Reference does not exist: AutoSize($reference)")
else {
if (bufferParam !is StructMemberArray) {
if (bufferParam.nativeType !is PointerType<*>)
it.error("Reference must be a pointer type: AutoSize($reference)")
if (!bufferParam.nativeType.isPointerData)
it.error("Reference must not be a opaque pointer: AutoSize($reference)")
} else if (autoSize.optional || autoSize.atLeastOne)
it.error("Optional cannot be used with array references: AutoSize($reference)")
if (autoSize.atLeastOne && !bufferParam.has(nullable))
it.error("The \"atLeastOne\" option requires references to be nullable: AutoSize($reference)")
}
}
}
}
override fun PrintWriter.generateJava() = generateJava(false, 1)
private fun PrintWriter.generateJava(nested: Boolean, level: Int) {
if (alias != null) {
usageInput = usageInput or alias.usageInput
usageOutput = usageOutput or alias.usageOutput
usageResultPointer = usageResultPointer or alias.usageResultPointer
}
generateBitfields()
val mallocable = mutableMembers().any() || usageOutput || (usageInput && !usageResultPointer)
validate(mallocable)
val nativeLayout = !skipNative
if (nativeLayout) {
if (module !== Module.CORE && !module.key.startsWith("core.")) {
checkNotNull(module.library) {
"${t}Missing module library for native layout of struct: ${module.packageKotlin}.$className"
}
}
} else if (preamble.hasNativeDirectives) {
kotlin.io.println("${t}Unnecessary native directives in struct: ${module.packageKotlin}.$className")
}
if (!nested) {
print(HEADER)
println("package $packageName;\n")
println("import javax.annotation.*;\n")
println("import java.nio.*;\n")
if (mallocable || members.any { m ->
m.nativeType.let {
(it.mapping === PointerMapping.DATA_POINTER && it is PointerType<*> && (it.elementType !is StructType || m is StructMemberArray)) ||
(m is StructMemberArray && m.arrayType.elementType.isPointer && m.arrayType.elementType !is StructType)
}
})
println("import org.lwjgl.*;")
println("import org.lwjgl.system.*;\n")
fun Struct.hasChecks(): Boolean = visibleMembers.any {
(it is StructMemberArray && it.nativeType !is CharType) ||
(
(mutable || it.mutable) &&
(
it is StructMemberArray ||
it.nativeType is CharSequenceType ||
(it.nativeType is PointerType<*> && !it.has<Nullable>())
)
) ||
it.isNestedStructDefinition && (it.nativeType as StructType).definition.hasChecks()
}
if (Module.CHECKS && hasChecks())
println("import static org.lwjgl.system.Checks.*;")
println("import static org.lwjgl.system.MemoryUtil.*;")
if (nativeLayout || mallocable)
println("import static org.lwjgl.system.MemoryStack.*;")
}
println()
preamble.printJava(this)
printDocumentation()
if (className != nativeName) {
println("@NativeType(\"$nativeNameQualified\")")
}
print("${access.modifier}${if (nested) "static " else ""}class $className extends ")
print(alias?.className ?: "Struct${if (mallocable) " implements NativeResource" else ""}")
println(" {")
if (alias == null) {
print("""
/** The struct size in bytes. */
public static final int SIZEOF;
/** The struct alignment in bytes. */
public static final int ALIGNOF;
"""
)
val visibleMembersExceptBitfields = visibleMembers.filter { it.bits == -1 }
if (members.isNotEmpty() && (!nativeLayout || visibleMembersExceptBitfields.any())) {
val memberCount = getMemberCount(members)
// Member offset fields
if (visibleMembersExceptBitfields.any()) {
print(
"""
/** The struct member offsets. */
public static final int
"""
)
generateOffsetFields(visibleMembersExceptBitfields)
println(";")
}
print(
"""
static {"""
)
if (static != null)
print(
"""
$static
"""
)
// Member offset initialization
if (nativeLayout) {
if (module.library != null) {
print(
"""
${module.library.expression(module)}""")
}
print(
"""
try (MemoryStack stack = stackPush()) {
IntBuffer offsets = stack.mallocInt(${memberCount + 1});
SIZEOF = offsets(memAddress(offsets));
"""
)
generateOffsetInit(true, members, indentation = "$t$t$t")
println(
"""
ALIGNOF = offsets.get($memberCount);
}"""
)
} else {
print(
"""
Layout layout = """
)
generateLayout(this@Struct)
print(
""";
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
"""
)
generateOffsetInit(false, members)
}
println("$t}")
} else if (nativeLayout) {
print(
"""
static {"""
)
if (static != null)
print(
"""
$static
"""
)
println(
"""
${module.library!!.expression(module)}
try (MemoryStack stack = stackPush()) {
IntBuffer offsets = stack.mallocInt(1);
SIZEOF = offsets(memAddress(offsets));
ALIGNOF = offsets.get(0);
}
}"""
)
}
if (nativeLayout)
println(
"""
private static native int offsets(long buffer);"""
)
}
printCustomMethods(customMethods, static = true)
print("""
/**
* Creates a {@code $className} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
${access.modifier}$className(ByteBuffer container) {
super(${if (alias == null) "memAddress(container), __checkContainer(container, SIZEOF)" else "container"});
}
""")
if (alias == null) {
print("""
@Override
public int sizeof() { return SIZEOF; }
""")
}
var members = publicMembers
if (members.any()) {
if (alias == null) {
println()
generateGetters(AccessMode.INSTANCE, members)
}
if (hasMutableMembers()) {
println()
generateSetters(AccessMode.INSTANCE, settableMembers)
if (settableMembers.singleOrNull() == null && !containsUnion) {
val javadoc = "Initializes this struct with the specified values."
if (generateAlternativeMultiSetter(settableMembers))
generateMultiSetter(javadoc, settableMembers, Struct::generateAlternativeMultiSetterParameters, Struct::generateAlternativeMultiSetterSetters, MultiSetterMode.ALTER)
else
generateMultiSetter(javadoc, settableMembers, Struct::generateMultiSetterParameters, Struct::generateMultiSetterSetters)
}
print("""
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public $className set($className src) {
memCopy(src.$ADDRESS, $ADDRESS, SIZEOF);
return this;
}
""")
}
}
print("""
// -----------------------------------
""")
// Factory constructors
if (mallocable) {
print("""
/** Returns a new {@code $className} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static $className malloc() {
return wrap($className.class, nmemAllocChecked(SIZEOF));
}
/** Returns a new {@code $className} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static $className calloc() {
return wrap($className.class, nmemCallocChecked(1, SIZEOF));
}
/** Returns a new {@code $className} instance allocated with {@link BufferUtils}. */
public static $className create() {
ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
return wrap($className.class, memAddress(container), container);
}
""")
}
print("""
/** Returns a new {@code $className} instance for the specified memory address. */
public static $className create(long address) {
return wrap($className.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static $className createSafe(long address) {
return address == NULL ? null : wrap($className.class, address);
}
""")
val subtypes = Generator.structChildren[module]?.get([email protected])
subtypes?.forEach {
print("""
/** Upcasts the specified {@code ${it.className}} instance to {@code $className}. */
public static $className create(${it.className} value) {
return wrap($className.class, value);
}
""")
}
if (parentStruct != null) {
print("""
/** Downcasts the specified {@code ${parentStruct.className}} instance to {@code $className}. */
public static $className create(${parentStruct.className} value) {
return wrap($className.class, value);
}
""")
}
if (generateBuffer) {
if (mallocable) {
print("""
/**
* Returns a new {@link $className.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static $className.Buffer malloc(int $BUFFER_CAPACITY_PARAM) {
return wrap(Buffer.class, nmemAllocChecked(__checkMalloc($BUFFER_CAPACITY_PARAM, SIZEOF)), $BUFFER_CAPACITY_PARAM);
}
/**
* Returns a new {@link $className.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static $className.Buffer calloc(int $BUFFER_CAPACITY_PARAM) {
return wrap(Buffer.class, nmemCallocChecked($BUFFER_CAPACITY_PARAM, SIZEOF), $BUFFER_CAPACITY_PARAM);
}
/**
* Returns a new {@link $className.Buffer} instance allocated with {@link BufferUtils}.
*
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static $className.Buffer create(int $BUFFER_CAPACITY_PARAM) {
ByteBuffer container = __create($BUFFER_CAPACITY_PARAM, SIZEOF);
return wrap(Buffer.class, memAddress(container), $BUFFER_CAPACITY_PARAM, container);
}
""")
}
print("""
/**
* Create a {@link $className.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static $className.Buffer create(long address, int $BUFFER_CAPACITY_PARAM) {
return wrap(Buffer.class, address, $BUFFER_CAPACITY_PARAM);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static $className.Buffer createSafe(long address, int $BUFFER_CAPACITY_PARAM) {
return address == NULL ? null : wrap(Buffer.class, address, $BUFFER_CAPACITY_PARAM);
}
""")
subtypes?.forEach {
print("""
/** Upcasts the specified {@code ${it.className}.Buffer} instance to {@code $className.Buffer}. */
public static $className.Buffer create(${it.className}.Buffer value) {
return wrap(Buffer.class, value);
}
""")
}
if (parentStruct != null) {
print("""
/** Downcasts the specified {@code ${parentStruct.className}.Buffer} instance to {@code $className.Buffer}. */
public static $className.Buffer create(${parentStruct.className}.Buffer value) {
return wrap(Buffer.class, value);
}
""")
}
}
if (mallocable) {
if (STRUCTS_323.contains("$packageName.$className")) {
print("""
// -----------------------------------
/** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
@Deprecated public static $className mallocStack() { return malloc(stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
@Deprecated public static $className callocStack() { return calloc(stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
@Deprecated public static $className mallocStack(MemoryStack stack) { return malloc(stack); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
@Deprecated public static $className callocStack(MemoryStack stack) { return calloc(stack); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */""")
if (generateBuffer) {
print("""
@Deprecated public static $className.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
@Deprecated public static $className.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
@Deprecated public static $className.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
@Deprecated public static $className.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); }""")
}
println()
}
print("""
/**
* Returns a new {@code $className} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static $className malloc(MemoryStack stack) {
return wrap($className.class, stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@code $className} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static $className calloc(MemoryStack stack) {
return wrap($className.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
""")
if (generateBuffer) {
print("""
/**
* Returns a new {@link $className.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static $className.Buffer malloc(int $BUFFER_CAPACITY_PARAM, MemoryStack stack) {
return wrap(Buffer.class, stack.nmalloc(ALIGNOF, $BUFFER_CAPACITY_PARAM * SIZEOF), $BUFFER_CAPACITY_PARAM);
}
/**
* Returns a new {@link $className.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static $className.Buffer calloc(int $BUFFER_CAPACITY_PARAM, MemoryStack stack) {
return wrap(Buffer.class, stack.ncalloc(ALIGNOF, $BUFFER_CAPACITY_PARAM, SIZEOF), $BUFFER_CAPACITY_PARAM);
}
""")
}
}
if (alias == null) {
print("""
// -----------------------------------
""")
members = visibleMembers
if (members.any()) {
println()
generateStaticGetters(members)
if (hasMutableMembers(visibleMembers)) {
println()
generateStaticSetters(mutableMembers(visibleMembers))
if (Module.CHECKS && validations.any()) {
println(
"""
/**
* Validates pointer members that should not be {@code NULL}.
*
* @param $STRUCT the struct to validate
*/
public static void validate(long $STRUCT) {
${validations.joinToString("\n")}
}""")
}
}
}
}
printCustomMethods(customMethods, static = false)
if (generateBuffer) {
println("\n$t// -----------------------------------")
print("""
/** An array of {@link $className} structs. */
public static class Buffer extends """)
print(if (alias == null)
"StructBuffer<$className, Buffer>${if (mallocable) " implements NativeResource" else ""}"
else
"${alias.className}.Buffer"
)
print(""" {
private static final $className ELEMENT_FACTORY = $className.create(-1L);
/**
* Creates a new {@code $className.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link $className#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/""")
print(if (alias == null)
"""
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}"""
else
"""
public Buffer(ByteBuffer container) {
super(container);
}""")
print("""
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected $className getElementFactory() {
return ELEMENT_FACTORY;
}
""")
members = publicMembers
if (members.any()) {
if (alias == null) {
println()
generateGetters(AccessMode.FLYWEIGHT, members)
}
if (hasMutableMembers()) {
println()
generateSetters(AccessMode.FLYWEIGHT, settableMembers)
}
}
printCustomMethods(customMethodsBuffer, static = false, indent = "$t$t")
print("""
}
""")
}
// Recursively output inner classes for array-of-anonymous-nested-struct members.
[email protected]
.filter { it is StructMemberArray && it.nativeType is StructType && it.nativeType.name === ANONYMOUS }
.forEach { member ->
(member.nativeType as StructType).definition.apply {
val writer = StringWriter(4 * 1024)
PrintWriter(writer).use {
it.generateJava(nested = true, level = level + 1)
}
println(writer.toString().replace("\n(?!$)".toRegex(), "\n "))
}
}
print("""
}""")
}
private fun PrintWriter.generateOffsetFields(
members: Sequence<StructMember>,
indentation: String = "$t$t",
parentField: String = "",
moreOverride: Boolean = false
) {
members.forEachWithMore(moreOverride) { member, more ->
if (member.name === ANONYMOUS && member.isNestedStruct) {
generateOffsetFields(member.nestedMembers, indentation, parentField, more) // recursion
} else {
if (more)
println(",")
val field = member.offsetField(parentField)
print("$indentation$field")
// Output nested field offsets
if (member.isNestedStructDefinition)
generateOffsetFields(member.nestedMembers, "$indentation$t", field, true) // recursion
}
}
}
private fun getMemberCount(members: List<StructMember>): Int {
var count = members.count { it.bits == -1 }
for (member in members.asSequence().filter { it.isNestedStructDefinition })
count += getMemberCount((member.nativeType as StructType).definition.members) // recursion
return count
}
private fun PrintWriter.generateOffsetInit(
nativeLayout: Boolean,
members: List<StructMember>,
indentation: String = "$t$t",
parentField: String = "",
offset: Int = 0
): Int {
var index = offset
members.forEach {
if (it.name === ANONYMOUS && it.isNestedStruct) {
index = generateOffsetInit(nativeLayout, (it.nativeType as StructType).definition.members, indentation, parentField, index + 1) // recursion
} else if (it is StructMemberPadding) {
index++
} else if (it.bits == -1) {
val field = it.offsetField(parentField)
println("$indentation$field = ${if (nativeLayout) "offsets.get" else "layout.offsetof"}(${index++});")
// Output nested fields
if (it.isNestedStructDefinition)
index = generateOffsetInit(nativeLayout, (it.nativeType as StructType).definition.members, "$indentation$t", field, index) // recursion
}
}
return index
}
private fun PrintWriter.generateLayout(
struct: Struct,
indentation: String = "$t$t",
parentField: String = ""
) {
println("__${if (struct.union) "union" else "struct"}(")
if (pack != null || alignas != null) {
println("$indentation$t${pack ?: "DEFAULT_PACK_ALIGNMENT"}, ${alignas ?: "DEFAULT_ALIGN_AS"},")
}
struct.members
.filter { it.bits == -1 }
.forEachWithMore { it, more ->
val field = it.offsetField(parentField)
if (more)
println(",")
if (it is StructMemberPadding) {
val bytesPerElement = (it.arrayType.elementType as PrimitiveType).mapping.bytesExpression
print("$indentation${t}__padding(${if (bytesPerElement == "1") it.size else "${it.size}, $bytesPerElement"}, ${it.condition ?: "true"})")
} else if (it.isNestedStructDefinition) {
print("$indentation$t")
generateLayout((it.nativeType as StructType).definition, "$indentation$t", field)
} else {
val size: String
val alignment: String
if (it.nativeType is StructType) {
size = "${it.nativeType.javaMethodType}.SIZEOF"
alignment = "${it.nativeType.javaMethodType}.ALIGNOF${if (it.nativeType.definition.alignas != null) ", true" else ""}"
} else {
size = if (it.nativeType.isPointer)
"POINTER_SIZE"
else
(it.nativeType.mapping as PrimitiveMapping).bytesExpression
alignment = size
}
if (it is StructMemberArray)
print("$indentation${t}__array($size${if (size != alignment) ", $alignment" else ""}, ${it.size})")
else
print("$indentation${t}__member($size${if (size != alignment) ", $alignment" else ""})")
}
}
print("\n$indentation)")
}
private fun PrintWriter.generateMultiSetter(
javaDoc: String,
members: Sequence<StructMember>,
generateParameters: (Struct, PrintWriter, Sequence<StructMember>, String, MultiSetterMode, Boolean) -> Unit,
generateSetters: (Struct, PrintWriter, Sequence<StructMember>, String, MultiSetterMode) -> Unit,
mode: MultiSetterMode = MultiSetterMode.NORMAL
) {
print("""
/** $javaDoc */""")
if (alias != null) {
print("""
@Override""")
}
print("""
public $className set(
""")
generateParameters(this@Struct, this, members, "", mode, false)
println("""
) {""")
generateSetters(this@Struct, this, members, "", mode)
print("""
return this;
}
""")
}
private fun generateMultiSetterParameters(writer: PrintWriter, members: Sequence<StructMember>, parentMember: String, mode: MultiSetterMode, more: Boolean) {
writer.apply {
members.forEachWithMore(more) { it, more ->
val method = it.field(parentMember)
if (it.isNestedStructDefinition) {
generateMultiSetterParameters(writer, it.nestedMembers, method, mode, more) // recursion
return@forEachWithMore
}
if (more)
println(",")
print("$t$t")
val param = it.field(parentMember)
print("${it.nativeType.javaMethodType} $param")
}
}
}
private fun generateMultiSetterSetters(writer: PrintWriter, members: Sequence<StructMember>, parentMember: String, mode: MultiSetterMode) {
writer.apply {
members.forEach {
val field = it.field(parentMember)
if (it.isNestedStructDefinition)
generateMultiSetterSetters(writer, it.nestedMembers, field, mode) // recursion
else
println("$t$t$field($field);")
}
}
}
private fun generateAlternativeMultiSetter(members: Sequence<StructMember>): Boolean =
members.any {
if (it.isNestedStructDefinition)
generateAlternativeMultiSetter(it.nestedMembers) // recursion
else
it is StructMemberArray || it.nativeType.isPointerData
}
private fun generateAlternativeMultiSetterParameters(writer: PrintWriter, members: Sequence<StructMember>, parentMember: String, mode: MultiSetterMode, more: Boolean) {
writer.apply {
members.forEachWithMore(more) { it, more ->
val method = it.field(parentMember)
if (it.isNestedStructDefinition) {
generateAlternativeMultiSetterParameters(writer, it.nestedMembers, method, mode, more) // recursion
return@forEachWithMore
}
if (more)
println(",")
print(
"$t$t${it.nullable(
if (it is StructMemberArray) {
if (it.nativeType is CharType) {
"ByteBuffer"
} else if (it.nativeType is StructType)
"${it.nativeType.javaMethodType}.Buffer"
else
it.primitiveMapping.toPointer.javaMethodName
} else if (it.nativeType is PointerType<*> && it.nativeType.elementType is StructType) {
val structType = it.nativeType.javaMethodType
if (it.isStructBuffer)
"$structType.Buffer"
else
structType
} else
it.nativeType.javaMethodType,
if (it is StructMemberArray) it.arrayType else it.nativeType
)} ${it.field(parentMember)}"
)
}
}
}
private fun generateAlternativeMultiSetterSetters(writer: PrintWriter, members: Sequence<StructMember>, parentMember: String, mode: MultiSetterMode) {
writer.apply {
members.forEach {
val field = it.field(parentMember)
if (it.isNestedStructDefinition)
generateAlternativeMultiSetterSetters(writer, it.nestedMembers, field, mode) // recursion
else
println("$t$t$field($field);")
}
}
}
private fun getFieldOffset(
m: StructMember,
parentStruct: Struct?,
parentField: String
) = if (parentStruct == null || parentField.isEmpty())
"$className.${m.offsetField}"
else if (parentStruct.className === ANONYMOUS)
"${parentField}_${m.offsetField}"
else
throw IllegalStateException()
private val StructMember.pointerValue get() = if (!Module.CHECKS || has(nullable)) "value" else "check(value)"
private val StructMember.isNullable
get() = has(nullable) ||
getReferenceMember<AutoSizeMember>(name)?.get<AutoSizeMember>()?.optional ?: false ||
(this is StructMemberArray && this.validSize < this.size)
private val StructMember.addressValue get() = if (isNullable) "memAddressSafe(value)" else "value.address()"
private val StructMember.memAddressValue get() = if (isNullable) "memAddressSafe(value)" else "memAddress(value)"
private val StructMember.autoSize get() = "n$name($STRUCT)"
.let {
val type = this.nativeType as IntegerType
if (!type.unsigned)
it
else {
val mapping = type.mapping
when (mapping.bytes) {
1 -> "Byte.toUnsignedInt($it)"
2 -> "Short.toUnsignedInt($it)"
else -> it
}
}
}
.let {
val factor = if (has<AutoSizeMember>()) get<AutoSizeMember>().factor else null
if (factor != null)
"(${factor.scale(it)})"
else
it
}
.let { if (4 < (nativeType.mapping as PrimitiveMapping).bytes && !it.startsWith('(')) "(int)$it" else it }
private fun PrintWriter.setRemaining(m: StructMember, offset: Int = 0, prefix: String = " ", suffix: String = "") {
// do not do this if the AutoSize parameter auto-sizes multiple members
val capacity = members.firstOrNull {
it.has<AutoSizeMember> { atLeastOne || (dependent.isEmpty() && reference == m.name) }
}
if (capacity != null) {
val autoSize = capacity.get<AutoSizeMember>()
val autoSizeExpression = "value.remaining()"
.let {
if (autoSize.factor != null)
"(${autoSize.factor.scaleInv(it)})"
else
it
}
.let { if ((capacity.nativeType.mapping as PrimitiveMapping).bytes < 4) "(${capacity.nativeType.javaMethodType})$it" else it }
.let { if (offset != 0) "$it - $offset" else it }
print(prefix)
print(if ((m has nullable || autoSize.optional) && m !is StructMemberArray) {
if (autoSize.atLeastOne || (m has nullable && autoSize.optional))
"if (value != null) { n${capacity.name}($STRUCT, $autoSizeExpression); }"
else
"n${capacity.name}($STRUCT, value == null ? 0 : $autoSizeExpression);"
} else
"n${capacity.name}($STRUCT, $autoSizeExpression);"
)
print(suffix)
}
}
private fun PrintWriter.generateStaticSetters(
members: Sequence<StructMember>,
parentStruct: Struct? = null,
parentMember: String = "",
parentField: String = ""
) {
members.forEach {
val setter = it.field(parentMember)
val field = getFieldOffset(it, parentStruct, parentField)
if (it.isNestedStruct) {
val nestedStruct = (it.nativeType as StructType).definition
val structType = nestedStruct.className
if (structType === ANONYMOUS)
generateStaticSetters(
it.nestedMembers, nestedStruct,
if (it.name === ANONYMOUS) parentMember else setter,
if (it.name === ANONYMOUS) parentField else field
)
else {
if (it.public)
println("$t/** Unsafe version of {@link #$setter($structType) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, $structType value) { memCopy(value.$ADDRESS, $STRUCT + $field, $structType.SIZEOF); }")
}
} else {
// Setter
if (it !is StructMemberArray && !it.nativeType.isPointerData) {
if (it.nativeType is WrappedPointerType) {
if (it.public)
println("$t/** Unsafe version of {@link #$setter(${it.nativeType.javaMethodType}) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, ${it.nullable(it.nativeType.javaMethodType)} value) { memPutAddress($STRUCT + $field, ${it.addressValue}); }")
} else {
val javaType = it.nativeType.nativeMethodType
if (it.public)
println(
if (it.has<AutoSizeMember>())
"$t/** Sets the specified value to the {@code ${it.name}} field of the specified {@code struct}. */"
else
"$t/** Unsafe version of {@link #$setter(${if (it.nativeType.mapping == PrimitiveMapping.BOOLEAN4) "boolean" else javaType}) $setter}. */"
)
if (it.setter != null) {
println("${t}public static void n$setter(long $STRUCT, $javaType value) { ${it.setter}; }")
} else if (it.bits != -1) {
println("${t}public static native void n$setter(long $STRUCT, $javaType value);")
} else {
print("${t}public static void n$setter(long $STRUCT, $javaType value) { ${getBufferMethod("put", it, javaType)}$STRUCT + $field, ")
print(
when {
javaType == "boolean"
-> "value ? (byte)1 : (byte)0"
it.nativeType.mapping === PointerMapping.OPAQUE_POINTER
-> it.pointerValue
else -> "value"
}
)
println("); }")
}
}
}
// Alternative setters
if (it is StructMemberArray) {
if (it.nativeType.dereference is StructType) {
val structType = it.nativeType.javaMethodType
if (it.nativeType is PointerType<*>) {
if (it.public)
println("$t/** Unsafe version of {@link #$setter(PointerBuffer) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, PointerBuffer value) {")
if (Module.CHECKS)
println("$t${t}if (CHECKS) { checkGT(value, ${it.size}); }")
println("$t${t}memCopy(memAddress(value), $STRUCT + $field, value.remaining() * POINTER_SIZE);")
setRemaining(it, prefix = "$t$t", suffix = "\n")
println("$t}")
val structTypeIndexed = "$structType${if (getReferenceMember<AutoSizeIndirect>(it.name) == null) "" else ".Buffer"}"
if (it.public)
println("$t/** Unsafe version of {@link #$setter(int, $structTypeIndexed) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, int index, ${it.nullable(structTypeIndexed)} value) {")
println("$t${t}memPutAddress($STRUCT + $field + check(index, ${it.size}) * POINTER_SIZE, ${it.addressValue});")
println("$t}")
} else {
if (it.public)
println("$t/** Unsafe version of {@link #$setter($structType.Buffer) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, $structType.Buffer value) {")
if (Module.CHECKS)
println("$t${t}if (CHECKS) { checkGT(value, ${it.size}); }")
println("$t${t}memCopy(value.$ADDRESS, $STRUCT + $field, value.remaining() * $structType.SIZEOF);")
setRemaining(it, prefix = "$t$t", suffix = "\n")
println("$t}")
if (it.public)
println("$t/** Unsafe version of {@link #$setter(int, $structType) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, int index, $structType value) {")
println("$t${t}memCopy(value.$ADDRESS, $STRUCT + $field + check(index, ${it.size}) * $structType.SIZEOF, $structType.SIZEOF);")
println("$t}")
}
} else if (it.nativeType is CharType) {
val mapping = it.nativeType.mapping as PrimitiveMapping
val byteSize = if (mapping.bytes == 1) it.size else "${it.size} * ${mapping.bytes}"
val nullTerminated = getReferenceMember<AutoSizeMember>(it.name) == null || it.has(NullTerminatedMember)
if (it.public)
println("$t/** Unsafe version of {@link #$setter(ByteBuffer) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, ByteBuffer value) {")
if (Module.CHECKS) {
println("$t${t}if (CHECKS) {")
if (nullTerminated) {
println("$t$t${t}checkNT${mapping.bytes}(value);")
}
println("$t$t${t}checkGT(value, $byteSize);")
println("$t$t}")
}
println("$t${t}memCopy(memAddress(value), $STRUCT + $field, value.remaining());")
setRemaining(it, if (nullTerminated) mapping.bytes else 0, prefix = "$t$t", suffix = "\n")
println("$t}")
} else {
val mapping = it.primitiveMapping
val bufferType = mapping.toPointer.javaMethodName
if (it.public)
println("$t/** Unsafe version of {@link #$setter($bufferType) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, $bufferType value) {")
if (Module.CHECKS)
println("$t${t}if (CHECKS) { checkGT(value, ${it.size}); }")
println("$t${t}memCopy(memAddress(value), $STRUCT + $field, value.remaining() * ${mapping.bytesExpression});")
setRemaining(it, prefix = "$t$t", suffix = "\n")
println("$t}")
val javaType = it.nativeType.nativeMethodType
if (it.public)
println("$t/** Unsafe version of {@link #$setter(int, $javaType) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, int index, $javaType value) {")
println("$t$t${getBufferMethod("put", it, javaType)}$STRUCT + $field + check(index, ${it.size}) * ${mapping.bytesExpression}, value);")
println("$t}")
}
} else if (it.nativeType is CharSequenceType) {
val mapping = it.nativeType.charMapping
val nullTerminated = getReferenceMember<AutoSizeMember>(it.name) == null || it.has(NullTerminatedMember)
if (it.public)
println("$t/** Unsafe version of {@link #$setter(ByteBuffer) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, ${it.nullable("ByteBuffer")} value) {")
if (Module.CHECKS && nullTerminated)
println("$t${t}if (CHECKS) { checkNT${mapping.bytes}${if (it.isNullable) "Safe" else ""}(value); }")
println("$t${t}memPutAddress($STRUCT + $field, ${it.memAddressValue});")
setRemaining(it, prefix = "$t$t", suffix = "\n")
println("$t}")
} else if (it.nativeType.isPointerData) {
val paramType = it.nativeType.javaMethodType
if (it.nativeType.dereference is StructType) {
if (it.isStructBuffer) {
if (it.public)
println("$t/** Unsafe version of {@link #$setter($paramType.Buffer) $setter}. */")
print("${t}public static void n$setter(long $STRUCT, ${it.nullable("$paramType.Buffer")} value) { memPutAddress($STRUCT + $field, ${it.addressValue});")
setRemaining(it)
println(" }")
} else {
if (it.public)
println("$t/** Unsafe version of {@link #$setter($paramType) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, ${it.nullable(paramType)} value) { memPutAddress($STRUCT + $field, ${it.addressValue}); }")
}
} else {
if (it.public)
println("$t/** Unsafe version of {@link #$setter($paramType) $setter}. */")
print("${t}public static void n$setter(long $STRUCT, ${it.nullable(paramType)} value) { memPutAddress($STRUCT + $field, ${it.memAddressValue});")
setRemaining(it)
println(" }")
}
}
}
}
}
private fun StructMember.annotate(
type: String,
nativeType: DataType = if (this is StructMemberArray) this.arrayType else this.nativeType
) = nullable(nativeType.annotate(type), nativeType)
private fun StructMember.nullable(type: String, nativeType: DataType = this.nativeType) =
if (nativeType.isReference && isNullable && nativeType !is CArrayType<*>) {
"@Nullable $type"
} else {
type
}
private fun StructMember.construct(type: String) = if (nativeType.isReference && isNullable) {
"$type.createSafe"
} else {
"$type.create"
}
private fun StructMember.mem(type: String) = if (nativeType.isReference && isNullable && this !is StructMemberArray) {
"mem${type}Safe"
} else {
"mem$type"
}
private fun PrintWriter.generateSetters(
accessMode: AccessMode,
members: Sequence<StructMember>,
parentSetter: String = "",
parentMember: String = ""
) {
val n = if (accessMode === AccessMode.INSTANCE) "n" else "$className.n"
members.forEach {
val setter = it.field(parentSetter)
val member = it.fieldName(parentMember)
val indent = accessMode.indent
val overrides = alias != null /*
TODO: forward declarations have no members (see VkPhysicalDeviceBufferDeviceAddressFeaturesEXT)
&& alias.members.any { parentMember -> parentMember.name == it.name }
*/
val returnType = if (accessMode === AccessMode.INSTANCE)
className
else
"$className.Buffer"
if (it.isNestedStruct) {
val nestedStruct = (it.nativeType as StructType).definition
val structType = nestedStruct.className
if (structType === ANONYMOUS)
generateSetters(
accessMode,
it.nestedMembers,
if (it.name === ANONYMOUS) parentSetter else setter,
if (it.name === ANONYMOUS) parentMember else member
)
else {
printSetterJavadoc(accessMode, it, indent, "Copies the specified {@link $structType} to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate(structType)} value) { $n$setter($ADDRESS, value); return this; }")
if (nestedStruct.mutable) {
printSetterJavadoc(accessMode, it, indent, "Passes the #member field to the specified {@link java.util.function.Consumer Consumer}.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $className${if (accessMode === AccessMode.INSTANCE) "" else ".Buffer"} $setter(java.util.function.Consumer<$structType> consumer) { consumer.accept($setter()); return this; }")
}
}
} else {
// Setter
if (it !is StructMemberArray && !it.nativeType.isPointerData) {
printSetterJavadoc(accessMode, it, indent, "Sets the specified value to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate(it.nativeType.javaMethodType)} value) { $n$setter($ADDRESS, value${if (it.nativeType.mapping === PrimitiveMapping.BOOLEAN4) " ? 1 : 0" else ""}); return this; }")
}
// Alternative setters
if (it is StructMemberArray) {
if (it.nativeType.dereference is StructType) {
val nestedStruct: Struct
val structType = it.nativeType.javaMethodType
val retType = "$structType${if (getReferenceMember<AutoSizeIndirect>(it.name) == null) "" else ".Buffer"}"
if (it.nativeType is PointerType<*>) {
nestedStruct = (it.nativeType.dereference as StructType).definition
printSetterJavadoc(accessMode, it, indent, "Copies the specified {@link PointerBuffer} to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate("PointerBuffer")} value) { $n$setter($ADDRESS, value); return this; }")
printSetterJavadoc(accessMode, it, indent, "Copies the address of the specified {@link $retType} at the specified index of the #member field.", setter)
} else {
nestedStruct = (it.nativeType as StructType).definition
printSetterJavadoc(accessMode, it, indent, "Copies the specified {@link $structType.Buffer} to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate("$structType.Buffer")} value) { $n$setter($ADDRESS, value); return this; }")
printSetterJavadoc(accessMode, it, indent, "Copies the specified {@link $structType} at the specified index of the #member field.", setter)
}
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(int index, ${it.annotate(retType, it.nativeType)} value) { $n$setter($ADDRESS, index, value); return this; }")
if (nestedStruct.mutable) {
if (it.nativeType !is PointerType<*>) {
printSetterJavadoc(accessMode, it, indent, "Passes the #member field to the specified {@link java.util.function.Consumer Consumer}.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $className${if (accessMode === AccessMode.INSTANCE) "" else ".Buffer"} $setter(java.util.function.Consumer<$structType.Buffer> consumer) { consumer.accept($setter()); return this; }")
}
printSetterJavadoc(accessMode, it, indent, "Passes the element at {@code index} of the #member field to the specified {@link java.util.function.Consumer Consumer}.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $className${if (accessMode === AccessMode.INSTANCE) "" else ".Buffer"} $setter(int index, java.util.function.Consumer<$retType> consumer) { consumer.accept($setter(index)); return this; }")
}
} else if (it.nativeType is CharType) {
printSetterJavadoc(accessMode, it, indent, "Copies the specified encoded string to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate("ByteBuffer")} value) { $n$setter($ADDRESS, value); return this; }")
} else {
val bufferType = it.primitiveMapping.toPointer.javaMethodName
printSetterJavadoc(accessMode, it, indent, "Copies the specified {@link $bufferType} to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate(bufferType)} value) { $n$setter($ADDRESS, value); return this; }")
printSetterJavadoc(accessMode, it, indent, "Sets the specified value at the specified index of the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(int index, ${it.annotate(it.nativeType.javaMethodType, it.nativeType)} value) { $n$setter($ADDRESS, index, value); return this; }")
}
} else if (it.nativeType is CharSequenceType) {
printSetterJavadoc(accessMode, it, indent, "Sets the address of the specified encoded string to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate("ByteBuffer")} value) { $n$setter($ADDRESS, value); return this; }")
} else if (it.nativeType.isPointerData) {
val pointerType = it.nativeType.javaMethodType
if ((it.nativeType as PointerType<*>).elementType is StructType && it.isStructBuffer) {
printSetterJavadoc(accessMode, it, indent, "Sets the address of the specified {@link $pointerType.Buffer} to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate("$pointerType.Buffer")} value) { $n$setter($ADDRESS, value); return this; }")
} else {
printSetterJavadoc(accessMode, it, indent, "Sets the address of the specified {@link $pointerType} to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate(pointerType)} value) { $n$setter($ADDRESS, value); return this; }")
}
}
if (it.has<Expression>()) {
val javadoc: String
val expression = it.get<Expression>().value.let { expression ->
if (expression.startsWith("#")) {
if (expression.endsWith(')')) {
throw NotImplementedError()
}
val token = Generator.tokens[module]!![expression.substring(1)]!!
javadoc = processDocumentation("Sets the $expression value to the \\#member field.")
token
} else {
javadoc = "Sets the default value to the #member field."
expression
}
}
printSetterJavadoc(accessMode, it, indent, javadoc, setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter\$Default() { return $setter(${expression.replace('#', '.')}); }")
}
if (it.has<PointerSetter>()) {
val pointerSetter = it.get<PointerSetter>()
pointerSetter.types.forEach { type ->
val hasOverrideAnnotation = overrides && alias != null && alias[member].let { member ->
member.has<PointerSetter>() && member.get<PointerSetter>().types.contains(type)
}
if (pointerSetter.prepend) {
printSetterJavadoc(accessMode, it, indent, "Prepends the specified {@link $type} value to the {@code $setter} chain.", setter)
if (hasOverrideAnnotation) println("$indent@Override")
println("${indent}public $returnType $setter($type value) { return this.$setter(value.${pointerSetter.targetSetter ?: setter}(this.$setter()).address()); }")
} else {
printSetterJavadoc(accessMode, it, indent, "Sets the address of the specified {@link $type} value to the #member field.", setter)
if (hasOverrideAnnotation) println("$indent@Override")
println("${indent}public $returnType $setter($type value) { return $setter(value.address()); }")
}
}
}
}
}
}
private fun PrintWriter.generateStaticGetters(
members: Sequence<StructMember>,
parentStruct: Struct? = null,
parentGetter: String = "",
parentField: String = ""
) {
members.forEach {
val getter = it.field(parentGetter)
val field = getFieldOffset(it, parentStruct, parentField)
if (it.isNestedStruct) {
val nestedStruct = (it.nativeType as StructType).definition
val structType = nestedStruct.className
if (structType === ANONYMOUS)
generateStaticGetters(
it.nestedMembers, nestedStruct,
if (it.name === ANONYMOUS) parentGetter else getter,
if (it.name === ANONYMOUS) parentField else field
)
else {
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println("${t}public static $structType n$getter(long $STRUCT) { return $structType.create($STRUCT + $field); }")
}
} else {
// Getter
if (it !is StructMemberArray && !it.nativeType.isPointerData) {
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
if (it.nativeType is FunctionType) {
println("$t${it.nullable("public")} static ${it.nativeType.className} n$getter(long $STRUCT) { return ${it.construct(it.nativeType.className)}(memGetAddress($STRUCT + $field)); }")
} else if (it.getter != null) {
println("${t}public static ${it.nativeType.nativeMethodType} n$getter(long $STRUCT) { return ${it.getter}; }")
} else if (it.bits != -1) {
println("${t}public static native ${it.nativeType.nativeMethodType} n$getter(long $STRUCT);")
} else {
val javaType = it.nativeType.nativeMethodType
print("${t}public static $javaType n$getter(long $STRUCT) { return ${getBufferMethod("get", it, javaType)}$STRUCT + $field)")
if (it.nativeType.mapping === PrimitiveMapping.BOOLEAN)
print(" != 0")
println("; }")
}
}
// Alternative getters
if (it is StructMemberArray) {
if (it.nativeType.dereference is StructType) {
val nestedStruct = it.nativeType.javaMethodType
val capacity = getAutoSizeExpression(it.name) ?: it.size
if (it.nativeType is PointerType<*>) {
val autoSizeIndirect = getReferenceMember<AutoSizeIndirect>(it.name)
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println("${t}public static PointerBuffer n$getter(long $STRUCT) { return ${it.mem("PointerBuffer")}($STRUCT + $field, $capacity); }")
if (it.public)
println("$t/** Unsafe version of {@link #$getter(int) $getter}. */")
println("$t${it.nullable("public")} static $nestedStruct${if (autoSizeIndirect == null) "" else ".Buffer"} n$getter(long $STRUCT, int index) {")
println("$t${t}return ${it.construct(nestedStruct)}(memGetAddress($STRUCT + $field + check(index, $capacity) * POINTER_SIZE)${
if (autoSizeIndirect == null) "" else ", n${autoSizeIndirect.name}($STRUCT)"
});")
println("$t}")
} else {
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println("${t}public static $nestedStruct.Buffer n$getter(long $STRUCT) { return ${it.construct(nestedStruct)}($STRUCT + $field, $capacity); }")
if (it.public)
println("$t/** Unsafe version of {@link #$getter(int) $getter}. */")
println("$t${it.nullable("public")} static $nestedStruct n$getter(long $STRUCT, int index) {")
println("$t${t}return ${it.construct(nestedStruct)}($STRUCT + $field + check(index, $capacity) * $nestedStruct.SIZEOF);")
println("$t}")
}
} else if (it.nativeType is CharType) {
val mapping = it.nativeType.mapping
val capacity = getAutoSizeExpression(it.name) ?: it.getCheckExpression()
val byteSize = capacity ?: if (mapping.bytes == 1) it.size else "${it.size} * ${mapping.bytes}"
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println("${t}public static ByteBuffer n$getter(long $STRUCT) { return memByteBuffer($STRUCT + $field, $byteSize); }")
if (it.public)
println("$t/** Unsafe version of {@link #${getter}String}. */")
println("${t}public static String n${getter}String(long $STRUCT) { return mem${mapping.charset}(${if (capacity != null) "n$getter($STRUCT)" else "$STRUCT + $field"}); }")
} else {
val mapping = it.primitiveMapping
val bufferType = mapping.toPointer.javaMethodName
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println("${t}public static $bufferType n$getter(long $STRUCT) { return ${it.mem(bufferType)}($STRUCT + $field, ${getAutoSizeExpression(it.name) ?: it.size}); }")
val javaType = it.nativeType.nativeMethodType
if (it.public)
println("$t/** Unsafe version of {@link #$getter(int) $getter}. */")
println("${t}public static $javaType n$getter(long $STRUCT, int index) {")
print("$t${t}return ${getBufferMethod("get", it, javaType)}$STRUCT + $field + check(index, ${it.size}) * ${mapping.bytesExpression})")
if (it.nativeType.mapping === PrimitiveMapping.BOOLEAN)
print(" != 0")
println(";\n$t}")
}
} else if (it.nativeType is CharSequenceType) {
val mapping = it.nativeType.charMapping
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println("$t${it.nullable("public")} static ByteBuffer n$getter(long $STRUCT) { return ${it.mem("ByteBufferNT${mapping.bytes}")}(memGetAddress($STRUCT + $field)); }")
if (it.public)
println("$t/** Unsafe version of {@link #${getter}String}. */")
println("$t${it.nullable("public")} static String n${getter}String(long $STRUCT) { return ${it.mem(mapping.charset)}(memGetAddress($STRUCT + $field)); }")
} else if (it.nativeType.isPointerData) {
val returnType = it.nativeType.javaMethodType
if (it.nativeType.dereference is StructType) {
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println(if (it.isStructBuffer) {
val capacity = getAutoSizeExpression(it.name) ?: it.getCheckExpression()
if (capacity == null)
"$t${it.nullable("public")} static $returnType.Buffer n$getter(long $STRUCT, int $BUFFER_CAPACITY_PARAM) { return ${it.construct(returnType)}(memGetAddress($STRUCT + $field), $BUFFER_CAPACITY_PARAM); }"
else
"$t${it.nullable("public")} static $returnType.Buffer n$getter(long $STRUCT) { return ${it.construct(returnType)}(memGetAddress($STRUCT + $field), $capacity); }"
} else
"$t${it.nullable("public")} static $returnType n$getter(long $STRUCT) { return ${it.construct(returnType)}(memGetAddress($STRUCT + $field)); }"
)
} else {
val capacity = getAutoSizeExpression(it.name) ?: it.getCheckExpression()
if (capacity == null) {
if (it.public)
println("$t/** Unsafe version of {@link #$getter(int) $getter}. */")
println("$t${it.nullable("public")} static $returnType n$getter(long $STRUCT, int $BUFFER_CAPACITY_PARAM) { return ${it.mem(returnType)}(memGetAddress($STRUCT + $field), $BUFFER_CAPACITY_PARAM); }")
} else {
if (it.public)
println("$t/** Unsafe version of {@link #$getter() $getter}. */")
println("$t${it.nullable("public")} static $returnType n$getter(long $STRUCT) { return ${it.mem(returnType)}(memGetAddress($STRUCT + $field), $capacity); }")
}
}
}
}
}
}
private fun PrintWriter.generateGetterAnnotations(indent: String, member: StructMember, type: String, nativeType: NativeType = member.nativeType) {
if (nativeType.isReference && member.isNullable) {
println("$indent@Nullable")
}
nativeType.annotation(type).let {
if (it != null)
println("$indent$it")
}
}
private fun PrintWriter.generateGetters(
accessMode: AccessMode,
members: Sequence<StructMember>,
parentGetter: String = "",
parentMember: String = ""
) {
val n = if (accessMode === AccessMode.INSTANCE) "n" else "$className.n"
members.forEach {
val getter = it.field(parentGetter)
val member = it.fieldName(parentMember)
val indent = accessMode.indent
if (it.isNestedStruct) {
val structType = it.nativeType.javaMethodType
if (structType === ANONYMOUS)
generateGetters(
accessMode,
it.nestedMembers,
if (it.name === ANONYMOUS) parentGetter else getter,
if (it.name === ANONYMOUS) parentMember else member
)
else {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $structType} view of the #member field.", getter, member)
generateGetterAnnotations(indent, it, structType)
println("${indent}public $structType $getter() { return $n$getter($ADDRESS); }")
}
} else {
// Getter
if (it !is StructMemberArray && !it.nativeType.isPointerData) {
val returnType = when (it.nativeType) {
is FunctionType -> it.nativeType.className
is WrappedPointerType -> "long"
else -> it.nativeType.javaMethodType
}
printGetterJavadoc(accessMode, it, indent, "@return the value of the #member field.", getter, member)
generateGetterAnnotations(indent, it, returnType)
println("${indent}public $returnType $getter() { return $n$getter($ADDRESS)${if (it.nativeType.mapping === PrimitiveMapping.BOOLEAN4) " != 0" else ""}; }")
}
// Alternative getters
if (it is StructMemberArray) {
if (it.nativeType.dereference is StructType) {
val structType = it.nativeType.javaMethodType
if (it.nativeType is PointerType<*>) {
printGetterJavadoc(accessMode, it, indent, "@return a {@link PointerBuffer} view of the #member field.", getter, member)
generateGetterAnnotations(indent, it, "PointerBuffer", it.arrayType)
println("${indent}public PointerBuffer $getter() { return $n$getter($ADDRESS); }")
val retType = "$structType${if (getReferenceMember<AutoSizeIndirect>(it.name) == null) "" else ".Buffer"}"
printGetterJavadoc(accessMode, it, indent, "@return a {@link $structType} view of the pointer at the specified index of the #member field.", getter, member)
generateGetterAnnotations(indent, it, retType)
println("${indent}public $retType $getter(int index) { return $n$getter($ADDRESS, index); }")
} else {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $structType}.Buffer view of the #member field.", getter, member)
generateGetterAnnotations(indent, it, "$structType.Buffer", it.arrayType)
println("${indent}public $structType.Buffer $getter() { return $n$getter($ADDRESS); }")
printGetterJavadoc(accessMode, it, indent, "@return a {@link $structType} view of the struct at the specified index of the #member field.", getter, member)
generateGetterAnnotations(indent, it, structType)
println("${indent}public $structType $getter(int index) { return $n$getter($ADDRESS, index); }")
}
} else if (it.nativeType is CharType) {
printGetterJavadoc(accessMode, it, indent, "@return a {@link ByteBuffer} view of the #member field.", getter, member)
generateGetterAnnotations(indent, it, "ByteBuffer", it.arrayType)
println("${indent}public ByteBuffer $getter() { return $n$getter($ADDRESS); }")
printGetterJavadoc(accessMode, it, indent, "@return the null-terminated string stored in the #member field.", getter, member)
generateGetterAnnotations(indent, it, "String", it.arrayType)
println("${indent}public String ${getter}String() { return $n${getter}String($ADDRESS); }")
} else {
val bufferType = it.primitiveMapping.toPointer.javaMethodName
printGetterJavadoc(accessMode, it, indent, "@return a {@link $bufferType} view of the #member field.", getter, member)
generateGetterAnnotations(indent, it, bufferType, it.arrayType)
println("${indent}public $bufferType $getter() { return $n$getter($ADDRESS); }")
printGetterJavadoc(accessMode, it, indent, "@return the value at the specified index of the #member field.", getter, member)
generateGetterAnnotations(indent, it, it.nativeType.nativeMethodType)
println("${indent}public ${it.nativeType.nativeMethodType} $getter(int index) { return $n$getter($ADDRESS, index); }")
}
} else if (it.nativeType is CharSequenceType) {
printGetterJavadoc(accessMode, it, indent, "@return a {@link ByteBuffer} view of the null-terminated string pointed to by the #member field.", getter, member)
generateGetterAnnotations(indent, it, "ByteBuffer")
println("${indent}public ByteBuffer $getter() { return $n$getter($ADDRESS); }")
printGetterJavadoc(accessMode, it, indent, "@return the null-terminated string pointed to by the #member field.", getter, member)
generateGetterAnnotations(indent, it, "String")
println("${indent}public String ${getter}String() { return $n${getter}String($ADDRESS); }")
} else if (it.nativeType.isPointerData) {
val returnType = it.nativeType.javaMethodType
if (it.nativeType.dereference is StructType) {
if (it.isStructBuffer) {
if (getReferenceMember<AutoSizeMember>(it.name) == null && !it.has<Check>()) {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $returnType.Buffer} view of the struct array pointed to by the #member field.", getter, member, BUFFER_CAPACITY)
generateGetterAnnotations(indent, it, "$returnType.Buffer")
println("${indent}public $returnType.Buffer $getter(int $BUFFER_CAPACITY_PARAM) { return $n$getter($ADDRESS, $BUFFER_CAPACITY_PARAM); }")
} else {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $returnType.Buffer} view of the struct array pointed to by the #member field.", getter, member)
generateGetterAnnotations(indent, it, "$returnType.Buffer")
println("${indent}public $returnType.Buffer $getter() { return $n$getter($ADDRESS); }")
}
} else {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $returnType} view of the struct pointed to by the #member field.", getter, member)
generateGetterAnnotations(indent, it, returnType)
println("${indent}public $returnType $getter() { return $n$getter($ADDRESS); }")
}
} else {
if (getReferenceMember<AutoSizeMember>(it.name) == null && !it.has<Check>()) {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $returnType} view of the data pointed to by the #member field.", getter, member, BUFFER_CAPACITY)
generateGetterAnnotations(indent, it, returnType)
println("${indent}public $returnType $getter(int $BUFFER_CAPACITY_PARAM) { return $n$getter($ADDRESS, $BUFFER_CAPACITY_PARAM); }")
} else {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $returnType} view of the data pointed to by the #member field.", getter, member)
generateGetterAnnotations(indent, it, returnType)
println("${indent}public $returnType $getter() { return $n$getter($ADDRESS); }")
}
}
}
}
}
}
private fun getBufferMethod(type: String, member: StructMember, javaType: String) = if (member.nativeType.isPointer)
"mem${type.upperCaseFirst}Address("
else if (member.nativeType.mapping === PrimitiveMapping.CLONG)
"mem${type.upperCaseFirst}CLong("
else
"UNSAFE.$type${
bufferMethodMap[javaType] ?: throw UnsupportedOperationException("Unsupported struct member java type: $className.${member.name} ($javaType)")
}(null, "
override val skipNative get() = !nativeLayout && members.isNotEmpty() && members.none { it.bits != -1 && it.getter == null }
override fun PrintWriter.generateNative() {
print(HEADER)
nativeImport("<stddef.h>")
nativeDirective(
"""#ifdef LWJGL_WINDOWS
#define alignof __alignof
#else
#include <stdalign.h>
#endif""")
preamble.printNative(this)
println("""
EXTERN_C_ENTER
JNIEXPORT jint JNICALL Java_${nativeFileNameJNI}_offsets(JNIEnv *$JNIENV, jclass clazz, jlong bufferAddress) {
jint *buffer = (jint *)(uintptr_t)bufferAddress;
UNUSED_PARAMS($JNIENV, clazz)
""")
if (virtual) {
// NOTE: Assumes a plain struct definition (no nested structs, no unions)
println("${t}typedef struct $nativeName {")
for (m in members) {
print("$t$t${m.nativeType.name}")
println(" ${m.name};")
}
println("$t} $nativeName;\n")
}
var index = 0
if (members.isNotEmpty()) {
index = generateNativeMembers(members)
if (index != 0) {
println()
}
}
print(
""" buffer[$index] = alignof($nativeName);
return sizeof($nativeName);
}""")
generateNativeGetters(members)
generateNativeSetters(mutableMembers())
println("""
EXTERN_C_EXIT""")
}
private fun PrintWriter.generateNativeMembers(members: List<StructMember>, offset: Int = 0, prefix: String = ""): Int {
var index = offset
members.forEach {
if (it.name === ANONYMOUS && it.isNestedStruct) {
index = generateNativeMembers((it.nativeType as StructType).definition.members, index + 1, prefix) // recursion
} else if (it is StructMemberPadding) {
index++
} else if (it.bits == -1) {
println("${t}buffer[$index] = (jint)offsetof($nativeName, $prefix${if (it.has<NativeName>()) it.get<NativeName>().nativeName else it.name});")
index++
if (it.isNestedStruct) {
// Output nested structs
val structType = it.nativeType as StructType
if (structType.name === ANONYMOUS)
index = generateNativeMembers(structType.definition.members, index, prefix = "$prefix${it.name}.") // recursion
}
}
}
return index
}
private fun PrintWriter.generateNativeGetters(members: List<StructMember>, prefix: String = "") {
members.forEach {
if (it.name === ANONYMOUS && it.isNestedStruct) {
generateNativeGetters((it.nativeType as StructType).definition.members, prefix) // recursion
} else if (it.isNestedStruct) {
// Output nested structs
val structType = it.nativeType as StructType
if (structType.name === ANONYMOUS)
generateNativeGetters(structType.definition.members, "$prefix${it.name}.") // recursion
} else if (it.bits != -1 && it.getter == null) {
val signature = "${nativeFileNameJNI}_n${"${prefix.replace('.', '_')}${it.name}".asJNIName}__J"
print("""
JNIEXPORT ${it.nativeType.jniFunctionType} JNICALL Java_$signature(JNIEnv *$JNIENV, jclass clazz, jlong bufferAddress) {
UNUSED_PARAMS($JNIENV, clazz)
$nativeName *buffer = ($nativeName *)(uintptr_t)bufferAddress;
return (${it.nativeType.jniFunctionType})buffer->$prefix${it.name};
}""")
}
}
}
private fun PrintWriter.generateNativeSetters(members: Sequence<StructMember>, prefix: String = "") {
members.forEach {
if (it.name === ANONYMOUS && it.isNestedStruct) {
generateNativeSetters((it.nativeType as StructType).definition.mutableMembers(), prefix) // recursion
} else if (it.isNestedStruct) {
// Output nested structs
val structType = it.nativeType as StructType
if (structType.name === ANONYMOUS)
generateNativeSetters(structType.definition.mutableMembers(), "$prefix${it.name}.") // recursion
} else if (it.bits != -1 && it.setter == null) {
val signature = "${nativeFileNameJNI}_n${"${prefix.replace('.', '_')}${it.name}".asJNIName}__J${it.nativeType.jniSignatureStrict}"
print("""
JNIEXPORT void JNICALL Java_$signature(JNIEnv *$JNIENV, jclass clazz, jlong bufferAddress, ${it.nativeType.jniFunctionType} value) {
UNUSED_PARAMS($JNIENV, clazz)
$nativeName *buffer = ($nativeName *)(uintptr_t)bufferAddress;
buffer->$prefix${it.name} = (${it.nativeType.name})value;
}""")
}
}
}
fun AutoSize(reference: String, vararg dependent: String, optional: Boolean = false, atLeastOne: Boolean = false) =
AutoSizeMember(reference, *dependent, optional = optional, atLeastOne = atLeastOne)
fun AutoSize(div: Int, reference: String, vararg dependent: String, optional: Boolean = false, atLeastOne: Boolean = false) =
when {
div < 1 -> throw IllegalArgumentException()
div == 1 -> AutoSizeMember(reference, *dependent, optional = optional, atLeastOne = atLeastOne)
Integer.bitCount(div) == 1 -> AutoSizeShr(Integer.numberOfTrailingZeros(div).toString(), reference, *dependent, optional = optional, atLeastOne = atLeastOne)
else -> AutoSizeDiv(div.toString(), reference, *dependent, optional = optional, atLeastOne = atLeastOne)
}
fun AutoSizeDiv(expression: String, reference: String, vararg dependent: String, optional: Boolean = false, atLeastOne: Boolean = false) =
AutoSizeMember(reference, *dependent, factor = AutoSizeFactor.div(expression), optional = optional, atLeastOne = atLeastOne)
fun AutoSizeMul(expression: String, reference: String, vararg dependent: String, optional: Boolean = false, atLeastOne: Boolean = false) =
AutoSizeMember(reference, *dependent, factor = AutoSizeFactor.mul(expression), optional = optional, atLeastOne = atLeastOne)
fun AutoSizeShr(expression: String, reference: String, vararg dependent: String, optional: Boolean = false, atLeastOne: Boolean = false) =
AutoSizeMember(reference, *dependent, factor = AutoSizeFactor.shr(expression), optional = optional, atLeastOne = atLeastOne)
fun AutoSizeShl(expression: String, reference: String, vararg dependent: String, optional: Boolean = false, atLeastOne: Boolean = false) =
AutoSizeMember(reference, *dependent, factor = AutoSizeFactor.shl(expression), optional = optional, atLeastOne = atLeastOne)
}
fun struct(
module: Module,
className: String,
nativeSubPath: String = "",
nativeName: String = className,
virtual: Boolean = false,
mutable: Boolean = true,
alias: StructType? = null,
parentStruct: StructType? = null,
nativeLayout: Boolean = false,
skipBuffer: Boolean = false,
setup: (Struct.() -> Unit)? = null
): StructType =
Struct(
module, className, nativeSubPath, nativeName, false,
virtual, mutable, alias?.definition, parentStruct?.definition, nativeLayout, !skipBuffer
).init(setup)
fun union(
module: Module,
className: String,
nativeSubPath: String = "",
nativeName: String = className,
virtual: Boolean = false,
mutable: Boolean = true,
alias: StructType? = null,
parentStruct: StructType? = null,
nativeLayout: Boolean = false,
skipBuffer: Boolean = false,
setup: (Struct.() -> Unit)? = null
): StructType =
Struct(
module, className, nativeSubPath, nativeName, true,
virtual, mutable, alias?.definition, parentStruct?.definition, nativeLayout, !skipBuffer
).init(setup) | bsd-3-clause |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/analytics/FindInPageFunnel.kt | 1 | 979 | package org.wikipedia.analytics
import org.json.JSONObject
import org.wikipedia.WikipediaApp
import org.wikipedia.dataclient.WikiSite
class FindInPageFunnel(app: WikipediaApp, wiki: WikiSite?, private val pageId: Int) :
TimedFunnel(app, SCHEMA_NAME, REV_ID, SAMPLE_LOG_ALL, wiki) {
private var numFindNext = 0
private var numFindPrev = 0
var pageHeight = 0
var findText: String? = null
override fun preprocessSessionToken(eventData: JSONObject) {}
fun addFindNext() {
numFindNext++
}
fun addFindPrev() {
numFindPrev++
}
fun logDone() {
log(
"pageID", pageId,
"numFindNext", numFindNext,
"numFindPrev", numFindPrev,
"findText", findText,
"pageHeight", pageHeight
)
}
companion object {
private const val SCHEMA_NAME = "MobileWikiAppFindInPage"
private const val REV_ID = 19690671
}
}
| apache-2.0 |
google/ground-android | ground/src/main/java/com/google/android/ground/ui/map/MapFragment.kt | 1 | 4288 | /*
* Copyright 2021 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.android.ground.ui.map
import android.annotation.SuppressLint
import androidx.annotation.IdRes
import com.cocoahero.android.gmaps.addons.mapbox.MapBoxOfflineTileProvider
import com.google.android.ground.model.geometry.Point
import com.google.android.ground.model.locationofinterest.LocationOfInterest
import com.google.android.ground.rx.Nil
import com.google.android.ground.rx.annotations.Hot
import com.google.android.ground.ui.common.AbstractFragment
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableSet
import io.reactivex.Flowable
import io.reactivex.Observable
import java8.util.function.Consumer
/** Interface for a Fragment that renders a map view. */
interface MapFragment {
/** Returns a list of supported basemap types. */
val availableMapTypes: ImmutableList<MapType>
/** Returns the current map zoom level. */
val currentZoomLevel: Float
/** Get or set the current map type. */
var mapType: Int
/** Get or set the bounds of the currently visible viewport. */
var viewport: Bounds
/** Adds the [MapFragment] to a fragment. */
fun attachToFragment(
containerFragment: AbstractFragment,
@IdRes containerId: Int,
mapAdapter: Consumer<MapFragment>
)
/** A stream of interaction events on rendered [MapLocationOfInterest]s. */
val locationOfInterestInteractions: @Hot Observable<MapLocationOfInterest>
/** A stream of ambiguous [MapLocationOfInterest] interactions. */
val ambiguousLocationOfInterestInteractions: @Hot Observable<ImmutableList<MapLocationOfInterest>>
/**
* Returns map drag events. Emits an empty event when the map starts to move by the user.
* Subscribers that can't keep up receive the latest event ([Flowable.onBackpressureLatest]).
*/
val startDragEvents: @Hot Flowable<Nil>
/**
* Returns camera movement events. Emits the new camera position each time the map stops moving.
* Subscribers that can't keep up receive the latest event ([Flowable.onBackpressureLatest]).
*/
val cameraMovedEvents: @Hot Flowable<CameraPosition>
/** Enables map gestures like pan and zoom. */
fun enableGestures()
/** Disables all map gestures like pan and zoom. */
fun disableGestures()
/** Centers the map viewport around the specified [Point]. */
fun moveCamera(point: Point)
/**
* Centers the map viewport around the specified [Point] and updates the map's current zoom level.
*/
fun moveCamera(point: Point, zoomLevel: Float)
/** Displays user location indicator on the map. */
@SuppressLint("MissingPermission") fun enableCurrentLocationIndicator()
/** Update the set of [MapLocationOfInterest]s rendered on the map. */
fun renderLocationsOfInterest(mapLocationsOfInterest: ImmutableSet<MapLocationOfInterest>)
/**
* Refresh the set of rendered [MapLocationOfInterest], updating their size according to the map's
* current zoom level.
*/
fun refreshRenderedLocationsOfInterest()
// TODO(#691): Create interface and impl to encapsulate MapBoxOfflineTileProvider impl.
/** Returns TileProviders associated with this map adapter. */
val tileProviders: @Hot Observable<MapBoxOfflineTileProvider>
/** Render locally stored tile overlays on the map. */
fun addLocalTileOverlays(mbtilesFiles: ImmutableSet<String>)
/** Render remote tile overlays on the map. */
fun addRemoteTileOverlays(urls: ImmutableList<String>)
/** Returns the actual distance in pixels between provided points. */
fun getDistanceInPixels(point1: Point, point2: Point): Double
/** Update UI of rendered [LocationOfInterest]. */
fun setActiveLocationOfInterest(locationOfInterest: LocationOfInterest?)
}
| apache-2.0 |
fwcd/kotlin-language-server | server/src/test/resources/references/ReferenceConstructor.kt | 1 | 268 | private class ReferenceConstructor(mainConstructor: String) {
constructor(secondaryConstructor: String, partTwo: String): this(secondaryConstructor + partTwo) {
}
}
private fun main() {
ReferenceConstructor("foo")
ReferenceConstructor("foo", "bar")
}
| mit |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/booleanLiteralArgument/hasName.kt | 13 | 116 | // PROBLEM: none
fun foo(a: Boolean, b: Boolean, c: Boolean) {}
fun test() {
foo(true, true, c = true<caret>)
} | apache-2.0 |
dahlstrom-g/intellij-community | java/java-impl-refactorings/src/com/intellij/refactoring/extractMethod/newImpl/ExtractMethodHelper.kt | 5 | 12765 | // 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.refactoring.extractMethod.newImpl
import com.intellij.codeInsight.Nullability
import com.intellij.codeInsight.NullableNotNullManager
import com.intellij.codeInsight.PsiEquivalenceUtil
import com.intellij.codeInsight.generation.GenerateMembersUtil
import com.intellij.codeInsight.intention.AddAnnotationPsiFix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.codeStyle.VariableKind
import com.intellij.psi.formatter.java.MultipleFieldDeclarationHelper
import com.intellij.psi.impl.source.DummyHolder
import com.intellij.psi.impl.source.codeStyle.JavaCodeStyleManagerImpl
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.refactoring.IntroduceVariableUtil
import com.intellij.refactoring.extractMethod.newImpl.structures.DataOutput
import com.intellij.refactoring.extractMethod.newImpl.structures.DataOutput.*
import com.intellij.refactoring.extractMethod.newImpl.structures.ExtractOptions
import com.intellij.refactoring.extractMethod.newImpl.structures.InputParameter
import com.intellij.util.CommonJavaRefactoringUtil
object ExtractMethodHelper {
fun hasReferencesToScope(scope: List<PsiElement>, elements: List<PsiElement>): Boolean {
val localVariables = scope.asSequence().flatMap { element -> PsiTreeUtil.findChildrenOfType(element, PsiVariable::class.java) }.toSet()
return elements.asSequence()
.flatMap { element -> PsiTreeUtil.findChildrenOfType(element, PsiReferenceExpression::class.java) }
.mapNotNull { reference -> reference.resolve() as? PsiVariable }
.any { variable -> variable in localVariables }
}
@JvmStatic
fun findEditorSelection(editor: Editor): TextRange? {
val selectionModel = editor.selectionModel
return if (selectionModel.hasSelection()) TextRange(selectionModel.selectionStart, selectionModel.selectionEnd) else null
}
fun isNullabilityAvailable(extractOptions: ExtractOptions): Boolean {
val project = extractOptions.project
val scope = extractOptions.elements.first().resolveScope
val defaultNullable = NullableNotNullManager.getInstance(project).defaultNullable
val annotationClass = JavaPsiFacade.getInstance(project).findClass(defaultNullable, scope)
return annotationClass != null
}
fun wrapWithCodeBlock(elements: List<PsiElement>): List<PsiCodeBlock> {
require(elements.isNotEmpty())
val codeBlock = PsiElementFactory.getInstance(elements.first().project).createCodeBlock()
elements.forEach { codeBlock.add(it) }
return listOf(codeBlock)
}
fun getReturnedExpression(returnOrYieldStatement: PsiStatement): PsiExpression? {
return when (returnOrYieldStatement) {
is PsiReturnStatement -> returnOrYieldStatement.returnValue
is PsiYieldStatement -> returnOrYieldStatement.expression
else -> null
}
}
fun findUsedTypeParameters(source: PsiTypeParameterList?, searchScope: List<PsiElement>): List<PsiTypeParameter> {
val typeParameterList = CommonJavaRefactoringUtil.createTypeParameterListWithUsedTypeParameters(
source, *searchScope.toTypedArray())
return typeParameterList?.typeParameters.orEmpty().toList()
}
fun inputParameterOf(externalReference: ExternalReference): InputParameter {
return InputParameter(externalReference.references, requireNotNull(externalReference.variable.name), externalReference.variable.type)
}
fun inputParameterOf(expressionGroup: List<PsiExpression>): InputParameter {
require(expressionGroup.isNotEmpty())
val expression = expressionGroup.first()
val objectType = PsiType.getJavaLangObject(expression.manager, GlobalSearchScope.projectScope(expression.project))
return InputParameter(expressionGroup, guessName(expression), expressionGroup.first().type ?: objectType)
}
fun PsiElement.addSiblingAfter(element: PsiElement): PsiElement {
return this.parent.addAfter(element, this)
}
fun getValidParentOf(element: PsiElement): PsiElement {
val physicalParent = when (val parent = element.parent) {
is DummyHolder -> parent.context
null -> element.context
else -> parent
}
return physicalParent ?: throw IllegalArgumentException()
}
fun normalizedAnchor(anchor: PsiMember): PsiMember {
return if (anchor is PsiField) {
MultipleFieldDeclarationHelper.findLastFieldInGroup(anchor.node).psi as? PsiField ?: anchor
} else {
anchor
}
}
fun addNullabilityAnnotation(owner: PsiModifierListOwner, nullability: Nullability) {
val nullabilityManager = NullableNotNullManager.getInstance(owner.project)
val annotation = when (nullability) {
Nullability.NOT_NULL -> nullabilityManager.defaultNotNull
Nullability.NULLABLE -> nullabilityManager.defaultNullable
else -> return
}
val target: PsiAnnotationOwner? = if (owner is PsiParameter) owner.typeElement else owner.modifierList
if (target == null) return
val annotationElement = AddAnnotationPsiFix.addPhysicalAnnotationIfAbsent(annotation, PsiNameValuePair.EMPTY_ARRAY, target)
if (annotationElement != null) {
JavaCodeStyleManager.getInstance(owner.project).shortenClassReferences(annotationElement)
}
}
private fun findVariableReferences(element: PsiElement): Sequence<PsiVariable> {
val references = PsiTreeUtil.findChildrenOfAnyType(element, PsiReferenceExpression::class.java)
return references.asSequence().mapNotNull { reference -> (reference.resolve() as? PsiVariable) }
}
fun hasConflictResolve(name: String?, scopeToIgnore: List<PsiElement>): Boolean {
require(scopeToIgnore.isNotEmpty())
if (name == null) return false
val lastElement = scopeToIgnore.last()
val helper = JavaPsiFacade.getInstance(lastElement.project).resolveHelper
val resolvedRange = helper.resolveAccessibleReferencedVariable(name, lastElement.context)?.textRange ?: return false
return resolvedRange !in TextRange(scopeToIgnore.first().textRange.startOffset, scopeToIgnore.last().textRange.endOffset)
}
fun uniqueNameOf(name: String?, scopeToIgnore: List<PsiElement>, reservedNames: List<String>): String? {
require(scopeToIgnore.isNotEmpty())
if (name == null) return null
val lastElement = scopeToIgnore.last()
if (hasConflictResolve(name, scopeToIgnore) || name in reservedNames){
val styleManager = JavaCodeStyleManager.getInstance(lastElement.project) as JavaCodeStyleManagerImpl
return styleManager.suggestUniqueVariableName(name, lastElement, true)
} else {
return name
}
}
fun guessName(expression: PsiExpression): String {
val codeStyleManager = JavaCodeStyleManager.getInstance(expression.project) as JavaCodeStyleManagerImpl
return findVariableReferences(expression).mapNotNull { variable -> variable.name }.firstOrNull()
?: codeStyleManager.suggestSemanticNames(expression).firstOrNull()
?: "x"
}
fun createDeclaration(variable: PsiVariable): PsiDeclarationStatement {
val factory = PsiElementFactory.getInstance(variable.project)
val declaration = factory.createVariableDeclarationStatement(requireNotNull(variable.name), variable.type, null)
val declaredVariable = declaration.declaredElements.first() as PsiVariable
PsiUtil.setModifierProperty(declaredVariable, PsiModifier.FINAL, variable.hasModifierProperty(PsiModifier.FINAL))
variable.annotations.forEach { annotation -> declaredVariable.modifierList?.add(annotation) }
return declaration
}
fun getExpressionType(expression: PsiExpression): PsiType {
val type = CommonJavaRefactoringUtil.getTypeByExpressionWithExpectedType(expression)
return when {
type != null -> type
expression.parent is PsiExpressionStatement -> PsiType.VOID
else -> PsiType.getJavaLangObject(expression.manager, GlobalSearchScope.allScope(expression.project))
}
}
fun areSame(elements: List<PsiElement?>): Boolean {
val first = elements.firstOrNull()
return elements.all { element -> areSame(first, element) }
}
fun areSame(first: PsiElement?, second: PsiElement?): Boolean {
return when {
first != null && second != null -> PsiEquivalenceUtil.areElementsEquivalent(first, second)
first == null && second == null -> true
else -> false
}
}
private fun boxedTypeOf(type: PsiType, context: PsiElement): PsiType {
return (type as? PsiPrimitiveType)?.getBoxedType(context) ?: type
}
fun PsiModifierListOwner?.hasExplicitModifier(modifier: String): Boolean {
return this?.modifierList?.hasExplicitModifier(modifier) == true
}
fun DataOutput.withBoxedType(): DataOutput {
return when (this) {
is VariableOutput -> copy(type = boxedTypeOf(type, variable))
is ExpressionOutput -> copy(type = boxedTypeOf(type, returnExpressions.first()))
ArtificialBooleanOutput, is EmptyOutput -> this
}
}
fun areSemanticallySame(statements: List<PsiStatement>): Boolean {
if (statements.isEmpty()) return true
if (! areSame(statements)) return false
val returnExpressions = statements.mapNotNull { statement -> (statement as? PsiReturnStatement)?.returnValue }
return returnExpressions.all { expression -> PsiUtil.isConstantExpression(expression) || expression.type == PsiType.NULL }
}
fun haveReferenceToScope(elements: List<PsiElement>, scope: List<PsiElement>): Boolean {
val scopeRange = TextRange(scope.first().textRange.startOffset, scope.last().textRange.endOffset)
return elements.asSequence()
.flatMap { PsiTreeUtil.findChildrenOfAnyType(it, false, PsiJavaCodeReferenceElement::class.java).asSequence() }
.mapNotNull { reference -> reference.resolve() }
.any{ referencedElement -> referencedElement.textRange in scopeRange }
}
fun guessMethodName(options: ExtractOptions): List<String> {
val project = options.project
val initialMethodNames: MutableSet<String> = LinkedHashSet()
val codeStyleManager = JavaCodeStyleManager.getInstance(project) as JavaCodeStyleManagerImpl
val returnType = options.dataOutput.type
val expression = options.elements.singleOrNull() as? PsiExpression
if (expression != null || returnType !is PsiPrimitiveType) {
codeStyleManager.suggestVariableName(VariableKind.FIELD, null, expression, returnType).names
.forEach { name ->
initialMethodNames += codeStyleManager.variableNameToPropertyName(name, VariableKind.FIELD)
}
}
val outVariable = (options.dataOutput as? VariableOutput)?.variable
if (outVariable != null) {
val outKind = codeStyleManager.getVariableKind(outVariable)
val propertyName = codeStyleManager.variableNameToPropertyName(outVariable.name!!, outKind)
val names = codeStyleManager.suggestVariableName(VariableKind.FIELD, propertyName, null, outVariable.type).names
names.forEach { name ->
initialMethodNames += codeStyleManager.variableNameToPropertyName(name, VariableKind.FIELD)
}
}
val normalizedType = (returnType as? PsiEllipsisType)?.toArrayType() ?: returnType
val field = JavaPsiFacade.getElementFactory(project).createField("fieldNameToReplace", normalizedType)
fun suggestGetterName(name: String): String {
field.name = name
return GenerateMembersUtil.suggestGetterName(field)
}
return initialMethodNames.filter { PsiNameHelper.getInstance(project).isIdentifier(it) }
.map { propertyName -> suggestGetterName(propertyName) }
}
fun replacePsiRange(source: List<PsiElement>, target: List<PsiElement>): List<PsiElement> {
val sourceAsExpression = source.singleOrNull() as? PsiExpression
val targetAsExpression = target.singleOrNull() as? PsiExpression
if (sourceAsExpression != null && targetAsExpression != null) {
val replacedExpression = IntroduceVariableUtil.replace(sourceAsExpression,
targetAsExpression,
sourceAsExpression.project)
return listOf(replacedExpression)
}
val normalizedTarget = if (target.size > 1 && source.first().parent !is PsiCodeBlock) {
wrapWithCodeBlock(target)
}
else {
target
}
val replacedElements = normalizedTarget.reversed().map { statement -> source.last().addSiblingAfter(statement) }.reversed()
source.first().parent.deleteChildRange(source.first(), source.last())
return replacedElements
}
} | apache-2.0 |
dahlstrom-g/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/list/search/ReviewListSearchPanelViewModel.kt | 1 | 421 | // 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?>
fun getSearchHistory(): List<S>
} | apache-2.0 |
spotify/heroic | aggregation/simple/src/main/java/com/spotify/heroic/aggregation/simple/TdigestMergingBucket.kt | 1 | 2483 | /*
* Copyright (c) 2015 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.aggregation.simple
import com.spotify.heroic.aggregation.AbstractBucket
import com.spotify.heroic.aggregation.TDigestBucket
import com.spotify.heroic.metric.DistributionPoint
import com.spotify.heroic.metric.HeroicDistribution
import com.spotify.heroic.metric.TdigestPoint
import com.tdunning.math.stats.MergingDigest
import com.tdunning.math.stats.TDigest;
/**
*
* This bucket merges data sketch in every distribution data point visited.
* As the name indicates, this implementation only supports Tdigest.
*
*/
data class TdigestMergingBucket(override val timestamp: Long) : AbstractBucket(), TDigestBucket {
private val datasketch : TDigest = TdigestInstanceUtils.inital()
override fun updateDistributionPoint(key: Map<String, String>, sample : DistributionPoint) {
val heroicDistribution : HeroicDistribution = HeroicDistribution.create(sample.value().value)
val serializedDatasketch = heroicDistribution.toByteBuffer()
val input: TDigest = MergingDigest.fromBytes(serializedDatasketch)
if ( input.size() > 0) {
update(input)
}
}
@Synchronized fun update(input : TDigest) {
//This is a temp fix to handle corrupted datapoint.
try {
datasketch.add(input)
}catch(ignore: Exception) {
}
}
override fun updateTDigestPoint(key: Map<String, String>, sample : TdigestPoint) {
val input: TDigest = sample.value()
if ( input.size() > 0) {
update(input)
}
}
@Synchronized override fun value(): TDigest {
return datasketch
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveNestedClass/deepInnerToTopLevelWithThis/after/usages.kt | 13 | 82 | package test2
import test.A
import test.C
fun foo(): C {
return C(A().B())
} | apache-2.0 |
bitterblue/livingdoc2 | livingdoc-engine/src/main/kotlin/org/livingdoc/engine/fixtures/FixtureMethodInvoker.kt | 2 | 5915 | package org.livingdoc.engine.fixtures
import org.livingdoc.api.conversion.TypeConverter
import org.livingdoc.converters.TypeConverters
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.lang.reflect.Parameter
class FixtureMethodInvoker(
private val document: Any?
) {
/**
* Invoke the given static `method` with the given [String] `arguments`.
*
* Before invoking the method, the [String] arguments will be converted into objects of the appropriate types.
* This is done by looking up a matching [TypeConverter] as follows:
*
* 1. `parameter`
* 2. `method`
* 3. `class`
* 4. `document`
* 5. `default`
*
* This method is capable of invoking any static method. If the invoked method is not public, it will be made so.
*
* @param method the [Method] to invoke
* @param arguments the arguments for the invoked method as strings
* @return the result of the invocation or `null` in case the invoked method has not return type (`void` / `Unit`)
* @throws StaticFixtureMethodInvocationException in case anything went wrong with the invocation
*/
fun invokeStatic(method: Method, arguments: Array<String> = emptyArray()): Any? {
try {
return doInvokeStatic(method, arguments)
} catch (e: Exception) {
throw StaticFixtureMethodInvocationException(method, method.declaringClass, e)
}
}
private fun doInvokeStatic(method: Method, arguments: Array<String>): Any? {
val methodParameters = method.parameters
assertThatAllArgumentsForMethodAreProvided(arguments, methodParameters)
val convertedArguments = convert(arguments, methodParameters)
return forceInvocation(method, convertedArguments)
}
/**
* Invoke the given `method` on the given `fixture` instance with the given [String] `arguments`.
*
* Before invoking the method, the [String] arguments will be converted into objects of the appropriate types.
* This is done by looking up a matching [TypeConverter] as follows:
*
* 1. `parameter`
* 2. `method`
* 3. `class`
* 4. `document`
* 5. `default`
*
* This method is capable of invoking any method on the given fixture instance. If the invoked method is not
* public, it will be made so.
*
* @param method the [Method] to invoke
* @param fixture the fixture instance to invoke the method on
* @param arguments the arguments for the invoked method as strings
* @return the result of the invocation or `null` in case the invoked method has not return type (`void` / `Unit`)
* @throws FixtureMethodInvocationException in case anything went wrong with the invocation
*/
fun invoke(method: Method, fixture: Any, arguments: Array<String> = emptyArray()): Any? {
try {
return doInvoke(method, fixture, arguments)
} catch (e: Exception) {
throw FixtureMethodInvocationException(method, fixture, e)
}
}
private fun doInvoke(method: Method, fixture: Any, arguments: Array<String>): Any? {
val methodParameters = method.parameters
assertThatAllArgumentsForMethodAreProvided(arguments, methodParameters)
val convertedArguments = convert(arguments, methodParameters)
return forceInvocation(method, convertedArguments, fixture)
}
private fun assertThatAllArgumentsForMethodAreProvided(
arguments: Array<String>,
methodParameters: Array<Parameter>
) {
val numberOfArguments = arguments.size
val numberOfMethodParameters = methodParameters.size
if (numberOfArguments != numberOfMethodParameters) {
throw MismatchedNumberOfArgumentsException(numberOfArguments, numberOfMethodParameters)
}
}
private fun convert(
arguments: Array<String>,
methodParameters: Array<Parameter>
): Array<Any> { // TODO: Zip function?
val convertedArguments = mutableListOf<Any>()
for (i in arguments.indices) {
val argument = arguments[i]
val methodParameter = methodParameters[i]
val convertedArgument = convert(argument, methodParameter)
convertedArguments.add(convertedArgument)
}
return convertedArguments.toTypedArray()
}
private fun convert(argument: String, methodParameter: Parameter): Any {
val documentClass = document?.javaClass
val typeConverter = TypeConverters.findTypeConverter(methodParameter, documentClass)
?: throw NoTypeConverterFoundException(methodParameter)
return typeConverter.convert(argument, methodParameter, documentClass)
}
private fun forceInvocation(method: Method, arguments: Array<Any>, instance: Any? = null): Any? {
method.isAccessible = true
try {
return method.invoke(instance, arguments)
} catch (e: InvocationTargetException) {
throw e.cause ?: e
}
}
class FixtureMethodInvocationException(method: Method, fixture: Any, e: Exception) :
RuntimeException("Could not invoke method '$method' on fixture '$fixture' because of an exception:", e)
class StaticFixtureMethodInvocationException(method: Method, fixtureClass: Class<*>, e: Exception) :
RuntimeException(
"Could not invoke method '$method' on fixture class '$fixtureClass' because of an exception:",
e
)
internal class MismatchedNumberOfArgumentsException(args: Int, params: Int) :
RuntimeException("Method argument number mismatch: arguments = $args, method parameters = $params")
internal class NoTypeConverterFoundException(parameter: Parameter) :
RuntimeException("No type converter could be found to convert method parameter: $parameter")
}
| apache-2.0 |
intellij-solidity/intellij-solidity | src/main/kotlin/me/serce/solidity/ide/run/compile/SolProcessingItem.kt | 1 | 497 | package me.serce.solidity.ide.run.compile
import com.intellij.openapi.compiler.FileProcessingCompiler
import com.intellij.openapi.compiler.ValidityState
import com.intellij.openapi.vfs.VirtualFile
class SolProcessingItem(
private val myValidityState: ValidityState,
private val myFile: VirtualFile
) : FileProcessingCompiler.ProcessingItem {
override fun getValidityState(): ValidityState? {
return myValidityState
}
override fun getFile(): VirtualFile {
return myFile
}
}
| mit |
dahlstrom-g/intellij-community | plugins/kotlin/j2k/old/tests/testData/fileOrElement/function/extendsBaseWhichExtendsObject.kt | 13 | 1045 | // ERROR: Unresolved reference: clone
// ERROR: Unresolved reference: finalize
package test
internal class Test : Base() {
override fun hashCode(): Int {
return super.hashCode()
}
override fun equals(o: Any?): Boolean {
return super.equals(o)
}
@Throws(CloneNotSupportedException::class)
override fun clone(): Any {
return super.clone()
}
override fun toString(): String {
return super.toString()
}
@Throws(Throwable::class)
override fun finalize() {
super.finalize()
}
}
internal open class Base {
override fun hashCode(): Int {
return super.hashCode()
}
override fun equals(o: Any?): Boolean {
return super.equals(o)
}
@Throws(CloneNotSupportedException::class)
protected open fun clone(): Any {
return super.clone()
}
override fun toString(): String {
return super.toString()
}
@Throws(Throwable::class)
protected open fun finalize() {
super.finalize()
}
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/fir-low-level-api-ide-impl/src/org/jetbrains/kotlin/idea/fir/low/level/api/ide/SealedClassInheritorsProviderIdeImpl.kt | 3 | 3405 | // 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.fir.low.level.api.ide
import com.intellij.openapi.module.Module
import com.intellij.psi.JavaDirectoryService
import com.intellij.psi.PsiPackage
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PackageScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.ClassInheritorsSearch
import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.utils.classId
import org.jetbrains.kotlin.fir.declarations.utils.isSealed
import org.jetbrains.kotlin.fir.psi
import org.jetbrains.kotlin.idea.base.psi.classIdIfNonLocal
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade
import java.util.concurrent.ConcurrentHashMap
internal class SealedClassInheritorsProviderIdeImpl : SealedClassInheritorsProvider() {
val cache = ConcurrentHashMap<ClassId, List<ClassId>>()
@OptIn(SealedClassInheritorsProviderInternals::class)
override fun getSealedClassInheritors(firClass: FirRegularClass): List<ClassId> {
require(firClass.isSealed)
firClass.sealedInheritorsAttr?.let { return it }
return cache.computeIfAbsent(firClass.classId) { getInheritors(firClass) }
}
private fun getInheritors(firClass: FirRegularClass): List<ClassId> {
// TODO fix for non-source classes
val sealedKtClass = firClass.psi as? KtClass ?: return emptyList()
val module = sealedKtClass.module ?: return emptyList()
val containingPackage = firClass.classId.packageFqName
val psiPackage = KotlinJavaPsiFacade.getInstance(sealedKtClass.project)
.findPackage(containingPackage.asString(), GlobalSearchScope.moduleScope(module))
?: getPackageViaDirectoryService(sealedKtClass)
?: return emptyList()
val kotlinAsJavaSupport = KotlinAsJavaSupport.getInstance(sealedKtClass.project)
val lightClass = sealedKtClass.toLightClass() ?: kotlinAsJavaSupport.getFakeLightClass(sealedKtClass)
val searchScope: SearchScope = getSearchScope(module, psiPackage)
val searchParameters = ClassInheritorsSearch.SearchParameters(lightClass, searchScope, false, true, false)
val subclasses = ClassInheritorsSearch.search(searchParameters)
.mapNotNull { it.classIdIfNonLocal }
.toMutableList()
// Enforce a deterministic order on the result.
subclasses.sortBy { it.toString() }
return subclasses
}
private fun getSearchScope(module: Module, psiPackage: PsiPackage): GlobalSearchScope {
val packageScope = PackageScope(psiPackage, false, false)
// MPP multiple common modules are not supported!!
return module.moduleScope.intersectWith(packageScope)
}
private fun getPackageViaDirectoryService(ktClass: KtClass): PsiPackage? {
val directory = ktClass.containingFile.containingDirectory ?: return null
return JavaDirectoryService.getInstance().getPackage(directory)
}
}
| apache-2.0 |
android/location-samples | ActivityRecognition/app/src/main/java/com/google/android/gms/location/sample/activityrecognition/data/db/AppDatabase.kt | 1 | 1003 | /*
* Copyright 2022 Google, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gms.location.sample.activityrecognition.data.db
import androidx.room.Database
import androidx.room.RoomDatabase
/**
* Room database for the app.
*/
@Database(
entities = [ActivityTransitionRecord::class],
version = 1,
exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
abstract fun getActivityTransitionRecordDao(): ActivityTransitionDao
}
| apache-2.0 |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/models/Target.kt | 1 | 3265 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.shared.models
import androidx.room.ColumnInfo
import androidx.room.Ignore
import android.os.Parcelable
import de.dreier.mytargets.shared.models.db.Shot
import de.dreier.mytargets.shared.targets.TargetFactory
import de.dreier.mytargets.shared.targets.drawable.TargetDrawable
import de.dreier.mytargets.shared.targets.models.TargetModelBase
import de.dreier.mytargets.shared.targets.scoringstyle.ScoringStyle
import kotlinx.android.parcel.IgnoredOnParcel
import kotlinx.android.parcel.Parcelize
/**
* Represents a target face, which is in contrast to a [TargetModelBase] bound to a specific
* scoring style and diameter.
*/
@Parcelize
data class Target(
@ColumnInfo(name = "targetId")
override var id: Long = 0,
@ColumnInfo(name = "targetScoringStyleIndex")
var scoringStyleIndex: Int = 0,
@ColumnInfo(name = "targetDiameter")
var diameter: Dimension = Dimension.UNKNOWN
) : IIdProvider, Comparable<Target>, Parcelable {
@IgnoredOnParcel
@delegate:Ignore
val model: TargetModelBase by lazy { TargetFactory.getTarget(id) }
@IgnoredOnParcel
@delegate:Ignore
val drawable: TargetDrawable by lazy { TargetDrawable(this) }
@Ignore
constructor(target: Long, scoringStyle: Int) : this(target, scoringStyle, Dimension.UNKNOWN) {
this.diameter = model.diameters[0]
}
val name: String
get() = String.format("%s (%s)", toString(), diameter.toString())
fun zoneToString(zone: Int, arrow: Int): String {
return getScoringStyle().zoneToString(zone, arrow)
}
fun getScoreByZone(zone: Int, arrow: Int): Int {
return getScoringStyle().getPointsByScoringRing(zone, arrow)
}
fun getDetails(): String {
return model.scoringStyles[scoringStyleIndex].toString()
}
fun getSelectableZoneList(arrow: Int): List<SelectableZone> {
return model.getSelectableZoneList(scoringStyleIndex, arrow)
}
fun getScoringStyle(): ScoringStyle {
return model.getScoringStyle(scoringStyleIndex)
}
fun getReachedScore(shots: List<Shot>): Score {
return getScoringStyle().getReachedScore(shots)
}
override fun toString(): String {
return model.toString()
}
override fun compareTo(other: Target) = compareBy(Target::id).compare(this, other)
companion object {
fun singleSpotTargetFrom(spotTarget: Target): Target {
if (spotTarget.model.faceCount == 1) {
return spotTarget
}
val singleSpotTargetId = spotTarget.model.singleSpotTargetId.toInt()
return Target(singleSpotTargetId.toLong(), spotTarget.scoringStyleIndex, spotTarget.diameter)
}
}
}
| gpl-2.0 |
tommyli/nem12-manager | fenergy-service/src/main/kotlin/co/firefire/fenergy/shared/repository/LoginNmiRepository.kt | 1 | 544 | // Tommy Li ([email protected]), 2017-07-04
package co.firefire.fenergy.shared.repository
import co.firefire.fenergy.shared.domain.Login
import co.firefire.fenergy.shared.domain.LoginNmi
import org.springframework.data.repository.PagingAndSortingRepository
interface LoginNmiRepository : PagingAndSortingRepository<LoginNmi, Long> {
fun findByLoginUsernameAndNmi(username: String, nmi: String): LoginNmi?
fun findByLoginAndNmi(login: Login, nmi: String): LoginNmi?
fun findAllByLogin(login: Login): Collection<LoginNmi>
}
| apache-2.0 |
spoptchev/kotlin-preconditions | src/main/kotlin/com/github/spoptchev/kotlin/preconditions/matcher/MapMatcher.kt | 1 | 961 | package com.github.spoptchev.kotlin.preconditions.matcher
import com.github.spoptchev.kotlin.preconditions.Condition
import com.github.spoptchev.kotlin.preconditions.Matcher
import com.github.spoptchev.kotlin.preconditions.PreconditionBlock
fun <K, M : Map<K, *>> PreconditionBlock<M>.hasKey(key: K) = object : Matcher<M>() {
override fun test(condition: Condition<M>) = condition.test {
withResult(value.containsKey(key)) { "$expectedTo contain key $key" }
}
}
fun <V, M : Map<*, V>> PreconditionBlock<M>.hasValue(v: V) = object : Matcher<M>() {
override fun test(condition: Condition<M>) = condition.test {
withResult(value.containsValue(v)) { "$expectedTo contain value $v" }
}
}
fun <K, V, M : Map<K, V>> PreconditionBlock<M>.contains(key: K, v: V) = object : Matcher<M>() {
override fun test(condition: Condition<M>) = condition.test {
withResult(value[key] == v) { "$expectedTo contain $key=$v" }
}
}
| mit |
CesarValiente/KUnidirectional | persistence/src/test/kotlin/com/cesarvaliente/kunidirectional/persistence/PersistenceSideEffectTest.kt | 1 | 1280 | /**
* Copyright (C) 2017 Cesar Valiente & Corey Shaw
*
* https://github.com/CesarValiente
* https://github.com/coshaw
*
* 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.cesarvaliente.kunidirectional.persistence
import com.cesarvaliente.kunidirectional.store.Store
import org.junit.Assert.assertThat
import org.junit.Test
import org.hamcrest.CoreMatchers.`is` as iz
class PersistenceSideEffectTest {
val store = object : Store() {}
@Test
fun should_subscribe_to_store() {
val persistenceActionSubscriber = PersistenceSideEffect(
store = store)
with(store.sideEffects) {
assertThat(isEmpty(), iz(false))
assertThat(contains(persistenceActionSubscriber), iz(true))
}
}
} | apache-2.0 |
MGaetan89/ShowsRage | app/src/test/kotlin/com/mgaetan89/showsrage/fragment/AddShowOptionsFragment_GetLocationTest.kt | 1 | 1215 | package com.mgaetan89.showsrage.fragment
import android.widget.Spinner
import com.mgaetan89.showsrage.model.RootDir
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
@RunWith(Parameterized::class)
class AddShowOptionsFragment_GetLocationTest(val spinner: Spinner?, val location: String?) {
@Test
fun getLocation() {
assertThat(AddShowOptionsFragment.getLocation(this.spinner)).isEqualTo(this.location)
}
companion object {
@JvmStatic
@Parameterized.Parameters
fun data(): Collection<Array<Any?>> {
return listOf(
arrayOf<Any?>(null, null),
arrayOf<Any?>(getMockedSpinner(null), null),
arrayOf<Any?>(getMockedSpinner(""), ""),
arrayOf<Any?>(getMockedSpinner("/home/videos/Shows"), "/home/videos/Shows")
)
}
private fun getMockedSpinner(location: String?): Spinner {
var rootDir: RootDir? = null
if (location != null) {
rootDir = RootDir()
rootDir.location = location
}
val spinner = mock(Spinner::class.java)
`when`(spinner.selectedItem).thenReturn(rootDir)
return spinner
}
}
}
| apache-2.0 |
cbeust/klaxon | klaxon/src/test/kotlin/com/beust/klaxon/Issue118Test.kt | 1 | 1157 | package com.beust.klaxon
import org.testng.annotations.Test
@Test
class Issue118Test {
interface Foo{ val x: Int }
data class FooImpl(override val x: Int): Foo
data class BarImpl(val y: Int, private val foo: FooImpl): Foo { // by foo {
@Json(ignored = true)
override val x = foo.x
}
@Test(enabled = false, description = "Work in progress")
fun test() {
val originalJson= """{"foo" : {"x" : 1}, "y" : 1}"""
val instance = Klaxon().parse<BarImpl>(originalJson)!! //Going from JSON to BarImpl
val newJson = Klaxon().toJsonString(instance) //Going back from BarImpl to JSON
println(newJson) //prints {"foo" : {"x" : 1}, "x" : 1, "y" : 1} instead of the original JSON
try {
/* Attempting to go back to BarImpl again, from our newly generated JSON.
* The following line would succeed if newJson was equal to originalJson, but since they differ,
* it fails with a NoSuchFieldException */
Klaxon().parse<BarImpl>(newJson)!!
}
catch (e: Exception)
{
e.printStackTrace()
}
}
}
| apache-2.0 |
cbeust/klaxon | klaxon/src/test/kotlin/com/beust/klaxon/ParseFromEmptyNameTest.kt | 1 | 809 | package com.beust.klaxon
import org.testng.Assert
import org.testng.annotations.Test
@Test
class ParseFromEmptyNameTest {
fun nameSetToEmptyString() {
data class EmptyName (
@Json(name = "")
val empty: String)
val sampleJson = """{"":"value"}"""
val result = Klaxon().parse<EmptyName>(sampleJson)
Assert.assertNotNull(result)
Assert.assertEquals(result!!.empty, "value")
}
fun nameSetToDefaultValue() {
data class SpecificName (
@Json(name = NAME_NOT_INITIALIZED)
val oddName: String)
val sampleJson = """{"$NAME_NOT_INITIALIZED":"value"}"""
Assert.assertThrows(KlaxonException::class.java) {
Klaxon().parse<SpecificName>(sampleJson)
}
}
}
| apache-2.0 |
MGaetan89/ShowsRage | app/src/test/kotlin/com/mgaetan89/showsrage/fragment/LogsFragment_GetLogLevelForMenuId.kt | 1 | 934 | package com.mgaetan89.showsrage.fragment
import com.mgaetan89.showsrage.R
import com.mgaetan89.showsrage.model.LogLevel
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(Parameterized::class)
class LogsFragment_GetLogLevelForMenuId(val menuId: Int, val logLevel: LogLevel?) {
@Test
fun getLogLevelForMenuId() {
assertThat(LogsFragment.getLogLevelForMenuId(this.menuId)).isEqualTo(this.logLevel)
}
companion object {
@JvmStatic
@Parameterized.Parameters
fun data(): Collection<Array<Any?>> {
return listOf(
arrayOf<Any?>(0, null),
arrayOf<Any?>(R.id.menu_debug, LogLevel.DEBUG),
arrayOf<Any?>(R.id.menu_error, LogLevel.ERROR),
arrayOf<Any?>(R.id.menu_info, LogLevel.INFO),
arrayOf<Any?>(R.id.menu_warning, LogLevel.WARNING),
arrayOf<Any?>(R.id.menu_change_quality, null)
)
}
}
}
| apache-2.0 |
DemonWav/MinecraftDevIntelliJ | src/test/kotlin/com/demonwav/mcdev/framework/ProjectBuilder.kt | 1 | 3004 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.framework
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import com.intellij.testFramework.fixtures.TempDirTestFixture
import com.intellij.testFramework.runInEdtAndWait
import org.intellij.lang.annotations.Language
/**
* Like most things in this project at this point, taken from the intellij-rust folks
* https://github.com/intellij-rust/intellij-rust/blob/master/src/test/kotlin/org/rust/ProjectBuilder.kt
*/
class ProjectBuilder(private val fixture: JavaCodeInsightTestFixture, private val tempDirFixture: TempDirTestFixture) {
private val project
get() = fixture.project
var intermediatePath = ""
fun java(
path: String,
@Language("JAVA")
code: String,
configure: Boolean = true,
allowAst: Boolean = false
) = file(path, code, ".java", configure, allowAst)
fun at(
path: String,
@Language("Access Transformers")
code: String,
configure: Boolean = true,
allowAst: Boolean = false
) = file(path, code, "_at.cfg", configure, allowAst)
fun lang(
path: String,
@Language("MCLang")
code: String,
configure: Boolean = true,
allowAst: Boolean = false
) = file(path, code, ".lang", configure, allowAst)
fun nbtt(
path: String,
@Language("NBTT")
code: String,
configure: Boolean = true,
allowAst: Boolean = false
) = file(path, code, ".nbtt", configure, allowAst)
inline fun dir(path: String, block: ProjectBuilder.() -> Unit) {
val oldIntermediatePath = intermediatePath
if (intermediatePath.isEmpty()) {
intermediatePath = path
} else {
intermediatePath += "/$path"
}
block()
intermediatePath = oldIntermediatePath
}
fun file(path: String, code: String, ext: String, configure: Boolean, allowAst: Boolean): VirtualFile {
check(path.endsWith(ext))
val fullPath = if (intermediatePath.isEmpty()) path else "$intermediatePath/$path"
val newFile = tempDirFixture.createFile(fullPath, code.trimIndent())
if (allowAst) {
fixture.allowTreeAccessForFile(newFile)
}
if (configure) {
fixture.configureFromExistingVirtualFile(newFile)
}
return newFile
}
fun <T : PsiFile> VirtualFile.toPsiFile(): T {
@Suppress("UNCHECKED_CAST")
return PsiManager.getInstance(project).findFile(this) as T
}
fun build(builder: ProjectBuilder.() -> Unit) {
runInEdtAndWait {
runWriteAction {
builder()
}
}
}
}
| mit |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mcp/actions/CopyAtAction.kt | 1 | 2097 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.actions
import com.demonwav.mcdev.platform.mcp.srg.McpSrgMap
import com.demonwav.mcdev.util.ActionData
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMethod
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
class CopyAtAction : SrgActionBase() {
override fun withSrgTarget(parent: PsiElement, srgMap: McpSrgMap, e: AnActionEvent, data: ActionData) {
when (parent) {
is PsiField -> {
val srg = srgMap.getSrgField(parent) ?: return showBalloon("No SRG name found", e)
copyToClipboard(
data.editor,
data.element,
parent.containingClass?.qualifiedName + " " + srg.name + " #" + parent.name
)
}
is PsiMethod -> {
val srg = srgMap.getSrgMethod(parent) ?: return showBalloon("No SRG name found", e)
copyToClipboard(
data.editor,
data.element,
parent.containingClass?.qualifiedName + " " + srg.name + srg.descriptor + " #" + parent.name
)
}
is PsiClass -> {
val classMcpToSrg = srgMap.getSrgClass(parent) ?: return showBalloon("No SRG name found", e)
copyToClipboard(data.editor, data.element, classMcpToSrg)
}
else -> showBalloon("Not a valid element", e)
}
}
private fun copyToClipboard(editor: Editor, element: PsiElement, text: String) {
val stringSelection = StringSelection(text)
val clpbrd = Toolkit.getDefaultToolkit().systemClipboard
clpbrd.setContents(stringSelection, null)
showSuccessBalloon(editor, element, "Copied " + text)
}
}
| mit |
google/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/actions/BookmarkTypeChooser.kt | 1 | 9865 | // 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.ide.bookmark.actions
import com.intellij.ide.bookmark.BookmarkBundle.message
import com.intellij.ide.bookmark.BookmarkType
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.JBColor.namedColor
import com.intellij.ui.components.JBTextField
import com.intellij.ui.components.panels.RowGridLayout
import com.intellij.ui.dsl.builder.BottomGap
import com.intellij.ui.dsl.builder.IntelliJSpacingConfiguration
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.RegionPaintIcon
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import org.jetbrains.annotations.Nls
import java.awt.*
import java.awt.RenderingHints.KEY_ANTIALIASING
import java.awt.RenderingHints.VALUE_ANTIALIAS_ON
import java.awt.event.KeyEvent
import java.awt.event.KeyListener
import javax.swing.*
private val ASSIGNED_FOREGROUND = namedColor("Bookmark.MnemonicAssigned.foreground", 0x000000, 0xBBBBBB)
private val ASSIGNED_BACKGROUND = namedColor("Bookmark.MnemonicAssigned.background", 0xF7C777, 0x665632)
private val CURRENT_FOREGROUND = namedColor("Bookmark.MnemonicCurrent.foreground", 0xFFFFFF, 0xFEFEFE)
private val CURRENT_BACKGROUND = namedColor("Bookmark.MnemonicCurrent.background", 0x389FD6, 0x345F85)
private val SHARED_CURSOR by lazy { Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) }
private val SHARED_LAYOUT by lazy {
object : RowGridLayout(0, 4, 2, SwingConstants.CENTER) {
override fun getCellSize(sizes: List<Dimension>) = when {
ExperimentalUI.isNewUI() -> Dimension(JBUI.scale(30), JBUI.scale(34))
else -> Dimension(JBUI.scale(24), JBUI.scale(28))
}
}
}
private object MySpacingConfiguration: IntelliJSpacingConfiguration() {
override val verticalComponentGap: Int
get() = 0
override val verticalSmallGap: Int
get() = JBUI.scale(8)
override val verticalMediumGap: Int
get() = JBUI.scale(if (ExperimentalUI.isNewUI()) 16 else 8)
}
internal class BookmarkTypeChooser(
private var current: BookmarkType?,
assigned: Set<BookmarkType>,
private var description: String?,
private val onChosen: (BookmarkType, String) -> Unit
): JPanel(FlowLayout(FlowLayout.CENTER, 0, 0)) {
private val bookmarkLayoutGrid = BookmarkLayoutGrid(
current,
assigned,
{ if (current == it) save() else current = it },
{ save() }
)
private lateinit var descriptionField: JBTextField
val firstButton = bookmarkLayoutGrid.buttons().first()
init {
add(panel {
customizeSpacingConfiguration(MySpacingConfiguration) {
row {
val lineLength = if (ExperimentalUI.isNewUI()) 63 else 55
comment(message("mnemonic.chooser.comment"), lineLength).apply {
if (ExperimentalUI.isNewUI()) border = JBUI.Borders.empty(2, 4, 0, 4)
}
}.bottomGap(BottomGap.MEDIUM)
row {
cell(bookmarkLayoutGrid)
.horizontalAlign(HorizontalAlign.CENTER)
}.bottomGap(BottomGap.MEDIUM)
row {
descriptionField = textField()
.horizontalAlign(HorizontalAlign.FILL)
.applyToComponent {
text = description ?: ""
emptyText.text = message("mnemonic.chooser.description")
isOpaque = false
addKeyListener(object : KeyListener {
override fun keyTyped(e: KeyEvent?) = Unit
override fun keyReleased(e: KeyEvent?) = Unit
override fun keyPressed(e: KeyEvent?) {
if (e != null && e.modifiersEx == 0 && e.keyCode == KeyEvent.VK_ENTER) {
save()
}
}
})
}
.component
}.bottomGap(BottomGap.SMALL)
row {
cell(createLegend(ASSIGNED_BACKGROUND, message("mnemonic.chooser.legend.assigned.bookmark")))
cell(createLegend(CURRENT_BACKGROUND, message("mnemonic.chooser.legend.current.bookmark")))
}
}
}.apply {
border = when {
ExperimentalUI.isNewUI() -> JBUI.Borders.empty(0, 20, 14, 20)
else -> JBUI.Borders.empty(12, 11)
}
isOpaque = false
isFocusCycleRoot = true
focusTraversalPolicy = object: LayoutFocusTraversalPolicy() {
override fun accept(aComponent: Component?): Boolean {
return super.accept(aComponent) && (aComponent !is JButton || aComponent == firstButton)
}
}
})
border = JBUI.Borders.empty()
background = namedColor("Popup.background")
}
private fun createLegend(color: Color, @Nls text: String) = JLabel(text).apply {
icon = RegionPaintIcon(8) { g, x, y, width, height, _ ->
g.color = color
g.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON)
g.fillOval(x, y, width, height)
}.withIconPreScaled(false)
}
private fun save() {
current?.let {
onChosen(it, descriptionField.text)
}
}
}
private class BookmarkLayoutGrid(
current: BookmarkType?,
private val assigned: Set<BookmarkType>,
private val onChosen: (BookmarkType) -> Unit,
private val save: () -> Unit
) : BorderLayoutPanel(), KeyListener {
companion object {
const val TYPE_KEY: String = "BookmarkLayoutGrid.Type"
}
init {
addToLeft(JPanel(SHARED_LAYOUT).apply {
border = when {
ExperimentalUI.isNewUI() -> JBUI.Borders.emptyRight(14)
else -> JBUI.Borders.empty(5)
}
isOpaque = false
BookmarkType.values()
.filter { it.mnemonic.isDigit() }
.forEach { add(createButton(it)) }
})
addToRight(JPanel(SHARED_LAYOUT).apply {
border = when {
ExperimentalUI.isNewUI() -> JBUI.Borders.empty()
else -> JBUI.Borders.empty(5)
}
isOpaque = false
BookmarkType.values()
.filter { it.mnemonic.isLetter() }
.forEach { add(createButton(it)) }
})
isOpaque = false
updateButtons(current)
}
fun buttons() = UIUtil.uiTraverser(this).traverse().filter(JButton::class.java)
fun createButton(type: BookmarkType) = JButton(type.mnemonic.toString()).apply {
setMnemonic(type.mnemonic)
isOpaque = false
putClientProperty("ActionToolbar.smallVariant", true)
putClientProperty(TYPE_KEY, type)
addPropertyChangeListener { repaint() }
addActionListener {
onChosen(type)
updateButtons(type)
}
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "released")
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "pressed")
cursor = SHARED_CURSOR
addKeyListener(this@BookmarkLayoutGrid)
}
fun updateButtons(current: BookmarkType?) {
buttons().forEach {
val type = it.getClientProperty(TYPE_KEY) as? BookmarkType
when {
type == current -> {
it.putClientProperty("JButton.textColor", CURRENT_FOREGROUND)
it.putClientProperty("JButton.backgroundColor", CURRENT_BACKGROUND)
it.putClientProperty("JButton.borderColor", CURRENT_BACKGROUND)
}
assigned.contains(type) -> {
it.putClientProperty("JButton.textColor", ASSIGNED_FOREGROUND)
it.putClientProperty("JButton.backgroundColor", ASSIGNED_BACKGROUND)
it.putClientProperty("JButton.borderColor", ASSIGNED_BACKGROUND)
}
else -> {
it.putClientProperty("JButton.textColor", UIManager.getColor("Bookmark.MnemonicAvailable.foreground"))
it.putClientProperty("JButton.backgroundColor", UIManager.getColor("Popup.background"))
it.putClientProperty("JButton.borderColor", UIManager.getColor("Bookmark.MnemonicAvailable.borderColor"))
}
}
}
}
private fun offset(delta: Int, size: Int) = when {
delta < 0 -> delta
delta > 0 -> delta + size
else -> size / 2
}
private fun next(source: Component, dx: Int, dy: Int): Component? {
val point = SwingUtilities.convertPoint(source, offset(dx, source.width), offset(dy, source.height), this)
val component = next(source, dx, dy, point)
if (component != null || !Registry.`is`("ide.bookmark.mnemonic.chooser.cyclic.scrolling.allowed")) return component
if (dx > 0) point.x = 0
if (dx < 0) point.x = dx + width
if (dy > 0) point.y = 0
if (dy < 0) point.y = dy + height
return next(source, dx, dy, point)
}
private fun next(source: Component, dx: Int, dy: Int, point: Point): Component? {
while (contains(point)) {
val component = SwingUtilities.getDeepestComponentAt(this, point.x, point.y)
if (component is JButton) return component
point.translate(dx * source.width / 2, dy * source.height / 2)
}
return null
}
override fun keyTyped(event: KeyEvent) = Unit
override fun keyReleased(event: KeyEvent) = Unit
override fun keyPressed(event: KeyEvent) {
if (event.modifiersEx == 0) {
when (event.keyCode) {
KeyEvent.VK_UP, KeyEvent.VK_KP_UP -> next(event.component, 0, -1)?.requestFocus()
KeyEvent.VK_DOWN, KeyEvent.VK_KP_DOWN -> next(event.component, 0, 1)?.requestFocus()
KeyEvent.VK_LEFT, KeyEvent.VK_KP_LEFT -> next(event.component, -1, 0)?.requestFocus()
KeyEvent.VK_RIGHT, KeyEvent.VK_KP_RIGHT -> next(event.component, 1, 0)?.requestFocus()
KeyEvent.VK_ENTER -> {
val button = next(event.component, 0, 0) as? JButton
button?.doClick()
save()
}
else -> {
val type = BookmarkType.get(event.keyCode.toChar())
if (type != BookmarkType.DEFAULT) {
onChosen(type)
save()
}
}
}
}
}
}
| apache-2.0 |
apache/isis | incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/utils/Point.kt | 2 | 911 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.utils
class Point(val x: Int, val y: Int)
| apache-2.0 |
aahlenst/spring-boot | spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/features/testing/utilities/configdataapplicationcontextinitializer/MyConfigFileTests.kt | 10 | 1028 | /*
* Copyright 2012-2022 the original author or authors.
*
* 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 org.springframework.boot.docs.features.testing.utilities.configdataapplicationcontextinitializer
import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer
import org.springframework.test.context.ContextConfiguration
@ContextConfiguration(classes = [Config::class], initializers = [ConfigDataApplicationContextInitializer::class])
class MyConfigFileTests {
// ...
}
| apache-2.0 |
google/intellij-community | platform/testFramework/src/com/intellij/testFramework/utils/inlays/InlayParameterHintsTest.kt | 4 | 8514 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.testFramework.utils.inlays
import com.intellij.codeInsight.daemon.impl.HintRenderer
import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager
import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.VisualPosition
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.util.TextRange
import com.intellij.rt.execution.junit.FileComparisonFailure
import com.intellij.testFramework.VfsTestUtil
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
import junit.framework.ComparisonFailure
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import java.util.regex.Pattern
class InlayHintsChecker(private val myFixture: CodeInsightTestFixture) {
private var isParamHintsEnabledBefore = false
companion object {
val pattern: Pattern = Pattern.compile("(<caret>)|(<selection>)|(</selection>)|<(hint|HINT|Hint|hINT)\\s+text=\"([^\n\r]+?(?=\"\\s*/>))\"\\s*/>")
private val default = ParameterNameHintsSettings()
}
fun setUp() {
val settings = EditorSettingsExternalizable.getInstance()
isParamHintsEnabledBefore = settings.isShowParameterNameHints
settings.isShowParameterNameHints = true
}
fun tearDown() {
EditorSettingsExternalizable.getInstance().isShowParameterNameHints = isParamHintsEnabledBefore
val hintSettings = ParameterNameHintsSettings.getInstance()
hintSettings.loadState(default.state)
}
val manager = ParameterHintsPresentationManager.getInstance()
val inlayPresenter: (Inlay<*>) -> String = { (it.renderer as HintRenderer).text ?: throw IllegalArgumentException("No text set to hint") }
val inlayFilter: (Inlay<*>) -> Boolean = { manager.isParameterHint(it) }
fun checkParameterHints() = checkInlays(inlayPresenter, inlayFilter)
fun checkInlays(inlayPresenter: (Inlay<*>) -> String, inlayFilter: (Inlay<*>) -> Boolean) {
val file = myFixture.file!!
val document = myFixture.getDocument(file)
val originalText = document.text
val expectedInlaysAndCaret = extractInlaysAndCaretInfo(document)
myFixture.doHighlighting()
verifyInlaysAndCaretInfo(expectedInlaysAndCaret, originalText, inlayPresenter, inlayFilter)
}
fun verifyInlaysAndCaretInfo(expectedInlaysAndCaret: CaretAndInlaysInfo,
originalText: String) =
verifyInlaysAndCaretInfo(expectedInlaysAndCaret, originalText, inlayPresenter, inlayFilter)
private fun verifyInlaysAndCaretInfo(expectedInlaysAndCaret: CaretAndInlaysInfo,
originalText: String,
inlayPresenter: (Inlay<*>) -> String,
inlayFilter: (Inlay<*>) -> Boolean) {
val file = myFixture.file!!
val document = myFixture.getDocument(file)
val actual: List<InlayInfo> = getActualInlays(inlayPresenter, inlayFilter)
val expected = expectedInlaysAndCaret.inlays
if (expectedInlaysAndCaret.inlays.size != actual.size || actual.zip(expected).any { it.first != it.second }) {
val entries: MutableList<Pair<Int, String>> = mutableListOf()
actual.forEach { entries.add(Pair(it.offset, buildString {
append("<")
append((if (it.highlighted) "H" else "h"))
append((if (it.current) "INT" else "int"))
append(" text=\"")
append(it.text)
append("\"/>")
}))}
if (expectedInlaysAndCaret.caretOffset != null) {
val actualCaretOffset = myFixture.editor.caretModel.offset
val actualInlaysBeforeCaret = myFixture.editor.caretModel.visualPosition.column -
myFixture.editor.offsetToVisualPosition(actualCaretOffset).column
val first = entries.indexOfFirst { it.first == actualCaretOffset }
val insertIndex = if (first == -1) -entries.binarySearch { it.first - actualCaretOffset } - 1
else first + actualInlaysBeforeCaret
entries.add(insertIndex, Pair(actualCaretOffset, "<caret>"))
}
val proposedText = StringBuilder(document.text)
entries.asReversed().forEach { proposedText.insert(it.first, it.second) }
VfsTestUtil.TEST_DATA_FILE_PATH.get(file.virtualFile)?.let { originalPath ->
throw FileComparisonFailure("Hints differ", originalText, proposedText.toString(), originalPath)
} ?: throw ComparisonFailure("Hints differ", originalText, proposedText.toString())
}
if (expectedInlaysAndCaret.caretOffset != null) {
assertEquals("Unexpected caret offset", expectedInlaysAndCaret.caretOffset, myFixture.editor.caretModel.offset)
val position = myFixture.editor.offsetToVisualPosition(expectedInlaysAndCaret.caretOffset)
assertEquals("Unexpected caret visual position",
VisualPosition(position.line, position.column + expectedInlaysAndCaret.inlaysBeforeCaret),
myFixture.editor.caretModel.visualPosition)
val selectionModel = myFixture.editor.selectionModel
if (expectedInlaysAndCaret.selection == null) assertFalse(selectionModel.hasSelection())
else assertEquals("Unexpected selection",
expectedInlaysAndCaret.selection,
TextRange(selectionModel.selectionStart, selectionModel.selectionEnd))
}
}
private fun getActualInlays(inlayPresenter: (Inlay<*>) -> String,
inlayFilter: (Inlay<*>) -> Boolean): List<InlayInfo> {
val editor = myFixture.editor
val allInlays = editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength) +
editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength)
val hintManager = ParameterHintsPresentationManager.getInstance()
return allInlays
.filterNotNull()
.filter { inlayFilter(it) }
.map {
val isHighlighted: Boolean
val isCurrent: Boolean
if (hintManager.isParameterHint(it)) {
isHighlighted = hintManager.isHighlighted(it)
isCurrent = hintManager.isCurrent(it)
} else {
isHighlighted = false
isCurrent = false
}
InlayInfo(it.offset, inlayPresenter(it), isHighlighted, isCurrent)
}
.sortedBy { it.offset }
}
fun extractInlaysAndCaretInfo(document: Document): CaretAndInlaysInfo {
val text = document.text
val matcher = pattern.matcher(text)
val inlays = mutableListOf<InlayInfo>()
var extractedLength = 0
var caretOffset : Int? = null
var inlaysBeforeCaret = 0
var selectionStart : Int? = null
var selectionEnd : Int? = null
while (matcher.find()) {
val start = matcher.start()
val matchedLength = matcher.end() - start
val realStartOffset = start - extractedLength
when {
matcher.group(1) != null -> {
caretOffset = realStartOffset
inlays.asReversed()
.takeWhile { it.offset == caretOffset }
.forEach { inlaysBeforeCaret++ }
}
matcher.group(2) != null -> selectionStart = realStartOffset
matcher.group(3) != null -> selectionEnd = realStartOffset
else -> inlays += InlayInfo(realStartOffset, matcher.group(5), matcher.group(4).startsWith("H"), matcher.group(4).endsWith("INT"))
}
removeText(document, realStartOffset, matchedLength)
extractedLength += (matcher.end() - start)
}
return CaretAndInlaysInfo(caretOffset, inlaysBeforeCaret,
if (selectionStart == null || selectionEnd == null) null else TextRange(selectionStart, selectionEnd),
inlays)
}
private fun removeText(document: Document, realStartOffset: Int, matchedLength: Int) {
WriteCommandAction.runWriteCommandAction(myFixture.project, {
document.replaceString(realStartOffset, realStartOffset + matchedLength, "")
})
}
}
class CaretAndInlaysInfo (val caretOffset: Int?, val inlaysBeforeCaret: Int, val selection: TextRange?,
val inlays: List<InlayInfo>)
data class InlayInfo (val offset: Int, val text: String, val highlighted: Boolean, val current: Boolean) | apache-2.0 |
RuneSuite/client | updater-deob/src/main/java/org/runestar/client/updater/deob/rs/OpaquePredicateCheckRemover.kt | 1 | 4790 | package org.runestar.client.updater.deob.rs
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.kxtra.slf4j.getLogger
import org.kxtra.slf4j.info
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type
import org.objectweb.asm.tree.AbstractInsnNode
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.JumpInsnNode
import org.objectweb.asm.tree.LabelNode
import org.objectweb.asm.tree.MethodInsnNode
import org.objectweb.asm.tree.MethodNode
import org.objectweb.asm.tree.VarInsnNode
import org.runestar.client.updater.deob.Transformer
import org.runestar.client.updater.deob.util.intValue
import org.runestar.client.updater.deob.util.isIntValue
import java.lang.reflect.Modifier
import java.nio.file.Path
import java.util.TreeMap
object OpaquePredicateCheckRemover : Transformer.Tree() {
private val ISE_INTERNAL_NAME = Type.getInternalName(IllegalStateException::class.java)
private val mapper = jacksonObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
private val logger = getLogger()
override fun transform(dir: Path, klasses: List<ClassNode>) {
val passingArgs = TreeMap<String, Int>()
var returns = 0
var exceptions = 0
klasses.forEach { c ->
c.methods.forEach { m ->
val instructions = m.instructions.iterator()
val lastParamIndex = m.lastParamIndex
while (instructions.hasNext()) {
val insn = instructions.next()
val toDelete = if (insn.matchesReturn(lastParamIndex)) {
returns++
4
} else if (insn.matchesException(lastParamIndex)) {
exceptions++
7
} else {
continue
}
val constantPushed = insn.next.intValue
val ifOpcode = insn.next.next.opcode
val label = (insn.next.next as JumpInsnNode).label.label
instructions.remove()
repeat(toDelete - 1) {
instructions.next()
instructions.remove()
}
instructions.add(JumpInsnNode(GOTO, LabelNode(label)))
passingArgs["${c.name}.${m.name}${m.desc}"] = passingVal(constantPushed, ifOpcode)
}
}
}
logger.info { "Opaque predicates checks removed: returns: $returns, exceptions: $exceptions" }
mapper.writeValue(dir.resolve("op.json").toFile(), passingArgs)
}
private fun AbstractInsnNode.matchesReturn(lastParamIndex: Int): Boolean {
val i0 = this
if (i0.opcode != ILOAD) return false
i0 as VarInsnNode
if (i0.`var` != lastParamIndex) return false
val i1 = i0.next
if (!i1.isIntValue) return false
val i2 = i1.next
if (!i2.isIf) return false
val i3 = i2.next
if (!i3.isReturn) return false
return true
}
private fun AbstractInsnNode.matchesException(lastParamIndex: Int): Boolean {
val i0 = this
if (i0.opcode != ILOAD) return false
i0 as VarInsnNode
if (i0.`var` != lastParamIndex) return false
val i1 = i0.next
if (!i1.isIntValue) return false
val i2 = i1.next
if (!i2.isIf) return false
val i3 = i2.next
if (i3.opcode != NEW) return false
val i4 = i3.next
if (i4.opcode != DUP) return false
val i5 = i4.next
if (i5.opcode != INVOKESPECIAL) return false
i5 as MethodInsnNode
if (i5.owner != ISE_INTERNAL_NAME) return false
val i6 = i5.next
if (i6.opcode != ATHROW) return false
return true
}
private val MethodNode.lastParamIndex: Int get() {
val offset = if (Modifier.isStatic(access)) 1 else 0
return (Type.getArgumentsAndReturnSizes(desc) shr 2) - offset - 1
}
private fun passingVal(pushed: Int, ifOpcode: Int): Int {
return when(ifOpcode) {
IF_ICMPEQ -> pushed
IF_ICMPGE,
IF_ICMPGT -> pushed + 1
IF_ICMPLE,
IF_ICMPLT,
IF_ICMPNE -> pushed - 1
else -> error(ifOpcode)
}
}
private val AbstractInsnNode.isIf: Boolean get() {
return this is JumpInsnNode && opcode != Opcodes.GOTO
}
private val AbstractInsnNode.isReturn: Boolean get() {
return when (opcode) {
RETURN, ARETURN, DRETURN, FRETURN, IRETURN, LRETURN -> true
else -> false
}
}
} | mit |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/OptInFixesFactory.kt | 3 | 14095 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.module.Module
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.resolveClassByFqName
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors.*
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.toDescriptor
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypesAndPredicate
import org.jetbrains.kotlin.resolve.AnnotationChecker
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.checkers.OptInNames
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
object OptInFixesFactory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val element = diagnostic.psiElement
val containingDeclaration: KtDeclaration = element.getParentOfTypesAndPredicate(
true,
KtDeclarationWithBody::class.java,
KtClassOrObject::class.java,
KtProperty::class.java,
KtTypeAlias::class.java
) {
!KtPsiUtil.isLocal(it)
} ?: return emptyList()
val annotationFqName = when (diagnostic.factory) {
OPT_IN_USAGE -> OPT_IN_USAGE.cast(diagnostic).a
OPT_IN_USAGE_ERROR -> OPT_IN_USAGE_ERROR.cast(diagnostic).a
OPT_IN_OVERRIDE -> OPT_IN_OVERRIDE.cast(diagnostic).a
OPT_IN_OVERRIDE_ERROR -> OPT_IN_OVERRIDE_ERROR.cast(diagnostic).a
else -> null
} ?: return emptyList()
val moduleDescriptor = containingDeclaration.resolveToDescriptorIfAny()?.module ?: return emptyList()
val annotationClassDescriptor = moduleDescriptor.resolveClassByFqName(
annotationFqName, NoLookupLocation.FROM_IDE
) ?: return emptyList()
val applicableTargets = AnnotationChecker.applicableTargetSet(annotationClassDescriptor)
val context = when (element) {
is KtElement -> element.analyze()
else -> containingDeclaration.analyze()
}
fun isApplicableTo(declaration: KtDeclaration): Boolean {
val actualTargetList = AnnotationChecker.getDeclarationSiteActualTargetList(
declaration, declaration.toDescriptor() as? ClassDescriptor, context
)
return actualTargetList.any { it in applicableTargets }
}
val isOverrideError = diagnostic.factory == OPT_IN_OVERRIDE_ERROR || diagnostic.factory == OPT_IN_OVERRIDE
val optInFqName = OptInNames.OPT_IN_FQ_NAME.takeIf { moduleDescriptor.annotationExists(it) }
?: OptInNames.OLD_USE_EXPERIMENTAL_FQ_NAME
val result = mutableListOf<IntentionAction>()
// just to avoid local variable name shadowing
run {
val kind = if (containingDeclaration is KtConstructor<*>)
AddAnnotationFix.Kind.Constructor
else
AddAnnotationFix.Kind.Declaration(containingDeclaration.name)
if (isApplicableTo(containingDeclaration)) {
// When we are fixing a missing annotation on an overridden function, we should
// propose to add a propagating annotation first, and in all other cases
// the non-propagating opt-in annotation should be default.
// The same logic applies to the similar conditional expressions onward.
result.add(
if (isOverrideError)
HighPriorityPropagateOptInAnnotationFix(containingDeclaration, annotationFqName, kind)
else
PropagateOptInAnnotationFix(containingDeclaration, annotationFqName, kind)
)
}
val existingAnnotationEntry = containingDeclaration.findAnnotation(optInFqName)?.createSmartPointer()
result.add(
if (isOverrideError)
UseOptInAnnotationFix(containingDeclaration, optInFqName, kind, annotationFqName, existingAnnotationEntry)
else
HighPriorityUseOptInAnnotationFix(containingDeclaration, optInFqName, kind, annotationFqName, existingAnnotationEntry)
)
}
if (containingDeclaration is KtCallableDeclaration) {
val containingClassOrObject = containingDeclaration.containingClassOrObject
if (containingClassOrObject != null) {
val kind = AddAnnotationFix.Kind.ContainingClass(containingClassOrObject.name)
val isApplicableToContainingClassOrObject = isApplicableTo(containingClassOrObject)
if (isApplicableToContainingClassOrObject) {
result.add(
if (isOverrideError)
HighPriorityPropagateOptInAnnotationFix(containingClassOrObject, annotationFqName, kind)
else
PropagateOptInAnnotationFix(containingClassOrObject, annotationFqName, kind)
)
}
val existingAnnotationEntry = containingClassOrObject.findAnnotation(optInFqName)?.createSmartPointer()
result.add(
if (isOverrideError)
UseOptInAnnotationFix(containingClassOrObject, optInFqName, kind, annotationFqName, existingAnnotationEntry)
else
HighPriorityUseOptInAnnotationFix(
containingClassOrObject, optInFqName, kind, annotationFqName, existingAnnotationEntry
)
)
}
}
val containingFile = containingDeclaration.containingKtFile
val module = containingFile.module
if (module != null) {
result.add(LowPriorityMakeModuleOptInFix(containingFile, module, annotationFqName))
}
// Add the file-level annotation `@file:OptIn(...)`
result.add(
UseOptInFileAnnotationFix(
containingFile, optInFqName, annotationFqName,
findFileAnnotation(containingFile, optInFqName)?.createSmartPointer()
)
)
return result
}
// Find the existing file-level annotation of the specified class if it exists
private fun findFileAnnotation(file: KtFile, annotationFqName: FqName): KtAnnotationEntry? {
val context = file.analyze(BodyResolveMode.PARTIAL)
return file.fileAnnotationList?.annotationEntries?.firstOrNull { entry ->
context.get(BindingContext.ANNOTATION, entry)?.fqName == annotationFqName
}
}
fun ModuleDescriptor.annotationExists(fqName: FqName): Boolean =
resolveClassByFqName(fqName, NoLookupLocation.FROM_IDE) != null
/**
* A specialized subclass of [AddAnnotationFix] that adds @OptIn(...) annotations to declarations,
* containing classes, or constructors.
*
* This class reuses the parent's [invoke] method but overrides the [getText] method to provide
* more descriptive opt-in-specific messages.
*
* @param element a declaration to annotate
* @param optInFqName name of OptIn annotation
* @param kind the annotation kind (desired scope)
* @param argumentClassFqName the fully qualified name of the annotation to opt-in
* @param existingAnnotationEntry the already existing annotation entry (if any)
*
*/
private open class UseOptInAnnotationFix(
element: KtDeclaration,
optInFqName: FqName,
private val kind: Kind,
private val argumentClassFqName: FqName,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : AddAnnotationFix(element, optInFqName, kind, argumentClassFqName, existingAnnotationEntry) {
private val elementName = element.name ?: "?"
override fun getText(): String {
val argumentText = argumentClassFqName.shortName().asString()
return when (kind) {
Kind.Self -> KotlinBundle.message("fix.opt_in.text.use.declaration", argumentText, elementName)
Kind.Constructor -> KotlinBundle.message("fix.opt_in.text.use.constructor", argumentText)
is Kind.Declaration -> KotlinBundle.message("fix.opt_in.text.use.declaration", argumentText, kind.name ?: "?")
is Kind.ContainingClass -> KotlinBundle.message("fix.opt_in.text.use.containing.class", argumentText, kind.name ?: "?")
}
}
override fun getFamilyName(): String = KotlinBundle.message("fix.opt_in.annotation.family")
}
private class HighPriorityUseOptInAnnotationFix(
element: KtDeclaration,
optInFqName: FqName,
kind: Kind,
argumentClassFqName: FqName,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : UseOptInAnnotationFix(element, optInFqName, kind, argumentClassFqName, existingAnnotationEntry),
HighPriorityAction
/**
* A specialized version of [AddFileAnnotationFix] that adds @OptIn(...) annotations to the containing file.
*
* This class reuses the parent's [invoke] method, but overrides the [getText] method to provide
* more descriptive opt-in related messages.
*
* @param file the file there the annotation should be added
* @param optInFqName name of OptIn annotation
* @param argumentClassFqName the fully qualified name of the annotation to opt-in
* @param existingAnnotationEntry the already existing annotation entry (if any)
*/
private open class UseOptInFileAnnotationFix(
file: KtFile,
optInFqName: FqName,
private val argumentClassFqName: FqName,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>?
) : AddFileAnnotationFix(file, optInFqName, argumentClassFqName, existingAnnotationEntry) {
private val fileName = file.name
override fun getText(): String {
val argumentText = argumentClassFqName.shortName().asString()
return KotlinBundle.message("fix.opt_in.text.use.containing.file", argumentText, fileName)
}
override fun getFamilyName(): String = KotlinBundle.message("fix.opt_in.annotation.family")
}
/**
* A specialized subclass of [AddAnnotationFix] that adds propagating opted-in annotations
* to declarations, containing classes, or constructors.
*
* This class reuses the parent's [invoke] method but overrides the [getText] method to provide
* more descriptive opt-in-specific messages.
*
* @param element a declaration to annotate
* @param annotationFqName the fully qualified name of the annotation
* @param kind the annotation kind (desired scope)
* @param existingAnnotationEntry the already existing annotation entry (if any)
*
*/
private open class PropagateOptInAnnotationFix(
element: KtDeclaration,
private val annotationFqName: FqName,
private val kind: Kind,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : AddAnnotationFix(element, annotationFqName, Kind.Self, null, existingAnnotationEntry) {
override fun getText(): String {
val argumentText = annotationFqName.shortName().asString()
return when (kind) {
Kind.Self -> KotlinBundle.message("fix.opt_in.text.propagate.declaration", argumentText, "?")
Kind.Constructor -> KotlinBundle.message("fix.opt_in.text.propagate.constructor", argumentText)
is Kind.Declaration -> KotlinBundle.message("fix.opt_in.text.propagate.declaration", argumentText, kind.name ?: "?")
is Kind.ContainingClass -> KotlinBundle.message(
"fix.opt_in.text.propagate.containing.class",
argumentText,
kind.name ?: "?"
)
}
}
override fun getFamilyName(): String = KotlinBundle.message("fix.opt_in.annotation.family")
}
/**
* A high-priority version of [PropagateOptInAnnotationFix] (for overridden constructor case)
*
* @param element a declaration to annotate
* @param annotationFqName the fully qualified name of the annotation
* @param kind the annotation kind (desired scope)
* @param existingAnnotationEntry the already existing annotation entry (if any)
*/
private class HighPriorityPropagateOptInAnnotationFix(
element: KtDeclaration,
annotationFqName: FqName,
kind: Kind,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : PropagateOptInAnnotationFix(element, annotationFqName, kind, existingAnnotationEntry),
HighPriorityAction
private class LowPriorityMakeModuleOptInFix(
file: KtFile,
module: Module,
annotationFqName: FqName
) : MakeModuleOptInFix(file, module, annotationFqName), LowPriorityAction
}
| apache-2.0 |
google/intellij-community | plugins/devkit/devkit-core/src/inspections/NonDefaultConstructorInspection.kt | 5 | 12680 | // 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.inspections
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.lang.jvm.JvmClassKind
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiParameterList
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.psi.xml.XmlTag
import com.intellij.util.SmartList
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.dom.Extension
import org.jetbrains.idea.devkit.dom.ExtensionPoint
import org.jetbrains.idea.devkit.dom.ExtensionPoint.Area
import org.jetbrains.idea.devkit.util.locateExtensionsByPsiClass
import org.jetbrains.idea.devkit.util.processExtensionDeclarations
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UMethod
import org.jetbrains.uast.UastFacade
import org.jetbrains.uast.convertOpt
import java.util.*
private const val serviceBeanFqn = "com.intellij.openapi.components.ServiceDescriptor"
class NonDefaultConstructorInspection : DevKitUastInspectionBase(UClass::class.java) {
override fun checkClass(aClass: UClass, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
val javaPsi = aClass.javaPsi
// Groovy from test data - ignore it
if (javaPsi.language.id == "Groovy" || javaPsi.classKind != JvmClassKind.CLASS ||
PsiUtil.isInnerClass(javaPsi) || PsiUtil.isLocalOrAnonymousClass(javaPsi) || PsiUtil.isAbstractClass(javaPsi) ||
javaPsi.hasModifierProperty(PsiModifier.PRIVATE) /* ignore private classes */) {
return null
}
val constructors = javaPsi.constructors
// very fast path - do nothing if no constructors
if (constructors.isEmpty()) {
return null
}
val area: Area?
val isService: Boolean
var serviceClientKind: ServiceDescriptor.ClientKind? = null
// hack, allow Project-level @Service
var isServiceAnnotation = false
var extensionPoint: ExtensionPoint? = null
if (javaPsi.hasAnnotation("com.intellij.openapi.components.Service")) {
area = null
isService = true
isServiceAnnotation = true
}
else {
// fast path - check by qualified name
if (!isExtensionBean(aClass)) {
// slow path - check using index
extensionPoint = findExtensionPoint(aClass, manager.project) ?: return null
}
else if (javaPsi.name == "VcsConfigurableEP") {
// VcsConfigurableEP extends ConfigurableEP but used directly, for now just ignore it as hardcoded exclusion
return null
}
area = getArea(extensionPoint)
isService = extensionPoint?.beanClass?.stringValue == serviceBeanFqn
if (isService) {
for (candidate in locateExtensionsByPsiClass(javaPsi)) {
val extensionTag = candidate.pointer.element ?: continue
val clientName = extensionTag.getAttribute("client")?.value ?: continue
val kind = when (clientName.lowercase(Locale.US)) {
"all" -> ServiceDescriptor.ClientKind.ALL
"guest" -> ServiceDescriptor.ClientKind.GUEST
"local" -> ServiceDescriptor.ClientKind.LOCAL
else -> null
}
if (serviceClientKind == null) {
serviceClientKind = kind
}
else if (serviceClientKind != kind) {
serviceClientKind = ServiceDescriptor.ClientKind.ALL
}
}
}
}
val isAppLevelExtensionPoint = area == null || area == Area.IDEA_APPLICATION
var errors: MutableList<ProblemDescriptor>? = null
loop@ for (method in constructors) {
if (isAllowedParameters(method.parameterList, extensionPoint, isAppLevelExtensionPoint, serviceClientKind, isServiceAnnotation)) {
// allow to have empty constructor and extra (e.g. DartQuickAssistIntention)
return null
}
if (errors == null) {
errors = SmartList()
}
// kotlin is not physical, but here only physical is expected, so, convert to uast element and use sourcePsi
val anchorElement = when {
method.isPhysical -> method.identifyingElement!!
else -> aClass.sourcePsi?.let { UastFacade.findPlugin(it)?.convertOpt<UMethod>(method, aClass)?.sourcePsi } ?: continue@loop
}
@NlsSafe val kind = if (isService) DevKitBundle.message("inspections.non.default.warning.type.service") else DevKitBundle.message("inspections.non.default.warning.type.extension")
@Nls val suffix =
if (area == null) DevKitBundle.message("inspections.non.default.warning.suffix.project.or.module")
else {
when {
isAppLevelExtensionPoint -> ""
area == Area.IDEA_PROJECT -> DevKitBundle.message("inspections.non.default.warning.suffix.project")
else -> DevKitBundle.message("inspections.non.default.warning.suffix.module")
}
}
errors.add(manager.createProblemDescriptor(anchorElement,
DevKitBundle.message("inspections.non.default.warning.and.suffix.message", kind, suffix),
true,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly))
}
return errors?.toTypedArray()
}
private fun getArea(extensionPoint: ExtensionPoint?): Area {
val areaName = (extensionPoint ?: return Area.IDEA_APPLICATION).area.stringValue
when (areaName) {
"IDEA_PROJECT" -> return Area.IDEA_PROJECT
"IDEA_MODULE" -> return Area.IDEA_MODULE
else -> {
when (extensionPoint.name.value) {
"projectService" -> return Area.IDEA_PROJECT
"moduleService" -> return Area.IDEA_MODULE
}
}
}
return Area.IDEA_APPLICATION
}
}
private fun findExtensionPoint(clazz: UClass, project: Project): ExtensionPoint? {
val parentClass = clazz.uastParent as? UClass
if (parentClass == null) {
val qualifiedName = clazz.qualifiedName ?: return null
return findExtensionPointByImplementationClass(qualifiedName, qualifiedName, project)
}
else {
val parentQualifiedName = parentClass.qualifiedName ?: return null
// parent$inner string cannot be found, so, search by parent FQN
return findExtensionPointByImplementationClass(parentQualifiedName, "$parentQualifiedName$${clazz.javaPsi.name}", project)
}
}
private fun findExtensionPointByImplementationClass(searchString: String, qualifiedName: String, project: Project): ExtensionPoint? {
var result: ExtensionPoint? = null
val strictMatch = searchString === qualifiedName
processExtensionDeclarations(searchString, project, strictMatch = strictMatch) { extension, tag ->
val point = extension.extensionPoint ?: return@processExtensionDeclarations true
if (point.name.value == "psi.symbolReferenceProvider") {
return@processExtensionDeclarations true
}
when (point.beanClass.stringValue) {
null -> {
if (tag.attributes.any { it.name == Extension.IMPLEMENTATION_ATTRIBUTE && it.value == qualifiedName }) {
result = point
return@processExtensionDeclarations false
}
}
serviceBeanFqn -> {
if (tag.attributes.any { it.name == "serviceImplementation" && it.value == qualifiedName }) {
result = point
return@processExtensionDeclarations false
}
}
else -> {
// bean EP
if (tag.name == "className" || tag.subTags.any {
it.name == "className" && (strictMatch || it.textMatches(qualifiedName))
} || checkAttributes(tag, qualifiedName)) {
result = point
return@processExtensionDeclarations false
}
}
}
true
}
return result
}
// todo can we use attribute `with`?
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
@NonNls
private val ignoredTagNames = java.util.Set.of("semContributor", "modelFacade", "scriptGenerator",
"editorActionHandler", "editorTypedHandler",
"dataImporter", "java.error.fix", "explainPlanProvider", "typeIcon")
// problem - tag
//<lang.elementManipulator forClass="com.intellij.psi.css.impl.CssTokenImpl"
// implementationClass="com.intellij.psi.css.impl.CssTokenImpl$Manipulator"/>
// will be found for `com.intellij.psi.css.impl.CssTokenImpl`, but we need to ignore `forClass` and check that we have exact match for implementation attribute
private fun checkAttributes(tag: XmlTag, qualifiedName: String): Boolean {
if (ignoredTagNames.contains(tag.name)) {
// DbmsExtension passes Dbms instance directly, doesn't need to check
return false
}
return tag.attributes.any {
val name = it.name
(name.startsWith(Extension.IMPLEMENTATION_ATTRIBUTE) || name == "instance") && it.value == qualifiedName
}
}
@NonNls
private val allowedClientSessionsQualifiedNames = setOf(
"com.intellij.openapi.client.ClientSession",
"com.jetbrains.rdserver.core.GuestSession",
)
@NonNls
private val allowedClientAppSessionsQualifiedNames = setOf(
"com.intellij.openapi.client.ClientAppSession",
"com.jetbrains.rdserver.core.GuestAppSession",
) + allowedClientSessionsQualifiedNames
@NonNls
private val allowedClientProjectSessionsQualifiedNames = setOf(
"com.intellij.openapi.client.ClientProjectSession",
"com.jetbrains.rdserver.core.GuestProjectSession",
) + allowedClientSessionsQualifiedNames
@NonNls
private val allowedServiceQualifiedNames = setOf(
"com.intellij.openapi.project.Project",
"com.intellij.openapi.module.Module",
"com.intellij.util.messages.MessageBus",
"com.intellij.openapi.options.SchemeManagerFactory",
"com.intellij.openapi.editor.actionSystem.TypedActionHandler",
"com.intellij.database.Dbms"
) + allowedClientAppSessionsQualifiedNames + allowedClientProjectSessionsQualifiedNames
private val allowedServiceNames = allowedServiceQualifiedNames.mapTo(HashSet(allowedServiceQualifiedNames.size)) { it.substringAfterLast('.') }
private fun isAllowedParameters(list: PsiParameterList,
extensionPoint: ExtensionPoint?,
isAppLevelExtensionPoint: Boolean,
clientKind: ServiceDescriptor.ClientKind?,
isServiceAnnotation: Boolean): Boolean {
if (list.isEmpty) {
return true
}
// hardcoded for now, later will be generalized
if (!isServiceAnnotation && extensionPoint?.effectiveQualifiedName == "com.intellij.semContributor") {
// disallow any parameters
return false
}
for (parameter in list.parameters) {
if (parameter.isVarArgs) {
return false
}
val type = parameter.type as? PsiClassType ?: return false
// before resolve, check unqualified name
val name = type.className
if (!allowedServiceNames.contains(name)) {
return false
}
val qualifiedName = (type.resolve() ?: return false).qualifiedName
if (!allowedServiceQualifiedNames.contains(qualifiedName)) {
return false
}
if (clientKind != ServiceDescriptor.ClientKind.GUEST &&
qualifiedName?.startsWith("com.jetbrains.rdserver.core") == true) {
return false
}
if (clientKind == null && allowedClientProjectSessionsQualifiedNames.contains(qualifiedName)) {
return false
}
if (isAppLevelExtensionPoint && !isServiceAnnotation && name == "Project") {
return false
}
}
return true
}
private val interfacesToCheck = HashSet(listOf(
"com.intellij.codeInsight.daemon.LineMarkerProvider",
"com.intellij.openapi.fileTypes.SyntaxHighlighterFactory"
))
private val classesToCheck = HashSet(listOf(
"com.intellij.codeInsight.completion.CompletionContributor",
"com.intellij.codeInsight.completion.CompletionConfidence",
"com.intellij.psi.PsiReferenceContributor"
))
private fun isExtensionBean(aClass: UClass): Boolean {
var found = false
InheritanceUtil.processSupers(aClass.javaPsi, true) {
val qualifiedName = it.qualifiedName
found = (if (it.isInterface) interfacesToCheck else classesToCheck).contains(qualifiedName)
!found
}
return found
} | apache-2.0 |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/ClanChat.kt | 1 | 3695 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.common.startsWith
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type.BYTE_TYPE
import org.objectweb.asm.Type.INT_TYPE
import org.objectweb.asm.Type.VOID_TYPE
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.Method2
import java.lang.reflect.Modifier
@DependsOn(UserList::class, ClanMate::class)
class ClanChat : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<UserList>() }
.and { it.instanceMethods.flatMap { it.instructions.toList() }.any { it.opcode == NEW && it.typeType == type<ClanMate>() } }
@DependsOn(UserList.newInstance::class)
class newInstance : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<UserList.newInstance>().mark }
}
@DependsOn(UserList.newTypedArray::class)
class newTypedArray : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<UserList.newTypedArray>().mark }
}
@DependsOn(LoginType::class)
class loginType : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<LoginType>() }
}
class minKick : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == BYTE_TYPE }
}
class name : OrderMapper.InConstructor.Field(ClanChat::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == String::class.type }
}
class owner : OrderMapper.InConstructor.Field(ClanChat::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == String::class.type }
}
@MethodParameters("packet")
@DependsOn(Packet::class)
class readUpdate : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.arguments.startsWith(type<Packet>()) }
.and { it.instructions.any { it.opcode == IINC } }
}
@DependsOn(Usernamed::class)
class localUser : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<Usernamed>() }
}
class rank : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == INT_TYPE && Modifier.isPublic(it.access) }
}
@MethodParameters()
@DependsOn(ClanMate.clearIsFriend::class)
class clearFriends : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE && it.arguments.isEmpty() }
.and { it.instructions.any { it.isMethod && it.methodId == method<ClanMate.clearIsFriend>().id } }
}
@MethodParameters()
@DependsOn(ClanMate.clearIsIgnored::class)
class clearIgnoreds : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE && it.arguments.isEmpty() }
.and { it.instructions.any { it.isMethod && it.methodId == method<ClanMate.clearIsIgnored>().id } }
}
} | mit |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/pullUpConflictsUtils.kt | 2 | 13612 | // 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.pullUp
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.RefactoringBundle
import com.intellij.util.containers.MultiMap
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.getChildrenToAnalyze
import org.jetbrains.kotlin.idea.refactoring.memberInfo.resolveToDescriptorWrapperAware
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.languageVersionSettings
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.base.util.useScope
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.util.findCallableMemberBySignature
fun checkConflicts(
project: Project,
sourceClass: KtClassOrObject,
targetClass: PsiNamedElement,
memberInfos: List<KotlinMemberInfo>,
onShowConflicts: () -> Unit = {},
onAccept: () -> Unit
) {
val conflicts = MultiMap<PsiElement, String>()
val conflictsCollected = runProcessWithProgressSynchronously(RefactoringBundle.message("detecting.possible.conflicts"), project) {
runReadAction { collectConflicts(sourceClass, targetClass, memberInfos, conflicts) }
}
if (conflictsCollected) {
project.checkConflictsInteractively(conflicts, onShowConflicts, onAccept)
} else {
onShowConflicts()
}
}
private fun runProcessWithProgressSynchronously(
progressTitle: @NlsContexts.ProgressTitle String,
project: Project?,
process: Runnable,
): Boolean = ProgressManager.getInstance().runProcessWithProgressSynchronously(process, progressTitle, true, project)
private fun collectConflicts(
sourceClass: KtClassOrObject,
targetClass: PsiNamedElement,
memberInfos: List<KotlinMemberInfo>,
conflicts: MultiMap<PsiElement, String>
) {
val pullUpData = KotlinPullUpData(sourceClass,
targetClass,
memberInfos.mapNotNull { it.member })
with(pullUpData) {
for (memberInfo in memberInfos) {
val member = memberInfo.member
val memberDescriptor = member.resolveToDescriptorWrapperAware(resolutionFacade)
checkClashWithSuperDeclaration(member, memberDescriptor, conflicts)
checkAccidentalOverrides(member, memberDescriptor, conflicts)
checkInnerClassToInterface(member, memberDescriptor, conflicts)
checkVisibility(memberInfo, memberDescriptor, conflicts, resolutionFacade.languageVersionSettings)
}
}
checkVisibilityInAbstractedMembers(memberInfos, pullUpData.resolutionFacade, conflicts)
}
internal fun checkVisibilityInAbstractedMembers(
memberInfos: List<KotlinMemberInfo>,
resolutionFacade: ResolutionFacade,
conflicts: MultiMap<PsiElement, String>
) {
val membersToMove = ArrayList<KtNamedDeclaration>()
val membersToAbstract = ArrayList<KtNamedDeclaration>()
for (memberInfo in memberInfos) {
val member = memberInfo.member ?: continue
(if (memberInfo.isToAbstract) membersToAbstract else membersToMove).add(member)
}
for (member in membersToAbstract) {
val memberDescriptor = member.resolveToDescriptorWrapperAware(resolutionFacade)
member.forEachDescendantOfType<KtSimpleNameExpression> {
val target = it.mainReference.resolve() as? KtNamedDeclaration ?: return@forEachDescendantOfType
if (!willBeMoved(target, membersToMove)) return@forEachDescendantOfType
if (target.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
val targetDescriptor = target.resolveToDescriptorWrapperAware(resolutionFacade)
val memberText = memberDescriptor.renderForConflicts()
val targetText = targetDescriptor.renderForConflicts()
val message = KotlinBundle.message("text.0.uses.1.which.will.not.be.accessible.from.subclass", memberText, targetText)
conflicts.putValue(target, message.capitalize())
}
}
}
}
internal fun willBeMoved(element: PsiElement, membersToMove: Collection<KtNamedDeclaration>) =
element.parentsWithSelf.any { it in membersToMove }
internal fun willBeUsedInSourceClass(
member: PsiElement,
sourceClass: KtClassOrObject,
membersToMove: Collection<KtNamedDeclaration>
): Boolean {
return !ReferencesSearch
.search(member, LocalSearchScope(sourceClass), false)
.all { willBeMoved(it.element, membersToMove) }
}
private val CALLABLE_RENDERER = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions {
parameterNameRenderingPolicy = ParameterNameRenderingPolicy.NONE
modifiers = emptySet()
startFromName = false
}
@Nls
fun DeclarationDescriptor.renderForConflicts(): String {
return when (this) {
is ClassDescriptor -> {
@NlsSafe val text = "${DescriptorRenderer.getClassifierKindPrefix(this)} " +
IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(this)
text
}
is FunctionDescriptor -> {
KotlinBundle.message("text.function.in.ticks.0", CALLABLE_RENDERER.render(this))
}
is PropertyDescriptor -> {
KotlinBundle.message("text.property.in.ticks.0", CALLABLE_RENDERER.render(this))
}
is PackageFragmentDescriptor -> {
@NlsSafe val text = fqName.asString()
text
}
is PackageViewDescriptor -> {
@NlsSafe val text = fqName.asString()
text
}
else -> {
""
}
}
}
internal fun KotlinPullUpData.getClashingMemberInTargetClass(memberDescriptor: CallableMemberDescriptor): CallableMemberDescriptor? {
val memberInSuper = memberDescriptor.substitute(sourceToTargetClassSubstitutor) ?: return null
return targetClassDescriptor.findCallableMemberBySignature(memberInSuper as CallableMemberDescriptor)
}
private fun KotlinPullUpData.checkClashWithSuperDeclaration(
member: KtNamedDeclaration,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>
) {
val message = KotlinBundle.message(
"text.class.0.already.contains.member.1",
targetClassDescriptor.renderForConflicts(),
memberDescriptor.renderForConflicts()
)
if (member is KtParameter) {
if (((targetClass as? KtClass)?.primaryConstructorParameters ?: emptyList()).any { it.name == member.name }) {
conflicts.putValue(member, message.capitalize())
}
return
}
if (memberDescriptor !is CallableMemberDescriptor) return
val clashingSuper = getClashingMemberInTargetClass(memberDescriptor) ?: return
if (clashingSuper.modality == Modality.ABSTRACT) return
if (clashingSuper.kind != CallableMemberDescriptor.Kind.DECLARATION) return
conflicts.putValue(member, message.capitalize())
}
private fun PsiClass.isSourceOrTarget(data: KotlinPullUpData): Boolean {
var element = unwrapped
if (element is KtObjectDeclaration && element.isCompanion()) element = element.containingClassOrObject
return element == data.sourceClass || element == data.targetClass
}
private fun KotlinPullUpData.checkAccidentalOverrides(
member: KtNamedDeclaration,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>
) {
if (memberDescriptor is CallableDescriptor && !member.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
val memberDescriptorInTargetClass = memberDescriptor.substitute(sourceToTargetClassSubstitutor)
if (memberDescriptorInTargetClass != null) {
val sequence = HierarchySearchRequest<PsiElement>(targetClass, targetClass.useScope())
.searchInheritors()
.asSequence()
.filterNot { it.isSourceOrTarget(this) }
.mapNotNull { it.unwrapped as? KtClassOrObject }
for (it in sequence) {
val subClassDescriptor = it.resolveToDescriptorWrapperAware(resolutionFacade) as ClassDescriptor
val substitution = getTypeSubstitution(targetClassDescriptor.defaultType, subClassDescriptor.defaultType).orEmpty()
val memberDescriptorInSubClass = memberDescriptorInTargetClass.substitute(substitution) as? CallableMemberDescriptor
val clashingMemberDescriptor = memberDescriptorInSubClass?.let {
subClassDescriptor.findCallableMemberBySignature(it)
} ?: continue
val clashingMember = clashingMemberDescriptor.source.getPsi() ?: continue
val message = KotlinBundle.message(
"text.member.0.in.super.class.will.clash.with.existing.member.of.1",
memberDescriptor.renderForConflicts(),
it.resolveToDescriptorWrapperAware(resolutionFacade).renderForConflicts()
)
conflicts.putValue(clashingMember, message.capitalize())
}
}
}
}
private fun KotlinPullUpData.checkInnerClassToInterface(
member: KtNamedDeclaration,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>
) {
if (isInterfaceTarget && memberDescriptor is ClassDescriptor && memberDescriptor.isInner) {
val message = KotlinBundle.message("text.inner.class.0.cannot.be.moved.to.intefrace", memberDescriptor.renderForConflicts())
conflicts.putValue(member, message.capitalize())
}
}
private fun KotlinPullUpData.checkVisibility(
memberInfo: KotlinMemberInfo,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>,
languageVersionSettings: LanguageVersionSettings
) {
fun reportConflictIfAny(targetDescriptor: DeclarationDescriptor, languageVersionSettings: LanguageVersionSettings) {
if (targetDescriptor in memberDescriptors.values) return
val target = (targetDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return
if (targetDescriptor is DeclarationDescriptorWithVisibility
&& !DescriptorVisibilityUtils.isVisibleIgnoringReceiver(targetDescriptor, targetClassDescriptor, languageVersionSettings)
) {
val message = RefactoringBundle.message(
"0.uses.1.which.is.not.accessible.from.the.superclass",
memberDescriptor.renderForConflicts(),
targetDescriptor.renderForConflicts()
)
conflicts.putValue(target, message.capitalize())
}
}
val member = memberInfo.member
val childrenToCheck = memberInfo.getChildrenToAnalyze()
if (memberInfo.isToAbstract && member is KtCallableDeclaration) {
if (member.typeReference == null) {
(memberDescriptor as CallableDescriptor).returnType?.let { returnType ->
val typeInTargetClass = sourceToTargetClassSubstitutor.substitute(returnType, Variance.INVARIANT)
val descriptorToCheck = typeInTargetClass?.constructor?.declarationDescriptor as? ClassDescriptor
if (descriptorToCheck != null) {
reportConflictIfAny(descriptorToCheck, languageVersionSettings)
}
}
}
}
childrenToCheck.forEach { children ->
children.accept(
object : KtTreeVisitorVoid() {
override fun visitReferenceExpression(expression: KtReferenceExpression) {
super.visitReferenceExpression(expression)
val context = resolutionFacade.analyze(expression)
expression.references
.flatMap { (it as? KtReference)?.resolveToDescriptors(context) ?: emptyList() }
.forEach { reportConflictIfAny(it, languageVersionSettings) }
}
}
)
}
}
| apache-2.0 |
square/okhttp | okhttp-testing-support/src/main/kotlin/okhttp3/DelegatingSSLSocketFactory.kt | 4 | 2789 | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import java.io.IOException
import java.net.InetAddress
import java.net.Socket
import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory
/**
* A [SSLSocketFactory] that delegates calls. Sockets can be configured after creation by
* overriding [.configureSocket].
*/
open class DelegatingSSLSocketFactory(private val delegate: SSLSocketFactory) : SSLSocketFactory() {
@Throws(IOException::class)
override fun createSocket(): SSLSocket {
val sslSocket = delegate.createSocket() as SSLSocket
return configureSocket(sslSocket)
}
@Throws(IOException::class)
override fun createSocket(host: String, port: Int): SSLSocket {
val sslSocket = delegate.createSocket(host, port) as SSLSocket
return configureSocket(sslSocket)
}
@Throws(IOException::class)
override fun createSocket(
host: String, port: Int, localAddress: InetAddress, localPort: Int
): SSLSocket {
val sslSocket = delegate.createSocket(host, port, localAddress, localPort) as SSLSocket
return configureSocket(sslSocket)
}
@Throws(IOException::class)
override fun createSocket(host: InetAddress, port: Int): SSLSocket {
val sslSocket = delegate.createSocket(host, port) as SSLSocket
return configureSocket(sslSocket)
}
@Throws(IOException::class)
override fun createSocket(
host: InetAddress, port: Int, localAddress: InetAddress, localPort: Int
): SSLSocket {
val sslSocket = delegate.createSocket(host, port, localAddress, localPort) as SSLSocket
return configureSocket(sslSocket)
}
override fun getDefaultCipherSuites(): Array<String> {
return delegate.defaultCipherSuites
}
override fun getSupportedCipherSuites(): Array<String> {
return delegate.supportedCipherSuites
}
@Throws(IOException::class)
override fun createSocket(
socket: Socket, host: String, port: Int, autoClose: Boolean
): SSLSocket {
val sslSocket = delegate.createSocket(socket, host, port, autoClose) as SSLSocket
return configureSocket(sslSocket)
}
@Throws(IOException::class)
protected open fun configureSocket(sslSocket: SSLSocket): SSLSocket {
// No-op by default.
return sslSocket
}
}
| apache-2.0 |
vhromada/Catalog | web/src/main/kotlin/com/github/vhromada/catalog/web/mapper/TimeMapper.kt | 1 | 488 | package com.github.vhromada.catalog.web.mapper
import com.github.vhromada.catalog.web.fo.TimeFO
/**
* An interface represents mapper for time.
*
* @author Vladimir Hromada
*/
interface TimeMapper {
/**
* Maps time.
*
* @param source time
* @return mapped FO for time
*/
fun map(source: Int): TimeFO
/**
* Maps FO for time.
*
* @param source FO for time
* @return mapped time
*/
fun mapBack(source: TimeFO): Int
}
| mit |
JetBrains/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/CreateMethodAction.kt | 1 | 7283 | // 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.lang.java.actions
import com.intellij.codeInsight.CodeInsightUtil.positionCursor
import com.intellij.codeInsight.CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement
import com.intellij.codeInsight.daemon.QuickFixBundle.message
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.setupEditor
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.setupMethodBody
import com.intellij.codeInsight.daemon.impl.quickfix.GuessTypeParameters
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.codeInsight.intention.preview.IntentionPreviewUtils
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.TemplateBuilder
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInsight.template.TemplateEditingAdapter
import com.intellij.lang.java.request.CreateMethodFromJavaUsageRequest
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.*
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.presentation.java.ClassPresentationUtil.getNameForClass
import com.intellij.psi.util.JavaElementKind
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil.setModifierProperty
/**
* @param abstract whether this action creates a method with explicit abstract modifier
*/
internal class CreateMethodAction(
targetClass: PsiClass,
override val request: CreateMethodRequest,
private val abstract: Boolean
) : CreateMemberAction(targetClass, request), JvmGroupIntentionAction {
override fun getActionGroup(): JvmActionGroup = if (abstract) CreateAbstractMethodActionGroup else CreateMethodActionGroup
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
return super.isAvailable(project, editor, file) && PsiNameHelper.getInstance(project).isIdentifier(request.methodName)
}
override fun getRenderData() = JvmActionGroup.RenderData { request.methodName }
override fun getFamilyName(): String = message("create.method.from.usage.family")
override fun getText(): String {
val what = request.methodName
val where = getNameForClass(target, false)
val kind = if (abstract) JavaElementKind.ABSTRACT_METHOD else JavaElementKind.METHOD
return message("create.element.in.class", kind.`object`(), what, where)
}
override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo {
val copyClass = PsiTreeUtil.findSameElementInCopy(target, file)
val previewRequest = if (request is CreateMethodFromJavaUsageRequest) {
val physicalRequest = request as? CreateMethodFromJavaUsageRequest ?: return IntentionPreviewInfo.EMPTY
val copyCall = PsiTreeUtil.findSameElementInCopy(physicalRequest.call, file)
CreateMethodFromJavaUsageRequest(copyCall, physicalRequest.modifiers)
} else request
JavaMethodRenderer(project, abstract, copyClass, previewRequest).doMagic()
return IntentionPreviewInfo.DIFF
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
JavaMethodRenderer(project, abstract, target, request).doMagic()
}
}
private class JavaMethodRenderer(
val project: Project,
val abstract: Boolean,
val targetClass: PsiClass,
val request: CreateMethodRequest
) {
val factory = JavaPsiFacade.getElementFactory(project)!!
val requestedModifiers = request.modifiers
val javaUsage = request as? CreateMethodFromJavaUsageRequest
val withoutBody = abstract || targetClass.isInterface && JvmModifier.STATIC !in requestedModifiers
fun doMagic() {
var method = renderMethod()
method = insertMethod(method)
method = forcePsiPostprocessAndRestoreElement(method) ?: return
val builder = setupTemplate(method)
method = forcePsiPostprocessAndRestoreElement(method) ?: return
val template = builder.buildInlineTemplate()
startTemplate(method, template)
}
fun renderMethod(): PsiMethod {
val method = factory.createMethod(request.methodName, PsiType.VOID)
val modifiersToRender = requestedModifiers.toMutableList()
if (targetClass.isInterface) {
modifiersToRender -= (visibilityModifiers + JvmModifier.ABSTRACT)
}
else if (abstract) {
if (modifiersToRender.remove(JvmModifier.PRIVATE)) {
modifiersToRender += JvmModifier.PROTECTED
}
modifiersToRender += JvmModifier.ABSTRACT
}
for (modifier in modifiersToRender) {
setModifierProperty(method, modifier.toPsiModifier(), true)
}
for (annotation in request.annotations) {
method.modifierList.addAnnotation(annotation.qualifiedName)
}
if (withoutBody) method.body?.delete()
return method
}
private fun insertMethod(method: PsiMethod): PsiMethod {
val anchor = javaUsage?.getAnchor(targetClass)
val inserted = if (anchor == null) {
targetClass.add(method)
}
else {
targetClass.addAfter(method, anchor)
}
return inserted as PsiMethod
}
private fun setupTemplate(method: PsiMethod): TemplateBuilderImpl {
val builder = TemplateBuilderImpl(method)
createTemplateContext(builder).run {
setupTypeElement(method.returnTypeElement, request.returnType)
setupParameters(method, request.expectedParameters)
}
builder.setEndVariableAfter(method.body ?: method)
return builder
}
private fun createTemplateContext(builder: TemplateBuilder): TemplateContext {
val substitutor = request.targetSubstitutor.toPsiSubstitutor(project)
val guesser = GuessTypeParameters(project, factory, builder, substitutor)
return TemplateContext(project, factory, targetClass, builder, guesser, javaUsage?.context)
}
private fun startTemplate(method: PsiMethod, template: Template) {
val targetFile = targetClass.containingFile
val newEditor = positionCursor(project, targetFile, method) ?: return
val templateListener = if (withoutBody) null else MyMethodBodyListener(project, newEditor, targetFile)
CreateFromUsageBaseFix.startTemplate(newEditor, template, project, templateListener, null)
}
}
private class MyMethodBodyListener(val project: Project, val editor: Editor, val file: PsiFile) : TemplateEditingAdapter() {
override fun templateFinished(template: Template, brokenOff: Boolean) {
if (brokenOff) return
PsiDocumentManager.getInstance(project).commitDocument(editor.document)
val offset = editor.caretModel.offset
val method = PsiTreeUtil.findElementOfClassAtOffset(file, offset - 1, PsiMethod::class.java, false) ?: return
if (IntentionPreviewUtils.isIntentionPreviewActive()) {
finishTemplate(method)
} else {
WriteCommandAction.runWriteCommandAction(project, message("create.method.body"), null, { finishTemplate(method) }, file)
}
}
private fun finishTemplate(method: PsiMethod) {
setupMethodBody(method)
setupEditor(method, editor)
}
}
| apache-2.0 |
JetBrains/intellij-community | plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/suite/performanceSuite.kt | 1 | 16524 | // 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.perf.suite
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.Disposable
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.PsiDocumentManagerBase
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.testFramework.*
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl
import com.intellij.usages.Usage
import com.intellij.util.ArrayUtilRt
import com.intellij.util.containers.toArray
import com.intellij.util.indexing.UnindexedFilesUpdater
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.perf.util.ExternalProject
import org.jetbrains.kotlin.idea.perf.util.ProfileTools.Companion.disableAllInspections
import org.jetbrains.kotlin.idea.perf.util.ProfileTools.Companion.enableAllInspections
import org.jetbrains.kotlin.idea.perf.util.ProfileTools.Companion.enableInspections
import org.jetbrains.kotlin.idea.perf.util.ProfileTools.Companion.enableSingleInspection
import org.jetbrains.kotlin.idea.perf.util.ProfileTools.Companion.initDefaultProfile
import org.jetbrains.kotlin.idea.performance.tests.utils.*
import org.jetbrains.kotlin.idea.performance.tests.utils.project.*
import org.jetbrains.kotlin.idea.test.invalidateLibraryCache
import org.jetbrains.kotlin.idea.testFramework.Fixture
import org.jetbrains.kotlin.idea.testFramework.Fixture.Companion.cleanupCaches
import org.jetbrains.kotlin.idea.testFramework.ProjectBuilder
import org.jetbrains.kotlin.idea.testFramework.Stats
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import java.io.File
class PerformanceSuite {
companion object {
fun suite(
name: String,
stats: StatsScope,
block: (StatsScope) -> Unit
) {
TeamCity.suite(name) {
stats.stats.use {
block(stats)
}
}
}
private fun PsiFile.highlightFile(toIgnore: IntArray = ArrayUtilRt.EMPTY_INT_ARRAY): List<HighlightInfo> {
val document = FileDocumentManager.getInstance().getDocument(virtualFile)!!
val editor = EditorFactory.getInstance().getEditors(document).first()
PsiDocumentManager.getInstance(project).commitAllDocuments()
return CodeInsightTestFixtureImpl.instantiateAndRun(this, editor, toIgnore, true)
}
fun rollbackChanges(vararg file: VirtualFile) {
val fileDocumentManager = FileDocumentManager.getInstance()
runInEdtAndWait {
fileDocumentManager.reloadFiles(*file)
}
ProjectManagerEx.getInstanceEx().openProjects.forEach { project ->
val psiDocumentManagerBase = PsiDocumentManager.getInstance(project) as PsiDocumentManagerBase
runInEdtAndWait {
psiDocumentManagerBase.clearUncommittedDocuments()
psiDocumentManagerBase.commitAllDocuments()
}
}
}
}
class StatsScope(val config: StatsScopeConfig, val stats: Stats, val rootDisposable: Disposable) {
fun app(f: ApplicationScope.() -> Unit) = ApplicationScope(rootDisposable, this).use(f)
fun <T> measure(name: String, f: MeasurementScope<T>.() -> Unit): List<T?> =
MeasurementScope<T>(name, stats, config).apply(f).run()
fun <T> measure(name: String, f: MeasurementScope<T>.() -> Unit, after: (() -> Unit)?): List<T?> =
MeasurementScope<T>(name, stats, config, after = after).apply(f).run()
fun typeAndMeasureAutoCompletion(name: String, fixture: Fixture, f: TypeAndAutoCompletionMeasurementScope.() -> Unit, after: (() -> Unit)?): List<String?> =
TypeAndAutoCompletionMeasurementScope(fixture, typeTestPrefix = "typeAndAutocomplete", name = name, stats = stats, config = config, after = after).apply(f).run()
fun typeAndMeasureUndo(name: String, fixture: Fixture, f: TypeAndUndoMeasurementScope.() -> Unit, after: (() -> Unit)?): List<String?> =
TypeAndUndoMeasurementScope(fixture, typeTestPrefix = "typeAndUndo", name = name, stats = stats, config = config, after = after).apply(f).run()
fun measureTypeAndHighlight(name: String, fixture: Fixture, f: TypeAndHighlightMeasurementScope.() -> Unit, after: (() -> Unit)?): List<HighlightInfo?> =
TypeAndHighlightMeasurementScope(fixture, typeTestPrefix = "", name = name, stats = stats, config = config, after = after).apply(f).run()
fun logStatValue(name: String, value: Any) {
logMessage { "buildStatisticValue key='${stats.name}: $name' value='$value'" }
TeamCity.statValue("${stats.name}: $name", value)
}
}
class ApplicationScope(val rootDisposable: Disposable, val stats: StatsScope) : AutoCloseable {
val application = initApp(rootDisposable)
val jdk: Sdk = initSdk(rootDisposable)
fun project(externalProject: ExternalProject, refresh: Boolean = false, block: ProjectScope.() -> Unit) =
ProjectScope(ProjectScopeConfig(externalProject, refresh), this).use(block)
fun project(block: ProjectWithDescriptorScope.() -> Unit) =
ProjectWithDescriptorScope(this).use(block)
fun project(name: String? = null, path: String, openWith: ProjectOpenAction = ProjectOpenAction.EXISTING_IDEA_PROJECT, block: ProjectScope.() -> Unit) =
ProjectScope(ProjectScopeConfig(path, openWith, name = name), this).use(block)
fun gradleProject(name: String? = null, path: String, refresh: Boolean = false, block: ProjectScope.() -> Unit) =
ProjectScope(ProjectScopeConfig(path, ProjectOpenAction.GRADLE_PROJECT, refresh, name = name), this).use(block)
fun warmUpProject() = project {
descriptor {
name("helloWorld")
module {
kotlinStandardLibrary()
kotlinFile("HelloMain") {
topFunction("main") {
param("args", "Array<String>")
body("""println("Hello World!")""")
}
}
}
}
fixture("src/HelloMain.kt").use { fixture ->
fixture.highlight()
.also {
fixture.checkNoErrors(it)
}
.firstOrNull { it.severity == HighlightSeverity.WARNING }
?: error("`[UNUSED_PARAMETER] Parameter 'args' is never used` has to be highlighted")
}
}
override fun close() {
application.setDataProvider(null)
}
}
abstract class AbstractProjectScope(val app: ApplicationScope) : AutoCloseable {
abstract val project: Project
private val openFiles = mutableListOf<VirtualFile>()
private var compilerTester: CompilerTester? = null
fun profile(profile: ProjectProfile): Unit = when (profile) {
EmptyProfile -> project.disableAllInspections()
DefaultProfile -> project.initDefaultProfile()
FullProfile -> project.enableAllInspections()
is CustomProfile -> project.enableInspections(*profile.inspectionNames.toArray(emptyArray()))
}
fun withCompiler() {
compilerTester = CompilerTester(project, ModuleManager.getInstance(project).modules.toList(), null)
}
fun rebuildProject() {
compilerTester?.rebuild() ?: error("compiler isn't ready for compilation")
}
fun Fixture.highlight() = highlight(psiFile)
fun Fixture.checkNoErrors(highlightInfos: List<HighlightInfo>?) {
val errorHighlightInfos = highlightInfos?.filter { it.severity == HighlightSeverity.ERROR }
check(errorHighlightInfos?.isNotEmpty() != true) {
"No ERRORs are expected in ${this.fileName}: $errorHighlightInfos"
}
}
fun highlight(editorFile: PsiFile?, toIgnore: IntArray = ArrayUtilRt.EMPTY_INT_ARRAY) =
editorFile?.highlightFile(toIgnore) ?: error("editor isn't ready for highlight")
fun findUsages(config: CursorConfig): Set<Usage> {
val offset = config.fixture.editor.caretModel.offset
val psiFile = config.fixture.psiFile
val psiElement = psiFile.findElementAt(offset) ?: error("psi element not found at ${psiFile.virtualFile} : $offset")
val ktDeclaration = PsiTreeUtil.getParentOfType(psiElement, KtDeclaration::class.java)
?: error("KtDeclaration not found at ${psiFile.virtualFile} : $offset")
return config.fixture.findUsages(ktDeclaration)
}
fun enableSingleInspection(inspectionName: String) =
this.project.enableSingleInspection(inspectionName)
fun enableAllInspections() =
this.project.enableAllInspections()
fun editor(path: String) =
openInEditor(project, path).psiFile.also { openFiles.add(it.virtualFile) }
fun fixture(path: String, updateScriptDependenciesIfNeeded: Boolean = true): Fixture {
return fixture(projectFileByName(project, path).virtualFile, path, updateScriptDependenciesIfNeeded)
}
fun fixture(file: VirtualFile, fileName: String? = null, updateScriptDependenciesIfNeeded: Boolean = true): Fixture {
val fixture = Fixture.openFixture(project, file, fileName)
openFiles.add(fixture.vFile)
if (file.name.endsWith(KotlinFileType.EXTENSION)) {
assert(fixture.psiFile is KtFile) {
"$file expected to be a Kotlin file"
}
}
if (updateScriptDependenciesIfNeeded) {
fixture.updateScriptDependenciesIfNeeded()
}
return fixture
}
fun <T> measure(vararg name: String, clearCaches: Boolean = true, f: MeasurementScope<T>.() -> Unit): List<T?> {
val after = wrapAfter(clearCaches)
return app.stats.measure(name.joinToString("-"), f, after)
}
private fun wrapAfter(clearCaches: Boolean): () -> Unit {
val after = if (clearCaches) {
fun() { project.cleanupCaches() }
} else {
fun() {}
}
return after
}
fun <T> measure(fixture: Fixture, f: MeasurementScope<T>.() -> Unit): List<T?> =
measure(fixture.fileName, f = f)
fun <T> measure(fixture: Fixture, vararg name: String, f: MeasurementScope<T>.() -> Unit): List<T?> =
measure(combineName(fixture, *name), f = f)
fun measureTypeAndHighlight(
fixture: Fixture,
vararg name: String,
f: TypeAndHighlightMeasurementScope.() -> Unit = {}
): List<HighlightInfo?> {
val after = wrapAfter(true)
return app.stats.measureTypeAndHighlight(combineName(fixture, *name), fixture, f, after)
}
fun measureHighlight(fixture: Fixture, vararg name: String): List<List<HighlightInfo>?> {
return measure<List<HighlightInfo>?>(combineNameWithSimpleFileName("highlighting", fixture, *name)) {
before = {
fixture.openInEditor()
}
test = {
fixture.highlight().also { fixture.checkNoErrors(it) }
}
after = {
fixture.close()
project.cleanupCaches()
}
}
}
fun typeAndMeasureAutoCompletion(fixture: Fixture, vararg name: String, clearCaches: Boolean = true, f: TypeAndAutoCompletionMeasurementScope.() -> Unit): List<String?> {
val after = wrapAfter(clearCaches)
return app.stats.typeAndMeasureAutoCompletion(combineName(fixture, *name), fixture, f, after)
}
fun typeAndMeasureUndo(fixture: Fixture, vararg name: String, clearCaches: Boolean = true, f: TypeAndUndoMeasurementScope.() -> Unit = {}): List<String?> {
val after = wrapAfter(clearCaches)
return app.stats.typeAndMeasureUndo(combineName(fixture, *name), fixture, f, after)
}
fun combineName(fixture: Fixture, vararg name: String) =
listOf(name.joinToString("-"), fixture.fileName)
.filter { it.isNotEmpty() }
.joinToString(" ")
fun combineNameWithSimpleFileName(type: String, fixture: Fixture, vararg name: String): String =
listOf(type, name.joinToString("-"), fixture.simpleFilename())
.filter { it.isNotEmpty() }
.joinToString(" ")
override fun close(): Unit = RunAll(
{ compilerTester?.tearDown() },
{ project.let { prj -> app.application.closeProject(prj) } }
).run()
}
class ProjectWithDescriptorScope(app: ApplicationScope) : AbstractProjectScope(app) {
private var descriptor: ProjectBuilder? = null
override val project: Project by lazy {
val builder = descriptor ?: error("project is not configured")
val openProject = builder.openProjectOperation()
openProject.openProject().also {
openProject.postOpenProject(it)
}
}
fun descriptor(descriptor: ProjectBuilder.() -> Unit) {
this.descriptor = ProjectBuilder().apply(descriptor)
}
}
class ProjectScope(config: ProjectScopeConfig, app: ApplicationScope) : AbstractProjectScope(app) {
override val project: Project = initProject(config, app)
companion object {
fun initProject(config: ProjectScopeConfig, app: ApplicationScope): Project {
val projectPath = File(config.path).canonicalPath
UsefulTestCase.assertTrue("path ${config.path} does not exist, check README.md", File(projectPath).exists())
val openProject = OpenProject(
projectPath = projectPath,
projectName = config.projectName,
jdk = app.jdk,
projectOpenAction = config.openWith
)
val project = ProjectOpenAction.openProject(openProject)
openProject.projectOpenAction.postOpenProject(project, openProject)
// indexing
if (config.refresh) {
invalidateLibraryCache(project)
}
CodeInsightTestFixtureImpl.ensureIndexesUpToDate(project)
dispatchAllInvocationEvents()
with(DumbService.getInstance(project)) {
UnindexedFilesUpdater(project).queue()
completeJustSubmittedTasks()
}
dispatchAllInvocationEvents()
Fixture.enableAnnotatorsAndLoadDefinitions(project)
app.application.setDataProvider(TestDataProvider(project))
return project
}
}
}
}
sealed class ProjectProfile
object EmptyProfile : ProjectProfile()
object DefaultProfile : ProjectProfile()
object FullProfile : ProjectProfile()
data class CustomProfile(val inspectionNames: List<String>) : ProjectProfile()
fun UsefulTestCase.suite(
suiteName: String? = null,
config: StatsScopeConfig = StatsScopeConfig(),
block: PerformanceSuite.StatsScope.() -> Unit
) {
val stats = Stats(config.name ?: suiteName ?: name, outputConfig = config.outputConfig, profilerConfig = config.profilerConfig)
PerformanceSuite.suite(
suiteName ?: this.javaClass.name,
PerformanceSuite.StatsScope(config, stats, testRootDisposable),
block
)
}
| apache-2.0 |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/domain/course_complete/model/CourseCompleteInfo.kt | 2 | 334 | package org.stepik.android.domain.course_complete.model
import org.stepik.android.model.Certificate
import org.stepik.android.model.Course
import org.stepik.android.model.Progress
data class CourseCompleteInfo(
val course: Course,
val courseProgress: Progress,
val certificate: Certificate?,
val hasReview: Boolean
) | apache-2.0 |
exercism/xkotlin | exercises/practice/clock/src/test/kotlin/ClockCreationTest.kt | 1 | 2396 | import org.junit.Ignore
import org.junit.Test
import kotlin.test.assertEquals
class ClockCreationTest {
@Test
fun `on the hour`() = assertEquals("08:00", Clock(8, 0).toString())
@Ignore
@Test
fun `past the hour`() = assertEquals("11:09", Clock(11, 9).toString())
@Ignore
@Test
fun `midnight is zero hours`() = assertEquals("00:00", Clock(24, 0).toString())
@Ignore
@Test
fun `hour rolls over`() = assertEquals("01:00", Clock(25, 0).toString())
@Ignore
@Test
fun `hour rolls over continuously`() = assertEquals("04:00", Clock(100, 0).toString())
@Ignore
@Test
fun `sixty minutes is next hour`() = assertEquals("02:00", Clock(1, 60).toString())
@Ignore
@Test
fun `minutes roll over`() = assertEquals("02:40", Clock(0, 160).toString())
@Ignore
@Test
fun `minutes roll over continuously`() = assertEquals("04:43", Clock(0, 1723).toString())
@Ignore
@Test
fun `hour and minutes roll over`() = assertEquals("03:40", Clock(25, 160).toString())
@Ignore
@Test
fun `hour and minutes roll over continuously`() = assertEquals("11:01", Clock(201, 3001).toString())
@Ignore
@Test
fun `hour and minutes roll over to exactly midnight`() = assertEquals("00:00", Clock(72, 8640).toString())
@Ignore
@Test
fun `negative hour`() = assertEquals("23:15", Clock(-1, 15).toString())
@Ignore
@Test
fun `negative hour rolls over`() = assertEquals("23:00", Clock(-25, 0).toString())
@Ignore
@Test
fun `negative hour rolls over continuously`() = assertEquals("05:00", Clock(-91, 0).toString())
@Ignore
@Test
fun `negative minutes`() = assertEquals("00:20", Clock(1, -40).toString())
@Ignore
@Test
fun `negative minutes roll over`() = assertEquals("22:20", Clock(1, -160).toString())
@Ignore
@Test
fun `negative minutes roll over continuously`() = assertEquals("16:40", Clock(1, -4820).toString())
@Ignore
@Test
fun `negative sixty minutes is previous hour`() = assertEquals("01:00", Clock(2, -60).toString())
@Ignore
@Test
fun `negative hour and minutes both roll over`() = assertEquals("20:20", Clock(-25, -160).toString())
@Ignore
@Test
fun `negative hour and minutes both roll over continuously`() =
assertEquals("22:10", Clock(-121, -5810).toString())
}
| mit |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/toolboks/font/FreeTypeFont.kt | 2 | 1837 | package io.github.chrislo27.toolboks.font
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator
import com.badlogic.gdx.utils.Disposable
import io.github.chrislo27.toolboks.util.gdxutils.copy
import kotlin.math.min
import kotlin.math.roundToInt
/**
* Handles a FreeType font. Used for dynamic resizing.
*/
class FreeTypeFont(val file: FileHandle, val defaultWindowSize: Pair<Int, Int>,
val fontSize: Int, val borderSize: Float,
val parameter: FreeTypeFontGenerator.FreeTypeFontParameter) : Disposable {
constructor(file: FileHandle, defaultWindowSize: Pair<Int, Int>,
parameter: FreeTypeFontGenerator.FreeTypeFontParameter):
this(file, defaultWindowSize, parameter.size, parameter.borderWidth, parameter)
private var generator: FreeTypeFontGenerator? = null
var font: BitmapFont? = null
private set
private var afterLoad: FreeTypeFont.() -> Unit = {}
fun setAfterLoad(func: FreeTypeFont.() -> Unit): FreeTypeFont {
afterLoad = func
return this
}
fun isLoaded(): Boolean = font != null
fun load(width: Float, height: Float) {
dispose()
val scale: Float = min(width / defaultWindowSize.first, height / defaultWindowSize.second)
val newParam = parameter.copy()
newParam.size = (fontSize * scale).roundToInt()
newParam.borderWidth = borderSize * scale
generator = FreeTypeFontGenerator(file)
font = generator!!.generateFont(newParam)
this.afterLoad()
}
override fun dispose() {
font?.dispose()
(font?.data as? Disposable)?.dispose()
generator?.dispose()
font = null
generator = null
}
} | gpl-3.0 |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/completion/htl/provider/option/HtlOptionCompletionProvider.kt | 1 | 1255 | package com.aemtools.completion.htl.provider.option
import com.aemtools.common.util.findParentByType
import com.aemtools.completion.model.htl.HtlOption
import com.aemtools.service.repository.inmemory.HtlAttributesRepository
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.util.ProcessingContext
/**
* @author Dmytro Troynikov
*/
object HtlOptionCompletionProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet) {
val currentPosition = parameters.position
val hel = currentPosition.findParentByType(com.aemtools.lang.htl.psi.mixin.HtlElExpressionMixin::class.java)
?: return
val names = hel.getOptions().map { it.name() }
.filterNot { it == "" }
val completionVariants = HtlAttributesRepository.getHtlOptions()
.filterNot { names.contains(it.name) }
.map(HtlOption::toLookupElement)
result.addAllElements(completionVariants)
result.stopHere()
}
}
| gpl-3.0 |
square/spoon | spoon-runner/src/test/java/com/squareup/spoon/LogRecordingTestRunListenerTest.kt | 1 | 4423 | package com.squareup.spoon
import com.android.ddmlib.testrunner.TestIdentifier
import com.google.common.truth.Truth.assertThat
import com.squareup.spoon.LogRecordingTestRunListener.Companion.stripParametersInClassName
import org.junit.Before
import org.junit.Test
class LogRecordingTestRunListenerTest {
private val className = "com.some.BusinessTest"
private val classNameWithParameterOnline = "$className[ONLINE]"
private val classNameWithParameterOffline = "$className[OFFLINE]"
private val classNameWithSquareBrackets = "com.some.[ONLINE]BusinessTest"
private val testMethod = "someTest"
private val testIdentifierWithoutParameter =
TestIdentifier(className, testMethod)
private val testIdentifierWithoutParameter2 =
TestIdentifier("${className}2", testMethod)
private val testIdentifierWithParameterOnline =
TestIdentifier(classNameWithParameterOnline, testMethod)
private val testIdentifierWithParameterOffline =
TestIdentifier(classNameWithParameterOffline, testMethod)
private lateinit var logRecordingTestRunListener: LogRecordingTestRunListener
@Before
fun setUp() {
logRecordingTestRunListener = LogRecordingTestRunListener()
}
@Test
fun stripParametersInClassNameOfParameterizedTest() {
val testIdentifier = TestIdentifier(classNameWithParameterOnline, testMethod)
val strippedTestIdentifier = stripParametersInClassName(testIdentifier)
assertThat(strippedTestIdentifier.className).isEqualTo(className)
}
@Test
fun classNameWithoutSquaredBracketsRemainsUntouched() {
val testIdentifier = TestIdentifier(className, testMethod)
val strippedTestIdentifier = stripParametersInClassName(testIdentifier)
assertThat(strippedTestIdentifier.className).isEqualTo(className)
}
@Test
fun classNameWithSquaredBracketsRemainsUntouched() {
val testIdentifier = TestIdentifier(classNameWithSquareBrackets, testMethod)
val strippedTestIdentifier = stripParametersInClassName(testIdentifier)
assertThat(strippedTestIdentifier.className).isEqualTo(classNameWithSquareBrackets)
}
@Test
fun trackVariantsOfParameterizedTestJustOnce() {
logRecordingTestRunListener.testStarted(testIdentifierWithParameterOnline)
logRecordingTestRunListener.testStarted(testIdentifierWithParameterOffline)
val result = logRecordingTestRunListener.activeTests()
assertThat(result).containsExactly(testIdentifierWithoutParameter)
}
@Test
fun removeActiveTestWhenIgnored() {
logRecordingTestRunListener.testStarted(testIdentifierWithoutParameter)
logRecordingTestRunListener.testIgnored(testIdentifierWithoutParameter)
val result = logRecordingTestRunListener.activeTests()
assertThat(result).isEmpty()
}
@Test
fun addIgnoredTest() {
logRecordingTestRunListener.testIgnored(testIdentifierWithoutParameter)
val result = logRecordingTestRunListener.ignoredTests()
assertThat(result).containsExactly(testIdentifierWithoutParameter)
}
@Test
fun addActiveTest() {
logRecordingTestRunListener.testStarted(testIdentifierWithoutParameter)
val result = logRecordingTestRunListener.activeTests()
assertThat(result).containsExactly(testIdentifierWithoutParameter)
}
@Test
fun addMultipleActiveTest() {
logRecordingTestRunListener.testStarted(testIdentifierWithoutParameter)
logRecordingTestRunListener.testStarted(testIdentifierWithoutParameter2)
val result = logRecordingTestRunListener.activeTests()
assertThat(result).containsExactly(testIdentifierWithoutParameter, testIdentifierWithoutParameter2)
}
@Test
fun addIgnoredTestHasNoImpactOntoActiveTest() {
logRecordingTestRunListener.testIgnored(testIdentifierWithoutParameter)
val result = logRecordingTestRunListener.activeTests()
assertThat(result).isEmpty()
}
@Test
fun addActiveTestHasNoImpactOntoIgnoredTest() {
logRecordingTestRunListener.testStarted(testIdentifierWithoutParameter)
val result = logRecordingTestRunListener.ignoredTests()
assertThat(result).isEmpty()
}
@Test
fun checkRunName() {
logRecordingTestRunListener.testRunStarted("NAME", 99)
assertThat(logRecordingTestRunListener.runName()).isEqualTo("NAME")
}
@Test
fun checkTestCount() {
logRecordingTestRunListener.testRunStarted("NAME", 99)
assertThat(logRecordingTestRunListener.testCount()).isEqualTo(99)
}
} | apache-2.0 |
vanshg/KrazyKotlin | src/test/kotlin/com/vanshgandhi/krazykotlin/BooleanExtensionsTest.kt | 1 | 353 | package com.vanshgandhi.krazykotlin
import org.junit.Test
import org.junit.Assert.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/**
* Created by Vansh Gandhi on 6/8/17.
*/
class BooleanExtensionsTest {
@Test fun testIntValue() {
assertEquals(true.intValue, 1)
assertEquals(false.intValue, 0)
}
}
| mit |
RichoDemus/chronicler | test/component-test/src/component-test/kotlin/com/richodemus/chronicler/test/util/Event.kt | 1 | 96 | package com.richodemus.chronicler.test.util
data class Event(val id: String, val data: String)
| gpl-3.0 |
martinlau/fixture | src/test/kotlin/io/fixture/feature/hook/EmbedScreenshotHook.kt | 1 | 1350 | /*
* #%L
* fixture
* %%
* Copyright (C) 2013 Martin Lau
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package io.fixture.feature.hook
import org.openqa.selenium.WebDriver
import cucumber.api.java.After
import cucumber.api.Scenario
import org.openqa.selenium.TakesScreenshot
import org.openqa.selenium.OutputType
import org.springframework.beans.factory.annotation.Autowired
public class EmbedScreenshotHook [Autowired(required = false)] (
val takesScreenshot: TakesScreenshot? = null
) {
[After]
fun embedScreenshot(scenario: Scenario) {
if (takesScreenshot != null) {
val screenshot = takesScreenshot.getScreenshotAs(OutputType.BYTES)
scenario.write("<p>")
scenario.embed(screenshot, "image/png")
scenario.write("</p>")
}
}
}
| apache-2.0 |
code-helix/slatekit | src/lib/kotlin/slatekit-migrations/src/main/kotlin/slatekit/migrations/MigrationSettings.kt | 1 | 483 | /**
* <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.migrations
data class MigrationSettings(
val enableLogging: Boolean = true,
val enableOutput: Boolean = true
)
| apache-2.0 |
zdary/intellij-community | platform/workspaceModel/ide/src/com/intellij/workspaceModel/ide/impl/StartupMeasurerHelper.kt | 1 | 584 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl
import com.intellij.diagnostic.Activity
import com.intellij.diagnostic.StartUpMeasurer.startActivity
internal var moduleLoadingActivity: Activity? = null
fun finishModuleLoadingActivity() {
moduleLoadingActivity?.end()
moduleLoadingActivity = null
}
fun recordModuleLoadingActivity() {
if (moduleLoadingActivity == null) {
moduleLoadingActivity = startActivity("moduleLoading")
}
}
| apache-2.0 |
leafclick/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesGroupingSupport.kt | 1 | 3936 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.KeyedExtensionFactory
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.DIRECTORY_GROUPING
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.MODULE_GROUPING
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.REPOSITORY_GROUPING
import gnu.trove.THashMap
import java.beans.PropertyChangeListener
import java.beans.PropertyChangeSupport
import javax.swing.tree.DefaultTreeModel
private val PREDEFINED_PRIORITIES = mapOf(DIRECTORY_GROUPING to 10, MODULE_GROUPING to 20, REPOSITORY_GROUPING to 30)
class ChangesGroupingSupport(val project: Project, source: Any, val showConflictsNode: Boolean) {
private val changeSupport = PropertyChangeSupport(source)
private val groupingConfig: MutableMap<String, Boolean>
val groupingKeys: Set<String>
get() = groupingConfig.filterValues { it }.keys
init {
groupingConfig = THashMap()
for (epBean in ChangesGroupingPolicyFactory.EP_NAME.extensionList) {
if (epBean.key != null) {
groupingConfig.put(epBean.key, false)
}
}
}
operator fun get(groupingKey: String): Boolean {
if (!isAvailable(groupingKey)) throw IllegalArgumentException("Unknown grouping $groupingKey")
return groupingConfig[groupingKey]!!
}
operator fun set(groupingKey: String, state: Boolean) {
if (!isAvailable(groupingKey)) throw IllegalArgumentException("Unknown grouping $groupingKey")
if (groupingConfig[groupingKey] != state) {
val oldGroupingKeys = groupingKeys
groupingConfig[groupingKey] = state
changeSupport.firePropertyChange(PROP_GROUPING_KEYS, oldGroupingKeys, groupingKeys)
}
}
val grouping: ChangesGroupingPolicyFactory
get() = object : ChangesGroupingPolicyFactory() {
override fun createGroupingPolicy(project: Project, model: DefaultTreeModel): ChangesGroupingPolicy {
var result = DefaultChangesGroupingPolicy.Factory(showConflictsNode).createGroupingPolicy(project, model)
groupingConfig.filterValues { it }.keys.sortedByDescending { PREDEFINED_PRIORITIES[it] }.forEach {
result = findFactory(it)!!.createGroupingPolicy(project, model).apply { setNextGroupingPolicy(result) }
}
return result
}
}
val isNone: Boolean get() = groupingKeys.isEmpty()
val isDirectory: Boolean get() = this[DIRECTORY_GROUPING]
fun setGroupingKeysOrSkip(groupingKeys: Set<String>) {
groupingConfig.entries.forEach { it.setValue(it.key in groupingKeys) }
}
fun isAvailable(groupingKey: String) = findFactory(groupingKey) != null
fun addPropertyChangeListener(listener: PropertyChangeListener): Unit = changeSupport.addPropertyChangeListener(listener)
fun removePropertyChangeListener(listener: PropertyChangeListener): Unit = changeSupport.removePropertyChangeListener(listener)
companion object {
@JvmField
val KEY = DataKey.create<ChangesGroupingSupport>("ChangesTree.GroupingSupport")
const val PROP_GROUPING_KEYS = "ChangesGroupingKeys"
const val DIRECTORY_GROUPING = "directory"
const val MODULE_GROUPING = "module"
const val REPOSITORY_GROUPING = "repository"
const val NONE_GROUPING = "none"
@JvmStatic
fun getFactory(key: String): ChangesGroupingPolicyFactory {
return findFactory(key) ?: NoneChangesGroupingFactory
}
private fun findFactory(key: String): ChangesGroupingPolicyFactory? {
return KeyedExtensionFactory.findByKey(key, ChangesGroupingPolicyFactory.EP_NAME, ApplicationManager.getApplication().picoContainer)
}
}
} | apache-2.0 |
Bastien7/Kotlin-presentation | KotlinApp/src/main/kotlin/kotlinApp/model/Topic.kt | 1 | 270 | package kotlinApp.model
import org.springframework.data.annotation.Id
import java.time.LocalDateTime
data class Topic(
@Id val id: String? = null,
val question: String = "",
val answers: List<Message> = listOf(),
val date: LocalDateTime = LocalDateTime.now()
) | mit |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/coroutines/SequenceBuilderTest/testInfiniteYieldAll.kt | 2 | 367 | import kotlin.test.*
import kotlin.coroutines.experimental.buildSequence
import kotlin.coroutines.experimental.buildIterator
fun box() {
val values = buildIterator {
while (true) {
yieldAll((1..5).map { it })
}
}
var sum = 0
repeat(10) {
sum += values.next() //.also(::println)
}
assertEquals(30, sum)
}
| apache-2.0 |
tinsukE/retrofit-coroutines | lib/src/main/java/com/tinsuke/retrofit/coroutines/experimental/CoroutinesCallAdapterFactory.kt | 1 | 2403 | package com.tinsuke.retrofit.coroutines.experimental
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.newFixedThreadPoolContext
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Response
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import kotlin.coroutines.experimental.CoroutineContext
class CoroutinesCallAdapterFactory private constructor(private val context: CoroutineContext,
interceptor: CoroutinesInterceptor?) : CallAdapter.Factory() {
private val executor = object : CoroutinesExecutor {
override fun execute(call: Call<Any>): Response<Any> {
return if (interceptor == null) {
call.execute()
} else {
interceptor.intercept(call)
}
}
}
override fun get(returnType: Type?, annotations: Array<out Annotation>?, retrofit: Retrofit?): CallAdapter<*, *>? {
val rawType = getRawType(returnType)
if (rawType != Deferred::class.java) {
return null
}
if (returnType !is ParameterizedType) {
throw createInvalidReturnTypeException()
}
val deferredType = getParameterUpperBound(0, returnType)
val rawDeferredType = getRawType(deferredType)
if (rawDeferredType == Response::class.java) {
if (deferredType !is ParameterizedType) {
throw throw createInvalidReturnTypeException()
}
val responseType = getParameterUpperBound(0, deferredType)
return CoroutinesResponseCallAdapter(context, responseType, executor)
} else {
return CoroutinesCallAdapter(context, deferredType, executor)
}
}
private fun createInvalidReturnTypeException(): RuntimeException {
return IllegalStateException("Return type must be parameterized as Deferred<Foo>, Deferred<out Foo>, " +
"Deferred<Response<Foo>> or Deferred<Response<out Foo>>")
}
companion object {
fun create(context: CoroutineContext = newFixedThreadPoolContext(5, "Network-Coroutines"),
interceptor: CoroutinesInterceptor? = null): CoroutinesCallAdapterFactory {
return CoroutinesCallAdapterFactory(context, interceptor)
}
}
} | apache-2.0 |
AndroidX/androidx | camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/impl/ZoomControl.kt | 3 | 2846 | /*
* 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.camera.camera2.pipe.integration.impl
import androidx.annotation.RequiresApi
import androidx.camera.camera2.pipe.integration.compat.ZoomCompat
import androidx.camera.camera2.pipe.integration.config.CameraScope
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoSet
import javax.inject.Inject
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
@CameraScope
class ZoomControl @Inject constructor(private val zoomCompat: ZoomCompat) : UseCaseCameraControl {
private var _zoomRatio = 1.0f
var zoomRatio: Float
get() = _zoomRatio
set(value) {
// TODO: Make this a suspend function?
_zoomRatio = value
update()
}
// NOTE: minZoom may be lower than 1.0
// NOTE: Default zoom ratio is 1.0
// NOTE: Linear zoom is
val minZoom: Float = zoomCompat.minZoom
val maxZoom: Float = zoomCompat.maxZoom
/** Linear zoom is between 0.0f and 1.0f */
fun toLinearZoom(zoomRatio: Float): Float {
val range = zoomCompat.maxZoom - zoomCompat.minZoom
if (range > 0) {
return (zoomRatio - zoomCompat.minZoom) / range
}
return 0.0f
}
/** Zoom ratio is commonly used as the "1x, 2x, 5x" zoom ratio. Zoom ratio may be less than 1 */
fun toZoomRatio(linearZoom: Float): Float {
val range = zoomCompat.maxZoom - zoomCompat.minZoom
if (range > 0) {
return linearZoom * range + zoomCompat.minZoom
}
return 1.0f
}
private var _useCaseCamera: UseCaseCamera? = null
override var useCaseCamera: UseCaseCamera?
get() = _useCaseCamera
set(value) {
_useCaseCamera = value
update()
}
override fun reset() {
// TODO: 1.0 may not be a reasonable value to reset the zoom state too.
zoomRatio = 1.0f
update()
}
private fun update() {
_useCaseCamera?.let {
zoomCompat.apply(_zoomRatio, it)
}
}
@Module
abstract class Bindings {
@Binds
@IntoSet
abstract fun provideControls(zoomControl: ZoomControl): UseCaseCameraControl
}
}
| apache-2.0 |
AndroidX/androidx | compose/animation/animation-graphics/src/androidAndroidTest/kotlin/androidx/compose/animation/graphics/vector/AnimatorAnimationSpecsTest.kt | 3 | 8207 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.graphics.vector
import androidx.compose.animation.core.InternalAnimationApi
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.keyframes
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.google.common.truth.Truth.assertWithMessage
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class AnimatorAnimationSpecsTest {
@get:Rule
val rule = createComposeRule()
private val tolerance = 0.01f
@OptIn(InternalAnimationApi::class)
@Test
fun reversed_tween() {
val isAtEnd = mutableStateOf(false)
rule.setContent {
val transition = updateTransition(targetState = isAtEnd.value, label = "test")
val control = transition.animateFloat(
label = "control",
transitionSpec = { tween(durationMillis = 1000, easing = LinearEasing) }
) {
if (it) 1000f else 0f
}
val reversed = transition.animateFloat(
label = "reversed",
transitionSpec = {
tween<Float>(durationMillis = 1000, easing = LinearEasing).reversed(1000)
}
) {
if (it) 1000f else 0f
}
assertWithMessage("at playTimeNanos: ${transition.playTimeNanos}")
.that(reversed.value).isWithin(tolerance).of(control.value)
}
rule.runOnIdle { isAtEnd.value = true }
rule.waitForIdle()
}
@OptIn(InternalAnimationApi::class)
@Test
fun reversed_keyframes() {
val isAtEnd = mutableStateOf(false)
rule.setContent {
val transition = updateTransition(targetState = isAtEnd.value, label = "test")
val control = transition.animateFloat(
label = "control",
transitionSpec = {
keyframes {
durationMillis = 1000
0f at 0 with LinearEasing
100f at 100 with LinearEasing
1000f at 1000 with LinearEasing
}
}
) {
if (it) 1000f else 0f
}
val reversed = transition.animateFloat(
label = "reversed",
transitionSpec = {
keyframes<Float> {
durationMillis = 1000
1000f at 0 with LinearEasing
100f at 900 with LinearEasing
0f at 1000 with LinearEasing
}.reversed(1000)
}
) {
if (it) 1000f else 0f
}
assertWithMessage("at playTimeNanos: ${transition.playTimeNanos}")
.that(reversed.value).isWithin(tolerance).of(control.value)
}
rule.runOnIdle { isAtEnd.value = true }
rule.waitForIdle()
}
@OptIn(InternalAnimationApi::class)
@Test
fun reversed_keyframes_delay() {
val isAtEnd = mutableStateOf(false)
rule.setContent {
val transition = updateTransition(targetState = isAtEnd.value, label = "test")
val control = transition.animateFloat(
label = "control",
transitionSpec = {
keyframes {
durationMillis = 1000
0f at 0 with LinearEasing
1000f at 500 with LinearEasing
}
}
) {
if (it) 1000f else 0f
}
val reversed = transition.animateFloat(
label = "reversed",
transitionSpec = {
keyframes<Float> {
durationMillis = 1000
1000f at 0 with LinearEasing
1000f at 500 with LinearEasing
0f at 1000 with LinearEasing
}.reversed(1000)
}
) {
if (it) 1000f else 0f
}
assertWithMessage("at playTimeNanos: ${transition.playTimeNanos}")
.that(reversed.value).isWithin(tolerance).of(control.value)
}
rule.runOnIdle { isAtEnd.value = true }
rule.waitForIdle()
}
@OptIn(InternalAnimationApi::class)
@Test
fun combined_single() {
val isAtEnd = mutableStateOf(false)
rule.setContent {
val transition = updateTransition(targetState = isAtEnd.value, label = "test")
val control = transition.animateFloat(
label = "control",
transitionSpec = { tween(durationMillis = 1000, easing = LinearEasing) }
) {
if (it) 1000f else 0f
}
val combined = transition.animateFloat(
label = "combined",
transitionSpec = {
combined(
listOf(
0 to tween(durationMillis = 1000, easing = LinearEasing)
)
)
}
) {
if (it) 1000f else 0f
}
assertWithMessage("at playTimeNanos: ${transition.playTimeNanos}")
.that(combined.value).isWithin(tolerance).of(control.value)
}
rule.runOnIdle { isAtEnd.value = true }
rule.waitForIdle()
}
@OptIn(InternalAnimationApi::class)
@Test
fun combined_multiple() {
val isAtEnd = mutableStateOf(false)
rule.setContent {
val transition = updateTransition(targetState = isAtEnd.value, label = "test")
val control = transition.animateFloat(
label = "control",
transitionSpec = {
keyframes {
durationMillis = 1000
0f at 0 with LinearEasing
1000f at 1000 with LinearEasing
}
}
) {
if (it) 1000f else 0f
}
val combined = transition.animateFloat(
label = "combined",
transitionSpec = {
combined(
listOf(
0 to keyframes {
durationMillis = 300
0f at 0 with LinearEasing
300f at 300 with LinearEasing
},
300 to keyframes {
durationMillis = 700
300f at 0 with LinearEasing
1000f at 700 with LinearEasing
}
)
)
}
) {
if (it) 1000f else 0f
}
assertWithMessage("at playTimeNanos: ${transition.playTimeNanos}")
.that(combined.value).isWithin(tolerance).of(control.value)
}
rule.runOnIdle { isAtEnd.value = true }
rule.waitForIdle()
}
}
| apache-2.0 |
nextras/orm-intellij | src/main/kotlin/org/nextras/orm/intellij/utils/OrmUtils.kt | 1 | 5501 | package org.nextras.orm.intellij.utils
import com.intellij.openapi.project.Project
import com.jetbrains.php.PhpIndex
import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocProperty
import com.jetbrains.php.lang.psi.elements.*
import com.jetbrains.php.lang.psi.resolve.types.PhpType
import java.util.*
object OrmUtils {
enum class OrmClass constructor(private val className: String) {
COLLECTION("\\Nextras\\Orm\\Collection\\ICollection"),
MAPPER("\\Nextras\\Orm\\Mapper\\IMapper"),
REPOSITORY("\\Nextras\\Orm\\Repository\\IRepository"),
ENTITY("\\Nextras\\Orm\\Entity\\IEntity"),
HAS_MANY("\\Nextras\\Orm\\Relationships\\HasMany"),
EMBEDDABLE("\\Nextras\\Orm\\Entity\\Embeddable\\IEmbeddable");
fun `is`(cls: PhpClass, index: PhpIndex): Boolean {
val classes = index.getAnyByFQN(className)
val instanceOf = when {
classes.isEmpty() -> null
else -> classes.iterator().next()
} ?: return false
return instanceOf.type.isConvertibleFrom(cls.type, index)
}
}
private var isV3: Boolean? = null
fun isV3(project: Project): Boolean {
val index = PhpIndex.getInstance(project)
if (isV3 != null) {
return isV3!!
}
val collectionFunction = index.getInterfacesByFQN("\\Nextras\\Orm\\Collection\\Functions\\IArrayFunction")
isV3 = collectionFunction.isEmpty()
return isV3!!
}
fun findRepositoryEntities(repositories: Collection<PhpClass>): Collection<PhpClass> {
val entities = HashSet<PhpClass>(1)
for (repositoryClass in repositories) {
val entityNamesMethod = repositoryClass.findMethodByName("getEntityClassNames") ?: return emptyList()
if (entityNamesMethod.lastChild !is GroupStatement) {
continue
}
if ((entityNamesMethod.lastChild as GroupStatement).firstPsiChild !is PhpReturn) {
continue
}
if ((entityNamesMethod.lastChild as GroupStatement).firstPsiChild!!.firstPsiChild !is ArrayCreationExpression) {
continue
}
val arr = (entityNamesMethod.lastChild as GroupStatement).firstPsiChild!!.firstPsiChild as ArrayCreationExpression?
val phpIndex = PhpIndex.getInstance(repositoryClass.project)
for (el in arr!!.children) {
if (el.firstChild !is ClassConstantReference) {
continue
}
val ref = el.firstChild as ClassConstantReference
if (ref.name != "class") {
continue
}
entities.addAll(PhpIndexUtils.getByType(ref.classReference!!.type, phpIndex))
}
}
return entities
}
fun findQueriedEntities(ref: MemberReference): Collection<PhpClass> {
val classReference = ref.classReference ?: return emptyList()
val entities = HashSet<PhpClass>()
val phpIndex = PhpIndex.getInstance(ref.project)
val classes = PhpIndexUtils.getByType(classReference.type, phpIndex)
val repositories = classes.filter { cls -> OrmClass.REPOSITORY.`is`(cls, phpIndex) }
if (repositories.isNotEmpty()) {
entities.addAll(findRepositoryEntities(repositories))
}
for (type in classReference.type.types) {
if (!type.endsWith("[]")) {
continue
}
val typeWithoutArray = PhpType().add(type.substring(0, type.length - 2))
val maybeEntities = PhpIndexUtils.getByType(typeWithoutArray, phpIndex)
entities.addAll(
maybeEntities.filter { cls ->
OrmClass.ENTITY.`is`(cls, phpIndex)
}
)
}
return entities
}
fun findQueriedEntities(reference: MethodReference, cls: String?, path: Array<String>): Collection<PhpClass> {
val rootEntities = if (cls == null || cls == "this") {
findQueriedEntities(reference)
} else {
val index = PhpIndex.getInstance(reference.project)
PhpIndexUtils.getByType(PhpType().add(cls), index)
}
if (rootEntities.isEmpty()) {
return emptyList()
}
return when {
path.size <= 1 -> rootEntities
else -> findTargetEntities(rootEntities, path, 0)
}
}
fun parsePathExpression(expression: String, isV3: Boolean): Pair<String?, Array<String>> {
if (isV3) {
val path = expression.split("->")
return when (path.size > 1) {
true -> Pair(
path.first(),
path.drop(1).toTypedArray()
)
false -> Pair(
null,
path.toTypedArray()
)
}
} else {
val delimiterPos = expression.indexOf("::")
val sourceClass = expression.substring(0, delimiterPos.coerceAtLeast(0))
val path = if (delimiterPos == -1) expression else expression.substring((delimiterPos + 2).coerceAtMost(expression.length))
return Pair(
sourceClass.ifEmpty { null },
path.split("->").toTypedArray()
)
}
}
private fun findTargetEntities(currentEntities: Collection<PhpClass>, path: Array<String>, pos: Int): Collection<PhpClass> {
if (path.size == pos + 1) {
return currentEntities
}
val entities = HashSet<PhpClass>()
for (cls in currentEntities) {
val field = cls.findFieldByName(path[pos], false) as? PhpDocProperty ?: continue
addEntitiesFromField(entities, field)
}
return findTargetEntities(entities, path, pos + 1)
}
private fun addEntitiesFromField(entities: MutableCollection<PhpClass>, field: PhpDocProperty) {
val index = PhpIndex.getInstance(field.project)
for (type in field.type.types) {
if (type.contains("Nextras\\Orm\\Relationship")) {
continue
}
val addType = if (type.endsWith("[]")) {
type.substring(0, type.length - 2)
} else {
type
}
for (entityCls in PhpIndexUtils.getByType(PhpType().add(addType), index)) {
if (!OrmClass.ENTITY.`is`(entityCls, index) && !OrmClass.EMBEDDABLE.`is`(entityCls, index)) {
continue
}
entities.add(entityCls)
}
}
}
}
| mit |
btkelly/gnag | example-java-kotlin/src/main/java/com/btkelly/gnag/example/KotlinFileInJavaSourceSet.kt | 2 | 1143 | /**
* Copyright 2016 Bryan Kelly
*
* 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.btkelly.gnag.example
/**
* Created by bobbake4 on 2/7/17.
*/
class KotlinFileInJavaSourceSet {
override fun toString(): String = super.toString()
companion object {
@JvmStatic
fun main(args: Array<String>) {
val test = ""
val testCompare = "Fail"
if (test === testCompare) {
print("Total Fail")
}
try {
print("Empty")
} catch (e: Exception) {
} finally {
}
}
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/template/postfix/templates/GrNegateBooleanPostfixTemplate.kt | 9 | 1079 | // 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.plugins.groovy.codeInsight.template.postfix.templates
import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateProvider
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.groovy.codeInsight.template.postfix.GroovyPostfixTemplateUtils
import org.jetbrains.plugins.groovy.codeInsight.template.postfix.GroovyPostfixTemplateUtils.shouldBeParenthesized
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
class GrNegateBooleanPostfixTemplate(sequence: String, provider: PostfixTemplateProvider) :
GrPostfixTemplateBase(sequence, "!expr", GroovyPostfixTemplateUtils.getBooleanExpressionSelector(), provider) {
override fun getGroovyTemplateString(element: PsiElement): String {
element as GrExpression
val elementText = element.text.let { if (shouldBeParenthesized(element)) "($it)" else it }
return "!$elementText"
}
} | apache-2.0 |
smmribeiro/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/ex/SimpleLocalLineStatusTracker.kt | 9 | 1931 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.ex
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.ex.DocumentTracker.Block
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.annotations.RequiresEdt
class SimpleLocalLineStatusTracker(project: Project,
document: Document,
virtualFile: VirtualFile
) : LocalLineStatusTrackerImpl<Range>(project, document, virtualFile) {
override val renderer: LocalLineStatusMarkerRenderer = LocalLineStatusMarkerRenderer(this)
override fun toRange(block: Block): Range = Range(block.start, block.end, block.vcsStart, block.vcsEnd, block.innerRanges)
@RequiresEdt
override fun setBaseRevision(vcsContent: CharSequence) {
setBaseRevisionContent(vcsContent, null)
}
@Suppress("UNCHECKED_CAST")
override var Block.innerRanges: List<Range.InnerRange>?
get() = data as List<Range.InnerRange>?
set(value) {
data = value
}
companion object {
@JvmStatic
fun createTracker(project: Project,
document: Document,
virtualFile: VirtualFile): SimpleLocalLineStatusTracker {
return SimpleLocalLineStatusTracker(project, document, virtualFile)
}
}
} | apache-2.0 |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/roots/builders/ModuleRootsIndexableIteratorHandler.kt | 1 | 3250 | // 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.util.indexing.roots.builders
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PlatformUtils
import com.intellij.util.indexing.roots.IndexableEntityProvider
import com.intellij.util.indexing.roots.IndexableEntityProviderMethods
import com.intellij.util.indexing.roots.IndexableFilesIterator
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.moduleMap
import com.intellij.workspaceModel.ide.impl.virtualFile
import com.intellij.workspaceModel.ide.isEqualOrParentOf
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleId
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
class ModuleRootsIndexableIteratorHandler : IndexableIteratorBuilderHandler {
override fun accepts(builder: IndexableEntityProvider.IndexableIteratorBuilder): Boolean =
builder is ModuleRootsIteratorBuilder || builder is FullModuleContentIteratorBuilder
override fun instantiate(builders: Collection<IndexableEntityProvider.IndexableIteratorBuilder>,
project: Project,
entityStorage: WorkspaceEntityStorage): List<IndexableFilesIterator> {
val fullIndexedModules: Set<ModuleId> = builders.mapNotNull { (it as? FullModuleContentIteratorBuilder)?.moduleId }.toSet()
@Suppress("UNCHECKED_CAST")
val partialIterators = builders.filter {
it is ModuleRootsIteratorBuilder && !fullIndexedModules.contains(it.moduleId)
} as List<ModuleRootsIteratorBuilder>
val partialIteratorsMap = partialIterators.groupBy { builder -> builder.moduleId }
val result = mutableListOf<IndexableFilesIterator>()
fullIndexedModules.forEach { moduleId ->
entityStorage.resolve(moduleId)?.also { entity ->
result.addAll(IndexableEntityProviderMethods.createIterators(entity, entityStorage, project))
}
}
val moduleMap = entityStorage.moduleMap
partialIteratorsMap.forEach { pair ->
entityStorage.resolve(pair.key)?.also { entity ->
result.addAll(IndexableEntityProviderMethods.createIterators(entity, resolveRoots(pair.value), moduleMap, project))
}
}
return result
}
private fun resolveRoots(builders: List<ModuleRootsIteratorBuilder>): List<VirtualFile> {
if (PlatformUtils.isRider()) {
return builders.flatMap { builder -> builder.urls }.mapNotNull { url -> url.virtualFile }
}
val roots = mutableListOf<VirtualFileUrl>()
for (builder in builders) {
for (root in builder.urls) {
var isChild = false
val it = roots.iterator()
while (it.hasNext()) {
val next = it.next()
if (next.isEqualOrParentOf(root)) {
isChild = true
break
}
if (root.isEqualOrParentOf(next)) {
it.remove()
}
}
if (!isChild) {
roots.add(root)
}
}
}
return roots.mapNotNull { url -> url.virtualFile }
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/changeSignature/jk/jkAddFunctionParameter.after.Dependency.kt | 13 | 50 | open class K {
open fun foo(i: Int) {
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/arguments/util.kt | 2 | 3244 | // 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.gradleTooling.arguments
import org.gradle.api.Task
import org.gradle.api.logging.Logger
import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder
import org.jetbrains.kotlin.idea.gradleTooling.arguments.CompilerArgumentsCachingManager.cacheCompilerArgument
import org.jetbrains.kotlin.idea.gradleTooling.getDeclaredMethodOrNull
import org.jetbrains.kotlin.idea.gradleTooling.getMethodOrNull
import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheMapper
import java.io.File
import java.lang.reflect.Method
private fun buildDependencyClasspath(compileKotlinTask: Task): List<String> {
val abstractKotlinCompileClass =
compileKotlinTask.javaClass.classLoader.loadClass(AbstractKotlinGradleModelBuilder.ABSTRACT_KOTLIN_COMPILE_CLASS)
val getCompileClasspath =
abstractKotlinCompileClass.getDeclaredMethodOrNull("getCompileClasspath") ?: abstractKotlinCompileClass.getDeclaredMethodOrNull(
"getClasspath"
) ?: return emptyList()
@Suppress("UNCHECKED_CAST")
return (getCompileClasspath(compileKotlinTask) as? Collection<File>)?.map { it.path } ?: emptyList()
}
fun buildCachedArgsInfo(
compileKotlinTask: Task,
cacheMapper: CompilerArgumentsCacheMapper,
): CachedExtractedArgsInfo {
val cachedCurrentArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileKotlinTask, cacheMapper, defaultsOnly = false)
val cachedDefaultArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileKotlinTask, cacheMapper, defaultsOnly = true)
val dependencyClasspath = buildDependencyClasspath(compileKotlinTask).map { cacheCompilerArgument(it, cacheMapper) }
return CachedExtractedArgsInfo(cacheMapper.cacheOriginIdentifier, cachedCurrentArguments, cachedDefaultArguments, dependencyClasspath)
}
fun buildSerializedArgsInfo(
compileKotlinTask: Task,
cacheMapper: CompilerArgumentsCacheMapper,
logger: Logger
): CachedSerializedArgsInfo {
val compileTaskClass = compileKotlinTask.javaClass
val getCurrentArguments = compileTaskClass.getMethodOrNull("getSerializedCompilerArguments")
val getDefaultArguments = compileTaskClass.getMethodOrNull("getDefaultSerializedCompilerArguments")
val currentArguments = safelyGetArguments(compileKotlinTask, getCurrentArguments, logger).map { cacheCompilerArgument(it, cacheMapper) }
val defaultArguments = safelyGetArguments(compileKotlinTask, getDefaultArguments, logger).map { cacheCompilerArgument(it, cacheMapper) }
val dependencyClasspath = buildDependencyClasspath(compileKotlinTask).map { cacheCompilerArgument(it, cacheMapper) }
return CachedSerializedArgsInfo(cacheMapper.cacheOriginIdentifier, currentArguments, defaultArguments, dependencyClasspath)
}
@Suppress("UNCHECKED_CAST")
private fun safelyGetArguments(compileKotlinTask: Task, accessor: Method?, logger: Logger) = try {
accessor?.invoke(compileKotlinTask) as? List<String>
} catch (e: Exception) {
logger.warn(e.message ?: "Unexpected exception: $e", e)
null
} ?: emptyList()
| apache-2.0 |
smmribeiro/intellij-community | platform/vcs-api/src/com/intellij/openapi/vcs/checkin/VcsCheckinHandlerFactory.kt | 9 | 2315 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.checkin
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.VcsKey
import com.intellij.openapi.vcs.changes.CommitContext
/**
* Provides VCS-specific [CheckinHandler] to the commit flow.
* This means that handler is only used in the commit flow if commit is performed to VCS with given [key].
*
* @see CheckinHandlerFactory
*/
abstract class VcsCheckinHandlerFactory protected constructor(val key: VcsKey) :
BaseCheckinHandlerFactory {
final override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
if (!panel.vcsIsAffected(key.name)) return CheckinHandler.DUMMY
return createVcsHandler(panel, commitContext)
}
@Deprecated(
"Use `createVcsHandler(CheckinProjectPanel, CommitContext)` instead",
ReplaceWith("createVcsHandler(panel, commitContext)")
)
protected open fun createVcsHandler(panel: CheckinProjectPanel): CheckinHandler = throw AbstractMethodError()
/**
* Creates [CheckinHandler]. Called for each commit operation.
*
* @param panel contains common commit data (e.g. commit message, files to commit)
* @param commitContext contains specific commit data (e.g. if "amend commit" should be performed)
* @return handler instance or [CheckinHandler.DUMMY] if no handler is necessary
*/
protected open fun createVcsHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
@Suppress("DEPRECATION")
return createVcsHandler(panel)
}
/**
* Creates [BeforeCheckinDialogHandler]. Called for each commit operation. Only used for Commit Dialog.
*
* @param project project where commit is performed
* @return handler instance or `null` if no handler is necessary
*/
override fun createSystemReadyHandler(project: Project): BeforeCheckinDialogHandler? = null
companion object {
@JvmStatic
val EP_NAME: ExtensionPointName<VcsCheckinHandlerFactory> = ExtensionPointName.create("com.intellij.vcsCheckinHandlerFactory")
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/tests/test/org/jetbrains/kotlin/tools/projectWizard/wizard/services/FormattingTestWizardService.kt | 6 | 535 | // 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.tools.projectWizard.wizard.services
import org.jetbrains.kotlin.tools.projectWizard.cli.TestWizardService
import org.jetbrains.kotlin.tools.projectWizard.core.service.FileFormattingService
class FormattingTestWizardService : FileFormattingService, TestWizardService {
override fun formatFile(text: String, filename: String): String = text
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/deprecatedCallableAddReplaceWith/Simple.kt | 13 | 59 | <caret>@Deprecated("")
fun foo() {
bar()
}
fun bar(){} | apache-2.0 |
zielu/GitToolBox | src/main/kotlin/zielu/gittoolbox/cache/LazyRepoChangeAware.kt | 1 | 334 | package zielu.gittoolbox.cache
import git4idea.repo.GitRepository
internal class LazyRepoChangeAware<out T : RepoChangeAware> (
supplier: () -> T
) : RepoChangeAware {
private val delegate: T by lazy {
supplier.invoke()
}
override fun repoChanged(repository: GitRepository) {
delegate.repoChanged(repository)
}
}
| apache-2.0 |
devjn/GithubSearch | app/src/main/kotlin/com/github/devjn/githubsearch/widgets/StaticGridView.kt | 1 | 693 | package com.github.devjn.githubsearch.widgets
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.GridView
class StaticGridView : GridView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
public override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(View.MEASURED_SIZE_MASK, MeasureSpec.AT_MOST))
layoutParams.height = measuredHeight
}
} | apache-2.0 |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt | 1 | 5601 | package info.nightscout.androidaps.plugins.general.automation.triggers
import android.location.Location
import android.widget.LinearLayout
import com.google.common.base.Optional
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.general.automation.elements.*
import info.nightscout.androidaps.utils.JsonHelper
import org.json.JSONObject
import java.text.DecimalFormat
class TriggerLocation(injector: HasAndroidInjector) : Trigger(injector) {
var latitude = InputDouble(injector, 0.0, -90.0, +90.0, 0.000001, DecimalFormat("0.000000"))
var longitude = InputDouble(injector, 0.0, -180.0, +180.0, 0.000001, DecimalFormat("0.000000"))
var distance = InputDouble(injector, 200.0, 0.0, 100000.0, 10.0, DecimalFormat("0"))
var modeSelected = InputLocationMode(injector)
var name: InputString = InputString(injector)
var lastMode = InputLocationMode.Mode.INSIDE
private val buttonAction = Runnable {
locationDataContainer.lastLocation?.let {
latitude.setValue(it.latitude)
longitude.setValue(it.longitude)
aapsLogger.debug(LTag.AUTOMATION, String.format("Grabbed location: %f %f", latitude.value, longitude.value))
}
}
private constructor(injector: HasAndroidInjector, triggerLocation: TriggerLocation) : this(injector) {
latitude = InputDouble(injector, triggerLocation.latitude)
longitude = InputDouble(injector, triggerLocation.longitude)
distance = InputDouble(injector, triggerLocation.distance)
modeSelected = InputLocationMode(injector, triggerLocation.modeSelected.value)
if (modeSelected.value == InputLocationMode.Mode.GOING_OUT)
lastMode = InputLocationMode.Mode.OUTSIDE
name = triggerLocation.name
}
@Synchronized override fun shouldRun(): Boolean {
val location: Location = locationDataContainer.lastLocation ?: return false
val a = Location("Trigger")
a.latitude = latitude.value
a.longitude = longitude.value
val calculatedDistance = location.distanceTo(a).toDouble()
if (modeSelected.value == InputLocationMode.Mode.INSIDE && calculatedDistance <= distance.value ||
modeSelected.value == InputLocationMode.Mode.OUTSIDE && calculatedDistance > distance.value ||
modeSelected.value == InputLocationMode.Mode.GOING_IN && calculatedDistance <= distance.value && lastMode == InputLocationMode.Mode.OUTSIDE ||
modeSelected.value == InputLocationMode.Mode.GOING_OUT && calculatedDistance > distance.value && lastMode == InputLocationMode.Mode.INSIDE) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
lastMode = currentMode(calculatedDistance)
return true
}
lastMode = currentMode(calculatedDistance) // current mode will be last mode for the next check
aapsLogger.debug(LTag.AUTOMATION, "NOT ready for execution: " + friendlyDescription())
return false
}
override fun toJSON(): String {
val data = JSONObject()
.put("latitude", latitude.value)
.put("longitude", longitude.value)
.put("distance", distance.value)
.put("name", name.value)
.put("mode", modeSelected.value)
return JSONObject()
.put("type", this::class.java.name)
.put("data", data)
.toString()
}
override fun fromJSON(data: String): Trigger {
val d = JSONObject(data)
latitude.value = JsonHelper.safeGetDouble(d, "latitude")
longitude.value = JsonHelper.safeGetDouble(d, "longitude")
distance.value = JsonHelper.safeGetDouble(d, "distance")
name.value = JsonHelper.safeGetString(d, "name")!!
modeSelected.value = InputLocationMode.Mode.valueOf(JsonHelper.safeGetString(d, "mode")!!)
if (modeSelected.value == InputLocationMode.Mode.GOING_OUT) lastMode = InputLocationMode.Mode.OUTSIDE
return this
}
override fun friendlyName(): Int = R.string.location
override fun friendlyDescription(): String =
resourceHelper.gs(R.string.locationis, resourceHelper.gs(modeSelected.value.stringRes), " " + name.value)
override fun icon(): Optional<Int?> = Optional.of(R.drawable.ic_location_on)
override fun duplicate(): Trigger = TriggerLocation(injector, this)
override fun generateDialog(root: LinearLayout) {
LayoutBuilder()
.add(StaticLabel(injector, R.string.location, this))
.add(LabelWithElement(injector, resourceHelper.gs(R.string.name_short), "", name))
.add(LabelWithElement(injector, resourceHelper.gs(R.string.latitude_short), "", latitude))
.add(LabelWithElement(injector, resourceHelper.gs(R.string.longitude_short), "", longitude))
.add(LabelWithElement(injector, resourceHelper.gs(R.string.distance_short), "", distance))
.add(LabelWithElement(injector, resourceHelper.gs(R.string.location_mode), "", modeSelected))
.add(InputButton(injector, resourceHelper.gs(R.string.currentlocation), buttonAction), locationDataContainer.lastLocation != null)
.build(root)
}
// Method to return the actual mode based on the current distance
fun currentMode(currentDistance: Double): InputLocationMode.Mode {
return if (currentDistance <= distance.value) InputLocationMode.Mode.INSIDE else InputLocationMode.Mode.OUTSIDE
}
} | agpl-3.0 |
dev-cloverlab/Kloveroid | app/src/main/kotlin/com/cloverlab/kloveroid/mvp/presenters/BasePresenter.kt | 1 | 655 | package com.cloverlab.kloveroid.mvp.presenters
import com.cloverlab.kloveroid.mvp.views.IView
import com.trello.rxlifecycle3.LifecycleProvider
/**
* @author Jieyi Wu
* @since 2017/09/28
*/
abstract class BasePresenter<V : IView> : IPresenter {
open lateinit var view: V
protected lateinit var lifecycleProvider: LifecycleProvider<*>
override fun <E> create(lifecycleProvider: LifecycleProvider<E>) {
this.lifecycleProvider = lifecycleProvider
}
override fun init() {}
override fun start() {}
override fun resume() {}
override fun pause() {}
override fun stop() {}
override fun destroy() {}
}
| mit |
kohesive/kohesive-iac | model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredDataPipeline.kt | 1 | 1119 | package uy.kohesive.iac.model.aws.clients
import com.amazonaws.services.datapipeline.AbstractDataPipeline
import com.amazonaws.services.datapipeline.DataPipeline
import com.amazonaws.services.datapipeline.model.*
import uy.kohesive.iac.model.aws.IacContext
import uy.kohesive.iac.model.aws.proxy.makeProxy
open class BaseDeferredDataPipeline(val context: IacContext) : AbstractDataPipeline(), DataPipeline {
override fun addTags(request: AddTagsRequest): AddTagsResult {
return with (context) {
request.registerWithAutoName()
AddTagsResult().registerWithSameNameAs(request)
}
}
override fun createPipeline(request: CreatePipelineRequest): CreatePipelineResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreatePipelineRequest, CreatePipelineResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
}
class DeferredDataPipeline(context: IacContext) : BaseDeferredDataPipeline(context)
| mit |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/activities/VideoActivity.kt | 1 | 6356 | package com.kickstarter.ui.activities
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.source.hls.HlsMediaSource
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource
import com.google.android.exoplayer2.util.Util
import com.kickstarter.R
import com.kickstarter.databinding.VideoPlayerLayoutBinding
import com.kickstarter.libs.BaseActivity
import com.kickstarter.libs.Build
import com.kickstarter.libs.qualifiers.RequiresActivityViewModel
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.libs.utils.WebUtils.userAgent
import com.kickstarter.ui.IntentKey
import com.kickstarter.viewmodels.VideoViewModel
import com.trello.rxlifecycle.ActivityEvent
@RequiresActivityViewModel(VideoViewModel.ViewModel::class)
class VideoActivity : BaseActivity<VideoViewModel.ViewModel>() {
private lateinit var build: Build
private var player: SimpleExoPlayer? = null
private var playerPosition: Long? = null
private var trackSelector: DefaultTrackSelector? = null
private lateinit var binding: VideoPlayerLayoutBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = VideoPlayerLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
build = requireNotNull(environment().build())
val fullscreenButton: ImageView = binding.playerView.findViewById(R.id.exo_fullscreen_icon)
fullscreenButton.setImageResource(R.drawable.ic_fullscreen_close)
fullscreenButton.setOnClickListener {
back()
}
viewModel.outputs.preparePlayerWithUrl()
.compose(Transformers.takeWhen(lifecycle().filter { other: ActivityEvent? -> ActivityEvent.RESUME.equals(other) }))
.compose(bindToLifecycle())
.subscribe { preparePlayer(it) }
viewModel.outputs.preparePlayerWithUrlAndPosition()
.compose(Transformers.takeWhen(lifecycle().filter { other: ActivityEvent? -> ActivityEvent.RESUME.equals(other) }))
.compose(bindToLifecycle())
.subscribe {
playerPosition = it.second
preparePlayer(it.first)
}
}
public override fun onDestroy() {
super.onDestroy()
releasePlayer()
}
public override fun onPause() {
super.onPause()
releasePlayer()
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
binding.videoPlayerLayout.systemUiVisibility = systemUIFlags()
}
}
override fun back() {
val intent = Intent()
.putExtra(IntentKey.VIDEO_SEEK_POSITION, player?.currentPosition)
setResult(Activity.RESULT_OK, intent)
finish()
}
private fun systemUIFlags(): Int {
return (
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_IMMERSIVE
)
}
private fun onStateChanged(playbackState: Int) {
if (playbackState == Player.STATE_READY) {
player?.duration?.let {
viewModel.inputs.onVideoStarted(it, playerPosition ?: 0L)
}
}
if (playbackState == Player.STATE_ENDED) {
finish()
}
if (playbackState == Player.STATE_BUFFERING) {
binding.loadingIndicator.visibility = View.VISIBLE
} else {
binding.loadingIndicator.visibility = View.GONE
}
}
private fun preparePlayer(videoUrl: String) {
val adaptiveTrackSelectionFactory: AdaptiveTrackSelection.Factory = AdaptiveTrackSelection.Factory()
trackSelector = DefaultTrackSelector(this, adaptiveTrackSelectionFactory)
// player = ExoPlayerFactory.newSimpleInstance(this, trackSelector)
val player2 = trackSelector?.let {
SimpleExoPlayer.Builder(this).setTrackSelector(
it
)
}
val playerBuilder = SimpleExoPlayer.Builder(this)
trackSelector?.let { playerBuilder.setTrackSelector(it) }
player = playerBuilder.build()
binding.playerView.player = player
player?.addListener(eventListener)
val playerIsResuming = (playerPosition != 0L)
player?.prepare(getMediaSource(videoUrl), playerIsResuming, false)
playerPosition?.let {
player?.seekTo(it)
}
player?.playWhenReady = true
}
private fun getMediaSource(videoUrl: String): MediaSource {
val dataSourceFactory = DefaultHttpDataSource.Factory().setUserAgent(userAgent(build))
val videoUri = Uri.parse(videoUrl)
val fileType = Util.inferContentType(videoUri)
return if (fileType == C.TYPE_HLS) {
HlsMediaSource.Factory(dataSourceFactory).createMediaSource(MediaItem.fromUri(videoUri))
} else {
ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(MediaItem.fromUri(videoUri))
}
}
private fun releasePlayer() {
if (player != null) {
playerPosition = player?.currentPosition
player?.duration?.let {
viewModel.inputs.onVideoCompleted(it, playerPosition ?: 0L)
}
player?.removeListener(eventListener)
player?.release()
trackSelector = null
player = null
}
}
private val eventListener: Player.Listener = object : Player.Listener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
onStateChanged(playbackState)
}
}
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/swapBinaryExpression/multipleOperandsWithDifferentPrecedence5.kt | 4 | 52 | fun main() {
val rabbit = 4 + 2 * 5 <caret>+ 1
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/compiler-plugins/parcelize/tests/testData/quickfix/deleteIncompatible/creatorField.kt | 3 | 880 | // "Remove custom ''CREATOR'' property" "true"
// ERROR: Overriding 'writeToParcel' is not allowed. Use 'Parceler' companion object instead
// WITH_RUNTIME
package com.myapp.activity
import android.os.*
import kotlinx.parcelize.Parcelize
@Parcelize
class Foo(val a: String) : Parcelable {
constructor(parcel: Parcel) : this(parcel.readString()) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(a)
}
override fun describeContents(): Int {
return 0
}
companion object {
@JvmField
val <caret>CREATOR = object : Parcelable.Creator<Foo> {
override fun createFromParcel(parcel: Parcel): Foo {
return Foo(parcel)
}
override fun newArray(size: Int): Array<Foo?> {
return arrayOfNulls(size)
}
}
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/multiModule/common/transitiveInlining/module2_b.kt | 5 | 101 | package b
inline fun b(body: () -> Unit) {
a.a { println("to be inlined into b") }
body()
}
| apache-2.0 |
lsmaira/gradle | buildSrc/subprojects/buildquality/src/main/kotlin/org/gradle/gradlebuild/buildquality/TaskPropertyValidationPlugin.kt | 1 | 3291 | /*
* Copyright 2018 the original author or authors.
*
* 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.gradle.gradlebuild.buildquality
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.plugins.JavaBasePlugin
import org.gradle.api.plugins.JavaLibraryPlugin
import org.gradle.api.tasks.testing.Test
import org.gradle.plugin.devel.tasks.ValidateTaskProperties
import accessors.java
import accessors.reporting
import org.gradle.kotlin.dsl.*
private
const val validateTaskName = "validateTaskProperties"
private
const val reportFileName = "task-properties/report.txt"
open class TaskPropertyValidationPlugin : Plugin<Project> {
override fun apply(project: Project): Unit = project.run {
plugins.withType<JavaBasePlugin> {
validateTaskPropertiesForConfiguration(configurations["compile"])
}
plugins.withType<JavaLibraryPlugin> {
validateTaskPropertiesForConfiguration(configurations["api"])
}
}
}
private
fun Project.validateTaskPropertiesForConfiguration(configuration: Configuration) =
project(":core").let { coreProject ->
// Apply to all projects depending on :core
// TODO Add a comment on why those projects.
when (this) {
coreProject -> addValidateTask()
else -> {
configuration.dependencies.withType<ProjectDependency>()
.matching { it.dependencyProject == coreProject }
.all {
addValidateTask()
}
}
}
}
private
fun Project.addValidateTask() =
afterEvaluate {
// This block gets called twice for the core project as core applies the base as well as the library plugin. That is why we need to check
// whether the task already exists.
if (tasks.findByName(validateTaskName) == null) {
val validateTask = tasks.register(validateTaskName, ValidateTaskProperties::class) {
val main by java.sourceSets
dependsOn(main.output)
classes = main.output.classesDirs
classpath = main.runtimeClasspath
// TODO Should we provide a more intuitive way in the task definition to configure this property from Kotlin?
outputFile.set(reporting.baseDirectory.file(reportFileName))
failOnWarning = true
}
tasks.named("codeQuality").configure {
dependsOn(validateTask)
}
tasks.withType(Test::class).configureEach {
shouldRunAfter(validateTask)
}
}
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AbstractReferenceSubstitutionRenameHandler.kt | 1 | 3385 | // 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.application.ApplicationManager
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.PsiWhiteSpace
import com.intellij.refactoring.rename.PsiElementRenameHandler
import com.intellij.refactoring.rename.RenameHandler
import com.intellij.refactoring.rename.inplace.MemberInplaceRenameHandler
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
abstract class AbstractReferenceSubstitutionRenameHandler(
private val delegateHandler: RenameHandler = MemberInplaceRenameHandler()
) : PsiElementRenameHandler() {
companion object {
fun getReferenceExpression(file: PsiFile, offset: Int): KtSimpleNameExpression? {
var elementAtCaret = file.findElementAt(offset) ?: return null
if (elementAtCaret.node?.elementType == KtTokens.AT) return null
if (elementAtCaret is PsiWhiteSpace) {
elementAtCaret = CodeInsightUtils.getElementAtOffsetIgnoreWhitespaceAfter(file, offset) ?: return null
if (offset != elementAtCaret.endOffset) return null
}
return elementAtCaret.getNonStrictParentOfType<KtSimpleNameExpression>()
}
fun getReferenceExpression(dataContext: DataContext): KtSimpleNameExpression? {
val caret = CommonDataKeys.CARET.getData(dataContext) ?: return null
val ktFile = CommonDataKeys.PSI_FILE.getData(dataContext) as? KtFile ?: return null
return getReferenceExpression(ktFile, caret.offset)
}
}
protected abstract fun getElementToRename(dataContext: DataContext): PsiElement?
override fun isAvailableOnDataContext(dataContext: DataContext): Boolean {
return CommonDataKeys.EDITOR.getData(dataContext) != null && getElementToRename(dataContext) != null
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?, dataContext: DataContext) {
val elementToRename = getElementToRename(dataContext) ?: return
val wrappingContext = DataContext { id ->
if (CommonDataKeys.PSI_ELEMENT.`is`(id)) return@DataContext elementToRename
dataContext.getData(id)
}
// Can't provide new name for inplace refactoring in unit test mode
if (!ApplicationManager.getApplication().isUnitTestMode && delegateHandler.isAvailableOnDataContext(wrappingContext)) {
delegateHandler.invoke(project, editor, file, wrappingContext)
} else {
super.invoke(project, editor, file, wrappingContext)
}
}
override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext) {
// Can't be invoked outside of a text editor
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/classHierarchyAffected/varianceChanged/A.kt | 5 | 20 | class A<in T>(x: T)
| apache-2.0 |
vovagrechka/fucking-everything | pieces/pieces-100/src/main/java/pieces100/Wilma.kt | 1 | 6413 | package pieces100
import alraune.*
import bolone.test.Test_Wilma
import com.fasterxml.jackson.annotation.JsonFilter
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.*
import com.fasterxml.jackson.databind.jsontype.TypeSerializer
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.ser.PropertyWriter
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import vgrechka.*
import java.sql.Timestamp
import kotlin.reflect.KClass
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.memberProperties
@TestRefs(Test_Wilma::class)
object Wilma {
val typeProperty = "@type"
private val insecureMapper = ObjectMapper().also {
it.setDefaultTyping(object : ObjectMapper.DefaultTypeResolverBuilder(ObjectMapper.DefaultTyping.NON_FINAL) {
init {
init(JsonTypeInfo.Id.CLASS, null)
inclusion(JsonTypeInfo.As.PROPERTY)
typeProperty([email protected])
}
override fun useForType(t: JavaType): Boolean {
if (t.isContainerType) return false
if (t.rawClass == java.lang.Long::class.java) return false
if (t.rawClass == JSLong::class.java) return false
if (t.rawClass == Timestamp::class.java) return false
if (t.isEnumType) return false
return true
}
})
it.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
it.registerModule(SimpleModule().also {
it.addSerializer(java.lang.Long::class.java, object : StdSerializer<java.lang.Long>(java.lang.Long::class.java) {
override fun serialize(value: java.lang.Long, gen: JsonGenerator, provider: SerializerProvider) {
fart(gen, value)
}
override fun serializeWithType(value: java.lang.Long, gen: JsonGenerator, serializers: SerializerProvider, typeSer: TypeSerializer) {
fart(gen, value)
}
private fun fart(gen: JsonGenerator, value: java.lang.Long) {
gen.writeString(value.toString())
}
})
it.addSerializer(Long::class.java, object : StdSerializer<Long>(Long::class.java) {
override fun serialize(value: Long, gen: JsonGenerator, provider: SerializerProvider) {
fart(gen, value)
}
override fun serializeWithType(value: Long, gen: JsonGenerator, serializers: SerializerProvider, typeSer: TypeSerializer) {
return fart(gen, value)
}
private fun fart(gen: JsonGenerator, value: Long) {
gen.writeString(value.toString())
}
})
it.addSerializer(JSLong::class.java, object : StdSerializer<JSLong>(JSLong::class.java) {
override fun serialize(value: JSLong, gen: JsonGenerator, provider: SerializerProvider) {
fart(gen, value)
}
override fun serializeWithType(value: JSLong, gen: JsonGenerator, serializers: SerializerProvider, typeSer: TypeSerializer) {
return fart(gen, value)
}
private fun fart(gen: JsonGenerator, value: JSLong) {
gen.writeNumber(value.value)
}
})
it.addSerializer(Timestamp::class.java, object : StdSerializer<Timestamp>(Timestamp::class.java) {
override fun serialize(value: Timestamp, gen: JsonGenerator, provider: SerializerProvider) {
fart(gen, value)
}
override fun serializeWithType(value: Timestamp, gen: JsonGenerator, serializers: SerializerProvider, typeSer: TypeSerializer) {
fart(gen, value)
}
private fun fart(gen: JsonGenerator, value: Timestamp) {
checkJSLong(value.time)
gen.writeStartObject()
gen.writeStringField(typeProperty, "alraunets.Timestamp")
gen.writeNumberField("time", value.time)
gen.writeEndObject()
}
})
it.addSerializer(Enum::class.java, object : StdSerializer<Enum<*>>(Enum::class.java) {
override fun serialize(value: Enum<*>, gen: JsonGenerator, provider: SerializerProvider) {
fart(gen, value)
}
override fun serializeWithType(value: Enum<*>, gen: JsonGenerator, serializers: SerializerProvider, typeSer: TypeSerializer) {
fart(gen, value)
}
private fun fart(gen: JsonGenerator, value: Enum<*>) {
gen.writeString(value.name)
}
})
})
@JsonFilter("6abd3b2c-1a93-4358-a43a-a0c4e9bc8eea")
class Mixin
it.addMixIn(java.lang.Object::class.java, Mixin::class.java)
}
val filteredWriter = insecureMapper.writer(SimpleFilterProvider().also {
it.addFilter("6abd3b2c-1a93-4358-a43a-a0c4e9bc8eea", object : SimpleBeanPropertyFilter() {
override fun serializeAsField(pojo: Any?, jgen: JsonGenerator, provider: SerializerProvider, writer: PropertyWriter) {
val member = writer.member
if (member != null) { // There is no members when writing, for example, Map
val prop = member.declaringClass.kotlin.memberProperties.first {it.name == writer.name}
if (prop.findAnnotation<AdminField>() != null)
if (!isAdmin())
return
}
super.serializeAsField(pojo, jgen, provider, writer)
}
})
})
fun <T : Any> readValue(json: String, cls: KClass<T>): T = insecureMapper.readValue(json, cls.java)!!
fun writeValue(x: Any): String = filteredWriter.writeValueAsString(x)
fun writeValuePretty(x: Any): String = filteredWriter.withDefaultPrettyPrinter().writeValueAsString(x)
}
| apache-2.0 |
jwren/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/data/VcsUserRegistryImpl.kt | 2 | 4952 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.data
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.util.containers.HashSetInterner
import com.intellij.util.containers.Interner
import com.intellij.util.io.IOUtil
import com.intellij.util.io.KeyDescriptor
import com.intellij.util.io.PersistentBTreeEnumerator
import com.intellij.util.io.PersistentEnumeratorBase
import com.intellij.util.io.storage.AbstractStorage
import com.intellij.vcs.log.VcsUser
import com.intellij.vcs.log.VcsUserRegistry
import com.intellij.vcs.log.impl.VcsUserImpl
import java.io.DataInput
import java.io.DataOutput
import java.io.File
import java.io.IOException
import java.util.concurrent.atomic.AtomicReference
class VcsUserRegistryImpl internal constructor(project: Project) : Disposable, VcsUserRegistry {
private val _persistentEnumerator = AtomicReference<PersistentEnumeratorBase<VcsUser>?>()
private val persistentEnumerator: PersistentEnumeratorBase<VcsUser>?
get() = _persistentEnumerator.get()
private val interner: Interner<VcsUser>
private val mapFile = File(USER_CACHE_APP_DIR, project.locationHash + "." + STORAGE_VERSION)
init {
initEnumerator()
interner = HashSetInterner()
}
private fun initEnumerator(): Boolean {
try {
val enumerator = IOUtil.openCleanOrResetBroken({
PersistentBTreeEnumerator(mapFile.toPath(), VcsUserKeyDescriptor(this),
AbstractStorage.PAGE_SIZE, null, STORAGE_VERSION)
}, mapFile)
val wasSet = _persistentEnumerator.compareAndSet(null, enumerator)
if (!wasSet) {
LOG.error("Could not assign newly opened enumerator")
enumerator?.close()
}
return wasSet
}
catch (e: IOException) {
LOG.warn(e)
}
return false
}
override fun createUser(name: String, email: String): VcsUser {
synchronized(interner) {
return interner.intern(VcsUserImpl(name, email))
}
}
fun addUser(user: VcsUser) {
try {
persistentEnumerator?.enumerate(user)
}
catch (e: IOException) {
LOG.warn(e)
rebuild()
}
}
fun addUsers(users: Collection<VcsUser>) {
for (user in users) {
addUser(user)
}
}
override fun getUsers(): Set<VcsUser> {
return try {
persistentEnumerator?.getAllDataObjects { true }?.toMutableSet() ?: emptySet()
}
catch (e: IOException) {
LOG.warn(e)
rebuild()
emptySet()
}
catch (pce: ProcessCanceledException) {
throw pce
}
catch (t: Throwable) {
LOG.error(t)
emptySet()
}
}
fun all(condition: (t: VcsUser) -> Boolean): Boolean {
return try {
persistentEnumerator?.iterateData(condition) ?: false
}
catch (e: IOException) {
LOG.warn(e)
rebuild()
false
}
catch (pce: ProcessCanceledException) {
throw pce
}
catch (t: Throwable) {
LOG.error(t)
false
}
}
private fun rebuild() {
if (persistentEnumerator?.isCorrupted == true) {
_persistentEnumerator.getAndSet(null)?.let { oldEnumerator ->
ApplicationManager.getApplication().executeOnPooledThread {
try {
oldEnumerator.close()
}
catch (_: IOException) {
}
finally {
initEnumerator()
}
}
}
}
}
fun flush() {
persistentEnumerator?.force()
}
override fun dispose() {
try {
persistentEnumerator?.close()
}
catch (e: IOException) {
LOG.warn(e)
}
}
companion object {
private val LOG = Logger.getInstance(VcsUserRegistryImpl::class.java)
private val USER_CACHE_APP_DIR = File(PathManager.getSystemPath(), "vcs-users")
private const val STORAGE_VERSION = 2
}
}
class VcsUserKeyDescriptor(private val userRegistry: VcsUserRegistry) : KeyDescriptor<VcsUser> {
@Throws(IOException::class)
override fun save(out: DataOutput, value: VcsUser) {
IOUtil.writeUTF(out, value.name)
IOUtil.writeUTF(out, value.email)
}
@Throws(IOException::class)
override fun read(`in`: DataInput): VcsUser {
val name = IOUtil.readUTF(`in`)
val email = IOUtil.readUTF(`in`)
return userRegistry.createUser(name, email)
}
override fun getHashCode(value: VcsUser): Int {
return value.hashCode()
}
override fun isEqual(val1: VcsUser, val2: VcsUser): Boolean {
return val1 == val2
}
}
| apache-2.0 |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/model/VirtualStorageDevice.kt | 2 | 1925 | package com.github.kerubistan.kerub.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonTypeName
import com.fasterxml.jackson.annotation.JsonView
import com.github.kerubistan.kerub.model.expectations.VirtualStorageDeviceReference
import com.github.kerubistan.kerub.model.expectations.VirtualStorageExpectation
import com.github.kerubistan.kerub.model.index.Indexed
import com.github.kerubistan.kerub.model.views.Simple
import com.github.kerubistan.kerub.utils.validateSize
import io.github.kerubistan.kroki.collections.concat
import org.hibernate.search.annotations.DocumentId
import org.hibernate.search.annotations.Field
import java.math.BigInteger
import java.util.UUID
import kotlin.reflect.KClass
@JsonTypeName("virtual-storage")
data class
VirtualStorageDevice(
@DocumentId
@JsonProperty("id")
override val id: UUID = UUID.randomUUID(),
@Field
val size: BigInteger,
@Field
val readOnly: Boolean = false,
@Field
override
val expectations: List<VirtualStorageExpectation> = listOf(),
@Field
override
val name: String,
@Field
@JsonView(Simple::class)
@JsonProperty("owner")
override val owner: AssetOwner? = null,
override val recycling: Boolean = false
) : Entity<UUID>, Constrained<VirtualStorageExpectation>, Named, Asset, Recyclable, Indexed<VirtualStorageDeviceIndex> {
init {
size.validateSize("size")
}
override fun references(): Map<KClass<out Asset>, List<UUID>> {
val mapOf: Map<KClass<out Asset>, List<UUID>> = mapOf(
VirtualStorageDevice::class to expectations
.filter { it is VirtualStorageDeviceReference }
.map { (it as VirtualStorageDeviceReference).virtualStorageDeviceReferences }
.concat()
)
return mapOf.filter { it.value.isNotEmpty() }
}
@get:JsonIgnore
override val index by lazy { VirtualStorageDeviceIndex(this) }
} | apache-2.0 |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/KotlinFunctionParameterInfoHandler.kt | 1 | 26964 | // 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.parameterInfo
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.lang.parameterInfo.*
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.project.Project
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.ui.Gray
import com.intellij.ui.JBColor
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.completion.canBeUsedWithoutNameInCall
import org.jetbrains.kotlin.idea.core.OptionalParametersHelper
import org.jetbrains.kotlin.idea.core.resolveCandidates
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.util.ShadowedDeclarationsFilter
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.NULLABILITY_ANNOTATIONS
import org.jetbrains.kotlin.load.java.sam.SamAdapterDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.calls.util.getCall
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.components.hasDefaultValue
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.DelegatingCall
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.containsError
import org.jetbrains.kotlin.utils.checkWithAttachment
import java.awt.Color
import kotlin.reflect.KClass
class KotlinFunctionParameterInfoHandler :
KotlinParameterInfoWithCallHandlerBase<KtValueArgumentList, KtValueArgument>(KtValueArgumentList::class, KtValueArgument::class) {
override fun getActualParameters(arguments: KtValueArgumentList) = arguments.arguments.toTypedArray()
override fun getActualParametersRBraceType(): KtSingleValueToken = KtTokens.RPAR
override fun getArgumentListAllowedParentClasses() = setOf(KtCallElement::class.java)
}
class KotlinLambdaParameterInfoHandler :
KotlinParameterInfoWithCallHandlerBase<KtLambdaArgument, KtLambdaArgument>(KtLambdaArgument::class, KtLambdaArgument::class) {
override fun getActualParameters(lambdaArgument: KtLambdaArgument) = arrayOf(lambdaArgument)
override fun getActualParametersRBraceType(): KtSingleValueToken = KtTokens.RBRACE
override fun getArgumentListAllowedParentClasses() = setOf(KtLambdaArgument::class.java)
override fun getParameterIndex(context: UpdateParameterInfoContext, argumentList: KtLambdaArgument): Int {
val size = (argumentList.parent as? KtCallElement)?.valueArguments?.size ?: 1
return size - 1
}
}
class KotlinArrayAccessParameterInfoHandler :
KotlinParameterInfoWithCallHandlerBase<KtContainerNode, KtExpression>(KtContainerNode::class, KtExpression::class) {
override fun getArgumentListAllowedParentClasses() = setOf(KtArrayAccessExpression::class.java)
override fun getActualParameters(containerNode: KtContainerNode): Array<out KtExpression> =
containerNode.allChildren.filterIsInstance<KtExpression>().toList().toTypedArray()
override fun getActualParametersRBraceType(): KtSingleValueToken = KtTokens.RBRACKET
}
abstract class KotlinParameterInfoWithCallHandlerBase<TArgumentList : KtElement, TArgument : KtElement>(
private val argumentListClass: KClass<TArgumentList>,
private val argumentClass: KClass<TArgument>
) : ParameterInfoHandlerWithTabActionSupport<TArgumentList, KotlinParameterInfoWithCallHandlerBase.CallInfo, TArgument> {
companion object {
@JvmField
val GREEN_BACKGROUND: Color = JBColor(Color(231, 254, 234), Gray._100)
val STOP_SEARCH_CLASSES: Set<Class<out KtElement>> = setOf(
KtNamedFunction::class.java,
KtVariableDeclaration::class.java,
KtValueArgumentList::class.java,
KtLambdaArgument::class.java,
KtContainerNode::class.java,
KtTypeArgumentList::class.java
)
private val RENDERER = DescriptorRenderer.SHORT_NAMES_IN_TYPES.withOptions {
enhancedTypes = true
renderUnabbreviatedType = false
}
}
private fun findCall(argumentList: TArgumentList, bindingContext: BindingContext): Call? {
return (argumentList.parent as? KtElement)?.getCall(bindingContext)
}
override fun getActualParameterDelimiterType(): KtSingleValueToken = KtTokens.COMMA
override fun getArgListStopSearchClasses(): Set<Class<out KtElement>> = STOP_SEARCH_CLASSES
override fun getArgumentListClass() = argumentListClass.java
override fun showParameterInfo(element: TArgumentList, context: CreateParameterInfoContext) {
context.showHint(element, element.textRange.startOffset, this)
}
override fun findElementForUpdatingParameterInfo(context: UpdateParameterInfoContext): TArgumentList? {
val element = context.file.findElementAt(context.offset) ?: return null
val argumentList = PsiTreeUtil.getParentOfType(element, argumentListClass.java) ?: return null
val argument = element.parents.takeWhile { it != argumentList }.lastOrNull()
if (argument != null && !argumentClass.java.isInstance(argument)) {
val arguments = getActualParameters(argumentList)
val index = arguments.indexOf(element)
context.setCurrentParameter(index)
context.highlightedParameter = element
}
return argumentList
}
override fun findElementForParameterInfo(context: CreateParameterInfoContext): TArgumentList? {
//todo: calls to this constructors, when we will have auxiliary constructors
val file = context.file as? KtFile ?: return null
val token = file.findElementAt(context.offset) ?: return null
val argumentList = PsiTreeUtil.getParentOfType(token, argumentListClass.java, true, *STOP_SEARCH_CLASSES.toTypedArray())
?: return null
val bindingContext = argumentList.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val call = findCall(argumentList, bindingContext) ?: return null
val resolutionFacade = file.getResolutionFacade()
val candidates =
call.resolveCandidates(bindingContext, resolutionFacade)
.map { it.resultingDescriptor }
.distinctBy { it.original }
val shadowedDeclarationsFilter = ShadowedDeclarationsFilter(
bindingContext,
resolutionFacade,
call.callElement,
call.explicitReceiver as? ReceiverValue
)
context.itemsToShow = shadowedDeclarationsFilter.filter(candidates).map { CallInfo(it) }.toTypedArray()
return argumentList
}
override fun updateParameterInfo(argumentList: TArgumentList, context: UpdateParameterInfoContext) {
if (context.parameterOwner !== argumentList) {
context.removeHint()
}
val parameterIndex = getParameterIndex(context, argumentList)
context.setCurrentParameter(parameterIndex)
runReadAction {
val resolutionFacade = argumentList.getResolutionFacade()
val bindingContext = argumentList.safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL)
val call = findCall(argumentList, bindingContext) ?: return@runReadAction
context.objectsToView.forEach { resolveCallInfo(it as CallInfo, call, bindingContext, resolutionFacade, parameterIndex) }
}
}
protected open fun getParameterIndex(context: UpdateParameterInfoContext, argumentList: TArgumentList): Int {
val offset = context.offset
return argumentList.allChildren
.takeWhile { it.startOffset < offset }
.count { it.node.elementType == KtTokens.COMMA }
}
override fun updateUI(itemToShow: CallInfo, context: ParameterInfoUIContext) {
if (!updateUIOrFail(itemToShow, context)) {
context.isUIComponentEnabled = false
return
}
}
private fun updateUIOrFail(itemToShow: CallInfo, context: ParameterInfoUIContext): Boolean {
if (context.parameterOwner == null || !context.parameterOwner.isValid) return false
if (!argumentListClass.java.isInstance(context.parameterOwner)) return false
val call = itemToShow.call ?: return false
val supportsMixedNamedArgumentsInTheirOwnPosition =
call.callElement.languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition)
@Suppress("UNCHECKED_CAST")
val argumentList = context.parameterOwner as TArgumentList
val currentArgumentIndex = context.currentParameterIndex
if (currentArgumentIndex < 0) return false // by some strange reason we are invoked with currentParameterIndex == -1 during initialization
val project = argumentList.project
val (substitutedDescriptor, argumentToParameter, highlightParameterIndex, isGrey) = matchCallWithSignature(
itemToShow, currentArgumentIndex
) ?: return false
var boldStartOffset = -1
var boldEndOffset = -1
var disabledBeforeHighlight = false
val text = buildString {
val usedParameterIndices = HashSet<Int>()
var namedMode = false
var argumentIndex = 0
if (call.callType == Call.CallType.ARRAY_SET_METHOD) {
// for set-operator the last parameter is used for the value assigned
usedParameterIndices.add(substitutedDescriptor.valueParameters.lastIndex)
}
val includeParameterNames = !substitutedDescriptor.hasSynthesizedParameterNames()
fun appendParameter(
parameter: ValueParameterDescriptor,
named: Boolean = false,
markUsedUnusedParameterBorder: Boolean = false
) {
argumentIndex++
if (length > 0) {
append(", ")
if (markUsedUnusedParameterBorder) {
// mark the space after the comma as bold; bold text needs to be at least one character long
boldStartOffset = length - 1
boldEndOffset = length
disabledBeforeHighlight = true
}
}
val highlightParameter = parameter.index == highlightParameterIndex
if (highlightParameter) {
boldStartOffset = length
}
append(renderParameter(parameter, includeParameterNames, named || namedMode, project))
if (highlightParameter) {
boldEndOffset = length
}
}
for (argument in call.valueArguments) {
if (argument is LambdaArgument) continue
val parameter = argumentToParameter(argument) ?: continue
if (!usedParameterIndices.add(parameter.index)) continue
if (argument.isNamed() &&
!(supportsMixedNamedArgumentsInTheirOwnPosition && argument.canBeUsedWithoutNameInCall(itemToShow))
) {
namedMode = true
}
appendParameter(parameter, argument.isNamed())
}
for (parameter in substitutedDescriptor.valueParameters) {
if (parameter.index !in usedParameterIndices) {
if (argumentIndex != parameter.index) {
namedMode = true
}
appendParameter(parameter, markUsedUnusedParameterBorder = highlightParameterIndex == null && boldStartOffset == -1)
}
}
if (length == 0) {
append(CodeInsightBundle.message("parameter.info.no.parameters"))
}
}
val color = if (itemToShow.isResolvedToDescriptor) GREEN_BACKGROUND else context.defaultParameterColor
context.setupUIComponentPresentation(
text,
boldStartOffset,
boldEndOffset,
isGrey,
itemToShow.isDeprecatedAtCallSite,
disabledBeforeHighlight,
color
)
return true
}
private fun renderParameter(parameter: ValueParameterDescriptor, includeName: Boolean, named: Boolean, project: Project): String {
return buildString {
if (named) append("[")
parameter
.annotations
.filterNot { it.fqName in NULLABILITY_ANNOTATIONS }
.forEach {
it.fqName?.let { fqName -> append("@${fqName.shortName().asString()} ") }
}
if (parameter.varargElementType != null) {
append("vararg ")
}
if (includeName) {
append(parameter.name)
append(": ")
}
append(RENDERER.renderType(parameterTypeToRender(parameter)))
if (parameter.hasDefaultValue()) {
append(" = ")
append(parameter.renderDefaultValue(project))
}
if (named) append("]")
}
}
private fun ValueParameterDescriptor.renderDefaultValue(project: Project): String {
val expression = OptionalParametersHelper.defaultParameterValueExpression(this, project)
if (expression != null) {
val text = expression.text
if (text.length <= 32) {
return text
}
if (expression is KtConstantExpression || expression is KtStringTemplateExpression) {
if (text.startsWith("\"")) {
return "\"...\""
} else if (text.startsWith("\'")) {
return "\'...\'"
}
}
}
return "..."
}
private fun parameterTypeToRender(descriptor: ValueParameterDescriptor): KotlinType {
var type = descriptor.varargElementType ?: descriptor.type
if (type.containsError()) {
val original = descriptor.original
type = original.varargElementType ?: original.type
}
return type
}
private fun isResolvedToDescriptor(
call: Call,
functionDescriptor: FunctionDescriptor,
bindingContext: BindingContext
): Boolean {
val target = call.getResolvedCall(bindingContext)?.resultingDescriptor as? FunctionDescriptor
return target != null && descriptorsEqual(target, functionDescriptor)
}
private data class SignatureInfo(
val substitutedDescriptor: FunctionDescriptor,
val argumentToParameter: (ValueArgument) -> ValueParameterDescriptor?,
val highlightParameterIndex: Int?,
val isGrey: Boolean
)
data class CallInfo(
val overload: FunctionDescriptor? = null,
var call: Call? = null,
var resolvedCall: ResolvedCall<FunctionDescriptor>? = null,
var parameterIndex: Int? = null,
var dummyArgument: ValueArgument? = null,
var dummyResolvedCall: ResolvedCall<FunctionDescriptor>? = null,
var isResolvedToDescriptor: Boolean = false,
var isGreyArgumentIndex: Int = -1,
var isDeprecatedAtCallSite: Boolean = false
) {
override fun toString(): String =
"CallInfo(overload=$overload, call=$call, resolvedCall=${resolvedCall?.resultingDescriptor}($resolvedCall), parameterIndex=$parameterIndex, dummyArgument=$dummyArgument, dummyResolvedCall=$dummyResolvedCall, isResolvedToDescriptor=$isResolvedToDescriptor, isGreyArgumentIndex=$isGreyArgumentIndex, isDeprecatedAtCallSite=$isDeprecatedAtCallSite)"
}
fun Call.arguments(): List<ValueArgument> {
val isArraySetMethod = callType == Call.CallType.ARRAY_SET_METHOD
return valueArguments.let<List<ValueArgument>, List<ValueArgument>> { args ->
// For array set method call, we're only interested in the arguments in brackets which are all except the last one
if (isArraySetMethod) args.dropLast(1) else args
}
}
private fun resolveCallInfo(
info: CallInfo,
call: Call,
bindingContext: BindingContext,
resolutionFacade: ResolutionFacade,
parameterIndex: Int
) {
val overload = info.overload ?: return
val isArraySetMethod = call.callType == Call.CallType.ARRAY_SET_METHOD
val arguments = call.arguments()
val resolvedCall = resolvedCall(call, bindingContext, resolutionFacade, overload) ?: return
// add dummy current argument if we don't have one
val dummyArgument = object : ValueArgument {
override fun getArgumentExpression(): KtExpression? = null
override fun getArgumentName(): ValueArgumentName? = null
override fun isNamed(): Boolean = false
override fun asElement(): KtElement = call.callElement // is a hack but what to do?
override fun getSpreadElement(): LeafPsiElement? = null
override fun isExternal() = false
}
val dummyResolvedCall =
dummyResolvedCall(call, arguments, dummyArgument, isArraySetMethod, bindingContext, resolutionFacade, overload)
val resultingDescriptor = resolvedCall.resultingDescriptor
val resolvedToDescriptor = isResolvedToDescriptor(call, resultingDescriptor, bindingContext)
// grey out if not all arguments are matched
val isGreyArgumentIndex = arguments.indexOfFirst { argument ->
resolvedCall.getArgumentMapping(argument).isError() &&
!argument.hasError(bindingContext) /* ignore arguments that have error type */
}
@OptIn(FrontendInternals::class)
val isDeprecated = resolutionFacade.frontendService<DeprecationResolver>().getDeprecations(resultingDescriptor).isNotEmpty()
with(info) {
this.call = call
this.resolvedCall = resolvedCall
this.parameterIndex = parameterIndex
this.dummyArgument = dummyArgument
this.dummyResolvedCall = dummyResolvedCall
this.isResolvedToDescriptor = resolvedToDescriptor
this.isGreyArgumentIndex = isGreyArgumentIndex
this.isDeprecatedAtCallSite = isDeprecated
}
}
private fun dummyResolvedCall(
call: Call,
arguments: List<ValueArgument>,
dummyArgument: ValueArgument,
isArraySetMethod: Boolean,
bindingContext: BindingContext,
resolutionFacade: ResolutionFacade,
overload: FunctionDescriptor
): ResolvedCall<FunctionDescriptor>? {
val callToUse = object : DelegatingCall(call) {
val argumentsWithCurrent =
arguments + dummyArgument +
// For array set method call, also add the argument in the right-hand side
(if (isArraySetMethod) listOf(call.valueArguments.last()) else listOf())
override fun getValueArguments() = argumentsWithCurrent
override fun getFunctionLiteralArguments() = emptyList<LambdaArgument>()
override fun getValueArgumentList(): KtValueArgumentList? = null
}
return resolvedCall(callToUse, bindingContext, resolutionFacade, overload)
}
private fun resolvedCall(
call: Call,
bindingContext: BindingContext,
resolutionFacade: ResolutionFacade,
overload: FunctionDescriptor
): ResolvedCall<FunctionDescriptor>? {
val candidates = call.resolveCandidates(bindingContext, resolutionFacade)
// First try to find strictly matching descriptor, then one with the same declaration.
// The second way is needed for the case when the descriptor was invalidated and new one has been built.
// See testLocalFunctionBug().
return candidates.firstOrNull { it.resultingDescriptor.original == overload.original }
?: candidates.firstOrNull { descriptorsEqual(it.resultingDescriptor, overload) }
}
private fun matchCallWithSignature(
info: CallInfo,
currentArgumentIndex: Int
): SignatureInfo? {
val call = info.call ?: return null
val resolvedCall = info.resolvedCall ?: return null
if (currentArgumentIndex == 0 && call.valueArguments.isEmpty() && resolvedCall.resultingDescriptor.valueParameters.isEmpty()) {
return SignatureInfo(resolvedCall.resultingDescriptor, { null }, null, isGrey = false)
}
val arguments = call.arguments()
checkWithAttachment(
arguments.size >= currentArgumentIndex,
lazyMessage = { "currentArgumentIndex: $currentArgumentIndex has to be not more than number of arguments ${arguments.size} " +
" (parameterIndex: ${info.parameterIndex}) :call.valueArguments: ${call.valueArguments} call.callType: ${call.callType}" },
attachments = {
info.call?.let { c ->
it.withPsiAttachment("file.kt", c.callElement.containingFile)
}
it.withAttachment("info.txt", info)
}
)
val callToUse: ResolvedCall<FunctionDescriptor>
val currentArgument = if (arguments.size > currentArgumentIndex) {
callToUse = resolvedCall
arguments[currentArgumentIndex]
} else {
callToUse = info.dummyResolvedCall ?: return null
info.dummyArgument ?: return null
}
val resultingDescriptor = callToUse.resultingDescriptor
fun argumentToParameter(argument: ValueArgument): ValueParameterDescriptor? {
return (callToUse.getArgumentMapping(argument) as? ArgumentMatch)?.valueParameter
}
val currentParameter = argumentToParameter(currentArgument)
val highlightParameterIndex = currentParameter?.index
val argumentsBeforeCurrent = arguments.subList(0, currentArgumentIndex)
if (argumentsBeforeCurrent.any { argumentToParameter(it) == null }) {
// some of arguments before the current one are not mapped to any of the parameters
return SignatureInfo(resultingDescriptor, ::argumentToParameter, highlightParameterIndex, isGrey = true)
}
if (currentParameter == null) {
if (currentArgumentIndex < arguments.lastIndex) {
// the current argument is not the last one and it is not mapped to any of the parameters
return SignatureInfo(resultingDescriptor, ::argumentToParameter, highlightParameterIndex, isGrey = true)
}
val usedParameters = argumentsBeforeCurrent.mapNotNull { argumentToParameter(it) }.toSet()
val availableParameters = if (call.callType == Call.CallType.ARRAY_SET_METHOD) {
resultingDescriptor.valueParameters.dropLast(1)
} else {
resultingDescriptor.valueParameters
}
val noUnusedParametersLeft = (availableParameters - usedParameters).isEmpty()
if (currentArgument == info.dummyArgument) {
val supportsTrailingCommas = call.callElement.languageVersionSettings.supportsFeature(LanguageFeature.TrailingCommas)
if (!supportsTrailingCommas && noUnusedParametersLeft) {
// current argument is empty but there are no unused parameters left and trailing commas are not supported
return SignatureInfo(resultingDescriptor, ::argumentToParameter, highlightParameterIndex, isGrey = true)
}
} else if (noUnusedParametersLeft) {
// there are no unused parameters left to which this argument could be matched
return SignatureInfo(resultingDescriptor, ::argumentToParameter, highlightParameterIndex, isGrey = true)
}
}
// grey out if not all arguments before the current are matched
val isGrey = info.isGreyArgumentIndex in 0 until currentArgumentIndex
return SignatureInfo(resultingDescriptor, ::argumentToParameter, highlightParameterIndex, isGrey)
}
private fun ValueArgument.hasError(bindingContext: BindingContext) =
getArgumentExpression()?.let { bindingContext.getType(it) }?.isError ?: true
private fun ValueArgument.canBeUsedWithoutNameInCall(callInfo: CallInfo) =
this is KtValueArgument && this.canBeUsedWithoutNameInCall(callInfo.resolvedCall as ResolvedCall<out CallableDescriptor>)
// we should not compare descriptors directly because partial resolve is involved
private fun descriptorsEqual(descriptor1: FunctionDescriptor, descriptor2: FunctionDescriptor): Boolean {
if (descriptor1.original == descriptor2.original) return true
val isSamDescriptor1 = descriptor1 is SamAdapterDescriptor<*>
val isSamDescriptor2 = descriptor2 is SamAdapterDescriptor<*>
// Previously it worked because of different order
// If descriptor1 is SamAdapter and descriptor2 isn't, this function shouldn't return `true` because of equal declaration
if (isSamDescriptor1 xor isSamDescriptor2) return false
val declaration1 = DescriptorToSourceUtils.descriptorToDeclaration(descriptor1) ?: return false
val declaration2 = DescriptorToSourceUtils.descriptorToDeclaration(descriptor2)
return declaration1 == declaration2
}
}
| apache-2.0 |
jwren/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/settings/language/SingleLanguageInlayHintsSettingsPanel.kt | 1 | 11940 | // 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.codeInsight.hints.settings.language
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.hint.EditorFragmentComponent
import com.intellij.codeInsight.hints.ChangeListener
import com.intellij.codeInsight.hints.InlayHintsSettings
import com.intellij.codeInsight.hints.settings.InlayHintsConfigurable
import com.intellij.codeInsight.hints.settings.InlayProviderSettingsModel
import com.intellij.ide.CopyProvider
import com.intellij.ide.DataManager
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypes
import com.intellij.openapi.fileTypes.PlainTextFileType
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.options.ex.Settings
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiDocumentManager
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.EditorTextField
import com.intellij.ui.JBColor
import com.intellij.ui.JBSplitter
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.layout.*
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.ui.JBUI
import java.awt.BorderLayout
import java.awt.GridLayout
import java.awt.datatransfer.StringSelection
import java.util.concurrent.Callable
import javax.swing.*
import javax.swing.border.LineBorder
private const val TOP_PANEL_PROPORTION = 0.35f
class SingleLanguageInlayHintsSettingsPanel(
private val myModels: Array<InlayProviderSettingsModel>,
private val myLanguage: Language,
private val myProject: Project
) : JPanel(), CopyProvider {
private val config = InlayHintsSettings.instance()
private val myProviderList = createList()
private var myCurrentProvider = selectLastViewedProvider()
private val myEditorTextField = createEditor(myLanguage, myProject) { updateHints() }
private val myCurrentProviderCustomSettingsPane = JBScrollPane().also {
it.border = null
}
private val myCurrentProviderCasesPane = JBScrollPane().also {
it.border = null
it.verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER
it.horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
}
private val myBottomPanel = createBottomPanel()
private var myCasesPanel: CasesPanel? = null
private val myRightPanel: JPanel = JPanel()
private val myWarningContainer = JPanel().also {
it.layout = BoxLayout(it, BoxLayout.Y_AXIS)
}
init {
layout = GridLayout(1, 1)
val splitter = JBSplitter(true)
splitter.firstComponent = createTopPanel()
splitter.secondComponent = myBottomPanel
for (model in myModels) {
model.onChangeListener = object : ChangeListener {
override fun settingsChanged() {
updateHints()
}
}
}
myProviderList.addListSelectionListener {
val newProviderModel = myProviderList.selectedValue
update(newProviderModel)
config.saveLastViewedProviderId(newProviderModel.id)
}
myProviderList.selectedIndex = findIndexToSelect()
add(splitter)
updateWithNewProvider()
}
internal fun getModels(): Array<InlayProviderSettingsModel> {
return myModels
}
internal fun setCurrentModel(model: InlayProviderSettingsModel) {
myProviderList.setSelectedValue(model, true)
}
private fun selectLastViewedProvider(): InlayProviderSettingsModel {
return myModels[findIndexToSelect()]
}
private fun findIndexToSelect(): Int {
val id = config.getLastViewedProviderId() ?: return 0
return when (val index = myModels.indexOfFirst { it.id == id }) {
-1 -> 0
else -> index
}
}
private fun createList(): JBList<InlayProviderSettingsModel> {
return JBList(*myModels).also {
it.cellRenderer = object : ColoredListCellRenderer<InlayProviderSettingsModel>(), ListCellRenderer<InlayProviderSettingsModel> {
override fun customizeCellRenderer(list: JList<out InlayProviderSettingsModel>,
value: InlayProviderSettingsModel,
index: Int,
selected: Boolean,
hasFocus: Boolean) {
append(value.name)
}
}
}
}
private fun createTopPanel(): JPanel {
val panel = JPanel()
panel.layout = GridLayout(1, 1)
val horizontalSplitter = JBSplitter(false, TOP_PANEL_PROPORTION)
horizontalSplitter.firstComponent = createLeftPanel()
horizontalSplitter.secondComponent = fillRightPanel()
panel.add(horizontalSplitter)
return panel
}
private fun createLeftPanel() = JBScrollPane(myProviderList)
private fun fillRightPanel(): JPanel {
return withInset(panel {
row {
myWarningContainer(growY)
}
row {
withInset(myCurrentProviderCasesPane)()
}
row {
withInset(myCurrentProviderCustomSettingsPane)()
}
})
}
private fun createBottomPanel(): JPanel {
val panel = JPanel()
panel.layout = BorderLayout()
panel.add(createPreviewPanel(), BorderLayout.CENTER)
return panel
}
private fun createPreviewPanel(): JPanel {
val previewPanel = JPanel()
previewPanel.layout = BorderLayout()
previewPanel.add(myEditorTextField, BorderLayout.CENTER)
return previewPanel
}
private fun withInset(component: JComponent): JPanel {
val panel = JPanel(GridLayout())
panel.add(component)
panel.border = JBUI.Borders.empty(2)
return panel
}
private fun update(newProvider: InlayProviderSettingsModel) {
if (myCurrentProvider == newProvider) return
myCurrentProvider = newProvider
updateWithNewProvider()
}
private fun updateWithNewProvider() {
myCurrentProviderCasesPane.setViewportView(createCasesPanel())
myCurrentProviderCustomSettingsPane.setViewportView(myCurrentProvider.component)
myRightPanel.validate()
updateWarningPanel()
val previewText = myCurrentProvider.previewText
if (previewText == null) {
myBottomPanel.isVisible = false
}
else {
myBottomPanel.isVisible = true
myEditorTextField.text = previewText
updateHints()
}
}
private fun updateWarningPanel() {
myWarningContainer.removeAll()
if (!config.hintsEnabled(myLanguage)) {
myWarningContainer.add(JLabel(CodeInsightBundle.message("settings.inlay.hints.warning.hints.for.language.disabled", myLanguage.displayName)))
myWarningContainer.add(ActionLink(CodeInsightBundle.message("settings.inlay.hints.warning.configure.settings", myLanguage.displayName)) {
val settings = Settings.KEY.getData(DataManager.getInstance().getDataContext(this))
if (settings != null) {
val mainConfigurable = settings.find(InlayHintsConfigurable::class.java)
if (mainConfigurable != null) {
settings.select(mainConfigurable)
}
}
})
}
myWarningContainer.revalidate()
myWarningContainer.repaint()
}
private fun createCasesPanel(): JPanel {
val model = myCurrentProvider
val casesPanel = CasesPanel(
cases = model.cases,
mainCheckBoxName = model.mainCheckBoxLabel,
loadMainCheckBoxValue = { model.isEnabled },
onUserChangedMainCheckBox = {
model.isEnabled = it
model.onChangeListener?.settingsChanged()
},
listener = model.onChangeListener!!, // must be installed at this point
disabledExternally = { !(config.hintsEnabled(myLanguage) && config.hintsEnabledGlobally()) }
)
myCasesPanel = casesPanel
return casesPanel
}
private fun updateHints() {
if (myBottomPanel.isVisible) {
myEditorTextField.editor?.let { editor ->
val model = myCurrentProvider
val document = myEditorTextField.document
val fileType = myLanguage.associatedFileType ?: PlainTextFileType.INSTANCE
ReadAction.nonBlocking(Callable {
val psiFile = model.createFile(myProject, fileType, document)
myCurrentProvider.collectData(editor, psiFile)
})
.finishOnUiThread(ModalityState.defaultModalityState()) { continuation ->
ApplicationManager.getApplication().runWriteAction {
continuation.run()
}
}
.inSmartMode(myProject)
.submit(AppExecutorUtil.getAppExecutorService())
}
}
}
fun isModified(): Boolean {
return myModels.any { it.isModified() }
}
fun apply() {
for (model in myModels) {
model.apply()
}
}
fun reset() {
for (model in myModels) {
model.reset()
}
myCasesPanel?.updateFromSettings()
updateWarningPanel()
updateHints()
}
override fun performCopy(dataContext: DataContext) {
val selectedIndex = myProviderList.selectedIndex
if (selectedIndex < 0) return
val selection = myProviderList.model.getElementAt(selectedIndex)
CopyPasteManager.getInstance().setContents(StringSelection(selection.name))
}
override fun isCopyEnabled(dataContext: DataContext): Boolean = !myProviderList.isSelectionEmpty
override fun isCopyVisible(dataContext: DataContext): Boolean = false
}
internal val SETTINGS_EDITOR_MARKER: Key<Boolean> = Key.create("inlay.settings.editor")
fun isInlaySettingsEditor(editor: Editor) : Boolean {
return editor.getUserData(SETTINGS_EDITOR_MARKER) == true
}
fun createEditor(language: Language,
project: Project,
updateHints: (editor: Editor) -> Any): EditorTextField {
val fileType: FileType = language.associatedFileType ?: FileTypes.PLAIN_TEXT
val editorField = object : EditorTextField(null, project, fileType, true, false) {
override fun createEditor(): EditorEx {
val editor = super.createEditor()
editor.putUserData(SETTINGS_EDITOR_MARKER, true)
updateHints(editor)
return editor
}
}
editorField.font = EditorFontType.PLAIN.globalFont
editorField.border = LineBorder(JBColor.border())
editorField.addSettingsProvider { editor ->
editor.setVerticalScrollbarVisible(true)
editor.setHorizontalScrollbarVisible(true)
with(editor.settings) {
additionalLinesCount = 0
isAutoCodeFoldingEnabled = false
}
// Sadly, but we can't use daemon here, because we need specific kind of settings instance here.
editor.document.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
updateHints(editor)
}
})
editor.backgroundColor = EditorFragmentComponent.getBackgroundColor(editor, false)
editor.setBorder(JBUI.Borders.empty())
// If editor is created as not viewer, daemon is enabled automatically. But we want to collect hints manually with another settings.
val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document)
if (psiFile != null) {
DaemonCodeAnalyzer.getInstance(project).setHighlightingEnabled(psiFile, false)
}
}
ReadAction.run<Throwable> { editorField.setCaretPosition(0) }
return editorField
}
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/RemoveNullableFix.kt | 3 | 3031 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
class RemoveNullableFix(element: KtNullableType, private val typeOfError: NullableKind) :
KotlinPsiOnlyQuickFixAction<KtNullableType>(element) {
enum class NullableKind(@Nls val message: String) {
REDUNDANT(KotlinBundle.message("remove.redundant")),
SUPERTYPE(KotlinBundle.message("text.remove.question")),
USELESS(KotlinBundle.message("remove.useless")),
PROPERTY(KotlinBundle.message("make.not.nullable"))
}
override fun getFamilyName() = KotlinBundle.message("text.remove.question")
override fun getText() = typeOfError.message
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val type = element.innerType ?: error("No inner type ${element.text}, should have been rejected in createFactory()")
element.replace(type)
}
companion object {
val removeForRedundant = createFactory(NullableKind.REDUNDANT)
val removeForSuperType = createFactory(NullableKind.SUPERTYPE)
val removeForUseless = createFactory(NullableKind.USELESS)
val removeForLateInitProperty = createFactory(NullableKind.PROPERTY)
private fun createFactory(typeOfError: NullableKind): QuickFixesPsiBasedFactory<KtElement> {
return quickFixesPsiBasedFactory { e ->
when (typeOfError) {
NullableKind.REDUNDANT, NullableKind.SUPERTYPE, NullableKind.USELESS -> {
val nullType: KtNullableType? = when (e) {
is KtTypeReference -> e.typeElement as? KtNullableType
else -> e.getNonStrictParentOfType()
}
if (nullType?.innerType == null) return@quickFixesPsiBasedFactory emptyList()
listOf(RemoveNullableFix(nullType, typeOfError))
}
NullableKind.PROPERTY -> {
val property = e as? KtProperty ?: return@quickFixesPsiBasedFactory emptyList()
val typeReference = property.typeReference ?: return@quickFixesPsiBasedFactory emptyList()
val typeElement = typeReference.typeElement as? KtNullableType ?: return@quickFixesPsiBasedFactory emptyList()
if (typeElement.innerType == null) return@quickFixesPsiBasedFactory emptyList()
listOf(RemoveNullableFix(typeElement, NullableKind.PROPERTY))
}
}
}
}
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.