repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddAnnotationFix.kt | 3 | 3405 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.util.addAnnotation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.renderer.render
open class AddAnnotationFix(
element: KtModifierListOwner,
private val annotationFqName: FqName,
private val kind: Kind = Kind.Self,
private val argumentClassFqName: FqName? = null,
private val existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : KotlinQuickFixAction<KtModifierListOwner>(element) {
override fun getText(): String {
val annotationArguments = (argumentClassFqName?.shortName()?.let { "($it::class)" } ?: "")
val annotationCall = annotationFqName.shortName().asString() + annotationArguments
return when (kind) {
Kind.Self -> KotlinBundle.message("fix.add.annotation.text.self", annotationCall)
Kind.Constructor -> KotlinBundle.message("fix.add.annotation.text.constructor", annotationCall)
is Kind.Declaration -> KotlinBundle.message("fix.add.annotation.text.declaration", annotationCall, kind.name ?: "?")
is Kind.ContainingClass -> KotlinBundle.message("fix.add.annotation.text.containing.class", annotationCall, kind.name ?: "?")
}
}
override fun getFamilyName(): String = KotlinBundle.message("fix.add.annotation.family")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val declaration = element ?: return
val annotationEntry = existingAnnotationEntry?.element
val annotationInnerText = argumentClassFqName?.let { "${it.render()}::class" }
if (annotationEntry != null) {
if (annotationInnerText == null) return
val psiFactory = KtPsiFactory(declaration)
annotationEntry.valueArgumentList?.addArgument(psiFactory.createArgument(annotationInnerText))
?: annotationEntry.addAfter(psiFactory.createCallArguments("($annotationInnerText)"), annotationEntry.lastChild)
ShortenReferences.DEFAULT.process(annotationEntry)
} else {
declaration.addAnnotation(annotationFqName, annotationInnerText)
}
}
sealed class Kind {
object Self : Kind()
object Constructor : Kind()
class Declaration(val name: String?) : Kind()
class ContainingClass(val name: String?) : Kind()
}
object TypeVarianceConflictFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val typeReference = diagnostic.psiElement.parent as? KtTypeReference ?: return null
return AddAnnotationFix(typeReference, FqName("kotlin.UnsafeVariance"), Kind.Self)
}
}
}
| apache-2.0 | dcb4730bc965e6bef576315412e5655e | 50.590909 | 158 | 0.728928 | 5.044444 | false | false | false | false |
jk1/intellij-community | platform/script-debugger/backend/src/debugger/SuspendContextManagerBase.kt | 3 | 2451 | // 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.debugger
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.rejectedPromise
import org.jetbrains.concurrency.resolvedPromise
import java.util.concurrent.atomic.AtomicReference
abstract class SuspendContextManagerBase<T : SuspendContextBase<CALL_FRAME>, CALL_FRAME : CallFrame> : SuspendContextManager<CALL_FRAME> {
val contextRef: AtomicReference<T> = AtomicReference<T>()
protected val suspendCallback: AtomicReference<AsyncPromise<Void?>> = AtomicReference<AsyncPromise<Void?>>()
protected abstract val debugListener: DebugEventListener
fun setContext(newContext: T) {
if (!contextRef.compareAndSet(null, newContext)) {
throw IllegalStateException("Attempt to set context, but current suspend context is already exists")
}
}
open fun updateContext(newContext: SuspendContext<*>) {
}
// dismiss context on resumed
protected fun dismissContext() {
contextRef.get()?.let {
contextDismissed(it)
}
}
protected fun dismissContextOnDone(promise: Promise<*>): Promise<*> {
val context = contextOrFail
promise.onSuccess { contextDismissed(context) }
return promise
}
fun contextDismissed(context: T) {
if (!contextRef.compareAndSet(context, null)) {
throw IllegalStateException("Expected $context, but another suspend context exists")
}
context.valueManager.markObsolete()
debugListener.resumed(context.vm)
}
override val context: SuspendContext<CALL_FRAME>?
get() = contextRef.get()
override val contextOrFail: T
get() = contextRef.get() ?: throw IllegalStateException("No current suspend context")
override fun suspend(): Promise<out Any?> = suspendCallback.get() ?: if (context == null) doSuspend() else resolvedPromise()
protected abstract fun doSuspend(): Promise<*>
override fun setOverlayMessage(message: String?) {
}
override fun restartFrame(callFrame: CALL_FRAME): Promise<Boolean> = restartFrame(callFrame, contextOrFail)
protected open fun restartFrame(callFrame: CALL_FRAME, currentContext: T): Promise<Boolean> = rejectedPromise<Boolean>("Unsupported")
override fun canRestartFrame(callFrame: CallFrame): Boolean = false
override val isRestartFrameSupported: Boolean = false
} | apache-2.0 | d16d818884b201b4d62a4962b2314320 | 35.597015 | 140 | 0.756018 | 4.73166 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/data/media/MediaRepository.kt | 1 | 1650 | package org.dvbviewer.controller.data.media
import org.apache.commons.collections4.CollectionUtils
import org.apache.commons.lang3.StringUtils
import org.dvbviewer.controller.data.api.DMSInterface
import org.dvbviewer.controller.data.entities.NaturalOrderComparator
import java.util.*
import kotlin.math.max
/**
* Created by rbaun on 02.04.18.
*/
class MediaRepository(private val dmsInterface: DMSInterface) {
private val comparator = NaturalOrderComparator()
fun getMedias(dirid: Long): List<MediaFile> {
val videoDirs = dmsInterface.getMediaDir(dirid).execute().body()
val mediaFiles = ArrayList<MediaFile>()
if (CollectionUtils.isNotEmpty(videoDirs!!.dirs)) {
val dirs = ArrayList<MediaFile>()
videoDirs.dirs?.forEach { dir ->
val f = MediaFile()
f.dirId = dir.dirid
val dirArr = StringUtils.split(dir.path, "\\")
val index = max(0, dirArr.size - 1)
f.name = dirArr[index]
dirs.add(f)
}
Collections.sort(dirs, comparator)
mediaFiles.addAll(dirs)
}
if (CollectionUtils.isNotEmpty(videoDirs.files)) {
val files = ArrayList<MediaFile>()
videoDirs.files?.forEach { file ->
val f = MediaFile()
f.dirId = -1L
f.id = file.objid
f.name = file.name
f.thumb = file.thumb
files.add(f)
}
Collections.sort(files, comparator)
mediaFiles.addAll(files)
}
return mediaFiles
}
} | apache-2.0 | 4e5981782478874c5d45f0e56f7267ac | 33.395833 | 72 | 0.589697 | 4.308094 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/llvm/src/templates/kotlin/llvm/templates/ClangDocumentation.kt | 4 | 15345 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package llvm.templates
import llvm.*
import org.lwjgl.generator.*
val ClangDocumentation = "ClangDocumentation".nativeClass(
Module.LLVM,
prefixConstant = "CX",
prefixMethod = "clang_",
binding = CLANG_BINDING_DELEGATE
) {
nativeImport("clang-c/Documentation.h")
EnumConstant(
"""
Describes the type of the comment AST node ( {@code CXComment}). A comment node can be considered block content (e. g., paragraph), inline content
(plain text) or neither (the root AST node).
({@code enum CXCommentKind})
""",
"Comment_Null".enum("Null comment. No AST node is constructed at the requested location because there is no text or a syntax error.", "0"),
"Comment_Text".enum("Plain text. Inline content."),
"Comment_InlineCommand".enum(
"""
A command with word-like arguments that is considered inline content.
For example: \c command.
"""
),
"Comment_HTMLStartTag".enum(
"""
HTML start tag with attributes (name-value pairs). Considered inline content.
For example:
${codeBlock("""
<br> <br /> <a href="http://example.org/">""")}
"""
),
"Comment_HTMLEndTag".enum(
"""
HTML end tag. Considered inline content.
For example:
${codeBlock("""
</a>""")}
"""
),
"Comment_Paragraph".enum("A paragraph, contains inline comment. The paragraph itself is block content."),
"Comment_BlockCommand".enum(
"""
A command that has zero or more word-like arguments (number of word-like arguments depends on command name) and a paragraph as an argument. Block
command is block content.
Paragraph argument is also a child of the block command.
For example: has 0 word-like arguments and a paragraph argument.
AST nodes of special kinds that parser knows about (e. g.,\param command) have their own node kinds.
"""
),
"Comment_ParamCommand".enum(
"""
A \param or \arg command that describes the function parameter (name, passing direction, description).
For example: \param [in] ParamName description.
"""
),
"Comment_TParamCommand".enum(
"""
A \tparam command that describes a template parameter (name and description).
For example: \tparam T description.
"""
),
"Comment_VerbatimBlockCommand".enum(
"""
A verbatim block command (e. g., preformatted code). Verbatim block has an opening and a closing command and contains multiple lines of text (
#Comment_VerbatimBlockLine child nodes).
For example: \verbatim aaa \endverbatim
"""
),
"Comment_VerbatimBlockLine".enum("A line of text that is contained within a CXComment_VerbatimBlockCommand node."),
"Comment_VerbatimLine".enum(
"""
A verbatim line command. Verbatim line has an opening command, a single line of text (up to the newline after the opening command) and has no
closing command.
"""
),
"Comment_FullComment".enum("A full comment attached to a declaration, contains block content.")
)
EnumConstant(
"""
The most appropriate rendering mode for an inline command, chosen on command semantics in Doxygen.
({@code enum CXCommentInlineCommandRenderKind})
""",
"CommentInlineCommandRenderKind_Normal".enum("Command argument should be rendered in a normal font.", "0"),
"CommentInlineCommandRenderKind_Bold".enum("Command argument should be rendered in a bold font."),
"CommentInlineCommandRenderKind_Monospaced".enum("Command argument should be rendered in a monospaced font."),
"CommentInlineCommandRenderKind_Emphasized".enum("Command argument should be rendered emphasized (typically italic font)."),
"CommentInlineCommandRenderKind_Anchor".enum("Command argument should not be rendered (since it only defines an anchor).")
)
EnumConstant(
"""
Describes parameter passing direction for \param or \arg command.
({@code enum CXCommentParamPassDirection})
""",
"CommentParamPassDirection_In".enum("The parameter is an input parameter.", "0"),
"CommentParamPassDirection_Out".enum("The parameter is an output parameter."),
"CommentParamPassDirection_InOut".enum("The parameter is an input and output parameter.")
)
CXComment(
"Cursor_getParsedComment",
"Given a cursor that represents a documentable entity (e.g., declaration), return the associated parsed comment as a #Comment_FullComment AST node.",
CXCursor("C", "")
)
CXCommentKind(
"Comment_getKind",
"",
CXComment("Comment", "AST node of any kind"),
returnDoc = "the type of the AST node"
)
unsigned(
"Comment_getNumChildren",
"",
CXComment("Comment", "AST node of any kind"),
returnDoc = "number of children of the AST node"
)
CXComment(
"Comment_getChild",
"",
CXComment("Comment", "AST node of any kind"),
unsigned("ChildIdx", "child index (zero-based)"),
returnDoc = "the specified child of the AST node"
)
unsignedb(
"Comment_isWhitespace",
"""
A #Comment_Paragraph node is considered whitespace if it contains only #Comment_Text nodes that are empty or whitespace.
Other AST nodes (except {@code CXComment_Paragraph} and {@code CXComment_Text}) are never considered whitespace.
""",
CXComment("Comment", ""),
returnDoc = "non-zero if {@code Comment} is whitespace"
)
unsignedb(
"InlineContentComment_hasTrailingNewline",
"",
CXComment("Comment", ""),
returnDoc =
"""
non-zero if {@code Comment} is inline content and has a newline immediately following it in the comment text. Newlines between paragraphs do not count.
"""
)
CXString(
"TextComment_getText",
"",
CXComment("Comment", "a #Comment_Text AST node"),
returnDoc = "text contained in the AST node"
)
CXString(
"InlineCommandComment_getCommandName",
"",
CXComment("Comment", "a #Comment_InlineCommand AST node"),
returnDoc = "name of the inline command"
)
CXCommentInlineCommandRenderKind(
"InlineCommandComment_getRenderKind",
"",
CXComment("Comment", "a #Comment_InlineCommand AST node"),
returnDoc = "the most appropriate rendering mode, chosen on command semantics in Doxygen"
)
unsigned(
"InlineCommandComment_getNumArgs",
"",
CXComment("Comment", "a #Comment_InlineCommand AST node"),
returnDoc = "number of command arguments"
)
CXString(
"InlineCommandComment_getArgText",
"",
CXComment("Comment", "a #Comment_InlineCommand AST node"),
unsigned("ArgIdx", "argument index (zero-based)"),
returnDoc = "text of the specified argument"
)
CXString(
"HTMLTagComment_getTagName",
"",
CXComment("Comment", "a #Comment_HTMLStartTag or #Comment_HTMLEndTag AST node"),
returnDoc = "HTML tag name"
)
unsignedb(
"HTMLStartTagComment_isSelfClosing",
"",
CXComment("Comment", "a #Comment_HTMLStartTag AST node"),
returnDoc = "non-zero if tag is self-closing (for example, <br /> )"
)
unsigned(
"HTMLStartTag_getNumAttrs",
"",
CXComment("Comment", "a #Comment_HTMLStartTag AST node"),
returnDoc = "number of attributes (name-value pairs) attached to the start tag"
)
CXString(
"HTMLStartTag_getAttrName",
"",
CXComment("Comment", "a #Comment_HTMLStartTag AST node"),
unsigned("AttrIdx", "attribute index (zero-based)"),
returnDoc = "name of the specified attribute"
)
CXString(
"HTMLStartTag_getAttrValue",
"",
CXComment("Comment", "a #Comment_HTMLStartTag AST node"),
unsigned("AttrIdx", "attribute index (zero-based)"),
returnDoc = "value of the specified attribute"
)
CXString(
"BlockCommandComment_getCommandName",
"",
CXComment("Comment", "a #Comment_BlockCommand AST node"),
returnDoc = "name of the block command"
)
unsigned(
"BlockCommandComment_getNumArgs",
"",
CXComment("Comment", "a #Comment_BlockCommand AST node"),
returnDoc = "number of word-like arguments"
)
CXString(
"BlockCommandComment_getArgText",
"",
CXComment("Comment", "a #Comment_BlockCommand AST node"),
unsigned("ArgIdx", "argument index (zero-based)"),
returnDoc = "text of the specified word-like argument"
)
CXComment(
"BlockCommandComment_getParagraph",
"",
CXComment("Comment", "a #Comment_BlockCommand or #Comment_VerbatimBlockCommand AST node"),
returnDoc = "paragraph argument of the block command"
)
CXString(
"ParamCommandComment_getParamName",
"",
CXComment("Comment", "a #Comment_ParamCommand AST node"),
returnDoc = "parameter name"
)
unsignedb(
"ParamCommandComment_isParamIndexValid",
"",
CXComment("Comment", "a #Comment_ParamCommand AST node"),
returnDoc =
"""
non-zero if the parameter that this AST node represents was found in the function prototype and #ParamCommandComment_getParamIndex() function will
return a meaningful value
"""
)
unsigned(
"ParamCommandComment_getParamIndex",
"",
CXComment("Comment", "a #Comment_ParamCommand AST node"),
returnDoc = "zero-based parameter index in function prototype"
)
unsignedb(
"ParamCommandComment_isDirectionExplicit",
"",
CXComment("Comment", "a #Comment_ParamCommand AST node"),
returnDoc = "non-zero if parameter passing direction was specified explicitly in the comment"
)
CXCommentParamPassDirection(
"ParamCommandComment_getDirection",
"",
CXComment("Comment", "a #Comment_ParamCommand AST node"),
returnDoc = "parameter passing direction"
)
CXString(
"TParamCommandComment_getParamName",
"",
CXComment("Comment", "a #Comment_TParamCommand AST node"),
returnDoc = "template parameter name"
)
unsignedb(
"TParamCommandComment_isParamPositionValid",
"",
CXComment("Comment", "a #Comment_TParamCommand AST node"),
returnDoc =
"""
non-zero if the parameter that this AST node represents was found in the template parameter list and #TParamCommandComment_getDepth() and
#TParamCommandComment_getIndex() functions will return a meaningful value
"""
)
unsigned(
"TParamCommandComment_getDepth",
"""
For example,
${codeBlock("""
template<typename C, template<typename T> class TT>
void test(TT<int> aaa);""")}
for C and TT nesting depth is 0, for T nesting depth is 1.
""",
CXComment("Comment", "a #Comment_TParamCommand AST node"),
returnDoc = "zero-based nesting depth of this parameter in the template parameter list"
)
unsigned(
"TParamCommandComment_getIndex",
"""
For example,
${codeBlock("""
template<typename C, template<typename T> class TT>
void test(TT<int> aaa);""")}
for C and TT nesting depth is 0, so we can ask for index at depth 0: at depth 0 C's index is 0, TT's index is 1.
For T nesting depth is 1, so we can ask for index at depth 0 and 1: at depth 0 T's index is 1 (same as TT's), at depth 1 T's index is 0.
""",
CXComment("Comment", "a #Comment_TParamCommand AST node"),
unsigned("Depth", ""),
returnDoc = "zero-based parameter index in the template parameter list at a given nesting depth"
)
CXString(
"VerbatimBlockLineComment_getText",
"",
CXComment("Comment", "a #Comment_VerbatimBlockLine AST node"),
returnDoc = "text contained in the AST node"
)
CXString(
"VerbatimLineComment_getText",
"",
CXComment("Comment", "a #Comment_VerbatimLine AST node"),
returnDoc = "text contained in the AST node"
)
CXString(
"HTMLTagComment_getAsString",
"Convert an HTML tag AST node to string.",
CXComment("Comment", "a #Comment_HTMLStartTag or #Comment_HTMLEndTag AST node"),
returnDoc = "string containing an HTML tag"
)
CXString(
"FullComment_getAsHTML",
"""
Convert a given full parsed comment to an HTML fragment.
Specific details of HTML layout are subject to change. Don't try to parse this HTML back into an AST, use other APIs instead.
Currently the following CSS classes are used:
${ul(
"\"para-brief\" for \\paragraph and equivalent commands;",
"\"para-returns\" for \\returns paragraph and equivalent commands;",
"\"word-returns\" for the \"Returns\" word in \\returns paragraph."
)}
Function argument documentation is rendered as a <dl> list with arguments sorted in function prototype order. CSS classes used:
${ul(
"\"param-name-index-NUMBER\" for parameter name ( <dt> );",
"\"param-descr-index-NUMBER\" for parameter description ( <dd> );",
"\"param-name-index-invalid\" and \"param-descr-index-invalid\" are used if parameter index is invalid."
)}
Template parameter documentation is rendered as a <dl> list with parameters sorted in template parameter list order. CSS classes used:
${ul(
"\"tparam-name-index-NUMBER\" for parameter name ( <dt> );",
"\"tparam-descr-index-NUMBER\" for parameter description ( <dd> );",
"\"tparam-name-index-other\" and \"tparam-descr-index-other\" are used for names inside template template parameters;",
"\"tparam-name-index-invalid\" and \"tparam-descr-index-invalid\" are used if parameter position is invalid."
)}
""",
CXComment("Comment", "a #Comment_FullComment AST node"),
returnDoc = "string containing an HTML fragment"
)
CXString(
"FullComment_getAsXML",
"""
Convert a given full parsed comment to an XML document.
A Relax NG schema for the XML can be found in comment-xml-schema.rng file inside clang source tree.
""",
CXComment("Comment", "a #Comment_FullComment AST node"),
returnDoc = "string containing an XML document"
)
} | bsd-3-clause | 4a6e12cdb93d685e84f7d3cbffe25bea | 29.630739 | 159 | 0.612643 | 4.672655 | false | false | false | false |
mdanielwork/intellij-community | uast/uast-common/src/org/jetbrains/uast/values/UDependentValue.kt | 2 | 4978 | // 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.uast.values
open class UDependentValue protected constructor(
val value: UValue,
override val dependencies: Set<UDependency> = emptySet()
) : UValueBase() {
private fun UValue.unwrap() = (this as? UDependentValue)?.unwrap() ?: this
private fun unwrap(): UValue = value.unwrap()
private val dependenciesWithThis: Set<UDependency>
get() = (this as? UDependency)?.let { dependencies + it } ?: dependencies
private fun wrapBinary(result: UValue, arg: UValue): UValue {
val wrappedDependencies = (arg as? UDependentValue)?.dependenciesWithThis ?: emptySet()
val resultDependencies = dependenciesWithThis + wrappedDependencies
return create(result, resultDependencies)
}
private fun wrapUnary(result: UValue) = create(result, dependenciesWithThis)
override fun plus(other: UValue): UValue = wrapBinary(unwrap() + other.unwrap(), other)
override fun minus(other: UValue): UValue = wrapBinary(unwrap() - other.unwrap(), other)
override fun times(other: UValue): UValue = wrapBinary(unwrap() * other.unwrap(), other)
override fun div(other: UValue): UValue = wrapBinary(unwrap() / other.unwrap(), other)
internal fun inverseDiv(other: UValue) = wrapBinary(other.unwrap() / unwrap(), other)
override fun rem(other: UValue): UValue = wrapBinary(unwrap() % other.unwrap(), other)
internal fun inverseMod(other: UValue) = wrapBinary(other.unwrap() % unwrap(), other)
override fun unaryMinus(): UValue = wrapUnary(-unwrap())
override fun valueEquals(other: UValue): UValue = wrapBinary(unwrap() valueEquals other.unwrap(), other)
override fun valueNotEquals(other: UValue): UValue = wrapBinary(unwrap() valueNotEquals other.unwrap(), other)
override fun not(): UValue = wrapUnary(!unwrap())
override fun greater(other: UValue): UValue = wrapBinary(unwrap() greater other.unwrap(), other)
override fun less(other: UValue): UValue = wrapBinary(other.unwrap() greater unwrap(), other)
override fun inc(): UValue = wrapUnary(unwrap().inc())
override fun dec(): UValue = wrapUnary(unwrap().dec())
override fun and(other: UValue): UValue = wrapBinary(unwrap() and other.unwrap(), other)
override fun or(other: UValue): UValue = wrapBinary(unwrap() or other.unwrap(), other)
override fun bitwiseAnd(other: UValue): UValue = wrapBinary(unwrap() bitwiseAnd other.unwrap(), other)
override fun bitwiseOr(other: UValue): UValue = wrapBinary(unwrap() bitwiseOr other.unwrap(), other)
override fun bitwiseXor(other: UValue): UValue = wrapBinary(unwrap() bitwiseXor other.unwrap(), other)
override fun shl(other: UValue): UValue = wrapBinary(unwrap() shl other.unwrap(), other)
internal fun inverseShiftLeft(other: UValue) = wrapBinary(other.unwrap() shl unwrap(), other)
override fun shr(other: UValue): UValue = wrapBinary(unwrap() shr other.unwrap(), other)
internal fun inverseShiftRight(other: UValue) = wrapBinary(other.unwrap() shr unwrap(), other)
override fun ushr(other: UValue): UValue = wrapBinary(unwrap() ushr other.unwrap(), other)
internal fun inverseShiftRightUnsigned(other: UValue) =
wrapBinary(other.unwrap() ushr unwrap(), other)
override fun merge(other: UValue): UValue = when (other) {
this -> this
value -> this
is UVariableValue -> other.merge(this)
is UDependentValue -> {
val allDependencies = dependencies + other.dependencies
if (value != other.value) UDependentValue(value.merge(other.value), allDependencies)
else UDependentValue(value, allDependencies)
}
else -> UPhiValue.create(this, other)
}
override fun toConstant(): UConstant? = value.toConstant()
internal open fun copy(dependencies: Set<UDependency>) =
if (dependencies == this.dependencies) this else create(value, dependencies)
override fun coerceConstant(constant: UConstant): UValue =
if (toConstant() == constant) this
else create(value.coerceConstant(constant), dependencies)
override fun equals(other: Any?): Boolean =
other is UDependentValue
&& javaClass == other.javaClass
&& value == other.value
&& dependencies == other.dependencies
override fun hashCode(): Int {
var result = 31
result = result * 19 + value.hashCode()
result = result * 19 + dependencies.hashCode()
return result
}
override fun toString(): String =
if (dependencies.isNotEmpty())
"$value" + dependencies.joinToString(prefix = " (depending on: ", postfix = ")", separator = ", ")
else
"$value"
companion object {
fun create(value: UValue, dependencies: Set<UDependency>): UValue =
if (dependencies.isNotEmpty()) UDependentValue(value, dependencies)
else value
internal fun UValue.coerceConstant(constant: UConstant): UValue =
(this as? UValueBase)?.coerceConstant(constant) ?: constant
}
}
| apache-2.0 | 1818b3a27cc6ef309a642ec1ad5adc5e | 38.824 | 140 | 0.714544 | 4.287683 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/commons/FilePageView.kt | 1 | 11102 | package org.wikipedia.commons
import android.content.Context
import android.icu.text.ListFormatter
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.Constants.PREFERRED_GALLERY_IMAGE_SIZE
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.commons.FilePageFragment.Companion.ACTIVITY_REQUEST_ADD_IMAGE_CAPTION
import org.wikipedia.commons.FilePageFragment.Companion.ACTIVITY_REQUEST_ADD_IMAGE_TAGS
import org.wikipedia.databinding.ViewFilePageBinding
import org.wikipedia.dataclient.mwapi.MwQueryPage
import org.wikipedia.descriptions.DescriptionEditActivity
import org.wikipedia.page.LinkMovementMethodExt
import org.wikipedia.richtext.RichTextUtil
import org.wikipedia.suggestededits.PageSummaryForEdit
import org.wikipedia.suggestededits.SuggestedEditsImageTagEditActivity
import org.wikipedia.util.ImageUrlUtil
import org.wikipedia.util.ResourceUtil
import org.wikipedia.util.StringUtil
import org.wikipedia.util.UriUtil
import org.wikipedia.views.ImageDetailView
import org.wikipedia.views.ImageZoomHelper
import org.wikipedia.views.ViewUtil
import java.util.*
class FilePageView constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout(context, attrs) {
val binding = ViewFilePageBinding.inflate(LayoutInflater.from(context), this)
init {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
fun setup(fragment: Fragment,
summaryForEdit: PageSummaryForEdit,
imageTags: Map<String, List<String>>,
page: MwQueryPage,
containerWidth: Int,
thumbWidth: Int,
thumbHeight: Int,
imageFromCommons: Boolean,
showFilename: Boolean,
showEditButton: Boolean,
suggestionReason: String? = null,
action: DescriptionEditActivity.Action? = null) {
loadImage(summaryForEdit, containerWidth, thumbWidth, thumbHeight)
if (showFilename) {
binding.filenameView.visibility = View.VISIBLE
binding.filenameView.binding.titleText.text = context.getString(if (imageFromCommons) R.string.suggested_edits_image_preview_dialog_file_commons else R.string.suggested_edits_image_preview_dialog_image)
binding.filenameView.binding.contentText.setTextIsSelectable(false)
binding.filenameView.binding.contentText.maxLines = 3
binding.filenameView.binding.contentText.ellipsize = TextUtils.TruncateAt.END
binding.filenameView.binding.contentText.text = StringUtil.removeNamespace(summaryForEdit.displayTitle.orEmpty())
binding.filenameView.binding.divider.visibility = View.GONE
}
binding.detailsContainer.removeAllViews()
if (summaryForEdit.pageTitle.description.isNullOrEmpty() && summaryForEdit.description.isNullOrEmpty() && showEditButton) {
addActionButton(context.getString(R.string.file_page_add_image_caption_button), imageCaptionOnClickListener(fragment, summaryForEdit))
} else if ((action == DescriptionEditActivity.Action.ADD_CAPTION || action == null) && summaryForEdit.pageTitle.description.isNullOrEmpty()) {
// Show the image description when a structured caption does not exist.
addDetail(context.getString(R.string.suggested_edits_image_preview_dialog_description_in_language_title,
WikipediaApp.getInstance().language().getAppLanguageLocalizedName(getProperLanguageCode(summaryForEdit, imageFromCommons))),
summaryForEdit.description, if (showEditButton) imageCaptionOnClickListener(fragment, summaryForEdit) else null)
} else {
addDetail(context.getString(R.string.suggested_edits_image_preview_dialog_caption_in_language_title,
WikipediaApp.getInstance().language().getAppLanguageLocalizedName(getProperLanguageCode(summaryForEdit, imageFromCommons))),
if (summaryForEdit.pageTitle.description.isNullOrEmpty()) summaryForEdit.description
else summaryForEdit.pageTitle.description, if (showEditButton) imageCaptionOnClickListener(fragment, summaryForEdit) else null)
}
if (!suggestionReason.isNullOrEmpty()) {
addDetail(context.getString(R.string.file_page_suggestion_reason), suggestionReason.capitalize(Locale.getDefault()))
}
if ((imageTags.isNullOrEmpty() || !imageTags.containsKey(getProperLanguageCode(summaryForEdit, imageFromCommons))) && showEditButton) {
addActionButton(context.getString(R.string.file_page_add_image_tags_button), imageTagsOnClickListener(fragment, page))
} else {
addDetail(context.getString(R.string.suggested_edits_image_tags), getImageTags(imageTags, getProperLanguageCode(summaryForEdit, imageFromCommons)))
}
addDetail(context.getString(R.string.suggested_edits_image_caption_summary_title_author), summaryForEdit.metadata!!.artist())
addDetail(context.getString(R.string.suggested_edits_image_preview_dialog_date), summaryForEdit.metadata!!.dateTime())
addDetail(context.getString(R.string.suggested_edits_image_caption_summary_title_source), summaryForEdit.metadata!!.credit())
addDetail(true, context.getString(R.string.suggested_edits_image_preview_dialog_licensing), summaryForEdit.metadata!!.licenseShortName(), summaryForEdit.metadata!!.licenseUrl())
if (imageFromCommons) {
addDetail(false, context.getString(R.string.suggested_edits_image_preview_dialog_more_info), context.getString(R.string.suggested_edits_image_preview_dialog_file_page_link_text), context.getString(R.string.suggested_edits_image_file_page_commons_link, summaryForEdit.title))
} else {
addDetail(false, context.getString(R.string.suggested_edits_image_preview_dialog_more_info), context.getString(R.string.suggested_edits_image_preview_dialog_file_page_wikipedia_link_text), summaryForEdit.pageTitle.uri)
}
requestLayout()
}
private fun getImageTags(imageTags: Map<String, List<String>>, languageCode: String): String? {
if (!imageTags.containsKey(languageCode)) {
return null
}
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && imageTags.isNotEmpty()) {
ListFormatter.getInstance(Locale(languageCode)).format(imageTags[languageCode])
} else {
imageTags[languageCode]?.joinToString(separator = "\n")
}
}
private fun getProperLanguageCode(summary: PageSummaryForEdit, imageFromCommons: Boolean): String {
return if (!imageFromCommons || summary.lang == "commons") {
WikipediaApp.getInstance().language().appLanguageCode
} else {
summary.lang
}
}
private fun loadImage(summaryForEdit: PageSummaryForEdit, containerWidth: Int, thumbWidth: Int, thumbHeight: Int) {
ImageZoomHelper.setViewZoomable(binding.imageView)
ViewUtil.loadImage(binding.imageView, ImageUrlUtil.getUrlForPreferredSize(summaryForEdit.thumbnailUrl!!, PREFERRED_GALLERY_IMAGE_SIZE), false, false, true, null)
binding.imageViewPlaceholder.layoutParams = LayoutParams(containerWidth, ViewUtil.adjustImagePlaceholderHeight(containerWidth.toFloat(), thumbWidth.toFloat(), thumbHeight.toFloat()))
}
private fun imageCaptionOnClickListener(fragment: Fragment, summaryForEdit: PageSummaryForEdit): OnClickListener {
return OnClickListener {
fragment.startActivityForResult(DescriptionEditActivity.newIntent(context,
summaryForEdit.pageTitle, null, summaryForEdit, null,
DescriptionEditActivity.Action.ADD_CAPTION, InvokeSource.FILE_PAGE_ACTIVITY
), ACTIVITY_REQUEST_ADD_IMAGE_CAPTION)
}
}
private fun imageTagsOnClickListener(fragment: Fragment, page: MwQueryPage): OnClickListener {
return OnClickListener {
fragment.startActivityForResult(SuggestedEditsImageTagEditActivity.newIntent(context, page, InvokeSource.FILE_PAGE_ACTIVITY),
ACTIVITY_REQUEST_ADD_IMAGE_TAGS)
}
}
private fun addDetail(titleString: String, detail: String?) {
addDetail(true, titleString, detail, null, null)
}
private fun addDetail(titleString: String, detail: String?, listener: OnClickListener?) {
addDetail(true, titleString, detail, null, listener)
}
private fun addDetail(showDivider: Boolean, titleString: String, detail: String?, externalLink: String?) {
addDetail(showDivider, titleString, detail, externalLink, null)
}
private fun addDetail(showDivider: Boolean, titleString: String, detail: String?, externalLink: String?, listener: OnClickListener?) {
if (!detail.isNullOrEmpty()) {
val view = ImageDetailView(context)
view.binding.titleText.text = titleString
view.binding.contentText.text = StringUtil.strip(StringUtil.fromHtml(detail))
RichTextUtil.removeUnderlinesFromLinks(view.binding.contentText)
if (!externalLink.isNullOrEmpty()) {
view.binding.contentText.setTextColor(ResourceUtil.getThemedColor(context, R.attr.colorAccent))
view.binding.contentText.setTextIsSelectable(false)
view.binding.externalLink.visibility = View.VISIBLE
view.binding.contentContainer.setOnClickListener {
UriUtil.visitInExternalBrowser(context, Uri.parse(UriUtil.resolveProtocolRelativeUrl(externalLink)))
}
} else {
view.binding.contentText.movementMethod = movementMethod
}
if (!showDivider) {
view.binding.divider.visibility = View.GONE
}
if (listener != null) {
view.binding.editButton.visibility = View.VISIBLE
view.binding.editButton.setOnClickListener(listener)
}
binding.detailsContainer.addView(view)
}
}
private fun addActionButton(buttonText: String, listener: OnClickListener) {
val view = ImageDetailView(context)
view.binding.titleContainer.visibility = View.GONE
view.binding.contentContainer.visibility = View.GONE
view.binding.actionButton.visibility = View.VISIBLE
view.binding.actionButton.text = buttonText
view.binding.actionButton.setOnClickListener(listener)
binding.detailsContainer.addView(view)
}
private val movementMethod = LinkMovementMethodExt { url: String ->
UriUtil.handleExternalLink(context, Uri.parse(UriUtil.resolveProtocolRelativeUrl(url)))
}
}
| apache-2.0 | 64fc23e005e2c5d1cf546f75060fd200 | 54.233831 | 286 | 0.724104 | 4.8629 | false | false | false | false |
ridibooks/rbhelper-android | src/main/kotlin/com/ridi/books/helper/io/IoHelper.kt | 1 | 3049 | package com.ridi.books.helper.io
import com.ridi.books.helper.Log
import java.io.Closeable
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.nio.ByteBuffer
private const val IOHELPER_TAG = "IoHelper"
fun File.copyTo(dest: File): Boolean {
runCatching {
copyTo(dest, overwrite = true)
}.let {
if (it.isSuccess) return true
Log.e(IOHELPER_TAG, "file copy error", it.exceptionOrNull())
return false
}
}
fun File.moveTo(dest: File): Boolean {
runCatching {
copyTo(dest, overwrite = true)
delete()
}.let {
if (it.isSuccess) return true
Log.e(IOHELPER_TAG, "file move error", it.exceptionOrNull())
return false
}
}
@Throws(IOException::class)
fun File.getBytes(): ByteArray {
this.inputStream().use { input ->
input.channel.use { channel ->
val length = length()
// Create the byte array to hold the data
val bytes = ByteArray(length.toInt())
val buffer = ByteBuffer.wrap(bytes)
var offset = 0L
var numRead: Int
do {
numRead = channel.read(buffer, offset)
offset += numRead
} while (offset < length && numRead >= 0)
return bytes
}
}
}
fun File.makeNoMediaFile() {
if (isDirectory.not()) return
val file = File(this, ".nomedia")
if (file.exists()) return
try {
file.createNewFile()
} catch (e: IOException) {
Log.e(IOHELPER_TAG, "file creating error", e)
}
}
@Throws(IOException::class)
fun InputStream.writeStreamToFile(file: File) {
runCatching {
file.outputStream().use { output ->
copyTo(output)
}
}.onFailure { throw it }
}
fun Any.saveToFile(file: File) {
runCatching {
file.createNewFile()
file.outputStream().use { fileOutput ->
ObjectOutputStream(fileOutput).use { objectOutput ->
objectOutput.writeObject(this)
objectOutput.flush()
}
}
}.onFailure { Log.e(IOHELPER_TAG, "writing object to file error", it) }
}
@Suppress("UNCHECKED_CAST")
fun <T> File.loadObject(): T? {
if (exists().not()) return null
var obj: T? = null
runCatching {
this.inputStream().use { fileInput ->
ObjectInputStream(fileInput).use { objectInput ->
obj = objectInput.readObject() as T?
}
}
}.onFailure { Log.e(IOHELPER_TAG, "loading object from file error", it) }
return obj
}
@Throws(IOException::class)
fun closeAndThrowExceptionToReport(closeable: Closeable?, primaryException: IOException?) {
var throwable = primaryException
if (closeable != null) {
try {
closeable.close()
} catch (e: IOException) {
throwable = primaryException ?: e
}
}
throwable?.let {
throw it
}
}
| mit | cee4442e6e1b2724a995ad9e8507aa81 | 23.991803 | 91 | 0.591013 | 4.131436 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/ParentAndChildWithNulls.kt | 2 | 3303 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import org.jetbrains.deft.annotations.Child
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableReferableWorkspaceEntity
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.referrersx
interface ParentWithNulls : WorkspaceEntity {
val parentData: String
@Child
val child: ChildWithNulls?
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: ParentWithNulls, ModifiableWorkspaceEntity<ParentWithNulls>, ObjBuilder<ParentWithNulls> {
override var parentData: String
override var entitySource: EntitySource
override var child: ChildWithNulls?
}
companion object: Type<ParentWithNulls, Builder>() {
operator fun invoke(parentData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ParentWithNulls {
val builder = builder()
builder.parentData = parentData
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ParentWithNulls, modification: ParentWithNulls.Builder.() -> Unit) = modifyEntity(ParentWithNulls.Builder::class.java, entity, modification)
//endregion
interface ChildWithNulls : WorkspaceEntity {
val childData: String
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: ChildWithNulls, ModifiableWorkspaceEntity<ChildWithNulls>, ObjBuilder<ChildWithNulls> {
override var childData: String
override var entitySource: EntitySource
}
companion object: Type<ChildWithNulls, Builder>() {
operator fun invoke(childData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ChildWithNulls {
val builder = builder()
builder.childData = childData
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ChildWithNulls, modification: ChildWithNulls.Builder.() -> Unit) = modifyEntity(ChildWithNulls.Builder::class.java, entity, modification)
var ChildWithNulls.Builder.parentEntity: ParentWithNulls?
get() {
return referrersx(ParentWithNulls::child).singleOrNull()
}
set(value) {
(this as ModifiableReferableWorkspaceEntity).linkExternalEntity(ParentWithNulls::class, false, if (value is List<*>) value as List<WorkspaceEntity?> else listOf(value) as List<WorkspaceEntity?> )
}
//endregion
val ChildWithNulls.parentEntity: ParentWithNulls?
get() = referrersx(ParentWithNulls::child).singleOrNull()
| apache-2.0 | b4f9a15d8e4f1b74df071127df5fcfba | 37.858824 | 203 | 0.75931 | 5.136858 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/builder/components/SegmentedButtonToolbar.kt | 1 | 10213 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.dsl.builder.components
import com.intellij.ide.ui.laf.darcula.DarculaUIUtil
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionButtonLook
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionButtonWithText
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.actionSystem.impl.IdeaActionButtonLook
import com.intellij.openapi.observable.properties.ObservableMutableProperty
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.NlsActions
import com.intellij.ui.dsl.builder.DslComponentProperty
import com.intellij.ui.dsl.builder.SpacingConfiguration
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.ApiStatus
import java.awt.*
import java.awt.event.FocusEvent
import java.awt.event.FocusListener
import java.awt.geom.Path2D
import java.awt.geom.RoundRectangle2D
import javax.swing.JComponent
import javax.swing.border.Border
import kotlin.math.max
@Deprecated("Use Row.segmentedButton")
@ApiStatus.ScheduledForRemoval
class SegmentedButtonToolbar(actionGroup: ActionGroup, private val spacingConfiguration: SpacingConfiguration) :
ActionToolbarImpl("ButtonSelector", actionGroup, true, true) {
init {
isFocusable = true
border = SegmentedButtonBorder()
setForceMinimumSize(true)
// Buttons preferred size is calculated in SegmentedButton.getPreferredSize, so reset default size
setMinimumButtonSize(Dimension(0, 0))
layoutPolicy = ActionToolbar.WRAP_LAYOUT_POLICY
putClientProperty(DslComponentProperty.VISUAL_PADDINGS, Gaps(size = DarculaUIUtil.BW.get()))
addFocusListener(object : FocusListener {
override fun focusGained(e: FocusEvent?) {
repaint()
}
override fun focusLost(e: FocusEvent?) {
repaint()
}
})
val actionLeft = DumbAwareAction.create { moveSelection(-1) }
actionLeft.registerCustomShortcutSet(ActionUtil.getShortcutSet("SegmentedButton-left"), this)
val actionRight = DumbAwareAction.create { moveSelection(1) }
actionRight.registerCustomShortcutSet(ActionUtil.getShortcutSet("SegmentedButton-right"), this)
}
override fun setEnabled(enabled: Boolean) {
super.setEnabled(enabled)
for (component in components) {
component.isEnabled = enabled
}
}
override fun paint(g: Graphics) {
super.paint(g)
// Paint selected button frame over all children
val g2 = g.create() as Graphics2D
try {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE)
g2.paint = getSegmentedButtonBorderPaint(this, true)
for (component in components) {
if ((component as? DeprecatedSegmentedButton)?.isSelected == true) {
val r = component.bounds
JBInsets.addTo(r, JBUI.insets(DarculaUIUtil.LW.unscaled.toInt()))
paintBorder(g2, r)
}
}
}
finally {
g2.dispose()
}
}
override fun createToolbarButton(action: AnAction,
look: ActionButtonLook?,
place: String,
presentation: Presentation,
minimumSize: Dimension): ActionButton {
val result = DeprecatedSegmentedButton(action, presentation, place, minimumSize, spacingConfiguration)
result.isEnabled = isEnabled
return result
}
override fun addNotify() {
super.addNotify()
// Create actions immediately, otherwise first SegmentedButtonToolbar preferred size calculation can be done without actions.
// In such case SegmentedButtonToolbar will keep narrow width for preferred size because of ActionToolbar.WRAP_LAYOUT_POLICY
updateActionsImmediately(true)
}
@ApiStatus.Internal
internal fun getSelectedOption(): Any? {
val selectedButton = getSelectedButton()
return if (selectedButton == null) null else (selectedButton.action as? DeprecatedSegmentedButtonAction<*>)?.option
}
private fun moveSelection(step: Int) {
if (components.isEmpty()) {
return
}
val selectedButton = getSelectedButton()
val selectedIndex = components.indexOf(selectedButton)
val newSelectedIndex = if (selectedIndex < 0) 0 else (selectedIndex + step).coerceIn(0, components.size - 1)
if (selectedIndex != newSelectedIndex) {
(components.getOrNull(selectedIndex) as? DeprecatedSegmentedButton)?.isSelected = false
(components[newSelectedIndex] as? DeprecatedSegmentedButton)?.click()
}
}
private fun getSelectedButton(): DeprecatedSegmentedButton? {
for (component in components) {
if ((component as? DeprecatedSegmentedButton)?.isSelected == true) {
return component
}
}
return null
}
}
@ApiStatus.Experimental
@Deprecated("Use Row.segmentedButton")
internal class DeprecatedSegmentedButtonAction<T>(val option: T,
private val property: ObservableMutableProperty<T>,
@NlsActions.ActionText optionText: String,
@NlsActions.ActionDescription optionDescription: String? = null)
: ToggleAction(optionText, optionDescription, null), DumbAware {
override fun isSelected(e: AnActionEvent): Boolean {
return property.get() == option
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (state) {
property.set(option)
}
}
}
@Deprecated("Use Row.segmentedButton")
private class DeprecatedSegmentedButton(
action: AnAction,
presentation: Presentation,
place: String?,
minimumSize: Dimension,
private val spacingConfiguration: SpacingConfiguration
) : ActionButtonWithText(action, presentation, place, minimumSize) {
init {
setLook(SegmentedButtonLook)
myPresentation.addPropertyChangeListener {
if (it.propertyName == Toggleable.SELECTED_PROPERTY) {
parent?.repaint()
}
}
}
override fun getPreferredSize(): Dimension {
val preferredSize = super.getPreferredSize()
return Dimension(preferredSize.width + spacingConfiguration.segmentedButtonHorizontalGap * 2,
preferredSize.height + spacingConfiguration.segmentedButtonVerticalGap * 2)
}
fun setSelected(selected: Boolean) {
Toggleable.setSelected(myPresentation, selected)
}
}
/**
* @param subButton determines border target: true for button inside segmented button, false for segmented button
*/
@ApiStatus.Internal
internal fun getSegmentedButtonBorderPaint(segmentedButton: Component, subButton: Boolean): Paint {
if (!segmentedButton.isEnabled) {
return JBUI.CurrentTheme.Button.disabledOutlineColor()
}
if (segmentedButton.hasFocus()) {
return JBUI.CurrentTheme.Button.focusBorderColor(false)
}
else {
if (subButton) {
return GradientPaint(0f, 0f, JBUI.CurrentTheme.SegmentedButton.SELECTED_START_BORDER_COLOR,
0f, segmentedButton.height.toFloat(), JBUI.CurrentTheme.SegmentedButton.SELECTED_END_BORDER_COLOR)
} else {
return GradientPaint(0f, 0f, JBUI.CurrentTheme.Button.buttonOutlineColorStart(false),
0f, segmentedButton.height.toFloat(), JBUI.CurrentTheme.Button.buttonOutlineColorEnd(false))
}
}
}
@ApiStatus.Internal
internal fun paintBorder(g: Graphics2D, r: Rectangle) {
val border = Path2D.Float(Path2D.WIND_EVEN_ODD)
val lw = DarculaUIUtil.LW.float
var arc = DarculaUIUtil.BUTTON_ARC.float
border.append(RoundRectangle2D.Float(r.x.toFloat(), r.y.toFloat(), r.width.toFloat(), r.height.toFloat(), arc, arc), false)
arc = max(arc - lw, 0f)
border.append(RoundRectangle2D.Float(r.x + lw, r.y + lw, r.width - lw * 2, r.height - lw * 2, arc, arc), false)
g.fill(border)
}
@ApiStatus.Internal
internal class SegmentedButtonBorder : Border {
override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) {
val g2 = g.create() as Graphics2D
try {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE)
val r = Rectangle(x, y, width, height)
val arc = DarculaUIUtil.BUTTON_ARC.float
if (c.hasFocus()) {
DarculaUIUtil.paintOutlineBorder(g2, r.width, r.height, arc, true, true, DarculaUIUtil.Outline.focus)
}
g2.paint = getSegmentedButtonBorderPaint(c, false)
JBInsets.removeFrom(r, JBUI.insets(DarculaUIUtil.BW.unscaled.toInt()))
paintBorder(g2, r)
}
finally {
g2.dispose()
}
}
override fun getBorderInsets(c: Component?): Insets {
val unscaledSize = DarculaUIUtil.BW.unscaled + DarculaUIUtil.LW.unscaled
return JBUI.insets(unscaledSize.toInt()).asUIResource()
}
override fun isBorderOpaque(): Boolean {
return false
}
}
@ApiStatus.Internal
internal object SegmentedButtonLook : IdeaActionButtonLook() {
override fun paintBorder(g: Graphics, component: JComponent, state: Int) {
// Border is painted in parent
}
override fun getStateBackground(component: JComponent, state: Int): Color {
if (!component.isEnabled) {
return component.background
}
val focused = component.parent?.hasFocus() == true
return when (state) {
ActionButtonComponent.POPPED -> JBUI.CurrentTheme.ActionButton.hoverBackground()
ActionButtonComponent.PUSHED ->
if (focused) JBUI.CurrentTheme.SegmentedButton.FOCUSED_SELECTED_BUTTON_COLOR
else JBUI.CurrentTheme.SegmentedButton.SELECTED_BUTTON_COLOR
else -> component.background
}
}
}
| apache-2.0 | 6311598f5d3bbd2aba010a11ae0719dd | 36.138182 | 158 | 0.718692 | 4.58599 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/action/Action_Reaction.kt | 1 | 20151 | package jp.juggler.subwaytooter.action
import jp.juggler.subwaytooter.ActMain
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.api.ApiTask
import jp.juggler.subwaytooter.api.TootParser
import jp.juggler.subwaytooter.api.entity.Host
import jp.juggler.subwaytooter.api.entity.InstanceCapability
import jp.juggler.subwaytooter.api.entity.TootReaction
import jp.juggler.subwaytooter.api.entity.TootStatus
import jp.juggler.subwaytooter.api.runApiTask
import jp.juggler.subwaytooter.api.syncStatus
import jp.juggler.subwaytooter.column.Column
import jp.juggler.subwaytooter.column.fireShowContent
import jp.juggler.subwaytooter.column.updateEmojiReactionByApiResponse
import jp.juggler.subwaytooter.dialog.DlgConfirm.confirm
import jp.juggler.subwaytooter.dialog.launchEmojiPicker
import jp.juggler.subwaytooter.dialog.pickAccount
import jp.juggler.subwaytooter.emoji.CustomEmoji
import jp.juggler.subwaytooter.emoji.UnicodeEmoji
import jp.juggler.subwaytooter.table.AcctColor
import jp.juggler.subwaytooter.table.SavedAccount
import jp.juggler.subwaytooter.util.DecodeOptions
import jp.juggler.util.*
private val rePleromaStatusUrl = """/objects/""".toRegex()
private fun String.likePleromaStatusUrl(): Boolean {
return rePleromaStatusUrl.find(this) != null
}
// 長押しでない普通のリアクション操作
fun ActMain.reactionAdd(
column: Column,
status: TootStatus,
// Unicode絵文字、 :name: :name@.: :name@domain: name name@domain 等
codeArg: String? = null,
urlArg: String? = null,
// 確認済みなら真
isConfirmed: Boolean = false,
) {
val activity = this@reactionAdd
val accessInfo = column.accessInfo
val canMultipleReaction = InstanceCapability.canMultipleReaction(accessInfo)
val hasMyReaction = status.reactionSet?.hasMyReaction() == true
if (hasMyReaction && !canMultipleReaction) {
showToast(false, R.string.already_reactioned)
return
}
if (codeArg == null) {
launchEmojiPicker(
activity,
accessInfo,
closeOnSelected = true
) { emoji, _ ->
var newUrl: String? = null
val newCode: String = when (emoji) {
is UnicodeEmoji -> emoji.unifiedCode
is CustomEmoji -> {
newUrl = emoji.staticUrl
if (accessInfo.isMisskey) {
":${emoji.shortcode}:"
} else {
emoji.shortcode
}
}
}
reactionAdd(column, status, newCode, newUrl)
}
return
}
var code = codeArg
if (accessInfo.isMisskey) {
val (name, domain) = TootReaction.splitEmojiDomain(code)
if (name == null) {
// unicode emoji
} else when (domain) {
null, "", ".", accessInfo.apDomain.ascii -> {
// normalize to local custom emoji
code = ":$name:"
}
else -> {
/*
#misskey のリアクションAPIはリモートのカスタム絵文字のコードをフォールバック絵文字に変更して、
何の追加情報もなしに204 no contentを返す。
よってクライアントはAPI応答からフォールバックが発生したことを認識できず、
後から投稿をリロードするまで気が付かない。
この挙動はこの挙動は多くのユーザにとって受け入れられないと判断するので、
クライアント側で事前にエラー扱いにする方が良い。
*/
showToast(true, R.string.cant_reaction_remote_custom_emoji, code)
return
}
}
}
if (canMultipleReaction && TootReaction.isCustomEmoji(code)) {
showToast(false, "can't reaction with custom emoji from this account")
return
}
activity.launchAndShowError {
if (!isConfirmed) {
val options = DecodeOptions(
activity,
accessInfo,
decodeEmoji = true,
enlargeEmoji = 1.5f,
enlargeCustomEmoji = 1.5f
)
val emojiSpan = TootReaction.toSpannableStringBuilder(options, code, urlArg)
confirm(
getString(R.string.confirm_reaction, emojiSpan, AcctColor.getNickname(accessInfo)),
accessInfo.confirm_reaction,
) { newConfirmEnabled ->
accessInfo.confirm_reaction = newConfirmEnabled
accessInfo.saveSetting()
}
}
var resultStatus: TootStatus? = null
runApiTask(accessInfo) { client ->
when {
accessInfo.isMisskey -> client.request(
"/api/notes/reactions/create",
accessInfo.putMisskeyApiToken().apply {
put("noteId", status.id.toString())
put("reaction", code)
}.toPostRequestBuilder()
) // 成功すると204 no content
canMultipleReaction -> client.request(
"/api/v1/pleroma/statuses/${status.id}/reactions/${code.encodePercent("@")}",
"".toFormRequestBody().toPut()
)?.also { result ->
// 成功すると新しいステータス
resultStatus = TootParser(activity, accessInfo).status(result.jsonObject)
}
else -> client.request(
"/api/v1/statuses/${status.id}/emoji_reactions/${code.encodePercent("@")}",
"".toFormRequestBody().toPut()
)?.also { result ->
// 成功すると新しいステータス
resultStatus = TootParser(activity, accessInfo).status(result.jsonObject)
}
}
}?.let { result ->
result.error?.let { error(it) }
when (val resCode = result.response?.code) {
in 200 until 300 -> when (val newStatus = resultStatus) {
null ->
if (status.increaseReactionMisskey(code, true, caller = "addReaction")) {
// 1個だけ描画更新するのではなく、TLにある複数の要素をまとめて更新する
column.fireShowContent(
reason = "addReaction complete",
reset = true
)
}
else ->
activity.appState.columnList.forEach { column ->
if (column.accessInfo.acct == accessInfo.acct) {
column.updateEmojiReactionByApiResponse(newStatus)
}
}
}
else -> showToast(false, "HTTP error $resCode")
}
}
}
}
// 長押しでない普通のリアクション操作
fun ActMain.reactionRemove(
column: Column,
status: TootStatus,
reactionArg: TootReaction? = null,
confirmed: Boolean = false,
) {
val activity = this
val accessInfo = column.accessInfo
val canMultipleReaction = InstanceCapability.canMultipleReaction(accessInfo)
// 指定されたリアクションまたは自分がリアクションした最初のもの
val reaction = reactionArg ?: status.reactionSet?.find { it.count > 0 && it.me }
if (reaction == null) {
showToast(false, R.string.not_reactioned)
return
}
launchAndShowError {
if (!confirmed) {
val options = DecodeOptions(
activity,
accessInfo,
decodeEmoji = true,
enlargeEmoji = 1.5f,
enlargeCustomEmoji = 1.5f
)
val emojiSpan = reaction.toSpannableStringBuilder(options, status)
confirm(R.string.reaction_remove_confirm, emojiSpan)
}
var resultStatus: TootStatus? = null
runApiTask(accessInfo) { client ->
when {
accessInfo.isMisskey -> client.request(
"/api/notes/reactions/delete",
accessInfo.putMisskeyApiToken().apply {
put("noteId", status.id.toString())
}.toPostRequestBuilder()
) // 成功すると204 no content
canMultipleReaction -> client.request(
"/api/v1/pleroma/statuses/${status.id}/reactions/${reaction.name.encodePercent("@")}",
"".toFormRequestBody().toDelete()
)?.also { result ->
// 成功すると新しいステータス
resultStatus = TootParser(activity, accessInfo).status(result.jsonObject)
}
else -> client.request(
"/api/v1/statuses/${status.id}/emoji_unreaction",
"".toFormRequestBody().toPost()
)?.also { result ->
// 成功すると新しいステータス
resultStatus = TootParser(activity, accessInfo).status(result.jsonObject)
}
}
}?.let { result ->
val resCode = result.response?.code
when {
result.error != null ->
activity.showToast(false, result.error)
resCode !in 200 until 300 -> showToast(false, "HTTP error $resCode")
else -> {
when (val newStatus = resultStatus) {
null ->
if (status.decreaseReactionMisskey(reaction.name,
true,
"removeReaction")
) {
// 1個だけ描画更新するのではなく、TLにある複数の要素をまとめて更新する
column.fireShowContent(reason = "removeReaction complete",
reset = true)
}
else ->
activity.appState.columnList.forEach { column ->
if (column.accessInfo.acct == accessInfo.acct) {
column.updateEmojiReactionByApiResponse(newStatus)
}
}
}
}
}
}
}
}
// リアクションの別アカ操作で使う
// 選択済みのアカウントと同期済みのステータスにリアクションを行う
private fun ActMain.reactionWithoutUi(
accessInfo: SavedAccount,
resolvedStatus: TootStatus,
reactionCode: String? = null,
reactionImage: String? = null,
callback: () -> Unit,
) {
val activity = this
if (reactionCode == null) {
launchEmojiPicker(activity, accessInfo, closeOnSelected = true) { emoji, _ ->
var newUrl: String? = null
val newCode = when (emoji) {
is UnicodeEmoji -> emoji.unifiedCode
is CustomEmoji -> {
newUrl = emoji.staticUrl
if (accessInfo.isMisskey) {
":${emoji.shortcode}:"
} else {
emoji.shortcode
}
}
}
reactionWithoutUi(
accessInfo = accessInfo,
resolvedStatus = resolvedStatus,
reactionCode = newCode,
reactionImage = newUrl,
callback = callback
)
}
return
}
val canMultipleReaction = InstanceCapability.canMultipleReaction(accessInfo)
val options = DecodeOptions(
activity,
accessInfo,
decodeEmoji = true,
enlargeEmoji = 1.5f,
enlargeCustomEmoji = 1.5f
)
val emojiSpan = TootReaction.toSpannableStringBuilder(options, reactionCode, reactionImage)
val isCustomEmoji = TootReaction.isCustomEmoji(reactionCode)
val url = resolvedStatus.url
launchAndShowError {
when {
isCustomEmoji && canMultipleReaction ->
error("can't reaction with custom emoji from this account")
isCustomEmoji && url?.likePleromaStatusUrl() == true -> confirm(
R.string.confirm_reaction_to_pleroma,
emojiSpan,
AcctColor.getNickname(accessInfo),
resolvedStatus.account.acct.host?.pretty ?: "(null)"
)
else -> confirm(
getString(R.string.confirm_reaction, emojiSpan, AcctColor.getNickname(accessInfo)),
accessInfo.confirm_reaction,
) { newConfirmEnabled ->
accessInfo.confirm_reaction = newConfirmEnabled
accessInfo.saveSetting()
}
}
// var resultStatus: TootStatus? = null
runApiTask(accessInfo) { client ->
when {
accessInfo.isMisskey -> client.request(
"/api/notes/reactions/create",
accessInfo.putMisskeyApiToken().apply {
put("noteId", resolvedStatus.id.toString())
put("reaction", reactionCode)
}.toPostRequestBuilder()
) // 成功すると204 no content
canMultipleReaction -> client.request(
"/api/v1/pleroma/statuses/${resolvedStatus.id}/reactions/${
reactionCode.encodePercent("@")
}",
"".toFormRequestBody().toPut()
) // 成功すると更新された投稿
else -> client.request(
"/api/v1/statuses/${resolvedStatus.id}/emoji_reactions/${reactionCode.encodePercent()}",
"".toFormRequestBody().toPut()
) // 成功すると更新された投稿
}
}?.let { result ->
when (val error = result.error) {
null -> callback()
else -> showToast(true, error)
}
}
}
}
// リアクションの別アカ操作で使う
// 選択済みのアカウントと同期済みのステータスと同期まえのリアクションから、同期後のリアクションコードを計算する
// 解決できなかった場合はnullを返す
private fun ActMain.reactionFixCode(
timelineAccount: SavedAccount,
actionAccount: SavedAccount,
reaction: TootReaction,
): String? {
val pair = reaction.splitEmojiDomain()
pair.first ?: return reaction.name // null または Unicode絵文字
val srcDomain = when (val d = pair.second) {
null, ".", "" -> timelineAccount.apDomain
else -> Host.parse(d)
}
// リアクション者から見てローカルな絵文字
if (srcDomain == actionAccount.apDomain) {
return when {
actionAccount.isMisskey -> ":${pair.first}:"
else -> pair.first
}
}
// リアクション者からみてリモートの絵文字
val newName = "${pair.first}@$srcDomain"
if (actionAccount.isMisskey) {
/*
Misskey のリアクションAPIはリモートのカスタム絵文字のコードをフォールバック絵文字に変更して、
何の追加情報もなしに204 no contentを返す。
よってクライアントはAPI応答からフォールバックが発生したことを認識できず、
後から投稿をリロードするまで気が付かない。
この挙動はこの挙動は多くのユーザにとって受け入れられないと判断するので、
クライアント側で事前にエラー扱いにする方が良い。
*/
} else {
// Fedibirdの場合、ステータスを同期した時点で絵文字も同期されてると期待できるのだろうか?
// 実際に試してみると
// nightly.fedibird.comの投稿にローカルな絵文字を付けた後、
// その投稿のURLをfedibird.comの検索欄にいれてローカルに同期すると、
// すでにインポート済みの投稿だとリアクション集合は古いままなのだった。
//
// if (resolvedStatus.reactionSet?.any { it.name == newName } == true)
return newName
}
// エラー
showToast(true, R.string.cant_reaction_remote_custom_emoji, newName)
return null
}
fun ActMain.reactionFromAnotherAccount(
timelineAccount: SavedAccount,
statusArg: TootStatus?,
reaction: TootReaction? = null,
) {
statusArg ?: return
val activity = this
launchMain {
fun afterResolveStatus(
actionAccount: SavedAccount,
resolvedStatus: TootStatus,
) {
val code = if (reaction == null) {
null // あとで選択する
} else {
reactionFixCode(
timelineAccount = timelineAccount,
actionAccount = actionAccount,
reaction = reaction,
) ?: return // エラー終了の場合がある
}
reactionWithoutUi(
accessInfo = actionAccount,
resolvedStatus = resolvedStatus,
reactionCode = code,
callback = reactionCompleteCallback,
)
}
val list = accountListCanReaction() ?: return@launchMain
if (list.isEmpty()) {
showToast(false, R.string.not_available_for_current_accounts)
return@launchMain
}
pickAccount(
accountListArg = list.toMutableList(),
bAuto = false,
message = activity.getString(R.string.account_picker_reaction)
)?.let { action_account ->
if (calcCrossAccountMode(timelineAccount, action_account).isNotRemote) {
afterResolveStatus(action_account, statusArg)
} else {
var newStatus: TootStatus? = null
runApiTask(action_account, progressStyle = ApiTask.PROGRESS_NONE) { client ->
val (result, status) = client.syncStatus(action_account, statusArg)
newStatus = status
result
}?.let { result ->
result.error?.let {
activity.showToast(true, it)
return@launchMain
}
newStatus?.let { afterResolveStatus(action_account, it) }
}
}
}
}
}
fun ActMain.clickReaction(accessInfo: SavedAccount, column: Column, status: TootStatus) {
val canMultipleReaction = InstanceCapability.canMultipleReaction(accessInfo)
val hasMyReaction = status.reactionSet?.hasMyReaction() == true
val bRemoveButton = hasMyReaction && !canMultipleReaction
when {
!TootReaction.canReaction(accessInfo) ->
reactionFromAnotherAccount(
accessInfo,
status
)
bRemoveButton ->
reactionRemove(column, status)
else ->
reactionAdd(column, status)
}
}
| apache-2.0 | 2e0664ac6e79876227f387987fed6b7e | 34.370297 | 108 | 0.527413 | 4.535062 | false | false | false | false |
LittleMikeDev/gishgraph | src/test/kotlin/uk/co/littlemike/gishgraph/ddag/git/GitRepository.kt | 1 | 787 | package uk.co.littlemike.gishgraph.ddag.git
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.revwalk.RevWalk
import uk.co.littlemike.gishgraph.extensions.use
import java.nio.file.Path
class GitRepository(val workingDirectory: Path) {
val git : Git = Git.init().setDirectory(workingDirectory.toFile()).call()
fun isClean() = git.status().call().isClean
fun asRemote(id: String) = workingDirectory.remote(id)
fun refExists(refName: String) = git.repository.findRef(refName) != null
fun findCommit(refName: String): RevCommit? {
val commitId = git.repository.findRef(refName)?.leaf?.objectId ?: return null
RevWalk(git.repository).use {
return it.parseCommit(commitId)
}
}
}
| bsd-2-clause | 51b568e7ba211ca48f2ede66c47ee466 | 31.791667 | 85 | 0.717916 | 3.561086 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/config/ISYProperties.kt | 1 | 2632 | package top.zbeboy.isy.config
import org.springframework.boot.context.properties.ConfigurationProperties
/**
* Spring boot 配置属性加载.
*
* @author zbeboy
* @version 1.0
* @since 1.0
*/
@ConfigurationProperties(prefix = "isy", ignoreUnknownFields = false)
class ISYProperties {
private val async = Async()
private val mobile = Mobile()
private val mail = Mail()
private val constants = Constants()
private val weixin = Weixin()
private val security = Security()
private val certificate = Certificate()
fun getAsync(): Async {
return async
}
fun getMobile(): Mobile {
return mobile
}
fun getMail(): Mail {
return mail
}
fun getConstants(): Constants {
return constants
}
fun getWeixin(): Weixin {
return weixin
}
fun getSecurity(): Security {
return security
}
fun getCertificate(): Certificate {
return certificate
}
/**
* 异常初始化参数
*/
class Async {
var corePoolSize = 2
var maxPoolSize = 50
var queueCapacity = 10000
}
/**
* 短信初始化参数
*/
class Mobile {
var isOpen: Boolean = false
var url: String? = null
var userId: String? = null
var account: String? = null
var password: String? = null
var sign: String? = null
}
/**
* 邮件初始化参数
*/
class Mail {
var user: String? = null
var password: String? = null
var host: String? = null
var port: Int = 0
var apiUser: String? = null
var apiKey: String? = null
var fromName: String? = null
var sendMethod: Int = 0
var isOpen: Boolean = false
}
/**
* 通用初始化参数
*/
class Constants {
var mailForm: String? = null
var serverHttpPort: Int = 0
var serverHttpsPort: Int = 0
var tempDir: String? = null
var undertowListenerIp: String? = null
}
/**
* 微信初始化参数
*/
class Weixin {
var token: String? = null
var appId: String? = null
var appSecret: String? = null
var encodingAESKey: String? = null
var smallToken: String? = null
var smallEncodingAESKey: String? = null
}
/**
* Security初始化参数
*/
class Security {
var desDefaultKey: String? = null
}
/**
* let's encrypt 证书参数
*/
class Certificate {
var place: String? = null
}
} | mit | 0f335e9a90eac694f0fd36ab1717edff | 15.664474 | 74 | 0.547788 | 4.291525 | false | false | false | false |
akhbulatov/wordkeeper | app/src/main/java/com/akhbulatov/wordkeeper/presentation/ui/global/models/WordUiModel.kt | 1 | 511 | package com.akhbulatov.wordkeeper.presentation.ui.global.models
import android.os.Parcelable
import com.akhbulatov.wordkeeper.domain.global.models.Word
import kotlinx.android.parcel.Parcelize
@Parcelize
data class WordUiModel(
val id: Long,
val name: String,
val translation: String,
val datetime: Long,
val category: String
) : Parcelable
fun Word.toUiModel() = WordUiModel(
id = id,
name = name,
translation = translation,
datetime = datetime,
category = category
)
| apache-2.0 | a66c8d98ba28884c12a731b6312444fd | 22.227273 | 63 | 0.729941 | 3.992188 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer | data/src/main/java/de/ph1b/audiobook/data/Book.kt | 1 | 2388 | package de.ph1b.audiobook.data
import android.content.Context
import android.os.Environment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.util.UUID
data class Book(
val id: UUID,
val content: BookContent,
val metaData: BookMetaData
) {
init {
require(content.id == id) { "wrong book content" }
require(metaData.id == id) { "Wrong metaData for $this" }
}
val type = metaData.type
val author = metaData.author
val name = metaData.name
val root = metaData.root
fun updateMetaData(update: BookMetaData.() -> BookMetaData): Book = copy(
metaData = update(metaData)
)
val coverTransitionName = "bookCoverTransition_$id"
inline fun updateContent(update: BookContent.() -> BookContent): Book = copy(
content = update(content)
)
inline fun update(
updateContent: BookContent.() -> BookContent = { this },
updateMetaData: BookMetaData.() -> BookMetaData = { this },
updateSettings: BookSettings.() -> BookSettings = { this }
): Book {
val newSettings = updateSettings(content.settings)
val contentWithNewSettings = if (newSettings === content.settings) {
content
} else {
content.copy(
settings = newSettings
)
}
val newContent = updateContent(contentWithNewSettings)
val newMetaData = updateMetaData(metaData)
return copy(content = newContent, metaData = newMetaData)
}
suspend fun coverFile(context: Context): File = withContext(Dispatchers.IO) {
val name = type.name + if (type == Type.COLLECTION_FILE || type == Type.COLLECTION_FOLDER) {
// if its part of a collection, take the first file
content.chapters.first().file.absolutePath.replace("/", "")
} else {
// if its a single, just take the root
root.replace("/", "")
} + ".jpg"
val externalStoragePath = Environment.getExternalStorageDirectory().absolutePath
val coverFile = File(
"$externalStoragePath/Android/data/${context.packageName}",
name
)
if (!coverFile.parentFile.exists()) {
//noinspection ResultOfMethodCallIgnored
coverFile.parentFile.mkdirs()
}
coverFile
}
enum class Type {
COLLECTION_FOLDER,
COLLECTION_FILE,
SINGLE_FOLDER,
SINGLE_FILE
}
companion object {
const val SPEED_MAX = 2.5F
const val SPEED_MIN = 0.5F
}
}
| lgpl-3.0 | 4a05521e897f59b0a6ce80223e6f5a1a | 26.767442 | 96 | 0.677136 | 4.241563 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/checkers/ImmutableOptionsAnnotationChecker.kt | 6 | 2090 | // 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.annotator.checkers
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.psi.PsiModifier
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArrayInitializer
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.transformations.immutable.GROOVY_TRANSFORM_IMMUTABLE_OPTIONS
import org.jetbrains.plugins.groovy.transformations.immutable.KNOWN_IMMUTABLES_OPTION
class ImmutableOptionsAnnotationChecker : CustomAnnotationChecker() {
override fun checkArgumentList(holder: AnnotationHolder, annotation: GrAnnotation): Boolean {
if (GROOVY_TRANSFORM_IMMUTABLE_OPTIONS != annotation.qualifiedName) return false
val containingClass = PsiTreeUtil.getParentOfType(annotation, GrTypeDefinition::class.java) ?: return false
val immutableFieldsList = AnnotationUtil.findDeclaredAttribute(annotation, KNOWN_IMMUTABLES_OPTION)?.value ?: return false
val fields = (immutableFieldsList as? GrAnnotationArrayInitializer)?.initializers ?: return false
for (literal in fields.filterIsInstance<GrLiteral>()) {
val value = literal.value as? String ?: continue
val field = containingClass.findCodeFieldByName(value, false) as? GrField
if (field == null || !field.isProperty || field.hasModifierProperty(PsiModifier.STATIC)) {
holder.createErrorAnnotation(literal, GroovyBundle.message("immutable.options.property.not.exist", value))
}
}
return false
}
} | apache-2.0 | 3698ff16c40099182e8bd2cab33bdfef | 62.363636 | 140 | 0.811483 | 4.603524 | false | false | false | false |
google/intellij-community | plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/synthetic/AbstractPerformanceImportTest.kt | 5 | 5765 | // 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.perf.synthetic
import com.intellij.openapi.application.runWriteAction
import com.intellij.psi.PsiDocumentManager
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.RunAll
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.core.formatter.KotlinPackageEntry
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.test.*
import org.jetbrains.kotlin.idea.testFramework.Stats
import org.jetbrains.kotlin.idea.testFramework.performanceTest
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import java.io.File
abstract class AbstractPerformanceImportTest : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
protected abstract fun stats(): Stats
override fun tearDown() {
RunAll(
ThrowableRunnable { super.tearDown() }
).run()
}
protected fun doPerfTest(unused: String) {
val testName = getTestName(false)
configureCodeStyleAndRun(project) {
val fixture = myFixture
val dependencySuffixes = listOf(".dependency.kt", ".dependency.java", ".dependency1.kt", ".dependency2.kt")
for (suffix in dependencySuffixes) {
val dependencyPath = fileName().replace(".kt", suffix)
if (File(testDataPath, dependencyPath).exists()) {
fixture.configureByFile(dependencyPath)
}
}
fixture.configureByFile(fileName())
var file = fixture.file as KtFile
var fileText = file.text
val codeStyleSettings = file.kotlinCustomSettings
codeStyleSettings.NAME_COUNT_TO_USE_STAR_IMPORT = InTextDirectivesUtils.getPrefixedInt(
fileText,
"// NAME_COUNT_TO_USE_STAR_IMPORT:"
) ?: nameCountToUseStarImportDefault
codeStyleSettings.NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS = InTextDirectivesUtils.getPrefixedInt(
fileText,
"// NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS:"
) ?: nameCountToUseStarImportForMembersDefault
codeStyleSettings.IMPORT_NESTED_CLASSES = InTextDirectivesUtils.getPrefixedBoolean(
fileText,
"// IMPORT_NESTED_CLASSES:"
) ?: false
InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, "// PACKAGE_TO_USE_STAR_IMPORTS:").forEach {
codeStyleSettings.PACKAGES_TO_USE_STAR_IMPORTS.addEntry(KotlinPackageEntry(it.trim(), false))
}
InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, "// PACKAGES_TO_USE_STAR_IMPORTS:").forEach {
codeStyleSettings.PACKAGES_TO_USE_STAR_IMPORTS.addEntry(KotlinPackageEntry(it.trim(), true))
}
var descriptorName = InTextDirectivesUtils.findStringWithPrefixes(file.text, "// IMPORT:")
?: error("No IMPORT directive defined")
var filter: (DeclarationDescriptor) -> Boolean = { true }
if (descriptorName.startsWith("class:")) {
filter = { it is ClassDescriptor }
descriptorName = descriptorName.substring("class:".length).trim()
}
val fqName = FqName(descriptorName)
val importInsertHelper = ImportInsertHelper.getInstance(project)
val psiDocumentManager = PsiDocumentManager.getInstance(project)
performanceTest<Unit, String> {
name(testName)
stats(stats())
setUp {
fixture.configureByFile(fileName())
file = fixture.file as KtFile
fileText = file.text
}
test {
it.value = project.executeWriteCommand<String?>("") {
perfTestCore(file, fqName, filter, descriptorName, importInsertHelper, psiDocumentManager)
}
}
tearDown {
val log = it.value
val testPath = dataFilePath(fileName())
val afterFile = File("$testPath.after")
KotlinTestUtils.assertEqualsToFile(afterFile, fixture.file.text)
if (log != null) {
val logFile = File("$testPath.log")
if (log.isNotEmpty()) {
KotlinTestUtils.assertEqualsToFile(logFile, log)
} else {
assertFalse(logFile.exists())
}
}
runWriteAction {
myFixture.file.delete()
}
}
}
}
}
abstract fun perfTestCore(
file: KtFile,
fqName: FqName,
filter: (DeclarationDescriptor) -> Boolean,
descriptorName: String,
importInsertHelper: ImportInsertHelper,
psiDocumentManager: PsiDocumentManager
): String?
protected open val nameCountToUseStarImportDefault: Int
get() = 1
protected open val nameCountToUseStarImportForMembersDefault: Int
get() = 3
}
| apache-2.0 | 47e16baf0cd45eea2859f61ce02804aa | 40.178571 | 120 | 0.62307 | 5.591659 | false | true | false | false |
apollographql/apollo-android | apollo-adapters/src/jsMain/kotlin/com/apollographql/apollo3/adapter/BigDecimal.kt | 1 | 2441 | package com.apollographql.apollo3.adapter
@JsModule("big.js")
@JsNonModule
internal external fun jsBig(raw: dynamic): Big
@JsName("Number")
internal external fun jsNumber(raw: dynamic): Number
internal external class Big {
fun plus(other: Big): Big
fun minus(other: Big): Big
fun times(other: Big): Big
fun div(other: Big): Big
fun cmp(other: Big): Int
fun eq(other: Big): Boolean
fun round(dp: Int, rm: Int): Big
}
actual class BigDecimal {
internal val raw: Big
internal constructor(raw: Big) {
this.raw = raw
}
constructor() : this(raw = jsBig(0))
actual constructor(strVal: String) : this(raw = jsBig(strVal))
actual constructor(doubleVal: Double) {
check(!doubleVal.isNaN() && !doubleVal.isInfinite())
raw = jsBig(doubleVal)
}
actual constructor(intVal: Int) : this(raw = jsBig(intVal))
// JS does not support 64-bit integer natively.
actual constructor(longVal: Long) : this(raw = jsBig(longVal.toString()))
actual fun add(augend: BigDecimal): BigDecimal = BigDecimal(raw = raw.plus(augend.raw))
actual fun subtract(subtrahend: BigDecimal): BigDecimal = BigDecimal(raw = raw.minus(subtrahend.raw))
actual fun multiply(multiplicand: BigDecimal): BigDecimal = BigDecimal(raw = raw.times(multiplicand.raw))
actual fun divide(divisor: BigDecimal): BigDecimal = BigDecimal(raw = raw.div(divisor.raw))
actual fun negate(): BigDecimal = BigDecimal().subtract(this)
actual fun signum(): Int {
return raw.cmp(jsBig(0))
}
fun toInt(): Int {
return jsNumber(raw).toInt()
}
fun toLong(): Long {
// JSNumber is double precision, so it cannot exactly represent 64-bit `Long`.
return toString().toLong()
}
fun toShort(): Short {
return jsNumber(raw).toShort()
}
fun toByte(): Byte {
return jsNumber(raw).toByte()
}
fun toChar(): Char {
return jsNumber(raw).toChar()
}
fun toDouble(): Double {
return jsNumber(raw).toDouble()
}
fun toFloat(): Float {
return jsNumber(raw).toFloat()
}
override fun equals(other: Any?): Boolean {
if (other is BigDecimal) {
return raw.eq(other.raw)
}
return false
}
override fun hashCode(): Int = raw.toString().hashCode()
override fun toString(): String = raw.toString()
}
actual fun BigDecimal.toNumber(): Number {
val rounded = raw.round(0, 0)
return if (raw.minus(rounded).eq(jsBig(0))) {
toLong()
} else {
toDouble()
}
}
| mit | e81933491eff071b2ba12078be5534ef | 22.471154 | 107 | 0.671446 | 3.654192 | false | false | false | false |
mikepenz/Android-Iconics | iconics-core/src/main/java/com/mikepenz/iconics/utils/IconicsConverters.kt | 1 | 7456 | /*
* Copyright 2020 Mike Penz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE")
package com.mikepenz.iconics.utils
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.DimenRes
import androidx.annotation.Dimension
import androidx.core.graphics.drawable.IconCompat
import com.mikepenz.iconics.IconicsColor
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.IconicsSize
import com.mikepenz.iconics.dsl.NON_READABLE
// VARIOUS convenient extension functions for quick common setters
var IconicsDrawable.colorString: String
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(value) {
color = IconicsColor.parse(value)
}
var IconicsDrawable.colorRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(@ColorRes value) {
color = IconicsColor.colorRes(value)
}
var IconicsDrawable.contourColorString: String
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(value) {
contourColor = IconicsColor.parse(value)
}
var IconicsDrawable.contourColorRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(@ColorRes value) {
contourColor = IconicsColor.colorRes(value)
}
var IconicsDrawable.backgroundColorString: String
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(value) {
backgroundColor = IconicsColor.parse(value)
}
var IconicsDrawable.backgroundColorRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(@ColorRes value) {
backgroundColor = IconicsColor.colorRes(value)
}
var IconicsDrawable.backgroundContourColorString: String
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(value) {
backgroundContourColor = IconicsColor.parse(value)
}
var IconicsDrawable.backgroundContourColorRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(@ColorRes value) {
backgroundContourColor = IconicsColor.colorRes(value)
}
var IconicsDrawable.sizeDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(@Dimension(unit = Dimension.DP) value) {
size = IconicsSize.dp(value)
}
var IconicsDrawable.sizeRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(@DimenRes value) {
size = IconicsSize.res(value)
}
var IconicsDrawable.paddingDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(@Dimension(unit = Dimension.DP) value) {
padding = IconicsSize.dp(value)
}
var IconicsDrawable.paddingRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(@DimenRes value) {
padding = IconicsSize.res(value)
}
var IconicsDrawable.roundedCornersDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(@Dimension(unit = Dimension.DP) value) {
roundedCorners = IconicsSize.dp(value)
}
var IconicsDrawable.roundedCornersRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(@DimenRes value) {
roundedCorners = IconicsSize.res(value)
}
var IconicsDrawable.contourWidthDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(@Dimension(unit = Dimension.DP) value) {
contourWidth = IconicsSize.dp(value)
}
var IconicsDrawable.contourWidthRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE)
get() = throw UnsupportedOperationException()
set(@DimenRes value) {
contourWidth = IconicsSize.res(value)
}
/**
* Pretty converter to [androidx.core.graphics.drawable.IconCompat]
*
* Note: use [IconCompat.toIcon] to transform into Platform's Icon
*/
inline fun IconicsDrawable.toAndroidIconCompat(): IconCompat {
return IconCompat.createWithBitmap(toBitmap())
}
/** Pretty converter to [IconicsSize.dp] */
@Deprecated("Use IconicsSize.dp() instead", ReplaceWith("IconicsSize.dp(x)", "com.mikepenz.iconics.IconicsSize"))
@SuppressLint("SupportAnnotationUsage")
inline fun @receiver:Dimension(unit = Dimension.DP) Number.toIconicsSizeDp(): IconicsSize {
return IconicsSize.dp(this)
}
/** Pretty converter to [IconicsSize.px] */
@Deprecated("Use IconicsSize.px() instead", ReplaceWith("IconicsSize.px(x)", "com.mikepenz.iconics.IconicsSize"))
@SuppressLint("SupportAnnotationUsage")
inline fun @receiver:Dimension(unit = Dimension.PX) Number.toIconicsSizePx(): IconicsSize {
return IconicsSize.px(this)
}
/** Pretty converter to [IconicsSize.res] */
@Deprecated("Use IconicsSize.res() instead", ReplaceWith("IconicsSize.res(x)", "com.mikepenz.iconics.IconicsSize"))
inline fun @receiver:DimenRes Int.toIconicsSizeRes(): IconicsSize {
return IconicsSize.res(toInt())
}
/** Pretty converter to [IconicsColor.colorInt] */
@Deprecated("Use IconicsColor.colorInt() instead", ReplaceWith("IconicsColor.colorInt(x)", "com.mikepenz.iconics.IconicsColor"))
inline fun @receiver:ColorInt Int.toIconicsColor(): IconicsColor {
return IconicsColor.colorInt(this)
}
/** Pretty converter to [IconicsColor.parse] */
@Deprecated("Use IconicsColor.parse() instead", ReplaceWith("IconicsColor.parse(x)", "com.mikepenz.iconics.IconicsColor"))
inline fun String.toIconicsColor(): IconicsColor {
return IconicsColor.parse(this)
}
/** Pretty converter to [IconicsColor.colorList] */
@Deprecated("Use IconicsColor.colorList() instead", ReplaceWith("IconicsColor.colorList(x)", "com.mikepenz.iconics.IconicsColor"))
inline fun ColorStateList.toIconicsColor(): IconicsColor {
return IconicsColor.colorList(this)
}
/** Pretty converter to [IconicsColor.colorRes] */
@Deprecated("Use IconicsColor.colorRes() instead", ReplaceWith("IconicsColor.colorRes(x)", "com.mikepenz.iconics.IconicsColor"))
inline fun @receiver:ColorRes Int.toIconicsColorRes(): IconicsColor {
return IconicsColor.colorRes(this)
} | apache-2.0 | 2f88d1162cd5ce35d7b7f50ddfb42a3d | 36.852792 | 130 | 0.744769 | 4.297406 | false | false | false | false |
LWJGL-CI/lwjgl3 | modules/generator/src/main/kotlin/org/lwjgl/generator/Modules.kt | 2 | 46670 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.generator
import java.io.*
enum class Module(
val key: String,
val packageName: String,
packageInfo: String,
internal val callingConvention: CallingConvention = CallingConvention.DEFAULT,
internal val library: JNILibrary? = null,
internal val arrayOverloads: Boolean = true
) {
CORE("core", "org.lwjgl.system", ""),
CORE_JNI(
"core.jni",
"org.lwjgl.system.jni",
"Contains bindings to the Java Native Interface (JNI)."
),
CORE_LIBC(
"core.libc",
"org.lwjgl.system.libc",
"Contains bindings to standard C library APIs."
),
CORE_LIBFFI(
"core.libffi",
"org.lwjgl.system.libffi",
"""
Contains bindings to the ${url("https://sourceware.org/libffi/", "libffi")}, a portable, high level programming interface to various calling
conventions. This allows a programmer to call any function specified by a call interface description at run-time.
"""
),
CORE_LINUX(
"core.linux",
"org.lwjgl.system.linux",
"Contains bindings to native APIs specific to the Linux operating system."
),
CORE_LINUX_LIBURING(
"core.linux.liburing",
"org.lwjgl.system.linux.liburing",
"Contains bindings to liburing." // TODO:
),
CORE_MACOS(
"core.macos",
"org.lwjgl.system.macosx",
"Contains bindings to native APIs specific to the macOS operating system."
),
CORE_WINDOWS(
"core.windows",
"org.lwjgl.system.windows",
"Contains bindings to native APIs specific to the Windows operating system.",
CallingConvention.STDCALL
),
ASSIMP(
"assimp",
"org.lwjgl.assimp",
"""
Contains bindings to the ${url("http://www.assimp.org/", "Assimp")} library, a library to import and export various 3d-model-formats including
scene-post-processing to generate missing render data.
Assimp aims to provide a full asset conversion pipeline for use in game engines / realtime rendering systems of any kind, but it is not limited to this
purpose. In the past, it has been used in a wide range of applications.
Written in C++, it is available under a liberal BSD license. Assimp loads all input model formats into one straightforward data structure for further
processing. This feature set is augmented by various post processing tools, including frequently-needed operations such as computing normal and tangent
vectors.
"""
),
BGFX(
"bgfx",
"org.lwjgl.bgfx",
"""
Contains bindings to the ${url("https://github.com/bkaradzic/bgfx", "bgfx")} library.
The bgfx documentation can be found online ${url("https://bkaradzic.github.io/bgfx/", "here")}. The API reference is available
${url("https://bkaradzic.github.io/bgfx/bgfx.html", "here")}.
Starting with LWJGL 3.2.1, builds of the bgfx tools are available for download via the LWJGL site's <a href="https://www.lwjgl.org/browse">file
browser</a>. These tools are:
${ul(
"Geometry Compiler (geometryc)",
"Shader Compiler (shaderc)",
"Texture Compiler (texturec)",
"Texture Viewer (texturev)"
)}
The binaries are built from source, at the corresponding commit that was used to build the bgfx library. For example, the latest Windows x64 version of
shaderc can be found under {@code nightly/windows/x64/bgfx-tools/}.
"""
),
CUDA(
"cuda",
"org.lwjgl.cuda",
"""
Contains bindings to <a href="https://developer.nvidia.com/cuda-zone">CUDA</a>.
<h3>UNSTABLE API</h3>
Until these bindings are sufficiently tested, this API should be considered unstable. Also, bindings to more (and eventually, all) CUDA Toolkit
libraries will be added in the near future.
""",
CallingConvention.STDCALL,
arrayOverloads = false
),
EGL(
"egl",
"org.lwjgl.egl",
"""
Contains bindings to the ${url("https://www.khronos.org/egl", "EGL")} API, an interface between Khronos rendering APIs such as OpenGL ES or OpenVG and
the underlying native platform window system. It handles graphics context management, surface/buffer binding and rendering synchronization and enables
high-performance, accelerated, mixed-mode 2D and 3D rendering using other Khronos APIs.
The ${url("https://www.khronos.org/registry/EGL/", "Khronos EGL registry")} is a useful online resource that contains the EGL specification, as well
as specifications of EGL extensions.
""",
CallingConvention.STDCALL
),
FMOD(
"fmod",
"org.lwjgl.fmod",
"""
Contains bindings to the ${url("https://www.fmod.com", "FMOD")}, an end-to-end solution for adding sound and music to any game.
The FMOD license does not permit redistribution, so LWJGL does not include the FMOD native libraries. They must be downloaded and deployed separately.
The {@code SharedLibraryLoader} enables many options and it can be as simple as putting the libraries on the classpath. LWJGL by default will look for
these shared libraries:
${ul(
"fmod",
"fmodstudio",
"fsbank"
)}
but these can be overridden with an absolute/relative path or simple name, using the corresponding {@link org.lwjgl.system.Configuration Configuration}
options. For example, setting {@link org.lwjgl.system.Configuration\#FMOD_LIBRARY_NAME FMOD_LIBRARY_NAME} to "fmodL" will load the logging version of
the FMOD core library.
""",
CallingConvention.STDCALL,
arrayOverloads = false
),
GLFW(
"glfw",
"org.lwjgl.glfw",
"""
Contains bindings to the ${url("http://www.glfw.org/", "GLFW")} library.
GLFW comes with extensive documentation, which you can read online ${url("http://www.glfw.org/docs/latest/", "here")}. The
${url("http://www.glfw.org/faq.html", "Frequently Asked Questions")} are also useful.
<h3>Using GLFW on macOS</h3>
On macOS the JVM must be started with the {@code -XstartOnFirstThread} argument for GLFW to work. This is necessary because most GLFW functions must be
called on the main thread and the Cocoa API requires that thread to be the first thread in the process. GLFW windows and the GLFW event loop are
incompatible with other window toolkits (such as AWT/Swing or JavaFX).
Applications that cannot function with the above limitation may set {@link org.lwjgl.system.Configuration\#GLFW_LIBRARY_NAME GLFW_LIBRARY_NAME} to the
value {@code "glfw_async"}. This will instruct LWJGL to load an alternative GLFW build that dispatches Cocoa calls to the main thread in blocking mode.
The other window toolkit must be initialized (e.g. with AWT's {@code Toolkit.getDefaultToolkit()}) before #Init() is called.
"""
),
HARFBUZZ(
"harfbuzz",
"org.lwjgl.util.harfbuzz",
"""
Contains bindings to the ${url("https://harfbuzz.github.io/", "HarfBuzz")}, a text shaping library.
Using the HarfBuzz library allows programs to convert a sequence of Unicode input into properly formatted and positioned glyph output — for any writing
system and language.
""",
arrayOverloads = false
),
JAWT(
"jawt",
"org.lwjgl.system.jawt",
"Contains bindings to the AWT native interface (jawt.h).",
CallingConvention.STDCALL
),
JEMALLOC(
"jemalloc",
"org.lwjgl.system.jemalloc",
"""
Contains bindings to the ${url("http://jemalloc.net/", "jemalloc")} library. jemalloc is a general purpose malloc implementation that emphasizes
fragmentation avoidance and scalable concurrency support.
The jemalloc documentation can be found ${url("http://jemalloc.net/jemalloc.3.html", "here")}. The jemalloc
${url("https://github.com/jemalloc/jemalloc/wiki", "wiki")} also contains useful information.
The jemalloc shared library that comes with LWJGL is configured with:
${ul(
"--with-jemalloc-prefix=je_",
"--enable-lazy-lock (Linux)",
"--disable-stats",
"--disable-fill",
"--disable-cxx",
"--disable-initial-exec-tls (Linux & macOS)",
"--disable-zone-allocator (macOS)"
)}
The shared library may be replaced with a custom build that has more features enabled.
Dynamic configuration (for enabled features) is also possible, using either the {@code MALLOC_CONF} environment variable or the
${url("http://jemalloc.net/jemalloc.3.html\\#mallctl_namespace", "MALLCTL NAMESPACE")} and the {@code mallctl*} functions.
"""
),
KTX(
"ktx",
"org.lwjgl.util.ktx",
"""
Contains bindings to the ${url("https://www.khronos.org/ktx/", "KTX (Khronos Texture)")}, a lightweight container for textures for OpenGL®, Vulkan® and
other GPU APIs.
The LWJGL bindings support the KTX encoding functionality, but its presence is optional. Applications may choose to deploy the read-only version of the
KTX library ({@code ktx_read}) and the bindings will work. The {@link org.lwjgl.system.Configuration\#KTX_LIBRARY_NAME KTX_LIBRARY_NAME} option can be
used to change the loaded library.
""",
CallingConvention.STDCALL,
arrayOverloads = false
),
LIBDIVIDE(
"libdivide",
"org.lwjgl.util.libdivide",
"Contains bindings to ${url("https://libdivide.com/", "libdivide")}.",
library = JNILibrary.simple(),
arrayOverloads = false
),
LLVM(
"llvm",
"org.lwjgl.llvm",
"""
Contains bindings to <a href="https://llvm.org/">LLVM</a>, a collection of modular and reusable compiler and toolchain technologies.
<h3>UNSTABLE API</h3>
Until these bindings are sufficiently tested, this API should be considered unstable.
<h3>BINDINGS ONLY</h3>
LWJGL does not currently include pre-built LLVM/Clang binaries. The user must download or build LLVM separately and use
{@link org.lwjgl.system.Configuration Configuration} to point LWJGL to the appropriate binaries.
""",
library = JNILibrary.create("LibLLVM"),
arrayOverloads = false
),
LMDB(
"lmdb",
"org.lwjgl.util.lmdb",
"""
Bindings to ${url("https://symas.com/lmdb/", "LMDB")}, the Symas Lightning Memory-Mapped Database.
LMDB is a Btree-based database management library modeled loosely on the BerkeleyDB API, but much simplified. The entire database is exposed in a
memory map, and all data fetches return data directly from the mapped memory, so no malloc's or memcpy's occur during data fetches. As such, the
library is extremely simple because it requires no page caching layer of its own, and it is extremely high performance and memory-efficient. It is also
fully transactional with full ACID semantics, and when the memory map is read-only, the database integrity cannot be corrupted by stray pointer writes
from application code.
The library is fully thread-aware and supports concurrent read/write access from multiple processes and threads. Data pages use a copy-on-write
strategy so no active data pages are ever overwritten, which also provides resistance to corruption and eliminates the need of any special recovery
procedures after a system crash. Writes are fully serialized; only one write transaction may be active at a time, which guarantees that writers can
never deadlock. The database structure is multi-versioned so readers run with no locks; writers cannot block readers, and readers don't block writers.
Unlike other well-known database mechanisms which use either write-ahead transaction logs or append-only data writes, LMDB requires no maintenance
during operation. Both write-ahead loggers and append-only databases require periodic checkpointing and/or compaction of their log or database files
otherwise they grow without bound. LMDB tracks free pages within the database and re-uses them for new write operations, so the database size does not
grow without bound in normal use.
The memory map can be used as a read-only or read-write map. It is read-only by default as this provides total immunity to corruption. Using read-write
mode offers much higher write performance, but adds the possibility for stray application writes thru pointers to silently corrupt the database. Of
course if your application code is known to be bug-free (...) then this is not an issue.
<h3>Restrictions/caveats (in addition to those listed for some functions)</h3>
${ul(
"""
Only the database owner should normally use the database on BSD systems or when otherwise configured with {@code MDB_USE_POSIX_SEM}. Multiple users
can cause startup to fail later, as noted above.
""",
"""
There is normally no pure read-only mode, since readers need write access to locks and lock file. Exceptions: On read-only filesystems or with the
#NOLOCK flag described under #env_open().
""",
"""
An LMDB configuration will often reserve considerable unused memory address space and maybe file size for future growth. This does not use actual
memory or disk space, but users may need to understand the difference so they won't be scared off.
""",
"""
By default, in versions before 0.9.10, unused portions of the data file might receive garbage data from memory freed by other code. (This does not
happen when using the #WRITEMAP flag.) As of 0.9.10 the default behavior is to initialize such memory before writing to the data file. Since there
may be a slight performance cost due to this initialization, applications may disable it using the #NOMEMINIT flag. Applications handling sensitive
data which must not be written should not use this flag. This flag is irrelevant when using #WRITEMAP.
""",
"""
A thread can only use one transaction at a time, plus any child transactions. Each transaction belongs to one thread. The #NOTLS flag changes this
for read-only transactions.
""",
"Use an {@code MDB_env*} in the process which opened it, without {@code fork()}ing.",
"""
Do not have open an LMDB database twice in the same process at the same time. Not even from a plain {@code open()} call - {@code close()}ing it
breaks {@code flock()} advisory locking.
""",
"""
Avoid long-lived transactions. Read transactions prevent reuse of pages freed by newer write transactions, thus the database can grow quickly.
Write transactions prevent other write transactions, since writes are serialized.
""",
"""
Avoid suspending a process with active transactions. These would then be "long-lived" as above. Also read transactions suspended when writers
commit could sometimes see wrong data.
"""
)}
...when several processes can use a database concurrently:
${ul(
"""
Avoid aborting a process with an active transaction. The transaction becomes "long-lived" as above until a check for stale readers is performed or
the lockfile is reset, since the process may not remove it from the lockfile.
This does not apply to write transactions if the system clears stale writers, see above.
""",
"If you do that anyway, do a periodic check for stale readers. Or close the environment once in a while, so the lockfile can get reset.",
"""
Do not use LMDB databases on remote filesystems, even between processes on the same host. This breaks {@code flock()} on some OSes, possibly memory
map sync, and certainly sync between programs on different hosts.
""",
"Opening a database can fail if another process is opening or closing it at exactly the same time."
)}
<h3>Reader Lock Table</h3>
Readers don't acquire any locks for their data access. Instead, they simply record their transaction ID in the reader table. The reader mutex is needed
just to find an empty slot in the reader table. The slot's address is saved in thread-specific data so that subsequent read transactions started by the
same thread need no further locking to proceed.
If #NOTLS is set, the slot address is not saved in thread-specific data.
No reader table is used if the database is on a read-only filesystem, or if #NOLOCK is set.
Since the database uses multi-version concurrency control, readers don't actually need any locking. This table is used to keep track of which readers
are using data from which old transactions, so that we'll know when a particular old transaction is no longer in use. Old transactions that have
discarded any data pages can then have those pages reclaimed for use by a later write transaction.
The lock table is constructed such that reader slots are aligned with the processor's cache line size. Any slot is only ever used by one thread. This
alignment guarantees that there will be no contention or cache thrashing as threads update their own slot info, and also eliminates any need for
locking when accessing a slot.
A writer thread will scan every slot in the table to determine the oldest outstanding reader transaction. Any freed pages older than this will be
reclaimed by the writer. The writer doesn't use any locks when scanning this table. This means that there's no guarantee that the writer will see the
most up-to-date reader info, but that's not required for correct operation - all we need is to know the upper bound on the oldest reader, we don't care
at all about the newest reader. So the only consequence of reading stale information here is that old pages might hang around a while longer before
being reclaimed. That's actually good anyway, because the longer we delay reclaiming old pages, the more likely it is that a string of contiguous pages
can be found after coalescing old pages from many old transactions together.
""",
library = JNILibrary.create("LibLMDB", setupAllocator = true)
),
LZ4(
"lz4",
"org.lwjgl.util.lz4",
"""
Contains bindings to ${url("http://lz4.github.io/lz4/", "LZ4")}, a lossless compression algorithm, providing compression speed > 500 MB/s per core,
scalable with multi-cores CPU. It features an extremely fast decoder, with speed in multiple GB/s per core, typically reaching RAM speed limits on
multi-core systems.
""",
library = JNILibrary.create("LibLZ4", setupAllocator = true),
arrayOverloads = false
),
MEOW(
"meow",
"org.lwjgl.util.meow",
"Contains bindings to ${url("https://github.com/cmuratori/meow_hash", "Meow hash")}, an extremely fast non-cryptographic hash.",
library = JNILibrary.create("LibMeow"),
arrayOverloads = false
),
MESHOPTIMIZER(
"meshoptimizer",
"org.lwjgl.util.meshoptimizer",
"Contains bindings to ${url("https://github.com/zeux/meshoptimizer", "meshoptimizer")}, a library that provides algorithms to help optimize meshes.",
library = JNILibrary.create("LibMeshOptimizer"),
arrayOverloads = false
),
NANOVG(
"nanovg",
"org.lwjgl.nanovg",
"""
Contains bindings to ${url("https://github.com/memononen/nanovg", "NanoVG")}, a small antialiased vector graphics rendering library for OpenGL. It has
lean API modeled after HTML5 canvas API. It is aimed to be a practical and fun toolset for building scalable user interfaces and visualizations.
""",
library = JNILibrary.create("LibNanoVG", setupAllocator = true)
),
NFD(
"nfd",
"org.lwjgl.util.nfd",
"""
Contains bindings to ${url("https://github.com/mlabbe/nativefiledialog", "Native File Dialog")}, a tiny, neat C library that portably invokes native
file open and save dialogs. Write dialog code once and have it popup native dialogs on all supported platforms.
""",
library = JNILibrary.create("LibNFD", setupAllocator = true)
),
NUKLEAR(
"nuklear",
"org.lwjgl.nuklear",
"""
Bindings to the ${url("https://github.com/vurtun/nuklear", "Nuklear")} library.
A minimal state immediate mode graphical user interface single header toolkit written in ANSI C and licensed under public domain. It was designed as a
simple embeddable user interface for application and does not have any dependencies, a default renderbackend or OS window and input handling but
instead provides a very modular library approach by using simple input state for input and draw commands describing primitive shapes as output. So
instead of providing a layered library that tries to abstract over a number of platform and render backends it only focuses on the actual UI.
Developed by Micha Mettke.
""",
library = JNILibrary.simple()
),
ODBC(
"odbc",
"org.lwjgl.odbc",
"""
Contains bindings to ${url("https://docs.microsoft.com/en-us/sql/odbc/microsoft-open-database-connectivity-odbc", "ODBC")}.
The Microsoft Open Database Connectivity (ODBC) interface is a C programming language interface that makes it possible for applications to access data
from a variety of database management systems (DBMSs). ODBC is a low-level, high-performance interface that is designed specifically for relational
data stores.
The ODBC interface allows maximum interoperability — an application can access data in diverse DBMSs through a single interface. Moreover, that
application will be independent of any DBMS from which it accesses data. Users of the application can add software components called drivers, which
interface between an application and a specific DBMS.
""",
CallingConvention.STDCALL,
arrayOverloads = false
),
OPENAL(
"openal",
"org.lwjgl.openal",
"""
Contains bindings to the ${url("http://www.openal.org/", "OpenAL")} cross-platform 3D audio API.
LWJGL comes with a software OpenAL implementation, ${url("http://www.openal-soft.org/", "OpenAL Soft")}.
OpenAL Soft can be dynamically configured with ${url("https://github.com/kcat/openal-soft/blob/master/docs/env-vars.txt", "environment variables")}. A
very useful option for debugging is {@code ALSOFT_LOGLEVEL}; it can be set to values 0 through 4, with higher values producing more information.
In addition to standard OpenAL features, OpenAL Soft supports ${url("https://en.wikipedia.org/wiki/Head-related_transfer_function", "HRTF")},
${url("https://en.wikipedia.org/wiki/Ambisonics", "Ambisonics")} and ${url("http://www.codemasters.com/research/3D_sound_for_3D_games.pdf", "3D7.1")}.
Documentation for these features is available in the OpenAL Soft ${url("https://github.com/kcat/openal-soft/tree/master/docs", "repository")}.
"""
),
OPENCL(
"opencl",
"org.lwjgl.opencl",
"""
Contains bindings to the ${url("https://www.khronos.org/opencl/", "OpenCL")} cross-platform parallel programming API.
The ${url("https://www.khronos.org/registry/OpenCL/", "Khronos OpenCL registry")} is a useful online resource that contains the OpenCL specification, as
well as the specifications of OpenCL extensions.
""",
CallingConvention.STDCALL
),
OPENGL(
"opengl",
"org.lwjgl.opengl",
"""
Contains bindings to the ${url("https://www.opengl.org/", "OpenGL")} cross-platform 2D and 3D rendering API.
The ${url("https://www.khronos.org/registry/OpenGL/index_gl.php", "OpenGL registry")} is a useful online resource that contains the OpenGL and OpenGL
Shading Language specifications, as well as specifications of OpenGL extensions.
The ${url("https://www.khronos.org/registry/OpenGL-Refpages/", "OpenGL Reference Pages")} is another convenient source of documentation.
The bindings of the core OpenGL functionality are contained in two distinct class hierarchies:
${ul(
"{@code GL11..GL46}: all symbols of the Compatibility Profile are included",
"{@code GL11C..GL46C}: only symbols of the Core Profile are included"
)}
Each of the above classes extends the class of the previous OpenGL version in the corresponding hierarchy.
The recommended way to write OpenGL applications with LWJGL is to statically import the class that corresponds to the minimum required OpenGL version.
This will expose all symbols up to that version. Additional functionality (later core versions or extensions) should be guarded with appropriate checks
using the {@link org.lwjgl.opengl.GLCapabilities GLCapabilities} instance of the OpenGL context.
The Compatibility Profile and Core Profile class hierarchies should not be mixed with static imports, as that would result in compilation ambiguities
when resolving the symbols. Note that the Compatibility Profile hierarchy can be used with a Core Profile context (as long as no deprecated symbol is
used) and the Core Profile hierarchy can be used with a Compatibility Profile context. The recommendation is to use the Compatibility Profile hierarchy
only when deprecated functionality is required. In any other case, the Core Profile hierarchy should be preferred.
For example, an OpenGL application that requires OpenGL 3.3, must use modern OpenGL features only and needs the best possible performance:
${ul(
"Should create a 3.3 Compatibility Profile context. A Core Profile context would have extra validation overhead.",
"Should use the Core Profile hierarchy to avoid deprecated symbols. Auto-complete lists in an IDE will also be cleaner."
)}
""",
CallingConvention.STDCALL,
library = JNILibrary.create("GL", custom = true)
),
OPENGLES(
"opengles",
"org.lwjgl.opengles",
"""
Contains bindings to the ${url("https://www.khronos.org/opengles/", "OpenGL ES")}, a royalty-free, cross-platform API for full-function 2D and 3D
graphics on embedded systems - including consoles, phones, appliances and vehicles. It consists of well-defined subsets of desktop OpenGL, creating a
flexible and powerful low-level interface between software and graphics acceleration.
The ${url(
"https://www.khronos.org/registry/OpenGL/index_es.php",
"Khronos OpenGL ES registry"
)} is a useful online resource that contains the OpenGL ES and OpenGL
ES Shading Language specifications, as well as specifications of OpenGL ES extensions. The ${url(
"https://www.khronos.org/registry/OpenGL-Refpages/",
"OpenGL ES Reference Pages"
)} is another convenient source of documentation.
""",
CallingConvention.STDCALL,
library = JNILibrary.create("GLES", custom = true)
),
OPENVR(
"openvr",
"org.lwjgl.openvr",
"""
Contains bindings to ${url("https://github.com/ValveSoftware/openvr", "OpenVR")}.
OpenVR is an API and runtime that allows access to VR hardware from multiple vendors without requiring that applications have specific knowledge of the
hardware they are targeting.
""",
CallingConvention.STDCALL,
library = JNILibrary.create("OpenVR", custom = true),
arrayOverloads = false
),
OPENXR(
"openxr",
"org.lwjgl.openxr",
"""
Contains bindings to ${url("https://www.khronos.org/openxr/", "OpenXR")}.
OpenXR is a royalty-free, open standard that provides high-performance access to Augmented Reality (AR) and Virtual Reality (VR)—collectively known as
XR—platforms and devices.
""",
CallingConvention.STDCALL,
arrayOverloads = false
),
OPUS(
"opus",
"org.lwjgl.util.opus",
"Contains bindings to the <a href=\"https://opus-codec.org\">opus-codec</a> library.",
arrayOverloads = false
),
OVR(
"ovr",
"org.lwjgl.ovr",
"""
Contains bindings to LibOVR, the ${url("https://developer.oculus.com/", "Oculus SDK")} library.
Documentation on how to get started with the Oculus SDK can be found ${url("https://developer.oculus.com/documentation/", "here")}.
""",
library = JNILibrary.create("LibOVR")
),
PAR(
"par",
"org.lwjgl.util.par",
"Contains bindings to the ${url("https://github.com/prideout/par", "par")} library.",
library = JNILibrary.create("LibPar", setupAllocator = true)
),
REMOTERY(
"remotery",
"org.lwjgl.util.remotery",
"""
Contains bindings to ${url("https://github.com/Celtoys/Remotery", "Remotery")}, a realtime CPU/GPU profiler hosted in a single C file with a viewer
that runs in a web browser.
""",
library = JNILibrary.create("LibRemotery"),
arrayOverloads = false
),
RPMALLOC(
"rpmalloc",
"org.lwjgl.system.rpmalloc",
"""
Contains bindings to the ${url("https://github.com/mjansson/rpmalloc", "rpmalloc")} library. rpmalloc is a public domain cross platform lock free
thread caching 16-byte aligned memory allocator implemented in C.
""",
library = JNILibrary.create("LibRPmalloc"),
arrayOverloads = false
),
SHADERC(
"shaderc",
"org.lwjgl.util.shaderc",
"""
Contains bindings to ${url("https://github.com/google/shaderc", "Shaderc")}, a collection of libraries for shader compilation.
Shaderc wraps around core functionality in ${url("https://github.com/KhronosGroup/glslang", "glslang")} and ${url(
"https://github.com/KhronosGroup/SPIRV-Tools",
"SPIRV-Tools"
)}. Shaderc aims to to provide:
${ul(
"a command line compiler with GCC- and Clang-like usage, for better integration with build systems",
"an API where functionality can be added without breaking existing clients",
"an API supporting standard concurrency patterns across multiple operating systems",
"increased functionality such as file \\#include support"
)}
""",
arrayOverloads = false
),
SPVC(
"spvc",
"org.lwjgl.util.spvc",
"""
Contains bindings to ${url("https://github.com/KhronosGroup/SPIRV-Cross", "SPIRV-Cross")}, a library for performing reflection on SPIR-V and
disassembling SPIR-V back to high level languages.
""",
arrayOverloads = false
),
SSE(
"sse",
"org.lwjgl.util.simd",
"Contains bindings to SSE macros.",
library = JNILibrary.create("LibSSE")
),
STB(
"stb",
"org.lwjgl.stb",
"""
Contains bindings to ${url("https://github.com/nothings/stb", "stb")}, a set of single-file public domain libraries.
The functionality provided by stb includes:
${ul(
"Parsing TrueType files, extract glyph metrics and rendering packed font textures.",
"Easy rendering of bitmap fonts.",
"Reading/writing image files and resizing images (e.g. for gamma-correct MIP map creation).",
"Decoding Ogg Vorbis audio files.",
"Compressing DXT textures at runtime.",
"Packing rectangular textures into texture atlases.",
"Computing Perlin noise."
)}
""",
library = JNILibrary.create("LibSTB", setupAllocator = true)
),
TINYEXR(
"tinyexr",
"org.lwjgl.util.tinyexr",
"""
Contains bindings to the ${url("https://github.com/syoyo/tinyexr", "Tiny OpenEXR")} image library.
tinyexr is a small, single header-only library to load and save OpenEXR(.exr) images.
""",
library = JNILibrary.simple(),
arrayOverloads = false
),
TINYFD(
"tinyfd",
"org.lwjgl.util.tinyfd",
"Contains bindings to ${url("https://sourceforge.net/projects/tinyfiledialogs/", "tiny file dialogs")}.",
library = JNILibrary.simple(
"""Library.loadSystem(System::load, System::loadLibrary, TinyFileDialogs.class, "org.lwjgl.tinyfd", Platform.mapLibraryNameBundled("lwjgl_tinyfd"));
if (Platform.get() == Platform.WINDOWS) {
tinyfd_setGlobalInt("tinyfd_winUtf8", 1);
}"""
)
),
TOOTLE(
"tootle",
"org.lwjgl.util.tootle",
"""
Contains bindings to ${url("https://github.com/GPUOpen-Tools/amd-tootle", "AMD Tootle")}.
AMD Tootle (Triangle Order Optimization Tool) is a 3D triangle mesh optimization library that improves on existing mesh preprocessing techniques. By
using AMD Tootle, developers can optimize their models for pixel overdraw as well as vertex cache performance. This can provide significant performance
improvements in pixel limited situations, with no penalty in vertex-limited scenarios, and no runtime cost.
""",
library = JNILibrary.simple(),
arrayOverloads = false
),
VMA(
"vma",
"org.lwjgl.util.vma",
"""
Contains bindings to ${url("https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator", "VMA")}, an easy to integrate Vulkan memory
allocation library.
<h4>Problem</h4>
Memory allocation and resource (buffer and image) creation in Vulkan is difficult (comparing to older graphics API-s, like D3D11 or OpenGL) for several
reasons:
${ul(
"It requires a lot of boilerplate code, just like everything else in Vulkan, because it is a low-level and high-performance API.",
"""
There is additional level of indirection: {@code VkDeviceMemory} is allocated separately from creating {@code VkBuffer/VkImage} and they must be
bound together. The binding cannot be changed later - resource must be recreated.
""",
"Driver must be queried for supported memory heaps and memory types. Different IHVs provide different types of it.",
"It is recommended practice to allocate bigger chunks of memory and assign parts of them to particular resources."
)}
<h4>Features</h4>
This library can help game developers to manage memory allocations and resource creation by offering some higher-level functions. Features of the
library are divided into several layers, low level to high level:
${ol(
"""
Functions that help to choose correct and optimal memory type based on intended usage of the memory.
- Required or preferred traits of the memory are expressed using higher-level description comparing to Vulkan flags.
""",
"""
Functions that allocate memory blocks, reserve and return parts of them (`VkDeviceMemory` + offset + size) to the user.
- Library keeps track of allocated memory blocks, used and unused ranges inside them, finds best matching unused ranges for new allocations, takes
all the rules of alignment and buffer/image granularity into consideration.
""",
"Functions that can create an image/buffer, allocate memory for it and bind them together - all in one call."
)}
Additional features:
${ul(
"Thread-safety: Library is designed to be used by multithreaded code.",
"Configuration: Fill optional members of CreateInfo structure to provide custom CPU memory allocator and other parameters.",
"""
Customization: Predefine appropriate macros to provide your own implementation of all external facilities used by the library, from assert, mutex,
and atomic, to vector and linked list.
""",
"""
Support memory mapping, reference-counted internally. Support for persistently mapped memory: Just allocate with appropriate flag and you get
access to mapped pointer.
""",
"Custom memory pools: Create a pool with desired parameters (e.g. fixed or limited maximum size) and allocate memory out of it.",
"Support for VK_KHR_dedicated_allocation extension: Enable it and it will be used automatically by the library.",
"Defragmentation: Call one function and let the library move data around to free some memory blocks and make your allocations better compacted.",
"""
Lost allocations: Allocate memory with appropriate flags and let the library remove allocations that are not used for many frames to make room for
new ones.
""",
"""
Statistics: Obtain detailed statistics about the amount of memory used, unused, number of allocated blocks, number of allocations etc. - globally,
per memory heap, and per memory type.
""",
"Debug annotations: Associate string with name or opaque pointer to your own data with every allocation.",
"JSON dump: Obtain a string in JSON format with detailed map of internal state, including list of allocations and gaps between them."
)}
""",
library = JNILibrary.create("LibVma", setupAllocator = true, cpp = true),
arrayOverloads = false
),
VULKAN(
"vulkan",
"org.lwjgl.vulkan",
"""
Contains bindings to ${url("https://www.khronos.org/vulkan/", "Vulkan")}, a new generation graphics and compute API that provides high-efficiency,
cross-platform access to modern GPUs used in a wide variety of devices from PCs and consoles to mobile phones and embedded platforms.
Experimental extensions (KHX, NVX, etc) is not supported API. When such an extension is promoted to stable, the corresponding experimental bindings
will be removed.
<b>macOS</b>: LWJGL bundles ${url("https://moltengl.com/moltenvk/", "MoltenVK")}, which emulates Vulkan over Metal.
""",
CallingConvention.STDCALL
),
XXHASH(
"xxhash",
"org.lwjgl.util.xxhash",
"""
Contains bindings to ${url("https://github.com/Cyan4973/xxHash", "xxHash")}, an extremely fast non-cryptographic hash algorithm.
xxHash successfully completes the ${url("https://github.com/aappleby/smhasher", "SMHasher")} test suite which evaluates collision, dispersion and
randomness qualities of hash functions.
""",
library = JNILibrary.create("LibXXHash", setupAllocator = true)
),
YOGA(
"yoga",
"org.lwjgl.util.yoga",
"""
Contains bindings to ${url("https://facebook.github.io/yoga/", "Yoga")}.
Yoga is a cross-platform layout engine enabling maximum collaboration within your team by implementing an API familiar to many designers and opening it
up to developers across different platforms.
${ul(
"Do you already know Flexbox? Then you already know Yoga.",
"Write code in a language familiar to you - Java, C#, Objective-C, C.",
"C under the hood so your code moves fast.",
"Battle tested in popular frameworks like React Native."
)}
<h3>LWJGL implementation</h3>
Unlike the official Yoga Java bindings, the LWJGL bindings directly expose the native C API. {@code YGNodeRef} handles do not need to be wrapped in Java
instances, so there is no memory overhead. The internal Yoga structs are also exposed, which makes it very efficient to read the current tree layout
after a call to #NodeCalculateLayout():
${codeBlock("""
// Public API, 4x JNI call overhead
float l = YGNodeLayoutGetLeft(node);
float t = YGNodeLayoutGetTop(node);
float w = YGNodeLayoutGetWidth(node);
float h = YGNodeLayoutGetHeight(node);
// Internal API without overhead (plain memory accesses, assuming allocations are eliminated via EA)
YGLayout layout = YGNode.create(node).layout();
float l = layout.positions(YGEdgeLeft);
float t = layout.positions(YGEdgeTop);
float w = layout.dimensions(YGDimensionWidth);
float h = layout.dimensions(YGDimensionHeight);""")}
""",
library = JNILibrary.create("LibYoga"),
arrayOverloads = false
),
ZSTD(
"zstd",
"org.lwjgl.util.zstd",
"""
Contains bindings to ${url("http://facebook.github.io/zstd/", "Zstandard")} (zstd), a fast lossless compression algorithm, targeting real-time
compression scenarios at zlib-level and better compression ratios.
Zstandard is a real-time compression algorithm, providing high compression ratios. It offers a very wide range of compression / speed trade-off, while
being backed by a very fast decoder. It also offers a special mode for small data, called dictionary compression, and can create dictionaries from any
sample set.
""",
library = JNILibrary.create("LibZstd", setupAllocator = true),
arrayOverloads = false
);
companion object {
internal val CHECKS = !System.getProperty("binding.DISABLE_CHECKS", "false")!!.toBoolean()
}
init {
if (packageInfo.isNotEmpty()) {
packageInfo(this, packageInfo)
}
if (library != null && enabled) {
library.configure(this)
}
}
val enabled
get() = key.startsWith("core") || System.getProperty("binding.$key", "false")!!.toBoolean()
val path = if (name.startsWith("CORE_")) "core" else name.lowercase()
val java = if (name.startsWith("CORE_")) "org.lwjgl" else "org.lwjgl.${name.lowercase()}"
internal val packageKotlin
get() = name.let {
if (it.startsWith("CORE_")) {
this.key
} else {
it.lowercase()
}
}
@Suppress("LeakingThis")
private val CALLBACK_RECEIVER = ANONYMOUS.nativeClass(this)
fun callback(init: NativeClass.() -> FunctionType) = CALLBACK_RECEIVER.init()
}
internal interface JNILibrary {
companion object {
fun simple(expression: String? = null): JNILibrary = JNILibrarySimple(expression)
fun create(className: String, custom: Boolean = false, setupAllocator: Boolean = false, cpp: Boolean = false): JNILibrary =
JNILibraryWithInit(className, custom, setupAllocator, cpp)
}
fun expression(module: Module): String
fun configure(module: Module)
}
private class JNILibrarySimple(private val expression: String?) : JNILibrary {
override fun expression(module: Module) = if (expression != null)
expression
else
"lwjgl_${module.key}"
override fun configure(module: Module) = Unit
}
private class JNILibraryWithInit constructor(
private val className: String,
private val custom: Boolean = false,
private val setupAllocator: Boolean = false,
private val cpp: Boolean = false
) : JNILibrary {
override fun expression(module: Module) = "$className.initialize();"
override fun configure(module: Module) {
if (custom) {
return
}
Generator.register(object : GeneratorTargetNative(module, className) {
init {
this.access = Access.INTERNAL
this.cpp = [email protected]
this.documentation = "Initializes the ${module.key} shared library."
javaImport("org.lwjgl.system.*")
if (setupAllocator)
javaImport("static org.lwjgl.system.MemoryUtil.*")
nativeDirective(
"""#define LWJGL_MALLOC_LIB $nativeFileNameJNI
#include "lwjgl_malloc.h""""
)
}
override fun PrintWriter.generateJava() {
generateJavaPreamble()
println(
"""${access.modifier}final class $className {
static {
String libName = Platform.mapLibraryNameBundled("lwjgl_${module.key}");
Library.loadSystem(System::load, System::loadLibrary, $className.class, "${module.java}", libName);${if (setupAllocator) """
MemoryAllocator allocator = getAllocator(Configuration.DEBUG_MEMORY_ALLOCATOR_INTERNAL.get(true));
setupMalloc(
allocator.getMalloc(),
allocator.getCalloc(),
allocator.getRealloc(),
allocator.getFree(),
allocator.getAlignedAlloc(),
allocator.getAlignedFree()
);""" else ""}
}
private $className() {
}
static void initialize() {
// intentionally empty to trigger static initializer
}${if (setupAllocator) """
private static native void setupMalloc(
long malloc,
long calloc,
long realloc,
long free,
long aligned_alloc,
long aligned_free
);""" else ""}
}"""
)
}
override val skipNative
get() = !setupAllocator
override fun PrintWriter.generateNative() {
generateNativePreamble()
}
})
}
}
fun String.dependsOn(vararg modules: Module): String? = if (modules.any { it.enabled }) this else null | bsd-3-clause | af82e2047d86a4c43155165592b6cbad | 48.168599 | 160 | 0.656322 | 4.644635 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GHPasswordCredentialsUi.kt | 2 | 4455 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication.ui
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.ui.Messages.showInputDialog
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.components.JBTextField
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.ui.layout.*
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.util.GHAccessTokenCreator
import org.jetbrains.plugins.github.authentication.util.GHSecurityUtil.DEFAULT_CLIENT_NAME
import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException
import org.jetbrains.plugins.github.exceptions.GithubParseException
import org.jetbrains.plugins.github.i18n.GithubBundle.message
import org.jetbrains.plugins.github.ui.util.DialogValidationUtils
import org.jetbrains.plugins.github.ui.util.DialogValidationUtils.notBlank
import java.net.UnknownHostException
import java.util.function.Supplier
import javax.swing.JComponent
import javax.swing.JPasswordField
internal class GHPasswordCredentialsUi(
private val serverTextField: ExtendableTextField,
private val executorFactory: GithubApiRequestExecutor.Factory,
private val isAccountUnique: UniqueLoginPredicate
) : GHCredentialsUi() {
private val loginTextField = JBTextField()
private val passwordField = JPasswordField()
fun setLogin(login: String, editable: Boolean = true) {
loginTextField.text = login
loginTextField.isEditable = editable
}
fun setPassword(password: String) {
passwordField.text = password
}
override fun LayoutBuilder.centerPanel() {
row(message("credentials.server.field")) { serverTextField(pushX, growX) }
row(message("credentials.login.field")) { loginTextField(pushX, growX) }
row(message("credentials.password.field")) {
passwordField(
comment = message("credentials.password.not.saved"),
constraints = *arrayOf(pushX, growX)
)
}
}
override fun getPreferredFocusableComponent(): JComponent =
if (loginTextField.isEditable && loginTextField.text.isEmpty()) loginTextField else passwordField
override fun getValidator() =
DialogValidationUtils.chain(
{ notBlank(loginTextField, message("credentials.login.cannot.be.empty")) },
{ notBlank(passwordField, message("credentials.password.cannot.be.empty")) }
)
override fun createExecutor(): GithubApiRequestExecutor.WithBasicAuth {
val modalityState = ModalityState.stateForComponent(passwordField)
return executorFactory.create(loginTextField.text, passwordField.password, Supplier {
invokeAndWaitIfNeeded(modalityState) {
showInputDialog(passwordField, message("credentials.2fa.dialog.code.field"), message("credentials.2fa.dialog.title"), null)
}
})
}
override fun acquireLoginAndToken(
server: GithubServerPath,
executor: GithubApiRequestExecutor,
indicator: ProgressIndicator
): Pair<String, String> {
val login = loginTextField.text.trim()
if (!isAccountUnique(login, server)) throw LoginNotUniqueException(login)
val token = GHAccessTokenCreator(server, executor, indicator).createMaster(DEFAULT_CLIENT_NAME).token
return login to token
}
override fun handleAcquireError(error: Throwable): ValidationInfo =
when (error) {
is LoginNotUniqueException -> ValidationInfo(message("login.account.already.added", loginTextField.text),
loginTextField).withOKEnabled()
is UnknownHostException -> ValidationInfo(message("server.unreachable")).withOKEnabled()
is GithubAuthenticationException -> ValidationInfo(message("credentials.incorrect", error.message.orEmpty())).withOKEnabled()
is GithubParseException -> ValidationInfo(error.message ?: message("credentials.invalid.server.path"), serverTextField)
else -> ValidationInfo(message("credentials.invalid.auth.data", error.message.orEmpty())).withOKEnabled()
}
override fun setBusy(busy: Boolean) {
loginTextField.isEnabled = !busy
passwordField.isEnabled = !busy
}
} | apache-2.0 | 413fe0c8391b2ff0397ba6d17c46bf1d | 44.010101 | 140 | 0.775084 | 4.749467 | false | false | false | false |
allotria/intellij-community | java/java-impl/src/com/intellij/refactoring/extractMethod/newImpl/ExtractOptionsPipeline.kt | 3 | 15091 | // 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.refactoring.extractMethod.newImpl
import com.intellij.codeInsight.AnnotationUtil.*
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil
import com.intellij.codeInsight.daemon.impl.quickfix.AnonymousTargetClassPreselectionUtil
import com.intellij.codeInsight.navigation.NavigationUtil
import com.intellij.ide.util.PsiClassListCellRenderer
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.util.TextRange
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.*
import com.intellij.psi.search.PsiElementProcessor
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.findUsedTypeParameters
import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.hasExplicitModifier
import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.inputParameterOf
import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.normalizedAnchor
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.refactoring.util.VariableData
object ExtractMethodPipeline {
fun remap(extractOptions: ExtractOptions,
variableData: Array<VariableData>,
methodName: String,
isStatic: Boolean,
visibility: String,
isConstructor: Boolean,
returnType: PsiType
): ExtractOptions {
val analyzer = CodeFragmentAnalyzer(extractOptions.elements)
var options = withMappedName(extractOptions, methodName)
if (isStatic && ! options.isStatic) {
options = withForcedStatic(analyzer, options) ?: options
}
options = withMappedParametersInput(options, variableData.toList())
val targetClass = extractOptions.anchor.containingClass!!
options = if (targetClass.isInterface) {
adjustModifiersForInterface(options.copy(visibility = PsiModifier.PRIVATE))
} else {
options.copy(visibility = visibility)
}
if (isConstructor) {
options = asConstructor(analyzer, options) ?: options
} else {
options = options.copy(dataOutput = extractOptions.dataOutput.withType(returnType))
}
return options
}
fun withTargetClass(analyzer: CodeFragmentAnalyzer, extractOptions: ExtractOptions, targetClass: PsiClass): ExtractOptions? {
val anchor = extractOptions.anchor
if (anchor.parent == targetClass) return extractOptions
val newAnchor = targetClass.children.find { child -> anchor.textRange in child.textRange } as? PsiMember
if (newAnchor == null) return null
val typeParameters = findAllTypeLists(anchor, targetClass).flatMap { findUsedTypeParameters(it, extractOptions.elements) }
val additionalReferences = analyzer.findOuterLocals(anchor, newAnchor) ?: return null
val additionalParameters = additionalReferences.map { inputParameterOf(it) }
val options = extractOptions.copy(
anchor = normalizedAnchor(newAnchor),
inputParameters = extractOptions.inputParameters + additionalParameters,
typeParameters = typeParameters
)
return withDefaultStatic(options)
}
private fun findAllTypeLists(element: PsiElement, stopper: PsiElement): List<PsiTypeParameterList> {
return generateSequence (element) { it.parent }
.takeWhile { it != stopper && it !is PsiFile }
.filterIsInstance<PsiTypeParameterListOwner>()
.mapNotNull { it.typeParameterList }
.toList()
}
private fun findCommonCastParameter(inputParameter: InputParameter): InputParameter? {
val castExpressions = inputParameter.references.map { reference -> (reference.parent as? PsiTypeCastExpression) ?: return null }
val type = castExpressions.first().castType?.type ?: return null
if ( castExpressions.any { castExpression -> castExpression.castType?.type != type } ) return null
return InputParameter(name = inputParameter.name, type = type, references = castExpressions)
}
fun withCastedParameters(extractOptions: ExtractOptions): ExtractOptions {
val parameters = extractOptions.inputParameters.map { inputParameter -> findCommonCastParameter(inputParameter) ?: inputParameter }
return extractOptions.copy(inputParameters = parameters)
}
fun withMappedParametersInput(extractOptions: ExtractOptions, variablesData: List<VariableData>): ExtractOptions {
fun findMappedParameter(variableData: VariableData): InputParameter? {
return extractOptions.inputParameters
.find { parameter -> parameter.name == variableData.variable.name }
?.copy(name = variableData.name ?: "x", type = variableData.type)
}
val mappedParameters = variablesData.filter { it.passAsParameter }.mapNotNull(::findMappedParameter)
val disabledParameters = variablesData.filterNot { it.passAsParameter }.mapNotNull(::findMappedParameter)
return extractOptions.copy(
inputParameters = mappedParameters,
disabledParameters = disabledParameters
)
}
fun adjustModifiersForInterface(options: ExtractOptions): ExtractOptions {
val targetClass = options.anchor.containingClass!!
if (! targetClass.isInterface) return options
val isJava8 = PsiUtil.getLanguageLevel(targetClass) == LanguageLevel.JDK_1_8
val visibility = if (options.visibility == PsiModifier.PRIVATE && isJava8) null else options.visibility
val holder = findClassMember(options.elements.first())
val isStatic = holder is PsiField || options.isStatic
return options.copy(visibility = visibility, isStatic = isStatic)
}
fun withMappedName(extractOptions: ExtractOptions, methodName: String) = if (extractOptions.isConstructor) extractOptions else extractOptions.copy(methodName = methodName)
fun withDefaultStatic(extractOptions: ExtractOptions): ExtractOptions {
val expression = extractOptions.elements.singleOrNull() as? PsiExpression
val statement = PsiTreeUtil.getParentOfType(expression, PsiExpressionStatement::class.java)
if (statement != null && JavaHighlightUtil.isSuperOrThisCall(statement, true, true)) {
return extractOptions.copy(isStatic = true)
}
val shouldBeStatic = extractOptions.anchor.hasExplicitModifier(PsiModifier.STATIC)
return extractOptions.copy(isStatic = shouldBeStatic)
}
fun findTargetCandidates(analyzer: CodeFragmentAnalyzer, options: ExtractOptions): List<PsiClass> {
return generateSequence (options.anchor as PsiElement) { it.parent }
.takeWhile { it !is PsiFile }
.filterIsInstance<PsiClass>()
.filter { targetClass -> withTargetClass(analyzer, options, targetClass) != null }
.toList()
}
fun findDefaultTargetCandidate(candidates: List<PsiClass>): PsiClass {
return AnonymousTargetClassPreselectionUtil.getPreselection(candidates, candidates.first()) ?: candidates.first()
}
fun selectTargetClass(options: ExtractOptions, onSelect: (ExtractOptions) -> Unit): ExtractOptions {
val analyzer = CodeFragmentAnalyzer(options.elements)
val targetCandidates = findTargetCandidates(analyzer, options)
val preselection = findDefaultTargetCandidate(targetCandidates)
val editor = FileEditorManager.getInstance(options.project).selectedTextEditor ?: return options
val processor = PsiElementProcessor<PsiClass> { selected ->
val mappedOptions = withTargetClass(analyzer, options, selected)!!
onSelect(mappedOptions)
true
}
if (targetCandidates.size > 1) {
NavigationUtil.getPsiElementPopup(targetCandidates.toTypedArray(), PsiClassListCellRenderer(),
RefactoringBundle.message("choose.destination.class"), processor, preselection)
.showInBestPositionFor(editor)
} else {
processor.execute(preselection)
}
return options
}
private fun findFoldableArrayExpression(reference: PsiElement): PsiArrayAccessExpression? {
val arrayAccess = reference.parent as? PsiArrayAccessExpression
return if (arrayAccess?.arrayExpression == reference) arrayAccess else null
}
fun withFoldedArrayParameters(analyzer: CodeFragmentAnalyzer, extractOptions: ExtractOptions): ExtractOptions {
val writtenVariables = analyzer.findWrittenVariables().mapNotNull { it.name }
fun findFoldedCandidate(inputParameter: InputParameter): InputParameter? {
val arrayAccesses = inputParameter.references.map { findFoldableArrayExpression(it) ?: return null }
if (arrayAccesses.any { (it.parent as? PsiAssignmentExpression)?.lExpression == it }) return null
if (!ExtractMethodHelper.areSame(arrayAccesses.map { it.indexExpression })) return null
if (arrayAccesses.any { it.indexExpression?.text in writtenVariables }) return null
val parameterName = arrayAccesses.first().arrayExpression.text + "Element"
return InputParameter(arrayAccesses, parameterName, arrayAccesses.first().type ?: return null)
}
fun findHiddenExpression(arrayAccess: PsiArrayAccessExpression?): List<InputParameter> {
return extractOptions.inputParameters.filter {
ExtractMethodHelper.areSame(it.references.first(), arrayAccess?.arrayExpression)
|| ExtractMethodHelper.areSame(it.references.first(), arrayAccess?.indexExpression)
}
}
val foldedCandidates = extractOptions.inputParameters.mapNotNull { findFoldedCandidate(it) }
val (folded, hidden) = foldedCandidates
.map { it to findHiddenExpression(it.references.first() as? PsiArrayAccessExpression) }
.filter { it.second.size > 1 }.unzip()
return extractOptions.copy(inputParameters = extractOptions.inputParameters - hidden.flatten() + folded)
}
fun asConstructor(analyzer: CodeFragmentAnalyzer, extractOptions: ExtractOptions): ExtractOptions? {
if (! canBeConstructor(analyzer)) return null
return extractOptions.copy(isConstructor = true,
methodName = "this",
dataOutput = EmptyOutput(),
requiredVariablesInside = emptyList()
)
}
fun withForcedStatic(analyzer: CodeFragmentAnalyzer, extractOptions: ExtractOptions): ExtractOptions? {
val targetClass = PsiTreeUtil.getParentOfType(extractOptions.anchor, PsiClass::class.java)!!
if (PsiUtil.isLocalOrAnonymousClass(targetClass) || PsiUtil.isInnerClass(targetClass)) return null
val localUsages = analyzer.findInstanceMemberUsages(targetClass, extractOptions.elements)
val (violatedUsages, fieldUsages) = localUsages
.partition { localUsage -> PsiUtil.isAccessedForWriting(localUsage.reference) || localUsage.member !is PsiField }
if (violatedUsages.isNotEmpty()) return null
val fieldInputParameters =
fieldUsages.groupBy { it.member }.entries.map { (field, fieldUsages) ->
field as PsiField
InputParameter(
references = fieldUsages.map { it.reference },
name = field.name,
type = field.type
)
}
return extractOptions.copy(inputParameters = extractOptions.inputParameters + fieldInputParameters, isStatic = true)
}
fun canBeConstructor(analyzer: CodeFragmentAnalyzer): Boolean {
val elements = analyzer.elements
val parent = ExtractMethodHelper.getValidParentOf(elements.first())
val holderClass = PsiTreeUtil.getNonStrictParentOfType(parent, PsiClass::class.java) ?: return false
val method = PsiTreeUtil.getNonStrictParentOfType(parent, PsiMethod::class.java) ?: return false
val firstStatement = method.body?.statements?.firstOrNull() ?: return false
val startsOnBegin = firstStatement.textRange in TextRange(elements.first().textRange.startOffset, elements.last().textRange.endOffset)
val outStatements = method.body?.statements.orEmpty().dropWhile { it.textRange.endOffset <= elements.last().textRange.endOffset }
val hasOuterFinalFieldAssignments = analyzer.findInstanceMemberUsages(holderClass, outStatements)
.any { localUsage -> localUsage.member.hasModifierProperty(PsiModifier.FINAL) && PsiUtil.isAccessedForWriting(localUsage.reference) }
return method.isConstructor && startsOnBegin && !hasOuterFinalFieldAssignments && analyzer.findOutputVariables().isEmpty()
}
private val annotationsToKeep: Set<String> = setOf(
NLS, NON_NLS, LANGUAGE, PROPERTY_KEY, PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER, "org.intellij.lang.annotations.RegExp",
"org.intellij.lang.annotations.Pattern", "org.intellij.lang.annotations.MagicConstant", "org.intellij.lang.annotations.Subst",
"org.intellij.lang.annotations.PrintFormat"
)
private fun findAnnotationsToKeep(variable: PsiVariable?): List<PsiAnnotation> {
return variable?.annotations.orEmpty().filter { it.qualifiedName in annotationsToKeep }
}
private fun findAnnotationsToKeep(reference: PsiReference?): List<PsiAnnotation> {
return findAnnotationsToKeep(reference?.resolve() as? PsiVariable)
}
private fun withFilteredAnnotations(type: PsiType, context: PsiElement?): PsiType {
val project = type.annotations.firstOrNull()?.project ?: return type
val factory = PsiElementFactory.getInstance(project)
val typeHolder = factory.createParameter("x", type, context)
typeHolder.type.annotations.filterNot { it.qualifiedName in annotationsToKeep }.forEach { it.delete() }
return typeHolder.type
}
private fun withFilteredAnnotations(inputParameter: InputParameter, context: PsiElement?): InputParameter {
return inputParameter.copy(
annotations = findAnnotationsToKeep(inputParameter.references.firstOrNull() as? PsiReference),
type = withFilteredAnnotations(inputParameter.type, context)
)
}
private fun withFilteredAnnotation(output: DataOutput, context: PsiElement?): DataOutput {
val filteredType = withFilteredAnnotations(output.type, context)
return when(output) {
is VariableOutput -> output.copy(annotations = findAnnotationsToKeep(output.variable), type = filteredType)
is ExpressionOutput -> output.copy(annotations = findAnnotationsToKeep(output.returnExpressions.singleOrNull() as? PsiReference), type = filteredType)
is EmptyOutput, ArtificialBooleanOutput -> output
}
}
fun withFilteredAnnotations(extractOptions: ExtractOptions): ExtractOptions {
return extractOptions.copy(
inputParameters = extractOptions.inputParameters.map { withFilteredAnnotations(it, extractOptions.anchor.context) },
disabledParameters = extractOptions.disabledParameters.map { withFilteredAnnotations(it, extractOptions.anchor.context) },
dataOutput = withFilteredAnnotation(extractOptions.dataOutput, extractOptions.anchor.context)
)
}
} | apache-2.0 | e17cadcde97ed3f8c108355342cc18bb | 50.684932 | 173 | 0.760718 | 4.896496 | false | false | false | false |
allotria/intellij-community | platform/platform-tests/testSrc/com/intellij/lang/LanguageExtensionCacheTest.kt | 1 | 5910 | // 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.lang
import com.intellij.codeInsight.completion.CompletionExtension
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.mock.MockLanguageFileType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.DefaultPluginDescriptor
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.fileTypes.PlainTextLanguage
import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.testFramework.registerExtension
import com.intellij.util.KeyedLazyInstance
import java.util.*
class LanguageExtensionCacheTest : LightPlatformTestCase() {
private val myExtensionPointName = ExtensionPointName<KeyedLazyInstance<String>>("testLangExt")
private val myCompletionExtensionPointName = ExtensionPointName<KeyedLazyInstance<String>>("testCompletionExt")
private val myExtensionPointXML = """
<extensionPoint qualifiedName="$myExtensionPointName" beanClass="com.intellij.lang.LanguageExtensionPoint">
<with attribute="implementationClass" implements="java.lang.String"/>
</extensionPoint>
"""
private val myCompletionExtensionPointXML = """
<extensionPoint qualifiedName="$myCompletionExtensionPointName" beanClass="com.intellij.lang.LanguageExtensionPoint">
<with attribute="implementationClass" implements="java.lang.String"/>
</extensionPoint>
"""
private val descriptor = DefaultPluginDescriptor(PluginId.getId(""), javaClass.classLoader)
private lateinit var area: ExtensionsAreaImpl
private lateinit var extension: LanguageExtension<String>
private lateinit var completionExtension: CompletionExtension<String>
override fun setUp() {
super.setUp()
area = ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl
area.registerExtensionPoints(descriptor, listOf(JDOMUtil.load(myExtensionPointXML), JDOMUtil.load(myCompletionExtensionPointXML)))
Disposer.register(testRootDisposable, Disposable {
area.unregisterExtensionPoint(myExtensionPointName.name)
area.unregisterExtensionPoint(myCompletionExtensionPointName.name)
})
extension = LanguageExtension(myExtensionPointName, null)
completionExtension = CompletionExtension(myCompletionExtensionPointName.name)
}
private fun registerExtension(extensionPointName: ExtensionPointName<KeyedLazyInstance<String>>,
languageID: String,
implementationFqn: String
): Disposable {
val disposable = Disposer.newDisposable(testRootDisposable, "registerExtension")
val languageExtensionPoint = LanguageExtensionPoint<String>(languageID, implementationFqn, PluginManagerCore.getPlugin(PluginManagerCore.CORE_ID)!!)
ApplicationManager.getApplication().registerExtension(extensionPointName, languageExtensionPoint, disposable)
return disposable
}
fun `test extensions are cleared when explicit extension is added`() {
val language = PlainTextLanguage.INSTANCE
val unregisterDialectDisposable = Disposer.newDisposable(testRootDisposable, getTestName(false))
val plainTextDialect = registerLanguageDialect(unregisterDialectDisposable)
val extensionRegistrationDisposable = registerExtension(myExtensionPointName, language.id, String::class.java.name) // emulate registration via plugin.xml
assertSize(1, extension.allForLanguage(language))
assertEquals("", extension.forLanguage(language)) // empty because created with new String(); it is cached within forLanguage()
extension.addExplicitExtension(language, "hello")
assertSize(2, extension.allForLanguage(language))
assertEquals("hello", extension.forLanguage(language)) // explicit extension takes precedence over extension from plugin.xml
assertSize(2, extension.allForLanguage(plainTextDialect))
extension.removeExplicitExtension(language, "hello")
assertSize(1, extension.allForLanguage(language))
assertSize(1, extension.allForLanguage(plainTextDialect))
assertEquals("", extension.forLanguage(language))
Disposer.dispose(unregisterDialectDisposable)
Disposer.dispose(extensionRegistrationDisposable)
}
private fun registerLanguageDialect(parentDisposable: Disposable): Language {
val plainTextDialectFileType = MockLanguageFileType(object : Language(PlainTextLanguage.INSTANCE, "PlainTextDialect") {
}, "xxxx")
FileTypeManager.getInstance().registerFileType(plainTextDialectFileType)
Disposer.register(parentDisposable, Disposable { FileTypeManagerEx.getInstanceEx().unregisterFileType(plainTextDialectFileType) })
return plainTextDialectFileType.language
}
fun `test CompletionExtension extensions are cleared when explicit extension is added`() {
val unregisterDialectDisposable = Disposer.newDisposable(testRootDisposable, getTestName(false))
val plainTextDialect = registerLanguageDialect(unregisterDialectDisposable)
val extensionRegistrationDisposable = registerExtension(myCompletionExtensionPointName, PlainTextLanguage.INSTANCE.id, String::class.java.name)
assertSize(1, completionExtension.forKey(PlainTextLanguage.INSTANCE))
assertSize(1, completionExtension.forKey(plainTextDialect))
Disposer.dispose(unregisterDialectDisposable)
Disposer.dispose(extensionRegistrationDisposable)
assertSize(0, completionExtension.forKey(plainTextDialect))
}
}
| apache-2.0 | 8e61d0c213d3d762d175583a911f1ca8 | 51.767857 | 160 | 0.812014 | 5.436983 | false | true | false | false |
scenerygraphics/scenery | src/main/kotlin/graphics/scenery/controls/behaviours/VRSelectionWheel.kt | 1 | 5253 | package graphics.scenery.controls.behaviours
import graphics.scenery.Scene
import graphics.scenery.attribute.spatial.Spatial
import graphics.scenery.controls.OpenVRHMD
import graphics.scenery.controls.TrackedDeviceType
import graphics.scenery.controls.TrackerInput
import graphics.scenery.controls.TrackerRole
import graphics.scenery.utils.Wiggler
import org.scijava.ui.behaviour.DragBehaviour
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Future
/**
* A fast selection wheel to let the user choose between different actions.
*
* Use the [createAndSet] method to create.
*
* The list of selectable actions can be changed dynamically.
*
* @param actions List of named lambdas which can be selected by the user
* @param cutoff after this distance between controller and targets no action will be selected if the button is released
*
* @author Jan Tiemann
*/
class VRSelectionWheel(
val controller: Spatial,
val scene: Scene,
val hmd: TrackerInput,
var actions: List<Action>,
val cutoff: Float = 0.1f,
) : DragBehaviour {
private var activeWheel: WheelMenu? = null
private var activeWiggler: Wiggler? = null
/**
* This function is called by the framework. Usually you don't need to call this.
*/
override fun init(x: Int, y: Int) {
activeWheel = WheelMenu(hmd, actions)
activeWheel?.spatial()?.position = controller.worldPosition()
scene.addChild(activeWheel!!)
}
/**
* This function is called by the framework. Usually you don't need to call this.
*/
override fun drag(x: Int, y: Int) {
val (closestSphere, distance) = activeWheel?.closestActionSphere(controller.worldPosition()) ?: return
if (distance > cutoff) {
activeWiggler?.deativate()
activeWiggler = null
} else if (activeWiggler?.target != closestSphere.representation.spatial()) {
activeWiggler?.deativate()
activeWiggler = Wiggler(closestSphere.representation.spatial(), 0.01f)
}
}
/**
* This function is called by the framework. Usually you don't need to call this.
*/
override fun end(x: Int, y: Int) {
val (closestActionSphere, distance) = activeWheel?.closestActionSphere(controller.worldPosition()) ?: return
if (distance < cutoff) {
when(val entry = closestActionSphere.action){
is Action -> entry.action()
is Switch -> entry.toggle()
else -> throw IllegalStateException("${entry.javaClass.simpleName} not implemented for Selection Wheel")
}
}
activeWiggler?.deativate()
activeWiggler = null
activeWheel?.let { scene.removeChild(it) }
activeWheel = null
}
/**
* Contains Convenience method for adding tool select behaviour
*/
companion object {
/**
* Convenience method for adding tool select behaviour
*/
fun createAndSet(
scene: Scene,
hmd: OpenVRHMD,
button: List<OpenVRHMD.OpenVRButton>,
controllerSide: List<TrackerRole>,
actions: List<Pair<String, (Spatial) -> Unit>>,
): Future<VRSelectionWheel> {
val future = CompletableFuture<VRSelectionWheel>()
hmd.events.onDeviceConnect.add { _, device, _ ->
if (device.type == TrackedDeviceType.Controller) {
device.model?.let { controller ->
if (controllerSide.contains(device.role)) {
val name = "VRSelectionWheel:${hmd.trackingSystemName}:${device.role}:$button"
val vrToolSelector = VRSelectionWheel(
controller.children.first().spatialOrNull()
?: throw IllegalArgumentException("The target controller needs a spatial."),
scene,
hmd,
actions.toActions(
controller.children.first().spatialOrNull() ?: throw IllegalArgumentException(
"The target controller needs a spatial."
)
)
)
hmd.addBehaviour(name, vrToolSelector)
button.forEach {
hmd.addKeyBinding(name, device.role, it)
}
future.complete(vrToolSelector)
}
}
}
}
return future
}
/**
* Convert lambdas to wheel menu action.
*/
fun List<Pair<String, () -> Unit>>.toActions(): List<Action> = map { Action(it.first, action = it.second)}
/**
* Convert lambdas which take the spatial of the controller as an argument to wheel menu action.
*/
fun List<Pair<String, (Spatial) -> Unit>>.toActions(device: Spatial): List<Action> =
map { Action(it.first) { it.second.invoke(device) } }
}
}
| lgpl-3.0 | 6edd7e5a9a4d75966768301475c88724 | 35.479167 | 121 | 0.579669 | 4.913938 | false | false | false | false |
RanolP/Kubo | Kubo-Telegram/src/main/kotlin/io/github/ranolp/kubo/telegram/bot/functions/TelegramFunction.kt | 1 | 1382 | package io.github.ranolp.kubo.telegram.bot.functions
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Response
import com.github.kittinunf.fuel.httpPost
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import io.github.ranolp.kubo.telegram.Telegram
import io.github.ranolp.kubo.telegram.util.parseJson
internal abstract class TelegramFunction<T>(private val functionName: String) {
fun request(): T {
val (request, response, result) = "https://api.telegram.org/bot${Telegram.getBotAdapter().getToken()}/$functionName".httpPost(generateArguments().toList()).responseString()
val (data, error) = result
if (error != null) {
throw error
} else {
return parse(request, response, data!!)
}
}
inline fun <T> work(result: String, worker: JsonElement.() -> T): T? {
val jsonObject = parseJson(result).asJsonObject
if (jsonObject["ok"].asBoolean) {
return worker(jsonObject["result"])
}
return null
}
inline fun <T> workObject(result: String, worker: JsonObject.() -> T): T? {
return work(result, { worker(asJsonObject) })
}
open internal fun generateArguments(): Map<String, Any?> = emptyMap()
abstract internal fun parse(request: Request, response: Response, result: String): T
} | mit | 3fd11b925a9883a61559b733c39a9b1e | 35.394737 | 180 | 0.676556 | 4.213415 | false | false | false | false |
CORDEA/MackerelClient | app/src/main/java/jp/cordea/mackerelclient/adapter/UserAdapter.kt | 1 | 2806 | package jp.cordea.mackerelclient.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.fragment.app.Fragment
import com.squareup.picasso.Picasso
import jp.cordea.mackerelclient.PicassoCircularTransform
import jp.cordea.mackerelclient.R
import jp.cordea.mackerelclient.api.response.User
import jp.cordea.mackerelclient.databinding.ListItemUserBinding
import jp.cordea.mackerelclient.di.FragmentScope
import jp.cordea.mackerelclient.fragment.UserDeleteConfirmDialogFragment
import jp.cordea.mackerelclient.utils.GravatarUtils
import javax.inject.Inject
@FragmentScope
class UserAdapter @Inject constructor(
private val fragment: Fragment
) : ArrayAdapter<User>(
fragment.context!!,
R.layout.list_item_user
) {
private var items: List<User> = emptyList()
private var own: String? = null
override fun getView(
position: Int,
convertView: View?,
parent: ViewGroup?
): View? {
var view = convertView
val viewHolder: ViewHolder
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.list_item_user, parent, false)
viewHolder = ViewHolder(view)
view.tag = viewHolder
} else {
viewHolder = view.tag as ViewHolder
}
val item = items[position]
viewHolder.binding.run {
GravatarUtils.getGravatarImage(
item.email,
context.resources.getDimensionPixelSize(R.dimen.user_thumbnail_size_small)
)?.let { url ->
Picasso.with(context)
.load(url)
.transform(PicassoCircularTransform())
.into(userThumbnailImageView)
}
nameTextView.text = item.screenName
emailTextView.text = item.email
var isOwn = false
own?.let {
if (it == item.email) {
isOwn = true
deleteImageView.visibility = View.GONE
}
}
if (!isOwn) {
deleteImageView.setOnClickListener {
UserDeleteConfirmDialogFragment.newInstance(item.id)
.show(fragment.childFragmentManager, UserDeleteConfirmDialogFragment.TAG)
}
}
}
return view
}
override fun getItem(position: Int): User? = items[position]
override fun getCount(): Int = items.size
fun update(users: List<User>, own: String?) {
items = users
this.own = own
notifyDataSetChanged()
}
class ViewHolder(view: View) {
val binding: ListItemUserBinding = ListItemUserBinding.bind(view)
}
}
| apache-2.0 | 5d6aabe9b46fdbc803cd739ea94cdb9d | 31.252874 | 97 | 0.625445 | 4.846287 | false | false | false | false |
zdary/intellij-community | platform/lang-impl/src/com/intellij/ide/util/PsiElementBackgroundListCellRendererComputer.kt | 1 | 6092 | // 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.ide.util
import com.intellij.ide.util.PsiElementListCellRenderer.ItemMatchers
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.application.readAction
import com.intellij.openapi.progress.runUnderIndicator
import com.intellij.openapi.ui.popup.util.PopupUtil
import com.intellij.psi.PsiElement
import com.intellij.ui.AnimatedIcon.ANIMATION_IN_RENDERER_ALLOWED
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.ScreenUtil
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.popup.AbstractPopup
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.concurrency.annotations.RequiresReadLock
import com.intellij.util.ui.UIUtil.runWhenChanged
import com.intellij.util.ui.UIUtil.runWhenHidden
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.future.asCompletableFuture
import java.awt.Dimension
import java.awt.Point
import java.awt.Rectangle
import java.util.concurrent.Future
import javax.swing.AbstractListModel
import javax.swing.DefaultListCellRenderer
import javax.swing.JLabel
import javax.swing.JList
import javax.swing.event.ListDataEvent
internal fun getComputer(list: JList<*>, renderer: PsiElementListCellRenderer<*>): PsiElementBackgroundListCellRendererComputer {
list.getClientProperty(renderer)?.let {
return it as PsiElementBackgroundListCellRendererComputer
}
val computer = PsiElementBackgroundListCellRendererComputer(list, renderer)
list.putClientProperty(renderer, computer)
list.putClientProperty(ANIMATION_IN_RENDERER_ALLOWED, true)
fun cleanUp() {
list.putClientProperty(renderer, null)
list.putClientProperty(ANIMATION_IN_RENDERER_ALLOWED, null)
computer.dispose()
}
runWhenHidden(list, ::cleanUp)
runWhenChanged(list, "cellRenderer", ::cleanUp)
return computer
}
internal class PsiElementBackgroundListCellRendererComputer(
private val list: JList<*>,
private val renderer: PsiElementListCellRenderer<*>,
) {
private val myCoroutineScope = CoroutineScope(Job())
private val myRepaintQueue = Channel<Unit>(Channel.CONFLATED)
private val uiDispatcher = AppUIExecutor.onUiThread().later().coroutineDispatchingContext()
private val myComponentsMap: MutableMap<Any, Future<RendererComponents>> = HashMap()
init {
myCoroutineScope.launch(uiDispatcher) {
// A tick happens when an element has finished computing.
// Several elements are also merged into a single tick because the Channel is CONFLATED.
for (tick in myRepaintQueue) {
notifyModelChanged(list)
redrawListAndContainer(list)
delay(100) // update UI no more often that once in 100ms
}
}
}
fun dispose() {
myCoroutineScope.cancel()
myRepaintQueue.close()
myComponentsMap.clear()
}
@RequiresEdt
fun computeComponentsAsync(element: PsiElement): Future<RendererComponents> {
return myComponentsMap.computeIfAbsent(element, ::doComputeComponentsAsync)
}
private fun doComputeComponentsAsync(item: Any): Future<RendererComponents> {
val result = myCoroutineScope.async {
//delay((Math.random() * 3000 + 2000).toLong()) // uncomment to add artificial delay to check out how it looks in UI
readAction { progress ->
runUnderIndicator(progress) {
rendererComponents(item)
}
}
}
myCoroutineScope.launch {
result.join()
myRepaintQueue.send(Unit) // repaint _after_ the resulting future is done
}
return result.asCompletableFuture()
}
@RequiresReadLock(generateAssertion = false)
private fun rendererComponents(item: Any): RendererComponents {
val leftComponent = renderer.LeftRenderer(ItemMatchers(null, null)).getListCellRendererComponent(
list, item, -1, false, false
) as ColoredListCellRenderer<*>
val rightComponent = renderer.rightRenderer(item)?.getListCellRendererComponent(
list, item, -1, false, false
) as DefaultListCellRenderer?
return RendererComponents(leftComponent, rightComponent)
}
}
internal data class RendererComponents(
val leftComponent: SimpleColoredComponent,
val rightComponent: JLabel?
)
/**
* This method forces [javax.swing.plaf.basic.BasicListUI.updateLayoutStateNeeded] to become non-zero via the path:
* [JList.getModel]
* -> [AbstractListModel.getListDataListeners]
* -> [javax.swing.event.ListDataListener.contentsChanged]
* -> [javax.swing.plaf.basic.BasicListUI.Handler.contentsChanged]
*
* It's needed so next call of [javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState] will recompute list's preferred size.
*/
private fun notifyModelChanged(list: JList<*>) {
val model = list.model
if (model !is AbstractListModel) {
error("Unsupported list model: " + model.javaClass.name)
}
val size = model.size
if (size == 0) {
return
}
val listeners = model.listDataListeners
if (listeners.isEmpty()) {
return
}
val e = ListDataEvent(list, ListDataEvent.CONTENTS_CHANGED, 0, size - 1)
for (listener in listeners) {
listener.contentsChanged(e)
}
}
private fun redrawListAndContainer(list: JList<*>) {
if (!list.isShowing) {
return
}
resizePopup(list)
list.repaint()
}
private fun resizePopup(list: JList<*>) {
val popup = PopupUtil.getPopupContainerFor(list) ?: return
if (popup is AbstractPopup && popup.dimensionServiceKey != null) {
return
}
val popupLocation = popup.locationOnScreen
val rectangle = Rectangle(popupLocation, list.parent.preferredSize)
ScreenUtil.fitToScreen(rectangle)
if (rectangle.width > popup.size.width) { // don't shrink popup
popup.setLocation(Point(rectangle.x, popupLocation.y)) // // don't change popup vertical position on screen
popup.size = Dimension(rectangle.width, popup.size.height) // don't change popup height
}
}
| apache-2.0 | 7a13024f0a516f81ce0f40a5331ffdd7 | 35.921212 | 140 | 0.763132 | 4.43377 | false | false | false | false |
zdary/intellij-community | plugins/ide-features-trainer/src/training/dsl/impl/LessonExecutor.kt | 1 | 13089 | // 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 training.dsl.impl
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Alarm
import org.intellij.lang.annotations.Language
import training.dsl.*
import training.learn.ActionsRecorder
import training.learn.course.KLesson
import training.learn.exceptons.NoTextEditor
import training.learn.lesson.LessonManager
import training.statistic.StatisticBase
import training.ui.LearnToolWindowFactory
import training.util.WeakReferenceDelegator
import java.awt.Component
import kotlin.math.max
class LessonExecutor(val lesson: KLesson, val project: Project, initialEditor: Editor?, val predefinedFile: VirtualFile?) : Disposable {
private data class TaskInfo(val content: () -> Unit,
var restoreIndex: Int,
var taskProperties: TaskProperties?,
val taskContent: (TaskContext.() -> Unit)?,
var messagesNumberBeforeStart: Int = 0,
var rehighlightComponent: (() -> Component)? = null,
var userVisibleInfo: PreviousTaskInfo? = null,
val removeAfterDoneMessages: MutableList<Int> = mutableListOf())
var predefinedEditor: Editor? by WeakReferenceDelegator(initialEditor)
private set
private val selectedEditor: Editor?
get() {
val result = if (lesson.lessonType.isSingleEditor) predefinedEditor
else FileEditorManager.getInstance(project).selectedTextEditor?.also {
// We may need predefined editor in the multi-editor lesson in the start of the lesson.
// It seems, there is a platform bug with no selected editor when the needed editor is actually opened.
// But better do not use it later to avoid possible bugs.
predefinedEditor = null
} ?: predefinedEditor // It may be needed in the start of the lesson.
return result?.takeIf { !it.isDisposed }
}
val editor: Editor
get() = selectedEditor ?: throw NoTextEditor()
data class TaskData(var shouldRestoreToTask: (() -> TaskContext.TaskId?)? = null,
var delayMillis: Int = 0)
private val taskActions: MutableList<TaskInfo> = ArrayList()
var foundComponent: Component? = null
var rehighlightComponent: (() -> Component)? = null
private var currentRecorder: ActionsRecorder? = null
private var currentRestoreRecorder: ActionsRecorder? = null
internal var currentTaskIndex = 0
private set
private val parentDisposable: Disposable = LearnToolWindowFactory.learnWindowPerProject[project]?.parentDisposable ?: project
// Is used from ui detection pooled thread
@Volatile
var hasBeenStopped = false
private set
init {
Disposer.register(parentDisposable, this)
}
private fun addTaskAction(taskProperties: TaskProperties? = null, taskContent: (TaskContext.() -> Unit)? = null, content: () -> Unit) {
val previousIndex = max(taskActions.size - 1, 0)
taskActions.add(TaskInfo(content, previousIndex, taskProperties, taskContent))
}
fun getUserVisibleInfo(index: Int): PreviousTaskInfo {
return taskActions[index].userVisibleInfo ?: throw IllegalArgumentException("No information available for task $index")
}
fun waitBeforeContinue(delayMillis: Int) {
addTaskAction {
val action = {
foundComponent = taskActions[currentTaskIndex].userVisibleInfo?.ui
rehighlightComponent = taskActions[currentTaskIndex].rehighlightComponent
processNextTask(currentTaskIndex + 1)
}
Alarm().addRequest(action, delayMillis)
}
}
fun task(taskContent: TaskContext.() -> Unit) {
ApplicationManager.getApplication().assertIsDispatchThread()
val taskProperties = LessonExecutorUtil.taskProperties(taskContent, project)
addTaskAction(taskProperties, taskContent) {
val taskInfo = taskActions[currentTaskIndex]
taskInfo.taskProperties?.messagesNumber?.let {
LessonManager.instance.removeInactiveMessages(it)
taskInfo.taskProperties?.messagesNumber = 0 // Here could be runtime messages
}
processTask(taskContent)
}
}
override fun dispose() {
if (!hasBeenStopped) {
ApplicationManager.getApplication().assertIsDispatchThread()
disposeRecorders()
hasBeenStopped = true
taskActions.clear()
}
}
fun stopLesson() {
Disposer.dispose(this)
}
private fun disposeRecorders() {
currentRecorder?.let { Disposer.dispose(it) }
currentRecorder = null
currentRestoreRecorder?.let { Disposer.dispose(it) }
currentRestoreRecorder = null
}
val virtualFile: VirtualFile
get() = FileDocumentManager.getInstance().getFile(editor.document) ?: error("No Virtual File")
fun startLesson() {
addAllInactiveMessages()
if (lesson.properties.canStartInDumbMode) {
processNextTask(0)
}
else {
DumbService.getInstance(project).runWhenSmart {
if (!hasBeenStopped)
processNextTask(0)
}
}
}
private fun processNextTask(taskIndex: Int) {
// ModalityState.current() or without argument - cannot be used: dialog steps can stop to work.
// Good example: track of rename refactoring
invokeLater(ModalityState.any()) {
disposeRecorders()
currentTaskIndex = taskIndex
processNextTask2()
}
}
private fun processNextTask2() {
LessonManager.instance.clearRestoreMessage()
ApplicationManager.getApplication().assertIsDispatchThread()
if (currentTaskIndex == taskActions.size) {
LessonManager.instance.passLesson(lesson)
disposeRecorders()
return
}
val taskInfo = taskActions[currentTaskIndex]
taskInfo.messagesNumberBeforeStart = LessonManager.instance.messagesNumber()
setUserVisibleInfo()
taskInfo.content()
}
private fun setUserVisibleInfo() {
val taskInfo = taskActions[currentTaskIndex]
// do not reset information from the previous tasks if it is available already
if (taskInfo.userVisibleInfo == null) {
taskInfo.userVisibleInfo = object : PreviousTaskInfo {
override val text: String = selectedEditor?.document?.text ?: ""
override val position: LogicalPosition = selectedEditor?.caretModel?.currentCaret?.logicalPosition ?: LogicalPosition(0, 0)
override val sample: LessonSample = selectedEditor?.let { prepareSampleFromCurrentState(it) } ?: parseLessonSample("")
override val ui: Component? = foundComponent
override val file: VirtualFile? = selectedEditor?.let { FileDocumentManager.getInstance().getFile(it.document) }
}
taskInfo.rehighlightComponent = rehighlightComponent
}
//Clear user visible information for later tasks
for (i in currentTaskIndex + 1 until taskActions.size) {
taskActions[i].userVisibleInfo = null
taskActions[i].rehighlightComponent = null
}
foundComponent = null
rehighlightComponent = null
}
private fun processTask(taskContent: TaskContext.() -> Unit) {
ApplicationManager.getApplication().assertIsDispatchThread()
val recorder = ActionsRecorder(project, selectedEditor?.document, this)
currentRecorder = recorder
val taskCallbackData = TaskData()
val taskContext = TaskContextImpl(this, recorder, currentTaskIndex, taskCallbackData)
taskContext.apply(taskContent)
if (taskContext.steps.isEmpty()) {
processNextTask(currentTaskIndex + 1)
return
}
chainNextTask(taskContext, recorder, taskCallbackData)
processTestActions(taskContext)
}
internal fun applyRestore(taskContext: TaskContextImpl, restoreId: TaskContext.TaskId? = null) {
taskContext.steps.forEach { it.cancel(true) }
val restoreIndex = restoreId?.idx ?: taskActions[taskContext.taskIndex].restoreIndex
val restoreInfo = taskActions[restoreIndex]
restoreInfo.rehighlightComponent?.let { it() }
LessonManager.instance.resetMessagesNumber(restoreInfo.messagesNumberBeforeStart)
StatisticBase.logRestorePerformed(lesson, currentTaskIndex)
processNextTask(restoreIndex)
}
/** @return a callback to clear resources used to track restore */
private fun checkForRestore(taskContext: TaskContextImpl,
taskData: TaskData): () -> Unit {
var clearRestore: () -> Unit = {}
fun restore(restoreId: TaskContext.TaskId) {
clearRestore()
invokeLater(ModalityState.any()) { // restore check must be done after pass conditions (and they will be done during current event processing)
if (canBeRestored(taskContext)) {
applyRestore(taskContext, restoreId)
}
}
}
val shouldRestoreToTask = taskData.shouldRestoreToTask ?: return {}
fun checkFunction(): Boolean {
if (hasBeenStopped) {
// Strange situation
clearRestore()
return false
}
val checkAndRestoreIfNeeded = {
if (canBeRestored(taskContext)) {
val restoreId = shouldRestoreToTask()
if (restoreId != null) {
restore(restoreId)
}
}
}
if (taskData.delayMillis == 0) {
checkAndRestoreIfNeeded()
}
else {
Alarm().addRequest(checkAndRestoreIfNeeded, taskData.delayMillis)
}
return false
}
// Not sure about use-case when we need to check restore at the start of current task
// But it theoretically can be needed in case of several restores of dependent steps
if (checkFunction()) return {}
val restoreRecorder = ActionsRecorder(project, selectedEditor?.document, this)
currentRestoreRecorder = restoreRecorder
val restoreFuture = restoreRecorder.futureCheck { checkFunction() }
clearRestore = {
if (!restoreFuture.isDone) {
restoreFuture.cancel(true)
}
}
return clearRestore
}
private fun chainNextTask(taskContext: TaskContextImpl,
recorder: ActionsRecorder,
taskData: TaskData) {
val clearRestore = checkForRestore(taskContext, taskData)
recorder.tryToCheckCallback()
taskContext.steps.forEach { step ->
step.thenAccept {
ApplicationManager.getApplication().assertIsDispatchThread()
val taskHasBeenDone = isTaskCompleted(taskContext)
if (taskHasBeenDone) {
clearRestore()
LessonManager.instance.passExercise()
val taskInfo = taskActions[currentTaskIndex]
if (foundComponent == null) foundComponent = taskInfo.userVisibleInfo?.ui
if (rehighlightComponent == null) rehighlightComponent = taskInfo.rehighlightComponent
for (index in taskInfo.removeAfterDoneMessages) {
LessonManager.instance.removeMessage(index)
}
taskInfo.taskProperties?.let { it.messagesNumber -= taskInfo.removeAfterDoneMessages.size }
processNextTask(currentTaskIndex + 1)
}
}
}
}
private fun isTaskCompleted(taskContext: TaskContextImpl) = taskContext.steps.all { it.isDone && it.get() }
private fun canBeRestored(taskContext: TaskContextImpl): Boolean {
return !hasBeenStopped && taskContext.steps.any { !it.isCancelled && !it.isCompletedExceptionally && (!it.isDone || !it.get()) }
}
private fun processTestActions(taskContext: TaskContextImpl) {
if (TaskTestContext.inTestMode && taskContext.testActions.isNotEmpty()) {
LessonManager.instance.testActionsExecutor.execute {
taskContext.testActions.forEach { it.run() }
}
}
}
fun text(@Language("HTML") text: String, removeAfterDone: Boolean = false) {
val taskInfo = taskActions[currentTaskIndex]
if (removeAfterDone) taskInfo.removeAfterDoneMessages.add(LessonManager.instance.messagesNumber())
// Here could be runtime messages
taskInfo.taskProperties?.let {
it.messagesNumber++
}
var hasDetection = false
for (i in currentTaskIndex until taskActions.size) {
if (taskInfo.taskProperties?.hasDetection == true) {
hasDetection = true
break
}
}
LessonManager.instance.addMessage(text, !hasDetection)
}
private fun addAllInactiveMessages() {
val tasksWithContent = taskActions.mapNotNull { it.taskContent }
val messages = tasksWithContent.map { LessonExecutorUtil.textMessages(it, project) }.flatten()
LessonManager.instance.addInactiveMessages(messages)
}
} | apache-2.0 | dea33e63c9f2411d900532eebd5d3ba7 | 36.723343 | 148 | 0.705554 | 4.801541 | false | false | false | false |
bitsydarel/DBWeather | app/src/main/java/com/dbeginc/dbweather/managelocations/ManageLocationsFragment.kt | 1 | 6183 | /*
* Copyright (C) 2017 Darel Bitsy
* 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.dbeginc.dbweather.managelocations
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.databinding.DataBindingUtil
import android.graphics.Color
import android.os.Bundle
import android.support.design.widget.BaseTransientBottomBar
import android.support.design.widget.Snackbar
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.dbeginc.dbweather.MainActivity
import com.dbeginc.dbweather.R
import com.dbeginc.dbweather.base.BaseFragment
import com.dbeginc.dbweather.databinding.FragmentManageLocationsBinding
import com.dbeginc.dbweather.utils.utility.LOADING_PERIOD
import com.dbeginc.dbweather.utils.utility.hide
import com.dbeginc.dbweather.utils.utility.show
import com.dbeginc.dbweathercommon.utils.RequestState
import com.dbeginc.dbweathercommon.view.MVMPVView
import com.dbeginc.dbweatherweather.managelocations.ManageLocationsViewModel
import com.dbeginc.dbweatherweather.viewmodels.WeatherLocationModel
/**
* A ManageLocationsFragment [BaseFragment] subclass.
*/
class ManageLocationsFragment : BaseFragment(), MVMPVView, LocationManagerBridge, SwipeRefreshLayout.OnRefreshListener {
private lateinit var binding: FragmentManageLocationsBinding
private val viewModel: ManageLocationsViewModel by lazy {
return@lazy ViewModelProviders.of(this, factory.get())[ManageLocationsViewModel::class.java]
}
private val locationsAdapter: ManageLocationsAdapter by lazy {
return@lazy ManageLocationsAdapter()
}
private val swipeToDeleteLocations: ItemTouchHelper by lazy {
return@lazy ItemTouchHelper(SwipeToDeleteLocations(this))
}
override val stateObserver: Observer<RequestState> = Observer { state ->
state?.let { onStateChanged(state = it) }
}
private val userListsObserver: Observer<List<WeatherLocationModel>> = Observer { locations ->
locations?.let {
if (it.isEmpty()) {
binding.manageLocations.hide()
binding.emptyList.show()
} else locationsAdapter.updateData(newData = it)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(
inflater.cloneInContext(android.view.ContextThemeWrapper(activity, R.style.AppTheme)),
R.layout.fragment_manage_locations,
container,
false
)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as? AppCompatActivity)?.setSupportActionBar(binding.manageLocationsToolbar)
setupView()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
(activity as? MainActivity)?.let { container ->
binding.manageLocationsToolbar.setNavigationOnClickListener {
container.openNavigationDrawer()
}
}
viewModel.getRequestState().observe(this, stateObserver)
viewModel.getLocations().observe(this, userListsObserver)
onRefresh()
}
override fun setupView() {
binding.manageLocations.adapter = locationsAdapter
binding.manageLocations.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
swipeToDeleteLocations.attachToRecyclerView(binding.manageLocations)
binding.manageLocationsContainer.setOnRefreshListener(this)
}
override fun onStateChanged(state: RequestState) {
when (state) {
RequestState.LOADING -> binding.manageLocationsContainer.isRefreshing = true
RequestState.COMPLETED -> binding.manageLocationsContainer.postDelayed(this::hideLoadingStatus, LOADING_PERIOD)
RequestState.ERROR -> binding.manageLocationsLayout.postDelayed(this::onRequestFailed, LOADING_PERIOD)
}
}
override fun onLocationDeleted(location: WeatherLocationModel, position: Int) {
Snackbar.make(binding.manageLocationsLayout, R.string.location_removed, Snackbar.LENGTH_LONG)
.setAction(android.R.string.cancel) { locationsAdapter.cancelItemDeletion(position) }
.addCallback(object : BaseTransientBottomBar.BaseCallback<Snackbar>() {
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
if (event == BaseTransientBottomBar.BaseCallback.DISMISS_EVENT_TIMEOUT) {
locationsAdapter.remoteItemAt(position)
viewModel.deleteLocation(location)
}
}
})
.show()
}
override fun onRefresh() = viewModel.loadUserLocations()
private fun hideLoadingStatus() {
binding.manageLocationsContainer.isRefreshing = false
}
private fun onRequestFailed() {
hideLoadingStatus()
Snackbar.make(binding.manageLocationsLayout, R.string.could_not_load_your_locations, Snackbar.LENGTH_LONG)
.setAction(R.string.retry) { viewModel.loadUserLocations() }
.setActionTextColor(Color.RED)
.show()
}
}
| gpl-3.0 | 3688b07de251a250d0d25540631e9f71 | 37.886792 | 123 | 0.718745 | 5.018669 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/repl/KtScratchReplExecutor.kt | 6 | 8964 | // 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.scratch.repl
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.execution.target.TargetProgressIndicator
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.cli.common.repl.replInputAsXml
import org.jetbrains.kotlin.cli.common.repl.replNormalizeLineBreaks
import org.jetbrains.kotlin.cli.common.repl.replRemoveLineBreaksInTheEnd
import org.jetbrains.kotlin.cli.common.repl.replUnescapeLineBreaks
import org.jetbrains.kotlin.console.KotlinConsoleKeeper
import org.jetbrains.kotlin.console.actions.logError
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.scratch.*
import org.jetbrains.kotlin.idea.scratch.output.ScratchOutput
import org.jetbrains.kotlin.idea.scratch.output.ScratchOutputType
import org.w3c.dom.Element
import org.xml.sax.InputSource
import java.io.ByteArrayInputStream
import java.nio.charset.Charset
import javax.xml.parsers.DocumentBuilderFactory
class KtScratchReplExecutor(file: ScratchFile) : SequentialScratchExecutor(file) {
private val history: ReplHistory = ReplHistory()
@Volatile
private var osProcessHandler: OSProcessHandler? = null
override fun startExecution() {
val module = file.module
val (environmentRequest, cmdLine) = KotlinConsoleKeeper.createReplCommandLine(file.project, module)
val environment = environmentRequest.prepareEnvironment(TargetProgressIndicator.EMPTY)
val commandPresentation = cmdLine.getCommandPresentation(environment)
LOG.printDebugMessage("Execute REPL: $commandPresentation")
osProcessHandler = ReplOSProcessHandler(environment.createProcess(cmdLine, EmptyProgressIndicator()), commandPresentation)
osProcessHandler?.startNotify()
}
override fun stopExecution(callback: (() -> Unit)?) {
val processHandler = osProcessHandler
if (processHandler == null) {
callback?.invoke()
return
}
try {
if (callback != null) {
processHandler.addProcessListener(object : ProcessAdapter() {
override fun processTerminated(event: ProcessEvent) {
callback()
}
})
}
sendCommandToProcess(":quit")
} catch (e: Exception) {
errorOccurs(KotlinJvmBundle.message("couldn.t.stop.repl.process"), e, false)
processHandler.destroyProcess()
clearState()
}
}
// There should be some kind of more wise synchronization cause this method is called from non-UI thread (process handler thread)
// and actually there could be side effects in handlers
private fun clearState() {
history.clear()
osProcessHandler = null
handler.onFinish(file)
}
override fun executeStatement(expression: ScratchExpression) {
if (needProcessToStart()) {
startExecution()
}
history.addEntry(expression)
try {
sendCommandToProcess(runReadAction { expression.element.text })
} catch (e: Throwable) {
errorOccurs(KotlinJvmBundle.message("couldn.t.execute.statement.0", expression.element.text), e, true)
}
}
override fun needProcessToStart(): Boolean {
return osProcessHandler == null
}
private fun sendCommandToProcess(command: String) {
LOG.printDebugMessage("Send to REPL: $command")
val processInputOS = osProcessHandler?.processInput ?: return logError(this::class.java, "<p>Broken execute stream</p>")
val charset = osProcessHandler?.charset ?: Charsets.UTF_8
val xmlRes = command.replInputAsXml()
val bytes = ("$xmlRes\n").toByteArray(charset)
processInputOS.write(bytes)
processInputOS.flush()
}
private class ReplHistory {
private var entries = arrayListOf<ScratchExpression>()
private var processedEntriesCount: Int = 0
fun addEntry(entry: ScratchExpression) {
entries.add(entry)
}
fun lastUnprocessedEntry(): ScratchExpression? {
return entries.takeIf { processedEntriesCount < entries.size }?.get(processedEntriesCount)
}
fun lastProcessedEntry(): ScratchExpression? {
if (processedEntriesCount < 1) return null
val lastProcessedEntryIndex = processedEntriesCount - 1
return entries.takeIf { lastProcessedEntryIndex < entries.size }?.get(lastProcessedEntryIndex)
}
fun entryProcessed() {
processedEntriesCount++
}
fun clear() {
entries = arrayListOf()
processedEntriesCount = 0
}
fun isAllProcessed() = entries.size == processedEntriesCount
}
private inner class ReplOSProcessHandler(process: Process, commandLine: String) : OSProcessHandler(process, commandLine) {
private val factory = DocumentBuilderFactory.newInstance()
override fun notifyTextAvailable(text: String, outputType: Key<*>) {
if (text.startsWith("warning: classpath entry points to a non-existent location")) return
when (outputType) {
ProcessOutputTypes.STDOUT -> handleReplMessage(text)
ProcessOutputTypes.STDERR -> errorOccurs(text)
}
}
override fun notifyProcessTerminated(exitCode: Int) {
// Do state cleaning before notification otherwise KtScratchFileEditorWithPreview.dispose
// would try to stop process again (after stop in tests 'stopReplProcess`)
// via `stopExecution` (because handler is not null) with next exception:
//
// Caused by: com.intellij.testFramework.TestLogger$TestLoggerAssertionError: The pipe is being closed
// at com.intellij.testFramework.TestLogger.error(TestLogger.java:40)
// at com.intellij.openapi.diagnostic.Logger.error(Logger.java:170)
// at org.jetbrains.kotlin.idea.scratch.ScratchExecutor.errorOccurs(ScratchExecutor.kt:50)
// at org.jetbrains.kotlin.idea.scratch.repl.KtScratchReplExecutor.stopExecution(KtScratchReplExecutor.kt:61)
// at org.jetbrains.kotlin.idea.scratch.SequentialScratchExecutor.stopExecution$default(ScratchExecutor.kt:90)
clearState()
super.notifyProcessTerminated(exitCode)
}
private fun strToSource(s: String, encoding: Charset = Charsets.UTF_8) = InputSource(ByteArrayInputStream(s.toByteArray(encoding)))
private fun handleReplMessage(text: String) {
if (text.isBlank()) return
val output = try {
factory.newDocumentBuilder().parse(strToSource(text))
} catch (e: Exception) {
return handler.error(file, "Couldn't parse REPL output: $text")
}
val root = output.firstChild as Element
val outputType = root.getAttribute("type")
val content = root.textContent.replUnescapeLineBreaks().replNormalizeLineBreaks().replRemoveLineBreaksInTheEnd()
LOG.printDebugMessage("REPL output: $outputType $content")
if (outputType in setOf("SUCCESS", "COMPILE_ERROR", "INTERNAL_ERROR", "RUNTIME_ERROR", "READLINE_END")) {
history.entryProcessed()
if (history.isAllProcessed()) {
handler.onFinish(file)
}
}
val result = parseReplOutput(content, outputType)
if (result != null) {
val lastExpression = if (outputType == "USER_OUTPUT") {
// success command is printed after user output
history.lastUnprocessedEntry()
} else {
history.lastProcessedEntry()
}
if (lastExpression != null) {
handler.handle(file, lastExpression, result)
}
}
}
private fun parseReplOutput(text: String, outputType: String): ScratchOutput? = when (outputType) {
"USER_OUTPUT" -> ScratchOutput(text, ScratchOutputType.OUTPUT)
"REPL_RESULT" -> ScratchOutput(text, ScratchOutputType.RESULT)
"REPL_INCOMPLETE",
"INTERNAL_ERROR",
"COMPILE_ERROR",
"RUNTIME_ERROR",
-> ScratchOutput(text, ScratchOutputType.ERROR)
else -> null
}
}
}
| apache-2.0 | bd085ef60780c8da0b7f947e33116c78 | 40.119266 | 158 | 0.662651 | 5.013423 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/references/GrLiteralConstructorReference.kt | 10 | 8419 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.references
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.CommonClassNames.*
import com.intellij.psi.PsiClassType.ClassResolveResult
import com.intellij.psi.util.InheritanceUtil
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrSafeCastExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrClassTypeElement
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.DEFAULT_GROOVY_METHODS
import org.jetbrains.plugins.groovy.lang.psi.util.isCompileStatic
import org.jetbrains.plugins.groovy.lang.resolve.BaseGroovyResolveResult
import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments
import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument
import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyPropertyWriteReference
import org.jetbrains.plugins.groovy.lang.resolve.impl.getExpressionArguments
import org.jetbrains.plugins.groovy.lang.resolve.impl.resolveConstructor
import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.getAssignmentExpectedType
import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.getAssignmentOrReturnExpectedType
import org.jetbrains.plugins.groovy.lang.typing.box
import org.jetbrains.plugins.groovy.lang.typing.getWritePropertyType
class GrLiteralConstructorReference(element: GrListOrMap) : GrConstructorReference<GrListOrMap>(element) {
override fun getRangeInElement(): TextRange = TextRange.EMPTY_RANGE
override fun handleElementRename(newElementName: String): PsiElement = element
override fun bindToElement(element: PsiElement): PsiElement = element
override fun doResolveClass(): GroovyResolveResult? {
val literal: GrListOrMap = element
val cs = isCompileStatic(literal)
val lType: PsiClassType = getExpectedType(literal, cs) as? PsiClassType ?: return null
val resolveResult: ClassResolveResult = lType.resolveGenerics()
val clazz: PsiClass = resolveResult.element ?: return null
val fallsBackToConstructor = if (cs) {
fallsBackToConstructorCS(clazz, literal)
}
else {
fallsBackToConstructor(clazz, literal)
}
if (fallsBackToConstructor) {
return BaseGroovyResolveResult(clazz, literal, substitutor = resolveResult.substitutor)
}
else {
return null
}
}
override val arguments: Arguments? get() = getArguments(element)
override val supportsEnclosingInstance: Boolean get() = false
}
private fun getExpectedType(literal: GrListOrMap, cs: Boolean): PsiType? {
return getExpectedTypeFromAssignmentOrReturn(literal, cs)
?: getExpectedTypeFromNamedArgument(literal)
?: getExpectedTypeFromCoercion(literal)
}
/**
* @see org.codehaus.groovy.transform.stc.StaticTypeCheckingVisitor.addListAssignmentConstructorErrors
*/
private fun getExpectedTypeFromAssignmentOrReturn(literal: GrListOrMap, cs: Boolean): PsiType? {
return if (cs) {
val type: PsiType? = getAssignmentExpectedType(literal)
when {
literal.isMap || !literal.isEmpty -> type?.box(literal)
type is PsiClassType && type.resolve()?.isInterface == true -> null
else -> type
}
}
else {
getAssignmentOrReturnExpectedType(literal)
}
}
private fun getExpectedTypeFromNamedArgument(literal: GrListOrMap): PsiType? {
val namedArgument: GrNamedArgument = literal.parent as? GrNamedArgument ?: return null
val label: GrArgumentLabel = namedArgument.label ?: return null
val propertyReference: GroovyPropertyWriteReference = label.constructorPropertyReference ?: return null
return getWritePropertyType(propertyReference.advancedResolve())
}
private fun getExpectedTypeFromCoercion(literal: GrListOrMap): PsiType? {
val safeCast: GrSafeCastExpression = literal.parent as? GrSafeCastExpression ?: return null
if (!resolvesToDGM(safeCast)) {
return null
}
val typeElement: GrClassTypeElement = safeCast.castTypeElement as? GrClassTypeElement ?: return null
val typeResult: GroovyResolveResult = typeElement.referenceElement.resolve(false).singleOrNull() ?: return null
if (safeCastFallsBackToCast(literal, typeResult)) {
return typeElement.type
}
else {
return null
}
}
private fun resolvesToDGM(safeCast: GrSafeCastExpression): Boolean {
val method = safeCast.reference.resolve() as? PsiMethod ?: return false
val containingClass = (method as? GrGdkMethod)?.staticMethod?.containingClass
return containingClass?.qualifiedName == DEFAULT_GROOVY_METHODS
}
/**
* @return `true` if [org.codehaus.groovy.runtime.DefaultGroovyMethods.asType]
* will fall back to [org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType]
* inside `[] as X` or `[:] as X` expression, otherwise `false`
*/
private fun safeCastFallsBackToCast(literal: GrListOrMap, classResult: GroovyResolveResult): Boolean {
val clazz: PsiClass = classResult.element as? PsiClass ?: return false
if (literal.isMap) {
return !clazz.isInterface
}
if (clazz.qualifiedName in ignoredFqnsInSafeCast) {
return false
}
// new X(literal)
val constructors = resolveConstructor(clazz, PsiSubstitutor.EMPTY, listOf(ExpressionArgument(literal)), literal)
if (constructors.isNotEmpty() && constructors.all { it.isApplicable }) {
return false
}
if (InheritanceUtil.isInheritor(clazz, JAVA_UTIL_COLLECTION)) {
// def x = new X()
// x.addAll(literal)
val noArgConstructors = resolveConstructor(clazz, PsiSubstitutor.EMPTY, emptyList(), literal)
if (noArgConstructors.isNotEmpty() && noArgConstructors.all { it.isApplicable }) {
return false
}
}
return true
}
/**
* FQNs skipped in [org.codehaus.groovy.runtime.DefaultGroovyMethods.asType] for [Collection]
*/
private val ignoredFqnsInSafeCast = setOf(
JAVA_UTIL_LIST,
JAVA_UTIL_SET,
JAVA_UTIL_SORTED_SET,
JAVA_UTIL_QUEUE,
JAVA_UTIL_STACK,
JAVA_UTIL_LINKED_LIST,
JAVA_LANG_STRING
)
private fun fallsBackToConstructorCS(clazz: PsiClass, literal: GrListOrMap): Boolean {
if (clazz.qualifiedName == JAVA_LANG_CLASS) {
return false
}
val literalClass = (literal.type as? PsiClassType)?.resolve()
return !InheritanceUtil.isInheritorOrSelf(literalClass, clazz, true)
}
/**
* @return `true` if [org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType]
* will fall back to [org.codehaus.groovy.runtime.InvokerHelper.invokeConstructorOf], otherwise `false`
*/
private fun fallsBackToConstructor(clazz: PsiClass, literal: GrListOrMap): Boolean {
if (clazz.isEnum) {
return false
}
val qualifiedName = clazz.qualifiedName ?: return false
if (qualifiedName in ignoredFqnsInTransformation) {
return false
}
if (InheritanceUtil.isInheritor(clazz, JAVA_LANG_NUMBER)) {
return false
}
val literalClass = (literal.type as? PsiClassType)?.resolve()
if (InheritanceUtil.isInheritorOrSelf(literalClass, clazz, true)) {
return false
}
if (!literal.isMap) {
if (qualifiedName == JAVA_UTIL_LINKED_HASH_SET) {
return false
}
if (clazz.hasModifier(JvmModifier.ABSTRACT)) {
val lhs = JavaPsiFacade.getInstance(literal.project).findClass(JAVA_UTIL_LINKED_HASH_SET, literal.resolveScope)
if (InheritanceUtil.isInheritor(lhs, qualifiedName)) {
return false
}
}
}
return true
}
/**
* FQNs skipped in [org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType]
*/
private val ignoredFqnsInTransformation = setOf(
JAVA_LANG_OBJECT,
JAVA_LANG_CLASS,
JAVA_LANG_STRING,
JAVA_LANG_BOOLEAN,
JAVA_LANG_CHARACTER
)
private fun getArguments(literal: GrListOrMap): Arguments? {
if (literal.isMap) {
return listOf(ExpressionArgument(literal))
}
else {
return getExpressionArguments(literal.initializers)
}
}
| apache-2.0 | 44f06deca53630ae33c5c53d01b40670 | 37.797235 | 140 | 0.770519 | 4.301993 | false | false | false | false |
jotomo/AndroidAPS | core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt | 1 | 6044 | package info.nightscout.androidaps.plugins.general.maintenance.activities
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import dagger.android.support.DaggerAppCompatActivity
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.core.databinding.MaintenanceImportListActivityBinding
import info.nightscout.androidaps.core.databinding.MaintenanceImportListItemBinding
import info.nightscout.androidaps.plugins.general.maintenance.PrefFileListProvider
import info.nightscout.androidaps.plugins.general.maintenance.PrefsFile
import info.nightscout.androidaps.plugins.general.maintenance.PrefsFileContract
import info.nightscout.androidaps.plugins.general.maintenance.PrefsFormatsHandler
import info.nightscout.androidaps.plugins.general.maintenance.formats.PrefsMetadataKey
import info.nightscout.androidaps.plugins.general.maintenance.formats.PrefsStatus
import info.nightscout.androidaps.utils.extensions.toVisibility
import info.nightscout.androidaps.utils.locale.LocaleHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper
import javax.inject.Inject
class PrefImportListActivity : DaggerAppCompatActivity() {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var prefFileListProvider: PrefFileListProvider
private lateinit var binding: MaintenanceImportListActivityBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTheme(R.style.AppTheme)
binding = MaintenanceImportListActivityBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
title = resourceHelper.gs(R.string.preferences_import_list_title)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.setDisplayShowTitleEnabled(true)
binding.recyclerview.layoutManager = LinearLayoutManager(this)
binding.recyclerview.adapter = RecyclerViewAdapter(prefFileListProvider.listPreferenceFiles(loadMetadata = true))
}
inner class RecyclerViewAdapter internal constructor(private var prefFileList: List<PrefsFile>) : RecyclerView.Adapter<RecyclerViewAdapter.PrefFileViewHolder>() {
inner class PrefFileViewHolder(val maintenanceImportListItemBinding: MaintenanceImportListItemBinding) : RecyclerView.ViewHolder(maintenanceImportListItemBinding.root) {
init {
with(maintenanceImportListItemBinding) {
root.isClickable = true
maintenanceImportListItemBinding.root.setOnClickListener {
val prefFile = filelistName.tag as PrefsFile
val i = Intent()
i.putExtra(PrefsFileContract.OUTPUT_PARAM, prefFile)
setResult(FragmentActivity.RESULT_OK, i)
finish()
}
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PrefFileViewHolder {
val binding = MaintenanceImportListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return PrefFileViewHolder(binding)
}
override fun getItemCount(): Int {
return prefFileList.size
}
override fun onBindViewHolder(holder: PrefFileViewHolder, position: Int) {
val prefFile = prefFileList[position]
with(holder.maintenanceImportListItemBinding) {
filelistName.text = prefFile.file.name
filelistName.tag = prefFile
filelistDir.text = resourceHelper.gs(R.string.in_directory, prefFile.file.parentFile.absolutePath)
val visible = (prefFile.handler != PrefsFormatsHandler.CLASSIC).toVisibility()
metalineName.visibility = visible
metaDateTimeIcon.visibility = visible
metaAppVersion.visibility = visible
if (prefFile.handler == PrefsFormatsHandler.CLASSIC) {
metaVariantFormat.text = resourceHelper.gs(R.string.metadata_format_old)
metaVariantFormat.setTextColor(resourceHelper.gc(R.color.metadataTextWarning))
metaDateTime.text = " "
} else {
prefFile.metadata[PrefsMetadataKey.AAPS_FLAVOUR]?.let {
metaVariantFormat.text = it.value
val color = if (it.status == PrefsStatus.OK) R.color.metadataOk else R.color.metadataTextWarning
metaVariantFormat.setTextColor(resourceHelper.gc(color))
}
prefFile.metadata[PrefsMetadataKey.CREATED_AT]?.let {
metaDateTime.text = prefFileListProvider.formatExportedAgo(it.value)
}
prefFile.metadata[PrefsMetadataKey.AAPS_VERSION]?.let {
metaAppVersion.text = it.value
val color = if (it.status == PrefsStatus.OK) R.color.metadataOk else R.color.metadataTextWarning
metaAppVersion.setTextColor(resourceHelper.gc(color))
}
prefFile.metadata[PrefsMetadataKey.DEVICE_NAME]?.let {
metaDeviceName.text = it.value
}
}
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return false
}
public override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(LocaleHelper.wrap(newBase))
}
} | agpl-3.0 | 4b8b59577883a948758172ed527f0a4b | 44.451128 | 177 | 0.686466 | 5.454874 | false | false | false | false |
dev-cloverlab/Kloveroid | app/src/main/kotlin/com/cloverlab/kloveroid/feature/main/MainFragment.kt | 1 | 1870 | package com.cloverlab.kloveroid.feature.main
import android.os.Bundle
import com.cloverlab.kloveroid.R
import com.cloverlab.kloveroid.feature.base.MvpFragment
import com.cloverlab.kloveroid.mvp.contracts.MainContract.Presenter
import com.cloverlab.kloveroid.mvp.contracts.MainContract.View
import dagger.internal.Preconditions
import kotlinx.android.synthetic.main.fragment_main.tv_show
import javax.inject.Inject
/**
* @author Jieyi Wu
* @since 2017/09/25
*/
class MainFragment : MvpFragment<View, Presenter>(), View {
companion object Factory {
// The key name of the fragment initialization parameters.
private val ARG_PARAM_: String = "param_"
/**
* Use this factory method to create a new instance of this fragment using the provided parameters.
*
* @return A new instance of fragment BlankFragment.
*/
fun newInstance(arg1: String) = MainFragment().apply {
arguments = bundleOf(arrayOf<Pair<String, Any?>>(ARG_PARAM_ to arg1))
}
}
@Inject override lateinit var presenter: Presenter
// The fragment initialization parameters.
private val arg1 by lazy { arguments?.getString(ARG_PARAM_).orEmpty() }
//endregion
//region Base fragment
override fun init(savedInstanceState: Bundle?) {
// btn_test.setOnClickListener { RxBus.get().post("test") }
tv_show.text = "Hello World!!"
}
override fun provideInflateView() = R.layout.fragment_main
override fun provideCurrentFragmentView() = this
//endregion
//region Presenter implements
override fun showLoading() {
}
override fun hideLoading() {
}
override fun showRetry() {
}
override fun hideRetry() {
}
override fun showError(message: String) {
Preconditions.checkNotNull(message)
}
//endregion
}
| mit | 17ad39bfc06037fa0476fc9d6f78068e | 27.769231 | 107 | 0.684492 | 4.495192 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/UselessCallOnCollectionInspection.kt | 1 | 5243 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.collections
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.quickfix.ReplaceSelectorOfQualifiedExpressionFix
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.calls.inference.model.TypeVariableTypeConstructor
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isFlexible
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
class UselessCallOnCollectionInspection : AbstractUselessCallInspection() {
override val uselessFqNames = mapOf(
"kotlin.collections.filterNotNull" to deleteConversion,
"kotlin.sequences.filterNotNull" to deleteConversion,
"kotlin.collections.filterIsInstance" to deleteConversion,
"kotlin.sequences.filterIsInstance" to deleteConversion,
"kotlin.collections.mapNotNull" to Conversion("map"),
"kotlin.sequences.mapNotNull" to Conversion("map"),
"kotlin.collections.mapNotNullTo" to Conversion("mapTo"),
"kotlin.sequences.mapNotNullTo" to Conversion("mapTo"),
"kotlin.collections.mapIndexedNotNull" to Conversion("mapIndexed"),
"kotlin.sequences.mapIndexedNotNull" to Conversion("mapIndexed"),
"kotlin.collections.mapIndexedNotNullTo" to Conversion("mapIndexedTo"),
"kotlin.sequences.mapIndexedNotNullTo" to Conversion("mapIndexedTo")
)
override val uselessNames = uselessFqNames.keys.toShortNames()
override fun QualifiedExpressionVisitor.suggestConversionIfNeeded(
expression: KtQualifiedExpression,
calleeExpression: KtExpression,
context: BindingContext,
conversion: Conversion
) {
val receiverType = expression.receiverExpression.getType(context) ?: return
val receiverTypeArgument = receiverType.arguments.singleOrNull()?.type ?: return
val resolvedCall = expression.getResolvedCall(context) ?: return
if (calleeExpression.text == "filterIsInstance") {
val typeParameterDescriptor = resolvedCall.candidateDescriptor.typeParameters.singleOrNull() ?: return
val argumentType = resolvedCall.typeArguments[typeParameterDescriptor] ?: return
if (receiverTypeArgument.isFlexible() || !receiverTypeArgument.isSubtypeOf(argumentType)) return
} else {
// xxxNotNull
if (TypeUtils.isNullableType(receiverTypeArgument)) return
if (calleeExpression.text != "filterNotNull") {
// Also check last argument functional type to have not-null result
val lastParameterMatches = resolvedCall.hasLastFunctionalParameterWithResult(context) {
!TypeUtils.isNullableType(it) && it.constructor !is TypeVariableTypeConstructor
}
if (!lastParameterMatches) return
}
}
val newName = conversion.replacementName
if (newName != null) {
val descriptor = holder.manager.createProblemDescriptor(
expression,
TextRange(
expression.operationTokenNode.startOffset - expression.startOffset,
calleeExpression.endOffset - expression.startOffset
),
KotlinBundle.message("call.on.collection.type.may.be.reduced"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly,
RenameUselessCallFix(newName)
)
holder.registerProblem(descriptor)
} else {
val fix = if (resolvedCall.resultingDescriptor.returnType.isList() && !receiverType.isList()) {
ReplaceSelectorOfQualifiedExpressionFix("toList()")
} else {
RemoveUselessCallFix()
}
val descriptor = holder.manager.createProblemDescriptor(
expression,
TextRange(
expression.operationTokenNode.startOffset - expression.startOffset,
calleeExpression.endOffset - expression.startOffset
),
KotlinBundle.message("useless.call.on.collection.type"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
isOnTheFly,
fix
)
holder.registerProblem(descriptor)
}
}
private fun KotlinType?.isList() = this?.constructor?.declarationDescriptor?.fqNameSafe == StandardNames.FqNames.list
}
| apache-2.0 | 2395f189ef4eced6d919ca5781c4d56b | 49.902913 | 158 | 0.69979 | 5.565817 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/cloneableProjects/CloneableProjectsService.kt | 2 | 7227 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl.welcomeScreen.cloneableProjects
import com.intellij.CommonBundle
import com.intellij.ide.RecentProjectMetaInfo
import com.intellij.ide.RecentProjectsManager
import com.intellij.ide.RecentProjectsManagerBase
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.components.Service.Level
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.TaskInfo
import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.wm.ex.ProgressIndicatorEx
import com.intellij.openapi.wm.impl.welcomeScreen.recentProjects.CloneableProjectItem
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.messages.Topic
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.SystemIndependent
import java.util.*
@Service(Level.APP)
class CloneableProjectsService {
private val cloneableProjects: MutableSet<CloneableProject> = Collections.synchronizedSet(mutableSetOf())
@RequiresEdt
fun runCloneTask(projectPath: @SystemIndependent String, cloneTask: CloneTask) {
val taskInfo = cloneTask.taskInfo()
val progressIndicator = CloneableProjectProgressIndicator(taskInfo)
val cloneableProject = CloneableProject(projectPath, taskInfo, progressIndicator, CloneStatus.PROGRESS)
addCloneableProject(cloneableProject)
ApplicationManager.getApplication().executeOnPooledThread {
ProgressManager.getInstance().runProcess(Runnable {
val activity = VcsCloneCollector.cloneStarted()
val cloneStatus: CloneStatus = try {
cloneTask.run(progressIndicator)
}
catch (_: ProcessCanceledException) {
CloneStatus.CANCEL
}
catch (exception: Throwable) {
logger<CloneableProjectsService>().error(exception)
CloneStatus.FAILURE
}
VcsCloneCollector.cloneFinished(activity, cloneStatus)
when (cloneStatus) {
CloneStatus.SUCCESS -> onSuccess(cloneableProject)
CloneStatus.FAILURE -> onFailure(cloneableProject)
CloneStatus.CANCEL -> onCancel(cloneableProject)
else -> {}
}
}, progressIndicator)
}
}
internal fun collectCloneableProjects(): List<CloneableProjectItem> {
val recentProjectManager = RecentProjectsManager.getInstance() as RecentProjectsManagerBase
return cloneableProjects.map { cloneableProject ->
val projectPath = cloneableProject.projectPath
val projectName = recentProjectManager.getProjectName(projectPath)
val displayName = recentProjectManager.getDisplayName(projectPath) ?: projectName
CloneableProjectItem(projectPath, projectName, displayName, cloneableProject)
}
}
fun cloneCount(): Int {
return cloneableProjects.size
}
fun isCloneActive(): Boolean {
return !cloneableProjects.isEmpty()
}
fun cancelClone(cloneableProject: CloneableProject) {
cloneableProject.progressIndicator.cancel()
}
fun removeCloneableProject(cloneableProject: CloneableProject) {
if (cloneableProject.cloneStatus == CloneStatus.PROGRESS) {
cloneableProject.progressIndicator.cancel()
}
cloneableProjects.removeIf { it.projectPath == cloneableProject.projectPath }
fireCloneRemovedEvent()
}
private fun upgradeCloneProjectToRecent(cloneableProject: CloneableProject) {
val recentProjectsManager = RecentProjectsManager.getInstance() as RecentProjectsManagerBase
recentProjectsManager.addRecentPath(cloneableProject.projectPath, RecentProjectMetaInfo())
removeCloneableProject(cloneableProject)
}
private fun addCloneableProject(cloneableProject: CloneableProject) {
cloneableProjects.removeIf { it.projectPath == cloneableProject.projectPath }
cloneableProjects.add(cloneableProject)
fireCloneAddedEvent(cloneableProject)
}
private fun onSuccess(cloneableProject: CloneableProject) {
cloneableProject.cloneStatus = CloneStatus.SUCCESS
upgradeCloneProjectToRecent(cloneableProject)
fireCloneSuccessEvent()
}
private fun onFailure(cloneableProject: CloneableProject) {
cloneableProject.cloneStatus = CloneStatus.FAILURE
fireCloneFailedEvent()
}
private fun onCancel(cloneableProject: CloneableProject) {
cloneableProject.cloneStatus = CloneStatus.CANCEL
fireCloneCanceledEvent()
}
private fun fireCloneAddedEvent(cloneableProject: CloneableProject) {
ApplicationManager.getApplication().messageBus
.syncPublisher(TOPIC)
.onCloneAdded(cloneableProject.progressIndicator, cloneableProject.cloneTaskInfo)
}
private fun fireCloneRemovedEvent() {
ApplicationManager.getApplication().messageBus
.syncPublisher(TOPIC)
.onCloneRemoved()
}
private fun fireCloneSuccessEvent() {
ApplicationManager.getApplication().messageBus
.syncPublisher(TOPIC)
.onCloneSuccess()
}
private fun fireCloneFailedEvent() {
ApplicationManager.getApplication().messageBus
.syncPublisher(TOPIC)
.onCloneFailed()
}
private fun fireCloneCanceledEvent() {
ApplicationManager.getApplication().messageBus
.syncPublisher(TOPIC)
.onCloneCanceled()
}
enum class CloneStatus {
SUCCESS,
PROGRESS,
FAILURE,
CANCEL
}
class CloneTaskInfo(
@NlsContexts.ProgressTitle private val title: String,
@Nls private val cancelTooltipText: String,
@Nls val actionTitle: String,
@Nls val actionTooltipText: String,
@Nls val failedTitle: String,
@Nls val canceledTitle: String,
@Nls val stopTitle: String,
@Nls val stopDescription: String
) : TaskInfo {
override fun getTitle(): String = title
override fun getCancelText(): String = CommonBundle.getCancelButtonText()
override fun getCancelTooltipText(): String = cancelTooltipText
override fun isCancellable(): Boolean = true
}
data class CloneableProject(
val projectPath: @SystemIndependent String,
val cloneTaskInfo: CloneTaskInfo,
val progressIndicator: ProgressIndicatorEx,
var cloneStatus: CloneStatus
)
private class CloneableProjectProgressIndicator(cloneTaskInfo: CloneTaskInfo) : AbstractProgressIndicatorExBase() {
init {
setOwnerTask(cloneTaskInfo)
}
}
interface CloneTask {
fun taskInfo(): CloneTaskInfo
fun run(indicator: ProgressIndicator): CloneStatus
}
interface CloneProjectListener {
fun onCloneAdded(progressIndicator: ProgressIndicatorEx, taskInfo: TaskInfo) {
}
fun onCloneRemoved() {
}
fun onCloneSuccess() {
}
fun onCloneFailed() {
}
fun onCloneCanceled() {
}
}
companion object {
@JvmField
val TOPIC = Topic(CloneProjectListener::class.java)
@JvmStatic
fun getInstance() = service<CloneableProjectsService>()
}
} | apache-2.0 | 946840504cdfcbaa105e4056c6131d3c | 32.004566 | 120 | 0.760343 | 4.953393 | false | false | false | false |
SimpleMobileTools/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/adapters/MyRecyclerViewListAdapter.kt | 1 | 12748 | package com.simplemobiletools.commons.adapters
import android.graphics.Color
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.ActionBar
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.interfaces.MyActionModeCallback
import com.simplemobiletools.commons.models.RecyclerSelectionPayload
import com.simplemobiletools.commons.views.MyRecyclerView
import kotlin.math.max
import kotlin.math.min
abstract class MyRecyclerViewListAdapter<T>(
val activity: BaseSimpleActivity,
val recyclerView: MyRecyclerView,
diffUtil: DiffUtil.ItemCallback<T>,
val itemClick: (T) -> Unit,
val onRefresh: () -> Unit = {}
) : ListAdapter<T, MyRecyclerViewListAdapter<T>.ViewHolder>(diffUtil) {
protected val baseConfig = activity.baseConfig
protected val resources = activity.resources!!
protected val layoutInflater = activity.layoutInflater
protected var textColor = activity.getProperTextColor()
protected var backgroundColor = activity.getProperBackgroundColor()
protected var properPrimaryColor = activity.getProperPrimaryColor()
protected var contrastColor = properPrimaryColor.getContrastColor()
protected var actModeCallback: MyActionModeCallback
protected var selectedKeys = LinkedHashSet<Int>()
protected var positionOffset = 0
protected var actMode: ActionMode? = null
private var actBarTextView: TextView? = null
private var lastLongPressedItem = -1
abstract fun getActionMenuId(): Int
abstract fun prepareActionMode(menu: Menu)
abstract fun actionItemPressed(id: Int)
abstract fun getSelectableItemCount(): Int
abstract fun getIsItemSelectable(position: Int): Boolean
abstract fun getItemSelectionKey(position: Int): Int?
abstract fun getItemKeyPosition(key: Int): Int
abstract fun onActionModeCreated()
abstract fun onActionModeDestroyed()
protected fun isOneItemSelected() = selectedKeys.size == 1
init {
actModeCallback = object : MyActionModeCallback() {
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
actionItemPressed(item.itemId)
return true
}
override fun onCreateActionMode(actionMode: ActionMode, menu: Menu?): Boolean {
if (getActionMenuId() == 0) {
return true
}
isSelectable = true
actMode = actionMode
actBarTextView = layoutInflater.inflate(R.layout.actionbar_title, null) as TextView
actBarTextView!!.layoutParams = ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
actMode!!.customView = actBarTextView
actBarTextView!!.setOnClickListener {
if (getSelectableItemCount() == selectedKeys.size) {
finishActMode()
} else {
selectAll()
}
}
activity.menuInflater.inflate(getActionMenuId(), menu)
val bgColor = if (baseConfig.isUsingSystemTheme) {
ResourcesCompat.getColor(resources, R.color.you_contextual_status_bar_color, activity.theme)
} else {
Color.BLACK
}
actBarTextView!!.setTextColor(bgColor.getContrastColor())
activity.updateMenuItemColors(menu, baseColor = bgColor)
onActionModeCreated()
if (baseConfig.isUsingSystemTheme) {
actBarTextView?.onGlobalLayout {
val backArrow = activity.findViewById<ImageView>(R.id.action_mode_close_button)
backArrow?.applyColorFilter(bgColor.getContrastColor())
}
}
return true
}
override fun onPrepareActionMode(actionMode: ActionMode, menu: Menu): Boolean {
prepareActionMode(menu)
return true
}
override fun onDestroyActionMode(actionMode: ActionMode) {
isSelectable = false
(selectedKeys.clone() as HashSet<Int>).forEach {
val position = getItemKeyPosition(it)
if (position != -1) {
toggleItemSelection(false, position, false)
}
}
updateTitle()
selectedKeys.clear()
actBarTextView?.text = ""
actMode = null
lastLongPressedItem = -1
onActionModeDestroyed()
}
}
}
protected fun toggleItemSelection(select: Boolean, pos: Int, updateTitle: Boolean = true) {
if (select && !getIsItemSelectable(pos)) {
return
}
val itemKey = getItemSelectionKey(pos) ?: return
if ((select && selectedKeys.contains(itemKey)) || (!select && !selectedKeys.contains(itemKey))) {
return
}
if (select) {
selectedKeys.add(itemKey)
} else {
selectedKeys.remove(itemKey)
}
notifyItemChanged(pos + positionOffset, RecyclerSelectionPayload(select))
if (updateTitle) {
updateTitle()
}
if (selectedKeys.isEmpty()) {
finishActMode()
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: MutableList<Any>) {
val any = payloads.firstOrNull()
if (any is RecyclerSelectionPayload) {
holder.itemView.isSelected = any.selected
} else {
onBindViewHolder(holder, position)
}
}
private fun updateTitle() {
val selectableItemCount = getSelectableItemCount()
val selectedCount = min(selectedKeys.size, selectableItemCount)
val oldTitle = actBarTextView?.text
val newTitle = "$selectedCount / $selectableItemCount"
if (oldTitle != newTitle) {
actBarTextView?.text = newTitle
actMode?.invalidate()
}
}
fun itemLongClicked(position: Int) {
recyclerView.setDragSelectActive(position)
lastLongPressedItem = if (lastLongPressedItem == -1) {
position
} else {
val min = min(lastLongPressedItem, position)
val max = max(lastLongPressedItem, position)
for (i in min..max) {
toggleItemSelection(true, i, false)
}
updateTitle()
position
}
}
protected fun getSelectedItemPositions(sortDescending: Boolean = true): ArrayList<Int> {
val positions = ArrayList<Int>()
val keys = selectedKeys.toList()
keys.forEach {
val position = getItemKeyPosition(it)
if (position != -1) {
positions.add(position)
}
}
if (sortDescending) {
positions.sortDescending()
}
return positions
}
protected fun selectAll() {
val cnt = itemCount - positionOffset
for (i in 0 until cnt) {
toggleItemSelection(true, i, false)
}
lastLongPressedItem = -1
updateTitle()
}
protected fun setupDragListener(enable: Boolean) {
if (enable) {
recyclerView.setupDragListener(object : MyRecyclerView.MyDragListener {
override fun selectItem(position: Int) {
toggleItemSelection(true, position, true)
}
override fun selectRange(initialSelection: Int, lastDraggedIndex: Int, minReached: Int, maxReached: Int) {
selectItemRange(
initialSelection,
max(0, lastDraggedIndex - positionOffset),
max(0, minReached - positionOffset),
maxReached - positionOffset
)
if (minReached != maxReached) {
lastLongPressedItem = -1
}
}
})
} else {
recyclerView.setupDragListener(null)
}
}
protected fun selectItemRange(from: Int, to: Int, min: Int, max: Int) {
if (from == to) {
(min..max).filter { it != from }.forEach { toggleItemSelection(false, it, true) }
return
}
if (to < from) {
for (i in to..from) {
toggleItemSelection(true, i, true)
}
if (min > -1 && min < to) {
(min until to).filter { it != from }.forEach { toggleItemSelection(false, it, true) }
}
if (max > -1) {
for (i in from + 1..max) {
toggleItemSelection(false, i, true)
}
}
} else {
for (i in from..to) {
toggleItemSelection(true, i, true)
}
if (max > -1 && max > to) {
(to + 1..max).filter { it != from }.forEach { toggleItemSelection(false, it, true) }
}
if (min > -1) {
for (i in min until from) {
toggleItemSelection(false, i, true)
}
}
}
}
fun setupZoomListener(zoomListener: MyRecyclerView.MyZoomListener?) {
recyclerView.setupZoomListener(zoomListener)
}
fun addVerticalDividers(add: Boolean) {
if (recyclerView.itemDecorationCount > 0) {
recyclerView.removeItemDecorationAt(0)
}
if (add) {
DividerItemDecoration(activity, DividerItemDecoration.VERTICAL).apply {
setDrawable(resources.getDrawable(R.drawable.divider))
recyclerView.addItemDecoration(this)
}
}
}
fun finishActMode() {
actMode?.finish()
}
fun updateTextColor(textColor: Int) {
this.textColor = textColor
onRefresh.invoke()
}
fun updatePrimaryColor() {
properPrimaryColor = activity.getProperPrimaryColor()
contrastColor = properPrimaryColor.getContrastColor()
}
fun updateBackgroundColor(backgroundColor: Int) {
this.backgroundColor = backgroundColor
}
protected fun createViewHolder(layoutType: Int, parent: ViewGroup?): ViewHolder {
val view = layoutInflater.inflate(layoutType, parent, false)
return ViewHolder(view)
}
protected fun bindViewHolder(holder: ViewHolder) {
holder.itemView.tag = holder
}
protected fun removeSelectedItems(positions: ArrayList<Int>) {
positions.forEach {
notifyItemRemoved(it)
}
finishActMode()
}
open inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bindView(item: T, allowSingleClick: Boolean, allowLongClick: Boolean, callback: (itemView: View, adapterPosition: Int) -> Unit): View {
return itemView.apply {
callback(this, adapterPosition)
if (allowSingleClick) {
setOnClickListener { viewClicked(item) }
setOnLongClickListener { if (allowLongClick) viewLongClicked() else viewClicked(item); true }
} else {
setOnClickListener(null)
setOnLongClickListener(null)
}
}
}
fun viewClicked(any: T) {
if (actModeCallback.isSelectable) {
val currentPosition = adapterPosition - positionOffset
val isSelected = selectedKeys.contains(getItemSelectionKey(currentPosition))
toggleItemSelection(!isSelected, currentPosition, true)
} else {
itemClick.invoke(any)
}
lastLongPressedItem = -1
}
fun viewLongClicked() {
val currentPosition = adapterPosition - positionOffset
if (!actModeCallback.isSelectable) {
activity.startActionMode(actModeCallback)
}
toggleItemSelection(true, currentPosition, true)
itemLongClicked(currentPosition)
}
}
}
| gpl-3.0 | 734c8faf2598fe59999f19161db3d460 | 33.735695 | 147 | 0.588877 | 5.630742 | false | false | false | false |
androidx/androidx | inspection/inspection-gradle-plugin/src/main/kotlin/androidx/inspection/gradle/GenerateProguardDetectionFileTask.kt | 3 | 4529 | /*
* 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.inspection.gradle
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
import org.gradle.work.DisableCachingByDefault
import java.io.File
/**
* Task purposely empty, unused class that would be removed by proguard. See javadoc below for more
* information.
*/
@Suppress("UnstableApiUsage")
@DisableCachingByDefault(because = "Simply generates a small file and doesn't benefit from caching")
abstract class GenerateProguardDetectionFileTask : DefaultTask() {
@get:Input
abstract val mavenGroup: Property<String>
@get:Input
abstract val mavenArtifactId: Property<String>
@get:OutputDirectory
abstract val outputDir: DirectoryProperty
@TaskAction
fun generateProguardDetectionFile() {
val packageName = generatePackageName(mavenGroup.get(), mavenArtifactId.get())
val path = packageName.replace('.', '/')
val dir = File(outputDir.get().asFile, path)
if (!dir.exists() && !dir.mkdirs()) {
throw GradleException("Failed to create directory $dir")
}
val file = File(dir, "ProguardDetection.kt")
logger.debug("Generating ProguardDetection in $dir")
val text = """
package $packageName;
/**
* Purposely empty, unused class that would be removed by proguard.
*
* We use this class to detect if a target app was proguarded or not, because if it was,
* it likely means we can't reliably inspect it, since library's methods used only by
* an inspector would get removed. Instead, we'll need to tell users that app
* inspection isn't available for the current app and that they should rebuild it
* again without proguarding to continue.
*/
private class ProguardDetection {}
""".trimIndent()
file.writeText(text)
}
}
@ExperimentalStdlibApi
@Suppress("DEPRECATION") // BaseVariant
fun Project.registerGenerateProguardDetectionFileTask(
variant: com.android.build.gradle.api.BaseVariant
) {
val outputDir = taskWorkingDir(variant, "generateProguardDetection")
val taskName = variant.taskName("generateProguardDetection")
val mavenGroup = project.group as? String
?: throw GradleException("MavenGroup must be specified")
val mavenArtifactId = project.name
val task = tasks.register(taskName, GenerateProguardDetectionFileTask::class.java) {
it.outputDir.set(outputDir)
it.mavenGroup.set(mavenGroup)
it.mavenArtifactId.set(mavenArtifactId)
}
variant.registerJavaGeneratingTask(task, outputDir)
}
/**
* Produces package name for `ProguardDetection` class, e.g for following params:
* mavenGroup: androidx.work, mavenArtifact: work-runtime, result will be:
* androidx.inspection.work.runtime.
*
* The file is specifically generated in package androidx.inspection, so keep rules like
* "androidx.work.*" won't keep this file, because keeping library itself is not enough.
* Inspectors could use API dependencies of the inspected library, so if those API
* dependencies are renamed / minified that can break an inspector.
*/
internal fun generatePackageName(mavenGroup: String, mavenArtifact: String): String {
val strippedArtifact = mavenArtifact.removePrefix(mavenGroup.split('.').last())
.removePrefix("-").replace('-', '.')
val group = mavenGroup.removePrefix("androidx.")
// It's possible for strippedArtifact to be empty, e.g. "compose.ui/ui" has no hyphen
return "androidx.inspection.$group" +
if (strippedArtifact.isNotEmpty()) ".$strippedArtifact" else ""
}
| apache-2.0 | c593c9bf3fa56e81517f8ba49a8a5153 | 39.801802 | 100 | 0.712961 | 4.551759 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/utils/src/org/jetbrains/kotlin/idea/codeinsight/utils/EditorUtils.kt | 5 | 903 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeinsight.utils
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.psi.PsiElement
fun PsiElement.findExistingEditor(): Editor? {
ApplicationManager.getApplication().assertReadAccessAllowed()
val containingFile = containingFile
if (!containingFile.isValid) return null
val file = containingFile?.virtualFile ?: return null
val document = FileDocumentManager.getInstance().getDocument(file) ?: return null
val editorFactory = EditorFactory.getInstance()
val editors = editorFactory.getEditors(document)
return editors.firstOrNull()
} | apache-2.0 | 6f2d81f9f0f6a1adaf81fa40907b094f | 40.090909 | 120 | 0.799557 | 5.016667 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/ui/branch/GitBranchesTreePopup.kt | 1 | 24918 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.ui.branch
import com.intellij.dvcs.branch.DvcsBranchManager
import com.intellij.dvcs.branch.GroupingKey
import com.intellij.dvcs.ui.DvcsBundle
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.service
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.*
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.WindowStateService
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.*
import com.intellij.ui.popup.NextStepHandler
import com.intellij.ui.popup.PopupFactoryImpl
import com.intellij.ui.popup.WizardPopup
import com.intellij.ui.popup.util.PopupImplUtil
import com.intellij.ui.render.RenderingUtil
import com.intellij.ui.scale.JBUIScale
import com.intellij.ui.speedSearch.SpeedSearchUtil
import com.intellij.ui.tree.ui.Control
import com.intellij.ui.tree.ui.DefaultControl
import com.intellij.ui.tree.ui.DefaultTreeUI
import com.intellij.ui.treeStructure.Tree
import com.intellij.util.text.nullize
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.tree.TreeUtil
import git4idea.GitBranch
import git4idea.actions.branch.GitBranchActionsUtil
import git4idea.branch.GitBranchType
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryChangeListener
import git4idea.repo.GitRepositoryManager
import git4idea.ui.branch.GitBranchesTreePopupStep.Companion.SPEED_SEARCH_DEFAULT_ACTIONS_GROUP
import git4idea.ui.branch.GitBranchesTreeUtil.overrideBuiltInAction
import git4idea.ui.branch.GitBranchesTreeUtil.selectFirstLeaf
import git4idea.ui.branch.GitBranchesTreeUtil.selectLastLeaf
import git4idea.ui.branch.GitBranchesTreeUtil.selectNextLeaf
import git4idea.ui.branch.GitBranchesTreeUtil.selectPrevLeaf
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.drop
import java.awt.AWTEvent
import java.awt.Component
import java.awt.Cursor
import java.awt.Point
import java.awt.datatransfer.DataFlavor
import java.awt.event.*
import java.util.function.Function
import java.util.function.Supplier
import javax.swing.*
import javax.swing.tree.TreeCellRenderer
import javax.swing.tree.TreeModel
import javax.swing.tree.TreePath
import javax.swing.tree.TreeSelectionModel
class GitBranchesTreePopup(project: Project, step: GitBranchesTreePopupStep, parent: JBPopup? = null)
: WizardPopup(project, parent, step),
TreePopup, NextStepHandler {
private lateinit var tree: BranchesTree
private var showingChildPath: TreePath? = null
private var pendingChildPath: TreePath? = null
private val treeStep: GitBranchesTreePopupStep
get() = step as GitBranchesTreePopupStep
private lateinit var searchPatternStateFlow: MutableStateFlow<String?>
internal var userResized: Boolean
private set
init {
setMinimumSize(JBDimension(300, 200))
dimensionServiceKey = if (isChild()) null else GitBranchPopup.DIMENSION_SERVICE_KEY
userResized = !isChild() && WindowStateService.getInstance(project).getSizeFor(project, dimensionServiceKey) != null
installGeneralShortcutActions()
installShortcutActions(step.treeModel)
if (!isChild()) {
setSpeedSearchAlwaysShown()
installHeaderToolbar()
installRepoListener()
installResizeListener()
warnThatBranchesDivergedIfNeeded()
}
installBranchSettingsListener()
DataManager.registerDataProvider(component, DataProvider { dataId ->
when {
POPUP_KEY.`is`(dataId) -> this
GitBranchActionsUtil.REPOSITORIES_KEY.`is`(dataId) -> treeStep.repositories
else -> null
}
})
}
private fun warnThatBranchesDivergedIfNeeded() {
if (treeStep.isBranchesDiverged()) {
setWarning(DvcsBundle.message("branch.popup.warning.branches.have.diverged"))
}
}
override fun createContent(): JComponent {
tree = BranchesTree(treeStep.treeModel).also {
configureTreePresentation(it)
overrideTreeActions(it)
addTreeMouseControlsListeners(it)
Disposer.register(this) {
it.model = null
}
val topBorder = if (step.title.isNullOrEmpty()) JBUIScale.scale(5) else 0
it.border = JBUI.Borders.empty(topBorder, JBUIScale.scale(10), 0, 0)
}
searchPatternStateFlow = MutableStateFlow(null)
speedSearch.installSupplyTo(tree, false)
@OptIn(FlowPreview::class)
with(uiScope(this)) {
launch {
searchPatternStateFlow.drop(1).debounce(100).collectLatest { pattern ->
applySearchPattern(pattern)
}
}
}
return tree
}
private fun isChild() = parent != null
private fun applySearchPattern(pattern: String? = speedSearch.enteredPrefix.nullize(true)) {
treeStep.setSearchPattern(pattern)
val haveBranches = haveBranchesToShow()
if (haveBranches) {
selectPreferred()
}
super.updateSpeedSearchColors(!haveBranches)
if (!pattern.isNullOrBlank()) {
tree.emptyText.text = GitBundle.message("git.branches.popup.tree.no.branches", pattern)
}
}
private fun haveBranchesToShow(): Boolean {
val model = tree.model
val root = model.root
return (0 until model.getChildCount(root))
.asSequence()
.map { model.getChild(root, it) }
.filterIsInstance<GitBranchType>()
.any { !model.isLeaf(it) }
}
internal fun restoreDefaultSize() {
userResized = false
WindowStateService.getInstance(project).putSizeFor(project, dimensionServiceKey, null)
pack(true, true)
}
private fun installRepoListener() {
project.messageBus.connect(this).subscribe(GitRepository.GIT_REPO_CHANGE, GitRepositoryChangeListener {
runInEdt {
applySearchPattern()
}
})
}
private fun installResizeListener() {
addResizeListener({ userResized = true }, this)
}
private fun installBranchSettingsListener() {
project.messageBus.connect(this)
.subscribe(DvcsBranchManager.DVCS_BRANCH_SETTINGS_CHANGED,
object : DvcsBranchManager.DvcsBranchManagerListener {
override fun branchGroupingSettingsChanged(key: GroupingKey, state: Boolean) {
runInEdt {
treeStep.setPrefixGrouping(state)
}
}
override fun branchFavoriteSettingsChanged() {
runInEdt {
tree.repaint()
}
}
})
}
override fun storeDimensionSize() {
if (userResized) {
super.storeDimensionSize()
}
}
private fun toggleFavorite(branch: GitBranch) {
val branchType = GitBranchType.of(branch)
val branchManager = project.service<GitBranchManager>()
val anyNotFavorite = treeStep.repositories.any { repository -> !branchManager.isFavorite(branchType, repository, branch.name) }
treeStep.repositories.forEach { repository ->
branchManager.setFavorite(branchType, repository, branch.name, anyNotFavorite)
}
}
private fun installGeneralShortcutActions() {
registerAction("toggle_favorite", KeyStroke.getKeyStroke("SPACE"), object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) {
(tree.lastSelectedPathComponent?.let(TreeUtil::getUserObject) as? GitBranch)?.run(::toggleFavorite)
}
})
}
private fun installSpeedSearchActions() {
val updateSpeedSearch = {
val textInEditor = mySpeedSearchPatternField.textEditor.text
speedSearch.updatePattern(textInEditor)
applySearchPattern(textInEditor)
}
val editorActionsContext = mapOf(PlatformCoreDataKeys.CONTEXT_COMPONENT to mySpeedSearchPatternField.textEditor)
(ActionManager.getInstance()
.getAction(SPEED_SEARCH_DEFAULT_ACTIONS_GROUP) as ActionGroup)
.getChildren(null)
.forEach { action ->
registerAction(ActionManager.getInstance().getId(action),
KeymapUtil.getKeyStroke(action.shortcutSet),
createShortcutAction(action, editorActionsContext, updateSpeedSearch, false))
}
}
private fun installShortcutActions(model: TreeModel) {
val root = model.root
(0 until model.getChildCount(root))
.asSequence()
.map { model.getChild(root, it) }
.filterIsInstance<PopupFactoryImpl.ActionItem>()
.map(PopupFactoryImpl.ActionItem::getAction)
.forEach { action ->
registerAction(ActionManager.getInstance().getId(action),
KeymapUtil.getKeyStroke(action.shortcutSet),
createShortcutAction<Any>(action))
}
}
private fun installHeaderToolbar() {
val settingsGroup = ActionManager.getInstance().getAction(GitBranchesTreePopupStep.HEADER_SETTINGS_ACTION_GROUP)
val toolbarGroup = DefaultActionGroup(GitBranchPopupFetchAction(javaClass), settingsGroup)
val toolbar = ActionManager.getInstance()
.createActionToolbar(GitBranchesTreePopupStep.ACTION_PLACE, toolbarGroup, true)
.apply {
targetComponent = [email protected]
setReservePlaceAutoPopupIcon(false)
component.isOpaque = false
}
title.setButtonComponent(object : ActiveComponent.Adapter() {
override fun getComponent(): JComponent = toolbar.component
}, JBUI.Borders.emptyRight(2))
}
private fun <T> createShortcutAction(action: AnAction,
actionContext: Map<DataKey<T>, T> = emptyMap(),
afterActionPerformed: (() -> Unit)? = null,
closePopup: Boolean = true) = object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) {
if (closePopup) {
cancel()
}
val stepContext = GitBranchesTreePopupStep.createDataContext(project, treeStep.repositories)
val resultContext =
with(SimpleDataContext.builder().setParent(stepContext)) {
actionContext.forEach { (key, value) -> add(key, value) }
build()
}
ActionUtil.invokeAction(action, resultContext, GitBranchesTreePopupStep.ACTION_PLACE, null, afterActionPerformed)
}
}
private fun configureTreePresentation(tree: JTree) = with(tree) {
ClientProperty.put(this, RenderingUtil.CUSTOM_SELECTION_BACKGROUND, Supplier { JBUI.CurrentTheme.Tree.background(true, true) })
ClientProperty.put(this, RenderingUtil.CUSTOM_SELECTION_FOREGROUND, Supplier { JBUI.CurrentTheme.Tree.foreground(true, true) })
val renderer = Renderer(treeStep)
ClientProperty.put(this, Control.CUSTOM_CONTROL, Function { renderer.getLeftTreeIconRenderer(it) })
selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION
isRootVisible = false
showsRootHandles = true
cellRenderer = renderer
accessibleContext.accessibleName = GitBundle.message("git.branches.popup.tree.accessible.name")
ClientProperty.put(this, DefaultTreeUI.LARGE_MODEL_ALLOWED, true)
rowHeight = treeRowHeight
isLargeModel = true
expandsSelectedPaths = true
}
private fun overrideTreeActions(tree: JTree) = with(tree) {
overrideBuiltInAction("toggle") {
val path = selectionPath
if (path != null && model.getChildCount(path.lastPathComponent) == 0) {
handleSelect(true, null)
true
}
else false
}
overrideBuiltInAction(TreeActions.Left.ID) {
if (isChild()) {
cancel()
true
}
else false
}
overrideBuiltInAction(TreeActions.Right.ID) {
val path = selectionPath
if (path != null && (path.lastPathComponent is GitRepository || model.getChildCount(path.lastPathComponent) == 0)) {
handleSelect(false, null)
true
}
else false
}
overrideBuiltInAction(TreeActions.Down.ID) {
if (speedSearch.isHoldingFilter) selectNextLeaf()
else false
}
overrideBuiltInAction(TreeActions.Up.ID) {
if (speedSearch.isHoldingFilter) selectPrevLeaf()
else false
}
overrideBuiltInAction(TreeActions.Home.ID) {
if (speedSearch.isHoldingFilter) selectFirstLeaf()
else false
}
overrideBuiltInAction(TreeActions.End.ID) {
if (speedSearch.isHoldingFilter) selectLastLeaf()
else false
}
overrideBuiltInAction(TransferHandler.getPasteAction().getValue(Action.NAME) as String) {
speedSearch.type(CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor))
speedSearch.update()
true
}
}
private fun addTreeMouseControlsListeners(tree: JTree) = with(tree) {
addMouseMotionListener(SelectionMouseMotionListener())
addMouseListener(SelectOnClickListener())
}
override fun getActionMap(): ActionMap = tree.actionMap
override fun getInputMap(): InputMap = tree.inputMap
private val selectAllKeyStroke = KeymapUtil.getKeyStroke(ActionManager.getInstance().getAction(IdeActions.ACTION_SELECT_ALL).shortcutSet)
override fun process(e: KeyEvent?) {
if (e == null) return
val eventStroke = KeyStroke.getKeyStroke(e.keyCode, e.modifiersEx, e.id == KeyEvent.KEY_RELEASED)
if (selectAllKeyStroke == eventStroke) {
return
}
tree.processEvent(e)
}
override fun afterShow() {
selectPreferred()
if (treeStep.isSpeedSearchEnabled) {
installSpeedSearchActions()
}
}
override fun updateSpeedSearchColors(error: Boolean) {} // update colors only after branches tree model update
private fun selectPreferred() {
val preferredSelection = treeStep.getPreferredSelection()
if (preferredSelection != null) {
tree.makeVisible(preferredSelection)
tree.selectionPath = preferredSelection
TreeUtil.scrollToVisible(tree, preferredSelection, true)
}
else TreeUtil.promiseSelectFirstLeaf(tree)
}
override fun isResizable(): Boolean = true
private inner class SelectionMouseMotionListener : MouseMotionAdapter() {
private var lastMouseLocation: Point? = null
/**
* this method should be changed only in par with
* [com.intellij.ui.popup.list.ListPopupImpl.MyMouseMotionListener.isMouseMoved]
*/
private fun isMouseMoved(location: Point): Boolean {
if (lastMouseLocation == null) {
lastMouseLocation = location
return false
}
val prev = lastMouseLocation
lastMouseLocation = location
return prev != location
}
override fun mouseMoved(e: MouseEvent) {
if (!isMouseMoved(e.locationOnScreen)) return
val path = getPath(e)
if (path != null) {
tree.selectionPath = path
notifyParentOnChildSelection()
if (treeStep.isSelectable(TreeUtil.getUserObject(path.lastPathComponent))) {
tree.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
if (pendingChildPath == null || pendingChildPath != path) {
pendingChildPath = path
restartTimer()
}
return
}
}
tree.cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)
}
}
private inner class SelectOnClickListener : MouseAdapter() {
override fun mousePressed(e: MouseEvent) {
if (e.button != MouseEvent.BUTTON1) return
val path = getPath(e) ?: return
val selected = path.lastPathComponent
if (treeStep.isSelectable(TreeUtil.getUserObject(selected))) {
handleSelect(true, e)
}
}
}
private fun getPath(e: MouseEvent): TreePath? = tree.getClosestPathForLocation(e.point.x, e.point.y)
private fun handleSelect(handleFinalChoices: Boolean, e: MouseEvent?) {
val selectionPath = tree.selectionPath
val pathIsAlreadySelected = showingChildPath != null && showingChildPath == selectionPath
if (pathIsAlreadySelected) return
pendingChildPath = null
val selected = tree.lastSelectedPathComponent
if (selected != null) {
val userObject = TreeUtil.getUserObject(selected)
val point = e?.point
if (point != null && userObject is GitBranch && isMainIconAt(point, userObject)) {
toggleFavorite(userObject)
return
}
if (treeStep.isSelectable(userObject)) {
disposeChildren()
val hasNextStep = myStep.hasSubstep(userObject)
if (!hasNextStep && !handleFinalChoices) {
showingChildPath = null
return
}
val queriedStep = PopupImplUtil.prohibitFocusEventsInHandleSelect().use {
myStep.onChosen(userObject, handleFinalChoices)
}
if (queriedStep == PopupStep.FINAL_CHOICE || !hasNextStep) {
setFinalRunnable(myStep.finalRunnable)
setOk(true)
disposeAllParents(e)
}
else {
showingChildPath = selectionPath
handleNextStep(queriedStep, selected)
showingChildPath = null
}
}
}
}
private fun isMainIconAt(point: Point, selected: Any): Boolean {
val row = tree.getRowForLocation(point.x, point.y)
val rowBounds = tree.getRowBounds(row) ?: return false
point.translate(-rowBounds.x, -rowBounds.y)
val rowComponent = tree.cellRenderer
.getTreeCellRendererComponent(tree, selected, true, false, true, row, false) as? JComponent
?: return false
val iconComponent = UIUtil.uiTraverser(rowComponent)
.filter { ClientProperty.get(it, Renderer.MAIN_ICON) == true }
.firstOrNull() ?: return false
// todo: implement more precise check
return iconComponent.bounds.width >= point.x
}
override fun handleNextStep(nextStep: PopupStep<*>?, parentValue: Any) {
val selectionPath = tree.selectionPath ?: return
val pathBounds = tree.getPathBounds(selectionPath) ?: return
val point = Point(pathBounds.x, pathBounds.y)
SwingUtilities.convertPointToScreen(point, tree)
myChild =
if (nextStep is GitBranchesTreePopupStep) GitBranchesTreePopup(project, nextStep, this)
else createPopup(this, nextStep, parentValue)
myChild.show(content, content.locationOnScreen.x + content.width - STEP_X_PADDING, point.y, true)
}
override fun onSpeedSearchPatternChanged() {
with(uiScope(this)) {
launch {
searchPatternStateFlow.emit(speedSearch.enteredPrefix.nullize(true))
}
}
}
override fun getPreferredFocusableComponent(): JComponent = tree
override fun onChildSelectedFor(value: Any) {
val path = value as? TreePath ?: return
if (tree.selectionPath != path) {
tree.selectionPath = path
}
}
companion object {
internal val POPUP_KEY = DataKey.create<GitBranchesTreePopup>("GIT_BRANCHES_TREE_POPUP")
private val treeRowHeight = if (ExperimentalUI.isNewUI()) JBUI.CurrentTheme.List.rowHeight() else JBUIScale.scale(22)
@JvmStatic
fun isEnabled() = Registry.`is`("git.branches.popup.tree", false)
&& !ExperimentalUI.isNewUI()
@JvmStatic
fun show(project: Project) {
create(project).showCenteredInCurrentWindow(project)
}
@JvmStatic
fun create(project: Project): JBPopup {
val repositories = GitRepositoryManager.getInstance(project).repositories
return GitBranchesTreePopup(project, GitBranchesTreePopupStep(project, repositories, true))
}
@JvmStatic
internal fun createTreeSeparator(text: @NlsContexts.Separator String? = null) =
SeparatorWithText().apply {
caption = text
border = JBUI.Borders.emptyTop(
if (text == null) treeRowHeight / 2 else JBUIScale.scale(SeparatorWithText.DEFAULT_H_GAP))
}
private fun uiScope(parent: Disposable) =
CoroutineScope(SupervisorJob() + Dispatchers.Main).also {
Disposer.register(parent) { it.cancel() }
}
private class BranchesTree(model: TreeModel): Tree(model) {
init {
background = JBUI.CurrentTheme.Popup.BACKGROUND
}
//Change visibility of processEvent to be able to delegate key events dispatched in WizardPopup directly to tree
//This will allow to handle events like "copy-paste" in AbstractPopup.speedSearch
public override fun processEvent(e: AWTEvent?) {
e?.source = this
super.processEvent(e)
}
}
private class Renderer(private val step: GitBranchesTreePopupStep) : TreeCellRenderer {
fun getLeftTreeIconRenderer(path: TreePath): Control? {
val lastComponent = path.lastPathComponent
val defaultIcon = step.getNodeIcon(lastComponent, false) ?: return null
val selectedIcon = step.getNodeIcon(lastComponent, true) ?: return null
return DefaultControl(defaultIcon, defaultIcon, selectedIcon, selectedIcon)
}
private val mainIconComponent = JLabel().apply {
ClientProperty.put(this, MAIN_ICON, true)
border = JBUI.Borders.emptyRight(4) // 6 px in spec, but label width is differed
}
private val mainTextComponent = SimpleColoredComponent().apply {
isOpaque = false
border = JBUI.Borders.empty()
}
private val secondaryLabel = JLabel().apply {
border = JBUI.Borders.emptyLeft(10)
horizontalAlignment = SwingConstants.RIGHT
}
private val arrowLabel = JLabel().apply {
border = JBUI.Borders.emptyLeft(4) // 6 px in spec, but label width is differed
}
private val incomingOutgoingLabel = JLabel().apply {
border = JBUI.Borders.emptyLeft(10)
}
private val textPanel = JBUI.Panels.simplePanel()
.addToLeft(JBUI.Panels.simplePanel(mainTextComponent).addToLeft(mainIconComponent).andTransparent())
.addToCenter(JBUI.Panels.simplePanel(incomingOutgoingLabel).addToRight(secondaryLabel).andTransparent())
.andTransparent()
private val mainPanel = JBUI.Panels.simplePanel()
.addToCenter(textPanel)
.addToRight(arrowLabel)
.andTransparent()
.withBorder(JBUI.Borders.emptyRight(JBUI.CurrentTheme.ActionsList.cellPadding().right))
override fun getTreeCellRendererComponent(tree: JTree?,
value: Any?,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean): Component {
val userObject = TreeUtil.getUserObject(value)
mainIconComponent.apply {
icon = step.getIcon(userObject, selected)
isVisible = icon != null
}
mainTextComponent.apply {
background = JBUI.CurrentTheme.Tree.background(selected, true)
foreground = JBUI.CurrentTheme.Tree.foreground(selected, true)
clear()
append(step.getText(userObject).orEmpty())
}
val (inOutIcon, inOutTooltip) = step.getIncomingOutgoingIconWithTooltip(userObject)
tree?.toolTipText = inOutTooltip
incomingOutgoingLabel.apply {
icon = inOutIcon
isVisible = icon != null
}
arrowLabel.apply {
isVisible = step.hasSubstep(userObject)
icon = if (selected) AllIcons.Icons.Ide.MenuArrowSelected else AllIcons.Icons.Ide.MenuArrow
}
secondaryLabel.apply {
text = step.getSecondaryText(userObject)
//todo: LAF color
foreground = if (selected) JBUI.CurrentTheme.Tree.foreground(true, true) else JBColor.GRAY
border = if (!arrowLabel.isVisible && ExperimentalUI.isNewUI()) {
JBUI.Borders.empty(0, 10, 0, JBUI.CurrentTheme.Popup.Selection.innerInsets().right)
} else {
JBUI.Borders.emptyLeft(10)
}
}
if (tree != null && value != null) {
SpeedSearchUtil.applySpeedSearchHighlightingFiltered(tree, value, mainTextComponent, true, selected)
}
return mainPanel
}
companion object {
@JvmField
internal val MAIN_ICON = Key.create<Boolean>("MAIN_ICON")
}
}
}
}
| apache-2.0 | 73a2ee8e9249f395cebb1c305d294af5 | 34.69914 | 139 | 0.689582 | 4.798382 | false | false | false | false |
GunoH/intellij-community | plugins/ide-features-trainer/src/training/actions/RestartLessonAction.kt | 4 | 1430 | // 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 training.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import training.FeaturesTrainerIcons
import training.learn.CourseManager
import training.learn.lesson.LessonManager
import training.statistic.LessonStartingWay
import training.statistic.StatisticBase
import training.ui.LearningUiManager
private class RestartLessonAction : AnAction(FeaturesTrainerIcons.ResetLesson) {
override fun actionPerformed(e: AnActionEvent) {
val activeToolWindow = LearningUiManager.activeToolWindow ?: return
val lesson = LessonManager.instance.currentLesson ?: return
StatisticBase.logLessonStopped(StatisticBase.LessonStopReason.RESTART)
LessonManager.instance.stopLesson()
lesson.module.primaryLanguage?.let { it.onboardingFeedbackData = null }
CourseManager.instance.openLesson(activeToolWindow.project, lesson, LessonStartingWay.RESTART_BUTTON)
}
override fun getActionUpdateThread() = ActionUpdateThread.EDT
override fun update(e: AnActionEvent) {
val activeToolWindow = LearningUiManager.activeToolWindow
e.presentation.isEnabled = activeToolWindow != null && activeToolWindow.project == e.project
}
}
| apache-2.0 | a284d2ccceff81aac1e9e960a8ee4233 | 46.666667 | 158 | 0.821678 | 5.088968 | false | false | false | false |
GunoH/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/CollaborationToolsUIUtil.kt | 2 | 5382 | // 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.collaboration.ui
import com.intellij.ide.ui.laf.darcula.ui.DarculaButtonUI
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.ClientProperty
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.ScrollingUtil
import com.intellij.ui.SearchTextField
import com.intellij.ui.content.Content
import com.intellij.ui.speedSearch.NameFilteringListModel
import com.intellij.ui.speedSearch.SpeedSearch
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import java.beans.PropertyChangeListener
import javax.swing.*
import javax.swing.event.DocumentEvent
object CollaborationToolsUIUtil {
/**
* Connects [searchTextField] to a [list] to be used as a filter
*/
fun <T> attachSearch(list: JList<T>, searchTextField: SearchTextField, searchBy: (T) -> String) {
val speedSearch = SpeedSearch(false)
val filteringListModel = NameFilteringListModel<T>(list.model, searchBy, speedSearch::shouldBeShowing, speedSearch.filter::orEmpty)
list.model = filteringListModel
searchTextField.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) = speedSearch.updatePattern(searchTextField.text)
})
speedSearch.addChangeListener {
val prevSelection = list.selectedValue // save to restore the selection on filter drop
filteringListModel.refilter()
if (filteringListModel.size > 0) {
val fullMatchIndex = if (speedSearch.isHoldingFilter) filteringListModel.closestMatchIndex
else filteringListModel.getElementIndex(prevSelection)
if (fullMatchIndex != -1) {
list.selectedIndex = fullMatchIndex
}
if (filteringListModel.size <= list.selectedIndex || !filteringListModel.contains(list.selectedValue)) {
list.selectedIndex = 0
}
}
}
ScrollingUtil.installActions(list)
ScrollingUtil.installActions(list, searchTextField.textEditor)
}
/**
* Adds actions to transfer focus by tab/shift-tab key for given [component].
*
* May be helpful for overwriting tab symbol input for text fields
*/
fun registerFocusActions(component: JComponent) {
component.registerKeyboardAction({ component.transferFocus() },
KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0),
JComponent.WHEN_FOCUSED)
component.registerKeyboardAction({ component.transferFocusBackward() },
KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_DOWN_MASK),
JComponent.WHEN_FOCUSED)
}
/**
* Add [listener] that will be invoked on each "UI" property change
*/
fun <T : JComponent> overrideUIDependentProperty(component: T, listener: T.() -> Unit) {
component.addPropertyChangeListener("UI", PropertyChangeListener {
listener.invoke(component)
})
listener.invoke(component)
}
/**
* Makes the button blue like a default button in dialogs
*/
fun JButton.defaultButton(): JButton = apply {
isDefault = true
}
/**
* Makes the button blue like a default button in dialogs
*/
var JButton.isDefault: Boolean
get() = ClientProperty.isTrue(this, DarculaButtonUI.DEFAULT_STYLE_KEY)
set(value) {
if (value) {
ClientProperty.put(this, DarculaButtonUI.DEFAULT_STYLE_KEY, true)
}
else {
ClientProperty.remove(this, DarculaButtonUI.DEFAULT_STYLE_KEY)
}
}
/**
* Removes http(s) protocol and trailing slash from given [url]
*/
@Suppress("HttpUrlsUsage")
@NlsSafe
fun cleanupUrl(@NlsSafe url: String): String = url
.removePrefix("https://")
.removePrefix("http://")
.removeSuffix("/")
/**
* Checks if focus is somewhere down the hierarchy from [component]
*/
fun isFocusParent(component: JComponent): Boolean {
val focusOwner = IdeFocusManager.findInstanceByComponent(component).focusOwner ?: return false
return SwingUtilities.isDescendingFrom(focusOwner, component)
}
/**
* Finds the proper focus target for [panel] and set focus to it
*/
fun focusPanel(panel: JComponent) {
val focusManager = IdeFocusManager.findInstanceByComponent(panel)
val toFocus = focusManager.getFocusTargetFor(panel) ?: return
focusManager.doWhenFocusSettlesDown { focusManager.requestFocus(toFocus, true) }
}
fun setComponentPreservingFocus(content: Content, component: JComponent) {
val focused = isFocusParent(content.component)
content.component = component
if (focused) {
focusPanel(content.component)
}
}
}
internal fun <E> ListModel<E>.findIndex(item: E): Int {
for (i in 0 until size) {
if (getElementAt(i) == item) return i
}
return -1
}
internal val <E> ListModel<E>.items
get() = Iterable {
object : Iterator<E> {
private var idx = -1
override fun hasNext(): Boolean = idx < size - 1
override fun next(): E {
idx++
return getElementAt(idx)
}
}
}
fun ComboBoxModel<*>.selectFirst() {
val size = size
if (size == 0) {
return
}
val first = getElementAt(0)
selectedItem = first
} | apache-2.0 | 7adf0c93b38d8f0ac31e438a462b8b4e | 32.02454 | 158 | 0.694537 | 4.503766 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/WykopImageView.kt | 1 | 3762 | package io.github.feelfreelinux.wykopmobilny.ui.widgets
import android.content.Context
import android.graphics.Bitmap
import android.util.AttributeSet
import android.util.DisplayMetrics
import android.widget.ImageView
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.bumptech.glide.signature.ObjectKey
import io.github.feelfreelinux.wykopmobilny.glide.GlideApp
import io.github.feelfreelinux.wykopmobilny.utils.getActivityContext
import io.github.feelfreelinux.wykopmobilny.utils.preferences.SettingsPreferences
import io.github.feelfreelinux.wykopmobilny.utils.preferences.SettingsPreferencesApi
class WykopImageView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ImageView(context, attrs, defStyleAttr) {
init {
setOnClickListener { openImageListener() }
scaleType = ScaleType.CENTER_CROP
}
var isResized = false
var forceDisableMinimizedMode = false
var openImageListener: () -> Unit = {}
var onResizedListener: (Boolean) -> Unit = {}
var showResizeView: (Boolean) -> Unit = {}
private val settingsPreferencesApi by lazy { SettingsPreferences(context) as SettingsPreferencesApi }
private val screenMetrics by lazy {
val metrics = DisplayMetrics()
getActivityContext()!!.windowManager.defaultDisplay.getMetrics(metrics)
metrics
}
fun loadImageFromUrl(url: String) {
GlideApp.with(context)
.asBitmap()
.load(url)
.apply(
RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.signature(ObjectKey(url))
)
.into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
setImageBitmap(resource)
}
})
}
fun resetImage() {
setImageBitmap(null)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val proportion =
(screenMetrics.heightPixels.toFloat() * (settingsPreferencesApi.cutImageProportion.toFloat() / 100)) / screenMetrics.widthPixels.toFloat()
val widthSpec =
MeasureSpec.getSize(if (settingsPreferencesApi.showMinifiedImages && !forceDisableMinimizedMode) widthMeasureSpec / 2 else widthMeasureSpec)
if (drawable != null) {
val measuredMultiplier = (drawable.intrinsicHeight.toFloat() / drawable.intrinsicWidth.toFloat())
val heightSpec = widthSpec.toFloat() * measuredMultiplier
if (measuredMultiplier > proportion && !isResized && settingsPreferencesApi.cutImages) {
setOnClickListener {
isResized = true
onResizedListener(true)
requestLayout()
invalidate()
setOnClickListener { openImageListener() }
}
setMeasuredDimension(widthSpec, (widthSpec.toFloat() * proportion).toInt())
showResizeView(true)
} else {
setMeasuredDimension(widthSpec, heightSpec.toInt())
setOnClickListener { openImageListener() }
showResizeView(false)
}
} else {
setMeasuredDimension(widthSpec, (widthSpec.toFloat() * proportion).toInt())
setOnClickListener { openImageListener() }
showResizeView(false)
}
if (!settingsPreferencesApi.cutImages) showResizeView(false)
}
} | mit | 1fd8d9ee172bcbfa814ac774e40b922f | 40.811111 | 152 | 0.664009 | 5.397418 | false | false | false | false |
zsmb13/MaterialDrawerKt | app/src/main/java/co/zsmb/materialdrawerktexample/customitems/customprimary/CustomPrimaryDrawerItemKt.kt | 1 | 1222 | package co.zsmb.materialdrawerktexample.customitems.customprimary
import co.zsmb.materialdrawerkt.builders.Builder
import co.zsmb.materialdrawerkt.createItem
import co.zsmb.materialdrawerkt.draweritems.badgeable.AbstractBadgeableDrawerItemKt
import co.zsmb.materialdrawerkt.nonReadable
fun Builder.customPrimaryItem(
name: String = "",
description: String? = null,
setup: CustomPrimaryDrawerItemKt.() -> Unit = {}): CustomPrimaryDrawerItem {
return createItem(CustomPrimaryDrawerItemKt(), name, description, setup)
}
fun Builder.customPrimaryItem(
nameRes: Int,
descriptionRes: Int? = null,
setup: CustomPrimaryDrawerItemKt.() -> Unit = {}): CustomPrimaryDrawerItem {
return createItem(CustomPrimaryDrawerItemKt(), nameRes, descriptionRes, setup)
}
class CustomPrimaryDrawerItemKt : AbstractBadgeableDrawerItemKt<CustomPrimaryDrawerItem>(CustomPrimaryDrawerItem()) {
// Props and methods
var backgroundColor: Int
get() = nonReadable()
set(value) {
item.withBackgroundColor(value)
}
var backgroundRes: Int
get() = nonReadable()
set(value) {
item.withBackgroundRes(value)
}
}
| apache-2.0 | 1d4ec17093735ac44b5ce41b035b6f85 | 31.157895 | 117 | 0.714403 | 4.907631 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/framework/stdlib/stdlib.kt | 2 | 2012 | /*
* Copyright 2010-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.
*/
@file:Suppress("UNUSED")
package stdlib
fun <K, V> isEmpty(map: Map<K, V>) = map.isEmpty()
fun <K, V> getKeysAsSet(map: Map<K, V>) = map.keys
fun <K, V> getKeysAsList(map: Map<K, V>) = map.keys.toList()
fun <K, V> toMutableMap(map: HashMap<K, V>) = map.toMutableMap()
fun <E> getFirstElement(collection: Collection<E>) = collection.first()
class GenericExtensionClass<K, out V, out T : Map<K, V>> (private val holder: T?) {
fun getFirstKey(): K? = holder?.entries?.first()?.key
fun getFirstValue() : V? {
holder?.entries?.forEach { e -> println("KEY: ${e.key} VALUE: ${e.value}") }
return holder?.entries?.first()?.value
}
}
fun <K, V> createPair():
Pair<LinkedHashMap<K, V>, GenericExtensionClass<K, V, Map<K, V>>> {
val l = createLinkedMap<K, V>()
val g = GenericExtensionClass(l)
return Pair(l, g)
}
fun <K, V> createLinkedMap() = linkedMapOf<K, V>()
fun createTypedMutableMap() = linkedMapOf<Int, String>()
fun addSomeElementsToMap(map: MutableMap<String, Int>) {
map.put(key = "XYZ", value = 321)
map.put(key = "TMP", value = 451)
}
fun list(vararg elements: Any?): Any = listOf(*elements)
fun set(vararg elements: Any?): Any = setOf(*elements)
fun map(vararg keysAndValues: Any?): Any = mutableMapOf<Any?, Any?>().apply {
(0 until keysAndValues.size step 2).forEach {index ->
this[keysAndValues[index]] = keysAndValues[index + 1]
}
}
fun emptyMutableList(): Any = mutableListOf<Any?>()
fun emptyMutableSet(): Any = mutableSetOf<Any?>()
fun emptyMutableMap(): Any = mutableMapOf<Any?, Any?>()
data class TripleVals<T>(val first: T, val second: T, val third: T)
data class TripleVars<T>(var first: T, var second: T, var third: T) {
override fun toString(): String {
return "[$first, $second, $third]"
}
}
fun gc() = kotlin.native.internal.GC.collect() | apache-2.0 | b7807fbe89ac3672e3c1e40fb177120a | 30.453125 | 101 | 0.652087 | 3.266234 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/model/richText/RichText.kt | 8 | 4590 | // 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.codeInsight.codeVision.ui.model.richText
import com.intellij.openapi.util.TextRange
import com.intellij.ui.SimpleTextAttributes
import org.jetbrains.annotations.Nls
import java.awt.Color
import java.awt.Font
// please consider talking to someone from Rider Team before changing anything here
data class RichString(val textRange: TextRange, var attributes: SimpleTextAttributes, val richText: RichText) {
val text: String get() = richText.text.substring(textRange.startOffset, textRange.endOffset)
}
open class RichText(text: String, parts: Collection<RichString>) : Cloneable {
private var myString: String = text
private var myParts = ArrayList<RichString>(parts)
val parts: List<RichString> get() = myParts
val text: String get() = myString
val length: Int get() = text.length
constructor() : this("", emptyList())
constructor(text: String) : this() {
append(text, SimpleTextAttributes.REGULAR_ATTRIBUTES)
}
fun append(text: String, style: SimpleTextAttributes) {
val range = TextRange(myString.length, myString.length + text.length)
myString += text
myParts.add(RichString(range, style, this))
}
fun setForeColor(fgColor: Color) {
for (part in parts) {
val attributes = part.attributes
val style = attributes.style
val bgColor = attributes.bgColor
val waveColor = attributes.waveColor
part.attributes = attributes.derive(style, fgColor, bgColor, waveColor)
}
}
fun addStyle(@SimpleTextAttributes.StyleAttributeConstant style: Int, textRange: TextRange) {
if (textRange.startOffset !in 0 until length) throw IllegalArgumentException("textRange")
if (textRange.endOffset !in 0..length)
throw IllegalArgumentException("textRange")
val newParts = ArrayList<RichString>()
for (part in myParts) {
val (partRange, attributes) = part
val intersection: TextRange? = textRange.intersection(partRange)
if (intersection == null) {
newParts.add(part)
continue
} else {
if (partRange.startOffset != intersection.startOffset) {
newParts.add(RichString(TextRange(partRange.startOffset, intersection.startOffset), attributes, this))
}
val newAttributes = attributes.derive(attributes.style or style, null, null, null)
newParts.add(RichString(intersection, newAttributes, this))
if (intersection.endOffset != partRange.endOffset) {
newParts.add(RichString(TextRange(intersection.endOffset, partRange.endOffset), attributes, this))
}
}
}
myParts = newParts
}
public override fun clone(): RichText {
val copy = RichText()
copy.myString = myString
for ((textRange, attributes) in myParts) copy.myParts.add(RichString(textRange, attributes, copy))
return copy
}
@Nls
override fun toString(): String {
val acc = StringBuilder()
for (p in myParts) {
val (r, a) = p
acc.apply {
append("<span styles=\"")
val bgColor = a.bgColor
if (bgColor != null) {
append("background-color:")
dumpColor(bgColor)
}
val fgColor = a.fgColor
if (fgColor != null) {
append("color:")
dumpColor(fgColor)
}
val waveColor = a.waveColor
if (waveColor != null) {
append("wave-color:")
dumpColor(fgColor)
}
dumpStyleAndFont(a)
append("")
append("\">")
append(p.text)
append("</span>")
}
}
return acc.toString()
}
private fun StringBuilder.dumpStyleAndFont(a: SimpleTextAttributes) {
when (a.fontStyle) {
Font.PLAIN -> append("font-style: plain;")
Font.ITALIC -> append("font-style: italic;")
Font.BOLD -> append("font-weight: bold;")
}
when {
a.isSearchMatch -> append("text-decoration: searchMatch;")
a.isStrikeout -> append("text-decoration: strikeout;")
a.isWaved -> append("text-decoration: waved;")
a.isUnderline -> append("text-decoration: underline;")
a.isBoldDottedLine -> append("text-decoration: boldDottedLine;")
a.isOpaque -> append("text-decoration: opaque;")
a.isSmaller -> append("text-decoration: smaller;")
}
}
private fun StringBuilder.dumpColor(bgColor: Color) {
append("rgb(")
append(bgColor.red)
append(",")
append(bgColor.green)
append(",")
append(bgColor.blue)
append(");")
}
} | apache-2.0 | 76fe71a053d04f205d135808539ecb4d | 32.268116 | 120 | 0.661874 | 4.191781 | false | false | false | false |
smmribeiro/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/storage/MutableLookupStorage.kt | 8 | 7076 | // 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.completion.ml.storage
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.ml.ContextFeatures
import com.intellij.codeInsight.completion.ml.MLFeatureValue
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.completion.ml.experiment.ExperimentStatus
import com.intellij.completion.ml.features.ContextFeaturesStorage
import com.intellij.completion.ml.performance.CompletionPerformanceTracker
import com.intellij.completion.ml.personalization.UserFactorStorage
import com.intellij.completion.ml.personalization.UserFactorsManager
import com.intellij.completion.ml.personalization.session.LookupSessionFactorsStorage
import com.intellij.completion.ml.sorting.RankingModelWrapper
import com.intellij.completion.ml.sorting.RankingSupport
import com.intellij.completion.ml.util.idString
import com.intellij.lang.Language
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.UserDataHolderBase
import org.jetbrains.annotations.TestOnly
class MutableLookupStorage(
override val startedTimestamp: Long,
override val language: Language,
override val model: RankingModelWrapper?)
: LookupStorage {
private var _userFactors: Map<String, String>? = null
override val userFactors: Map<String, String>
get() = _userFactors ?: emptyMap()
private var contextFeaturesStorage: ContextFeatures? = null
override val contextFactors: Map<String, String>
get() = contextFeaturesStorage?.asMap() ?: emptyMap()
private var mlUsed: Boolean = false
private var shouldReRank = model != null
private var _loggingEnabled: Boolean = false
override val performanceTracker: CompletionPerformanceTracker = CompletionPerformanceTracker()
companion object {
private val LOG = logger<MutableLookupStorage>()
private val LOOKUP_STORAGE = Key.create<MutableLookupStorage>("completion.ml.lookup.storage")
@Volatile
private var alwaysComputeFeaturesInTests = true
@TestOnly
fun setComputeFeaturesAlways(value: Boolean, parentDisposable: Disposable) {
val valueBefore = alwaysComputeFeaturesInTests
alwaysComputeFeaturesInTests = value
Disposer.register(parentDisposable, Disposable {
alwaysComputeFeaturesInTests = valueBefore
})
}
fun get(lookup: LookupImpl): MutableLookupStorage? {
return lookup.getUserData(LOOKUP_STORAGE)
}
fun initOrGetLookupStorage(lookup: LookupImpl, language: Language): MutableLookupStorage {
val existed = get(lookup)
if (existed != null) return existed
val storage = MutableLookupStorage(System.currentTimeMillis(), language, RankingSupport.getRankingModel(language))
lookup.putUserData(LOOKUP_STORAGE, storage)
return storage
}
fun get(parameters: CompletionParameters): MutableLookupStorage? {
var storage = parameters.getUserData(LOOKUP_STORAGE)
if (storage == null) {
val activeLookup = LookupManager.getActiveLookup(parameters.editor) as? LookupImpl
if (activeLookup != null) {
storage = get(activeLookup)
if (storage != null) {
LOG.debug("Can't get storage from parameters. Fallback to storage from active lookup")
saveAsUserData(parameters, storage)
}
}
}
return storage
}
fun saveAsUserData(parameters: CompletionParameters, storage: MutableLookupStorage) {
val completionProcess = parameters.process
if (completionProcess is UserDataHolder) {
completionProcess.putUserData(LOOKUP_STORAGE, storage)
}
}
private fun <T> CompletionParameters.getUserData(key: Key<T>): T? {
return (process as? UserDataHolder)?.getUserData(key)
}
}
override val sessionFactors: LookupSessionFactorsStorage = LookupSessionFactorsStorage(startedTimestamp)
private val item2storage: MutableMap<String, MutableElementStorage> = mutableMapOf()
override fun getItemStorage(id: String): MutableElementStorage = item2storage.computeIfAbsent(id) {
MutableElementStorage()
}
override fun mlUsed(): Boolean = mlUsed
fun fireReorderedUsingMLScores() {
mlUsed = true
performanceTracker.reorderedByML()
}
override fun shouldComputeFeatures(): Boolean = shouldReRank() ||
(ApplicationManager.getApplication().isUnitTestMode && alwaysComputeFeaturesInTests) ||
(_loggingEnabled && !experimentWithoutComputingFeatures())
override fun shouldReRank(): Boolean = model != null && shouldReRank
fun disableReRanking() {
shouldReRank = false
}
fun isContextFactorsInitialized(): Boolean = contextFeaturesStorage != null
fun fireElementScored(element: LookupElement, factors: MutableMap<String, Any>, mlScore: Double?) {
getItemStorage(element.idString()).fireElementScored(factors, mlScore)
}
fun initUserFactors(project: Project) {
ApplicationManager.getApplication().assertIsDispatchThread()
if (_userFactors == null && UserFactorsManager.ENABLE_USER_FACTORS) {
val userFactorValues = mutableMapOf<String, String>()
val userFactors = UserFactorsManager.getInstance().getAllFactors()
val applicationStorage: UserFactorStorage = UserFactorStorage.getInstance()
val projectStorage: UserFactorStorage = UserFactorStorage.getInstance(project)
for (factor in userFactors) {
factor.compute(applicationStorage)?.let { userFactorValues["${factor.id}:App"] = it }
factor.compute(projectStorage)?.let { userFactorValues["${factor.id}:Project"] = it }
}
_userFactors = userFactorValues
}
}
override fun contextProvidersResult(): ContextFeatures = contextFeaturesStorage ?: ContextFeaturesStorage.EMPTY
fun initContextFactors(contextFactors: MutableMap<String, MLFeatureValue>,
environment: UserDataHolderBase) {
if (isContextFactorsInitialized()) {
LOG.error("Context factors should be initialized only once")
}
else {
val features = ContextFeaturesStorage(contextFactors)
environment.copyUserDataTo(features)
contextFeaturesStorage = features
}
}
private fun experimentWithoutComputingFeatures(): Boolean {
val experimentInfo = ExperimentStatus.getInstance().forLanguage(language)
if (experimentInfo.inExperiment) {
return !experimentInfo.shouldCalculateFeatures
}
return false
}
fun markLoggingEnabled() {
_loggingEnabled = true
}
} | apache-2.0 | 8e93b532673b70fbe003f727762362c1 | 39.44 | 140 | 0.749011 | 4.866575 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertForEachToForLoopIntention.kt | 1 | 4208 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
class ConvertForEachToForLoopIntention : SelfTargetingOffsetIndependentIntention<KtSimpleNameExpression>(
KtSimpleNameExpression::class.java, KotlinBundle.lazyMessage("replace.with.a.for.loop")
) {
companion object {
private const val FOR_EACH_NAME = "forEach"
private val FOR_EACH_FQ_NAMES: Set<String> by lazy {
sequenceOf("collections", "sequences", "text", "ranges").map { "kotlin.$it.$FOR_EACH_NAME" }.toSet()
}
}
override fun isApplicableTo(element: KtSimpleNameExpression): Boolean {
if (element.getReferencedName() != FOR_EACH_NAME) return false
val data = extractData(element) ?: return false
if (data.functionLiteral.valueParameters.size > 1) return false
if (data.functionLiteral.bodyExpression == null) return false
return true
}
override fun applyTo(element: KtSimpleNameExpression, editor: Editor?) {
val (expressionToReplace, receiver, functionLiteral, context) = extractData(element)!!
val commentSaver = CommentSaver(expressionToReplace)
val loop = generateLoop(functionLiteral, receiver, context)
val result = expressionToReplace.replace(loop) as KtForExpression
result.loopParameter?.also { editor?.caretModel?.moveToOffset(it.startOffset) }
commentSaver.restore(result)
}
private data class Data(
val expressionToReplace: KtExpression,
val receiver: KtExpression,
val functionLiteral: KtLambdaExpression,
val context: BindingContext
)
private fun extractData(nameExpr: KtSimpleNameExpression): Data? {
val parent = nameExpr.parent
val expression = (when (parent) {
is KtCallExpression -> parent.parent as? KtDotQualifiedExpression
is KtBinaryExpression -> parent
else -> null
} ?: return null) as KtExpression //TODO: submit bug
val context = expression.analyze()
val resolvedCall = expression.getResolvedCall(context) ?: return null
if (DescriptorUtils.getFqName(resolvedCall.resultingDescriptor).toString() !in FOR_EACH_FQ_NAMES) return null
val receiver = resolvedCall.call.explicitReceiver as? ExpressionReceiver ?: return null
val argument = resolvedCall.call.valueArguments.singleOrNull() ?: return null
val functionLiteral = argument.getArgumentExpression() as? KtLambdaExpression ?: return null
return Data(expression, receiver.expression, functionLiteral, context)
}
private fun generateLoop(functionLiteral: KtLambdaExpression, receiver: KtExpression, context: BindingContext): KtExpression {
val factory = KtPsiFactory(functionLiteral)
val body = functionLiteral.bodyExpression!!
val function = functionLiteral.functionLiteral
body.forEachDescendantOfType<KtReturnExpression> {
if (it.getTargetFunction(context) == function) {
it.replace(factory.createExpression("continue"))
}
}
val loopRange = KtPsiUtil.safeDeparenthesize(receiver)
val parameter = functionLiteral.valueParameters.singleOrNull()
return factory.createExpressionByPattern("for($0 in $1){ $2 }", parameter ?: "it", loopRange, body.allChildren)
}
}
| apache-2.0 | 8496734b6636b69512f36ab26964b15d | 44.247312 | 158 | 0.730276 | 5.156863 | false | false | false | false |
smmribeiro/intellij-community | python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypeShed.kt | 1 | 6385 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.codeInsight.typing
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.PyPsiPackageUtil
import com.jetbrains.python.PythonHelpersLocator
import com.jetbrains.python.PythonRuntimeService
import com.jetbrains.python.packaging.PyPackageManagers
import com.jetbrains.python.psi.LanguageLevel
import java.io.File
/**
* Utilities for managing the local copy of the typeshed repository.
*
* The original Git repo is located [here](https://github.com/JetBrains/typeshed).
*
* @author vlan
*/
object PyTypeShed {
private val stdlibNamesAvailableOnlyInSubsetOfSupportedLanguageLevels = mapOf(
// name to python versions when this name was introduced and removed
"_bootlocale" to (LanguageLevel.PYTHON36 to LanguageLevel.PYTHON39),
"_dummy_thread" to (LanguageLevel.PYTHON36 to LanguageLevel.PYTHON38),
"_dummy_threading" to (LanguageLevel.PYTHON27 to LanguageLevel.PYTHON38),
"_py_abc" to (LanguageLevel.PYTHON37 to null),
"binhex" to (LanguageLevel.PYTHON27 to LanguageLevel.PYTHON310),
"contextvars" to (LanguageLevel.PYTHON37 to null),
"dataclasses" to (LanguageLevel.PYTHON37 to null),
"distutils.command.bdist_msi" to (LanguageLevel.PYTHON27 to LanguageLevel.PYTHON310), // likely it is ignored now
"dummy_threading" to (LanguageLevel.PYTHON27 to LanguageLevel.PYTHON38),
"formatter" to (LanguageLevel.PYTHON27 to LanguageLevel.PYTHON39),
"graphlib" to (LanguageLevel.PYTHON39 to null),
"importlib.metadata" to (LanguageLevel.PYTHON38 to null), // likely it is ignored now
"importlib.metadata._meta" to (LanguageLevel.PYTHON310 to null), // likely it is ignored now
"importlib.resources" to (LanguageLevel.PYTHON37 to null), // likely it is ignored now
"macpath" to (LanguageLevel.PYTHON27 to LanguageLevel.PYTHON37),
"macurl2path" to (LanguageLevel.PYTHON27 to LanguageLevel.PYTHON36),
"parser" to (LanguageLevel.PYTHON27 to LanguageLevel.PYTHON39),
"symbol" to (LanguageLevel.PYTHON27 to LanguageLevel.PYTHON39),
"unittest._log" to (LanguageLevel.PYTHON39 to null), // likely it is ignored now
"zoneinfo" to (LanguageLevel.PYTHON39 to null)
)
/**
* Returns true if we allow to search typeshed for a stub for [name].
*/
fun maySearchForStubInRoot(name: QualifiedName, root: VirtualFile, sdk: Sdk): Boolean {
if (isInStandardLibrary(root)) {
val head = name.firstComponent ?: return true
val languageLevels = stdlibNamesAvailableOnlyInSubsetOfSupportedLanguageLevels[head] ?: return true
val currentLanguageLevel = PythonRuntimeService.getInstance().getLanguageLevelForSdk(sdk)
return currentLanguageLevel.isAtLeast(languageLevels.first) && languageLevels.second.let {
it == null || it.isAtLeast(currentLanguageLevel)
}
}
if (isInThirdPartyLibraries(root)) {
if (ApplicationManager.getApplication().isUnitTestMode) {
return true
}
val possiblePackage = name.firstComponent ?: return false
val alternativePossiblePackages = PyPsiPackageUtil.PACKAGES_TOPLEVEL[possiblePackage] ?: emptyList()
val packageManager = PyPackageManagers.getInstance().forSdk(sdk)
val installedPackages = if (ApplicationManager.getApplication().isHeadlessEnvironment) {
packageManager.refreshAndGetPackages(false)
}
else {
packageManager.packages ?: return true
}
return packageManager.parseRequirement(possiblePackage)?.match(installedPackages) != null ||
alternativePossiblePackages.any { PyPsiPackageUtil.findPackage(installedPackages, it) != null }
}
return false
}
/**
* Returns the list of roots in typeshed for the Python language level of [sdk].
*/
fun findRootsForSdk(sdk: Sdk): List<VirtualFile> {
val level = PythonRuntimeService.getInstance().getLanguageLevelForSdk(sdk)
return findRootsForLanguageLevel(level)
}
/**
* Returns the list of roots in typeshed for the specified Python language [level].
*/
fun findRootsForLanguageLevel(level: LanguageLevel): List<VirtualFile> {
val dir = directory ?: return emptyList()
val common = sequenceOf(dir.findChild("stdlib"))
.plus(dir.findFileByRelativePath("stubs")?.children ?: VirtualFile.EMPTY_ARRAY)
.filterNotNull()
.toList()
return if (level.isPython2) common.flatMap { listOfNotNull(it.findChild("@python2"), it) } else common
}
/**
* Checks if the [file] is located inside the typeshed directory.
*/
fun isInside(file: VirtualFile): Boolean {
val dir = directory
return dir != null && VfsUtilCore.isAncestor(dir, file, true)
}
/**
* The actual typeshed directory.
*/
val directory: VirtualFile? by lazy {
val path = directoryPath ?: return@lazy null
StandardFileSystems.local().findFileByPath(path)
}
private val directoryPath: String?
get() {
val paths = listOf("${PathManager.getConfigPath()}/typeshed",
"${PathManager.getConfigPath()}/../typeshed",
PythonHelpersLocator.getHelperPath("typeshed"))
return paths.asSequence()
.filter { File(it).exists() }
.firstOrNull()
}
/**
* A shallow check for a [file] being located inside the typeshed third-party stubs.
*/
fun isInThirdPartyLibraries(file: VirtualFile): Boolean = "stubs" in file.path
fun isInStandardLibrary(file: VirtualFile): Boolean = "stdlib" in file.path
}
| apache-2.0 | 3b2bb1fce6f9a99c1794addfbe9432b0 | 41.006579 | 118 | 0.729366 | 4.480702 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/hierarchy/calls/callees/kotlinPackageProperty/main0.kt | 13 | 471 | class KA {
val name = "A"
fun foo(s: String): String = "A: $s"
}
fun packageFun(s: String): String = s
val <caret>packageVal: String
get() {
fun localFun(s: String): String = packageFun(s)
val localVal = localFun("")
KA().foo(KA().name)
JA().foo(JA().name)
localFun("")
run {
KA().foo(KA().name)
JA().foo(JA().name)
packageFun(localVal)
}
return ""
} | apache-2.0 | 6d539384c9eb70f96333d348c3ad9c2d | 18.666667 | 55 | 0.473461 | 3.413043 | false | false | false | false |
shalupov/idea-cloudformation | src/main/kotlin/com/intellij/aws/cloudformation/model/CfnResourceNode.kt | 2 | 1778 | package com.intellij.aws.cloudformation.model
import com.intellij.aws.cloudformation.CloudFormationMetadataProvider
import com.intellij.aws.cloudformation.metadata.CloudFormationResourceAttribute
import com.intellij.aws.cloudformation.metadata.awsServerlessFunction
class CfnResourceNode(name: CfnScalarValueNode?,
val type: CfnResourceTypeNode?,
val properties: CfnResourcePropertiesNode?,
val condition: CfnResourceConditionNode?,
val dependsOn: CfnResourceDependsOnNode?,
val allTopLevelProperties: Map<String, CfnNamedNode>) : CfnNamedNode(name) {
val typeName: String?
get() = type?.value?.value
fun getAttributes(root: CfnRootNode): Map<String, CloudFormationResourceAttribute> {
val resourceTypeName = typeName ?: return emptyMap()
val resourceType = CloudFormationMetadataProvider.METADATA.findResourceType(resourceTypeName, root) ?: return emptyMap()
// https://github.com/awslabs/serverless-application-model/blob/develop/versions/2016-10-31.md#referencing-lambda-version--alias-resources
if (isAwsServerlessFunctionWithAutoPublishAlias()) {
val additionalAttributes = listOf("Version", "Alias")
return resourceType.attributes + additionalAttributes.map { it to CloudFormationResourceAttribute(it) }.toMap()
}
return resourceType.attributes
}
// https://github.com/awslabs/serverless-application-model/blob/develop/versions/2016-10-31.md#referencing-lambda-version--alias-resources
fun isAwsServerlessFunctionWithAutoPublishAlias() =
typeName == awsServerlessFunction.name &&
properties != null && properties.properties.any { it.name?.value == "AutoPublishAlias" && it.value != null }
} | apache-2.0 | 40abf4dcfa44a29c8803ae347cfbe74c | 52.909091 | 142 | 0.74072 | 4.703704 | false | false | false | false |
bixlabs/bkotlin | bkotlin/src/main/java/com/bixlabs/bkotlin/SharedPreferences.kt | 1 | 5133 | package com.bixlabs.bkotlin
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
@Suppress("unused")
object GlobalSharedPreferences {
private lateinit var sharedPreferences: SharedPreferences
private lateinit var editor: SharedPreferences.Editor
private var initialized = false
/**
* @param application Global context in order use everywhere
* without the need for context every time
* @param sharedPreferencesName custom name for SharedPreferences
* @return instance of the GlobalSharedPreferences
*/
@SuppressLint("CommitPrefEdits")
fun initialize(application: Application, sharedPreferencesName: String = "DefaultSharedPreferences"):
GlobalSharedPreferences {
sharedPreferences = application.getSharedPreferences(sharedPreferencesName, Context.MODE_PRIVATE)
editor = sharedPreferences.edit()
initialized = true
return this
}
fun getAll(): Map<String, *> = requiredOrThrow(sharedPreferences.all)
fun getInt(key: String, defaultValue: Int) =
requiredOrThrow(sharedPreferences.getInt(key, defaultValue))
fun getLong(key: String, defaultValue: Long) =
requiredOrThrow(sharedPreferences.getLong(key, defaultValue))
fun getFloat(key: String, defaultValue: Float) =
requiredOrThrow(sharedPreferences.getFloat(key, defaultValue))
fun getBoolean(key: String, defaultValue: Boolean) =
requiredOrThrow(sharedPreferences.getBoolean(key, defaultValue))
fun getString(key: String, defaultValue: String) : String =
requiredOrThrow(sharedPreferences.getString(key, defaultValue))
fun getStringSet(key: String, defaultValue: Set<String>): MutableSet<String>? =
requiredOrThrow(sharedPreferences.getStringSet(key, defaultValue))
infix fun String.forStringSet(defaultValue: Set<String>): MutableSet<String>? =
requiredOrThrow(sharedPreferences.getStringSet(this, defaultValue))
infix fun String.forInt(defaultValue: Int) =
requiredOrThrow(sharedPreferences.getInt(this, defaultValue))
infix fun String.forLong(defaultValue: Long) =
requiredOrThrow(sharedPreferences.getLong(this, defaultValue))
infix fun String.forFloat(defaultValue: Float) =
requiredOrThrow(sharedPreferences.getFloat(this, defaultValue))
infix fun String.forBoolean(defaultValue: Boolean) =
requiredOrThrow(sharedPreferences.getBoolean(this, defaultValue))
infix fun String.forString(defaultValue: String) : String =
requiredOrThrow(sharedPreferences.getString(this, defaultValue))
operator fun contains(key: String) = requiredOrThrow(sharedPreferences.contains(key))
fun put(key: String, value: String) = also { editor.putString(key, value) }
fun put(key: String, value: Int) = also { editor.putInt(key, value) }
fun put(key: String, value: Long) = also { editor.putLong(key, value) }
fun put(key: String, value: Boolean) = also { editor.putBoolean(key, value) }
fun put(key: String, value: Float) = also { editor.putFloat(key, value) }
fun put(key: String, value: Set<String>) = also { editor.putStringSet(key, value) }
infix fun String.put(value: Any) {
also {
when (value) {
is String ->
put(this, value)
is Int ->
put(this, value)
is Long ->
put(this, value)
is Boolean ->
put(this, value)
is Float ->
put(this, value)
is Set<*> -> {
put(this, value.map { it.toString() }.toSet())
}
}
}
}
fun remove(key: String) = also { editor.remove(key) }
operator fun String.plusAssign(value: Any) = this.put(value)
operator fun plusAssign(keyValuePair: Pair<String, Any>) =
keyValuePair.first.put(keyValuePair.second)
operator fun plus(keyValuePair: Pair<String, Any>) =
keyValuePair.first.put(keyValuePair.second)
operator fun minus(key: String) = remove(key)
fun commit() = editor.commit()
fun apply() = editor.apply()
/**
* Mark in the editor to remove all values from the preferences.
*
* **Please note that this does not call commit neither apply**
*/
fun clear(): SharedPreferences.Editor = editor.clear()
/**
* @param returnIfInitialized object to be returned if class is initialized
* @throws RuntimeException
*/
@Throws(RuntimeException::class)
private fun <T> requiredOrThrow(returnIfInitialized: T) = if (initialized) {
returnIfInitialized
} else {
throw RuntimeException("GlobalSharedPreferences need to be initialized before its usage")
}
}
inline fun prefs(sharedPreferences: GlobalSharedPreferences.() -> Unit) = with(GlobalSharedPreferences) {
also {
sharedPreferences()
apply()
}
} | apache-2.0 | 8eb94a76292d791e3ef02850a6989f5d | 34.902098 | 105 | 0.664134 | 4.860795 | false | false | false | false |
koma-im/koma | src/main/kotlin/koma/controller/requests/membership/invite.kt | 1 | 2340 | package koma.controller.requests.membership
import javafx.geometry.Pos
import javafx.scene.control.*
import javafx.scene.layout.Priority
import koma.gui.view.window.auth.uilaunch
import koma.matrix.room.naming.RoomId
import koma.koma_app.appState.apiClient
import koma.matrix.UserId
import koma.util.getOr
import koma.util.testFailure
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import link.continuum.desktop.gui.VBox
import link.continuum.desktop.gui.add
import link.continuum.desktop.gui.hbox
import link.continuum.desktop.gui.label
import link.continuum.desktop.util.gui.alert
import java.util.*
fun dialogInviteMember(roomId: RoomId) {
val res = dialog_get_member()
if (!res.isPresent) {
return
}
val username = res.get()
val userid = UserId(username)
GlobalScope.launch {
val (s, f, r) = apiClient!!.inviteMember(roomId, userid)
if (r.testFailure(s, f)) {
uilaunch {
val content = f.toString()
alert(Alert.AlertType.ERROR, "failed to invite $userid to $roomId", content)
}
return@launch
}
}
}
private fun dialog_get_member(): Optional<String> {
val dialog = Dialog<String>()
dialog.title = "Send an invitation"
dialog.headerText = "Invite someone to the room"
val inviteButtonType = ButtonType("Ok", ButtonBar.ButtonData.OK_DONE)
dialog.dialogPane.buttonTypes.addAll(inviteButtonType, ButtonType.CANCEL)
val usernamef = TextField()
usernamef.promptText = "e.g. @chris:matrix.org"
dialog.dialogPane.content = VBox(5.0).apply {
VBox.setVgrow(this, Priority.ALWAYS)
hbox(5.0) {
alignment = Pos.CENTER
label("User ID:")
add(usernamef)
}
}
val inviteButton = dialog.dialogPane.lookupButton(inviteButtonType)
inviteButton.isDisable = true
usernamef.textProperty().addListener { _, _, newValue ->
inviteButton.isDisable = newValue.trim().isEmpty()
}
// Convert the result to a username-password-pair when the login button is clicked.
dialog.setResultConverter { dialogButton ->
if (dialogButton === inviteButtonType) {
return@setResultConverter usernamef.getText()
}
null
}
return dialog.showAndWait()
}
| gpl-3.0 | 1f145f351161d9b7e6ee1bfd08c99166 | 29.38961 | 92 | 0.679915 | 4.041451 | false | false | false | false |
sungmin-park/jOOQ-tools | src/main/kotlin/com/github/parksungmin/jooq/tools/Pagination.kt | 1 | 1817 | package com.github.parksungmin.jooq.tools
import org.jooq.Record
import org.jooq.SelectLimitStep
import org.jooq.impl.dslContext
class Pagination<E>(val page: Int, val rows: List<E>, val totalCount: Int, numberOfRowsPerPage: Int, numberOfPagesPerNavigation: Int) {
val navigation: Navigation = Navigation(page, totalCount, numberOfRowsPerPage, numberOfPagesPerNavigation)
companion object {
@JvmStatic
@JvmOverloads
fun <R : Record, E> of(query: SelectLimitStep<R>, page: Int, numberOfRowsPerPage: Int = 10,
numberOfPagesPerNavigation: Int = 10,
mapper: (record: R) -> E): Pagination<E> {
val totalCount = query.dslContext().fetchCount(query)
val rows = query.limit(page * numberOfRowsPerPage, numberOfRowsPerPage).fetch().map(mapper)
return Pagination(page, rows, totalCount, numberOfRowsPerPage, numberOfPagesPerNavigation)
}
}
data class Navigation(val current: Int, val totalCount: Int, val numberOfRowsPerPage: Int, val numberOfPagesPerNavigation: Int) {
val first: Int = 0
// lastPage number inclusive
val last: Int = Math.max(((totalCount / numberOfRowsPerPage) + Math.min(1, totalCount % numberOfRowsPerPage)) - 1, 0)
val next: Int = Math.min(current + 1, last)
val previous: Int = Math.max((current - 1), 0)
val pages: List<Int> = {
val firstOnPages = (current - (current % numberOfPagesPerNavigation))
val lastOnPages = Math.min(firstOnPages + numberOfPagesPerNavigation - 1, last)
(firstOnPages..lastOnPages).toList()
}()
val previousNavigation: Int = Math.max(pages[0] - 1, first)
val nextNavigation: Int = Math.min(pages.last() + 1, last)
}
} | mit | e6b44eac37a84a7bcefaa877b8e29018 | 49.5 | 135 | 0.654926 | 4.177011 | false | false | false | false |
dscoppelletti/spaceship | lib/src/main/kotlin/it/scoppelletti/spaceship/widget/CardViewItemDecoration.kt | 1 | 2683 | /*
* Copyright (C) 2015 Dario Scoppelletti, <http://www.scoppelletti.it/>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("JoinDeclarationAndAssignment", "RedundantVisibilityModifier")
package it.scoppelletti.spaceship.widget
import android.content.Context
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import it.scoppelletti.spaceship.R
/**
* Inserts the margins around the `CardView` items in a `LinearLayoutManager`
* list. It supports both `HORIZONTAL` and `VERTICAL` orientations.
*
* @since 1.0.0
*
* @property orientation Can be either `LinearLayoutManager.HORIZONTAL` or
* `LinearLayoutManager.VERTICAL`.
*
* @constructor Constructor.
* @param ctx Context.
*/
@Suppress("unused")
public class CardViewItemDecoration(
ctx: Context,
private val orientation: Int
) : RecyclerView.ItemDecoration() {
private val marginHorz: Int
private val marginVert: Int
init {
marginHorz = ctx.resources.getDimensionPixelOffset(
R.dimen.it_scoppelletti_marginHorz)
marginVert = ctx.resources.getDimensionPixelOffset(
R.dimen.it_scoppelletti_spacingVert)
}
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
outRect.left = marginHorz
outRect.bottom = marginVert
when (orientation) {
LinearLayoutManager.HORIZONTAL -> {
val pos = parent.getChildAdapterPosition(view)
outRect.right = if (pos == 0) marginHorz else 0
outRect.top = marginVert
}
LinearLayoutManager.VERTICAL -> {
val pos = parent.getChildAdapterPosition(view)
outRect.right = marginHorz
outRect.top = if (pos == 0) marginVert else 0
}
else -> {
outRect.right = marginHorz
outRect.top = marginVert
}
}
}
}
| apache-2.0 | bb3bd88dda75e54f55d428cb3f4a62df | 30.564706 | 77 | 0.652628 | 4.666087 | false | false | false | false |
Adven27/Exam | exam-core/src/main/java/io/github/adven27/concordion/extensions/exam/core/AbstractSpecs.kt | 1 | 2284 | package io.github.adven27.concordion.extensions.exam.core
import org.concordion.api.AfterSuite
import org.concordion.api.BeforeSuite
import org.concordion.api.ConcordionResources
import org.concordion.api.extension.Extension
import org.concordion.api.option.ConcordionOptions
import org.concordion.api.option.MarkdownExtensions.AUTOLINKS
import org.concordion.api.option.MarkdownExtensions.DEFINITIONS
import org.concordion.api.option.MarkdownExtensions.FENCED_CODE_BLOCKS
import org.concordion.api.option.MarkdownExtensions.FORCELISTITEMPARA
import org.concordion.api.option.MarkdownExtensions.TASKLISTITEMS
import org.concordion.api.option.MarkdownExtensions.WIKILINKS
import org.concordion.integration.junit4.ConcordionRunner
import org.junit.runner.RunWith
@Suppress("unused")
@RunWith(ConcordionRunner::class)
@ConcordionOptions(
markdownExtensions = [WIKILINKS, AUTOLINKS, FENCED_CODE_BLOCKS, DEFINITIONS, FORCELISTITEMPARA, TASKLISTITEMS],
declareNamespaces = ["c", "http://www.concordion.org/2007/concordion", "e", ExamExtension.NS]
)
@ConcordionResources(includeDefaultStyling = false)
abstract class AbstractSpecs {
@Extension
private val exam = if (EXAM == null) this.init().also { EXAM = it } else EXAM
@BeforeSuite
fun specsSetUp() {
beforeSetUp()
EXAM!!.setUp()
beforeSutStart()
if (SPECS_SUT_START) {
startSut()
}
}
@AfterSuite
fun specsTearDown() {
if (SPECS_SUT_START) {
stopSut()
}
afterSutStop()
EXAM!!.tearDown()
afterTearDown()
}
protected abstract fun init(): ExamExtension
protected open fun beforeSetUp() = Unit
protected open fun beforeSutStart() = Unit
protected abstract fun startSut()
protected abstract fun stopSut()
protected open fun afterSutStop() = Unit
protected open fun afterTearDown() = Unit
fun addToMap(old: Map<String, String>?, name: String, value: String) = mapOf(name to value) + (old ?: emptyMap())
companion object {
const val PROP_SPECS_SUT_START = "SPECS_SUT_START"
@JvmField
val SPECS_SUT_START: Boolean = System.getProperty(PROP_SPECS_SUT_START, "true").toBoolean()
private var EXAM: ExamExtension? = null
}
}
| mit | a547d0a84ef2258d86fa27c41084f8d2 | 33.606061 | 117 | 0.721541 | 3.858108 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-block-logging-bukkit/src/main/kotlin/com/rpkit/blocklog/bukkit/listener/BlockBreakListener.kt | 1 | 2500 | /*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.blocklog.bukkit.listener
import com.rpkit.blocklog.bukkit.RPKBlockLoggingBukkit
import com.rpkit.blocklog.bukkit.block.RPKBlockChangeImpl
import com.rpkit.blocklog.bukkit.block.RPKBlockHistoryProvider
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import com.rpkit.players.bukkit.profile.RPKProfile
import org.bukkit.Material
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority.MONITOR
import org.bukkit.event.Listener
import org.bukkit.event.block.BlockBreakEvent
class BlockBreakListener(private val plugin: RPKBlockLoggingBukkit): Listener {
@EventHandler(priority = MONITOR)
fun onBlockBreak(event: BlockBreakEvent) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val blockHistoryProvider = plugin.core.serviceManager.getServiceProvider(RPKBlockHistoryProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(event.player)
val profile = minecraftProfile?.profile as? RPKProfile
val character = if (minecraftProfile == null) null else characterProvider.getActiveCharacter(minecraftProfile)
val blockHistory = blockHistoryProvider.getBlockHistory(event.block)
val blockChange = RPKBlockChangeImpl(
blockHistory = blockHistory,
time = System.currentTimeMillis(),
profile = profile,
minecraftProfile = minecraftProfile,
character = character,
from = event.block.type,
to = Material.AIR,
reason = "BREAK"
)
blockHistoryProvider.addBlockChange(blockChange)
}
} | apache-2.0 | fe1d21effa775aabd5c23159dc23fd35 | 43.660714 | 120 | 0.7496 | 5 | false | false | false | false |
BILLyTheLiTTle/KotlinExperiments | src/main/kotlin/coroutines/Cancellation.kt | 1 | 1341 | package coroutines
import kotlinx.coroutines.*
fun main(args: Array<String>) {
val job = Job()
val scope = CoroutineScope(Dispatchers.Default + job)
val job1 = doAJob(scope)
val job2 = doOtherJob(scope)
//job.cancel() // Cancels the parent job --> doAnotherJob() below is cancelled before ever started
job.cancelChildren() // Cancels the children jobs but not the parent job --> doAnotherJob() below is running normally
println("-- Main Job status --\nActive: ${job.isActive}\nCancelled: ${job.isCancelled}\nCompleted: ${job.isCompleted}\n")
println("-- Job 1 status --\nActive: ${job1.isActive}\nCancelled: ${job1.isCancelled}\nCompleted: ${job1.isCompleted}\n")
println("-- Job 2 status--\nActive: ${job2.isActive}\nCancelled: ${job2.isCancelled}\nCompleted: ${job2.isCompleted}\n")
val job3 = doAnotherJob(scope)
println("-- Job 3 status--\nActive: ${job3.isActive}\nCancelled: ${job3.isCancelled}\nCompleted: ${job3.isCompleted}\n")
Thread.sleep(100)
}
private fun doAJob(scope: CoroutineScope) = scope.launch { println("I am doing a job"); delay(2000) }
private fun doOtherJob(scope: CoroutineScope) = scope.launch { println("I am doing other job"); delay(2000) }
private fun doAnotherJob(scope: CoroutineScope) = scope.launch { println("I am doing another job"); delay(2000) } | gpl-3.0 | c8bde3de3968e16819e82e3e57af70ba | 43.733333 | 125 | 0.705444 | 3.725 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-core-bukkit/src/main/kotlin/com/rpkit/core/bukkit/servlet/StaticServlet.kt | 1 | 2392 | /*
* Copyright 2019 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.core.bukkit.servlet
import com.rpkit.core.bukkit.RPKCoreBukkit
import com.rpkit.core.web.RPKServlet
import org.apache.velocity.VelocityContext
import org.apache.velocity.app.Velocity
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletResponse.SC_NOT_FOUND
import javax.servlet.http.HttpServletResponse.SC_OK
/**
* Servlet for serving static content.
* One may be required for each individual plugin's static content,
*/
class StaticServlet(private val plugin: RPKCoreBukkit): RPKServlet() {
override val url = "/static/*"
override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
val resource = javaClass.getResourceAsStream("/web/static${req.pathInfo}")
if (resource != null) {
resp.status = SC_OK
val builder = StringBuilder()
val scanner = Scanner(resource)
while (scanner.hasNextLine()) {
builder.append(scanner.nextLine()).append('\n')
}
resp.writer.println(builder.toString())
} else {
resp.status = SC_NOT_FOUND
val templateBuilder = StringBuilder()
val scanner = Scanner(javaClass.getResourceAsStream("/web/404.html"))
while (scanner.hasNextLine()) {
templateBuilder.append(scanner.nextLine()).append('\n')
}
scanner.close()
val velocityContext = VelocityContext()
velocityContext.put("server", plugin.core.web.title)
velocityContext.put("navigationBar", plugin.core.web.navigationBar)
Velocity.evaluate(velocityContext, resp.writer, "/web/404.html", templateBuilder.toString())
}
}
} | apache-2.0 | 76117ae669118a545f0412010d57963d | 37.596774 | 104 | 0.685619 | 4.530303 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/gene/collection/PairGene.kt | 1 | 4590 | package org.evomaster.core.search.gene.collection
import org.evomaster.core.output.OutputFormat
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.string.StringGene
import org.evomaster.core.search.gene.root.CompositeFixedGene
import org.evomaster.core.search.gene.utils.GeneUtils
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo
import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy
/**
* handling pair type or Map.Entry type
*/
class PairGene<F,S>(
name: String,
val first: F,
val second : S,
/**
*
* whether the [first] is mutable
*/
val isFirstMutable : Boolean = true //TODO shouldn't be first.isMutable()?
): CompositeFixedGene(name, listOf(first, second)) where F: Gene, S: Gene {
companion object{
/**
* create simple pair gene based on [gene]
* first is a StringGene and its name is based on the name of [gene]
* second is [gene]
* @param gene is the second of the pair
* @param isFixedFirst specifies whether the first is fixed value.
*/
fun <T: Gene> createStringPairGene(gene: T, isFixedFirst: Boolean = false) : PairGene<StringGene, T> {
val key = StringGene(gene.name)
if (isFixedFirst)
key.value = gene.name
return PairGene(gene.name, key, gene, isFirstMutable = !isFixedFirst)
}
}
override fun isLocallyValid() : Boolean{
return getViewOfChildren().all { it.isLocallyValid() }
}
override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) {
if(first.isMutable()) {
first.randomize(randomness, tryToForceNewValue)
}
if(second.isMutable()) {
second.randomize(randomness, tryToForceNewValue)
}
}
override fun getValueAsPrintableString(previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean): String {
return "${first.getValueAsPrintableString(targetFormat = targetFormat)}:${second.getValueAsPrintableString(targetFormat = targetFormat)}"
}
override fun copyValueFrom(other: Gene) {
if (other !is PairGene<*, *>) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
first.copyValueFrom(other.first)
second.copyValueFrom(other.second)
}
override fun containsSameValueAs(other: Gene): Boolean {
if (other !is PairGene<*, *>) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
return first.containsSameValueAs(other.first) && second.containsSameValueAs(other.second)
}
override fun bindValueBasedOn(gene: Gene): Boolean {
if (gene !is PairGene<*, *>) {
throw IllegalArgumentException("Invalid gene type ${gene.javaClass}")
}
return first.bindValueBasedOn(gene.first) && second.bindValueBasedOn(gene.second)
}
override fun copyContent(): Gene {
return PairGene(name, first.copy(), second.copy(), isFirstMutable)
}
override fun isMutable(): Boolean {
/*
Can be tricky... assume a first that is mutable, but we do not want to change it.
we still need to initialize with randomize, otherwise its constraints might fail
*/
return (first.isMutable() && (isFirstMutable || !first.initialized)) || second.isMutable()
}
override fun isPrintable(): Boolean {
return first.isPrintable() && second.isPrintable()
}
override fun mutablePhenotypeChildren(): List<Gene> {
/*
FIXME what is the role of isFirstMutable???
couldn't had used a DisruptiveGene instead?
*/
val list = mutableListOf<Gene>()
if (first.isMutable() && isFirstMutable)
list.add(first)
if (second.isMutable())
list.add(second)
return list
}
override fun mutationWeight(): Double {
return (if (isFirstMutable) first.mutationWeight() else 0.0) + second.mutationWeight()
}
override fun customShouldApplyShallowMutation(
randomness: Randomness,
selectionStrategy: SubsetGeneMutationSelectionStrategy,
enableAdaptiveGeneMutation: Boolean,
additionalGeneMutationInfo: AdditionalGeneMutationInfo?
): Boolean {
return false
}
} | lgpl-3.0 | a64b734f6560b2fb0a06ceded618d48a | 34.045802 | 158 | 0.655556 | 4.872611 | false | false | false | false |
Litote/kmongo | kmongo-serialization-mapping/src/main/kotlin/SerializationClassMappingTypeService.kt | 1 | 5288 | /*
* Copyright (C) 2016/2022 Litote
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.litote.kmongo.serialization
import kotlinx.serialization.SerialName
import org.bson.BsonDocument
import org.bson.BsonDocumentWriter
import org.bson.codecs.Codec
import org.bson.codecs.EncoderContext
import org.bson.codecs.configuration.CodecRegistry
import org.bson.json.JsonMode
import org.bson.json.JsonWriter
import org.bson.json.JsonWriterSettings
import org.litote.kmongo.id.MongoId
import org.litote.kmongo.id.MongoProperty
import org.litote.kmongo.service.ClassMappingTypeService
import org.litote.kmongo.util.ObjectMappingConfiguration
import java.io.StringWriter
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
import kotlin.reflect.KProperty1
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.hasAnnotation
private class BaseRegistryWithoutCustomSerializers(private val codecRegistry: CodecRegistry) : CodecRegistry {
override fun <T : Any> get(clazz: Class<T>): Codec<T>? =
if (customSerializersMap.containsKey(clazz.kotlin)) null else codecRegistry.get(clazz)
override fun <T : Any> get(clazz: Class<T>, registry: CodecRegistry): Codec<T>? =
if (customSerializersMap.containsKey(clazz.kotlin)) null else codecRegistry.get(clazz, registry)
}
/**
* kotlinx serialization ClassMapping.
*/
class SerializationClassMappingTypeService : ClassMappingTypeService {
override fun priority(): Int = 200
@Volatile
private lateinit var codecRegistryWithNonEncodeNull: CodecRegistry
@Volatile
private lateinit var codecRegistryWithEncodeNull: CodecRegistry
override fun filterIdToBson(obj: Any, filterNullProperties: Boolean): BsonDocument {
val doc = BsonDocument()
val writer = BsonDocumentWriter(doc)
(if (filterNullProperties) codecRegistryWithNonEncodeNull else codecRegistryWithEncodeNull)
.get(obj.javaClass).encode(writer, obj, EncoderContext.builder().build())
writer.flush()
doc.remove("_id")
return doc
}
override fun toExtendedJson(obj: Any?): String {
return if (obj == null) {
"null"
} else {
val writer = StringWriter()
val jsonWriter = JsonWriter(
writer,
JsonWriterSettings
.builder()
.indent(false)
.outputMode(JsonMode.RELAXED)
.build()
)
//create a fake document to bypass bson writer built-in checks
jsonWriter.writeStartDocument()
jsonWriter.writeName("tmp")
codecRegistryWithNonEncodeNull.get(obj.javaClass).encode(jsonWriter, obj, EncoderContext.builder().build())
jsonWriter.writeEndDocument()
writer.toString().run {
substring("{ \"tmp\":".length, length - "}".length).trim()
}
}
}
override fun findIdProperty(type: KClass<*>): KProperty1<*, *>? = idController.findIdProperty(type)
override fun <T, R> getIdValue(idProperty: KProperty1<T, R>, instance: T): R? =
idController.getIdValue(idProperty, instance)
override fun coreCodecRegistry(baseCodecRegistry: CodecRegistry): CodecRegistry {
val withNonEncodeNull = SerializationCodecRegistry(configuration.copy(nonEncodeNull = true))
codecRegistryWithNonEncodeNull =
codecRegistryWithCustomCodecs(
filterBaseCodecRegistry(baseCodecRegistry),
withNonEncodeNull
)
val withEncodeNull = SerializationCodecRegistry(configuration.copy(nonEncodeNull = false))
codecRegistryWithEncodeNull = codecRegistryWithCustomCodecs(
filterBaseCodecRegistry(baseCodecRegistry),
withEncodeNull
)
return object : CodecRegistry {
override fun <T : Any> get(clazz: Class<T>): Codec<T> =
if (ObjectMappingConfiguration.serializeNull) withEncodeNull.get(clazz)
else withNonEncodeNull.get(clazz)
override fun <T : Any> get(clazz: Class<T>, registry: CodecRegistry): Codec<T> =
if (ObjectMappingConfiguration.serializeNull) withEncodeNull.get(clazz, registry)
else withNonEncodeNull.get(clazz, registry)
}
}
override fun filterBaseCodecRegistry(baseCodecRegistry: CodecRegistry): CodecRegistry =
BaseRegistryWithoutCustomSerializers(baseCodecRegistry)
override fun <T> calculatePath(property: KProperty<T>): String =
property.findAnnotation<SerialName>()?.value
?: (if (property.hasAnnotation<MongoId>()) "_id" else property.findAnnotation<MongoProperty>()?.value)
?: property.name
} | apache-2.0 | 267dcb1d8053534e531ebe506417c78e | 39.068182 | 119 | 0.695348 | 4.700444 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/rest/resource/ResourceImpactOfIndividual.kt | 1 | 7315 | package org.evomaster.core.problem.rest.resource
import org.evomaster.core.database.DbAction
import org.evomaster.core.problem.rest.RestIndividual
import org.evomaster.core.search.FitnessValue
import org.evomaster.core.search.impact.impactinfocollection.ActionStructureImpact
import org.evomaster.core.search.impact.impactinfocollection.ImpactsOfAction
import org.evomaster.core.search.impact.impactinfocollection.ImpactsOfIndividual
import org.evomaster.core.search.impact.impactinfocollection.InitializationActionImpacts
import org.evomaster.core.search.impact.impactinfocollection.value.numeric.IntegerGeneImpact
/**
* created by manzhang on 2021/10/21
*/
class ResourceImpactOfIndividual : ImpactsOfIndividual {
/**
* impact of changing size of the resource in the individual
* key - a name of resource, i.e., path
* value - impact
*/
val resourceSizeImpact: MutableMap<String, IntegerGeneImpact>
/**
* impact of changing size of any resource in the individual
*/
val anyResourceSizeImpact : IntegerGeneImpact
/**
* impact of changing size of the table in the initialization of individual.
* note that here we do not consider the table in resource handling,
* since those could be handled by [resourceSizeImpact]
* key - a name of table
* value - impact
*/
val sqlTableSizeImpact: MutableMap<String, IntegerGeneImpact>
/**
* impact of changing size of any sql in the individual
*/
val anySqlTableSizeImpact : IntegerGeneImpact
constructor(
initActionImpacts: InitializationActionImpacts,
fixedMainActionImpacts: MutableList<ImpactsOfAction>,
dynamicMainActionImpacts: MutableList<ImpactsOfAction>,
impactsOfStructure: ActionStructureImpact = ActionStructureImpact("StructureSize"),
resourceSizeImpact: MutableMap<String, IntegerGeneImpact>,
sqlTableImpact: MutableMap<String, IntegerGeneImpact>,
anyResourceSizeImpact: IntegerGeneImpact,
anySqlTableSizeImpact: IntegerGeneImpact
) : super(initActionImpacts, fixedMainActionImpacts, dynamicMainActionImpacts, impactsOfStructure) {
this.resourceSizeImpact = resourceSizeImpact
this.sqlTableSizeImpact = sqlTableImpact
this.anyResourceSizeImpact = anyResourceSizeImpact
this.anySqlTableSizeImpact = anySqlTableSizeImpact
}
constructor(individual: RestIndividual, abstractInitializationGeneToMutate: Boolean, fitnessValue: FitnessValue?)
: super(individual, abstractInitializationGeneToMutate, fitnessValue) {
resourceSizeImpact = mutableMapOf<String, IntegerGeneImpact>().apply {
individual.seeResource(RestIndividual.ResourceFilter.ALL).forEach { r->
putIfAbsent(r, IntegerGeneImpact("size"))
}
}
sqlTableSizeImpact = mutableMapOf<String, IntegerGeneImpact>().apply {
individual.seeInitializingActions().filterIsInstance<DbAction>().filterNot { it.representExistingData }.forEach { d->
putIfAbsent(d.table.name, IntegerGeneImpact("size"))
}
}
anyResourceSizeImpact = IntegerGeneImpact("anyResourceSizeImpact")
anySqlTableSizeImpact = IntegerGeneImpact("anySqlTableSizeImpact")
}
/**
* @return a copy of [this]
*/
override fun copy(): ResourceImpactOfIndividual {
return ResourceImpactOfIndividual(
initActionImpacts.copy(),
fixedMainActionImpacts.map { it.copy() }.toMutableList(),
dynamicMainActionImpacts.map { it.copy() }.toMutableList(),
impactsOfStructure.copy(),
mutableMapOf<String, IntegerGeneImpact>().apply {
putAll(resourceSizeImpact.map { it.key to it.value.copy() })
},
mutableMapOf<String, IntegerGeneImpact>().apply {
putAll(sqlTableSizeImpact.map { it.key to it.value.copy() })
},
anyResourceSizeImpact.copy(),
anySqlTableSizeImpact.copy()
)
}
/**
* @return a clone of [this]
*/
override fun clone(): ResourceImpactOfIndividual {
return ResourceImpactOfIndividual(
initActionImpacts.clone(),
fixedMainActionImpacts.map { it.clone() }.toMutableList(),
dynamicMainActionImpacts.map { it.clone() }.toMutableList(),
impactsOfStructure.clone(),
mutableMapOf<String, IntegerGeneImpact>().apply {
putAll(resourceSizeImpact.map { it.key to it.value.clone() })
},
mutableMapOf<String, IntegerGeneImpact>().apply {
putAll(sqlTableSizeImpact.map { it.key to it.value.clone() })
},
anyResourceSizeImpact.clone(),
anySqlTableSizeImpact.clone()
)
}
/**
* count an impact of changing resource size
*/
fun countResourceSizeImpact(previous: RestIndividual, current: RestIndividual, noImpactTargets: Set<Int>, impactTargets: Set<Int>, improvedTargets: Set<Int>, onlyManipulation: Boolean = false) {
val currentRs = current.seeResource(RestIndividual.ResourceFilter.ALL)
val previousRs = previous.seeResource(RestIndividual.ResourceFilter.ALL)
var anyResourceChange = false
currentRs.toSet().forEach { cr ->
val rImpact = resourceSizeImpact.getOrPut(cr){IntegerGeneImpact("size")}
if (currentRs.count { it == cr } != previousRs.count { it == cr }) {
if (!anyResourceChange){
anyResourceSizeImpact.countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = 1)
anyResourceChange = true
}
rImpact.countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = 1)
}
}
val currentTs = current.seeInitializingActions().filterIsInstance<DbAction>().filterNot { it.representExistingData }.map { it.table.name }
val previousTs = previous.seeInitializingActions().filterIsInstance<DbAction>().filterNot { it.representExistingData }.map { it.table.name }
var anySqlChange = false
currentTs.toSet().forEach { cr ->
val tImpact = sqlTableSizeImpact.getOrPut(cr){IntegerGeneImpact("size")}
if (currentTs.count { it == cr } != previousTs.count { it == cr }) {
if (!anySqlChange){
anySqlTableSizeImpact.countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = 1)
anySqlChange = true
}
tImpact.countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = 1)
}
}
// shall I remove impacts of deleted resources or table?
}
} | lgpl-3.0 | a95d1600a6b095b77ec7fb1018e7ceee | 48.100671 | 214 | 0.674641 | 5.144163 | false | false | false | false |
ibinti/intellij-community | platform/lang-impl/src/com/intellij/ide/projectView/impl/ModuleGroupingTreeHelper.kt | 9 | 10922 | /*
* 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.
*/
/*
* 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.ide.projectView.impl
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleGrouper
import com.intellij.openapi.util.Pair
import com.intellij.util.ui.tree.TreeUtil
import org.jetbrains.annotations.TestOnly
import java.util.*
import javax.swing.JTree
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.DefaultTreeModel
import javax.swing.tree.MutableTreeNode
import javax.swing.tree.TreeNode
/**
* Provides methods to build trees where nodes are grouped by modules (and optionally by module groups). Type parameter M specified class
* of modules (may be [Module] if real modules are shown, or [com.intellij.openapi.module.ModuleDescription] if loaded and unloaded modules are shown.
*
* @author nik
*/
class ModuleGroupingTreeHelper<M: Any, N: MutableTreeNode> private constructor(
private val groupingEnabled: Boolean,
private val grouping: ModuleGroupingImplementation<M>,
private val moduleGroupNodeFactory: (ModuleGroup) -> N,
private val moduleNodeFactory: (M) -> N,
private val nodeComparator: Comparator<in N>
) {
private val nodeForGroup = HashMap<ModuleGroup, N>()
private val nodeData = HashMap<N, ModuleTreeNodeData<M>>()
companion object {
@JvmStatic
fun <M: Any, N : MutableTreeNode> forEmptyTree(groupingEnabled: Boolean, grouping: ModuleGroupingImplementation<M>,
moduleGroupNodeFactory: (ModuleGroup) -> N, moduleNodeFactory: (M) -> N,
nodeComparator: Comparator<in N>) =
ModuleGroupingTreeHelper(groupingEnabled, grouping, moduleGroupNodeFactory, moduleNodeFactory, nodeComparator)
@JvmStatic
fun <M: Any, N : MutableTreeNode> forTree(rootNode: N, moduleGroupByNode: (N) -> ModuleGroup?, moduleByNode: (N) -> M?,
groupingEnabled: Boolean, grouping: ModuleGroupingImplementation<M>,
moduleGroupNodeFactory: (ModuleGroup) -> N, moduleNodeFactory: (M) -> N,
nodeComparator: Comparator<in N>): ModuleGroupingTreeHelper<M, N> {
val helper = ModuleGroupingTreeHelper(groupingEnabled, grouping, moduleGroupNodeFactory, moduleNodeFactory, nodeComparator)
TreeUtil.traverse(rootNode) { node ->
@Suppress("UNCHECKED_CAST")
val group = moduleGroupByNode(node as N)
val module = moduleByNode(node)
if (group != null) {
helper.nodeForGroup[group] = node
}
if (group != null || module != null) {
helper.nodeData[node] = ModuleTreeNodeData(module, group)
}
true
}
return helper
}
@JvmStatic
fun createDefaultGrouping(grouper: ModuleGrouper) = object : ModuleGroupingImplementation<Module> {
override fun getGroupPath(m: Module) = grouper.getGroupPath(m)
override fun getModuleAsGroupPath(m: Module) = grouper.getModuleAsGroupPath(m)
}
}
fun createModuleNodes(modules: Collection<M>, rootNode: N, model: DefaultTreeModel): List<N> {
val nodes = modules.map { createModuleNode(it, rootNode, model, true) }
TreeUtil.sortRecursively(rootNode, nodeComparator)
model.nodeStructureChanged(rootNode)
return nodes
}
fun createModuleNode(module: M, rootNode: N, model: DefaultTreeModel): N {
return createModuleNode(module, rootNode, model, false)
}
private fun createModuleNode(module: M, rootNode: N, model: DefaultTreeModel, bulkOperation: Boolean): N {
val group = ModuleGroup(grouping.getGroupPath(module))
val parentNode = getOrCreateNodeForModuleGroup(group, rootNode, model, bulkOperation)
val moduleNode = moduleNodeFactory(module)
insertModuleNode(moduleNode, parentNode, module, model, bulkOperation)
return moduleNode
}
/**
* If [bulkOperation] is true, no events will be fired and new node will be added into arbitrary place in the children list
*/
private fun insertModuleNode(moduleNode: N, parentNode: N, module: M, model: DefaultTreeModel, bulkOperation: Boolean) {
val moduleAsGroup = moduleAsGroup(module)
if (moduleAsGroup != null) {
val oldModuleGroupNode = nodeForGroup[moduleAsGroup]
if (oldModuleGroupNode != null) {
moveChildren(oldModuleGroupNode, moduleNode, model)
model.removeNodeFromParent(oldModuleGroupNode)
removeNodeData(oldModuleGroupNode)
}
nodeForGroup[moduleAsGroup] = moduleNode
nodeData[moduleNode] = ModuleTreeNodeData(module, moduleAsGroup)
}
else {
nodeData[moduleNode] = ModuleTreeNodeData(module, null)
}
insertNode(moduleNode, parentNode, model, bulkOperation)
}
private fun moduleAsGroup(module: M) = grouping.getModuleAsGroupPath(module)?.let(::ModuleGroup)
private fun moveChildren(fromNode: N, toNode: N, model: DefaultTreeModel) {
val children = TreeUtil.listChildren(fromNode)
moveChildren(children, toNode, model)
}
private fun moveChildren(children: List<TreeNode>, toNode: N, model: DefaultTreeModel) {
TreeUtil.addChildrenTo(toNode, children)
TreeUtil.sortChildren(toNode, nodeComparator)
model.nodeStructureChanged(toNode)
}
/**
* If [bulkOperation] is true, no events will be fired and new node will be added into arbitrary place in the children list
*/
private fun getOrCreateNodeForModuleGroup(group: ModuleGroup, rootNode: N, model: DefaultTreeModel, bulkOperation: Boolean): N {
if (!groupingEnabled) return rootNode
var parentNode = rootNode
val path = group.groupPathList
for (i in path.indices) {
val current = ModuleGroup(path.subList(0, i+1))
var node = nodeForGroup[current]
if (node == null) {
node = moduleGroupNodeFactory(current)
insertNode(node, parentNode, model, bulkOperation)
nodeForGroup[current] = node
nodeData[node] = ModuleTreeNodeData<M>(null,group)
}
parentNode = node
}
return parentNode
}
private fun insertNode(node: N, parentNode: N, model: DefaultTreeModel, bulkOperation: Boolean) {
if (bulkOperation) {
parentNode.insert(node, parentNode.childCount)
}
else {
TreeUtil.insertNode(node, parentNode, model, nodeComparator)
}
}
fun moveAllModuleNodesToProperGroups(rootNode: N, model: DefaultTreeModel) {
val modules = nodeData.values.map { it.module }.filterNotNull()
nodeData.keys.forEach { it.removeFromParent() }
nodeData.clear()
nodeForGroup.clear()
createModuleNodes(modules, rootNode, model)
}
fun moveModuleNodesToProperGroup(nodes: List<Pair<N, M>>, rootNode: N, model: DefaultTreeModel, tree: JTree) {
nodes.forEach {
moveModuleNodeToProperGroup(it.first, it.second, rootNode, model, tree)
}
}
fun moveModuleNodeToProperGroup(node: N, module: M, rootNode: N, model: DefaultTreeModel, tree: JTree): N {
val actualGroup = ModuleGroup(grouping.getGroupPath(module))
val parent = node.parent
val nodeAsGroup = nodeData[node]?.group
val expectedParent = if (groupingEnabled && !actualGroup.groupPathList.isEmpty()) nodeForGroup[actualGroup] else rootNode
if (expectedParent == parent && nodeAsGroup == moduleAsGroup(module)) {
return node
}
val selectionPath = tree.selectionPath
val wasSelected = selectionPath?.lastPathComponent == node
removeNode(node, rootNode, model)
val newParent = getOrCreateNodeForModuleGroup(actualGroup, rootNode, model, false)
val newNode = moduleNodeFactory(module)
insertModuleNode(newNode, newParent, module, model, false)
if (wasSelected) {
tree.expandPath(TreeUtil.getPath(rootNode, newParent))
tree.selectionPath = TreeUtil.getPath(rootNode, newNode)
}
return newNode
}
fun removeNode(node: N, rootNode: N, model: DefaultTreeModel) {
val parent = node.parent
val nodeAsGroup = nodeData[node]?.group
model.removeNodeFromParent(node)
removeNodeData(node)
if (nodeAsGroup != null) {
val childrenToKeep = TreeUtil.listChildren(node).filter { it in nodeData }
if (childrenToKeep.isNotEmpty()) {
val newGroupNode = getOrCreateNodeForModuleGroup(nodeAsGroup, rootNode, model, false)
moveChildren(childrenToKeep, newGroupNode, model)
}
}
removeEmptySyntheticModuleGroupNodes(parent, model)
}
private fun removeEmptySyntheticModuleGroupNodes(parentNode: TreeNode?, model: DefaultTreeModel) {
var parent = parentNode
while (parent is MutableTreeNode && parent in nodeData && nodeData[parent]?.module == null && parent.childCount == 0) {
val grandParent = parent.parent
model.removeNodeFromParent(parent)
@Suppress("UNCHECKED_CAST")
removeNodeData(parent as N)
parent = grandParent
}
}
private fun removeNodeData(node: N) {
val group = nodeData.remove(node)?.group
if (group != null) {
nodeForGroup.remove(group)
}
}
fun removeAllNodes(root: DefaultMutableTreeNode, model: DefaultTreeModel) {
nodeData.clear()
nodeForGroup.clear()
root.removeAllChildren()
model.nodeStructureChanged(root)
}
@TestOnly
fun getNodeForGroupMap() = Collections.unmodifiableMap(nodeForGroup)
@TestOnly
fun getModuleByNodeMap() = nodeData.mapValues { it.value.module }.filterValues { it != null }
@TestOnly
fun getGroupByNodeMap() = nodeData.mapValues { it.value.group }.filterValues { it != null }
}
private class ModuleTreeNodeData<M>(val module: M?, val group: ModuleGroup?)
interface ModuleGroupingImplementation<M: Any> {
fun getGroupPath(m: M): List<String>
fun getModuleAsGroupPath(m: M): List<String>?
} | apache-2.0 | 5f03617e57f9d9d8d971a05b05f1f93f | 38.576087 | 150 | 0.710401 | 4.438033 | false | false | false | false |
mpranj/libelektra | src/bindings/jna/libelektra-kotlin/src/main/kotlin/org/libelektra/keySetExt/KeySetSerializationExt.kt | 2 | 1799 | package org.libelektra.keySetExt
import kotlinx.serialization.SerializationException
import org.libelektra.KeySet
import org.libelektra.keySetExt.serialformat.KeySetFormat
/**
* Converts a KeySet to a Kotlin data class using Kotlin Json Serialization with support for Collections
*
* The data class must be annotated with @Serializable
*
* The KeySet must contain all properties of the data class either on the root-level or one level below the root-level
*
* Simple Example:
*
* data class User(val username: String, val password: String)
*
* KeySet (<keyName> to <value>):
* /username to "jane"
* /password to "1234"
*
* keySet.convert<User>()
* // User(username = "jane", password = "1234")
*
* Example with below root level:
*
* KeySet (<keyName> to <value>):
* /user/username to "jane"
* /user/password to "1234"
*
* keySet.convert<User>()
* // User(username = "jane", password = "1234")
*
* Example with nesting:
*
* data class Employee(val user: User, val salary: Double)
*
* KeySet (<keyName> to <value>):
* /user/username to "jane"
* /user/password to "1234"
* /salary to "4321.0"
*
* keySet.convert<Employee>()
* // Employee(user = User(username = "jane", password = "1234"), salary = 4321.0)
*
* @param parentKey starting point for serialization of this KeySet, only keys below this key are considered for serialization
* @throws SerializationException when decoding fails or the properties are not on root-level or one below root
* @return an object decoded from this KeySet (see [KeySetFormat.decodeFromKeySet]])
*/
inline fun <reified T : Any> KeySet.convert(parentKey: String? = null): T {
return KeySetFormat.decodeFromKeySet(this, parentKey)
}
| bsd-3-clause | deb46b5c1366e97585b7f10300f13c47 | 33.596154 | 126 | 0.677599 | 3.555336 | false | false | false | false |
google/private-compute-libraries | java/com/google/android/libraries/pcc/chronicle/storage/datacache/DataCacheReader.kt | 1 | 2543 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.storage.datacache
import com.google.android.libraries.pcc.chronicle.api.ReadConnection
import com.google.android.libraries.pcc.chronicle.api.storage.WrappedEntity
import com.google.android.libraries.pcc.chronicle.api.storage.toInstant
import java.time.Instant
/** The chronicle default reader interface for [DataCache]. */
interface DataCacheReader<T> : ReadConnection {
fun all(): List<T>
/**
* Returns a list of [Timestamped<T>] for all stored labels, ordered by update timestamp from
* latest to earliest.
*/
fun allTimestamped(): List<Timestamped<T>>
fun forEntity(entityId: String): T?
/** Returns a [Timestamped<T>] for stored label instance indexed by [entityId] */
fun forEntityTimestamped(entityId: String): Timestamped<T>?
companion object {
/** Wraps the provided [TypedDataCache] with a [DataCacheReader] connection. */
fun <T> createDefault(cache: TypedDataCacheReader<T>): DataCacheReader<T> {
return object : DataCacheReader<T> {
override fun all(): List<T> = cache.all().map { it.entity }
override fun allTimestamped(): List<Timestamped<T>> =
cache
.all()
.asSequence()
.map { it.asTimestampedInstance() }
.sortedBy { it.updateTimestamp }
.toList()
override fun forEntity(entityId: String): T? = cache.get(entityId)?.entity
override fun forEntityTimestamped(entityId: String): Timestamped<T>? =
cache.get(entityId)?.asTimestampedInstance()
}
}
}
}
/** A wrapper class for a label instance with its last updated time in the storage. */
data class Timestamped<T>(val instance: T, val updateTimestamp: Instant)
/** Helper function to convert a [WrappedEntity] to a [Timestamped] instance. */
fun <T> WrappedEntity<T>.asTimestampedInstance(): Timestamped<T> =
Timestamped(entity, metadata.updated.toInstant())
| apache-2.0 | 251c36a97cf6e839baaf5296080fc77d | 36.955224 | 95 | 0.707432 | 4.175698 | false | false | false | false |
vjache/klips | src/main/java/org/klips/engine/rete/BetaNode.kt | 1 | 3461 | package org.klips.engine.rete
import org.klips.dsl.Facet.FacetRef
import org.klips.dsl.substitute
import org.klips.engine.Binding
import org.klips.engine.Modification
import org.klips.engine.ProjectBinding
import org.klips.engine.query.BindingSet
import org.klips.engine.util.Log
import org.klips.engine.util.activationFailed
import org.klips.engine.util.activationHappen
import org.klips.engine.util.collectPattern
import java.util.concurrent.atomic.AtomicInteger
abstract class BetaNode : Node, Consumer {
final override val refs: Set<FacetRef<*>>
val commonRefs: Set<FacetRef<*>>
var left: Node
set(value) {
value.addConsumer(this)
field = value
}
var right: Node
set(value) {
value.addConsumer(this)
field = value
}
constructor(log: Log, l: Node, r: Node):super(log) {
left = l
right = r
refs = l.refs.union(right.refs)
commonRefs = left.refs.intersect(right.refs)
}
protected fun otherSource(source: Node) = when (source) {
left -> right
right -> left
else -> throw IllegalArgumentException("No such source $source.")
}
protected abstract fun modifyIndex(
source: Node,
key: Binding,
mdf: Modification<Binding>,
hookModify:() -> Unit): Boolean
protected abstract fun lookupIndex(
source: Node,
key: Binding): BindingSet
protected abstract fun composeBinding(
source: Node,
mdf: Modification<Binding>,
cachedBinding: Binding): Binding
fun other(n: Node) = when (n) {
left -> right
right -> left
else -> throw IllegalArgumentException("Failed to get complement node: $n")
}
companion object dbg {
val cnt = AtomicInteger(0)
}
override fun consume(source: Node, mdf: Modification<Binding>) {
val binding = mdf.arg
val key = makeKey(binding)
modifyIndex(source, key, mdf){
val lookupResults = lookupIndex(otherSource(source), key)
log.reteEvent {
if (lookupResults.size == 0) {
dbg.cnt.andIncrement
val patt1 = collectPattern(source)
val patt2 = collectPattern(other(source))
activationFailed()
val hcs = "[${hashCode()}:${left.hashCode()},${right.hashCode()}()]"
"JOIN FAIL(${dbg.cnt})$hcs: \n\t$key\n\t${patt1.substitute(mdf.arg)}\n\t$patt2"
} else null
}
val lookupResultsCopy = lookupResults.map { it }
lookupResultsCopy.forEach {
log.reteEvent {
dbg.cnt.andIncrement
val patt1 = collectPattern(source)
val patt2 = collectPattern(other(source))
activationHappen()
val hcs = "[${hashCode()}:${left.hashCode()},${right.hashCode()}()]"
"JOIN HAPPEN(${dbg.cnt})$hcs: \n\t$key\n\t${patt1.substitute(mdf.arg)}\n\t${patt2.substitute(it)}"
}
notifyConsumers(mdf.inherit(composeBinding(source, mdf, it)))
}
}
}
private fun makeKey(binding: Binding) = ProjectBinding(commonRefs, binding)
override fun toString() = "B-Node($refs) [${System.identityHashCode(this)}]"
}
| apache-2.0 | 10875de194c6c762ed5b394e3a61db25 | 31.345794 | 118 | 0.579312 | 4.220732 | false | false | false | false |
BenoitDuffez/AndroidCupsPrint | app/src/main/java/org/cups4j/operations/cups/CupsGetPPDOperation.kt | 1 | 2278 | package org.cups4j.operations.cups
/**
* @author Frank Carnevale
* / *
*
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option) any
* later version.
*
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
*
*
* See the GNU Lesser General Public License for more details. You should have
* received a copy of the GNU Lesser General Public License along with this
* program; if not, see <http:></http:>//www.gnu.org/licenses/>.
*/
/*Notice. This file is not part of the original cups4j. It is an implementaion
* of a patch to cups4j suggested by Frank Carnevale
*/
import android.content.Context
import ch.ethz.vppserver.ippclient.IppTag
import org.cups4j.operations.IppOperation
import java.io.UnsupportedEncodingException
import java.net.URL
import java.nio.ByteBuffer
import java.util.HashMap
class CupsGetPPDOperation(context: Context) : IppOperation(context) {
init {
operationID = 0x400F
bufferSize = 8192
}
@Throws(UnsupportedEncodingException::class)
override fun getIppHeader(url: URL, map: Map<String, String>?): ByteBuffer {
var ippBuf = ByteBuffer.allocateDirect(bufferSize.toInt())
ippBuf = IppTag.getOperation(ippBuf, operationID)
if (map == null) {
ippBuf = IppTag.getEnd(ippBuf)
ippBuf.flip()
return ippBuf
}
ippBuf = IppTag.getUri(ippBuf, "printer-uri", map["printer-uri"])
ippBuf = IppTag.getEnd(ippBuf)
ippBuf.flip()
return ippBuf
}
@Throws(Exception::class)
fun getPPDFile(printerUrl: URL): String {
val url = URL(printerUrl.protocol + "://" + printerUrl.host + ":" + printerUrl.port)
val map = HashMap<String, String>()
map["printer-uri"] = printerUrl.path
val result = request(url, map)
val buf = String(result!!.buf!!)
return buf.substring(buf.indexOf("*")) // Remove request attributes when returning the string
}
}
| lgpl-3.0 | 2891b10f384706bd8cbe238a798358bd | 32.5 | 101 | 0.684811 | 3.854484 | false | false | false | false |
MaridProject/marid | marid-ide/src/main/kotlin/org/marid/ide/context/FxContext.kt | 1 | 1437 | /*
* MARID, the visual component programming environment.
* Copyright (C) 2020 Dzmitry Auchynnikau
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.marid.ide.context
import javafx.application.Platform
import javafx.event.EventType
import javafx.stage.Window
import javafx.stage.WindowEvent
import org.marid.moan.Context
fun fxContext(name: String): Context = Context(name, closer = { Runnable { Platform.runLater(it) } })
fun fxContext(name: String, parent: Context) = Context(name, parent, closer = { Runnable { Platform.runLater(it) } })
fun Context.link(window: Window, eventType: EventType<WindowEvent> = WindowEvent.WINDOW_HIDDEN): Context {
window.properties["context"] = this
window.addEventHandler(eventType) {
window.properties.remove("context")
close()
}
return this
} | agpl-3.0 | 3f266b4b67d19f7450f9f459f42ec10b | 38.944444 | 117 | 0.752958 | 4.002786 | false | false | false | false |
googlecodelabs/android-compose-codelabs | AccessibilityCodelab/app/src/main/java/com/example/jetnews/ui/interests/InterestsScreen.kt | 1 | 7492 | /*
* 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.
*/
package com.example.jetnews.ui.interests
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Checkbox
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.ScaffoldState
import androidx.compose.material.Text
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.jetnews.R
import com.example.jetnews.data.interests.InterestsRepository
import com.example.jetnews.data.interests.TopicSelection
import com.example.jetnews.data.interests.TopicsMap
import com.example.jetnews.ui.components.InsetAwareTopAppBar
import com.example.jetnews.ui.theme.JetnewsTheme
import com.google.accompanist.insets.navigationBarsPadding
import kotlinx.coroutines.launch
/**
* Stateful InterestsScreen that handles the interaction with the repository
*
* @param interestsRepository data source for this screen
* @param openDrawer (event) request opening the app drawer
* @param scaffoldState (state) state for screen Scaffold
*/
@Composable
fun InterestsScreen(
interestsRepository: InterestsRepository,
openDrawer: () -> Unit,
modifier: Modifier = Modifier,
scaffoldState: ScaffoldState = rememberScaffoldState()
) {
// Returns a [CoroutineScope] that is scoped to the lifecycle of [InterestsScreen]. When this
// screen is removed from composition, the scope will be cancelled.
val coroutineScope = rememberCoroutineScope()
// collectAsState will read a [Flow] in Compose
val selectedTopics by interestsRepository.observeTopicsSelected().collectAsState(setOf())
val onTopicSelect: (TopicSelection) -> Unit = {
coroutineScope.launch { interestsRepository.toggleTopicSelection(it) }
}
InterestsScreen(
topics = interestsRepository.topics,
selectedTopics = selectedTopics,
onTopicSelect = onTopicSelect,
openDrawer = openDrawer,
modifier = modifier,
scaffoldState = scaffoldState
)
}
/**
* Stateless interest screen displays the topics the user can subscribe to
*
* @param topics (state) topics to display, mapped by section
* @param selectedTopics (state) currently selected topics
* @param onTopicSelect (event) request a topic selection be changed
* @param openDrawer (event) request opening the app drawer
* @param scaffoldState (state) the state for the screen's [Scaffold]
*/
@Composable
fun InterestsScreen(
topics: TopicsMap,
selectedTopics: Set<TopicSelection>,
onTopicSelect: (TopicSelection) -> Unit,
openDrawer: () -> Unit,
scaffoldState: ScaffoldState,
modifier: Modifier = Modifier
) {
Scaffold(
scaffoldState = scaffoldState,
topBar = {
InsetAwareTopAppBar(
title = { Text("Interests") },
navigationIcon = {
IconButton(onClick = openDrawer) {
Icon(
painter = painterResource(R.drawable.ic_jetnews_logo),
contentDescription = stringResource(R.string.cd_open_navigation_drawer)
)
}
}
)
}
) { padding ->
LazyColumn(
modifier = modifier.padding(padding)
) {
topics.forEach { (section, topics) ->
item {
Text(
text = section,
modifier = Modifier
.padding(16.dp),
style = MaterialTheme.typography.subtitle1
)
}
items(topics) { topic ->
TopicItem(
itemTitle = topic,
selected = selectedTopics.contains(TopicSelection(section, topic))
) { onTopicSelect(TopicSelection(section, topic)) }
TopicDivider()
}
}
}
}
}
/**
* Display a full-width topic item
*
* @param itemTitle (state) topic title
* @param selected (state) is topic currently selected
* @param onToggle (event) toggle selection for topic
*/
@Composable
private fun TopicItem(itemTitle: String, selected: Boolean, onToggle: () -> Unit) {
val image = painterResource(R.drawable.placeholder_1_1)
Row(
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier
.align(Alignment.CenterVertically)
.size(56.dp, 56.dp)
.clip(RoundedCornerShape(4.dp))
)
Text(
text = itemTitle,
modifier = Modifier
.align(Alignment.CenterVertically)
.padding(16.dp),
style = MaterialTheme.typography.subtitle1
)
Spacer(Modifier.weight(1f))
Checkbox(
checked = selected,
onCheckedChange = { onToggle() },
modifier = Modifier.align(Alignment.CenterVertically)
)
}
}
/**
* Full-width divider for topics
*/
@Composable
private fun TopicDivider() {
Divider(
modifier = Modifier.padding(start = 90.dp),
color = MaterialTheme.colors.onSurface.copy(alpha = 0.1f)
)
}
@Preview("Interests screen", "Interests")
@Preview("Interests screen (dark)", "Interests", uiMode = UI_MODE_NIGHT_YES)
@Preview("Interests screen (big font)", "Interests", fontScale = 1.5f)
@Preview("Interests screen (large screen)", "Interests", device = Devices.PIXEL_C)
@Composable
fun PreviewInterestsScreen() {
JetnewsTheme {
InterestsScreen(
interestsRepository = InterestsRepository(),
openDrawer = {}
)
}
}
| apache-2.0 | 01d78bbf9020cdefd636fa6f9d61b1fe | 34.67619 | 99 | 0.672451 | 4.723834 | false | false | false | false |
Catherine22/WebServices | WebServices/messagecenter/src/main/java/catherine/messagecenter/Result.kt | 1 | 337 | package catherine.messagecenter
import android.os.Bundle
/**
* Created by Catherine on 2017/9/7.
* Soft-World Inc.
* [email protected]
*/
data class Result(var mBundle: Bundle? = null, var mBoolean: Boolean? = false, var mString: String? = null, var mInt: Int? = Int.MIN_VALUE, var mDouble: Double? = Double.MIN_VALUE) | apache-2.0 | 1846711035bff05be36047bcfeec94df | 32.8 | 180 | 0.721068 | 3.008929 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/Game.kt | 1 | 10199 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle
import org.joml.Vector2d
import org.lwjgl.glfw.GLFW.*
import uk.co.nickthecoder.tickle.events.*
import uk.co.nickthecoder.tickle.graphics.Renderer
import uk.co.nickthecoder.tickle.graphics.Window
import uk.co.nickthecoder.tickle.loop.FullSpeedGameLoop
import uk.co.nickthecoder.tickle.loop.GameLoop
import uk.co.nickthecoder.tickle.resources.Resources
import uk.co.nickthecoder.tickle.resources.SceneResource
import uk.co.nickthecoder.tickle.util.AutoFlushPreferences
import uk.co.nickthecoder.tickle.util.ErrorHandler
import uk.co.nickthecoder.tickle.util.JsonScene
import java.io.File
import java.util.concurrent.ConcurrentLinkedQueue
class Game(
val window: Window,
val resources: Resources)
: WindowListener {
/**
* When true, prevent all stage, views and roles from receiving tick events.
*
* NOTE. [Director] and [Producer] have their tick methods called whether paused or not
*
* If you want some role to continue to tick while paused, then add extra code into your
* [Director]'s or [Producer]'s preTick, tick or postTick methods, manually calling those
* role's tick method.
*/
var paused: Boolean = false
var renderer = Renderer(window)
var producer: Producer = NoProducer()
var director: Director = NoDirector()
set(v) {
if (v is MouseListener) {
mouseListeners.remove(v)
}
field = v
}
var sceneName: String = ""
var scene: Scene = Scene()
var gameLoop: GameLoop
var errorHandler: GameErrorHandler = SimpleGameErrorHandler()
/**
* A measure of time in seconds. Updated once per frame, It is actually just System.nano converted to
* seconds.
*/
var seconds: Double = 0.0
/**
* The time between two "ticks" in seconds.
*/
var tickDuration: Double = 1.0 / 60.0
private var mouseCapturedBy: MouseButtonListener? = null
private val previousScreenMousePosition = Vector2d(-1.0, -1.0)
private val currentScreenMousePosition = Vector2d()
private val mouseListeners = mutableListOf<MouseListener>()
val preferences by lazy { AutoFlushPreferences(producer.preferencesRoot()) }
init {
Game.instance = this
window.enableVSync()
producer = resources.gameInfo.createProducer()
instance = this
seconds = System.nanoTime() / 1_000_000_000.0
window.listeners.add(this)
gameLoop = FullSpeedGameLoop(this)
gameLoop.resetStats()
}
fun run(scenePath: String) {
producer.begin()
producer.startScene(scenePath)
loop()
cleanUp()
}
fun loop() {
while (isRunning()) {
gameLoop.tick()
glfwPollEvents()
val now = System.nanoTime() / 1_000_000_000.0
tickCount++
tickDuration = now - seconds
seconds = now
}
}
fun loadScene(sceneFile: File): SceneResource {
return JsonScene(sceneFile).sceneResource
}
fun mergeScene(scenePath: String) {
mergeScene(Resources.instance.scenePathToFile(scenePath))
}
fun mergeScene(sceneFile: File) {
val sr = loadScene(sceneFile)
val extraScene = sr.createScene()
scene.merge(extraScene)
sr.includes.forEach { include ->
mergeScene(include)
}
}
fun startScene(scenePath: String) {
val oldSceneName = sceneName
sceneName = scenePath
try {
startScene(loadScene(Resources.instance.scenePathToFile(scenePath)))
} catch (e: Exception) {
sceneName = oldSceneName
ErrorHandler.handleError(e)
}
}
private fun startScene(sceneResource: SceneResource) {
mouseCapturedBy = null
director = Director.createDirector(sceneResource.directorString)
sceneResource.directorAttributes.applyToObject(director)
scene = sceneResource.createScene()
sceneResource.includes.forEach { include ->
mergeScene(include)
}
producer.sceneLoaded()
director.sceneLoaded()
producer.sceneBegin()
director.begin()
scene.begin()
scene.activated()
director.activated()
producer.sceneActivated()
seconds = System.nanoTime() / 1_000_000_000.0
gameLoop.sceneStarted()
System.gc()
}
fun endScene() {
scene.end()
director.end()
producer.sceneEnd()
mouseCapturedBy = null
}
fun cleanUp() {
processRunLater()
renderer.delete()
window.listeners.remove(this)
producer.end()
}
var quitting = false
fun quit() {
quitting = true
}
/**
* Returns true until the game is about to end. The game can end either by calling [quit], or
* by closing the window (e.g. Alt+F4, or by clicking the window's close button).
*
* In both cases, the game doesn't stop immediately. The game loop is completed, allowing
* everything to end cleanly.
*
* NOTE. isRunning ignores the [paused] boolean. i.e. a paused game is still considered to be running.
*/
fun isRunning() = !quitting && !window.shouldClose()
/**
* Called by the [GameLoop]. Do NOT call this directly from elsewhere!
*
* If the mouse position has moved, then create a MouseEvent, and call all mouse listeners.
*
* Note, if the mouse has been captured, then only the listener that has captured the mouse
* will be notified of the event.
*/
fun mouseMoveTick() {
Window.instance?.mousePosition(currentScreenMousePosition)
if (currentScreenMousePosition != previousScreenMousePosition) {
previousScreenMousePosition.set(currentScreenMousePosition)
var button = -1
for (b in 0..2) {
val state = glfwGetMouseButton(window.handle, b)
if (state == GLFW_PRESS) {
button = b
}
}
val event = MouseEvent(Window.instance!!, button, if (button == -1) ButtonState.UNKNOWN else ButtonState.PRESSED, 0)
event.screenPosition.set(currentScreenMousePosition)
mouseCapturedBy?.let { capturedBy ->
if (capturedBy is MouseListener) {
event.captured = true
capturedBy.onMouseMove(event)
if (!event.captured) {
mouseCapturedBy = null
}
event.consume()
}
}
if (!event.isConsumed()) {
for (ml in mouseListeners) {
ml.onMouseMove(event)
if (event.captured) {
mouseCapturedBy = ml
break
}
if (event.isConsumed()) break
}
}
}
}
override fun onKey(event: KeyEvent) {
producer.onKey(event)
if (event.isConsumed()) {
return
}
director.onKey(event)
}
fun addMouseListener(listener: MouseListener) {
mouseListeners.add(listener)
}
fun removeMouseListener(listener: MouseListener) {
mouseListeners.remove(listener)
}
override fun onMouseButton(event: MouseEvent) {
mouseCapturedBy?.let {
event.captured = true
it.onMouseButton(event)
if (!event.captured) {
mouseCapturedBy = null
}
return
}
if (sendMouseButtonEvent(event, producer)) {
return
}
if (sendMouseButtonEvent(event, director)) {
return
}
if (event.state == ButtonState.PRESSED) {
// TODO Need to iterate BACKWARDS
scene.views().forEach { view ->
if (sendMouseButtonEvent(event, view)) {
return
}
}
}
}
override fun onResize(event: ResizeEvent) {
producer.onResize(event)
}
private fun sendMouseButtonEvent(event: MouseEvent, to: MouseButtonListener): Boolean {
to.onMouseButton(event)
if (event.captured) {
event.captured = false
mouseCapturedBy = to
previousScreenMousePosition.set(event.screenPosition)
}
return event.isConsumed()
}
/**
* Uses a ConcurrentLinkedQueue, rather than a simple list, so that [runLater] can be called within
* a runLater lambda without fear of a concurrent modification exception.
*/
private var runLaters = ConcurrentLinkedQueue<() -> Unit>()
/**
* Called by the [GameLoop] (do NOT call this directly from elsewhere!)
*
* Runs all of the lambdas sent to [runLater] since the last call to [processRunLater].
*/
fun processRunLater() {
var entry = runLaters.poll()
while (entry != null) {
entry()
entry = runLaters.poll()
}
}
fun runLater(func: () -> Unit) {
runLaters.add(func)
}
companion object {
lateinit var instance: Game
/**
* Increments by one for each frame.
*/
var tickCount: Int = 0
fun runLater(func: () -> Unit) {
instance.runLater(func)
}
}
}
| gpl-3.0 | f3b25359c65b3f64ed39f737b18d00bb | 27.488827 | 128 | 0.603098 | 4.58382 | false | false | false | false |
ajalt/clikt | clikt/src/jsMain/kotlin/com/github/ajalt/clikt/mpp/MppImpl.kt | 1 | 1762 | package com.github.ajalt.clikt.mpp
private external val process: dynamic
private interface JsMppImpls {
fun readEnvvar(key: String): String?
fun isWindowsMpp(): Boolean
fun exitProcessMpp(status: Int)
fun readFileIfExists(filename: String): String?
}
private object BrowserMppImpls : JsMppImpls {
override fun readEnvvar(key: String): String? = null
override fun isWindowsMpp(): Boolean = false
override fun exitProcessMpp(status: Int) {}
override fun readFileIfExists(filename: String): String? = null
}
private class NodeMppImpls(private val fs: dynamic) : JsMppImpls {
override fun readEnvvar(key: String): String? = process.env[key] as? String
override fun isWindowsMpp(): Boolean = process.platform == "win32"
override fun exitProcessMpp(status: Int): Unit = process.exit(status).unsafeCast<Unit>()
override fun readFileIfExists(filename: String): String? {
return try {
fs.readFileSync(filename, "utf-8") as? String
} catch (e: Throwable) {
null
}
}
}
private val impls: JsMppImpls = try {
NodeMppImpls(nodeRequire("fs"))
} catch (e: Exception) {
BrowserMppImpls
}
private val LETTER_OR_DIGIT_RE = Regex("""[a-zA-Z0-9]""")
internal actual val String.graphemeLengthMpp: Int get() = replace(ANSI_CODE_RE, "").length
internal actual fun isLetterOrDigit(c: Char): Boolean = LETTER_OR_DIGIT_RE.matches(c.toString())
internal actual fun readEnvvar(key: String): String? = impls.readEnvvar(key)
internal actual fun isWindowsMpp(): Boolean = impls.isWindowsMpp()
internal actual fun exitProcessMpp(status: Int): Unit = impls.exitProcessMpp(status)
internal actual fun readFileIfExists(filename: String): String? = impls.readFileIfExists(filename)
| apache-2.0 | b24782a30fc216e6e970381cc89ba7ff | 36.489362 | 98 | 0.717934 | 3.864035 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/SVNLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/svnlogparser/converter/ProjectConverter.kt | 1 | 2720 | package de.maibornwolff.codecharta.importer.svnlogparser.converter
import de.maibornwolff.codecharta.importer.svnlogparser.input.VersionControlledFile
import de.maibornwolff.codecharta.importer.svnlogparser.input.metrics.MetricsFactory
import de.maibornwolff.codecharta.model.Edge
import de.maibornwolff.codecharta.model.MutableNode
import de.maibornwolff.codecharta.model.NodeType
import de.maibornwolff.codecharta.model.PathFactory
import de.maibornwolff.codecharta.model.Project
import de.maibornwolff.codecharta.model.ProjectBuilder
/**
* creates Projects from List of VersionControlledFiles
*/
class ProjectConverter(private val containsAuthors: Boolean) {
private val ROOT_PREFIX = "/root/"
private fun addVersionControlledFile(projectBuilder: ProjectBuilder, versionControlledFile: VersionControlledFile) {
val attributes = extractAttributes(versionControlledFile)
val edges = versionControlledFile.getEdgeList()
val fileName = versionControlledFile.actualFilename.substringAfterLast(PATH_SEPARATOR)
val newNode = MutableNode(fileName, NodeType.File, attributes, "", mutableSetOf())
val path = PathFactory.fromFileSystemPath(
versionControlledFile.actualFilename.substringBeforeLast(PATH_SEPARATOR, "")
)
projectBuilder.insertByPath(path, newNode)
edges.forEach { projectBuilder.insertEdge(addRootToEdgePaths(it)) }
versionControlledFile.removeMetricsToFreeMemory()
}
private fun extractAttributes(versionControlledFile: VersionControlledFile): Map<String, Any> {
return when {
containsAuthors ->
versionControlledFile.metricsMap
.plus(Pair("authors", versionControlledFile.authors))
else -> versionControlledFile.metricsMap
}
}
private fun addRootToEdgePaths(edge: Edge): Edge {
edge.fromNodeName = ROOT_PREFIX + edge.fromNodeName
edge.toNodeName = ROOT_PREFIX + edge.toNodeName
return edge
}
fun convert(versionControlledFiles: List<VersionControlledFile>, metricsFactory: MetricsFactory): Project {
val projectBuilder = ProjectBuilder()
versionControlledFiles
.filter { vc -> !vc.markedDeleted() }
.forEach { vcFile -> addVersionControlledFile(projectBuilder, vcFile) }
val metrics = metricsFactory.createMetrics()
projectBuilder.addAttributeTypes(AttributeTypesFactory.createNodeAttributeTypes(metrics))
projectBuilder.addAttributeTypes(AttributeTypesFactory.createEdgeAttributeTypes(metrics))
return projectBuilder.build()
}
companion object {
private const val PATH_SEPARATOR = '/'
}
}
| bsd-3-clause | c710b64be12916fc5948ef0514597cea | 41.5 | 120 | 0.742279 | 5.037037 | false | false | false | false |
MaibornWolff/codecharta | analysis/model/src/main/kotlin/de/maibornwolff/codecharta/model/MutableNode.kt | 1 | 2428 | package de.maibornwolff.codecharta.model
import de.maibornwolff.codecharta.translator.MetricNameTranslator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.util.NoSuchElementException
class MutableNode(
val name: String,
val type: NodeType? = NodeType.File,
var attributes: Map<String, Any> = mapOf(),
val link: String? = "",
childrenList: Set<MutableNode> = setOf(),
@Transient val nodeMergingStrategy: NodeMergerStrategy = NodeMaxAttributeMerger()
) : Tree<MutableNode>() {
override var children = childrenList.toMutableSet()
override fun getPathOfChild(child: Tree<MutableNode>): Path {
if (!children.contains(child))
throw NoSuchElementException("Child $child not contained in MutableNode.")
return Path(listOf((child.asTreeNode()).name))
}
override fun toString(): String {
return "MutableNode(name='$name', type=$type, attributes=$attributes, link=$link, children=$children)"
}
override fun insertAt(path: Path, node: MutableNode) {
NodeInserter.insertByPath(this, path, node)
}
override fun merge(nodes: List<MutableNode>): MutableNode {
return nodeMergingStrategy.merge(this, nodes)
}
fun translateMetrics(metricNameTranslator: MetricNameTranslator, recursive: Boolean = false): MutableNode {
if (recursive) {
runBlocking(Dispatchers.Default) {
children.forEach {
launch { it.translateMetrics(metricNameTranslator, recursive) }
}
}
}
attributes = attributes.mapKeys { metricNameTranslator.translate(it.key) }.filterKeys { it.isNotBlank() }
return this
}
fun toNode(): Node {
return Node(name, type, attributes, link, children = children.map { it.toNode() }.toSet())
}
val isEmptyFolder
get() = type == NodeType.Folder && children.isEmpty()
fun filterChildren(filterRule: (MutableNode) -> Boolean, recursive: Boolean = false): MutableNode? {
children.removeAll { !filterRule(it) }
if (recursive) {
children.forEach { it.filterChildren(filterRule, recursive) }
}
children.removeAll { !filterRule(it) }
return when {
children.isEmpty() && type == NodeType.Folder -> null
else -> this
}
}
}
| bsd-3-clause | d356a6494d80ee29d2adf90b6c1505d9 | 33.685714 | 113 | 0.656919 | 4.714563 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/util/logging/TimberFileTree.kt | 1 | 2932 | package me.proxer.app.util.logging
import android.annotation.SuppressLint
import android.os.Environment
import android.os.Environment.DIRECTORY_DOWNLOADS
import android.util.Log
import io.reactivex.Completable
import io.reactivex.schedulers.Schedulers
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalDateTime
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.format.DateTimeParseException
import timber.log.Timber
import java.io.File
import java.util.concurrent.Executors
/**
* @author Ruben Gees
*/
@SuppressLint("LogNotTimber")
class TimberFileTree : Timber.Tree() {
private companion object {
private const val LOGS_DIRECTORY = "Proxer.Me Logs"
private const val ROTATION_THRESHOLD = 7L
private val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
private val executor = Executors.newSingleThreadExecutor()
}
@Suppress("DEPRECATION") // What is Android even doing?
private val downloadsDirectory
get() = Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS)
private val resolvedLogsDirectory get() = File(downloadsDirectory, LOGS_DIRECTORY).also { it.mkdirs() }
override fun isLoggable(tag: String?, priority: Int) = priority >= Log.INFO
@SuppressLint("CheckResult")
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
if (!resolvedLogsDirectory.canWrite()) {
return
}
Completable
.fromAction { internalLog(tag, message) }
.subscribeOn(Schedulers.from(executor))
.subscribe(
{},
{
Log.e(TimberFileTree::class.java.name, "Failure while logging to file", it)
}
)
}
private fun internalLog(tag: String?, message: String) {
val currentLogFiles = resolvedLogsDirectory.listFiles() ?: emptyArray()
val currentDateTime = LocalDateTime.now()
val rotationThresholdDate = currentDateTime.toLocalDate().minusDays(ROTATION_THRESHOLD)
for (currentLogFile in currentLogFiles) {
val fileDate = try {
LocalDate.parse(currentLogFile.nameWithoutExtension)
} catch (error: DateTimeParseException) {
Log.e(TimberFileTree::class.java.name, "Invalid log file $currentLogFile found, deleting", error)
null
}
if (fileDate == null || fileDate.isBefore(rotationThresholdDate)) {
currentLogFile.deleteRecursively()
}
}
val logFile = File(resolvedLogsDirectory, "${LocalDate.now()}.log").also { it.createNewFile() }
val currentDateTimeText = currentDateTime.format(dateTimeFormatter)
val maybeTag = if (tag != null) "$tag: " else ""
logFile.appendText("$currentDateTimeText $maybeTag${message.trim()}\n")
}
}
| gpl-3.0 | 983c6856bfa396cda217e438c63dab6b | 34.756098 | 113 | 0.669509 | 4.729032 | false | false | false | false |
j2ghz/tachiyomi-extensions | src/en/readcomictv/src/eu/kanade/tachiyomi/extension/en/readcomictv/Readcomictv.kt | 1 | 4037 | package eu.kanade.tachiyomi.extension.en.readcomictv
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
class Readcomictv : ParsedHttpSource() {
override val lang = "en"
override val name = "ReadComicsWebsite"
override val supportsLatest = true
override val baseUrl = "http://readcomics.io"
override fun chapterFromElement(element: Element): SChapter {
val chapter = SChapter.create()
val info = element.select("a")
chapter.name=info.text()
chapter.setUrlWithoutDomain(info.attr("href") + "/full")
chapter.date_upload = SimpleDateFormat("M/d/y").parse(element.select("span").text()).time
return chapter
}
override fun chapterListParse(response: Response): List<SChapter> {
return super.chapterListParse(response).asReversed()
}
override fun chapterListSelector(): String {
return "ul.basic-list li"
}
override fun imageUrlParse(document: Document): String {
throw UnsupportedOperationException("imageUrlParse not implemented")
}
override fun latestUpdatesFromElement(element: Element): SManga {
val manga = SManga.create()
manga.setUrlWithoutDomain(element.attr("href"))
manga.title = element.text()
return manga
}
override fun latestUpdatesNextPageSelector(): String? {
return null
}
override fun latestUpdatesRequest(page: Int): Request {
return GET(baseUrl + "/comic-updates/$page",headers)
}
override fun latestUpdatesSelector(): String {
return ".hlb-name"
}
override fun mangaDetailsParse(document: Document): SManga {
val manga = SManga.create()
val info = document.select(".manga-details table")
manga.author = info.select("tr:nth-child(5) > td:nth-child(2)").text()
manga.artist = info.select("tr:nth-child(5) > td:nth-child(2)").text()
manga.description = document.select(".detail-desc-content p").text()
manga.thumbnail_url = document.select(".anime-image img").attr("src")
manga.genre = info.select("tr:nth-child(6) > td:nth-child(2)").text()
val status = info.select("tr:nth-child(4) > td:nth-child(2)").text()
manga.status = if (status == "Completed") SManga.COMPLETED else if (status == "Ongoing") SManga.ONGOING else SManga.UNKNOWN
return manga
}
override fun pageListParse(document: Document): List<Page> {
var i = 0
return document.select(".chapter_img").map {
Page(i++,"",it.attr("src"))
}
}
override fun popularMangaFromElement(element: Element): SManga {
return SManga.create().apply {
title = element.text()
setUrlWithoutDomain(element.attr("href"))
}
}
override fun popularMangaNextPageSelector(): String? = ".general-nav :last-child"
override fun popularMangaRequest(page: Int): Request {
return GET(baseUrl + "/popular-comics/$page",headers)
}
override fun popularMangaSelector(): String = ".manga-box h3 a"
override fun searchMangaFromElement(element: Element): SManga {
return SManga.create().apply {
title = element.text()
setUrlWithoutDomain(element.attr("href"))
}
}
override fun searchMangaNextPageSelector(): String? {
return ".general-nav :last-child[href]"
}
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
return GET(baseUrl + "/advanced-search?key=$query&page=$page",headers)
}
override fun searchMangaSelector(): String {
return ".dlb-title"
}
} | apache-2.0 | 3993e2b8bdde66d78591be555f3adbc9 | 33.810345 | 131 | 0.666832 | 4.392818 | false | false | false | false |
ansman/kotshi | compiler/src/main/kotlin/se/ansman/kotshi/kapt/TypeMaps.kt | 1 | 2332 | package se.ansman.kotshi.kapt
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import se.ansman.kotshi.Types
fun TypeName.toKotlinVersion(mutable: Boolean = true): TypeName =
when (this) {
is ClassName -> toKotlinVersion(mutable)
Dynamic -> this
is LambdaTypeName -> this
is ParameterizedTypeName -> rawType.toKotlinVersion(mutable)
.parameterizedBy(typeArguments.map { it.toKotlinVersion(mutable) })
is TypeVariableName -> copy(bounds = bounds.map { it.toKotlinVersion(mutable) })
is WildcardTypeName -> when {
inTypes.size == 1 -> WildcardTypeName.consumerOf(inTypes[0].toKotlinVersion(mutable))
outTypes == STAR.outTypes -> STAR
else -> WildcardTypeName.producerOf(outTypes[0].toKotlinVersion(mutable))
}
}
fun ClassName.toKotlinVersion(mutable: Boolean = true): ClassName =
when (this) {
JavaTypes.boolean -> BOOLEAN
JavaTypes.byte -> BYTE
JavaTypes.char -> CHAR
JavaTypes.short -> SHORT
JavaTypes.int -> INT
JavaTypes.long -> LONG
JavaTypes.float -> FLOAT
JavaTypes.double -> DOUBLE
JavaTypes.string -> STRING
JavaTypes.annotation -> Types.Kotlin.annotation
JavaTypes.collection -> if (mutable) MUTABLE_COLLECTION else COLLECTION
JavaTypes.list -> if (mutable) MUTABLE_LIST else LIST
JavaTypes.set -> if (mutable) MUTABLE_SET else SET
JavaTypes.map -> if (mutable) MUTABLE_MAP else MAP
else -> this
}
private object JavaTypes {
val boolean = ClassName("java.lang", "Boolean")
val byte = ClassName("java.lang", "Byte")
val char = ClassName("java.lang", "Char")
val short = ClassName("java.lang", "Short")
val int = ClassName("java.lang", "Int")
val long = ClassName("java.lang", "Long")
val float = ClassName("java.lang", "Float")
val double = ClassName("java.lang", "Double")
val string = ClassName("java.lang", "String")
val annotation = ClassName("java.lang.annotation", "Annotation")
val collection = ClassName("java.util", "Collection")
val list = ClassName("java.util", "List")
val set = ClassName("java.util", "Set")
val map = ClassName("java.util", "Map")
} | apache-2.0 | d8032e9176ae1185100b62c75ff4070a | 40.660714 | 97 | 0.656518 | 4.302583 | false | false | false | false |
jiangkang/KTools | app/src/main/java/com/jiangkang/ktools/KApplication.kt | 1 | 4550 | package com.jiangkang.ktools
import android.app.Application
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Debug
import android.os.StrictMode
import android.util.Log
import android.view.Choreographer
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.multidex.MultiDex
import com.facebook.drawee.backends.pipeline.Fresco
import com.jiangkang.ktools.receiver.KToolsAppWidgetProvider
import com.jiangkang.ktools.works.AppOptWorker
import com.jiangkang.ndk.NdkMainActivity
import com.jiangkang.tools.King
import com.jiangkang.tools.widget.KNotification
import com.jiangkang.tools.widget.KShortcut
/**
* @author jiangkang
* @date 2017/9/6
*/
open class KApplication : Application() {
private val tag = "KApplication"
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
MultiDex.install(this)
KNotification.createNotificationChannel(base)
Thread.setDefaultUncaughtExceptionHandler { t, e ->
val stackTrace = e.stackTrace
val reason = StringBuilder()
reason.appendLine(e.message)
stackTrace.forEach {
reason.appendLine(it.toString())
}
val intent = Intent(applicationContext, CrashInfoActivity::class.java)
.apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
putExtra("crash_info", reason.toString())
}
startActivity(intent)
}
}
override fun onCreate() {
Debug.startMethodTracing()
super.onCreate()
enableStrictMode()
King.init(this)
Debug.stopMethodTracing()
Fresco.initialize(this)
AppOptWorker.launch(this)
initShortcuts()
initWidgets()
val callback = Choreographer.FrameCallback { frameTimeNanos ->
Log.d(tag, frameTimeNanos.toString())
}
Choreographer.getInstance().postFrameCallback(callback)
}
/**
* 创建固定微件
*/
private fun initWidgets() {
val appWidgetManager: AppWidgetManager = applicationContext.getSystemService(AppWidgetManager::class.java)
val myProvider = ComponentName(applicationContext, KToolsAppWidgetProvider::class.java)
val successCallback: PendingIntent? = if (appWidgetManager.isRequestPinAppWidgetSupported) {
Intent(applicationContext, MainActivity::class.java).let { intent ->
PendingIntent.getBroadcast(applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
} else {
null
}
successCallback?.also { pendingIntent ->
appWidgetManager.requestPinAppWidget(myProvider, null, pendingIntent)
}
}
private fun initShortcuts() {
val shortcutSystem = KShortcut.createShortcutInfo(this, "system", "System", "System Demos", R.drawable.ic_system, Intent(this, SystemActivity::class.java))
val shortcutUI = KShortcut.createShortcutInfo(this, "ui", "UI", "UI Demos", R.drawable.ic_widget, Intent(this, WidgetActivity::class.java))
val shortcutNdk = KShortcut.createShortcutInfo(this, "ndk", "NDK", "NDK Demos", R.drawable.ic_cpp, Intent(this, NdkMainActivity::class.java))
ShortcutManagerCompat.addDynamicShortcuts(this, listOf(shortcutSystem, shortcutUI, shortcutNdk))
if (ShortcutManagerCompat.isRequestPinShortcutSupported(this)) {
val pinIntent = ShortcutManagerCompat.createShortcutResultIntent(this, shortcutNdk)
val successCallback = PendingIntent.getBroadcast(this, 0, pinIntent, 0)
ShortcutManagerCompat.requestPinShortcut(this, shortcutNdk, successCallback.intentSender)
}
}
private fun enableStrictMode() {
if (BuildConfig.DEBUG) {
enableThreadPolicy()
enableVmPolicy()
}
}
private fun enableVmPolicy() {
StrictMode.setVmPolicy(
StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build()
)
}
private fun enableThreadPolicy() {
StrictMode.setThreadPolicy(
StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build()
)
}
}
| mit | 506c067454485f0ee07c85c20ec79e32 | 33.378788 | 163 | 0.654473 | 5.003308 | false | false | false | false |
alondero/nestlin | src/main/kotlin/com/github/alondero/nestlin/cpu/Cpu.kt | 1 | 3878 | package com.github.alondero.nestlin.cpu
import com.github.alondero.nestlin.*
import com.github.alondero.nestlin.gamepak.GamePak
import com.github.alondero.nestlin.log.Logger
class Cpu(var memory: Memory)
{
var currentGame: GamePak? = null
var interrupt: Interrupt? = null
var workCyclesLeft = 0
var pageBoundaryFlag = false
var registers = Registers()
var processorStatus = ProcessorStatus()
var idle = false
private var logger: Logger? = null
private val opcodes = Opcodes()
fun reset() {
memory.clear()
processorStatus.reset()
registers.reset()
workCyclesLeft = 0
currentGame?.let {
memory.readCartridge(it)
registers.initialise(memory)
if (it.isTestRom()) registers.activateAutomationMode()
}
}
fun enableLogging() {
logger = Logger()
}
fun tick() {
if (readyForNextInstruction()) {
val initialPC = registers.programCounter
val opcodeVal = readByteAtPC().toUnsignedInt()
opcodes[opcodeVal]?.also {
logger?.cpuTick(initialPC, opcodeVal, this)
it.op(this)
} ?: throw UnhandledOpcodeException(opcodeVal)
}
if (workCyclesLeft > 0) workCyclesLeft--
}
fun push(value: Byte) { memory[0x100 + ((registers.stackPointer--).toUnsignedInt())] = value }
fun pop() = memory[(0x100 + (++registers.stackPointer).toUnsignedInt())]
fun readByteAtPC() = memory[registers.programCounter++.toUnsignedInt()]
fun readShortAtPC() = memory[registers.programCounter++.toUnsignedInt(), registers.programCounter++.toUnsignedInt()]
fun hasCrossedPageBoundary(previousCounter: Short, programCounter: Short) = (previousCounter.toUnsignedInt() and 0xFF00) != (programCounter.toUnsignedInt() and 0xFF00)
private fun readyForNextInstruction() = workCyclesLeft <= 0
}
enum class Interrupt {
IRQ_BRK,
NMI,
RESET
}
data class Registers(
var stackPointer: Byte = 0,
var accumulator: Byte = 0,
var indexX: Byte = 0,
var indexY: Byte = 0,
var programCounter: Short = 0
) {
fun reset() {
stackPointer = -3 // Skips decrementing three times from init
accumulator = 0
indexX = 0
indexY = 0
}
fun initialise(memory: Memory) {
programCounter = memory.resetVector()
}
fun activateAutomationMode() {
programCounter = 0xc000.toSignedShort()
}
}
data class ProcessorStatus(
var carry: Boolean = false,
var zero: Boolean = true,
var interruptDisable: Boolean = true,
var decimalMode: Boolean = false,
var breakCommand: Boolean = false,
var overflow: Boolean = false,
var negative: Boolean = false
) {
fun reset() {
carry = false
zero = false
interruptDisable = true
decimalMode = false
breakCommand = false
overflow = false
negative = false
}
fun asByte() =
((if (negative) (1 shl 7) else 0) or
(if (overflow) (1 shl 6) else 0) or
(1 shl 5) or // Special logic needed for the B flag...
(0 shl 4) or
(if (decimalMode) (1 shl 3) else 0) or
(if (interruptDisable) (1 shl 2) else 0) or
(if (zero) (1 shl 1) else 0) or
(if (carry) 1 else 0)).toSignedByte()
fun toFlags(status: Byte) {
carry = status.isBitSet(0)
zero = status.isBitSet(1)
interruptDisable = status.isBitSet(2)
decimalMode = status.isBitSet(3)
overflow = status.isBitSet(6)
negative = status.isBitSet(7)
}
fun resolveZeroAndNegativeFlags(result: Byte) {
zero = (result.toUnsignedInt() == 0)
negative = (result.toUnsignedInt() and 0xFF).toSignedByte().isBitSet(7)
}
}
| gpl-3.0 | a5e66ec8536b9de92969c55946d123b4 | 28.603053 | 171 | 0.612429 | 4.077813 | false | false | false | false |
nisrulz/android-examples | GitVersioning/app/src/main/java/github/nisrulz/example/git_versioning/ui/theme/Type.kt | 1 | 814 | package github.nisrulz.example.git_versioning.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
) | apache-2.0 | 0d2d00d80a8ed0653cdf82e067744c47 | 28.107143 | 54 | 0.695332 | 4.423913 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/searchsuggestions/SearchSuggestionsPreferences.kt | 1 | 1918 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.searchsuggestions
import android.content.Context
import androidx.preference.PreferenceManager
import org.mozilla.focus.R
import org.mozilla.focus.ext.settings
import org.mozilla.focus.telemetry.TelemetryWrapper
class SearchSuggestionsPreferences(private val context: Context) {
private val settings = context.settings
private val preferences = PreferenceManager.getDefaultSharedPreferences(context)
fun searchSuggestionsEnabled(): Boolean = settings.shouldShowSearchSuggestions()
fun hasUserToggledSearchSuggestions(): Boolean = settings.userHasToggledSearchSuggestions()
fun userHasDismissedNoSuggestionsMessage(): Boolean = settings.userHasDismissedNoSuggestionsMessage()
fun enableSearchSuggestions() {
preferences.edit()
.putBoolean(TOGGLED_SUGGESTIONS_PREF, true)
.putBoolean(context.resources.getString(R.string.pref_key_show_search_suggestions), true)
.apply()
TelemetryWrapper.respondToSearchSuggestionPrompt(true)
}
fun disableSearchSuggestions() {
preferences.edit()
.putBoolean(TOGGLED_SUGGESTIONS_PREF, true)
.putBoolean(context.resources.getString(R.string.pref_key_show_search_suggestions), false)
.apply()
TelemetryWrapper.respondToSearchSuggestionPrompt(false)
}
fun dismissNoSuggestionsMessage() {
preferences.edit()
.putBoolean(DISMISSED_NO_SUGGESTIONS_PREF, true)
.apply()
}
companion object {
const val TOGGLED_SUGGESTIONS_PREF = "user_has_toggled_search_suggestions"
const val DISMISSED_NO_SUGGESTIONS_PREF = "user_dismissed_no_search_suggestions"
}
}
| mpl-2.0 | 2b20a6919729781a41dcb81aa9014e24 | 38.142857 | 105 | 0.73097 | 4.65534 | false | false | false | false |
stiangao/pipixia | src/main/kotlin/com/github/stiangao/pipixia/domain/Tag.kt | 1 | 583 | package com.github.stiangao.pipixia.domain
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository
import java.util.*
import javax.persistence.Entity
import javax.persistence.Index
import javax.persistence.Table
/**
* Created by ttgg on 2017/8/22.
*/
@Entity
@Table(indexes = arrayOf(
Index(columnList = "name", name = "idx_name", unique = true)
))
class Tag : BaseEntity() {
var name: String = ""
}
@Repository
interface TagRepository : CrudRepository<Tag, Long> {
fun findByName(name: String): Optional<Tag>
} | apache-2.0 | 8e271f7db88f892ce0301939725eff62 | 23.333333 | 68 | 0.744425 | 3.713376 | false | false | false | false |
ze-pequeno/okhttp | okhttp/src/commonMain/kotlin/okhttp3/internal/-HeadersCommon.kt | 3 | 5867 | /*
* 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 okhttp3.internal
import okhttp3.Headers
internal fun Headers.commonName(index: Int): String = namesAndValues.getOrNull(index * 2) ?: throw IndexOutOfBoundsException("name[$index]")
internal fun Headers.commonValue(index: Int): String = namesAndValues.getOrNull(index * 2 + 1) ?: throw IndexOutOfBoundsException("value[$index]")
internal fun Headers.commonValues(name: String): List<String> {
var result: MutableList<String>? = null
for (i in 0 until size) {
if (name.equals(name(i), ignoreCase = true)) {
if (result == null) result = ArrayList(2)
result.add(value(i))
}
}
return result?.toList().orEmpty()
}
internal fun Headers.commonIterator(): Iterator<Pair<String, String>> {
return Array(size) { name(it) to value(it) }.iterator()
}
internal fun Headers.commonNewBuilder(): Headers.Builder {
val result = Headers.Builder()
result.namesAndValues += namesAndValues
return result
}
internal fun Headers.commonEquals(other: Any?): Boolean {
return other is Headers && namesAndValues.contentEquals(other.namesAndValues)
}
internal fun Headers.commonHashCode(): Int = namesAndValues.contentHashCode()
internal fun Headers.commonToString(): String {
return buildString {
for (i in 0 until size) {
val name = name(i)
val value = value(i)
append(name)
append(": ")
append(if (isSensitiveHeader(name)) "██" else value)
append("\n")
}
}
}
internal fun commonHeadersGet(namesAndValues: Array<String>, name: String): String? {
for (i in namesAndValues.size - 2 downTo 0 step 2) {
if (name.equals(namesAndValues[i], ignoreCase = true)) {
return namesAndValues[i + 1]
}
}
return null
}
internal fun Headers.Builder.commonAdd(name: String, value: String) = apply {
headersCheckName(name)
headersCheckValue(value, name)
commonAddLenient(name, value)
}
internal fun Headers.Builder.commonAddAll(headers: Headers) = apply {
for (i in 0 until headers.size) {
commonAddLenient(headers.name(i), headers.value(i))
}
}
internal fun Headers.Builder.commonAddLenient(name: String, value: String) = apply {
namesAndValues.add(name)
namesAndValues.add(value.trim())
}
internal fun Headers.Builder.commonRemoveAll(name: String) = apply {
var i = 0
while (i < namesAndValues.size) {
if (name.equals(namesAndValues[i], ignoreCase = true)) {
namesAndValues.removeAt(i) // name
namesAndValues.removeAt(i) // value
i -= 2
}
i += 2
}
}
/**
* Set a field with the specified value. If the field is not found, it is added. If the field is
* found, the existing values are replaced.
*/
internal fun Headers.Builder.commonSet(name: String, value: String) = apply {
headersCheckName(name)
headersCheckValue(value, name)
removeAll(name)
commonAddLenient(name, value)
}
/** Equivalent to `build().get(name)`, but potentially faster. */
internal fun Headers.Builder.commonGet(name: String): String? {
for (i in namesAndValues.size - 2 downTo 0 step 2) {
if (name.equals(namesAndValues[i], ignoreCase = true)) {
return namesAndValues[i + 1]
}
}
return null
}
internal fun Headers.Builder.commonBuild(): Headers = Headers(namesAndValues.toTypedArray())
internal fun headersCheckName(name: String) {
require(name.isNotEmpty()) { "name is empty" }
for (i in name.indices) {
val c = name[i]
require(c in '\u0021'..'\u007e') {
"Unexpected char 0x${c.charCode()} at $i in header name: $name"
}
}
}
internal fun headersCheckValue(value: String, name: String) {
for (i in value.indices) {
val c = value[i]
require(c == '\t' || c in '\u0020'..'\u007e') {
"Unexpected char 0x${c.charCode()} at $i in $name value" +
(if (isSensitiveHeader(name)) "" else ": $value")
}
}
}
private fun Char.charCode() = code.toString(16).let {
if (it.length < 2) {
"0$it"
} else {
it
}
}
internal fun commonHeadersOf(vararg inputNamesAndValues: String): Headers {
require(inputNamesAndValues.size % 2 == 0) { "Expected alternating header names and values" }
// Make a defensive copy and clean it up.
val namesAndValues: Array<String> = arrayOf(*inputNamesAndValues)
for (i in namesAndValues.indices) {
require(namesAndValues[i] != null) { "Headers cannot be null" }
namesAndValues[i] = inputNamesAndValues[i].trim()
}
// Check for malformed headers.
for (i in namesAndValues.indices step 2) {
val name = namesAndValues[i]
val value = namesAndValues[i + 1]
headersCheckName(name)
headersCheckValue(value, name)
}
return Headers(namesAndValues)
}
internal fun Map<String, String>.commonToHeaders(): Headers {
// Make a defensive copy and clean it up.
val namesAndValues = arrayOfNulls<String>(size * 2)
var i = 0
for ((k, v) in this) {
val name = k.trim()
val value = v.trim()
headersCheckName(name)
headersCheckValue(value, name)
namesAndValues[i] = name
namesAndValues[i + 1] = value
i += 2
}
return Headers(namesAndValues as Array<String>)
}
| apache-2.0 | 5c52078b38c41c5faffb4f4104d15409 | 29.696335 | 146 | 0.69009 | 3.671259 | false | false | false | false |
nestlabs/connectedhomeip | src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/attestation/AttestationAppLauncher.kt | 2 | 1899 | package com.google.chip.chiptool.attestation
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
/** Class for finding and launching external attestation apps */
object AttestationAppLauncher {
/** Registers and returns an [ActivityResultLauncher] for attestation */
fun getLauncher(
caller: ActivityResultCaller,
block: (String?) -> Unit
): ActivityResultLauncher<Intent> {
return caller.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
val data = result.data
if (result.resultCode == Activity.RESULT_OK && data != null) {
val chipResult = data.getStringExtra(CHIP_RESULT_KEY)
Log.i(TAG, "Attestation result: $chipResult")
block(chipResult)
}
}
}
/** Queries apps which support attestation and returns the first [Intent] */
fun getAttestationIntent(context: Context): Intent? {
val packageManager = context.packageManager as PackageManager
val attestationActivityIntent = Intent(CHIP_ACTION)
val attestationAppInfo = packageManager
.queryIntentActivities(attestationActivityIntent, 0)
.firstOrNull()
return if (attestationAppInfo != null) {
attestationActivityIntent.setClassName(
attestationAppInfo.activityInfo.packageName,
attestationAppInfo.activityInfo.name
)
attestationActivityIntent
} else {
Log.e(TAG, "No attestation app found")
null
}
}
private const val TAG = "AttestationAppLauncher"
private const val CHIP_ACTION = "chip.intent.action.ATTESTATION"
private const val CHIP_RESULT_KEY = "chip_result_key"
}
| apache-2.0 | 58cea893896b95632658fdde2f6161c2 | 34.830189 | 105 | 0.745129 | 4.457746 | false | true | false | false |
wordpress-mobile/WordPress-FluxC-Android | fluxc/src/main/java/org/wordpress/android/fluxc/store/StockMediaStore.kt | 2 | 6184 | package org.wordpress.android.fluxc.store
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode.ASYNC
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.Payload
import org.wordpress.android.fluxc.action.StockMediaAction
import org.wordpress.android.fluxc.action.StockMediaAction.FETCH_STOCK_MEDIA
import org.wordpress.android.fluxc.annotations.action.Action
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.StockMediaModel
import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError
import org.wordpress.android.fluxc.network.rest.wpcom.stockmedia.StockMediaRestClient
import org.wordpress.android.fluxc.persistence.StockMediaSqlUtils
import org.wordpress.android.fluxc.store.MediaStore.OnStockMediaUploaded
import org.wordpress.android.fluxc.tools.CoroutineEngine
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T.MEDIA
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class StockMediaStore
@Inject constructor(
dispatcher: Dispatcher?,
private val restClient: StockMediaRestClient,
private val coroutineEngine: CoroutineEngine,
private val sqlUtils: StockMediaSqlUtils,
private val mediaStore: MediaStore
) : Store(dispatcher) {
/**
* Actions: FETCH_MEDIA_LIST
*/
data class FetchStockMediaListPayload(val searchTerm: String, val page: Int) : Payload<BaseNetworkError?>()
/**
* Actions: FETCHED_MEDIA_LIST
*/
class FetchedStockMediaListPayload(
@JvmField val mediaList: List<StockMediaModel>,
@JvmField val searchTerm: String,
@JvmField val nextPage: Int,
@JvmField val canLoadMore: Boolean
) : Payload<StockMediaError?>() {
constructor(error: StockMediaError, searchTerm: String) : this(listOf(), searchTerm, 0, false) {
this.error = error
}
}
class OnStockMediaListFetched(
@JvmField val mediaList: List<StockMediaModel>,
@JvmField val searchTerm: String,
@JvmField val nextPage: Int,
@JvmField val canLoadMore: Boolean
) : OnChanged<StockMediaError?>() {
constructor(error: StockMediaError, searchTerm: String) : this(listOf(), searchTerm, 0, false) {
this.error = error
}
}
enum class StockMediaErrorType {
GENERIC_ERROR;
companion object {
// endpoint returns an empty media list for any type of error, including timeouts, server error, etc.
fun fromBaseNetworkError() = GENERIC_ERROR
}
}
data class StockMediaError(val type: StockMediaErrorType, val message: String) : OnChangedError
@Subscribe(threadMode = ASYNC)
override fun onAction(action: Action<*>) {
val actionType = action.type as? StockMediaAction ?: return
when (actionType) {
FETCH_STOCK_MEDIA -> performFetchStockMediaList(action.payload as FetchStockMediaListPayload)
}
}
override fun onRegister() {
AppLog.d(MEDIA, "StockMediaStore onRegister")
}
private fun performFetchStockMediaList(payload: FetchStockMediaListPayload) {
coroutineEngine.launch(MEDIA, this, "Fetching stock media") {
val mediaListPayload = restClient.searchStockMedia(
payload.searchTerm,
payload.page,
PAGE_SIZE
)
handleStockMediaListFetched(mediaListPayload)
}
}
suspend fun fetchStockMedia(filter: String, loadMore: Boolean): OnStockMediaListFetched {
return coroutineEngine.withDefaultContext(MEDIA, this, "Fetching stock media") {
val loadedPage = if (loadMore) {
sqlUtils.getNextPage() ?: 0
} else {
0
}
if (loadedPage == 0) {
sqlUtils.clear()
}
val payload = restClient.searchStockMedia(filter, loadedPage, PAGE_SIZE)
if (payload.isError) {
OnStockMediaListFetched(requireNotNull(payload.error), filter)
} else {
sqlUtils.insert(
loadedPage,
if (payload.canLoadMore) payload.nextPage else null,
payload.mediaList.map {
StockMediaItem(it.id, it.name, it.title, it.url, it.date, it.thumbnail)
})
OnStockMediaListFetched(payload.mediaList, filter, payload.nextPage, payload.canLoadMore)
}
}
}
suspend fun getStockMedia(): List<StockMediaItem> {
return coroutineEngine.withDefaultContext(MEDIA, this, "Getting stock media") {
sqlUtils.selectAll()
}
}
private fun handleStockMediaListFetched(payload: FetchedStockMediaListPayload) {
val onStockMediaListFetched: OnStockMediaListFetched = if (payload.isError) {
OnStockMediaListFetched(payload.error!!, payload.searchTerm)
} else {
OnStockMediaListFetched(
payload.mediaList,
payload.searchTerm,
payload.nextPage,
payload.canLoadMore
)
}
emitChange(onStockMediaListFetched)
}
suspend fun performUploadStockMedia(site: SiteModel, stockMedia: List<StockMediaUploadItem>): OnStockMediaUploaded {
return coroutineEngine.withDefaultContext(MEDIA, this, "Upload stock media") {
val payload = restClient.uploadStockMedia(site, stockMedia)
if (payload.isError) {
OnStockMediaUploaded(payload.site, payload.error!!)
} else {
// add uploaded media to the store
for (media in payload.mediaList) {
mediaStore.updateMedia(media, false)
}
OnStockMediaUploaded(payload.site, payload.mediaList)
}
}
}
companion object {
// this should be a multiple of both 3 and 4 since WPAndroid shows either 3 or 4 pics per row
const val PAGE_SIZE = 36
}
}
| gpl-2.0 | 57e9736a6f73773c084ac67bdae2f98c | 37.65 | 120 | 0.651843 | 4.939297 | false | false | false | false |
Kotlin/dokka | plugins/base/base-test-utils/src/main/kotlin/utils/TestOutputWriter.kt | 1 | 1164 | package utils
import org.jetbrains.dokka.base.DokkaBase
import org.jetbrains.dokka.base.renderers.OutputWriter
import org.jetbrains.dokka.plugability.DokkaPlugin
import java.util.*
class TestOutputWriterPlugin(failOnOverwrite: Boolean = true) : DokkaPlugin() {
val writer = TestOutputWriter(failOnOverwrite)
private val dokkaBase by lazy { plugin<DokkaBase>() }
val testWriter by extending {
(dokkaBase.outputWriter
with writer
override dokkaBase.fileWriter)
}
}
class TestOutputWriter(private val failOnOverwrite: Boolean = true) : OutputWriter {
val contents: Map<String, String> get() = _contents
private val _contents = Collections.synchronizedMap(mutableMapOf<String, String>())
override suspend fun write(path: String, text: String, ext: String) {
val fullPath = "$path$ext"
_contents.putIfAbsent(fullPath, text)?.also {
if (failOnOverwrite) throw AssertionError("File $fullPath is being overwritten.")
}
}
override suspend fun writeResources(pathFrom: String, pathTo: String) =
write(pathTo, "*** content of $pathFrom ***", "")
}
| apache-2.0 | 63acb7ae50ce8435d904c1b0cee03663 | 34.272727 | 93 | 0.697595 | 4.476923 | false | true | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/editor/text/TextHtmlPanelProvider.kt | 1 | 1164 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.editor.text
import com.intellij.openapi.project.Project
import com.vladsch.md.nav.MdBundle
import com.vladsch.md.nav.editor.HtmlPanelHost
import com.vladsch.md.nav.editor.util.HtmlCompatibility
import com.vladsch.md.nav.editor.util.HtmlPanel
import com.vladsch.md.nav.editor.util.HtmlPanelProvider
object TextHtmlPanelProvider : HtmlPanelProvider() {
val NAME = MdBundle.message("editor.text.html.panel.provider.name")
val ID = "com.vladsch.md.nav.editor.text.html.panel"
override val INFO = Info(ID, NAME)
override val COMPATIBILITY = HtmlCompatibility(ID, null, null, null, arrayOf(), arrayOf())
override fun isSupportedSetting(settingName: String): Boolean {
return false
}
override fun createHtmlPanel(project: Project, htmlPanelHost: HtmlPanelHost): HtmlPanel {
return TextHtmlPanel(project, htmlPanelHost)
}
override val isAvailable: AvailabilityInfo
get() = AvailabilityInfo.AVAILABLE
}
| apache-2.0 | 35b003c7ce8aff3aefcde1ac06be2a07 | 42.111111 | 177 | 0.762887 | 4.041667 | false | false | false | false |
Jire/layer7shield | src/main/kotlin/org/jire/layer7shield/EnableDebugPrivilege.kt | 1 | 1234 | @file:JvmName("EnableDebugPrivilege")
package org.jire.layer7shield
import com.sun.jna.Native
import com.sun.jna.platform.win32.*
fun enableDebugPrivilege() {
val hToken = WinNT.HANDLEByReference()
try {
if (!Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(),
WinNT.TOKEN_QUERY or WinNT.TOKEN_ADJUST_PRIVILEGES, hToken)) {
val lastError = Native.getLastError()
System.err.println("OpenProcessToken failed. Error: " + lastError)
throw Win32Exception(lastError)
}
val luid = WinNT.LUID()
if (!Advapi32.INSTANCE.LookupPrivilegeValue(null, WinNT.SE_DEBUG_NAME, luid)) {
val lastError = Native.getLastError()
System.err.println("LookupprivilegeValue failed. Error: " + lastError)
throw Win32Exception(lastError)
}
val tkp = WinNT.TOKEN_PRIVILEGES(1)
tkp.Privileges[0] = WinNT.LUID_AND_ATTRIBUTES(luid, WinDef.DWORD(WinNT.SE_PRIVILEGE_ENABLED.toLong()))
if (!Advapi32.INSTANCE.AdjustTokenPrivileges(hToken.value, false,
tkp, 0, null, null)) {
val lastError = Native.getLastError()
System.err.println("AdjustTokenPrivileges failed. Error: " + lastError)
throw Win32Exception(lastError)
}
} finally {
Kernel32.INSTANCE.CloseHandle(hToken.value)
}
} | agpl-3.0 | b7c28fb7e177fa1c886f0b02794fc119 | 32.378378 | 104 | 0.741491 | 3.069652 | false | false | false | false |
dataloom/conductor-client | src/test/kotlin/com/openlattice/data/storage/PostgresDataTablesTest.kt | 1 | 968 | package com.openlattice.data.storage
import com.openlattice.postgres.PostgresDataTables
import org.junit.Test
import org.slf4j.LoggerFactory
import java.util.*
/**
*
* @author Matthew Tamayo-Rios <[email protected]>
*/
class PostgresDataTablesTest {
companion object {
private val logger = LoggerFactory.getLogger(PostgresDataTablesTest::class.java)
}
@Test
fun testIds() {
logger.info("(0,0) = ${UUID(0, 0)}")
logger.info("(0,2) = ${UUID(0, 1)}")
val id = "00000000-0000-0000-8000-00000000002c"
logger.info("$id = ${UUID.fromString(id).leastSignificantBits.toInt()}")
}
@Test
fun testQuery() {
val tableDefinition = PostgresDataTables.buildDataTableDefinition()
logger.info("create table sql: {}", tableDefinition.createTableQuery())
tableDefinition.createIndexQueries.forEach { sql ->
logger.info("create index sql: {}", sql)
}
}
} | gpl-3.0 | c7e68026e030e8b8c3d05950e111282d | 28.363636 | 88 | 0.658058 | 4.067227 | false | true | false | false |
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/HomeActivity.kt | 1 | 11877 | package com.mifos.mifosxdroid
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.VisibleForTesting
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.widget.SwitchCompat
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import androidx.test.espresso.IdlingResource
import butterknife.BindView
import butterknife.ButterKnife
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.navigation.NavigationView
import com.mifos.mifosxdroid.activity.pathtracking.PathTrackingActivity
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.offline.offlinedashbarod.OfflineDashboardFragment
import com.mifos.mifosxdroid.online.GenerateCollectionSheetActivity
import com.mifos.mifosxdroid.online.RunReportsActivity
import com.mifos.mifosxdroid.online.centerlist.CenterListFragment
import com.mifos.mifosxdroid.online.checkerinbox.CheckerInboxPendingTasksActivity
import com.mifos.mifosxdroid.online.clientlist.ClientListFragment
import com.mifos.mifosxdroid.online.createnewcenter.CreateNewCenterFragment
import com.mifos.mifosxdroid.online.createnewclient.CreateNewClientFragment
import com.mifos.mifosxdroid.online.createnewgroup.CreateNewGroupFragment
import com.mifos.mifosxdroid.online.groupslist.GroupsListFragment
import com.mifos.mifosxdroid.online.search.SearchFragment
import com.mifos.utils.Constants
import com.mifos.utils.EspressoIdlingResource
import com.mifos.utils.PrefManager
/**
* Created by shashankpriyadarshi on 19/06/20.
*/
open class HomeActivity : MifosBaseActivity(), NavigationView.OnNavigationItemSelectedListener {
@BindView(R.id.navigation_view)
lateinit var mNavigationView: NavigationView
@BindView(R.id.drawer)
lateinit var mDrawerLayout: DrawerLayout
private var menu: Menu? = null
private var itemClient = true
private var itemCenter = true
private var itemGroup = true
var navController: NavController? = null
private var mNavigationHeader: View? = null
var userStatusToggle: SwitchCompat? = null
private var doubleBackToExitPressedOnce = false
var appBarConfiguration: AppBarConfiguration? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
mDrawerLayout = findViewById(R.id.drawer)
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.nav_view)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
mNavigationView = findViewById(R.id.navigation_view)
setSupportActionBar(toolbar)
navController = Navigation.findNavController(this, R.id.nav_host_fragment)
appBarConfiguration = AppBarConfiguration.Builder()
.setDrawerLayout(mDrawerLayout)
.build()
NavigationUI.setupActionBarWithNavController(this, navController!!, appBarConfiguration!!)
NavigationUI.setupWithNavController(mNavigationView, navController!!)
if (savedInstanceState == null) {
val fragment: Fragment = SearchFragment()
supportFragmentManager.beginTransaction().replace(R.id.container_a, fragment).commit()
supportActionBar!!.setTitle(R.string.dashboard)
}
bottomNavigationView.setOnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_dashboard -> {
openFragment(SearchFragment())
supportActionBar!!.setTitle(R.string.dashboard)
}
R.id.navigation_client_list -> {
openFragment(ClientListFragment())
supportActionBar!!.setTitle(R.string.clients)
}
R.id.navigation_center_list -> {
openFragment(CenterListFragment())
supportActionBar!!.setTitle(R.string.title_activity_centers)
}
R.id.navigation_group_list -> {
openFragment(GroupsListFragment())
supportActionBar!!.setTitle(R.string.title_center_list)
}
}
true
}
setupNavigationBar()
}
private fun setMenuCreateGroup(isEnabled: Boolean) {
if (menu != null) {
//position of mItem_create_new_group is 2
menu!!.getItem(2).isEnabled = isEnabled
}
}
private fun setMenuCreateCentre(isEnabled: Boolean) {
if (menu != null) {
//position of mItem_create_new_centre is 1
menu!!.getItem(1).isEnabled = isEnabled
}
}
private fun setMenuCreateClient(isEnabled: Boolean) {
if (menu != null) {
//position of mItem_create_new_client is 0
menu!!.getItem(0).isEnabled = isEnabled
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// ignore the current selected item
/*if (item.isChecked()) {
mDrawerLayout.closeDrawer(Gravity.LEFT);
return false;
}*/
clearFragmentBackStack()
val intent = Intent()
when (item.itemId) {
R.id.item_checker_inbox -> {
intent.setClass(this, CheckerInboxPendingTasksActivity::class.java);
startActivity(intent);
}
R.id.item_path_tracker -> {
intent.setClass(applicationContext, PathTrackingActivity::class.java)
startNavigationClickActivity(intent)
}
R.id.item_offline -> {
replaceFragment(OfflineDashboardFragment.newInstance(), false, R.id.container_a)
supportActionBar!!.setTitle(R.string.offline)
}
R.id.individual_collection_sheet -> {
intent.setClass(this, GenerateCollectionSheetActivity::class.java)
intent.putExtra(Constants.COLLECTION_TYPE, Constants.EXTRA_COLLECTION_INDIVIDUAL)
startActivity(intent)
}
R.id.collection_sheet -> {
intent.setClass(this, GenerateCollectionSheetActivity::class.java)
intent.putExtra(Constants.COLLECTION_TYPE, Constants.EXTRA_COLLECTION_COLLECTION)
startActivity(intent)
}
R.id.item_settings -> {
intent.setClass(this, SettingsActivity::class.java)
startActivity(intent)
}
R.id.runreport -> {
intent.setClass(this, RunReportsActivity::class.java)
startActivity(intent)
}
R.id.about -> {
intent.setClass(this, AboutActivity::class.java);
startActivity(intent);
}
}
mDrawerLayout!!.closeDrawer(GravityCompat.START)
return true
}
/**
* This SwitchCompat Toggle Handling the User Status.
* Setting the User Status to Offline or Online
*/
fun setupUserStatusToggle() {
userStatusToggle = mNavigationHeader!!.findViewById(R.id.user_status_toggle)
if (PrefManager.getUserStatus() == Constants.USER_OFFLINE) {
userStatusToggle?.isChecked = true
}
userStatusToggle?.setOnClickListener(View.OnClickListener {
if (PrefManager.getUserStatus() == Constants.USER_OFFLINE) {
PrefManager.setUserStatus(Constants.USER_ONLINE)
userStatusToggle!!.isChecked = false
} else {
PrefManager.setUserStatus(Constants.USER_OFFLINE)
userStatusToggle!!.isChecked = true
}
})
}
fun startNavigationClickActivity(intent: Intent?) {
val handler = Handler()
handler.postDelayed({ startActivity(intent) }, 500)
}
/**
* downloads the logged in user's username
* sets dummy profile picture as no profile picture attribute available
*/
private fun loadClientDetails() {
// download logged in user
val loggedInUser = PrefManager.getUser()
val textViewUsername = ButterKnife.findById<TextView>(mNavigationHeader!!, R.id.tv_user_name)
textViewUsername.text = loggedInUser.username
// no profile picture credential, using dummy profile picture
val imageViewUserPicture = ButterKnife
.findById<ImageView>(mNavigationHeader!!, R.id.iv_user_picture)
imageViewUserPicture.setImageResource(R.drawable.ic_dp_placeholder)
}
override fun onBackPressed() {
// check if the nav mDrawer is open
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START)
} else {
if (doubleBackToExitPressedOnce) {
setMenuCreateClient(true)
setMenuCreateCentre(true)
setMenuCreateGroup(true)
super.onBackPressed()
return
}
doubleBackToExitPressedOnce = true
Toast.makeText(this, R.string.back_again, Toast.LENGTH_SHORT).show()
Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000)
}
}
@get:VisibleForTesting
val countingIdlingResource: IdlingResource
get() = EspressoIdlingResource.getIdlingResource()
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp(navController!!, appBarConfiguration!!)
}
protected fun setupNavigationBar() {
mNavigationHeader = mNavigationView.getHeaderView(0)
setupUserStatusToggle()
mNavigationView.setNavigationItemSelectedListener(this as NavigationView.OnNavigationItemSelectedListener)
// setup drawer layout and sync to toolbar
val actionBarDrawerToggle: ActionBarDrawerToggle = object : ActionBarDrawerToggle(this,
mDrawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer) {
override fun onDrawerClosed(drawerView: View) {
super.onDrawerClosed(drawerView)
}
override fun onDrawerOpened(drawerView: View) {
super.onDrawerOpened(drawerView)
setUserStatus(userStatusToggle)
hideKeyboard(mDrawerLayout)
}
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
if (slideOffset != 0f) super.onDrawerSlide(drawerView, slideOffset)
}
}
mDrawerLayout.addDrawerListener(actionBarDrawerToggle)
actionBarDrawerToggle.syncState()
// make an API call to fetch logged in client's details
loadClientDetails()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
this.menu = menu
menuInflater.inflate(R.menu.menu_main, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.logout) {
logout()
}
return super.onOptionsItemSelected(item)
}
fun openFragment(fragment: Fragment?) {
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.container_a, fragment!!)
transaction.addToBackStack(null)
transaction.commit()
}
} | mpl-2.0 | 5a62c61b1c689bdcd85d55e3a338534d | 38.461794 | 114 | 0.666667 | 5.188729 | false | false | false | false |
SirWellington/alchemy-http | src/main/java/tech/sirwellington/alchemy/http/Step4Impl.kt | 1 | 2316 | /*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.http
import tech.sirwellington.alchemy.annotations.access.Internal
import tech.sirwellington.alchemy.annotations.designs.StepMachineDesign
import tech.sirwellington.alchemy.annotations.designs.StepMachineDesign.Role.STEP
import tech.sirwellington.alchemy.arguments.Arguments.checkThat
import tech.sirwellington.alchemy.http.HttpAssertions.validResponseClass
import tech.sirwellington.alchemy.http.exceptions.AlchemyHttpException
import java.net.URL
/**
*
* @author SirWellington
*/
@Internal
@StepMachineDesign(role = STEP)
internal class Step4Impl<ResponseType>(private val stateMachine: AlchemyHttpStateMachine,
private val request: HttpRequest,
private val classOfResponseType: Class<ResponseType>) : AlchemyRequestSteps.Step4<ResponseType>
{
init
{
checkThat(classOfResponseType).isA(validResponseClass())
}
@Throws(AlchemyHttpException::class)
override fun at(url: URL): ResponseType
{
val newRequest = HttpRequest.Builder
.from(request)
.usingUrl(url)
.build()
return stateMachine.executeSync(newRequest, classOfResponseType)
}
override fun onSuccess(onSuccessCallback: AlchemyRequestSteps.OnSuccess<ResponseType>): AlchemyRequestSteps.Step5<ResponseType>
{
return stateMachine.jumpToStep5(request, classOfResponseType, onSuccessCallback)
}
override fun toString(): String
{
return "Step4Impl{stateMachine=$stateMachine, request=$request, classOfResponseType=$classOfResponseType}"
}
}
| apache-2.0 | 0e00beba1debfc44c2714a5821111717 | 36.33871 | 134 | 0.711015 | 4.802905 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/validator/AddAlsoShopForInsurance.kt | 1 | 1179 | package de.westnordost.streetcomplete.quests.validator
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddAlsoShopForInsurance() : OsmFilterQuestType<Boolean>() {
override val elementFilter = "nodes, ways, relations with office=insurance and !shop and name"
override val commitMessage = "better tagging for insurance shop"
override val icon = R.drawable.ic_quest_power
override fun getTitle(tags: Map<String, String>) = R.string.quest_add_also_shop_variant_for_insurance_shop
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
if (answer){
changes.add("shop", "insurance");
}
}
override val wikiLink = "Tag:shop=insurance"
override val questTypeAchievements: List<QuestTypeAchievement>
get() = listOf()
}
| gpl-3.0 | c1d50ede2dd3bd1182b42d2ab22a3791 | 39.655172 | 110 | 0.770144 | 4.569767 | false | false | false | false |
yujintao529/android_practice | MyPractice/app/src/main/java/com/demon/yu/avatar/interact/CloneXComposeLayoutManager.kt | 1 | 25786 | package com.demon.yu.avatar.interact
import android.content.Context
import android.graphics.*
import android.util.Pair
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import androidx.core.os.TraceCompat
import androidx.recyclerview.widget.AvatarLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.demon.yu.extenstion.dp2Px
import com.demon.yu.view.recyclerview.*
import com.example.mypractice.BuildConfig
import com.example.mypractice.Logger
import com.example.mypractice.common.Common
import kotlin.math.*
class CloneXComposeLayoutManager(val context: Context) : AvatarLayoutManager(),
CloneXComposeRecyclerView.OnDrawListener {
companion object {
private const val TAG = "CloneXComposeLayoutManager"
}
private var measuredWidth: Int = 0
private var measuredHeight: Int = 0
private var centerX: Int = 0
private var centerY: Int = 0
private var radius: Int = CloneXComposeUiConfig.RADIUS
private var maxScaleSize = CloneXComposeUiConfig.MAX_SCALE
private var secondScaleSize = CloneXComposeUiConfig.SECOND_MAX_SCALE
private var dismiss2NormalScaleDistance = CloneXComposeUiConfig.DISMISS_2_NORMAL_SCALE_DISTANCE
private var radiusDouble = radius * 2
private var scaleDistance = radiusDouble
private val coordinateCache: SparseArray<Point> = SparseArray(200)
private var cloneXComposeRecyclerView: CloneXComposeRecyclerView? = null
private var maxCircleRadius = 0
private var currentPosition: Int = -1
var onCenterChangedListener: OnCenterChangedListener? = null
private val layoutState = LayoutState()
//仅支持matchParent及exactly width/height
override fun onMeasure(
recycler: RecyclerView.Recycler,
state: RecyclerView.State,
widthSpec: Int,
heightSpec: Int
) {
// super.onMeasure(recycler, state, widthSpec, heightSpec)
measuredWidth = View.MeasureSpec.getSize(widthSpec)
measuredHeight = View.MeasureSpec.getSize(heightSpec)
setMeasuredDimension(measuredWidth, measuredHeight)
centerX = measuredWidth / 2
centerY = measuredHeight / 2
scaleDistance =
(2 * cos(PI / 6) * radius).toInt() + (radiusDouble - (2 * cos(PI / 6) * radius).toInt()) / 6
Logger.debug("AvatarComposeLayoutManager", "onMeasure centerX=$centerX,centerY=$centerY")
offsetShowRegion()
}
override fun setRecyclerView(recyclerView: RecyclerView?) {
super.setRecyclerView(recyclerView)
cloneXComposeRecyclerView = recyclerView as? CloneXComposeRecyclerView
cloneXComposeRecyclerView?.onDrawListener = this
}
//关闭
override fun isMeasurementCacheEnabled(): Boolean {
return false
}
override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
if (itemCount == 0) {
removeAndRecycleAllViews(recycler);
return
}
offsetShowRegion()
detachAndScrapAttachedViews(recycler)
clearCoordinateCacheIfNeed(state.itemCount)
fill(recycler, state, true)
recycleScrapViews(recycler)
}
/**
* 回收所有没有使用的scrapViews
*/
private fun recycleScrapViews(recycler: RecyclerView.Recycler) {
Logger.debug(
CloneXComposeUiConfig.TAG,
"recycleScrapViews scrapSize = " + recycler.scrapList.size
)
val list = recycler.scrapList.toList()
for (element in list) {
removeAndRecycleView(element.itemView, recycler)
}
}
private val viewRegion = Rect()
private var lastChildCount = 0
private fun clearCoordinateCacheIfNeed(currentCount: Int) {
if ((lastChildCount >= 7 && currentCount < 7) || (lastChildCount < 7 && currentCount >= 7)
|| (lastChildCount < 7 && currentCount != lastChildCount)
) {
coordinateCache.clear()
}
lastChildCount = currentCount
}
private fun fill(
recycler: RecyclerView.Recycler,
state: RecyclerView.State,
checkFillStatus: Boolean
) {
fillInternal(recycler, state)
val itemCount = getItemCount(state)
if (itemCount > 0 && childCount == 0 && checkFillStatus) {
layoutState.reset()
fillInternal(recycler, state)
calculateViewRegion(state)
} else {
calculateViewRegion(state)
}
if (checkFillStatus) {
if ((layoutState.scrollY != 0 || layoutState.scrollX != 0) && layoutState.minCloseDistance != 0f) {
scrollToPosition(currentPosition)
}
}
}
private fun fillInternal(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
val visibleChildCount = getItemCount(state)
var destPosition: Int = -1
var destChildDistance = 0f
var minCloseDistance: Float = Float.MAX_VALUE
TraceCompat.beginSection("CCLM fill")
// for (position in visibleChildCount - 1 downTo 0) {
for (position in 0 until visibleChildCount) {
val point = calculateChildCoordinate(position, visibleChildCount)
if (layoutState.showRegion.contains(point.x, point.y).not()) {
continue
}
val view = recycler.getViewForPosition(position) //会处理
if (view.parent == null) {
addView(view)
measureChildWithMargins(view, 0, 0)
layoutChildInternal(view, position, point)
FakeLayoutCoorExchangeUtils.setCenterPivot(view)
}
offsetChildHorAndVer(view, -layoutState.scrollX, -layoutState.scrollY)
destChildDistance = shapeChange(view, position)
TraceCompat.beginSection("CCLM fill bindRealViewHolderIfNeed")
bindRealViewHolderIfNeed(view, position)
TraceCompat.endSection()
if (destChildDistance < minCloseDistance) {
minCloseDistance = destChildDistance
destPosition = position
}
}
if(destPosition!=-1){
layoutState.minCloseDistance = minCloseDistance
setCenterPosition(destPosition)
}
}
private fun calculateViewRegion(state: RecyclerView.State) {
if (getItemCount(state) == 1) {
maxCircleRadius = radius
val left = (measuredWidth - maxCircleRadius * 2) / 2
val top = (measuredHeight - maxCircleRadius * 2) / 2
viewRegion.set(
left,
top,
left + maxCircleRadius * 2,
top + maxCircleRadius * 2
) //找到四周的范围
} else {
viewRegion.set(find4Coordinate()) //找到四周的范围
val point = getCenterPoint()
val centerDiffX = abs(viewRegion.exactCenterX() - point.x)
val centerDiffY = abs(viewRegion.exactCenterY() - point.y)
val radiusDiff = calDistance(centerDiffX.toInt(), centerDiffY.toInt())
maxCircleRadius =
(max(viewRegion.width(), viewRegion.height()) / 2 + radiusDiff).toInt()
}
Logger.debug(
CloneXComposeUiConfig.TAG,
"viewRegion = $viewRegion, maxCircleRadius= $maxCircleRadius"
)
TraceCompat.endSection()
}
override fun scrollToPosition(position: Int) {
val centerChild = findViewByPosition(position) ?: return
val childPoint = FakeLayoutCoorExchangeUtils.getCenterPoint(centerChild)
val diffX = centerX - childPoint.x
val diffY = centerY - childPoint.y
layoutState.scrollX -= diffX
layoutState.scrollY -= diffY
postOnAnimation {
requestLayout()
}
}
override fun smoothScrollToPosition(
recyclerView: RecyclerView?,
state: RecyclerView.State?,
position: Int
) {
cloneXComposeRecyclerView?.scrollCenterToPosition(position)
}
fun calculateDistance(x: Int, y: Int): Float {
return calDistance(x - centerX, y - centerY)
}
private fun calDistance(x: Int, y: Int): Float {
return sqrt(abs(x).toDouble().pow(2) + abs(y).toDouble().pow(2)).toFloat()
}
private fun getCenterPoint(): Point {
return cloneXComposeRecyclerView?.getCenterPoint() ?: Point(
Common.screenWidth / 2,
Common.screenHeight / 2
)
}
private fun layoutChildInternal(view: View, position: Int, point: Point) {
val childWidth = view.measuredWidth
val childHeight = view.measuredHeight
FakeLayoutCoorExchangeUtils.shiftingLayout(view, point) { left, top ->
layoutDecorated(
view,
left,
top,
left + childWidth,
top + childHeight
)
}
}
private fun shapeChange(child: View, position: Int): Float {
val childPoint = FakeLayoutCoorExchangeUtils.getCenterPoint(child)
val destChildDistance = calculateDistance(childPoint.x, childPoint.y)
translateXY(
child,
childPoint.x,
childPoint.y,
destChildDistance
)
scaleXY(child, childPoint.x, childPoint.y, destChildDistance)
return destChildDistance
}
private fun setCenterPosition(destPosition: Int) {
val lastPosition = currentPosition
if (lastPosition != destPosition) {
currentPosition = destPosition
notifyCenterChanged(lastPosition, currentPosition)
}
}
private fun notifyCenterChanged(lastPosition: Int, currentPosition: Int) {
onCenterChangedListener?.onCenter(lastPosition, currentPosition)
}
private fun calculateChildCoordinate(position: Int, childCount: Int): Point {
var cache = coordinateCache.get(position)
// if (cache != null) {
// return cache
// }
if (position == 0) {
cache = Point(measuredWidth / 2, measuredHeight / 2)
coordinateCache.put(position, cache)
return cache
} else {
cache = coordinateCache.get(0)
if (cache == null) {
cache = Point(measuredWidth / 2, measuredHeight / 2)
coordinateCache.put(0, cache)
}
}
val zero = coordinateCache.get(0)
val dest: Point = if (childCount >= 7) {
calculateCenteredHexagonalCoordinate(position, radius, zero.x, zero.y).toPoint()
} else {
calculateCoordinate(position, radius, childCount, zero.x, zero.y).toPoint()
}
coordinateCache.put(position, dest)
return dest
}
//先不复用的view的场景下也就是所有的view都添加的情况下,找到最上,最左,最右,最下的坐标,用来辅助是否可以滑动的情况
private fun find4Coordinate(): Rect {
val rect = Rect()
val count = coordinateCache.size()
for (position in 0 until count) {
val value = coordinateCache.valueAt(position)
if (value.x < rect.left || rect.left == 0) {
rect.left = value.x
}
if (value.x > rect.right || rect.right == 0) {
rect.right = value.x
}
if (value.y < rect.top || rect.top == 0) {
rect.top = value.y
}
if (value.y > rect.bottom || rect.bottom == 0) {
rect.bottom = value.y
}
}
return rect
}
private fun calculateCoordinate(
index: Int,
radius: Int,
childCount: Int,
centerX: Int,
centerY: Int
): DPoint {
if (childCount == 1 || childCount >= 7 || index == 0) {
throw IllegalAccessException("not suppose to be here childCount=$childCount,index=$index")
}
if (childCount == 2) {
return DPoint(centerX.toDouble(), (centerY - radius).toDouble())
}
val avgAngle = Math.PI * 2 / (childCount - 1)
when (childCount) {
3 -> {
return if (index == 1) {
DPoint((centerX + radius).toDouble(), centerY.toDouble())
} else {
DPoint((centerX - radius).toDouble(), centerY.toDouble())
}
}
4, 6 -> {
val x = sin(avgAngle * (index - 1)) * radius
val y = cos(avgAngle * (index - 1)) * radius
return DPoint(centerX + x, centerY - y)
}
5 -> {
val x = sin(Math.PI / 4 + avgAngle * (index - 1)) * radius
val y = cos(Math.PI / 4 + avgAngle * (index - 1)) * radius
return DPoint(centerX + x, centerY - y)
}
}
throw IllegalAccessException("not suppose to be here | end")
}
/**
* 6变形的布局结构,非正规,按照设计有特殊规则。
*/
private fun calculateCenteredHexagonalCoordinate(
index: Int,
radius: Int,
centerX: Int,
centerY: Int
): DPoint {
val du = PI / 3.0
val result = DPoint(0.0, 0.0)
val hexagonalPoint = calculateHexagonalPoint(index)
val level = hexagonalPoint.level
if (level == 1) {
return DPoint(centerX.toDouble(), centerY.toDouble())
} else if (level == 2) {
return DPoint(
centerX - radius * cos(du * hexagonalPoint.levelNumber),
centerY - radius * sin(du * hexagonalPoint.levelNumber)
)
} else if (level == 3) {
var itemGroup = ceil((hexagonalPoint.levelNumber.toDouble() / (level - 1))).toInt()
var itemGroupNum = hexagonalPoint.levelNumber - (itemGroup - 1) * (level - 1)
when (itemGroup) {
1 -> {
if (itemGroupNum == 1) {
itemGroup = 1
itemGroupNum = 2
} else {
itemGroup = 4
itemGroupNum = 2
}
}
2 -> {
if (itemGroupNum == 1) {
itemGroup = 2
itemGroupNum = 2
} else {
itemGroup = 6
itemGroupNum = 2
}
}
3 -> {
if (itemGroupNum == 1) {
itemGroup = 3
itemGroupNum = 2
} else {
itemGroup = 5
itemGroupNum = 2
}
}
4 -> {
if (itemGroupNum == 1) {
itemGroup = 2
itemGroupNum = 1
} else {
itemGroup = 1
itemGroupNum = 1
}
}
5 -> {
if (itemGroupNum == 1) {
itemGroup = 4
itemGroupNum = 1
} else {
itemGroup = 5
itemGroupNum = 1
}
}
6 -> {
if (itemGroupNum == 1) {
itemGroup = 3
itemGroupNum = 1
} else {
itemGroup = 6
itemGroupNum = 1
}
}
}
val tempPointX = centerX - (level - 1) * radius * cos((du * itemGroup))
val tempPointY = centerY - (level - 1) * radius * sin((du * itemGroup))
if (itemGroup == 1) {
result.x = tempPointX + radius * (itemGroupNum - 1)
result.y = tempPointY
} else if (itemGroup == 2) {
result.x = tempPointX + radius * cos(du) * (itemGroupNum - 1)
result.y = tempPointY + radius * sin(du) * (itemGroupNum - 1)
} else if (itemGroup == 3) {
result.x = tempPointX - radius * cos(du) * (itemGroupNum - 1)
result.y = tempPointY + radius * sin(du) * (itemGroupNum - 1)
} else if (itemGroup == 4) {
result.x = tempPointX - radius * (itemGroupNum - 1)
result.y = tempPointY
} else if (itemGroup == 5) {
result.x = tempPointX - radius * cos(du) * (itemGroupNum - 1)
result.y = tempPointY - radius * sin(du) * (itemGroupNum - 1)
} else if (itemGroup == 6) {
result.x = tempPointX + radius * cos(du) * (itemGroupNum - 1)
result.y = tempPointY - radius * sin(du) * (itemGroupNum - 1)
}
return result
} else {
val itemGroup = ceil((hexagonalPoint.levelNumber.toDouble() / (level - 1))).toInt()
val itemGroupNum = hexagonalPoint.levelNumber - (itemGroup - 1) * (level - 1)
val tempPointX = centerX - (level - 1) * radius * cos((du * itemGroup))
val tempPointY = centerY - (level - 1) * radius * sin((du * itemGroup))
if (itemGroup == 1) {
result.x = tempPointX + radius * (itemGroupNum - 1)
result.y = tempPointY
} else if (itemGroup == 2) {
result.x = tempPointX + radius * cos(du) * (itemGroupNum - 1)
result.y = tempPointY + radius * sin(du) * (itemGroupNum - 1)
} else if (itemGroup == 3) {
result.x = tempPointX - radius * cos(du) * (itemGroupNum - 1)
result.y = tempPointY + radius * sin(du) * (itemGroupNum - 1)
} else if (itemGroup == 4) {
result.x = tempPointX - radius * (itemGroupNum - 1)
result.y = tempPointY
} else if (itemGroup == 5) {
result.x = tempPointX - radius * cos(du) * (itemGroupNum - 1)
result.y = tempPointY - radius * sin(du) * (itemGroupNum - 1)
} else if (itemGroup == 6) {
result.x = tempPointX + radius * cos(du) * (itemGroupNum - 1)
result.y = tempPointY - radius * sin(du) * (itemGroupNum - 1)
}
return result
}
}
/**
* 3n(2) -3n + 1
*/
private fun calculateLevel(number: Int): Int {
for (level in 1..100) {
if (number > calFormulaCount(level) && number <= calFormulaCount(level + 1)) {
return level + 1
}
}
return -1
}
private fun calculateHexagonalPoint(index: Int): HexagonalPoint {
val result = HexagonalPoint(index = index)
assert(index != 0)
result.level = calculateLevel(index + 1)
result.levelNumber = index + 1 - calFormulaCount(result.level - 1)
return result
}
private fun scaleXY(view: View, x: Int, y: Int, distance: Float) {
val scale = when {
distance >= 0 && distance <= radius -> {
val scale =
(radius - distance) / (radius) * (maxScaleSize - secondScaleSize)
scale + secondScaleSize
}
distance > radius && distance <= scaleDistance -> { //0...secondScaleSize,不要问我怎么算的
val ratio =
max(
0f,
StrictMath.min(
((StrictMath.abs((y - centerY))) / (distance)),
1f
)
)
val scale = (scaleDistance - distance) / (scaleDistance - radius)
val scaleRatio =
secondScaleSize + StrictMath.pow(ratio.toDouble(), 6.0) * 2.5f
StrictMath.min(secondScaleSize, 1 + scale * (scaleRatio.toFloat() - 1))
}
distance > scaleDistance -> {
val scale =
(distance - scaleDistance + dismiss2NormalScaleDistance) / dismiss2NormalScaleDistance - 1 //0...max
max(0f, 1 - StrictMath.pow(scale.toDouble(), 6.0).toFloat()) // 0..1
}
else -> {
0f
}
}
view.scaleX = scale
view.scaleY = scale
}
private fun translateXY(view: View, x: Int, y: Int, distance: Float) {
val translateRange = radius
val centerPoint = getCenterPoint()
val centerX = centerPoint.x
val centerY = centerPoint.y
if (distance <= translateRange) {
view.translationX = 0f
view.translationY = 0f
return
}
when {
else -> {
val magnitude = (distance - translateRange) * 0.35f/// translateRange * 124f
val cos = StrictMath.abs((centerY - y) / distance)
val ratio = 1f - 0.5 * (StrictMath.pow(cos.toDouble(), 8.0))
val magnitudeX = centerX - (centerX - x) * (distance - magnitude) / distance
view.translationX = ((magnitudeX - x) * ratio).toFloat()
val magnitudeY = centerY - (centerY - y) * (distance - magnitude) / distance
view.translationY = ((magnitudeY - y) * ratio).toFloat()
}
}
}
private fun calFormulaCount(level: Int): Int {
return 3 * level.toDouble().pow(2.0).toInt() - 3 * level + 1
}
private fun getItemCount(state: RecyclerView.State): Int {
return state.itemCount
}
override fun onLayoutCompleted(state: RecyclerView.State) {
super.onLayoutCompleted(state)
}
override fun scrollHorAndVerBy(
dx: Int,
dy: Int,
recycler: RecyclerView.Recycler,
state: RecyclerView.State
): Pair<Int, Int> {
if (dx == 0 && dy == 0) {
return Pair(0, 0)
}
val scrollXY = checkIfScroll(dx, dy)
if (scrollXY.first == 0 && scrollXY.second == 0) {
return Pair(0, 0)
}
layoutState.scrollX += scrollXY.first
layoutState.scrollY += scrollXY.second
offsetShowRegion()
detachAndScrapAttachedViews(recycler)
fill(recycler, state, false)
recycleScrapViews(recycler)
// offsetChild(-dx, -dy, state)
return Pair(dx, dy)
}
private fun offsetShowRegion() {
val len = 50.dp2Px()
layoutState.showRegion.set(
-len,
-len,
measuredWidth + len,
measuredHeight + len
)
layoutState.showRegion.offset(layoutState.scrollX, layoutState.scrollY)
}
private fun offsetChild(dx: Int, dy: Int, state: RecyclerView.State) {
val childCount = getItemCount(state)
var destPosition: Int = 0
var destChildDistance = 0f
var minCloseDistance: Float = Float.MAX_VALUE
for (position in 0 until childCount) {
val child = findViewByPosition(position)
if (child != null) {
offsetChildHorAndVer(child, dx, dy)
destChildDistance = shapeChange(child, position)
bindRealViewHolderIfNeed(child, position)
}
if (destChildDistance < minCloseDistance) {
minCloseDistance = destChildDistance
destPosition = position
}
}
setCenterPosition(destPosition)
}
private fun checkIfScroll(dx: Int, dy: Int): Pair<Int, Int> {
val distance = calDistance(layoutState.scrollX + dx, layoutState.scrollY + dy)
val maxDistance = maxCircleRadius.toFloat() + 100.dp2Px()
if (distance <= maxDistance) {
return Pair.create(dx, dy)
} else {
return Pair.create(0, 0)
}
}
override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
return RecyclerView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
}
interface OnCenterChangedListener {
fun onCenter(lastPosition: Int, currentPosition: Int)
}
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.CYAN
style = Paint.Style.STROKE
strokeWidth = 5f
}
override fun onDraw(canvas: Canvas) {
if (BuildConfig.DEBUG.not()) {
return
}
val restore = canvas.save()
paint.strokeWidth = 5f
canvas.translate(-layoutState.scrollX.toFloat(), -layoutState.scrollY.toFloat())
canvas.drawRect(viewRegion, paint)
canvas.drawCircle(
getCenterPoint().x.toFloat(),
getCenterPoint().y.toFloat(),
maxCircleRadius.toFloat(),
paint
)
paint.strokeWidth = 10f
canvas.drawPoint(viewRegion.exactCenterX(), viewRegion.exactCenterY(), paint)
canvas.restoreToCount(restore)
}
/**
* 滚动处理逻辑梳理:
* 1. 收集滚动信息
* 2. 滚动不处理detach/remove,只处理添加
*/
private inner class LayoutState {
var scrollX: Int = 0
var scrollY: Int = 0
var showRegion = Rect()
var minCloseDistance: Float = 0f
fun reset() {
scrollX = 0
scrollY = 0
minCloseDistance = 0f
showRegion.set(0, 0, measuredWidth, measuredHeight)
}
}
}
| apache-2.0 | c0c76d29b1b7d97cb5032a517c617f24 | 34.032967 | 120 | 0.546267 | 4.551035 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/mappers/GeekListMapper.kt | 1 | 2707 | package com.boardgamegeek.mappers
import com.boardgamegeek.entities.GeekListCommentEntity
import com.boardgamegeek.entities.GeekListEntity
import com.boardgamegeek.entities.GeekListItemEntity
import com.boardgamegeek.extensions.toMillis
import com.boardgamegeek.io.model.*
import com.boardgamegeek.provider.BggContract
import java.text.SimpleDateFormat
import java.util.*
fun GeekListsResponse.mapToEntity() = this.lists.map { it.mapToEntity() }
fun GeekListResponse.mapToEntity() = GeekListEntity(
id = id,
title = title.orEmpty().trim(),
username = username.orEmpty(),
description = description.orEmpty().trim(),
numberOfItems = numitems.toIntOrNull() ?: 0,
numberOfThumbs = thumbs.toIntOrNull() ?: 0,
postTicks = postdate.toMillis(FORMAT),
editTicks = editdate.toMillis(FORMAT),
items = items?.map { it.mapToEntity() }.orEmpty(),
comments = comments.mapToEntity()
)
fun GeekListEntry.mapToEntity(): GeekListEntity {
val id = if (this.href.isEmpty()) {
BggContract.INVALID_ID
} else {
this.href.substring(
this.href.indexOf("/geeklist/") + 10,
this.href.lastIndexOf("/"),
).toIntOrNull() ?: BggContract.INVALID_ID
}
return GeekListEntity(
id = id,
title = this.title.orEmpty().trim(),
username = this.username.orEmpty().trim(),
numberOfItems = this.numitems,
numberOfThumbs = this.numpositive
)
}
private fun GeekListItem.mapToEntity() = GeekListItemEntity(
id = this.id.toLongOrNull() ?: BggContract.INVALID_ID.toLong(),
objectId = this.objectid.toIntOrNull() ?: BggContract.INVALID_ID,
objectName = this.objectname.orEmpty(),
objectType = this.objecttype.orEmpty(),
subtype = this.subtype.orEmpty(),
imageId = this.imageid.toIntOrNull() ?: 0,
username = this.username.orEmpty(),
body = this.body.orEmpty(),
numberOfThumbs = this.thumbs.toIntOrNull() ?: 0,
postDateTime = this.postdate.toMillis(FORMAT),
editDateTime = this.editdate.toMillis(FORMAT),
comments = this.comments.mapToEntity()
)
private fun GeekListComment.mapToEntity() = GeekListCommentEntity(
postDate = this.postdate.toMillis(FORMAT),
editDate = this.editdate.toMillis(FORMAT),
numberOfThumbs = this.thumbs.toIntOrNull() ?: 0,
username = this.username.orEmpty(),
content = this.content.orEmpty().trim()
)
private fun List<GeekListComment>?.mapToEntity() = this?.map { it.mapToEntity() }.orEmpty()
private val FORMAT = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US)
| gpl-3.0 | 1b3148ca3a3e44362f6af945289ef70a | 37.671429 | 91 | 0.66679 | 4.177469 | false | false | false | false |
fossasia/open-event-android | app/src/playStore/java/org/fossasia/openevent/general/search/location/LocationServiceImpl.kt | 1 | 3425 | package org.fossasia.openevent.general.search.location
import android.content.Context
import android.location.Geocoder
import android.location.LocationManager
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import io.reactivex.Single
import java.io.IOException
import java.lang.Exception
import java.util.Locale
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.location.LocationPermissionException
import org.fossasia.openevent.general.location.NoLocationSourceException
import org.fossasia.openevent.general.utils.nullToEmpty
import timber.log.Timber
class LocationServiceImpl(
private val context: Context,
private val resource: Resource
) : LocationService {
override fun getAdministrativeArea(): Single<String> {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE)
if (locationManager !is LocationManager) {
return Single.error(IllegalStateException())
}
if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
return Single.error(NoLocationSourceException())
}
val locationRequest = LocationRequest.create().apply {
priority = LocationRequest.PRIORITY_LOW_POWER
}
return Single.create { emitter ->
try {
LocationServices
.getFusedLocationProviderClient(context)
.requestLocationUpdates(locationRequest, object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
if (locationResult == null) {
emitter.onError(IllegalStateException())
return
}
try {
val adminArea = locationResult.getAdminArea()
emitter.onSuccess(adminArea)
} catch (e: Exception) {
Timber.e(e, "Error finding user current location")
emitter.onSuccess(resource.getString(R.string.no_location).nullToEmpty())
}
}
}, null)
} catch (e: SecurityException) {
emitter.onError(LocationPermissionException())
}
}
}
private fun LocationResult.getAdminArea(): String {
locations.filterNotNull().forEach { location ->
val latitude = location.latitude
val longitude = location.longitude
try {
val maxResults = 2
val geocoder = Geocoder(context, Locale.getDefault())
val addresses = geocoder.getFromLocation(latitude, longitude, maxResults)
val address = addresses.first { address -> address.adminArea != null }
return address.adminArea
} catch (exception: IOException) {
Timber.e(exception, "Error Fetching Location")
throw IllegalArgumentException()
}
}
throw IllegalArgumentException()
}
}
| apache-2.0 | 2ec3192a89cf229cb3d67bb1639495a0 | 40.26506 | 105 | 0.61781 | 5.737018 | false | false | false | false |
Pluckypan/bigAndroid | app/src/main/java/engineer/echo/bigandroid/swipe/rangeview/RangeView.kt | 1 | 12772 | package com.iammert.rangeview.library
import android.content.Context
import android.graphics.*
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import engineer.echo.bigandroid.R
class RangeView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) {
interface OnRangeValueListener {
fun rangeChanged(maxValue: Float, minValue: Float, currentLeftValue: Float, currentRightValue: Float)
}
interface OnRangePositionListener {
fun leftTogglePositionChanged(xCoordinate: Float, value: Float)
fun rightTogglePositionChanged(xCoordinate: Float, value: Float)
}
interface OnRangeDraggingListener {
fun onDraggingStateChanged(draggingState: DraggingState)
}
var rangeValueChangeListener: OnRangeValueListener? = null
var rangePositionChangeListener: OnRangePositionListener? = null
var rangeDraggingChangeListener: OnRangeDraggingListener? = null
private var maxValue: Float = DEFAULT_MAX_VALUE
private var minValue: Float = DEFAULT_MIN_VALUE
private var currentLeftValue: Float? = null
private var currentRightValue: Float? = null
private var bgColor: Int = ContextCompat.getColor(context, R.color.rangeView_colorBackground)
private var strokeColor: Int = ContextCompat.getColor(context, R.color.rangeView_colorStroke)
private var maskColor: Int = ContextCompat.getColor(context, R.color.rangeView_colorMask)
private var strokeWidth: Float = resources.getDimension(R.dimen.rangeView_StrokeWidth)
private var toggleRadius: Float = resources.getDimension(R.dimen.rangeView_ToggleRadius)
private var horizontalMargin: Float = resources.getDimension(R.dimen.rangeView_HorizontalSpace)
private var bitmap: Bitmap? = null
private var canvas: Canvas? = null
private var backgroundBitmap: Bitmap? = null
private var backgroundCanvas: Canvas? = null
private val eraser: Paint = Paint().apply {
color = -0x1
xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
flags = Paint.ANTI_ALIAS_FLAG
}
private var backgroundPaint: Paint = Paint().apply {
style = Paint.Style.FILL
flags = Paint.ANTI_ALIAS_FLAG
}
private var maskPaint: Paint = Paint().apply {
style = Paint.Style.FILL
color = maskColor
flags = Paint.ANTI_ALIAS_FLAG
}
private var rangeStrokePaint: Paint = Paint().apply {
style = Paint.Style.STROKE
flags = Paint.ANTI_ALIAS_FLAG
strokeWidth = [email protected]
}
private var rangeTogglePaint: Paint = Paint().apply {
style = Paint.Style.FILL
color = strokeColor
flags = Paint.ANTI_ALIAS_FLAG
}
private var draggingStateData: DraggingStateData = DraggingStateData.idle()
private val totalValueRect: RectF = RectF()
private val rangeValueRectF: RectF = RectF()
private val rangeStrokeRectF: RectF = RectF()
init {
val a = context.obtainStyledAttributes(attrs, R.styleable.RangeView)
bgColor = a.getColor(R.styleable.RangeView_colorBackground, bgColor)
strokeColor = a.getColor(R.styleable.RangeView_colorStroke, strokeColor)
minValue = a.getFloat(R.styleable.RangeView_minValue, minValue)
maxValue = a.getFloat(R.styleable.RangeView_maxValue, maxValue)
backgroundPaint.color = bgColor
rangeStrokePaint.color = strokeColor
rangeTogglePaint.color = strokeColor
a.recycle()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
totalValueRect.set(0f + horizontalMargin, 0f, measuredWidth.toFloat() - horizontalMargin, measuredHeight.toFloat())
if (currentLeftValue == null || currentRightValue == null) {
rangeValueRectF.set(
totalValueRect.left,
totalValueRect.top,
totalValueRect.right,
totalValueRect.bottom)
} else {
val leftRangePosition = ((totalValueRect.width()) * currentLeftValue!!) / maxValue
val rightRangePosition = (totalValueRect.width() * currentRightValue!!) / maxValue
rangeValueRectF.set(
leftRangePosition + horizontalMargin,
totalValueRect.top,
rightRangePosition + horizontalMargin,
totalValueRect.bottom)
}
rangeStrokeRectF.set(rangeValueRectF.left,
rangeValueRectF.top + strokeWidth / 2,
rangeValueRectF.right,
rangeValueRectF.bottom - strokeWidth / 2)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
initializeBitmap()
//Draw background color
this.backgroundCanvas?.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
this.backgroundCanvas?.drawRect(totalValueRect, backgroundPaint)
//Draw mask
this.canvas?.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
this.canvas?.drawRect(totalValueRect, maskPaint)
//Clear range rectangle
this.canvas?.drawRect(rangeValueRectF, eraser)
//Draw range rectangle stroke
this.canvas?.drawRect(rangeStrokeRectF, rangeStrokePaint)
//Draw left toggle over range stroke
val cxLeft = rangeValueRectF.left
val cyLeft = height.toFloat() / 2
this.canvas?.drawCircle(cxLeft, cyLeft, toggleRadius, rangeTogglePaint)
//Draw right toggle over range stroke
val cxRight = rangeValueRectF.right
val cyRight = height.toFloat() / 2
this.canvas?.drawCircle(cxRight, cyRight, toggleRadius, rangeTogglePaint)
//Draw background bitmap to original canvas
backgroundBitmap?.let {
canvas?.drawBitmap(it, 0f, 0f, null)
}
//Draw prepared bitmap to original canvas
bitmap?.let {
canvas?.drawBitmap(it, 0f, 0f, null)
}
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
when (event!!.action) {
MotionEvent.ACTION_DOWN -> {
draggingStateData = when {
isTouchOnLeftToggle(event) && isTouchOnRightToggle(event) -> DraggingStateData.createConflict(event)
isTouchOnLeftToggle(event) -> DraggingStateData.left(event)
isTouchOnRightToggle(event) -> DraggingStateData.right(event)
else -> return false
}
}
MotionEvent.ACTION_MOVE -> {
when (draggingStateData.draggingState) {
DraggingState.DRAGGING_CONFLICT_TOGGLE -> {
if (Math.abs(draggingStateData.motionX - event.x) < SLOP_DIFF) {
return true
}
val direction = resolveMovingWay(event, draggingStateData)
draggingStateData = when (direction) {
Direction.LEFT -> {
draggingLeftToggle(event)
DraggingStateData.left(event)
}
Direction.RIGHT -> {
draggingRightToggle(event)
DraggingStateData.right(event)
}
}
}
DraggingState.DRAGGING_RIGHT_TOGGLE -> {
if (isRightToggleExceed(event)) {
return true
} else {
draggingRightToggle(event)
}
}
DraggingState.DRAGGING_LEFT_TOGGLE -> {
if (isLeftToggleExceed(event)) {
return true
} else {
draggingLeftToggle(event)
}
}
else -> {
}
}
}
MotionEvent.ACTION_UP -> {
rangeDraggingChangeListener?.onDraggingStateChanged(DraggingState.DRAGGING_END)
draggingStateData = DraggingStateData.idle()
}
}
rangeDraggingChangeListener?.onDraggingStateChanged(draggingStateData.draggingState)
return true
}
fun setMaxValue(maxValue: Float) {
this.maxValue = maxValue
postInvalidate()
}
fun setMinValue(minValue: Float) {
this.minValue = minValue
postInvalidate()
}
fun setCurrentValues(leftValue: Float, rightValue: Float) {
currentLeftValue = leftValue
currentRightValue = rightValue
requestLayout()
postInvalidate()
}
fun getXPositionOfValue(value: Float): Float {
if (value < minValue || value > maxValue) {
return 0f
}
return (((totalValueRect.width()) * value) / maxValue) + horizontalMargin
}
private fun resolveMovingWay(motionEvent: MotionEvent, stateData: DraggingStateData): Direction {
return if (motionEvent.x > stateData.motionX) Direction.RIGHT else Direction.LEFT
}
private fun initializeBitmap() {
if (bitmap == null || canvas == null) {
bitmap?.recycle()
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
backgroundBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
bitmap?.let {
this.canvas = Canvas(it)
}
backgroundBitmap?.let {
this.backgroundCanvas = Canvas(it)
}
}
}
private fun draggingLeftToggle(motionEvent: MotionEvent) {
rangeValueRectF.set(motionEvent.x, rangeValueRectF.top, rangeValueRectF.right, rangeValueRectF.bottom)
rangeStrokeRectF.set(rangeValueRectF.left, rangeValueRectF.top + strokeWidth / 2, rangeValueRectF.right, rangeValueRectF.bottom - strokeWidth / 2)
rangePositionChangeListener?.leftTogglePositionChanged(rangeValueRectF.left, getLeftValue())
postInvalidate()
notifyRangeChanged()
}
private fun draggingRightToggle(motionEvent: MotionEvent) {
rangeValueRectF.set(rangeValueRectF.left, rangeValueRectF.top, motionEvent.x, rangeValueRectF.bottom)
rangeStrokeRectF.set(rangeValueRectF.left, rangeValueRectF.top + strokeWidth / 2, rangeValueRectF.right, rangeValueRectF.bottom - strokeWidth / 2)
rangePositionChangeListener?.rightTogglePositionChanged(rangeValueRectF.right, getRightValue())
postInvalidate()
notifyRangeChanged()
}
private fun isLeftToggleExceed(motionEvent: MotionEvent): Boolean {
return motionEvent.x < totalValueRect.left || motionEvent.x > rangeValueRectF.right
}
private fun isRightToggleExceed(motionEvent: MotionEvent): Boolean {
return motionEvent.x < rangeValueRectF.left || motionEvent.x > totalValueRect.right
}
private fun isTouchOnLeftToggle(motionEvent: MotionEvent): Boolean {
return motionEvent.x > rangeValueRectF.left - toggleRadius && motionEvent.x < rangeValueRectF.left + toggleRadius
}
private fun isTouchOnRightToggle(motionEvent: MotionEvent): Boolean {
return motionEvent.x > rangeValueRectF.right - toggleRadius && motionEvent.x < rangeValueRectF.right + toggleRadius
}
private fun getLeftValue(): Float {
val totalDiffInPx = totalValueRect.right - totalValueRect.left
val firstValueInPx = rangeValueRectF.left - totalValueRect.left
return maxValue * firstValueInPx / totalDiffInPx
}
private fun getRightValue(): Float {
val totalDiffInPx = totalValueRect.right - totalValueRect.left
val secondValueInPx = rangeValueRectF.right - totalValueRect.left
return maxValue * secondValueInPx / totalDiffInPx
}
private fun notifyRangeChanged() {
val firstValue = getLeftValue()
val secondValue = getRightValue()
val leftValue = Math.min(firstValue, secondValue)
val rightValue = Math.max(firstValue, secondValue)
currentLeftValue = leftValue
currentRightValue = rightValue
rangeValueChangeListener?.rangeChanged(maxValue, minValue, leftValue, rightValue)
}
companion object {
private const val DEFAULT_MAX_VALUE = 1f
private const val DEFAULT_MIN_VALUE = 0f
private const val SLOP_DIFF = 20f
}
} | apache-2.0 | ddbb8f0248220a3cd22d9a188721cee7 | 35.916185 | 154 | 0.635296 | 4.92367 | false | false | false | false |
PaulWoitaschek/AndroidPlayer | app/src/main/java/de/paul_woitaschek/mediaplayer/SpeedPlayer.kt | 1 | 14342 | package de.paul_woitaschek.mediaplayer
import android.annotation.TargetApi
import android.content.Context
import android.media.*
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import de.paul_woitaschek.mediaplayer.internals.Sonic
import java.io.IOException
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.thread
import kotlin.concurrent.withLock
/**
* 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.
*
* @author James Falcon, Paul Woitaschek
*/
@Suppress("unused")
@TargetApi(16)
class SpeedPlayer(private val context: Context) : MediaPlayer {
private var onError: (() -> Unit)? = null
private var onCompletion: (() -> Unit)? = null
private var onPrepared: (() -> Unit)? = null
override var playbackSpeed = 1.0f
override var duration: Int = 0
private set
override fun isPlaying() = state == State.STARTED
private val handler = Handler(context.mainLooper)
private val lock = ReentrantLock()
private val decoderLock = Object()
private val executor = Executors.newSingleThreadExecutor()
private var wakeLock: PowerManager.WakeLock? = null
private var track: AudioTrack? = null
private var sonic: Sonic? = null
private var extractor: MediaExtractor? = null
private var codec: MediaCodec? = null
private var uri: Uri? = null
private var audioStreamType: Int = AudioManager.STREAM_MUSIC
@Volatile private var continuing = false
@Volatile private var isDecoding = false
@Volatile private var flushCodec = false
@Volatile private var state = State.IDLE
@Suppress("DEPRECATION")
private val decoderRunnable = Runnable {
isDecoding = true
val codec = codec!!
codec.start()
val inputBuffers = codec.inputBuffers
var outputBuffers = codec.outputBuffers
var sawInputEOS = false
var sawOutputEOS = false
while (!sawInputEOS && !sawOutputEOS && continuing) {
if (state == State.PAUSED) {
try {
synchronized(decoderLock) {
decoderLock.wait()
}
} catch (e: InterruptedException) {
// Purposely not doing anything here
}
continue
}
val sonic = sonic!!
sonic.speed = playbackSpeed
sonic.pitch = 1f
val inputBufIndex = codec.dequeueInputBuffer(200)
if (inputBufIndex >= 0) {
val dstBuf = inputBuffers[inputBufIndex]
var sampleSize = extractor!!.readSampleData(dstBuf, 0)
var presentationTimeUs: Long = 0
if (sampleSize < 0) {
sawInputEOS = true
sampleSize = 0
} else {
presentationTimeUs = extractor!!.sampleTime
}
codec.queueInputBuffer(
inputBufIndex,
0,
sampleSize,
presentationTimeUs,
if (sawInputEOS) MediaCodec.BUFFER_FLAG_END_OF_STREAM else 0)
if (flushCodec) {
codec.flush()
flushCodec = false
}
if (!sawInputEOS) {
extractor!!.advance()
}
}
val info = MediaCodec.BufferInfo()
var modifiedSamples = ByteArray(info.size)
var res: Int
do {
res = codec.dequeueOutputBuffer(info, 200)
if (res >= 0) {
val chunk = ByteArray(info.size)
outputBuffers[res].get(chunk)
outputBuffers[res].clear()
if (chunk.isNotEmpty()) {
sonic.writeBytesToStream(chunk, chunk.size)
} else {
sonic.flushStream()
}
val available = sonic.availableBytes()
if (available > 0) {
if (modifiedSamples.size < available) {
modifiedSamples = ByteArray(available)
}
sonic.readBytesFromStream(modifiedSamples, available)
track!!.write(modifiedSamples, 0, available)
}
codec.releaseOutputBuffer(res, false)
if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) {
sawOutputEOS = true
}
} else if (res == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
outputBuffers = codec.outputBuffers
} else if (res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
track!!.stop()
lock.lock()
try {
track!!.release()
val oFormat = codec.outputFormat
initDevice(
oFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE),
oFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT))
outputBuffers = codec.outputBuffers
track!!.play()
} catch (e: IOException) {
e.printStackTrace()
} finally {
lock.unlock()
}
}
} while (res == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED || res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED)
}
codec.stop()
track!!.stop()
isDecoding = false
if (continuing && (sawInputEOS || sawOutputEOS)) {
state = State.PLAYBACK_COMPLETED
handler.post {
onCompletion?.invoke()
stayAwake(false)
}
}
synchronized(decoderLock) {
decoderLock.notifyAll()
}
}
private fun errorInWrongState(validStates: Iterable<State>, method: String) {
if (!validStates.contains(state)) {
error()
throw IllegalStateException("Must not call $method in $state")
}
}
override fun start() {
errorInWrongState(validStatesForStart, "start")
if (state == State.PLAYBACK_COMPLETED) {
try {
initStream()
state = State.PREPARED
} catch (e: IOException) {
error()
return
}
}
when (state) {
State.PREPARED -> {
state = State.STARTED
continuing = true
track!!.play()
decode()
stayAwake(true)
}
State.STARTED -> {
}
State.PAUSED -> {
state = State.STARTED
synchronized(decoderLock) {
decoderLock.notify()
}
track!!.play()
stayAwake(true)
}
else -> throw AssertionError("Unexpected state $state")
}
}
override fun reset() {
errorInWrongState(validStatesForReset, "reset")
stayAwake(false)
lock.withLock {
continuing = false
try {
if (state != State.PLAYBACK_COMPLETED) {
while (isDecoding) {
synchronized(decoderLock) {
decoderLock.notify()
decoderLock.wait()
}
}
}
} catch (e: InterruptedException) {
}
codec?.release()
codec = null
extractor?.release()
extractor = null
track?.release()
track = null
state = State.IDLE
}
}
@Throws(IOException::class)
private fun internalPrepare() {
initStream()
state = State.PREPARED
doOnMain { onPrepared?.invoke() }
}
override fun seekTo(to: Int) {
errorInWrongState(validStatesForSeekTo, "seekTo")
when (state) {
State.PREPARED,
State.STARTED,
State.PAUSED,
State.PLAYBACK_COMPLETED -> {
thread(isDaemon = true) {
lock.withLock {
if (track != null) {
track!!.flush()
flushCodec = true
val internalTo = to.toLong() * 1000
extractor!!.seekTo(internalTo, MediaExtractor.SEEK_TO_NEXT_SYNC)
}
}
}
}
else -> throw AssertionError("Unexpected state $state")
}
}
override val currentPosition: Int
get() {
errorInWrongState(validStatesForCurrentPosition, "currentPosition")
return when (state) {
State.IDLE -> 0
State.PREPARED, State.STARTED, State.PAUSED, State.PLAYBACK_COMPLETED -> (extractor!!.sampleTime / 1000).toInt()
else -> throw AssertionError("Unexpected state $state")
}
}
override fun audioSessionId() = track?.audioSessionId ?: -1
override fun pause() {
errorInWrongState(validStatesForPause, "pause")
when (state) {
State.PLAYBACK_COMPLETED -> {
state = State.PAUSED
stayAwake(false)
}
State.STARTED, State.PAUSED -> {
track!!.pause()
state = State.PAUSED
stayAwake(false)
}
else -> throw AssertionError("Unexpected state $state")
}
}
@Throws(IOException::class)
override fun prepare(uri: Uri) {
errorInWrongState(validStatesForPrepare, "prepare")
this.uri = uri
try {
internalPrepare()
} catch(e: IOException) {
error()
throw IOException(e)
}
}
override fun release() {
onError = null
onCompletion = null
onPrepared = null
reset()
}
override fun setAudioStreamType(streamType: Int) {
audioStreamType = streamType
}
override fun setVolume(volume: Float) {
if (Build.VERSION.SDK_INT >= 21) track?.setVolume(volume)
else {
@Suppress("DEPRECATION")
track?.setStereoVolume(volume, volume)
}
}
override fun prepareAsync(uri: Uri) {
errorInWrongState(validStatesForPrepare, "prepareAsync")
this.uri = uri
state = State.PREPARING
thread(isDaemon = true) {
try {
internalPrepare()
} catch(e: IOException) {
error()
}
}
}
override fun setWakeMode(mode: Int) {
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
wakeLock = pm.newWakeLock(mode, "CustomPlayer").apply {
setReferenceCounted(false)
}
}
@Throws(IOException::class)
private fun initStream() {
lock.withLock {
extractor = MediaExtractor().also { extractor ->
if (uri != null) {
extractor.setDataSource(context, uri!!, null)
} else {
error()
throw IOException("Error at initializing stream")
}
if (extractor.trackCount == 0) {
error()
throw IOException("trackCount is 0")
}
val trackNum = 0
val oFormat = extractor.getTrackFormat(trackNum)
if (!oFormat.containsKeys(MediaFormat.KEY_SAMPLE_RATE, MediaFormat.KEY_CHANNEL_COUNT, MediaFormat.KEY_MIME, MediaFormat.KEY_DURATION)) {
throw IOException("MediaFormat misses keys.")
}
val sampleRate = oFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE)
val channelCount = oFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT)
val mime = oFormat.getString(MediaFormat.KEY_MIME)
duration = (oFormat.getLong(MediaFormat.KEY_DURATION) / 1000).toInt()
initDevice(sampleRate, channelCount)
extractor.selectTrack(trackNum)
codec = MediaCodec.createDecoderByType(mime)
.apply {
configure(oFormat, null, null, 0)
}
}
}
}
private fun error() {
state = State.ERROR
stayAwake(false)
doOnMain { onError?.invoke() }
}
private inline fun doOnMain(crossinline func: () -> Unit) {
if (Thread.currentThread() == Looper.getMainLooper().thread) {
func()
} else {
handler.post { func() }
}
}
private fun Sonic.availableBytes() = numChannels * samplesAvailable() * 2
private fun MediaFormat.containsKeys(vararg keys: String): Boolean = keys.all { containsKey(it) }
private fun findFormatFromChannels(numChannels: Int) = when (numChannels) {
1 -> AudioFormat.CHANNEL_OUT_MONO
2 -> AudioFormat.CHANNEL_OUT_STEREO
3 -> AudioFormat.CHANNEL_OUT_STEREO or AudioFormat.CHANNEL_OUT_FRONT_CENTER
4 -> AudioFormat.CHANNEL_OUT_QUAD
5 -> AudioFormat.CHANNEL_OUT_QUAD or AudioFormat.CHANNEL_OUT_FRONT_CENTER
6 -> AudioFormat.CHANNEL_OUT_5POINT1
7 -> AudioFormat.CHANNEL_OUT_5POINT1 or AudioFormat.CHANNEL_OUT_BACK_CENTER
8 -> if (Build.VERSION.SDK_INT >= 23) {
AudioFormat.CHANNEL_OUT_7POINT1_SURROUND
} else -1
else -> -1 // Error
}
@Throws(IOException::class)
private fun initDevice(sampleRate: Int, numChannels: Int) {
lock.withLock {
val format = findFormatFromChannels(numChannels)
val minSize = AudioTrack.getMinBufferSize(sampleRate, format, AudioFormat.ENCODING_PCM_16BIT)
if (minSize == AudioTrack.ERROR || minSize == AudioTrack.ERROR_BAD_VALUE) {
throw IOException("getMinBufferSize returned " + minSize)
}
track?.release()
track = AudioTrack(
audioStreamType, sampleRate, format, AudioFormat.ENCODING_PCM_16BIT, minSize * 4, AudioTrack.MODE_STREAM
)
sonic = Sonic(sampleRate, numChannels)
}
}
private fun stayAwake(awake: Boolean) {
wakeLock?.let {
if (awake && !it.isHeld) {
it.acquire()
} else if (!awake && it.isHeld) {
it.release()
}
}
}
override fun onError(action: (() -> Unit)?) {
onError = action
}
override fun onCompletion(action: (() -> Unit)?) {
onCompletion = action
}
override fun onPrepared(action: (() -> Unit)?) {
onPrepared = action
}
private fun decode() {
executor.execute(decoderRunnable)
}
private val validStatesForStart = EnumSet.of(State.PREPARED, State.STARTED, State.PAUSED, State.PLAYBACK_COMPLETED)
private val validStatesForReset = EnumSet.of(State.IDLE, State.PREPARED, State.STARTED, State.PAUSED, State.PLAYBACK_COMPLETED, State.ERROR)
private val validStatesForPrepare = EnumSet.of(State.IDLE)
private val validStatesForCurrentPosition = EnumSet.of(State.IDLE, State.PREPARED, State.STARTED, State.PAUSED, State.PLAYBACK_COMPLETED)
private val validStatesForPause = EnumSet.of(State.STARTED, State.PAUSED, State.PLAYBACK_COMPLETED)
private val validStatesForSeekTo = EnumSet.of(State.PREPARED, State.STARTED, State.PAUSED, State.PLAYBACK_COMPLETED)
private enum class State {
IDLE,
ERROR,
STARTED,
PAUSED,
PREPARED,
PREPARING,
PLAYBACK_COMPLETED
}
} | apache-2.0 | fcac087b39b8ab20311a698b50e359cf | 28.093306 | 144 | 0.627318 | 4.294012 | false | false | false | false |
lightem90/Sismic | app/src/main/java/com/polito/sismic/Interactors/Helpers/LocalizationActionHelper.kt | 1 | 3769 | package com.polito.sismic.Interactors.Helpers
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.location.Location
import android.os.Looper
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.places.Place
import com.google.android.gms.location.places.ui.PlaceAutocomplete
import com.google.android.gms.location.places.ui.PlacePicker
import com.google.android.gms.tasks.OnSuccessListener
import com.polito.sismic.Extensions.toast
import com.polito.sismic.Presenters.ReportActivity.Fragments.InfoLocReportFragment
import com.polito.sismic.R
import com.google.android.gms.location.places.AutocompleteFilter
class LocalizationActionHelper {
val PLACE_PICKER_REQUEST = 50
val REVERSE_LOCALIZATION_REQUEST = 51
private var mFusedLocationClient: FusedLocationProviderClient? = null
fun handleActionRequest(typeLocalization: LocalizationActionType, caller : InfoLocReportFragment, mLocationCallback: InfoLocReportFragment.CurrentLocationProvided?)
{
when (typeLocalization)
{
LocalizationActionType.PlacePicker -> launchPlacePicker(caller)
LocalizationActionType.Localization -> launchLocalization(caller.activity, mLocationCallback)
LocalizationActionType.ReverseLocalization -> launchReverseLocalization(caller)
}
}
private fun launchReverseLocalization(caller: InfoLocReportFragment) {
//Autocomplete filter on Italian addresses
val typeFilter = AutocompleteFilter.Builder()
.setCountry("IT")
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS)
.build()
val intent = PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
.setFilter(typeFilter)
.build(caller.activity)
caller.startActivityForResult(intent, REVERSE_LOCALIZATION_REQUEST)
}
//Already checked!
@SuppressLint("MissingPermission")
private fun launchLocalization(caller: Activity, mLocationCallback: InfoLocReportFragment.CurrentLocationProvided?) {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(caller)
mFusedLocationClient?.let {
it.requestLocationUpdates(LocationRequest(), LocationCallback(), Looper.getMainLooper())
it.lastLocation?.addOnSuccessListener(caller, { location ->
// Got last known location. In some rare situations this can be null.
mLocationCallback?.onLocationAcquired(location)
})
it.removeLocationUpdates(LocationCallback())
}
}
private fun launchPlacePicker(caller: InfoLocReportFragment) {
//The fragment launches and handles the result
caller.startActivityForResult(PlacePicker.IntentBuilder().build(caller.activity), PLACE_PICKER_REQUEST)
}
fun handlePickerResponse(caller: Activity, resultCode : Int, data : Intent?) : Place?
{
if (resultCode == Activity.RESULT_OK) {
return PlacePicker.getPlace(caller, data)
}
//Error message on failure
caller.toast(R.string.place_picker_failed)
return null
}
fun handleAutoCompleteMapsResponse(caller: Activity, resultCode : Int, data : Intent?) : Place?
{
if (resultCode == Activity.RESULT_OK) {
return PlaceAutocomplete.getPlace(caller, data)
}
//Error message on failure
caller.toast(R.string.autocomplete_failed)
return null
}
}
| mit | c73a3e555e9c9660e7bd3e5e6aac00be | 39.095745 | 168 | 0.729106 | 5.03877 | false | false | false | false |
Mauin/detekt | detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/baseline/BaselineFacade.kt | 1 | 1528 | package io.gitlab.arturbosch.detekt.cli.baseline
import io.gitlab.arturbosch.detekt.api.Finding
import io.gitlab.arturbosch.detekt.cli.baselineId
import io.gitlab.arturbosch.detekt.core.exists
import io.gitlab.arturbosch.detekt.core.isFile
import java.nio.file.Files
import java.nio.file.Path
import java.time.Instant
/**
* @author Artur Bosch
*/
class BaselineFacade(val baselineFile: Path) {
private val listings: Pair<Whitelist, Blacklist>? =
if (baselineExists()) {
val format = BaselineFormat().read(baselineFile)
format.whitelist to format.blacklist
} else null
fun filter(smells: List<Finding>) =
if (listings != null) {
val whiteFiltered = smells.filterNot { finding -> listings.first.ids.contains(finding.baselineId) }
val blackFiltered = whiteFiltered.filterNot { finding -> listings.second.ids.contains(finding.baselineId) }
blackFiltered
} else smells
fun create(smells: List<Finding>) {
val timestamp = Instant.now().toEpochMilli().toString()
val blacklist = if (baselineExists()) {
BaselineFormat().read(baselineFile).blacklist
} else {
Blacklist(emptySet(), timestamp)
}
val ids = smells.map { it.baselineId }.toSortedSet()
val smellBaseline = Baseline(blacklist, Whitelist(ids, timestamp))
baselineFile.parent?.let { Files.createDirectories(it) }
BaselineFormat().write(smellBaseline, baselineFile)
println("Successfully wrote smell baseline to $baselineFile")
}
private fun baselineExists() = baselineFile.exists() && baselineFile.isFile()
}
| apache-2.0 | 8955f2fdcbf0759348d082e788bb12b8 | 33.727273 | 111 | 0.748691 | 3.735941 | false | false | false | false |
clappr/clappr-android | app/src/main/kotlin/io/clappr/player/app/plugin/NextVideoPlugin.kt | 1 | 3069 | package io.clappr.player.app.plugin
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import com.squareup.picasso.Picasso
import io.clappr.player.app.R
import io.clappr.player.base.*
import io.clappr.player.components.Core
import io.clappr.player.plugin.PluginEntry
import io.clappr.player.plugin.core.UICorePlugin
class NextVideoPlugin(core: Core) : UICorePlugin(core, name = name) {
companion object : NamedType {
override val name = "nextVideo"
val entry = PluginEntry.Core(name = name, factory = { core -> NextVideoPlugin(core) })
}
private val picasso: Picasso by lazy {
Picasso.Builder(applicationContext).build()
}
override val view by lazy {
LayoutInflater.from(applicationContext).inflate(R.layout.next_video_plugin, null) as RelativeLayout
}
private val videoListView by lazy { view.findViewById(R.id.video_list) as LinearLayout }
private val videoList = listOf(
Pair("http://clappr.io/poster.png", "https://clappr.io/highline.mp4"),
Pair("http://clappr.io/poster.png", "https://clappr.io/highline.mp4"),
Pair("http://clappr.io/poster.png", "https://clappr.io/highline.mp4")
)
private val playbackListenerIds = mutableListOf<String>()
private val hideNextVideo: EventHandler = {
hide()
}
private val showNextVideo: EventHandler = {
view.bringToFront()
show()
}
init {
bindCoreEvents()
}
override fun render() {
super.render()
setupLayout()
}
private fun bindCoreEvents() {
listenTo(core, InternalEvent.DID_CHANGE_ACTIVE_PLAYBACK.value) {
hide()
bindPlaybackEvents()
}
}
private fun bindPlaybackEvents() {
stopPlaybackListeners()
core.activePlayback?.let {
playbackListenerIds.add(listenTo(it, Event.WILL_PLAY.value, hideNextVideo))
playbackListenerIds.add(listenTo(it, Event.DID_STOP.value, showNextVideo))
playbackListenerIds.add(listenTo(it, Event.DID_COMPLETE.value, showNextVideo))
}
}
private fun setupLayout() {
videoList.forEach { entry ->
videoListView.addView(getNextVideoView(entry))
}
}
private fun getNextVideoView(entry: Pair<String, String>) =
(LayoutInflater.from(applicationContext).inflate(R.layout.next_video_item, null) as RelativeLayout).apply {
val videoPoster = findViewById<ImageView>(R.id.video_poster)
picasso.load(entry.first).fit().centerCrop().into(videoPoster)
setOnClickListener { onClick(entry.second) }
}
private fun stopPlaybackListeners() {
playbackListenerIds.forEach(::stopListening)
playbackListenerIds.clear()
}
private fun onClick(url: String) {
core.activePlayback?.stop()
Options(source = url).also { core.options = it }
core.load()
}
} | bsd-3-clause | cedc8f10057b1986e06370a99d7684d4 | 30.010101 | 119 | 0.656891 | 4.328632 | false | false | false | false |
jereksel/LibreSubstratum | app/src/main/kotlin/com/jereksel/libresubstratum/activities/detailed/DetailedAdapter.kt | 1 | 10145 | package com.jereksel.libresubstratum.activities.detailed
import android.content.Context
import android.graphics.Color
import android.support.v7.app.AlertDialog
import android.support.v7.util.DiffUtil
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.widget.*
import com.jereksel.libresubstratum.R
import com.jereksel.libresubstratum.activities.detailed.DetailedViewState.Theme
import com.jereksel.libresubstratum.data.Type1ExtensionToString
import com.jereksel.libresubstratum.data.Type2ExtensionToString
import com.jereksel.libresubstratum.extensions.getLogger
import com.jereksel.libresubstratum.extensions.list
import com.jereksel.libresubstratum.extensions.selectListener
import com.jereksel.libresubstratum.views.TypeView
import io.reactivex.subjects.BehaviorSubject
import kotterknife.bindView
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk25.coroutines.onCheckedChange
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.sdk25.coroutines.onLongClick
import org.jetbrains.anko.textColor
import org.jetbrains.anko.toast
class DetailedAdapter(
var themes: List<Theme>,
val detailedPresenter: DetailedPresenter
): RecyclerView.Adapter<DetailedAdapter.ViewHolder>() {
val log = getLogger()
val recyclerViewDetailedActions = BehaviorSubject.create<DetailedAction>()!!
override fun getItemCount() = themes.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val theme = themes[position]
holder.appId.text = theme.appId
holder.appName.text = theme.name
holder.appIcon.setImageDrawable(detailedPresenter.getAppIcon(theme.appId))
//Reset
holder.checkbox.onCheckedChange { _, _ -> }
holder.checkbox.isChecked = theme.checked
if (theme.compilationState == DetailedViewState.CompilationState.DEFAULT) {
holder.overlay.visibility = GONE
} else {
holder.overlay.visibility = VISIBLE
}
val installedState = theme.installedState
val enabledState = theme.enabledState
val compilationState = theme.compilationState
holder.upToDate.textColor = Color.BLACK
holder.upToDate.text = ""
holder.appName.textColor = Color.BLACK
if (theme.compilationError != null) {
holder.errorIcon.visibility = VISIBLE
holder.errorIcon.onClick {
showError(holder.itemView.context, theme.compilationError)
}
} else {
holder.errorIcon.visibility = GONE
}
when(enabledState) {
DetailedViewState.EnabledState.ENABLED -> holder.appName.textColor = Color.GREEN
DetailedViewState.EnabledState.DISABLED -> holder.appName.textColor = Color.RED
DetailedViewState.EnabledState.UNKNOWN -> holder.appName.textColor = Color.BLACK
}
when(installedState) {
is DetailedViewState.InstalledState.Outdated -> {
holder.upToDate.text = "${installedState.installedVersionName} (${installedState.installedVersionCode}) -> ${installedState.newestVersionName} (${installedState.newestVersionCode})"
holder.upToDate.textColor = Color.RED
}
is DetailedViewState.InstalledState.Installed -> {
holder.upToDate.text = "Up to date"
holder.upToDate.textColor = Color.GREEN
}
}
when(compilationState) {
DetailedViewState.CompilationState.DEFAULT -> {
holder.overlay.visibility = GONE
}
DetailedViewState.CompilationState.COMPILING -> {
holder.overlay.visibility = VISIBLE
holder.overlayText.text = "Compiling"
}
DetailedViewState.CompilationState.INSTALLING -> {
holder.overlay.visibility = VISIBLE
holder.overlayText.text = "Installing"
}
}
holder.type1aSpinner((theme.type1a?.data ?: listOf()).map { Type1ExtensionToString(it) }, theme.type1a?.position ?: 0)
holder.type1aView.onPositionChange { recyclerViewDetailedActions.onNext(DetailedAction.ChangeSpinnerSelection.ChangeType1aSpinnerSelection(holder.adapterPosition, it)) }
holder.type1bSpinner((theme.type1b?.data ?: listOf()).map { Type1ExtensionToString(it) }, theme.type1b?.position ?: 0)
holder.type1bView.onPositionChange{ recyclerViewDetailedActions.onNext(DetailedAction.ChangeSpinnerSelection.ChangeType1bSpinnerSelection(holder.adapterPosition, it)) }
holder.type1cSpinner((theme.type1c?.data ?: listOf()).map { Type1ExtensionToString(it) }, theme.type1c?.position ?: 0)
holder.type1cView.onPositionChange { recyclerViewDetailedActions.onNext(DetailedAction.ChangeSpinnerSelection.ChangeType1cSpinnerSelection(holder.adapterPosition, it)) }
holder.type2Spinner((theme.type2?.data ?: listOf()).map { Type2ExtensionToString(it) }, theme.type2?.position ?: 0)
holder.type2Spinner.selectListener { recyclerViewDetailedActions.onNext(DetailedAction.ChangeSpinnerSelection.ChangeType2SpinnerSelection(holder.adapterPosition, it)) }
holder.card.onClick {
val isChecked = holder.checkbox.isChecked
recyclerViewDetailedActions.onNext(DetailedAction.ToggleCheckbox(holder.adapterPosition, !isChecked))
}
holder.card.onLongClick(returnValue = true) {
recyclerViewDetailedActions.onNext(DetailedAction.CompilationLocationAction(holder.adapterPosition, DetailedAction.CompileMode.DISABLE_COMPILE_AND_ENABLE))
}
holder.appIcon.onLongClick(returnValue = true) { view ->
if (!detailedPresenter.openInSplit(theme.appId)) {
view?.context?.toast("Application cannot be opened")
}
}
holder.checkbox.onCheckedChange { _, isChecked ->
recyclerViewDetailedActions.onNext(DetailedAction.ToggleCheckbox(holder.adapterPosition, isChecked))
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.item_detailed, parent, false)
return ViewHolder(v)
}
fun update(themes: List<Theme>) {
val oldList = this.themes
val newList = themes
this.themes = themes
DiffUtil.calculateDiff(ThemeDiffCallback(oldList, newList)).dispatchUpdatesTo(this)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val card: CardView by bindView(R.id.card_view)
val checkbox: CheckBox by bindView(R.id.checkbox)
val appName: TextView by bindView(R.id.appName)
val appId: TextView by bindView(R.id.appId)
val appIcon: ImageView by bindView(R.id.imageView)
val upToDate: TextView by bindView(R.id.uptodate)
val type1aView: TypeView by bindView(R.id.type1aview)
val type1bView: TypeView by bindView(R.id.type1bview)
val type1cView: TypeView by bindView(R.id.type1cview)
val type2Spinner: Spinner by bindView(R.id.spinner_2)
val overlay: RelativeLayout by bindView(R.id.overlay)
val overlayText: TextView by bindView(R.id.overlay_text)
val errorIcon: ImageView by bindView(R.id.error)
fun type1aSpinner(list: List<Type1ExtensionToString>, position: Int) {
if (list.isEmpty()) {
type1aView.visibility = GONE
} else {
type1aView.visibility = VISIBLE
type1aView.setType1((list))
type1aView.setSelection(position)
}
}
fun type1bSpinner(list: List<Type1ExtensionToString>, position: Int) {
if (list.isEmpty()) {
type1bView.visibility = GONE
} else {
type1bView.visibility = VISIBLE
type1bView.setType1((list))
type1bView.setSelection(position)
}
}
fun type1cSpinner(list: List<Type1ExtensionToString>, position: Int) {
if (list.isEmpty()) {
type1cView.visibility = GONE
} else {
type1cView.visibility = VISIBLE
type1cView.setType1((list))
type1cView.setSelection(position)
}
}
fun type2Spinner(list: List<Type2ExtensionToString>, position: Int) {
if (list.isEmpty()) {
type2Spinner.visibility = GONE
} else {
type2Spinner.visibility = VISIBLE
type2Spinner.list = list
type2Spinner.setSelection(position)
}
}
}
class ThemeDiffCallback(
private val oldList: List<Theme>,
private val newList: List<Theme>
): DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
oldList[oldItemPosition].appId == newList[newItemPosition].appId
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
oldList[oldItemPosition] == newList[newItemPosition]
}
fun showError(context: Context, error: Throwable) {
val view = LayoutInflater.from(context).inflate(R.layout.dialog_compilationerror, null)
val textView = view.find<TextView>(R.id.errorTextView)
val message = error.message ?: ""
textView.text = message
val builder = AlertDialog.Builder(context)
builder.setTitle("Error")
builder.setView(view)
builder.setPositiveButton("Copy to clipboard", { _, _ ->
detailedPresenter.setClipboard(message)
context.toast("Copied to clipboard")
})
builder.show()
}
} | mit | 68587d550f86912cb292e44a59e14b69 | 38.788235 | 197 | 0.673928 | 4.734018 | false | false | false | false |
nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/ProjectEntityExtensions.kt | 1 | 6204 | package net.nemerosa.ontrack.model.structure
import net.nemerosa.ontrack.common.getOrNull
import net.nemerosa.ontrack.model.exceptions.InputException
/**
* Map of fields/values for the names of this entity
*/
val ProjectEntity.nameValues: Map<String, String>
get() = when (this) {
is Project -> mapOf(
"project" to name
)
is Branch -> mapOf(
"project" to project.name,
"branch" to name
)
is Build -> mapOf(
"project" to project.name,
"branch" to branch.name,
"build" to name
)
is ValidationStamp -> mapOf(
"project" to project.name,
"branch" to branch.name,
"validation" to name
)
is PromotionLevel -> mapOf(
"project" to project.name,
"branch" to branch.name,
"promotion" to name
)
is ValidationRun -> mapOf(
"project" to project.name,
"branch" to build.branch.name,
"build" to build.name,
"validation" to validationStamp.name,
"run" to runOrder.toString()
)
is PromotionRun -> mapOf(
"project" to project.name,
"branch" to build.branch.name,
"build" to build.name,
"promotion" to promotionLevel.name
)
else -> throw IllegalStateException("Unknown project entity: $this")
}
/**
* Name for an entity
*/
val ProjectEntity.displayName: String
get() = when (this) {
is Project -> name
is Branch -> name
is Build -> name
is ValidationStamp -> name
is PromotionLevel -> name
is ValidationRun -> "${build.name}/${validationStamp.name}"
is PromotionRun -> "${build.name}/${promotionLevel.name}"
else -> throw IllegalStateException("Unknown project entity: $this")
}
/**
* List of names of this entity
*/
val ProjectEntityType.names: List<String>
get() = when (this) {
ProjectEntityType.PROJECT -> listOf(
"project"
)
ProjectEntityType.BRANCH -> listOf(
"project",
"branch"
)
ProjectEntityType.BUILD -> listOf(
"project",
"branch",
"build"
)
ProjectEntityType.VALIDATION_STAMP -> listOf(
"project",
"branch",
"validation"
)
ProjectEntityType.PROMOTION_LEVEL -> listOf(
"project",
"branch",
"promotion"
)
ProjectEntityType.VALIDATION_RUN -> listOf(
"project",
"branch",
"build",
"validation",
"run"
)
ProjectEntityType.PROMOTION_RUN -> listOf(
"project",
"branch",
"build",
"promotion"
)
}
/**
* Loading an entity using its names
*/
fun ProjectEntityType.loadByNames(structureService: StructureService, names: Map<String, String>): ProjectEntity? {
return when (this) {
ProjectEntityType.PROJECT -> structureService.findProjectByName(names.require("project")).orElse(null)
ProjectEntityType.BRANCH -> structureService.findBranchByName(
names.require("project"),
names.require("branch")
).orElse(null)
ProjectEntityType.BUILD -> structureService.findBuildByName(
names.require("project"),
names.require("branch"),
names.require("build")
).orElse(null)
ProjectEntityType.VALIDATION_STAMP -> structureService.findValidationStampByName(
names.require("project"),
names.require("branch"),
names.require("validation")
).orElse(null)
ProjectEntityType.PROMOTION_LEVEL -> structureService.findPromotionLevelByName(
names.require("project"),
names.require("branch"),
names.require("promotion")
).orElse(null)
ProjectEntityType.VALIDATION_RUN -> {
// Gets the build
val build = structureService.findBuildByName(
names.require("project"),
names.require("branch"),
names.require("build")
).getOrNull() ?: return null
// Gets the validation stamp
val vs = structureService.findValidationStampByName(
names.require("project"),
names.require("branch"),
names.require("validation")
).getOrNull() ?: return null
// Run order
val order = names.require("run").toInt()
// Gets the runs
// TODO Today, there is no query based on the order
structureService.getValidationRunsForBuildAndValidationStamp(
buildId = build.id,
validationStampId = vs.id,
offset = 0,
count = 10
).find { it.runOrder == order }
}
ProjectEntityType.PROMOTION_RUN -> {
// Gets the build
val build = structureService.findBuildByName(
names.require("project"),
names.require("branch"),
names.require("build")
).getOrNull() ?: return null
// Gets the promotion level
val pl = structureService.findPromotionLevelByName(
names.require("project"),
names.require("branch"),
names.require("promotion")
).getOrNull() ?: return null
// Gets the LAST promotion run
structureService.getPromotionRunsForBuildAndPromotionLevel(build, pl).firstOrNull()
}
}
}
/**
* Given a project entity, returns the list of all the parents
*/
fun ProjectEntity?.parents(): List<ProjectEntity> = if (this == null) {
emptyList()
} else {
listOf(this) + parent.parents()
}
private fun Map<String, String>.require(name: String) =
get(name) ?: throw ProjectEntityNameMissingException(name)
class ProjectEntityNameMissingException(name: String) : InputException(
"""Name for "$name" is missing."""
) | mit | 704873fb33f3043a0bfe7b55042f8266 | 32.005319 | 115 | 0.556415 | 5.089418 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.