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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AoEiuV020/PaNovel
|
api/src/main/java/cc/aoeiuv020/panovel/api/site/sifang.kt
|
1
|
2419
|
package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.encrypt.base64Decode
import cc.aoeiuv020.jsonpath.get
import cc.aoeiuv020.jsonpath.jsonPath
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
import cc.aoeiuv020.panovel.api.firstIntPattern
class SiFang : DslJsoupNovelContext() {init {
hide = true
site {
name = "四方中文网"
baseUrl = "http://www.sifangbook.com"
logo = "http://www.sifangbook.com/static/index/Img/logo.jpg"
}
search {
get {
url = "/booklibrary/index"
data {
"keywords" to it
}
}
document {
items("#BooklibraryIndex > div.BooklibraryList > ul > li:not([class])") {
name("> span > a")
author("> a > dl > dd.nickname")
}
}
}
detailPageTemplate = "/booklibrary/show/id/%s/"
detail {
document {
novel {
name("#BooklibraryShow_Left > div.BookContent > div > div.title > span")
author("#BooklibraryShow_Left > div.BookContent > div > div.title > em") {
it.text().removeSuffix(" 著")
}
}
image("#BooklibraryShow_Left > div.BookContent > div > div.pic > img")
introduction("#BooklibraryShow_Left > div.BookContent > div > div.jianjie")
update("#BooklibraryShow_Left > div.BookContent > div > div.title > i", format = "yyyy-MM-dd HH:mm:ss", block = pickString("更新时间:(.*)"))
}
}
chaptersPageTemplate = "/booklibrary/readdir/id/%s/"
chapters {
document {
items("#BooklibraryShow_Left > div.BookDir > div.chapter_list > ul > li > a")
lastUpdate("#BooklibraryShow_Left > div.BookContent > div > div.title > i", format = "yyyy-MM-dd HH:mm:ss", block = pickString("更新时间:(.*)"))
}
}
//http://www.sifangbook.com/booklibrary/membersinglechapter/chapter_id/712.html
bookIdWithChapterIdRegex = firstIntPattern
contentPageTemplate = "http://www.sifangbook.com/booklibrary/membersinglechapter/chapter_id/%s.html"
content {
get {
url = getNovelContentUrl(it)
}
response {
it.jsonPath.get<List<String>>("@.data.show_content[*].content").map {
String(it.base64Decode()).trim()
}
}
}
}
}
|
gpl-3.0
|
7f69e0c6d53229c594db0ed2a21f5b5e
| 34.641791 | 152 | 0.570591 | 3.85 | false | false | false | false |
michaelgallacher/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/actionSystem/ex/QuickListsManager.kt
|
3
|
4688
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.actionSystem.ex
import com.intellij.configurationStore.LazySchemeProcessor
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.QuickSwitchSchemeAction
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.impl.BundledQuickListsProvider
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ExportableApplicationComponent
import com.intellij.openapi.options.SchemeManager
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.Project
import gnu.trove.THashSet
import java.util.function.Function
class QuickListsManager(private val myActionManager: ActionManager, schemeManagerFactory: SchemeManagerFactory) : ExportableApplicationComponent {
private val mySchemeManager: SchemeManager<QuickList>
init {
mySchemeManager = schemeManagerFactory.create("quicklists",
object : LazySchemeProcessor<QuickList, QuickList>(QuickList.DISPLAY_NAME_TAG) {
override fun createScheme(dataHolder: SchemeDataHolder<QuickList>,
name: String,
attributeProvider: Function<String, String?>,
isBundled: Boolean): QuickList {
val item = QuickList()
item.readExternal(dataHolder.read())
dataHolder.updateDigest(item)
return item
}
})
}
companion object {
@JvmStatic
val instance: QuickListsManager
get() = ApplicationManager.getApplication().getComponent(QuickListsManager::class.java)
}
override fun getExportFiles() = arrayOf(mySchemeManager.rootDirectory)
override fun getPresentableName() = IdeBundle.message("quick.lists.presentable.name")!!
override fun getComponentName() = "QuickListsManager"
override fun initComponent() {
for (provider in BundledQuickListsProvider.EP_NAME.extensions) {
for (path in provider.bundledListsRelativePaths) {
mySchemeManager.loadBundledScheme(path, provider)
}
}
mySchemeManager.loadSchemes()
registerActions()
}
override fun disposeComponent() {
}
val schemeManager: SchemeManager<QuickList>
get() = mySchemeManager
val allQuickLists: Array<QuickList>
get() {
return mySchemeManager.allSchemes.toTypedArray()
}
private fun registerActions() {
// to prevent exception if 2 or more targets have the same name
val registeredIds = THashSet<String>()
for (scheme in mySchemeManager.allSchemes) {
val actionId = scheme.actionId
if (registeredIds.add(actionId)) {
myActionManager.registerAction(actionId, InvokeQuickListAction(scheme))
}
}
}
private fun unregisterActions() {
for (oldId in myActionManager.getActionIds(QuickList.QUICK_LIST_PREFIX)) {
myActionManager.unregisterAction(oldId)
}
}
// used by external plugin
fun setQuickLists(quickLists: List<QuickList>) {
unregisterActions()
mySchemeManager.setSchemes(quickLists)
registerActions()
}
}
private class InvokeQuickListAction(private val myQuickList: QuickList) : QuickSwitchSchemeAction() {
init {
myActionPlace = ActionPlaces.ACTION_PLACE_QUICK_LIST_POPUP_ACTION
templatePresentation.description = myQuickList.description
templatePresentation.setText(myQuickList.name, false)
}
override fun fillActions(project: Project, group: DefaultActionGroup, dataContext: DataContext) {
val actionManager = ActionManager.getInstance()
for (actionId in myQuickList.actionIds) {
if (QuickList.SEPARATOR_ID == actionId) {
group.addSeparator()
}
else {
val action = actionManager.getAction(actionId)
if (action != null) {
group.add(action)
}
}
}
}
}
|
apache-2.0
|
889ae60cc2cc7aeeddd6e5d16b9eb7e0
| 34.515152 | 146 | 0.731015 | 5.024652 | false | false | false | false |
nemerosa/ontrack
|
ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/AutoValidationStampPropertyMutationProvider.kt
|
1
|
1573
|
package net.nemerosa.ontrack.extension.general
import graphql.schema.GraphQLInputObjectField
import net.nemerosa.ontrack.graphql.schema.MutationInput
import net.nemerosa.ontrack.graphql.schema.PropertyMutationProvider
import net.nemerosa.ontrack.graphql.schema.optionalBooleanInputField
import net.nemerosa.ontrack.model.structure.ProjectEntity
import net.nemerosa.ontrack.model.structure.PropertyType
import org.springframework.stereotype.Component
import kotlin.reflect.KClass
@Component
class AutoValidationStampPropertyMutationProvider: PropertyMutationProvider<AutoValidationStampProperty> {
override val propertyType: KClass<out PropertyType<AutoValidationStampProperty>> = AutoValidationStampPropertyType::class
override val mutationNameFragment: String = "AutoValidationStamp"
override val inputFields: List<GraphQLInputObjectField> = listOf(
optionalBooleanInputField(AutoValidationStampProperty::isAutoCreate.name, "If validation stamps must be created from predefined validation stamps"),
optionalBooleanInputField(AutoValidationStampProperty::isAutoCreateIfNotPredefined.name, "If validation stamps must be created even if predefined validation stamp is not available"),
)
override fun readInput(entity: ProjectEntity, input: MutationInput) = AutoValidationStampProperty(
isAutoCreate = input.getInput<Boolean>(AutoValidationStampProperty::isAutoCreate.name) ?: false,
isAutoCreateIfNotPredefined = input.getInput<Boolean>(AutoValidationStampProperty::isAutoCreateIfNotPredefined.name) ?: false,
)
}
|
mit
|
642d35bb750c0b3205db0f9886f7e0d1
| 55.214286 | 190 | 0.834711 | 5.123779 | false | false | false | false |
DemonWav/IntelliJBukkitSupport
|
src/main/kotlin/translations/reference/TranslationGotoModel.kt
|
1
|
2534
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.reference
import com.demonwav.mcdev.translations.TranslationConstants
import com.demonwav.mcdev.translations.TranslationFiles
import com.intellij.ide.util.gotoByName.ContributorsBasedGotoByModel
import com.intellij.navigation.ChooseByNameContributor
import com.intellij.navigation.NavigationItem
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.util.indexing.FindSymbolParameters
import java.util.TreeSet
class TranslationGotoModel(project: Project, private val prefix: String, private val suffix: String) :
ContributorsBasedGotoByModel(
project,
arrayOf(
ChooseByNameContributor.SYMBOL_EP_NAME.findExtensionOrFail(TranslationGotoSymbolContributor::class.java)
)
) {
override fun acceptItem(item: NavigationItem?): Boolean {
return TranslationFiles.getLocale(
(item as PsiElement).containingFile?.virtualFile
) == TranslationConstants.DEFAULT_LOCALE
}
override fun getElementsByName(
name: String,
parameters: FindSymbolParameters,
canceled: ProgressIndicator
): Array<Any> {
val superResult = super.getElementsByName(name, parameters, canceled).asSequence()
val result = TreeSet<PsiNamedElement> { o1, o2 ->
(o1 as PsiNamedElement).name?.compareTo((o2 as PsiNamedElement).name ?: return@TreeSet -1) ?: -1
}
result.addAll(
superResult.map { it as PsiNamedElement }.filter {
val key = it.name ?: return@filter false
key.startsWith(prefix) && key.endsWith(suffix)
}
)
return result.toArray()
}
override fun getPromptText() = "Choose translation to use"
override fun getNotInMessage() = "Couldn't find translation with that name"
override fun getNotFoundMessage() = "Couldn't find translation with that name"
override fun getCheckBoxName() = "Include non-project translations"
override fun loadInitialCheckBoxState() = false
override fun saveInitialCheckBoxState(state: Boolean) {
}
override fun getSeparators(): Array<String> = emptyArray()
override fun getFullName(element: Any) = element.toString()
override fun willOpenEditor() = false
}
|
mit
|
aa4ea602b4e7e1ef2f10100cd9531239
| 33.243243 | 116 | 0.716259 | 4.745318 | false | false | false | false |
DemonWav/IntelliJBukkitSupport
|
src/main/kotlin/platform/forge/inspections/sideonly/MethodCallSideOnlyInspection.kt
|
1
|
10184
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.inspections.sideonly
import com.demonwav.mcdev.platform.forge.util.ForgeConstants
import com.demonwav.mcdev.util.findContainingClass
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.PsiReferenceExpression
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.BaseInspectionVisitor
import com.siyeh.ig.InspectionGadgetsFix
import org.jetbrains.annotations.Nls
class MethodCallSideOnlyInspection : BaseInspection() {
@Nls
override fun getDisplayName() =
"Invalid usage of a @SideOnly method call"
override fun buildErrorString(vararg infos: Any): String {
val error = infos[0] as Error
return error.getErrorString(*SideOnlyUtil.getSubArray(infos))
}
override fun getStaticDescription() =
"Methods which are declared with a @SideOnly annotation can only be " +
"used in matching @SideOnly classes and methods."
override fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
val annotation = infos[3] as PsiAnnotation
return if (annotation.isWritable) {
RemoveAnnotationInspectionGadgetsFix(annotation, "Remove @SideOnly annotation from method declaration")
} else {
null
}
}
override fun buildVisitor(): BaseInspectionVisitor {
return object : BaseInspectionVisitor() {
override fun visitMethodCallExpression(expression: PsiMethodCallExpression) {
if (!SideOnlyUtil.beginningCheck(expression)) {
return
}
val referenceExpression = expression.methodExpression
val qualifierExpression = referenceExpression.qualifierExpression
// If this field is a @SidedProxy field, don't check. This is because people often are naughty and use the server impl as
// the base class for their @SidedProxy class, and client extends it. this messes up our checks, so we will just assume the
// right class is loaded for @SidedProxy's
run skip@{
if (qualifierExpression is PsiReferenceExpression) {
val resolve = qualifierExpression.resolve() as? PsiField ?: return@skip
val resolveFieldModifierList = resolve.modifierList ?: return@skip
if (resolveFieldModifierList.findAnnotation(ForgeConstants.SIDED_PROXY_ANNOTATION) == null) {
return@skip
}
return
}
}
val declaration = referenceExpression.resolve() as? PsiMethod ?: return
var (elementAnnotation, elementSide) = SideOnlyUtil.checkMethod(declaration)
// Check the class(es) the element is declared in
val declarationContainingClass = declaration.containingClass ?: return
val declarationClassHierarchySides = SideOnlyUtil.checkClassHierarchy(declarationContainingClass)
val (declarationClassAnnotation, declarationClassSide) =
SideOnlyUtil.getFirstSide(declarationClassHierarchySides)
// The element inherits the @SideOnly from it's parent class if it doesn't explicitly set it itself
var inherited = false
if (declarationClassAnnotation != null &&
declarationClassSide !== Side.NONE && (elementSide === Side.INVALID || elementSide === Side.NONE)
) {
inherited = true
elementSide = declarationClassSide
}
if (elementAnnotation == null || elementSide === Side.INVALID || elementSide === Side.NONE) {
return
}
// Check the class(es) the element is in
val containingClass = expression.findContainingClass() ?: return
val (classAnnotation, classSide) = SideOnlyUtil.getSideForClass(containingClass)
var classAnnotated = false
if (classAnnotation != null && classSide !== Side.NONE && classSide !== Side.INVALID) {
if (classSide !== elementSide) {
if (inherited) {
registerError(
referenceExpression.element,
Error.ANNOTATED_CLASS_METHOD_IN_CROSS_ANNOTATED_CLASS_METHOD,
elementAnnotation.renderSide(elementSide),
classAnnotation.renderSide(classSide),
declaration.getAnnotation(elementAnnotation.annotationName)
)
} else {
registerError(
referenceExpression.element,
Error.ANNOTATED_METHOD_IN_CROSS_ANNOTATED_CLASS_METHOD,
elementAnnotation.renderSide(elementSide),
classAnnotation.renderSide(classSide),
declaration.getAnnotation(elementAnnotation.annotationName)
)
}
}
classAnnotated = true
}
// Check the method the element is in
val (methodAnnotation, methodSide) = SideOnlyUtil.checkElementInMethod(expression)
// Put error on for method
if (methodAnnotation != null && elementSide !== methodSide && methodSide !== Side.INVALID) {
if (methodSide === Side.NONE) {
// If the class is properly annotated the method doesn't need to also be annotated
if (!classAnnotated) {
if (inherited) {
registerError(
referenceExpression.element,
Error.ANNOTATED_CLASS_METHOD_IN_UNANNOTATED_METHOD,
elementAnnotation.renderSide(elementSide),
null,
declaration.getAnnotation(elementAnnotation.annotationName)
)
} else {
registerError(
referenceExpression.element,
Error.ANNOTATED_METHOD_IN_UNANNOTATED_METHOD,
elementAnnotation.renderSide(elementSide),
null,
declaration.getAnnotation(elementAnnotation.annotationName)
)
}
}
} else {
if (inherited) {
registerError(
referenceExpression.element,
Error.ANNOTATED_CLASS_METHOD_IN_CROSS_ANNOTATED_METHOD,
elementAnnotation.renderSide(elementSide),
methodAnnotation.renderSide(methodSide),
declaration.getAnnotation(elementAnnotation.annotationName)
)
} else {
registerError(
referenceExpression.element,
Error.ANNOTATED_METHOD_IN_CROSS_ANNOTATED_METHOD,
elementAnnotation.renderSide(elementSide),
methodAnnotation.renderSide(methodSide),
declaration.getAnnotation(elementAnnotation.annotationName)
)
}
}
}
}
}
}
enum class Error {
ANNOTATED_METHOD_IN_UNANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method annotated with " + infos[0] + " cannot be referenced in an un-annotated method."
}
},
ANNOTATED_CLASS_METHOD_IN_UNANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method declared in a class annotated with " + infos[0] +
" cannot be referenced in an un-annotated method."
}
},
ANNOTATED_METHOD_IN_CROSS_ANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method annotated with " + infos[0] +
" cannot be referenced in a method annotated with " + infos[1] + "."
}
},
ANNOTATED_CLASS_METHOD_IN_CROSS_ANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method declared in a class annotated with " + infos[0] +
" cannot be referenced in a method annotated with " + infos[1] + "."
}
},
ANNOTATED_METHOD_IN_CROSS_ANNOTATED_CLASS_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method annotated with " + infos[0] +
" cannot be referenced in a class annotated with " + infos[1] + "."
}
},
ANNOTATED_CLASS_METHOD_IN_CROSS_ANNOTATED_CLASS_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method declared in a class annotated with " + infos[0] +
" cannot be referenced in a class annotated with " + infos[1] + "."
}
};
abstract fun getErrorString(vararg infos: Any): String
}
}
|
mit
|
dfa70f1da1d29b20079c8a4c8cd306e0
| 45.081448 | 139 | 0.538786 | 6.217338 | false | false | false | false |
DemonWav/IntelliJBukkitSupport
|
src/test/kotlin/framework/MockJdk.kt
|
1
|
2093
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.framework
import com.intellij.openapi.Disposable
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkAdditionalData
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.RootProvider
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ArrayUtil
import com.intellij.util.IncorrectOperationException
@Suppress("NonExtendableApiUsage")
class MockJdk(private val name: String, jar: VirtualFile, private val home: VirtualFile) :
UserDataHolderBase(), Sdk, RootProvider {
private val urls = arrayOf(jar.url)
private val roots = arrayOf(jar)
override fun getSdkType(): JavaSdk = JavaSdk.getInstance()
override fun getName() = name
override fun getVersionString() = name
override fun getHomePath() = this.home.path
override fun getHomeDirectory() = this.home
override fun getRootProvider() = this
override fun getSdkModificator() =
throw IncorrectOperationException("Can't modify, MockJDK is read-only")
override fun getSdkAdditionalData(): SdkAdditionalData? = null
override fun clone() = throw CloneNotSupportedException()
// Root provider
override fun getUrls(rootType: OrderRootType): Array<String> =
if (rootType == OrderRootType.CLASSES) urls else ArrayUtil.EMPTY_STRING_ARRAY
override fun getFiles(rootType: OrderRootType): Array<VirtualFile> =
if (rootType == OrderRootType.CLASSES) roots else VirtualFile.EMPTY_ARRAY
override fun addRootSetChangedListener(listener: RootProvider.RootSetChangedListener) {}
override fun addRootSetChangedListener(
listener: RootProvider.RootSetChangedListener,
parentDisposable: Disposable
) {
}
override fun removeRootSetChangedListener(listener: RootProvider.RootSetChangedListener) {}
}
|
mit
|
55709921e79b1607799407e39942d6eb
| 32.222222 | 95 | 0.763497 | 4.947991 | false | false | false | false |
traversals/kapsule
|
kapsule-core/src/test/kotlin/net/gouline/kapsule/TransitiveTest.kt
|
1
|
3310
|
/*
* Copyright 2017 Mike Gouline
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.gouline.kapsule
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Test case for transitive dependencies.
*/
class TransitiveTest {
@Test fun testCast_legal() {
try {
Module1(
object : ModuleA {
override val stringA = "A"
},
object : ModuleB {
val stringA by required { stringA }
override val stringB get() = "${stringA}B"
}
).transitive()
assertTrue(true)
} catch (e: TransitiveInjectionException) {
assertTrue(false)
}
}
@Test fun testCast_illegal() {
try {
Module2(
object : ModuleA {
override val stringA = "A"
},
object : ModuleC {
val stringA by required { stringA }
override val stringC get() = "${stringA}C"
}
).transitive()
assertTrue(false)
} catch (e: TransitiveInjectionException) {
assertTrue(true)
}
}
@Test fun testCast_valid() {
val a = object : ModuleA {
override val stringA = "A"
}
val b = object : ModuleB {
val stringA by required { stringA }
override val stringB get() = "${stringA}B"
}
Module1(a, b).transitive()
assertEquals("A", a.stringA)
assertEquals("A", b.stringA)
assertEquals("AB", b.stringB)
}
}
interface ModuleA {
val stringA: String
}
interface ModuleB : Injects<ModuleA> {
val stringB: String
}
interface ModuleC : Injects<RogueModule> {
val stringC: String
}
interface RogueModule {
val stringA: String
}
class Module1(
a: ModuleA,
b: ModuleB) :
ModuleA by a,
ModuleB by b,
HasModules {
override val modules = setOf(a, b)
}
class Module2(
a: ModuleA,
c: ModuleC) :
ModuleA by a,
ModuleC by c,
HasModules {
override val modules = setOf(a, c)
}
|
mit
|
81380038f8e0557b694535d42db624d7
| 30.52381 | 463 | 0.591541 | 4.534247 | false | true | false | false |
karollewandowski/aem-intellij-plugin
|
src/main/kotlin/co/nums/intellij/aem/htl/highlighting/AnnotationHolderHighlightingExtensions.kt
|
1
|
1479
|
package co.nums.intellij.aem.htl.highlighting
import com.intellij.lang.annotation.*
import com.intellij.lang.annotation.Annotation
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
private val noMessage = null
fun AnnotationHolder.highlightText(start: Int, end: Int, textAttributesKey: TextAttributesKey) {
highlightText(TextRange(start, end), textAttributesKey)
}
fun AnnotationHolder.highlightText(element: PsiElement, textAttributesKey: TextAttributesKey) {
highlightText(element.textRange, textAttributesKey)
}
fun AnnotationHolder.highlightText(textRange: TextRange, textAttributesKey: TextAttributesKey) {
val annotation = this.createInfoAnnotation(textRange, noMessage)
annotation.textAttributes = textAttributesKey
}
fun AnnotationHolder.createReferenceErrorAnnotation(start: Int, end: Int, errorMessage: String) =
createReferenceErrorAnnotation(TextRange(start, end), errorMessage)
fun AnnotationHolder.createReferenceErrorAnnotation(element: PsiElement, errorMessage: String) =
createReferenceErrorAnnotation(element.textRange, errorMessage)
fun AnnotationHolder.createReferenceErrorAnnotation(textRange: TextRange, errorMessage: String): Annotation {
val errorAnnotation = this.createErrorAnnotation(textRange, errorMessage)
errorAnnotation.textAttributes = HtlHighlighterColors.UNREFERENCED_IDENTIFIER
return errorAnnotation
}
|
gpl-3.0
|
594062ab9a9f97c796b4846d99dd3e98
| 42.5 | 109 | 0.82691 | 5.030612 | false | false | false | false |
Ztiany/Repository
|
Kotlin/Kotlin-github/app/src/main/java/com/bennyhuo/github/view/fragments/subfragments/IssueListAdapter.kt
|
2
|
1164
|
package com.bennyhuo.github.view.fragments.subfragments
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.View
import com.bennyhuo.github.R
import com.bennyhuo.github.network.entities.Issue
import com.bennyhuo.github.utils.githubTimeToDate
import com.bennyhuo.github.utils.htmlText
import com.bennyhuo.github.utils.view
import com.bennyhuo.github.view.common.CommonListAdapter
import kotlinx.android.synthetic.main.item_issue.view.*
import org.jetbrains.anko.imageResource
/**
* Created by benny on 7/9/17.
*/
open class IssueListAdapter : CommonListAdapter<Issue>(R.layout.item_issue) {
override fun onItemClicked(itemView: View, issue: Issue) {
// todo
}
override fun onBindData(viewHolder: ViewHolder, issue: Issue) {
viewHolder.itemView.apply {
iconView.imageResource = if (issue.state == "open") R.drawable.ic_issue_open else R.drawable.ic_issue_closed
titleView.text = issue.title
timeView.text = githubTimeToDate(issue.created_at).view()
bodyView.htmlText = issue.body_html
commentCount.text = issue.comments.toString()
}
}
}
|
apache-2.0
|
ff057331c683e2af07f4c4e6ff816a01
| 36.580645 | 120 | 0.734536 | 3.892977 | false | false | false | false |
vanita5/twittnuker
|
twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/users/AbsRequestUsersLoader.kt
|
1
|
4473
|
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.loader.users
import android.accounts.AccountManager
import android.content.Context
import org.mariotaku.kpreferences.get
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.microblog.library.twitter.model.Paging
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.constant.loadItemLimitKey
import de.vanita5.twittnuker.exception.AccountNotFoundException
import de.vanita5.twittnuker.extension.model.api.applyLoadLimit
import de.vanita5.twittnuker.loader.iface.IPaginationLoader
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.ListResponse
import de.vanita5.twittnuker.model.ParcelableUser
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.pagination.PaginatedList
import de.vanita5.twittnuker.model.pagination.Pagination
import de.vanita5.twittnuker.model.util.AccountUtils
import de.vanita5.twittnuker.util.DebugLog
import de.vanita5.twittnuker.util.dagger.DependencyHolder
import java.util.*
abstract class AbsRequestUsersLoader(
context: Context,
val accountKey: UserKey?,
data: List<ParcelableUser>?,
fromUser: Boolean
) : ParcelableUsersLoader(context, data, fromUser), IPaginationLoader {
protected val profileImageSize: String = context.getString(R.string.profile_image_size)
override var pagination: Pagination? = null
override var prevPagination: Pagination? = null
protected set
override var nextPagination: Pagination? = null
protected set
protected val loadItemLimit: Int
init {
val preferences = DependencyHolder.get(context).preferences
loadItemLimit = preferences[loadItemLimitKey]
}
override fun loadInBackground(): List<ParcelableUser> {
val data = data
val details: AccountDetails
val users: List<ParcelableUser>
try {
val am = AccountManager.get(context)
details = accountKey?.let { AccountUtils.getAccountDetails(am, it, true) } ?:
throw AccountNotFoundException()
users = getUsersInternal(details)
} catch (e: MicroBlogException) {
DebugLog.w(tr = e)
return ListResponse.getListInstance(data, e)
}
var pos = data.size
for (user in users) {
if (hasId(user.key)) {
continue
}
user.position = pos.toLong()
processUser(details, user)
pos++
}
data.addAll(users)
processUsersData(details, data)
return ListResponse.getListInstance(data)
}
protected open fun processUser(details: AccountDetails, user: ParcelableUser) {
}
protected open fun processUsersData(details: AccountDetails, list: MutableList<ParcelableUser>) {
Collections.sort(data)
}
protected open fun processPaging(paging: Paging, details: AccountDetails, loadItemLimit: Int) {
paging.applyLoadLimit(details, loadItemLimit)
}
@Throws(MicroBlogException::class)
protected abstract fun getUsers(details: AccountDetails, paging: Paging):
PaginatedList<ParcelableUser>
@Throws(MicroBlogException::class)
private fun getUsersInternal(details: AccountDetails): List<ParcelableUser> {
val paging = Paging()
processPaging(paging, details, loadItemLimit)
pagination?.applyTo(paging)
val users = getUsers(details, paging)
prevPagination = users.previousPage
nextPagination = users.nextPage
return users
}
}
|
gpl-3.0
|
0626b290b210b34e3e8732f2877f4863
| 36.283333 | 101 | 0.717639 | 4.536511 | false | false | false | false |
stripe/stripe-android
|
payments-core/src/main/java/com/stripe/android/model/parsers/SourceJsonParser.kt
|
1
|
15165
|
package com.stripe.android.model.parsers
import androidx.annotation.Size
import com.stripe.android.core.model.StripeJsonUtils
import com.stripe.android.core.model.StripeJsonUtils.optString
import com.stripe.android.core.model.StripeModel
import com.stripe.android.core.model.parsers.ModelJsonParser
import com.stripe.android.model.Source
import com.stripe.android.model.SourceTypeModel
import org.json.JSONObject
internal class SourceJsonParser : ModelJsonParser<Source> {
override fun parse(json: JSONObject): Source? {
return when (json.optString(FIELD_OBJECT)) {
VALUE_CARD -> fromCardJson(json)
VALUE_SOURCE -> fromSourceJson(json)
else -> null
}
}
internal class RedirectJsonParser : ModelJsonParser<Source.Redirect> {
override fun parse(json: JSONObject): Source.Redirect {
return Source.Redirect(
returnUrl = optString(json, FIELD_RETURN_URL),
status = Source.Redirect.Status.fromCode(optString(json, FIELD_STATUS)),
url = optString(json, FIELD_URL)
)
}
internal companion object {
private const val FIELD_RETURN_URL = "return_url"
private const val FIELD_STATUS = "status"
private const val FIELD_URL = "url"
}
}
internal class CodeVerificationJsonParser : ModelJsonParser<Source.CodeVerification> {
override fun parse(json: JSONObject): Source.CodeVerification {
return Source.CodeVerification(
attemptsRemaining = json.optInt(FIELD_ATTEMPTS_REMAINING, INVALID_ATTEMPTS_REMAINING),
status = Source.CodeVerification.Status.fromCode(optString(json, FIELD_STATUS))
)
}
private companion object {
private const val FIELD_ATTEMPTS_REMAINING = "attempts_remaining"
private const val FIELD_STATUS = "status"
private const val INVALID_ATTEMPTS_REMAINING = -1
}
}
internal class ReceiverJsonParser : ModelJsonParser<Source.Receiver> {
override fun parse(json: JSONObject): Source.Receiver {
return Source.Receiver(
optString(json, FIELD_ADDRESS),
json.optLong(FIELD_AMOUNT_CHARGED),
json.optLong(FIELD_AMOUNT_RECEIVED),
json.optLong(FIELD_AMOUNT_RETURNED)
)
}
private companion object {
private const val FIELD_ADDRESS = "address"
private const val FIELD_AMOUNT_CHARGED = "amount_charged"
private const val FIELD_AMOUNT_RECEIVED = "amount_received"
private const val FIELD_AMOUNT_RETURNED = "amount_returned"
}
}
internal class OwnerJsonParser : ModelJsonParser<Source.Owner> {
override fun parse(json: JSONObject): Source.Owner {
return Source.Owner(
address = json.optJSONObject(FIELD_ADDRESS)?.let {
AddressJsonParser().parse(it)
},
email = optString(json, FIELD_EMAIL),
name = optString(json, FIELD_NAME),
phone = optString(json, FIELD_PHONE),
verifiedAddress = json.optJSONObject(FIELD_VERIFIED_ADDRESS)?.let {
AddressJsonParser().parse(it)
},
verifiedEmail = optString(json, FIELD_VERIFIED_EMAIL),
verifiedName = optString(json, FIELD_VERIFIED_NAME),
verifiedPhone = optString(json, FIELD_VERIFIED_PHONE)
)
}
private companion object {
private const val FIELD_ADDRESS = "address"
private const val FIELD_EMAIL = "email"
private const val FIELD_NAME = "name"
private const val FIELD_PHONE = "phone"
private const val FIELD_VERIFIED_ADDRESS = "verified_address"
private const val FIELD_VERIFIED_EMAIL = "verified_email"
private const val FIELD_VERIFIED_NAME = "verified_name"
private const val FIELD_VERIFIED_PHONE = "verified_phone"
}
}
internal class KlarnaJsonParser : ModelJsonParser<Source.Klarna> {
override fun parse(json: JSONObject): Source.Klarna {
return Source.Klarna(
firstName = optString(json, FIELD_FIRST_NAME),
lastName = optString(json, FIELD_LAST_NAME),
purchaseCountry = optString(json, FIELD_PURCHASE_COUNTRY),
clientToken = optString(json, FIELD_CLIENT_TOKEN),
payLaterAssetUrlsDescriptive = optString(json, FIELD_PAY_LATER_ASSET_URLS_DESCRIPTIVE),
payLaterAssetUrlsStandard = optString(json, FIELD_PAY_LATER_ASSET_URLS_STANDARD),
payLaterName = optString(json, FIELD_PAY_LATER_NAME),
payLaterRedirectUrl = optString(json, FIELD_PAY_LATER_REDIRECT_URL),
payNowAssetUrlsDescriptive = optString(json, FIELD_PAY_NOW_ASSET_URLS_DESCRIPTIVE),
payNowAssetUrlsStandard = optString(json, FIELD_PAY_NOW_ASSET_URLS_STANDARD),
payNowName = optString(json, FIELD_PAY_NOW_NAME),
payNowRedirectUrl = optString(json, FIELD_PAY_NOW_REDIRECT_URL),
payOverTimeAssetUrlsDescriptive = optString(json, FIELD_PAY_OVER_TIME_ASSET_URLS_DESCRIPTIVE),
payOverTimeAssetUrlsStandard = optString(json, FIELD_PAY_OVER_TIME_ASSET_URLS_STANDARD),
payOverTimeName = optString(json, FIELD_PAY_OVER_TIME_NAME),
payOverTimeRedirectUrl = optString(json, FIELD_PAY_OVER_TIME_REDIRECT_URL),
paymentMethodCategories = parseSet(json, FIELD_PAYMENT_METHOD_CATEGORIES),
customPaymentMethods = parseSet(json, FIELD_CUSTOM_PAYMENT_METHODS)
)
}
private fun parseSet(json: JSONObject, key: String): Set<String> {
return optString(json, key)?.split(",")?.toSet().orEmpty()
}
private companion object {
private const val FIELD_FIRST_NAME = "first_name"
private const val FIELD_LAST_NAME = "last_name"
private const val FIELD_PURCHASE_COUNTRY = "purchase_country"
private const val FIELD_CLIENT_TOKEN = "client_token"
private const val FIELD_PAY_LATER_ASSET_URLS_DESCRIPTIVE = "pay_later_asset_urls_descriptive"
private const val FIELD_PAY_LATER_ASSET_URLS_STANDARD = "pay_later_asset_urls_standard"
private const val FIELD_PAY_LATER_NAME = "pay_later_name"
private const val FIELD_PAY_LATER_REDIRECT_URL = "pay_later_redirect_url"
private const val FIELD_PAY_NOW_ASSET_URLS_DESCRIPTIVE = "pay_now_asset_urls_descriptive"
private const val FIELD_PAY_NOW_ASSET_URLS_STANDARD = "pay_now_asset_urls_standard"
private const val FIELD_PAY_NOW_NAME = "pay_now_name"
private const val FIELD_PAY_NOW_REDIRECT_URL = "pay_now_redirect_url"
private const val FIELD_PAY_OVER_TIME_ASSET_URLS_DESCRIPTIVE = "pay_over_time_asset_urls_descriptive"
private const val FIELD_PAY_OVER_TIME_ASSET_URLS_STANDARD = "pay_over_time_asset_urls_standard"
private const val FIELD_PAY_OVER_TIME_NAME = "pay_over_time_name"
private const val FIELD_PAY_OVER_TIME_REDIRECT_URL = "pay_over_time_redirect_url"
private const val FIELD_PAYMENT_METHOD_CATEGORIES = "payment_method_categories"
private const val FIELD_CUSTOM_PAYMENT_METHODS = "custom_payment_methods"
}
}
private companion object {
private const val VALUE_SOURCE = "source"
private const val VALUE_CARD = "card"
private val MODELED_TYPES = setOf(
Source.SourceType.CARD,
Source.SourceType.SEPA_DEBIT
)
private const val FIELD_ID: String = "id"
private const val FIELD_OBJECT: String = "object"
private const val FIELD_AMOUNT: String = "amount"
private const val FIELD_CLIENT_SECRET: String = "client_secret"
private const val FIELD_CODE_VERIFICATION: String = "code_verification"
private const val FIELD_CREATED: String = "created"
private const val FIELD_CURRENCY: String = "currency"
private const val FIELD_FLOW: String = "flow"
private const val FIELD_LIVEMODE: String = "livemode"
private const val FIELD_OWNER: String = "owner"
private const val FIELD_RECEIVER: String = "receiver"
private const val FIELD_REDIRECT: String = "redirect"
private const val FIELD_SOURCE_ORDER: String = "source_order"
private const val FIELD_STATEMENT_DESCRIPTOR: String = "statement_descriptor"
private const val FIELD_STATUS: String = "status"
private const val FIELD_TYPE: String = "type"
private const val FIELD_USAGE: String = "usage"
private const val FIELD_WECHAT: String = "wechat"
private const val FIELD_KLARNA: String = "klarna"
private fun fromCardJson(jsonObject: JSONObject): Source {
return Source(
optString(jsonObject, FIELD_ID),
sourceTypeModel = SourceCardDataJsonParser().parse(jsonObject),
type = Source.SourceType.CARD,
typeRaw = Source.SourceType.CARD
)
}
private fun fromSourceJson(jsonObject: JSONObject): Source {
@Source.SourceType val typeRaw = optString(jsonObject, FIELD_TYPE)
?: Source.SourceType.UNKNOWN
@Source.SourceType val type = asSourceType(typeRaw)
// Until we have models for all types, keep the original hash and the
// model object. The customType variable can be any field, and is not altered by
// trying to force it to be a type that we know of.
val sourceTypeData = StripeJsonUtils.jsonObjectToMap(
jsonObject.optJSONObject(typeRaw)
)
val sourceTypeModel = if (MODELED_TYPES.contains(typeRaw)) {
optStripeJsonModel<SourceTypeModel>(jsonObject, typeRaw)
} else {
null
}
return Source(
id = optString(jsonObject, FIELD_ID),
amount = StripeJsonUtils.optLong(jsonObject, FIELD_AMOUNT),
clientSecret = optString(jsonObject, FIELD_CLIENT_SECRET),
codeVerification = optStripeJsonModel(
jsonObject,
FIELD_CODE_VERIFICATION
),
created = StripeJsonUtils.optLong(jsonObject, FIELD_CREATED),
currency = optString(jsonObject, FIELD_CURRENCY),
flow = Source.Flow.fromCode(optString(jsonObject, FIELD_FLOW)),
isLiveMode = jsonObject.optBoolean(FIELD_LIVEMODE),
owner = optStripeJsonModel(jsonObject, FIELD_OWNER),
receiver = optStripeJsonModel(jsonObject, FIELD_RECEIVER),
redirect = optStripeJsonModel(jsonObject, FIELD_REDIRECT),
sourceOrder = jsonObject.optJSONObject(FIELD_SOURCE_ORDER)?.let {
SourceOrderJsonParser().parse(it)
},
statementDescriptor = optString(jsonObject, FIELD_STATEMENT_DESCRIPTOR),
status = Source.Status.fromCode(optString(jsonObject, FIELD_STATUS)),
sourceTypeData = sourceTypeData,
sourceTypeModel = sourceTypeModel,
type = type,
typeRaw = typeRaw,
usage = Source.Usage.fromCode(optString(jsonObject, FIELD_USAGE)),
_weChat = if (Source.SourceType.WECHAT == type) {
WeChatJsonParser().parse(
jsonObject.optJSONObject(FIELD_WECHAT) ?: JSONObject()
)
} else {
null
},
_klarna = if (Source.SourceType.KLARNA == type) {
KlarnaJsonParser().parse(
jsonObject.optJSONObject(FIELD_KLARNA) ?: JSONObject()
)
} else {
null
}
)
}
private inline fun <reified T : StripeModel> optStripeJsonModel(
jsonObject: JSONObject,
@Size(min = 1) key: String
): T? {
if (!jsonObject.has(key)) {
return null
}
val model: StripeModel? = when (key) {
FIELD_CODE_VERIFICATION -> {
jsonObject.optJSONObject(FIELD_CODE_VERIFICATION)?.let {
CodeVerificationJsonParser().parse(it)
}
}
FIELD_OWNER -> {
jsonObject.optJSONObject(FIELD_OWNER)?.let {
OwnerJsonParser().parse(it)
}
}
FIELD_RECEIVER -> {
jsonObject.optJSONObject(FIELD_RECEIVER)?.let {
ReceiverJsonParser().parse(it)
}
}
FIELD_REDIRECT -> {
jsonObject.optJSONObject(FIELD_REDIRECT)?.let {
RedirectJsonParser().parse(it)
}
}
Source.SourceType.CARD -> {
jsonObject.optJSONObject(Source.SourceType.CARD)?.let {
SourceCardDataJsonParser().parse(it)
}
}
Source.SourceType.SEPA_DEBIT -> {
jsonObject.optJSONObject(Source.SourceType.SEPA_DEBIT)?.let {
SourceSepaDebitDataJsonParser().parse(it)
}
}
else -> {
null
}
}
return model as? T
}
@Source.SourceType
private fun asSourceType(sourceType: String?): String {
return when (sourceType) {
Source.SourceType.CARD -> Source.SourceType.CARD
Source.SourceType.THREE_D_SECURE -> Source.SourceType.THREE_D_SECURE
Source.SourceType.GIROPAY -> Source.SourceType.GIROPAY
Source.SourceType.SEPA_DEBIT -> Source.SourceType.SEPA_DEBIT
Source.SourceType.IDEAL -> Source.SourceType.IDEAL
Source.SourceType.SOFORT -> Source.SourceType.SOFORT
Source.SourceType.BANCONTACT -> Source.SourceType.BANCONTACT
Source.SourceType.ALIPAY -> Source.SourceType.ALIPAY
Source.SourceType.EPS -> Source.SourceType.EPS
Source.SourceType.P24 -> Source.SourceType.P24
Source.SourceType.MULTIBANCO -> Source.SourceType.MULTIBANCO
Source.SourceType.WECHAT -> Source.SourceType.WECHAT
Source.SourceType.UNKNOWN -> Source.SourceType.UNKNOWN
Source.SourceType.KLARNA -> Source.SourceType.KLARNA
else -> Source.SourceType.UNKNOWN
}
}
}
}
|
mit
|
511617fa85d8e6bed938327e7ca77dce
| 46.990506 | 113 | 0.593604 | 4.832696 | false | false | false | false |
Devifish/ReadMe
|
app/src/main/java/cn/devifish/readme/view/adapter/StackItemListRecyclerAdapter.kt
|
1
|
1417
|
package cn.devifish.readme.view.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.devifish.readme.R
import cn.devifish.readme.entity.Book
import cn.devifish.readme.util.Config
import cn.devifish.readme.view.base.BaseRecyclerAdapter
import cn.devifish.readme.view.base.BaseViewHolder
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.book_item_stack.view.*
/**
* Created by zhang on 2017/6/9.
* 书库子列表适配器
*/
class StackItemListRecyclerAdapter(): BaseRecyclerAdapter<Book, StackItemListRecyclerAdapter.StackItemListHolder>() {
constructor(data: MutableList<Book>) : this() {
super.data = data
}
override fun onCreateView(group: ViewGroup, viewType: Int): StackItemListHolder {
val view = LayoutInflater.from(group.context).inflate(R.layout.book_item_stack, group, false)
return StackItemListHolder(view)
}
override fun onBindView(holder: StackItemListHolder, position: Int) = holder.bind(getItem(position)!!)
inner class StackItemListHolder(itemView: View): BaseViewHolder<Book>(itemView, listener) {
override fun bind(m: Book) {
itemView.title.text = m.title
itemView.author.text = m.author
Glide.with(itemView.context).load(Config.IMG_BASE_URL + m.cover)
.into(itemView.book_image);
}
}
}
|
apache-2.0
|
b5a2b95a71215a82cf00690985e9a5c9
| 32.380952 | 117 | 0.724483 | 3.980114 | false | false | false | false |
ARostovsky/teamcity-rest-client
|
teamcity-rest-client-api/src/main/kotlin/org/jetbrains/teamcity/rest/api.kt
|
1
|
24154
|
package org.jetbrains.teamcity.rest
import java.io.File
import java.io.OutputStream
import java.time.Duration
import java.time.Instant
import java.time.ZonedDateTime
import java.util.*
import java.util.concurrent.TimeUnit
abstract class TeamCityInstance {
abstract val serverUrl: String
abstract fun withLogResponses(): TeamCityInstance
abstract fun withTimeout(timeout: Long, unit: TimeUnit): TeamCityInstance
abstract fun builds(): BuildLocator
abstract fun investigations(): InvestigationLocator
abstract fun build(id: BuildId): Build
abstract fun build(buildConfigurationId: BuildConfigurationId, number: String): Build?
abstract fun buildConfiguration(id: BuildConfigurationId): BuildConfiguration
abstract fun vcsRoots(): VcsRootLocator
abstract fun vcsRoot(id: VcsRootId): VcsRoot
abstract fun project(id: ProjectId): Project
abstract fun rootProject(): Project
abstract fun buildQueue(): BuildQueue
abstract fun user(id: UserId): User
abstract fun user(userName: String): User
abstract fun users(): UserLocator
abstract fun buildAgents(): BuildAgentLocator
abstract fun buildAgentPools(): BuildAgentPoolLocator
abstract fun testRuns(): TestRunsLocator
abstract fun change(buildConfigurationId: BuildConfigurationId, vcsRevision: String): Change
abstract fun change(id: ChangeId): Change
@Deprecated(message = "use project(projectId).getHomeUrl(branch)",
replaceWith = ReplaceWith("project(projectId).getHomeUrl(branch)"))
abstract fun getWebUrl(projectId: ProjectId, branch: String? = null): String
@Deprecated(message = "use buildConfiguration(buildConfigurationId).getHomeUrl(branch)",
replaceWith = ReplaceWith("buildConfiguration(buildConfigurationId).getHomeUrl(branch)"))
abstract fun getWebUrl(buildConfigurationId: BuildConfigurationId, branch: String? = null): String
@Deprecated(message = "use build(buildId).getHomeUrl()",
replaceWith = ReplaceWith("build(buildId).getHomeUrl()"))
abstract fun getWebUrl(buildId: BuildId): String
@Deprecated(message = "use change(changeId).getHomeUrl()",
replaceWith = ReplaceWith("change(changeId).getHomeUrl(specificBuildConfigurationId, includePersonalBuilds)"))
abstract fun getWebUrl(changeId: ChangeId, specificBuildConfigurationId: BuildConfigurationId? = null, includePersonalBuilds: Boolean? = null): String
@Deprecated(message = "use buildQueue().queuedBuilds(projectId)",
replaceWith = ReplaceWith("buildQueue().queuedBuilds(projectId)"))
abstract fun queuedBuilds(projectId: ProjectId? = null): List<Build>
companion object {
private const val factoryFQN = "org.jetbrains.teamcity.rest.TeamCityInstanceFactory"
@JvmStatic
@Deprecated("Use [TeamCityInstanceFactory] class instead", ReplaceWith("TeamCityInstanceFactory.guestAuth(serverUrl)", factoryFQN))
fun guestAuth(serverUrl: String): TeamCityInstance = TeamCityInstance::class.java.classLoader
.loadClass(factoryFQN)
.getMethod("guestAuth", String::class.java)
.invoke(null, serverUrl) as TeamCityInstance
@JvmStatic
@Deprecated("Use [TeamCityInstanceFactory] class instead", ReplaceWith("TeamCityInstanceFactory.httpAuth(serverUrl, username, password)", factoryFQN))
fun httpAuth(serverUrl: String, username: String, password: String): TeamCityInstance
= TeamCityInstance::class.java.classLoader
.loadClass(factoryFQN)
.getMethod("httpAuth", String::class.java, String::class.java, String::class.java)
.invoke(null, serverUrl, username, password) as TeamCityInstance
}
}
data class VcsRootType(val stringType: String) {
companion object {
val GIT = VcsRootType("jetbrains.git")
}
}
interface VcsRootLocator {
fun all(): Sequence<VcsRoot>
@Deprecated(message = "use all() which returns lazy sequence",
replaceWith = ReplaceWith("all().toList()"))
fun list(): List<VcsRoot>
}
interface BuildAgentLocator {
fun all(): Sequence<BuildAgent>
}
interface BuildAgentPoolLocator {
fun all(): Sequence<BuildAgentPool>
}
interface UserLocator {
fun all(): Sequence<User>
@Deprecated("use instance.user(id)")
fun withId(id: UserId): UserLocator
@Deprecated(message = "use instance.user(userName)")
fun withUsername(name: String): UserLocator
@Deprecated(message = "use all() method which returns lazy sequence",
replaceWith = ReplaceWith("all().toList()"))
fun list(): List<User>
}
interface BuildLocator {
fun fromConfiguration(buildConfigurationId: BuildConfigurationId): BuildLocator
fun withNumber(buildNumber: String): BuildLocator
/**
* Filters builds to include only ones which are built on top of the specified revision.
*/
fun withVcsRevision(vcsRevision: String): BuildLocator
fun snapshotDependencyTo(buildId: BuildId): BuildLocator
/**
* By default only successful builds are returned, call this method to include failed builds as well.
*/
fun includeFailed(): BuildLocator
/**
* By default only finished builds are returned
*/
fun includeRunning(): BuildLocator
fun onlyRunning(): BuildLocator
/**
* By default canceled builds are not returned
*/
fun includeCanceled(): BuildLocator
fun onlyCanceled(): BuildLocator
fun withStatus(status: BuildStatus): BuildLocator
fun withTag(tag: String): BuildLocator
fun withBranch(branch: String): BuildLocator
/**
* By default only builds from the default branch are returned, call this method to include builds from all branches.
*/
fun withAllBranches(): BuildLocator
fun pinnedOnly(): BuildLocator
fun includePersonal() : BuildLocator
fun onlyPersonal(): BuildLocator
fun limitResults(count: Int): BuildLocator
fun pageSize(pageSize: Int): BuildLocator
fun since(date: Instant) : BuildLocator
fun until(date: Instant) : BuildLocator
fun latest(): Build?
fun all(): Sequence<Build>
@Deprecated(message = "use all() which returns lazy sequence",
replaceWith = ReplaceWith("all().toList()"))
fun list(): List<Build>
@Deprecated(message = "use `since` with java.time.Instant",
replaceWith = ReplaceWith("since(date.toInstant())"))
fun sinceDate(date: Date) : BuildLocator
@Deprecated(message = "use `until` with java.time.Instant",
replaceWith = ReplaceWith("until(date.toInstant())"))
fun untilDate(date: Date) : BuildLocator
@Deprecated(message = "use includeFailed()",
replaceWith = ReplaceWith("includeFailed()"))
fun withAnyStatus(): BuildLocator
}
interface InvestigationLocator {
fun limitResults(count: Int): InvestigationLocator
fun forProject(projectId: ProjectId): InvestigationLocator
fun withTargetType(targetType: InvestigationTargetType): InvestigationLocator
fun all(): Sequence<Investigation>
}
interface TestRunsLocator {
fun limitResults(count: Int): TestRunsLocator
fun pageSize(pageSize: Int): TestRunsLocator
fun forBuild(buildId: BuildId): TestRunsLocator
fun forTest(testId: TestId): TestRunsLocator
fun forProject(projectId: ProjectId): TestRunsLocator
fun withStatus(testStatus: TestStatus): TestRunsLocator
fun all(): Sequence<TestRun>
}
data class ProjectId(val stringId: String) {
override fun toString(): String = stringId
}
data class BuildId(val stringId: String) {
override fun toString(): String = stringId
}
data class TestId(val stringId: String) {
override fun toString(): String = stringId
}
data class ChangeId(val stringId: String) {
override fun toString(): String = stringId
}
data class BuildConfigurationId(val stringId: String) {
override fun toString(): String = stringId
}
data class VcsRootId(val stringId: String) {
override fun toString(): String = stringId
}
data class BuildProblemId(val stringId: String) {
override fun toString(): String = stringId
}
data class BuildAgentPoolId(val stringId: String) {
override fun toString(): String = stringId
}
data class BuildAgentId(val stringId: String) {
override fun toString(): String = stringId
}
data class InvestigationId(val stringId: String) {
override fun toString(): String = stringId
}
data class BuildProblemType(val stringType: String) {
override fun toString(): String = stringType
val isSnapshotDependencyError: Boolean
get() = stringType == "SNAPSHOT_DEPENDENCY_ERROR_BUILD_PROCEEDS_TYPE" ||
stringType == "SNAPSHOT_DEPENDENCY_ERROR"
companion object {
val FAILED_TESTS = BuildProblemType("TC_FAILED_TESTS")
}
}
interface Project {
val id: ProjectId
val name: String
val archived: Boolean
val parentProjectId: ProjectId?
/**
* Web UI URL for user, especially useful for error and log messages
*/
fun getHomeUrl(branch: String? = null): String
fun getTestHomeUrl(testId: TestId): String
val childProjects: List<Project>
val buildConfigurations: List<BuildConfiguration>
val parameters: List<Parameter>
fun setParameter(name: String, value: String)
/**
* See properties example from existing VCS roots via inspection of the following url:
* https://teamcity/app/rest/vcs-roots/id:YourVcsRootId
*/
fun createVcsRoot(id: VcsRootId, name: String, type: VcsRootType, properties: Map<String, String>): VcsRoot
fun createProject(id: ProjectId, name: String): Project
/**
* XML in the same format as
* https://teamcity/app/rest/buildTypes/YourBuildConfigurationId
* returns
*/
fun createBuildConfiguration(buildConfigurationDescriptionXml: String): BuildConfiguration
@Deprecated(message = "use getHomeUrl(branch)",
replaceWith = ReplaceWith("getHomeUrl(branch"))
fun getWebUrl(branch: String? = null): String
@Deprecated(message = "use childProjects",
replaceWith = ReplaceWith("childProjects"))
fun fetchChildProjects(): List<Project>
@Deprecated(message = "use buildConfigurations",
replaceWith = ReplaceWith("buildConfigurations"))
fun fetchBuildConfigurations(): List<BuildConfiguration>
@Deprecated(message = "use parameters",
replaceWith = ReplaceWith("parameters"))
fun fetchParameters(): List<Parameter>
}
interface BuildConfiguration {
val id: BuildConfigurationId
val name: String
val projectId: ProjectId
val paused: Boolean
/**
* Web UI URL for user, especially useful for error and log messages
*/
fun getHomeUrl(branch: String? = null): String
val buildTags: List<String>
val finishBuildTriggers: List<FinishBuildTrigger>
val artifactDependencies: List<ArtifactDependency>
fun setParameter(name: String, value: String)
var buildCounter: Int
var buildNumberFormat: String
fun runBuild(parameters: Map<String, String>? = null,
queueAtTop: Boolean = false,
cleanSources: Boolean? = null,
rebuildAllDependencies: Boolean = false,
comment: String? = null,
logicalBranchName: String? = null,
personal: Boolean = false): Build
@Deprecated(message = "use getHomeUrl(branch)",
replaceWith = ReplaceWith("getHomeUrl(branch)"))
fun getWebUrl(branch: String? = null): String
@Deprecated(message = "use buildTags",
replaceWith = ReplaceWith("buildTags"))
fun fetchBuildTags(): List<String>
@Deprecated(message = "use finishBuildTriggers",
replaceWith = ReplaceWith("finishBuildTriggers"))
fun fetchFinishBuildTriggers(): List<FinishBuildTrigger>
@Deprecated(message = "use artifactDependencies",
replaceWith = ReplaceWith("artifactDependencies"))
fun fetchArtifactDependencies(): List<ArtifactDependency>
}
interface BuildProblem {
val id: BuildProblemId
val type: BuildProblemType
val identity: String
}
interface BuildProblemOccurrence {
val buildProblem: BuildProblem
val build: Build
val details: String
val additionalData: String?
}
interface Parameter {
val name: String
val value: String
val own: Boolean
}
interface Branch {
val name: String?
val isDefault: Boolean
}
interface BuildCommentInfo {
val user: User?
val timestamp: ZonedDateTime
val text: String
}
interface BuildAgentEnabledInfo {
val user: User?
val timestamp: ZonedDateTime
val text: String
}
interface BuildAgentAuthorizedInfo {
val user: User?
val timestamp: ZonedDateTime
val text: String
}
interface BuildCanceledInfo {
val user: User?
val cancelDateTime: ZonedDateTime
@Deprecated(message = "use cancelDateTime", replaceWith = ReplaceWith("Date.from(cancelDateTime.toInstant())"))
val cancelDate: Date
}
interface Build {
val id: BuildId
val buildConfigurationId: BuildConfigurationId
val buildNumber: String?
val status: BuildStatus?
val branch: Branch
val state: BuildState
val personal: Boolean
val name: String
val canceledInfo: BuildCanceledInfo?
val comment: BuildCommentInfo?
val composite: Boolean?
/**
* Web UI URL for user, especially useful for error and log messages
*/
fun getHomeUrl(): String
val statusText: String?
val queuedDateTime: ZonedDateTime
val startDateTime: ZonedDateTime?
val finishDateTime: ZonedDateTime?
val runningInfo: BuildRunningInfo?
val parameters: List<Parameter>
val tags: List<String>
/**
* The same as revisions table on the build's Changes tab in TeamCity UI:
* it lists the revisions of all of the VCS repositories associated with this build
* that will be checked out by the build on the agent.
*/
val revisions: List<Revision>
/**
* Changes is meant to represent changes the same way as displayed in the build's Changes in TeamCity UI.
* In the most cases these are the commits between the current and previous build.
*/
val changes: List<Change>
/**
* All snapshot-dependency-linked builds this build depends on
*/
val snapshotDependencies: List<Build>
val pinInfo: PinInfo?
val triggeredInfo: TriggeredInfo?
val agent: BuildAgent?
@Suppress("DEPRECATION")
@Deprecated(message = "Deprecated due to unclear naming. use testRuns()", replaceWith = ReplaceWith("testRuns()"))
fun tests(status: TestStatus? = null) : Sequence<TestOccurrence>
fun testRuns(status: TestStatus? = null) : Sequence<TestRun>
val buildProblems: Sequence<BuildProblemOccurrence>
fun addTag(tag: String)
fun replaceTags(tags: List<String>)
fun pin(comment: String = "pinned via REST API")
fun unpin(comment: String = "unpinned via REST API")
fun getArtifacts(parentPath: String = "", recursive: Boolean = false, hidden: Boolean = false): List<BuildArtifact>
fun findArtifact(pattern: String, parentPath: String = ""): BuildArtifact
fun findArtifact(pattern: String, parentPath: String = "", recursive: Boolean = false): BuildArtifact
fun downloadArtifacts(pattern: String, outputDir: File)
fun downloadArtifact(artifactPath: String, output: OutputStream)
fun downloadArtifact(artifactPath: String, output: File)
fun downloadBuildLog(output: File)
fun cancel(comment: String = "", reAddIntoQueue: Boolean = false)
fun getResultingParameters(): List<Parameter>
@Deprecated(message = "use getHomeUrl()", replaceWith = ReplaceWith("getHomeUrl()"))
fun getWebUrl(): String
@Deprecated(message = "use statusText", replaceWith = ReplaceWith("statusText"))
fun fetchStatusText(): String?
@Deprecated(message = "use queuedDateTime", replaceWith = ReplaceWith("Date.from(queuedDateTime.toInstant())"))
fun fetchQueuedDate(): Date
@Deprecated(message = "use startDateTime", replaceWith = ReplaceWith("startDateTime?.toInstant()?.let { Date.from(it) }"))
fun fetchStartDate(): Date?
@Deprecated(message = "use finishDateTime", replaceWith = ReplaceWith("finishDateTime?.toInstant()?.let { Date.from(it) }"))
fun fetchFinishDate(): Date?
@Deprecated(message = "use parameters", replaceWith = ReplaceWith("parameters"))
fun fetchParameters(): List<Parameter>
@Deprecated(message = "use revisions", replaceWith = ReplaceWith("revisions"))
fun fetchRevisions(): List<Revision>
@Deprecated(message = "use changes", replaceWith = ReplaceWith("changes"))
fun fetchChanges(): List<Change>
@Deprecated(message = "use pinInfo", replaceWith = ReplaceWith("pinInfo"))
fun fetchPinInfo(): PinInfo?
@Deprecated(message = "use triggeredInfo", replaceWith = ReplaceWith("triggeredInfo"))
fun fetchTriggeredInfo(): TriggeredInfo?
@Deprecated(message = "use buildConfigurationId", replaceWith = ReplaceWith("buildConfigurationId"))
val buildTypeId: BuildConfigurationId
@Deprecated(message = "use queuedDateTime", replaceWith = ReplaceWith("Date.from(queuedDateTime.toInstant())"))
val queuedDate: Date
@Deprecated(message = "use startDateTime", replaceWith = ReplaceWith("startDateTime?.toInstant()?.let { Date.from(it) }"))
val startDate: Date?
@Deprecated(message = "use finishDateTime", replaceWith = ReplaceWith("finishDateTime?.toInstant()?.let { Date.from(it) }"))
val finishDate: Date?
}
interface Investigation {
val id: InvestigationId
val state: InvestigationState
val assignee: User
val reporter: User?
val comment: String
val resolveMethod: InvestigationResolveMethod
val targetType: InvestigationTargetType
val testIds: List<TestId>?
val problemIds: List<BuildProblemId>?
val scope: InvestigationScope
}
interface BuildRunningInfo {
val percentageComplete: Int
val elapsedSeconds: Long
val estimatedTotalSeconds: Long
val outdated: Boolean
val probablyHanging: Boolean
}
interface Change {
val id: ChangeId
val version: String
val username: String
val user: User?
val dateTime: ZonedDateTime
val comment: String
/**
* Web UI URL for user, especially useful for error and log messages
*/
fun getHomeUrl(specificBuildConfigurationId: BuildConfigurationId? = null, includePersonalBuilds: Boolean? = null): String
/**
* Returns an uncertain amount of builds which contain the revision. The builds are not necessarily from the same
* configuration as the revision. The feature is experimental, see https://youtrack.jetbrains.com/issue/TW-24633
*/
fun firstBuilds(): List<Build>
@Deprecated(message = "use getHomeUrl()",
replaceWith = ReplaceWith("getHomeUrl(specificBuildConfigurationId, includePersonalBuilds)"))
fun getWebUrl(specificBuildConfigurationId: BuildConfigurationId? = null, includePersonalBuilds: Boolean? = null): String
@Deprecated(message = "use datetime",
replaceWith = ReplaceWith("Date.from(datetime.toInstant())"))
val date: Date
}
data class UserId(val stringId: String) {
override fun toString(): String = stringId
}
interface User {
val id: UserId
val username: String
val name: String?
val email: String?
/**
* Web UI URL for user, especially useful for error and log messages
*/
fun getHomeUrl(): String
}
interface BuildArtifact {
/** Artifact name without path. e.g. my.jar */
val name: String
/** Artifact name with path. e.g. directory/my.jar */
val fullName: String
val size: Long?
val modificationDateTime: ZonedDateTime
val build: Build
fun download(output: File)
@Deprecated(message = "use modificationDateTime",
replaceWith = ReplaceWith("Date.from(modificationDateTime.toInstant())"))
val modificationTime: Date
}
interface VcsRoot {
val id: VcsRootId
val name: String
val url: String?
val defaultBranch: String?
}
interface BuildAgent {
val id: BuildAgentId
val name: String
val pool: BuildAgentPool
val connected: Boolean
val enabled: Boolean
val authorized: Boolean
val outdated: Boolean
val ipAddress: String
val parameters: List<Parameter>
val enabledInfo: BuildAgentEnabledInfo?
val authorizedInfo: BuildAgentAuthorizedInfo?
val currentBuild: Build?
fun getHomeUrl(): String
}
interface BuildAgentPool {
val id: BuildAgentPoolId
val name: String
val projects: List<Project>
val agents: List<BuildAgent>
}
interface VcsRootInstance {
val vcsRootId: VcsRootId
val name: String
}
enum class BuildStatus {
SUCCESS,
FAILURE,
ERROR,
UNKNOWN,
}
enum class BuildState {
QUEUED,
RUNNING,
FINISHED,
DELETED,
UNKNOWN,
}
enum class InvestigationState {
TAKEN,
FIXED,
GIVEN_UP
}
enum class InvestigationResolveMethod {
MANUALLY,
WHEN_FIXED;
}
enum class InvestigationTargetType(val value: String) {
TEST("test"),
BUILD_PROBLEM("problem"),
BUILD_CONFIGURATION("anyProblem")
}
interface PinInfo {
val user: User
val dateTime: ZonedDateTime
@Deprecated(message = "use dateTime",
replaceWith = ReplaceWith("Date.from(dateTime.toInstant())"))
val time: Date
}
interface Revision {
val version: String
val vcsBranchName: String
val vcsRootInstance: VcsRootInstance
}
enum class TestStatus {
SUCCESSFUL,
IGNORED,
FAILED,
UNKNOWN
}
@Deprecated(message = "Deprecated due to unclear naming. use TestRun class", replaceWith = ReplaceWith("TestRun"))
interface TestOccurrence {
val name : String
val status: TestStatus
/**
* Test run duration. It may be ZERO if a test finished too fast (<1ms)
*/
val duration: Duration
val details : String
val ignored: Boolean
/**
* Current 'muted' status of this test on TeamCity
*/
val currentlyMuted: Boolean
/**
* Muted at the moment of running tests
*/
val muted: Boolean
/**
* Newly failed test or not
*/
val newFailure: Boolean
val buildId: BuildId
val testId: TestId
}
@Suppress("DEPRECATION")
interface TestRun : TestOccurrence
interface TriggeredInfo {
val user: User?
val build: Build?
}
interface FinishBuildTrigger {
val initiatedBuildConfiguration: BuildConfigurationId
val afterSuccessfulBuildOnly: Boolean
val includedBranchPatterns: Set<String>
val excludedBranchPatterns: Set<String>
}
interface ArtifactDependency {
val dependsOnBuildConfiguration: BuildConfiguration
val branch: String?
val artifactRules: List<ArtifactRule>
val cleanDestinationDirectory: Boolean
}
interface ArtifactRule {
val include: Boolean
/**
* Specific file, directory, or wildcards to match multiple files can be used. Ant-like wildcards are supported.
*/
val sourcePath: String
/**
* Follows general rules for sourcePath: ant-like wildcards are allowed.
*/
val archivePath: String?
/**
* Destination directory where files are to be placed.
*/
val destinationPath: String?
}
open class TeamCityRestException(message: String?, cause: Throwable?) : RuntimeException(message, cause)
open class TeamCityQueryException(message: String?, cause: Throwable? = null) : TeamCityRestException(message, cause)
open class TeamCityConversationException(message: String?, cause: Throwable? = null) : TeamCityRestException(message, cause)
interface BuildQueue {
fun removeBuild(id: BuildId, comment: String = "", reAddIntoQueue: Boolean = false)
fun queuedBuilds(projectId: ProjectId? = null): Sequence<Build>
}
sealed class InvestigationScope {
class InProject(val project: Project): InvestigationScope()
class InBuildConfiguration(val configuration: BuildConfiguration): InvestigationScope()
}
|
apache-2.0
|
b0129765c4fbfd1049c9b087dd16d475
| 31.205333 | 158 | 0.704645 | 4.636084 | false | true | false | false |
codeka/wwmmo
|
client/src/main/kotlin/au/com/codeka/warworlds/client/game/solarsystem/StoreView.kt
|
1
|
4323
|
package au.com.codeka.warworlds.client.game.solarsystem
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import au.com.codeka.warworlds.client.R
import au.com.codeka.warworlds.client.game.world.EmpireManager
import au.com.codeka.warworlds.client.util.NumberFormatter
import au.com.codeka.warworlds.common.Log
import au.com.codeka.warworlds.common.proto.EmpireStorage
import au.com.codeka.warworlds.common.proto.Star
import au.com.codeka.warworlds.common.sim.StarHelper
import com.google.common.base.Preconditions
import com.squareup.wire.get
import java.util.*
import kotlin.math.roundToInt
/**
* [StoreView] displays the current contents of your store.
*/
class StoreView(context: Context?, attributeSet: AttributeSet?)
: RelativeLayout(context, attributeSet) {
private val storedGoods: TextView
private val totalGoods: TextView
private val deltaGoods: TextView
private val storedMinerals: TextView
private val totalMinerals: TextView
private val deltaMinerals: TextView
private val storedEnergy: TextView
private val totalEnergy: TextView
private val deltaEnergy: TextView
fun setStar(star: Star) {
val myEmpire = Preconditions.checkNotNull(EmpireManager.getMyEmpire())
var storage: EmpireStorage? = null
for (s in star.empire_stores) {
if (s.empire_id == myEmpire.id) {
storage = s
break
}
}
if (storage == null) {
log.debug("storage is null")
visibility = View.GONE
} else {
log.debug("storage is not null")
visibility = View.VISIBLE
storedGoods.text = NumberFormatter.format((storage.total_goods).roundToInt())
totalGoods.text = String.format(Locale.ENGLISH, "/ %s",
NumberFormatter.format((storage.max_goods).roundToInt()))
storedMinerals.text = NumberFormatter.format((storage.total_minerals).roundToInt())
totalMinerals.text = String.format(Locale.ENGLISH, "/ %s",
NumberFormatter.format((storage.max_minerals).roundToInt()))
storedEnergy.text = NumberFormatter.format((storage.total_energy).roundToInt())
totalEnergy.text = String.format(Locale.ENGLISH, "/ %s",
NumberFormatter.format((storage.max_energy).roundToInt()))
if (get(storage.goods_delta_per_hour, 0.0f) >= 0) {
deltaGoods.setTextColor(Color.GREEN)
deltaGoods.text = String.format(Locale.ENGLISH, "+%d/hr",
get(storage.goods_delta_per_hour, 0.0f).roundToInt())
} else {
deltaGoods.setTextColor(Color.RED)
deltaGoods.text = String.format(Locale.ENGLISH, "%d/hr",
get(storage.goods_delta_per_hour, 0.0f).roundToInt())
}
if (get(storage.minerals_delta_per_hour, 0.0f) >= 0) {
deltaMinerals.setTextColor(Color.GREEN)
deltaMinerals.text = String.format(Locale.ENGLISH, "+%d/hr",
StarHelper.getDeltaMineralsPerHour(
star, myEmpire.id, System.currentTimeMillis()).roundToInt()
)
} else {
deltaMinerals.setTextColor(Color.RED)
deltaMinerals.text = String.format(Locale.ENGLISH, "%d/hr",
get(storage.minerals_delta_per_hour, 0.0f).roundToInt())
}
if (get(storage.energy_delta_per_hour, 0.0f) >= 0) {
deltaEnergy.setTextColor(Color.GREEN)
deltaEnergy.text = String.format(Locale.ENGLISH, "+%d/hr",
get(storage.energy_delta_per_hour, 0.0f).roundToInt())
} else {
deltaEnergy.setTextColor(Color.RED)
deltaEnergy.text = String.format(Locale.ENGLISH, "%d/hr",
get(storage.energy_delta_per_hour, 0.0f).roundToInt())
}
}
}
companion object {
private val log = Log("StoreView")
}
init {
View.inflate(context, R.layout.solarsystem_store, this)
storedGoods = findViewById(R.id.stored_goods)
totalGoods = findViewById(R.id.total_goods)
deltaGoods = findViewById(R.id.delta_goods)
storedMinerals = findViewById(R.id.stored_minerals)
totalMinerals = findViewById(R.id.total_minerals)
deltaMinerals = findViewById(R.id.delta_minerals)
storedEnergy = findViewById(R.id.stored_energy)
totalEnergy = findViewById(R.id.total_energy)
deltaEnergy = findViewById(R.id.delta_energy)
}
}
|
mit
|
f4ae3168775ca402de4fbb7f1569ad7e
| 39.411215 | 89 | 0.701596 | 3.805458 | false | false | false | false |
HabitRPG/habitrpg-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/helpers/HealthFormatter.kt
|
1
|
1042
|
package com.habitrpg.android.habitica.helpers
import android.os.Build
import java.text.NumberFormat
import java.util.Locale
import kotlin.math.ceil
import kotlin.math.floor
object HealthFormatter {
fun format(input: Int) = format(input.toDouble())
@JvmStatic
fun format(input: Double) =
if (input < 1 && input > 0) {
ceil(input * 10) / 10
} else {
floor(input)
}
fun formatToString(input: Int, locale: Locale = getDefaultLocale()) = formatToString(input.toDouble(), locale)
@JvmStatic
@JvmOverloads
fun formatToString(input: Double, locale: Locale = getDefaultLocale()): String {
val doubleValue = format(input)
val numberFormat = NumberFormat.getInstance(locale).apply { maximumFractionDigits = 1 }
return numberFormat.format(doubleValue)
}
private fun getDefaultLocale() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Locale.getDefault(Locale.Category.FORMAT)
} else {
Locale.getDefault()
}
}
|
gpl-3.0
|
fe6477e184b6914b0586b35b509bcc51
| 28.771429 | 114 | 0.666027 | 4.235772 | false | false | false | false |
djkovrik/YapTalker
|
app/src/main/java/com/sedsoftware/yaptalker/presentation/mapper/util/DateTransformer.kt
|
1
|
3799
|
package com.sedsoftware.yaptalker.presentation.mapper.util
import android.content.Context
import com.sedsoftware.yaptalker.R
import com.sedsoftware.yaptalker.presentation.extensions.quantityString
import com.sedsoftware.yaptalker.presentation.extensions.string
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import javax.inject.Inject
class DateTransformer @Inject constructor(private val context: Context) {
companion object {
private const val MILLISECONDS_PER_SECOND = 1000
private const val SECONDS_PER_MINUTE = 60
private const val MINUTES_PER_HOUR = 60
private const val HOURS_PER_DAY = 24
private const val DAYS_PER_MONTH = 30
private const val MONTH_PER_YEAR = 12
}
fun transformDateToShortView(date: String): String {
val diff = getDifference(date)
val calcTime = getCalculatedTime(diff)
return buildString(calcTime)
}
fun transformLongToDateString(value: Long): String {
val date = Date(value)
val sdf = SimpleDateFormat("dd.MM.yyyy - HH:mm", Locale.getDefault())
return when {
value != 0L -> sdf.format(date)
else -> ""
}
}
private fun getDifference(source: String): Int {
val format = SimpleDateFormat("dd.MM.yyyy - HH:mm", Locale.getDefault())
val topicDate = format.parse(source)
val currentDate = Calendar.getInstance().time
return ((currentDate.time - topicDate.time) / MILLISECONDS_PER_SECOND).toInt()
}
private fun getCalculatedTime(diff: Int): CalculatedTime {
var diffInSeconds = diff
// Skip seconds
diffInSeconds /= MINUTES_PER_HOUR
val min = if (diffInSeconds >= SECONDS_PER_MINUTE) (diffInSeconds % SECONDS_PER_MINUTE) else diffInSeconds
diffInSeconds /= SECONDS_PER_MINUTE
val hrs = if (diffInSeconds >= HOURS_PER_DAY) (diffInSeconds % HOURS_PER_DAY) else diffInSeconds
diffInSeconds /= HOURS_PER_DAY
val days = if (diffInSeconds >= DAYS_PER_MONTH) (diffInSeconds % DAYS_PER_MONTH) else diffInSeconds
diffInSeconds /= DAYS_PER_MONTH
val months = if (diffInSeconds >= MONTH_PER_YEAR) (diffInSeconds % MONTH_PER_YEAR) else diffInSeconds
diffInSeconds /= MONTH_PER_YEAR
val years = diffInSeconds
return CalculatedTime(min, hrs, days, months, years)
}
private fun buildString(time: CalculatedTime): String =
when {
time.years > 0 -> {
val template = context.quantityString(R.plurals.short_date_years, time.years)
String.format(Locale.getDefault(), template, time.years)
}
time.months > 0 -> {
val template = context.string(R.string.short_date_month)
String.format(Locale.getDefault(), template, time.months)
}
time.days > 0 -> {
val template = context.quantityString(R.plurals.short_date_days, time.days)
String.format(Locale.getDefault(), template, time.days)
}
time.hours > 0 -> {
val template = context.quantityString(R.plurals.short_date_hours, time.hours)
String.format(Locale.getDefault(), template, time.hours)
}
time.minutes > 0 -> {
val template = context.string(R.string.short_date_minutes)
String.format(Locale.getDefault(), template, time.minutes)
}
else -> context.string(R.string.short_date_seconds_now)
}
private inner class CalculatedTime(
val minutes: Int,
val hours: Int,
val days: Int,
val months: Int,
val years: Int
)
}
|
apache-2.0
|
f95090e124688e1752263bb6ff1036c2
| 37.373737 | 114 | 0.635167 | 4.356651 | false | false | false | false |
androidx/androidx
|
health/connect/connect-client/src/test/java/androidx/health/connect/client/impl/HealthConnectClientImplTest.kt
|
3
|
32775
|
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.connect.client.impl
import android.app.Application
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.os.Looper
import androidx.health.connect.client.changes.DeletionChange
import androidx.health.connect.client.changes.UpsertionChange
import androidx.health.connect.client.impl.converters.datatype.toDataType
import androidx.health.connect.client.permission.HealthPermission.Companion.createReadPermission
import androidx.health.connect.client.records.ActiveCaloriesBurnedRecord
import androidx.health.connect.client.records.HeartRateRecord
import androidx.health.connect.client.records.NutritionRecord
import androidx.health.connect.client.records.StepsRecord
import androidx.health.connect.client.records.StepsRecord.Companion.COUNT_TOTAL
import androidx.health.connect.client.records.WeightRecord
import androidx.health.connect.client.records.metadata.DataOrigin
import androidx.health.connect.client.records.metadata.Device
import androidx.health.connect.client.records.metadata.Metadata
import androidx.health.connect.client.request.AggregateGroupByDurationRequest
import androidx.health.connect.client.request.AggregateGroupByPeriodRequest
import androidx.health.connect.client.request.AggregateRequest
import androidx.health.connect.client.request.ChangesTokenRequest
import androidx.health.connect.client.request.ReadRecordsRequest
import androidx.health.connect.client.time.TimeRangeFilter
import androidx.health.connect.client.units.grams
import androidx.health.connect.client.units.kilograms
import androidx.health.platform.client.impl.ServiceBackedHealthDataClient
import androidx.health.platform.client.impl.error.errorCodeExceptionMap
import androidx.health.platform.client.impl.ipc.ClientConfiguration
import androidx.health.platform.client.impl.ipc.internal.ConnectionManager
import androidx.health.platform.client.impl.testing.FakeHealthDataService
import androidx.health.platform.client.proto.ChangeProto
import androidx.health.platform.client.proto.DataProto
import androidx.health.platform.client.proto.PermissionProto
import androidx.health.platform.client.proto.RequestProto
import androidx.health.platform.client.proto.ResponseProto
import androidx.health.platform.client.proto.TimeProto
import androidx.health.platform.client.response.AggregateDataResponse
import androidx.health.platform.client.response.GetChangesResponse
import androidx.health.platform.client.response.GetChangesTokenResponse
import androidx.health.platform.client.response.InsertDataResponse
import androidx.health.platform.client.response.ReadDataRangeResponse
import androidx.health.platform.client.response.ReadDataResponse
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.intent.Intents
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import java.time.Duration
import java.time.Instant
import java.time.LocalDateTime
import java.time.Period
import java.time.ZoneOffset
import kotlin.test.assertFailsWith
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Shadows
private const val PROVIDER_PACKAGE_NAME = "com.google.fake.provider"
private val API_METHOD_LIST =
listOf<suspend HealthConnectClientImpl.() -> Unit>(
{ getGrantedPermissions(setOf()) },
{ revokeAllPermissions() },
{ insertRecords(listOf()) },
{ updateRecords(listOf()) },
{ deleteRecords(ActiveCaloriesBurnedRecord::class, listOf(), listOf()) },
{ deleteRecords(ActiveCaloriesBurnedRecord::class, TimeRangeFilter.none()) },
{ readRecord(StepsRecord::class, "uid") },
{
readRecords(
ReadRecordsRequest(
StepsRecord::class,
TimeRangeFilter.between(
Instant.ofEpochMilli(1234L),
Instant.ofEpochMilli(1235L)
),
)
)
},
{ aggregate(AggregateRequest(setOf(), TimeRangeFilter.none())) },
{
aggregateGroupByDuration(
AggregateGroupByDurationRequest(setOf(), TimeRangeFilter.none(), Duration.ZERO)
)
},
{
aggregateGroupByPeriod(
AggregateGroupByPeriodRequest(setOf(), TimeRangeFilter.none(), Period.ZERO)
)
},
{ getChanges("token") },
{ getChangesToken(ChangesTokenRequest(recordTypes = setOf(StepsRecord::class))) },
{
registerForDataNotifications(
notificationIntentAction = "action",
recordTypes = emptyList(),
)
},
{ unregisterFromDataNotifications(notificationIntentAction = "action") }
)
@Suppress("GoodTime") // Safe to use in test setup
@RunWith(AndroidJUnit4::class)
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class HealthConnectClientImplTest {
private lateinit var healthConnectClient: HealthConnectClientImpl
private lateinit var fakeAhpServiceStub: FakeHealthDataService
@Before
fun setup() {
val clientConfig =
ClientConfiguration("FakeAHPProvider", PROVIDER_PACKAGE_NAME, "FakeProvider")
healthConnectClient =
HealthConnectClientImpl(
PROVIDER_PACKAGE_NAME,
ServiceBackedHealthDataClient(
ApplicationProvider.getApplicationContext(),
clientConfig,
ConnectionManager(
ApplicationProvider.getApplicationContext(),
Looper.getMainLooper()
)
)
)
fakeAhpServiceStub = FakeHealthDataService()
Shadows.shadowOf(ApplicationProvider.getApplicationContext<Context>() as Application)
.setComponentNameAndServiceForBindServiceForIntent(
Intent()
.setPackage(clientConfig.servicePackageName)
.setAction(clientConfig.bindAction),
ComponentName(clientConfig.servicePackageName, clientConfig.bindAction),
fakeAhpServiceStub
)
installPackage(ApplicationProvider.getApplicationContext(), PROVIDER_PACKAGE_NAME, true)
Intents.init()
}
@After
fun teardown() {
Intents.release()
}
@Test
fun apiMethods_hasError_throwsException() = runTest {
for (error in errorCodeExceptionMap) {
fakeAhpServiceStub.errorCode = error.key
val responseList = mutableListOf<Deferred<Any>>()
for (method in API_METHOD_LIST) {
responseList.add(
async { assertFailsWith(error.value) { healthConnectClient.method() } }
)
}
advanceUntilIdle()
waitForMainLooperIdle()
for (response in responseList) {
response.await()
}
}
}
@Test
fun getGrantedPermissions_none() = runTest {
val response = testBlocking {
healthConnectClient.getGrantedPermissions(
setOf(createReadPermission(StepsRecord::class))
)
}
assertThat(response).isEmpty()
}
@Test
fun getGrantedPermissions_steps() = runTest {
fakeAhpServiceStub.addGrantedPermission(
androidx.health.platform.client.permission.Permission(
PermissionProto.Permission.newBuilder()
.setDataType(DataProto.DataType.newBuilder().setName("Steps"))
.setAccessType(PermissionProto.AccessType.ACCESS_TYPE_READ)
.build()
)
)
val response = testBlocking {
healthConnectClient.getGrantedPermissions(
setOf(createReadPermission(StepsRecord::class))
)
}
assertThat(response).containsExactly(createReadPermission(StepsRecord::class))
}
@Test
fun insertRecords_steps() = runTest {
fakeAhpServiceStub.insertDataResponse = InsertDataResponse(listOf("0"))
val response = testBlocking {
healthConnectClient.insertRecords(
listOf(
StepsRecord(
count = 100,
startTime = Instant.ofEpochMilli(1234L),
startZoneOffset = null,
endTime = Instant.ofEpochMilli(5678L),
endZoneOffset = null
)
)
)
}
assertThat(response.recordIdsList).containsExactly("0")
assertThat(fakeAhpServiceStub.lastUpsertDataRequest?.dataPoints)
.containsExactly(
DataProto.DataPoint.newBuilder()
.setStartTimeMillis(1234L)
.setEndTimeMillis(5678L)
.putValues("count", DataProto.Value.newBuilder().setLongVal(100).build())
.setDataType(DataProto.DataType.newBuilder().setName("Steps"))
.build()
)
}
@Test
fun insertRecords_weight() = runTest {
fakeAhpServiceStub.insertDataResponse = InsertDataResponse(listOf("0"))
val response = testBlocking {
healthConnectClient.insertRecords(
listOf(
WeightRecord(
weight = 45.8.kilograms,
time = Instant.ofEpochMilli(1234L),
zoneOffset = null,
)
)
)
}
assertThat(response.recordIdsList).containsExactly("0")
assertThat(fakeAhpServiceStub.lastUpsertDataRequest?.dataPoints)
.containsExactly(
DataProto.DataPoint.newBuilder()
.setInstantTimeMillis(1234L)
.putValues("weight", DataProto.Value.newBuilder().setDoubleVal(45.8).build())
.setDataType(DataProto.DataType.newBuilder().setName("Weight"))
.build()
)
}
@Test
fun insertRecords_nutrition() = runTest {
fakeAhpServiceStub.insertDataResponse = InsertDataResponse(listOf("0"))
val response = testBlocking {
healthConnectClient.insertRecords(
listOf(
NutritionRecord(
vitaminE = 10.grams,
vitaminC = 20.grams,
startTime = Instant.ofEpochMilli(1234L),
startZoneOffset = null,
endTime = Instant.ofEpochMilli(5678L),
endZoneOffset = null
)
)
)
}
assertThat(response.recordIdsList).containsExactly("0")
assertThat(fakeAhpServiceStub.lastUpsertDataRequest?.dataPoints)
.containsExactly(
DataProto.DataPoint.newBuilder()
.setStartTimeMillis(1234L)
.setEndTimeMillis(5678L)
.putValues("vitaminC", DataProto.Value.newBuilder().setDoubleVal(20.0).build())
.putValues("vitaminE", DataProto.Value.newBuilder().setDoubleVal(10.0).build())
.setDataType(DataProto.DataType.newBuilder().setName("Nutrition"))
.build()
)
}
@Test
fun readRecordById_steps() = runTest {
fakeAhpServiceStub.readDataResponse =
ReadDataResponse(
ResponseProto.ReadDataResponse.newBuilder()
.setDataPoint(
DataProto.DataPoint.newBuilder()
.setUid("testUid")
.setStartTimeMillis(1234L)
.setEndTimeMillis(5678L)
.putValues(
"count",
DataProto.Value.newBuilder().setLongVal(100).build()
)
.setDataType(DataProto.DataType.newBuilder().setName("Steps"))
)
.build()
)
val response = testBlocking {
healthConnectClient.readRecord(
StepsRecord::class,
recordId = "testUid",
)
}
assertThat(fakeAhpServiceStub.lastReadDataRequest?.proto)
.isEqualTo(
RequestProto.ReadDataRequest.newBuilder()
.setDataTypeIdPair(
RequestProto.DataTypeIdPair.newBuilder()
.setDataType(DataProto.DataType.newBuilder().setName("Steps"))
.setId("testUid")
)
.build()
)
assertThat(response.record)
.isEqualTo(
StepsRecord(
count = 100,
startTime = Instant.ofEpochMilli(1234L),
startZoneOffset = null,
endTime = Instant.ofEpochMilli(5678L),
endZoneOffset = null,
metadata =
Metadata(
id = "testUid",
device = Device(),
)
)
)
}
@Test
fun readRecords_steps() = runTest {
fakeAhpServiceStub.readDataRangeResponse =
ReadDataRangeResponse(
ResponseProto.ReadDataRangeResponse.newBuilder()
.addDataPoint(
DataProto.DataPoint.newBuilder()
.setUid("testUid")
.setStartTimeMillis(1234L)
.setEndTimeMillis(5678L)
.putValues(
"count",
DataProto.Value.newBuilder().setLongVal(100).build()
)
.setDataType(DataProto.DataType.newBuilder().setName("Steps"))
)
.setPageToken("nextPageToken")
.build()
)
val response = testBlocking {
healthConnectClient.readRecords(
ReadRecordsRequest(
StepsRecord::class,
timeRangeFilter = TimeRangeFilter.before(endTime = Instant.ofEpochMilli(7890L)),
pageSize = 10
)
)
}
assertThat(fakeAhpServiceStub.lastReadDataRangeRequest?.proto)
.isEqualTo(
RequestProto.ReadDataRangeRequest.newBuilder()
.setTimeSpec(TimeProto.TimeSpec.newBuilder().setEndTimeEpochMs(7890L))
.setDataType(DataProto.DataType.newBuilder().setName("Steps"))
.setAscOrdering(true)
.setPageSize(10)
.build()
)
assertThat(response.pageToken).isEqualTo("nextPageToken")
assertThat(response.records)
.containsExactly(
StepsRecord(
count = 100,
startTime = Instant.ofEpochMilli(1234L),
startZoneOffset = null,
endTime = Instant.ofEpochMilli(5678L),
endZoneOffset = null,
metadata =
Metadata(
id = "testUid",
device = Device(),
)
)
)
}
@Test
fun deleteRecordsById_steps() = runTest {
testBlocking {
healthConnectClient.deleteRecords(
StepsRecord::class,
listOf("myUid"),
listOf("myClientId")
)
}
val stepsTypeProto = DataProto.DataType.newBuilder().setName("Steps")
assertThat(fakeAhpServiceStub.lastDeleteDataRequest?.clientIds)
.containsExactly(
RequestProto.DataTypeIdPair.newBuilder()
.setDataType(stepsTypeProto)
.setId("myClientId")
.build()
)
assertThat(fakeAhpServiceStub.lastDeleteDataRequest?.uids)
.containsExactly(
RequestProto.DataTypeIdPair.newBuilder()
.setDataType(stepsTypeProto)
.setId("myUid")
.build()
)
}
@Test
fun deleteRecordsByRange_steps() = runTest {
testBlocking {
healthConnectClient.deleteRecords(
StepsRecord::class,
timeRangeFilter = TimeRangeFilter.before(endTime = Instant.ofEpochMilli(7890L)),
)
}
assertThat(fakeAhpServiceStub.lastDeleteDataRangeRequest?.proto)
.isEqualTo(
RequestProto.DeleteDataRangeRequest.newBuilder()
.setTimeSpec(TimeProto.TimeSpec.newBuilder().setEndTimeEpochMs(7890L))
.addDataType(DataProto.DataType.newBuilder().setName("Steps"))
.build()
)
}
@Test
fun updateRecords_steps() = runTest {
testBlocking {
healthConnectClient.updateRecords(
listOf(
StepsRecord(
count = 100,
startTime = Instant.ofEpochMilli(1234L),
startZoneOffset = null,
endTime = Instant.ofEpochMilli(5678L),
endZoneOffset = null,
metadata = Metadata(id = "testUid")
)
)
)
}
assertThat(fakeAhpServiceStub.lastUpsertDataRequest?.dataPoints)
.containsExactly(
DataProto.DataPoint.newBuilder()
.setUid("testUid")
.setStartTimeMillis(1234L)
.setEndTimeMillis(5678L)
.putValues("count", DataProto.Value.newBuilder().setLongVal(100).build())
.setDataType(DataProto.DataType.newBuilder().setName("Steps"))
.build()
)
}
@Test
fun aggregate_totalSteps(): Unit = runTest {
val dataOrigin = DataProto.DataOrigin.newBuilder().setApplicationId("id").build()
val aggregateDataRow =
DataProto.AggregateDataRow.newBuilder()
.setStartTimeEpochMs(1234)
.setEndTimeEpochMs(4567)
.setZoneOffsetSeconds(999)
.addDataOrigins(dataOrigin)
.build()
fakeAhpServiceStub.aggregateDataResponse =
AggregateDataResponse(
ResponseProto.AggregateDataResponse.newBuilder().addRows(aggregateDataRow).build()
)
val response = testBlocking {
val startTime = Instant.ofEpochMilli(1234)
val endTime = Instant.ofEpochMilli(4567)
healthConnectClient.aggregate(
AggregateRequest(
setOf(StepsRecord.COUNT_TOTAL),
TimeRangeFilter.between(startTime, endTime)
)
)
}
// This is currently impossible to test for 3p devs, we'll need to override equals()
assertThat(response.longValues).isEmpty()
assertThat(response.doubleValues).isEmpty()
assertThat(response.dataOrigins).contains(DataOrigin("id"))
assertThat(fakeAhpServiceStub.lastAggregateRequest?.proto)
.isEqualTo(
RequestProto.AggregateDataRequest.newBuilder()
.setTimeSpec(
TimeProto.TimeSpec.newBuilder()
.setStartTimeEpochMs(1234)
.setEndTimeEpochMs(4567)
.build()
)
.addMetricSpec(
RequestProto.AggregateMetricSpec.newBuilder()
.setDataTypeName("Steps")
.setAggregationType("total")
.setFieldName("count")
.build()
)
.build()
)
}
@Test
fun aggregateGroupByDuration_totalSteps() = runTest {
val bucket1 =
DataProto.AggregateDataRow.newBuilder()
.setStartTimeEpochMs(1234)
.setEndTimeEpochMs(2234)
.setZoneOffsetSeconds(999)
.addDataOrigins(DataProto.DataOrigin.newBuilder().setApplicationId("id"))
.putLongValues("Steps_count_total", 1000)
.build()
val bucket2 =
DataProto.AggregateDataRow.newBuilder()
.setStartTimeEpochMs(2234)
.setEndTimeEpochMs(3234)
.setZoneOffsetSeconds(999)
.addDataOrigins(DataProto.DataOrigin.newBuilder().setApplicationId("id2"))
.putLongValues("Steps_count_total", 1500)
.build()
fakeAhpServiceStub.aggregateDataResponse =
AggregateDataResponse(
ResponseProto.AggregateDataResponse.newBuilder()
.addRows(bucket1)
.addRows(bucket2)
.build()
)
val response = testBlocking {
val startTime = Instant.ofEpochMilli(1234)
val endTime = Instant.ofEpochMilli(4567)
healthConnectClient.aggregateGroupByDuration(
AggregateGroupByDurationRequest(
setOf(COUNT_TOTAL),
TimeRangeFilter.between(startTime, endTime),
Duration.ofMillis(1000)
)
)
}
assertThat(response[0].result.contains(COUNT_TOTAL)).isTrue()
assertThat(response[0].result[COUNT_TOTAL]).isEqualTo(1000)
assertThat(response[0].result.dataOrigins).contains(DataOrigin("id"))
assertThat(response[0].startTime).isEqualTo(Instant.ofEpochMilli(1234))
assertThat(response[0].endTime).isEqualTo(Instant.ofEpochMilli(2234))
assertThat(response[0].zoneOffset).isEqualTo(ZoneOffset.ofTotalSeconds(999))
assertThat(response[1].result.contains(COUNT_TOTAL)).isTrue()
assertThat(response[1].result[COUNT_TOTAL]).isEqualTo(1500)
assertThat(response[1].result.dataOrigins).contains(DataOrigin("id2"))
assertThat(response[1].startTime).isEqualTo(Instant.ofEpochMilli(2234))
assertThat(response[1].endTime).isEqualTo(Instant.ofEpochMilli(3234))
assertThat(response[1].zoneOffset).isEqualTo(ZoneOffset.ofTotalSeconds(999))
assertThat(fakeAhpServiceStub.lastAggregateRequest?.proto)
.isEqualTo(
RequestProto.AggregateDataRequest.newBuilder()
.setTimeSpec(
TimeProto.TimeSpec.newBuilder()
.setStartTimeEpochMs(1234)
.setEndTimeEpochMs(4567)
.build()
)
.setSliceDurationMillis(1000)
.addMetricSpec(
RequestProto.AggregateMetricSpec.newBuilder()
.setDataTypeName("Steps")
.setAggregationType("total")
.setFieldName("count")
.build()
)
.build()
)
}
@Test
fun aggregateGroupByPeriod_totalSteps() = runTest {
val dataOrigin = DataProto.DataOrigin.newBuilder().setApplicationId("id").build()
val bucket1 =
DataProto.AggregateDataRow.newBuilder()
.setStartLocalDateTime("2022-02-11T20:22:02")
.setEndLocalDateTime("2022-02-12T20:22:02")
.addDataOrigins(dataOrigin)
.putLongValues("Steps_count_total", 1500)
.build()
val bucket2 =
DataProto.AggregateDataRow.newBuilder()
.setStartLocalDateTime("2022-02-12T20:22:02")
.setEndLocalDateTime("2022-02-13T20:22:02")
.addDataOrigins(dataOrigin)
.putLongValues("Steps_count_total", 2000)
.build()
fakeAhpServiceStub.aggregateDataResponse =
AggregateDataResponse(
ResponseProto.AggregateDataResponse.newBuilder()
.addRows(bucket1)
.addRows(bucket2)
.build()
)
val response = testBlocking {
val startTime = LocalDateTime.parse("2022-02-11T20:22:02")
val endTime = LocalDateTime.parse("2022-02-22T20:22:02")
healthConnectClient.aggregateGroupByPeriod(
AggregateGroupByPeriodRequest(
setOf(COUNT_TOTAL),
TimeRangeFilter.between(startTime, endTime),
Period.ofDays(1)
)
)
}
assertThat(response[0].result.contains(COUNT_TOTAL)).isTrue()
assertThat(response[0].result[COUNT_TOTAL]).isEqualTo(1500)
assertThat(response[0].result.dataOrigins).contains(DataOrigin("id"))
assertThat(response[0].startTime).isEqualTo(LocalDateTime.parse("2022-02-11T20:22:02"))
assertThat(response[0].endTime).isEqualTo(LocalDateTime.parse("2022-02-12T20:22:02"))
assertThat(response[1].result.contains(COUNT_TOTAL)).isTrue()
assertThat(response[1].result[COUNT_TOTAL]).isEqualTo(2000)
assertThat(response[1].result.dataOrigins).contains(DataOrigin("id"))
assertThat(response[1].startTime).isEqualTo(LocalDateTime.parse("2022-02-12T20:22:02"))
assertThat(response[1].endTime).isEqualTo(LocalDateTime.parse("2022-02-13T20:22:02"))
assertThat(fakeAhpServiceStub.lastAggregateRequest?.proto)
.isEqualTo(
RequestProto.AggregateDataRequest.newBuilder()
.setTimeSpec(
TimeProto.TimeSpec.newBuilder()
.setStartLocalDateTime("2022-02-11T20:22:02")
.setEndLocalDateTime("2022-02-22T20:22:02")
.build()
)
.setSlicePeriod(Period.ofDays(1).toString())
.addMetricSpec(
RequestProto.AggregateMetricSpec.newBuilder()
.setDataTypeName("Steps")
.setAggregationType("total")
.setFieldName("count")
.build()
)
.build()
)
}
@Test
fun getChangesToken() = runTest {
fakeAhpServiceStub.changesTokenResponse =
GetChangesTokenResponse(
ResponseProto.GetChangesTokenResponse.newBuilder()
.setChangesToken("changesToken")
.build()
)
val response = testBlocking {
healthConnectClient.getChangesToken(ChangesTokenRequest(setOf(StepsRecord::class)))
}
assertThat(response).isEqualTo("changesToken")
assertThat(fakeAhpServiceStub.lastGetChangesTokenRequest?.proto)
.isEqualTo(
RequestProto.GetChangesTokenRequest.newBuilder()
.addDataType(DataProto.DataType.newBuilder().setName("Steps"))
.build()
)
}
@Test
fun getChanges_steps() = runTest {
fakeAhpServiceStub.changesResponse =
GetChangesResponse(
ResponseProto.GetChangesResponse.newBuilder()
.addChanges(ChangeProto.DataChange.newBuilder().setDeleteUid("deleteUid"))
.addChanges(
ChangeProto.DataChange.newBuilder()
.setUpsertDataPoint(
DataProto.DataPoint.newBuilder()
.setUid("testUid")
.setStartTimeMillis(1234L)
.setEndTimeMillis(5678L)
.putValues(
"count",
DataProto.Value.newBuilder().setLongVal(100).build()
)
.setDataType(DataProto.DataType.newBuilder().setName("Steps"))
.build()
)
)
.setHasMore(true)
.setChangesTokenExpired(false)
.build()
)
val response = testBlocking { healthConnectClient.getChanges("steps_changes_token") }
assertThat(response.changes).hasSize(2)
assertThat(response.changes[0]).isInstanceOf(DeletionChange::class.java)
assertThat(response.changes[1]).isInstanceOf(UpsertionChange::class.java)
assertThat(response.hasMore).isTrue()
assertThat(response.changesTokenExpired).isFalse()
assertThat(fakeAhpServiceStub.lastGetChangesRequest?.proto)
.isEqualTo(
RequestProto.GetChangesRequest.newBuilder()
.setChangesToken("steps_changes_token")
.build()
)
}
@Test
fun registerForDataNotifications() = runTest {
testBlocking {
healthConnectClient.registerForDataNotifications(
notificationIntentAction = "action",
recordTypes = listOf(HeartRateRecord::class, StepsRecord::class),
)
}
assertThat(fakeAhpServiceStub.lastRegisterForDataNotificationsRequest?.proto)
.isEqualTo(
RequestProto.RegisterForDataNotificationsRequest.newBuilder()
.setNotificationIntentAction("action")
.addDataTypes(HeartRateRecord::class.toDataType())
.addDataTypes(StepsRecord::class.toDataType())
.build()
)
}
@Test
fun unregisterFromDataNotifications() = runTest {
testBlocking {
healthConnectClient.unregisterFromDataNotifications(notificationIntentAction = "action")
}
assertThat(fakeAhpServiceStub.lastUnregisterFromDataNotificationsRequest?.proto)
.isEqualTo(
RequestProto.UnregisterFromDataNotificationsRequest.newBuilder()
.setNotificationIntentAction("action")
.build()
)
}
private suspend fun <T> TestScope.testBlocking(block: suspend CoroutineScope.() -> T): T =
asyncAndWaitForIdle(block).await()
private fun <T> TestScope.asyncAndWaitForIdle(
block: suspend CoroutineScope.() -> T,
): Deferred<T> =
async(block = block).also {
advanceUntilIdle()
waitForMainLooperIdle()
}
private fun waitForMainLooperIdle() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
}
private fun installPackage(context: Context, packageName: String, enabled: Boolean) {
val packageInfo = PackageInfo()
packageInfo.packageName = packageName
packageInfo.applicationInfo = ApplicationInfo()
packageInfo.applicationInfo.enabled = enabled
val packageManager = context.packageManager
Shadows.shadowOf(packageManager).installPackage(packageInfo)
}
}
|
apache-2.0
|
9d10c3a50800f9bbface64604e6b7776
| 39.917603 | 100 | 0.576629 | 5.529779 | false | true | false | false |
kenrube/Fantlab-client
|
app/src/main/kotlin/ru/fantlab/android/data/dao/response/BookcaseEditionsResponse.kt
|
2
|
1161
|
package ru.fantlab.android.data.dao.response
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.google.gson.JsonParser
import ru.fantlab.android.data.dao.Pageable
import ru.fantlab.android.data.dao.model.BookcaseEdition
import ru.fantlab.android.provider.rest.DataManager
data class BookcaseEditionsResponse(
val editions: Pageable<BookcaseEdition>
) {
class Deserializer(private val perPage: Int) : ResponseDeserializable<BookcaseEditionsResponse> {
override fun deserialize(content: String): BookcaseEditionsResponse {
val jsonObject = JsonParser().parse(content).asJsonObject
val items: ArrayList<BookcaseEdition> = arrayListOf()
val array = jsonObject.getAsJsonArray("bookcase_items")
array.map {
items.add(DataManager.gson.fromJson(it, BookcaseEdition::class.java))
}
val totalCount = jsonObject.getAsJsonPrimitive("count").asInt
val lastPage = (totalCount - 1) / perPage + 1
val editions = Pageable(lastPage, totalCount, items)
return BookcaseEditionsResponse(editions)
}
}
}
|
gpl-3.0
|
b0170ba963998b03d28cd23abe120fb7
| 42.037037 | 101 | 0.70801 | 4.738776 | false | false | false | false |
TUWien/DocScan
|
app/src/main/java/at/ac/tuwien/caa/docscan/ui/docviewer/documents/selector/SelectDocumentAdapter.kt
|
1
|
3050
|
package at.ac.tuwien.caa.docscan.ui.docviewer.documents.selector
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import at.ac.tuwien.caa.docscan.R
import at.ac.tuwien.caa.docscan.databinding.SelectDocumentRowLayoutBinding
import at.ac.tuwien.caa.docscan.db.model.DocumentWithPages
import at.ac.tuwien.caa.docscan.db.model.isProcessing
import at.ac.tuwien.caa.docscan.logic.GlideHelper
class SelectDocumentAdapter(private val clickListener: (DocumentWithPages) -> Unit) :
ListAdapter<DocumentWithPages, SelectDocumentAdapter.ViewHolder>(DocumentWithPagesDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
SelectDocumentRowLayoutBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position))
}
inner class ViewHolder(val binding: SelectDocumentRowLayoutBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(document: DocumentWithPages) {
val isEmpty = document.pages.isEmpty()
if (!isEmpty) {
val page = document.pages[0]
GlideHelper.loadPageIntoImageView(
page,
binding.documentThumbnailImageview,
GlideHelper.GlideStyles.DOCUMENT_PREVIEW
)
binding.documentThumbnailImageview.transitionName = page.id.toString()
} else {
binding.documentThumbnailImageview.setImageResource(R.drawable.ic_do_not_disturb_black_24dp)
binding.documentThumbnailImageview.setBackgroundColor(
ContextCompat.getColor(
itemView.context,
R.color.second_light_gray
)
)
}
binding.documentTitleText.text = document.document.title
itemView.setOnClickListener { clickListener(document) }
binding.documentDescriptionTextview.text = itemView.resources.getQuantityString(R.plurals.images, document.pages.size, document.pages.size)
}
}
}
class DocumentWithPagesDiffCallback : DiffUtil.ItemCallback<DocumentWithPages>() {
override fun areItemsTheSame(
oldItem: DocumentWithPages,
newItem: DocumentWithPages
) = oldItem.document.id == newItem.document.id
override fun areContentsTheSame(
oldItem: DocumentWithPages,
newItem: DocumentWithPages
): Boolean {
return oldItem.document.title == newItem.document.title &&
oldItem.pages.size == newItem.pages.size &&
oldItem.isProcessing() == newItem.isProcessing()
}
}
|
lgpl-3.0
|
69eafe9d5c8800bd1d98d1063b80c3d5
| 38.61039 | 151 | 0.670492 | 5.195911 | false | false | false | false |
ronashco/pushe-android-studio-sample
|
app/src/main/java/co/pushe/sample/as/utils/Stuff.kt
|
2
|
4685
|
package co.pushe.sample.`as`.utils
import android.content.Context
import android.view.View
import android.widget.EditText
import android.widget.ScrollView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.util.Consumer
import co.pushe.sample.`as`.R
import java.text.DateFormat
import java.util.*
@Suppress("unused")
object Stuff {
/**
* Shows a dialog having an EditText.
* @param callback will be called when user clicked on OK. Callback contains the text that was entered in editText.
* @see Consumer which is a simple interface.
*/
fun prompt(activityContext: Context, title: String, message: String, callback: Consumer<String>) {
val editText = EditText(activityContext)
editText.setSingleLine()
editText.maxLines = 1
AlertDialog.Builder(activityContext)
.setIcon(R.drawable.ic_input_get)
.setTitle(title)
.setMessage(message)
.setView(editText)
.setPositiveButton("OK") { _, _ ->
val text = editText.text.toString()
callback.accept(text)
}
.setNegativeButton("Cancel") { _, _ ->
//
}.create().show()
}
/**
* Shows a dialog having an EditText.
* @param callback will be called when user clicked on button1(positive) or button2(negative). Callback contains the text that was entered in editText.
* @see Callback which is a simple interface.
*/
fun prompt(activityContext: Context, title: String, message: String, hint: String, button1: String, button2: String, callback: Callback<String>) {
val editText = EditText(activityContext)
editText.setSingleLine()
editText.maxLines = 1
editText.hint = hint
AlertDialog.Builder(activityContext)
.setIcon(R.drawable.ic_input_get)
.setTitle(title)
.setMessage(message)
.setView(editText)
.setPositiveButton(button1) { _, _ ->
val text = editText.text.toString()
callback.onPositiveButtonClicked(text)
}
.setNegativeButton(button2) { _, _ ->
val text = editText.text.toString()
callback.onNegativeButtonClicked(text)
}.create().show()
}
/**
* Same as the other function but can pass default text to editText.
*/
@JvmStatic
fun prompt(activityContext: Context, title: String, message: String, defaultText: String, callback: Consumer<String>) {
val editText = EditText(activityContext)
editText.setSingleLine()
editText.maxLines = 1
editText.setText(defaultText)
AlertDialog.Builder(activityContext)
.setIcon(R.drawable.ic_input_get)
.setTitle(title)
.setMessage(message)
.setView(editText)
.setPositiveButton("OK") { _, _ ->
val text = editText.text.toString()
callback.accept(text)
}
.setNegativeButton("Cancel", null).create().show()
}
/**
* Show simple information using alertDialog.
*/
@JvmStatic
fun alert(activityContext: Context, title: String, message: String) {
AlertDialog.Builder(activityContext)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(title)
.setMessage(message)
.setPositiveButton("OK", null)
.create()
.show()
}
/**
* Add text instead of replacing the text in android studio.
* Takes a textView and a text and adds the text to the textView.
*/
fun addText(textView: TextView?, text: String) {
if (textView == null) return
val currentText = textView.text as String
val currentDateTimeString = DateFormat.getDateTimeInstance().format(Date())
val newText = "$currentText\n-----\n$text\nTime: $currentDateTimeString\n"
textView.text = newText
}
/**
* Add text instead of replacing the text in android studio.
* Takes a textView and a text and adds the text to the textView.
*/
@JvmStatic
fun addText(scrollView: ScrollView, textView: TextView?, text: String) {
if (textView == null) return
val currentText = textView.text as String
val currentDateTimeString = DateFormat.getDateTimeInstance().format(Date())
val newText = "$currentText\n-----\n$text\nTime: $currentDateTimeString\n"
textView.text = newText
scrollView.fullScroll(View.FOCUS_DOWN)
}
interface Callback<T> {
fun onPositiveButtonClicked(t: T)
fun onNegativeButtonClicked(t: T)
}
}
|
apache-2.0
|
fefafa587a2c57fab73428a421fb9c66
| 35.046154 | 155 | 0.630523 | 4.588639 | false | false | false | false |
0x1bad1d3a/Kaku
|
app/src/main/java/ca/fuwafuwa/kaku/Windows/InstantKanjiWindow.kt
|
1
|
8978
|
package ca.fuwafuwa.kaku.Windows
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.View.INVISIBLE
import android.widget.LinearLayout
import ca.fuwafuwa.kaku.R
import ca.fuwafuwa.kaku.Windows.Data.DisplayDataOcr
import ca.fuwafuwa.kaku.Windows.Enums.LayoutPosition
import ca.fuwafuwa.kaku.Windows.Interfaces.ICopyText
import ca.fuwafuwa.kaku.Windows.Interfaces.IRecalculateKanjiViews
import ca.fuwafuwa.kaku.Windows.Views.KanjiGridView
import ca.fuwafuwa.kaku.dpToPx
class InstantKanjiWindow(context: Context,
windowCoordinator: WindowCoordinator) : Window(context, windowCoordinator, R.layout.window_instant_kanji), IRecalculateKanjiViews, ICopyText
{
private val isBoxHorizontal: Boolean
get()
{
return displayData.boxParams.width > displayData.boxParams.height;
}
private lateinit var displayData: DisplayDataOcr
private lateinit var layoutPosition: LayoutPosition
private val kanjiGrid = window.findViewById<View>(R.id.kanji_grid) as KanjiGridView
private val kanjiFrame = window.findViewById<LinearLayout>(R.id.instant_window_kanji_frame)
private val instantInfoWindow = InstantInfoWindow(context, windowCoordinator, this)
private val minHeight = dpToPx(context, 65)
private val minWidth = dpToPx(context, 65)
init
{
kanjiGrid.setDependencies(windowCoordinator, instantInfoWindow)
kanjiFrame.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
run {
var count = displayData.count + 1
if (isBoxHorizontal)
{
count = if (count > 8) 8 else count
params.width = dpToPx(context, 37) * count
if (params.height < minHeight)
{
params.height = minHeight
}
}
else {
count = if (count > 9) 9 else count
params.height = dpToPx(context, 37) * count
if (params.width < minWidth)
{
params.width = minWidth
}
}
when (layoutPosition)
{
LayoutPosition.TOP ->
{
params.y = displayData.boxParams.y - (params.height + statusBarHeight)
}
LayoutPosition.BOTTOM ->
{
params.y = displayData.boxParams.y + displayData.boxParams.height - statusBarHeight
}
LayoutPosition.LEFT ->
{
params.x = displayData.boxParams.x - params.width
}
LayoutPosition.RIGHT ->
{
params.x = displayData.boxParams.x + displayData.boxParams.width
}
}
if (isBoxHorizontal)
{
calcParamsForHorizontal(params.width)
} else
{
calcParamsForVertical(params.height)
}
window.visibility = View.VISIBLE
windowManager.updateViewLayout(window, params)
Log.d(TAG, "layoutChanged - InstantKanjiWindow")
}
}
}
fun getLayoutPosition() : LayoutPosition
{
return layoutPosition
}
fun getWidth() : Int
{
return window.width
}
fun getHeight() : Int
{
return window.height
}
fun setResult(result: DisplayDataOcr)
{
displayData = result
instantInfoWindow.setResult(result)
instantInfoWindow.performSearch(displayData.squareChars[0])
}
override fun recalculateKanjiViews()
{
kanjiGrid.recalculateKanjiViews()
}
override fun copyText()
{
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText(null, kanjiGrid.getText())
clipboard.primaryClip = clip
hide()
}
override fun hide()
{
instantInfoWindow.hide()
super.hide()
}
override fun stop()
{
instantInfoWindow.stop()
super.stop()
}
override fun show()
{
synchronized(this)
{
if (!addedToWindowManager)
{
if (isBoxHorizontal)
{
kanjiGrid.setRowLimit(1)
calcParamsForHorizontal(dpToPx(context, 300))
} else
{
kanjiGrid.setRowLimit(2)
calcParamsForVertical(dpToPx(context, 320))
}
kanjiGrid.clearText()
kanjiGrid.setText(displayData)
window.visibility = INVISIBLE
windowManager.addView(window, params)
addedToWindowManager = true
}
}
instantInfoWindow.show()
}
override fun reInit(options: ReinitOptions?)
{
instantInfoWindow.reInit(options)
super.reInit(options)
}
override fun onTouch(e: MotionEvent?): Boolean
{
return false
}
override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean
{
return false
}
override fun onResize(e: MotionEvent?): Boolean
{
return false
}
fun getKanjiView() : KanjiGridView
{
return kanjiGrid
}
private fun calcParamsForHorizontal(maxWidth: Int)
{
val topRectHeight = displayData.boxParams.y - statusBarHeight
val bottomRectHeight = realDisplaySize.y - displayData.boxParams.y - displayData.boxParams.height - (realDisplaySize.y - viewHeight - statusBarHeight)
var xPos = displayData.boxParams.x
var maxWidth = minOf(realDisplaySize.x, maxWidth)
if (xPos + maxWidth > realDisplaySize.x)
{
xPos = viewWidth - maxWidth
}
params.width = maxWidth
val drawOnTop = fun()
{
params.x = xPos
params.y = displayData.boxParams.y - (minHeight + statusBarHeight)
params.height = minHeight
layoutPosition = LayoutPosition.TOP
}
val drawOnBottom = fun()
{
params.x = xPos
params.y = displayData.boxParams.y + displayData.boxParams.height - statusBarHeight
params.height = minHeight
layoutPosition = LayoutPosition.BOTTOM
}
if (topRectHeight < bottomRectHeight)
{
if (topRectHeight > minHeight)
{
drawOnTop()
}
else {
drawOnBottom()
}
}
else {
if (bottomRectHeight > minHeight)
{
drawOnBottom()
}
else {
drawOnTop()
}
}
}
private fun calcParamsForVertical(maxHeight: Int)
{
val leftRectWidth = displayData.boxParams.x
val rightRectWidth = viewWidth - (displayData.boxParams.x + displayData.boxParams.width)
var yPos = displayData.boxParams.y - statusBarHeight
var maxHeight = minOf(maxHeight, realDisplaySize.y)
if (yPos + maxHeight > realDisplaySize.y)
{
yPos = viewHeight - maxHeight
}
params.height = maxHeight
val drawOnLeftSide = fun()
{
var xPos = displayData.boxParams.x - minWidth
if (xPos < 0)
{
xPos = 0
}
params.x = xPos
params.y = yPos
params.width = minOf(leftRectWidth, minWidth)
layoutPosition = LayoutPosition.LEFT
}
val drawOnRightSide = fun()
{
var xPos = displayData.boxParams.x + displayData.boxParams.width
params.x = xPos
params.y = yPos
params.width = minOf(rightRectWidth, minWidth)
layoutPosition = LayoutPosition.RIGHT
}
if (leftRectWidth < rightRectWidth)
{
if (leftRectWidth > minWidth)
{
drawOnLeftSide()
}
else {
drawOnRightSide()
}
}
else {
if (rightRectWidth > minWidth)
{
drawOnRightSide()
}
else {
drawOnLeftSide()
}
}
}
companion object
{
val TAG = InstantKanjiWindow::class.java.name
}
}
|
bsd-3-clause
|
a48eb935e4745fc5e65ddee45aab6b25
| 26.798762 | 165 | 0.544553 | 5.15977 | false | false | false | false |
rhdunn/xquery-intellij-plugin
|
src/plugin-marklogic/main/uk/co/reecedunn/intellij/plugin/marklogic/query/rest/debugger/MarkLogicDebugSession.kt
|
1
|
9816
|
/*
* Copyright (C) 2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.marklogic.query.rest.debugger
import com.intellij.lang.Language
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.breakpoints.XBreakpointHandler
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator
import com.intellij.xdebugger.frame.XStackFrame
import com.intellij.xdebugger.frame.XSuspendContext
import uk.co.reecedunn.intellij.plugin.core.psi.document
import uk.co.reecedunn.intellij.plugin.core.xml.dom.XmlDocument
import uk.co.reecedunn.intellij.plugin.marklogic.query.rest.MarkLogicQueryProcessor
import uk.co.reecedunn.intellij.plugin.marklogic.query.rest.debugger.breakpoints.MarkLogicXQueryBreakpointHandler
import uk.co.reecedunn.intellij.plugin.marklogic.resources.MarkLogicQueries
import uk.co.reecedunn.intellij.plugin.processor.debug.DebugSession
import uk.co.reecedunn.intellij.plugin.processor.debug.DebugSessionListener
import uk.co.reecedunn.intellij.plugin.processor.debug.StepAction
import uk.co.reecedunn.intellij.plugin.processor.debug.frame.QueryResultsValue
import uk.co.reecedunn.intellij.plugin.processor.debug.frame.QuerySuspendContext
import uk.co.reecedunn.intellij.plugin.processor.query.QueryProcessState
import uk.co.reecedunn.intellij.plugin.xpm.module.loader.XpmModuleLoaderSettings
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression
import uk.co.reecedunn.intellij.plugin.xquery.lang.XQuery
import uk.co.reecedunn.intellij.plugin.xquery.xdebugger.breakpoints.XQueryExpressionBreakpointType
import java.lang.ref.WeakReference
internal class MarkLogicDebugSession(
private val processor: MarkLogicQueryProcessor,
private val query: VirtualFile
) : XDebuggerEvaluator(), DebugSession {
private var modulePath: String = "/"
private var state: QueryProcessState = QueryProcessState.Starting
private var requestId: String? = null
private val breakpointHandlers: Array<XBreakpointHandler<*>> = arrayOf(
MarkLogicXQueryBreakpointHandler(XQueryExpressionBreakpointType::class.java, WeakReference(this))
)
// region XDebuggerEvaluator
override fun evaluate(expression: String, callback: XEvaluationCallback, expressionPosition: XSourcePosition?) {
val query = processor.createRunnableQuery(MarkLogicQueries.Debug.Value, XQuery)
query.bindVariable("requestId", requestId, "xs:unsignedLong")
query.bindVariable("expression", expression, "xs:string")
try {
val results = query.run().results
callback.evaluated(QueryResultsValue(results))
} catch (e: Throwable) {
e.message?.let {
callback.errorOccurred(it)
}
}
}
// endregion
// region DebugSession
override fun getBreakpointHandlers(language: Language): Array<XBreakpointHandler<*>> = breakpointHandlers
override var listener: DebugSessionListener? = null
private fun performAction(queryFile: VirtualFile, ifState: QueryProcessState, nextState: QueryProcessState) {
if (state === ifState) {
state = QueryProcessState.UpdatingState
val query = processor.createRunnableQuery(queryFile, XQuery)
query.bindVariable("requestId", requestId, "xs:unsignedLong")
query.run()
state = nextState
}
}
override fun suspend() {
performAction(MarkLogicQueries.Debug.Break, QueryProcessState.Running, QueryProcessState.Suspending)
}
override fun resume() {
performAction(MarkLogicQueries.Debug.Continue, QueryProcessState.Suspended, QueryProcessState.Resuming)
}
override fun step(action: StepAction) {
val query = when (action) {
StepAction.Into -> MarkLogicQueries.Debug.StepInto
StepAction.Over -> MarkLogicQueries.Debug.StepOver
StepAction.Out -> MarkLogicQueries.Debug.StepOut
}
performAction(query, QueryProcessState.Suspended, QueryProcessState.Resuming)
}
override val stackFrames: List<XStackFrame>
get() {
val query = processor.createRunnableQuery(MarkLogicQueries.Debug.Stack, XQuery)
query.bindVariable("requestId", requestId, "xs:unsignedLong")
val xml = query.run().results.firstOrNull()?.value as? String ?: return listOf()
val stack = XmlDocument.parse(xml, DBG_STACK_NAMESPACES)
return stack.root.children("dbg:frame").map {
MarkLogicDebugFrame.create(it, this.query, this)
}.toList()
}
override val suspendContext: XSuspendContext
get() = QuerySuspendContext(query.name, this)
// endregion
private fun getModuleUri(element: PsiElement): String? {
val file = element.containingFile.virtualFile
if (file == query) return ""
val project = element.project
val path = XpmModuleLoaderSettings.getInstance(project).relativePathTo(file, project)
return when {
path == null -> null
path.startsWith("/MarkLogic/") -> path
modulePath.endsWith("/") -> "$modulePath$path"
else -> "$modulePath/$path"
}
}
private fun updateBreakpoint(uri: String, line: Int, column: Int, register: Boolean): Boolean {
val query = processor.createRunnableQuery(MarkLogicQueries.Debug.Breakpoint, XQuery)
query.bindVariable("requestId", requestId, "xs:unsignedLong")
query.bindVariable("register", register.toString(), "xs:boolean")
query.bindVariable("exprUri", uri, "xs:string")
query.bindVariable("exprLine", line.toString(), "xs:nonNegativeInteger")
query.bindVariable("exprColumn", column.toString(), "xs:nonNegativeInteger")
return query.run().results.first().value == "true"
}
fun updateBreakpoint(element: XpmExpression, register: Boolean, initializing: Boolean = false): Boolean {
if (!initializing && state === QueryProcessState.Starting) return true
val uri = getModuleUri(element as PsiElement) ?: return false
val document = element.containingFile.document ?: return false
val offset = element.expressionElement?.textOffset ?: return false
val line = document.getLineNumber(offset)
val column = offset - document.getLineStartOffset(line)
val currentState = state
state = QueryProcessState.UpdatingState
val ret = updateBreakpoint(uri, line + 1, column, register = register)
if (state == QueryProcessState.UpdatingState) {
state = currentState
}
return ret
}
private fun registerBreakpoints() {
// Accessing the containing file and associated document need to be
// accessed via a read action on the EDT thread.
runInEdt {
runReadAction {
val xquery = breakpointHandlers[0] as MarkLogicXQueryBreakpointHandler
xquery.expressionBreakpoints.forEach { updateBreakpoint(it, register = true, initializing = true) }
// MarkLogic requests are suspended at the start of the first expression.
state = QueryProcessState.Suspended
}
}
// Wait for the breakpoints to be processed.
while (state !== QueryProcessState.Suspended) {
Thread.sleep(100)
}
}
fun run(requestId: String) {
this.requestId = requestId
registerBreakpoints()
resume() // MarkLogic requests are suspended at the start of the first expression.
while (state !== QueryProcessState.Stopped) {
Thread.sleep(100)
val newState = when (val status = status()) {
"none" -> QueryProcessState.Stopped
"running" -> QueryProcessState.Running
"stopped" -> QueryProcessState.Suspending
else -> throw RuntimeException(status)
}
if (state !== QueryProcessState.UpdatingState) {
if (newState === QueryProcessState.Suspending) {
if (state !== QueryProcessState.Suspended) {
state = QueryProcessState.Suspended
listener?.positionReached()
}
} else {
state = newState
}
}
}
}
private fun status(): String {
val query = processor.createRunnableQuery(MarkLogicQueries.Debug.Status, XQuery)
query.bindVariable("requestId", requestId, "xs:unsignedLong")
return query.run().results.first().value as String
}
fun stop() {
state = QueryProcessState.UpdatingState
val query = processor.createRunnableQuery(MarkLogicQueries.Request.Cancel, XQuery)
query.bindVariable("requestId", requestId, "xs:unsignedLong")
query.run()
state = QueryProcessState.Stopping
}
companion object {
private val DBG_STACK_NAMESPACES = mapOf("dbg" to "http://marklogic.com/xdmp/debug")
}
}
|
apache-2.0
|
a59c5f352250a28e7b58e87a9d5b244f
| 40.59322 | 116 | 0.687857 | 4.783626 | false | false | false | false |
google/private-compute-services
|
src/com/google/android/as/oss/assets/federatedcompute/ContentCapturePerformanceDataPolicy_FederatedCompute.kt
|
1
|
3122
|
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.policies.federatedcompute
/** Content Capture Performance Data FederatedCompute policy. */
val ContentCapturePerformanceDataPolicy_FederatedCompute =
flavoredPolicies(
name = "ContentCapturePerformanceDataPolicy_FederatedCompute",
policyType = MonitorOrImproveUserExperienceWithFederatedCompute,
) {
description =
"""
To track system health costs associated with the content capture service to detect problems
and allow optimization of features based on content capture.
ALLOWED EGRESSES: FederatedCompute.
ALLOWED USAGES: Federated analytics, federated learning.
"""
.trimIndent()
flavors(Flavor.ASI_PROD) { minRoundSize(minRoundSize = 1000, minSecAggRoundSize = 0) }
consentRequiredForCollectionOrStorage(Consent.UsageAndDiagnosticsCheckbox)
presubmitReviewRequired(OwnersApprovalOnly)
checkpointMaxTtlDays(720)
target(
PERSISTED_CONTENT_CAPTURE_PERFORMANCE_ENTITY_GENERATED_DTD,
maxAge = Duration.ofDays(14)
) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"id" { rawUsage(UsageType.JOIN) }
"timestampMillis" {
ConditionalUsage.TruncatedToDays.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"autofillModelVersion" { rawUsage(UsageType.ANY) }
"sessionType" { rawUsage(UsageType.ANY) }
"processingTimeMs" { rawUsage(UsageType.ANY) }
"cpuTimeMs" { rawUsage(UsageType.ANY) }
"elapsedTimeMs" { rawUsage(UsageType.ANY) }
"eventsProcessed" { rawUsage(UsageType.ANY) }
"activityEventsProcessed" { rawUsage(UsageType.ANY) }
"annotatorCalls" { rawUsage(UsageType.ANY) }
"globalAnnotationUpdates" { rawUsage(UsageType.ANY) }
"taskAnnotationUpdates" { rawUsage(UsageType.ANY) }
"nodeAnnotationUpdates" { rawUsage(UsageType.ANY) }
"eventAnnotationUpdates" { rawUsage(UsageType.ANY) }
"nodesAdded" { rawUsage(UsageType.ANY) }
"nodesRemoved" { rawUsage(UsageType.ANY) }
"propertyUpdates" { rawUsage(UsageType.ANY) }
"stringsAdded" { rawUsage(UsageType.ANY) }
"charsAdded" { rawUsage(UsageType.ANY) }
"nativeProcessingCalls" { rawUsage(UsageType.ANY) }
"nativeProcessingTimeMs" { rawUsage(UsageType.ANY) }
"activeSessionTimeMs" { rawUsage(UsageType.ANY) }
"sourcePackageName" {
ConditionalUsage.Top2000PackageNamesWith2000Wau.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
}
}
|
apache-2.0
|
71986bdd35d1d6e4ebf243283029670e
| 39.545455 | 97 | 0.716848 | 4.288462 | false | false | false | false |
Akjir/WiFabs
|
src/main/kotlin/net/kejira/wifabs/Handlers.kt
|
1
|
2019
|
/*
* Copyright (c) 2017 Stefan Neubert
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kejira.wifabs
import javafx.event.EventHandler
import javafx.scene.input.DragEvent
import javafx.scene.input.TransferMode
import java.nio.file.Path
fun onFileDragDropped(handle: (Path) -> Boolean) = EventHandler<DragEvent> { event ->
val db = event.dragboard
if (db.hasFiles() && db.files.size == 1) {
event.isDropCompleted = handle(db.files[0].toPath())
}
event.consume()
}
val onImageFileDragOver = EventHandler<DragEvent> { event ->
val file_extensions = listOf("jpg", "jpeg")
val db = event.dragboard
if (db.hasFiles()) {
val files = db.files
if (files.size == 1) {
val file = files[0]
if (file_extensions.any { file.name.endsWith(it, ignoreCase = true) }) {
event.acceptTransferModes(TransferMode.COPY)
} else {
event.consume()
}
}
}
}
|
mit
|
4673769924dcee7d22d3bd4d225356c4
| 37.846154 | 85 | 0.695394 | 4.20625 | false | false | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepik/android/view/profile/ui/animation/ProfileHeaderAnimationDelegate.kt
|
2
|
2105
|
package org.stepik.android.view.profile.ui.animation
import android.animation.ArgbEvaluator
import android.content.res.ColorStateList
import android.view.View
import androidx.annotation.ColorInt
import androidx.core.view.ViewCompat
import androidx.core.view.isVisible
import kotlinx.android.synthetic.main.fragment_profile.view.*
import kotlinx.android.synthetic.main.header_profile.view.*
import org.stepik.android.view.base.ui.extension.ColorExtensions
class ProfileHeaderAnimationDelegate(
view: View,
@ColorInt
private val menuColorStart: Int,
@ColorInt
private val menuColorEnd: Int,
@ColorInt
private val toolbarColor: Int,
private val onMenuColorChanged: (ColorStateList) -> Unit
) {
private val profileCover = view.profileCover
private val profileImage = view.profileImage
private val toolbarTitle = view.toolbarTitle
private val toolbarSeparator = view.toolbarSeparator
private val appbar = view.appbar
private val header = view.header
private val argbEvaluator = ArgbEvaluator()
fun onScroll(scrollY: Int) {
val coverHeight = profileCover.height
val toolbarHeight = appbar.height
val headerHeight = header.height
val coverScrollPercent = ((scrollY + 1f) / (coverHeight - toolbarHeight).coerceAtLeast(1))
.coerceIn(0f, 1f)
val toolbarBackground = ColorExtensions.colorWithAlpha(toolbarColor, coverScrollPercent)
appbar.setBackgroundColor(toolbarBackground)
val menuColor = argbEvaluator.evaluate(coverScrollPercent, menuColorStart, menuColorEnd) as Int
onMenuColorChanged(ColorStateList.valueOf(menuColor))
ViewCompat.setElevation(appbar, if (scrollY > headerHeight - toolbarHeight) ViewCompat.getElevation(header) else 0f)
val scroll = (scrollY - profileImage.top).coerceAtMost(0).toFloat()
toolbarTitle.translationY = -scroll
val separatorBound = coverHeight.takeIf { it > 0 } ?: profileImage.top + 1
toolbarSeparator.isVisible = (scrollY + toolbarHeight) in separatorBound until headerHeight
}
}
|
apache-2.0
|
919b7cbf5da0eea28d9ac04b8037244c
| 35.947368 | 124 | 0.748219 | 4.526882 | false | false | false | false |
dhleong/ideavim
|
src/com/maddyhome/idea/vim/ex/handler/DigraphHandler.kt
|
1
|
1719
|
/*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2019 The IdeaVim authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.maddyhome.idea.vim.ex.handler
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.ex.CommandHandler
import com.maddyhome.idea.vim.ex.ExCommand
import com.maddyhome.idea.vim.ex.commands
import com.maddyhome.idea.vim.ex.flags
class DigraphHandler : CommandHandler.SingleExecution() {
override val names = commands("dig[raphs]")
override val argFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_OPTIONAL)
override fun execute(editor: Editor, context: DataContext, cmd: ExCommand): Boolean {
val arg = cmd.argument
if (logger.isDebugEnabled) {
logger.debug("arg=$arg")
}
return VimPlugin.getDigraph().parseCommandLine(editor, arg)
}
companion object {
private val logger = Logger.getInstance(DigraphHandler::class.java.name)
}
}
|
gpl-2.0
|
28e66de5192fc0e0bb265b7719484e11
| 36.369565 | 89 | 0.762071 | 4.092857 | false | false | false | false |
apollostack/apollo-android
|
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/adapter/AdapterCommon.kt
|
1
|
4413
|
package com.apollographql.apollo3.compiler.codegen.adapter
import com.apollographql.apollo3.compiler.codegen.Identifier
import com.apollographql.apollo3.compiler.codegen.Identifier.responseAdapterCache
import com.apollographql.apollo3.compiler.codegen.Identifier.toResponse
import com.apollographql.apollo3.compiler.codegen.Identifier.value
import com.apollographql.apollo3.compiler.codegen.Identifier.writer
import com.apollographql.apollo3.compiler.codegen.kotlinNameForVariable
import com.apollographql.apollo3.compiler.codegen.CgContext
import com.apollographql.apollo3.compiler.unified.ir.IrModel
import com.apollographql.apollo3.compiler.unified.ir.IrNonNullType
import com.apollographql.apollo3.compiler.unified.ir.IrProperty
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.MemberName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.joinToCode
internal fun responseNamesPropertySpec(model: IrModel): PropertySpec {
val initializer = model.properties.map {
CodeBlock.of("%S", it.info.responseName)
}.joinToCode(prefix = "listOf(", separator = ", ", suffix = ")")
return PropertySpec.builder(Identifier.RESPONSE_NAMES, List::class.parameterizedBy(String::class))
.initializer(initializer)
.build()
}
internal fun readFromResponseCodeBlock(
model: IrModel,
context: CgContext,
variableInitializer: (String) -> String
): CodeBlock {
val prefix = model.properties.map { property ->
CodeBlock.of(
"var·%L:·%T·=·%L",
kotlinNameForVariable(property.info.responseName),
context.resolver.resolveType(property.info.type).copy(nullable = true),
variableInitializer(property.info.responseName)
)
}.joinToCode(separator = "\n", suffix = "\n")
val loop = CodeBlock.builder()
.beginControlFlow("while(true)")
.beginControlFlow("when·(${Identifier.reader}.selectName(${Identifier.RESPONSE_NAMES}))")
.add(
model.properties.mapIndexed { index, property ->
CodeBlock.of(
"%L·->·%L·=·%L.${Identifier.fromResponse}(${Identifier.reader}, ${Identifier.responseAdapterCache})",
index,
context.layout.variableName(property.info.responseName),
context.resolver.adapterInitializer(property.info.type)
)
}.joinToCode(separator = "\n", suffix = "\n")
)
.addStatement("else -> break")
.endControlFlow()
.endControlFlow()
.build()
val suffix = CodeBlock.builder()
.addStatement("return·%T(", context.resolver.resolveModel(model.id))
.indent()
.add(model.properties.map { property ->
val maybeAssertNotNull = if (property.info.type is IrNonNullType) "!!" else ""
CodeBlock.of(
"%L·=·%L%L",
context.layout.propertyName(property.info.responseName),
context.layout.variableName(property.info.responseName),
maybeAssertNotNull
)
}.joinToCode(separator = ",\n", suffix = "\n"))
.unindent()
.addStatement(")")
.build()
return CodeBlock.builder()
.add(prefix)
.add(loop)
.add(suffix)
.build()
}
internal fun writeToResponseCodeBlock(model: IrModel, context: CgContext): CodeBlock {
val builder = CodeBlock.builder()
model.properties.forEach {
builder.add(writeToResponseCodeBlock(it, context))
}
return builder.build()
}
internal fun writeToResponseCodeBlock(property: IrProperty, context: CgContext): CodeBlock {
return CodeBlock.builder().apply {
val propertyName = context.layout.propertyName(property.info.responseName)
addStatement("$writer.name(%S)", property.info.responseName)
addStatement(
"%L.$toResponse($writer, $responseAdapterCache, $value.$propertyName)",
context.resolver.adapterInitializer(property.info.type)
)
}.build()
}
internal fun ClassName.Companion.from(path: List<String>) = ClassName(
packageName = path.first(),
path.drop(1)
)
internal fun CodeBlock.obj(buffered: Boolean): CodeBlock {
return CodeBlock.Builder()
.add("%L", this)
.add(
".%M(%L)",
MemberName("com.apollographql.apollo3.api", "obj"),
if (buffered) "true" else ""
).build()
}
|
mit
|
1f4471ce0c0eb78de3b35ffd30ffad49
| 36.623932 | 117 | 0.699614 | 4.252174 | false | false | false | false |
CarlosEsco/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/util/lang/RetryWithDelay.kt
|
1
|
782
|
package eu.kanade.tachiyomi.util.lang
import rx.Observable
import rx.Scheduler
import rx.functions.Func1
import rx.schedulers.Schedulers
import java.util.concurrent.TimeUnit.MILLISECONDS
class RetryWithDelay(
private val maxRetries: Int = 1,
private val retryStrategy: (Int) -> Int = { 1000 },
private val scheduler: Scheduler = Schedulers.computation(),
) : Func1<Observable<out Throwable>, Observable<*>> {
private var retryCount = 0
override fun call(attempts: Observable<out Throwable>) = attempts.flatMap { error ->
val count = ++retryCount
if (count <= maxRetries) {
Observable.timer(retryStrategy(count).toLong(), MILLISECONDS, scheduler)
} else {
Observable.error(error as Throwable)
}
}
}
|
apache-2.0
|
43bdbcda074d521bedf6558f1b1bd8cc
| 30.28 | 88 | 0.689258 | 4.418079 | false | false | false | false |
Saketme/JRAW
|
meta/src/test/kotlin/net/dean/jraw/meta/test/EndpointParserTest.kt
|
1
|
2319
|
import com.winterbe.expekt.should
import net.dean.jraw.meta.EndpointParser
import net.dean.jraw.meta.ParsedEndpoint
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import kotlin.properties.Delegates
class EndpointParserTest : Spek({
describe("fetch") {
val METHODS = listOf("GET", "POST", "PUT", "PATCH", "DELETE")
var endpoints: List<ParsedEndpoint> by Delegates.notNull()
beforeGroup {
endpoints = EndpointParser().fetch()
}
it("should return a list of valid Endpoints") {
// There are at least 100 endpoints in the reddit API
endpoints.should.have.size.above(100)
for ((method, path, oauthScope, redditDocLink) in endpoints) {
METHODS.should.contain(method)
// http://regexr.com/3g4ad
path.should.match(Regex("(/[a-z{}_0-9.]+)+"))
// http://regexr.com/3g4a7
oauthScope.should.match(Regex("[a-z]+"))
// http://regexr.com/3g4ap
redditDocLink.should.match(Regex("https://www\\.reddit\\.com/dev/api/oauth#[A-Z]+_[0-9a-z_{}:.]+"))
}
}
it("should turn colon path parameters into path bracket parameters") {
// For example: /api/mod/conversations/:conversation_id/archive
// should become: /api/mod/conversations/{conversation_id}/archive
endpoints.firstOrNull { it.path == "/api/mod/conversations/{conversation_id}/archive" }.should.not.equal(null)
}
fun ensureFound(path: String) {
endpoints.firstOrNull { it.path == path }.should.not.equal(null)
}
it("should preserve path variables") {
// Single out these two
ensureFound("/user/{username}/{where}")
ensureFound("/api/v1/me/friends/{username}")
}
it("should preserve underscores") {
ensureFound("/api/accept_moderator_invite")
ensureFound("/api/read_all_messages")
}
it("should only replace the proper instance of the path parameter keyword") {
// Instead of /api/live/{thread}/close_{thread}
ensureFound("/api/live/{thread}/close_thread")
}
}
})
|
mit
|
9b5241aa14a6a0f36ed9290f12a37c71
| 35.809524 | 122 | 0.594653 | 4.104425 | false | false | false | false |
Maccimo/intellij-community
|
plugins/package-search/gradle/src/com/jetbrains/packagesearch/intellij/plugin/gradle/CoroutineGradleTaskManager.kt
|
2
|
3033
|
/*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.gradle
import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode
import com.intellij.openapi.externalSystem.task.TaskCallback
import com.intellij.openapi.project.Project
import org.gradle.api.Task
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.gradle.service.task.GradleTaskManager
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
import kotlin.reflect.KClass
object CoroutineGradleTaskManager {
/**
* See [GradleTaskManager.runCustomTask].
* @return `true` if task is successful, else `false`
*/
suspend inline fun <reified T : Task> runCustomTask(
project: Project,
executionName: @Nls String,
projectPath: String,
gradlePath: String,
progressExecutionMode: ProgressExecutionMode,
taskConfiguration: String? = null,
toolingExtensionClasses: Set<KClass<*>> = emptySet()
): Boolean = suspendCoroutine { continuation ->
GradleTaskManager.runCustomTask(
project,
executionName,
T::class.java,
projectPath,
gradlePath,
taskConfiguration,
progressExecutionMode,
object : TaskCallback {
override fun onSuccess() = continuation.resume(true)
override fun onFailure() = continuation.resume(false)
},
toolingExtensionClasses.map { it.java }.toSet()
)
}
suspend fun runTask(
taskScript: String,
taskName: String,
project: Project,
executionName: @Nls String,
projectPath: String,
gradlePath: String,
progressExecutionMode: ProgressExecutionMode
): Boolean = suspendCoroutine { continuation ->
GradleTaskManager.runCustomTaskScript(
project,
executionName,
projectPath,
gradlePath,
progressExecutionMode,
object : TaskCallback {
override fun onSuccess() = continuation.resume(true)
override fun onFailure() = continuation.resume(false)
},
taskScript,
taskName
)
}
}
|
apache-2.0
|
af76d5122c32708e3d6bc922de22e524
| 36 | 82 | 0.630069 | 5.321053 | false | false | false | false |
Maccimo/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinDoubleNegationInspection.kt
|
2
|
2524
|
// 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
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtParenthesizedExpression
import org.jetbrains.kotlin.psi.KtPrefixExpression
import org.jetbrains.kotlin.psi.prefixExpressionVisitor
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.types.typeUtil.isBoolean
class KotlinDoubleNegationInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) =
prefixExpressionVisitor(fun(expression) {
if (expression.operationToken != KtTokens.EXCL ||
expression.baseExpression?.getType(expression.analyze())?.isBoolean() != true
) {
return
}
var parent = expression.parent
while (parent is KtParenthesizedExpression) {
parent = parent.parent
}
if (parent is KtPrefixExpression && parent.operationToken == KtTokens.EXCL) {
holder.registerProblem(
expression,
KotlinBundle.message("redundant.double.negation"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
DoubleNegationFix()
)
}
})
private class DoubleNegationFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("double.negation.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
applyFix(descriptor.psiElement as? KtPrefixExpression ?: return)
}
private fun applyFix(expression: KtPrefixExpression) {
var parent = expression.parent
while (parent is KtParenthesizedExpression) {
parent = parent.parent
}
if (parent is KtPrefixExpression && parent.operationToken == KtTokens.EXCL) {
expression.baseExpression?.let { parent.replaced(it) }
}
}
}
}
|
apache-2.0
|
74fd78654ab0c966bf2aa1347b4eb953
| 43.298246 | 158 | 0.674723 | 5.347458 | false | false | false | false |
Hexworks/zircon
|
zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/internal/component/impl/DefaultToggleButtonTest.kt
|
1
|
6528
|
package org.hexworks.zircon.internal.component.impl
import org.assertj.core.api.Assertions.assertThat
import org.hexworks.cobalt.databinding.api.extension.toProperty
import org.hexworks.zircon.api.DrawSurfaces
import org.hexworks.zircon.api.builder.component.ComponentStyleSetBuilder
import org.hexworks.zircon.api.builder.data.TileBuilder
import org.hexworks.zircon.api.builder.graphics.StyleSetBuilder
import org.hexworks.zircon.api.color.TileColor
import org.hexworks.zircon.api.component.ComponentStyleSet
import org.hexworks.zircon.api.component.ToggleButton
import org.hexworks.zircon.api.component.data.ComponentMetadata
import org.hexworks.zircon.api.component.data.ComponentState.ACTIVE
import org.hexworks.zircon.api.component.data.ComponentState.DEFAULT
import org.hexworks.zircon.api.component.data.ComponentState.FOCUSED
import org.hexworks.zircon.api.component.data.ComponentState.HIGHLIGHTED
import org.hexworks.zircon.api.component.renderer.ComponentRenderContext
import org.hexworks.zircon.api.component.renderer.ComponentRenderer
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.graphics.TileGraphics
import org.hexworks.zircon.api.uievent.MouseEvent
import org.hexworks.zircon.api.uievent.MouseEventType
import org.hexworks.zircon.api.uievent.Processed
import org.hexworks.zircon.api.uievent.UIEventPhase
import org.hexworks.zircon.internal.component.renderer.DefaultComponentRenderingStrategy
import org.hexworks.zircon.internal.component.renderer.DefaultToggleButtonRenderer
import org.junit.Before
import org.junit.Test
@Suppress("UNCHECKED_CAST", "TestFunctionName")
class DefaultToggleButtonTest : FocusableComponentImplementationTest<DefaultToggleButton>() {
override lateinit var target: DefaultToggleButton
override lateinit var graphics: TileGraphics
override val expectedComponentStyles: ComponentStyleSet
get() = ComponentStyleSetBuilder.newBuilder()
.withDefaultStyle(
StyleSetBuilder.newBuilder()
.withForegroundColor(DEFAULT_THEME.accentColor)
.withBackgroundColor(TileColor.transparent())
.build()
)
.withHighlightedStyle(
StyleSetBuilder.newBuilder()
.withForegroundColor(DEFAULT_THEME.primaryBackgroundColor)
.withBackgroundColor(DEFAULT_THEME.accentColor)
.build()
)
.withFocusedStyle(
StyleSetBuilder.newBuilder()
.withForegroundColor(DEFAULT_THEME.secondaryBackgroundColor)
.withBackgroundColor(DEFAULT_THEME.accentColor)
.build()
)
.withActiveStyle(
StyleSetBuilder.newBuilder()
.withForegroundColor(DEFAULT_THEME.secondaryForegroundColor)
.withBackgroundColor(DEFAULT_THEME.accentColor)
.build()
)
.build()
@Before
override fun setUp() {
rendererStub = ComponentRendererStub(DefaultToggleButtonRenderer())
graphics = DrawSurfaces.tileGraphicsBuilder().withSize(SIZE_15X1).build()
target = DefaultToggleButton(
componentMetadata = ComponentMetadata(
size = SIZE_15X1,
relativePosition = POSITION_2_3,
componentStyleSetProperty = COMPONENT_STYLES.toProperty(),
tilesetProperty = TILESET_REX_PAINT_20X20.toProperty()
),
renderingStrategy = DefaultComponentRenderingStrategy(
decorationRenderers = listOf(),
componentRenderer = rendererStub as ComponentRenderer<ToggleButton>
),
textProperty = TEXT.toProperty(),
initialSelected = false
)
rendererStub.render(graphics, ComponentRenderContext(target))
}
@Test
fun shouldProperlyAssignStyleSetForUnselectedState() {
target.selectedProperty.value = false
assertThat(target.componentState)
.isEqualTo(UNSELECTED_ACTION)
}
@Test
fun shouldProperlyAddButtonText() {
val offset = target.contentOffset.x + DefaultToggleButtonRenderer.DECORATION_WIDTH
TEXT.forEachIndexed { i, char ->
assertThat(graphics.getTileAtOrNull(Position.create(i + offset, 0)))
.isEqualTo(
TileBuilder.newBuilder()
.withCharacter(char)
.withStyleSet(target.componentStyleSet.fetchStyleFor(DEFAULT))
.build()
)
}
}
@Test
fun shouldProperlyReturnText() {
assertThat(target.text).isEqualTo(TEXT)
}
@Test
fun shouldAcceptFocus() {
assertThat(target.acceptsFocus()).isTrue()
}
@Test
fun shouldProperlyGiveFocus() {
val result = target.focusGiven()
assertThat(result).isEqualTo(Processed)
assertThat(target.componentState).isEqualTo(FOCUSED)
}
@Test
fun shouldProperlyTakeFocus() {
target.focusTaken()
assertThat(target.componentState).isEqualTo(DEFAULT)
}
@Test
override fun When_a_focused_component_is_activated_Then_it_becomes_active() {
target.focusGiven()
rendererStub.clear()
target.activated()
assertThat(target.componentState).isEqualTo(ACTIVE)
}
@Test
override fun When_a_highlighted_component_without_focus_is_activated_Then_it_becomes_active() {
target.mouseEntered(
event = MouseEvent(MouseEventType.MOUSE_ENTERED, 1, Position.zero()),
phase = UIEventPhase.TARGET
)
rendererStub.clear()
target.activated()
assertThat(target.componentState).isEqualTo(ACTIVE)
}
@Test
override fun When_a_highlighted_component_with_focus_is_activated_Then_it_becomes_active() {
target.mouseEntered(
event = MouseEvent(MouseEventType.MOUSE_ENTERED, 1, Position.zero()),
phase = UIEventPhase.TARGET
)
target.focusGiven()
rendererStub.clear()
target.activated()
assertThat(target.componentState).isEqualTo(ACTIVE)
}
companion object {
val SIZE_15X1 = Size.create(15, 1)
const val TEXT = "Button text"
private val SELECTED_ACTION = HIGHLIGHTED
private val UNSELECTED_ACTION = DEFAULT
}
}
|
apache-2.0
|
289241c2b3e4c0f238092cb221eb13e1
| 36.302857 | 99 | 0.676164 | 5.017679 | false | true | false | false |
Turbo87/intellij-rust
|
src/main/kotlin/org/toml/ide/TomlHighlighter.kt
|
1
|
1796
|
package org.toml.ide
import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.tree.IElementType
import gnu.trove.THashMap
import org.toml.lang.core.lexer.TomlLexer
import org.toml.lang.core.psi.TomlTypes
import kotlin.collections.set
class TomlHighlighter : SyntaxHighlighterBase() {
override fun getHighlightingLexer(): Lexer =
TomlLexer()
override fun getTokenHighlights(tokenType: IElementType?): Array<out TextAttributesKey> =
pack(tokenType?.let { tokenMap[it] })
private val tokenMap: Map<IElementType, TextAttributesKey> = makeTokenMap()
}
private fun makeTokenMap(): Map<IElementType, TextAttributesKey> {
val result = THashMap<IElementType, TextAttributesKey>()
result[TomlTypes.KEY] =
TextAttributesKey.createTextAttributesKey("TOML_KEY", DefaultLanguageHighlighterColors.KEYWORD)
result[TomlTypes.COMMENT] =
TextAttributesKey.createTextAttributesKey("TOML_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT)
result[TomlTypes.STRING] =
TextAttributesKey.createTextAttributesKey("TOML_STRING", DefaultLanguageHighlighterColors.STRING)
result[TomlTypes.NUMBER] =
TextAttributesKey.createTextAttributesKey("TOML_NUMBER", DefaultLanguageHighlighterColors.NUMBER)
result[TomlTypes.BOOLEAN] =
TextAttributesKey.createTextAttributesKey("TOML_BOOLEAN", DefaultLanguageHighlighterColors.PREDEFINED_SYMBOL)
result[TomlTypes.DATE] =
TextAttributesKey.createTextAttributesKey("TOML_DATE", DefaultLanguageHighlighterColors.PREDEFINED_SYMBOL)
return result;
}
|
mit
|
46cf38565d13150ea488ea69921634e9
| 35.653061 | 121 | 0.77951 | 5.393393 | false | false | false | false |
Endran/ShowcaseReference
|
Mobile/app/src/main/java/nl/endran/productbrowser/DetailActivity.kt
|
1
|
1390
|
/*
* Copyright (c) 2016 by David Hardy. Licensed under the Apache License, Version 2.0.
*/
package nl.endran.productbrowser
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_main.*
import nl.endran.productbrowser.fragments.DetailFragment
import nl.endran.productbrowser.interactors.Product
class DetailActivity : AppCompatActivity() {
companion object {
val PRODUCT_KEY = "PRODUCT_KEY"
fun createIntent(context: Context, product: Product): Intent {
val intent = Intent(context, DetailActivity::class.java)
intent.putExtra(PRODUCT_KEY, Gson().toJson(product))
return intent
}
fun getProduct(intent: Intent) = Gson().fromJson(intent.getStringExtra(PRODUCT_KEY), Product::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val product = getProduct(intent)
supportActionBar?.title = product.name
val transition = supportFragmentManager.beginTransaction()
transition.replace(R.id.contentView, DetailFragment.createInstance(product))
transition.commit()
}
}
|
apache-2.0
|
8415d935f22f3b932b59795212cceb53
| 31.325581 | 113 | 0.720863 | 4.695946 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/sealedSubClassToObject/GenerateIdentityEqualsFix.kt
|
1
|
1948
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.sealedSubClassToObject
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtPsiFactory.CallableBuilder
import org.jetbrains.kotlin.psi.KtPsiFactory.CallableBuilder.Target.FUNCTION
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
class GenerateIdentityEqualsFix : LocalQuickFix {
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val klass = descriptor.psiElement.getParentOfType<KtClass>(false) ?: return
val factory = KtPsiFactory(klass)
val equalsFunction = factory.createFunction(
CallableBuilder(FUNCTION).apply {
modifier(KtTokens.OVERRIDE_KEYWORD.value)
typeParams()
name("equals")
param("other", "Any?")
returnType("Boolean")
blockBody("return this === other")
}.asString()
)
klass.addDeclaration(equalsFunction)
val hashCodeFunction = factory.createFunction(
CallableBuilder(FUNCTION).apply {
modifier(KtTokens.OVERRIDE_KEYWORD.value)
typeParams()
name("hashCode")
returnType("Int")
blockBody("return System.identityHashCode(this)")
}.asString()
)
klass.addDeclaration(hashCodeFunction)
}
override fun getFamilyName() = KotlinBundle.message("generate.identity.equals.fix.family.name")
}
|
apache-2.0
|
acf76ba9838fe3bf0cb6eaf765da13de
| 41.369565 | 158 | 0.695585 | 5.086162 | false | false | false | false |
ingokegel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/wordSelection/KotlinListSelectioner.kt
|
4
|
1746
|
// 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.editor.wordSelection
import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.TokenSet
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtParameterList
import org.jetbrains.kotlin.psi.KtTypeArgumentList
import org.jetbrains.kotlin.psi.KtTypeParameterList
import org.jetbrains.kotlin.psi.KtValueArgumentList
class KotlinListSelectioner : ExtendWordSelectionHandlerBase() {
companion object {
fun canSelect(e: PsiElement) =
e is KtParameterList || e is KtValueArgumentList || e is KtTypeParameterList || e is KtTypeArgumentList
}
override fun canSelect(e: PsiElement) = KotlinListSelectioner.canSelect(e)
override fun select(e: PsiElement, editorText: CharSequence, cursorOffset: Int, editor: Editor): List<TextRange>? {
val node = e.node!!
val startNode = node.findChildByType(TokenSet.create(KtTokens.LPAR, KtTokens.LT)) ?: return null
val endNode = node.findChildByType(TokenSet.create(KtTokens.RPAR, KtTokens.GT)) ?: return null
val innerRange = TextRange(startNode.startOffset + 1, endNode.startOffset)
if (e is KtTypeArgumentList || e is KtTypeParameterList) {
return listOf(
innerRange,
TextRange(startNode.startOffset, endNode.startOffset + endNode.textLength)
)
}
return listOf(innerRange)
}
}
|
apache-2.0
|
99b4452a4663657e7e6074e4d0a58098
| 46.189189 | 158 | 0.744559 | 4.680965 | false | false | false | false |
hermantai/samples
|
kotlin/Mastering-Kotlin-master/Chapter15/androidapp/src/main/java/com/packt/androidmultiplatform/MainActivity.kt
|
1
|
876
|
package com.packt.androidmultiplatform
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import Presenter
import android.widget.Button
class MainActivity : AppCompatActivity() {
lateinit var title: TextView
lateinit var subtitle: TextView
lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = findViewById(R.id.titleText)
subtitle = findViewById(R.id.subtitleText)
button = findViewById(R.id.button)
val presenter = Presenter().apply {
viewStateListener = {
title.text = it.title
subtitle.text = it.subtitle
}
}
button.setOnClickListener { presenter.onClick() }
}
}
|
apache-2.0
|
559a500d1cc17dde678592c4062b5244
| 26.375 | 57 | 0.676941 | 4.949153 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/util/FileAttributeUtils.kt
|
4
|
4365
|
// 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.core.util
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.io.DataInputOutputUtilRt.readSeq
import com.intellij.openapi.util.io.DataInputOutputUtilRt.writeSeq
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileWithId
import com.intellij.openapi.vfs.newvfs.FileAttribute
import com.intellij.util.ObjectUtils
import com.intellij.util.io.IOUtil.readUTF
import com.intellij.util.io.IOUtil.writeUTF
import java.io.*
import java.util.concurrent.ConcurrentHashMap
abstract class AbstractFileAttributePropertyService<T: Any>(
name: String,
version: Int,
private val default: T? = null,
private val read: DataInputStream.() -> T,
private val write: DataOutputStream.(T) -> Unit
): Disposable {
private val attribute = attribute(name, version)
private val cache = ConcurrentHashMap<VirtualFile, Any?>()
private fun computeValue(file: VirtualFile): T? {
if (file !is VirtualFileWithId || !file.isValid) return null
return attribute.readFileAttribute(file)?.use { input ->
try {
input.readNullable {
read(input)
}
} catch (e: Throwable) {
Logger.getInstance("#org.jetbrains.kotlin.idea.core.util.FileAttributeProperty")
.warn("Unable to read attribute from $file", e)
null
}
} ?: default
}
operator fun set(file: VirtualFile, newValue: T?) {
if (file !is VirtualFileWithId || !file.isValid) return
attribute.writeFileAttribute(file).use { output ->
output.writeNullable(newValue) { value ->
write(output, value)
}
}
// clear cache
cache.remove(file)
}
@Suppress("UNCHECKED_CAST")
operator fun get(file: VirtualFile): T? =
cache.computeIfAbsent(file) {
computeValue(file) ?: ObjectUtils.NULL
}.takeIf { it != ObjectUtils.NULL } as T?
override fun dispose() {
cache.clear()
}
companion object {
@JvmStatic
private val attributes = mutableMapOf<String, FileAttribute>()
@JvmStatic
private fun attribute(name: String, version: Int): FileAttribute {
val attribute = synchronized(attributes) {
attributes.computeIfAbsent(name) {
FileAttribute(name, version, false)
}
}
check(attribute.version == version) {
"FileAttribute version $version differs with existed one ${attribute.version}"
}
return attribute
}
}
}
fun DataInput.readStringList(): List<String> = readSeq(this) { readString() }
fun DataInput.readFileList(): List<File> = readSeq(this) { readFile() }
fun DataInput.readString(): String = readUTF(this)
fun DataInput.readFile() = File(readUTF(this))
fun DataOutput.writeFileList(iterable: Iterable<File>) = writeSeq(this, iterable.toList()) { writeFile(it) }
fun DataOutput.writeFile(it: File) = writeString(it.canonicalPath)
fun DataOutput.writeString(string: String) = writeUTF(this, string)
fun DataOutput.writeStringList(iterable: Iterable<String>) = writeSeq(this, iterable.toList()) { writeString(it) }
fun <T : Any> DataOutput.writeNullable(nullable: T?, writeT: DataOutput.(T) -> Unit) {
writeBoolean(nullable != null)
nullable?.let { writeT(it) }
}
fun <T : Any> DataInput.readNullable(readT: DataInput.() -> T): T? {
val hasValue = readBoolean()
return if (hasValue) readT() else null
}
inline fun <reified T : Any> DataOutputStream.writeObject(obj: T) {
val os = ByteArrayOutputStream()
ObjectOutputStream(os).use { oos ->
oos.writeObject(obj)
}
val bytes = os.toByteArray()
writeInt(bytes.size)
write(bytes)
}
inline fun <reified T : Any> DataInputStream.readObject(): T {
val size = readInt()
val bytes = ByteArray(size)
read(bytes, 0, size)
val bis = ByteArrayInputStream(bytes)
return ObjectInputStream(bis).use { ois ->
ois.readObject() as T
}
}
|
apache-2.0
|
b6ad388b587d0b0a808d1f929a20866a
| 33.928 | 158 | 0.657045 | 4.321782 | false | false | false | false |
jkennethcarino/AnkiEditor
|
app/src/main/java/com/jkcarino/ankieditor/ui/richeditor/InsertLinkDialogFragment.kt
|
1
|
2482
|
/*
* Copyright (C) 2018 Jhon Kenneth Cariño
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jkcarino.ankieditor.ui.richeditor
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.FragmentManager
import com.jkcarino.ankieditor.R
import kotlinx.android.synthetic.main.dialog_insert_link.view.*
class InsertLinkDialogFragment : AppCompatDialogFragment() {
var onInsertClickListener: OnInsertClickListener? = null
override fun show(manager: FragmentManager, tag: String) {
if (manager.findFragmentByTag(tag) == null) {
super.show(manager, tag)
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val view = LayoutInflater.from(context).inflate(R.layout.dialog_insert_link, null)
return AlertDialog.Builder(activity!!).apply {
setTitle(R.string.title_insert_link)
setView(view)
setPositiveButton(R.string.insert) { _, _ ->
val title = view.text_to_display.text.toString().trim()
val url = view.link_to.text.toString().trim()
onInsertClickListener?.onInsertClick(title, url)
}
setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.cancel() }
}.create()
}
interface OnInsertClickListener {
fun onInsertClick(title: String, url: String)
}
companion object {
fun newInstance() = InsertLinkDialogFragment()
}
}
|
gpl-3.0
|
4be99ea20856f6f5a9cc8ae7fe2338d8
| 35.485294 | 92 | 0.708182 | 4.47027 | false | false | false | false |
GunoH/intellij-community
|
platform/diff-impl/src/com/intellij/diff/impl/ui/DiffToolChooser.kt
|
2
|
2585
|
// 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.diff.impl.ui
import com.intellij.diff.DiffTool
import com.intellij.diff.FrameDiffTool
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.dsl.builder.IntelliJSpacingConfiguration
import com.intellij.ui.dsl.builder.components.SegmentedButtonToolbar
import javax.swing.JComponent
@Suppress("DialogTitleCapitalization")
abstract class DiffToolChooser(private val targetComponent: JComponent? = null) : DumbAwareAction(), CustomComponentAction {
private val actions = arrayListOf<MyDiffToolAction>()
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun update(e: AnActionEvent) {
val presentation = e.presentation
val activeTool = getActiveTool()
presentation.text = activeTool.name
if (getForcedDiffTool() != null) {
presentation.isEnabledAndVisible = false
return
}
for (tool in getTools()) {
if (tool !== activeTool) {
presentation.isEnabledAndVisible = true
return
}
}
presentation.isEnabledAndVisible = false
}
override fun actionPerformed(e: AnActionEvent) {
//do nothing
}
abstract fun onSelected(e: AnActionEvent, diffTool: DiffTool)
abstract fun getTools(): List<FrameDiffTool>
abstract fun getActiveTool(): DiffTool
abstract fun getForcedDiffTool(): DiffTool?
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
actions.clear()
for (tool in getTools()) {
actions.add(MyDiffToolAction(tool, tool == getActiveTool()))
}
return SegmentedButtonToolbar(DefaultActionGroup(actions), IntelliJSpacingConfiguration())
.also { it.targetComponent = targetComponent }
}
private inner class MyDiffToolAction(private val diffTool: DiffTool, private var state: Boolean) :
ToggleAction(diffTool.name), DumbAware {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun isSelected(e: AnActionEvent): Boolean = state
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (getActiveTool() === diffTool) return
actions.forEach { action -> action.state = !state }
this.state = state
onSelected(e, diffTool)
}
}
}
|
apache-2.0
|
756fc644a4e388e8f0e8faff5df0e146
| 31.721519 | 158 | 0.747389 | 4.81378 | false | false | false | false |
ktorio/ktor
|
ktor-client/ktor-client-curl/desktop/src/io/ktor/client/engine/curl/Curl.kt
|
1
|
1998
|
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.curl
import io.ktor.client.engine.*
import io.ktor.util.*
import kotlinx.cinterop.*
import libcurl.*
// This function is thread unsafe!
// The man page asks to run it once per program,
// while the program "is still single threaded", explicitly stating that
// it should not called while any other thread is running.
// See the curl_global_init(3) man page for details.
@Suppress("DEPRECATION")
@OptIn(ExperimentalStdlibApi::class)
@EagerInitialization
private val curlGlobalInitReturnCode = curlInitBridge()
internal fun curlInitBridge(): Int = curl_global_init(CURL_GLOBAL_ALL.convert()).convert()
@OptIn(ExperimentalStdlibApi::class)
@Suppress("unused", "DEPRECATION")
@EagerInitialization
private val initHook = Curl
/**
* A Kotlin/Native client engine that can be used on desktop platforms.
*
* To create the client with this engine, pass it to the `HttpClient` constructor:
* ```kotlin
* val client = HttpClient(Curl)
* ```
* To configure the engine, pass settings exposed by [CurlClientEngineConfig] to the `engine` method:
* ```kotlin
* val client = HttpClient(Curl) {
* engine {
* // this: CurlClientEngineConfig
* }
* }
* ```
*
* You can learn more about client engines from [Engines](https://ktor.io/docs/http-client-engines.html).
*/
@OptIn(InternalAPI::class)
public object Curl : HttpClientEngineFactory<CurlClientEngineConfig> {
init {
engines.append(this)
}
override fun create(block: CurlClientEngineConfig.() -> Unit): HttpClientEngine {
@Suppress("DEPRECATION")
if (curlGlobalInitReturnCode != 0) {
throw CurlRuntimeException("curl_global_init() returned non-zero verify: $curlGlobalInitReturnCode")
}
return CurlClientEngine(CurlClientEngineConfig().apply(block))
}
override fun toString(): String = "Curl"
}
|
apache-2.0
|
25dd6c90b40714a1771330eb2939a56b
| 30.714286 | 118 | 0.715215 | 3.98008 | false | true | false | false |
DarrenAtherton49/droid-community-app
|
app/src/main/kotlin/com/darrenatherton/droidcommunity/features/feed/adapter/FeedListAdapter.kt
|
1
|
6000
|
package com.darrenatherton.droidcommunity.features.feed.adapter
import android.os.Parcelable
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.darrenatherton.droidcommunity.R
import com.darrenatherton.droidcommunity.common.injection.scope.PerScreen
import com.darrenatherton.droidcommunity.features.feed.SubscriptionFeedItem
import com.darrenatherton.droidcommunity.features.feed.SubscriptionViewHolder
import com.darrenatherton.droidcommunity.features.feed.SubscriptionViewItem
import kotlinx.android.synthetic.main.item_subscription.view.*
import java.util.*
import javax.inject.Inject
/**
* This class is a RecyclerView adapter whose items also have (nested) RecyclerView adapters. Each
* item in this adapter represents a subscription and the nested (horizontal RecyclerView in that
* subscription represents items which belong to that subscription.
*/
@PerScreen
class FeedListAdapter @Inject constructor() : RecyclerView.Adapter<SubscriptionViewHolder>() {
private var items: List<SubscriptionViewItem> = ArrayList()
private val onItemClickListeners: MutableList<OnItemClickListener> = ArrayList()
// Maps of child RecyclerView adapters and state to restore
private lateinit var childAdapters: HashMap<String, FeedChildAdapter<*, *>> //todo check projection syntax
private lateinit var childAdapterStates: HashMap<String, Parcelable>
init {
setUpChildAdapters(items)
}
//===================================================================================
// Initialization
//===================================================================================
private fun setUpChildAdapters(subscriptions: List<SubscriptionViewItem>) {
childAdapters = HashMap(subscriptions.size)
childAdapterStates = HashMap(subscriptions.size)
// store an adapter for each subscription
subscriptions.forEach {
with(it) {
when (subscription) {
is SubscriptionFeedItem.Reddit -> {
childAdapters.put(subscription.key, FeedRedditChildAdapter())
}
is SubscriptionFeedItem.Twitter -> {
//todo add 'is SubscriptionFeedItem.Twitter
}
}
}
}
}
//===================================================================================
// RecyclerView.Adapter lifecycle/functions
//===================================================================================
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SubscriptionViewHolder {
return when (viewType) {
SubscriptionFeedItem.redditItem -> {
//todo change to use pattern for managing viewholder instead of creating and binding inside viewholder
SubscriptionViewHolder.Reddit.Factory.create(
LayoutInflater.from(parent.context).inflate(R.layout.item_subscription, parent, false))
}
SubscriptionFeedItem.twitter -> {
SubscriptionViewHolder.Twitter(LayoutInflater.from(parent.context).inflate(R.layout.item_subscription, parent, false))
}
else -> {
SubscriptionViewHolder.Simple(LayoutInflater.from(parent.context).inflate(R.layout.item_subscription, parent, false))
}
}
}
override fun onBindViewHolder(holder: SubscriptionViewHolder, position: Int) {
when (holder) {
is SubscriptionViewHolder.Reddit -> {
//todo change to use pattern for managing viewholder instead of creating and binding inside viewholder
val item = getSubscription(position) as SubscriptionFeedItem.Reddit
holder.bind(item, childAdapters[item.key], childAdapterStates[item.key])
}
is SubscriptionViewHolder.Twitter -> holder.bind(getSubscription(position) as SubscriptionFeedItem.Twitter)
}
}
override fun getItemViewType(position: Int) = getSubscription(position).viewType
override fun getItemCount() = items.size
// Cache the scroll position of the session list so that we can restore it when re-binding.
override fun onViewRecycled(holder: SubscriptionViewHolder) {
val position = holder.adapterPosition
if (position != RecyclerView.NO_POSITION) {
val key = getSubscription(position).key
when (holder) {
is SubscriptionViewHolder.Reddit, is SubscriptionViewHolder.Twitter -> {
childAdapterStates.put(key, holder.itemView.childRecyclerView
.layoutManager.onSaveInstanceState())
}
}
}
super.onViewRecycled(holder)
}
internal fun replaceData(newSubscriptions: List<SubscriptionViewItem>) {
items = newSubscriptions
//todo check if changed before executing the code below
setUpChildAdapters(newSubscriptions)
notifyDataSetChanged() //todo change to use DiffUtils
}
private fun getSubscription(position: Int) = items[position].subscription
private fun getSubscriptionChildren(position: Int) = items[position].subscriptionItems
//===================================================================================
// Click listener
//===================================================================================
internal fun addOnItemClickListener(onItemClickListener: OnItemClickListener) {
onItemClickListeners.add(onItemClickListener)
}
private fun notifyOnFeedItemClicked(subscriptionFeedItem: SubscriptionFeedItem) {
onItemClickListeners.forEach { it.onSubscriptionItemClicked(subscriptionFeedItem) }
}
interface OnItemClickListener {
fun onSubscriptionItemClicked(subscriptionFeedItem: SubscriptionFeedItem)
}
}
|
mit
|
546b73944b019602863d5682d28da63c
| 42.80292 | 134 | 0.6345 | 5.976096 | false | false | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonLayoutManager.kt
|
3
|
1844
|
@file:Suppress("PackageDirectoryMismatch")
package androidx.recyclerview.widget
import androidx.recyclerview.widget.RecyclerView.NO_POSITION
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
/**
* Layout manager used by the webtoon viewer. Item prefetch is disabled because the extra layout
* space feature is used which allows setting the image even if the holder is not visible,
* avoiding (in most cases) black views when they are visible.
*
* This layout manager uses the same package name as the support library in order to use a package
* protected method.
*/
class WebtoonLayoutManager(activity: ReaderActivity) : LinearLayoutManager(activity) {
/**
* Extra layout space is set to half the screen height.
*/
private val extraLayoutSpace = activity.resources.displayMetrics.heightPixels / 2
init {
isItemPrefetchEnabled = false
}
/**
* Returns the custom extra layout space.
*/
override fun getExtraLayoutSpace(state: RecyclerView.State): Int {
return extraLayoutSpace
}
/**
* Returns the position of the last item whose end side is visible on screen.
*/
fun findLastEndVisibleItemPosition(): Int {
ensureLayoutState()
@ViewBoundsCheck.ViewBounds val preferredBoundsFlag =
(ViewBoundsCheck.FLAG_CVE_LT_PVE or ViewBoundsCheck.FLAG_CVE_EQ_PVE)
val fromIndex = childCount - 1
val toIndex = -1
val child = if (mOrientation == HORIZONTAL) {
mHorizontalBoundCheck
.findOneViewWithinBoundFlags(fromIndex, toIndex, preferredBoundsFlag, 0)
} else {
mVerticalBoundCheck
.findOneViewWithinBoundFlags(fromIndex, toIndex, preferredBoundsFlag, 0)
}
return if (child == null) NO_POSITION else getPosition(child)
}
}
|
apache-2.0
|
c44179fc0f342a69068feff01a1d1b1f
| 32.527273 | 98 | 0.694685 | 4.680203 | false | false | false | false |
ayatk/biblio
|
app/src/main/kotlin/com/ayatk/biblio/ui/detail/info/InfoFragment.kt
|
1
|
2114
|
/*
* Copyright (c) 2016-2018 ayatk.
*
* 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.ayatk.biblio.ui.detail.info
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.lifecycle.ViewModelProvider
import com.ayatk.biblio.databinding.FragmentInfoBinding
import com.ayatk.biblio.di.ViewModelFactory
import com.ayatk.biblio.model.Novel
import dagger.android.support.DaggerFragment
import javax.inject.Inject
class InfoFragment : DaggerFragment() {
@Inject
lateinit var viewModelFactory: ViewModelFactory
private val viewModel: InfoViewModel by lazy {
ViewModelProvider(this, viewModelFactory).get(InfoViewModel::class.java)
}
private lateinit var binding: FragmentInfoBinding
private val novel: Novel by lazy {
arguments?.getSerializable(BUNDLE_ARGS_NOVEL) as Novel
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.novel = novel
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentInfoBinding.inflate(inflater, container, false)
lifecycle.addObserver(viewModel)
binding.lifecycleOwner = this
binding.viewModel = viewModel
return binding.root
}
companion object {
private const val BUNDLE_ARGS_NOVEL = "NOVEL"
fun newInstance(novel: Novel): InfoFragment =
InfoFragment().apply {
arguments = bundleOf(BUNDLE_ARGS_NOVEL to novel)
}
}
}
|
apache-2.0
|
da1374e1e8e73e78d889dc55a2e3d0a4
| 27.958904 | 76 | 0.753548 | 4.459916 | false | false | false | false |
code-disaster/lwjgl3
|
modules/lwjgl/glfw/src/templates/kotlin/glfw/templates/GLFWNativeWayland.kt
|
4
|
1875
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package glfw.templates
import org.lwjgl.generator.*
import glfw.*
import core.linux.*
val GLFWNativeWayland = "GLFWNativeWayland".nativeClass(Module.GLFW, nativeSubPath = "linux", prefix = "GLFW", binding = GLFW_BINDING_DELEGATE) {
documentation = "Native bindings to the GLFW library's Wayland native access functions."
wl_display.p(
"GetWaylandDisplay",
"""
Returns the {@code struct wl_display*} used by GLFW.
This function may be called from any thread. Access is not synchronized.
""",
returnDoc =
"""
the {@code struct wl_display*} used by GLFW, or #NULL if an error occurred.
Possible errors include #NOT_INITIALIZED.
""",
since = "version 3.2"
)
wl_output.p(
"GetWaylandMonitor",
"""
Returns the {@code struct wl_output*} of the specified monitor.
This function may be called from any thread. Access is not synchronized.
""",
GLFWmonitor.p("monitor", ""),
returnDoc =
"""
the {@code struct wl_output*} of the specified monitor, or #NULL if an error occurred.
Possible errors include #NOT_INITIALIZED.
""",
since = "version 3.2"
)
wl_surface.p(
"GetWaylandWindow",
"""
Returns the main {@code struct wl_surface*} of the specified window.
This function may be called from any thread. Access is not synchronized.
""",
GLFWwindow.p("window", ""),
returnDoc =
"""
the main {@code struct wl_surface*} of the specified window, or #NULL if an error occurred.
Possible errors include #NOT_INITIALIZED.
""",
since = "version 3.2"
)
}
|
bsd-3-clause
|
915e6b56247131de267e311a257fc631
| 26.588235 | 145 | 0.594133 | 4.595588 | false | false | false | false |
mdanielwork/intellij-community
|
java/java-impl/src/com/intellij/codeInspection/javaDoc/JavadocHtmlLintAnnotator.kt
|
5
|
7865
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.javaDoc
import com.intellij.codeInsight.daemon.HighlightDisplayKey
import com.intellij.codeInsight.intention.EmptyIntentionAction
import com.intellij.codeInspection.InspectionsBundle
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.configurations.SimpleJavaParameters
import com.intellij.execution.util.ExecUtil
import com.intellij.lang.annotation.Annotation
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.ExternalAnnotator
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdkVersion
import com.intellij.openapi.projectRoots.JdkUtil
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.ex.JavaSdkUtil
import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.javadoc.PsiDocComment
import com.intellij.psi.util.PsiTreeUtil
import com.sun.tools.doclint.DocLint
import java.io.File
class JavadocHtmlLintAnnotator : ExternalAnnotator<JavadocHtmlLintAnnotator.Info, JavadocHtmlLintAnnotator.Result>() {
data class Info(val file: PsiFile)
data class Anno(val row: Int, val col: Int, val error: Boolean, val message: String)
data class Result(val annotations: List<Anno>)
override fun getPairedBatchInspectionShortName(): String = JavadocHtmlLintInspection.SHORT_NAME
override fun collectInformation(file: PsiFile): Info? =
runReadAction { if (isJava8SourceFile(file) && "/**" in file.text) Info(file) else null }
override fun doAnnotate(collectedInfo: Info): Result? {
val text = runReadAction { if (collectedInfo.file.isValid) collectedInfo.file.text else null }
if (text == null) return null
val file = collectedInfo.file.virtualFile!!
val copy = createTempFile(text.toByteArray(file.charset))
try {
val command = toolCommand(file, collectedInfo.file.project, copy)
val output = ExecUtil.execAndGetOutput(command)
if (output.exitCode != 0) {
val log = Logger.getInstance(JavadocHtmlLintAnnotator::class.java)
if (log.isDebugEnabled) log.debug("${file}: ${output.exitCode}, ${output.stderr}")
return null
}
val annotations = parse(output.stdoutLines)
return if (annotations.isNotEmpty()) Result(annotations) else null
}
catch (e: Exception) {
val log = Logger.getInstance(JavadocHtmlLintAnnotator::class.java)
log.debug(file.path, e)
return null
}
finally {
FileUtil.delete(copy)
}
}
override fun apply(file: PsiFile, annotationResult: Result, holder: AnnotationHolder) {
val text = file.text
val offsets = text.foldIndexed(mutableListOf(0)) { i, offsets, c -> if (c == '\n') offsets += (i + 1); offsets }
for ((row, col, error, message) in annotationResult.annotations) {
if (row < offsets.size) {
val offset = offsets[row] + col
val element = file.findElementAt(offset)
if (element != null && PsiTreeUtil.getParentOfType(element, PsiDocComment::class.java) != null) {
val range = adjust(element, text, offset)
val description = StringUtil.capitalize(message)
val annotation = if (error) holder.createErrorAnnotation(range, description) else holder.createWarningAnnotation(range, description)
registerFix(annotation)
}
}
}
}
//<editor-fold desc="Helpers">
private val key = lazy { HighlightDisplayKey.find(JavadocHtmlLintInspection.SHORT_NAME) }
private val lintOptions = "${DocLint.XMSGS_CUSTOM_PREFIX}html/private,accessibility/private"
private val lintPattern = "^.+:(\\d+):\\s+(error|warning):\\s+(.+)$".toPattern()
private fun isJava8SourceFile(file: PsiFile) =
file.isValid &&
file is PsiJavaFile &&
file.languageLevel.isAtLeast(LanguageLevel.JDK_1_8) &&
file.virtualFile != null &&
ProjectFileIndex.SERVICE.getInstance(file.project).isInSourceContent(file.virtualFile)
private fun createTempFile(bytes: ByteArray): File {
val tempFile = FileUtil.createTempFile(File(PathManager.getTempPath()), "javadocHtmlLint", ".java")
tempFile.writeBytes(bytes)
return tempFile
}
private fun toolCommand(file: VirtualFile, project: Project, copy: File): GeneralCommandLine {
val parameters = SimpleJavaParameters()
val jdk = findJdk(file, project)
parameters.jdk = jdk
if (!JavaSdkUtil.isJdkAtLeast(jdk, JavaSdkVersion.JDK_1_9)) {
val toolsJar = FileUtil.findFirstThatExist("${jdk.homePath}/lib/tools.jar", "${jdk.homePath}/../lib/tools.jar")
if (toolsJar != null) parameters.classPath.add(toolsJar.path)
}
parameters.charset = file.charset
parameters.vmParametersList.addProperty("user.language", "en")
parameters.mainClass = DocLint::class.qualifiedName
parameters.programParametersList.add(lintOptions)
parameters.programParametersList.add(copy.path)
return parameters.toCommandLine()
}
private fun findJdk(file: VirtualFile, project: Project): Sdk {
val rootManager = ProjectRootManager.getInstance(project)
val module = runReadAction { rootManager.fileIndex.getModuleForFile(file) }
if (module != null) {
val sdk = ModuleRootManager.getInstance(module).sdk
if (isJdk8(sdk)) return sdk!!
}
val sdk = rootManager.projectSdk
if (isJdk8(sdk)) return sdk!!
return JavaAwareProjectJdkTableImpl.getInstanceEx().internalJdk
}
private fun isJdk8(sdk: Sdk?) =
sdk != null && JavaSdkUtil.isJdkAtLeast(sdk, JavaSdkVersion.JDK_1_8) && JdkUtil.checkForJre(sdk.homePath!!)
private fun parse(lines: List<String>): List<Anno> {
val result = mutableListOf<Anno>()
val i = lines.iterator()
while (i.hasNext()) {
val line = i.next()
val matcher = lintPattern.matcher(line)
if (matcher.matches() && i.hasNext() && !i.next().isEmpty() && i.hasNext()) {
val row = matcher.group(1).toInt() - 1
val col = i.next().indexOf('^')
val error = matcher.group(2) == "error"
val message = matcher.group(3)
result += Anno(row, col, error, message)
}
}
return result
}
private fun adjust(element: PsiElement, text: String, offset: Int): TextRange {
val range = element.textRange
if (text[offset] == '<') {
val right = text.indexOf('>', offset)
if (right > 0) return TextRange(offset, Integer.min(right + 1, range.endOffset))
}
else if (text[offset] == '&') {
val right = text.indexOf(';', offset)
if (right > 0) return TextRange(offset, Integer.min(right + 1, range.endOffset))
}
else if (text[offset].isLetter() && !text[offset - 1].isLetter()) {
var right = offset + 1
while (text[right].isLetter() && right <= range.endOffset) right++
return TextRange(offset, right)
}
return range
}
private fun registerFix(annotation: Annotation) =
annotation.registerFix(EmptyIntentionAction(InspectionsBundle.message("inspection.javadoc.lint.display.name")), null, key.value)
//</editor-fold>
}
|
apache-2.0
|
25131471077027e114ed6de514fade71
| 39.338462 | 142 | 0.722568 | 4.176845 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeMetaInfo/CodeMetaInfoRenderer.kt
|
4
|
4111
|
// 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.codeMetaInfo
import com.intellij.util.containers.Stack
import org.jetbrains.kotlin.codeMetaInfo.model.CodeMetaInfo
import org.jetbrains.kotlin.idea.codeMetaInfo.CodeMetaInfoParser
import java.io.File
object CodeMetaInfoRenderer {
fun renderTagsToText(codeMetaInfos: List<CodeMetaInfo>, originalText: String): StringBuilder {
return StringBuilder().apply {
renderTagsToText(this, codeMetaInfos, originalText)
}
}
fun renderTagsToText(builder: StringBuilder, codeMetaInfos: List<CodeMetaInfo>, originalText: String) {
if (codeMetaInfos.isEmpty()) {
builder.append(originalText)
return
}
val sortedMetaInfos = getSortedCodeMetaInfos(codeMetaInfos).groupBy { it.start }
val opened = Stack<CodeMetaInfo>()
for ((i, c) in originalText.withIndex()) {
processMetaInfosStartedAtOffset(i, sortedMetaInfos, opened, builder)
builder.append(c)
}
val lastSymbolIsNewLine = builder.last() == '\n'
if (lastSymbolIsNewLine) {
builder.deleteCharAt(builder.length - 1)
}
processMetaInfosStartedAtOffset(originalText.length, sortedMetaInfos, opened, builder)
if (lastSymbolIsNewLine) {
builder.appendLine()
}
}
private fun processMetaInfosStartedAtOffset(
offset: Int,
sortedMetaInfos: Map<Int, List<CodeMetaInfo>>,
opened: Stack<CodeMetaInfo>,
builder: StringBuilder
) {
checkOpenedAndCloseStringIfNeeded(opened, offset, builder)
val matchedCodeMetaInfos = sortedMetaInfos[offset] ?: emptyList()
if (matchedCodeMetaInfos.isNotEmpty()) {
openStartTag(builder)
val iterator = matchedCodeMetaInfos.listIterator()
var current: CodeMetaInfo? = iterator.next()
while (current != null) {
val next: CodeMetaInfo? = if (iterator.hasNext()) iterator.next() else null
opened.push(current)
builder.append(current.asString())
when {
next == null ->
closeStartTag(builder)
next.end == current.end ->
builder.append(", ")
else ->
closeStartAndOpenNewTag(builder)
}
current = next
}
}
// Here we need to handle meta infos which has start == end and close them immediately
checkOpenedAndCloseStringIfNeeded(opened, offset, builder)
}
private val metaInfoComparator =
compareBy<CodeMetaInfo> { it.start }
.thenByDescending { it.end }
.thenBy { it.tag }
.thenBy { it.asString() }
private fun getSortedCodeMetaInfos(metaInfos: Collection<CodeMetaInfo>): List<CodeMetaInfo> {
return metaInfos.sortedWith(metaInfoComparator)
}
private fun closeString(result: StringBuilder) = result.append("<!>")
private fun openStartTag(result: StringBuilder) = result.append("<!")
private fun closeStartTag(result: StringBuilder) = result.append("!>")
private fun closeStartAndOpenNewTag(result: StringBuilder) = result.append("!><!")
private fun checkOpenedAndCloseStringIfNeeded(opened: Stack<CodeMetaInfo>, end: Int, result: StringBuilder) {
var prev: CodeMetaInfo? = null
while (!opened.isEmpty() && end == opened.peek().end) {
if (prev == null || prev.start != opened.peek().start)
closeString(result)
prev = opened.pop()
}
}
}
fun clearFileFromDiagnosticMarkup(file: File) {
val text = file.readText()
val cleanText = clearTextFromDiagnosticMarkup(text)
file.writeText(cleanText)
}
fun clearTextFromDiagnosticMarkup(text: String): String = text.replace(CodeMetaInfoParser.openingOrClosingRegex, "")
|
apache-2.0
|
ef609d8ec3a80cc444969ede76251593
| 39.313725 | 158 | 0.639261 | 4.941106 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveUtils.kt
|
2
|
30993
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.move
import com.intellij.ide.util.DirectoryUtil
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.*
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.move.moveMembers.MoveMemberHandler
import com.intellij.refactoring.move.moveMembers.MoveMembersOptions
import com.intellij.refactoring.move.moveMembers.MoveMembersProcessor
import com.intellij.refactoring.util.MoveRenameUsageInfo
import com.intellij.refactoring.util.NonCodeUsageInfo
import com.intellij.usageView.UsageInfo
import com.intellij.util.IncorrectOperationException
import com.intellij.util.SmartList
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.utils.fqname.isImported
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.codeInsight.shorten.addDelayedImportRequest
import org.jetbrains.kotlin.idea.core.getPackage
import org.jetbrains.kotlin.idea.core.util.toPsiDirectory
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference.ShorteningMode
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.statistics.KotlinMoveRefactoringFUSCollector
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS
import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeAsciiOnly
import org.jetbrains.kotlin.utils.addIfNotNull
import java.io.File
import java.lang.System.currentTimeMillis
import java.util.*
sealed class ContainerInfo {
abstract val fqName: FqName?
abstract fun matches(descriptor: DeclarationDescriptor): Boolean
object UnknownPackage : ContainerInfo() {
override val fqName: FqName? = null
override fun matches(descriptor: DeclarationDescriptor) = descriptor is PackageViewDescriptor
}
class Package(override val fqName: FqName) : ContainerInfo() {
override fun matches(descriptor: DeclarationDescriptor): Boolean {
return descriptor is PackageFragmentDescriptor && descriptor.fqName == fqName
}
override fun equals(other: Any?) = other is Package && other.fqName == fqName
override fun hashCode() = fqName.hashCode()
}
class Class(override val fqName: FqName) : ContainerInfo() {
override fun matches(descriptor: DeclarationDescriptor): Boolean {
return descriptor is ClassDescriptor && descriptor.importableFqName == fqName
}
override fun equals(other: Any?) = other is Class && other.fqName == fqName
override fun hashCode() = fqName.hashCode()
}
}
data class ContainerChangeInfo(val oldContainer: ContainerInfo, val newContainer: ContainerInfo)
fun KtElement.getInternalReferencesToUpdateOnPackageNameChange(containerChangeInfo: ContainerChangeInfo): List<UsageInfo> {
val usages = ArrayList<UsageInfo>()
processInternalReferencesToUpdateOnPackageNameChange(containerChangeInfo) { expr, factory -> usages.addIfNotNull(factory(expr)) }
return usages
}
private typealias UsageInfoFactory = (KtSimpleNameExpression) -> UsageInfo?
fun KtElement.processInternalReferencesToUpdateOnPackageNameChange(
containerChangeInfo: ContainerChangeInfo,
body: (originalRefExpr: KtSimpleNameExpression, usageFactory: UsageInfoFactory) -> Unit
) {
val file = containingFile as? KtFile ?: return
val importPaths = file.importDirectives.mapNotNull { it.importPath }
tailrec fun isImported(descriptor: DeclarationDescriptor): Boolean {
val fqName = DescriptorUtils.getFqName(descriptor).let { if (it.isSafe) it.toSafe() else return@isImported false }
if (importPaths.any { fqName.isImported(it, false) }) return true
return when (val containingDescriptor = descriptor.containingDeclaration) {
is ClassDescriptor, is PackageViewDescriptor -> isImported(containingDescriptor)
else -> false
}
}
fun processReference(refExpr: KtSimpleNameExpression, bindingContext: BindingContext): (UsageInfoFactory)? {
val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, refExpr]?.getImportableDescriptor() ?: return null
val containingDescriptor = descriptor.containingDeclaration ?: return null
val callableKind = (descriptor as? CallableMemberDescriptor)?.kind
if (callableKind != null && callableKind != CallableMemberDescriptor.Kind.DECLARATION) return null
// Special case for enum entry superclass references (they have empty text and don't need to be processed by the refactoring)
if (refExpr.textRange.isEmpty) return null
if (descriptor is ClassDescriptor && descriptor.isInner && refExpr.parent is KtCallExpression) return null
val isCallable = descriptor is CallableDescriptor
val isExtension = isCallable && refExpr.isExtensionRef(bindingContext)
val isCallableReference = isCallableReference(refExpr.mainReference)
val declaration by lazy {
var result = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) ?: return@lazy null
if (descriptor.isCompanionObject() &&
bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, refExpr] !== null
) {
result = (result as? KtObjectDeclaration)?.containingClassOrObject ?: result
}
result
}
if (isCallable) {
if (!isCallableReference) {
if (isExtension && containingDescriptor is ClassDescriptor) {
val dispatchReceiver = refExpr.getResolvedCall(bindingContext)?.dispatchReceiver
val implicitClass = (dispatchReceiver as? ImplicitClassReceiver)?.classDescriptor
if (implicitClass?.isCompanionObject == true) {
return { ImplicitCompanionAsDispatchReceiverUsageInfo(it, implicitClass) }
}
if (dispatchReceiver != null || containingDescriptor.kind != ClassKind.OBJECT) return null
}
}
if (!isExtension) {
val isCompatibleDescriptor = containingDescriptor is PackageFragmentDescriptor ||
containingDescriptor is ClassDescriptor && containingDescriptor.kind == ClassKind.OBJECT ||
descriptor is JavaCallableMemberDescriptor && ((declaration as? PsiMember)?.hasModifierProperty(PsiModifier.STATIC) == true)
if (!isCompatibleDescriptor) return null
}
}
if (!DescriptorUtils.getFqName(descriptor).isSafe) return null
val (oldContainer, newContainer) = containerChangeInfo
val containerFqName = descriptor
.parents
.mapNotNull {
when {
oldContainer.matches(it) -> oldContainer.fqName
newContainer.matches(it) -> newContainer.fqName
else -> null
}
}
.firstOrNull()
val isImported = isImported(descriptor)
if (isImported && this is KtFile) return null
val declarationNotNull = declaration ?: return null
if (isExtension || containerFqName != null || isImported) return {
createMoveUsageInfoIfPossible(it.mainReference, declarationNotNull, addImportToOriginalFile = false, isInternal = true)
}
return null
}
@Suppress("DEPRECATION")
val bindingContext = analyzeWithAllCompilerChecks().bindingContext
forEachDescendantOfType<KtReferenceExpression> { refExpr ->
if (refExpr !is KtSimpleNameExpression || refExpr.parent is KtThisExpression) return@forEachDescendantOfType
processReference(refExpr, bindingContext)?.let { body(refExpr, it) }
}
}
internal var KtSimpleNameExpression.internalUsageInfo: UsageInfo? by CopyablePsiUserDataProperty(Key.create("INTERNAL_USAGE_INFO"))
internal fun markInternalUsages(usages: Collection<UsageInfo>) {
usages.forEach { (it.element as? KtSimpleNameExpression)?.internalUsageInfo = it }
}
internal fun restoreInternalUsages(
scope: KtElement,
oldToNewElementsMapping: Map<PsiElement, PsiElement>,
forcedRestore: Boolean = false
): List<UsageInfo> {
return scope.collectDescendantsOfType<KtSimpleNameExpression>().mapNotNull {
val usageInfo = it.internalUsageInfo
if (!forcedRestore && usageInfo?.element != null) return@mapNotNull usageInfo
val referencedElement = (usageInfo as? MoveRenameUsageInfo)?.referencedElement ?: return@mapNotNull null
val newReferencedElement = mapToNewOrThis(referencedElement, oldToNewElementsMapping)
if (!newReferencedElement.isValid) return@mapNotNull null
(usageInfo as? KotlinMoveUsage)?.refresh(it, newReferencedElement)
}
}
internal fun cleanUpInternalUsages(usages: Collection<UsageInfo>) {
usages.forEach { (it.element as? KtSimpleNameExpression)?.internalUsageInfo = null }
}
class ImplicitCompanionAsDispatchReceiverUsageInfo(
callee: KtSimpleNameExpression,
val companionDescriptor: ClassDescriptor
) : UsageInfo(callee)
interface KotlinMoveUsage {
val isInternal: Boolean
fun refresh(refExpr: KtSimpleNameExpression, referencedElement: PsiElement): UsageInfo?
}
class UnqualifiableMoveRenameUsageInfo(
element: PsiElement,
reference: PsiReference,
referencedElement: PsiElement,
val originalFile: PsiFile,
val addImportToOriginalFile: Boolean,
override val isInternal: Boolean
) : MoveRenameUsageInfo(
element,
reference,
reference.rangeInElement.startOffset,
reference.rangeInElement.endOffset,
referencedElement,
false
), KotlinMoveUsage {
override fun refresh(refExpr: KtSimpleNameExpression, referencedElement: PsiElement): UsageInfo {
return UnqualifiableMoveRenameUsageInfo(
refExpr,
refExpr.mainReference,
referencedElement,
originalFile,
addImportToOriginalFile,
isInternal
)
}
}
class QualifiableMoveRenameUsageInfo(
element: PsiElement,
reference: PsiReference,
referencedElement: PsiElement,
override val isInternal: Boolean
) : MoveRenameUsageInfo(
element,
reference,
reference.rangeInElement.startOffset,
reference.rangeInElement.endOffset,
referencedElement,
false
),
KotlinMoveUsage {
override fun refresh(refExpr: KtSimpleNameExpression, referencedElement: PsiElement): UsageInfo {
return QualifiableMoveRenameUsageInfo(refExpr, refExpr.mainReference, referencedElement, isInternal)
}
}
interface DeferredKotlinMoveUsage : KotlinMoveUsage {
fun resolve(newElement: PsiElement): UsageInfo?
}
class CallableReferenceMoveRenameUsageInfo(
element: PsiElement,
reference: PsiReference,
referencedElement: PsiElement,
val originalFile: PsiFile,
val addImportToOriginalFile: Boolean,
override val isInternal: Boolean
) : MoveRenameUsageInfo(
element,
reference,
reference.rangeInElement.startOffset,
reference.rangeInElement.endOffset,
referencedElement,
false
), DeferredKotlinMoveUsage {
override fun refresh(refExpr: KtSimpleNameExpression, referencedElement: PsiElement): UsageInfo {
return CallableReferenceMoveRenameUsageInfo(
refExpr,
refExpr.mainReference,
referencedElement,
originalFile,
addImportToOriginalFile,
isInternal
)
}
override fun resolve(newElement: PsiElement): UsageInfo? {
val target = newElement.unwrapped
val element = element ?: return null
val reference = reference ?: return null
val referencedElement = referencedElement ?: return null
if (target != null && target.isTopLevelKtOrJavaMember()) {
element.getStrictParentOfType<KtCallableReferenceExpression>()?.receiverExpression?.delete()
return UnqualifiableMoveRenameUsageInfo(
element,
reference,
referencedElement,
element.containingFile!!,
addImportToOriginalFile,
isInternal
)
}
return QualifiableMoveRenameUsageInfo(element, reference, referencedElement, isInternal)
}
}
fun createMoveUsageInfoIfPossible(
reference: PsiReference,
referencedElement: PsiElement,
addImportToOriginalFile: Boolean,
isInternal: Boolean
): UsageInfo? {
val element = reference.element
return when (getReferenceKind(reference, referencedElement)) {
ReferenceKind.QUALIFIABLE -> QualifiableMoveRenameUsageInfo(
element, reference, referencedElement, isInternal
)
ReferenceKind.UNQUALIFIABLE -> UnqualifiableMoveRenameUsageInfo(
element, reference, referencedElement, element.containingFile!!, addImportToOriginalFile, isInternal
)
ReferenceKind.CALLABLE_REFERENCE -> CallableReferenceMoveRenameUsageInfo(
element, reference, referencedElement, element.containingFile!!, addImportToOriginalFile, isInternal
)
else -> null
}
}
private enum class ReferenceKind {
QUALIFIABLE,
UNQUALIFIABLE,
CALLABLE_REFERENCE,
IRRELEVANT
}
private fun KtSimpleNameExpression.isExtensionRef(bindingContext: BindingContext? = null): Boolean {
val resolvedCall = getResolvedCall(bindingContext ?: analyze(BodyResolveMode.PARTIAL)) ?: return false
if (resolvedCall is VariableAsFunctionResolvedCall) {
return resolvedCall.variableCall.candidateDescriptor.isExtension || resolvedCall.functionCall.candidateDescriptor.isExtension
}
return resolvedCall.candidateDescriptor.isExtension
}
private fun getReferenceKind(reference: PsiReference, referencedElement: PsiElement): ReferenceKind {
val target = referencedElement.unwrapped
val element = reference.element as? KtSimpleNameExpression ?: return ReferenceKind.QUALIFIABLE
if (element.getStrictParentOfType<KtSuperExpression>() != null) return ReferenceKind.IRRELEVANT
if (element.isExtensionRef() &&
reference.element.getNonStrictParentOfType<KtImportDirective>() == null
) return ReferenceKind.UNQUALIFIABLE
element.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference }?.let {
val receiverExpression = it.receiverExpression
if (receiverExpression != null) {
val lhs = it.analyze(BodyResolveMode.PARTIAL)[BindingContext.DOUBLE_COLON_LHS, receiverExpression]
return if (lhs is DoubleColonLHS.Type) ReferenceKind.CALLABLE_REFERENCE else ReferenceKind.IRRELEVANT
}
if (target is KtDeclaration && target.parent is KtFile) return ReferenceKind.UNQUALIFIABLE
if (target is PsiMember && target.containingClass == null) return ReferenceKind.UNQUALIFIABLE
}
return ReferenceKind.QUALIFIABLE
}
private fun isCallableReference(reference: PsiReference): Boolean {
return reference is KtSimpleNameReference
&& reference.element.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference } != null
}
fun guessNewFileName(declarationsToMove: Collection<KtNamedDeclaration>): String? {
if (declarationsToMove.isEmpty()) return null
val representative = declarationsToMove.singleOrNull()
?: declarationsToMove.filterIsInstance<KtClassOrObject>().singleOrNull()
val newFileName = representative?.run {
if (containingKtFile.isScript()) "$name.kts" else "$name.${KotlinFileType.EXTENSION}"
} ?: declarationsToMove.first().containingFile.name
return newFileName.capitalizeAsciiOnly()
}
// returns true if successful
private fun updateJavaReference(reference: PsiReferenceExpression, oldElement: PsiElement, newElement: PsiElement): Boolean {
if (oldElement is PsiMember && newElement is PsiMember) {
// Remove import of old package facade, if any
val oldClassName = oldElement.containingClass?.qualifiedName
if (oldClassName != null) {
val importOfOldClass = (reference.containingFile as? PsiJavaFile)?.importList?.allImportStatements?.firstOrNull {
when (it) {
is PsiImportStatement -> it.qualifiedName == oldClassName
is PsiImportStaticStatement -> it.isOnDemand && it.importReference?.canonicalText == oldClassName
else -> false
}
}
if (importOfOldClass != null && importOfOldClass.resolve() == null) {
importOfOldClass.delete()
}
}
val newClass = newElement.containingClass
if (newClass != null && reference.qualifierExpression != null) {
val refactoringOptions = object : MoveMembersOptions {
override fun getMemberVisibility(): String = PsiModifier.PUBLIC
override fun makeEnumConstant(): Boolean = true
override fun getSelectedMembers(): Array<PsiMember> = arrayOf(newElement)
override fun getTargetClassName(): String? = newClass.qualifiedName
}
val moveMembersUsageInfo = MoveMembersProcessor.MoveMembersUsageInfo(
newElement, reference.element, newClass, reference.qualifierExpression, reference
)
val moveMemberHandler = MoveMemberHandler.EP_NAME.forLanguage(reference.element.language)
if (moveMemberHandler != null) {
moveMemberHandler.changeExternalUsage(refactoringOptions, moveMembersUsageInfo)
return true
}
}
}
return false
}
internal fun mapToNewOrThis(e: PsiElement, oldToNewElementsMapping: Map<PsiElement, PsiElement>) = oldToNewElementsMapping[e] ?: e
private fun postProcessMoveUsage(
usage: UsageInfo,
oldToNewElementsMapping: Map<PsiElement, PsiElement>,
nonCodeUsages: ArrayList<NonCodeUsageInfo>,
shorteningMode: ShorteningMode
) {
if (usage is NonCodeUsageInfo) {
nonCodeUsages.add(usage)
return
}
if (usage !is MoveRenameUsageInfo) return
val oldElement = usage.referencedElement!!
val newElement = mapToNewOrThis(oldElement, oldToNewElementsMapping)
when (usage) {
is DeferredKotlinMoveUsage -> {
val newUsage = usage.resolve(newElement) ?: return
postProcessMoveUsage(newUsage, oldToNewElementsMapping, nonCodeUsages, shorteningMode)
}
is UnqualifiableMoveRenameUsageInfo -> {
val file = with(usage) {
if (addImportToOriginalFile) originalFile else mapToNewOrThis(
originalFile,
oldToNewElementsMapping
)
} as KtFile
addDelayedImportRequest(newElement, file)
}
else -> {
val reference = (usage.element as? KtSimpleNameExpression)?.mainReference ?: usage.reference
processReference(reference, newElement, shorteningMode, oldElement)
}
}
}
private fun processReference(reference: PsiReference?, newElement: PsiElement, shorteningMode: ShorteningMode, oldElement: PsiElement) {
try {
when {
reference is KtSimpleNameReference -> reference.bindToElement(newElement, shorteningMode)
reference is PsiReferenceExpression && updateJavaReference(reference, oldElement, newElement) -> return
else -> reference?.bindToElement(newElement)
}
} catch (e: IncorrectOperationException) {
// Suppress exception if bindToElement is not implemented
}
}
/**
* Perform usage postprocessing and return non-code usages
*/
fun postProcessMoveUsages(
usages: Collection<UsageInfo>,
oldToNewElementsMapping: Map<PsiElement, PsiElement> = Collections.emptyMap(),
shorteningMode: ShorteningMode = ShorteningMode.DELAYED_SHORTENING
): List<NonCodeUsageInfo> {
val sortedUsages = usages.sortedWith(
Comparator { o1, o2 ->
val file1 = o1.virtualFile
val file2 = o2.virtualFile
if (Comparing.equal(file1, file2)) {
val rangeInElement1 = o1.rangeInElement
val rangeInElement2 = o2.rangeInElement
if (rangeInElement1 != null && rangeInElement2 != null) {
return@Comparator rangeInElement2.startOffset - rangeInElement1.startOffset
}
return@Comparator 0
}
if (file1 == null) return@Comparator -1
if (file2 == null) return@Comparator 1
Comparing.compare(file1.path, file2.path)
}
)
val nonCodeUsages = ArrayList<NonCodeUsageInfo>()
val progressStep = 1.0 / sortedUsages.size
val progressIndicator = ProgressManager.getInstance().progressIndicator
progressIndicator?.isIndeterminate = false
progressIndicator?.text = KotlinBundle.message("text.updating.usages.progress")
usageLoop@ for ((i, usage) in sortedUsages.withIndex()) {
progressIndicator?.fraction = (i + 1) * progressStep
postProcessMoveUsage(usage, oldToNewElementsMapping, nonCodeUsages, shorteningMode)
}
progressIndicator?.text = ""
return nonCodeUsages
}
var KtFile.updatePackageDirective: Boolean? by UserDataProperty(Key.create("UPDATE_PACKAGE_DIRECTIVE"))
sealed class OuterInstanceReferenceUsageInfo(element: PsiElement, private val isIndirectOuter: Boolean) : UsageInfo(element) {
open fun reportConflictIfAny(conflicts: MultiMap<PsiElement, String>): Boolean {
val element = element ?: return false
if (isIndirectOuter) {
conflicts.putValue(element, KotlinBundle.message("text.indirect.outer.instances.will.not.be.extracted.0", element.text))
return true
}
return false
}
class ExplicitThis(
expression: KtThisExpression,
isIndirectOuter: Boolean
) : OuterInstanceReferenceUsageInfo(expression, isIndirectOuter) {
val expression: KtThisExpression?
get() = element as? KtThisExpression
}
class ImplicitReceiver(
callElement: KtElement,
isIndirectOuter: Boolean,
private val isDoubleReceiver: Boolean
) : OuterInstanceReferenceUsageInfo(callElement, isIndirectOuter) {
val callElement: KtElement?
get() = element as? KtElement
override fun reportConflictIfAny(conflicts: MultiMap<PsiElement, String>): Boolean {
if (super.reportConflictIfAny(conflicts)) return true
val fullCall = callElement?.let { it.getQualifiedExpressionForSelector() ?: it } ?: return false
return when {
fullCall is KtQualifiedExpression -> {
conflicts.putValue(fullCall, KotlinBundle.message("text.qualified.call.will.not.be.processed.0", fullCall.text))
true
}
isDoubleReceiver -> {
conflicts.putValue(fullCall, KotlinBundle.message("text.member.extension.call.will.not.be.processed.0", fullCall.text))
true
}
else -> false
}
}
}
}
@JvmOverloads
fun traverseOuterInstanceReferences(
member: KtNamedDeclaration,
stopAtFirst: Boolean,
body: (OuterInstanceReferenceUsageInfo) -> Unit = {}
): Boolean {
if (member is KtObjectDeclaration || member is KtClass && !member.isInner()) return false
val context = member.analyzeWithContent()
val containingClassOrObject = member.containingClassOrObject ?: return false
val outerClassDescriptor = containingClassOrObject.unsafeResolveToDescriptor() as ClassDescriptor
var found = false
member.accept(
object : PsiRecursiveElementWalkingVisitor() {
private fun getOuterInstanceReference(element: PsiElement): OuterInstanceReferenceUsageInfo? {
return when (element) {
is KtThisExpression -> {
val descriptor = context[BindingContext.REFERENCE_TARGET, element.instanceReference]
val isIndirect = when {
descriptor == outerClassDescriptor -> false
descriptor?.isAncestorOf(outerClassDescriptor, true) ?: false -> true
else -> return null
}
OuterInstanceReferenceUsageInfo.ExplicitThis(element, isIndirect)
}
is KtSimpleNameExpression -> {
val resolvedCall = element.getResolvedCall(context) ?: return null
val dispatchReceiver = resolvedCall.dispatchReceiver as? ImplicitReceiver
val extensionReceiver = resolvedCall.extensionReceiver as? ImplicitReceiver
var isIndirect = false
val isDoubleReceiver = when (outerClassDescriptor) {
dispatchReceiver?.declarationDescriptor -> extensionReceiver != null
extensionReceiver?.declarationDescriptor -> dispatchReceiver != null
else -> {
isIndirect = true
when {
dispatchReceiver?.declarationDescriptor?.isAncestorOf(outerClassDescriptor, true) ?: false ->
extensionReceiver != null
extensionReceiver?.declarationDescriptor?.isAncestorOf(outerClassDescriptor, true) ?: false ->
dispatchReceiver != null
else -> return null
}
}
}
OuterInstanceReferenceUsageInfo.ImplicitReceiver(resolvedCall.call.callElement, isIndirect, isDoubleReceiver)
}
else -> null
}
}
override fun visitElement(element: PsiElement) {
getOuterInstanceReference(element)?.let {
body(it)
found = true
if (stopAtFirst) stopWalking()
return
}
super.visitElement(element)
}
}
)
return found
}
fun collectOuterInstanceReferences(member: KtNamedDeclaration): List<OuterInstanceReferenceUsageInfo> {
val result = SmartList<OuterInstanceReferenceUsageInfo>()
traverseOuterInstanceReferences(member, false) { result += it }
return result
}
@Throws(IncorrectOperationException::class)
internal fun getOrCreateDirectory(path: String, project: Project): PsiDirectory {
File(path).toPsiDirectory(project)?.let { return it }
return project.executeCommand(RefactoringBundle.message("move.title"), null) {
runWriteAction {
val fixUpSeparators = path.replace(File.separatorChar, '/')
DirectoryUtil.mkdirs(PsiManager.getInstance(project), fixUpSeparators)
}
}
}
internal fun getTargetPackageFqName(targetContainer: PsiElement): FqName? {
if (targetContainer is PsiDirectory) {
val targetPackage = targetContainer.getPackage()
return if (targetPackage != null) FqName(targetPackage.qualifiedName) else null
}
return if (targetContainer is KtFile) targetContainer.packageFqName else null
}
internal fun logFusForMoveRefactoring(
numberOfEntities: Int,
entity: KotlinMoveRefactoringFUSCollector.MovedEntity,
destination: KotlinMoveRefactoringFUSCollector.MoveRefactoringDestination,
isDefault: Boolean,
body: Runnable
) {
val timeStarted = currentTimeMillis()
var succeeded = false
try {
body.run()
succeeded = true
} finally {
KotlinMoveRefactoringFUSCollector.log(
timeStarted = timeStarted,
timeFinished = currentTimeMillis(),
numberOfEntities = numberOfEntities,
destination = destination,
isDefault = isDefault,
entity = entity,
isSucceeded = succeeded,
)
}
}
internal fun <T> List<KtNamedDeclaration>.mapWithReadActionInProcess(
project: Project,
@NlsContexts.DialogTitle title: String,
body: (KtNamedDeclaration) -> T
): List<T> = let { declarations ->
val result = mutableListOf<T>()
val task: Task.Modal = object : Task.Modal(project, title, false) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = false
val fraction: Double = 1.0 / declarations.size
indicator.fraction = 0.0
runReadAction {
declarations.forEachIndexed { index, declaration ->
result.add(body(declaration))
indicator.fraction = fraction * index
}
}
}
}
ProgressManager.getInstance().run(task)
return result
}
|
apache-2.0
|
2891d3a5b58bb32ba1718f1dc3ebf1a6
| 41.110054 | 148 | 0.691479 | 5.598447 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/HighlightingWatcher.kt
|
6
|
3421
|
// 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.analysis.problemsView.toolWindow
import com.intellij.analysis.problemsView.Problem
import com.intellij.analysis.problemsView.ProblemsListener
import com.intellij.analysis.problemsView.ProblemsProvider
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.ex.MarkupModelEx
import com.intellij.openapi.editor.ex.RangeHighlighterEx
import com.intellij.openapi.editor.impl.DocumentMarkupModel.forDocument
import com.intellij.openapi.editor.impl.event.MarkupModelListener
import com.intellij.openapi.vfs.VirtualFile
import java.lang.ref.WeakReference
internal class HighlightingWatcher(
private val provider: ProblemsProvider,
private val listener: ProblemsListener,
private val file: VirtualFile,
private val level: Int)
: MarkupModelListener, Disposable {
private val problems = mutableMapOf<RangeHighlighterEx, Problem>()
private var reference: WeakReference<MarkupModelEx>? = null
init {
ApplicationManager.getApplication().runReadAction { update() }
}
override fun dispose() {
synchronized(problems) {
val list = problems.values.toList()
problems.clear()
list
}.forEach { listener.problemDisappeared(it) }
}
override fun afterAdded(highlighter: RangeHighlighterEx) {
getProblem(highlighter)?.let { listener.problemAppeared(it) }
}
override fun beforeRemoved(highlighter: RangeHighlighterEx) {
getProblem(highlighter)?.let { listener.problemDisappeared(it) }
}
override fun attributesChanged(highlighter: RangeHighlighterEx, renderersChanged: Boolean, fontStyleOrColorChanged: Boolean) {
findProblem(highlighter)?.let { listener.problemUpdated(it) }
}
fun update() {
val model = reference?.get() ?: getMarkupModel() ?: return
val highlighters = arrayListOf<RangeHighlighterEx>()
model.processRangeHighlightersOverlappingWith(0, model.document.textLength) { highlighter: RangeHighlighterEx ->
highlighters.add(highlighter)
true
}
highlighters.forEach { afterAdded(it) }
}
fun getProblems(): Collection<Problem> = synchronized(problems) { problems.values.toList() }
fun findProblem(highlighter: RangeHighlighterEx) = synchronized(problems) { problems[highlighter] }
private fun getHighlightingProblem(highlighter: RangeHighlighterEx): HighlightingProblem
= HighlightingProblem(provider, file, highlighter)
private fun getProblem(highlighter: RangeHighlighterEx) = when {
!isValid(highlighter) -> null
else -> synchronized(problems) {
problems.computeIfAbsent(highlighter) { getHighlightingProblem(highlighter) }
}
}
private fun isValid(highlighter: RangeHighlighterEx): Boolean {
val info = highlighter.errorStripeTooltip as? HighlightInfo ?: return false
return info.description != null && info.severity.myVal >= level
}
private fun getMarkupModel(): MarkupModelEx? {
val document = ProblemsView.getDocument(provider.project, file) ?: return null
val model = forDocument(document, provider.project, true) as? MarkupModelEx ?: return null
model.addMarkupModelListener(this, this)
reference = WeakReference(model)
return model
}
}
|
apache-2.0
|
b18738c74d4b3a7c110653fcaed817ae
| 38.321839 | 140 | 0.77112 | 4.673497 | false | false | false | false |
DreierF/MyTargets
|
app/src/main/java/de/dreier/mytargets/features/settings/backup/synchronization/GenericAccountService.kt
|
1
|
3650
|
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.features.settings.backup.synchronization
import android.accounts.AbstractAccountAuthenticator
import android.accounts.Account
import android.accounts.AccountAuthenticatorResponse
import android.accounts.NetworkErrorException
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.IBinder
import timber.log.Timber
class GenericAccountService : Service() {
private var mAuthenticator: Authenticator? = null
override fun onCreate() {
Timber.i("Service created")
mAuthenticator = Authenticator(this)
}
override fun onDestroy() {
Timber.i("Service destroyed")
}
override fun onBind(intent: Intent): IBinder? {
return mAuthenticator!!.iBinder
}
inner class Authenticator(context: Context) : AbstractAccountAuthenticator(context) {
override fun editProperties(
accountAuthenticatorResponse: AccountAuthenticatorResponse,
s: String
): Bundle {
throw UnsupportedOperationException()
}
@Throws(NetworkErrorException::class)
override fun addAccount(
accountAuthenticatorResponse: AccountAuthenticatorResponse,
s: String, s2: String, strings: Array<String>, bundle: Bundle
): Bundle? {
return null
}
@Throws(NetworkErrorException::class)
override fun confirmCredentials(
accountAuthenticatorResponse: AccountAuthenticatorResponse,
account: Account, bundle: Bundle
): Bundle? {
return null
}
@Throws(NetworkErrorException::class)
override fun getAuthToken(
accountAuthenticatorResponse: AccountAuthenticatorResponse,
account: Account, s: String, bundle: Bundle
): Bundle {
throw UnsupportedOperationException()
}
override fun getAuthTokenLabel(s: String): String {
throw UnsupportedOperationException()
}
@Throws(NetworkErrorException::class)
override fun updateCredentials(
accountAuthenticatorResponse: AccountAuthenticatorResponse,
account: Account, s: String, bundle: Bundle
): Bundle {
throw UnsupportedOperationException()
}
@Throws(NetworkErrorException::class)
override fun hasFeatures(
accountAuthenticatorResponse: AccountAuthenticatorResponse,
account: Account, strings: Array<String>
): Bundle {
throw UnsupportedOperationException()
}
}
companion object {
private const val ACCOUNT_NAME = "MyTargets"
private const val ACCOUNT_TYPE = "mytargets.dreier.de"
/**
* Obtain a handle to the [Account] used for sync in this application.
*
* @return Handle to application's account (not guaranteed to resolve unless createSyncAccount()
* has been called)
*/
val account: Account
get() = Account(ACCOUNT_NAME, ACCOUNT_TYPE)
}
}
|
gpl-2.0
|
4c9ca1d28bb53d40189584316a304311
| 30.73913 | 104 | 0.670959 | 5.58104 | false | false | false | false |
freedombox/android-app
|
app/src/test/java/org/freedombox/freedombox/utils/storage/SharedPreferenceTest.kt
|
1
|
2504
|
/*
* This file is part of FreedomBox.
*
* FreedomBox 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.
*
* FreedomBox 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 FreedomBox. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freedombox.freedombox.utils.storage
import android.content.Context
import android.content.SharedPreferences
import org.freedombox.freedombox.BuildConfig
import org.freedombox.freedombox.views.model.ConfigModel
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(constants = BuildConfig::class)
class SharedPreferenceTest {
private val preferenceName = "PrefTest"
private val key = "preference"
private val value = "success"
private lateinit var sharedPreference: SharedPreferences
@Before
fun setup() {
sharedPreference = RuntimeEnvironment.application
.getSharedPreferences(preferenceName, Context.MODE_PRIVATE)
}
private fun putKeyAndValueIntoSharedPreference() {
val edit = sharedPreference.edit()
edit.putString(key, value)
edit.commit()
}
@Test
fun shouldReturnNullWhenKeyNotExist() {
putKeyAndValueIntoSharedPreference()
val returnString = getSharedPreference(sharedPreference, "not_found")
Assert.assertEquals(null, returnString)
}
@Test
fun shouldReturnValueWhenKeyExist() {
putKeyAndValueIntoSharedPreference()
val returnString = getSharedPreference(sharedPreference, key)
Assert.assertEquals(value, returnString)
}
@Test
fun shouldPutKeyAndValueIntoSharedPreference() {
val configModelList = listOf<ConfigModel>()
putSharedPreference(sharedPreference, key, configModelList)
val storedValue = sharedPreference.getString(key, null)
Assert.assertNotNull(storedValue)
}
}
|
gpl-3.0
|
06b5b9964ccfb0d95e2d627a6a9480ef
| 32.837838 | 77 | 0.746006 | 4.503597 | false | true | false | false |
neilellis/kontrol
|
api/src/main/kotlin/kontrol/api/Monitorable.kt
|
1
|
1421
|
/*
* Copyright 2014 Cazcade Limited (http://cazcade.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kontrol.api
/**
* @todo document.
* @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a>
*/
public trait Monitorable<E : Enum<E>> {
var disableAction: ((in Monitorable<E>) -> Unit)?;
var enableAction: ((in Monitorable<E>) -> Unit)?;
fun state(): E?
fun transition(state: E?)
var enabled: Boolean
fun name(): String
fun id(): String
fun groupName(): String
fun disabled(): Boolean {
return !enabled
}
fun enabled(): Boolean {
return enabled
}
fun disable() {
enabled = false;
if (disableAction != null) {
disableAction!!(this)
};
}
fun enable() {
enabled = true;
if (enableAction != null) {
enableAction!!(this)
};
}
}
|
apache-2.0
|
093b1445ebd78d9343e6369eaa7712b5
| 25.830189 | 75 | 0.626319 | 4.036932 | false | false | false | false |
Virtlink/aesi
|
pie/src/main/kotlin/com/virtlink/pie/BuildManagerProviderImpl.kt
|
1
|
2300
|
package com.virtlink.pie
import com.google.inject.Inject
import com.google.inject.Provider
import com.virtlink.dummy.DummyCodeCompletionBuilder
import mb.pie.runtime.core.BuildCache
import mb.pie.runtime.core.BuildManager
import mb.pie.runtime.core.BuildManagerFactory
import mb.pie.runtime.core.BuildStore
import mb.pie.runtime.core.impl.store.InMemoryBuildStore
import mb.pie.runtime.core.impl.store.LMDBBuildStoreFactory
import mb.vfs.path.PathSrv
import org.slf4j.LoggerFactory
import java.io.File
import java.net.URI
import java.util.concurrent.ConcurrentHashMap
class BuildManagerProviderImpl @Inject constructor(
private val pathSrv: PathSrv,
private val buildManagerFactory: BuildManagerFactory,
private val storeFactory: LMDBBuildStoreFactory,
private val cacheFactory: Provider<BuildCache>)
: IBuildManagerProvider {
private val logger = LoggerFactory.getLogger(DummyCodeCompletionBuilder::class.java)
private val buildManagers = ConcurrentHashMap<URI, BuildManager>()
override fun getBuildManager(projectUri: URI): BuildManager {
return this.buildManagers.getOrPut(projectUri) {
val store = createStore(projectUri)
val cache = this.cacheFactory.get()
this.buildManagerFactory.create(store, cache)
}
}
private fun createStore(projectUri: URI): BuildStore {
val localStoreDir = getLocalStoreDir(projectUri)
val store: BuildStore
if (localStoreDir != null) {
store = this.storeFactory.create(localStoreDir)
logger.debug("Created PIE LMDB store at $localStoreDir for project $projectUri.")
} else {
store = InMemoryBuildStore()
logger.warn("Could not create PIE LMDB store for project $projectUri because it is not on the local filesystem. Using an in-memory store instead.")
}
return store
}
private fun getLocalStoreDir(projectUri: URI): File? {
return try {
val projectRootDir = this.pathSrv.resolve(projectUri)
val storeDir = projectRootDir.resolve(".pie")
this.pathSrv.localPath(storeDir)
} catch (_: RuntimeException) {
// `projectUri` is not a local file system URI.
null
}
}
}
|
apache-2.0
|
a485a262b677f1cc5ba21bf88fed81fe
| 36.704918 | 159 | 0.706957 | 4.423077 | false | false | false | false |
camunda/camunda-process-test-coverage
|
extension/spring-test-platform-7/src/main/kotlin/org/camunda/community/process_test_coverage/spring_test/platform7/ProcessEngineCoverageProperties.kt
|
1
|
4903
|
package org.camunda.community.process_test_coverage.spring_test.platform7
import org.assertj.core.api.Condition
data class ProcessEngineCoverageProperties(
/**
* Log class and test method coverages?
*/
val detailedCoverageLogging: Boolean = false,
/**
* Is method coverage handling needed?
*/
val handleTestMethodCoverage: Boolean = true,
/**
* A list of process definition keys excluded from the test run.
*/
val excludedProcessDefinitionKeys: List<String> = listOf(),
/**
* Conditions to be asserted on the class coverage percentage.
*/
val classCoverageAssertionConditions: List<Condition<Double>> = listOf(),
/**
* Conditions to be asserted on the individual test method coverages.
*/
val testMethodCoverageConditions: Map<String, List<Condition<Double>>> = mapOf()
) {
companion object {
@JvmStatic
fun builder() = Builder()
}
class Builder {
companion object {
/**
* If you set this property to a ratio (e.g. "1.0" for full coverage),
* the Extension will fail the test run if the coverage is less.<br></br>
* Example parameter for running java:<br></br>
* `-Dorg.camunda.community.process_test_coverage.ASSERT_AT_LEAST=1.0`
*/
const val DEFAULT_ASSERT_AT_LEAST_PROPERTY = "org.camunda.community.process_test_coverage.ASSERT_AT_LEAST"
}
private var detailedCoverageLogging: Boolean = false
private var handleTestMethodCoverage: Boolean = true
private var excludedProcessDefinitionKeys: List<String> = listOf()
private var coverageAtLeast: Double? = null
private var optionalAssertCoverageAtLeastProperty: String = DEFAULT_ASSERT_AT_LEAST_PROPERTY
private var testMethodCoverageConditions: MutableMap<String, MutableList<Condition<Double>>> = mutableMapOf()
/**
* Log class and test method coverages?
*/
fun withDetailedCoverageLogging() = apply { this.detailedCoverageLogging = true }
/**
* Is method coverage handling needed?
*/
fun handleTestMethodCoverage(handleTestMethodCoverage: Boolean) = apply { this.handleTestMethodCoverage = handleTestMethodCoverage }
/**
* Asserts if the class coverage is greater than the percentage.
*/
fun assertClassCoverageAtLeast(coverageAtLeast: Double) = apply { this.coverageAtLeast = coverageAtLeast }
/**
* A list of process definition keys excluded from the test run.
*/
fun excludeProcessDefinitionKeys(vararg processDefinitionKeys: String) = apply { this.excludedProcessDefinitionKeys = processDefinitionKeys.toList() }
/**
* Specifies the key of the system property for optionally reading a minimal assertion coverage.
*/
fun optionalAssertCoverageAtLeastProperty(property: String) = apply { this.optionalAssertCoverageAtLeastProperty = property }
/**
* Add a condition to be asserted on the individual test method coverages.
*/
fun addTestMethodCoverageCondition(methodName: String, condition: Condition<Double>) =
apply { this.testMethodCoverageConditions.getOrPut(methodName) { mutableListOf() }.add(condition) }
fun build(): ProcessEngineCoverageProperties {
val classCoverageConditions: MutableList<Condition<Double>> = mutableListOf()
coverageAtLeast?.let { classCoverageConditions.add(buildClassCoverageCondition(it)) }
readCoverageFromSystemProperty()?.let { classCoverageConditions.add(buildClassCoverageCondition(it)) }
return ProcessEngineCoverageProperties(
detailedCoverageLogging = detailedCoverageLogging,
handleTestMethodCoverage = handleTestMethodCoverage,
excludedProcessDefinitionKeys = excludedProcessDefinitionKeys,
classCoverageAssertionConditions = classCoverageConditions,
testMethodCoverageConditions = testMethodCoverageConditions
)
}
private fun buildClassCoverageCondition(percentage: Double): Condition<Double> {
require(percentage in 0.0..1.0) { "Not a valid percentage: $percentage (${percentage * 100}%)" }
return Condition<Double>({ p -> p >= percentage }, "matches if the coverage ratio is at least $percentage")
}
private fun readCoverageFromSystemProperty(): Double? {
try {
return System.getProperty(optionalAssertCoverageAtLeastProperty)?.toDouble()
} catch (e: NumberFormatException) {
throw IllegalArgumentException("System property \"$optionalAssertCoverageAtLeastProperty\" is not a number")
}
}
}
}
|
apache-2.0
|
8165246b6b7562ef8b394384f85a162b
| 43.18018 | 158 | 0.666123 | 5.227079 | false | true | false | false |
JetBrains/intellij-community
|
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/roots/GradleBuildRootsManager.kt
|
1
|
19074
|
// 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.gradleJava.scripting.roots
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import com.intellij.ui.EditorNotifications
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.jetbrains.kotlin.idea.caches.trackers.KotlinCodeBlockModificationListener
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.configuration.DefaultScriptingSupport
import org.jetbrains.kotlin.idea.core.script.configuration.ScriptingSupport
import org.jetbrains.kotlin.idea.core.script.scriptingDebugLog
import org.jetbrains.kotlin.idea.core.script.scriptingErrorLog
import org.jetbrains.kotlin.idea.core.script.scriptingInfoLog
import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsBuilder
import org.jetbrains.kotlin.idea.core.util.EDT
import org.jetbrains.kotlin.idea.gradle.scripting.LastModifiedFiles
import org.jetbrains.kotlin.idea.gradleJava.scripting.*
import org.jetbrains.kotlin.idea.gradleJava.scripting.importing.KotlinDslGradleBuildSync
import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRoot.ImportingStatus.*
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.plugins.gradle.config.GradleSettingsListenerAdapter
import org.jetbrains.plugins.gradle.service.GradleInstallationManager
import org.jetbrains.plugins.gradle.settings.DistributionType
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.settings.GradleSettingsListener
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.BasicFileAttributes
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicBoolean
/**
* [GradleBuildRoot] is a linked gradle build (don't confuse with gradle project and included build).
* Each [GradleBuildRoot] may have it's own Gradle version, Java home and other settings.
*
* Typically, IntelliJ project have no more than one [GradleBuildRoot].
*
* This manager allows to find related Gradle build by the Gradle Kotlin script file path.
* Each imported build have info about all of it's Kotlin Build Scripts.
* It is populated by calling [update], stored in FS and will be loaded from FS on next project opening
*
* [CompositeScriptConfigurationManager] may ask about known scripts by calling [collectConfigurations].
*
* It also used to show related notification and floating actions depending on root kind, state and script state itself.
*
* Roots may be:
* - [GradleBuildRoot] - Linked project, that may be itself:
* - [Legacy] - Gradle build with old Gradle version (<6.0)
* - [New] - not yet imported
* - [Imported] - imported
*/
class GradleBuildRootsManager(val project: Project) : GradleBuildRootsLocator(project), ScriptingSupport {
private val manager: CompositeScriptConfigurationManager
get() = ScriptConfigurationManager.getInstance(project) as CompositeScriptConfigurationManager
private val updater
get() = manager.updater
var enabled: Boolean = true
set(value) {
if (value != field) {
field = value
roots.list.toList().forEach {
reloadBuildRoot(it.pathPrefix, null)
}
}
}
////////////
/// ScriptingSupport.Provider implementation:
override fun isApplicable(file: VirtualFile): Boolean {
val scriptUnderRoot = findScriptBuildRoot(file) ?: return false
if (scriptUnderRoot.nearest is Legacy) return false
if (roots.isStandaloneScript(file.path)) return false
return true
}
override fun isConfigurationLoadingInProgress(file: KtFile): Boolean {
return findScriptBuildRoot(file.originalFile.virtualFile)?.nearest?.isImportingInProgress() ?: return false
}
fun isConfigurationOutOfDate(file: VirtualFile): Boolean {
val script = getScriptInfo(file) ?: return false
if (script.buildRoot.isImportingInProgress()) return false
return !script.model.inputs.isUpToDate(project, file)
}
override fun collectConfigurations(builder: ScriptClassRootsBuilder) {
roots.list.forEach { root ->
if (root is Imported) {
root.collectConfigurations(builder)
}
}
}
override fun afterUpdate() {
roots.list.forEach { root ->
if (root.importing.compareAndSet(updatingCaches, updated)) {
updateNotifications { it.startsWith(root.pathPrefix) }
}
}
}
//////////////////
override fun getScriptInfo(localPath: String): GradleScriptInfo? =
manager.getLightScriptInfo(localPath) as? GradleScriptInfo
override fun getScriptFirstSeenTs(path: String): Long {
val nioPath = FileSystems.getDefault().getPath(path)
return Files.readAttributes(nioPath, BasicFileAttributes::class.java)
?.creationTime()?.toMillis()
?: Long.MAX_VALUE
}
fun fileChanged(filePath: String, ts: Long = System.currentTimeMillis()) {
findAffectedFileRoot(filePath)?.fileChanged(filePath, ts)
scheduleModifiedFilesCheck(filePath)
}
fun markImportingInProgress(workingDir: String, inProgress: Boolean = true) {
actualizeBuildRoot(workingDir, null)?.importing?.set(if (inProgress) importing else updated)
updateNotifications { it.startsWith(workingDir) }
}
fun update(sync: KotlinDslGradleBuildSync) {
val oldRoot = actualizeBuildRoot(sync.workingDir, sync.gradleVersion) ?: return
try {
val newRoot = updateRoot(oldRoot, sync)
if (newRoot == null) {
markImportingInProgress(sync.workingDir, false)
return
}
add(newRoot)
} catch (e: Exception) {
markImportingInProgress(sync.workingDir, false)
return
}
}
private fun updateRoot(oldRoot: GradleBuildRoot, sync: KotlinDslGradleBuildSync): Imported? {
// fast path for linked gradle builds without .gradle.kts support
if (sync.models.isEmpty()) {
if (oldRoot is Imported && oldRoot.data.models.isEmpty()) return null
}
if (oldRoot is Legacy) return null
scriptingDebugLog { "gradle project info after import: $sync" }
// TODO: can gradleHome be null, what to do in this case
val gradleHome = sync.gradleHome
if (gradleHome == null) {
scriptingInfoLog("Cannot find valid gradle home with version = ${sync.gradleVersion}, script models cannot be saved")
return null
}
oldRoot.importing.set(updatingCaches)
scriptingDebugLog { "save script models after import: ${sync.models}" }
val newData = GradleBuildRootData(sync.ts, sync.projectRoots, gradleHome, sync.javaHome, sync.models)
val mergedData = if (sync.failed && oldRoot is Imported) merge(oldRoot.data, newData) else newData
val newRoot = tryCreateImportedRoot(sync.workingDir, LastModifiedFiles()) { mergedData } ?: return null
val buildRootDir = newRoot.dir ?: return null
GradleBuildRootDataSerializer.write(buildRootDir, mergedData)
newRoot.saveLastModifiedFiles()
return newRoot
}
private fun merge(old: GradleBuildRootData, new: GradleBuildRootData): GradleBuildRootData {
val roots = old.projectRoots.toMutableSet()
roots.addAll(new.projectRoots)
val models = old.models.associateByTo(mutableMapOf()) { it.file }
new.models.associateByTo(models) { it.file }
return GradleBuildRootData(new.importTs, roots, new.gradleHome, new.javaHome, models.values)
}
private val modifiedFilesCheckScheduled = AtomicBoolean()
private val modifiedFiles = ConcurrentLinkedQueue<String>()
private fun scheduleModifiedFilesCheck(filePath: String) {
modifiedFiles.add(filePath)
if (modifiedFilesCheckScheduled.compareAndSet(false, true)) {
val disposable = KotlinPluginDisposable.getInstance(project)
BackgroundTaskUtil.executeOnPooledThread(disposable) {
if (modifiedFilesCheckScheduled.compareAndSet(true, false)) {
checkModifiedFiles()
}
}
}
}
private fun checkModifiedFiles() {
updateNotifications(restartAnalyzer = false) { true }
roots.list.forEach {
it.saveLastModifiedFiles()
}
// process modifiedFiles queue
while (true) {
val file = modifiedFiles.poll() ?: break
// detect gradle version change
val buildDir = findGradleWrapperPropertiesBuildDir(file)
if (buildDir != null) {
actualizeBuildRoot(buildDir, null)
}
}
}
fun updateStandaloneScripts(update: StandaloneScriptsUpdater.() -> Unit) {
val changes = StandaloneScriptsUpdater.collectChanges(delegate = roots, update)
updateNotifications { it in changes.new || it in changes.removed }
loadStandaloneScriptConfigurations(changes.new)
}
init {
getGradleProjectSettings(project).forEach {
// don't call this.add, as we are inside scripting manager initialization
roots.add(loadLinkedRoot(it))
}
// subscribe to linked gradle project modification
val listener = object : GradleSettingsListenerAdapter() {
override fun onProjectsLinked(settings: MutableCollection<GradleProjectSettings>) {
settings.forEach {
add(loadLinkedRoot(it))
}
}
override fun onProjectsUnlinked(linkedProjectPaths: MutableSet<String>) {
linkedProjectPaths.forEach {
remove(it)
}
}
override fun onGradleHomeChange(oldPath: String?, newPath: String?, linkedProjectPath: String) {
val version = GradleInstallationManager.getGradleVersion(newPath)
reloadBuildRoot(linkedProjectPath, version)
}
override fun onGradleDistributionTypeChange(currentValue: DistributionType?, linkedProjectPath: String) {
reloadBuildRoot(linkedProjectPath, null)
}
}
val disposable = KotlinPluginDisposable.getInstance(project)
project.messageBus.connect(disposable).subscribe(GradleSettingsListener.TOPIC, listener)
}
private fun getGradleProjectSettings(workingDir: String): GradleProjectSettings? {
return (ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID) as GradleSettings)
.getLinkedProjectSettings(workingDir)
}
/**
* Check that root under [workingDir] in sync with it's [GradleProjectSettings].
* Actually this should be true, but we may miss some change events.
* For that cases we are rechecking this on each Gradle Project sync (importing/reimporting)
*/
private fun actualizeBuildRoot(workingDir: String, gradleVersion: String?): GradleBuildRoot? {
val actualSettings = getGradleProjectSettings(workingDir)
val buildRoot = getBuildRootByWorkingDir(workingDir)
val version = gradleVersion ?: actualSettings?.let { getGradleVersion(project, it) }
return when {
buildRoot != null -> {
when {
!buildRoot.checkActual(version) -> reloadBuildRoot(workingDir, version)
else -> buildRoot
}
}
actualSettings != null && version != null -> {
loadLinkedRoot(actualSettings, version)
}
else -> null
}
}
private fun GradleBuildRoot.checkActual(version: String?): Boolean {
if (version == null) return false
val knownAsSupported = this !is Legacy
val shouldBeSupported = kotlinDslScriptsModelImportSupported(version)
return knownAsSupported == shouldBeSupported
}
private fun reloadBuildRoot(rootPath: String, version: String?): GradleBuildRoot? {
val settings = getGradleProjectSettings(rootPath)
if (settings == null) {
remove(rootPath)
return null
} else {
val gradleVersion = version ?: getGradleVersion(project, settings)
val newRoot = loadLinkedRoot(settings, gradleVersion)
add(newRoot)
return newRoot
}
}
private fun loadLinkedRoot(settings: GradleProjectSettings, version: String = getGradleVersion(project, settings)): GradleBuildRoot {
if (!enabled) {
return Legacy(settings)
}
val supported = kotlinDslScriptsModelImportSupported(version)
return when {
supported -> tryLoadFromFsCache(settings, version) ?: New(settings)
else -> Legacy(settings)
}
}
private fun tryLoadFromFsCache(settings: GradleProjectSettings, version: String): Imported? {
return tryCreateImportedRoot(settings.externalProjectPath) {
GradleBuildRootDataSerializer.read(it)?.let { data ->
val gradleHome = data.gradleHome
if (gradleHome.isNotBlank() && GradleInstallationManager.getGradleVersion(gradleHome) != version) return@let null
addFromSettings(data, settings)
}
}
}
private fun addFromSettings(
data: GradleBuildRootData,
settings: GradleProjectSettings
) = data.copy(projectRoots = data.projectRoots.toSet() + settings.modules)
private fun tryCreateImportedRoot(
externalProjectPath: String,
lastModifiedFiles: LastModifiedFiles = loadLastModifiedFiles(externalProjectPath) ?: LastModifiedFiles(),
dataProvider: (buildRoot: VirtualFile) -> GradleBuildRootData?
): Imported? {
try {
val buildRoot = VfsUtil.findFile(Paths.get(externalProjectPath), true) ?: return null
val data = dataProvider(buildRoot) ?: return null
return Imported(externalProjectPath, data, lastModifiedFiles)
} catch (e: Exception) {
scriptingErrorLog("Cannot load script configurations from file attributes for $externalProjectPath", e)
return null
}
}
private fun add(newRoot: GradleBuildRoot) {
val old = roots.add(newRoot)
if (old is Imported && newRoot !is Imported) {
removeData(old.pathPrefix)
}
if (old !is Legacy || newRoot !is Legacy) {
updater.invalidateAndCommit()
}
updateNotifications { it.startsWith(newRoot.pathPrefix) }
}
private fun remove(rootPath: String) {
val removed = roots.remove(rootPath)
if (removed is Imported) {
removeData(rootPath)
updater.invalidateAndCommit()
}
updateNotifications { it.startsWith(rootPath) }
}
private fun removeData(rootPath: String) {
val buildRoot = LocalFileSystem.getInstance().findFileByPath(rootPath)
if (buildRoot != null) {
GradleBuildRootDataSerializer.remove(buildRoot)
LastModifiedFiles.remove(buildRoot)
}
}
fun updateNotifications(
restartAnalyzer: Boolean = true,
shouldUpdatePath: (String) -> Boolean
) {
if (!project.isOpen) return
// import notification is a balloon, so should be shown only for selected editor
FileEditorManager.getInstance(project).selectedEditor?.file?.let {
if (shouldUpdatePath(it.path) && maybeAffectedGradleProjectFile(it.path)) {
updateFloatingAction(it)
}
}
val openedScripts = FileEditorManager.getInstance(project).selectedEditors
.mapNotNull { it.file }
.filter {
shouldUpdatePath(it.path) && maybeAffectedGradleProjectFile(it.path)
}
if (openedScripts.isEmpty()) return
GlobalScope.launch(EDT(project)) {
if (project.isDisposed) return@launch
openedScripts.forEach {
if (isApplicable(it)) {
DefaultScriptingSupport.getInstance(project).ensureNotificationsRemoved(it)
}
if (restartAnalyzer) {
KotlinCodeBlockModificationListener.getInstance(project).incModificationCount()
// this required only for "pause" state
PsiManager.getInstance(project).findFile(it)?.let { ktFile ->
DaemonCodeAnalyzer.getInstance(project).restart(ktFile)
}
}
EditorNotifications.getInstance(project).updateAllNotifications()
}
}
}
private fun updateFloatingAction(file: VirtualFile) {
if (isConfigurationOutOfDate(file)) {
scriptConfigurationsNeedToBeUpdated(project, file)
} else {
scriptConfigurationsAreUpToDate(project)
}
}
private fun loadStandaloneScriptConfigurations(files: MutableSet<String>) {
runReadAction {
files.forEach {
val virtualFile = LocalFileSystem.getInstance().findFileByPath(it)
if (virtualFile != null) {
val ktFile = PsiManager.getInstance(project).findFile(virtualFile) as? KtFile
if (ktFile != null) {
DefaultScriptingSupport.getInstance(project)
.ensureUpToDatedConfigurationSuggested(ktFile, skipNotification = true)
}
}
}
}
}
companion object {
fun getInstanceSafe(project: Project): GradleBuildRootsManager =
ScriptingSupport.EPN.findExtensionOrFail(GradleBuildRootsManager::class.java, project)
fun getInstance(project: Project): GradleBuildRootsManager? =
ScriptingSupport.EPN.findExtension(GradleBuildRootsManager::class.java, project)
}
}
|
apache-2.0
|
684abdbc15748adf0f82aad1330fc904
| 39.073529 | 137 | 0.671647 | 5.176119 | false | false | false | false |
StepicOrg/stepik-android
|
app/src/main/java/org/stepik/android/presentation/auth/RegistrationPresenter.kt
|
2
|
2930
|
package org.stepik.android.presentation.auth
import org.stepik.android.domain.auth.interactor.AuthInteractor
import io.reactivex.Scheduler
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepic.droid.util.toObject
import org.stepik.android.domain.auth.model.RegistrationError
import org.stepik.android.model.user.RegistrationCredentials
import org.stepik.android.presentation.base.PresenterBase
import retrofit2.HttpException
import javax.inject.Inject
class RegistrationPresenter
@Inject
constructor(
private val analytic: Analytic,
private val authInteractor: AuthInteractor,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
@MainScheduler
private val mainScheduler: Scheduler
) : PresenterBase<RegistrationView>() {
private var state: RegistrationView.State = RegistrationView.State.Idle
set(value) {
field = value
view?.setState(value)
}
override fun attachView(view: RegistrationView) {
super.attachView(view)
view.setState(state)
}
fun onFormChanged() {
state = RegistrationView.State.Idle
}
fun submit(registrationCredentials: RegistrationCredentials) {
if (state == RegistrationView.State.Loading ||
state is RegistrationView.State.Success) {
return
}
state = RegistrationView.State.Loading
compositeDisposable += authInteractor
.createAccount(registrationCredentials)
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onSuccess = { state = RegistrationView.State.Success(it) },
onError = { throwable ->
val error = (throwable as? HttpException)
?.response()
?.errorBody()
?.string()
.runCatching {
this?.toObject<RegistrationError>()
}
.getOrNull()
if (throwable is HttpException) {
analytic.reportEvent(Analytic.Error.REGISTRATION_FAILED, throwable.response()?.errorBody()?.string() ?: "empty response")
} else {
analytic.reportError(Analytic.Error.REGISTRATION_FAILED, throwable)
}
state =
if (error != null) {
RegistrationView.State.Error(error)
} else {
view?.showNetworkError()
RegistrationView.State.Idle
}
}
)
}
}
|
apache-2.0
|
940667fc0b84f6f2e745ef2eef723094
| 34.743902 | 145 | 0.601706 | 5.528302 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2
|
core/src/main/kotlin/io/github/chrislo27/rhre3/soundsystem/BeadsSound.kt
|
2
|
2862
|
package io.github.chrislo27.rhre3.soundsystem
import net.beadsproject.beads.ugens.SamplePlayer
import net.beadsproject.beads.ugens.Static
import java.util.concurrent.ConcurrentHashMap
class BeadsSound(val audio: BeadsAudio) {
private val players: MutableMap<Long, GainedSamplePlayer> = ConcurrentHashMap()
@Volatile
private var disposed = false
val duration: Double
get() = audio.sample.length / 1000
private fun obtainPlayer(): Pair<Long, GainedSamplePlayer> {
val id = BeadsSoundSystem.obtainSoundID()
val samplePlayer = SamplePlayer(BeadsSoundSystem.audioContext, audio.sample)
val result = id to GainedSamplePlayer(samplePlayer) { players.remove(id) }.also { gsp ->
samplePlayer.apply {
killOnEnd = true
}
}
players[result.first] = result.second
return result
}
fun play(loop: Boolean, pitch: Float, rate: Float, volume: Float, position: Double): Long {
return playWithLoop(pitch, rate, volume, position, if (loop) LoopParams.LOOP_FORWARDS_ENTIRE.copy(endPoint = duration) else LoopParams.NO_LOOP_FORWARDS)
}
fun playWithLoop(pitch: Float, rate: Float, volume: Float, position: Double, loopParams: LoopParams): Long {
if (disposed)
return -1L
val (id, player) = obtainPlayer()
player.player.loopType = loopParams.loopType
player.player.rateUGen.value = rate
player.gain.gain = volume
player.pitch.value = pitch
player.rate.value = rate
val dur = duration
val clampedPosition = (position.coerceIn(-dur, dur))
player.player.position = (if (clampedPosition < 0) (dur + clampedPosition) else clampedPosition) * 1000
if (loopParams.startPoint > 0) {
player.player.setLoopStart(Static(player.player.context, loopParams.startPoint.toFloat() * 1000))
}
if (loopParams.endPoint > 0) {
player.player.setLoopEnd(Static(player.player.context, loopParams.endPoint.toFloat() * 1000))
}
player.addToContext()
return id
}
fun setPitch(id: Long, pitch: Float) {
val player = players[id] ?: return
player.pitch.value = pitch
}
fun setRate(id: Long, rate: Float) {
val player = players[id] ?: return
player.rate.value = rate
}
fun setVolume(id: Long, vol: Float) {
val player = players[id] ?: return
player.gain.gain = vol
}
fun stop(id: Long) {
val player = players[id] ?: return
players.remove(id)
player.player.kill()
}
fun dispose() {
if (disposed)
return
disposed = true
players.forEach { stop(it.key) }
players.clear()
}
fun getPlayer(id: Long): GainedSamplePlayer? = players[id]
}
|
gpl-3.0
|
4468579b5b1d8c0617d9165e869c38bd
| 29.784946 | 160 | 0.632075 | 4.002797 | false | false | false | false |
allotria/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/actions/AbstractCommonCheckinAction.kt
|
1
|
5958
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.actions
import com.intellij.configurationStore.StoreUtil
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.UpdateInBackground
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsActions
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.VcsDataKeys.COMMIT_WORKFLOW_HANDLER
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog
import com.intellij.util.containers.ContainerUtil.concat
import com.intellij.util.ui.UIUtil.removeMnemonic
import com.intellij.vcs.commit.CommitWorkflowHandler
import com.intellij.vcs.commit.CommitModeManager
import com.intellij.vcs.commit.removeEllipsisSuffix
import org.jetbrains.annotations.ApiStatus
private val LOG = logger<AbstractCommonCheckinAction>()
private fun getChangesIn(project: Project, roots: Array<FilePath>): Set<Change> {
val manager = ChangeListManager.getInstance(project)
return roots.flatMap { manager.getChangesIn(it) }.toSet()
}
internal fun AnActionEvent.getContextCommitWorkflowHandler(): CommitWorkflowHandler? = getData(COMMIT_WORKFLOW_HANDLER)
abstract class AbstractCommonCheckinAction : AbstractVcsAction(), UpdateInBackground {
override fun update(vcsContext: VcsContext, presentation: Presentation) {
val project = vcsContext.project
if (project == null ||
!ProjectLevelVcsManager.getInstance(project).hasActiveVcss() ||
!ChangeListManager.getInstance(project).areChangeListsEnabled()) {
presentation.isEnabledAndVisible = false
}
else if (!approximatelyHasRoots(vcsContext)) {
presentation.isEnabled = false
}
else {
getActionName(vcsContext)?.let { presentation.text = "$it..." }
presentation.isEnabled = !ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning
presentation.isVisible = true
}
}
protected abstract fun approximatelyHasRoots(dataContext: VcsContext): Boolean
protected open fun getActionName(dataContext: VcsContext): @NlsActions.ActionText String? = null
public override fun actionPerformed(context: VcsContext) {
LOG.debug("actionPerformed. ")
val project = context.project!!
val actionName = getActionName(context) ?: templatePresentation.text
val isFreezedDialogTitle = actionName?.let {
VcsBundle.message("error.cant.perform.operation.now", removeMnemonic(actionName).removeEllipsisSuffix().toLowerCase())
}
if (ChangeListManager.getInstance(project).isFreezedWithNotification(isFreezedDialogTitle)) {
LOG.debug("ChangeListManager is freezed. returning.")
}
else if (ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning) {
LOG.debug("Background operation is running. returning.")
}
else {
val roots = prepareRootsForCommit(getRoots(context), project)
queueCheckin(project, context, roots)
}
}
protected open fun queueCheckin(
project: Project,
context: VcsContext,
roots: Array<FilePath>
) {
ChangeListManager.getInstance(project).invokeAfterUpdateWithModal(
true, VcsBundle.message("waiting.changelists.update.for.show.commit.dialog.message")) {
performCheckIn(context, project, roots)
}
}
@Deprecated("getActionName() will be used instead")
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
protected open fun getMnemonicsFreeActionName(context: VcsContext): String? = null
protected abstract fun getRoots(dataContext: VcsContext): Array<FilePath>
protected open fun prepareRootsForCommit(roots: Array<FilePath>, project: Project): Array<FilePath> {
StoreUtil.saveDocumentsAndProjectSettings(project)
return DescindingFilesFilter.filterDescindingFiles(roots, project)
}
protected open fun isForceUpdateCommitStateFromContext(): Boolean = false
protected open fun performCheckIn(context: VcsContext, project: Project, roots: Array<FilePath>) {
LOG.debug("invoking commit dialog after update")
val selectedChanges = context.selectedChanges
val selectedUnversioned = context.selectedUnversionedFilePaths
val initialChangeList = getInitiallySelectedChangeList(context, project)
val changesToCommit: Collection<Change>
val included: Collection<Any>
if (selectedChanges.isNullOrEmpty() && selectedUnversioned.isEmpty()) {
changesToCommit = getChangesIn(project, roots)
included = initialChangeList.changes.intersect(changesToCommit)
}
else {
changesToCommit = selectedChanges.orEmpty().toList()
included = concat(changesToCommit, selectedUnversioned)
}
val executor = getExecutor(project)
val workflowHandler = ChangesViewManager.getInstanceEx(project).commitWorkflowHandler
if (executor == null && workflowHandler != null) {
workflowHandler.run {
setCommitState(initialChangeList, included, isForceUpdateCommitStateFromContext())
activate()
}
}
else {
CommitChangeListDialog.commitChanges(project, changesToCommit, included, initialChangeList, executor, null)
}
}
protected open fun getInitiallySelectedChangeList(context: VcsContext, project: Project): LocalChangeList {
val manager = ChangeListManager.getInstance(project)
return context.selectedChangeLists?.firstOrNull()?.let { manager.findChangeList(it.name) }
?: context.selectedChanges?.firstOrNull()?.let { manager.getChangeList(it) }
?: manager.defaultChangeList
}
protected open fun getExecutor(project: Project): CommitExecutor? = null
}
|
apache-2.0
|
4e84f69e83fb440da5534521a5b57063
| 40.957746 | 140 | 0.770393 | 4.915842 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer
|
app/src/main/kotlin/com/vrem/wifianalyzer/navigation/items/NavigationItems.kt
|
1
|
2231
|
/*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.navigation.items
import android.view.View
import com.vrem.wifianalyzer.about.AboutFragment
import com.vrem.wifianalyzer.export.Export
import com.vrem.wifianalyzer.settings.SettingsFragment
import com.vrem.wifianalyzer.vendor.VendorFragment
import com.vrem.wifianalyzer.wifi.accesspoint.AccessPointsFragment
import com.vrem.wifianalyzer.wifi.channelavailable.ChannelAvailableFragment
import com.vrem.wifianalyzer.wifi.channelgraph.ChannelGraphFragment
import com.vrem.wifianalyzer.wifi.channelrating.ChannelRatingFragment
import com.vrem.wifianalyzer.wifi.timegraph.TimeGraphFragment
val navigationItemAccessPoints: NavigationItem = FragmentItem(AccessPointsFragment())
val navigationItemChannelRating: NavigationItem = FragmentItem(ChannelRatingFragment())
val navigationItemChannelGraph: NavigationItem = FragmentItem(ChannelGraphFragment())
val navigationItemTimeGraph: NavigationItem = FragmentItem(TimeGraphFragment())
val navigationItemExport: NavigationItem = ExportItem(Export())
val navigationItemChannelAvailable: NavigationItem = FragmentItem(ChannelAvailableFragment(), false)
val navigationItemVendors: NavigationItem = FragmentItem(VendorFragment(), false, View.GONE)
val navigationItemSettings: NavigationItem = FragmentItem(SettingsFragment(), false, View.GONE)
val navigationItemAbout: NavigationItem = FragmentItem(AboutFragment(), false, View.GONE)
val navigationItemPortAuthority: NavigationItem = PortAuthorityItem()
|
gpl-3.0
|
ee74e0952796e4ca8463941538cd1d88
| 54.775 | 100 | 0.826087 | 4.667364 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/serialization/KonanPackageFragment.kt
|
1
|
3088
|
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.serialization
import org.jetbrains.kotlin.backend.konan.library.KonanLibraryReader
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.serialization.KonanLinkData
import org.jetbrains.kotlin.serialization.deserialization.DeserializedPackageFragment
import org.jetbrains.kotlin.serialization.deserialization.NameResolverImpl
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPackageMemberScope
import org.jetbrains.kotlin.storage.StorageManager
class KonanPackageFragment(
val fqNameString: String,
val reader: KonanLibraryReader,
storageManager: StorageManager, module: ModuleDescriptor
) : DeserializedPackageFragment(FqName(fqNameString), storageManager, module) {
// The proto field is lazy so that we can load only needed
// packages from the library.
private val protoForNames: KonanLinkData.PackageFragment by lazy {
parsePackageFragment(reader.packageMetadata(fqNameString))
}
val proto: KonanLinkData.PackageFragment get() = protoForNames.also {
reader.markPackageAccessed(fqNameString)
}
private val nameResolver by lazy {
NameResolverImpl(protoForNames.getStringTable(), protoForNames.getNameTable())
}
override val classDataFinder by lazy {
KonanClassDataFinder(proto, nameResolver)
}
override fun computeMemberScope(): DeserializedPackageMemberScope {
val packageProto = proto.getPackage()
return DeserializedPackageMemberScope( this, packageProto,
nameResolver, /* containerSource = */ null,
components, {loadClassNames()} )
}
private val classifierNames by lazy {
val result = mutableSetOf<Name>()
result.addAll(loadClassNames())
protoForNames.getPackage().typeAliasList.mapTo(result) { nameResolver.getName(it.name) }
result
}
fun hasTopLevelClassifier(name: Name): Boolean = name in classifierNames
private fun loadClassNames(): Collection<Name> {
val classNameList = protoForNames.getClasses().getClassNameList()
val names = classNameList.mapNotNull {
val classId = nameResolver.getClassId(it)
val shortName = classId.getShortClassName()
if (!classId.isNestedClass) shortName else null
}
return names
}
}
|
apache-2.0
|
487607c8665c8842aad8e19d5645fd9d
| 36.204819 | 100 | 0.74158 | 4.847724 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/stdlib/coroutines/CoroutinesReferenceValuesTest/testBadClass.kt
|
2
|
1236
|
import kotlin.test.*
import kotlin.coroutines.experimental.*
class BadClass {
override fun equals(other: Any?): Boolean = error("equals")
override fun hashCode(): Int = error("hashCode")
override fun toString(): String = error("toString")
}
var counter = 0
// tail-suspend function via suspendCoroutine (test SafeContinuation)
suspend fun getBadClassViaSuspend(): BadClass = suspendCoroutine { cont ->
counter++
cont.resume(BadClass())
}
// state machine
suspend fun checkBadClassTwice() {
assertTrue(getBadClassViaSuspend() is BadClass)
assertTrue(getBadClassViaSuspend() is BadClass)
}
fun <T> suspend(block: suspend () -> T) = block
fun box() {
val bad = suspend {
checkBadClassTwice()
getBadClassViaSuspend()
}
var result: BadClass? = null
bad.startCoroutine(object : Continuation<BadClass> {
override val context: CoroutineContext = EmptyCoroutineContext
override fun resume(value: BadClass) {
assertTrue(result == null)
result = value
}
override fun resumeWithException(exception: Throwable) {
throw exception
}
})
assertTrue(result is BadClass)
assertEquals(3, counter)
}
|
apache-2.0
|
7b86a79acd0e329480697d468aaecea3
| 25.297872 | 74 | 0.670712 | 4.398577 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/secondaryConstructors/withReturnUnit.kt
|
5
|
339
|
class A {
val prop: Int
constructor(arg: Boolean) {
if (arg) {
prop = 1
return Unit
}
prop = 2
}
}
fun box(): String {
val a1 = A(true)
if (a1.prop != 1) return "fail1: ${a1.prop}"
val a2 = A(false)
if (a2.prop != 2) return "fail2: ${a2.prop}"
return "OK"
}
|
apache-2.0
|
eb6e912f04bf0978faff07db2c93d734
| 17.833333 | 48 | 0.457227 | 2.973684 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/InspectBreakpointApplicabilityAction.kt
|
2
|
2803
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.breakpoints
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.TextAnnotationGutterProvider
import com.intellij.openapi.editor.colors.ColorKey
import com.intellij.openapi.editor.colors.EditorFontType
import org.jetbrains.kotlin.idea.core.util.getLineCount
import org.jetbrains.kotlin.idea.debugger.breakpoints.BreakpointChecker.BreakpointType
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.psi.KtFile
import java.awt.Color
import java.util.*
@Suppress("ComponentNotRegistered")
class InspectBreakpointApplicabilityAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val data = e.getData() ?: return
if (data.editor.gutter.isAnnotationsShown) {
data.editor.gutter.closeAllAnnotations()
}
val checker = BreakpointChecker()
val lineCount = data.file.getLineCount()
val breakpoints = (0..lineCount).map { line -> checker.check(data.file, line) }
val gutterProvider = BreakpointsGutterProvider(breakpoints)
data.editor.gutter.registerTextAnnotation(gutterProvider)
}
private class BreakpointsGutterProvider(private val breakpoints: List<EnumSet<BreakpointType>>) : TextAnnotationGutterProvider {
override fun getLineText(line: Int, editor: Editor?): String? {
val breakpoints = breakpoints.getOrNull(line) ?: return null
return breakpoints.map { it.prefix }.distinct().joinToString()
}
override fun getToolTip(line: Int, editor: Editor?): String? = null
override fun getStyle(line: Int, editor: Editor?) = EditorFontType.PLAIN
override fun getPopupActions(line: Int, editor: Editor?) = emptyList<AnAction>()
override fun getColor(line: Int, editor: Editor?): ColorKey? = null
override fun getBgColor(line: Int, editor: Editor?): Color? = null
override fun gutterClosed() {}
}
override fun update(e: AnActionEvent) {
e.presentation.isVisible = isApplicationInternalMode()
e.presentation.isEnabled = e.getData() != null
}
class ActionData(val editor: Editor, val file: KtFile)
private fun AnActionEvent.getData(): ActionData? {
val editor = getData(CommonDataKeys.EDITOR) ?: return null
val file = getData(CommonDataKeys.PSI_FILE) as? KtFile ?: return null
return ActionData(editor, file)
}
}
|
apache-2.0
|
d2f2d15a2009df162be1e727697205ba
| 43.492063 | 158 | 0.7335 | 4.513688 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/utils.kt
|
4
|
4327
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.safeDelete
import com.intellij.ide.IdeBundle
import com.intellij.openapi.ui.Messages
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiParameter
import com.intellij.psi.search.searches.OverridingMethodsSearch
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.formatJavaOrLightMethod
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parameterIndex
import java.util.*
fun PsiElement.canDeleteElement(): Boolean {
if (this is KtObjectDeclaration && isObjectLiteral()) return false
if (this is KtParameter) {
val parameterList = parent as? KtParameterList ?: return false
val declaration = parameterList.parent as? KtDeclaration ?: return false
return declaration !is KtPropertyAccessor
}
return this is KtClassOrObject
|| this is KtSecondaryConstructor
|| this is KtNamedFunction
|| this is PsiMethod
|| this is PsiClass
|| this is KtProperty
|| this is KtTypeParameter
|| this is KtTypeAlias
}
fun PsiElement.removeOverrideModifier() {
when (this) {
is KtNamedFunction, is KtProperty -> {
(this as KtModifierListOwner).modifierList?.getModifier(KtTokens.OVERRIDE_KEYWORD)?.delete()
}
is PsiMethod -> {
modifierList.annotations.firstOrNull { annotation ->
annotation.qualifiedName == "java.lang.Override"
}?.delete()
}
}
}
fun PsiMethod.cleanUpOverrides() {
val superMethods = findSuperMethods(true)
for (overridingMethod in OverridingMethodsSearch.search(this, true).findAll()) {
val currentSuperMethods = overridingMethod.findSuperMethods(true).asSequence() + superMethods.asSequence()
if (currentSuperMethods.all { superMethod -> superMethod.unwrapped == unwrapped }) {
overridingMethod.unwrapped?.removeOverrideModifier()
}
}
}
fun checkParametersInMethodHierarchy(parameter: PsiParameter): Collection<PsiElement>? {
val method = parameter.declarationScope as PsiMethod
val parametersToDelete = collectParametersHierarchy(method, parameter)
if (parametersToDelete.size <= 1 || isUnitTestMode()) return parametersToDelete
val message = KotlinBundle.message("override.declaration.delete.multiple.parameters", formatJavaOrLightMethod(method))
val exitCode = Messages.showOkCancelDialog(parameter.project, message, IdeBundle.message("title.warning"), Messages.getQuestionIcon())
return if (exitCode == Messages.OK) parametersToDelete else null
}
// TODO: generalize breadth-first search
private fun collectParametersHierarchy(method: PsiMethod, parameter: PsiParameter): Set<PsiElement> {
val queue = ArrayDeque<PsiMethod>()
val visited = HashSet<PsiMethod>()
val parametersToDelete = HashSet<PsiElement>()
queue.add(method)
while (!queue.isEmpty()) {
val currentMethod = queue.poll()
visited += currentMethod
addParameter(currentMethod, parametersToDelete, parameter)
currentMethod.findSuperMethods(true)
.filter { it !in visited }
.forEach { queue.offer(it) }
OverridingMethodsSearch.search(currentMethod)
.filter { it !in visited }
.forEach { queue.offer(it) }
}
return parametersToDelete
}
private fun addParameter(method: PsiMethod, result: MutableSet<PsiElement>, parameter: PsiParameter) {
val parameterIndex = parameter.unwrapped!!.parameterIndex()
if (method is KtLightMethod) {
val declaration = method.kotlinOrigin
if (declaration is KtFunction) {
result.add(declaration.valueParameters[parameterIndex])
}
} else {
result.add(method.parameterList.parameters[parameterIndex])
}
}
|
apache-2.0
|
878e063227b0fc31b5141f1f943bb500
| 38.706422 | 158 | 0.719436 | 5.031395 | false | false | false | false |
google/intellij-community
|
platform/collaboration-tools/src/com/intellij/collaboration/api/httpclient/HttpClientContentUtil.kt
|
5
|
1797
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.collaboration.api.httpclient
import com.intellij.collaboration.api.HttpStatusErrorException
import java.awt.Image
import java.io.InputStream
import java.net.http.HttpRequest
import java.net.http.HttpRequest.BodyPublisher
import java.net.http.HttpRequest.BodyPublishers
import java.net.http.HttpResponse.*
import java.nio.ByteBuffer
import java.util.concurrent.Flow
import javax.imageio.ImageIO
abstract class ByteArrayProducingBodyPublisher
: BodyPublisher {
override fun subscribe(subscriber: Flow.Subscriber<in ByteBuffer>) {
val body = produceBytes()
BodyPublishers.ofByteArray(body).subscribe(subscriber)
}
protected abstract fun produceBytes(): ByteArray
override fun contentLength(): Long = -1
}
abstract class StreamReadingBodyHandler<T>(protected val request: HttpRequest) : BodyHandler<T> {
final override fun apply(responseInfo: ResponseInfo): BodySubscriber<T> {
val subscriber = HttpClientUtil.gzipInflatingBodySubscriber(responseInfo)
return BodySubscribers.mapping(subscriber) {
val statusCode = responseInfo.statusCode()
if (statusCode >= 400) {
val errorBody = it.reader().readText()
handleError(statusCode, errorBody)
}
read(it)
}
}
protected abstract fun read(bodyStream: InputStream): T
protected open fun handleError(statusCode: Int, errorBody: String): Nothing {
throw HttpStatusErrorException(request.method(), request.uri().toString(), statusCode, errorBody)
}
}
open class ImageBodyHandler(request: HttpRequest) : StreamReadingBodyHandler<Image>(request) {
override fun read(bodyStream: InputStream): Image = ImageIO.read(bodyStream)
}
|
apache-2.0
|
6c24c506b0e338351b71b73104e9ca3d
| 34.254902 | 120 | 0.771842 | 4.393643 | false | false | false | false |
fabmax/kool
|
kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/physics/terrain/Sky.kt
|
1
|
8889
|
package de.fabmax.kool.demo.physics.terrain
import de.fabmax.kool.KoolContext
import de.fabmax.kool.math.*
import de.fabmax.kool.modules.ksl.KslUnlitShader
import de.fabmax.kool.modules.ksl.blocks.ColorBlockConfig
import de.fabmax.kool.modules.ksl.blocks.mvpMatrix
import de.fabmax.kool.modules.ksl.lang.a
import de.fabmax.kool.modules.ksl.lang.float4
import de.fabmax.kool.modules.ksl.lang.getFloat4Port
import de.fabmax.kool.modules.ksl.lang.times
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.pipeline.CullMethod
import de.fabmax.kool.pipeline.Texture2d
import de.fabmax.kool.pipeline.ibl.EnvironmentMaps
import de.fabmax.kool.pipeline.ibl.SkyCubeIblSystem
import de.fabmax.kool.scene.*
import de.fabmax.kool.util.*
import kotlin.collections.set
import kotlin.math.abs
import kotlin.math.acos
import kotlin.math.atan2
class Sky(mainScene: Scene, moonTex: Texture2d) {
var timeOfDay = 0.25f
var fullDayDuration = 180f
val isDay: Boolean
get() = timeOfDay > 0.25f && timeOfDay < 0.75f
val skies = TreeMap<Float, SkyCubeIblSystem>()
val sunDirection = MutableVec3f()
val moonDirection = MutableVec3f()
private val skybox = Skybox.Cube(texLod = 1f)
private val sunShader = SkyObjectShader {
uniformColor(Color.WHITE.mix(MdColor.YELLOW, 0.15f).toLinear())
}
private val moonShader = SkyObjectShader {
textureColor(moonTex)
}
private val starShader = SkyObjectShader(isPointShader = true) {
vertexColor()
}
private val sunMesh = colorMesh {
isFrustumChecked = false
generate {
circle {
center.set(0f, 0f, -1f)
radius = 0.015f
}
}
shader = sunShader
}
private val moonMesh = textureMesh {
isFrustumChecked = false
generate {
rect {
size.set(0.17f, 0.17f)
origin.set(size.x * -0.5f, size.y * -0.5f, -1f)
}
}
shader = moonShader
}
private val starMesh = PointMesh().apply {
isFrustumChecked = false
val r = Random(1337)
for (i in 0..5_000) {
val p = MutableVec3f(1f, 1f, 1f)
while (p.sqrLength() > 1f) {
p.set(r.randomF(-1f, 1f), r.randomF(-1f, 1f), r.randomF(-1f, 1f))
}
p.norm()
val sz = r.randomF(1f, 3f)
addPoint(p, sz, Color.fromHsv(r.randomF(0f, 360f), r.randomF(0.2f, 0.5f), 1f, sz / 3f))
}
shader = starShader
}
val skyGroup = Group().apply {
+skybox
+sunMesh
+starMesh
+moonMesh
}
lateinit var weightedEnvs: WeightedEnvMaps
private val sunColorGradient = ColorGradient(
0.00f to MdColor.YELLOW.mix(Color.WHITE, 0.7f),
0.72f to MdColor.YELLOW.mix(Color.WHITE, 0.4f),
0.84f to MdColor.AMBER.mix(Color.WHITE, 0.3f),
0.92f to MdColor.AMBER,
1.00f to MdColor.ORANGE,
toLinear = true
)
init {
mainScene.onUpdate += {
val timeInc = Time.deltaT / fullDayDuration
timeOfDay = (timeOfDay + timeInc) % 1f
var fKey = skies.floorKey(timeOfDay)
var cKey = skies.ceilingKey(timeOfDay)
if (fKey == null) fKey = cKey!!
if (cKey == null) cKey = fKey
weightedEnvs.envA = skies[cKey]!!.envMaps
weightedEnvs.envB = skies[fKey]!!.envMaps
if (fKey != cKey) {
weightedEnvs.weightA = (timeOfDay - fKey) / (cKey - fKey)
weightedEnvs.weightB = (1f - weightedEnvs.weightA)
} else {
weightedEnvs.weightA = 1f
weightedEnvs.weightB = 0f
}
skybox.skyboxShader.setBlendSkies(
weightedEnvs.envA.reflectionMap, weightedEnvs.weightA * 2f,
weightedEnvs.envB.reflectionMap, weightedEnvs.weightB * 2f
)
}
}
suspend fun generateMaps(terrainDemo: TerrainDemo, parentScene: Scene, ctx: KoolContext) {
val hours = listOf(4f, 5f, 5.5f, 6f, 6.5f, 7f, 8f, 9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f, 17f, 17.5f, 18f, 18.5f, 19f, 20f)
hours.forEachIndexed { i, h ->
terrainDemo.showLoadText("Creating sky (${i * 100f / hours.lastIndex}%)...", 0)
precomputeSky(h / 24f, parentScene, ctx)
}
weightedEnvs = WeightedEnvMaps(skies[0.5f]!!.envMaps, skies[0.5f]!!.envMaps)
}
private suspend fun precomputeSky(timeOfDay: Float, parentScene: Scene, ctx: KoolContext) {
val sunDir = computeLightDirection(SUN_TILT, sunProgress(timeOfDay), Mat3f())
val sky = SkyCubeIblSystem(parentScene)
sky.skyPass.elevation = 90f - acos(-sunDir.y).toDeg()
sky.skyPass.azimuth = atan2(sunDir.x, -sunDir.z).toDeg()
sky.setupOffscreenPasses()
skies[timeOfDay] = sky
ctx.delayFrames(1)
}
fun updateLight(sceneLight: Light) {
computeLightDirection(SUN_TILT, sunProgress(timeOfDay), sunShader.orientation, sunDirection)
computeLightDirection(MOON_TILT, moonProgress(timeOfDay), moonShader.orientation, moonDirection)
starShader.orientation.set(moonShader.orientation)
starShader.alpha = 1f - smoothStep(0.23f, 0.28f, timeOfDay) + smoothStep(0.72f, 0.77f, timeOfDay)
if (isDay) {
// daytime -> light is the sun
val sunProgress = sunProgress(timeOfDay)
val sunColor = sunColorGradient.getColorInterpolated(abs(sunProgress - 0.5f) * 2f, MutableColor())
val sunIntensity = smoothStep(0.0f, 0.06f, sunProgress) * (1f - smoothStep(0.94f, 1.0f, sunProgress))
sceneLight.setColor(sunColor, sunIntensity * 1.5f)
sceneLight.setDirectional(sunDirection)
} else {
// nighttime -> light is the moon
val moonProgress = moonProgress(timeOfDay)
val moonIntensity = smoothStep(0.0f, 0.06f, moonProgress) * (1f - smoothStep(0.94f, 1.0f, moonProgress))
sceneLight.setColor(moonColor, moonIntensity * 0.07f)
sceneLight.setDirectional(moonDirection)
}
}
private fun computeLightDirection(tilt: Float, progress: Float, orientation: Mat3f, direction: MutableVec3f = MutableVec3f()): Vec3f {
orientation
.setIdentity()
.rotate(tilt, Vec3f.Z_AXIS)
.rotate(progress * 180f, Vec3f.X_AXIS)
return orientation.transform(direction.set(0f, 0f, 1f))
}
fun sunProgress(timeOfDay: Float): Float {
return (timeOfDay - 0.26f) * 2.083f
}
fun moonProgress(timeOfDay: Float): Float {
val nightTime = (timeOfDay + 0.5f) % 1f
return (nightTime - 0.26f) * 2.083f
}
private class SkyObjectShader(isPointShader: Boolean = false, colorBlock: ColorBlockConfig.() -> Unit)
: KslUnlitShader(config(isPointShader, colorBlock)) {
val orientation: Mat3f by uniformMat3f("uOrientation", Mat3f().setIdentity())
var alpha: Float by uniform1f("uAlpha", 1f)
companion object {
fun config(isPointShader: Boolean, colorBlock: ColorBlockConfig.() -> Unit) = UnlitShaderConfig().apply {
color {
colorBlock()
}
pipeline {
cullMethod = CullMethod.NO_CULLING
isWriteDepth = false
}
modelCustomizer = {
vertexStage {
main {
val mvpMat = mvpMatrix().matrix
val localPos = vertexAttribFloat3(Attribute.POSITIONS.name)
val orientation = uniformMat3("uOrientation")
outPosition set (mvpMat * float4Value(orientation * localPos, 0f)).float4("xyww")
if (isPointShader) {
outPointSize set vertexAttribFloat1(PointMesh.ATTRIB_POINT_SIZE.name)
}
}
}
fragmentStage {
main {
val baseColorPort = getFloat4Port("baseColor")
val alphaColor = float4Var(baseColorPort.input.input)
alphaColor.a *= uniformFloat1("uAlpha")
baseColorPort.input(alphaColor)
}
}
}
}
}
}
companion object {
private const val SUN_TILT = 30f
private const val MOON_TILT = 45f
private val moonColor = MdColor.BLUE toneLin 200
}
class WeightedEnvMaps(var envA: EnvironmentMaps, var envB: EnvironmentMaps) {
var weightA = 1f
var weightB = 0f
}
}
|
apache-2.0
|
15afcba97059d8ccd53a6a87002996cf
| 36.196653 | 138 | 0.587243 | 3.834771 | false | false | false | false |
obask/lispify
|
kotlin/src/main.kt
|
1
|
3066
|
import ast.ABranch
import ast.AString
import ast.ATree
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import java.util.stream.Collectors
import java.util.stream.Stream
private val path = Paths.get("/Users/oleg.baskakov/IdeaProjects/lispify/java15/src/main/resources/example.scm")
private const val L_PAREN = "("
private const val R_PAREN = ")"
// TODO replace to splitAsStream method
// Pattern.compile("\\W").splitAsStream("Some sentence");
fun splitMeAsStream(input: String, ch: Char): Stream<String> {
val value = input.toCharArray()
val sep = ch.toString()
var off = 0
var next = 0
val limited = false
val list = ArrayList<String>()
while (input.indexOf(ch, off).also { next = it } != -1) {
list.add(input.substring(off, next))
list.add(sep)
off = next + 1
}
// If no match was found, return this
if (off == 0) {
return Stream.of(input)
}
// Add remaining segment
list.add(input.substring(off, value.size))
return list.stream()
}
fun reduceTree(tokens: Iterator<String?>, state: MutableList<ATree>): ATree {
return if (tokens.hasNext()) {
when (val curr = tokens.next()) {
L_PAREN -> {
// System.out.println("L_PAREN");
val tmp: MutableList<ATree> = ArrayList()
val aTree = reduceTree(tokens, tmp)
state.add(aTree)
reduceTree(tokens, state)
}
R_PAREN -> // System.out.println("R_PAREN");
ABranch(state)
else -> {
// System.out.println("L_ATOM");
// System.out.println(state.getClass());
state.add(AString(curr!!))
reduceTree(tokens, state)
}
}
} else {
ABranch(state)
}
}
fun main(args: Array<String>) {
// write your code here
try {
val stream0 = Files.lines(path)
val stream1 = stream0.map { ss: String -> ss.split(" ".toRegex()).toTypedArray() }
.flatMap { array: Array<String>? -> Arrays.stream(array) }
val stream2 = stream1.flatMap { ss: String -> splitMeAsStream(ss, L_PAREN[0]) }
val stream3 = stream2.flatMap { ss: String -> splitMeAsStream(ss, R_PAREN[0]) }
// String stream4 = stream3.filter(ss -> !ss.isEmpty()).collect(Collectors.joining("\n"));
// String[] stmp = stream4.toArray(String[]::new);
// System.out.println(stream4);
val objects = stream3.filter { ss: String -> !ss.isEmpty() }.collect(Collectors.toList())
val stringIterator = objects.iterator()
while (stringIterator.hasNext()) {
val next = stringIterator.next()
assert(next == L_PAREN)
val aTree = reduceTree(stringIterator, ArrayList())
println(aTree)
println("----")
}
} catch (e: IOException) {
e.printStackTrace()
}
}
|
mit
|
0a27b9efb33c31cfb74ba7f1546c884f
| 35.070588 | 111 | 0.567841 | 3.86633 | false | false | false | false |
moko256/twicalico
|
app/src/main/java/com/github/moko256/twitlatte/model/impl/ListModelImpl.kt
|
1
|
10538
|
/*
* Copyright 2015-2019 The twitlatte authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.moko256.twitlatte.model.impl
import com.github.moko256.latte.client.base.entity.Paging
import com.github.moko256.latte.client.base.entity.Post
import com.github.moko256.twitlatte.LIMIT_OF_SIZE_OF_STATUSES_LIST
import com.github.moko256.twitlatte.database.CachedIdListSQLiteOpenHelper
import com.github.moko256.twitlatte.entity.Client
import com.github.moko256.twitlatte.entity.EventType
import com.github.moko256.twitlatte.entity.UpdateEvent
import com.github.moko256.twitlatte.model.base.ListModel
import com.github.moko256.twitlatte.repository.server.base.ListServerRepository
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
import java.lang.IllegalStateException
/**
* Created by moko256 on 2018/10/11.
*
* @author moko256
*/
class ListModelImpl(
private val api: ListServerRepository<Post>,
private val client: Client,
private val database: CachedIdListSQLiteOpenHelper
) : ListModel {
private val nothingEvent = UpdateEvent(EventType.NOTHING, 0, 0)
private val list = ArrayList<Long>()
private val requests = CompositeDisposable()
private var seeingId = -1L
private val updateObserver = PublishSubject.create<UpdateEvent>()
private val errorObserver = PublishSubject.create<Throwable>()
init {
val c = database.getIds()
if (c.isNotEmpty()) {
list.addAll(c)
}
}
override fun getIdsList(): List<Long> {
return list
}
override fun getListEventObservable(): Observable<UpdateEvent> {
return updateObserver
}
override fun getErrorEventObservable(): Observable<Throwable> {
return errorObserver
}
override fun getSeeingPosition(): Int {
if (seeingId == -1L) {
seeingId = database.getSeeingId()
}
return list.indexOf(seeingId)
}
override fun updateSeeingPosition(position: Int) {
val id = getIdsList()[position]
if (id != seeingId) {
seeingId = id
database.setSeeingId(id)
}
}
override fun refreshFirst() {
requests.add(
Completable.create { status ->
try {
api.request(Paging(count = 10))
} catch (e: Throwable) {
e.printStackTrace()
errorObserver.onNext(e)
return@create
}.also { client.postCache.addAll(it) }
.map { it.id }
.let {
list.addAll(it)
database.insertIdsAtFirst(it)
updateObserver.onNext(UpdateEvent(EventType.ADD_FIRST, 0, it.size))
}
status.onComplete()
}.subscribeOn(Schedulers.io())
.subscribe()
)
}
override fun refreshOnTop() {
val sinceId: Long = if (list.size >= 2) {
if (list[1] == -1L) {
list[0]
} else {
list[1]
}
} else {
list[0]
}
val excludeId = list.takeIf { it.size >= 2 }?.firstOrNull() ?: 0
requests.add(
Completable.create { status ->
try {
api.request(
Paging(
sinceId = sinceId,
count = client.statusLimit
)
)
} catch (e: Throwable) {
e.printStackTrace()
errorObserver.onNext(e)
return@create
}.apply {
if (isNotEmpty()) {
client.postCache.addAll(this, excludeId)
val ids = map { it.id }.toMutableList()
if (ids[ids.size - 1] == list[0]) {
ids.removeAt(ids.size - 1)
} else {
ids.add(-1L)
}
if (ids.size > 0) {
list.addAll(0, ids)
database.insertIdsAtFirst(ids)
updateObserver.onNext(UpdateEvent(EventType.ADD_TOP, 0, ids.size))
} else {
updateObserver.onNext(nothingEvent)
}
} else {
updateObserver.onNext(nothingEvent)
}
}
status.onComplete()
}.subscribeOn(Schedulers.io())
.subscribe()
)
}
override fun loadOnBottom() {
val bottomPos = list.size - 1
if (list[bottomPos] == -1L) {
database.removeAt(bottomPos)
list.removeAt(bottomPos)
updateObserver.onNext(UpdateEvent(EventType.REMOVE, bottomPos, 1))
}
requests.add(
Completable.create { status ->
try {
api.request(
Paging(
maxId = list[list.size - 1] - 1L,
count = client.statusLimit
)
)
} catch (e: Throwable) {
e.printStackTrace()
errorObserver.onNext(e)
return@create
}.apply {
if (isNotEmpty()) {
client.postCache.addAll(this)
val ids = map { it.id }
val sizeBeforeAdded = list.size
list.addAll(ids)
database.insertIdsAtLast(ids)
updateObserver.onNext(
UpdateEvent(
EventType.ADD_BOTTOM,
sizeBeforeAdded,
size
)
)
} else {
updateObserver.onNext(nothingEvent)
}
}
status.onComplete()
}.subscribeOn(Schedulers.io())
.subscribe()
)
}
override fun loadOnGap(position: Int) {
val sinceId: Long = if (list.size > position + 2) {
if (list[position + 2] == -1L) {
list[position + 1]
} else {
list[position + 2]
}
} else {
list[position + 1]
}
val excludeId = list.takeIf { it.size >= position + 2 }?.get(position + 1) ?: 0
requests.add(
Completable.create { status ->
try {
api.request(
Paging(
sinceId = sinceId,
maxId = list[position - 1] - 1L,
count = client.statusLimit
)
)
} catch (e: Throwable) {
e.printStackTrace()
errorObserver.onNext(e)
updateObserver.onNext(UpdateEvent(EventType.UPDATE, position, 1))
return@create
}.apply {
if (isNotEmpty()) {
client.postCache.addAll(this, excludeId)
val ids = map { it.id }.toMutableList()
val noGap = ids[ids.size - 1] == list[position + 1]
if (noGap) {
ids.removeAt(ids.size - 1)
list.removeAt(position)
database.removeAt(position)
updateObserver.onNext(UpdateEvent(EventType.REMOVE, position, 1))
} else {
updateObserver.onNext(UpdateEvent(EventType.UPDATE, position, 1))
}
list.addAll(position, ids)
database.insertIdsAt(position, ids)
updateObserver.onNext(UpdateEvent(EventType.INSERT, position, ids.size))
} else {
list.removeAt(position)
database.removeAt(position)
updateObserver.onNext(UpdateEvent(EventType.REMOVE, position, 1))
}
}
status.onComplete()
}.subscribeOn(Schedulers.io())
.subscribe()
)
}
override fun removeOldCache(position: Int) {
val parentSize = list.size
if (parentSize - position > LIMIT_OF_SIZE_OF_STATUSES_LIST * 11 / 10) {
val targetFirst = position + LIMIT_OF_SIZE_OF_STATUSES_LIST
val targetToRemove = list.subList(targetFirst, parentSize)
requests.add(
Completable.create {
try {
client.statusCache.delete(targetToRemove)
database.removeFromLast(targetToRemove.size)
targetToRemove.clear() //Clear this range from parent's list
updateObserver.onNext(
UpdateEvent(
EventType.REMOVE,
targetFirst,
parentSize
)
)
} catch (ignore: IllegalStateException) {}
it.onComplete()
}.subscribeOn(Schedulers.io())
.subscribe()
)
}
}
override fun close() {
requests.dispose()
database.close()
}
}
|
apache-2.0
|
fb63bd7bf2fb9b2e19784661277a99da
| 33.441176 | 96 | 0.481685 | 5.219416 | false | false | false | false |
kivensolo/UiUsingListView
|
library/network/src/main/java/com/zeke/network/interceptor/GzipRequestInterceptor.kt
|
1
|
1627
|
package com.zeke.network.interceptor
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.Response
import okio.BufferedSink
import okio.GzipSink
import okio.buffer
import java.io.IOException
/**
* author:KingZ
* date:2019/9/17
* description:This interceptor compresses the HTTP request body.
* Many webservers can't handle this!
*/
class GzipRequestInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
if (originalRequest.body() == null ||
originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest)
}
val compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), gzip(originalRequest.body()))
.build()
return chain.proceed(compressedRequest)
}
private fun gzip(body: RequestBody?): RequestBody {
return object : RequestBody() {
override fun contentType(): MediaType? {
return body!!.contentType()
}
override fun contentLength(): Long {
return -1 // We don't know the compressed length in advance!
}
@Throws(IOException::class)
override fun writeTo(sink: BufferedSink) {
val gzipSink = GzipSink(sink).buffer()
body!!.writeTo(gzipSink)
gzipSink.close()
}
}
}
}
|
gpl-2.0
|
71f6534e4240f638a1e843603c15d582
| 30.803922 | 79 | 0.621838 | 4.957187 | false | false | false | false |
siosio/intellij-community
|
uast/uast-common/src/org/jetbrains/uast/analysis/UastLocalUsageDependencyGraph.kt
|
1
|
12963
|
// 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.uast.analysis
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
import kotlin.collections.ArrayList
import kotlin.collections.HashSet
/**
* Dependency graph of UElements in some scope.
* Dependencies of element are elements needed to compute value of this element.
* Handles variable assignments and branching
*/
@ApiStatus.Experimental
class UastLocalUsageDependencyGraph private constructor(
val dependents: Map<UElement, Set<Dependent>>,
val dependencies: Map<UElement, Set<Dependency>>,
val scopesObjectsStates: Map<UElement, UScopeObjectsState>,
private val psiAnchor: PsiElement?
) {
val uAnchor: UElement?
get() = psiAnchor.toUElement()
companion object {
private val DEPENDENCY_GRAPH_KEY = Key.create<CachedValue<UastLocalUsageDependencyGraph>>("uast.local.dependency.graph")
/**
* Creates or takes from cache of [element] dependency graph
*/
@JvmStatic
fun getGraphByUElement(element: UElement): UastLocalUsageDependencyGraph? {
val sourcePsi = element.sourcePsi ?: return null
return CachedValuesManager.getCachedValue(sourcePsi, DEPENDENCY_GRAPH_KEY) {
val graph = try {
buildFromElement(sourcePsi.toUElement()!!)
}
catch (e: DependencyGraphBuilder.Companion.BuildOverflowException) {
null
}
CachedValueProvider.Result.create(graph, PsiModificationTracker.MODIFICATION_COUNT)
}
}
private fun buildFromElement(element: UElement): UastLocalUsageDependencyGraph {
val visitor = DependencyGraphBuilder()
try {
element.accept(visitor)
}
finally {
thisLogger().apply {
debug {
"graph size: dependants = ${visitor.dependents.asSequence().map { (_, arr) -> arr.size }.sum()}," +
" dependencies = ${visitor.dependencies.asSequence().map { (_, arr) -> arr.size }.sum()}"
}
debug {
"visualisation:\n${dumpDependencies(visitor.dependencies)}"
}
}
}
return UastLocalUsageDependencyGraph(visitor.dependents, visitor.dependencies, visitor.scopesStates, element.sourcePsi)
}
/**
* Connects [method] graph with [callerGraph] graph and provides connections from [uCallExpression].
* This graph may has cycles. To proper handle them, use [Dependency.ConnectionDependency].
* It is useful to analyse methods call hierarchy.
*/
@JvmStatic
fun connectMethodWithCaller(method: UMethod,
callerGraph: UastLocalUsageDependencyGraph,
uCallExpression: UCallExpression): UastLocalUsageDependencyGraph? {
val methodGraph = getGraphByUElement(method) ?: return null
val parametersToValues = method.uastParameters.mapIndexedNotNull { paramIndex, param ->
uCallExpression.getArgumentForParameter(paramIndex)?.let { param to it }
}.toMap()
val methodAndCallerMaps = MethodAndCallerMaps(method, parametersToValues, methodGraph, callerGraph)
// TODO: handle user data holders
return UastLocalUsageDependencyGraph(
dependents = methodAndCallerMaps.dependentsMap,
dependencies = methodAndCallerMaps.dependenciesMap,
scopesObjectsStates = methodGraph.scopesObjectsStates,
callerGraph.psiAnchor
)
}
}
private class MethodAndCallerMaps(
method: UMethod,
argumentValues: Map<UParameter, UExpression>,
private val methodGraph: UastLocalUsageDependencyGraph,
private val callerGraph: UastLocalUsageDependencyGraph
) {
private val parameterUsagesDependencies: Map<UElement, Set<Dependency>>
private val parameterValueDependents: Map<UElement, Set<Dependent>>
init {
val parameterUsagesDependencies = mutableMapOf<UElement, MutableSet<Dependency>>()
val parameterValueDependents = mutableMapOf<UElement, MutableSet<Dependent>>()
val searchScope = LocalSearchScope(method.sourcePsi!!)
for ((parameter, value) in argumentValues) {
val parameterValueAsDependency = Dependency.ConnectionDependency(value.extractBranchesResultAsDependency(), callerGraph)
for (reference in ReferencesSearch.search(parameter.sourcePsi!!, searchScope).asSequence().mapNotNull { it.element.toUElement() }) {
parameterUsagesDependencies[reference] = mutableSetOf(parameterValueAsDependency)
val referenceAsDependent = Dependent.CommonDependent(reference)
for (valueElement in parameterValueAsDependency.elements) {
parameterValueDependents.getOrPut(valueElement) { HashSet() }.add(referenceAsDependent)
}
}
}
this.parameterUsagesDependencies = parameterUsagesDependencies
this.parameterValueDependents = parameterValueDependents
}
val dependenciesMap: Map<UElement, Set<Dependency>>
get() = MergedMaps(callerGraph.dependencies, methodGraph.dependencies, parameterUsagesDependencies)
val dependentsMap: Map<UElement, Set<Dependent>>
get() = MergedMaps(callerGraph.dependents, methodGraph.dependents, parameterValueDependents)
private class MergedMaps<T>(val first: Map<UElement, Set<T>>,
val second: Map<UElement, Set<T>>,
val connection: Map<UElement, Set<T>>) : Map<UElement, Set<T>> {
override val entries: Set<Map.Entry<UElement, Set<T>>>
get() = HashSet<Map.Entry<UElement, Set<T>>>().apply {
addAll(first.entries)
addAll(second.entries)
addAll(connection.entries)
}
override val keys: Set<UElement>
get() = HashSet<UElement>().apply {
addAll(first.keys)
addAll(second.keys)
addAll(connection.keys)
}
// not exact size
override val size: Int
get() = first.size + second.size + connection.size
override val values: Collection<Set<T>>
get() = ArrayList<Set<T>>().apply {
addAll(first.values)
addAll(second.values)
addAll(connection.values)
}
override fun containsKey(key: UElement): Boolean = key in connection || key in first || key in second
override fun containsValue(value: Set<T>): Boolean =
connection.containsValue(value) || first.containsValue(value) || second.containsValue(value)
override fun get(key: UElement): Set<T>? = connection[key] ?: first[key] ?: second[key]
override fun isEmpty(): Boolean = first.isEmpty() || second.isEmpty() || connection.isEmpty()
}
}
}
data class UScopeObjectsState(
val lastVariablesUpdates: Map<String, Dependency.PotentialSideEffectDependency.CandidatesTree>,
val variableToValueMarks: Map<String, Collection<UValueMark>>
)
//region Dump to PlantUML section
@ApiStatus.Internal
fun UastLocalUsageDependencyGraph.dumpVisualisation(): String {
return dumpDependencies(dependencies)
}
private fun dumpDependencies(dependencies: Map<UElement, Set<Dependency>>): String = buildString {
val elements = dependencies.keys.toMutableSet().apply {
addAll(dependencies.values.flatMap { it.flatMap { dependency -> dependency.elements } })
}
val elementToID = elements.mapIndexed { index, uElement -> uElement to index }.toMap()
fun elementName(uElement: UElement) = "UElement_${elementToID[uElement]}"
append("@startuml").append("\n")
for ((element, id) in elementToID) {
append("object UElement_").append(id).appendLine(" {")
indent().append("render=\"").append(element.asRenderString().escape()).appendLine("\"")
element.sourcePsi?.let { psiElement ->
PsiDocumentManager.getInstance(psiElement.project).getDocument(psiElement.containingFile)?.let { document ->
val line = document.getLineNumber(psiElement.textOffset)
val begin = document.getLineStartOffset(line)
val end = document.getLineEndOffset(line)
indent().append("line=").append("\"").append(line + 1)
append(": ")
append(document.charsSequence.subSequence(begin, end).toString().escape().trim())
appendLine("\"")
}
}
appendLine("}")
}
val dependencyToID = dependencies.values.flatten().mapIndexed { index, dependency -> dependency to index }.toMap()
fun dependencyName(dependency: Dependency) = "${dependency.javaClass.simpleName}_${dependencyToID[dependency]}"
for ((dependency, depIndex) in dependencyToID) {
append("object ")
append(dependency.javaClass.simpleName).append("_").append(depIndex)
if (dependency is DependencyOfReference) {
appendLine(" {")
indent().append("values = ").append(dependency.referenceInfo?.possibleReferencedValues).appendLine()
append("}")
}
appendLine()
}
val candidatesTreeToID = dependencies.values.flatten()
.filterIsInstance<Dependency.PotentialSideEffectDependency>()
.map { it.candidates }
.mapIndexed { index, branch ->
branch to index
}
.toMap()
fun candidateTreeName(branch: Dependency.PotentialSideEffectDependency.CandidatesTree) =
"CandidatesTree_${candidatesTreeToID[branch]}"
var nodeIndexShift = 0
for ((tree, id) in candidatesTreeToID) {
append("package CandidatesTree_").append(id).appendLine(" {")
val nodeToID = tree.allNodes().withIndex().map { (index, node) -> node to index + nodeIndexShift }.toMap()
nodeIndexShift += nodeToID.size
fun candidateNodeName(node: Dependency.PotentialSideEffectDependency.CandidatesTree.Node) =
"CandidateNode_${nodeToID[node]}"
for ((node, nodeId) in nodeToID) {
indent().append("object CandidateNode_").append(nodeId).appendLine(" {")
indent().indent().append("type = ").append(node.javaClass.simpleName).appendLine()
if (node is Dependency.PotentialSideEffectDependency.CandidatesTree.Node.CandidateNode) {
val candidate = node.candidate
indent().indent().append("witness = ").append(candidate.dependencyWitnessValues).appendLine()
indent().indent().append("evidence = ").append(candidate.dependencyEvidence.evidenceElement?.asRenderString()?.escape()).appendLine()
generateSequence(candidate.dependencyEvidence.requires) { reqs -> reqs.flatMap { req -> req.requires }.takeUnless { it.isEmpty() } }
.flatten()
.map { it.evidenceElement?.asRenderString()?.escape() }
.toSet()
.takeUnless { it.isEmpty() }
?.joinTo(this, prefix = "$INDENT${INDENT}require = ", postfix = "\n", separator = " && ")
}
indent().append("}\n")
if (node is Dependency.PotentialSideEffectDependency.CandidatesTree.Node.CandidateNode) {
val candidate = node.candidate
indent().edge("CandidateNode_$nodeId", ".u.>", elementName(candidate.updateElement))
}
}
for (node in nodeToID.keys) {
for (anotherNode in node.next) {
indent().edge(candidateNodeName(node), "-u->", candidateNodeName(anotherNode))
}
}
append("}\n")
}
for (dependency in dependencyToID.keys) {
when (dependency) {
is Dependency.ArgumentDependency, is Dependency.BranchingDependency, is Dependency.CommonDependency -> {
for (element in dependency.elements) {
edge(dependencyName(dependency), "-u->", elementName(element))
}
}
is Dependency.ConnectionDependency -> {
}
is Dependency.PotentialSideEffectDependency -> {
edge(dependencyName(dependency), ".u.>", candidateTreeName(dependency.candidates))
}
}
}
for (element in elementToID.keys) {
for (elementDependency in dependencies[element].orEmpty()) {
edge(
elementName(element),
if (elementDependency is Dependency.PotentialSideEffectDependency) {
".u.>"
}
else {
"-u->"
},
dependencyName(elementDependency)
)
}
}
appendLine("@enduml")
}
private fun StringBuilder.edge(begin: String, type: String, end: String) {
append(begin).append(" ").append(type).append(" ").append(end).appendLine()
}
private const val INDENT = " "
private fun StringBuilder.indent(): StringBuilder {
return append(INDENT)
}
private fun String.escape() =
replace("\"", "<U+0022>")
.replace("(", "<U+0028>")
.replace(")", "<U+0029>")
//endregion
|
apache-2.0
|
01c595e49be15d7c06af118e1c76cb9c
| 39.386293 | 141 | 0.689578 | 4.637925 | false | false | false | false |
asarazan/Bismarck
|
app/src/commonMain/kotlin/net/sarazan/bismarck/mobile/FooViewModel.kt
|
1
|
923
|
package net.sarazan.bismarck.mobile
import kotlin.native.concurrent.ThreadLocal
import kotlinx.coroutines.*
import net.sarazan.bismarck.Bismarck
import net.sarazan.bismarck.platform.BismarckDispatchers
import net.sarazan.bismarck.ratelimit.SimpleFreshness
class FooViewModel(private val scope: CoroutineScope) {
constructor() : this(CoroutineScope(BismarckDispatchers.main))
@ThreadLocal
companion object {
private var counter = 0
val bismarck = Bismarck.create<String> {
checkOnLaunch = true
freshness = SimpleFreshness(60 * 1000)
}
}
val foo = bismarck.rescope(scope).apply {
println("Created FooViewModel")
scope.launch {
while (true) {
delay(1000)
insert("${counter++}")
}
}
}
fun tearDown() {
println("Tearing Down")
scope.cancel()
}
}
|
apache-2.0
|
b5bd9f6ca24e78d6c4d7a2793bd616a3
| 24.638889 | 66 | 0.631636 | 4.416268 | false | false | false | false |
K0zka/kerub
|
src/main/kotlin/com/github/kerubistan/kerub/utils/junix/benchmarks/fio/Fio.kt
|
2
|
1346
|
package com.github.kerubistan.kerub.utils.junix.benchmarks.fio
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.module.kotlin.readValue
import com.github.kerubistan.kerub.host.executeOrDie
import com.github.kerubistan.kerub.model.HostCapabilities
import com.github.kerubistan.kerub.utils.createObjectMapper
import com.github.kerubistan.kerub.utils.junix.common.OsCommand
import com.github.kerubistan.kerub.utils.junix.common.anyPackageNamed
import org.apache.sshd.client.session.ClientSession
import java.util.UUID
object Fio : OsCommand {
override fun available(hostCapabilities: HostCapabilities?): Boolean = hostCapabilities.anyPackageNamed("fio")
private const val runtimeLimit = 10
private val mapper = createObjectMapper(prettyPrint = false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
fun benchmarkIoDevice(session: ClientSession, device: String): FioBenchmarkResults {
session.createSftpClient().use { sftp ->
val iniFile = "/tmp/${UUID.randomUUID()}"
sftp.write(iniFile).writer(Charsets.US_ASCII).use {
it.write("""
[rand]
filename=$device
readwrite=randrw
runtime=$runtimeLimit
[seq]
filename=$device
readwrite=rw
runtime=$runtimeLimit
""")
}
return mapper.readValue(session.executeOrDie("fio $iniFile --output-format=json"))
}
}
}
|
apache-2.0
|
a119313e2a8fa232d88f06296e85a05c
| 31.853659 | 111 | 0.797177 | 3.823864 | false | false | false | false |
K0zka/kerub
|
src/main/kotlin/com/github/kerubistan/kerub/utils/ListUtils.kt
|
1
|
3855
|
package com.github.kerubistan.kerub.utils
import com.github.kerubistan.kerub.model.Entity
import io.github.kerubistan.kroki.collections.concat
operator fun <X, Y> Collection<X>.times(other: Collection<Y>): List<Pair<X, Y>> {
return this.map { x -> other.map { y -> x to y } }.concat()
}
// move to kroki
inline fun <reified C : Any> Iterable<*>.hasAny(predicate: (C) -> Boolean = { true }) =
this.any { it is C && predicate(it) }
// move to kroki
inline fun <reified C : Any> Iterable<*>.hasNone(crossinline predicate: (C) -> Boolean = { true }) =
!this.hasAny(predicate)
inline fun <reified C : Any> Iterable<*>.any() = this.any { it is C }
inline fun <reified C : Any> Iterable<*>.none() = this.none { it is C }
fun <T> Collection<T>.containsAny(vararg elems: T) =
elems.any {
this.contains(it)
}
fun <K, V : Entity<K>> Collection<V>.toMap(): Map<K, V> =
this.associateBy { it.id }
fun <T> Collection<T>.avgBy(fn: (T) -> Int): Double {
var sum = 0
this.forEach { sum += fn(it) }
return sum.toDouble() / this.size
}
// TODO should be moved to kroki
inline fun <T> List<T>.update(
selector: (T) -> Boolean, default: () -> T = { throw IllegalArgumentException("key not found") }, map: (T) -> T
): List<T> =
this.firstOrNull(selector)?.let {
this.filterNot(selector) + map(it)
} ?: this + map(default())
/**
* Update a list with another, different type of items. Not updated items will remain the same, updates
* not matching a data will be ignored.
* @param updateList a list of elements with which the list is to be updated
* @param selfKey extract the join key from the original list
* @param upKey extract the join key from the update list
* @param merge creates an updated instance from the original
*/
inline fun <T : Any, U : Any, I : Any> List<T>.update(
updateList: List<U>,
selfKey: (T) -> I,
upKey: (U) -> I,
merge: (T, U) -> T
): List<T> = this.update(updateList, selfKey, upKey, merge, { it }, { null })
/**
* Update a list with another, different type of items
* @param updateList a list of elements with which the list is to be updated
* @param selfKey extract the join key from the original list
* @param upKey extract the join key from the update list
* @param merge creates an updated instance from the original
* @param updateMiss handle items that did not get updated
* @param selfMiss handle updates that do not match any data
*/
inline fun <T : Any, U : Any, I : Any> List<T>.update(
updateList: List<U>,
selfKey: (T) -> I,
upKey: (U) -> I,
merge: (T, U) -> T,
updateMiss: (T) -> T?,
selfMiss: (U) -> T?
): List<T> {
val selfMap = this.associateBy(selfKey)
val updateMap = updateList.associateBy(upKey)
return selfMap.map { (key, value) ->
updateMap[key]?.let { merge(value, it) } ?: updateMiss(value)
}.filterNotNull() + updateMap.filterNot { selfMap.containsKey(it.key) }.map {
selfMiss(it.value)
}.filterNotNull()
}
fun <T> List<T>.subLists(minLength: Int = 1, selector: (T) -> Boolean): List<List<T>> {
val ret = mutableListOf<List<T>>()
var start: Int? = null
for (idx in this.indices) {
val match = selector(this[idx])
if (start != null) {
if (!match) {
if (idx - 1 - start > minLength) {
ret += listOf(this.subList(start, idx))
}
start = null
}
} else if (match) {
start = idx
}
}
if (start != null && this.size - 1 - start >= minLength) {
ret += listOf(this.subList(start, this.size + 1))
}
return ret
}
fun <I, E : Entity<I>> Collection<E>.byId() = this.associateBy { it.id }
inline fun <reified C : Any, reified R : Any> Iterable<*>.mapInstances(predicate: (C) -> R?) = this.mapNotNull {
if (it is C) {
predicate(it)
} else null
}
operator fun <T> Collection<T>?.contains(element: T): Boolean =
this?.contains(element) ?: false
|
apache-2.0
|
3a745d730f16a65ea633830d2ad745d2
| 31.669492 | 113 | 0.641245 | 3.084 | false | false | false | false |
nimakro/tornadofx
|
src/test/kotlin/tornadofx/testapps/BuilderWindowTest.kt
|
3
|
2389
|
package tornadofx.testapps
import javafx.application.Platform
import javafx.scene.paint.Color
import javafx.scene.text.FontWeight
import javafx.stage.StageStyle.DECORATED
import javafx.stage.StageStyle.UNDECORATED
import tornadofx.*
class BuilderWindowTestApp : App(DangerButtonView::class)
class DangerButtonView : View("Do not click the button!") {
override val root = stackpane {
setPrefSize(400.0, 150.0)
hbox {
button("Don't click me") {
style {
fontSize = 20.px
fontWeight = FontWeight.BOLD
textFill = Color.RED
}
action {
builderWindow("What do you want?", stageStyle = UNDECORATED, owner = primaryStage) {
vbox(10) {
style {
padding = box(20.px)
borderColor += box(Color.ORANGE)
borderWidth += box(2.px)
}
label("So, you clicked it anyway.. What do you want?") {
style {
fontWeight = FontWeight.BOLD
}
}
hbox(10) {
button("Tell them you clicked").action {
[email protected] = "It's not dangerous to click the button :)"
close()
}
button("Close app").action {
Platform.exit()
}
button("Cancel").action {
close()
}
}
}
}
}
}
button("the same in internalWindow").action {
openInternalBuilderWindow("Internal window", modal = true, overlayPaint = Color.DARKRED) {
vbox(20) {
label("opened in an internalwindow")
button("close").action { close() }
}
}
}
}
}
}
|
apache-2.0
|
83e6589e712c800ee88d2e712756d61b
| 36.936508 | 109 | 0.391796 | 6.270341 | false | false | false | false |
androidx/androidx
|
collection/integration-tests/testapp/src/main/kotlin/androidx/collection/integration/SparseArrayCompatKotlin.kt
|
3
|
3871
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.collection.integration
import androidx.collection.SparseArrayCompat
/**
* Integration (actually build) test that SparseArrayCompat can be subclassed.
*/
@Suppress("unused")
class SparseArrayCompatKotlin : SparseArrayCompat<Int>() {
override fun clone(): SparseArrayCompat<Int> {
return super.clone()
}
override fun get(key: Int): Int? {
return super.get(key)
}
override fun get(key: Int, defaultValue: Int): Int {
return super.get(key, defaultValue)
}
@Deprecated(
message = "Alias for remove(int).",
replaceWith = ReplaceWith("remove(key)"),
)
override fun delete(key: Int) {
@Suppress("DEPRECATION")
super.delete(key)
}
override fun remove(key: Int) {
super.remove(key)
}
override fun remove(key: Int, value: Any?): Boolean {
return super.remove(key, value)
}
override fun removeAt(index: Int) {
super.removeAt(index)
}
override fun removeAtRange(index: Int, size: Int) {
super.removeAtRange(index, size)
}
override fun replace(key: Int, value: Int): Int? {
return super.replace(key, value)
}
override fun replace(key: Int, oldValue: Int, newValue: Int): Boolean {
return super.replace(key, oldValue, newValue)
}
override fun put(key: Int, value: Int) {
super.put(key, value)
}
override fun putAll(other: SparseArrayCompat<out Int>) {
super.putAll(other)
}
override fun putIfAbsent(key: Int, value: Int): Int? {
return super.putIfAbsent(key, value)
}
override fun size(): Int {
return super.size()
}
override fun isEmpty(): Boolean {
return super.isEmpty()
}
override fun keyAt(index: Int): Int {
return super.keyAt(index)
}
override fun valueAt(index: Int): Int {
return super.valueAt(index)
}
override fun setValueAt(index: Int, value: Int) {
super.setValueAt(index, value)
}
override fun indexOfKey(key: Int): Int {
return super.indexOfKey(key)
}
override fun indexOfValue(value: Int): Int {
return super.indexOfValue(value)
}
override fun containsKey(key: Int): Boolean {
return super.containsKey(key)
}
override fun containsValue(value: Int): Boolean {
return super.containsValue(value)
}
override fun clear() {
super.clear()
}
override fun append(key: Int, value: Int) {
super.append(key, value)
}
override fun toString(): String {
return super.toString()
}
override fun equals(other: Any?): Boolean {
return super.equals(other)
}
override fun hashCode(): Int {
return super.hashCode()
}
}
/**
* Sample usage of SparseArrayCompat for ensuring source compatibility.
*/
@Suppress("unused")
fun sparseArraySourceCompatibility() {
val sparseArray = SparseArrayCompat<Int>()
// Property / function syntax.
sparseArray.isEmpty
@Suppress("UsePropertyAccessSyntax")
sparseArray.isEmpty()
sparseArray.size()
// Operator access
@Suppress("UNUSED_VARIABLE")
val returnsNullable = sparseArray[0] == null
}
|
apache-2.0
|
dc46ee8a9d3df0c774cac0a854e636a0
| 23.66242 | 78 | 0.64247 | 4.249177 | false | false | false | false |
androidx/androidx
|
compose/ui/ui-text/benchmark/src/main/java/androidx/compose/ui/text/benchmark/TextBenchmarkHelper.kt
|
3
|
7507
|
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.benchmark
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.intl.LocaleList
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.BaselineShift
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextGeometricTransform
import androidx.compose.ui.unit.em
import androidx.compose.ui.unit.sp
import kotlin.math.ceil
import kotlin.random.Random
class RandomTextGenerator(
private val alphabet: Alphabet = Alphabet.Latin,
private val random: Random = Random(0)
) {
// a set of predefined TextStyle's to add to styled text
private val nonMetricAffectingTextStyles = arrayOf(
SpanStyle(color = Color.Blue),
SpanStyle(background = Color.Cyan),
SpanStyle(textDecoration = TextDecoration.Underline),
SpanStyle(shadow = Shadow(Color.Black, Offset(3f, 3f), 2.0f))
)
private val metricAffectingTextStyles = arrayOf(
SpanStyle(fontSize = 18.sp),
SpanStyle(fontSize = 2.em),
SpanStyle(fontWeight = FontWeight.Bold),
SpanStyle(fontStyle = FontStyle.Italic),
SpanStyle(letterSpacing = 0.2.em),
SpanStyle(baselineShift = BaselineShift.Subscript),
SpanStyle(textGeometricTransform = TextGeometricTransform(0.5f, 0.5f)),
SpanStyle(localeList = LocaleList("it"))
)
private fun getSpanStyleList(hasMetricAffectingStyle: Boolean) =
nonMetricAffectingTextStyles + if (hasMetricAffectingStyle) {
metricAffectingTextStyles
} else {
arrayOf()
}
/**
* Creates a sequence of characters group of length [length].
*/
private fun nextWord(length: Int): String = List(length) {
alphabet.charRanges.random(random).random(random).toChar()
}.joinToString(separator = "")
/**
* Create a sequence of character groups separated by the [Alphabet.space]. Each character group consists of
* [wordLength] characters. The total length of the returned string is [length].
*/
fun nextParagraph(
length: Int,
wordLength: Int = 9
): String {
return if (length == 0) {
""
} else {
StringBuilder().apply {
while (this.length < length) {
append(nextWord(wordLength))
append(alphabet.space)
}
}.substring(0, length)
}
}
/**
* Given a [text] mark each character group with a predefined TextStyle. The order of TextStyles is predefined,
* and not randomized on purpose in order to get a consistent result in our benchmarks.
* @param text The text on which the markup is applied.
* @param styleCount The number of the text styles applied on the [text].
* @param hasMetricAffectingStyle Whether to apply metric affecting [TextStyle]s text, which
* increases the difficulty to measure text.
*/
fun createStyles(
text: String,
styleCount: Int = text.split(alphabet.space).size,
hasMetricAffectingStyle: Boolean = true
): List<AnnotatedString.Range<SpanStyle>> {
val spanStyleList = getSpanStyleList(hasMetricAffectingStyle)
val words = text.split(alphabet.space)
var index = 0
var styleIndex = 0
val stylePerWord = styleCount / words.size
val remains = styleCount % words.size
return words.withIndex().flatMap { (wordIndex, word) ->
val start = index
val end = start + word.length
index += word.length + 1
val styleCountOnWord = stylePerWord + if (wordIndex < remains) 1 else 0
List(styleCountOnWord) {
AnnotatedString.Range(
start = start,
end = end,
item = spanStyleList[styleIndex++ % spanStyleList.size]
)
}
}
}
/**
* Create an [AnnotatedString] with randomly generated text but predefined TextStyles.
* @see nextParagraph
* @see createStyles
*/
fun nextAnnotatedString(
length: Int,
wordLength: Int = 9,
styleCount: Int,
hasMetricAffectingStyle: Boolean = true
): AnnotatedString {
val text = nextParagraph(length, wordLength)
return AnnotatedString(
text = text,
spanStyles = createStyles(text, styleCount, hasMetricAffectingStyle)
)
}
/**
* Create a list of word(character group)-[TextStyle] pairs, words are randomly generated while
* the [TextStyle] is created in a fixed order.
*/
fun nextStyledWordList(
length: Int,
wordLength: Int = 9,
hasMetricAffectingStyle: Boolean = true
): List<Pair<String, SpanStyle>> {
val textStyleList = getSpanStyleList(hasMetricAffectingStyle)
val wordCount = ceil(length.toFloat() / (wordLength + 1)).toInt()
var styleIndex = 0
return List(wordCount) {
Pair("${nextWord(length)} ", textStyleList[styleIndex++ % textStyleList.size])
}
}
}
/**
* Defines the character ranges to be picked randomly for a script.
*/
class Alphabet(
val charRanges: List<IntRange>,
val space: Char,
val name: String
) {
override fun toString(): String {
return name
}
companion object {
val Latin = Alphabet(
charRanges = listOf(
IntRange('a'.code, 'z'.code),
IntRange('A'.code, 'Z'.code)
),
space = ' ',
name = "Latin"
)
val Cjk = Alphabet(
charRanges = listOf(
IntRange(0x4E00, 0x62FF),
IntRange(0x6300, 0x77FF),
IntRange(0x7800, 0x8CFF)
),
space = 0x3000.toChar(),
name = "CJK"
)
}
}
/**
* Used by [RandomTextGenerator] in order to create plain text or multi-styled text.
*/
enum class TextType {
PlainText,
StyledText
}
/**
* Given a list of Arrays and make cartesian product each of them with the [array].
*/
fun List<Array<Any>>.cartesian(vararg array: Any): List<Array<Any>> {
return flatMap { row -> array.map { row + it } }
}
/**
* Creates a cartesian product of the given arrays.
*/
fun cartesian(vararg arrays: Array<Any?>): List<Array<Any?>> {
return arrays.fold(listOf(arrayOf())) { acc, list ->
// add items from the current list
// to each list that was accumulated
acc.flatMap { accListItem -> list.map { accListItem + it } }
}
}
|
apache-2.0
|
e43c3840b3afca5b35d62f6e0b849b52
| 32.070485 | 115 | 0.634075 | 4.346844 | false | false | false | false |
androidx/androidx
|
wear/compose/compose-material/src/commonMain/kotlin/androidx/wear/compose/material/ScalingLazyListItemScope.kt
|
3
|
4223
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Stable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
/**
* Receiver scope being used by the item content parameter of ScalingLazyColumn.
*/
@Stable
@ScalingLazyScopeMarker
public sealed interface ScalingLazyListItemScope {
/**
* Have the content fill the [Constraints.maxWidth] and [Constraints.maxHeight] of the parent
* measurement constraints by setting the [minimum width][Constraints.minWidth] to be equal to
* the [maximum width][Constraints.maxWidth] multiplied by [fraction] and the [minimum
* height][Constraints.minHeight] to be equal to the [maximum height][Constraints.maxHeight]
* multiplied by [fraction]. Note that, by default, the [fraction] is 1, so the modifier will
* make the content fill the whole available space. [fraction] must be between `0` and `1`.
*
* Regular [Modifier.fillMaxSize] can't work inside the scrolling layouts as the items are
* measured with [Constraints.Infinity] as the constraints for the main axis.
*/
fun Modifier.fillParentMaxSize(
/*@FloatRange(from = 0.0, to = 1.0)*/
fraction: Float = 1f
): Modifier
/**
* Have the content fill the [Constraints.maxWidth] of the parent measurement constraints
* by setting the [minimum width][Constraints.minWidth] to be equal to the
* [maximum width][Constraints.maxWidth] multiplied by [fraction]. Note that, by default, the
* [fraction] is 1, so the modifier will make the content fill the whole parent width.
* [fraction] must be between `0` and `1`.
*
* Regular [Modifier.fillMaxWidth] can't work inside the scrolling horizontally layouts as the
* items are measured with [Constraints.Infinity] as the constraints for the main axis.
*/
fun Modifier.fillParentMaxWidth(
/*@FloatRange(from = 0.0, to = 1.0)*/
fraction: Float = 1f
): Modifier
/**
* Have the content fill the [Constraints.maxHeight] of the incoming measurement constraints
* by setting the [minimum height][Constraints.minHeight] to be equal to the
* [maximum height][Constraints.maxHeight] multiplied by [fraction]. Note that, by default, the
* [fraction] is 1, so the modifier will make the content fill the whole parent height.
* [fraction] must be between `0` and `1`.
*
* Regular [Modifier.fillMaxHeight] can't work inside the scrolling vertically layouts as the
* items are measured with [Constraints.Infinity] as the constraints for the main axis.
*/
fun Modifier.fillParentMaxHeight(
/*@FloatRange(from = 0.0, to = 1.0)*/
fraction: Float = 1f
): Modifier
}
internal data class ScalingLazyListItemScopeImpl(
val density: Density,
val constraints: Constraints
) : ScalingLazyListItemScope {
private val maxWidth: Dp = with(density) { constraints.maxWidth.toDp() }
private val maxHeight: Dp = with(density) { constraints.maxHeight.toDp() }
override fun Modifier.fillParentMaxSize(fraction: Float) = size(
maxWidth * fraction,
maxHeight * fraction
)
override fun Modifier.fillParentMaxWidth(fraction: Float) =
width(maxWidth * fraction)
override fun Modifier.fillParentMaxHeight(fraction: Float) =
height(maxHeight * fraction)
}
|
apache-2.0
|
8cdc3d3cf39c18406c1d0a0ec05d7d56
| 42.536082 | 99 | 0.717263 | 4.440589 | false | false | false | false |
GunoH/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/api/GHRepositoryPath.kt
|
12
|
961
|
// 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.github.api
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtil
class GHRepositoryPath(val owner: String, val repository: String) {
fun toString(showOwner: Boolean) = if (showOwner) "$owner/$repository" else repository
@NlsSafe
override fun toString() = "$owner/$repository"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GHRepositoryPath) return false
if (!owner.equals(other.owner, true)) return false
if (!repository.equals(other.repository, true)) return false
return true
}
override fun hashCode(): Int {
var result = StringUtil.stringHashCodeInsensitive(owner)
result = 31 * result + StringUtil.stringHashCodeInsensitive(repository)
return result
}
}
|
apache-2.0
|
498238130192e5afe3ecd988dbd18c8f
| 32.172414 | 140 | 0.737773 | 4.196507 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/findUsages/KotlinInnerClassInheritorsSearcher.kt
|
1
|
2938
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.findUsages
import com.intellij.java.indexing.JavaIndexingBundle
import com.intellij.openapi.application.QueryExecutorBase
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.openapi.progress.ProgressManager.checkCanceled
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ClassInheritorsSearch
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.Processor
import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration
import org.jetbrains.kotlin.asJava.toLightClass
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class KotlinInnerClassInheritorsSearcher: QueryExecutorBase<PsiClass, ClassInheritorsSearch.SearchParameters>() {
override fun processQuery(queryParameters: ClassInheritorsSearch.SearchParameters, consumer: Processor<in PsiClass>) {
val searchScope = queryParameters.scope.safeAs<LocalSearchScope>() ?: return
val classToProcess = queryParameters.classToProcess
val baseClass = classToProcess.safeAs<KtLightClassForSourceDeclaration>() ?: return
val kotlinOrigin = baseClass.kotlinOrigin
if (runReadAction { kotlinOrigin.isTopLevel() || (!kotlinOrigin.isLocal && !kotlinOrigin.isPrivate()) }) return
val progress = ProgressIndicatorProvider.getGlobalProgressIndicator()
if (progress != null) {
progress.pushState()
progress.text =
runReadAction { baseClass.name }?.let { JavaIndexingBundle.message("psi.search.inheritors.of.class.progress", it) }
?: JavaIndexingBundle.message("psi.search.inheritors.progress")
}
try {
for (element in searchScope.scope) {
checkCanceled()
if (!runReadAction { processElementInScope(element, classToProcess, consumer) }) break
}
} finally {
progress?.popState()
}
}
private fun processElementInScope(element: PsiElement, classToProcess: PsiClass, consumer: Processor<in PsiClass>): Boolean {
val classesOrObjects = PsiTreeUtil.findChildrenOfType(element, KtClassOrObject::class.java)
for (ktClassOrObject in classesOrObjects) {
checkCanceled()
if (ktClassOrObject.superTypeListEntries.isEmpty()) continue
ktClassOrObject.toLightClass()?.let {
if (it.isInheritor(classToProcess, true) && !consumer.process(it)) {
return false
}
}
}
return true
}
}
|
apache-2.0
|
80fbe0e8322f132eb9e0dbe4e6c00f5f
| 47.180328 | 131 | 0.723962 | 5.237077 | false | false | false | false |
drmashu/dikonsuite
|
buri/src/main/kotlin/io/github/drmashu/buri/buri.kt
|
1
|
5772
|
package io.github.drmashu.buri
import io.github.drmashu.dikon.Container
import io.github.drmashu.dikon.Dikon
import io.github.drmashu.dikon.Factory
import io.github.drmashu.dikon.Holder
import org.apache.logging.log4j.LogManager
import org.eclipse.jetty.servlet.DefaultServlet
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.util.regex.Pattern
/**
* Buri バインダークラス.
* URIとViewModelを結びつけるために定義を解釈し、リクエストに応じてViewModelのアクションを呼ぶ。
* これを継承し、バインディング設定を行ったサブクラスを作成して使用する。
* @author NAGASAWA Takahiro<[email protected]>
*/
public abstract class Buri() : DefaultServlet() {
companion object {
val groupNamePattern = Pattern.compile("\\(\\?<([a-zA-Z][a-zA-Z0-9]+)>")
val logger = LogManager.getLogger(Buri::class.java)
}
/**
* 設定
*/
abstract val config: Map<String, Factory<*>>
/**
* Dikon
*/
public val dikon: Dikon = Dikon(config)
/** パスとアクションを結びつけるマップ */
val pathMap: Map<String, List<Pair<NamedPattern, Factory<*>>>>
/**
* 初期化
*/
init {
logger.entry()
var result: MutableMap<String, MutableList<kotlin.Pair<NamedPattern, Factory<*>>>> = HashMap()
// "/"で始まるキーはビューまたはアクションとして扱う
for (entry in dikon.objectMap) {
if (!entry.key.startsWith("/")) continue
var key = entry.key
val methodIdx = key.lastIndexOf(":")
val methods = if (methodIdx > 0) {
val method = key.substring(methodIdx+1)
key = key.substring(0, methodIdx)
method.split(delimiters = ",")
} else {
listOf("GET", "POST")
}
val pattern = Pattern.compile(key)
val names = ArrayList<String>()
val patternStr = pattern.pattern()
val matcher = groupNamePattern.matcher(patternStr)
while (matcher.find()) {
names.add(matcher.group(1))
}
val value = NamedPattern(pattern, names.toArray(arrayOfNulls<String>(names.size))) to entry.value
for (method in methods) {
var list = result.get(method)
if (list == null) {
list = ArrayList()
result.put(method, list)
}
list.add(value)
}
}
pathMap = result
logger.exit()
}
/**
* サービス実行.
* パス/メソッドに応じたアクション/ビューを呼び出す
*/
public override final fun service(req: HttpServletRequest, res: HttpServletResponse) {
logger.entry(req, res)
val list = pathMap[req.method]
if (list != null) {
for(item in list) {
val pattern = item.first.pattern
val matcher = pattern.matcher(req.pathInfo)
if (matcher.matches()) {
val paramMap: MutableMap<String, Factory<*>> = hashMapOf(
"request" to Holder(req),
"response" to Holder(res),
"context" to Holder(servletContext)
)
for(name in item.first.names) {
paramMap.put(name, Holder(matcher.group(name)))
}
// デフォルトのコンテントタイプをhtmlにする
res.contentType = "text/html"
res.characterEncoding = "UTF-8"
val factory = item.second
callAction(factory, paramMap, req)
return
}
}
}
super.service(req, res)
logger.exit()
}
/**
*
*/
fun callAction(factory: Factory<*>, paramMap: MutableMap<String, Factory<*>>, req: HttpServletRequest) {
logger.entry(factory, paramMap, req)
val action = factory.get(ParamContainer(dikon, paramMap))
logger.trace("action $action")
try {
when (action) {
is HttpAction -> {
action.___buri = this
when (req.method) {
"GET" -> action.get()
"POST" -> action.post()
"PUT" -> action.put()
"DELETE" -> action.delete()
else -> action.get()
}
}
is Action -> {
}
else -> throw InvalidTargetException()
}
} finally {
logger.exit()
}
}
}
/**
*
*/
public class InvalidTargetException : Exception()
/**
* 名前付きグループの名前をパターンと一緒に保持する
*/
public class NamedPattern(val pattern: Pattern, val names: Array<String>)
/**
* パスのパラメータと、Dikonの両方から値を取得するコンテナ
*/
class ParamContainer(val dikon: Dikon, val params: Map<String, Factory<*>>): Container {
companion object {
val logger = LogManager.getLogger(ParamContainer::class.java)
}
/**
*
*/
override fun get(name: String): Any? {
logger.entry(name)
val param = params[name]
var result :Any? = null
if (param != null) {
result = param.get(dikon)
} else {
result = dikon[name]
}
logger.exit(result)
return result
}
}
|
apache-2.0
|
1cf8d9c68db83b0b946a5e498bd53886
| 29.474286 | 109 | 0.523068 | 4.048595 | false | false | false | false |
android/compose-samples
|
Jetchat/app/src/main/java/com/example/compose/jetchat/conversation/MessageFormatter.kt
|
1
|
6205
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.compose.jetchat.conversation
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.BaselineShift
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.sp
// Regex containing the syntax tokens
val symbolPattern by lazy {
Regex("""(https?://[^\s\t\n]+)|(`[^`]+`)|(@\w+)|(\*[\w]+\*)|(_[\w]+_)|(~[\w]+~)""")
}
// Accepted annotations for the ClickableTextWrapper
enum class SymbolAnnotationType {
PERSON, LINK
}
typealias StringAnnotation = AnnotatedString.Range<String>
// Pair returning styled content and annotation for ClickableText when matching syntax token
typealias SymbolAnnotation = Pair<AnnotatedString, StringAnnotation?>
/**
* Format a message following Markdown-lite syntax
* | @username -> bold, primary color and clickable element
* | http(s)://... -> clickable link, opening it into the browser
* | *bold* -> bold
* | _italic_ -> italic
* | ~strikethrough~ -> strikethrough
* | `MyClass.myMethod` -> inline code styling
*
* @param text contains message to be parsed
* @return AnnotatedString with annotations used inside the ClickableText wrapper
*/
@Composable
fun messageFormatter(
text: String,
primary: Boolean
): AnnotatedString {
val tokens = symbolPattern.findAll(text)
return buildAnnotatedString {
var cursorPosition = 0
val codeSnippetBackground =
if (primary) {
MaterialTheme.colorScheme.secondary
} else {
MaterialTheme.colorScheme.surface
}
for (token in tokens) {
append(text.slice(cursorPosition until token.range.first))
val (annotatedString, stringAnnotation) = getSymbolAnnotation(
matchResult = token,
colorScheme = MaterialTheme.colorScheme,
primary = primary,
codeSnippetBackground = codeSnippetBackground
)
append(annotatedString)
if (stringAnnotation != null) {
val (item, start, end, tag) = stringAnnotation
addStringAnnotation(tag = tag, start = start, end = end, annotation = item)
}
cursorPosition = token.range.last + 1
}
if (!tokens.none()) {
append(text.slice(cursorPosition..text.lastIndex))
} else {
append(text)
}
}
}
/**
* Map regex matches found in a message with supported syntax symbols
*
* @param matchResult is a regex result matching our syntax symbols
* @return pair of AnnotatedString with annotation (optional) used inside the ClickableText wrapper
*/
private fun getSymbolAnnotation(
matchResult: MatchResult,
colorScheme: ColorScheme,
primary: Boolean,
codeSnippetBackground: Color
): SymbolAnnotation {
return when (matchResult.value.first()) {
'@' -> SymbolAnnotation(
AnnotatedString(
text = matchResult.value,
spanStyle = SpanStyle(
color = if (primary) colorScheme.inversePrimary else colorScheme.primary,
fontWeight = FontWeight.Bold
)
),
StringAnnotation(
item = matchResult.value.substring(1),
start = matchResult.range.first,
end = matchResult.range.last,
tag = SymbolAnnotationType.PERSON.name
)
)
'*' -> SymbolAnnotation(
AnnotatedString(
text = matchResult.value.trim('*'),
spanStyle = SpanStyle(fontWeight = FontWeight.Bold)
),
null
)
'_' -> SymbolAnnotation(
AnnotatedString(
text = matchResult.value.trim('_'),
spanStyle = SpanStyle(fontStyle = FontStyle.Italic)
),
null
)
'~' -> SymbolAnnotation(
AnnotatedString(
text = matchResult.value.trim('~'),
spanStyle = SpanStyle(textDecoration = TextDecoration.LineThrough)
),
null
)
'`' -> SymbolAnnotation(
AnnotatedString(
text = matchResult.value.trim('`'),
spanStyle = SpanStyle(
fontFamily = FontFamily.Monospace,
fontSize = 12.sp,
background = codeSnippetBackground,
baselineShift = BaselineShift(0.2f)
)
),
null
)
'h' -> SymbolAnnotation(
AnnotatedString(
text = matchResult.value,
spanStyle = SpanStyle(
color = if (primary) colorScheme.inversePrimary else colorScheme.primary
)
),
StringAnnotation(
item = matchResult.value,
start = matchResult.range.first,
end = matchResult.range.last,
tag = SymbolAnnotationType.LINK.name
)
)
else -> SymbolAnnotation(AnnotatedString(matchResult.value), null)
}
}
|
apache-2.0
|
e5f506edd4c07da5636f3eb834919979
| 33.472222 | 99 | 0.613215 | 5.016168 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/model/kapt/KaptModelBuilderService.kt
|
1
|
6385
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradleTooling.model.kapt
import org.gradle.api.Named
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.jetbrains.kotlin.idea.gradleTooling.*
import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder
import org.jetbrains.plugins.gradle.tooling.ModelBuilderContext
import org.jetbrains.plugins.gradle.tooling.ModelBuilderService
import java.io.File
import java.io.Serializable
import java.lang.reflect.Modifier
interface KaptSourceSetModel : Serializable {
val sourceSetName: String
val isTest: Boolean
val generatedSourcesDir: String
val generatedClassesDir: String
val generatedKotlinSourcesDir: String
val generatedSourcesDirFile get() = generatedSourcesDir.takeIf { it.isNotEmpty() }?.let(::File)
val generatedClassesDirFile get() = generatedClassesDir.takeIf { it.isNotEmpty() }?.let(::File)
val generatedKotlinSourcesDirFile get() = generatedKotlinSourcesDir.takeIf { it.isNotEmpty() }?.let(::File)
}
class KaptSourceSetModelImpl(
override val sourceSetName: String,
override val isTest: Boolean,
override val generatedSourcesDir: String,
override val generatedClassesDir: String,
override val generatedKotlinSourcesDir: String
) : KaptSourceSetModel
interface KaptGradleModel : Serializable {
val isEnabled: Boolean
val buildDirectory: File
val sourceSets: List<KaptSourceSetModel>
}
class KaptGradleModelImpl(
override val isEnabled: Boolean,
override val buildDirectory: File,
override val sourceSets: List<KaptSourceSetModel>
) : KaptGradleModel
class KaptModelBuilderService : AbstractKotlinGradleModelBuilder(), ModelBuilderService.Ex {
override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder {
return ErrorMessageBuilder.create(project, e, "Gradle import errors")
.withDescription("Unable to build kotlin-kapt plugin configuration")
}
override fun canBuild(modelName: String?): Boolean = modelName == KaptGradleModel::class.java.name
override fun buildAll(modelName: String?, project: Project): KaptGradleModelImpl? {
return buildAll(project, null)
}
override fun buildAll(modelName: String, project: Project, builderContext: ModelBuilderContext): KaptGradleModelImpl? {
return buildAll(project, builderContext)
}
private fun buildAll(project: Project, builderContext: ModelBuilderContext?): KaptGradleModelImpl? {
val androidVariantRequest = AndroidAwareGradleModelProvider.parseParameter(project, builderContext?.parameter)
if (androidVariantRequest.shouldSkipBuildAllCall()) return null
val kaptPlugin: Plugin<*>? = project.plugins.findPlugin("kotlin-kapt")
val kaptIsEnabled = kaptPlugin != null
val sourceSets = mutableListOf<KaptSourceSetModel>()
if (kaptIsEnabled) {
// When running in Android Studio, Android Studio would request specific source sets only to avoid syncing
// currently not active build variants. We convert names to the lower case to avoid ambiguity with build variants
// accidentally named starting with upper case.
val targets = project.getTargets()
fun handleCompileTask(moduleName: String, compileTask: Task) {
if (compileTask.javaClass.name !in kotlinCompileJvmTaskClasses) {
return
}
val sourceSetName = compileTask.getSourceSetName()
val isTest = sourceSetName.toLowerCase().endsWith("test")
val kaptGeneratedSourcesDir = getKaptDirectory("getKaptGeneratedSourcesDir", project, sourceSetName)
val kaptGeneratedClassesDir = getKaptDirectory("getKaptGeneratedClassesDir", project, sourceSetName)
val kaptGeneratedKotlinSourcesDir = getKaptDirectory("getKaptGeneratedKotlinSourcesDir", project, sourceSetName)
sourceSets += KaptSourceSetModelImpl(
moduleName, isTest, kaptGeneratedSourcesDir, kaptGeneratedClassesDir, kaptGeneratedKotlinSourcesDir
)
}
if (targets != null && targets.isNotEmpty()) {
for (target in targets) {
if (!isWithJavaEnabled(target)) {
continue
}
val compilations = target.compilations ?: continue
for (compilation in compilations) {
val compileTask = compilation.getCompileKotlinTaskName(project) ?: continue
val moduleName = target.name + compilation.name.capitalize()
handleCompileTask(moduleName, compileTask)
}
}
} else {
val compileTasks = project.getTarget()?.compilations?.map { compilation -> compilation.getCompileKotlinTaskName(project) }
?: project.getAllTasks(false)[project]
compileTasks?.forEach{ compileTask ->
val sourceSetName = compileTask.getSourceSetName()
if (androidVariantRequest.shouldSkipSourceSet(sourceSetName)) return@forEach
handleCompileTask(sourceSetName, compileTask)
}
}
}
return KaptGradleModelImpl(kaptIsEnabled, project.buildDir, sourceSets)
}
private fun isWithJavaEnabled(target: Named): Boolean {
val getWithJavaEnabledMethod = target.javaClass.methods
.firstOrNull { it.name == "getWithJavaEnabled" && it.parameterCount == 0 } ?: return false
return getWithJavaEnabledMethod.invoke(target) == true
}
private fun getKaptDirectory(funName: String, project: Project, sourceSetName: String): String {
val kotlinKaptPlugin = project.plugins.findPlugin("kotlin-kapt") ?: return ""
val targetMethod = kotlinKaptPlugin::class.java.methods.firstOrNull {
Modifier.isStatic(it.modifiers) && it.name == funName && it.parameterCount == 2
} ?: return ""
return (targetMethod(null, project, sourceSetName) as? File)?.absolutePath ?: ""
}
}
|
apache-2.0
|
cf56b10dc25e0423f5ecd862a58c47bd
| 44.29078 | 158 | 0.690211 | 5.383642 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stackFrame/CapturedValueData.kt
|
6
|
1802
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.stackFrame
import com.intellij.debugger.DebuggerContext
import com.intellij.debugger.engine.JavaValue
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.impl.descriptors.data.DescriptorData
import com.intellij.debugger.impl.descriptors.data.DisplayKey
import com.intellij.debugger.impl.descriptors.data.SimpleDisplayKey
import com.intellij.debugger.ui.impl.watch.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiExpression
import com.intellij.xdebugger.frame.XValueModifier
import com.sun.jdi.*
data class CapturedValueData(
val valueName: String,
val obj: ObjectReference,
val field: Field
) : DescriptorData<ValueDescriptorImpl>() {
override fun createDescriptorImpl(project: Project): ValueDescriptorImpl {
val fieldDescriptor = FieldDescriptorImpl(project, obj, field)
return CustomFieldDescriptor(valueName, fieldDescriptor)
}
private class CustomFieldDescriptor(
val valueName: String,
val delegate: FieldDescriptorImpl
) : ValueDescriptorImpl(delegate.project) {
override fun getName() = valueName
override fun calcValue(evaluationContext: EvaluationContextImpl?): Value? = delegate.calcValue(evaluationContext)
override fun getDescriptorEvaluation(context: DebuggerContext?): PsiExpression = delegate.getDescriptorEvaluation(context)
override fun getModifier(value: JavaValue?): XValueModifier = delegate.getModifier(value)
}
override fun getDisplayKey(): DisplayKey<ValueDescriptorImpl> = SimpleDisplayKey(field)
}
|
apache-2.0
|
1ede6cc39a06e7dcd42631706df0dae2
| 45.230769 | 158 | 0.789678 | 4.831099 | false | false | false | false |
Webtrekk/webtrekk-android-sdk
|
sdk_test/src/main/java/com/webtrekk/SDKTest/ProductList/ProductItem.kt
|
1
|
5045
|
package com.webtrekk.SDKTest.ProductList
import android.os.Bundle
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Webtrekk GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Created by vartbaronov on 13.11.17.
*/
const val PRODUCT_POSITION: String = "PRODUCT_POSITION"
const val PRODUCT_ID: String = "PRODUCT_ID"
const val PRODUCT_CATEGORIES: String = "PRODUCT_CATEGORIES"
const val PRODUCT_COST: String = "PRODUCT_COST"
const val PRODUCT_ECOM_PARAMETERS: String = "PRODUCT_ECOM_PARAMETERS"
const val PRODUCT_PAYMENT_METHOD: String = "PRODUCT_PAYMENT_METHOD"
const val PRODUCT_SHIPPING_SERVICE: String = "PRODUCT_SHIPPING_SERVICE"
const val PRODUCT_SHIPPING_SPEED: String = "PRODUCT_SHIPPING_SPEED"
const val PRODUCT_SHIPPING_COST: String = "PRODUCT_SHIPPING_COST"
const val PRODUCT_GROSS_MARGIN: String = "PRODUCT_GROSS_MARGIN"
const val PRODUCT_PRODUCT_VARIANT: String = "PRODUCT_PRODUCT_VARIANT"
const val PRODUCT_PRODUCT_SOLD_OUT: String = "PRODUCT_PRODUCT_SOLD_OUT"
public data class ProductItem(val ind: Int, val id: String, val categories: Array<String>, val cost: Float,
val ecomParameters: Array<String>, val paymentMethod: String,
val shippingService: String, val shippingSpeed: String,
val shippingCost: Float, val grossMargin: Float,
val productVariant: String, val productSoldOut: Boolean){
companion object Handler{
fun getProductItemByIndex(ind: Int): ProductItem{
return ProductItem(ind,
"productId" + ind,
arrayOf("Cat" + ind + "1", "Cat" + ind + "2"),
13.5f + ind,
arrayOf("Ecom" + ind + "1", "Ecom" + ind + "2", "Ecom" + ind + "3"),
"PayMethod" + ind,
"ShippingService" + ind,
"ShippingSpeed" + ind,
23.5f + ind,
33.5f + ind,
"ProductVariant" + ind,
ind % 2 == 0)
}
fun getFromBundle(bundle: Bundle): ProductItem {
val indNew = bundle.getInt(PRODUCT_POSITION)
val idNew = bundle.getString(PRODUCT_ID)
val categoriesNew = bundle.getStringArray(PRODUCT_CATEGORIES)
val costNew = bundle.getFloat(PRODUCT_COST)
val ecomParametersNew = bundle.getStringArray(PRODUCT_ECOM_PARAMETERS)
val paymentMethodNew = bundle.getString(PRODUCT_PAYMENT_METHOD)
val shippingServiceNew = bundle.getString(PRODUCT_SHIPPING_SERVICE)
val shippingSpeedNew = bundle.getString(PRODUCT_SHIPPING_SPEED)
val shippingCostsNew = bundle.getFloat(PRODUCT_SHIPPING_COST)
val grossMarginNew = bundle.getFloat(PRODUCT_GROSS_MARGIN)
val productVariantNew = bundle.getString(PRODUCT_PRODUCT_VARIANT)
val productSoldOutNew = bundle.getBoolean(PRODUCT_PRODUCT_SOLD_OUT)
return ProductItem(indNew, idNew, categoriesNew, costNew, ecomParametersNew,
paymentMethodNew, shippingServiceNew, shippingSpeedNew, shippingCostsNew,
grossMarginNew, productVariantNew, productSoldOutNew)
}
}
fun saveToBundle():Bundle{
val bundle = Bundle()
bundle.putInt(PRODUCT_POSITION, ind)
bundle.putString(PRODUCT_ID, id)
bundle.putStringArray(PRODUCT_CATEGORIES, categories)
bundle.putFloat(PRODUCT_COST, cost)
bundle.putStringArray(PRODUCT_ECOM_PARAMETERS, ecomParameters)
bundle.putString(PRODUCT_PAYMENT_METHOD, paymentMethod)
bundle.putString(PRODUCT_SHIPPING_SERVICE, shippingService)
bundle.putString(PRODUCT_SHIPPING_SPEED, shippingSpeed)
bundle.putFloat(PRODUCT_SHIPPING_COST, shippingCost)
bundle.putFloat(PRODUCT_GROSS_MARGIN, grossMargin)
bundle.putString(PRODUCT_PRODUCT_VARIANT, productVariant)
bundle.putBoolean(PRODUCT_PRODUCT_SOLD_OUT, productSoldOut)
return bundle
}
}
|
mit
|
a6b880707a03f5f1385b172aab5beec7
| 53.836957 | 160 | 0.68107 | 4.364187 | false | false | false | false |
hsz/idea-gitignore
|
src/main/kotlin/mobi/hsz/idea/gitignore/projectView/HideIgnoredFilesTreeStructureProvider.kt
|
1
|
1919
|
// 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 mobi.hsz.idea.gitignore.projectView
import com.intellij.ide.projectView.TreeStructureProvider
import com.intellij.ide.projectView.ViewSettings
import com.intellij.ide.projectView.impl.nodes.BasePsiNode
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import mobi.hsz.idea.gitignore.IgnoreManager
import mobi.hsz.idea.gitignore.settings.IgnoreSettings
/**
* Extension for the [TreeStructureProvider] that provides the ability to hide ignored files
* or directories in the project tree view.
*/
class HideIgnoredFilesTreeStructureProvider(project: Project) : TreeStructureProvider {
private val ignoreSettings = service<IgnoreSettings>()
private val manager = project.service<IgnoreManager>()
/**
* If [IgnoreSettings.hideIgnoredFiles] is set to `true`, checks if specific
* nodes are ignored and filters them out.
*
* @param parent the parent node
* @param children the list of child nodes according to the default project structure
* @param settings the current project view settings
* @return the modified collection of child nodes
*/
override fun modify(parent: AbstractTreeNode<*>, children: Collection<AbstractTreeNode<*>?>, settings: ViewSettings?) =
when {
!ignoreSettings.hideIgnoredFiles -> children
else -> children.filter {
if (it !is BasePsiNode<*>) {
return@filter true
}
val file = it.virtualFile
return@filter file != null && !manager.isFileIgnored(file)
}
}
override fun getData(collection: Collection<AbstractTreeNode<*>?>, s: String): Any? = null
}
|
mit
|
a577fdb073741a2b9a55aadd6ceef831
| 41.644444 | 140 | 0.710787 | 4.714988 | false | false | false | false |
microg/android_packages_apps_UnifiedNlp
|
client/src/main/kotlin/org/microg/nlp/client/UnifiedLocationClient.kt
|
1
|
22637
|
/*
* SPDX-FileCopyrightText: 2019, microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package org.microg.nlp.client
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.ApplicationInfo
import android.content.pm.ResolveInfo
import android.location.Address
import android.location.Location
import android.os.Bundle
import android.os.DeadObjectException
import android.os.IBinder
import android.os.RemoteException
import android.util.Log
import org.microg.nlp.service.AddressCallback
import org.microg.nlp.service.LocationCallback
import org.microg.nlp.service.UnifiedLocationService
import java.lang.ref.WeakReference
import java.util.Timer
import java.util.TimerTask
import java.util.concurrent.atomic.AtomicInteger
import android.content.pm.PackageManager.SIGNATURE_MATCH
import kotlinx.coroutines.*
import java.lang.RuntimeException
import java.util.concurrent.*
import kotlin.coroutines.*
import kotlin.math.min
private const val CALL_TIMEOUT = 10000L
class UnifiedLocationClient private constructor(context: Context) {
private var bound = false
private val serviceReferenceCount = AtomicInteger(0)
private val options = Bundle()
private var context: WeakReference<Context> = WeakReference(context)
private var service: UnifiedLocationService? = null
private val syncThreads: ThreadPoolExecutor = ThreadPoolExecutor(1, Runtime.getRuntime().availableProcessors(), 1, TimeUnit.SECONDS, LinkedBlockingQueue())
private val waitingForService = arrayListOf<Continuation<UnifiedLocationService>>()
private var timer: Timer? = null
private var reconnectCount = 0
private val requests = CopyOnWriteArraySet<LocationRequest>()
private val coroutineScope = CoroutineScope(Dispatchers.IO + Job())
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
[email protected](name, service)
}
override fun onServiceDisconnected(name: ComponentName) {
[email protected](name)
}
override fun onBindingDied(name: ComponentName) {
[email protected](name)
}
override fun onNullBinding(name: ComponentName) {
[email protected](name)
}
}
var forceNextUpdate: Boolean
get() = options.getBoolean(KEY_FORCE_NEXT_UPDATE, false)
set(value) = options.putBoolean(KEY_FORCE_NEXT_UPDATE, value)
var opPackageName: String?
get() = options.getString(KEY_OP_PACKAGE_NAME)
set(value) = options.putString(KEY_OP_PACKAGE_NAME, value)
val isAvailable: Boolean
get() = bound || resolve() != null
val targetPackage: String?
get() = resolve()?.`package`
private fun resolve(): Intent? {
val context = this.context.get() ?: return null
val intent = Intent(ACTION_UNIFIED_LOCATION_SERVICE)
val pm = context.packageManager
var resolveInfos = pm.queryIntentServices(intent, 0)
if (resolveInfos.size > 1) {
// Restrict to self if possible
val isSelf: (it: ResolveInfo) -> Boolean = {
it.serviceInfo.packageName == context.packageName
}
if (resolveInfos.size > 1 && resolveInfos.any(isSelf)) {
Log.d(TAG, "Found more than one active unified service, restricted to own package " + context.packageName)
resolveInfos = resolveInfos.filter(isSelf)
}
// Restrict to package with matching signature if possible
val isSelfSig: (it: ResolveInfo) -> Boolean = {
it.serviceInfo.packageName == context.packageName
}
if (resolveInfos.size > 1 && resolveInfos.any(isSelfSig)) {
Log.d(TAG, "Found more than one active unified service, restricted to related packages")
resolveInfos = resolveInfos.filter(isSelfSig)
}
// Restrict to system if any package is system
val isSystem: (it: ResolveInfo) -> Boolean = {
(it.serviceInfo?.applicationInfo?.flags ?: 0) and ApplicationInfo.FLAG_SYSTEM > 0
}
if (resolveInfos.size > 1 && resolveInfos.any(isSystem)) {
Log.d(TAG, "Found more than one active unified service, restricted to system packages")
resolveInfos = resolveInfos.filter(isSystem)
}
val highestPriority: ResolveInfo? = resolveInfos.maxBy { it.priority }
intent.setPackage(highestPriority!!.serviceInfo.packageName)
intent.setClassName(highestPriority.serviceInfo.packageName, highestPriority.serviceInfo.name)
if (resolveInfos.size > 1) {
Log.d(TAG, "Found more than one active unified service, picked highest priority " + intent.component)
}
return intent
} else if (!resolveInfos.isEmpty()) {
intent.setPackage(resolveInfos[0].serviceInfo.packageName)
return intent
} else {
Log.w(TAG, "No service to bind to, your system does not support unified service")
return null
}
}
@Synchronized
private fun updateBinding(): Boolean {
Log.d(TAG, "updateBinding - current: $bound, refs: ${serviceReferenceCount.get()}, reqs: ${requests.size}, avail: $isAvailable")
if (!bound && (serviceReferenceCount.get() > 0 || !requests.isEmpty()) && isAvailable) {
timer = Timer("unified-client")
bound = true
bind()
return true
} else if (bound && serviceReferenceCount.get() == 0 && requests.isEmpty()) {
timer!!.cancel()
timer = null
bound = false
unbind()
return false
}
return bound
}
@Synchronized
private fun bindLater() {
val timer = timer
if (timer == null) {
updateBinding()
return
}
timer.schedule(object : TimerTask() {
override fun run() {
bind()
}
}, 1000)
}
@Synchronized
private fun bind() {
val context = this.context.get() ?: return
if (!bound) {
Log.w(TAG, "Tried to bind while not being bound!")
return
}
if (reconnectCount > 3) {
Log.w(TAG, "Reconnecting failed three times in a row, die out.")
return
}
val intent = resolve() ?: return
unbind()
reconnectCount++
Log.d(TAG, "Binding to $intent")
bound = context.bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
@Synchronized
private fun unbind() {
try {
this.context.get()?.unbindService(connection)
} catch (ignored: Exception) {
}
this.service = null
}
@Synchronized
fun ref() {
Log.d(TAG, "ref: ${Exception().stackTrace[1]}")
serviceReferenceCount.incrementAndGet()
updateBinding()
}
@Synchronized
fun unref() {
Log.d(TAG, "unref: ${Exception().stackTrace[1]}")
serviceReferenceCount.decrementAndGet()
updateBinding()
}
suspend fun getSingleLocation(): Location = suspendCoroutine { continuation ->
requestSingleLocation(LocationListener.wrap { continuation.resume(it) })
}
fun requestSingleLocation(listener: LocationListener) {
requestLocationUpdates(listener, 0, 1)
}
fun requestLocationUpdates(listener: LocationListener, interval: Long) {
requestLocationUpdates(listener, interval, Integer.MAX_VALUE)
}
fun requestLocationUpdates(listener: LocationListener, interval: Long, count: Int) {
requests.removeAll(requests.filter { it.listener === listener })
requests.add(LocationRequest(listener, interval, count))
coroutineScope.launch {
updateServiceInterval()
updateBinding()
}
}
fun removeLocationUpdates(listener: LocationListener) {
coroutineScope.launch {
removeRequests(requests.filter { it.listener === listener })
}
}
private suspend fun refAndGetService(): UnifiedLocationService = suspendCoroutine { continuation -> refAndGetServiceContinued(continuation) }
@Synchronized
private fun refAndGetServiceContinued(continuation: Continuation<UnifiedLocationService>) {
Log.d(TAG, "ref+get: ${Exception().stackTrace[2]}")
serviceReferenceCount.incrementAndGet()
waitForServiceContinued(continuation)
}
private suspend fun waitForService(): UnifiedLocationService = suspendCoroutine { continuation -> waitForServiceContinued(continuation) }
@Synchronized
private fun waitForServiceContinued(continuation: Continuation<UnifiedLocationService>) {
val service = service
if (service != null) {
continuation.resume(service)
} else {
synchronized(waitingForService) {
waitingForService.add(continuation)
}
updateBinding()
val timer = timer
if (timer == null) {
synchronized(waitingForService) {
waitingForService.remove(continuation)
}
continuation.resumeWithException(RuntimeException("No timer, called waitForService when not connected"))
} else {
timer.schedule(object : TimerTask() {
override fun run() {
try {
continuation.resumeWithException(TimeoutException())
} catch (e: IllegalStateException) {
// Resumed pretty much the same moment as timeout triggered, ignore
}
}
}, CALL_TIMEOUT)
}
}
}
private fun <T> configureContinuationTimeout(continuation: Continuation<T>, timeout: Long) {
if (timeout <= 0 || timeout == Long.MAX_VALUE) return
timer!!.schedule(object : TimerTask() {
override fun run() {
try {
Log.w(TAG, "Timeout reached")
continuation.resumeWithException(TimeoutException())
} catch (ignored: Exception) {
// Ignore
}
}
}, timeout)
}
private fun <T> executeSyncWithTimeout(timeout: Long = CALL_TIMEOUT, action: suspend () -> T): T {
var result: T? = null
val latch = CountDownLatch(1)
var err: Exception? = null
syncThreads.execute {
try {
runBlocking {
result = withTimeout(timeout) { action() }
}
} catch (e: Exception) {
err = e
} finally {
latch.countDown()
}
}
if (!latch.await(timeout, TimeUnit.MILLISECONDS))
throw TimeoutException()
err?.let { throw it }
return result ?: throw NullPointerException()
}
suspend fun getFromLocation(latitude: Double, longitude: Double, maxResults: Int, locale: String, timeout: Long = Long.MAX_VALUE): List<Address> {
try {
val service = refAndGetService()
return suspendCoroutine { continuation ->
service.getFromLocationWithOptions(latitude, longitude, maxResults, locale, options, AddressContinuation(continuation))
configureContinuationTimeout(continuation, timeout)
}
} catch (e: Exception) {
Log.w(TAG, "Failed to request geocode", e)
return emptyList()
} finally {
unref()
}
}
fun getFromLocationSync(latitude: Double, longitude: Double, maxResults: Int, locale: String, timeout: Long = CALL_TIMEOUT): List<Address> = executeSyncWithTimeout(timeout) {
getFromLocation(latitude, longitude, maxResults, locale, timeout)
}
suspend fun getFromLocationName(locationName: String, maxResults: Int, lowerLeftLatitude: Double, lowerLeftLongitude: Double, upperRightLatitude: Double, upperRightLongitude: Double, locale: String, timeout: Long = Long.MAX_VALUE): List<Address> {
return try {
val service = refAndGetService()
suspendCoroutine { continuation ->
service.getFromLocationNameWithOptions(locationName, maxResults, lowerLeftLatitude, lowerLeftLongitude, upperRightLatitude, upperRightLongitude, locale, options, AddressContinuation(continuation))
configureContinuationTimeout(continuation, timeout)
}
} catch (e: Exception) {
Log.w(TAG, "Failed to request geocode", e)
emptyList()
} finally {
unref()
}
}
fun getFromLocationNameSync(locationName: String, maxResults: Int, lowerLeftLatitude: Double, lowerLeftLongitude: Double, upperRightLatitude: Double, upperRightLongitude: Double, locale: String, timeout: Long = CALL_TIMEOUT): List<Address> = executeSyncWithTimeout(timeout) {
getFromLocationName(locationName, maxResults, lowerLeftLatitude, lowerLeftLongitude, upperRightLatitude, upperRightLongitude, locale, timeout)
}
suspend fun reloadPreferences() {
try {
refAndGetService().reloadPreferences()
} catch (e: RemoteException) {
Log.w(TAG, "Failed to handle request", e)
} finally {
unref()
}
}
suspend fun getLocationBackends(): Array<String> {
try {
return refAndGetService().locationBackends
} catch (e: Exception) {
Log.w(TAG, "Failed to handle request", e)
return emptyArray()
} finally {
unref()
}
}
suspend fun setLocationBackends(backends: Array<String>) {
try {
refAndGetService().locationBackends = backends
} catch (e: Exception) {
Log.w(TAG, "Failed to handle request", e)
} finally {
unref()
}
}
suspend fun getGeocoderBackends(): Array<String> {
try {
return refAndGetService().geocoderBackends
} catch (e: RemoteException) {
Log.w(TAG, "Failed to handle request", e)
return emptyArray()
} finally {
unref()
}
}
suspend fun setGeocoderBackends(backends: Array<String>) {
try {
refAndGetService().geocoderBackends = backends
} catch (e: RemoteException) {
Log.w(TAG, "Failed to handle request", e)
} finally {
unref()
}
}
fun getLastLocationSync(timeout: Long = CALL_TIMEOUT): Location? = executeSyncWithTimeout(timeout) {
getLastLocation()
}
suspend fun getLastLocation(): Location? {
return try {
refAndGetService().lastLocation
} catch (e: RemoteException) {
Log.w(TAG, "Failed to handle request", e)
null
} finally {
unref()
}
}
suspend fun getLastLocationForBackend(packageName: String, className: String, signatureDigest: String? = null): Location? {
return try {
refAndGetService().getLastLocationForBackend(packageName, className, signatureDigest)
} catch (e: RemoteException) {
Log.w(TAG, "Failed to handle request", e)
null
} finally {
unref()
}
}
private suspend fun removeRequestPendingRemoval() {
removeRequests(requests.filter { it.needsRemoval })
}
private suspend fun removeRequests(removalNeeded: List<LocationRequest>) {
if (removalNeeded.isNotEmpty()) {
requests.removeAll(removalNeeded)
updateServiceInterval()
updateBinding()
}
}
private suspend fun updateServiceInterval() {
var interval: Long = Long.MAX_VALUE
var requestSingle = false
for (request in requests) {
if (request.interval <= 0) {
requestSingle = true
continue
}
interval = min(interval, request.interval)
}
if (interval == Long.MAX_VALUE) {
Log.d(TAG, "Disable automatic updates")
interval = 0
} else {
Log.d(TAG, "Set update interval to $interval")
}
val service: UnifiedLocationService
try {
service = waitForService()
} catch (e: Exception) {
Log.w(TAG, e)
return
}
try {
service.setUpdateInterval(interval, options)
if (requestSingle) {
Log.d(TAG, "Request single update (force update: $forceNextUpdate)")
service.requestSingleUpdate(options)
forceNextUpdate = false
}
} catch (e: DeadObjectException) {
Log.w(TAG, "Connection is dead, reconnecting")
bind()
} catch (e: RemoteException) {
Log.w(TAG, "Failed to set location update interval", e)
}
}
@Synchronized
private fun onServiceConnected(name: ComponentName, binder: IBinder) {
Log.d(TAG, "Connected to $name")
reconnectCount = 0
val service = UnifiedLocationService.Stub.asInterface(binder)
this.service = service
val continuations = arrayListOf<Continuation<UnifiedLocationService>>()
synchronized(waitingForService) {
continuations.addAll(waitingForService)
waitingForService.clear()
}
coroutineScope.launch {
try {
Log.d(TAG, "Registering location callback")
service.registerLocationCallback(object : LocationCallback.Stub() {
override fun onLocationUpdate(location: Location) {
coroutineScope.launch {
[email protected](location)
}
}
}, options)
Log.d(TAG, "Registered location callback")
} catch (e: Exception) {
Log.w(TAG, "Failed to register location callback", e)
}
updateServiceInterval()
if (continuations.size > 0) {
Log.d(TAG, "Resuming ${continuations.size} continuations")
}
for (continuation in continuations) {
try {
continuation.resume(service)
} catch (e: Exception) {
Log.w(TAG, e)
}
}
}
}
private suspend fun onLocationUpdate(location: Location) {
for (request in requests) {
request.handleLocation(location)
}
removeRequestPendingRemoval()
}
@Synchronized
private fun onServiceDisconnected(name: ComponentName) {
Log.d(TAG, "Disconnected from $name")
this.service = null
}
private fun onBindingDied(name: ComponentName) {
Log.d(TAG, "Connection to $name died, reconnecting")
bind()
}
private fun onNullBinding(name: ComponentName) {
Log.w(TAG, "Null binding from $name, reconnecting")
bindLater()
}
interface LocationListener {
fun onLocation(location: Location)
companion object {
fun wrap(listener: (Location) -> Unit): LocationListener {
return object : LocationListener {
override fun onLocation(location: Location) {
listener(location)
}
}
}
}
}
private inner class LocationRequest(val listener: LocationListener, var interval: Long, var pendingCount: Int) {
private var lastUpdate: Long = 0
private var failed: Boolean = false
val needsRemoval: Boolean
get() = pendingCount <= 0 || failed
fun reset(interval: Long, count: Int) {
this.interval = interval
this.pendingCount = count
}
@Synchronized
fun handleLocation(location: Location) {
if (needsRemoval) return
if (lastUpdate > System.currentTimeMillis()) {
lastUpdate = System.currentTimeMillis()
}
if (lastUpdate <= System.currentTimeMillis() - interval / 2) {
lastUpdate = System.currentTimeMillis()
if (pendingCount > 0) {
pendingCount--
}
try {
listener.onLocation(location)
} catch (e: Exception) {
Log.w(TAG, "Listener threw uncaught exception, stopping location request", e)
failed = true
}
}
}
}
companion object {
const val ACTION_UNIFIED_LOCATION_SERVICE = "org.microg.nlp.service.UnifiedLocationService"
const val PERMISSION_SERVICE_ADMIN = "org.microg.nlp.SERVICE_ADMIN"
const val KEY_FORCE_NEXT_UPDATE = "org.microg.nlp.FORCE_NEXT_UPDATE"
const val KEY_OP_PACKAGE_NAME = "org.microg.nlp.OP_PACKAGE_NAME"
private val TAG = "ULocClient"
private var client: UnifiedLocationClient? = null
@JvmStatic
@Synchronized
operator fun get(context: Context): UnifiedLocationClient {
var client = client
if (client == null) {
client = UnifiedLocationClient(context)
this.client = client
} else {
client.context = WeakReference(context)
}
return client
}
}
}
class AddressContinuation(private val continuation: Continuation<List<Address>>) : AddressCallback.Stub() {
override fun onResult(addresses: List<Address>?) {
try {
if (addresses != null) {
Log.d("ULocClient", "Resume with ${addresses.size} addresses")
continuation.resume(addresses)
} else {
continuation.resumeWithException(NullPointerException("Service returned null"))
}
} catch (ignored: Exception) {
// Ignore
}
}
}
|
apache-2.0
|
823316b870537add83671ebb575715a4
| 35.2208 | 279 | 0.59606 | 5.015954 | false | false | false | false |
orgzly/orgzly-android
|
app/src/main/java/com/orgzly/android/ui/views/richtext/RichTextView.kt
|
1
|
6768
|
package com.orgzly.android.ui.views.richtext
import android.annotation.SuppressLint
import android.content.Context
import android.text.Layout
import android.text.Spannable
import android.text.Spanned
import android.text.TextUtils
import android.text.style.ClickableSpan
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.GestureDetectorCompat
import com.orgzly.BuildConfig
import com.orgzly.R
import com.orgzly.android.prefs.AppPreferences
import com.orgzly.android.ui.SpanUtils
import com.orgzly.android.ui.util.styledAttributes
import com.orgzly.android.ui.views.style.CheckboxSpan
import com.orgzly.android.ui.views.style.DrawerMarkerSpan
import com.orgzly.android.ui.views.style.Offsetting
import com.orgzly.android.util.LogUtils
class RichTextView : AppCompatTextView, ActionableRichTextView {
fun interface OnTapUpListener {
fun onTapUp(x: Float, y: Float, charOffset: Int)
}
private data class Listeners(
var onTapUp: OnTapUpListener? = null,
var onActionListener: ActionableRichTextView? = null)
private val listeners = Listeners()
fun setOnTapUpListener(listener: OnTapUpListener) {
listeners.onTapUp = listener
}
fun setOnActionListener(listener: ActionableRichTextView) {
listeners.onActionListener = listener
}
constructor(context: Context) : super(context) {
// addTextChangedListener(EditTextWatcher())
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
// addTextChangedListener(EditTextWatcher())
parseAttrs(attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
// addTextChangedListener(EditTextWatcher())
parseAttrs(attrs)
}
private var parseCheckboxes = true
private fun parseAttrs(attrs: AttributeSet?) {
if (attrs != null) {
context.styledAttributes(attrs, R.styleable.RichText) { typedArray ->
parseCheckboxes = typedArray.getBoolean(R.styleable.RichText_parse_checkboxes, true)
}
}
}
private val singleTapUpDetector = GestureDetectorCompat(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(e: MotionEvent): Boolean {
return true
}
})
/**
* Added as setMovementMethod was preventing clicks outside of ClickableSpan.
* https://stackoverflow.com/q/30452627
*/
private fun interceptClickableSpan(event: MotionEvent): Boolean? {
layout?.let { layout ->
val line = layout.getLineForVertical(event.y.toInt() - totalPaddingTop)
if (isEventOnText(event, layout, line) && !TextUtils.isEmpty(text) && text is Spanned) {
val spanned = text as Spanned
val charOffset = getOffsetForPosition(event.x, event.y)
val clickableSpans = spanned.getSpans(charOffset, charOffset, ClickableSpan::class.java)
if (clickableSpans.isNotEmpty()) {
return when (event.action) {
MotionEvent.ACTION_DOWN ->
true
MotionEvent.ACTION_UP -> {
clickableSpans[0].onClick(this)
super.onTouchEvent(event)
}
else ->
super.onTouchEvent(event)
}
}
}
}
return null
}
/**
* Check if event's coordinates are within line's text.
*
* Needed as getOffsetForHorizontal will return closest character,
* which is an issue when clicking the empty space next to the text.
*/
private fun isEventOnText(event: MotionEvent, layout: Layout, line: Int): Boolean {
val left = layout.getLineLeft(line) + totalPaddingLeft
val right = layout.getLineRight(line) + totalPaddingRight
val bottom = (layout.getLineBottom(line) + totalPaddingTop).toFloat()
val top = (layout.getLineTop(line) + totalPaddingTop).toFloat()
return event.x in left..right && event.y in top..bottom
}
private val hideRichTextSymbols = !AppPreferences.styledTextWithMarks(context)
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
interceptClickableSpan(event)?.let { handled ->
// if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, "ClickableSpan intercepted")
return handled
}
val isSingleTapUp = singleTapUpDetector.onTouchEvent(event)
if (isSingleTapUp) {
val tapCharOffset = getOffsetForPosition(event.x, event.y)
val spansChars = if (hideRichTextSymbols) {
offsettingSpansOffset(tapCharOffset)
} else {
0
}
if (BuildConfig.LOG_DEBUG && event.action != MotionEvent.ACTION_MOVE) {
LogUtils.d(TAG, tapCharOffset, spansChars, event)
}
listeners.onTapUp?.onTapUp(event.x, event.y, tapCharOffset + spansChars)
}
return super.onTouchEvent(event)
}
private fun offsettingSpansOffset(tapCharOffset: Int): Int {
var spansChars = 0
run allDone@ {
SpanUtils.forEachSpan(text as Spannable, Offsetting::class.java) { span, curr, next ->
if (tapCharOffset < next) {
return@allDone
}
spansChars += span.characterOffset
LogUtils.d(TAG, span, curr, next, tapCharOffset, span.characterOffset)
}
}
return spansChars
}
fun activate() {
visibility = View.VISIBLE
}
fun deactivate() {
visibility = View.GONE
}
// Just pass to RichView
override fun toggleDrawer(drawerSpan: DrawerMarkerSpan) {
listeners.onActionListener?.toggleDrawer(drawerSpan)
}
// Just pass to RichView
override fun toggleCheckbox(checkboxSpan: CheckboxSpan) {
listeners.onActionListener?.toggleCheckbox(checkboxSpan)
}
// Just pass to RichView
override fun followLinkToNoteWithProperty(name: String, value: String) {
listeners.onActionListener?.followLinkToNoteWithProperty(name, value)
}
// Just pass to RichView
override fun followLinkToFile(path: String) {
listeners.onActionListener?.followLinkToFile(path)
}
companion object {
val TAG: String = RichTextView::class.java.name
}
}
|
gpl-3.0
|
1de90992a77e874186d434079cfe4b4b
| 32.019512 | 121 | 0.647754 | 4.77292 | false | false | false | false |
solokot/Simple-Gallery
|
app/src/main/kotlin/com/simplemobiletools/gallery/pro/databases/GalleryDatabase.kt
|
1
|
3851
|
package com.simplemobiletools.gallery.pro.databases
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.simplemobiletools.gallery.pro.interfaces.*
import com.simplemobiletools.gallery.pro.models.*
@Database(entities = [Directory::class, Medium::class, Widget::class, DateTaken::class, Favorite::class], version = 9)
abstract class GalleryDatabase : RoomDatabase() {
abstract fun DirectoryDao(): DirectoryDao
abstract fun MediumDao(): MediumDao
abstract fun WidgetsDao(): WidgetsDao
abstract fun DateTakensDao(): DateTakensDao
abstract fun FavoritesDao(): FavoritesDao
companion object {
private var db: GalleryDatabase? = null
fun getInstance(context: Context): GalleryDatabase {
if (db == null) {
synchronized(GalleryDatabase::class) {
if (db == null) {
db = Room.databaseBuilder(context.applicationContext, GalleryDatabase::class.java, "gallery.db")
.fallbackToDestructiveMigration()
.addMigrations(MIGRATION_4_5)
.addMigrations(MIGRATION_5_6)
.addMigrations(MIGRATION_6_7)
.addMigrations(MIGRATION_7_8)
.addMigrations(MIGRATION_8_9)
.build()
}
}
}
return db!!
}
fun destroyInstance() {
if (db?.isOpen == true) {
db?.close()
}
db = null
}
private val MIGRATION_4_5 = object : Migration(4, 5) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE media ADD COLUMN video_duration INTEGER default 0 NOT NULL")
}
}
private val MIGRATION_5_6 = object : Migration(5, 6) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE IF NOT EXISTS `widgets` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `widget_id` INTEGER NOT NULL, `folder_path` TEXT NOT NULL)")
database.execSQL("CREATE UNIQUE INDEX `index_widgets_widget_id` ON `widgets` (`widget_id`)")
}
}
private val MIGRATION_6_7 = object : Migration(6, 7) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE IF NOT EXISTS `date_takens` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `full_path` TEXT NOT NULL, `filename` TEXT NOT NULL, `parent_path` TEXT NOT NULL, `date_taken` INTEGER NOT NULL, `last_fixed` INTEGER NOT NULL)")
database.execSQL("CREATE TABLE IF NOT EXISTS `favorites` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `full_path` TEXT NOT NULL, `filename` TEXT NOT NULL, `parent_path` TEXT NOT NULL)")
database.execSQL("CREATE UNIQUE INDEX `index_date_takens_full_path` ON `date_takens` (`full_path`)")
database.execSQL("CREATE UNIQUE INDEX `index_favorites_full_path` ON `favorites` (`full_path`)")
}
}
private val MIGRATION_7_8 = object : Migration(7, 8) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE directories ADD COLUMN sort_value TEXT default '' NOT NULL")
}
}
private val MIGRATION_8_9 = object : Migration(8, 9) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE date_takens ADD COLUMN last_modified INTEGER default 0 NOT NULL")
}
}
}
}
|
gpl-3.0
|
1c1253fcb60c11b27f307fdc6ca922cf
| 42.761364 | 261 | 0.608154 | 4.80774 | false | false | false | false |
EMResearch/EvoMaster
|
core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/ImpactUtils.kt
|
1
|
17161
|
package org.evomaster.core.search.impact.impactinfocollection
import org.evomaster.core.search.Action
import org.evomaster.core.search.Individual
import org.evomaster.core.search.ActionFilter
import org.evomaster.core.search.gene.*
import org.evomaster.core.search.gene.sql.*
import org.evomaster.core.search.impact.impactinfocollection.sql.*
import org.evomaster.core.search.impact.impactinfocollection.value.*
import org.evomaster.core.search.impact.impactinfocollection.value.collection.ArrayGeneImpact
import org.evomaster.core.search.impact.impactinfocollection.value.collection.MapGeneImpact
import org.evomaster.core.search.impact.impactinfocollection.value.collection.EnumGeneImpact
import org.evomaster.core.search.impact.impactinfocollection.value.date.DateGeneImpact
import org.evomaster.core.search.impact.impactinfocollection.value.date.DateTimeGeneImpact
import org.evomaster.core.search.impact.impactinfocollection.value.date.TimeGeneImpact
import org.evomaster.core.search.impact.impactinfocollection.value.numeric.*
import org.evomaster.core.Lazy
import org.evomaster.core.logging.LoggingUtil
import org.evomaster.core.problem.external.service.ApiExternalServiceAction
import org.evomaster.core.problem.util.ParamUtil
import org.evomaster.core.search.gene.collection.*
import org.evomaster.core.search.gene.datetime.DateGene
import org.evomaster.core.search.gene.datetime.DateTimeGene
import org.evomaster.core.search.gene.datetime.TimeGene
import org.evomaster.core.search.gene.numeric.*
import org.evomaster.core.search.gene.optional.CustomMutationRateGene
import org.evomaster.core.search.gene.optional.OptionalGene
import org.evomaster.core.search.gene.optional.NullableGene
import org.evomaster.core.search.gene.regex.*
import org.evomaster.core.search.gene.root.CompositeFixedGene
import org.evomaster.core.search.gene.string.NumericStringGene
import org.evomaster.core.search.gene.string.StringGene
import org.evomaster.core.search.impact.impactinfocollection.regex.*
import org.evomaster.core.search.impact.impactinfocollection.value.collection.SqlMultidimensionalArrayGeneImpact
import org.evomaster.core.search.service.mutator.MutatedGeneSpecification
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* created by manzh on 2019-09-09
*
* this utility can be used to e.g.,
* 1) create new impact
* 2) generate gene id for linking with its impact
*/
class ImpactUtils {
companion object{
private val log: Logger = LoggerFactory.getLogger(ImpactUtils::class.java)
fun createGeneImpact(gene : Gene, id : String) : GeneImpact{
return when(gene){
is CustomMutationRateGene<*> -> DisruptiveGeneImpact(id, gene)
is OptionalGene -> OptionalGeneImpact(id, gene)
is BooleanGene -> BinaryGeneImpact(id)
is EnumGene<*> -> EnumGeneImpact(id, gene)
is IntegerGene -> IntegerGeneImpact(id)
is LongGene -> LongGeneImpact(id)
is DoubleGene -> DoubleGeneImpact(id)
is FloatGene -> FloatGeneImpact(id)
is StringGene -> StringGeneImpact(id, gene)
//is Base64StringGene -> StringGeneImpact(id, gene.data)
is ObjectGene -> ObjectGeneImpact(id, gene)
is TupleGene -> TupleGeneImpact(id, gene)
is MapGene<*, *> -> MapGeneImpact(id)
is PairGene<*, *> -> throw IllegalStateException("do not count impacts for PairGene yet")
is ArrayGene<*> -> ArrayGeneImpact(id)
is DateGene -> DateGeneImpact(id, gene)
is DateTimeGene -> DateTimeGeneImpact(id, gene)
is TimeGene -> TimeGeneImpact(id, gene)
is SeededGene<*> -> SeededGeneImpact(id, gene)
// math
is BigDecimalGene -> BigDecimalGeneImpact(id)
is BigIntegerGene -> BigIntegerGeneImpact(id)
is NumericStringGene -> NumericStringGeneImpact(id, gene)
//sql
is NullableGene -> NullableImpact(id, gene)
is SqlJSONGene -> SqlJsonGeneImpact(id, gene)
is SqlXMLGene -> SqlXmlGeneImpact(id, gene)
is UUIDGene -> SqlUUIDGeneImpact(id, gene)
is SqlPrimaryKeyGene -> SqlPrimaryKeyGeneImpact(id, gene)
is SqlForeignKeyGene -> SqlForeignKeyGeneImpact(id)
is SqlAutoIncrementGene -> GeneImpact(id)
is SqlMultidimensionalArrayGene<*> -> SqlMultidimensionalArrayGeneImpact(id)
// regex
is RegexGene -> RegexGeneImpact(id, gene)
is DisjunctionListRxGene -> DisjunctionListRxGeneImpact(id, gene)
is DisjunctionRxGene -> DisjunctionRxGeneImpact(id, gene)
is QuantifierRxGene -> QuantifierRxGeneImpact(id, gene)
is RxAtom -> RxAtomImpact(id)
is RxTerm -> RxTermImpact(id)
// general for composite fixed gene
is CompositeFixedGene -> CompositeFixedGeneImpact(id, gene)
else ->{
LoggingUtil.uniqueWarn(log, "the impact of {} was collected in a general manner, i.e., GeneImpact", gene::class.java.simpleName)
GeneImpact(id)
}
}
}
private const val SEPARATOR_ACTION_TO_GENE = "::"
private const val SEPARATOR_GENE = ";"
private const val SEPARATOR_GENE_WITH_TYPE = ">"
/**
* TODO
* Man: might employ local id of the action, check it later
*/
fun generateGeneId(action: Action, gene : Gene) : String = "${action.getName()}$SEPARATOR_ACTION_TO_GENE${generateGeneId(gene)}$SEPARATOR_ACTION_TO_GENE${action.seeTopGenes().indexOf(gene)}"
fun extractActionName(geneId : String) : String?{
if (!geneId.contains(SEPARATOR_ACTION_TO_GENE)) return null
return geneId.split(SEPARATOR_ACTION_TO_GENE).first()
}
fun <T : Individual> generateGeneId(individual: T, gene: Gene) : String{
if (!individual.seeGenes().contains(gene)){
log.warn("cannot find this gene ${gene.name} ($gene) in this individual")
return generateGeneId(gene)
}
individual.seeInitializingActions().find { da->
da.seeTopGenes().contains(gene)
}?.let {
return generateGeneId(it, gene)
}
individual.seeActions(ActionFilter.NO_INIT).find { a-> a.seeTopGenes().contains(gene) }?.let {
return generateGeneId(action = it, gene = gene)
}
return generateGeneId(gene)
}
/**
* extract info regarding a gene (on a action of an individual if it has) before mutated and the gene after mutated
*
* @param mutatedGenes genes were mutated
* @param individual a mutated individual with [mutatedGenes]
* @param previousIndividual mutating [previousIndividual] becomes [individual]
*/
private fun extractMutatedGeneWithContext(
mutatedGenes : MutableList<Gene>,
individual: Individual,
previousIndividual: Individual
) : Map<String, MutableList<MutatedGeneWithContext>>{
val mutatedGenesWithContext = mutableMapOf<String, MutableList<MutatedGeneWithContext>>()
if (individual.seeAllActions().isEmpty()){
individual.seeGenes().filter { mutatedGenes.contains(it) }.forEach { g->
val id = generateGeneId(individual, g)
val contexts = mutatedGenesWithContext.getOrPut(id){ mutableListOf()}
val previous = findGeneById(previousIndividual, id)?: throw IllegalArgumentException("mismatched previous individual")
contexts.add(MutatedGeneWithContext(g, previous = previous, numOfMutatedGene = mutatedGenes.size))
}
}else{
individual.seeAllActions().forEachIndexed { index, action ->
action.seeTopGenes().filter { mutatedGenes.contains(it) }.forEach { g->
val id = generateGeneId(action, g)
val contexts = mutatedGenesWithContext.getOrPut(id){ mutableListOf()}
val previous = findGeneById(previousIndividual, id, action.getName(), index, action.getLocalId(), action is ApiExternalServiceAction, false)?: throw IllegalArgumentException("mismatched previous individual")
contexts.add(MutatedGeneWithContext(g, action.getName(), index, action.getLocalId(), action is ApiExternalServiceAction, previous, mutatedGenes.size))
}
}
}
Lazy.assert{
mutatedGenesWithContext.values.sumOf { it.size } == mutatedGenes.size
}
return mutatedGenesWithContext
}
private fun extractMutatedGeneWithContext(mutatedGeneSpecification: MutatedGeneSpecification,
actions: List<Pair<Action, Int?>>,
previousIndividual: Individual,
isInit : Boolean, list: MutableList<MutatedGeneWithContext>, num : Int) {
actions.forEach { indexedAction ->
val a = indexedAction.first
val index = indexedAction.second
val manipulated = mutatedGeneSpecification.isActionMutated(index, a.getLocalId(), isInit)
if (manipulated){
a.seeTopGenes().filter {
if (isInit)
mutatedGeneSpecification.mutatedInitGeneInfo().contains(it)
else
mutatedGeneSpecification.mutatedGeneInfo().contains(it) || mutatedGeneSpecification.mutatedDbGeneInfo().contains(it)
}.forEach { mutatedg->
val id = generateGeneId(a, mutatedg)
/*
index for db gene might be changed if new insertions are added.
then there is a need to update the index in previous based on the number of added
*/
val indexInPrevious = if (index == null) null else index - (if (isInit && !mutatedGeneSpecification.addedExistingDataInitialization.contains(a)) mutatedGeneSpecification.addedExistingDataInitialization.size else 0)
val previous = findGeneById(
individual=previousIndividual,
id = id,
actionName = a.getName(),
indexOfAction = indexInPrevious,
localId = a.getLocalId(),
isDynamic = a is ApiExternalServiceAction,
isDb = isInit
)
list.add(MutatedGeneWithContext(
current = mutatedg,
previous = previous,
position = index,
action = a.getName(), actionLocalId = a.getLocalId(), isDynamicAction = index == null, numOfMutatedGene = num))
}
}
}
}
fun extractMutatedGeneWithContext(mutatedGeneSpecification: MutatedGeneSpecification,
individual: Individual,
previousIndividual: Individual,
isInit : Boolean) : MutableList<MutatedGeneWithContext>{
val num = mutatedGeneSpecification.numOfMutatedGeneInfo()
val list = mutableListOf<MutatedGeneWithContext>()
if (individual.hasAnyAction()){
if (isInit){
Lazy.assert { mutatedGeneSpecification.mutatedInitGenes.isEmpty() || individual.seeInitializingActions().isNotEmpty() }
extractMutatedGeneWithContext(mutatedGeneSpecification, individual.getRelativeIndexedInitActions(), previousIndividual, isInit, list, num)
}else{
extractMutatedGeneWithContext(mutatedGeneSpecification, individual.getRelativeIndexedNonInitAction(), previousIndividual, isInit, list, num)
}
}else{
Lazy.assert { !isInit }
individual.seeGenes().filter { mutatedGeneSpecification.mutatedGeneInfo().contains(it) }.forEach { g->
val id = generateGeneId(individual, g)
val previous = findGeneById(previousIndividual, id)?: throw IllegalArgumentException("mismatched previous individual")
list.add(MutatedGeneWithContext(g, previous = previous, numOfMutatedGene = num))
}
}
return list
}
private fun findGeneById(individual: Individual, id : String, actionName : String, indexOfAction : Int?, localId: String?, isDynamic : Boolean, isDb : Boolean):Gene?{
if (!isDynamic && indexOfAction == null)
throw IllegalArgumentException("indexOfAction must be specified if the action is not dynamic, ie, external service action")
if (isDynamic && localId == null)
throw IllegalArgumentException("localId must be specified if the action is dynamic, ie, external service action")
val action = if (indexOfAction!=null && !isDynamic){
if (indexOfAction >= (if (isDb) individual.seeInitializingActions() else individual.seeFixedMainActions()).size) return null
if (isDb) individual.seeInitializingActions()[indexOfAction] else individual.seeFixedMainActions()[indexOfAction]
}else {
individual.findActionByLocalId(localId!!)?:return null
}
if (action.getName() != actionName)
throw IllegalArgumentException("mismatched gene mutated info ${action.getName()} vs. $actionName")
return action.seeTopGenes().find { generateGeneId(action, it) == id }
}
private fun findGeneById(individual: Individual, id : String):Gene?{
return individual.seeGenes().find { generateGeneId(individual, it) == id }
}
fun extractGeneById(actions: List<Action>, id: String) : MutableList<Gene>{
if (actions.isEmpty() || id.contains(SEPARATOR_ACTION_TO_GENE)) return mutableListOf()
val names = id.split(SEPARATOR_ACTION_TO_GENE)
Lazy.assert{names.size == 2}
return actions.filter { it.getName() == names[0] }.flatMap { it.seeTopGenes() }.filter { it.name == names[1] }.toMutableList()
}
fun isAnyChange(geneA : Gene, geneB : Gene) : Boolean{
Lazy.assert{geneA::class.java.simpleName == geneB::class.java.simpleName}
return geneA.getValueAsRawString() == geneB.getValueAsRawString()
}
/**
* TODO: should handle SQL related genes separately?
*/
fun generateGeneId(gene: Gene):String{
return when(gene){
is CustomMutationRateGene<*> -> "DisruptiveGene$SEPARATOR_GENE_WITH_TYPE${generateGeneId(gene.gene)}"
is OptionalGene -> "OptionalGene$SEPARATOR_GENE_WITH_TYPE${generateGeneId(gene.gene)}"
is ObjectGene -> if (gene.refType.isNullOrBlank()) gene.name else "${gene.refType}$SEPARATOR_GENE_WITH_TYPE${gene.name}"
else -> gene.name
}
}
/**
* find a gene that has the same with [gene], but different value
* @param gene is one of root genes of [action]
*/
fun findMutatedGene(action: Action, gene : Gene, includeSameValue : Boolean = false) : Gene?{
return findMutatedGene(action.seeTopGenes(), gene, includeSameValue)
}
fun findMutatedGene(genes: List<Gene>, gene : Gene, includeSameValue : Boolean = false) : Gene?{
val template = ParamUtil.getValueGene(gene)
val found = genes.filter { it.isMutable() }.filter {o->
val g = ParamUtil.getValueGene(o)
g.name == template.name && g::class.java.simpleName == template::class.java.simpleName
&& (includeSameValue
|| !try { g.containsSameValueAs(template) }catch (e: Exception){
if (g !is ArrayGene<*> && g !is FixedMapGene<*,*>) throw e else false
}
)
}
if (found.size == 1) return found.first()
return found.firstOrNull { it.getLocalId() == gene.getLocalId() }?: found.also {
if (it.size > 1) log.warn("{} genes have been mutated with the name {} and localId {}",it.size, gene.name, gene.getLocalId())
}.firstOrNull()
}
}
}
|
lgpl-3.0
|
df146fdc7b5ec868afbfec36524d39f0
| 52.799373 | 238 | 0.612027 | 5.190865 | false | false | false | false |
ibinti/intellij-community
|
platform/testGuiFramework/src/com/intellij/testGuiFramework/remote/server/JUnitServerImpl.kt
|
3
|
6710
|
/*
* 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.testGuiFramework.remote.server
import com.intellij.testGuiFramework.remote.transport.TransportMessage
import org.apache.log4j.Logger
import java.io.InvalidClassException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.net.ServerSocket
import java.net.Socket
import java.util.*
import java.util.concurrent.BlockingQueue
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
/**
* @author Sergey Karashevich
*/
class JUnitServerImpl: JUnitServer {
private val SEND_THREAD = "JUnit Server Send Thread"
private val RECEIVE_THREAD = "JUnit Server Receive Thread"
private val postingMessages: BlockingQueue<TransportMessage> = LinkedBlockingQueue()
private val receivingMessages: BlockingQueue<TransportMessage> = LinkedBlockingQueue()
private val handlers: ArrayList<ServerHandler> = ArrayList()
private var failHandler: ((Throwable) -> Unit)? = null
private val LOG = Logger.getLogger("#com.intellij.testGuiFramework.remote.server.JUnitServerImpl")
private val serverSocket = ServerSocket(0)
lateinit private var serverSendThread: ServerSendThread
lateinit private var serverReceiveThread: ServerReceiveThread
lateinit private var connection: Socket
lateinit private var objectInputStream: ObjectInputStream
lateinit private var objectOutputStream: ObjectOutputStream
private val port: Int
init {
port = serverSocket.localPort
serverSocket.soTimeout = 180000
}
fun start() {
execOnParallelThread {
try {
connection = serverSocket.accept()
LOG.info("Server accepted client on port: ${connection.port}")
objectOutputStream = ObjectOutputStream(connection.getOutputStream())
serverSendThread = ServerSendThread(connection, objectOutputStream)
serverSendThread.start()
objectInputStream = ObjectInputStream(connection.getInputStream())
serverReceiveThread = ServerReceiveThread(connection, objectInputStream)
serverReceiveThread.start()
} catch (e: Exception) {
failHandler?.invoke(e)
}
}
}
override fun send(message: TransportMessage) {
postingMessages.put(message)
LOG.info("Add message to send pool: $message ")
}
override fun receive(): TransportMessage =
receivingMessages.take()
override fun sendAndWaitAnswer(message: TransportMessage)
= sendAndWaitAnswerBase(message)
override fun sendAndWaitAnswer(message: TransportMessage, timeout: Long, timeUnit: TimeUnit)
= sendAndWaitAnswerBase(message, timeout, timeUnit)
fun sendAndWaitAnswerBase(message: TransportMessage, timeout: Long = 0L, timeUnit: TimeUnit = TimeUnit.SECONDS): Unit {
val countDownLatch = CountDownLatch(1)
val waitHandler = createCallbackServerHandler({ countDownLatch.countDown() }, message.id)
addHandler(waitHandler)
send(message)
if (timeout == 0L)
countDownLatch.await()
else
countDownLatch.await(timeout, timeUnit)
removeHandler(waitHandler)
}
override fun addHandler(serverHandler: ServerHandler) {
handlers.add(serverHandler)
}
override fun removeHandler(serverHandler: ServerHandler) {
handlers.remove(serverHandler)
}
override fun removeAllHandlers() {
handlers.clear()
}
override fun setFailHandler(failHandler: (Throwable) -> Unit) {
this.failHandler = failHandler
}
override fun isConnected(): Boolean {
try {
return connection.isConnected
} catch (lateInitException: UninitializedPropertyAccessException) {
return false
}
}
override fun getPort() = port
override fun stopServer() {
serverSendThread.objectOutputStream.close()
LOG.info("Object output stream closed")
serverSendThread.join()
LOG.info("Server Send Thread joined")
serverReceiveThread.objectInputStream.close()
LOG.info("Object input stream closed")
serverReceiveThread.join()
LOG.info("Server Receive Thread joined")
connection.close()
}
private fun execOnParallelThread(body: () -> Unit) {
(object: Thread("JUnitServer: Exec On Parallel Thread") { override fun run() { body(); Thread.currentThread().join() } }).start()
}
private fun createCallbackServerHandler(handler: (TransportMessage) -> Unit, id: Long)
= object : ServerHandler() {
override fun acceptObject(message: TransportMessage) = message.id == id
override fun handleObject(message: TransportMessage) { handler(message) }
}
inner class ServerSendThread(val connection: Socket, val objectOutputStream: ObjectOutputStream) : Thread(SEND_THREAD) {
override fun run() {
LOG.info("Server Send Thread started")
try {
while (connection.isConnected) {
val message = postingMessages.take()
LOG.info("Sending message: $message ")
objectOutputStream.writeObject(message)
}
}
catch(e: InterruptedException) {
Thread.currentThread().interrupt()
}
catch (e: Exception) {
if (e is InvalidClassException) LOG.error("Probably client is down:", e)
failHandler?.invoke(e)
}
finally {
objectOutputStream.close()
}
}
}
inner class ServerReceiveThread(val connection: Socket, val objectInputStream: ObjectInputStream) : Thread(RECEIVE_THREAD) {
override fun run() {
try {
LOG.info("Server Receive Thread started")
while (connection.isConnected) {
val obj = objectInputStream.readObject()
LOG.info("Receiving message: $obj")
assert(obj is TransportMessage)
val message = obj as TransportMessage
receivingMessages.put(message)
val copied: Array<ServerHandler> = handlers.toTypedArray().copyOf()
copied
.filter { it.acceptObject(message) }
.forEach { it.handleObject(message) }
}
} catch (e: Exception) {
if (e is InvalidClassException) LOG.error("Probably serialization error:", e)
failHandler?.invoke(e)
}
}
}
}
|
apache-2.0
|
202584f3a4e438f08aa9779d38503900
| 32.555 | 133 | 0.714754 | 4.80315 | false | false | false | false |
daemontus/Distributed-CTL-Model-Checker
|
src/main/kotlin/com/github/sybila/checker/map/SingletonStateMap.kt
|
3
|
749
|
package com.github.sybila.checker.map
import com.github.sybila.checker.StateMap
//TODO: Add to string/hashcode/equals methods to all state maps
class SingletonStateMap<out Params : Any>(
private val state: Int,
private val value: Params,
private val default: Params
) : StateMap<Params> {
private val states = sequenceOf(state)
private val entries = sequenceOf(state to value)
override fun states(): Iterator<Int> = states.iterator()
override fun entries(): Iterator<Pair<Int, Params>> = entries.iterator()
override fun get(state: Int): Params = if (state == this.state) value else default
override fun contains(state: Int): Boolean = state == this.state
override val sizeHint: Int = 1
}
|
gpl-3.0
|
408497e3452ca294241e416c4aeacad8
| 27.846154 | 86 | 0.700935 | 4.138122 | false | false | false | false |
UweTrottmann/SeriesGuide
|
app/src/main/java/com/battlelancer/seriesguide/movies/MoviesActivityImpl.kt
|
1
|
5298
|
package com.battlelancer.seriesguide.movies
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.activity.viewModels
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.databinding.ActivityMoviesBinding
import com.battlelancer.seriesguide.movies.MoviesSettings.getLastMoviesTabPosition
import com.battlelancer.seriesguide.movies.search.MoviesSearchActivity
import com.battlelancer.seriesguide.traktapi.TraktCredentials
import com.battlelancer.seriesguide.ui.BaseTopActivity
import com.battlelancer.seriesguide.ui.TabStripAdapter
/**
* Movie section of the app, displays various movie tabs.
*/
open class MoviesActivityImpl : BaseTopActivity() {
private lateinit var binding: ActivityMoviesBinding
private lateinit var tabsAdapter: TabStripAdapter
private var showNowTab = false
private val viewModel by viewModels<MoviesActivityViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMoviesBinding.inflate(layoutInflater)
setContentView(binding.root)
setupActionBar()
setupBottomNavigation(R.id.navigation_item_movies)
setupViews(savedInstanceState)
setupSyncProgressBar(R.id.progressBarTabs)
if (savedInstanceState != null) {
postponeEnterTransition()
// Allow the adapters to repopulate during the next layout pass
// before starting the transition animation
binding.viewPagerMovies.post { startPostponedEnterTransition() }
}
}
private fun setupViews(savedInstanceState: Bundle?) {
binding.tabLayoutMovies.setOnTabClickListener { position: Int ->
if (binding.viewPagerMovies.currentItem == position) {
scrollSelectedTabToTop()
}
}
showNowTab = TraktCredentials.get(this@MoviesActivityImpl).hasCredentials()
tabsAdapter = TabStripAdapter(this, binding.viewPagerMovies, binding.tabLayoutMovies)
.apply {
// discover
addTab(R.string.title_discover, MoviesDiscoverFragment::class.java, null)
// Trakt-only tabs should only be visible if connected
if (showNowTab) {
// history tab
addTab(R.string.user_stream, MoviesNowFragment::class.java, null)
}
// watchlist
addTab(R.string.movies_watchlist, MoviesWatchListFragment::class.java, null)
// collection
addTab(R.string.movies_collection, MoviesCollectionFragment::class.java, null)
// watched
addTab(R.string.movies_watched, MoviesWatchedFragment::class.java, null)
notifyTabsChanged()
}
if (savedInstanceState == null) {
binding.viewPagerMovies.setCurrentItem(getLastMoviesTabPosition(this), false)
}
}
private fun scrollSelectedTabToTop() {
viewModel.scrollTabToTop(binding.viewPagerMovies.currentItem, showNowTab)
}
override fun onSelectedCurrentNavItem() {
scrollSelectedTabToTop()
}
override fun onStart() {
super.onStart()
maybeAddNowTab()
}
private fun maybeAddNowTab() {
val currentTabCount = tabsAdapter.itemCount
showNowTab = TraktCredentials.get(this).hasCredentials()
if (showNowTab && currentTabCount != TAB_COUNT_WITH_TRAKT) {
tabsAdapter.addTab(
R.string.user_stream, MoviesNowFragment::class.java, null, TAB_POSITION_NOW
)
// update tabs
tabsAdapter.notifyTabsChanged()
}
}
override fun onPause() {
super.onPause()
MoviesSettings.saveLastMoviesTabPosition(this, binding.viewPagerMovies.currentItem)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.movies_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_action_movies_search -> {
startActivity(Intent(this, MoviesSearchActivity::class.java))
true
}
else -> super.onOptionsItemSelected(item)
}
}
override val snackbarParentView: View
get() = binding.coordinatorLayoutMovies
companion object {
// const val SEARCH_LOADER_ID = 100
const val NOW_TRAKT_USER_LOADER_ID = 101
const val NOW_TRAKT_FRIENDS_LOADER_ID = 102
const val WATCHLIST_LOADER_ID = 103
const val COLLECTION_LOADER_ID = 104
const val TAB_POSITION_DISCOVER = 0
const val TAB_POSITION_WATCHLIST_DEFAULT = 1
const val TAB_POSITION_COLLECTION_DEFAULT = 2
const val TAB_POSITION_WATCHED_DEFAULT = 3
const val TAB_POSITION_NOW = 1
const val TAB_POSITION_WATCHLIST_WITH_NOW = 2
const val TAB_POSITION_COLLECTION_WITH_NOW = 3
const val TAB_POSITION_WATCHED_WITH_NOW = 4
private const val TAB_COUNT_WITH_TRAKT = 5
}
}
|
apache-2.0
|
7d70aabb1b4e8c5d12fb8e62db9b065f
| 36.58156 | 94 | 0.664213 | 4.910102 | false | false | false | false |
TheFakeMontyOnTheRun/GiovanniTheExplorer
|
app/src/main/java/br/odb/giovanni/menus/ItCameFromTheCaveActivity.kt
|
1
|
1259
|
package br.odb.giovanni.menus
import android.media.MediaPlayer
import android.os.Bundle
import android.view.KeyEvent
import androidx.appcompat.app.AppCompatActivity
import br.odb.giovanni.R
class ItCameFromTheCaveActivity : AppCompatActivity() {
private var view: ItCameView? = null
private var mp: MediaPlayer? = null
private var hasSound: Boolean = false
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
hasSound = intent.extras!!.getBoolean("hasSound")
view = ItCameView(this, hasSound)
setContentView(view)
setResult(RESULT_CANCELED)
}
override fun onPause() {
if (mp != null) {
mp!!.pause()
mp!!.release()
}
mp = null
view!!.playing = false
super.onPause()
}
override fun onResume() {
super.onResume()
if (hasSound) {
mp = MediaPlayer.create(this, R.raw.ingame)
mp!!.isLooping = true
mp!!.start()
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
return view!!.onKeyDown(keyCode, event)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
return view!!.onKeyUp(keyCode, event)
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
view!!.playing = hasFocus
super.onWindowFocusChanged(hasFocus)
}
}
|
bsd-3-clause
|
b1978137f27ca8efea537cb3a687472b
| 21.105263 | 65 | 0.722002 | 3.477901 | false | false | false | false |
joseph-roque/BowlingCompanion
|
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/series/HighSeriesOf2Statistic.kt
|
1
|
951
|
package ca.josephroque.bowlingcompanion.statistics.impl.series
import android.os.Parcel
import android.os.Parcelable
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator
/**
* Copyright (C) 2018 Joseph Roque
*
* Highest series of 2 games.
*/
class HighSeriesOf2Statistic(value: Int = 0) : HighSeriesStatistic(value) {
// MARK: Overrides
override val seriesSize = 2
override val titleId = Id
override val id = Id.toLong()
// MARK: Parcelable
companion object {
/** Creator, required by [Parcelable]. */
@Suppress("unused")
@JvmField val CREATOR = parcelableCreator(::HighSeriesOf2Statistic)
/** Unique ID for the statistic. */
const val Id = R.string.statistic_high_series_of_2
}
/**
* Construct this statistic from a [Parcel].
*/
private constructor(p: Parcel): this(value = p.readInt())
}
|
mit
|
78460e8cbf8a50a3cb675ce6b4035675
| 25.416667 | 75 | 0.685594 | 4.245536 | false | false | false | false |
RP-Kit/RPKit
|
bukkit/rpk-stat-builds-bukkit/src/main/kotlin/com/rpkit/statbuilds/bukkit/skillpoint/RPKSkillPointServiceImpl.kt
|
1
|
2701
|
/*
* Copyright 2022 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.statbuilds.bukkit.skillpoint
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.core.expression.RPKExpressionService
import com.rpkit.core.service.Services
import com.rpkit.experience.bukkit.experience.RPKExperienceService
import com.rpkit.skills.bukkit.skills.RPKSkillPointService
import com.rpkit.skills.bukkit.skills.RPKSkillType
import com.rpkit.statbuilds.bukkit.RPKStatBuildsBukkit
import com.rpkit.statbuilds.bukkit.statattribute.RPKStatAttributeService
import com.rpkit.statbuilds.bukkit.statbuild.RPKStatBuildService
import java.util.concurrent.CompletableFuture
import java.util.logging.Level
class RPKSkillPointServiceImpl(override val plugin: RPKStatBuildsBukkit) : RPKSkillPointService {
override fun getSkillPoints(character: RPKCharacter, skillType: RPKSkillType): CompletableFuture<Int> {
return CompletableFuture.supplyAsync {
val statBuildService = Services[RPKStatBuildService::class.java] ?: return@supplyAsync 0
val statAttributeService = Services[RPKStatAttributeService::class.java] ?: return@supplyAsync 0
val experienceService = Services[RPKExperienceService::class.java] ?: return@supplyAsync 0
val expressionService = Services[RPKExpressionService::class.java] ?: return@supplyAsync 0
val expression = expressionService.createExpression(
plugin.config.getString("skill-points.${skillType.name}") ?: return@supplyAsync 0
)
return@supplyAsync expression.parseInt(
mapOf(
"level" to experienceService.getLevel(character).join().toDouble(),
*statAttributeService.statAttributes.map { statAttribute ->
statAttribute.name.value to statBuildService.getStatPoints(character, statAttribute).join().toDouble()
}.toTypedArray()
)
) ?: 0
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to get skill points", exception)
throw exception
}
}
}
|
apache-2.0
|
72e0ce72f395eb9a9dd55e118e88ad46
| 49.037037 | 126 | 0.726398 | 4.772085 | false | false | false | false |
cketti/k-9
|
app/core/src/test/java/com/fsck/k9/notification/SyncNotificationControllerTest.kt
|
1
|
6322
|
package com.fsck.k9.notification
import android.app.Notification
import android.app.PendingIntent
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.test.core.app.ApplicationProvider
import com.fsck.k9.Account
import com.fsck.k9.RobolectricTest
import com.fsck.k9.mailstore.LocalFolder
import com.fsck.k9.notification.NotificationIds.getFetchingMailNotificationId
import com.fsck.k9.testing.MockHelper.mockBuilder
import org.junit.Test
import org.mockito.ArgumentMatchers.anyLong
import org.mockito.Mockito.verify
import org.mockito.kotlin.any
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
private const val ACCOUNT_NUMBER = 1
private const val ACCOUNT_NAME = "TestAccount"
private const val FOLDER_SERVER_ID = "INBOX"
private const val FOLDER_NAME = "Inbox"
class SyncNotificationControllerTest : RobolectricTest() {
private val resourceProvider: NotificationResourceProvider = TestNotificationResourceProvider()
private val notification = mock<Notification>()
private val lockScreenNotification = mock<Notification>()
private val notificationManager = mock<NotificationManagerCompat>()
private val builder = createFakeNotificationBuilder(notification)
private val lockScreenNotificationBuilder = createFakeNotificationBuilder(lockScreenNotification)
private val account = createFakeAccount()
private val contentIntent = mock<PendingIntent>()
private val controller = SyncNotificationController(
notificationHelper = createFakeNotificationHelper(notificationManager, builder, lockScreenNotificationBuilder),
actionBuilder = createActionBuilder(contentIntent),
resourceProvider = resourceProvider
)
@Test
fun testShowSendingNotification() {
val notificationId = getFetchingMailNotificationId(account)
controller.showSendingNotification(account)
verify(notificationManager).notify(notificationId, notification)
verify(builder).setSmallIcon(resourceProvider.iconSendingMail)
verify(builder).setTicker("Sending mail: $ACCOUNT_NAME")
verify(builder).setContentTitle("Sending mail")
verify(builder).setContentText(ACCOUNT_NAME)
verify(builder).setContentIntent(contentIntent)
verify(builder).setPublicVersion(lockScreenNotification)
verify(lockScreenNotificationBuilder).setContentTitle("Sending mail")
verify(lockScreenNotificationBuilder, never()).setContentText(any())
verify(lockScreenNotificationBuilder, never()).setTicker(any())
}
@Test
fun testClearSendingNotification() {
val notificationId = getFetchingMailNotificationId(account)
controller.clearSendingNotification(account)
verify(notificationManager).cancel(notificationId)
}
@Test
fun testGetFetchingMailNotificationId() {
val localFolder = createFakeLocalFolder()
val notificationId = getFetchingMailNotificationId(account)
controller.showFetchingMailNotification(account, localFolder)
verify(notificationManager).notify(notificationId, notification)
verify(builder).setSmallIcon(resourceProvider.iconCheckingMail)
verify(builder).setTicker("Checking mail: $ACCOUNT_NAME:$FOLDER_NAME")
verify(builder).setContentTitle("Checking mail")
verify(builder).setContentText("$ACCOUNT_NAME:$FOLDER_NAME")
verify(builder).setContentIntent(contentIntent)
verify(builder).setPublicVersion(lockScreenNotification)
verify(lockScreenNotificationBuilder).setContentTitle("Checking mail")
verify(lockScreenNotificationBuilder, never()).setContentText(any())
verify(lockScreenNotificationBuilder, never()).setTicker(any())
}
@Test
fun testShowEmptyFetchingMailNotification() {
val notificationId = getFetchingMailNotificationId(account)
controller.showEmptyFetchingMailNotification(account)
verify(notificationManager).notify(notificationId, notification)
verify(builder).setSmallIcon(resourceProvider.iconCheckingMail)
verify(builder).setContentTitle("Checking mail")
verify(builder).setContentText(ACCOUNT_NAME)
verify(builder).setPublicVersion(lockScreenNotification)
verify(lockScreenNotificationBuilder).setContentTitle("Checking mail")
verify(lockScreenNotificationBuilder, never()).setContentText(any())
verify(lockScreenNotificationBuilder, never()).setTicker(any())
}
@Test
fun testClearSendFailedNotification() {
val notificationId = getFetchingMailNotificationId(account)
controller.clearFetchingMailNotification(account)
verify(notificationManager).cancel(notificationId)
}
private fun createFakeNotificationBuilder(notification: Notification): NotificationCompat.Builder {
return mockBuilder {
on { build() } doReturn notification
}
}
private fun createFakeNotificationHelper(
notificationManager: NotificationManagerCompat,
notificationBuilder: NotificationCompat.Builder,
lockScreenNotificationBuilder: NotificationCompat.Builder
): NotificationHelper {
return mock {
on { getContext() } doReturn ApplicationProvider.getApplicationContext()
on { getNotificationManager() } doReturn notificationManager
on { createNotificationBuilder(any(), any()) }.doReturn(notificationBuilder, lockScreenNotificationBuilder)
}
}
private fun createFakeAccount(): Account {
return mock {
on { accountNumber } doReturn ACCOUNT_NUMBER
on { name } doReturn ACCOUNT_NAME
on { displayName } doReturn ACCOUNT_NAME
on { outboxFolderId } doReturn 33L
}
}
private fun createActionBuilder(contentIntent: PendingIntent): NotificationActionCreator {
return mock {
on { createViewFolderPendingIntent(eq(account), anyLong()) } doReturn contentIntent
}
}
private fun createFakeLocalFolder(): LocalFolder {
return mock {
on { serverId } doReturn FOLDER_SERVER_ID
on { name } doReturn FOLDER_NAME
}
}
}
|
apache-2.0
|
977c6f05908002e9222912c1435176ba
| 40.592105 | 119 | 0.744227 | 5.526224 | false | true | false | false |
mbuenoferrer/barfastic
|
app/src/main/kotlin/com/refactorizado/barfastic/presentation/food/view/FoodListAdapter.kt
|
1
|
1285
|
package com.refactorizado.barfastic.presentation.food.view
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.refactorizado.barfastic.R
import com.refactorizado.barfastic.domain.food.entity.Food
import com.refactorizado.barfastic.presentation.common.inflate
import com.refactorizado.barfastic.presentation.common.loadUrl
import kotlinx.android.synthetic.main.food_list_item.view.*
class FoodListAdapter()
: RecyclerView.Adapter<FoodListAdapter.ViewHolder>() {
var items: List<Food> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(parent.inflate(R.layout.food_list_item))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
with(holder.itemView){
val item = items[position]
tv_name.text = item.name
iv_photo.loadUrl(item.imageUrl)
}
}
override fun getItemCount() = items.size
fun setData(foodList: List<Food>) {
items = foodList
notifyDataSetChanged()
}
fun clearData() {
items = ArrayList()
this.notifyDataSetChanged()
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
}
}
|
mit
|
5e44198de7e2bc5b7af39cbd429e915d
| 27.555556 | 83 | 0.708949 | 4.079365 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/administration/UnwarnCommand.kt
|
1
|
4582
|
package net.perfectdreams.loritta.morenitta.commands.vanilla.administration
import net.perfectdreams.loritta.morenitta.dao.Warn
import net.perfectdreams.loritta.morenitta.tables.Warns
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.utils.extensions.retrieveMemberOrNull
import net.dv8tion.jda.api.Permission
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase
import net.perfectdreams.loritta.common.utils.Emotes
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.deleteWhere
class UnwarnCommand(loritta: LorittaBot): DiscordAbstractCommandBase(loritta, listOf("unwarn", "desavisar"), net.perfectdreams.loritta.common.commands.CommandCategory.MODERATION) {
companion object {
const val LOCALE_PREFIX = "commands.command.unwarn"
}
override fun command() = create {
localizedDescription("$LOCALE_PREFIX.description")
localizedExamples("$LOCALE_PREFIX.examples")
usage {
argument(ArgumentType.USER) {
optional = false
}
argument(ArgumentType.NUMBER) {
optional = false
}
}
canUseInPrivateChannel = false
userRequiredPermissions = listOf(
Permission.KICK_MEMBERS
)
botRequiredPermissions = listOf(
Permission.BAN_MEMBERS,
Permission.KICK_MEMBERS
)
executesDiscord {
if (args.isEmpty())
return@executesDiscord explain()
val user = AdminUtils.checkUser(this) ?:
return@executesDiscord
val member = guild.retrieveMemberOrNull(user.handle)
if (member != null) {
if (!AdminUtils.checkPermissions(this, member))
return@executesDiscord
}
val warns = loritta.newSuspendedTransaction {
Warn.find { (Warns.guildId eq guild.idLong) and (Warns.userId eq user.id) }.toList()
}
if (warns.isEmpty()) {
reply(
LorittaReply(
locale["$LOCALE_PREFIX.noWarnsFound", "`${serverConfig.commandPrefix}warnlist`"],
Constants.ERROR
)
)
return@executesDiscord
}
if (args.getOrNull(1) == "all") {
loritta.newSuspendedTransaction {
Warns.deleteWhere { (Warns.guildId eq guild.idLong) and (Warns.userId eq user.id) }
}
if (warns.size == 1) {
reply(
LorittaReply(
locale["$LOCALE_PREFIX.warnRemoved"],
Emotes.LORI_HMPF
)
)
return@executesDiscord
}
reply(
locale["$LOCALE_PREFIX.warnsRemoved", warns.size],
Emotes.LORI_HMPF
)
return@executesDiscord
}
var warnIndex = 0
if (args.size >= 2) {
if (args[1].toIntOrNull() == null && args.getOrNull(1) == "all") {
reply(
LorittaReply(
locale["commands.invalidNumber", args[1]],
Constants.ERROR
)
)
return@executesDiscord
}
warnIndex = args[1].toInt()
} else warnIndex = warns.size
if (warnIndex > warns.size) {
reply(
LorittaReply(
locale["$LOCALE_PREFIX.notEnoughWarns", warnIndex, "`${serverConfig.commandPrefix}warnlist`"],
Constants.ERROR
)
)
return@executesDiscord
}
val selectedWarn = warns[warnIndex - 1]
loritta.newSuspendedTransaction {
selectedWarn.delete()
}
reply(
LorittaReply(
locale["${LOCALE_PREFIX}.warnRemoved"] + " ${Emotes.LORI_HMPF}",
"\uD83C\uDF89"
)
)
}
}
}
|
agpl-3.0
|
000413bbfdce93c1b46767536e59ae46
| 34.527132 | 180 | 0.533173 | 5.384254 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/discord/LorittaInfoExecutor.kt
|
1
|
6697
|
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.discord
import kotlinx.datetime.toKotlinInstant
import net.perfectdreams.discordinteraktions.common.builder.message.actionRow
import net.perfectdreams.discordinteraktions.common.builder.message.embed
import net.perfectdreams.discordinteraktions.common.utils.author
import net.perfectdreams.discordinteraktions.common.utils.footer
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.common.utils.GACampaigns
import net.perfectdreams.loritta.common.utils.LorittaColors
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.discord.declarations.LorittaCommand
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.loriEmoji
import net.perfectdreams.loritta.cinnamon.discord.utils.toKordColor
import java.time.Instant
class LorittaInfoExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) {
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
context.deferChannelMessage()
val since = Instant.now()
.minusSeconds(86400)
.toKotlinInstant()
val guildCount = context.loritta.pudding.stats.getGuildCount()
val executedApplicationCommands = context.loritta.pudding.executedInteractionsLog.getExecutedApplicationCommands(since)
val uniqueUsersExecutedApplicationCommands = context.loritta.pudding.executedInteractionsLog.getUniqueUsersExecutedApplicationCommands(since)
context.sendMessage {
embed {
color = LorittaColors.LorittaAqua.toKordColor()
author(context.i18nContext.get(LorittaCommand.I18N_PREFIX.Info.Embed.Title))
description = context.i18nContext.get(
LorittaCommand.I18N_PREFIX.Info.Embed.Description(
guildCount = guildCount,
commandCount = context.loritta.getCommandCount(),
executedApplicationCommands = executedApplicationCommands,
uniqueUsersExecutedApplicationCommands = uniqueUsersExecutedApplicationCommands,
userMention = "<@${context.user.id.value}>",
loriSunglasses = Emotes.LoriSunglasses,
loriYay = Emotes.LoriYay,
loriKiss = Emotes.LoriKiss,
loriHeart = Emotes.LoriHeart
)
).joinToString("\n")
image = "${context.loritta.config.loritta.website.url}v3/assets/img/sonhos/lori-space.gif"
footer(context.i18nContext.get(LorittaCommand.I18N_PREFIX.Info.Embed.Footer("MrPowerGamerBR#4185", "https://mrpowergamerbr.com")), "https://mrpowergamerbr.com/assets/img/avatar.png")
}
actionRow {
linkButton(
GACampaigns.createUrlWithCampaign(
"https://loritta.website",
"discord",
"loritta-info",
"loritta-info-links",
"home-page"
).toString()
) {
label = context.i18nContext.get(LorittaCommand.I18N_PREFIX.Info.Website)
loriEmoji = Emotes.LoriSunglasses
}
linkButton(
GACampaigns.createUrlWithCampaign(
"https://loritta.website/dashboard",
"discord",
"loritta-info",
"loritta-info-links",
"dashboard"
).toString()
) {
label = context.i18nContext.get(LorittaCommand.I18N_PREFIX.Info.Dashboard)
loriEmoji = Emotes.LoriReading
}
linkButton(
GACampaigns.createUrlWithCampaign(
"https://loritta.website/commands",
"discord",
"loritta-info",
"loritta-info-links",
"commands"
).toString()
) {
label = context.i18nContext.get(LorittaCommand.I18N_PREFIX.Info.Commands)
loriEmoji = Emotes.LoriWow
}
linkButton(
GACampaigns.createUrlWithCampaign(
"https://loritta.website/support",
"discord",
"loritta-info",
"loritta-info-links",
"support"
).toString()
) {
label = context.i18nContext.get(LorittaCommand.I18N_PREFIX.Info.Support)
loriEmoji = Emotes.LoriHm
}
linkButton(
GACampaigns.createUrlWithCampaign(
"https://loritta.website/donate",
"discord",
"loritta-info",
"loritta-info-links",
"premium"
).toString()
) {
label = context.i18nContext.get(LorittaCommand.I18N_PREFIX.Info.Premium)
loriEmoji = Emotes.LoriCard
}
}
actionRow {
linkButton("https://twitter.com/LorittaBot") {
label = "Twitter"
loriEmoji = Emotes.Twitter
}
linkButton("https://instagram.com/lorittabot") {
label = "Instagram"
loriEmoji = Emotes.Instagram
}
linkButton("https://youtube.com/c/Loritta") {
label = "YouTube"
loriEmoji = Emotes.YouTube
}
linkButton("https://www.tiktok.com/@lorittamorenittabot") {
label = "TikTok"
loriEmoji = Emotes.TikTok
}
linkButton("https://github.com/LorittaBot") {
label = "GitHub"
loriEmoji = Emotes.GitHub
}
}
}
}
}
|
agpl-3.0
|
b963fafb52b049ce104e65b9e3dae626
| 43.065789 | 198 | 0.558758 | 5.353317 | false | false | false | false |
jitsi/jibri
|
src/main/kotlin/org/jitsi/jibri/selenium/JibriSelenium.kt
|
1
|
15794
|
/*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.jibri.selenium
import org.jitsi.jibri.CallUrlInfo
import org.jitsi.jibri.MainConfig
import org.jitsi.jibri.config.Config
import org.jitsi.jibri.config.XmppCredentials
import org.jitsi.jibri.selenium.pageobjects.CallPage
import org.jitsi.jibri.selenium.pageobjects.HomePage
import org.jitsi.jibri.selenium.status_checks.EmptyCallStatusCheck
import org.jitsi.jibri.selenium.status_checks.IceConnectionStatusCheck
import org.jitsi.jibri.selenium.status_checks.LocalParticipantKickedStatusCheck
import org.jitsi.jibri.selenium.status_checks.MediaReceivedStatusCheck
import org.jitsi.jibri.selenium.util.BrowserFileHandler
import org.jitsi.jibri.status.ComponentState
import org.jitsi.jibri.util.StatusPublisher
import org.jitsi.jibri.util.TaskPools
import org.jitsi.jibri.util.extensions.scheduleAtFixedRate
import org.jitsi.jibri.util.getLoggerWithHandler
import org.jitsi.metaconfig.config
import org.jitsi.metaconfig.from
import org.jitsi.utils.logging2.Logger
import org.jitsi.utils.logging2.createChildLogger
import org.openqa.selenium.TimeoutException
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeDriverService
import org.openqa.selenium.chrome.ChromeOptions
import org.openqa.selenium.logging.LogType
import org.openqa.selenium.logging.LoggingPreferences
import org.openqa.selenium.remote.CapabilityType
import org.openqa.selenium.remote.UnreachableBrowserException
import java.time.Duration
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.logging.Level
/**
* Parameters needed for joining the call in Selenium
*/
data class CallParams(
val callUrlInfo: CallUrlInfo,
/**
* The email that should be used for jibri. Note that this
* is currently only used in the sipgateway gateway scenario; when doing
* recording the jibri is 'invisible' in the call
*/
val email: String = "",
/**
* SipJibri will set the passcode in the local storage
* This will be used by jitsi-meet to send the conference passcode to prosody
* and bypass the password prompt
*/
val passcode: String? = null,
/**
* Override the default value of callStats username.
* Note that this is currently only used in the sipgateway gateway scenario;
*/
val callStatsUsernameOverride: String = "",
/**
* Display name which when it is set, it is used by jibri when joining the web conference.
* Note that this is currently only used in the sipgateway gateway scenario;
*/
val displayName: String = ""
) {
override fun toString(): String {
return if (passcode.isNullOrEmpty()) {
"CallParams(callUrlInfo=$callUrlInfo, email='$email', passcode=$passcode" +
", callStatsUsernameOverride=$callStatsUsernameOverride, displayName=$displayName)"
} else {
"CallParams(callUrlInfo=$callUrlInfo, email='$email', passcode=*****" +
", callStatsUsernameOverride=$callStatsUsernameOverride, displayName=$displayName)"
}
}
}
/**
* Options that can be passed to [JibriSelenium]
*/
data class JibriSeleniumOptions(
/**
* Which display selenium should be started on
*/
val display: String = ":0",
/**
* The display name that should be used for jibri. Note that this
* is currently only used in the sipgateway gateway scenario; when doing
* recording the jibri is 'invisible' in the call
*/
val displayName: String = "",
/**
* The email that should be used for jibri. Note that this
* is currently only used in the sipgateway gateway scenario; when doing
* recording the jibri is 'invisible' in the call
*/
val email: String = "",
/**
* The callstats username to be used for jibri.
* Set this only to override the default callStatsUsername
*/
val callStatsUsernameOverride: String = "",
/**
* Chrome command line flags to add (in addition to the common
* ones)
*/
val extraChromeCommandLineFlags: List<String> = listOf(),
/**
* How long we should stay in a call with no other participants before quitting
*/
val emptyCallTimeout: Duration = EmptyCallStatusCheck.defaultCallEmptyTimeout,
/**
* Use local participant status checks, such as if the local participant is kicked out
* This is currently only used in the sipgateway gateway scenario;
*/
val enableLocalParticipantStatusChecks: Boolean = false
)
val SIP_GW_URL_OPTIONS = listOf(
"config.iAmRecorder=true",
"config.iAmSipGateway=true",
"config.ignoreStartMuted=true",
"config.analytics.disabled=true",
"config.enableEmailInStats=false",
"config.p2p.enabled=false",
"config.prejoinPageEnabled=false",
"config.prejoinConfig.enabled=false",
"config.requireDisplayName=false",
"devices.videoInput=\"PJSUA\""
)
val RECORDING_URL_OPTIONS = listOf(
"config.iAmRecorder=true",
"config.externalConnectUrl=null",
"config.startWithAudioMuted=true",
"config.startWithVideoMuted=true",
"interfaceConfig.APP_NAME=\"Jibri\"",
"config.analytics.disabled=true",
"config.p2p.enabled=false",
"config.prejoinPageEnabled=false",
"config.prejoinConfig.enabled=false",
"config.requireDisplayName=false"
)
/**
* The [JibriSelenium] class is responsible for all of the interactions with
* Selenium. It:
* 1) Owns the webdriver
* 2) Handles passing the proper options to Chrome
* 3) Sets the necessary localstorage variables before joining a call
* It implements [StatusPublisher] to publish its status
*/
class JibriSelenium(
parentLogger: Logger,
private val jibriSeleniumOptions: JibriSeleniumOptions = JibriSeleniumOptions()
) : StatusPublisher<ComponentState>() {
private val logger = createChildLogger(parentLogger)
private var chromeDriver: ChromeDriver
private var currCallUrl: String? = null
private val stateMachine = SeleniumStateMachine()
private var shuttingDown = AtomicBoolean(false)
private val chromeOpts: List<String> by config("jibri.chrome.flags".from(Config.configSource))
/**
* A task which executes at an interval and checks various aspects of the call to make sure things are
* working correctly
*/
private var recurringCallStatusCheckTask: ScheduledFuture<*>? = null
/**
* Set up default chrome driver options (using fake device, etc.)
*/
init {
System.setProperty("webdriver.chrome.logfile", "/tmp/chromedriver.log")
val chromeOptions = ChromeOptions()
chromeOptions.addArguments(chromeOpts)
chromeOptions.setExperimentalOption("w3c", false)
chromeOptions.addArguments(jibriSeleniumOptions.extraChromeCommandLineFlags)
val chromeDriverService = ChromeDriverService.Builder().withEnvironment(
mapOf("DISPLAY" to jibriSeleniumOptions.display)
).build()
val logPrefs = LoggingPreferences()
logPrefs.enable(LogType.DRIVER, Level.ALL)
chromeOptions.setCapability(CapabilityType.LOGGING_PREFS, logPrefs)
chromeDriver = ChromeDriver(chromeDriverService, chromeOptions)
chromeDriver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS)
stateMachine.onStateTransition(this::onSeleniumStateChange)
}
/**
* Set various values to be put in local storage. NOTE: the driver
* should have already navigated to the desired page
*/
private fun setLocalStorageValues(keyValues: Map<String, String>) {
for ((key, value) in keyValues) {
chromeDriver.executeScript("window.localStorage.setItem('$key', '$value')")
}
}
private fun onSeleniumStateChange(oldState: ComponentState, newState: ComponentState) {
logger.info("Transitioning from state $oldState to $newState")
publishStatus(newState)
}
private fun startRecurringCallStatusChecks() {
// Note that the order here is important: we always want to check for no participants before we check
// for media being received, since the call being empty will also mean Jibri is not receiving media but should
// not cause Jibri to go unhealthy (like not receiving media when there are others in the call will).
val callStatusChecks = buildList {
add(EmptyCallStatusCheck(logger, callEmptyTimeout = jibriSeleniumOptions.emptyCallTimeout))
add(MediaReceivedStatusCheck(logger))
add(IceConnectionStatusCheck(logger))
if (jibriSeleniumOptions.enableLocalParticipantStatusChecks) {
add(LocalParticipantKickedStatusCheck(logger))
}
}
// We fire all state transitions in the ioPool, otherwise we may try and cancel the
// recurringCallStatusCheckTask from within the thread it was executing in. Another solution would've been
// to pass 'false' to recurringCallStatusCheckTask.cancel, but it felt cleaner to separate the threads
val transitionState = { event: SeleniumEvent ->
TaskPools.ioPool.submit {
stateMachine.transition(event)
}
}
recurringCallStatusCheckTask = TaskPools.recurringTasksPool.scheduleAtFixedRate(15, TimeUnit.SECONDS, 15) {
val callPage = CallPage(chromeDriver)
try {
// Run through each of the checks. If we hit one that returns an event, then we stop and process the
// state transition from that event. Note: it's intentional that we stop at the first check that fails
// and 'asSequence' is necessary to do that.
val event = callStatusChecks
.asSequence()
.map { check -> check.run(callPage) }
.firstOrNull { result -> result != null }
if (event != null) {
logger.info("Recurring call status checks generated event $event")
transitionState(event)
}
} catch (t: TimeoutException) {
// We've found that a timeout here often implies chrome has hung so consider this as an error
// which will result in this Jibri being marked as unhealthy
logger.error("Javascript timed out, assuming chrome has hung", t)
transitionState(SeleniumEvent.ChromeHung)
} catch (t: UnreachableBrowserException) {
if (!shuttingDown.get()) {
logger.error("Can't reach browser", t)
transitionState(SeleniumEvent.ChromeHung)
}
} catch (t: Throwable) {
logger.error("Error while running call status checks", t)
// We'll just assume anything here is an issue
transitionState(SeleniumEvent.ChromeHung)
}
}
}
/**
* Keep track of all the participants who take part in the call while
* Jibri is active
*/
private fun addParticipantTrackers() {
CallPage(chromeDriver).injectParticipantTrackerScript()
if (jibriSeleniumOptions.enableLocalParticipantStatusChecks) {
CallPage(chromeDriver).injectLocalParticipantTrackerScript()
}
}
fun addToPresence(key: String, value: String): Boolean = CallPage(chromeDriver).addToPresence(key, value)
fun sendPresence(): Boolean = CallPage(chromeDriver).sendPresence()
/**
* Join a a web call with Selenium
*/
fun joinCall(callUrlInfo: CallUrlInfo, xmppCredentials: XmppCredentials? = null, passcode: String? = null) {
// These are all blocking calls, so offload the work to another thread
TaskPools.ioPool.submit {
try {
HomePage(chromeDriver).visit(callUrlInfo.baseUrl)
var callStatsUsername = "jibri"
if (jibriSeleniumOptions.callStatsUsernameOverride.isNotEmpty()) {
callStatsUsername = jibriSeleniumOptions.callStatsUsernameOverride
} else if (MainConfig.jibriId.isNotEmpty()) {
callStatsUsername = MainConfig.jibriId
}
val localStorageValues = mutableMapOf(
"displayname" to jibriSeleniumOptions.displayName,
"email" to jibriSeleniumOptions.email,
"callStatsUserName" to callStatsUsername
)
xmppCredentials?.let {
localStorageValues["xmpp_username_override"] =
"${xmppCredentials.username}@${xmppCredentials.domain}"
localStorageValues["xmpp_password_override"] = xmppCredentials.password
}
passcode?.let {
localStorageValues["xmpp_conference_password_override"] = passcode
}
setLocalStorageValues(localStorageValues)
if (!CallPage(chromeDriver).visit(callUrlInfo.callUrl)) {
stateMachine.transition(SeleniumEvent.FailedToJoinCall)
} else {
startRecurringCallStatusChecks()
addParticipantTrackers()
currCallUrl = callUrlInfo.callUrl
stateMachine.transition(SeleniumEvent.CallJoined)
}
} catch (t: Throwable) {
logger.error("An error occurred while joining the call", t)
stateMachine.transition(SeleniumEvent.FailedToJoinCall)
}
}
}
fun getParticipants(): List<Map<String, Any>> {
return CallPage(chromeDriver).getParticipants()
}
fun leaveCallAndQuitBrowser() {
logger.info("Leaving call and quitting browser")
shuttingDown.set(true)
recurringCallStatusCheckTask?.cancel(true)
logger.info("Recurring call status checks cancelled")
browserOutputLogger.info("Logs for call $currCallUrl")
try {
chromeDriver.manage().logs().availableLogTypes.forEach { logType ->
val logEntries = chromeDriver.manage().logs().get(logType)
logger.info("Got ${logEntries.all.size} log entries for type $logType")
browserOutputLogger.info("========= TYPE=$logType ===========")
logEntries.all.forEach {
browserOutputLogger.info(it.toString())
}
}
} catch (t: Throwable) {
logger.error("Error trying to get chromedriver logs", t)
}
logger.info("Leaving web call")
try {
CallPage(chromeDriver).leave()
} catch (t: Throwable) {
logger.error("Error trying to leave the call", t)
}
currCallUrl = null
logger.info("Quitting chrome driver")
chromeDriver.quit()
logger.info("Chrome driver quit")
}
companion object {
private val browserOutputLogger = getLoggerWithHandler("browser", BrowserFileHandler())
const val COMPONENT_ID = "Selenium"
}
}
|
apache-2.0
|
5a8870bb5309cf7896a3a82da32c38f0
| 41.456989 | 118 | 0.668482 | 4.595287 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.