repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractClass/ui/KotlinExtractSuperDialogBase.kt | 1 | 7411 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.introduce.extractClass.ui
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.classMembers.MemberInfoChange
import com.intellij.refactoring.extractSuperclass.JavaExtractSuperBaseDialog
import com.intellij.refactoring.util.DocCommentPolicy
import com.intellij.refactoring.util.RefactoringMessageUtil
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.FormBuilder
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.base.util.onTextChange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.psi.unquoteKotlinIdentifier
import org.jetbrains.kotlin.idea.refactoring.introduce.extractClass.ExtractSuperInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberSelectionPanel
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinUsesAndInterfacesDependencyMemberInfoModel
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.psiUtil.isIdentifier
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import java.awt.BorderLayout
import javax.swing.*
abstract class KotlinExtractSuperDialogBase(
protected val originalClass: KtClassOrObject,
protected val targetParent: PsiElement,
private val conflictChecker: (KotlinExtractSuperDialogBase) -> Boolean,
private val isExtractInterface: Boolean,
@Nls refactoringName: String,
private val refactoring: (ExtractSuperInfo) -> Unit
) : JavaExtractSuperBaseDialog(originalClass.project, originalClass.toLightClass()!!, emptyList(), refactoringName) {
private var initComplete: Boolean = false
private lateinit var memberInfoModel: MemberInfoModelBase
val selectedMembers: List<KotlinMemberInfo>
get() = memberInfoModel.memberInfos.filter { it.isChecked }
private val fileNameField = JTextField()
open class MemberInfoModelBase(
originalClass: KtClassOrObject,
val memberInfos: List<KotlinMemberInfo>,
interfaceContainmentVerifier: (KtNamedDeclaration) -> Boolean
) : KotlinUsesAndInterfacesDependencyMemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>(
originalClass,
null,
false,
interfaceContainmentVerifier
) {
override fun isMemberEnabled(member: KotlinMemberInfo): Boolean {
val declaration = member.member ?: return false
return !declaration.hasModifier(KtTokens.CONST_KEYWORD)
}
override fun isAbstractEnabled(memberInfo: KotlinMemberInfo): Boolean {
val member = memberInfo.member
return !(member.hasModifier(KtTokens.INLINE_KEYWORD) ||
member.hasModifier(KtTokens.EXTERNAL_KEYWORD) ||
member.hasModifier(KtTokens.LATEINIT_KEYWORD))
}
override fun isFixedAbstract(memberInfo: KotlinMemberInfo?) = true
}
val selectedTargetParent: PsiElement
get() = if (targetParent is PsiDirectory) targetDirectory else targetParent
val targetFileName: String
get() = fileNameField.text
private fun resetFileNameField() {
if (!initComplete) return
fileNameField.text = "$extractedSuperName.${KotlinFileType.EXTENSION}"
}
protected abstract fun createMemberInfoModel(): MemberInfoModelBase
override fun getDocCommentPanelName() = KotlinBundle.message("title.kdoc.for.abstracts")
override fun checkConflicts() = conflictChecker(this)
override fun createActionComponent() = Box.createHorizontalBox()!!
override fun createExtractedSuperNameField(): JTextField {
return super.createExtractedSuperNameField().apply {
onTextChange { resetFileNameField() }
}
}
override fun createDestinationRootPanel(): JPanel? {
if (targetParent !is PsiDirectory) return null
val targetDirectoryPanel = super.createDestinationRootPanel()
val targetFileNamePanel = JPanel(BorderLayout()).apply {
border = BorderFactory.createEmptyBorder(10, 0, 0, 0)
val label = JBLabel(KotlinBundle.message("label.text.target.file.name"))
add(label, BorderLayout.NORTH)
label.labelFor = fileNameField
add(fileNameField, BorderLayout.CENTER)
}
val formBuilder = FormBuilder.createFormBuilder()
if (targetDirectoryPanel != null) {
formBuilder.addComponent(targetDirectoryPanel)
}
return formBuilder.addComponent(targetFileNamePanel).panel
}
override fun createNorthPanel(): JComponent? {
return super.createNorthPanel().apply {
if (targetParent !is PsiDirectory) {
myPackageNameLabel.parent.remove(myPackageNameLabel)
myPackageNameField.parent.remove(myPackageNameField)
}
}
}
override fun createCenterPanel(): JComponent? {
memberInfoModel = createMemberInfoModel().apply {
memberInfoChanged(MemberInfoChange(memberInfos))
}
return JPanel(BorderLayout()).apply {
val memberSelectionPanel = KotlinMemberSelectionPanel(
RefactoringBundle.message(if (isExtractInterface) "members.to.form.interface" else "members.to.form.superclass"),
memberInfoModel.memberInfos,
RefactoringBundle.message("make.abstract")
)
memberSelectionPanel.table.memberInfoModel = memberInfoModel
memberSelectionPanel.table.addMemberInfoChangeListener(memberInfoModel)
add(memberSelectionPanel, BorderLayout.CENTER)
add(myDocCommentPanel, BorderLayout.EAST)
}
}
override fun init() {
super.init()
initComplete = true
resetFileNameField()
}
override fun preparePackage() {
if (targetParent is PsiDirectory) super.preparePackage()
}
override fun isExtractSuperclass() = true
override fun validateName(name: String): String? {
return when {
!name.quoteIfNeeded().isIdentifier() -> RefactoringMessageUtil.getIncorrectIdentifierMessage(name)
name.unquoteKotlinIdentifier() == mySourceClass.name -> KotlinBundle.message("error.text.different.name.expected")
else -> null
}
}
override fun createProcessor() = null
override fun executeRefactoring() {
val extractInfo = ExtractSuperInfo(
mySourceClass.unwrapped as KtClassOrObject,
selectedMembers,
if (targetParent is PsiDirectory) targetDirectory else targetParent,
targetFileName,
extractedSuperName.quoteIfNeeded(),
isExtractInterface,
DocCommentPolicy<PsiComment>(docCommentPolicy)
)
refactoring(extractInfo)
}
} | apache-2.0 | 0b65689e384d1ce9f91dad1e85e875c1 | 39.282609 | 158 | 0.723654 | 5.366401 | false | false | false | false |
ingokegel/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/list/search/ReviewListSearchPanelFactory.kt | 1 | 6181 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.collaboration.ui.codereview.list.search
import com.intellij.collaboration.messages.CollaborationToolsBundle
import com.intellij.collaboration.ui.codereview.list.search.ChooserPopupUtil.showAndAwaitListSubmission
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.ui.*
import com.intellij.ui.components.GradientViewport
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.JBThinOverlappingScrollBar
import com.intellij.ui.components.panels.HorizontalLayout
import com.intellij.util.ui.JBUI
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.jetbrains.annotations.Nls
import java.awt.Adjustable
import java.awt.BorderLayout
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.ScrollPaneConstants
abstract class ReviewListSearchPanelFactory<S : ReviewListSearchValue, Q : ReviewListQuickFilter<S>, VM : ReviewListSearchPanelViewModel<S, Q>>(
protected val vm: VM
) {
fun create(viewScope: CoroutineScope): JComponent {
val searchField = ReviewListSearchTextFieldFactory(vm.queryState).create(viewScope, chooseFromHistory = { point ->
val value = JBPopupFactory.getInstance()
.createPopupChooserBuilder(vm.getSearchHistory().reversed())
.setRenderer(SimpleListCellRenderer.create { label, value, _ ->
label.text = getShortText(value)
})
.createPopup()
.showAndAwaitListSubmission<S>(point)
if (value != null) {
vm.searchState.update { value }
}
})
val filters = createFilters(viewScope)
val filtersPanel = JPanel(HorizontalLayout(4)).apply {
isOpaque = false
filters.forEach { add(it, HorizontalLayout.LEFT) }
}.let {
ScrollPaneFactory.createScrollPane(it, true).apply {
viewport = GradientViewport(it, JBUI.insets(0, 10), false)
verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS
horizontalScrollBar = JBThinOverlappingScrollBar(Adjustable.HORIZONTAL)
ClientProperty.put(this, JBScrollPane.FORCE_HORIZONTAL_SCROLL, true)
}
}
val quickFilterButton = QuickFilterButtonFactory().create(viewScope, vm.quickFilters)
val filterPanel = JPanel(BorderLayout()).apply {
border = JBUI.Borders.emptyTop(10)
isOpaque = false
add(quickFilterButton, BorderLayout.WEST)
add(filtersPanel, BorderLayout.CENTER)
}
val searchPanel = JPanel(BorderLayout()).apply {
border = JBUI.Borders.compound(IdeBorderFactory.createBorder(SideBorder.BOTTOM), JBUI.Borders.empty(8, 10, 0, 10))
add(searchField, BorderLayout.CENTER)
add(filterPanel, BorderLayout.SOUTH)
}
return searchPanel
}
protected abstract fun getShortText(searchValue: S): @Nls String
protected abstract fun createFilters(viewScope: CoroutineScope): List<JComponent>
protected abstract fun Q.getQuickFilterTitle(): @Nls String
private inner class QuickFilterButtonFactory {
fun create(viewScope: CoroutineScope, quickFilters: List<Q>): JComponent {
val toolbar = ActionManager.getInstance().createActionToolbar(
"Review.FilterToolbar",
DefaultActionGroup(FilterPopupMenuAction(quickFilters)),
true
).apply {
layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY
component.isOpaque = false
component.border = null
targetComponent = null
}
viewScope.launch {
vm.searchState.collect {
toolbar.updateActionsImmediately()
}
}
return toolbar.component
}
private fun showQuickFiltersPopup(parentComponent: JComponent, quickFilters: List<Q>) {
val quickFiltersActions =
quickFilters.map { QuickFilterAction(it.getQuickFilterTitle(), it.filter) } +
Separator() +
ClearFiltersAction()
JBPopupFactory.getInstance()
.createActionGroupPopup(CollaborationToolsBundle.message("review.list.filter.quick.title"), DefaultActionGroup(quickFiltersActions),
DataManager.getInstance().getDataContext(parentComponent),
JBPopupFactory.ActionSelectionAid.SPEEDSEARCH,
false)
.showUnderneathOf(parentComponent)
}
private inner class FilterPopupMenuAction(private val quickFilters: List<Q>) : AnActionButton() {
override fun updateButton(e: AnActionEvent) {
e.presentation.icon = FILTER_ICON.getLiveIndicatorIcon(vm.searchState.value.filterCount != 0)
}
override fun actionPerformed(e: AnActionEvent) {
showQuickFiltersPopup(e.inputEvent.component as JComponent, quickFilters)
}
}
private inner class QuickFilterAction(name: @Nls String, private val search: S)
: DumbAwareAction(name), Toggleable {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) = Toggleable.setSelected(e.presentation, vm.searchState.value == search)
override fun actionPerformed(e: AnActionEvent) = vm.searchState.update { search }
}
private inner class ClearFiltersAction
: DumbAwareAction(CollaborationToolsBundle.message("review.list.filter.quick.clear", vm.searchState.value.filterCount)) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = vm.searchState.value.filterCount > 0
}
override fun actionPerformed(e: AnActionEvent) = vm.searchState.update { vm.emptySearch }
}
}
companion object {
private val FILTER_ICON: BadgeIconSupplier = BadgeIconSupplier(AllIcons.General.Filter)
}
} | apache-2.0 | 1531dff5ccc64a169d1ec70206ffb002 | 38.628205 | 144 | 0.732568 | 5.021121 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/performance-tests/performance-test-utils/test/org/jetbrains/kotlin/idea/performance/tests/utils/project/StatefulTestGradleProjectRefreshCallback.kt | 6 | 2799 | // 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.performance.tests.utils.project
import com.intellij.openapi.components.service
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import org.jetbrains.kotlin.idea.test.GradleProcessOutputInterceptor
import java.io.Closeable
import kotlin.test.assertFalse
import kotlin.test.fail
class StatefulTestGradleProjectRefreshCallback(
private val projectPath: String,
private val project: Project
) : ExternalProjectRefreshCallback, Closeable {
private class Error(val message: String, val details: String? = null)
private var alreadyUsed = false
private var error: Error? = null
init {
GradleProcessOutputInterceptor.getInstance()?.reset()
}
override fun onSuccess(externalProject: DataNode<ProjectData>?) {
checkAlreadyUsed()
if (externalProject == null) {
error = Error("Got null external project after Gradle import")
return
}
service<ProjectDataManager>().importData(externalProject, project, true)
}
override fun onFailure(errorMessage: String, errorDetails: String?) {
checkAlreadyUsed()
error = Error(errorMessage, errorDetails)
}
override fun close() = assertError()
fun assertError() {
val error = error ?: return
val failure = buildString {
appendLine("Gradle import failed for ${project.name} at $projectPath")
project.guessProjectDir()
append("=".repeat(40)).appendLine(" Error message:")
appendLine(error.message.trimEnd())
append("=".repeat(40)).appendLine(" Error details:")
appendLine(error.details?.trimEnd().orEmpty())
append("=".repeat(40)).appendLine(" Gradle process output:")
appendLine(GradleProcessOutputInterceptor.getInstance()?.getOutput()?.trimEnd() ?: "<interceptor not installed>")
appendLine("=".repeat(40))
}
fail(failure)
}
private fun checkAlreadyUsed() {
assertFalse(
alreadyUsed,
"${StatefulTestGradleProjectRefreshCallback::class.java} can be used only once." +
" Please create a new instance of ${StatefulTestGradleProjectRefreshCallback::class.java} every time you" +
" do import from Gradle."
)
alreadyUsed = true
}
} | apache-2.0 | 2503633464656e7b4226fb7b3c20040e | 33.567901 | 125 | 0.700607 | 5.117002 | false | true | false | false |
mylog00/jPetrovich | src/main/kotlin/kt/petrovich/rules/Rule.kt | 1 | 1756 | package kt.petrovich.rules
import com.fasterxml.jackson.annotation.JsonCreator
import kt.petrovich.Gender
import kt.petrovich.exceptoins.RulesCreationException
/**
* @author Dmitrii Kniazev
* @since 08.06.2014
*/
class Rule constructor(
val gender: Gender,
val test: List<String>,
val mods: List<String>,
val tags: List<String>) {
@Throws(RulesCreationException::class)
@JsonCreator constructor(props: Map<String, Any>) : this(
gender = getGender(props["gender"]),
test = getStringList(props["test"]),
mods = getStringList(props["mods"]),
tags = getStringList(props.getOrDefault("tags", emptyList<String>())))
private companion object {
@Throws(RulesCreationException::class)
private fun getGender(genderStr: Any?): Gender =
if (genderStr is String) {
try {
Gender.valueOf(genderStr.toUpperCase())
} catch (iae: IllegalArgumentException) {
val message = "Can't find gender with the specified name:\'$genderStr\'"
throw RulesCreationException(message, iae)
}
} else {
throw RulesCreationException("Gender is not string:$genderStr")
}
@Throws(RulesCreationException::class)
private fun getStringList(obj: Any?): List<String> {
if (obj is List<*> && obj.all { it is String }) {
@Suppress("UNCHECKED_CAST")
return obj as List<String>
} else {
throw RulesCreationException("This object is not a list of string:\'$obj\'")
}
}
}
}
| mit | 89705426a8dd2a0f5c7158d9043a8b45 | 32.769231 | 96 | 0.567198 | 4.797814 | false | true | false | false |
micolous/metrodroid | src/main/java/au/id/micolous/metrodroid/provider/CardProvider.kt | 1 | 5220 | /*
* CardProvider.kt
*
* Copyright (C) 2011 Eric Butler
*
* Authors:
* Eric Butler <[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 au.id.micolous.metrodroid.provider
import android.content.ContentProvider
import android.content.ContentUris
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri
import android.text.TextUtils
import org.jetbrains.annotations.NonNls
import au.id.micolous.farebot.BuildConfig
class CardProvider : ContentProvider() {
private var mDbHelper: CardDBHelper? = null
override fun onCreate(): Boolean {
mDbHelper = CardDBHelper(context!!)
return true
}
override fun query(@NonNls uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? {
@NonNls val builder = SQLiteQueryBuilder()
when (sUriMatcher.match(uri)) {
CardDBHelper.CARD_COLLECTION_URI_INDICATOR -> builder.tables = CardsTableColumns.TABLE_NAME
CardDBHelper.SINGLE_CARD_URI_INDICATOR -> {
builder.tables = CardsTableColumns.TABLE_NAME
builder.appendWhere(CardsTableColumns._ID + " = " + uri.pathSegments[1])
}
else -> throw IllegalArgumentException("Unknown URI $uri")
}//builder.setProjectionMap();
val db = mDbHelper!!.readableDatabase
val cursor = builder.query(db, null, selection, selectionArgs, null, null, sortOrder)
cursor.setNotificationUri(context!!.contentResolver, uri)
return cursor
}
override fun getType(@NonNls uri: Uri): String? = when (sUriMatcher.match(uri)) {
CardDBHelper.CARD_COLLECTION_URI_INDICATOR -> CardDBHelper.CARD_DIR_TYPE
CardDBHelper.SINGLE_CARD_URI_INDICATOR -> CardDBHelper.CARD_ITEM_TYPE
else -> throw IllegalArgumentException("Unknown URI: $uri")
}
override fun insert(@NonNls uri: Uri, values: ContentValues?): Uri? {
if (sUriMatcher.match(uri) != CardDBHelper.CARD_COLLECTION_URI_INDICATOR) {
throw IllegalArgumentException("Incorrect URI: $uri")
}
val db = mDbHelper!!.writableDatabase
val rowId = db.insertOrThrow(CardsTableColumns.TABLE_NAME, null, values)
val cardUri = ContentUris.withAppendedId(CONTENT_URI_CARD, rowId)
context!!.contentResolver.notifyChange(cardUri, null)
return cardUri
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
@NonNls val db = mDbHelper!!.writableDatabase
var count = 0
when (sUriMatcher.match(uri)) {
CardDBHelper.CARD_COLLECTION_URI_INDICATOR -> count = db.delete(CardsTableColumns.TABLE_NAME, selection, selectionArgs)
CardDBHelper.SINGLE_CARD_URI_INDICATOR -> {
val rowId = uri.pathSegments[1]
count = db.delete(CardsTableColumns.TABLE_NAME, CardsTableColumns._ID + "=" + rowId
+ if (!TextUtils.isEmpty(selection)) " AND ($selection)" else "", selectionArgs)
}
}
context!!.contentResolver.notifyChange(uri, null)
return count
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {
@NonNls val db = mDbHelper!!.writableDatabase
val count: Int = when (sUriMatcher.match(uri)) {
CardDBHelper.CARD_COLLECTION_URI_INDICATOR -> db.update(CardsTableColumns.TABLE_NAME, values, selection, selectionArgs)
CardDBHelper.SINGLE_CARD_URI_INDICATOR -> {
val rowId = uri.pathSegments[1]
db.update(CardsTableColumns.TABLE_NAME, values, CardsTableColumns._ID + "=" + rowId
+ if (!TextUtils.isEmpty(selection)) " AND ($selection)" else "", selectionArgs)
}
else -> throw IllegalArgumentException("Unknown URI $uri")
}
context!!.contentResolver.notifyChange(uri, null)
return count
}
companion object {
@NonNls
val AUTHORITY = BuildConfig.APPLICATION_ID + ".cardprovider"
val CONTENT_URI_CARD: Uri = Uri.parse("content://$AUTHORITY/cards")
private val sUriMatcher = UriMatcher(UriMatcher.NO_MATCH)
init {
sUriMatcher.addURI(AUTHORITY, "cards", CardDBHelper.CARD_COLLECTION_URI_INDICATOR)
sUriMatcher.addURI(AUTHORITY, "cards/#", CardDBHelper.SINGLE_CARD_URI_INDICATOR)
}
}
}
| gpl-3.0 | 76663c878bcb2771251833d17e8a8396 | 39.78125 | 150 | 0.672797 | 4.69847 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/kdoc/KDocTemplate.kt | 4 | 2063 | // 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.kdoc
import com.intellij.lang.documentation.DocumentationMarkup.*
open class KDocTemplate : Template<StringBuilder> {
val definition = Placeholder<StringBuilder>()
val description = Placeholder<StringBuilder>()
val deprecation = Placeholder<StringBuilder>()
val containerInfo = Placeholder<StringBuilder>()
override fun StringBuilder.apply() {
append(DEFINITION_START)
insert(definition)
append(DEFINITION_END)
if (!deprecation.isEmpty()) {
append(SECTIONS_START)
insert(deprecation)
append(SECTIONS_END)
}
insert(description)
if (!containerInfo.isEmpty()) {
append("<div class='bottom'>")
insert(containerInfo)
append("</div>")
}
}
sealed class DescriptionBodyTemplate : Template<StringBuilder> {
class Kotlin : DescriptionBodyTemplate() {
val content = Placeholder<StringBuilder>()
val sections = Placeholder<StringBuilder>()
override fun StringBuilder.apply() {
val computedContent = buildString { insert(content) }
if (computedContent.isNotBlank()) {
append(CONTENT_START)
append(computedContent)
append(CONTENT_END)
}
append(SECTIONS_START)
insert(sections)
append(SECTIONS_END)
}
}
class FromJava : DescriptionBodyTemplate() {
override fun StringBuilder.apply() {
append(body)
}
lateinit var body: String
}
}
class NoDocTemplate : KDocTemplate() {
val error = Placeholder<StringBuilder>()
override fun StringBuilder.apply() {
insert(error)
}
}
}
| apache-2.0 | 9c18b3cfafc210e985d4ffc25e274394 | 27.652778 | 158 | 0.585555 | 5.386423 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/util/SafeAnalysisUtils.kt | 4 | 2703 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("SafeAnalysisUtils")
package org.jetbrains.kotlin.idea.util
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.NonPhysicalFileSystem
import com.intellij.psi.PsiElement
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.kotlin.config.ALL_KOTLIN_SOURCE_ROOT_TYPES
import org.jetbrains.kotlin.idea.base.util.isUnderKotlinSourceRootTypes
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.lazy.NoDescriptorForDeclarationException
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
/**
* Best effort to analyze element:
* - Best effort for file that is out of source root scope: NoDescriptorForDeclarationException could be swallowed
* - Do not swallow NoDescriptorForDeclarationException during analysis for in source scope files
*/
inline fun <T> PsiElement.actionUnderSafeAnalyzeBlock(
crossinline action: () -> T,
crossinline fallback: () -> T
): T = try {
action()
} catch (e: Exception) {
e.returnIfNoDescriptorForDeclarationException(condition = {
val file = containingFile
it && (!file.isPhysical || !file.isUnderKotlinSourceRootTypes())
}) { fallback() }
}
val Exception.isItNoDescriptorForDeclarationException: Boolean
get() = this is NoDescriptorForDeclarationException || cause?.safeAs<Exception>()?.isItNoDescriptorForDeclarationException == true
inline fun <T> Exception.returnIfNoDescriptorForDeclarationException(
crossinline condition: (Boolean) -> Boolean = { v -> v },
crossinline computable: () -> T
): T =
if (condition(this.isItNoDescriptorForDeclarationException)) {
computable()
} else {
throw this
}
val KOTLIN_AWARE_SOURCE_ROOT_TYPES: Set<JpsModuleSourceRootType<JavaSourceRootProperties>> =
JavaModuleSourceRootTypes.SOURCES + ALL_KOTLIN_SOURCE_ROOT_TYPES
@Deprecated("Use 'org.jetbrains.kotlin.idea.base.util.isUnderKotlinSourceRootTypes()' instead")
fun PsiElement?.isUnderKotlinSourceRootTypes(): Boolean {
val ktFile = this?.containingFile.safeAs<KtFile>() ?: return false
val file = ktFile.virtualFile?.takeIf { it !is VirtualFileWindow && it.fileSystem !is NonPhysicalFileSystem } ?: return false
val projectFileIndex = ProjectRootManager.getInstance(ktFile.project).fileIndex
return projectFileIndex.isUnderSourceRootOfType(file, KOTLIN_AWARE_SOURCE_ROOT_TYPES)
}
| apache-2.0 | 1c18e3aea1b65d207b9a62f4e64c3f46 | 46.421053 | 134 | 0.782834 | 4.792553 | false | false | false | false |
charroch/Kevice | src/main/kotlin/adb/LocalDeviceBridgeVerticle.kt | 1 | 1540 | package adb
import org.vertx.java.platform.Verticle
import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener
import com.android.ddmlib.IDevice
import com.android.ddmlib.AndroidDebugBridge
public class LocalDeviceBridgeVerticle : Verticle(), IDeviceChangeListener {
override fun deviceConnected(device: IDevice?) {
if (device != null && vertx != null) {
container?.logger()?.info(device.log())
container?.logger()?.debug(device.log())
vertx?.eventBus()?.publish(address(), device.asJsonObject())
}
}
override fun deviceDisconnected(device: IDevice?) {
if (device != null && vertx != null) {
container?.logger()?.info(device.log())
vertx?.eventBus()?.publish(address(), device.asJsonObject())
}
}
override fun deviceChanged(device: IDevice?, status: Int) {
if (device != null && vertx != null) {
container?.logger()?.info(device.log())
vertx?.eventBus()?.publish(address(), device.asJsonObject())
}
}
override fun start() {
container?.logger()?.info("Starting device monitoring VERTICLE")
AndroidDebugBridge.initIfNeeded(true)
AndroidDebugBridge.createBridge()
AndroidDebugBridge.addDeviceChangeListener(this)
AndroidDebugBridge.addDeviceChangeListener(DeviceChangeListener())
}
fun address(): String {
val host = container?.config()?.getString("clientname") ?: "london"
return "devices." + host
}
} | apache-2.0 | 0824090dd33f4afb9983423dc15b2246 | 35.690476 | 76 | 0.645455 | 4.767802 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/database/SessionDatabase.kt | 1 | 7419 | package org.thoughtcrime.securesms.database
import android.content.Context
import org.signal.core.util.CursorUtil
import org.signal.core.util.SqlUtil
import org.signal.core.util.logging.Log
import org.signal.core.util.requireInt
import org.signal.core.util.requireNonNullBlob
import org.signal.core.util.requireNonNullString
import org.signal.libsignal.protocol.SignalProtocolAddress
import org.signal.libsignal.protocol.state.SessionRecord
import org.whispersystems.signalservice.api.push.ServiceId
import org.whispersystems.signalservice.api.push.SignalServiceAddress
import java.io.IOException
import java.util.LinkedList
class SessionDatabase(context: Context, databaseHelper: SignalDatabase) : Database(context, databaseHelper) {
companion object {
private val TAG = Log.tag(SessionDatabase::class.java)
const val TABLE_NAME = "sessions"
const val ID = "_id"
const val ACCOUNT_ID = "account_id"
const val ADDRESS = "address"
const val DEVICE = "device"
const val RECORD = "record"
const val CREATE_TABLE = """
CREATE TABLE $TABLE_NAME (
$ID INTEGER PRIMARY KEY AUTOINCREMENT,
$ACCOUNT_ID TEXT NOT NULL,
$ADDRESS TEXT NOT NULL,
$DEVICE INTEGER NOT NULL,
$RECORD BLOB NOT NULL,
UNIQUE($ACCOUNT_ID, $ADDRESS, $DEVICE)
)
"""
}
fun store(serviceId: ServiceId, address: SignalProtocolAddress, record: SessionRecord) {
require(address.name[0] != '+') { "Cannot insert an e164 into this table!" }
writableDatabase.compileStatement("INSERT INTO $TABLE_NAME ($ACCOUNT_ID, $ADDRESS, $DEVICE, $RECORD) VALUES (?, ?, ?, ?) ON CONFLICT ($ACCOUNT_ID, $ADDRESS, $DEVICE) DO UPDATE SET $RECORD = excluded.$RECORD").use { statement ->
statement.apply {
bindString(1, serviceId.toString())
bindString(2, address.name)
bindLong(3, address.deviceId.toLong())
bindBlob(4, record.serialize())
execute()
}
}
}
fun load(serviceId: ServiceId, address: SignalProtocolAddress): SessionRecord? {
val projection = arrayOf(RECORD)
val selection = "$ACCOUNT_ID = ? AND $ADDRESS = ? AND $DEVICE = ?"
val args = SqlUtil.buildArgs(serviceId, address.name, address.deviceId)
readableDatabase.query(TABLE_NAME, projection, selection, args, null, null, null).use { cursor ->
if (cursor.moveToFirst()) {
try {
return SessionRecord(cursor.requireNonNullBlob(RECORD))
} catch (e: IOException) {
Log.w(TAG, e)
}
}
}
return null
}
fun load(serviceId: ServiceId, addresses: List<SignalProtocolAddress>): List<SessionRecord?> {
val projection = arrayOf(ADDRESS, DEVICE, RECORD)
val query = "$ACCOUNT_ID = ? AND $ADDRESS = ? AND $DEVICE = ?"
val args: MutableList<Array<String>> = ArrayList(addresses.size)
val sessions: HashMap<SignalProtocolAddress, SessionRecord?> = LinkedHashMap(addresses.size)
for (address in addresses) {
args.add(SqlUtil.buildArgs(serviceId, address.name, address.deviceId))
sessions[address] = null
}
for (combinedQuery in SqlUtil.buildCustomCollectionQuery(query, args)) {
readableDatabase.query(TABLE_NAME, projection, combinedQuery.where, combinedQuery.whereArgs, null, null, null).use { cursor ->
while (cursor.moveToNext()) {
val address = cursor.requireNonNullString(ADDRESS)
val device = cursor.requireInt(DEVICE)
try {
val record = SessionRecord(cursor.requireNonNullBlob(RECORD))
sessions[SignalProtocolAddress(address, device)] = record
} catch (e: IOException) {
Log.w(TAG, e)
}
}
}
}
return sessions.values.toList()
}
fun getAllFor(serviceId: ServiceId, addressName: String): List<SessionRow> {
val results: MutableList<SessionRow> = mutableListOf()
readableDatabase.query(TABLE_NAME, null, "$ACCOUNT_ID = ? AND $ADDRESS = ?", SqlUtil.buildArgs(serviceId, addressName), null, null, null).use { cursor ->
while (cursor.moveToNext()) {
try {
results.add(
SessionRow(
CursorUtil.requireString(cursor, ADDRESS),
CursorUtil.requireInt(cursor, DEVICE),
SessionRecord(CursorUtil.requireBlob(cursor, RECORD))
)
)
} catch (e: IOException) {
Log.w(TAG, e)
}
}
}
return results
}
fun getAllFor(serviceId: ServiceId, addressNames: List<String?>): List<SessionRow> {
val query: SqlUtil.Query = SqlUtil.buildSingleCollectionQuery(ADDRESS, addressNames)
val results: MutableList<SessionRow> = LinkedList()
val queryString = "$ACCOUNT_ID = ? AND (${query.where})"
val queryArgs: Array<String> = arrayOf(serviceId.toString()) + query.whereArgs
readableDatabase.query(TABLE_NAME, null, queryString, queryArgs, null, null, null).use { cursor ->
while (cursor.moveToNext()) {
try {
results.add(
SessionRow(
address = CursorUtil.requireString(cursor, ADDRESS),
deviceId = CursorUtil.requireInt(cursor, DEVICE),
record = SessionRecord(cursor.requireNonNullBlob(RECORD))
)
)
} catch (e: IOException) {
Log.w(TAG, e)
}
}
}
return results
}
fun getAll(serviceId: ServiceId): List<SessionRow> {
val results: MutableList<SessionRow> = mutableListOf()
readableDatabase.query(TABLE_NAME, null, "$ACCOUNT_ID = ?", SqlUtil.buildArgs(serviceId), null, null, null).use { cursor ->
while (cursor.moveToNext()) {
try {
results.add(
SessionRow(
address = cursor.requireNonNullString(ADDRESS),
deviceId = cursor.requireInt(DEVICE),
record = SessionRecord(cursor.requireNonNullBlob(RECORD))
)
)
} catch (e: IOException) {
Log.w(TAG, e)
}
}
}
return results
}
fun getSubDevices(serviceId: ServiceId, addressName: String): List<Int> {
val projection = arrayOf(DEVICE)
val selection = "$ACCOUNT_ID = ? AND $ADDRESS = ? AND $DEVICE != ?"
val args = SqlUtil.buildArgs(serviceId, addressName, SignalServiceAddress.DEFAULT_DEVICE_ID)
val results: MutableList<Int> = mutableListOf()
readableDatabase.query(TABLE_NAME, projection, selection, args, null, null, null).use { cursor ->
while (cursor.moveToNext()) {
results.add(cursor.requireInt(DEVICE))
}
}
return results
}
fun delete(serviceId: ServiceId, address: SignalProtocolAddress) {
writableDatabase.delete(TABLE_NAME, "$ACCOUNT_ID = ? AND $ADDRESS = ? AND $DEVICE = ?", SqlUtil.buildArgs(serviceId, address.name, address.deviceId))
}
fun deleteAllFor(serviceId: ServiceId, addressName: String) {
writableDatabase.delete(TABLE_NAME, "$ACCOUNT_ID = ? AND $ADDRESS = ?", SqlUtil.buildArgs(serviceId, addressName))
}
fun hasSessionFor(serviceId: ServiceId, addressName: String): Boolean {
val query = "$ACCOUNT_ID = ? AND $ADDRESS = ?"
val args = SqlUtil.buildArgs(serviceId, addressName)
readableDatabase.query(TABLE_NAME, arrayOf("1"), query, args, null, null, null, "1").use { cursor ->
return cursor.moveToFirst()
}
}
class SessionRow(val address: String, val deviceId: Int, val record: SessionRecord)
}
| gpl-3.0 | e05141583aa85f16aa4d57132b7bba57 | 36.281407 | 231 | 0.657231 | 4.379575 | false | false | false | false |
ftomassetti/kolasu | core/src/main/kotlin/com/strumenta/kolasu/model/Naming.kt | 1 | 2634 | package com.strumenta.kolasu.model
/**
* An entity that can have a name
*/
interface PossiblyNamed {
/**
* The optional name of the entity.
*/
val name: String?
}
/**
* An entity which has a name.
*/
interface Named : PossiblyNamed {
/**
* The mandatory name of the entity.
*/
override val name: String
}
/**
* A reference associated by using a name.
* It can be used only to refer to Nodes and not to other values.
*
* This is not statically enforced as we may want to use some interface, which cannot extend Node.
* However, this is enforced dynamically.
*/
class ReferenceByName<N>(val name: String, initialReferred: N? = null) where N : PossiblyNamed {
var referred: N? = null
set(value) {
require(value is Node || value == null) {
"We cannot enforce it statically but only Node should be referred to. Instead $value was assigned " +
"(class: ${value?.javaClass})"
}
field = value
}
init {
this.referred = initialReferred
}
override fun toString(): String {
return if (resolved) {
"Ref($name)[Solved]"
} else {
"Ref($name)[Unsolved]"
}
}
val resolved: Boolean
get() = referred != null
override fun hashCode(): Int {
return name.hashCode() * (7 + if (resolved) 2 else 1)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ReferenceByName<*>) return false
if (name != other.name) return false
if (referred != other.referred) return false
return true
}
}
/**
* Try to resolve the reference by finding a named element with a matching name.
* The name match is performed in a case sensitive or insensitive way depending on the value of @param[caseInsensitive].
*/
fun <N> ReferenceByName<N>.tryToResolve(
candidates: Iterable<N>,
caseInsensitive: Boolean = false
): Boolean where N : PossiblyNamed {
val res: N? = candidates.find { if (it.name == null) false else it.name.equals(this.name, caseInsensitive) }
this.referred = res
return res != null
}
/**
* Try to resolve the reference by assigining @param[possibleValue]. The assignment is not performed if
* @param[possibleValue] is null.
*
* @return true if the assignment has been performed
*/
fun <N> ReferenceByName<N>.tryToResolve(possibleValue: N?): Boolean where N : PossiblyNamed {
return if (possibleValue == null) {
false
} else {
this.referred = possibleValue
true
}
}
| apache-2.0 | 86144f1e8ca0903654e815508c598e51 | 26.154639 | 120 | 0.620729 | 4.221154 | false | false | false | false |
ManojMadanmohan/dlt | app/src/main/java/com/manoj/dlt/ui/adapters/FilterableListAdapter.kt | 1 | 1989 | package com.manoj.dlt.ui.adapters
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Filter
import android.widget.Filterable
import java.util.ArrayList
abstract class FilterableListAdapter<T:Any>(protected var _originalList: ArrayList<T>, defaultListEmpty: Boolean) : BaseAdapter(), Filterable {
protected var _resultList: MutableList<T>
protected var _searchString: String
init {
_resultList = ArrayList()
if (!defaultListEmpty) {
_resultList.addAll(_originalList)
}
_searchString = ""
}
override fun getCount(): Int {
Log.d("deep", "size = " + _resultList.size)
return _resultList.size
}
override fun getItem(i: Int): Any {
Log.d("deep", "call for item " + i)
return _resultList[i]
}
fun updateBaseData(baseData: ArrayList<T>) {
_originalList = baseData
updateResults(_searchString)
}
fun updateResults(searchString: CharSequence) {
filter.filter(searchString)
}
override fun getFilter(): Filter {
return object : Filter() {
override fun performFiltering(charSequence: CharSequence): Filter.FilterResults {
val results = Filter.FilterResults()
val resultList = getMatchingResults(charSequence)
results.values = resultList
results.count = resultList.size
Log.d("deep", "filtering, cnt = " + resultList.size)
return results
}
override fun publishResults(charSequence: CharSequence, filterResults: Filter.FilterResults) {
_searchString = charSequence.toString()
_resultList = filterResults.values as ArrayList<T>
notifyDataSetChanged()
}
}
}
protected abstract fun getMatchingResults(constraint: CharSequence): ArrayList<T>
}
| mit | 91864a6f4bd8852d30afaa19cb0d8bee | 30.571429 | 143 | 0.634992 | 4.9601 | false | false | false | false |
himikof/intellij-rust | src/main/kotlin/org/rust/ide/annotator/fixes/AddStructFieldsFix.kt | 1 | 4373 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator.fixes
import com.intellij.codeInsight.CodeInsightUtilBase
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.ide.formatter.RsTrailingCommaFormatProcessor
import org.rust.ide.formatter.impl.CommaList
import org.rust.lang.core.psi.RsElementTypes.COMMA
import org.rust.lang.core.psi.RsFieldDecl
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.RsStructLiteralBody
import org.rust.lang.core.psi.RsStructLiteralField
import org.rust.lang.core.psi.ext.elementType
import org.rust.lang.core.psi.ext.getNextNonCommentSibling
/**
* Adds the given fields to the stricture defined by `expr`
*/
class AddStructFieldsFix(
val declaredFields: List<RsFieldDecl>,
val fieldsToAdd: List<RsFieldDecl>,
structBody: RsStructLiteralBody
) : LocalQuickFixAndIntentionActionOnPsiElement(structBody) {
override fun getText(): String = "Add missing fields"
override fun getFamilyName(): String = text
override fun invoke(
project: Project,
file: PsiFile,
editor: Editor?,
startElement: PsiElement,
endElement: PsiElement
) {
val psiFactory = RsPsiFactory(project)
var expr = startElement as RsStructLiteralBody
val forceMultiline = expr.structLiteralFieldList.isEmpty() && fieldsToAdd.size > 2
var firstAdded: RsStructLiteralField? = null
for (fieldDecl in fieldsToAdd) {
val field = psiFactory.createStructLiteralField(fieldDecl.name!!)
val addBefore = findPlaceToAdd(field, expr.structLiteralFieldList, declaredFields)
expr.ensureTrailingComma()
val comma = expr.addBefore(psiFactory.createComma(), addBefore ?: expr.rbrace)
val added = expr.addBefore(field, comma) as RsStructLiteralField
if (firstAdded == null) {
firstAdded = added
}
}
if (forceMultiline) {
expr.addAfter(psiFactory.createNewline(), expr.lbrace)
}
expr = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(expr)
RsTrailingCommaFormatProcessor.fixSingleLineBracedBlock(expr, CommaList.forElement(expr.elementType)!!)
if (editor != null && firstAdded != null) {
editor.caretModel.moveToOffset(firstAdded.expr!!.textOffset)
}
}
private fun findPlaceToAdd(
fieldToAdd: RsStructLiteralField,
existingFields: List<RsStructLiteralField>,
declaredFields: List<RsFieldDecl>
): RsStructLiteralField? {
// If `fieldToAdd` is first in the original declaration, add it first
if (fieldToAdd.referenceName == declaredFields.firstOrNull()?.name) {
return existingFields.firstOrNull()
}
// If it was last, add last
if (fieldToAdd.referenceName == declaredFields.lastOrNull()?.name) {
return null
}
val pos = declaredFields.indexOfFirst { it.name == fieldToAdd.referenceName }
check(pos != -1)
val prev = declaredFields[pos - 1]
val next = declaredFields[pos + 1]
val prevIdx = existingFields.indexOfFirst { it.referenceName == prev.name }
val nextIdx = existingFields.indexOfFirst { it.referenceName == next.name }
// Fit between two existing fields in the same order
if (prevIdx != -1 && prevIdx + 1 == nextIdx) {
return existingFields[nextIdx]
}
// We have next field, but the order is different.
// It's impossible to guess the best position, so
// let's add to the end
if (nextIdx != -1) {
return null
}
if (prevIdx != -1) {
return existingFields.getOrNull(prevIdx + 1)
}
return null
}
private fun RsStructLiteralBody.ensureTrailingComma() {
val lastField = structLiteralFieldList.lastOrNull()
?: return
if (lastField.getNextNonCommentSibling()?.elementType == COMMA) return
addAfter(RsPsiFactory(project).createComma(), lastField)
}
}
| mit | 7a1842bd127092ba550e9ebd866a071f | 35.140496 | 111 | 0.67871 | 4.758433 | false | false | false | false |
ktorio/ktor | ktor-utils/jvm/test/io/ktor/tests/utils/StatelessHmacNonceManagerTest.kt | 1 | 1854 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.tests.utils
import io.ktor.util.*
import kotlinx.coroutines.*
import kotlin.test.*
class StatelessHmacNonceManagerTest {
private val nonceValues = listOf("11111111", "22222222", "33333333")
private val nonceSequence = nonceValues.iterator()
private val key = "test-key".toByteArray()
private val manager = StatelessHmacNonceManager(key) { nonceSequence.next() }
@Test
fun smokeTest(): Unit = runBlocking {
val nonce = manager.newNonce()
assertTrue(manager.verifyNonce(nonce))
}
@Test
fun testContains(): Unit = runBlocking {
assertTrue(nonceValues[0] in manager.newNonce())
assertTrue(nonceValues[1] in manager.newNonce())
assertTrue(nonceValues[2] in manager.newNonce())
}
@Test
fun testIllegalValues(): Unit = runBlocking {
assertFalse(manager.verifyNonce(""))
assertFalse(manager.verifyNonce("+"))
assertFalse(manager.verifyNonce("++"))
assertFalse(manager.verifyNonce("+++"))
assertFalse(manager.verifyNonce("1"))
assertFalse(manager.verifyNonce("1777777777777777777777777777"))
assertFalse(manager.verifyNonce("1777777777+777777777777777777"))
assertFalse(manager.verifyNonce("1777777777+77777777+7777777777"))
assertFalse(manager.verifyNonce("1777777777+77777777+7777777777"))
val managerWithTheSameKey = StatelessHmacNonceManager(key) { "some-other-nonce" }
assertTrue(manager.verifyNonce(managerWithTheSameKey.newNonce()))
val managerWithAnotherKey = StatelessHmacNonceManager("some-other-key".toByteArray()) { nonceValues[0] }
assertFalse(manager.verifyNonce(managerWithAnotherKey.newNonce()))
}
}
| apache-2.0 | 72aa707c2174155f81038bd534662bcf | 37.625 | 119 | 0.704962 | 4.555283 | false | true | false | false |
ktorio/ktor | ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/test/io/ktor/tests/sessions/CacheTest.kt | 1 | 1784 | /*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.tests.sessions
import io.ktor.server.netty.*
import io.ktor.server.sessions.*
import kotlinx.coroutines.*
import java.util.concurrent.atomic.*
import kotlin.test.*
class CacheTest {
@Test
fun testTimeout1(): Unit = runBlocking {
val counter = AtomicInteger()
val timeout = BaseTimeoutCache(
1000L,
true,
BaseCache<Int, String> { counter.incrementAndGet(); it.toString() }
)
assertEquals("1", timeout.getOrCompute(1))
assertEquals(1, counter.get())
assertEquals("1", timeout.getOrCompute(1))
assertEquals(1, counter.get())
}
@Test
fun testTimeout2(): Unit = runBlocking {
val counter = AtomicInteger()
val timeout = BaseTimeoutCache(
10L,
true,
BaseCache<Int, String> { counter.incrementAndGet(); it.toString() }
)
assertEquals("1", timeout.getOrCompute(1))
assertEquals(1, counter.get())
Thread.sleep(500)
assertNull(timeout.peek(1))
}
@Test
fun canReadDataFromCacheStorageWithinEventLoopGroupProxy() {
runBlocking {
val memoryStorage = SessionStorageMemory()
memoryStorage.write("id", "123")
val storage = CacheStorage(memoryStorage, 100)
val group = EventLoopGroupProxy.create(4)
group.submit(
Runnable {
runBlocking {
assertEquals("123", storage.read("id"))
}
}
).sync()
group.shutdownGracefully().sync()
}
}
}
| apache-2.0 | 79de5afa292aa4e1ccb0a8a2886bcc1f | 26.446154 | 119 | 0.575673 | 4.670157 | false | true | false | false |
eyneill777/SpacePirates | core/src/rustyice/game/actors/Player.kt | 1 | 2981 | package rustyice.game.actors
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.Sprite
import rustyengine.RustyEngine
import rustyice.game.Actor
import rustyice.game.character.CharacterPhysics
import rustyice.graphics.Camera
import rustyice.graphics.RenderLayer
import rustyice.input.Actions
import rustyice.input.PlayerInput
import rustyice.physics.Collision
class Player() : Actor() {
private val characterPhysics: CharacterPhysics
@Transient var playerInput: PlayerInput? = null
@Transient private var boxSprite: Sprite? = null
var speed: Float
@Transient private var count = 0
override fun update(delta: Float) {
super.update(delta)
updateControls()
var fx = 0f
var fy = 0f
val playerInput = playerInput
if(playerInput != null) {
if (playerInput.isPressed(Actions.MOVE_UP)) {
fy += this.speed
}
if (playerInput.isPressed(Actions.MOVE_DOWN)) {
fy -= this.speed
}
if (playerInput.isPressed(Actions.MOVE_LEFT)) {
fx -= this.speed
}
if (playerInput.isPressed(Actions.MOVE_RIGHT)) {
fx += this.speed
}
}
characterPhysics.walk(fx, fy, 1f)
if (count > 0) {
boxSprite?.color = Color.BLUE
} else {
boxSprite?.color = Color.GREEN
}
}
override fun beginCollision(collision: Collision) {
super.beginCollision(collision)
count++
}
override fun endCollision(collision: Collision) {
super.endCollision(collision)
count--
}
override fun render(batch: Batch, camera: Camera, layer: RenderLayer) {
val boxSprite = boxSprite
if(boxSprite != null){
boxSprite.x = x - width / 2
boxSprite.y = y - height / 2
boxSprite.rotation = rotation
boxSprite.draw(batch)
}
}
private fun updateControls(){
val game = game
if(game != null){
if(game.playerInputs.isNotEmpty()){
playerInput = game.playerInputs[0]
} else {
playerInput = null
}
if(game.cameras.isNotEmpty()){
game.cameras[0].target = this
game.cameras[0].isTracking = true
}
} else {
playerInput = null
}
}
override fun init() {
super.init()
val boxSprite = Sprite(RustyEngine.resorces.circle)
this.boxSprite = boxSprite
boxSprite.color = Color.CYAN
boxSprite.setSize(width, height)
boxSprite.setOrigin(width / 2, height / 2)
}
init {
characterPhysics = CharacterPhysics()
physicsComponent = characterPhysics
width = 0.98f
height = 0.98f
speed = 6f
}
}
| mit | 748ab3f58af0056d0c8795765c5371fd | 25.380531 | 75 | 0.578329 | 4.579109 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/controls/TrackerInput.kt | 2 | 5900 | package graphics.scenery.controls
import org.joml.Matrix4f
import org.joml.Vector3f
import graphics.scenery.Camera
import graphics.scenery.Mesh
import graphics.scenery.Node
import org.joml.Quaternionf
/**
* Enum class for the types of devices that can be tracked.
* Includes HMDs, controllers, base stations, generic devices, and invalid ones for the moment.
*/
enum class TrackedDeviceType {
Invalid,
HMD,
Controller,
BaseStation,
Generic
}
enum class TrackerRole {
Invalid,
LeftHand,
RightHand
}
/**
* Class for tracked devices and querying information about them.
*
* @property[type] The [TrackedDeviceType] of the device.
* @property[name] A name for the device.
* @property[pose] The current pose of the device.
* @property[timestamp] The latest timestamp with respect to the pose.
* @property[velocity] The (optional) velocity of the device.
* @property[angularVelocity] The (optional) angular velocity of the device.
*/
class TrackedDevice(val type: TrackedDeviceType, var name: String, var pose: Matrix4f, var timestamp: Long, var velocity: Vector3f? = null, var angularVelocity: Vector3f? = null) {
var metadata: Any? = null
var orientation = Quaternionf()
get(): Quaternionf {
// val pose = pose.floatArray
//
// field.w = Math.sqrt(1.0 * Math.max(0.0f, 1.0f + pose[0] + pose[5] + pose[10])).toFloat() / 2.0f
// field.x = Math.sqrt(1.0 * Math.max(0.0f, 1.0f + pose[0] - pose[5] - pose[10])).toFloat() / 2.0f
// field.y = Math.sqrt(1.0 * Math.max(0.0f, 1.0f - pose[0] + pose[5] - pose[10])).toFloat() / 2.0f
// field.z = Math.sqrt(1.0 * Math.max(0.0f, 1.0f - pose[0] - pose[5] + pose[10])).toFloat() / 2.0f
//
// field.x *= Math.signum(field.x * (pose[9] - pose[6]))
// field.y *= Math.signum(field.y * (pose[2] - pose[8]))
// field.z *= Math.signum(field.z * (pose[4] - pose[1]))
field = Quaternionf().setFromUnnormalized(pose)
return field
}
var position = Vector3f(0.0f, 0.0f, 0.0f)
get(): Vector3f {
field = Vector3f(pose.get(0, 3), pose.get(1, 3), pose.get(2, 3))
return field
}
var model: Node? = null
var modelPath: String? = null
var role: TrackerRole = TrackerRole.Invalid
}
typealias TrackerInputEventHandler = (TrackerInput, TrackedDevice, Long) -> Any
/**
* Contains event handlers in the form of lists of lambdas (see [TrackerInputEventHandler])
* for handling device connect/disconnect events.
*/
class TrackerInputEventHandlers {
/** List of handlers for connect events */
var onDeviceConnect = ArrayList<TrackerInputEventHandler>()
protected set
/** List of handlers for disconnect events */
var onDeviceDisconnect = ArrayList<TrackerInputEventHandler>()
protected set
}
/**
* Generic interface for head-mounted displays (HMDs) providing tracker input.
*
* @author Ulrik Günther <[email protected]>
*/
interface TrackerInput {
/** Event handler class */
var events: TrackerInputEventHandlers
/**
* Returns the orientation of the HMD
*
* @returns Matrix4f with orientation
*/
fun getOrientation(): Quaternionf
/**
* Returns the orientation of the given device, or a unit quaternion if the device is not found.
*
* @returns Matrix4f with orientation
*/
fun getOrientation(id: String): Quaternionf
/**
* Returns the absolute position as Vector3f
*
* @return HMD position as Vector3f
*/
fun getPosition(): Vector3f
/**
* Returns the HMD pose
*
* @return HMD pose as Matrix4f
*/
fun getPose(): Matrix4f
/**
* Returns a list of poses for the devices [type] given.
*
* @return Pose as Matrix4f
*/
fun getPose(type: TrackedDeviceType): List<TrackedDevice>
/**
* Returns the HMD pose for a given eye.
*
* @param[eye] The eye to return the pose for.
* @return HMD pose as Matrix4f
*/
fun getPoseForEye(eye: Int): Matrix4f
/**
* Check whether the HMD is initialized and working
*
* @return True if HMD is initialiased correctly and working properly
*/
fun initializedAndWorking(): Boolean
/**
* update state
*/
fun update()
/**
* Check whether there is a working TrackerInput for this device.
*
* @returns the [TrackerInput] if that is the case, null otherwise.
*/
fun getWorkingTracker(): TrackerInput?
/**
* Loads a model representing the [TrackedDevice].
*
* @param[device] The device to load the model for.
* @param[mesh] The [Mesh] to attach the model data to.
*/
fun loadModelForMesh(device: TrackedDevice, mesh: Mesh): Mesh
/**
* Loads a model representing a kind of [TrackedDeviceType].
*
* @param[type] The device type to load the model for, by default [TrackedDeviceType.Controller].
* @param[mesh] The [Mesh] to attach the model data to.
*/
fun loadModelForMesh(type: TrackedDeviceType = TrackedDeviceType.Controller, mesh: Mesh): Mesh
/**
* Attaches a given [TrackedDevice] to a scene graph [Node], camera-relative in case [camera] is non-null.
*
* @param[device] The [TrackedDevice] to use.
* @param[node] The node which should take tracking data from [device].
* @param[camera] A camera, in case the node should also be added as a child to the camera.
*/
fun attachToNode(device: TrackedDevice, node: Node, camera: Camera? = null)
/**
* Returns all tracked devices a given type.
*
* @param[ofType] The [TrackedDeviceType] of the devices to return.
* @return A [Map] of device name to [TrackedDevice]
*/
fun getTrackedDevices(ofType: TrackedDeviceType): Map<String, TrackedDevice>
}
| lgpl-3.0 | b8016880516d13d3a8cacea79e09f397 | 30.37766 | 180 | 0.642651 | 3.893729 | false | false | false | false |
Tickaroo/tikxml | annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/regressiontests/paths/Employee.kt | 1 | 725 | package com.tickaroo.tikxml.regressiontests.paths
import com.tickaroo.tikxml.annotation.PropertyElement
import com.tickaroo.tikxml.annotation.Xml
@Xml
class Employee : Person() {
@PropertyElement
var name: String? = null
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Employee) return false
if (!super.equals(other)) return false
val employee = other as Employee?
return if (name != null) name == employee!!.name else employee!!.name == null
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + if (name != null) name!!.hashCode() else 0
return result
}
} | apache-2.0 | 399367593fb94b0b8d63b1022cb1d436 | 26.923077 | 85 | 0.644138 | 4.341317 | false | false | false | false |
iSoron/uhabits | uhabits-core-legacy/src/main/common/org/isoron/platform/time/Dates.kt | 1 | 4806 | /*
* Copyright (C) 2016-2019 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.platform.time
import kotlin.math.*
enum class DayOfWeek(val index: Int) {
SUNDAY(0),
MONDAY(1),
TUESDAY(2),
WEDNESDAY(3),
THURSDAY(4),
FRIDAY(5),
SATURDAY(6),
}
data class Timestamp(val millisSince1970: Long) {
val localDate: LocalDate
get() {
val millisSince2000 = millisSince1970 - 946684800000
val daysSince2000 = millisSince2000 / 86400000
return LocalDate(daysSince2000.toInt())
}
}
data class LocalDate(val daysSince2000: Int) {
var yearCache = -1
var monthCache = -1
var dayCache = -1
// init {
// if (daysSince2000 < 0)
// throw IllegalArgumentException("$daysSince2000 < 0")
// }
constructor(year: Int, month: Int, day: Int) :
this(daysSince2000(year, month, day))
val dayOfWeek: DayOfWeek
get() {
return when (daysSince2000 % 7) {
0 -> DayOfWeek.SATURDAY
1 -> DayOfWeek.SUNDAY
2 -> DayOfWeek.MONDAY
3 -> DayOfWeek.TUESDAY
4 -> DayOfWeek.WEDNESDAY
5 -> DayOfWeek.THURSDAY
else -> DayOfWeek.FRIDAY
}
}
val timestamp: Timestamp
get() {
return Timestamp(946684800000 + daysSince2000.toLong() * 86400000)
}
val year: Int
get() {
if (yearCache < 0) updateYearMonthDayCache()
return yearCache
}
val month: Int
get() {
if (monthCache < 0) updateYearMonthDayCache()
return monthCache
}
val day: Int
get() {
if (dayCache < 0) updateYearMonthDayCache()
return dayCache
}
private fun updateYearMonthDayCache() {
var currYear = 2000
var currDay = 0
while (true) {
val currYearLength = if (isLeapYear(currYear)) 366 else 365
if (daysSince2000 < currDay + currYearLength) {
yearCache = currYear
break
} else {
currYear++
currDay += currYearLength
}
}
var currMonth = 1
val monthOffset = if (isLeapYear(currYear)) leapOffset else nonLeapOffset
while (true) {
if (daysSince2000 < currDay + monthOffset[currMonth]) {
monthCache = currMonth
break
} else {
currMonth++
}
}
currDay += monthOffset[currMonth - 1]
dayCache = daysSince2000 - currDay + 1
}
fun isOlderThan(other: LocalDate): Boolean {
return daysSince2000 < other.daysSince2000
}
fun isNewerThan(other: LocalDate): Boolean {
return daysSince2000 > other.daysSince2000
}
fun plus(days: Int): LocalDate {
return LocalDate(daysSince2000 + days)
}
fun minus(days: Int): LocalDate {
return LocalDate(daysSince2000 - days)
}
fun distanceTo(other: LocalDate): Int {
return abs(daysSince2000 - other.daysSince2000)
}
}
interface LocalDateFormatter {
fun shortWeekdayName(date: LocalDate): String
fun shortMonthName(date: LocalDate): String
}
private fun isLeapYear(year: Int): Boolean {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}
val leapOffset = arrayOf(0, 31, 60, 91, 121, 152, 182,
213, 244, 274, 305, 335, 366)
val nonLeapOffset = arrayOf(0, 31, 59, 90, 120, 151, 181,
212, 243, 273, 304, 334, 365)
private fun daysSince2000(year: Int, month: Int, day: Int): Int {
var result = 365 * (year - 2000)
result += ceil((year - 2000) / 4.0).toInt()
result -= ceil((year - 2000) / 100.0).toInt()
result += ceil((year - 2000) / 400.0).toInt()
if (isLeapYear(year)) {
result += leapOffset[month - 1]
} else {
result += nonLeapOffset[month - 1]
}
result += (day - 1)
return result
} | gpl-3.0 | e61354113e7b13ea9f9c5e6be8927559 | 26.780347 | 81 | 0.580021 | 4.290179 | false | false | false | false |
nadraliev/DsrWeatherApp | app/src/main/java/soutvoid/com/DsrWeatherApp/ui/screen/weather/WeatherActivityView.kt | 1 | 6366 | package soutvoid.com.DsrWeatherApp.ui.screen.weather
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import com.agna.ferro.mvp.component.ScreenComponent
import com.mikepenz.iconics.IconicsDrawable
import kotlinx.android.synthetic.main.activity_weather.*
import kotlinx.android.synthetic.main.layout_current_weather.*
import soutvoid.com.DsrWeatherApp.R
import soutvoid.com.DsrWeatherApp.domain.CurrentWeather
import soutvoid.com.DsrWeatherApp.domain.Forecast
import soutvoid.com.DsrWeatherApp.domain.location.SavedLocation
import soutvoid.com.DsrWeatherApp.ui.base.activity.BaseActivityView
import soutvoid.com.DsrWeatherApp.ui.base.activity.BasePresenter
import soutvoid.com.DsrWeatherApp.ui.screen.weather.data.AllWeatherData
import soutvoid.com.DsrWeatherApp.ui.screen.weather.widgets.forecastList.ForecastListAdapter
import soutvoid.com.DsrWeatherApp.ui.util.*
import javax.inject.Inject
/**
* экран для отображения погоды в определенной точке
*/
class WeatherActivityView : BaseActivityView() {
companion object {
const val LOCATION_KEY = "location"
const val LOCATION_ID_KEY = "location_id"
/**
* метод для старта активити
* @param [savedLocation] для какой точки загружать погоду
*/
fun start(context: Context, savedLocation: SavedLocation) {
val intent = Intent(context, WeatherActivityView::class.java)
intent.putExtra(LOCATION_KEY, savedLocation)
context.startActivity(intent)
}
fun start(context: Context, locationId: Int) {
val intent = Intent(context, WeatherActivityView::class.java)
intent.putExtra(LOCATION_ID_KEY, locationId)
context.startActivity(intent)
}
}
@Inject
lateinit var presenter : WeatherActivityPresenter
private val forecastAdapter: ForecastListAdapter = ForecastListAdapter()
private var messageSnackbar: Snackbar? = null
override fun onCreate(savedInstanceState: Bundle?, viewRecreated: Boolean) {
super.onCreate(savedInstanceState, viewRecreated)
initSwipeRefresh()
initBackButton()
}
override fun getPresenter(): BasePresenter<*> = presenter
override fun getName(): String = "WeatherActivity"
override fun getContentView(): Int = R.layout.activity_weather
override fun createScreenComponent(): ScreenComponent<*> {
return DaggerWeatherActivityComponent.builder()
.activityModule(activityModule)
.appComponent(appComponent)
.build()
}
private fun initSwipeRefresh() {
weather_refresh_layout.setOnRefreshListener { presenter.refresh() }
}
private fun initBackButton() {
weather_back_btn.setOnClickListener { onBackPressed() }
}
fun maybeInitForecastList(showForecast: Boolean) {
if (showForecast) {
weather_forecast_list.adapter = forecastAdapter
weather_forecast_list.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
weather_forecast_list.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL))
}
}
fun fillCityName(name: String) {
weather_city_tv.text = name
}
fun fillAllData(allWeatherData: AllWeatherData, showForecast: Boolean) {
fillCurrentWeatherData(allWeatherData.currentWeather)
fillForecastData(allWeatherData.forecast)
maybeFillNextDaysForecast(allWeatherData.forecast, showForecast)
}
fun fillCurrentWeatherData(currentWeather: CurrentWeather) {
with(currentWeather) {
val primaryTextColor = getThemeColor(android.R.attr.textColorPrimary)
weather_date_tv.text = CalendarUtils.getFormattedDate(timeOfData)
weather_temp_tv.text = "${Math.round(main.temperature)} ${UnitsUtils.getDegreesUnits(this@WeatherActivityView)}"
weather_icon_iv.setImageDrawable(IconicsDrawable(this@WeatherActivityView)
.icon(WeatherIconsHelper.getWeatherIcon(weather.first().id, timeOfData))
.color(primaryTextColor)
.sizeDp(100))
weather_description_tv.text = weather.first().description
weather_wind_speed_tv.text = "${wind.speed} ${UnitsUtils.getVelocityUnits(this@WeatherActivityView)}"
weather_wind_direction_tv.text = WindUtils.getFromByDegrees(wind.degrees, this@WeatherActivityView)
weather_pressure_tv.text = " ${main.pressure} ${UnitsUtils.getPressureUnits(this@WeatherActivityView)}"
weather_humidity_tv.text = " ${main.humidity}%"
}
}
fun fillForecastData(forecast: Forecast) {
weather_forecast.setWeather(forecast.list.filterIndexed { index, _ -> index % 2 == 0 }.take(4))
}
fun maybeFillNextDaysForecast(forecast: Forecast, showForecast: Boolean) {
if (showForecast) {
forecastAdapter.forecasts = forecast.list
forecastAdapter.notifyDataSetChanged()
}
}
fun setProgressBarEnabled(enabled: Boolean) {
weather_refresh_layout.isRefreshing = enabled
}
fun getLocationParam(): SavedLocation? {
if (intent.hasExtra(LOCATION_KEY))
return intent.getSerializableExtra(WeatherActivityView.LOCATION_KEY) as SavedLocation
return null
}
fun getCachedDataMessage(value: Int, isDays: Boolean): String {
val noConnection = getString(R.string.no_internet_connection_error_message)
val lastUpdate = getString(R.string.last_update)
var time = ""
if (isDays)
time = "$value ${resources.getQuantityString(R.plurals.days, value)}"
else
time = "$value ${resources.getQuantityString(R.plurals.hours, value)}"
val ago = getString(R.string.ago)
return "$noConnection \n$lastUpdate $time $ago"
}
fun showIndefiniteMessage(snackbar: Snackbar) {
messageSnackbar = snackbar
}
fun hideIndefiniteMessage() {
messageSnackbar?.dismiss()
}
} | apache-2.0 | 595034f28d6564e6a26c3ede304eca9f | 38.459119 | 124 | 0.703013 | 4.670886 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/cloudformation/src/main/kotlin/com/kotlin/cloudformation/DeleteStack.kt | 1 | 1476 | // snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
// snippet-sourcedescription:[DeleteStack.kt demonstrates how to delete an existing stack.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[AWS CloudFormation]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.cloudformation
// snippet-start:[cf.kotlin.delete_stack.import]
import aws.sdk.kotlin.services.cloudformation.CloudFormationClient
import aws.sdk.kotlin.services.cloudformation.model.DeleteStackRequest
import kotlin.system.exitProcess
// snippet-end:[cf.kotlin.delete_stack.import]
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<stackName>
Where:
stackName - The name of the AWS CloudFormation stack.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val stackName = args[0]
deleteSpecificTemplate(stackName)
}
// snippet-start:[cf.kotlin.delete_stack.main]
suspend fun deleteSpecificTemplate(stackNameVal: String?) {
val request = DeleteStackRequest {
stackName = stackNameVal
}
CloudFormationClient { region = "us-east-1" }.use { cfClient ->
cfClient.deleteStack(request)
println("The AWS CloudFormation stack was successfully deleted!")
}
}
// snippet-end:[cf.kotlin.delete_stack.main]
| apache-2.0 | d050ce3f5c1af7ec84382875f061cc03 | 27.52 | 91 | 0.684959 | 4.032787 | false | true | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/service/internship/InternshipReleaseServiceImpl.kt | 1 | 10341 | package top.zbeboy.isy.service.internship
import com.alibaba.fastjson.JSON
import org.jooq.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.ValueOperations
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import top.zbeboy.isy.domain.Tables.*
import top.zbeboy.isy.domain.tables.daos.InternshipReleaseDao
import top.zbeboy.isy.domain.tables.pojos.InternshipRelease
import top.zbeboy.isy.domain.tables.pojos.Science
import top.zbeboy.isy.domain.tables.records.InternshipReleaseRecord
import top.zbeboy.isy.service.cache.CacheBook
import top.zbeboy.isy.service.util.DateTimeUtils
import top.zbeboy.isy.service.util.SQLQueryUtils
import top.zbeboy.isy.web.bean.error.ErrorBean
import top.zbeboy.isy.web.bean.internship.release.InternshipReleaseBean
import top.zbeboy.isy.web.util.PaginationUtils
import java.sql.Timestamp
import java.util.*
import javax.annotation.Resource
/**
* Created by zbeboy 2017-12-19 .
**/
@Service("internshipReleaseService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
open class InternshipReleaseServiceImpl @Autowired constructor(dslContext: DSLContext) : InternshipReleaseService {
private val create: DSLContext = dslContext
@Resource(name = "redisTemplate")
open lateinit var errorBeanValueOperations: ValueOperations<String, ErrorBean<InternshipRelease>>
@Resource
open lateinit var internshipReleaseDao: InternshipReleaseDao
@Resource
open lateinit var internshipReleaseScienceService: InternshipReleaseScienceService
override fun findByEndTime(endTime: Timestamp): Result<InternshipReleaseRecord> {
return create.selectFrom<InternshipReleaseRecord>(INTERNSHIP_RELEASE)
.where(INTERNSHIP_RELEASE.END_TIME.le(endTime))
.fetch()
}
override fun findById(internshipReleaseId: String): InternshipRelease {
return internshipReleaseDao.findById(internshipReleaseId)
}
override fun findByIdRelation(internshipReleaseId: String): Optional<Record> {
return create.select()
.from(INTERNSHIP_RELEASE)
.join(INTERNSHIP_TYPE)
.on(INTERNSHIP_RELEASE.INTERNSHIP_TYPE_ID.eq(INTERNSHIP_TYPE.INTERNSHIP_TYPE_ID))
.join(DEPARTMENT)
.on(INTERNSHIP_RELEASE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID))
.join(COLLEGE)
.on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID))
.join(SCHOOL)
.on(COLLEGE.SCHOOL_ID.eq(SCHOOL.SCHOOL_ID))
.where(INTERNSHIP_RELEASE.INTERNSHIP_RELEASE_ID.eq(internshipReleaseId))
.fetchOptional()
}
override fun findByReleaseTitle(releaseTitle: String): List<InternshipRelease> {
return internshipReleaseDao.fetchByInternshipTitle(releaseTitle)
}
override fun findByReleaseTitleNeInternshipReleaseId(releaseTitle: String, internshipReleaseId: String): Result<InternshipReleaseRecord> {
return create.selectFrom<InternshipReleaseRecord>(INTERNSHIP_RELEASE)
.where(INTERNSHIP_RELEASE.INTERNSHIP_TITLE.eq(releaseTitle).and(INTERNSHIP_RELEASE.INTERNSHIP_RELEASE_ID.ne(internshipReleaseId)))
.fetch()
}
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
override fun save(internshipRelease: InternshipRelease) {
internshipReleaseDao.insert(internshipRelease)
}
override fun update(internshipRelease: InternshipRelease) {
val cacheKey = CacheBook.INTERNSHIP_BASE_CONDITION + internshipRelease.internshipReleaseId
if (errorBeanValueOperations.operations.hasKey(cacheKey)!!) {
errorBeanValueOperations.operations.delete(cacheKey)
}
internshipReleaseDao.update(internshipRelease)
}
override fun findAllByPage(paginationUtils: PaginationUtils, internshipReleaseBean: InternshipReleaseBean): Result<Record> {
val pageNum = paginationUtils.getPageNum()
val pageSize = paginationUtils.getPageSize()
var a = searchCondition(paginationUtils)
a = otherCondition(a, internshipReleaseBean)
return create.select()
.from(INTERNSHIP_RELEASE)
.join(DEPARTMENT)
.on(INTERNSHIP_RELEASE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID))
.join(INTERNSHIP_TYPE)
.on(INTERNSHIP_TYPE.INTERNSHIP_TYPE_ID.eq(INTERNSHIP_RELEASE.INTERNSHIP_TYPE_ID))
.join(COLLEGE)
.on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID))
.join(SCHOOL)
.on(COLLEGE.COLLEGE_ID.eq(SCHOOL.SCHOOL_ID))
.where(a)
.orderBy(INTERNSHIP_RELEASE.RELEASE_TIME.desc())
.limit((pageNum - 1) * pageSize, pageSize)
.fetch()
}
override fun dealData(paginationUtils: PaginationUtils, records: Result<Record>, internshipReleaseBean: InternshipReleaseBean): List<InternshipReleaseBean> {
var internshipReleaseBeens: List<InternshipReleaseBean> = ArrayList()
if (records.isNotEmpty) {
internshipReleaseBeens = records.into(InternshipReleaseBean::class.java)
val format = "yyyy-MM-dd HH:mm:ss"
internshipReleaseBeens.forEach { i ->
i.teacherDistributionStartTimeStr = DateTimeUtils.timestampToString(i.teacherDistributionStartTime, format)
i.teacherDistributionEndTimeStr = DateTimeUtils.timestampToString(i.teacherDistributionEndTime, format)
i.startTimeStr = DateTimeUtils.timestampToString(i.startTime, format)
i.endTimeStr = DateTimeUtils.timestampToString(i.endTime, format)
i.releaseTimeStr = DateTimeUtils.timestampToString(i.releaseTime, format)
val records1 = internshipReleaseScienceService.findByInternshipReleaseIdRelation(i.internshipReleaseId)
i.sciences = records1.into(Science::class.java)
}
paginationUtils.setTotalDatas(countByCondition(paginationUtils, internshipReleaseBean))
}
return internshipReleaseBeens
}
override fun countByCondition(paginationUtils: PaginationUtils, internshipReleaseBean: InternshipReleaseBean): Int {
val count: Record1<Int>
var a = searchCondition(paginationUtils)
a = otherCondition(a, internshipReleaseBean)
count = if (ObjectUtils.isEmpty(a)) {
val selectJoinStep = create.selectCount()
.from(INTERNSHIP_RELEASE)
selectJoinStep.fetchOne()
} else {
val selectConditionStep = create.selectCount()
.from(INTERNSHIP_RELEASE)
.join(DEPARTMENT)
.on(INTERNSHIP_RELEASE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID))
.join(INTERNSHIP_TYPE)
.on(INTERNSHIP_TYPE.INTERNSHIP_TYPE_ID.eq(INTERNSHIP_RELEASE.INTERNSHIP_TYPE_ID))
.join(COLLEGE)
.on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID))
.join(SCHOOL)
.on(COLLEGE.COLLEGE_ID.eq(SCHOOL.SCHOOL_ID))
.where(a)
selectConditionStep.fetchOne()
}
return count.value1()
}
/**
* 搜索条件
*
* @param paginationUtils 分页工具
* @return 条件
*/
fun searchCondition(paginationUtils: PaginationUtils): Condition? {
var a: Condition? = null
val search = JSON.parseObject(paginationUtils.getSearchParams())
if (!ObjectUtils.isEmpty(search)) {
val internshipTitle = StringUtils.trimWhitespace(search.getString("internshipTitle"))
if (StringUtils.hasLength(internshipTitle)) {
a = INTERNSHIP_RELEASE.INTERNSHIP_TITLE.like(SQLQueryUtils.likeAllParam(internshipTitle))
}
}
return a
}
/**
* 其它条件参数
*
* @param a 搜索条件
* @param internshipReleaseBean 额外参数
* @return 条件
*/
private fun otherCondition(a: Condition?, internshipReleaseBean: InternshipReleaseBean): Condition? {
var tempCondition = a
if (!ObjectUtils.isEmpty(internshipReleaseBean)) {
if (!ObjectUtils.isEmpty(internshipReleaseBean.departmentId) && internshipReleaseBean.departmentId > 0) {
tempCondition = if (!ObjectUtils.isEmpty(tempCondition)) {
tempCondition!!.and(INTERNSHIP_RELEASE.DEPARTMENT_ID.eq(internshipReleaseBean.departmentId))
} else {
INTERNSHIP_RELEASE.DEPARTMENT_ID.eq(internshipReleaseBean.departmentId)
}
}
if (!ObjectUtils.isEmpty(internshipReleaseBean.collegeId) && internshipReleaseBean.collegeId!! > 0) {
tempCondition = if (!ObjectUtils.isEmpty(tempCondition)) {
tempCondition!!.and(COLLEGE.COLLEGE_ID.eq(internshipReleaseBean.collegeId))
} else {
COLLEGE.COLLEGE_ID.eq(internshipReleaseBean.collegeId)
}
}
if (!ObjectUtils.isEmpty(internshipReleaseBean.internshipReleaseIsDel)) {
tempCondition = if (!ObjectUtils.isEmpty(tempCondition)) {
tempCondition!!.and(INTERNSHIP_RELEASE.INTERNSHIP_RELEASE_IS_DEL.eq(internshipReleaseBean.internshipReleaseIsDel))
} else {
INTERNSHIP_RELEASE.INTERNSHIP_RELEASE_IS_DEL.eq(internshipReleaseBean.internshipReleaseIsDel)
}
}
if (!ObjectUtils.isEmpty(internshipReleaseBean.allowGrade)) {
tempCondition = if (!ObjectUtils.isEmpty(tempCondition)) {
tempCondition!!.and(INTERNSHIP_RELEASE.ALLOW_GRADE.eq(internshipReleaseBean.allowGrade))
} else {
INTERNSHIP_RELEASE.ALLOW_GRADE.eq(internshipReleaseBean.allowGrade)
}
}
}
return tempCondition
}
} | mit | 9187f52c0ff9126cbfb5f17d04d271f1 | 45.351351 | 161 | 0.672466 | 5.214901 | false | false | false | false |
paplorinc/intellij-community | platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.kt | 1 | 19932 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("PropertyName")
package com.intellij.ide.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.ComponentTreeEventDispatcher
import com.intellij.util.SystemProperties
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.xmlb.annotations.Transient
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.RenderingHints
import javax.swing.JComponent
import javax.swing.SwingConstants
private val LOG = logger<UISettings>()
@State(name = "UISettings", storages = [(Storage("ui.lnf.xml"))], reportStatistic = true)
class UISettings @JvmOverloads constructor(private val notRoamableOptions: NotRoamableUiSettings = NotRoamableUiSettings()) : PersistentStateComponent<UISettingsState> {
private var state = UISettingsState()
private val myTreeDispatcher = ComponentTreeEventDispatcher.create(UISettingsListener::class.java)
var ideAAType: AntialiasingType
get() = notRoamableOptions.state.ideAAType
set(value) {
notRoamableOptions.state.ideAAType = value
}
var editorAAType: AntialiasingType
get() = notRoamableOptions.state.editorAAType
set(value) {
notRoamableOptions.state.editorAAType = value
}
var allowMergeButtons: Boolean
get() = state.allowMergeButtons
set(value) {
state.allowMergeButtons = value
}
val alwaysShowWindowsButton: Boolean
get() = state.alwaysShowWindowsButton
var animateWindows: Boolean
get() = state.animateWindows
set(value) {
state.animateWindows = value
}
var showMemoryIndicator: Boolean
get() = state.showMemoryIndicator
set(value) {
state.showMemoryIndicator = value
}
var colorBlindness: ColorBlindness?
get() = state.colorBlindness
set(value) {
state.colorBlindness = value
}
var hideToolStripes: Boolean
get() = state.hideToolStripes
set(value) {
state.hideToolStripes = value
}
var hideNavigationOnFocusLoss: Boolean
get() = state.hideNavigationOnFocusLoss
set(value) {
state.hideNavigationOnFocusLoss = value
}
var reuseNotModifiedTabs: Boolean
get() = state.reuseNotModifiedTabs
set(value) {
state.reuseNotModifiedTabs = value
}
var disableMnemonics: Boolean
get() = state.disableMnemonics
set(value) {
state.disableMnemonics = value
}
var disableMnemonicsInControls: Boolean
get() = state.disableMnemonicsInControls
set(value) {
state.disableMnemonicsInControls = value
}
var dndWithPressedAltOnly: Boolean
get() = state.dndWithPressedAltOnly
set(value) {
state.dndWithPressedAltOnly = value
}
var useSmallLabelsOnTabs: Boolean
get() = state.useSmallLabelsOnTabs
set(value) {
state.useSmallLabelsOnTabs = value
}
val smoothScrolling: Boolean
get() = state.smoothScrolling
val closeTabButtonOnTheRight: Boolean
get() = state.closeTabButtonOnTheRight
var cycleScrolling: Boolean
get() = state.cycleScrolling
set(value) {
state.cycleScrolling = value
}
var navigateToPreview: Boolean
get() = state.navigateToPreview
set(value) {
state.navigateToPreview = value
}
val scrollTabLayoutInEditor: Boolean
get() = state.scrollTabLayoutInEditor
var showToolWindowsNumbers: Boolean
get() = state.showToolWindowsNumbers
set(value) {
state.showToolWindowsNumbers = value
}
var showEditorToolTip: Boolean
get() = state.showEditorToolTip
set(value) {
state.showEditorToolTip = value
}
var showNavigationBar: Boolean
get() = state.showNavigationBar
set(value) {
state.showNavigationBar = value
}
var showStatusBar: Boolean
get() = state.showStatusBar
set(value) {
state.showStatusBar = value
}
var showIconInQuickNavigation: Boolean
get() = state.showIconInQuickNavigation
set(value) {
state.showIconInQuickNavigation = value
}
var moveMouseOnDefaultButton: Boolean
get() = state.moveMouseOnDefaultButton
set(value) {
state.moveMouseOnDefaultButton = value
}
var showMainToolbar: Boolean
get() = state.showMainToolbar
set(value) {
state.showMainToolbar = value
}
var showIconsInMenus: Boolean
get() = state.showIconsInMenus
set(value) {
state.showIconsInMenus = value
}
var sortLookupElementsLexicographically: Boolean
get() = state.sortLookupElementsLexicographically
set(value) {
state.sortLookupElementsLexicographically = value
}
val hideTabsIfNeed: Boolean
get() = state.hideTabsIfNeed
var hideKnownExtensionInTabs: Boolean
get() = state.hideKnownExtensionInTabs
set(value) {
state.hideKnownExtensionInTabs = value
}
var leftHorizontalSplit: Boolean
get() = state.leftHorizontalSplit
set(value) {
state.leftHorizontalSplit = value
}
var rightHorizontalSplit: Boolean
get() = state.rightHorizontalSplit
set(value) {
state.rightHorizontalSplit = value
}
var wideScreenSupport: Boolean
get() = state.wideScreenSupport
set(value) {
state.wideScreenSupport = value
}
var sortBookmarks: Boolean
get() = state.sortBookmarks
set(value) {
state.sortBookmarks = value
}
val showCloseButton: Boolean
get() = state.showCloseButton
var presentationMode: Boolean
get() = state.presentationMode
set(value) {
state.presentationMode = value
}
val presentationModeFontSize: Int
get() = state.presentationModeFontSize
var editorTabPlacement: Int
get() = state.editorTabPlacement
set(value) {
state.editorTabPlacement = value
}
var editorTabLimit: Int
get() = state.editorTabLimit
set(value) {
state.editorTabLimit = value
}
val recentFilesLimit: Int
get() = state.recentFilesLimit
val recentLocationsLimit: Int
get() = state.recentLocationsLimit
var maxLookupWidth: Int
get() = state.maxLookupWidth
set(value) {
state.maxLookupWidth = value
}
var maxLookupListHeight: Int
get() = state.maxLookupListHeight
set(value) {
state.maxLookupListHeight = value
}
var overrideLafFonts: Boolean
get() = state.overrideLafFonts
set(value) {
state.overrideLafFonts = value
}
var fontFace: String?
get() = notRoamableOptions.state.fontFace
set(value) {
notRoamableOptions.state.fontFace = value
}
var fontSize: Int
get() = notRoamableOptions.state.fontSize
set(value) {
notRoamableOptions.state.fontSize = value
}
var fontScale: Float
get() = notRoamableOptions.state.fontScale
set(value) {
notRoamableOptions.state.fontScale = value
}
var showDirectoryForNonUniqueFilenames: Boolean
get() = state.showDirectoryForNonUniqueFilenames
set(value) {
state.showDirectoryForNonUniqueFilenames = value
}
var pinFindInPath: Boolean
get() = state.pinFindInPath
set(value) {
state.pinFindInPath = value
}
var activeRightEditorOnClose: Boolean
get() = state.activeRightEditorOnClose
set(value) {
state.activeRightEditorOnClose = value
}
var showTabsTooltips: Boolean
get() = state.showTabsTooltips
set(value) {
state.showTabsTooltips = value
}
var markModifiedTabsWithAsterisk: Boolean
get() = state.markModifiedTabsWithAsterisk
set(value) {
state.markModifiedTabsWithAsterisk = value
}
@Suppress("unused")
var overrideConsoleCycleBufferSize: Boolean
get() = state.overrideConsoleCycleBufferSize
set(value) {
state.overrideConsoleCycleBufferSize = value
}
var consoleCycleBufferSizeKb: Int
get() = state.consoleCycleBufferSizeKb
set(value) {
state.consoleCycleBufferSizeKb = value
}
var consoleCommandHistoryLimit: Int
get() = state.consoleCommandHistoryLimit
set(value) {
state.consoleCommandHistoryLimit = value
}
companion object {
init {
verbose("defFontSize=%d, defFontScale=%.2f", defFontSize, defFontScale)
}
@JvmStatic
private fun verbose(msg: String, vararg args: Any) {
if (UIUtil.SCALE_VERBOSE) {
LOG.info(String.format(msg, *args))
}
}
const val ANIMATION_DURATION = 300 // Milliseconds
/** Not tabbed pane. */
const val TABS_NONE = 0
@Suppress("ObjectPropertyName")
@Volatile
private var _instance: UISettings? = null
@JvmStatic
val instance: UISettings
get() = instanceOrNull!!
@JvmStatic
val instanceOrNull: UISettings?
get() {
var result = _instance
if (result == null) {
if (ApplicationManager.getApplication() == null) {
return null
}
result = ServiceManager.getService(UISettings::class.java)
_instance = result
}
return result
}
/**
* Use this method if you are not sure whether the application is initialized.
* @return persisted UISettings instance or default values.
*/
@JvmStatic
val shadowInstance: UISettings
get() {
val uiSettings = if (ApplicationManager.getApplication() == null) null else instanceOrNull
return when {
uiSettings != null -> uiSettings
else -> {
return UISettings()
}
}
}
@JvmField
val FORCE_USE_FRACTIONAL_METRICS = SystemProperties.getBooleanProperty("idea.force.use.fractional.metrics", false)
@JvmStatic
fun setupFractionalMetrics(g2d: Graphics2D) {
if (FORCE_USE_FRACTIONAL_METRICS) {
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON)
}
}
/**
* This method must not be used for set up antialiasing for editor components. To make sure antialiasing settings are taken into account
* when preferred size of component is calculated, [.setupComponentAntialiasing] method should be called from
* `updateUI()` or `setUI()` method of component.
*/
@JvmStatic
fun setupAntialiasing(g: Graphics) {
val g2d = g as Graphics2D
g2d.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, UIUtil.getLcdContrastValue())
val application = ApplicationManager.getApplication()
if (application == null) {
// We cannot use services while Application has not been loaded yet
// So let's apply the default hints.
UIUtil.applyRenderingHints(g)
return
}
val uiSettings = ServiceManager.getService(UISettings::class.java)
if (uiSettings != null) {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false))
}
else {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF)
}
setupFractionalMetrics(g2d)
}
/**
* @see #setupAntialiasing(Graphics)
*/
@JvmStatic
fun setupComponentAntialiasing(component: JComponent) {
GraphicsUtil.setAntialiasingType(component, AntialiasingType.getAAHintForSwingComponent())
}
@JvmStatic
fun setupEditorAntialiasing(component: JComponent) {
GraphicsUtil.setAntialiasingType(component, instance.editorAAType.textInfo)
}
/**
* Returns the default font scale, which depends on the HiDPI mode (see JBUI#ScaleType).
* <p>
* The font is represented:
* - in relative (dpi-independent) points in the JRE-managed HiDPI mode, so the method returns 1.0f
* - in absolute (dpi-dependent) points in the IDE-managed HiDPI mode, so the method returns the default screen scale
*
* @return the system font scale
*/
@JvmStatic
val defFontScale: Float
get() = if (UIUtil.isJreHiDPIEnabled()) 1f else JBUI.sysScale()
/**
* Returns the default font size scaled by #defFontScale
*
* @return the default scaled font size
*/
@JvmStatic
val defFontSize: Int
get() = UISettingsState.defFontSize
@JvmStatic
fun restoreFontSize(readSize: Int, readScale: Float?): Int {
var size = readSize
if (readScale == null || readScale <= 0) {
verbose("Reset font to default")
// Reset font to default on switch from IDE-managed HiDPI to JRE-managed HiDPI. Doesn't affect OSX.
if (UIUtil.isJreHiDPIEnabled() && !SystemInfo.isMac) size = UISettingsState.defFontSize
}
else {
var oldDefFontScale = defFontScale
if (SystemInfo.isLinux) {
val fdata = UIUtil.getSystemFontData()
if (fdata != null) {
// [tav] todo: temp workaround for transitioning IDEA 173 to 181
// not converting fonts stored with scale equal to the old calculation
oldDefFontScale = fdata.second / 12f
verbose("oldDefFontScale=%.2f", oldDefFontScale)
}
}
if (readScale != defFontScale && readScale != oldDefFontScale) size = Math.round((readSize / readScale) * defFontScale)
}
LOG.info("Loaded: fontSize=$readSize, fontScale=$readScale; restored: fontSize=$size, fontScale=$defFontScale")
return size
}
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Please use {@link UISettingsListener#TOPIC}")
fun addUISettingsListener(listener: UISettingsListener, parentDisposable: Disposable) {
ApplicationManager.getApplication().messageBus.connect(parentDisposable).subscribe(UISettingsListener.TOPIC, listener)
}
/**
* Notifies all registered listeners that UI settings has been changed.
*/
fun fireUISettingsChanged() {
updateDeprecatedProperties()
// todo remove when all old properties will be converted
state._incrementModificationCount()
IconLoader.setFilter(ColorBlindnessSupport.get(state.colorBlindness)?.filter)
// if this is the main UISettings instance (and not on first call to getInstance) push event to bus and to all current components
if (this === _instance) {
myTreeDispatcher.multicaster.uiSettingsChanged(this)
ApplicationManager.getApplication().messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(this)
}
}
@Suppress("DEPRECATION")
private fun updateDeprecatedProperties() {
HIDE_TOOL_STRIPES = hideToolStripes
SHOW_MAIN_TOOLBAR = showMainToolbar
CYCLE_SCROLLING = cycleScrolling
SHOW_CLOSE_BUTTON = showCloseButton
EDITOR_AA_TYPE = editorAAType
PRESENTATION_MODE = presentationMode
OVERRIDE_NONIDEA_LAF_FONTS = overrideLafFonts
PRESENTATION_MODE_FONT_SIZE = presentationModeFontSize
CONSOLE_COMMAND_HISTORY_LIMIT = state.consoleCommandHistoryLimit
FONT_SIZE = fontSize
FONT_FACE = fontFace
EDITOR_TAB_LIMIT = editorTabLimit
OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE = overrideConsoleCycleBufferSize
CONSOLE_CYCLE_BUFFER_SIZE_KB = consoleCycleBufferSizeKb
}
override fun getState() = state
override fun loadState(state: UISettingsState) {
this.state = state
updateDeprecatedProperties()
migrateOldSettings()
if (migrateOldFontSettings()) {
notRoamableOptions.fixFontSettings()
}
// Check tab placement in editor
val editorTabPlacement = state.editorTabPlacement
if (editorTabPlacement != TABS_NONE &&
editorTabPlacement != SwingConstants.TOP &&
editorTabPlacement != SwingConstants.LEFT &&
editorTabPlacement != SwingConstants.BOTTOM &&
editorTabPlacement != SwingConstants.RIGHT) {
state.editorTabPlacement = SwingConstants.TOP
}
// Check that alpha delay and ratio are valid
if (state.alphaModeDelay < 0) {
state.alphaModeDelay = 1500
}
if (state.alphaModeRatio < 0.0f || state.alphaModeRatio > 1.0f) {
state.alphaModeRatio = 0.5f
}
fireUISettingsChanged()
}
@Suppress("DEPRECATION")
private fun migrateOldSettings() {
if (state.ideAAType != AntialiasingType.SUBPIXEL) {
editorAAType = state.ideAAType
state.ideAAType = AntialiasingType.SUBPIXEL
}
if (state.editorAAType != AntialiasingType.SUBPIXEL) {
editorAAType = state.editorAAType
state.editorAAType = AntialiasingType.SUBPIXEL
}
}
@Suppress("DEPRECATION")
private fun migrateOldFontSettings(): Boolean {
var migrated = false
if (state.fontSize != 0) {
fontSize = restoreFontSize(state.fontSize, state.fontScale)
state.fontSize = 0
migrated = true
}
if (state.fontScale != 0f) {
fontScale = state.fontScale
state.fontScale = 0f
migrated = true
}
if (state.fontFace != null) {
fontFace = state.fontFace
state.fontFace = null
migrated = true
}
return migrated
}
//<editor-fold desc="Deprecated stuff.">
@Suppress("unused")
@Deprecated("Use fontFace", replaceWith = ReplaceWith("fontFace"))
@JvmField
@Transient
var FONT_FACE: String? = null
@Suppress("unused")
@Deprecated("Use fontSize", replaceWith = ReplaceWith("fontSize"))
@JvmField
@Transient
var FONT_SIZE: Int? = 0
@Suppress("unused")
@Deprecated("Use hideToolStripes", replaceWith = ReplaceWith("hideToolStripes"))
@JvmField
@Transient
var HIDE_TOOL_STRIPES = true
@Suppress("unused")
@Deprecated("Use consoleCommandHistoryLimit", replaceWith = ReplaceWith("consoleCommandHistoryLimit"))
@JvmField
@Transient
var CONSOLE_COMMAND_HISTORY_LIMIT = 300
@Suppress("unused")
@Deprecated("Use cycleScrolling", replaceWith = ReplaceWith("cycleScrolling"))
@JvmField
@Transient
var CYCLE_SCROLLING = true
@Suppress("unused")
@Deprecated("Use showMainToolbar", replaceWith = ReplaceWith("showMainToolbar"))
@JvmField
@Transient
var SHOW_MAIN_TOOLBAR = false
@Suppress("unused")
@Deprecated("Use showCloseButton", replaceWith = ReplaceWith("showCloseButton"))
@JvmField
@Transient
var SHOW_CLOSE_BUTTON = true
@Suppress("unused")
@Deprecated("Use editorAAType", replaceWith = ReplaceWith("editorAAType"))
@JvmField
@Transient
var EDITOR_AA_TYPE: AntialiasingType? = AntialiasingType.SUBPIXEL
@Suppress("unused")
@Deprecated("Use presentationMode", replaceWith = ReplaceWith("presentationMode"))
@JvmField
@Transient
var PRESENTATION_MODE = false
@Suppress("unused", "SpellCheckingInspection")
@Deprecated("Use overrideLafFonts", replaceWith = ReplaceWith("overrideLafFonts"))
@JvmField
@Transient
var OVERRIDE_NONIDEA_LAF_FONTS = false
@Suppress("unused")
@Deprecated("Use presentationModeFontSize", replaceWith = ReplaceWith("presentationModeFontSize"))
@JvmField
@Transient
var PRESENTATION_MODE_FONT_SIZE = 24
@Suppress("unused")
@Deprecated("Use editorTabLimit", replaceWith = ReplaceWith("editorTabLimit"))
@JvmField
@Transient
var EDITOR_TAB_LIMIT = editorTabLimit
@Suppress("unused")
@Deprecated("Use overrideConsoleCycleBufferSize", replaceWith = ReplaceWith("overrideConsoleCycleBufferSize"))
@JvmField
@Transient
var OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE = false
@Suppress("unused")
@Deprecated("Use consoleCycleBufferSizeKb", replaceWith = ReplaceWith("consoleCycleBufferSizeKb"))
@JvmField
@Transient
var CONSOLE_CYCLE_BUFFER_SIZE_KB = consoleCycleBufferSizeKb
//</editor-fold>
} | apache-2.0 | daeea2d5c7eea228c9359d3b364c3081 | 28.014556 | 169 | 0.700682 | 4.890088 | false | false | false | false |
kmagiera/react-native-gesture-handler | android/lib/src/main/java/com/swmansion/gesturehandler/GestureHandlerOrchestrator.kt | 1 | 21500 | package com.swmansion.gesturehandler
import android.graphics.Matrix
import android.graphics.PointF
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import java.util.*
class GestureHandlerOrchestrator(
private val wrapperView: ViewGroup,
private val handlerRegistry: GestureHandlerRegistry,
private val viewConfigHelper: ViewConfigurationHelper,
) {
/**
* Minimum alpha (value from 0 to 1) that should be set to a view so that it can be treated as a
* gesture target. E.g. if set to 0.1 then views that less than 10% opaque will be ignored when
* traversing view hierarchy and looking for gesture handlers.
*/
var minimumAlphaForTraversal = DEFAULT_MIN_ALPHA_FOR_TRAVERSAL
private val gestureHandlers = arrayOfNulls<GestureHandler<*>?>(SIMULTANEOUS_GESTURE_HANDLER_LIMIT)
private val awaitingHandlers = arrayOfNulls<GestureHandler<*>?>(SIMULTANEOUS_GESTURE_HANDLER_LIMIT)
private val preparedHandlers = arrayOfNulls<GestureHandler<*>?>(SIMULTANEOUS_GESTURE_HANDLER_LIMIT)
private val handlersToCancel = arrayOfNulls<GestureHandler<*>?>(SIMULTANEOUS_GESTURE_HANDLER_LIMIT)
private var gestureHandlersCount = 0
private var awaitingHandlersCount = 0
private var isHandlingTouch = false
private var handlingChangeSemaphore = 0
private var finishedHandlersCleanupScheduled = false
private var activationIndex = 0
/**
* Should be called from the view wrapper
*/
fun onTouchEvent(event: MotionEvent): Boolean {
isHandlingTouch = true
val action = event.actionMasked
if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN) {
extractGestureHandlers(event)
} else if (action == MotionEvent.ACTION_CANCEL) {
cancelAll()
}
deliverEventToGestureHandlers(event)
isHandlingTouch = false
if (finishedHandlersCleanupScheduled && handlingChangeSemaphore == 0) {
cleanupFinishedHandlers()
}
return true
}
private fun scheduleFinishedHandlersCleanup() {
if (isHandlingTouch || handlingChangeSemaphore != 0) {
finishedHandlersCleanupScheduled = true
} else {
cleanupFinishedHandlers()
}
}
private inline fun compactHandlersIf(handlers: Array<GestureHandler<*>?>, count: Int, predicate: (handler: GestureHandler<*>?) -> Boolean): Int {
var out = 0
for (i in 0 until count) {
if (predicate(handlers[i])) {
handlers[out++] = handlers[i]
}
}
return out
}
private fun cleanupFinishedHandlers() {
var shouldCleanEmptyCells = false
for (i in gestureHandlersCount - 1 downTo 0) {
val handler = gestureHandlers[i]!!
if (isFinished(handler.state) && !handler.isAwaiting) {
gestureHandlers[i] = null
shouldCleanEmptyCells = true
handler.reset()
handler.apply {
isActive = false
isAwaiting = false
activationIndex = Int.MAX_VALUE
}
}
}
if (shouldCleanEmptyCells) {
gestureHandlersCount = compactHandlersIf(gestureHandlers, gestureHandlersCount) { handler ->
handler != null
}
}
finishedHandlersCleanupScheduled = false
}
private fun hasOtherHandlerToWaitFor(handler: GestureHandler<*>): Boolean {
for (i in 0 until gestureHandlersCount) {
val otherHandler = gestureHandlers[i]!!
if (!isFinished(otherHandler.state) && shouldHandlerWaitForOther(handler, otherHandler)) {
return true
}
}
return false
}
private fun tryActivate(handler: GestureHandler<*>) {
// see if there is anyone else who we need to wait for
if (hasOtherHandlerToWaitFor(handler)) {
addAwaitingHandler(handler)
} else {
// we can activate handler right away
makeActive(handler)
handler.isAwaiting = false
}
}
private fun cleanupAwaitingHandlers() {
awaitingHandlersCount = compactHandlersIf(awaitingHandlers, awaitingHandlersCount) { handler ->
handler!!.isAwaiting
}
}
/*package*/
fun onHandlerStateChange(handler: GestureHandler<*>, newState: Int, prevState: Int) {
handlingChangeSemaphore += 1
if (isFinished(newState)) {
// if there were handlers awaiting completion of this handler, we can trigger active state
for (i in 0 until awaitingHandlersCount) {
val otherHandler = awaitingHandlers[i]
if (shouldHandlerWaitForOther(otherHandler!!, handler)) {
if (newState == GestureHandler.STATE_END) {
// gesture has ended, we need to kill the awaiting handler
otherHandler.cancel()
otherHandler.isAwaiting = false
} else {
// gesture has failed recognition, we may try activating
tryActivate(otherHandler)
}
}
}
cleanupAwaitingHandlers()
}
if (newState == GestureHandler.STATE_ACTIVE) {
tryActivate(handler)
} else if (prevState == GestureHandler.STATE_ACTIVE || prevState == GestureHandler.STATE_END) {
if (handler.isActive) {
handler.dispatchStateChange(newState, prevState)
}
} else {
handler.dispatchStateChange(newState, prevState)
}
handlingChangeSemaphore -= 1
scheduleFinishedHandlersCleanup()
}
private fun makeActive(handler: GestureHandler<*>) {
val currentState = handler.state
with(handler) {
isAwaiting = false
isActive = true
activationIndex = [email protected]++
}
var toCancelCount = 0
// Cancel all handlers that are required to be cancel upon current handler's activation
for (i in 0 until gestureHandlersCount) {
val otherHandler = gestureHandlers[i]!!
if (shouldHandlerBeCancelledBy(otherHandler, handler)) {
handlersToCancel[toCancelCount++] = otherHandler
}
}
for (i in toCancelCount - 1 downTo 0) {
handlersToCancel[i]!!.cancel()
}
// Clear all awaiting handlers waiting for the current handler to fail
for (i in awaitingHandlersCount - 1 downTo 0) {
val otherHandler = awaitingHandlers[i]!!
if (shouldHandlerBeCancelledBy(otherHandler, handler)) {
otherHandler.cancel()
otherHandler.isAwaiting = false
}
}
cleanupAwaitingHandlers()
// Dispatch state change event if handler is no longer in the active state we should also
// trigger END state change and UNDETERMINED state change if necessary
handler.dispatchStateChange(GestureHandler.STATE_ACTIVE, GestureHandler.STATE_BEGAN)
if (currentState != GestureHandler.STATE_ACTIVE) {
handler.dispatchStateChange(GestureHandler.STATE_END, GestureHandler.STATE_ACTIVE)
if (currentState != GestureHandler.STATE_END) {
handler.dispatchStateChange(GestureHandler.STATE_UNDETERMINED, GestureHandler.STATE_END)
}
}
}
private fun deliverEventToGestureHandlers(event: MotionEvent) {
// Copy handlers to "prepared handlers" array, because the list of active handlers can change
// as a result of state updates
val handlersCount = gestureHandlersCount
gestureHandlers.copyInto(preparedHandlers, 0, 0, handlersCount)
// We want to deliver events to active handlers first in order of their activation (handlers
// that activated first will first get event delivered). Otherwise we deliver events in the
// order in which handlers has been added ("most direct" children goes first). Therefore we rely
// on Arrays.sort providing a stable sort (as children are registered in order in which they
// should be tested)
preparedHandlers.sortWith(handlersComparator, 0, handlersCount)
for (i in 0 until handlersCount) {
deliverEventToGestureHandler(preparedHandlers[i]!!, event)
}
}
private fun cancelAll() {
for (i in awaitingHandlersCount - 1 downTo 0) {
awaitingHandlers[i]!!.cancel()
}
// Copy handlers to "prepared handlers" array, because the list of active handlers can change
// as a result of state updates
val handlersCount = gestureHandlersCount
for (i in 0 until handlersCount) {
preparedHandlers[i] = gestureHandlers[i]
}
for (i in handlersCount - 1 downTo 0) {
preparedHandlers[i]!!.cancel()
}
}
private fun deliverEventToGestureHandler(handler: GestureHandler<*>, event: MotionEvent) {
if (!isViewAttachedUnderWrapper(handler.view)) {
handler.cancel()
return
}
if (!handler.wantEvents()) {
return
}
val action = event.actionMasked
val coords = tempCoords
extractCoordsForView(handler.view, event, coords)
val oldX = event.x
val oldY = event.y
// TODO: we may consider scaling events if necessary using MotionEvent.transform
// for now the events are only offset to the top left corner of the view but if
// view or any ot the parents is scaled the other pointers position will not reflect
// their actual place in the view. On the other hand not scaling seems like a better
// approach when we want to use pointer coordinates to calculate velocity or distance
// for pinch so I don't know yet if we should transform or not...
event.setLocation(coords[0], coords[1])
if (handler.needsPointerData) {
handler.updatePointerData(event)
}
if (!handler.isAwaiting || action != MotionEvent.ACTION_MOVE) {
handler.handle(event)
if (handler.isActive) {
handler.dispatchHandlerUpdate(event)
}
// if event was of type UP or POINTER_UP we request handler to stop tracking now that
// the event has been dispatched
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) {
val pointerId = event.getPointerId(event.actionIndex)
handler.stopTrackingPointer(pointerId)
}
}
event.setLocation(oldX, oldY)
}
/**
* isViewAttachedUnderWrapper checks whether all of parents for view related to handler
* view are attached. Since there might be an issue rarely observed when view
* has been detached and handler's state hasn't been change to canceled, failed or
* ended yet. Probably it's a result of some race condition and stopping delivering
* for this handler and changing its state to failed of end appear to be good enough solution.
*/
private fun isViewAttachedUnderWrapper(view: View?): Boolean {
if (view == null) {
return false
}
if (view === wrapperView) {
return true
}
var parent = view.parent
while (parent != null && parent !== wrapperView) {
parent = parent.parent
}
return parent === wrapperView
}
private fun extractCoordsForView(view: View?, event: MotionEvent, outputCoords: FloatArray) {
if (view === wrapperView) {
outputCoords[0] = event.x
outputCoords[1] = event.y
return
}
require(!(view == null || view.parent !is ViewGroup)) { "Parent is null? View is no longer in the tree" }
val parent = view.parent as ViewGroup
extractCoordsForView(parent, event, outputCoords)
val childPoint = tempPoint
transformTouchPointToViewCoords(outputCoords[0], outputCoords[1], parent, view, childPoint)
outputCoords[0] = childPoint.x
outputCoords[1] = childPoint.y
}
private fun addAwaitingHandler(handler: GestureHandler<*>) {
for (i in 0 until awaitingHandlersCount) {
if (awaitingHandlers[i] === handler) {
return
}
}
check(awaitingHandlersCount < awaitingHandlers.size) { "Too many recognizers" }
awaitingHandlers[awaitingHandlersCount++] = handler
with(handler) {
isAwaiting = true
activationIndex = [email protected]++
}
}
private fun recordHandlerIfNotPresent(handler: GestureHandler<*>, view: View) {
for (i in 0 until gestureHandlersCount) {
if (gestureHandlers[i] === handler) {
return
}
}
check(gestureHandlersCount < gestureHandlers.size) { "Too many recognizers" }
gestureHandlers[gestureHandlersCount++] = handler
handler.isActive = false
handler.isAwaiting = false
handler.activationIndex = Int.MAX_VALUE
handler.prepare(view, this)
}
private fun isViewOverflowingParent(view: View): Boolean {
val parent = view.parent as? ViewGroup ?: return false
val matrix = view.matrix
val localXY = matrixTransformCoords
localXY[0] = 0f
localXY[1] = 0f
matrix.mapPoints(localXY)
val left = localXY[0] + view.left
val top = localXY[1] + view.top
return left < 0f || left + view.width > parent.width || top < 0f || top + view.height > parent.height
}
private fun extractAncestorHandlers(view: View, coords: FloatArray, pointerId: Int): Boolean {
var found = false
var parent = view.parent
while (parent != null) {
if (parent is ViewGroup) {
val parentViewGroup: ViewGroup = parent
handlerRegistry.getHandlersForView(parent)?.let {
for (handler in it) {
if (handler.isEnabled && handler.isWithinBounds(view, coords[0], coords[1])) {
found = true
recordHandlerIfNotPresent(handler, parentViewGroup)
handler.startTrackingPointer(pointerId)
}
}
}
}
parent = parent.parent
}
return found
}
private fun recordViewHandlersForPointer(view: View, coords: FloatArray, pointerId: Int): Boolean {
var found = false
handlerRegistry.getHandlersForView(view)?.let {
val size = it.size
for (i in 0 until size) {
val handler = it[i]
if (handler.isEnabled && handler.isWithinBounds(view, coords[0], coords[1])) {
recordHandlerIfNotPresent(handler, view)
handler.startTrackingPointer(pointerId)
found = true
}
}
}
// if the pointer is inside the view but it overflows its parent, handlers attached to the parent
// might not have been extracted (pointer might be in a child, but may be outside parent)
if (coords[0] in 0f..view.width.toFloat() && coords[1] in 0f..view.height.toFloat()
&& isViewOverflowingParent(view) && extractAncestorHandlers(view, coords, pointerId)) {
found = true
}
return found
}
private fun extractGestureHandlers(event: MotionEvent) {
val actionIndex = event.actionIndex
val pointerId = event.getPointerId(actionIndex)
tempCoords[0] = event.getX(actionIndex)
tempCoords[1] = event.getY(actionIndex)
traverseWithPointerEvents(wrapperView, tempCoords, pointerId)
extractGestureHandlers(wrapperView, tempCoords, pointerId)
}
private fun extractGestureHandlers(viewGroup: ViewGroup, coords: FloatArray, pointerId: Int): Boolean {
val childrenCount = viewGroup.childCount
for (i in childrenCount - 1 downTo 0) {
val child = viewConfigHelper.getChildInDrawingOrderAtIndex(viewGroup, i)
if (canReceiveEvents(child)) {
val childPoint = tempPoint
transformTouchPointToViewCoords(coords[0], coords[1], viewGroup, child, childPoint)
val restoreX = coords[0]
val restoreY = coords[1]
coords[0] = childPoint.x
coords[1] = childPoint.y
var found = false
if (!isClipping(child) || isTransformedTouchPointInView(coords[0], coords[1], child)) {
// we only consider the view if touch is inside the view bounds or if the view's children
// can render outside of the view bounds (overflow visible)
found = traverseWithPointerEvents(child, coords, pointerId)
}
coords[0] = restoreX
coords[1] = restoreY
if (found) {
return true
}
}
}
return false
}
private fun traverseWithPointerEvents(view: View, coords: FloatArray, pointerId: Int): Boolean =
when (viewConfigHelper.getPointerEventsConfigForView(view)) {
PointerEventsConfig.NONE -> {
// This view and its children can't be the target
false
}
PointerEventsConfig.BOX_ONLY -> {
// This view is the target, its children don't matter
(recordViewHandlersForPointer(view, coords, pointerId)
|| shouldHandlerlessViewBecomeTouchTarget(view, coords))
}
PointerEventsConfig.BOX_NONE -> {
// This view can't be the target, but its children might
if (view is ViewGroup) {
extractGestureHandlers(view, coords, pointerId)
} else false
}
PointerEventsConfig.AUTO -> {
// Either this view or one of its children is the target
val found = if (view is ViewGroup) {
extractGestureHandlers(view, coords, pointerId)
} else false
(recordViewHandlersForPointer(view, coords, pointerId)
|| found || shouldHandlerlessViewBecomeTouchTarget(view, coords))
}
}
private fun canReceiveEvents(view: View) =
view.visibility == View.VISIBLE && view.alpha >= minimumAlphaForTraversal
// if view is not a view group it is clipping, otherwise we check for `getClipChildren` flag to
// be turned on and also confirm with the ViewConfigHelper implementation
private fun isClipping(view: View) =
view !is ViewGroup || viewConfigHelper.isViewClippingChildren(view)
companion object {
// The limit doesn't necessarily need to exists, it was just simpler to implement it that way
// it is also more allocation-wise efficient to have a fixed limit
private const val SIMULTANEOUS_GESTURE_HANDLER_LIMIT = 20
// Be default fully transparent views can receive touch
private const val DEFAULT_MIN_ALPHA_FOR_TRAVERSAL = 0f
private val tempPoint = PointF()
private val matrixTransformCoords = FloatArray(2)
private val inverseMatrix = Matrix()
private val tempCoords = FloatArray(2)
private val handlersComparator = Comparator<GestureHandler<*>?> { a, b ->
return@Comparator if (a.isActive && b.isActive || a.isAwaiting && b.isAwaiting) {
// both A and B are either active or awaiting activation, in which case we prefer one that
// has activated (or turned into "awaiting" state) earlier
Integer.signum(b.activationIndex - a.activationIndex)
} else if (a.isActive) {
-1 // only A is active
} else if (b.isActive) {
1 // only B is active
} else if (a.isAwaiting) {
-1 // only A is awaiting, B is inactive
} else if (b.isAwaiting) {
1 // only B is awaiting, A is inactive
} else {
0 // both A and B are inactive, stable order matters
}
}
private fun shouldHandlerlessViewBecomeTouchTarget(view: View, coords: FloatArray): Boolean {
// The following code is to match the iOS behavior where transparent parts of the views can
// pass touch events through them allowing sibling nodes to handle them.
// TODO: this is not an ideal solution as we only consider ViewGroups that has no background set
// TODO: ideally we should determine the pixel color under the given coordinates and return
// false if the color is transparent
val isLeafOrTransparent = view !is ViewGroup || view.getBackground() != null
return isLeafOrTransparent && isTransformedTouchPointInView(coords[0], coords[1], view)
}
private fun transformTouchPointToViewCoords(
x: Float,
y: Float,
parent: ViewGroup,
child: View,
outLocalPoint: PointF,
) {
var localX = x + parent.scrollX - child.left
var localY = y + parent.scrollY - child.top
val matrix = child.matrix
if (!matrix.isIdentity) {
val localXY = matrixTransformCoords
localXY[0] = localX
localXY[1] = localY
matrix.invert(inverseMatrix)
inverseMatrix.mapPoints(localXY)
localX = localXY[0]
localY = localXY[1]
}
outLocalPoint[localX] = localY
}
private fun isTransformedTouchPointInView(x: Float, y: Float, child: View) =
x in 0f..child.width.toFloat() && y in 0f..child.height.toFloat()
private fun shouldHandlerWaitForOther(handler: GestureHandler<*>, other: GestureHandler<*>): Boolean {
return handler !== other && (handler.shouldWaitForHandlerFailure(other)
|| other.shouldRequireToWaitForFailure(handler))
}
private fun canRunSimultaneously(a: GestureHandler<*>, b: GestureHandler<*>) =
a === b || a.shouldRecognizeSimultaneously(b) || b.shouldRecognizeSimultaneously(a)
private fun shouldHandlerBeCancelledBy(handler: GestureHandler<*>, other: GestureHandler<*>): Boolean {
if (!handler.hasCommonPointers(other)) {
// if two handlers share no common pointer one can never trigger cancel for the other
return false
}
if (canRunSimultaneously(handler, other)) {
// if handlers are allowed to run simultaneously, when first activates second can still remain
// in began state
return false
}
return if (handler !== other &&
(handler.isAwaiting || handler.state == GestureHandler.STATE_ACTIVE)) {
// in every other case as long as the handler is about to be activated or already in active
// state, we delegate the decision to the implementation of GestureHandler#shouldBeCancelledBy
handler.shouldBeCancelledBy(other)
} else true
}
private fun isFinished(state: Int) =
state == GestureHandler.STATE_CANCELLED
|| state == GestureHandler.STATE_FAILED
|| state == GestureHandler.STATE_END
}
}
| mit | f1e3634429e45bd6822f2cec70c476d0 | 37.256228 | 147 | 0.68107 | 4.901961 | false | false | false | false |
Zeyad-37/RxRedux | app/src/main/java/com/zeyad/rxredux/screens/User.kt | 1 | 513 | package com.zeyad.rxredux.screens
import android.os.Parcelable
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import kotlinx.android.parcel.Parcelize
@Parcelize
open class User(@PrimaryKey
var login: String = "",
var id: Long = 0,
var avatarUrl: String = "") : RealmObject(), Parcelable {
companion object {
const val LOGIN = "login"
private const val ID = "id"
private const val AVATAR_URL = "avatar_url"
}
}
| apache-2.0 | d9da4ca58805dca7345d184df2236d22 | 26 | 73 | 0.637427 | 4.384615 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/ScriptTemplatesFromDependenciesProvider.kt | 1 | 10198 | // 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.script
import com.intellij.ProjectTopics
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.*
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.FileTypeIndex
import com.intellij.util.indexing.DumbModeAccessType
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.allScope
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionSourceAsContributor
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.core.script.loadDefinitionsFromTemplatesByPaths
import org.jetbrains.kotlin.scripting.definitions.SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.definitions.getEnvironment
import java.io.File
import java.nio.file.Path
import java.util.concurrent.Callable
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.script.experimental.host.ScriptingHostConfiguration
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
class ScriptTemplatesFromDependenciesProvider(private val project: Project) : ScriptDefinitionSourceAsContributor {
private val logger = Logger.getInstance(ScriptTemplatesFromDependenciesProvider::class.java)
override val id = "ScriptTemplatesFromDependenciesProvider"
override fun isReady(): Boolean = _definitions != null
override val definitions: Sequence<ScriptDefinition>
get() {
definitionsLock.withLock {
_definitions?.let { return it.asSequence() }
}
forceStartUpdate = false
asyncRunUpdateScriptTemplates()
return emptySequence()
}
init {
val connection = project.messageBus.connect()
connection.subscribe(
ProjectTopics.PROJECT_ROOTS,
object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
if (project.isInitialized) {
forceStartUpdate = true
asyncRunUpdateScriptTemplates()
}
}
},
)
}
private fun asyncRunUpdateScriptTemplates() {
definitionsLock.withLock {
if (!forceStartUpdate && _definitions != null) return
}
if (inProgress.compareAndSet(false, true)) {
loadScriptDefinitions()
}
}
@Volatile
private var _definitions: List<ScriptDefinition>? = null
private val definitionsLock = ReentrantLock()
private var oldTemplates: TemplatesWithCp? = null
private data class TemplatesWithCp(
val templates: List<String>,
val classpath: List<Path>,
)
private val inProgress = AtomicBoolean(false)
@Volatile
private var forceStartUpdate = false
private fun loadScriptDefinitions() {
if (project.isDefault) {
return onEarlyEnd()
}
if (logger.isDebugEnabled) {
logger.debug("async script definitions update started")
}
val task = object : Task.Backgroundable(
project, KotlinBundle.message("kotlin.script.lookup.definitions"), false
) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
val pluginDisposable = KotlinPluginDisposable.getInstance(project)
val (templates, classpath) =
ReadAction.nonBlocking(Callable {
DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode(ThrowableComputable {
val files = mutableSetOf<VirtualFile>()
FileTypeIndex.processFiles(ScriptDefinitionMarkerFileType, {
indicator.checkCanceled()
files.add(it)
true
}, project.allScope())
getTemplateClassPath(files, indicator)
})
})
.expireWith(pluginDisposable)
.wrapProgress(indicator)
.executeSynchronously() ?: return onEarlyEnd()
try {
indicator.checkCanceled()
if (pluginDisposable.disposed || !inProgress.get() || templates.isEmpty()) return onEarlyEnd()
val newTemplates = TemplatesWithCp(templates.toList(), classpath.toList())
if (!inProgress.get() || newTemplates == oldTemplates) return onEarlyEnd()
if (logger.isDebugEnabled) {
logger.debug("script templates found: $newTemplates")
}
oldTemplates = newTemplates
val hostConfiguration = ScriptingHostConfiguration(defaultJvmScriptingHostConfiguration) {
getEnvironment {
mapOf(
"projectRoot" to (project.basePath ?: project.baseDir.canonicalPath)?.let(::File),
)
}
}
val newDefinitions = loadDefinitionsFromTemplatesByPaths(
templateClassNames = newTemplates.templates,
templateClasspath = newTemplates.classpath,
baseHostConfiguration = hostConfiguration,
)
indicator.checkCanceled()
if (logger.isDebugEnabled) {
logger.debug("script definitions found: ${newDefinitions.joinToString()}")
}
val needReload = definitionsLock.withLock {
if (newDefinitions != _definitions) {
_definitions = newDefinitions
return@withLock true
}
return@withLock false
}
if (needReload) {
ScriptDefinitionsManager.getInstance(project).reloadDefinitionsBy(this@ScriptTemplatesFromDependenciesProvider)
}
} finally {
inProgress.set(false)
}
}
}
ProgressManager.getInstance().runProcessWithProgressAsynchronously(
task,
BackgroundableProcessIndicator(task)
)
}
private fun onEarlyEnd() {
definitionsLock.withLock {
_definitions = emptyList()
}
inProgress.set(false)
}
// public for tests
fun getTemplateClassPath(files: Collection<VirtualFile>, indicator: ProgressIndicator): Pair<Collection<String>, Collection<Path>> {
val rootDirToTemplates: MutableMap<VirtualFile, MutableList<VirtualFile>> = hashMapOf()
for (file in files) {
val dir = file.parent?.parent?.parent?.parent?.parent ?: continue
rootDirToTemplates.getOrPut(dir) { arrayListOf() }.add(file)
}
val templates = linkedSetOf<String>()
val classpath = linkedSetOf<Path>()
rootDirToTemplates.forEach { (root, templateFiles) ->
if (logger.isDebugEnabled) {
logger.debug("root matching SCRIPT_DEFINITION_MARKERS_PATH found: ${root.path}")
}
val orderEntriesForFile = ProjectFileIndex.getInstance(project).getOrderEntriesForFile(root)
.filter {
indicator.checkCanceled()
if (it is ModuleSourceOrderEntry) {
if (ModuleRootManager.getInstance(it.ownerModule).fileIndex.isInTestSourceContent(root)) {
return@filter false
}
it.getFiles(OrderRootType.SOURCES).contains(root)
} else {
it is LibraryOrSdkOrderEntry && it.getRootFiles(OrderRootType.CLASSES).contains(root)
}
}
.takeIf { it.isNotEmpty() } ?: return@forEach
for (virtualFile in templateFiles) {
templates.add(virtualFile.name.removeSuffix(SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT))
}
// assuming that all libraries are placed into classes roots
// TODO: extract exact library dependencies instead of putting all module dependencies into classpath
// minimizing the classpath needed to use the template by taking cp only from modules with new templates found
// on the other hand the approach may fail if some module contains a template without proper classpath, while
// the other has properly configured classpath, so assuming that the dependencies are set correctly everywhere
for (orderEntry in orderEntriesForFile) {
for (virtualFile in OrderEnumerator.orderEntries(orderEntry.ownerModule).withoutSdk().classesRoots) {
indicator.checkCanceled()
val localVirtualFile = VfsUtil.getLocalFile(virtualFile)
localVirtualFile.fileSystem.getNioPath(localVirtualFile)?.let(classpath::add)
}
}
}
return templates to classpath
}
} | apache-2.0 | 2955147d6866700f44cf6f5a12154ce9 | 41.67364 | 158 | 0.616984 | 6.135981 | false | false | false | false |
google/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/FileInDirectorySourceNames.kt | 1 | 3936 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.ide.impl
import com.intellij.openapi.util.io.FileUtil
import com.intellij.workspaceModel.ide.CustomModuleEntitySource
import com.intellij.workspaceModel.ide.JpsFileDependentEntitySource
import com.intellij.workspaceModel.ide.JpsFileEntitySource
import com.intellij.workspaceModel.ide.JpsImportedEntitySource
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.ArtifactEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.FacetEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity
/**
* This class is used to reuse [JpsFileEntitySource.FileInDirectory] instances when project is synchronized with JPS files after loading
* storage from binary cache.
*/
class FileInDirectorySourceNames private constructor(entitiesBySource: Map<EntitySource, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>>) {
private val mainEntityToSource: Map<Pair<Class<out WorkspaceEntity>, String>, JpsFileEntitySource.FileInDirectory>
init {
val sourcesMap = HashMap<Pair<Class<out WorkspaceEntity>, String>, JpsFileEntitySource.FileInDirectory>()
for ((source, entities) in entitiesBySource) {
val (type, entityName) = when {
ModuleEntity::class.java in entities -> ModuleEntity::class.java to (entities.getValue(ModuleEntity::class.java).first() as ModuleEntity).name
FacetEntity::class.java in entities -> ModuleEntity::class.java to (entities.getValue(FacetEntity::class.java).first() as FacetEntity).module.name
LibraryEntity::class.java in entities -> LibraryEntity::class.java to (entities.getValue(LibraryEntity::class.java).first() as LibraryEntity).name
ArtifactEntity::class.java in entities -> ArtifactEntity::class.java to (entities.getValue(ArtifactEntity::class.java).first() as ArtifactEntity).name
else -> null to null
}
if (type != null && entityName != null) {
val fileName = when {
// At external storage libs and artifacts store in its own file and at [JpsLibrariesExternalFileSerializer]/[JpsArtifactEntitiesSerializer]
// we can distinguish them only by directly entity name
(type == LibraryEntity::class.java || type == ArtifactEntity::class.java) && (source as? JpsImportedEntitySource)?.storedExternally == true -> entityName
// Module file stored at external and internal modules.xml has .iml file extension
type == ModuleEntity::class.java -> "$entityName.iml"
// In internal store (i.e. under `.idea` folder) each library or artifact has its own file, and we can distinguish them only by file name
else -> FileUtil.sanitizeFileName(entityName) + ".xml"
}
sourcesMap[type to fileName] = getInternalFileSource(source) as JpsFileEntitySource.FileInDirectory
}
}
mainEntityToSource = sourcesMap
}
fun findSource(entityClass: Class<out WorkspaceEntity>, fileName: String): JpsFileEntitySource.FileInDirectory? =
mainEntityToSource[entityClass to fileName]
companion object {
fun from(storage: EntityStorage) = FileInDirectorySourceNames(
storage.entitiesBySource { getInternalFileSource(it) is JpsFileEntitySource.FileInDirectory }
)
fun empty() = FileInDirectorySourceNames(emptyMap())
private fun getInternalFileSource(source: EntitySource) = when (source) {
is JpsFileDependentEntitySource -> source.originalSource
is CustomModuleEntitySource -> source.internalSource
is JpsFileEntitySource -> source
else -> null
}
}
}
| apache-2.0 | 89da45d252957f362e2fc0102f9a2522 | 57.746269 | 163 | 0.764482 | 5.206349 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/gradle/projectStructureDSL.kt | 1 | 20106 | // 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.gradle
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.*
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtil
import org.intellij.lang.annotations.Language
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.jps.util.JpsPathUtil
import org.jetbrains.kotlin.config.ExternalSystemTestRunTask
import org.jetbrains.kotlin.idea.base.facet.externalSystemTestRunTasks
import org.jetbrains.kotlin.idea.base.facet.isHMPPEnabled
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.gradleJava.configuration.kotlinGradleProjectDataOrFail
import org.jetbrains.kotlin.idea.gradleTooling.KotlinImportingDiagnostic
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.utils.addToStdlib.filterIsInstanceWithChecker
import org.jetbrains.plugins.gradle.util.GradleUtil
import java.io.File
import kotlin.test.fail
class MessageCollector {
private val builder = StringBuilder()
fun report(message: String) {
builder.append(message).append("\n\n")
}
fun check() {
val message = builder.toString()
if (message.isNotEmpty()) {
fail("\n\n" + message)
}
}
}
class ProjectInfo(
project: Project,
internal val projectPath: String,
internal val exhaustiveModuleList: Boolean,
internal val exhaustiveSourceSourceRootList: Boolean,
internal val exhaustiveDependencyList: Boolean,
internal val exhaustiveTestsList: Boolean
) {
val messageCollector = MessageCollector()
private val moduleManager = ModuleManager.getInstance(project)
private val expectedModuleNames = HashSet<String>()
private var allModulesAsserter: (ModuleInfo.() -> Unit)? = null
private val moduleInfos = moduleManager.modules.associateWith { module -> ModuleInfo(module, this) }
@Deprecated("Use .forEachModule instead. This method is error prone and has to be called before 'module(..)' in order to run")
fun allModules(body: ModuleInfo.() -> Unit) {
assert(allModulesAsserter == null)
allModulesAsserter = body
}
fun forEachModule(body: ModuleInfo.() -> Unit) {
moduleInfos.values.forEach { moduleInfo ->
moduleInfo.run(body)
}
}
fun module(name: String, isOptional: Boolean = false, body: ModuleInfo.() -> Unit = {}) {
val module = moduleManager.findModuleByName(name)
if (module == null) {
if (!isOptional) {
messageCollector.report("No module found: '$name' in ${moduleManager.modules.map { it.name }}")
}
return
}
val moduleInfo = moduleInfos.getValue(module)
allModulesAsserter?.let { moduleInfo.it() }
moduleInfo.run(body)
expectedModuleNames += name
}
fun run(body: ProjectInfo.() -> Unit = {}) {
body()
if (exhaustiveModuleList) {
val actualNames = moduleManager.modules.map { it.name }.sorted()
val expectedNames = expectedModuleNames.sorted()
if (actualNames != expectedNames) {
messageCollector.report("Expected module list $expectedNames doesn't match the actual one: $actualNames")
}
}
messageCollector.check()
}
}
class ModuleInfo(val module: Module, val projectInfo: ProjectInfo) {
private val rootModel = module.rootManager
private val expectedDependencyNames = HashSet<String>()
private val expectedDependencies = HashSet<OrderEntry>()
private val expectedSourceRoots = HashSet<String>()
private val expectedExternalSystemTestTasks = ArrayList<ExternalSystemTestRunTask>()
private val assertions = mutableListOf<(ModuleInfo) -> Unit>()
private var mustHaveSdk: Boolean = true
private val sourceFolderByPath by lazy {
rootModel.contentEntries.asSequence()
.flatMap { it.sourceFolders.asSequence() }
.mapNotNull {
val path = it.file?.path ?: return@mapNotNull null
FileUtil.getRelativePath(projectInfo.projectPath, path, '/')!! to it
}
.toMap()
}
fun report(text: String) {
projectInfo.messageCollector.report("Module '${module.name}': $text")
}
private fun checkReport(subject: String, expected: Any?, actual: Any?) {
if (expected != actual) {
report(
"$subject differs:\n" +
"expected $expected\n" +
"actual: $actual"
)
}
}
fun externalSystemTestTask(taskName: String, projectId: String, targetName: String) {
expectedExternalSystemTestTasks.add(ExternalSystemTestRunTask(taskName, projectId, targetName))
}
fun languageVersion(expectedVersion: String) {
val actualVersion = module.languageVersionSettings.languageVersion.versionString
checkReport("Language version", expectedVersion, actualVersion)
}
fun isHMPP(expectedValue: Boolean) {
checkReport("isHMPP", expectedValue, module.isHMPPEnabled)
}
fun targetPlatform(vararg platforms: TargetPlatform) {
val expected = platforms.flatMap { it.componentPlatforms }.toSet()
val actual = runReadAction { module.platform?.componentPlatforms }
if (actual == null) {
report("Actual target platform is null")
return
}
val notFound = expected.subtract(actual)
if (notFound.isNotEmpty()) {
report("These target platforms were not found: " + notFound.joinToString())
}
val unexpected = actual.subtract(expected)
if (unexpected.isNotEmpty()) {
report("Unexpected target platforms found: " + unexpected.joinToString())
}
}
fun apiVersion(expectedVersion: String) {
val actualVersion = module.languageVersionSettings.apiVersion.versionString
checkReport("API version", expectedVersion, actualVersion)
}
fun platform(expectedPlatform: TargetPlatform) {
val actualPlatform = module.platform
checkReport("Platform", expectedPlatform, actualPlatform)
}
fun additionalArguments(arguments: String?) {
val actualArguments = KotlinFacet.get(module)?.configuration?.settings?.compilerSettings?.additionalArguments
checkReport("Additional arguments", arguments, actualArguments)
}
fun kotlinFacetSettingCreated() {
val facet = KotlinFacet.get(module)?.configuration?.settings
if (facet == null) report("KotlinFacetSettings does not exist")
}
fun noLibraryDependency(libraryNameRegex: Regex) {
val libraryEntries = rootModel.orderEntries.filterIsInstance<LibraryOrderEntry>()
.filter { it.libraryName?.matches(libraryNameRegex) == true }
if (libraryEntries.isNotEmpty()) {
report(
"Expected no dependencies for $libraryNameRegex, but found:\n" +
libraryEntries.joinToString(prefix = "[", postfix = "]", separator = ",") { it.presentableName }
)
}
}
fun noLibraryDependency(@Language("regex") libraryNameRegex: String) {
noLibraryDependency(Regex(libraryNameRegex))
}
fun libraryDependency(libraryName: String, scope: DependencyScope, isOptional: Boolean = false) {
libraryDependency(Regex.fromLiteral(libraryName), scope, allowMultiple = false, isOptional)
}
fun libraryDependency(libraryName: Regex, scope: DependencyScope, allowMultiple: Boolean = false, isOptional: Boolean = false) {
val libraryEntries = rootModel.orderEntries.filterIsInstance<LibraryOrderEntry>()
.filter { it.libraryName?.matches(libraryName) == true }
if (!allowMultiple && libraryEntries.size > 1) {
report("Multiple root entries for library $libraryName")
}
if (!isOptional && libraryEntries.isEmpty()) {
val candidate = rootModel.orderEntries
.filterIsInstance<LibraryOrderEntry>()
.sortedWith(Comparator { o1, o2 ->
val o1len = o1?.libraryName?.commonPrefixWith(libraryName.toString())?.length ?: 0
val o2len = o2?.libraryName?.commonPrefixWith(libraryName.toString())?.length ?: 0
o2len - o1len
}).firstOrNull()
val candidateName = candidate?.libraryName
report("Expected library dependency $libraryName, found nothing. Most probably candidate: $candidateName")
}
libraryEntries.forEach { library ->
checkLibrary(library, scope)
}
}
fun libraryDependencyByUrl(classesUrl: String, scope: DependencyScope) {
libraryDependencyByUrl(Regex.fromLiteral(classesUrl), scope)
}
fun libraryDependencyByUrl(classesUrl: Regex, scope: DependencyScope) {
val libraryEntries = rootModel.orderEntries.filterIsInstance<LibraryOrderEntry>().filter { entry ->
entry.library?.getUrls(OrderRootType.CLASSES)?.any { it.matches(classesUrl) } ?: false
}
if (libraryEntries.size > 1) {
report("Multiple entries for library $classesUrl")
}
if (libraryEntries.isEmpty()) {
report("No library dependency found for $classesUrl")
}
checkLibrary(libraryEntries.firstOrNull() ?: return, scope)
}
private fun checkLibrary(libraryEntry: LibraryOrderEntry, scope: DependencyScope) {
checkDependencyScope(libraryEntry, scope)
expectedDependencies += libraryEntry
expectedDependencyNames += libraryEntry.debugText
}
fun moduleDependency(
moduleName: String, scope: DependencyScope,
productionOnTest: Boolean? = null, allowMultiple: Boolean = false, isOptional: Boolean = false
) {
val moduleEntries = rootModel.orderEntries.asList()
.filterIsInstanceWithChecker<ModuleOrderEntry> { it.moduleName == moduleName && it.scope == scope }
// In normal conditions, 'allowMultiple' should always be 'false'. In reality, however, a lot of tests fails because of it.
if (!allowMultiple && moduleEntries.size > 1) {
val allEntries = rootModel.orderEntries.filterIsInstance<ModuleOrderEntry>().joinToString { it.debugText }
report("Multiple order entries found for module $moduleName: $allEntries")
return
}
if (moduleEntries.isEmpty() && !isOptional) {
val allModules = rootModel.orderEntries.filterIsInstance<ModuleOrderEntry>().joinToString { it.debugText }
report("Module dependency ${moduleName} (${scope.displayName}) not found. All module dependencies: $allModules")
}
moduleEntries.forEach { moduleEntry ->
checkDependencyScope(moduleEntry, scope)
checkProductionOnTest(moduleEntry, productionOnTest)
expectedDependencies += moduleEntry
expectedDependencyNames += moduleEntry.debugText
}
}
private val ANY_PACKAGE_PREFIX = "any_package_prefix"
fun sourceFolder(pathInProject: String, rootType: JpsModuleSourceRootType<*>, packagePrefix: String? = ANY_PACKAGE_PREFIX) {
val sourceFolder = sourceFolderByPath[pathInProject]
if (sourceFolder == null) {
report("No source root found: '$pathInProject' among $sourceFolderByPath")
return
}
if (packagePrefix != ANY_PACKAGE_PREFIX && sourceFolder.packagePrefix != packagePrefix) {
report("Source root '$pathInProject': Expected package prefix $packagePrefix, got: ${sourceFolder.packagePrefix}")
}
expectedSourceRoots += pathInProject
val actualRootType = sourceFolder.rootType
if (actualRootType != rootType) {
report("Source root '$pathInProject': Expected root type $rootType, got: $actualRootType")
return
}
}
fun inheritProjectOutput() {
val isInherited = CompilerModuleExtension.getInstance(module)?.isCompilerOutputPathInherited ?: true
if (!isInherited) {
report("Project output is not inherited")
}
}
fun outputPath(pathInProject: String, isProduction: Boolean) {
val compilerModuleExtension = CompilerModuleExtension.getInstance(module)
val url = if (isProduction) compilerModuleExtension?.compilerOutputUrl else compilerModuleExtension?.compilerOutputUrlForTests
val actualPathInProject = url?.let {
FileUtil.getRelativePath(
projectInfo.projectPath,
JpsPathUtil.urlToPath(
it
),
'/'
)
}
checkReport("Output path", pathInProject, actualPathInProject)
}
fun noSdk() {
mustHaveSdk = false
}
inline fun <reified T : KotlinImportingDiagnostic> assertDiagnosticsCount(count: Int) {
val moduleNode = GradleUtil.findGradleModuleData(module)
val diagnostics = moduleNode!!.kotlinGradleProjectDataOrFail.kotlinImportingDiagnosticsContainer!!
val typedDiagnostics = diagnostics.filterIsInstance<T>()
if (typedDiagnostics.size != count) {
projectInfo.messageCollector.report(
"Expected number of ${T::class.java.simpleName} diagnostics $count doesn't match the actual one: ${typedDiagnostics.size}"
)
}
}
fun assertExhaustiveDependencyList() {
assertions += {
val expectedDependencyNames = expectedDependencyNames.sorted()
val actualDependencyNames = rootModel
.orderEntries.asList()
.filterIsInstanceWithChecker<ExportableOrderEntry> { it is ModuleOrderEntry || it is LibraryOrderEntry }
.map { it.debugText }
.sorted()
.distinct()
// increasing readability of log outputs
.sortedBy { if (it in expectedDependencyNames) 0 else 1 }
checkReport("Dependency list", expectedDependencyNames, actualDependencyNames)
}
}
fun assertExhaustiveModuleDependencyList() {
assertions += {
val expectedModuleDependencies = expectedDependencies.filterIsInstance<ModuleOrderEntry>()
.map { it.debugText }.sorted().distinct()
val actualModuleDependencies = rootModel.orderEntries.filterIsInstance<ModuleOrderEntry>()
.map { it.debugText }.sorted().distinct()
// increasing readability of log outputs
.sortedBy { if (it in expectedModuleDependencies) 0 else 1 }
if (actualModuleDependencies != expectedModuleDependencies) {
report(
"Bad Module dependency list for ${module.name}\n" +
"Expected: $expectedModuleDependencies\n" +
"Actual: $actualModuleDependencies"
)
}
}
}
fun assertExhaustiveLibraryDependencyList() {
assertions += {
val expectedLibraryDependencies = expectedDependencies.filterIsInstance<LibraryOrderEntry>()
.map { it.debugText }.sorted().distinct()
val actualLibraryDependencies = rootModel.orderEntries.filterIsInstance<LibraryOrderEntry>()
.map { it.debugText }.sorted().distinct()
// increasing readability of log outputs
.sortedBy { if (it in expectedLibraryDependencies) 0 else 1 }
if (actualLibraryDependencies != expectedLibraryDependencies) {
report(
"Bad Library dependency list for ${module.name}\n" +
"Expected: $expectedLibraryDependencies\n" +
"Actual: $actualLibraryDependencies"
)
}
}
}
fun assertExhaustiveTestsList() {
assertions += {
val actualTasks = module.externalSystemTestRunTasks()
val containsAllTasks = actualTasks.containsAll(expectedExternalSystemTestTasks)
val containsSameTasks = actualTasks == expectedExternalSystemTestTasks
if (!containsAllTasks || !containsSameTasks) {
report("Expected tests list $expectedExternalSystemTestTasks, got: $actualTasks")
}
}
}
fun assertExhaustiveSourceRootList() {
assertions += {
val actualSourceRoots = sourceFolderByPath.keys.sorted()
val expectedSourceRoots = expectedSourceRoots.sorted()
if (actualSourceRoots != expectedSourceRoots) {
report("Expected source root list $expectedSourceRoots, got: $actualSourceRoots")
}
}
}
fun assertNoDependencyInBuildClasses() {
val librariesOnly = OrderEnumerator.orderEntries(module).recursively().librariesOnly()
val rootUrls = librariesOnly.classes().urls + librariesOnly.sources().urls
val dependenciesInBuildDirectory = rootUrls
.map { url -> PathUtil.getLocalPath(VfsUtilCore.urlToPath(url)) }
.filter { path -> "/build/classes/" in path }
if (dependenciesInBuildDirectory.isNotEmpty()) {
report("References dependency in build directory:\n${dependenciesInBuildDirectory.joinToString("\n")}")
}
}
fun run(body: ModuleInfo.() -> Unit = {}) {
body()
assertions.forEach { it.invoke(this) }
assertions.clear()
if (mustHaveSdk && rootModel.sdk == null) {
report("No SDK defined")
}
}
private fun checkDependencyScope(library: ExportableOrderEntry, expectedScope: DependencyScope) {
checkReport("Dependency scope", expectedScope, library.scope)
}
private fun checkProductionOnTest(library: ExportableOrderEntry, productionOnTest: Boolean?) {
if (productionOnTest == null) return
val actualFlag = (library as? ModuleOrderEntry)?.isProductionOnTestDependency
if (actualFlag == null) {
report("Dependency '${library.presentableName}' has no 'productionOnTest' property")
} else {
if (actualFlag != productionOnTest) {
report("Dependency '${library.presentableName}': expected productionOnTest '$productionOnTest', got '$actualFlag'")
}
}
}
init {
if (projectInfo.exhaustiveDependencyList) {
assertExhaustiveDependencyList()
}
if (projectInfo.exhaustiveTestsList) {
assertExhaustiveTestsList()
}
if (projectInfo.exhaustiveSourceSourceRootList) {
assertExhaustiveSourceRootList()
}
}
}
fun checkProjectStructure(
project: Project,
projectPath: String,
exhaustiveModuleList: Boolean = false,
exhaustiveSourceSourceRootList: Boolean = false,
exhaustiveDependencyList: Boolean = false,
exhaustiveTestsList: Boolean = false,
body: ProjectInfo.() -> Unit = {}
) {
ProjectInfo(
project,
projectPath,
exhaustiveModuleList,
exhaustiveSourceSourceRootList,
exhaustiveDependencyList,
exhaustiveTestsList
).run(body)
}
private val ExportableOrderEntry.debugText: String
get() = "$presentableName (${scope.displayName})"
private fun VirtualFile.toIoFile(): File = VfsUtil.virtualToIoFile(this)
| apache-2.0 | f3307bb84f7a152c4c91d60ed74a9b5d | 39.131737 | 138 | 0.657664 | 5.47549 | false | true | false | false |
JetBrains/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/PrivacyNoticeComponent.kt | 1 | 4171 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.diagnostic
import com.intellij.icons.AllIcons
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.BrowserHyperlinkListener
import com.intellij.ui.ColorUtil
import com.intellij.util.ui.HTMLEditorKitBuilder
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JComponent
import javax.swing.JEditorPane
import javax.swing.JLabel
import javax.swing.JPanel
@Deprecated("Use Kotlin UI DSL 2, or com.intellij.diagnostic.PrivacyNotice from Java code")
class PrivacyNoticeComponent(@NlsContexts.Label private val label: String, @NlsContexts.Label private val expandedLabel: String) : JPanel(
GridBagLayout()) {
private val iconLabel: JLabel = JLabel()
private val titleLabel = JLabel()
private val privacyPolicyPane: JEditorPane = JEditorPane()
var expanded: Boolean = true
set(expanded) {
field = expanded
if (expanded) {
titleLabel.text = expandedLabel
iconLabel.icon = AllIcons.General.ArrowDown
privacyPolicyPane.isVisible = true
}
else {
titleLabel.text = label
iconLabel.icon = AllIcons.General.ArrowRight
privacyPolicyPane.isVisible = false
}
}
var privacyPolicy: String
get() = privacyPolicyPane.text
set(@Nls(capitalization = Nls.Capitalization.Sentence) text) {
privacyPolicyPane.text = text
}
init {
background = backgroundColor()
val iconLabelPanel = JPanel(BorderLayout())
useInHeader(iconLabelPanel)
iconLabelPanel.add(iconLabel, BorderLayout.WEST)
val mySeparatorPanel = JPanel()
useInHeader(mySeparatorPanel)
mySeparatorPanel.preferredSize = Dimension(6, 1)
useInHeader(titleLabel)
titleLabel.foreground = titleColor()
titleLabel.font = titleLabel.font.deriveFont((titleLabel.font.size - 1).toFloat())
privacyPolicyPane.isEditable = false
privacyPolicyPane.isFocusable = false
privacyPolicyPane.background = backgroundColor()
privacyPolicyPane.foreground = noticeColor()
privacyPolicyPane.font = privacyPolicyPane.font.deriveFont((privacyPolicyPane.font.size - if (SystemInfo.isWindows) 2 else 1).toFloat())
privacyPolicyPane.editorKit = HTMLEditorKitBuilder.simple()
privacyPolicyPane.border = JBUI.Borders.empty(0, 0, 6, 6)
privacyPolicyPane.addHyperlinkListener(BrowserHyperlinkListener.INSTANCE)
add(mySeparatorPanel, GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL,
JBInsets.emptyInsets(),
0, 0))
add(iconLabelPanel,
GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, JBInsets.emptyInsets(), 0, 0))
add(titleLabel, GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, JBInsets.emptyInsets(), 0,
0))
add(privacyPolicyPane, GridBagConstraints(2, 1, 1, 1, 0.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
JBInsets.emptyInsets(), 0, 0))
expanded = true
}
private fun useInHeader(component: JComponent) {
component.border = JBUI.Borders.empty(6, 0)
component.background = backgroundColor()
component.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
component.addMouseListener(object : MouseAdapter() {
override fun mouseReleased(e: MouseEvent?) {
expanded = !expanded
}
})
}
companion object {
private fun titleColor() = UIUtil.getLabelForeground()
private fun noticeColor() = UIUtil.getContextHelpForeground()
private fun backgroundColor() = ColorUtil.hackBrightness(JBUI.CurrentTheme.CustomFrameDecorations.paneBackground(), 1, 1 / 1.05f)
}
} | apache-2.0 | 82a89d6f76699ab5963ee8d8edb5aad3 | 38.733333 | 143 | 0.716854 | 4.644766 | false | false | false | false |
youdonghai/intellij-community | platform/diff-impl/tests/com/intellij/diff/DiffTestCase.kt | 1 | 7633 | /*
* 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.diff
import com.intellij.diff.comparison.ComparisonManagerImpl
import com.intellij.diff.comparison.iterables.DiffIterableUtil
import com.intellij.diff.util.ThreeSide
import com.intellij.openapi.editor.Document
import com.intellij.openapi.progress.DumbProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.testFramework.UsefulTestCase
import com.intellij.util.containers.HashMap
import com.intellij.util.text.CharSequenceSubSequence
import junit.framework.ComparisonFailure
import java.util.*
import java.util.concurrent.atomic.AtomicLong
abstract class DiffTestCase : UsefulTestCase() {
companion object {
private val DEFAULT_CHAR_COUNT = 12
private val DEFAULT_CHAR_TABLE: Map<Int, Char> = {
val map = HashMap<Int, Char>()
listOf('\n', '\n', '\t', ' ', ' ', '.', '<', '!').forEachIndexed { i, c -> map.put(i, c) }
map
}()
}
val RNG: Random = Random()
private var gotSeedException = false
val INDICATOR: ProgressIndicator = DumbProgressIndicator.INSTANCE
val MANAGER: ComparisonManagerImpl = ComparisonManagerImpl()
override fun setUp() {
super.setUp()
DiffIterableUtil.setVerifyEnabled(true)
}
override fun tearDown() {
DiffIterableUtil.setVerifyEnabled(Registry.`is`("diff.verify.iterable"))
super.tearDown()
}
//
// Assertions
//
fun assertTrue(actual: Boolean, message: String = "") {
assertTrue(message, actual)
}
fun assertFalse(actual: Boolean, message: String = "") {
assertFalse(message, actual)
}
fun assertEquals(expected: Any?, actual: Any?, message: String = "") {
assertEquals(message, expected, actual)
}
fun assertEquals(expected: CharSequence?, actual: CharSequence?, message: String = "") {
if (!StringUtil.equals(expected, actual)) throw ComparisonFailure(message, expected?.toString(), actual?.toString())
}
fun assertEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) {
if (skipLastNewline && !ignoreSpaces) {
assertTrue(StringUtil.equals(chunk1, chunk2) ||
StringUtil.equals(stripNewline(chunk1), chunk2) ||
StringUtil.equals(chunk1, stripNewline(chunk2)))
}
else {
assertTrue(isEqualsCharSequences(chunk1, chunk2, ignoreSpaces))
}
}
fun assertNotEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) {
if (skipLastNewline && !ignoreSpaces) {
assertTrue(!StringUtil.equals(chunk1, chunk2) ||
!StringUtil.equals(stripNewline(chunk1), chunk2) ||
!StringUtil.equals(chunk1, stripNewline(chunk2)))
}
else {
assertFalse(isEqualsCharSequences(chunk1, chunk2, ignoreSpaces))
}
}
fun isEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean): Boolean {
if (ignoreSpaces) {
return StringUtil.equalsIgnoreWhitespaces(chunk1, chunk2)
}
else {
return StringUtil.equals(chunk1, chunk2)
}
}
//
// Parsing
//
fun textToReadableFormat(text: CharSequence?): String {
if (text == null) return "null"
return "'" + text.toString().replace('\n', '*').replace('\t', '+') + "'"
}
fun parseSource(string: CharSequence): String = string.toString().replace('_', '\n')
fun parseMatching(matching: String): BitSet {
val set = BitSet()
matching.filterNot { it == '.' }.forEachIndexed { i, c -> if (c != ' ') set.set(i) }
return set
}
//
// Misc
//
fun getLineCount(document: Document): Int {
return Math.max(1, document.lineCount)
}
infix fun Int.until(a: Int): IntRange = this..a - 1
//
// AutoTests
//
fun doAutoTest(seed: Long, runs: Int, test: (DebugData) -> Unit) {
RNG.setSeed(seed)
var lastSeed: Long = -1
val debugData = DebugData()
for (i in 1..runs) {
if (i % 1000 == 0) println(i)
try {
lastSeed = getCurrentSeed()
test(debugData)
debugData.reset()
}
catch (e: Throwable) {
println("Seed: " + seed)
println("Runs: " + runs)
println("I: " + i)
println("Current seed: " + lastSeed)
debugData.dump()
throw e
}
}
}
fun generateText(maxLength: Int, charCount: Int, predefinedChars: Map<Int, Char>): String {
val length = RNG.nextInt(maxLength + 1)
val builder = StringBuilder(length)
for (i in 1..length) {
val rnd = RNG.nextInt(charCount)
val char = predefinedChars[rnd] ?: (rnd + 97).toChar()
builder.append(char)
}
return builder.toString()
}
fun generateText(maxLength: Int): String {
return generateText(maxLength, DEFAULT_CHAR_COUNT, DEFAULT_CHAR_TABLE)
}
fun getCurrentSeed(): Long {
if (gotSeedException) return -1
try {
val seedField = RNG.javaClass.getDeclaredField("seed")
seedField.isAccessible = true
val seedFieldValue = seedField.get(RNG) as AtomicLong
return seedFieldValue.get() xor 0x5DEECE66DL
}
catch (e: Exception) {
gotSeedException = true
System.err.println("Can't get random seed: " + e.message)
return -1
}
}
private fun stripNewline(text: CharSequence): CharSequence? {
return when (StringUtil.endsWithChar(text, '\n')) {
true -> CharSequenceSubSequence(text, 0, text.length - 1)
false -> null
}
}
class DebugData() {
private val data: MutableList<Pair<String, Any>> = ArrayList()
fun put(key: String, value: Any) {
data.add(Pair(key, value))
}
fun reset() {
data.clear()
}
fun dump() {
data.forEach { println(it.first + ": " + it.second) }
}
}
//
// Helpers
//
open class Trio<out T>(val data1: T, val data2: T, val data3: T) {
companion object {
fun <V> from(f: (ThreeSide) -> V): Trio<V> = Trio(f(ThreeSide.LEFT), f(ThreeSide.BASE), f(ThreeSide.RIGHT))
}
fun <V> map(f: (T) -> V): Trio<V> = Trio(f(data1), f(data2), f(data3))
fun <V> map(f: (T, ThreeSide) -> V): Trio<V> = Trio(f(data1, ThreeSide.LEFT), f(data2, ThreeSide.BASE), f(data3, ThreeSide.RIGHT))
fun forEach(f: (T, ThreeSide) -> Unit): Unit {
f(data1, ThreeSide.LEFT)
f(data2, ThreeSide.BASE)
f(data3, ThreeSide.RIGHT)
}
operator fun invoke(side: ThreeSide): T = side.select(data1, data2, data3) as T
override fun toString(): String {
return "($data1, $data2, $data3)"
}
override fun equals(other: Any?): Boolean {
return other is Trio<*> && other.data1 == data1 && other.data2 == data2 && other.data3 == data3
}
override fun hashCode(): Int {
var h = 0
if (data1 != null) h = h * 31 + data1.hashCode()
if (data2 != null) h = h * 31 + data2.hashCode()
if (data3 != null) h = h * 31 + data3.hashCode()
return h
}
}
} | apache-2.0 | 08c1c08eef812fa1353eaf783d515d33 | 28.474903 | 134 | 0.650334 | 3.944703 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/entity/model/special/PlayalongEntity.kt | 2 | 1932 | package io.github.chrislo27.rhre3.entity.model.special
import com.badlogic.gdx.graphics.Color
import io.github.chrislo27.rhre3.editor.Editor
import io.github.chrislo27.rhre3.entity.model.IStretchable
import io.github.chrislo27.rhre3.entity.model.ModelEntity
import io.github.chrislo27.rhre3.playalong.InputAction
import io.github.chrislo27.rhre3.playalong.PlayalongInput
import io.github.chrislo27.rhre3.playalong.PlayalongMethod
import io.github.chrislo27.rhre3.sfxdb.datamodel.impl.special.PlayalongModel
import io.github.chrislo27.rhre3.theme.Theme
import io.github.chrislo27.rhre3.track.Remix
class PlayalongEntity(remix: Remix, datamodel: PlayalongModel)
: ModelEntity<PlayalongModel>(remix, datamodel), IStretchable {
override val isStretchable: Boolean = datamodel.stretchable
val playalongInput: PlayalongInput get() = datamodel.playalongInput
val playalongMethod: PlayalongMethod get() = datamodel.playalongMethod
override var needsNameTooltip: Boolean
get() = false
set(_) {}
init {
this.bounds.width = datamodel.duration
this.bounds.height = 1f
}
override fun getHoverText(inSelection: Boolean): String? {
return datamodel.pickerName.main
}
override fun getRenderColor(editor: Editor, theme: Theme): Color {
return theme.entities.cue
}
override fun getTextForSemitone(semitone: Int): String {
return playalongInput.displayText
}
override fun copy(remix: Remix): PlayalongEntity {
return PlayalongEntity(remix, datamodel).also {
it.updateBounds {
it.bounds.set([email protected])
}
}
}
override fun onStart() {
}
override fun whilePlaying() {
}
override fun onEnd() {
}
fun getInputAction(): InputAction {
return InputAction(bounds.x, bounds.width, playalongInput, playalongMethod)
}
} | gpl-3.0 | 0c4f308d61f495b3d4e08ca05bda3749 | 29.203125 | 83 | 0.719979 | 4.119403 | false | false | false | false |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/model/PreviewItem.kt | 1 | 3004 | package com.nononsenseapps.feeder.model
import androidx.room.ColumnInfo
import androidx.room.Ignore
import com.nononsenseapps.feeder.db.COL_BOOKMARKED
import com.nononsenseapps.feeder.db.COL_PINNED
import com.nononsenseapps.feeder.db.room.ID_UNSET
import com.nononsenseapps.feeder.util.sloppyLinkToStrictURLNoThrows
import java.net.URI
import java.net.URL
import org.threeten.bp.ZonedDateTime
const val previewColumns = """
feed_items.id AS id, guid, plain_title, plain_snippet, feed_items.image_url, enclosure_link,
author, pub_date, link, unread, feeds.tag AS tag, feeds.id AS feed_id, feeds.title AS feed_title,
feeds.custom_title as feed_customtitle, feeds.url AS feed_url,
feeds.open_articles_with AS feed_open_articles_with, pinned, bookmarked,
feeds.image_url as feed_image_url
"""
data class PreviewItem @Ignore constructor(
var id: Long = ID_UNSET,
var guid: String = "",
@ColumnInfo(name = "plain_title") var plainTitle: String = "",
@ColumnInfo(name = "plain_snippet") var plainSnippet: String = "",
@ColumnInfo(name = "image_url") var imageUrl: String? = null,
@ColumnInfo(name = "enclosure_link") var enclosureLink: String? = null,
var author: String? = null,
@ColumnInfo(name = "pub_date") var pubDate: ZonedDateTime? = null,
var link: String? = null,
var tag: String = "",
var unread: Boolean = true,
@ColumnInfo(name = "feed_id") var feedId: Long? = null,
@ColumnInfo(name = "feed_title") var feedTitle: String = "",
@ColumnInfo(name = "feed_customtitle") var feedCustomTitle: String = "",
@ColumnInfo(name = "feed_url") var feedUrl: URL = sloppyLinkToStrictURLNoThrows(""),
@ColumnInfo(name = "feed_open_articles_with") var feedOpenArticlesWith: String = "",
@ColumnInfo(name = COL_PINNED) var pinned: Boolean = false,
@ColumnInfo(name = COL_BOOKMARKED) var bookmarked: Boolean = false,
@ColumnInfo(name = "feed_image_url") var feedImageUrl: URL? = null,
) {
constructor() : this(id = ID_UNSET)
val feedDisplayTitle: String
get() = if (feedCustomTitle.isBlank()) feedTitle else feedCustomTitle
val enclosureFilename: String?
get() {
if (enclosureLink != null) {
var fname: String? = null
try {
fname = URI(enclosureLink).path.split("/").last()
} catch (e: Exception) {
}
if (fname == null || fname.isEmpty()) {
return null
} else {
return fname
}
}
return null
}
val pubDateString: String?
get() = pubDate?.toString()
val domain: String?
get() {
val l: String? = enclosureLink ?: link
if (l != null) {
try {
return URL(l).host.replace("www.", "")
} catch (e: Throwable) {
}
}
return null
}
}
| gpl-3.0 | 17937ef6987ce188b08cf0928ba16cac | 37.512821 | 101 | 0.610186 | 4.005333 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/cache/personal_deadlines/dao/DeadlinesBannerDaoImpl.kt | 2 | 1164 | package org.stepik.android.cache.personal_deadlines.dao
import android.content.ContentValues
import android.database.Cursor
import org.stepic.droid.storage.dao.DaoBase
import org.stepic.droid.storage.operations.DatabaseOperations
import org.stepik.android.cache.personal_deadlines.structure.DbStructureDeadlinesBanner
import javax.inject.Inject
class DeadlinesBannerDaoImpl
@Inject
constructor(
databaseOperations: DatabaseOperations
) : DaoBase<Long>(databaseOperations), DeadlinesBannerDao {
override fun getDbName(): String =
DbStructureDeadlinesBanner.DEADLINES_BANNER
override fun getDefaultPrimaryColumn(): String =
DbStructureDeadlinesBanner.Columns.COURSE_ID
override fun getDefaultPrimaryValue(persistentObject: Long): String =
persistentObject.toString()
override fun getContentValues(persistentObject: Long): ContentValues =
ContentValues().apply {
put(DbStructureDeadlinesBanner.Columns.COURSE_ID, persistentObject)
}
override fun parsePersistentObject(cursor: Cursor): Long =
cursor.getLong(cursor.getColumnIndex(DbStructureDeadlinesBanner.Columns.COURSE_ID))
} | apache-2.0 | eccab4815f064834571bda37aa3a843f | 36.580645 | 91 | 0.790378 | 5.06087 | false | false | false | false |
zdary/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistoryFilterer.kt | 2 | 12741 | // 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.vcs.log.history
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.UnorderedPair
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.history.VcsCachingHistory
import com.intellij.openapi.vcs.history.VcsFileRevision
import com.intellij.openapi.vcs.history.VcsFileRevisionEx
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.MultiMap
import com.intellij.vcs.log.CommitId
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.VcsLogFilterCollection
import com.intellij.vcs.log.VcsLogStructureFilter
import com.intellij.vcs.log.data.CompressedRefs
import com.intellij.vcs.log.data.DataPack
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.graph.GraphCommit
import com.intellij.vcs.log.graph.GraphCommitImpl
import com.intellij.vcs.log.graph.PermanentGraph
import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl
import com.intellij.vcs.log.history.FileHistoryPaths.fileHistory
import com.intellij.vcs.log.impl.HashImpl
import com.intellij.vcs.log.util.StopWatch
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.util.findBranch
import com.intellij.vcs.log.visible.*
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
internal class FileHistoryFilterer(logData: VcsLogData) : VcsLogFilterer {
private val project = logData.project
private val logProviders = logData.logProviders
private val storage = logData.storage
private val index = logData.index
private val indexDataGetter = index.dataGetter!!
private val vcsLogFilterer = VcsLogFiltererImpl(logProviders, storage, logData.topCommitsCache,
logData.commitDetailsGetter, index)
override fun filter(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> {
val filePath = getFilePath(filters) ?: return vcsLogFilterer.filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
LOG.assertTrue(!filePath.isDirectory)
val root = VcsLogUtil.getActualRoot(project, filePath)!!
return MyWorker(root, filePath, getHash(filters)).filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
}
override fun canFilterEmptyPack(filters: VcsLogFilterCollection): Boolean = true
private inner class MyWorker constructor(private val root: VirtualFile,
private val filePath: FilePath,
private val hash: Hash?) {
fun filter(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> {
val start = System.currentTimeMillis()
if (index.isIndexed(root) && dataPack.isFull) {
val visiblePack = filterWithIndex(dataPack, oldVisiblePack, sortType, filters,
commitCount == CommitCountStage.INITIAL)
LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) + " for computing history for $filePath with index")
if (checkNotEmpty(dataPack, visiblePack, true)) {
return Pair(visiblePack, commitCount)
}
}
ProjectLevelVcsManager.getInstance(project).getVcsFor(root)?.let { vcs ->
if (vcs.vcsHistoryProvider != null) {
return@filter try {
val visiblePack = filterWithProvider(vcs, dataPack, sortType, filters)
LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) +
" for computing history for $filePath with history provider")
checkNotEmpty(dataPack, visiblePack, false)
Pair(visiblePack, commitCount)
}
catch (e: VcsException) {
LOG.error(e)
vcsLogFilterer.filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
}
}
}
LOG.warn("Could not find vcs or history provider for file $filePath")
return vcsLogFilterer.filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
}
private fun checkNotEmpty(dataPack: DataPack, visiblePack: VisiblePack, withIndex: Boolean): Boolean {
if (!dataPack.isFull) {
LOG.debug("Data pack is not full while computing file history for $filePath\n" +
"Found ${visiblePack.visibleGraph.visibleCommitCount} commits")
return true
}
else if (visiblePack.visibleGraph.visibleCommitCount == 0) {
LOG.warn("Empty file history from ${if (withIndex) "index" else "provider"} for $filePath")
return false
}
return true
}
@Throws(VcsException::class)
private fun filterWithProvider(vcs: AbstractVcs,
dataPack: DataPack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection): VisiblePack {
val revisionNumber = if (hash != null) VcsLogUtil.convertToRevisionNumber(hash) else null
val revisions = VcsCachingHistory.collect(vcs, filePath, revisionNumber)
if (revisions.isEmpty()) return VisiblePack.EMPTY
if (dataPack.isFull) {
val pathsMap = HashMap<Int, MaybeDeletedFilePath>()
for (revision in revisions) {
val revisionEx = revision as VcsFileRevisionEx
pathsMap[getIndex(revision)] = MaybeDeletedFilePath(revisionEx.path, revisionEx.isDeleted)
}
val visibleGraph = vcsLogFilterer.createVisibleGraph(dataPack, sortType, null, pathsMap.keys)
return VisiblePack(dataPack, visibleGraph, false, filters, FileHistory(pathsMap))
}
val commits = ArrayList<GraphCommit<Int>>(revisions.size)
val pathsMap = HashMap<Int, MaybeDeletedFilePath>()
for (revision in revisions) {
val index = getIndex(revision)
val revisionEx = revision as VcsFileRevisionEx
pathsMap[index] = MaybeDeletedFilePath(revisionEx.path, revisionEx.isDeleted)
commits.add(GraphCommitImpl.createCommit(index, emptyList(), revision.getRevisionDate().time))
}
val refs = getFilteredRefs(dataPack)
val fakeDataPack = DataPack.build(commits, refs, mapOf(root to logProviders[root]), storage, false)
val visibleGraph = vcsLogFilterer.createVisibleGraph(fakeDataPack, sortType, null,
null/*no need to filter here, since we do not have any extra commits in this pack*/)
return VisiblePack(fakeDataPack, visibleGraph, false, filters, FileHistory(pathsMap))
}
private fun getFilteredRefs(dataPack: DataPack): Map<VirtualFile, CompressedRefs> {
val compressedRefs = dataPack.refsModel.allRefsByRoot[root] ?: CompressedRefs(emptySet(), storage)
return mapOf(Pair(root, compressedRefs))
}
private fun getIndex(revision: VcsFileRevision): Int {
return storage.getCommitIndex(HashImpl.build(revision.revisionNumber.asString()), root)
}
private fun filterWithIndex(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
isInitial: Boolean): VisiblePack {
val oldFileHistory = oldVisiblePack.fileHistory
if (isInitial) {
return filterWithIndex(dataPack, filters, sortType, oldFileHistory.commitToRename,
FileHistory(emptyMap(), processedAdditionsDeletions = oldFileHistory.processedAdditionsDeletions))
}
val renames = collectRenamesFromProvider(oldFileHistory)
return filterWithIndex(dataPack, filters, sortType, renames.union(oldFileHistory.commitToRename), oldFileHistory)
}
private fun filterWithIndex(dataPack: DataPack,
filters: VcsLogFilterCollection,
sortType: PermanentGraph.SortType,
oldRenames: MultiMap<UnorderedPair<Int>, Rename>,
oldFileHistory: FileHistory): VisiblePack {
val matchingHeads = vcsLogFilterer.getMatchingHeads(dataPack.refsModel, setOf(root), filters)
val data = indexDataGetter.createFileHistoryData(filePath).build(oldRenames)
val permanentGraph = dataPack.permanentGraph
if (permanentGraph !is PermanentGraphImpl) {
val visibleGraph = vcsLogFilterer.createVisibleGraph(dataPack, sortType, matchingHeads, data.getCommits())
return VisiblePack(dataPack, visibleGraph, false, filters, FileHistory(data.buildPathsMap()))
}
if (matchingHeads.matchesNothing() || data.isEmpty) {
return VisiblePack.EMPTY
}
val commit = (hash ?: getHead(dataPack))?.let { storage.getCommitIndex(it, root) }
val historyBuilder = FileHistoryBuilder(commit, filePath, data, oldFileHistory)
val visibleGraph = permanentGraph.createVisibleGraph(sortType, matchingHeads, data.getCommits(), historyBuilder)
val fileHistory = historyBuilder.fileHistory
return VisiblePack(dataPack, visibleGraph, fileHistory.unmatchedAdditionsDeletions.isNotEmpty(), filters, fileHistory)
}
private fun collectRenamesFromProvider(fileHistory: FileHistory): MultiMap<UnorderedPair<Int>, Rename> {
if (fileHistory.unmatchedAdditionsDeletions.isEmpty()) return MultiMap.empty()
val start = System.currentTimeMillis()
val handler = logProviders[root]?.fileHistoryHandler ?: return MultiMap.empty()
val renames = fileHistory.unmatchedAdditionsDeletions.mapNotNull {
val parentHash = storage.getCommitId(it.parent)!!.hash
val childHash = storage.getCommitId(it.child)!!.hash
if (it.isAddition) handler.getRename(root, it.filePath, parentHash, childHash)
else handler.getRename(root, it.filePath, childHash, parentHash)
}.map { r ->
Rename(r.filePath1, r.filePath2, storage.getCommitIndex(r.hash1, root), storage.getCommitIndex(r.hash2, root))
}
LOG.debug("Found ${renames.size} renames for ${fileHistory.unmatchedAdditionsDeletions.size} addition-deletions in " +
StopWatch.formatTime(System.currentTimeMillis() - start))
val result = MultiMap<UnorderedPair<Int>, Rename>()
renames.forEach { result.putValue(it.commits, it) }
return result
}
private fun getHead(pack: DataPack): Hash? {
return pack.refsModel.findBranch(VcsLogUtil.HEAD, root)?.commitHash
}
}
private fun getHash(filters: VcsLogFilterCollection): Hash? {
val fileHistoryFilter = getStructureFilter(filters) as? VcsLogFileHistoryFilter
if (fileHistoryFilter != null) {
return fileHistoryFilter.hash
}
val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER)
return revisionFilter?.heads?.singleOrNull()?.hash
}
companion object {
private val LOG = logger<FileHistoryFilterer>()
private fun getStructureFilter(filters: VcsLogFilterCollection) = filters.detailsFilters.singleOrNull() as? VcsLogStructureFilter
fun getFilePath(filters: VcsLogFilterCollection): FilePath? {
val filter = getStructureFilter(filters) ?: return null
return filter.files.singleOrNull()
}
@JvmStatic
fun createFilters(path: FilePath,
revision: Hash?,
root: VirtualFile,
showAllBranches: Boolean): VcsLogFilterCollection {
val fileFilter = VcsLogFileHistoryFilter(path, revision)
val revisionFilter = when {
showAllBranches -> null
revision != null -> VcsLogFilterObject.fromCommit(CommitId(revision, root))
else -> VcsLogFilterObject.fromBranch(VcsLogUtil.HEAD)
}
return VcsLogFilterObject.collection(fileFilter, revisionFilter)
}
}
}
private fun <K : Any?, V : Any?> MultiMap<K, V>.union(map: MultiMap<K, V>): MultiMap<K, V> {
if (isEmpty) {
return map
}
if (map.isEmpty) {
return this
}
val result = MultiMap<K, V>()
result.putAllValues(this)
result.putAllValues(map)
return result
}
| apache-2.0 | 8d5b25f8914a00797afbf83b1ace8ce4 | 45.5 | 143 | 0.692489 | 5.342138 | false | false | false | false |
tsagi/JekyllForAndroid | app/src/main/java/gr/tsagi/jekyllforandroid/app/data/PostsContract.kt | 2 | 6181 | package gr.tsagi.jekyllforandroid.app.data
import android.annotation.SuppressLint
import android.content.ContentUris
import android.net.Uri
import android.provider.BaseColumns
import android.util.Log
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
/**
\* Created with IntelliJ IDEA.
\* User: jchanghong
\* Date: 8/8/14
\* Time: 19:47
\*/
object PostsContract {
private val LOG_TAG = PostsContract::class.java.simpleName
// The "Content authority" is a name for the entire content provider, similar to the
// relationship between a domain name and its website. A convenient string to use for the
// content authority is the package name for the app, which is guaranteed to be unique on the
// device.
val CONTENT_AUTHORITY = "gr.tsagi.jekyllforandroid"
// Use CONTENT_AUTHORITY to create the base of all URI's which apps will use to contact
// the content provider.
val BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY)!!
// Possible paths (appended to base content URI for possible URI's)
// For instance, content://com.example.android.sunshine.app/weather/ is a valid path for
// looking at weather data. content://gr.tsagi.jekyllforandroid/givemeroot/ will fail,
// as the ContentProvider hasn't been given any information on what to do with "givemeroot".
// At least, let's hope not. Don't be that dev, reader. Don't be that dev.
val PATH_POSTS = "posts"
val PATH_TAGS = "tags"
val PATH_CATEGORIES = "categories"
// Format used for storing dates in the database. ALso used for converting those strings
// back into date objects for comparison/processing.
val DATE_FORMAT = "yyyyMMdd"
/**
* Converts Date class to a string representation, used for easy comparison and database lookup.
* @param date The input date
* *
* @return a DB-friendly representation of the date, using the format defined in DATE_FORMAT.
*/
fun getDbDateString(date: Date): String {
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
@SuppressLint("SimpleDateFormat")
val sdf = SimpleDateFormat(DATE_FORMAT)
return sdf.format(date)
}
/**
* Converts a dateText to a long Unix time representation
* @param dateText the input date string
* *
* @return the Date object
*/
fun getDateFromDb(dateText: String): Date {
@SuppressLint("SimpleDateFormat")
val dbDateFormat = SimpleDateFormat(DATE_FORMAT)
try {
return dbDateFormat.parse(dateText)
} catch (e: ParseException) {
// e.printStackTrace();
return Date()
}
}
/* Inner class that defines the table contents of the location table */
class PostEntry : BaseColumns {
companion object {
val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_POSTS).build()
val CONTENT_TYPE =
"vnd.android.cursor.dir/$CONTENT_AUTHORITY/$PATH_POSTS"
// Table name
val TABLE_NAME = "posts"
val COLUMN_POST_ID = "id"
val COLUMN_TITLE = "title"
val COLUMN_DRAFT = "draft"
val COLUMN_DATETEXT = "date"
val COLUMN_CONTENT = "content"
fun buildPostUri(id: Long): Uri {
return ContentUris.withAppendedId(CONTENT_URI, id)
}
fun buildPublishedPosts(): Uri {
return CONTENT_URI.buildUpon().appendPath("published").build()
}
fun buildDraftPosts(): Uri {
return CONTENT_URI.buildUpon().appendPath("drafts").build()
}
fun buildPostFromId(status: String, postId: String): Uri {
Log.d(LOG_TAG, "postId: " + postId)
return CONTENT_URI.buildUpon().appendPath(status).appendPath(postId)
.build()
}
fun getStatusFromUri(uri: Uri): String {
return uri.pathSegments[1]
}
fun getIdFromUri(uri: Uri): String {
return uri.pathSegments[2]
}
}
}
// public static final class TagEntry implements BaseColumns {
//
// public static final Uri CONTENT_URI =
// BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build();
//
// public static final String CONTENT_TYPE =
// "vnd.android.cursor.dir/" + CONTENT_AUTHORITY + "/" + PATH_TAGS;
// public static final String CONTENT_ITEM_TYPE =
// "vnd.android.cursor.item/" + CONTENT_AUTHORITY + "/" + PATH_TAGS;
//
// // Table name
// public static final String TABLE_NAME = "tags";
//
// public static final String COLUMN_TAG = "tag";
// public static final String COLUMN_POST_ID = "post_id";
//
// public static Uri buildTagUri(long id) {
// return ContentUris.withAppendedId(CONTENT_URI, id);
// }
// }
// public static final class CategoryEntry implements BaseColumns {
//
// public static final Uri CONTENT_URI =
// BASE_CONTENT_URI.buildUpon().appendPath(PATH_CATEGORIES).build();
//
// public static final String CONTENT_TYPE =
// "vnd.android.cursor.dir/" + CONTENT_AUTHORITY + "/" + PATH_CATEGORIES;
// public static final String CONTENT_ITEM_TYPE =
// "vnd.android.cursor.item/" + CONTENT_AUTHORITY + "/" + PATH_CATEGORIES;
//
// // Table name
// public static final String TABLE_NAME = "categories";
//
// public static final String COLUMN_CATEGORY = "category";
// public static final String COLUMN_POST_ID = "post_id";
//
// public static Uri buildCategoryUri(long id) {
// return ContentUris.withAppendedId(CONTENT_URI, id);
// }
// }
}
| gpl-2.0 | 5ef040600cdd7952cc75f9aa300813a5 | 36.23494 | 100 | 0.60233 | 4.488744 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/jvmStatic/propertyAccessorsObject.kt | 2 | 353 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
var result = "fail 2"
object Foo {
@JvmStatic
private val a = "OK"
val b = { a }
val c = Runnable { result = a }
}
fun box(): String {
if (Foo.b() != "OK") return "fail 1"
Foo.c.run()
return result
}
| apache-2.0 | b0f9fe8432a6e24a32c00cbf68fb8585 | 15.809524 | 72 | 0.586402 | 3.238532 | false | false | false | false |
android/xAnd11 | core/src/android/java/org/monksanctum/xand11/core/GraphicsContext.kt | 1 | 6142 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.monksanctum.xand11.core
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Paint.Cap
import android.graphics.Paint.Join
import android.graphics.Xfermode
import org.monksanctum.xand11.errors.ValueError
import org.monksanctum.xand11.fonts.FontManager
actual class GraphicsContext actual constructor(private val mId: Int) {
actual var drawable: Int = 0
actual var function: Byte = 0
actual var planeMask: Int = 0
actual var foreground = -0x1000000
actual var background = -0x1
actual var lineWidth: Int = 0 // Card16
actual var lineStyle: Byte = 0
actual var capStyle: Byte = 0
actual var joinStyle: Byte = 0
actual var fillStyle: Byte = 0
actual var fillRule: Byte = 0
actual var tile: Int = 0 // PIXMAP
actual var stipple: Int = 0 // PIXMAP
actual var tileStippleX: Int = 0 // Card16
actual var tileStippleY: Int = 0 // Card16
actual var font: Int = 0 // Font
actual var subwindowMode: Byte = 0
actual var graphicsExposures: Boolean = false
actual var clipX: Int = 0 // Card16
actual var clipY: Int = 0 // Card16
actual var clipMask: Int = 0 // PIXMAP
actual var dashOffset: Int = 0 // Card16
actual var dashes: Byte = 0
actual var arcMode: Byte = 0
var paint: Paint? = null
private set
private var p: Path? = null
fun applyToPaint(p: Paint): Paint {
p.color = foreground or -0x1000000
p.strokeWidth = lineWidth.toFloat()
when (function) {
FUNCTION_XOR -> {
}
else -> p.xfermode = null
}// TODO: Support this.
when (capStyle) {
CAP_STYLE_NOT_LAST, CAP_STYLE_BUTT -> p.strokeCap = Cap.BUTT
CAP_STYLE_ROUND -> p.strokeCap = Cap.ROUND
CAP_STYLE_PROJECTING -> p.strokeCap = Cap.SQUARE
}
when (joinStyle) {
JOIN_STYLE_MITER -> p.strokeJoin = Join.MITER
JOIN_STYLE_ROUND -> p.strokeJoin = Join.ROUND
JOIN_STYLE_BEVEL -> p.strokeJoin = Join.BEVEL
}
return p
}
@Throws(ValueError::class)
actual fun createPaint(fontManager: FontManager) {
val f = fontManager.getFont(font)
paint = applyToPaint(if (f != null) f.paint else Paint())
}
actual fun setClipPath(p: Path) {
this.p = p
}
actual fun init(c: Canvas) {
if (p != null) {
c.clipPath(p!!)
}
}
actual fun drawRect(canvas: Canvas, rect: Rect, stroke: Boolean) {
val p = Paint(paint)
p!!.style = if (stroke) Paint.Style.STROKE else Paint.Style.FILL
canvas.drawRect(rect, p)
}
actual fun drawText(canvas: Canvas, f: Font?, v: String, x: Int, y: Int, bounds: Rect) {
var paint = f?.paint?.let { applyToPaint(it) } ?: this.paint;
Font.getTextBounds(v, paint!!, x, y, bounds)
paint.color = foreground
if (DEBUG) Platform.logd("GraphicsContext", "Draw text $v $x $y")
canvas.drawText(v, x.toFloat(), y.toFloat(), paint)
}
actual fun drawPath(canvas: Canvas, p: Path, fill: Boolean) {
val paint = Paint(this.paint)
paint!!.style = if (fill) Paint.Style.FILL else Paint.Style.STROKE
canvas.drawPath(p, paint)
}
actual fun drawLine(canvas: Canvas, fx: Float, fy: Float, sx: Float, sy: Float) {
canvas.drawLine(fx, fy, sx, sy, paint!!)
}
actual fun drawBitmap(canvas: Canvas, bitmap: Bitmap, x: Float, y: Float) {
canvas.drawBitmap(bitmap, x, y, paint)
}
companion object {
val FUNCTION_CLEAR: Byte = 0
val FUNCTION_AND: Byte = 1
val FUNCTION_AND_REVERSE: Byte = 2
val FUNCTION_COPY: Byte = 3
val FUNCTION_AND_INVERTED: Byte = 4
val FUNCTION_NOOP: Byte = 5
val FUNCTION_XOR: Byte = 6
val FUNCTION_OR: Byte = 7
val FUNCTION_NOR: Byte = 8
val FUNCTION_EQUIV: Byte = 9
val FUNCTION_INVERT: Byte = 10
val FUNCTION_OR_REVERSE: Byte = 11
val FUNCTION_COPY_INVERTED: Byte = 12
val FUNCTION_OR_INVERTED: Byte = 13
val FUNCTION_NAND: Byte = 14
val FUNCTION_SET: Byte = 15
val STYLE_SOLID: Byte = 0
val STYLE_ON_OFF_DASH: Byte = 1
val STYLE_DOUBLE_DASH: Byte = 2
val CAP_STYLE_NOT_LAST: Byte = 0
val CAP_STYLE_BUTT: Byte = 1
val CAP_STYLE_ROUND: Byte = 2
val CAP_STYLE_PROJECTING: Byte = 3
val JOIN_STYLE_MITER: Byte = 0
val JOIN_STYLE_ROUND: Byte = 1
val JOIN_STYLE_BEVEL: Byte = 2
val FILL_STYLE_SOLID: Byte = 0
val FILL_STYLE_TILED: Byte = 1
val FILL_STYLE_STIPPLED: Byte = 2
val FILL_STYLE_OPAQUE_STIPPLED: Byte = 3
val FILL_RULE_EVEN_ODD: Byte = 0
val FILL_RULE_WINDING: Byte = 1
val SUBWINDOW_MODE_CLIP_BY_CHILDREN: Byte = 0
val SUBWINDOW_MODE_INCLUDE_INFERIORS: Byte = 1
val ARC_MODE_CHORD: Byte = 0
val ARC_MODE_PIE_SLICE: Byte = 1
}
}
actual fun Canvas.drawBitmap(context: GraphicsContext?, bitmap: Bitmap, src: Rect, bounds: Rect) {
drawBitmap(bitmap, src, bounds, context?.paint ?: Paint())
}
actual fun Canvas.drawBitmap(context: GraphicsContext?, bitmap: Bitmap, x: Float, y: Float) {
drawBitmap(bitmap, x, y, context?.paint ?: Paint())
}
| apache-2.0 | 68e5b1946a94859b641063bfef8709c0 | 32.505618 | 98 | 0.605177 | 3.841151 | false | false | false | false |
smmribeiro/intellij-community | java/java-impl/src/com/intellij/lang/java/request/createFieldFromUsage.kt | 12 | 5015 | // 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.
@file:JvmName("CreateFieldFromUsage")
package com.intellij.lang.java.request
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFieldFromUsageFix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.java.JavaLanguage
import com.intellij.lang.java.actions.toJavaClassOrNull
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmClassKind
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.CreateFieldRequest
import com.intellij.lang.jvm.actions.EP_NAME
import com.intellij.lang.jvm.actions.groupActionsByType
import com.intellij.psi.*
import com.intellij.psi.impl.PsiImplUtil
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil.resolveClassInClassTypeOnly
import com.intellij.psi.util.PsiUtilCore
import com.intellij.psi.util.parentOfType
fun generateActions(ref: PsiReferenceExpression): List<IntentionAction> {
if (!checkReference(ref)) return emptyList()
val fieldRequests = CreateFieldRequests(ref).collectRequests()
val extensions = EP_NAME.extensions
return fieldRequests.flatMap { (clazz, request) ->
extensions.flatMap { ext ->
ext.createAddFieldActions(clazz, request)
}
}.groupActionsByType(JavaLanguage.INSTANCE)
}
private fun checkReference(ref: PsiReferenceExpression): Boolean {
if (ref.referenceName == null) return false
if (ref.parent is PsiMethodCallExpression) return false
return true
}
private class CreateFieldRequests(val myRef: PsiReferenceExpression) {
private val requests = LinkedHashMap<JvmClass, CreateFieldRequest>()
fun collectRequests(): Map<JvmClass, CreateFieldRequest> {
doCollectRequests()
return requests
}
private fun addRequest(target: JvmClass, request: CreateFieldRequest) {
if (target is PsiElement) {
PsiUtilCore.ensureValid(target)
}
requests[target] = request
}
private fun doCollectRequests() {
val qualifier = myRef.qualifierExpression
if (qualifier != null) {
val instanceClass = resolveClassInClassTypeOnly(qualifier.type)
if (instanceClass != null) {
processHierarchy(instanceClass)
}
else {
val staticClass = (qualifier as? PsiJavaCodeReferenceElement)?.resolve() as? PsiClass
if (staticClass != null) {
processClass(staticClass, true)
}
}
}
else {
val baseClass = resolveClassInClassTypeOnly(PsiImplUtil.getSwitchLabel(myRef)?.enclosingSwitchStatement?.expression?.type)
if (baseClass != null) {
processHierarchy(baseClass)
}
else {
processOuterAndImported()
}
}
}
private fun processHierarchy(baseClass: PsiClass) {
for (clazz in hierarchy(baseClass)) {
processClass(clazz, false)
}
}
private fun processOuterAndImported() {
val inStaticContext = myRef.isInStaticContext()
for (outerClass in collectOuterClasses(myRef)) {
processClass(outerClass, inStaticContext)
}
for (imported in collectOnDemandImported(myRef)) {
processClass(imported, true)
}
}
private fun processClass(target: JvmClass, staticContext: Boolean) {
if (!staticContext && target.classKind in STATIC_ONLY) return
val modifiers = mutableSetOf<JvmModifier>()
if (staticContext) {
modifiers += JvmModifier.STATIC
}
if (shouldCreateFinalField(myRef, target)) {
modifiers += JvmModifier.FINAL
}
val ownerClass = myRef.parentOfType<PsiClass>()
val visibility = computeVisibility(myRef.project, ownerClass, target)
if (visibility != null) {
modifiers += visibility
}
val request = CreateFieldFromJavaUsageRequest(
modifiers = modifiers,
reference = myRef,
useAnchor = ownerClass != null && PsiTreeUtil.isAncestor(target.toJavaClassOrNull(), ownerClass, false),
isConstant = false
)
addRequest(target, request)
}
}
private val STATIC_ONLY = arrayOf(JvmClassKind.INTERFACE, JvmClassKind.ANNOTATION)
/**
* Given unresolved unqualified reference,
* this reference could be resolved into static member if some class which has it's members imported.
*
* @return list of classes from static on demand imports.
*/
private fun collectOnDemandImported(place: PsiElement): List<JvmClass> {
val containingFile = place.containingFile as? PsiJavaFile ?: return emptyList()
val importList = containingFile.importList ?: return emptyList()
val onDemandImports = importList.importStaticStatements.filter { it.isOnDemand }
if (onDemandImports.isEmpty()) return emptyList()
return onDemandImports.mapNotNull { it.resolveTargetClass() }
}
private fun shouldCreateFinalField(ref: PsiReferenceExpression, targetClass: JvmClass): Boolean {
val javaClass = targetClass.toJavaClassOrNull() ?: return false
return CreateFieldFromUsageFix.shouldCreateFinalMember(ref, javaClass)
}
| apache-2.0 | af898c475c0c9a8006b2a68f6d28193d | 33.349315 | 140 | 0.742971 | 4.652134 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifySuperTypeFix.kt | 1 | 5669 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.analysis.analyzeAsReplacement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.completion.KotlinIdeaCompletionBundle
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
class SpecifySuperTypeFix(
superExpression: KtSuperExpression,
private val superTypes: List<String>
) : KotlinQuickFixAction<KtSuperExpression>(superExpression) {
override fun getText() = KotlinIdeaCompletionBundle.message("intention.name.specify.supertype")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
if (editor == null) return
val superExpression = element ?: return
CommandProcessor.getInstance().runUndoTransparentAction {
if (superTypes.size == 1) {
superExpression.specifySuperType(superTypes.first())
} else {
JBPopupFactory
.getInstance()
.createListPopup(createListPopupStep(superExpression, superTypes))
.showInBestPositionFor(editor)
}
}
}
private fun KtSuperExpression.specifySuperType(superType: String) {
project.executeWriteCommand(KotlinIdeaCompletionBundle.message("intention.name.specify.supertype")) {
val label = this.labelQualifier?.text ?: ""
replace(KtPsiFactory(this).createExpression("super<$superType>$label"))
}
}
private fun createListPopupStep(superExpression: KtSuperExpression, superTypes: List<String>): ListPopupStep<*> {
return object : BaseListPopupStep<String>(KotlinIdeaCompletionBundle.message("popup.title.choose.supertype"), superTypes) {
override fun isAutoSelectionEnabled() = false
override fun onChosen(selectedValue: String, finalChoice: Boolean): PopupStep<*>? {
if (finalChoice) {
superExpression.specifySuperType(selectedValue)
}
return PopupStep.FINAL_CHOICE
}
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtSuperExpression>? {
val superExpression = diagnostic.psiElement as? KtSuperExpression ?: return null
val qualifiedExpression = superExpression.getQualifiedExpressionForReceiver() ?: return null
val selectorExpression = qualifiedExpression.selectorExpression ?: return null
val containingClassOrObject = superExpression.getStrictParentOfType<KtClassOrObject>() ?: return null
val superTypeListEntries = containingClassOrObject.superTypeListEntries
if (superTypeListEntries.isEmpty()) return null
val context = superExpression.analyze(BodyResolveMode.PARTIAL)
val superTypes = superTypeListEntries.mapNotNull {
val typeReference = it.typeReference ?: return@mapNotNull null
val typeElement = it.typeReference?.typeElement ?: return@mapNotNull null
val kotlinType = context[BindingContext.TYPE, typeReference] ?: return@mapNotNull null
typeElement to kotlinType
}
if (superTypes.size != superTypeListEntries.size) return null
val psiFactory = KtPsiFactory(superExpression)
val superTypesForSuperExpression = superTypes.mapNotNull { (typeElement, kotlinType) ->
if (superTypes.any { it.second != kotlinType && it.second.isSubtypeOf(kotlinType) }) return@mapNotNull null
val fqName = kotlinType.fqName ?: return@mapNotNull null
val fqNameAsString = fqName.asString()
val name = if (typeElement.text.startsWith(fqNameAsString)) fqNameAsString else fqName.shortName().asString()
val newQualifiedExpression = psiFactory.createExpressionByPattern("super<$name>.$0", selectorExpression, reformat = false)
val newContext = newQualifiedExpression.analyzeAsReplacement(qualifiedExpression, context)
if (newQualifiedExpression.getResolvedCall(newContext)?.resultingDescriptor == null) return@mapNotNull null
if (newContext.diagnostics.noSuppression().forElement(newQualifiedExpression).isNotEmpty()) return@mapNotNull null
name
}
if (superTypesForSuperExpression.isEmpty()) return null
return SpecifySuperTypeFix(superExpression, superTypesForSuperExpression)
}
}
}
| apache-2.0 | c4c768e96abae910f5714603148f8ed4 | 52.481132 | 158 | 0.718116 | 5.772912 | false | false | false | false |
smmribeiro/intellij-community | plugins/devkit/devkit-kotlin-tests/testData/codeInsight/MyLanguage.kt | 13 | 720 | @file:Suppress("unused")
class MyLanguage : com.intellij.lang.Language {
companion object {
const val PREFIX = "My"
const val ID = "LanguageID"
const val ANONYMOUS_ID = "AnonymousLanguageID"
val ANONYMOUS_LANGUAGE: com.intellij.lang.Language = object : MySubLanguage(PREFIX + ANONYMOUS_ID, "MyDisplayName") {}
}
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor() : super(PREFIX + ID)
private open class MySubLanguage(id: String?, private val myName: String) : com.intellij.lang.Language(id!!) {
override fun getDisplayName(): String = myName
}
abstract class AbstractLanguage protected constructor() : com.intellij.lang.Language("AbstractLanguageIDMustNotBeVisible")
} | apache-2.0 | 37872598125bc50950b8916888372bff | 35.05 | 124 | 0.738889 | 4.311377 | false | false | false | false |
android/compose-samples | Crane/app/src/main/java/androidx/compose/samples/crane/calendar/Month.kt | 1 | 1446 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.samples.crane.calendar
import androidx.compose.foundation.layout.Row
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.clearAndSetSemantics
@Composable
internal fun MonthHeader(modifier: Modifier = Modifier, month: String, year: String) {
Row(modifier = modifier.clearAndSetSemantics { }) {
Text(
modifier = Modifier.weight(1f),
text = month,
style = MaterialTheme.typography.h6
)
Text(
modifier = Modifier.align(Alignment.CenterVertically),
text = year,
style = MaterialTheme.typography.caption
)
}
}
| apache-2.0 | 9a4e04a7c8b9feeb662e24709f4a56a7 | 34.268293 | 86 | 0.7213 | 4.490683 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/TaskFormActivity.kt | 1 | 22264 | package com.habitrpg.android.habitica.ui.activities
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Handler
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.CheckBox
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatCheckBox
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.view.children
import androidx.core.view.forEachIndexed
import androidx.core.widget.NestedScrollView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.TagRepository
import com.habitrpg.android.habitica.data.TaskRepository
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.extensions.OnChangeTextWatcher
import com.habitrpg.android.habitica.extensions.addCancelButton
import com.habitrpg.android.habitica.extensions.dpToPx
import com.habitrpg.android.habitica.extensions.getThemeColor
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.helpers.TaskAlarmManager
import com.habitrpg.android.habitica.models.Tag
import com.habitrpg.android.habitica.models.tasks.HabitResetOption
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.android.habitica.models.user.Stats
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import com.habitrpg.android.habitica.ui.views.tasks.form.*
import io.reactivex.functions.Consumer
import io.realm.RealmList
import java.util.*
import javax.inject.Inject
class TaskFormActivity : BaseActivity() {
private var userScrolled: Boolean = false
private var isSaving: Boolean = false
@Inject
lateinit var userRepository: UserRepository
@Inject
lateinit var taskRepository: TaskRepository
@Inject
lateinit var tagRepository: TagRepository
@Inject
lateinit var taskAlarmManager: TaskAlarmManager
private val toolbar: Toolbar by bindView(R.id.toolbar)
private val scrollView: NestedScrollView by bindView(R.id.scroll_view)
private val upperTextWrapper: LinearLayout by bindView(R.id.upper_text_wrapper)
private val textEditText: EditText by bindView(R.id.text_edit_text)
private val notesEditText: EditText by bindView(R.id.notes_edit_text)
private val habitScoringButtons: HabitScoringButtonsView by bindView(R.id.habit_scoring_buttons)
private val checklistTitleView: TextView by bindView(R.id.checklist_title)
private val checklistContainer: ChecklistContainer by bindView(R.id.checklist_container)
private val habitResetStreakTitleView: TextView by bindView(R.id.habit_reset_streak_title)
private val habitResetStreakButtons: HabitResetStreakButtons by bindView(R.id.habit_reset_streak_buttons)
private val taskSchedulingTitleView: TextView by bindView(R.id.scheduling_title)
private val taskSchedulingControls: TaskSchedulingControls by bindView(R.id.scheduling_controls)
private val adjustStreakWrapper: ViewGroup by bindView(R.id.adjust_streak_wrapper)
private val adjustStreakTitleView: TextView by bindView(R.id.adjust_streak_title)
private val habitAdjustPositiveStreakView: EditText by bindView(R.id.habit_adjust_positive_streak)
private val habitAdjustNegativeStreakView: EditText by bindView(R.id.habit_adjust_negative_streak)
private val remindersTitleView: TextView by bindView(R.id.reminders_title)
private val remindersContainer: ReminderContainer by bindView(R.id.reminders_container)
private val taskDifficultyTitleView: TextView by bindView(R.id.task_difficulty_title)
private val taskDifficultyButtons: TaskDifficultyButtons by bindView(R.id.task_difficulty_buttons)
private val statWrapper: ViewGroup by bindView(R.id.stat_wrapper)
private val statStrengthButton: TextView by bindView(R.id.stat_strength_button)
private val statIntelligenceButton: TextView by bindView(R.id.stat_intelligence_button)
private val statConstitutionButton: TextView by bindView(R.id.stat_constitution_button)
private val statPerceptionButton: TextView by bindView(R.id.stat_perception_button)
private val rewardValueTitleView: TextView by bindView(R.id.reward_value_title)
private val stepperValueFormView: StepperValueFormView by bindView(R.id.reward_value)
private val tagsTitleView: TextView by bindView(R.id.tags_title)
private val tagsWrapper: LinearLayout by bindView(R.id.tags_wrapper)
private var isCreating = true
private var isChallengeTask = false
private var usesTaskAttributeStats = false
private var task: Task? = null
private var taskType: String = ""
private var tags = listOf<Tag>()
private var preselectedTags: ArrayList<String>? = null
private var hasPreselectedTags = false
private var selectedStat = Stats.STRENGTH
set(value) {
field = value
setSelectedAttribute(value)
}
private var canSave: Boolean = false
private var tintColor: Int = 0
set(value) {
field = value
upperTextWrapper.setBackgroundColor(value)
taskDifficultyButtons.tintColor = value
habitScoringButtons.tintColor = value
habitResetStreakButtons.tintColor = value
taskSchedulingControls.tintColor = value
supportActionBar?.setBackgroundDrawable(ColorDrawable(value))
updateTagViewsColors()
}
override fun getLayoutResId(): Int {
return R.layout.activity_task_form
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
val bundle = intent.extras ?: return
val taskId = bundle.getString(TASK_ID_KEY)
forcedTheme = if (taskId != null) {
val taskValue = bundle.getDouble(TASK_VALUE_KEY)
when {
taskValue < -20 -> "maroon"
taskValue < -10 -> "red"
taskValue < -1 -> "orange"
taskValue < 1 -> "yellow"
taskValue < 5 -> "green"
taskValue < 10 -> "teal"
else -> "blue"
}
} else {
"purple"
}
super.onCreate(savedInstanceState)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
tintColor = getThemeColor(R.attr.taskFormTint)
isChallengeTask = bundle.getBoolean(IS_CHALLENGE_TASK, false)
taskType = bundle.getString(TASK_TYPE_KEY) ?: Task.TYPE_HABIT
preselectedTags = bundle.getStringArrayList(SELECTED_TAGS_KEY)
compositeSubscription.add(tagRepository.getTags()
.map { tagRepository.getUnmanagedCopy(it) }
.subscribe(Consumer {
tags = it
setTagViews()
}, RxErrorHandler.handleEmptyError()))
compositeSubscription.add(userRepository.getUser().subscribe(Consumer {
usesTaskAttributeStats = it.preferences?.allocationMode == "taskbased"
configureForm()
}, RxErrorHandler.handleEmptyError()))
textEditText.addTextChangedListener(OnChangeTextWatcher { _, _, _, _ ->
checkCanSave()
})
statStrengthButton.setOnClickListener { selectedStat = Stats.STRENGTH }
statIntelligenceButton.setOnClickListener { selectedStat = Stats.INTELLIGENCE }
statConstitutionButton.setOnClickListener { selectedStat = Stats.CONSTITUTION }
statPerceptionButton.setOnClickListener { selectedStat = Stats.PERCEPTION }
scrollView.setOnTouchListener { view, event ->
userScrolled = view == scrollView && (event.action == MotionEvent.ACTION_SCROLL || event.action == MotionEvent.ACTION_MOVE)
return@setOnTouchListener false
}
scrollView.setOnScrollChangeListener { _: NestedScrollView?, _: Int, _: Int, _: Int, _: Int ->
if (userScrolled) {
dismissKeyboard()
}
}
title = ""
when {
taskId != null -> {
isCreating = false
compositeSubscription.add(taskRepository.getUnmanagedTask(taskId).firstElement().subscribe(Consumer {
task = it
//tintColor = ContextCompat.getColor(this, it.mediumTaskColor)
fillForm(it)
}, RxErrorHandler.handleEmptyError()))
}
bundle.containsKey(PARCELABLE_TASK) -> {
isCreating = false
task = bundle.getParcelable(PARCELABLE_TASK)
task?.let { fillForm(it) }
}
else -> title = getString(R.string.create_task, getString(when (taskType) {
Task.TYPE_DAILY -> R.string.daily
Task.TYPE_TODO -> R.string.todo
Task.TYPE_REWARD -> R.string.reward
else -> R.string.habit
}))
}
configureForm()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
if (isCreating) {
menuInflater.inflate(R.menu.menu_task_create, menu)
} else {
menuInflater.inflate(R.menu.menu_task_edit, menu)
}
menu.findItem(R.id.action_save).isEnabled = canSave
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.action_save -> saveTask()
R.id.action_delete -> deleteTask()
android.R.id.home -> {
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun checkCanSave() {
val newCanSave = textEditText.text.isNotBlank()
if (newCanSave != canSave) {
invalidateOptionsMenu()
}
canSave = newCanSave
}
private fun configureForm() {
val habitViewsVisibility = if (taskType == Task.TYPE_HABIT) View.VISIBLE else View.GONE
habitScoringButtons.visibility = habitViewsVisibility
habitResetStreakTitleView.visibility = habitViewsVisibility
habitResetStreakButtons.visibility = habitViewsVisibility
habitAdjustNegativeStreakView.visibility = habitViewsVisibility
val habitDailyVisibility = if (taskType == Task.TYPE_DAILY || taskType == Task.TYPE_HABIT) View.VISIBLE else View.GONE
adjustStreakTitleView.visibility = habitDailyVisibility
adjustStreakWrapper.visibility = habitDailyVisibility
if (taskType == Task.TYPE_HABIT) {
habitAdjustPositiveStreakView.hint = getString(R.string.positive_habit_form)
} else {
habitAdjustPositiveStreakView.hint = getString(R.string.streak)
}
val todoDailyViewsVisibility = if (taskType == Task.TYPE_DAILY || taskType == Task.TYPE_TODO) View.VISIBLE else View.GONE
checklistTitleView.visibility = if (isChallengeTask) View.GONE else todoDailyViewsVisibility
checklistContainer.visibility = if (isChallengeTask) View.GONE else todoDailyViewsVisibility
remindersTitleView.visibility = if (isChallengeTask) View.GONE else todoDailyViewsVisibility
remindersContainer.visibility = if (isChallengeTask) View.GONE else todoDailyViewsVisibility
remindersContainer.taskType = taskType
taskSchedulingTitleView.visibility = todoDailyViewsVisibility
taskSchedulingControls.visibility = todoDailyViewsVisibility
taskSchedulingControls.taskType = taskType
val rewardHideViews = if (taskType == Task.TYPE_REWARD) View.GONE else View.VISIBLE
taskDifficultyTitleView.visibility = rewardHideViews
taskDifficultyButtons.visibility = rewardHideViews
val rewardViewsVisibility = if (taskType == Task.TYPE_REWARD) View.VISIBLE else View.GONE
rewardValueTitleView.visibility = rewardViewsVisibility
stepperValueFormView.visibility = rewardViewsVisibility
tagsTitleView.visibility = if (isChallengeTask) View.GONE else View.VISIBLE
tagsWrapper.visibility = if (isChallengeTask) View.GONE else View.VISIBLE
statWrapper.visibility = if (usesTaskAttributeStats) View.VISIBLE else View.GONE
if (isCreating) {
adjustStreakTitleView.visibility = View.GONE
adjustStreakWrapper.visibility = View.GONE
}
}
private fun setTagViews() {
tagsWrapper.removeAllViews()
val padding = 20.dpToPx(this)
for (tag in tags) {
val view = CheckBox(this)
view.setPadding(padding, view.paddingTop, view.paddingRight, view.paddingBottom)
view.text = tag.name
if (preselectedTags?.contains(tag.id) == true) {
view.isChecked = true
}
tagsWrapper.addView(view)
}
setAllTagSelections()
updateTagViewsColors()
}
private fun setAllTagSelections() {
if (hasPreselectedTags) {
tags.forEachIndexed { index, tag ->
val view = tagsWrapper.getChildAt(index) as? CheckBox
view?.isChecked = task?.tags?.find { it.id == tag.id } != null
}
} else {
hasPreselectedTags = true
}
}
private fun fillForm(task: Task) {
if (!task.isValid) {
return
}
canSave = true
textEditText.setText(task.text)
notesEditText.setText(task.notes)
taskDifficultyButtons.selectedDifficulty = task.priority
when (taskType) {
Task.TYPE_HABIT -> {
habitScoringButtons.isPositive = task.up ?: false
habitScoringButtons.isNegative = task.down ?: false
task.frequency?.let {
if (it.isNotBlank()) {
habitResetStreakButtons.selectedResetOption = HabitResetOption.valueOf(it.toUpperCase(Locale.US))
}
}
habitAdjustPositiveStreakView.setText((task.counterUp ?: 0).toString())
habitAdjustNegativeStreakView.setText((task.counterDown ?: 0).toString())
habitAdjustPositiveStreakView.visibility = if (task.up == true) View.VISIBLE else View.GONE
habitAdjustNegativeStreakView.visibility = if (task.down == true) View.VISIBLE else View.GONE
if (task.up != true && task.down != true) {
adjustStreakTitleView.visibility = View.GONE
adjustStreakWrapper.visibility = View.GONE
}
}
Task.TYPE_DAILY -> {
taskSchedulingControls.startDate = task.startDate ?: Date()
taskSchedulingControls.everyX = task.everyX ?: 1
task.repeat?.let { taskSchedulingControls.weeklyRepeat = it }
taskSchedulingControls.daysOfMonth = task.getDaysOfMonth()
taskSchedulingControls.weeksOfMonth = task.getWeeksOfMonth()
habitAdjustPositiveStreakView.setText((task.streak ?: 0).toString())
taskSchedulingControls.frequency = task.frequency ?: Task.FREQUENCY_DAILY
}
Task.TYPE_TODO -> taskSchedulingControls.dueDate = task.dueDate
Task.TYPE_REWARD -> stepperValueFormView.value = task.value
}
if (taskType == Task.TYPE_DAILY || taskType == Task.TYPE_TODO) {
task.checklist?.let { checklistContainer.checklistItems = it }
remindersContainer.taskType = taskType
task.reminders?.let { remindersContainer.reminders = it }
}
task.attribute?.let { selectedStat = it }
setAllTagSelections()
}
private fun setSelectedAttribute(attributeName: String) {
if (!usesTaskAttributeStats) return
configureStatsButton(statStrengthButton, attributeName == Stats.STRENGTH )
configureStatsButton(statIntelligenceButton, attributeName == Stats.INTELLIGENCE )
configureStatsButton(statConstitutionButton, attributeName == Stats.CONSTITUTION )
configureStatsButton(statPerceptionButton, attributeName == Stats.PERCEPTION )
}
private fun configureStatsButton(button: TextView, isSelected: Boolean) {
button.background.setTint(if (isSelected) tintColor else ContextCompat.getColor(this, R.color.taskform_gray))
val textColorID = if (isSelected) R.color.white else R.color.gray_100
button.setTextColor(ContextCompat.getColor(this, textColorID))
}
private fun updateTagViewsColors() {
tagsWrapper.children.forEach { view ->
val tagView = view as? AppCompatCheckBox
val colorStateList = ColorStateList(
arrayOf(intArrayOf(-android.R.attr.state_checked), // unchecked
intArrayOf(android.R.attr.state_checked) // checked
),
intArrayOf(ContextCompat.getColor(this, R.color.gray_400), tintColor)
)
tagView?.buttonTintList = colorStateList
}
}
private fun saveTask() {
if (isSaving) {
return
}
isSaving = true
var thisTask = task
if (thisTask == null) {
thisTask = Task()
thisTask.type = taskType
thisTask.dateCreated = Date()
} else {
if (!thisTask.isValid) return
}
thisTask.text = textEditText.text.toString()
thisTask.notes = notesEditText.text.toString()
thisTask.priority = taskDifficultyButtons.selectedDifficulty
if (usesTaskAttributeStats) {
thisTask.attribute = selectedStat
}
if (taskType == Task.TYPE_HABIT) {
thisTask.up = habitScoringButtons.isPositive
thisTask.down = habitScoringButtons.isNegative
thisTask.frequency = habitResetStreakButtons.selectedResetOption.value
if (habitAdjustPositiveStreakView.text.isNotEmpty()) thisTask.counterUp = habitAdjustPositiveStreakView.text.toString().toIntCatchOverflow()
if (habitAdjustNegativeStreakView.text.isNotEmpty()) thisTask.counterDown = habitAdjustNegativeStreakView.text.toString().toIntCatchOverflow()
} else if (taskType == Task.TYPE_DAILY) {
thisTask.startDate = taskSchedulingControls.startDate
thisTask.everyX = taskSchedulingControls.everyX
thisTask.frequency = taskSchedulingControls.frequency
thisTask.repeat = taskSchedulingControls.weeklyRepeat
thisTask.setDaysOfMonth(taskSchedulingControls.daysOfMonth)
thisTask.setWeeksOfMonth(taskSchedulingControls.weeksOfMonth)
if (habitAdjustPositiveStreakView.text.isNotEmpty()) thisTask.streak = habitAdjustPositiveStreakView.text.toString().toIntCatchOverflow()
} else if (taskType == Task.TYPE_TODO) {
thisTask.dueDate = taskSchedulingControls.dueDate
} else if (taskType == Task.TYPE_REWARD) {
thisTask.value = stepperValueFormView.value
}
val resultIntent = Intent()
resultIntent.putExtra(TASK_TYPE_KEY, taskType)
if (!isChallengeTask) {
if (taskType == Task.TYPE_DAILY || taskType == Task.TYPE_TODO) {
thisTask.checklist = checklistContainer.checklistItems
thisTask.reminders = remindersContainer.reminders
}
thisTask.tags = RealmList()
tagsWrapper.forEachIndexed { index, view ->
val tagView = view as? CheckBox
if (tagView?.isChecked == true) {
thisTask.tags?.add(tags[index])
}
}
if (isCreating) {
taskRepository.createTaskInBackground(thisTask)
} else {
taskRepository.updateTaskInBackground(thisTask)
}
if (thisTask.type == Task.TYPE_DAILY || thisTask.type == Task.TYPE_TODO) {
taskAlarmManager.scheduleAlarmsForTask(thisTask)
}
} else {
resultIntent.putExtra(PARCELABLE_TASK, thisTask)
}
val mainHandler = Handler(this.mainLooper)
mainHandler.postDelayed({
setResult(Activity.RESULT_OK, resultIntent)
dismissKeyboard()
finish()
}, 500)
}
private fun deleteTask() {
val alert = HabiticaAlertDialog(this)
alert.setTitle(R.string.are_you_sure)
alert.addButton(R.string.delete_task, true) { _, _ ->
if (task?.isValid != true) return@addButton
task?.id?.let { taskRepository.deleteTask(it).subscribe(Consumer { }, RxErrorHandler.handleEmptyError()) }
dismissKeyboard()
finish()
}
alert.addCancelButton()
alert.show()
}
private fun dismissKeyboard() {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
val currentFocus = currentFocus
if (currentFocus != null && !habitAdjustPositiveStreakView.isFocused && !habitAdjustNegativeStreakView.isFocused) {
imm?.hideSoftInputFromWindow(currentFocus.windowToken, 0)
}
}
companion object {
val SELECTED_TAGS_KEY = "selectedTags"
const val TASK_ID_KEY = "taskId"
const val TASK_VALUE_KEY = "taskValue"
const val USER_ID_KEY = "userId"
const val TASK_TYPE_KEY = "type"
const val IS_CHALLENGE_TASK = "isChallengeTask"
const val PARCELABLE_TASK = "parcelable_task"
// in order to disable the event handler in MainActivity
const val SET_IGNORE_FLAG = "ignoreFlag"
}
}
private fun String.toIntCatchOverflow(): Int? {
return try {
toInt()
} catch (e: NumberFormatException) {
0
}
}
| gpl-3.0 | 5e35a23224d756748ae393a5f424538d | 42.826772 | 154 | 0.667355 | 5.146556 | false | false | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHPRToolWindowTabsManager.kt | 1 | 3813 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest
import com.intellij.dvcs.repo.VcsRepositoryMappingListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryChangeListener
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.plugins.github.authentication.accounts.AccountRemovedListener
import org.jetbrains.plugins.github.authentication.accounts.AccountTokenChangedListener
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings
import org.jetbrains.plugins.github.util.CollectionDelta
import org.jetbrains.plugins.github.util.GitRemoteUrlCoordinates
import org.jetbrains.plugins.github.util.GithubGitHelper
import kotlin.properties.Delegates.observable
@Service
internal class GHPRToolWindowTabsManager(private val project: Project) {
private val gitHelper = GithubGitHelper.getInstance()
private val settings = GithubPullRequestsProjectUISettings.getInstance(project)
private val contentManager by lazy(LazyThreadSafetyMode.NONE) {
GHPRToolWindowsTabsContentManager(project, ChangesViewContentManager.getInstance(project))
}
private var remoteUrls by observable(setOf<GitRemoteUrlCoordinates>()) { _, oldValue, newValue ->
val delta = CollectionDelta(oldValue, newValue)
for (item in delta.removedItems) {
contentManager.removeTab(item)
}
for (item in delta.newItems) {
contentManager.addTab(item, Disposable {
//means that tab closed by user
if (gitHelper.getPossibleRemoteUrlCoordinates(project).contains(item)) settings.addHiddenUrl(item.url)
ApplicationManager.getApplication().invokeLater(::updateRemoteUrls) { project.isDisposed }
})
}
}
@CalledInAwt
fun showTab(remoteUrl: GitRemoteUrlCoordinates) {
settings.removeHiddenUrl(remoteUrl.url)
updateRemoteUrls()
contentManager.focusTab(remoteUrl)
}
private fun updateRemoteUrls() {
remoteUrls = gitHelper.getPossibleRemoteUrlCoordinates(project).filter {
!settings.getHiddenUrls().contains(it.url)
}.toSet()
}
class RemoteUrlsListener(private val project: Project)
: VcsRepositoryMappingListener, GitRepositoryChangeListener {
override fun mappingChanged() = runInEdt(project) { updateRemotes(project) }
override fun repositoryChanged(repository: GitRepository) = runInEdt(project) { updateRemotes(project) }
}
class AccountsListener : AccountRemovedListener, AccountTokenChangedListener {
override fun accountRemoved(removedAccount: GithubAccount) = updateRemotes()
override fun tokenChanged(account: GithubAccount) = updateRemotes()
private fun updateRemotes() = runInEdt {
for (project in ProjectManager.getInstance().openProjects) {
updateRemotes(project)
}
}
}
companion object {
private inline fun runInEdt(project: Project, crossinline runnable: () -> Unit) {
val application = ApplicationManager.getApplication()
if (application.isDispatchThread) runnable()
else application.invokeLater({ runnable() }) { project.isDisposed }
}
private fun updateRemotes(project: Project) = project.service<GHPRToolWindowTabsManager>().updateRemoteUrls()
}
}
| apache-2.0 | 06db924e2058e5196621ba7d66e7f232 | 41.842697 | 140 | 0.79124 | 4.977807 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/detectProperties/FieldUsagesInFactoryMethods.kt | 4 | 293 | internal class C(val arg1: Int) {
var arg2 = 0
var arg3 = 0
constructor(arg1: Int, arg2: Int, arg3: Int) : this(arg1) {
this.arg2 = arg2
this.arg3 = arg3
}
constructor(arg1: Int, arg2: Int) : this(arg1) {
this.arg2 = arg2
arg3 = 0
}
} | apache-2.0 | 6ab1eb667ff5c816b1addf3492a9d5d9 | 18.6 | 63 | 0.525597 | 2.817308 | false | false | false | false |
pokk/SSFM | app/src/main/kotlin/taiwan/no1/app/ssfm/features/playlist/PlaylistDetailFragment.kt | 1 | 6011 | package taiwan.no1.app.ssfm.features.playlist
import android.os.Bundle
import android.support.v7.widget.helper.ItemTouchHelper
import android.transition.TransitionInflater
import com.devrapid.kotlinknifer.recyclerview.WrapContentLinearLayoutManager
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import org.jetbrains.anko.bundleOf
import taiwan.no1.app.ssfm.App
import taiwan.no1.app.ssfm.R
import taiwan.no1.app.ssfm.databinding.FragmentPlaylistDetailBinding
import taiwan.no1.app.ssfm.features.base.AdvancedFragment
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.HELPER_ADD_TO_PLAYLIST
import taiwan.no1.app.ssfm.misc.extension.recyclerview.DataInfo
import taiwan.no1.app.ssfm.misc.extension.recyclerview.PlaylistItemAdapter
import taiwan.no1.app.ssfm.misc.extension.recyclerview.firstFetch
import taiwan.no1.app.ssfm.misc.extension.recyclerview.refreshAndChangeList
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.playerHelper
import taiwan.no1.app.ssfm.misc.widgets.recyclerviews.ItemTouchViewmodelCallback
import taiwan.no1.app.ssfm.misc.widgets.recyclerviews.SimpleItemTouchHelperCallback
import taiwan.no1.app.ssfm.misc.widgets.recyclerviews.adapters.BaseDataBindingAdapter
import taiwan.no1.app.ssfm.models.entities.PlaylistEntity
import taiwan.no1.app.ssfm.models.entities.PlaylistItemEntity
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemCase
import javax.inject.Inject
/**
* @author jieyi
* @since 11/14/17
*/
class PlaylistDetailFragment : AdvancedFragment<PlaylistDetailFragmentViewModel, FragmentPlaylistDetailBinding>() {
//region Static initialization
companion object Factory {
// The key name of the fragment initialization parameters.
private const val ARG_PARAM_PLAYLIST_OBJECT: String = "param_playlist_object"
private const val ARG_PARAM_PLAYLIST_TRANSITION: String = "param_playlist_transition_params"
/**
* Use this factory method to create a new instance of this fragment using the provided parameters.
*
* @return A new instance of [android.app.Fragment] PlaylistDetailFragment.
*/
fun newInstance(playlist: PlaylistEntity, transition: List<String>) =
PlaylistDetailFragment().apply {
arguments = bundleOf(ARG_PARAM_PLAYLIST_OBJECT to playlist,
ARG_PARAM_PLAYLIST_TRANSITION to ArrayList(transition))
if (transition.isNotEmpty()) {
sharedElementEnterTransition = TransitionInflater.from(App.appComponent.context()).inflateTransition(
R.transition.change_bound_and_fade)
sharedElementReturnTransition = TransitionInflater.from(App.appComponent.context()).inflateTransition(
R.transition.change_bound_and_fade)
}
}
}
//endregion
@Inject override lateinit var viewModel: PlaylistDetailFragmentViewModel
@Inject lateinit var addPlaylistItemCase: AddPlaylistItemCase
private val playlistItemInfo by lazy { DataInfo() }
private var playlistItemRes = mutableListOf<PlaylistItemEntity>()
// Get the arguments from the bundle here.
private val playlist by lazy { arguments.getParcelable<PlaylistEntity>(ARG_PARAM_PLAYLIST_OBJECT) }
private val transition by lazy { arguments.getStringArrayList(ARG_PARAM_PLAYLIST_TRANSITION) }
//region Fragment lifecycle
override fun onDestroyView() {
(binding?.itemAdapter as BaseDataBindingAdapter<*, *>).detachAll()
super.onDestroyView()
}
//endregion
//region Base fragment implement
override fun rendered(savedInstanceState: Bundle?) {
binding?.apply {
// TODO(jieyi): 11/19/17 Create a map for each elements.
if (transition.isNotEmpty()) {
ivAlbumImage.transitionName = transition[0]
tvName.transitionName = transition[1]
}
itemLayoutManager = WrapContentLinearLayoutManager(activity)
itemAdapter = PlaylistItemAdapter(this@PlaylistDetailFragment,
R.layout.item_music_type_5,
playlistItemRes) { holder, item, index ->
if (null == holder.binding.avm)
holder.binding.avm = RecyclerViewPlaylistDetailViewModel(addPlaylistItemCase,
item,
index + 1)
else
holder.binding.avm?.setPlaylistItem(item, index + 1)
}
val callback = SimpleItemTouchHelperCallback(itemAdapter as PlaylistItemAdapter, vmItemTouchCallback)
ItemTouchHelper(callback).attachToRecyclerView(recyclerView)
}
viewModel.attachPlaylistInfo(playlist)
playlistItemInfo.firstFetch { info ->
viewModel.fetchPlaylistItems(playlist.id) {
playlistItemRes.refreshAndChangeList(it, 0, binding?.itemAdapter as PlaylistItemAdapter, info)
}
}
}
override fun provideInflateView(): Int = R.layout.fragment_playlist_detail
//endregion
/**
* @param playlistItem
*
* @event_from [taiwan.no1.app.ssfm.features.playlist.RecyclerViewPlaylistDetailViewModel.trackOnClick]
*/
@Subscribe(tags = [(Tag(HELPER_ADD_TO_PLAYLIST))])
fun addToPlaylist(playlistItem: PlaylistItemEntity) {
playerHelper.addToPlaylist(playlistItem, playlistItemRes, this.javaClass.name)
}
private val vmItemTouchCallback = object : ItemTouchViewmodelCallback {
override fun onItemDismiss(position: Int, direction: Int) {
playlistItemRes[position].let { deletedItem ->
viewModel.deleteItem(deletedItem) { if (it) playlistItemRes.remove(deletedItem) }
}
}
}
} | apache-2.0 | e88b49fe42d4c13600fe7d62b22fd84c | 47.096 | 122 | 0.686242 | 4.971878 | false | false | false | false |
stoyicker/dinger | views/src/main/kotlin/views/RoundCornerImageView.kt | 1 | 3211 | package views
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Path
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.support.annotation.DrawableRes
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory
import android.util.AttributeSet
import android.view.View
import com.squareup.picasso.Picasso
import com.squareup.picasso.Target
import org.stoyicker.dinger.views.R
class RoundCornerImageView(context: Context, attributeSet: AttributeSet? = null)
: View(context, attributeSet), Target {
private val cornerRadiusPx: Float
private val picasso = Picasso.get()
private val clipPath = Path()
private var drawable: Drawable? = null
set(value) {
field = value
postInvalidate()
}
private var queuedUrl: String? = null
private var queuedErrorRes: Int = 0
init {
context.theme.obtainStyledAttributes(
attributeSet,
R.styleable.RoundCornerImageView,
0,
0).apply {
try {
cornerRadiusPx = getDimension(R.styleable.RoundCornerImageView_cornerRadius, DEFAULT_RADIUS_PX)
} finally {
recycle()
}
}
}
fun loadImage(url: String, @DrawableRes errorRes: Int = 0) {
queuedUrl = url
queuedErrorRes = errorRes
loadImageInternal()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
queuedUrl?.let { picasso.invalidate(it) }
picasso.cancelRequest(this)
clipPath.reset()
RectF().apply {
set(0f, 0f, w.toFloat(), h.toFloat())
clipPath.addRoundRect(this, DEFAULT_RADIUS_PX, DEFAULT_RADIUS_PX, Path.Direction.CW)
}
clipPath.close()
loadImageInternal(w, h)
}
override fun onDraw(canvas: Canvas) {
val save = canvas.save()
canvas.clipPath(clipPath)
drawable?.apply {
setBounds(0, 0, width, height)
draw(canvas)
}
canvas.restoreToCount(save)
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
drawable = placeHolderDrawable
}
override fun onBitmapLoaded(bitmap: Bitmap, from: Picasso.LoadedFrom) {
val roundedDrawable = RoundedBitmapDrawableFactory.create(resources, bitmap)
layoutParams.apply {
width = Math.min((parent as View).width, bitmap.width)
height = bitmap.height
}
roundedDrawable.cornerRadius = cornerRadiusPx
drawable = roundedDrawable
layoutParams = layoutParams
}
override fun onBitmapFailed(e: Exception, errorDrawable: Drawable?) {
layoutParams.apply {
width = Math.min(width, height)
height = width
}
drawable = errorDrawable
layoutParams = layoutParams
}
private fun loadImageInternal(w: Int = Math.min((parent as View).width, width), h: Int = height) {
if (w < 1 && h < 1) {
return
}
queuedUrl?.let {
picasso.load(it)
.noPlaceholder()
.centerCrop()
.resize(w, h)
.stableKey(it)
.apply {
if (queuedErrorRes != 0) {
error(queuedErrorRes)
}
}
.into(this)
}
}
private companion object {
const val DEFAULT_RADIUS_PX = 25f
}
}
| mit | d7b9d7e7ac76fdc6736d252ba430e4a8 | 26.211864 | 103 | 0.670508 | 4.213911 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/test-framework/test/org/jetbrains/kotlin/projectModel/Model.kt | 3 | 6453 | // 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.projectModel
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import org.jetbrains.kotlin.idea.base.platforms.KotlinCommonLibraryKind
import org.jetbrains.kotlin.idea.base.platforms.KotlinJavaScriptLibraryKind
import org.jetbrains.kotlin.idea.base.platforms.KotlinNativeLibraryKind
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.konan.target.HostManager
import org.jetbrains.kotlin.platform.CommonPlatforms
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.platform.konan.NativePlatforms
import org.jetbrains.kotlin.utils.Printer
import java.io.File
open class ProjectResolveModel(val modules: List<ResolveModule>) {
open class Builder {
val modules: MutableList<ResolveModule.Builder> = mutableListOf()
open fun build(): ProjectResolveModel = ProjectResolveModel(modules.map { it.build() })
}
}
open class ResolveModule(
val name: String,
val root: File,
val platform: TargetPlatform,
val dependencies: List<ResolveDependency>,
val testRoot: File? = null,
val additionalCompilerArgs: String? = null
) {
final override fun toString(): String {
return buildString { renderDescription(Printer(this)) }
}
open fun renderDescription(printer: Printer) {
printer.println("Module $name")
printer.pushIndent()
printer.println("platform=$platform")
printer.println("root=${root.absolutePath}")
if (testRoot != null) printer.println("testRoot=${testRoot.absolutePath}")
printer.println("dependencies=${dependencies.joinToString { it.to.name }}")
if (additionalCompilerArgs != null) printer.println("additionalCompilerArgs=$additionalCompilerArgs")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ResolveModule
if (name != other.name) return false
return true
}
override fun hashCode(): Int {
return name.hashCode()
}
open class Builder {
private var state: State = State.NOT_BUILT
private var cachedResult: ResolveModule? = null
var name: String? = null
var root: File? = null
var platform: TargetPlatform? = null
val dependencies: MutableList<ResolveDependency.Builder> = mutableListOf()
var testRoot: File? = null
var additionalCompilerArgs: String? = null
open fun build(): ResolveModule {
if (state == State.BUILT) return cachedResult!!
require(state == State.NOT_BUILT) { "Re-building module $this with name $name (root at $root)" }
state = State.BUILDING
val builtDependencies = dependencies.map { it.build() }
cachedResult = ResolveModule(name!!, root!!, platform!!, builtDependencies, testRoot, additionalCompilerArgs= additionalCompilerArgs)
state = State.BUILT
return cachedResult!!
}
enum class State {
NOT_BUILT,
BUILDING,
BUILT
}
}
}
sealed class ResolveLibrary(
name: String,
root: File,
platform: TargetPlatform,
val kind: PersistentLibraryKind<*>?
) : ResolveModule(name, root, platform, emptyList()) {
class Builder(val target: ResolveLibrary) : ResolveModule.Builder() {
override fun build(): ResolveModule = target
}
}
sealed class Stdlib(
name: String,
root: File,
platform: TargetPlatform,
kind: PersistentLibraryKind<*>?
) : ResolveLibrary(name, root, platform, kind) {
object CommonStdlib : Stdlib(
"stdlib-common",
TestKotlinArtifacts.kotlinStdlibCommon,
CommonPlatforms.defaultCommonPlatform,
KotlinCommonLibraryKind
)
object NativeStdlib : Stdlib(
"stdlib-native-by-host",
TestKotlinArtifacts.kotlinStdlibNative,
NativePlatforms.nativePlatformBySingleTarget(HostManager.host),
KotlinNativeLibraryKind
)
object JvmStdlib : Stdlib(
"stdlib-jvm",
TestKotlinArtifacts.kotlinStdlib,
JvmPlatforms.defaultJvmPlatform,
null
)
object JsStdlib : Stdlib(
"stdlib-js",
TestKotlinArtifacts.kotlinStdlibJs,
JsPlatforms.defaultJsPlatform,
KotlinJavaScriptLibraryKind
)
}
sealed class KotlinTest(
name: String,
root: File,
platform: TargetPlatform,
kind: PersistentLibraryKind<*>?
) : ResolveLibrary(name, root, platform, kind) {
object JsKotlinTest : KotlinTest(
"kotlin-test-js",
TestKotlinArtifacts.kotlinTestJs,
JsPlatforms.defaultJsPlatform,
KotlinJavaScriptLibraryKind
)
object JvmKotlinTest : KotlinTest(
"kotlin-test-jvm",
TestKotlinArtifacts.kotlinTestJunit,
JvmPlatforms.defaultJvmPlatform,
null
)
object JustKotlinTest : KotlinTest(
"kotlin-test",
TestKotlinArtifacts.kotlinTest,
JvmPlatforms.defaultJvmPlatform,
null
)
object Junit : KotlinTest(
"junit",
File("$IDEA_TEST_DATA_DIR/lib/junit-4.12.jar"),
JvmPlatforms.defaultJvmPlatform,
null
)
}
interface ResolveSdk
object FullJdk : ResolveLibrary(
"full-jdk",
File("fake file for full jdk"),
JvmPlatforms.defaultJvmPlatform,
null
), ResolveSdk
object MockJdk : ResolveLibrary(
"mock-jdk",
File("fake file for mock jdk"),
JvmPlatforms.defaultJvmPlatform,
null
), ResolveSdk
object KotlinSdk : ResolveLibrary(
"kotlin-sdk",
File("fake file for kotlin sdk"),
CommonPlatforms.defaultCommonPlatform,
null,
), ResolveSdk
open class ResolveDependency(val to: ResolveModule, val kind: Kind) {
open class Builder {
var to: ResolveModule.Builder = ResolveModule.Builder()
var kind: Kind? = null
open fun build(): ResolveDependency = ResolveDependency(to.build(), kind!!)
}
enum class Kind {
DEPENDS_ON,
DEPENDENCY,
}
} | apache-2.0 | d82ac63aac191471d6e0bf6186e44ad6 | 29.018605 | 158 | 0.680769 | 4.922197 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/extensions/KtCompilerPluginsProviderIdeImpl.kt | 2 | 7346 | // 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.fir.extensions
import com.intellij.ide.impl.isTrusted
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.util.concurrency.SynchronizedClearableLazy
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.orNull
import com.intellij.util.lang.UrlClassLoader
import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.storage.EntityChange
import com.intellij.workspaceModel.storage.VersionedStorageChange
import com.intellij.workspaceModel.storage.bridgeEntities.FacetEntity
import org.jetbrains.kotlin.analysis.project.structure.KtCompilerPluginsProvider
import org.jetbrains.kotlin.analysis.project.structure.KtSourceModule
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.cli.plugins.processCompilerPluginsOptions
import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor
import org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar
import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.extensions.ProjectExtensionDescriptor
import org.jetbrains.kotlin.idea.base.projectStructure.ideaModule
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCompilerSettingsListener
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.facet.KotlinFacetType
import org.jetbrains.kotlin.util.ServiceLoaderLite
import java.nio.file.Path
import java.util.*
import java.util.concurrent.ConcurrentMap
@OptIn(ExperimentalCompilerApi::class)
internal class KtCompilerPluginsProviderIdeImpl(private val project: Project) : KtCompilerPluginsProvider(), Disposable {
private val pluginsCacheCachedValue: SynchronizedClearableLazy<PluginsCache?> = SynchronizedClearableLazy { createNewCache() }
private val pluginsCache: PluginsCache?
get() = pluginsCacheCachedValue.value
init {
val messageBusConnection = project.messageBus.connect(this)
messageBusConnection.subscribe(WorkspaceModelTopics.CHANGED,
object : WorkspaceModelChangeListener {
override fun changed(event: VersionedStorageChange) {
val hasChanges = event.getChanges(FacetEntity::class.java).any { change ->
change.facetTypes.any { it == KotlinFacetType.ID }
}
if (hasChanges) {
pluginsCacheCachedValue.drop()
}
}
}
)
messageBusConnection.subscribe(KotlinCompilerSettingsListener.TOPIC,
object : KotlinCompilerSettingsListener {
override fun <T> settingsChanged(oldSettings: T?, newSettings: T?) {
pluginsCacheCachedValue.drop()
}
}
)
}
private val EntityChange<FacetEntity>.facetTypes: List<String>
get() = when (this) {
is EntityChange.Added -> listOf(entity.facetType)
is EntityChange.Removed -> listOf(entity.facetType)
is EntityChange.Replaced -> listOf(oldEntity.facetType, newEntity.facetType)
}
private fun createNewCache(): PluginsCache? {
if (!project.isTrusted()) return null
val pluginsClassLoader: UrlClassLoader = UrlClassLoader.build().apply {
parent(KtSourceModule::class.java.classLoader)
val pluginsClasspath = ModuleManager.getInstance(project).modules
.flatMap { it.getCompilerArguments().getPluginClassPaths() }
.distinct()
files(pluginsClasspath)
}.get()
return PluginsCache(
pluginsClassLoader,
ContainerUtil.createConcurrentWeakMap<KtSourceModule, Optional<CompilerPluginRegistrar.ExtensionStorage>>()
)
}
private class PluginsCache(
val pluginsClassLoader: UrlClassLoader,
val registrarForModule: ConcurrentMap<KtSourceModule, Optional<CompilerPluginRegistrar.ExtensionStorage>>
)
override fun <T : Any> getRegisteredExtensions(module: KtSourceModule, extensionType: ProjectExtensionDescriptor<T>): List<T> {
val registrarForModule = pluginsCache?.registrarForModule ?: return emptyList()
val extensionStorage = registrarForModule.computeIfAbsent(module) {
Optional.ofNullable(computeExtensionStorage(module))
}.orNull() ?: return emptyList()
val registrars = extensionStorage.registeredExtensions[extensionType] ?: return emptyList()
@Suppress("UNCHECKED_CAST")
return registrars as List<T>
}
private fun computeExtensionStorage(module: KtSourceModule): CompilerPluginRegistrar.ExtensionStorage? {
val classLoader = pluginsCache?.pluginsClassLoader ?: return null
val compilerArguments = module.ideaModule.getCompilerArguments()
val classPaths = compilerArguments.getPluginClassPaths().map { it.toFile() }.takeIf { it.isNotEmpty() } ?: return null
val logger = logger<KtCompilerPluginsProviderIdeImpl>()
val pluginRegistrars =
logger.runAndLogException { ServiceLoaderLite.loadImplementations<CompilerPluginRegistrar>(classPaths, classLoader) }
?.takeIf { it.isNotEmpty() }
?: return null
val commandLineProcessors = logger.runAndLogException {
ServiceLoaderLite.loadImplementations<CommandLineProcessor>(classPaths, classLoader)
} ?: return null
val compilerConfiguration = CompilerConfiguration()
processCompilerPluginsOptions(compilerConfiguration, compilerArguments.pluginOptions?.toList(), commandLineProcessors)
val storage = CompilerPluginRegistrar.ExtensionStorage()
for (pluginRegistrar in pluginRegistrars) {
with(pluginRegistrar) {
storage.registerExtensions(compilerConfiguration)
}
}
return storage
}
private fun CommonCompilerArguments.getPluginClassPaths(): List<Path> {
return this
.pluginClasspaths
?.map { Path.of(it).toAbsolutePath() }
?.toList()
.orEmpty()
}
private fun Module.getCompilerArguments(): CommonCompilerArguments {
return KotlinFacet.get(this)?.configuration?.settings?.mergedCompilerArguments
?: KotlinCommonCompilerArgumentsHolder.getInstance(project).settings
}
override fun dispose() {
pluginsCacheCachedValue.drop()
}
companion object {
fun getInstance(project: Project): KtCompilerPluginsProviderIdeImpl {
return project.getService(KtCompilerPluginsProvider::class.java) as KtCompilerPluginsProviderIdeImpl
}
}
}
| apache-2.0 | aa8f058e3c5247993bc9f57ab6fc872c | 47.013072 | 131 | 0.728015 | 5.624809 | false | true | false | false |
siosio/intellij-community | plugins/devkit/devkit-core/src/actions/updateFromSources/UpdateIdeFromSourcesAction.kt | 1 | 24063 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.actions.updateFromSources
import com.intellij.CommonBundle
import com.intellij.execution.configurations.JavaParameters
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.ide.plugins.PluginInstaller
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.marketplace.MarketplaceRequests
import com.intellij.notification.*
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.UpdateInBackground
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.ex.ApplicationEx
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderEnumerator
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.libraries.LibraryUtil
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.task.ProjectTaskManager
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.PathUtil
import com.intellij.util.Restarter
import com.intellij.util.TimeoutUtil
import com.intellij.util.io.inputStream
import com.intellij.util.io.isFile
import org.jetbrains.annotations.NonNls
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.util.PsiUtil
import java.io.File
import java.nio.file.Paths
import java.util.*
private val LOG = logger<UpdateIdeFromSourcesAction>()
private val notificationGroup by lazy {
NotificationGroup(displayId = "Update from Sources", displayType = NotificationDisplayType.STICKY_BALLOON)
}
internal open class UpdateIdeFromSourcesAction
@JvmOverloads constructor(private val forceShowSettings: Boolean = false)
: AnAction(if (forceShowSettings) DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.show.settings.text")
else DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.text"),
DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.description"), null), DumbAware, UpdateInBackground {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
if (forceShowSettings || UpdateFromSourcesSettings.getState().showSettings) {
val oldWorkIdePath = UpdateFromSourcesSettings.getState().actualIdePath
val ok = UpdateFromSourcesDialog(project, forceShowSettings).showAndGet()
if (!ok) return
val updatedState = UpdateFromSourcesSettings.getState()
if (oldWorkIdePath != updatedState.actualIdePath) {
updatedState.workIdePathsHistory.remove(oldWorkIdePath)
updatedState.workIdePathsHistory.remove(updatedState.actualIdePath)
updatedState.workIdePathsHistory.add(0, updatedState.actualIdePath)
updatedState.workIdePathsHistory.add(0, oldWorkIdePath)
}
}
fun error(@NlsContexts.DialogMessage message : String) {
Messages.showErrorDialog(project, message, CommonBundle.getErrorTitle())
}
val state = UpdateFromSourcesSettings.getState()
val devIdeaHome = project.basePath ?: return
val workIdeHome = state.actualIdePath
val restartAutomatically = state.restartAutomatically
if (!ApplicationManager.getApplication().isRestartCapable && FileUtil.pathsEqual(workIdeHome, PathManager.getHomePath())) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.ide.cannot.restart"))
}
val notIdeHomeMessage = checkIdeHome(workIdeHome)
if (notIdeHomeMessage != null) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.work.home.not.valid.ide.home",
workIdeHome, notIdeHomeMessage))
}
if (FileUtil.isAncestor(workIdeHome, PathManager.getConfigPath(), false)) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.config.or.system.directory.under.home", workIdeHome, PathManager.PROPERTY_CONFIG_PATH))
}
if (FileUtil.isAncestor(workIdeHome, PathManager.getSystemPath(), false)) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.config.or.system.directory.under.home", workIdeHome, PathManager.PROPERTY_SYSTEM_PATH))
}
val scriptFile = File(devIdeaHome, "build/scripts/idea_ultimate.gant")
if (!scriptFile.exists()) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.build.scripts.not.exists", scriptFile))
}
if (!scriptFile.readText().contains(includeBinAndRuntimeProperty)) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.build.scripts.out.of.date"))
}
val bundledPluginDirsToSkip: List<String>
val nonBundledPluginDirsToInclude: List<String>
val buildEnabledPluginsOnly = !state.buildDisabledPlugins
if (buildEnabledPluginsOnly) {
val pluginDirectoriesToSkip = LinkedHashSet(state.pluginDirectoriesForDisabledPlugins)
pluginDirectoriesToSkip.removeAll(PluginManagerCore.getLoadedPlugins().asSequence().filter { it.isBundled }.map { it.path }.filter { it.isDirectory }.map { it.name })
PluginManagerCore.getPlugins().filter { it.isBundled && !it.isEnabled }.map { it.path }.filter { it.isDirectory }.mapTo(pluginDirectoriesToSkip) { it.name }
val list = pluginDirectoriesToSkip.toMutableList()
state.pluginDirectoriesForDisabledPlugins = list
bundledPluginDirsToSkip = list
nonBundledPluginDirsToInclude = PluginManagerCore.getPlugins().filter {
!it.isBundled && it.isEnabled && it.version != null && it.version.contains("SNAPSHOT")
}.map { it.path }.filter { it.isDirectory }.map { it.name }
}
else {
bundledPluginDirsToSkip = emptyList()
nonBundledPluginDirsToInclude = emptyList()
}
val deployDir = "$devIdeaHome/out/deploy" // NON-NLS
val distRelativePath = "dist" // NON-NLS
val backupDir = "$devIdeaHome/out/backup-before-update-from-sources" // NON-NLS
val params = createScriptJavaParameters(devIdeaHome, project, deployDir, distRelativePath, scriptFile,
buildEnabledPluginsOnly, bundledPluginDirsToSkip, nonBundledPluginDirsToInclude) ?: return
ProjectTaskManager.getInstance(project)
.buildAllModules()
.onSuccess {
if (!it.isAborted && !it.hasErrors()) {
runUpdateScript(params, project, workIdeHome, deployDir, distRelativePath, backupDir, restartAutomatically)
}
}
}
private fun checkIdeHome(workIdeHome: String): String? {
val homeDir = File(workIdeHome)
if (!homeDir.exists()) return null
if (homeDir.isFile) return DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.work.home.not.valid.ide.home.not.directory")
val buildTxt = if (SystemInfo.isMac) "Resources/build.txt" else "build.txt" // NON-NLS
for (name in listOf("bin", buildTxt)) {
if (!File(homeDir, name).exists()) {
return DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.work.home.not.valid.ide.home.not.exists", name)
}
}
return null
}
private fun runUpdateScript(params: JavaParameters,
project: Project,
workIdeHome: String,
deployDirPath: String,
distRelativePath: String,
backupDir: String,
restartAutomatically: Boolean) {
val builtDistPath = "$deployDirPath/$distRelativePath"
object : Task.Backgroundable(project, DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.title"), true) {
override fun run(indicator: ProgressIndicator) {
indicator.text = DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.progress.text")
backupImportantFilesIfNeeded(workIdeHome, backupDir, indicator)
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.progress.delete", builtDistPath)
FileUtil.delete(File(builtDistPath))
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.progress.start.gant.script")
val commandLine = params.toCommandLine()
commandLine.isRedirectErrorStream = true
val scriptHandler = OSProcessHandler(commandLine)
val output = Collections.synchronizedList(ArrayList<@NlsSafe String>())
scriptHandler.addProcessListener(object : ProcessAdapter() {
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
output.add(event.text)
if (outputType == ProcessOutputTypes.STDOUT) {
indicator.text2 = event.text
}
}
override fun processTerminated(event: ProcessEvent) {
if (indicator.isCanceled) {
return
}
if (event.exitCode != 0) {
notificationGroup.createNotification(title = DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.failed.title"),
content = DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.failed.content",
event.exitCode),
type = NotificationType.ERROR)
.addAction(NotificationAction.createSimple(DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.action.view.output")) {
FileEditorManager.getInstance(project).openFile(LightVirtualFile("output.txt", output.joinToString("")), true)
})
.addAction(NotificationAction.createSimple(DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.action.view.debug.log")) {
val logFile = LocalFileSystem.getInstance().refreshAndFindFileByPath("$deployDirPath/log/debug.log") ?: return@createSimple // NON-NLS
logFile.refresh(true, false)
FileEditorManager.getInstance(project).openFile(logFile, true)
})
.notify(project)
return
}
if (!FileUtil.pathsEqual(workIdeHome, PathManager.getHomePath())) {
startCopyingFiles(builtDistPath, workIdeHome, project)
return
}
val command = generateUpdateCommand(builtDistPath, workIdeHome)
if (restartAutomatically) {
ApplicationManager.getApplication().invokeLater { scheduleRestart(command, deployDirPath, project) }
}
else {
showRestartNotification(command, deployDirPath, project)
}
}
})
scriptHandler.startNotify()
while (!scriptHandler.isProcessTerminated) {
scriptHandler.waitFor(300)
indicator.checkCanceled()
}
}
}.queue()
}
private fun showRestartNotification(command: Array<String>, deployDirPath: String, project: Project) {
notificationGroup
.createNotification(DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.success.title"), DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.success.content"), NotificationType.INFORMATION)
.setListener(NotificationListener { _, _ -> restartWithCommand(command, deployDirPath) })
.notify(project)
}
private fun scheduleRestart(command: Array<String>, deployDirPath: String, project: Project) {
object : Task.Modal(project, DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.success.title"), true) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = false
var progress = 0
for (i in 10 downTo 1) {
indicator.text = DevKitBundle.message(
"action.UpdateIdeFromSourcesAction.progress.text.new.installation.prepared.ide.will.restart", i)
repeat(10) {
indicator.fraction = 0.01 * progress++
indicator.checkCanceled()
TimeoutUtil.sleep(100)
}
}
restartWithCommand(command, deployDirPath)
}
override fun onCancel() {
showRestartNotification(command, deployDirPath, project)
}
}.setCancelText(DevKitBundle.message("action.UpdateIdeFromSourcesAction.button.postpone")).queue()
}
private fun backupImportantFilesIfNeeded(workIdeHome: String,
backupDirPath: String,
indicator: ProgressIndicator) {
val backupDir = File(backupDirPath)
if (backupDir.exists()) {
LOG.debug("$backupDir already exists, skipping backup")
return
}
LOG.debug("Backing up files from $workIdeHome to $backupDir")
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.backup.progress.text")
FileUtil.createDirectory(backupDir)
File(workIdeHome, "bin").listFiles()
?.filter { it.name !in safeToDeleteFilesInBin && it.extension !in safeToDeleteExtensions }
?.forEach { FileUtil.copy(it, File(backupDir, "bin/${it.name}")) }
File(workIdeHome).listFiles()
?.filter { it.name !in safeToDeleteFilesInHome }
?.forEach { FileUtil.copyFileOrDir(it, File(backupDir, it.name)) }
}
private fun startCopyingFiles(builtDistPath: String, workIdeHome: String, project: Project) {
object : Task.Backgroundable(project, DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.title"), true) {
override fun run(indicator: ProgressIndicator) {
indicator.text = DevKitBundle.message("action.UpdateIdeFromSourcesAction.copy.progress.text")
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.copy.delete.old.files.text")
FileUtil.delete(File(workIdeHome))
indicator.checkCanceled()
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.copy.copy.new.files.text")
FileUtil.copyDir(File(builtDistPath), File(workIdeHome))
indicator.checkCanceled()
Notification("Update from Sources", DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.title"),
DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.content", workIdeHome),
NotificationType.INFORMATION).notify(project)
}
}.queue()
}
@Suppress("HardCodedStringLiteral")
private fun generateUpdateCommand(builtDistPath: String, workIdeHome: String): Array<String> {
if (SystemInfo.isWindows) {
val restartLogFile = File(PathManager.getLogPath(), "update-from-sources.log")
val updateScript = FileUtil.createTempFile("update", ".cmd", false)
val workHomePath = File(workIdeHome).absolutePath
/* deletion of the IDE files may fail to delete some executable files because they are still used by the IDE process,
so the script wait for some time and try to delete again;
'ping' command is used instead of 'timeout' because the latter doesn't work from batch files;
removal of the script file is performed in separate process to avoid errors while executing the script */
FileUtil.writeToFile(updateScript, """
@echo off
SET count=20
SET time_to_wait=1
:DELETE_DIR
RMDIR /Q /S "$workHomePath"
IF EXIST "$workHomePath" (
IF %count% GEQ 0 (
ECHO "$workHomePath" still exists, wait %time_to_wait%s and try delete again
SET /A time_to_wait=%time_to_wait%+1
PING 127.0.0.1 -n %time_to_wait% >NUL
SET /A count=%count%-1
ECHO %count% attempts remain
GOTO DELETE_DIR
)
ECHO Failed to delete "$workHomePath", IDE wasn't updated. You may delete it manually and copy files from "${File(builtDistPath).absolutePath}" by hand
GOTO CLEANUP_AND_EXIT
)
XCOPY "${File(builtDistPath).absolutePath}" "$workHomePath"\ /Q /E /Y
:CLEANUP_AND_EXIT
START /b "" cmd /c DEL /Q /F "${updateScript.absolutePath}" & EXIT /b
""".trimIndent())
return arrayOf("cmd", "/c", updateScript.absolutePath, ">${restartLogFile.absolutePath}", "2>&1")
}
val command = arrayOf(
"rm -rf \"$workIdeHome\"/*",
"cp -R \"$builtDistPath\"/* \"$workIdeHome\""
)
return arrayOf("/bin/sh", "-c", command.joinToString(" && "))
}
private fun restartWithCommand(command: Array<String>, deployDirPath: String) {
updatePlugins(deployDirPath)
Restarter.doNotLockInstallFolderOnRestart()
(ApplicationManager.getApplication() as ApplicationImpl).restart(ApplicationEx.FORCE_EXIT or ApplicationEx.EXIT_CONFIRMED or ApplicationEx.SAVE, command)
}
private fun updatePlugins(deployDirPath: String) {
val pluginsDir = Paths.get(deployDirPath).resolve("artifacts/${ApplicationInfo.getInstance().build.productCode}-plugins")
val pluginsXml = pluginsDir.resolve("plugins.xml")
if (!pluginsXml.isFile()) {
LOG.warn("Cannot read non-bundled plugins from $pluginsXml, they won't be updated")
return
}
val plugins = try {
pluginsXml.inputStream().reader().use {
MarketplaceRequests.parsePluginList(it)
}
}
catch (e: Exception) {
LOG.error("Failed to parse $pluginsXml", e)
return
}
val existingCustomPlugins =
PluginManagerCore.getLoadedPlugins().asSequence().filter { !it.isBundled }.associateBy { it.pluginId.idString }
LOG.debug("Existing custom plugins: $existingCustomPlugins")
val pluginsToUpdate =
plugins.mapNotNull { node -> existingCustomPlugins[node.pluginId.idString]?.let { it to node } }
for ((existing, update) in pluginsToUpdate) {
val pluginFile = pluginsDir.resolve(update.downloadUrl)
LOG.debug("Adding update command: ${existing.pluginPath} to $pluginFile")
PluginInstaller.installAfterRestart(pluginFile, false, existing.pluginPath, update)
}
}
private fun createScriptJavaParameters(devIdeaHome: String,
project: Project,
deployDir: String,
@Suppress("SameParameterValue") distRelativePath: String,
scriptFile: File,
buildEnabledPluginsOnly: Boolean,
bundledPluginDirsToSkip: List<String>,
nonBundledPluginDirsToInclude: List<String>): JavaParameters? {
val sdk = ProjectRootManager.getInstance(project).projectSdk
if (sdk == null) {
LOG.warn("Project SDK is not defined")
return null
}
val params = JavaParameters()
params.isUseClasspathJar = true
params.setDefaultCharset(project)
params.jdk = sdk
params.mainClass = "org.codehaus.groovy.tools.GroovyStarter"
params.programParametersList.add("--classpath")
val buildScriptsModuleName = "intellij.idea.ultimate.build"
val buildScriptsModule = ModuleManager.getInstance(project).findModuleByName(buildScriptsModuleName)
if (buildScriptsModule == null) {
LOG.warn("Build scripts module $buildScriptsModuleName is not found in the project")
return null
}
val classpath = OrderEnumerator.orderEntries(buildScriptsModule)
.recursively().withoutSdk().runtimeOnly().productionOnly().classes().pathsList
val classesFromCoreJars = listOf(
params.mainClass,
"org.apache.tools.ant.BuildException", //ant
"org.apache.tools.ant.launch.AntMain", //ant-launcher
"org.apache.commons.cli.ParseException", //commons-cli
"groovy.util.CliBuilder", //groovy-cli-commons
"org.codehaus.groovy.runtime.NioGroovyMethods", //groovy-nio
)
val coreClassPath = classpath.rootDirs.filter { root ->
classesFromCoreJars.any { LibraryUtil.isClassAvailableInLibrary(listOf(root), it) }
}.mapNotNull { PathUtil.getLocalPath(it) }
params.classPath.addAll(coreClassPath)
coreClassPath.forEach { classpath.remove(FileUtil.toSystemDependentName(it)) }
params.programParametersList.add(classpath.pathsString)
params.programParametersList.add("--main")
params.programParametersList.add("gant.Gant")
params.programParametersList.add("--debug")
params.programParametersList.add("-Dsome_unique_string_42_239")
params.programParametersList.add("--file")
params.programParametersList.add(scriptFile.absolutePath)
params.programParametersList.add("update-from-sources")
params.vmParametersList.add("-D$includeBinAndRuntimeProperty=true")
params.vmParametersList.add("-Dintellij.build.bundled.jre.prefix=jbrsdk-")
if (buildEnabledPluginsOnly) {
if (bundledPluginDirsToSkip.isNotEmpty()) {
params.vmParametersList.add("-Dintellij.build.bundled.plugin.dirs.to.skip=${bundledPluginDirsToSkip.joinToString(",")}")
}
val nonBundled = if (nonBundledPluginDirsToInclude.isNotEmpty()) nonBundledPluginDirsToInclude.joinToString(",") else "none"
params.vmParametersList.add("-Dintellij.build.non.bundled.plugin.dirs.to.include=$nonBundled")
}
if (!buildEnabledPluginsOnly || nonBundledPluginDirsToInclude.isNotEmpty()) {
params.vmParametersList.add("-Dintellij.build.local.plugins.repository=true")
}
params.vmParametersList.add("-Dintellij.build.output.root=$deployDir")
params.vmParametersList.add("-DdistOutputRelativePath=$distRelativePath")
return params
}
override fun update(e: AnActionEvent) {
val project = e.project
e.presentation.isEnabledAndVisible = project != null && isIdeaProject(project)
}
private fun isIdeaProject(project: Project) = try {
DumbService.getInstance(project).computeWithAlternativeResolveEnabled<Boolean, RuntimeException> { PsiUtil.isIdeaProject(project) }
}
catch (e: IndexNotReadyException) {
false
}
}
private const val includeBinAndRuntimeProperty = "intellij.build.generate.bin.and.runtime.for.unpacked.dist"
internal class UpdateIdeFromSourcesSettingsAction : UpdateIdeFromSourcesAction(true)
@NonNls
private val safeToDeleteFilesInHome = setOf(
"bin", "help", "jre", "jre64", "jbr", "lib", "license", "plugins", "redist", "MacOS", "Resources",
"build.txt", "product-info.json", "Install-Linux-tar.txt", "Install-Windows-zip.txt", "ipr.reg"
)
@NonNls
private val safeToDeleteFilesInBin = setOf(
"append.bat", "appletviewer.policy", "format.sh", "format.bat",
"fsnotifier", "fsnotifier64",
"inspect.bat", "inspect.sh",
"restarter"
/*
"idea.properties",
"idea.sh",
"idea.bat",
"idea.exe.vmoptions",
"idea64.exe.vmoptions",
"idea.vmoptions",
"idea64.vmoptions",
"log.xml",
*/
)
@NonNls
private val safeToDeleteExtensions = setOf("exe", "dll", "dylib", "so", "ico", "svg", "png", "py")
| apache-2.0 | cc1931d377914375e7c4526ebe5cae22 | 48.008147 | 213 | 0.703944 | 4.927913 | false | false | false | false |
Zeroami/CommonLib-Kotlin | commonlib/src/main/java/com/zeroami/commonlib/utils/LUtils.kt | 1 | 4548 | package com.zeroami.commonlib.utils
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.media.RingtoneManager
import android.os.*
import android.view.View
import com.zeroami.commonlib.CommonLib
import java.io.Serializable
/**
* 不好分类的工具方法
*
* @author Zeroami
*/
object LUtils {
private val vibrator by lazy { CommonLib.ctx.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator }
/**
* 复制文本到剪贴板
*/
fun copyToClipboard(text: String) {
if (Build.VERSION.SDK_INT >= 11) {
val cbm = CommonLib.ctx.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
cbm.primaryClip = ClipData.newPlainText(CommonLib.ctx.packageName, text)
} else {
val cbm = CommonLib.ctx.getSystemService(Context.CLIPBOARD_SERVICE) as android.text.ClipboardManager
cbm.text = text
}
}
/**
* 判断事件点是否在控件内
*/
fun isTouchPointInView(view: View, x: Float, y: Float): Boolean {
val location = IntArray(2)
view.getLocationOnScreen(location)
val left = location[0]
val top = location[1]
val right = left + view.measuredWidth
val bottom = top + view.measuredHeight
if (y in top..bottom && x in left..right) {
return true
}
return false
}
/**
* 生成Extras
*/
fun generateExtras(vararg params: Pair<String, Any>): Bundle {
val extras = Bundle()
if (params.isNotEmpty()) {
params.forEach {
val value = it.second
when (value) {
is Int -> extras.putInt(it.first, value)
is Long -> extras.putLong(it.first, value)
is CharSequence -> extras.putCharSequence(it.first, value)
is String -> extras.putString(it.first, value)
is Float -> extras.putFloat(it.first, value)
is Double -> extras.putDouble(it.first, value)
is Char -> extras.putChar(it.first, value)
is Short -> extras.putShort(it.first, value)
is Boolean -> extras.putBoolean(it.first, value)
is Serializable -> extras.putSerializable(it.first, value)
is Bundle -> extras.putBundle(it.first, value)
is Parcelable -> extras.putParcelable(it.first, value)
is Array<*> -> when {
value.isArrayOf<CharSequence>() -> extras.putCharSequenceArray(it.first, value as Array<out CharSequence>?)
value.isArrayOf<String>() -> extras.putStringArray(it.first, value as Array<out String>?)
value.isArrayOf<Parcelable>() -> extras.putParcelableArray(it.first, value as Array<out Parcelable>?)
else -> throw RuntimeException("extras ${it.first} has wrong type ${value.javaClass.name}")
}
is IntArray -> extras.putIntArray(it.first, value)
is LongArray -> extras.putLongArray(it.first, value)
is FloatArray -> extras.putFloatArray(it.first, value)
is DoubleArray -> extras.putDoubleArray(it.first, value)
is CharArray -> extras.putCharArray(it.first, value)
is ShortArray -> extras.putShortArray(it.first, value)
is BooleanArray -> extras.putBooleanArray(it.first, value)
else -> throw RuntimeException("extra ${it.first} has wrong type ${value.javaClass.name}")
}
}
}
return extras
}
@SuppressLint("MissingPermission")
fun vibrate() {
if (isAndroidO()) {
vibrator.vibrate(VibrationEffect.createWaveform(longArrayOf(300, 300, 300), intArrayOf(VibrationEffect.DEFAULT_AMPLITUDE, 0, VibrationEffect.DEFAULT_AMPLITUDE), -1))
} else {
vibrator.vibrate(longArrayOf(0, 300, 300, 300), -1) // OFF/ON/OFF/ON
}
}
fun playRing() {
try {
val ringtone = RingtoneManager.getRingtone(CommonLib.ctx, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
ringtone.play()
} catch (e: Exception) {
e.printStackTrace()
}
}
fun isAndroidO(): Boolean = Build.VERSION.SDK_INT >= 26
}
| apache-2.0 | c7c6521d20315e5d681ee5006c783820 | 39.432432 | 177 | 0.588904 | 4.598361 | false | false | false | false |
JetBrains/kotlin-native | performance/ring/src/main/kotlin/org/jetbrains/ring/ClassStreamBenchmark.kt | 4 | 2585 | /*
* 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.ring
import org.jetbrains.benchmarksLauncher.Blackhole
open class ClassStreamBenchmark {
private var _data: Iterable<Value>? = null
val data: Iterable<Value>
get() = _data!!
init {
_data = classValues(BENCHMARK_SIZE)
}
//Benchmark
fun copy(): List<Value> {
return data.asSequence().toList()
}
//Benchmark
fun copyManual(): List<Value> {
val list = ArrayList<Value>()
for (item in data.asSequence()) {
list.add(item)
}
return list
}
//Benchmark
fun filterAndCount(): Int {
return data.asSequence().filter { filterLoad(it) }.count()
}
//Benchmark
fun filterAndMap() {
for (item in data.asSequence().filter { filterLoad(it) }.map { mapLoad(it) })
Blackhole.consume(item)
}
//Benchmark
fun filterAndMapManual() {
for (it in data.asSequence()) {
if (filterLoad(it)) {
val item = mapLoad(it)
Blackhole.consume(item)
}
}
}
//Benchmark
fun filter() {
for (item in data.asSequence().filter { filterLoad(it) })
Blackhole.consume(item)
}
//Benchmark
fun filterManual(){
for (it in data.asSequence()) {
if (filterLoad(it))
Blackhole.consume(it)
}
}
//Benchmark
fun countFilteredManual(): Int {
var count = 0
for (it in data.asSequence()) {
if (filterLoad(it))
count++
}
return count
}
//Benchmark
fun countFiltered(): Int {
return data.asSequence().count { filterLoad(it) }
}
//Benchmark
// fun countFilteredLocal(): Int {
// return data.asSequence().cnt { filterLoad(it) }
// }
//Benchmark
fun reduce(): Int {
return data.asSequence().fold(0) {acc, it -> if (filterLoad(it)) acc + 1 else acc }
}
} | apache-2.0 | c5712751bbf874debc940ba740057f49 | 24.106796 | 91 | 0.583366 | 4.210098 | false | false | false | false |
jwren/intellij-community | platform/configuration-store-impl/src/schemeManager/SchemeManagerImpl.kt | 1 | 24168 | // 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.configurationStore.schemeManager
import com.intellij.concurrency.ConcurrentCollectionFactory
import com.intellij.configurationStore.*
import com.intellij.ide.ui.UITheme
import com.intellij.ide.ui.laf.TempUIThemeBasedLookAndFeelInfo
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorageOperation
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.options.Scheme
import com.intellij.openapi.options.SchemeProcessor
import com.intellij.openapi.options.SchemeState
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.SafeWriteRequestor
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.NewVirtualFile
import com.intellij.util.*
import com.intellij.util.containers.catch
import com.intellij.util.containers.mapSmart
import com.intellij.util.io.*
import com.intellij.util.text.UniqueNameGenerator
import org.jdom.Document
import org.jdom.Element
import java.io.File
import java.io.IOException
import java.nio.file.FileSystemException
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.Function
import java.util.function.Predicate
class SchemeManagerImpl<T: Scheme, MUTABLE_SCHEME : T>(val fileSpec: String,
processor: SchemeProcessor<T, MUTABLE_SCHEME>,
private val provider: StreamProvider?,
internal val ioDirectory: Path,
val roamingType: RoamingType = RoamingType.DEFAULT,
val presentableName: String? = null,
private val schemeNameToFileName: SchemeNameToFileName = CURRENT_NAME_CONVERTER,
private val fileChangeSubscriber: FileChangeSubscriber? = null,
private val virtualFileResolver: VirtualFileResolver? = null) : SchemeManagerBase<T, MUTABLE_SCHEME>(processor), SafeWriteRequestor, StorageManagerFileWriteRequestor {
private val isUseVfs: Boolean
get() = fileChangeSubscriber != null || virtualFileResolver != null
internal val isOldSchemeNaming = schemeNameToFileName == OLD_NAME_CONVERTER
private val isLoadingSchemes = AtomicBoolean()
internal val schemeListManager = SchemeListManager(this)
internal val schemes: MutableList<T>
get() = schemeListManager.schemes
internal var cachedVirtualDirectory: VirtualFile? = null
internal val schemeExtension: String
private val updateExtension: Boolean
internal val filesToDelete: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap())
// scheme could be changed - so, hashcode will be changed - we must use identity hashing strategy
internal val schemeToInfo = ConcurrentCollectionFactory.createConcurrentIdentityMap<T, ExternalInfo>()
init {
if (processor is SchemeExtensionProvider) {
schemeExtension = processor.schemeExtension
updateExtension = true
}
else {
schemeExtension = FileStorageCoreUtil.DEFAULT_EXT
updateExtension = false
}
if (isUseVfs) {
LOG.runAndLogException { refreshVirtualDirectory() }
}
}
override val rootDirectory: File
get() = ioDirectory.toFile()
override val allSchemeNames: Collection<String>
get() = schemes.mapSmart { processor.getSchemeKey(it) }
override val allSchemes: List<T>
get() = Collections.unmodifiableList(schemes)
override val isEmpty: Boolean
get() = schemes.isEmpty()
private fun refreshVirtualDirectory() {
// store refreshes root directory, so, we don't need to use refreshAndFindFile
val directory = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) ?: return
cachedVirtualDirectory = directory
directory.children
if (directory is NewVirtualFile) {
directory.markDirty()
}
directory.refresh(true, false)
}
override fun loadBundledScheme(resourceName: String, requestor: Any?, pluginDescriptor: PluginDescriptor?) {
try {
val bytes: ByteArray
if (pluginDescriptor == null) {
when (requestor) {
is TempUIThemeBasedLookAndFeelInfo -> {
bytes = Files.readAllBytes(Path.of(resourceName))
}
is UITheme -> {
bytes = ResourceUtil.getResourceAsBytes(resourceName.removePrefix("/"), requestor.providerClassLoader)
if (bytes == null) {
LOG.error("Cannot find $resourceName in ${requestor.providerClassLoader}")
return
}
}
else -> {
bytes = ResourceUtil.getResourceAsBytes(resourceName.removePrefix("/"),
(if (requestor is ClassLoader) requestor else requestor!!.javaClass.classLoader))
if (bytes == null) {
LOG.error("Cannot read scheme from $resourceName")
return
}
}
}
}
else {
val classLoader = pluginDescriptor.classLoader
bytes = ResourceUtil.getResourceAsBytes(resourceName.removePrefix("/"), classLoader, true)
if (bytes == null) {
LOG.error("Cannot found scheme $resourceName in $classLoader")
return
}
}
lazyPreloadScheme(bytes, isOldSchemeNaming) { name, parser ->
val attributeProvider = Function<String, String?> { parser.getAttributeValue(null, it) }
val fileName = PathUtilRt.getFileName(resourceName)
val extension = getFileExtension(fileName, true)
val externalInfo = ExternalInfo(fileName.substring(0, fileName.length - extension.length), extension)
val schemeKey = name
?: (processor as LazySchemeProcessor).getSchemeKey(attributeProvider, externalInfo.fileNameWithoutExtension)
?: throw nameIsMissed(bytes)
externalInfo.schemeKey = schemeKey
val scheme = (processor as LazySchemeProcessor).createScheme(SchemeDataHolderImpl(processor, bytes, externalInfo), schemeKey, attributeProvider, true)
val oldInfo = schemeToInfo.put(scheme, externalInfo)
LOG.assertTrue(oldInfo == null)
val oldScheme = schemeListManager.readOnlyExternalizableSchemes.put(schemeKey, scheme)
if (oldScheme != null) {
LOG.warn("Duplicated scheme $schemeKey - old: $oldScheme, new $scheme")
}
schemes.add(scheme)
if (requestor is UITheme) {
requestor.editorSchemeName = schemeKey
}
if (requestor is TempUIThemeBasedLookAndFeelInfo) {
requestor.theme.editorSchemeName = schemeKey
}
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error("Cannot read scheme from $resourceName", e)
}
}
internal fun createSchemeLoader(isDuringLoad: Boolean = false): SchemeLoader<T, MUTABLE_SCHEME> {
val filesToDelete = HashSet(filesToDelete)
// caller must call SchemeLoader.apply to bring back scheduled for delete files
this.filesToDelete.removeAll(filesToDelete)
// SchemeLoader can use retain list to bring back previously scheduled for delete file,
// but what if someone will call save() during load and file will be deleted, although should be loaded by a new load session
// (because modified on disk)
return SchemeLoader(this, schemes, filesToDelete, isDuringLoad)
}
internal fun getFileExtension(fileName: CharSequence, isAllowAny: Boolean): String {
return when {
StringUtilRt.endsWithIgnoreCase(fileName, schemeExtension) -> schemeExtension
StringUtilRt.endsWithIgnoreCase(fileName, FileStorageCoreUtil.DEFAULT_EXT) -> FileStorageCoreUtil.DEFAULT_EXT
isAllowAny -> PathUtil.getFileExtension(fileName.toString())!!
else -> throw IllegalStateException("Scheme file extension $fileName is unknown, must be filtered out")
}
}
override fun loadSchemes(): Collection<T> {
if (!isLoadingSchemes.compareAndSet(false, true)) {
throw IllegalStateException("loadSchemes is already called")
}
try {
// isDuringLoad is true even if loadSchemes called not first time, but on reload,
// because scheme processor should use cumulative event `reloaded` to update runtime state/caches
val schemeLoader = createSchemeLoader(isDuringLoad = true)
val isLoadOnlyFromProvider = provider != null && provider.processChildren(fileSpec, roamingType, { canRead(it) }) { name, input, readOnly ->
catchAndLog({ "${provider.javaClass.name}: $name" }) {
val scheme = schemeLoader.loadScheme(name, input, null)
if (readOnly && scheme != null) {
schemeListManager.readOnlyExternalizableSchemes.put(processor.getSchemeKey(scheme), scheme)
}
}
true
}
if (!isLoadOnlyFromProvider) {
if (virtualFileResolver == null) {
ioDirectory.directoryStreamIfExists({ canRead(it.fileName.toString()) }) { directoryStream ->
for (file in directoryStream) {
catchAndLog({ file.toString() }) {
val bytes = try {
Files.readAllBytes(file)
}
catch (e: FileSystemException) {
when {
file.isDirectory() -> return@catchAndLog
else -> throw e
}
}
schemeLoader.loadScheme(file.fileName.toString(), null, bytes)
}
}
}
}
else {
for (file in getVirtualDirectory(StateStorageOperation.READ)?.children ?: VirtualFile.EMPTY_ARRAY) {
catchAndLog({ file.path }) {
if (canRead(file.nameSequence)) {
schemeLoader.loadScheme(file.name, null, file.contentsToByteArray())
}
}
}
}
}
val newSchemes = schemeLoader.apply()
for (newScheme in newSchemes) {
if (processPendingCurrentSchemeName(newScheme)) {
break
}
}
fileChangeSubscriber?.invoke(this)
return newSchemes
}
finally {
isLoadingSchemes.set(false)
}
}
override fun reload() {
processor.beforeReloaded(this)
// we must not remove non-persistent (e.g. predefined) schemes, because we cannot load it (obviously)
// do not schedule scheme file removing because we just need to update our runtime state, not state on disk
removeExternalizableSchemesFromRuntimeState()
processor.reloaded(this, loadSchemes())
}
// method is used to reflect already performed changes on disk, so, `isScheduleToDelete = false` is passed to `retainExternalInfo`
internal fun removeExternalizableSchemesFromRuntimeState() {
// todo check is bundled/read-only schemes correctly handled
val iterator = schemes.iterator()
for (scheme in iterator) {
if ((scheme as? SerializableScheme)?.schemeState ?: processor.getState(scheme) == SchemeState.NON_PERSISTENT) {
continue
}
activeScheme?.let {
if (scheme === it) {
currentPendingSchemeName = processor.getSchemeKey(it)
activeScheme = null
}
}
iterator.remove()
@Suppress("UNCHECKED_CAST")
processor.onSchemeDeleted(scheme as MUTABLE_SCHEME)
}
retainExternalInfo(isScheduleToDelete = false)
}
internal fun getFileName(scheme: T) = schemeToInfo.get(scheme)?.fileNameWithoutExtension
fun canRead(name: CharSequence) = (updateExtension && name.endsWith(FileStorageCoreUtil.DEFAULT_EXT, true) || name.endsWith(schemeExtension, ignoreCase = true)) && (processor !is LazySchemeProcessor || processor.isSchemeFile(name))
override fun save(errors: MutableList<Throwable>) {
if (isLoadingSchemes.get()) {
LOG.warn("Skip save - schemes are loading")
}
var hasSchemes = false
val nameGenerator = UniqueNameGenerator()
val changedSchemes = SmartList<MUTABLE_SCHEME>()
for (scheme in schemes) {
val state = (scheme as? SerializableScheme)?.schemeState ?: processor.getState(scheme)
if (state == SchemeState.NON_PERSISTENT) {
continue
}
hasSchemes = true
if (state != SchemeState.UNCHANGED) {
@Suppress("UNCHECKED_CAST")
changedSchemes.add(scheme as MUTABLE_SCHEME)
}
val fileName = getFileName(scheme)
if (fileName != null && !isRenamed(scheme)) {
nameGenerator.addExistingName(fileName)
}
}
val filesToDelete = HashSet(filesToDelete)
for (scheme in changedSchemes) {
try {
saveScheme(scheme, nameGenerator, filesToDelete)
}
catch (e: Throwable) {
errors.add(RuntimeException("Cannot save scheme $fileSpec/$scheme", e))
}
}
if (filesToDelete.isNotEmpty()) {
val iterator = schemeToInfo.values.iterator()
for (info in iterator) {
if (filesToDelete.contains(info.fileName)) {
iterator.remove()
}
}
this.filesToDelete.removeAll(filesToDelete)
deleteFiles(errors, filesToDelete)
// remove empty directory only if some file was deleted - avoid check on each save
if (!hasSchemes && (provider == null || !provider.isApplicable(fileSpec, roamingType))) {
removeDirectoryIfEmpty(errors)
}
}
}
private fun removeDirectoryIfEmpty(errors: MutableList<Throwable>) {
ioDirectory.directoryStreamIfExists {
for (file in it) {
if (!file.isHidden()) {
LOG.info("Directory ${ioDirectory.fileName} is not deleted: at least one file ${file.fileName} exists")
return@removeDirectoryIfEmpty
}
}
}
LOG.info("Remove scheme directory ${ioDirectory.fileName}")
if (isUseVfs) {
val dir = getVirtualDirectory(StateStorageOperation.WRITE)
cachedVirtualDirectory = null
if (dir != null) {
runWriteAction {
try {
dir.delete(this)
}
catch (e: IOException) {
errors.add(e)
}
}
}
}
else {
errors.catch {
ioDirectory.delete()
}
}
}
private fun saveScheme(scheme: MUTABLE_SCHEME, nameGenerator: UniqueNameGenerator, filesToDelete: MutableSet<String>) {
var externalInfo: ExternalInfo? = schemeToInfo.get(scheme)
val currentFileNameWithoutExtension = externalInfo?.fileNameWithoutExtension
val element = processor.writeScheme(scheme)?.let { it as? Element ?: (it as Document).detachRootElement() }
if (JDOMUtil.isEmpty(element)) {
externalInfo?.scheduleDelete(filesToDelete, "empty")
return
}
var fileNameWithoutExtension = currentFileNameWithoutExtension
if (fileNameWithoutExtension == null || isRenamed(scheme)) {
fileNameWithoutExtension = nameGenerator.generateUniqueName(schemeNameToFileName(processor.getSchemeKey(scheme)))
}
val fileName = fileNameWithoutExtension + schemeExtension
// file will be overwritten, so, we don't need to delete it
filesToDelete.remove(fileName)
val newDigest = element!!.digest()
when {
externalInfo != null && currentFileNameWithoutExtension === fileNameWithoutExtension && externalInfo.isDigestEquals(newDigest) -> return
isEqualToBundledScheme(externalInfo, newDigest, scheme, filesToDelete) -> return
// we must check it only here to avoid delete old scheme just because it is empty (old idea save -> new idea delete on open)
processor is LazySchemeProcessor && processor.isSchemeDefault(scheme, newDigest) -> {
externalInfo?.scheduleDelete(filesToDelete, "equals to default")
return
}
}
// stream provider always use LF separator
val byteOut = element.toBufferExposingByteArray()
var providerPath: String?
if (provider != null && provider.enabled) {
providerPath = "$fileSpec/$fileName"
if (!provider.isApplicable(providerPath, roamingType)) {
providerPath = null
}
}
else {
providerPath = null
}
// if another new scheme uses old name of this scheme, we must not delete it (as part of rename operation)
@Suppress("SuspiciousEqualsCombination")
val renamed = externalInfo != null && fileNameWithoutExtension !== currentFileNameWithoutExtension && currentFileNameWithoutExtension != null && nameGenerator.isUnique(currentFileNameWithoutExtension)
if (providerPath == null) {
if (isUseVfs) {
var file: VirtualFile? = null
var dir = getVirtualDirectory(StateStorageOperation.WRITE)
if (dir == null || !dir.isValid) {
dir = createDir(ioDirectory, this)
cachedVirtualDirectory = dir
}
if (renamed) {
val oldFile = dir.findChild(externalInfo!!.fileName)
if (oldFile != null) {
// VFS doesn't allow to rename to existing file, so, check it
if (dir.findChild(fileName) == null) {
runWriteAction {
oldFile.rename(this, fileName)
}
file = oldFile
}
else {
externalInfo.scheduleDelete(filesToDelete, "renamed")
}
}
}
if (file == null) {
file = dir.getOrCreateChild(fileName, this)
}
runWriteAction {
file.getOutputStream(this).use { byteOut.writeTo(it) }
}
}
else {
if (renamed) {
externalInfo!!.scheduleDelete(filesToDelete, "renamed")
}
ioDirectory.resolve(fileName).write(byteOut.internalBuffer, 0, byteOut.size())
}
}
else {
if (renamed) {
externalInfo!!.scheduleDelete(filesToDelete, "renamed")
}
provider!!.write(providerPath, byteOut.internalBuffer, byteOut.size(), roamingType)
}
if (externalInfo == null) {
externalInfo = ExternalInfo(fileNameWithoutExtension, schemeExtension)
schemeToInfo.put(scheme, externalInfo)
}
else {
externalInfo.setFileNameWithoutExtension(fileNameWithoutExtension, schemeExtension)
}
externalInfo.digest = newDigest
externalInfo.schemeKey = processor.getSchemeKey(scheme)
}
private fun isEqualToBundledScheme(externalInfo: ExternalInfo?, newDigest: ByteArray, scheme: MUTABLE_SCHEME, filesToDelete: MutableSet<String>): Boolean {
fun serializeIfPossible(scheme: T): Element? {
LOG.runAndLogException {
@Suppress("UNCHECKED_CAST")
val bundledAsMutable = scheme as? MUTABLE_SCHEME ?: return null
return processor.writeScheme(bundledAsMutable) as Element
}
return null
}
val bundledScheme = schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(scheme))
if (bundledScheme == null) {
if ((processor as? LazySchemeProcessor)?.isSchemeEqualToBundled(scheme) == true) {
externalInfo?.scheduleDelete(filesToDelete, "equals to bundled")
return true
}
return false
}
val bundledExternalInfo = schemeToInfo.get(bundledScheme) ?: return false
if (bundledExternalInfo.digest == null) {
serializeIfPossible(bundledScheme)?.let {
bundledExternalInfo.digest = it.digest()
} ?: return false
}
if (bundledExternalInfo.isDigestEquals(newDigest)) {
externalInfo?.scheduleDelete(filesToDelete, "equals to bundled")
return true
}
return false
}
private fun isRenamed(scheme: T): Boolean {
val info = schemeToInfo.get(scheme)
return info != null && processor.getSchemeKey(scheme) != info.schemeKey
}
private fun deleteFiles(errors: MutableList<Throwable>, filesToDelete: MutableSet<String>) {
if (provider != null) {
val iterator = filesToDelete.iterator()
for (name in iterator) {
errors.catch {
val spec = "$fileSpec/$name"
if (provider.delete(spec, roamingType)) {
LOG.debug { "$spec deleted from provider $provider" }
iterator.remove()
}
}
}
}
if (filesToDelete.isEmpty()) {
return
}
LOG.debug { "Delete scheme files: ${filesToDelete.joinToString()}" }
if (isUseVfs) {
getVirtualDirectory(StateStorageOperation.WRITE)?.let { virtualDir ->
val childrenToDelete = virtualDir.children.filter { filesToDelete.contains(it.name) }
if (childrenToDelete.isNotEmpty()) {
runWriteAction {
for (file in childrenToDelete) {
errors.catch { file.delete(this) }
}
}
}
return
}
}
for (name in filesToDelete) {
errors.catch { ioDirectory.resolve(name).delete() }
}
}
internal fun getVirtualDirectory(reasonOperation: StateStorageOperation): VirtualFile? {
var result = cachedVirtualDirectory
if (result == null) {
val path = ioDirectory.systemIndependentPath
result = when (virtualFileResolver) {
null -> LocalFileSystem.getInstance().findFileByPath(path)
else -> virtualFileResolver.resolveVirtualFile(path, reasonOperation)
}
cachedVirtualDirectory = result
}
return result
}
override fun setSchemes(newSchemes: List<T>, newCurrentScheme: T?, removeCondition: Predicate<T>?) {
schemeListManager.setSchemes(newSchemes, newCurrentScheme, removeCondition)
}
internal fun retainExternalInfo(isScheduleToDelete: Boolean) {
if (schemeToInfo.isEmpty()) {
return
}
val iterator = schemeToInfo.entries.iterator()
l@ for ((scheme, info) in iterator) {
if (schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(scheme)) === scheme) {
continue
}
for (s in schemes) {
if (s === scheme) {
filesToDelete.remove(info.fileName)
continue@l
}
}
iterator.remove()
if (isScheduleToDelete) {
info.scheduleDelete(filesToDelete, "requested to delete")
}
}
}
override fun addScheme(scheme: T, replaceExisting: Boolean) = schemeListManager.addScheme(scheme, replaceExisting)
override fun findSchemeByName(schemeName: String) = schemes.firstOrNull { processor.getSchemeKey(it) == schemeName }
override fun removeScheme(name: String) = removeFirstScheme(true) { processor.getSchemeKey(it) == name }
override fun removeScheme(scheme: T) = removeScheme(scheme, isScheduleToDelete = true)
fun removeScheme(scheme: T, isScheduleToDelete: Boolean) = removeFirstScheme(isScheduleToDelete) { it === scheme } != null
override fun isMetadataEditable(scheme: T) = !schemeListManager.readOnlyExternalizableSchemes.containsKey(processor.getSchemeKey(scheme))
override fun toString() = fileSpec
internal fun removeFirstScheme(isScheduleToDelete: Boolean, condition: (T) -> Boolean): T? {
val iterator = schemes.iterator()
for (scheme in iterator) {
if (!condition(scheme)) {
continue
}
if (activeScheme === scheme) {
activeScheme = null
}
iterator.remove()
if (isScheduleToDelete && processor.isExternalizable(scheme)) {
schemeToInfo.remove(scheme)?.scheduleDelete(filesToDelete, "requested to delete (removeFirstScheme)")
}
return scheme
}
return null
}
} | apache-2.0 | 732016adf32587b628b755689c24923a | 36.29784 | 233 | 0.664474 | 5.170732 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeParameterToReceiverIntention.kt | 1 | 18900 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.CallableRefactoring
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.explicateReceiverOf
import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively
import org.jetbrains.kotlin.idea.refactoring.getAffectedCallables
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinIntroduceVariableHandler
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.references.KtSimpleReference
import org.jetbrains.kotlin.idea.search.usagesSearch.searchReferencesOrMethodReferences
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType
import org.jetbrains.kotlin.resolve.calls.util.getArgumentByParameterIndex
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntention<KtTypeReference>(
KtTypeReference::class.java,
KotlinBundle.lazyMessage("convert.function.type.parameter.to.receiver")
) {
class FunctionDefinitionInfo(element: KtFunction) : AbstractProcessableUsageInfo<KtFunction, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val function = element ?: return
val functionParameter = function.valueParameters.getOrNull(data.functionParameterIndex) ?: return
val functionType = functionParameter.typeReference?.typeElement as? KtFunctionType ?: return
val functionTypeParameterList = functionType.parameterList ?: return
val parameterToMove = functionTypeParameterList.parameters.getOrNull(data.typeParameterIndex) ?: return
val typeReferenceToMove = parameterToMove.typeReference ?: return
functionType.setReceiverTypeReference(typeReferenceToMove)
functionTypeParameterList.removeParameter(parameterToMove)
}
}
class ParameterCallInfo(element: KtCallExpression) : AbstractProcessableUsageInfo<KtCallExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val callExpression = element ?: return
val argumentList = callExpression.valueArgumentList ?: return
val expressionToMove = argumentList.arguments.getOrNull(data.typeParameterIndex)?.getArgumentExpression() ?: return
val callWithReceiver =
KtPsiFactory(callExpression).createExpressionByPattern("$0.$1", expressionToMove, callExpression) as KtQualifiedExpression
(callWithReceiver.selectorExpression as KtCallExpression).valueArgumentList!!.removeArgument(data.typeParameterIndex)
callExpression.replace(callWithReceiver)
}
}
class InternalReferencePassInfo(element: KtSimpleNameExpression) :
AbstractProcessableUsageInfo<KtSimpleNameExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val expression = element ?: return
val lambdaType = data.lambdaType
val validator = CollectingNameValidator()
val parameterNames = lambdaType.arguments
.dropLast(1)
.map { KotlinNameSuggester.suggestNamesByType(it.type, validator, "p").first() }
val receiver = parameterNames.getOrNull(data.typeParameterIndex) ?: return
val arguments = parameterNames.filter { it != receiver }
val adapterLambda = KtPsiFactory(expression).createLambdaExpression(
parameterNames.joinToString(),
"$receiver.${expression.text}(${arguments.joinToString()})"
)
expression.replaced(adapterLambda).moveFunctionLiteralOutsideParenthesesIfPossible()
}
}
class LambdaInfo(element: KtExpression) : AbstractProcessableUsageInfo<KtExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val expression = element ?: return
val context = expression.analyze(BodyResolveMode.PARTIAL)
val psiFactory = KtPsiFactory(expression)
if (expression is KtLambdaExpression || (expression !is KtSimpleNameExpression && expression !is KtCallableReferenceExpression)) {
expression.forEachDescendantOfType<KtThisExpression> {
if (it.getLabelName() != null) return@forEachDescendantOfType
val descriptor = context[BindingContext.REFERENCE_TARGET, it.instanceReference] ?: return@forEachDescendantOfType
it.replace(psiFactory.createExpression(explicateReceiverOf(descriptor)))
}
}
if (expression is KtLambdaExpression) {
expression.valueParameters.getOrNull(data.typeParameterIndex)?.let { parameterToConvert ->
val thisRefExpr = psiFactory.createThisExpression()
for (ref in ReferencesSearch.search(parameterToConvert, LocalSearchScope(expression))) {
(ref.element as? KtSimpleNameExpression)?.replace(thisRefExpr)
}
val lambda = expression.functionLiteral
lambda.valueParameterList!!.removeParameter(parameterToConvert)
if (lambda.valueParameters.isEmpty()) {
lambda.arrow?.delete()
}
}
return
}
val originalLambdaTypes = data.lambdaType
val originalParameterTypes = originalLambdaTypes.arguments.dropLast(1).map { it.type }
val calleeText = when (expression) {
is KtSimpleNameExpression -> expression.text
is KtCallableReferenceExpression -> "(${expression.text})"
else -> generateVariable(expression)
}
val parameterNameValidator = CollectingNameValidator(
if (expression !is KtCallableReferenceExpression) listOf(calleeText) else emptyList()
)
val parameterNamesWithReceiver = originalParameterTypes.mapIndexed { i, type ->
if (i != data.typeParameterIndex) KotlinNameSuggester.suggestNamesByType(type, parameterNameValidator, "p")
.first() else "this"
}
val parameterNames = parameterNamesWithReceiver.filter { it != "this" }
val body = psiFactory.createExpression(parameterNamesWithReceiver.joinToString(prefix = "$calleeText(", postfix = ")"))
val replacingLambda = psiFactory.buildExpression {
appendFixedText("{ ")
appendFixedText(parameterNames.joinToString())
appendFixedText(" -> ")
appendExpression(body)
appendFixedText(" }")
} as KtLambdaExpression
expression.replaced(replacingLambda).moveFunctionLiteralOutsideParenthesesIfPossible()
}
private fun generateVariable(expression: KtExpression): String {
var baseCallee = ""
KotlinIntroduceVariableHandler.doRefactoring(project, null, expression, false, emptyList()) {
baseCallee = it.name!!
}
return baseCallee
}
}
private inner class Converter(
private val data: ConversionData,
editor: Editor?
) : CallableRefactoring<CallableDescriptor>(data.function.project, editor, data.functionDescriptor, text) {
override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) {
val callables = getAffectedCallables(project, descriptorsForChange)
val conflicts = MultiMap<PsiElement, String>()
val usages = ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>()
project.runSynchronouslyWithProgress(KotlinBundle.message("looking.for.usages.and.conflicts"), true) {
runReadAction {
val progressIndicator = ProgressManager.getInstance().progressIndicator
progressIndicator.isIndeterminate = false
val progressStep = 1.0 / callables.size
for ((i, callable) in callables.withIndex()) {
progressIndicator.fraction = (i + 1) * progressStep
if (callable !is PsiNamedElement) continue
if (!checkModifiable(callable)) {
val renderedCallable = RefactoringUIUtil.getDescription(callable, true).capitalize()
conflicts.putValue(callable, KotlinBundle.message("can.t.modify.0", renderedCallable))
}
usageLoop@ for (ref in callable.searchReferencesOrMethodReferences()) {
val refElement = ref.element
when (ref) {
is KtSimpleReference<*> -> processExternalUsage(conflicts, refElement, usages)
is KtReference -> continue@usageLoop
else -> {
if (data.isFirstParameter) continue@usageLoop
conflicts.putValue(
refElement,
KotlinBundle.message(
"can.t.replace.non.kotlin.reference.with.call.expression.0",
StringUtil.htmlEmphasize(refElement.text)
)
)
}
}
}
if (callable is KtFunction) {
usages += FunctionDefinitionInfo(callable)
processInternalUsages(callable, usages)
}
}
}
}
project.checkConflictsInteractively(conflicts) {
project.executeWriteCommand(text) {
val elementsToShorten = ArrayList<KtElement>()
usages.sortedByDescending { it.element?.textOffset }.forEach { it.process(data, elementsToShorten) }
ShortenReferences.DEFAULT.process(elementsToShorten)
}
}
}
private fun processExternalUsage(
conflicts: MultiMap<PsiElement, String>,
refElement: PsiElement,
usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>
) {
val callElement = refElement.getParentOfTypeAndBranch<KtCallElement> { calleeExpression }
if (callElement != null) {
val context = callElement.analyze(BodyResolveMode.PARTIAL)
val expressionToProcess = getArgumentExpressionToProcess(callElement, context) ?: return
if (!data.isFirstParameter
&& callElement is KtConstructorDelegationCall
&& expressionToProcess !is KtLambdaExpression
&& expressionToProcess !is KtSimpleNameExpression
&& expressionToProcess !is KtCallableReferenceExpression
) {
conflicts.putValue(
expressionToProcess,
KotlinBundle.message(
"following.expression.won.t.be.processed.since.refactoring.can.t.preserve.its.semantics.0",
expressionToProcess.text
)
)
return
}
if (!checkThisExpressionsAreExplicatable(conflicts, context, expressionToProcess)) return
if (data.isFirstParameter && expressionToProcess !is KtLambdaExpression) return
usages += LambdaInfo(expressionToProcess)
return
}
if (data.isFirstParameter) return
val callableReference = refElement.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference }
if (callableReference != null) {
conflicts.putValue(
refElement,
KotlinBundle.message(
"callable.reference.transformation.is.not.supported.0",
StringUtil.htmlEmphasize(callableReference.text)
)
)
return
}
}
private fun getArgumentExpressionToProcess(callElement: KtCallElement, context: BindingContext): KtExpression? {
return callElement
.getArgumentByParameterIndex(data.functionParameterIndex, context)
.singleOrNull()
?.getArgumentExpression()
?.let { KtPsiUtil.safeDeparenthesize(it) }
}
private fun checkThisExpressionsAreExplicatable(
conflicts: MultiMap<PsiElement, String>,
context: BindingContext,
expressionToProcess: KtExpression
): Boolean {
for (thisExpr in expressionToProcess.collectDescendantsOfType<KtThisExpression>()) {
if (thisExpr.getLabelName() != null) continue
val descriptor = context[BindingContext.REFERENCE_TARGET, thisExpr.instanceReference] ?: continue
if (explicateReceiverOf(descriptor) == "this") {
conflicts.putValue(
thisExpr,
KotlinBundle.message(
"following.expression.won.t.be.processed.since.refactoring.can.t.preserve.its.semantics.0",
thisExpr.text
)
)
return false
}
}
return true
}
private fun processInternalUsages(callable: KtFunction, usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>) {
val body = when (callable) {
is KtConstructor<*> -> callable.containingClassOrObject?.body
else -> callable.bodyExpression
}
if (body != null) {
val functionParameter = callable.valueParameters.getOrNull(data.functionParameterIndex) ?: return
for (ref in ReferencesSearch.search(functionParameter, LocalSearchScope(body))) {
val element = ref.element as? KtSimpleNameExpression ?: continue
val callExpression = element.getParentOfTypeAndBranch<KtCallExpression> { calleeExpression }
if (callExpression != null) {
usages += ParameterCallInfo(callExpression)
} else if (!data.isFirstParameter) {
usages += InternalReferencePassInfo(element)
}
}
}
}
}
class ConversionData(
val typeParameterIndex: Int,
val functionParameterIndex: Int,
val lambdaType: KotlinType,
val function: KtFunction
) {
val isFirstParameter: Boolean get() = typeParameterIndex == 0
val functionDescriptor by lazy { function.unsafeResolveToDescriptor() as FunctionDescriptor }
}
private fun KtTypeReference.getConversionData(): ConversionData? {
val parameter = parent as? KtParameter ?: return null
val functionType = parameter.getParentOfTypeAndBranch<KtFunctionType> { parameterList } ?: return null
if (functionType.receiverTypeReference != null) return null
val lambdaType = functionType.getAbbreviatedTypeOrType(functionType.analyze(BodyResolveMode.PARTIAL)) ?: return null
val containingParameter = (functionType.parent as? KtTypeReference)?.parent as? KtParameter ?: return null
val ownerFunction = containingParameter.ownerFunction as? KtFunction ?: return null
val typeParameterIndex = functionType.parameters.indexOf(parameter)
val functionParameterIndex = ownerFunction.valueParameters.indexOf(containingParameter)
return ConversionData(typeParameterIndex, functionParameterIndex, lambdaType, ownerFunction)
}
override fun startInWriteAction(): Boolean = false
override fun applicabilityRange(element: KtTypeReference): TextRange? {
val data = element.getConversionData() ?: return null
val elementBefore = data.function.valueParameters[data.functionParameterIndex].typeReference!!.typeElement as KtFunctionType
val elementAfter = elementBefore.copied().apply {
setReceiverTypeReference(element)
parameterList!!.removeParameter(data.typeParameterIndex)
}
setTextGetter(KotlinBundle.lazyMessage("convert.0.to.1", elementBefore.text, elementAfter.text))
return element.textRange
}
override fun applyTo(element: KtTypeReference, editor: Editor?) {
element.getConversionData()?.let { Converter(it, editor).run() }
}
}
| apache-2.0 | 968f00d83398352ab64f46e780fb9f6c | 50.780822 | 158 | 0.646032 | 6.338028 | false | false | false | false |
Meisolsson/PocketHub | app/src/main/java/com/github/pockethub/android/ui/helpers/ListFetcher.kt | 1 | 3199 | package com.github.pockethub.android.ui.helpers
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.github.pockethub.android.R
import com.github.pockethub.android.rx.AutoDisposeUtils
import com.xwray.groupie.Item
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.disposables.Disposables
import io.reactivex.schedulers.Schedulers
class ListFetcher<E>(
private val swipeRefreshLayout: SwipeRefreshLayout?,
private val lifecycle: Lifecycle,
private val itemListHandler: ItemListHandler,
private val showError: (Throwable) -> Unit,
private val loadData: (force: Boolean) -> Single<List<E>>,
private val createItem: (item: E) -> Item<*>
): LifecycleObserver {
/**
* Disposable for data load request.
*/
private var dataLoadDisposable: Disposable = Disposables.disposed()
private var isLoading = false
var onDataLoaded: (MutableList<Item<*>>) -> MutableList<Item<*>> = { items -> items }
init {
lifecycle.addObserver(this)
if (swipeRefreshLayout != null) {
swipeRefreshLayout.setOnRefreshListener(this::forceRefresh)
swipeRefreshLayout.setColorSchemeResources(
R.color.pager_title_background_top_start,
R.color.pager_title_background_end,
R.color.text_link,
R.color.pager_title_background_end)
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private fun onStart() {
refresh()
}
private fun refresh(force: Boolean) {
if (isLoading) {
return
}
if (!dataLoadDisposable.isDisposed) {
dataLoadDisposable.dispose()
}
isLoading = true
dataLoadDisposable = loadData(force)
.flatMap { items ->
Observable.fromIterable<E>(items)
.map<Item<*>> { this.createItem(it) }
.toList()
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.`as`(AutoDisposeUtils.bindToLifecycle<MutableList<Item<*>>>(lifecycle))
.subscribe(
{ this.onLoadFinished(it) },
{ this.onDataLoadError(it) }
)
}
fun refresh() {
refresh(false)
}
fun forceRefresh() {
swipeRefreshLayout!!.isRefreshing = true
refresh(true)
}
/**
* Called when the data has loaded.
*
* @param newItems The items added to the list.
*/
private fun onLoadFinished(newItems: MutableList<Item<*>>) {
isLoading = false
swipeRefreshLayout!!.isRefreshing = false
val items = onDataLoaded(newItems)
itemListHandler.update(items)
}
private fun onDataLoadError(throwable: Throwable) {
isLoading = false
swipeRefreshLayout!!.isRefreshing = false
showError(throwable)
}
} | apache-2.0 | 7efa829806cec236f9ec4f432cec8749 | 29.47619 | 89 | 0.637699 | 5.014107 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/cli/src/org/jetbrains/kotlin/tools/projectWizard/YamlSettingsParser.kt | 4 | 3085 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSettingReference
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingReference
import org.jetbrains.kotlin.tools.projectWizard.wizard.core.YamlParsingError
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.parser.ParserException
import java.nio.file.Path
@Suppress("HardCodedStringLiteral")
class YamlSettingsParser(settings: List<PluginSetting<Any, *>>, private val parsingState: ParsingState) {
private val settingByName = settings.associateBy { it.path }
fun parseYamlText(yaml: String): TaskResult<Map<SettingReference<*, *>, Any>> {
val yamlObject = try {
Success(Yaml().load<Any>(yaml) ?: emptyMap<String, Any>())
} catch (e: ParserException) {
Failure(YamlParsingError(e))
} catch (e: Exception) {
Failure(ExceptionErrorImpl(e))
}
return yamlObject.flatMap { map ->
if (map is Map<*, *>) {
val result = ComputeContext.runInComputeContextWithState(parsingState) {
parseSettingValues(map, "")
}
result.map { (pluginSettings, newState) ->
pluginSettings + newState.settingValues
}
} else Failure(
BadSettingValueError("Settings file should be a map of settings")
)
}
}
fun parseYamlFile(file: Path) = computeM {
val (yaml) = safe { file.toFile().readText() }
parseYamlText(yaml)
}
private fun ParsingContext.parseSettingValues(
data: Any,
settingPath: String
): TaskResult<Map<PluginSettingReference<*, *>, Any>> =
if (settingPath in settingByName) compute {
val setting = settingByName.getValue(settingPath)
val (parsed) = setting.type.parse(this, data, settingPath)
listOf(PluginSettingReference(setting) to parsed)
} else {
when (data) {
is Map<*, *> -> {
data.entries.mapCompute { (name, value) ->
if (value == null) fail(BadSettingValueError("No value was found for a key `$settingPath`"))
val prefix = if (settingPath.isEmpty()) "" else "$settingPath."
val (children) = parseSettingValues(value, "$prefix$name")
children.entries.map { (key, value) -> key to value }
}.sequence().map { it.flatten() }
}
else -> Failure(
BadSettingValueError("No value was found for a key `$settingPath`")
)
}
}.map { it.toMap() }
} | apache-2.0 | 18bf7d28fbf007bd04a03f627673c242 | 44.382353 | 158 | 0.613614 | 4.724349 | false | false | false | false |
GunoH/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/outputs/impl/OutputCollapsingGutterMouseListener.kt | 2 | 5842 | package org.jetbrains.plugins.notebooks.visualization.outputs.impl
import com.intellij.codeInsight.hints.presentation.MouseButton
import com.intellij.codeInsight.hints.presentation.mouseButton
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.editor.event.EditorMouseEvent
import com.intellij.openapi.editor.event.EditorMouseListener
import com.intellij.openapi.editor.event.EditorMouseMotionListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.EditorGutterComponentEx
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.wm.impl.IdeGlassPaneImpl
import com.intellij.util.asSafely
import org.jetbrains.plugins.notebooks.visualization.NotebookCellInlayManager
import org.jetbrains.plugins.notebooks.ui.visualization.notebookAppearance
import org.jetbrains.plugins.notebooks.visualization.outputs.hoveredCollapsingComponentRect
import java.awt.BorderLayout
import java.awt.Cursor
import java.awt.Point
import javax.swing.JComponent
import javax.swing.SwingUtilities
private class OutputCollapsingGutterMouseListener : EditorMouseListener, EditorMouseMotionListener {
private val EditorMouseEvent.notebookEditor: EditorEx?
get() = editor.takeIf { NotebookCellInlayManager.get(it) != null } as? EditorEx
override fun mousePressed(e: EditorMouseEvent) {
val editor = e.notebookEditor ?: return
val gutterComponentEx = editor.gutterComponentEx
val point = e.mouseEvent.takeIf { it.component === gutterComponentEx }?.point ?: return
if (!isAtCollapseVerticalStripe(editor, point)) return
val component = gutterComponentEx.hoveredCollapsingComponentRect ?: return
val actionManager = ActionManager.getInstance()
when (e.mouseEvent.mouseButton) {
MouseButton.Left -> {
e.consume()
val action = actionManager.getAction(NotebookOutputCollapseSingleInCellAction::class.java.simpleName)!!
actionManager.tryToExecute(action, e.mouseEvent, component, ActionPlaces.EDITOR_GUTTER_POPUP, true)
SwingUtilities.invokeLater { // Being invoked without postponing, it would access old states of layouts and get the same results.
if (!editor.isDisposed) {
updateState(editor, point)
}
}
}
MouseButton.Right -> {
e.consume()
val group = actionManager.getAction("NotebookOutputCollapseActions")
if (group is ActionGroup) {
val menu = actionManager.createActionPopupMenu(ActionPlaces.EDITOR_GUTTER_POPUP, group)
menu.setTargetComponent(component)
menu.component.show(gutterComponentEx, e.mouseEvent.x, e.mouseEvent.y)
}
}
else -> Unit
}
}
override fun mouseExited(e: EditorMouseEvent) {
val editor = e.notebookEditor ?: return
updateState(editor, null)
}
override fun mouseMoved(e: EditorMouseEvent) {
val editor = e.notebookEditor ?: return
updateState(editor, e.mouseEvent.point)
}
private fun updateState(editor: EditorEx, point: Point?) {
val gutterComponentEx = editor.gutterComponentEx
if (point == null || !isAtCollapseVerticalStripe(editor, point)) {
IdeGlassPaneImpl.forgetPreProcessedCursor(gutterComponentEx)
gutterComponentEx.cursor = @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") null // Huh? It's a valid operation!
updateHoveredComponent(gutterComponentEx, null)
}
else {
val collapsingComponent = getCollapsingComponent(editor, point)
updateHoveredComponent(gutterComponentEx, collapsingComponent)
if (collapsingComponent != null) {
val cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
IdeGlassPaneImpl.savePreProcessedCursor(gutterComponentEx, cursor)
gutterComponentEx.cursor = cursor
}
else {
IdeGlassPaneImpl.forgetPreProcessedCursor(gutterComponentEx)
}
}
}
private fun isAtCollapseVerticalStripe(editor: EditorEx, point: Point): Boolean =
if ((editor as EditorImpl).isMirrored) {
val margin = editor.notebookAppearance.LINE_NUMBERS_MARGIN / 2
CollapsingComponent.collapseRectHorizontalLeft(editor).let {
point.x in it - margin until it + CollapsingComponent.COLLAPSING_RECT_WIDTH - margin
}
}
else {
CollapsingComponent.collapseRectHorizontalLeft(editor).let {
point.x in it until it + CollapsingComponent.COLLAPSING_RECT_WIDTH
}
}
private fun getCollapsingComponent(editor: EditorEx, point: Point): CollapsingComponent? {
val surroundingX = if ((editor as EditorImpl).isMirrored) 80 else 0
val surroundingComponent =
editor.contentComponent.getComponentAt(surroundingX, point.y)
.asSafely<JComponent>()
?.takeIf { it.componentCount > 0 }
?.getComponent(0)
?.asSafely<SurroundingComponent>()
?: return null
val innerComponent =
(surroundingComponent.layout as BorderLayout).getLayoutComponent(BorderLayout.CENTER).asSafely<InnerComponent>()
?: return null
val y = point.y - SwingUtilities.convertPoint(innerComponent, 0, 0, editor.contentComponent).y
val collapsingComponent =
innerComponent.getComponentAt(0, y).asSafely<CollapsingComponent>()
?: return null
if (!collapsingComponent.isWorthCollapsing) return null
return collapsingComponent
}
private fun updateHoveredComponent(gutterComponentEx: EditorGutterComponentEx, collapsingComponent: CollapsingComponent?) {
val old = gutterComponentEx.hoveredCollapsingComponentRect
if (old !== collapsingComponent) {
gutterComponentEx.hoveredCollapsingComponentRect = collapsingComponent
gutterComponentEx.repaint()
}
}
} | apache-2.0 | 68a7f41dd1d9b941ff594357cca6a3ce | 40.735714 | 138 | 0.750599 | 4.97615 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/ide/navigationToolbar/experimental/NewToolbarBorderLayout.kt | 1 | 2517 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.navigationToolbar.experimental
import java.awt.BorderLayout
import java.awt.Component
import java.awt.Container
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.lang.Integer.min
import javax.swing.JComponent
class NewToolbarBorderLayout : BorderLayout() {
private var lastTarget: Container? = null
private val componentListener = object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
layoutContainer(lastTarget)
}
override fun componentMoved(e: ComponentEvent?) {
layoutContainer(lastTarget)
}
}
override fun addLayoutComponent(comp: Component?, constraints: Any?) {
super.addLayoutComponent(comp, constraints)
if (comp is JComponent) {
comp.components.forEach { it.addComponentListener(componentListener) }
}
comp?.addComponentListener(componentListener)
}
override fun layoutContainer(target: Container?) {
synchronized(target!!.treeLock) {
lastTarget = target
val insets = target.insets
var top = insets.top
var bottom = target.height - insets.bottom
var left = insets.left
var right = target.width - insets.right
var c: Component?
if (getLayoutComponent(EAST).also { c = it } != null) {
val d = c!!.preferredSize
var hdiff = 0
if (target.height > 0 && d.height > 0) {
hdiff = (target.height - d.height) / 2
}
c!!.setSize(c!!.width, bottom - top)
c!!.setBounds(right - d.width, top + hdiff, d.width, bottom - top)
right -= d.width + hgap
}
if (getLayoutComponent(CENTER).also { c = it } != null) {
val d = c!!.preferredSize
var hdiff = 0
if (target.height > 0 && d.height > 0) {
hdiff = (target.height - d.height) / 2
}
c!!.setBounds(right - c!!.preferredSize.width, top + hdiff, c!!.preferredSize.width, bottom - top)
right -= d.width + hgap
}
if (getLayoutComponent(WEST).also { c = it } != null) {
val d = c!!.preferredSize
var hdiff = 0
if (target.height > 0 && d.height > 0) {
hdiff = (target.height - d.height) / 2
}
c!!.setBounds(left, top + hdiff, min(d.width, right), bottom - top)
left += d.width + hgap
}
}
}
} | apache-2.0 | bc859037afff1d09039832952bc59d7d | 32.131579 | 158 | 0.633294 | 4.160331 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/di/module/ActivityModule.kt | 1 | 2589 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.di.module
import com.zwq65.unity.di.ActivityScoped
import com.zwq65.unity.ui.activity.*
import com.zwq65.unity.ui.module.*
import com.zwq65.unity.ui.provider.*
import dagger.Module
import dagger.android.ContributesAndroidInjector
/**
* We want Dagger.Android to create a Subcomponent which has a parent Component of whichever module ActivityBindingModule is on,
* in our case that will be AppComponent. The beautiful part about this setup is that you never need to tell AppComponent
* that it is going to have all these subcomponents
* nor do you need to tell these subcomponents that AppComponent exists.
* We are also telling Dagger.Android that this generated SubComponent needs to include the specified modules
* and be aware of a scope annotation @ActivityScoped
* When Dagger.Android annotation processor runs it will create 4 subcomponents for us.
*/
@Module
abstract class ActivityModule {
@ActivityScoped
@ContributesAndroidInjector(modules = [(MainModule::class), (AlbumProvider::class), (RestVideoProvider::class), (TestProvider::class), (ArticleProvider::class), (TabArticleProvider::class)])
internal abstract fun mainActivity(): MainActivity
@ActivityScoped
@ContributesAndroidInjector(modules = [(AccountModule::class)])
internal abstract fun accountActivity(): AccountActivity
@ActivityScoped
@ContributesAndroidInjector(modules = [(ImageModule::class)])
internal abstract fun imageActivity(): ImageActivity
@ActivityScoped
@ContributesAndroidInjector(modules = [(LoginModule::class)])
internal abstract fun loginActivity(): LoginActivity
@ActivityScoped
@ContributesAndroidInjector(modules = [(WebArticleModule::class)])
internal abstract fun webArticleActivity(): WebArticleActivity
@ActivityScoped
@ContributesAndroidInjector(modules = [(WatchModule::class)])
internal abstract fun watchActivity(): WatchActivity
}
| apache-2.0 | 10ed71bf29c2bc9be6c69cae241416e6 | 40.758065 | 194 | 0.75898 | 4.73309 | false | false | false | false |
7449/Album | material/src/main/java/com/gallery/ui/material/activity/MaterialPreActivity.kt | 1 | 5088 | package com.gallery.ui.material.activity
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import com.bumptech.glide.Glide
import com.gallery.compat.activity.PrevCompatActivity
import com.gallery.compat.extensions.requirePrevFragment
import com.gallery.compat.widget.GalleryImageView
import com.gallery.core.GalleryBundle
import com.gallery.core.delegate.IPrevDelegate
import com.gallery.core.entity.ScanEntity
import com.gallery.core.extensions.drawableExpand
import com.gallery.core.extensions.safeToastExpand
import com.gallery.ui.material.R
import com.gallery.ui.material.args.MaterialGalleryBundle
import com.gallery.ui.material.databinding.MaterialGalleryActivityPreviewBinding
import com.gallery.ui.material.materialGalleryArgOrDefault
open class MaterialPreActivity : PrevCompatActivity() {
companion object {
private const val format = "%s / %s"
}
private val viewBinding: MaterialGalleryActivityPreviewBinding by lazy {
MaterialGalleryActivityPreviewBinding.inflate(layoutInflater)
}
private val materialGalleryBundle: MaterialGalleryBundle by lazy {
gapConfig.materialGalleryArgOrDefault
}
override val galleryFragmentId: Int
get() = R.id.preFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewBinding.root)
window.statusBarColor = materialGalleryBundle.statusBarColor
viewBinding.toolbar.setTitleTextColor(materialGalleryBundle.toolbarTextColor)
val drawable = drawableExpand(materialGalleryBundle.toolbarIcon)
drawable?.colorFilter =
PorterDuffColorFilter(materialGalleryBundle.toolbarIconColor, PorterDuff.Mode.SRC_ATOP)
viewBinding.toolbar.navigationIcon = drawable
viewBinding.toolbar.setBackgroundColor(materialGalleryBundle.toolbarBackground)
viewBinding.toolbar.elevation = materialGalleryBundle.toolbarElevation
viewBinding.count.textSize = materialGalleryBundle.preBottomCountTextSize
viewBinding.count.setTextColor(materialGalleryBundle.preBottomCountTextColor)
viewBinding.bottomView.setBackgroundColor(materialGalleryBundle.preBottomViewBackground)
viewBinding.bottomViewSelect.text = materialGalleryBundle.preBottomOkText
viewBinding.bottomViewSelect.textSize = materialGalleryBundle.preBottomOkTextSize
viewBinding.bottomViewSelect.setTextColor(materialGalleryBundle.preBottomOkTextColor)
viewBinding.bottomViewSelect.setOnClickListener {
if (requirePrevFragment.isSelectEmpty) {
onGallerySelectEmpty()
} else {
onGallerySelectEntities()
}
}
viewBinding.toolbar.setNavigationOnClickListener { onGalleryFinish() }
}
override fun onDisplayGalleryPrev(scanEntity: ScanEntity, container: FrameLayout) {
container.removeAllViews()
val imageView = GalleryImageView(container.context).apply {
layoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
).apply {
gravity = Gravity.CENTER
}
}
Glide.with(container.context)
.load(scanEntity.uri)
.into(imageView)
container.addView(imageView)
}
override fun onPrevCreated(
delegate: IPrevDelegate,
bundle: GalleryBundle,
savedInstanceState: Bundle?
) {
delegate.rootView.setBackgroundColor(materialGalleryBundle.prevRootBackground)
viewBinding.count.text =
format.format(delegate.selectCount, galleryConfig.multipleMaxCount)
viewBinding.toolbar.title =
materialGalleryBundle.preTitle + "(" + (delegate.currentPosition + 1) + "/" + delegate.itemCount + ")"
}
override fun onClickItemFileNotExist(
context: Context,
bundle: GalleryBundle,
scanEntity: ScanEntity
) {
super.onClickItemFileNotExist(context, bundle, scanEntity)
viewBinding.count.text =
format.format(requirePrevFragment.selectCount, bundle.multipleMaxCount)
}
override fun onPageSelected(position: Int) {
viewBinding.toolbar.title =
materialGalleryBundle.preTitle + "(" + (position + 1) + "/" + requirePrevFragment.itemCount + ")"
}
override fun onChangedCheckBox() {
viewBinding.count.text =
format.format(requirePrevFragment.selectCount, galleryConfig.multipleMaxCount)
}
open fun onGallerySelectEmpty() {
getString(R.string.material_gallery_prev_select_empty_pre).safeToastExpand(this)
}
} | mpl-2.0 | 867775a1e8a5df0b152f6a959c4590e3 | 39.382114 | 118 | 0.706368 | 5.41853 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | platform/testFramework/src/com/intellij/testFramework/utils/inlays/InlayParameterHintsTest.kt | 3 | 7101 | /*
* Copyright 2000-2017 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.testFramework.utils.inlays
import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager
import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.VisualPosition
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.util.TextRange
import com.intellij.rt.execution.junit.FileComparisonFailure
import com.intellij.testFramework.VfsTestUtil
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
import junit.framework.ComparisonFailure
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import java.util.regex.Pattern
class InlayHintsChecker(private val myFixture: CodeInsightTestFixture) {
private var isParamHintsEnabledBefore = false
companion object {
val pattern: Pattern = Pattern.compile("(<caret>)|(<selection>)|(</selection>)|<(hint|HINT|Hint|hINT)\\s+text=\"([^\"\n\r]+)\"\\s*/>")
private val default = ParameterNameHintsSettings()
}
fun setUp() {
val settings = EditorSettingsExternalizable.getInstance()
isParamHintsEnabledBefore = settings.isShowParameterNameHints
settings.isShowParameterNameHints = true
}
fun tearDown() {
EditorSettingsExternalizable.getInstance().isShowParameterNameHints = isParamHintsEnabledBefore
val hintSettings = ParameterNameHintsSettings.getInstance()
hintSettings.loadState(default.state)
}
fun checkInlays() {
val file = myFixture.file
val document = myFixture.getDocument(file)
val originalText = document.text
val expectedInlaysAndCaret = extractInlaysAndCaretInfo(document)
myFixture.doHighlighting()
verifyInlaysAndCaretInfo(expectedInlaysAndCaret, originalText)
}
fun verifyInlaysAndCaretInfo(expectedInlaysAndCaret: CaretAndInlaysInfo, originalText: String) {
val file = myFixture.file
val document = myFixture.getDocument(file)
val actual: List<ParamHintInfo> = getActualInlays()
val expected = expectedInlaysAndCaret.inlays
if (expectedInlaysAndCaret.inlays.size != actual.size || actual.zip(expected).any { it.first != it.second }) {
val entries: MutableList<Pair<Int, String>> = mutableListOf()
actual.forEach { entries.add(Pair(it.offset, buildString {
append("<")
append((if (it.highlighted) "H" else "h"))
append((if (it.current) "INT" else "int"))
append(" text=\"")
append(it.text)
append("\"/>")
}))}
if (expectedInlaysAndCaret.caretOffset != null) {
val actualCaretOffset = myFixture.editor.caretModel.offset
val actualInlaysBeforeCaret = myFixture.editor.caretModel.visualPosition.column -
myFixture.editor.offsetToVisualPosition(actualCaretOffset).column
val first = entries.indexOfFirst { it.first == actualCaretOffset }
val insertIndex = if (first == -1) -entries.binarySearch { it.first - actualCaretOffset } - 1
else first + actualInlaysBeforeCaret
entries.add(insertIndex, Pair(actualCaretOffset, "<caret>"))
}
val proposedText = StringBuilder(document.text)
entries.asReversed().forEach { proposedText.insert(it.first, it.second) }
VfsTestUtil.TEST_DATA_FILE_PATH.get(file.virtualFile)?.let { originalPath ->
throw FileComparisonFailure("Hints differ", originalText, proposedText.toString(), originalPath)
} ?: throw ComparisonFailure("Hints differ", originalText, proposedText.toString())
}
if (expectedInlaysAndCaret.caretOffset != null) {
assertEquals("Unexpected caret offset", expectedInlaysAndCaret.caretOffset, myFixture.editor.caretModel.offset)
val position = myFixture.editor.offsetToVisualPosition(expectedInlaysAndCaret.caretOffset)
assertEquals("Unexpected caret visual position",
VisualPosition(position.line, position.column + expectedInlaysAndCaret.inlaysBeforeCaret),
myFixture.editor.caretModel.visualPosition)
val selectionModel = myFixture.editor.selectionModel
if (expectedInlaysAndCaret.selection == null) assertFalse(selectionModel.hasSelection())
else assertEquals("Unexpected selection",
expectedInlaysAndCaret.selection,
TextRange(selectionModel.selectionStart, selectionModel.selectionEnd))
}
}
private fun getActualInlays(): List<ParamHintInfo> {
val editor = myFixture.editor
val allInlays = editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength)
val hintManager = ParameterHintsPresentationManager.getInstance()
return allInlays
.filter { hintManager.isParameterHint(it) }
.map { ParamHintInfo(it.offset, hintManager.getHintText(it), hintManager.isHighlighted(it), hintManager.isCurrent(it))}
.sortedBy { it.offset }
}
fun extractInlaysAndCaretInfo(document: Document): CaretAndInlaysInfo {
val text = document.text
val matcher = pattern.matcher(text)
val inlays = mutableListOf<ParamHintInfo>()
var extractedLength = 0
var caretOffset : Int? = null
var inlaysBeforeCaret = 0
var selectionStart : Int? = null
var selectionEnd : Int? = null
while (matcher.find()) {
val start = matcher.start()
val matchedLength = matcher.end() - start
val realStartOffset = start - extractedLength
if (matcher.group(1) != null) {
caretOffset = realStartOffset
inlays.asReversed()
.takeWhile { it.offset == caretOffset }
.forEach { inlaysBeforeCaret++ }
}
else if (matcher.group(2) != null) {
selectionStart = realStartOffset
}
else if (matcher.group(3) != null) {
selectionEnd = realStartOffset
}
else {
inlays += ParamHintInfo(realStartOffset, matcher.group(5), matcher.group(4).startsWith("H"), matcher.group(4).endsWith("INT"))
}
removeText(document, realStartOffset, matchedLength)
extractedLength += (matcher.end() - start)
}
return CaretAndInlaysInfo(caretOffset, inlaysBeforeCaret,
if (selectionStart == null || selectionEnd == null) null else TextRange(selectionStart, selectionEnd),
inlays)
}
private fun removeText(document: Document, realStartOffset: Int, matchedLength: Int) {
WriteCommandAction.runWriteCommandAction(myFixture.project, {
document.replaceString(realStartOffset, realStartOffset + matchedLength, "")
})
}
}
class CaretAndInlaysInfo (val caretOffset: Int?, val inlaysBeforeCaret: Int, val selection: TextRange?,
val inlays: List<ParamHintInfo>)
data class ParamHintInfo (val offset: Int, val text: String, val highlighted: Boolean, val current: Boolean) | apache-2.0 | 3e54d532fbe67e588b075e3d062360fd | 41.783133 | 140 | 0.712576 | 5.004228 | false | false | false | false |
vicpinm/KPresenterAdapter | kpa-processor/src/main/java/com/vicpin/kpa/annotation/processor/AdapterWritter.kt | 1 | 2549 | package com.vicpin.kpa.annotation.processor
import com.vicpin.kpa.annotation.processor.model.Model
import java.io.File
import java.io.IOException
import javax.annotation.processing.ProcessingEnvironment
/**
* Created by victor on 10/12/17.
*/
class AdapterWritter(private val entity: Model.EntityModel) {
private var text: String = ""
private val className: String
val KAPT_KOTLIN_GENERATED_OPTION = "kapt.kotlin.generated"
init {
this.className = entity.name + ADAPTER_SUFIX
}
private fun generateClass(): String {
appendPackpage()
appendImports()
appendClassName()
appendGetViewInfomethod()
appendClassEnding()
return text
}
private fun appendPackpage() {
newLine("package ${entity.pkg}", newLine = true)
}
private fun appendImports() {
newLine("import ${entity.modelClass}")
newLine("import com.vicpin.kpresenteradapter.PresenterAdapter")
newLine("import com.vicpin.kpresenteradapter.model.ViewInfo", newLine = true)
}
private fun appendClassName() {
newLine("class TownPresenterAdapter(val layoutRes: Int) : PresenterAdapter<${entity.name}>() {")
}
private fun appendGetViewInfomethod() {
newLine("override fun getViewInfo(position: Int) = ViewInfo(${entity.name}ViewHolderParent::class, layoutRes)", level = 1)
}
private fun appendClassEnding() {
newLine("}")
}
fun generateFile(env: ProcessingEnvironment) {
try { // write the env
val options = env.options
val kotlinGenerated = options[KAPT_KOTLIN_GENERATED_OPTION] ?: ""
File(kotlinGenerated.replace("kaptKotlin","kapt"), "$className.kt").writer().buffered().use {
it.appendln(generateClass())
}
} catch (e: IOException) {
// Note: calling e.printStackTrace() will print IO errors
// that occur from the file already existing after its first run, this is normal
}
}
fun newLine(line: String = "", level: Int = 0, newLine: Boolean = false) {
var indentation = ""
var semicolon = if (!line.isEmpty() && !line.endsWith("}") && !line.endsWith("{")) ";" else ""
(1..level).forEach { indentation += "\t" }
text += if (newLine) {
"$indentation$line$semicolon\n\n"
} else {
"$indentation$line$semicolon\n"
}
}
companion object {
public val ADAPTER_SUFIX = "PresenterAdapter"
}
} | apache-2.0 | d25aab1275017b086a744b25dfa4e878 | 27.651685 | 130 | 0.622597 | 4.47193 | false | false | false | false |
sksamuel/ktest | kotest-property/src/jvmMain/kotlin/io/kotest/property/arbitrary/targetDefaultForClassName.kt | 1 | 2880 | package io.kotest.property.arbitrary
import io.kotest.property.Arb
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
import java.math.BigDecimal
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.Period
import kotlin.reflect.full.isSubclassOf
@Suppress("UNCHECKED_CAST")
actual inline fun <reified A> targetDefaultForClass(): Arb<A>? {
return when {
A::class.isSubclassOf(List::class) -> {
val type = object : TypeReference<A>() {}.type as ParameterizedType
val first = type.actualTypeArguments.first() as WildcardType
val upper = first.upperBounds.first() as Class<*>
Arb.list(defaultForClass<Any>(upper.kotlin) as Arb<Any>) as Arb<A>
}
A::class.isSubclassOf(Set::class) -> {
val type = object : TypeReference<A>() {}.type as ParameterizedType
val first = type.actualTypeArguments.first() as WildcardType
val upper = first.upperBounds.first() as Class<*>
Arb.set(defaultForClass<Any>(upper.kotlin) as Arb<Any>) as Arb<A>
}
A::class.isSubclassOf(Pair::class) -> {
val type = object : TypeReference<A>() {}.type as ParameterizedType
val first = (type.actualTypeArguments[0] as WildcardType).upperBounds.first() as Class<*>
val second = (type.actualTypeArguments[1] as WildcardType).upperBounds.first() as Class<*>
Arb.pair(defaultForClass<Any>(first.kotlin)!!, defaultForClass<Any>(second.kotlin)!!) as Arb<A>
}
A::class.isSubclassOf(Map::class) -> {
val type = object : TypeReference<A>() {}.type as ParameterizedType
// map key type can have or have not variance
val first = if (type.actualTypeArguments[0] is Class<*>) {
type.actualTypeArguments[0] as Class<*>
} else {
(type.actualTypeArguments[0] as WildcardType).upperBounds.first() as Class<*>
}
val second = (type.actualTypeArguments[1] as WildcardType).upperBounds.first() as Class<*>
Arb.map(defaultForClass<Any>(first.kotlin)!!, defaultForClass<Any>(second.kotlin)!!) as Arb<A>
}
A::class == LocalDate::class -> Arb.localDate() as Arb<A>
A::class == LocalDateTime::class -> Arb.localDateTime() as Arb<A>
A::class == LocalTime::class -> Arb.localTime() as Arb<A>
A::class == Period::class -> Arb.period() as Arb<A>
A::class == BigDecimal::class -> Arb.bigDecimal() as Arb<A>
else -> null
}
}
// need some supertype that types a type param so it gets baked into the class file
abstract class TypeReference<T> : Comparable<TypeReference<T>> {
// this is the type of T
val type: Type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
override fun compareTo(other: TypeReference<T>) = 0
}
| mit | 9d7d52483859fc5d68bc7f29f8023cfa | 46.213115 | 104 | 0.671528 | 4.198251 | false | false | false | false |
zak0/CalendarCountdown | app/src/main/java/zak0/github/calendarcountdown/storage/DatabaseHelper.kt | 1 | 13807 | package zak0.github.calendarcountdown.storage
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import zak0.github.calendarcountdown.data.CountdownSettings
import zak0.github.calendarcountdown.data.ExcludedDays
import zak0.github.calendarcountdown.data.GeneralSettings
import java.util.*
/**
* Handler for all SQLite activity.
* Reads and writes into the database.
*
* Created by jaakko on 24.6.2018.
*/
class DatabaseHelper(context: Context,
name: String,
version: Int)
: SQLiteOpenHelper(context, name, null, version) {
// Member variables
private var db: SQLiteDatabase? = null
fun openDb() {
Log.d(TAG, "openDb() - called")
db = this.writableDatabase
}
fun closeDb() {
Log.d(TAG, "closeDb() - called")
db?.close()
}
override fun onCreate(db: SQLiteDatabase) {
initSchema(db)
Log.d(TAG, "onCreate() - done")
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// Add general settings table
if (oldVersion == 1 && newVersion > 1) {
// create generalsettings table
val sql = "CREATE TABLE '" + TBLGENERALSETTINGS + "' (" +
"'" + COLGSSORTBY + "' INTEGER)"
db.execSQL(sql)
// init general settings table with "default" values
// note: this table only has one row
this.db = db
saveGeneralSettings()
}
}
/**
* Constructs empty tables. This is called when DB is first created.
*/
private fun initSchema(db: SQLiteDatabase) {
// create countdown table
var sql = "CREATE TABLE '" + TBLCOUNTDOWN + "' (" +
"`" + COLCOUNTDOWNID + "` INTEGER," +
"`" + COLCDENDDATE + "` TEXT," +
"`" + COLCDEXCLUDEWEEKENDS + "` INTEGER," +
"`" + COLCDLABEL + "` TEXT," +
"`" + COLCDWIDGET + "` INTEGER," +
"PRIMARY KEY(" + COLCOUNTDOWNID + ")" +
")"
db.execSQL(sql)
// create excludeddays table
sql = "CREATE TABLE `" + TBLEXCLUDEDDAYS + "` (" +
"`" + COLEXCLUDEDDAYSID + "` INTEGER," +
"`" + COLCOUNTDOWNID + "` INTEGER," +
"`" + COLEDFROMDATE + "` TEXT," +
"`" + COLEDTODATE + "` TEXT," +
"PRIMARY KEY(" + COLEXCLUDEDDAYSID + ")" +
")"
db.execSQL(sql)
// create generalsettings table
sql = "CREATE TABLE '" + TBLGENERALSETTINGS + "' (" +
"'" + COLGSSORTBY + "' INTEGER)"
db.execSQL(sql)
// init general settings table with "default" values
// note: this table only has one row
this.db = db
saveGeneralSettings()
Log.d(TAG, "initSchema() - done")
}
/**
* Loads the Countdowns that are set to be used on a widget.
*/
fun loadSettingsForWidget(): List<CountdownSettings> {
val ret = ArrayList<CountdownSettings>()
val sql = "select * from $TBLCOUNTDOWN where $COLCDWIDGET=1"
db?.also { db ->
val cur = db.rawQuery(sql, null)
cur.moveToFirst()
var countdown: CountdownSettings
while (!cur.isAfterLast) {
countdown = cursorToCountdown(cur)
ret.add(countdown)
// Load excluded date ranges for countdown
loadExcludedDaysForCountdown(countdown)
cur.moveToNext()
}
}
return ret
}
fun saveGeneralSettings() {
val gs = GeneralSettings
// GeneralSettings table only has one row.
// Empty the table before saving to ensure there stays only one...
var sql = "delete from $TBLGENERALSETTINGS"
db?.execSQL(sql)
// ...Then insert the settings into the table.
sql = "insert into " + TBLGENERALSETTINGS + " (" +
COLGSSORTBY + ") values (" +
gs.sortOrder + ")"
db?.execSQL(sql)
}
fun loadGeneralSettings() {
val gs = GeneralSettings
// GeneralSettings table only has a one row
val sql = "select * from $TBLGENERALSETTINGS"
db?.also { db ->
val cur = db.rawQuery(sql, null)
cur.moveToFirst()
if (!cur.isAfterLast) {
gs.sortOrder = cur.getInt(0)
}
cur.close()
}
}
/**
* Loads countdown with specific ID from the database.
* Returns null if nothing is found.
*/
fun loadSetting(id: Int): CountdownSettings? {
val sql = "select * from $TBLCOUNTDOWN where $COLCOUNTDOWNID = $id"
var countdown: CountdownSettings? = null
db?.also { db ->
val cur = db.rawQuery(sql, null)
cur.moveToFirst()
if (!cur.isAfterLast) {
countdown = cursorToCountdown(cur)
// Load excluded date ranges for countdown
countdown?.also {
loadExcludedDaysForCountdown(it)
}
cur.moveToNext()
}
}
Log.d(TAG, "loadSetting() - loaded countdown with title '${countdown?.label ?: "null"}' from DB")
return countdown
}
/**
* Reads and returns settings from database.
*/
fun loadSettings(): List<CountdownSettings> {
val ret = ArrayList<CountdownSettings>()
val sql = "select * from $TBLCOUNTDOWN"
db?.also { db ->
val cur = db.rawQuery(sql, null)
cur.moveToFirst()
var countdown: CountdownSettings
while (!cur.isAfterLast) {
countdown = cursorToCountdown(cur)
ret.add(countdown)
// Load excluded date ranges for countdown
loadExcludedDaysForCountdown(countdown)
cur.moveToNext()
}
}
Log.d(TAG, "loadSettings() - loaded " + Integer.toString(ret.size) + " countdowns from DB")
return ret
}
/**
* Loads and sets excluded date ranges for given countdown.
*/
private fun loadExcludedDaysForCountdown(countdown: CountdownSettings) {
val sql = "select * from " + TBLEXCLUDEDDAYS +
" where " + COLCOUNTDOWNID + "=" + Integer.toString(countdown.dbId)
db?.also { db ->
val cur = db.rawQuery(sql, null)
cur.moveToFirst()
var exclDays: ExcludedDays
while (!cur.isAfterLast) {
exclDays = cursorToExcludedDays(cur)
exclDays.setSettings(countdown) // this is null before setting
countdown.addExcludedDays(exclDays)
cur.moveToNext()
}
}
}
/**
* Saves a given countdown into the database.
*/
fun saveCountdownToDB(settings: CountdownSettings) {
val list = ArrayList<CountdownSettings>()
list.add(settings)
saveToDB(list)
}
/**
* Saves all settings given as parameter into DB.
*/
private fun saveToDB(list: List<CountdownSettings>) {
var sql: String
// Iterate through all the settings.
for (settings in list) {
db?.also { db ->
// Check if entry for current CountDownSettings already exists in DB
sql = "select * from " + TBLCOUNTDOWN + " where " + COLCOUNTDOWNID + "=" + Integer.toString(settings.dbId)
val cur = db.rawQuery(sql, null)
if (cur.count > 0) {
// It id already exist --> update existing
Log.d(TAG, "saveToDB() - updating countdownid " + Integer.toString(settings.dbId))
sql = "update " + TBLCOUNTDOWN + " set " + COLCDENDDATE + "='" + settings.endDate + "'," +
COLCDEXCLUDEWEEKENDS + "=" + (if (settings.isExcludeWeekends) "1" else "0") + "," +
COLCDLABEL + "='" + settings.label + "'," +
COLCDWIDGET + "=" + (if (settings.isUseOnWidget) "1" else "0") + " where " + COLCOUNTDOWNID + "=" + Integer.toString(settings.dbId)
db.execSQL(sql)
} else {
// It did not exist --> insert a new entry
Log.d(TAG, "saveToDB() - inserting a new countdown entry")
sql = "insert into " + TBLCOUNTDOWN + "(" + COLCDENDDATE + "," + COLCDEXCLUDEWEEKENDS + "," + COLCDLABEL + "," + COLCDWIDGET + ") " +
"values('" + settings.endDate + "'," + (if (settings.isExcludeWeekends) "1" else "0") + "," +
"'" + settings.label + "'," + (if (settings.isUseOnWidget) "1" else "0") + ")"
db.execSQL(sql)
// Update settings with corresponding rowID.
// (Used when inserting excluded ranges)
val rowIdCur = db.rawQuery("select last_insert_rowid();", null)
rowIdCur.moveToFirst()
settings.dbId = rowIdCur.getInt(0)
rowIdCur.close()
}
cur.close()
// Save excluded date ranges.
saveExcludedDaysOfCountdown(settings)
}
}
}
private fun saveExcludedDaysOfCountdown(countdown: CountdownSettings) {
// First clear all the existing excluded ranges for the countdown.
var sql = "delete from " + TBLEXCLUDEDDAYS +
" where " + COLCOUNTDOWNID + "=" + Integer.toString(countdown.dbId)
db?.execSQL(sql)
db?.also { db ->
for (excludedDays in countdown.excludedDays) {
// Check if entry already exists.
sql = "select * from " + TBLEXCLUDEDDAYS + " where " + COLEXCLUDEDDAYSID + "=" + Integer.toString(excludedDays.dbId)
val cur = db.rawQuery(sql, null)
if (cur.count > 0) {
// Entry did already exist --> update it.
Log.d(TAG, "saveExcludedDaysOfCountdown() - updating an excludeddays entry")
sql = "update " + TBLEXCLUDEDDAYS + " set " +
COLEDFROMDATE + "='" + excludedDays.fromDate + "'," +
COLEDTODATE + "='" + excludedDays.toDate + "'" +
" where " + COLEXCLUDEDDAYSID + "=" + Integer.toString(excludedDays.dbId)
db.execSQL(sql)
} else {
// Did not already exist in the database.
// --> insert a new one.
Log.d(TAG, "saveExcludedDaysOfCountdown() - inserting a new excludeddays entry")
sql = ("insert into " + TBLEXCLUDEDDAYS + "(" +
COLCOUNTDOWNID + "," +
COLEDFROMDATE + "," +
COLEDTODATE + ") values ("
+ Integer.toString(countdown.dbId) + ",'" +
excludedDays.fromDate + "','" +
excludedDays.toDate + "')")
db.execSQL(sql)
// Update excludedDays with corresponding rowID.
val exclRowIdCur = db.rawQuery("select last_insert_rowid();", null)
exclRowIdCur.moveToFirst()
excludedDays.dbId = exclRowIdCur.getInt(0)
exclRowIdCur.close()
}
cur.close()
}
}
}
private fun cursorToCountdown(cur: Cursor): CountdownSettings {
val ret = CountdownSettings()
ret.dbId = cur.getInt(0)
ret.endDate = cur.getString(1)
ret.isExcludeWeekends = cur.getInt(2) == 1
ret.label = cur.getString(3)
ret.isUseOnWidget = cur.getInt(4) == 1
return ret
}
private fun cursorToExcludedDays(cur: Cursor): ExcludedDays {
val ret = ExcludedDays()
ret.dbId = cur.getInt(0)
ret.fromDate = cur.getString(2)
ret.toDate = cur.getString(3)
return ret
}
/**
* Daletes given countdown from the database.
*/
fun deleteCountdown(settings: CountdownSettings) {
// First delete excluded date ranges.
var sql = "delete from " + TBLEXCLUDEDDAYS +
" where " + COLCOUNTDOWNID + "=" + Integer.toString(settings.dbId)
db?.execSQL(sql)
// Then delete the countdown itself.
sql = "delete from " + TBLCOUNTDOWN +
" where " + COLCOUNTDOWNID + "=" + Integer.toString(settings.dbId)
db?.execSQL(sql)
}
companion object {
private val TAG = DatabaseHelper::class.java.simpleName
const val DB_NAME = "calendarcountdown.db"
const val DB_VERSION = 2
private const val TBLCOUNTDOWN = "countdown"
private const val TBLEXCLUDEDDAYS = "excludeddays"
private const val TBLGENERALSETTINGS = "generalsettings"
private const val COLCOUNTDOWNID = "countdownid"
private const val COLCDENDDATE = "cdenddate"
private const val COLCDEXCLUDEWEEKENDS = "cdexcludeweekends"
private const val COLCDLABEL = "cdlabel"
private const val COLCDWIDGET = "cdwidget"
private const val COLEXCLUDEDDAYSID = "excludeddaysid"
private const val COLEDFROMDATE = "edfromdate"
private const val COLEDTODATE = "edtodate"
private const val COLGSSORTBY = "gssortby"
}
}
| mit | 4be6c44e97003666b46f0af24f133a21 | 33.778338 | 159 | 0.535018 | 4.875353 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/inspections/kotlin/KotlinLogLevelInspection.kt | 1 | 4444 | package com.gmail.blueboxware.libgdxplugin.inspections.kotlin
import com.gmail.blueboxware.libgdxplugin.message
import com.gmail.blueboxware.libgdxplugin.utils.compat.getCalleeExpressionIfAny
import com.gmail.blueboxware.libgdxplugin.utils.compat.isGetter
import com.gmail.blueboxware.libgdxplugin.utils.isSetLogLevel
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName
import org.jetbrains.kotlin.idea.references.SyntheticPropertyAccessorReference
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.psi.*
/*
* Copyright 2016 Blue Box Ware
*
* 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.
*/
class KotlinLogLevelInspection : LibGDXKotlinBaseInspection() {
override fun getStaticDescription() = message("log.level.html.description")
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitCallExpression(expression: KtCallExpression) {
val refs = expression.calleeExpression?.references ?: return
for (ref in refs) {
val target = ref.resolve() ?: continue
if (target is PsiMethod) {
val clazz = target.containingClass ?: continue
val methodName = expression.calleeExpression?.text ?: continue
if (isSetLogLevel(clazz, methodName)) {
val argument =
expression.valueArgumentList?.arguments?.firstOrNull()?.getArgumentExpression() ?: return
if (isLogLevelArgument(argument)) {
holder.registerProblem(expression, message("log.level.problem.descriptor"))
}
}
}
}
}
override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
(expression.context as? KtBinaryExpression)?.let { context ->
val operator = (context.operationToken as? KtSingleValueToken)?.value ?: return
if (operator != "=") return
val refs = expression.selectorExpression?.references ?: return
for (ref in refs) {
if ((ref as? SyntheticPropertyAccessorReference)?.isGetter() == false) {
val target = ref.resolve()
if (target is PsiMethod) {
val clazz = target.containingClass ?: continue
val methodName = target.name
if (isSetLogLevel(clazz, methodName)) {
val argument = context.right ?: continue
if (isLogLevelArgument(argument)) {
holder.registerProblem(context, message("log.level.problem.descriptor"))
}
}
}
}
}
}
}
}
}
private fun isLogLevelArgument(expression: KtExpression?): Boolean {
if (expression is KtConstantExpression && (expression.text == "3" || expression.text == "4")) {
return true
} else if (expression is KtDotQualifiedExpression) {
val refs = expression.getCalleeExpressionIfAny()?.references ?: return false
for (ref in refs) {
val target = ref.resolve()?.getKotlinFqName()?.asString() ?: continue
if (
target == "com.badlogic.gdx.Application.LOG_DEBUG"
|| target == "com.badlogic.gdx.Application.LOG_INFO"
|| target == "com.badlogic.gdx.utils.Logger.DEBUG"
|| target == "com.badlogic.gdx.utils.Logger.INFO"
) {
return true
}
}
}
return false
}
| apache-2.0 | 72fbd472bb4530647daff6dd28221245 | 35.727273 | 117 | 0.60216 | 5.506815 | false | false | false | false |
thomasnield/kotlin-statistics | src/main/kotlin/org/nield/kotlinstatistics/Ranges.kt | 1 | 979 | package org.nield.kotlinstatistics
class OpenDoubleRange(
start: Double,
endExclusive: Double
) {
private val _start = start
private val _endExclusive = endExclusive
val start: Double get() = _start
val endExclusive: Double get() = _endExclusive
fun lessThanOrEquals(a: Double, b: Double): Boolean = a <= b
operator fun contains(value: Double): Boolean = value >= _start && value < _endExclusive
fun isEmpty(): Boolean = !(_start <= _endExclusive)
override fun equals(other: Any?): Boolean {
return other is OpenDoubleRange && (isEmpty() && other.isEmpty() ||
_start == other._start && _endExclusive == other._endExclusive)
}
override fun hashCode(): Int {
return if (isEmpty()) -1 else 31 * _start.hashCode() + _endExclusive.hashCode()
}
override fun toString(): String = "$_start..<$_endExclusive"
}
infix fun Double.openRange(double: Double) = OpenDoubleRange(this, double) | apache-2.0 | c666a4a3c0d87fa88f27cf8479630a68 | 32.793103 | 92 | 0.6476 | 4.40991 | false | false | false | false |
xwiki-contrib/android-authenticator | app/src/main/java/org/xwiki/android/sync/bean/Page.kt | 1 | 1330 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.android.sync.bean
/**
* Page
*/
class Page {
var id: String? = null
var name: String? = null
var lastModified: String? = null
override fun toString(): String {
return "Page{" +
"id='" + id + '\''.toString() +
", name='" + name + '\''.toString() +
", lastModified='" + lastModified + '\''.toString() +
'}'.toString()
}
}
| lgpl-2.1 | 926682d5a8ceedfca6440c62bd416286 | 33.102564 | 69 | 0.657143 | 4.332248 | false | false | false | false |
Tenkiv/Tekdaqc-JVM-Library | src/main/java/com/tenkiv/tekdaqc/communication/message/MessageBroadcaster.kt | 2 | 20546 | package com.tenkiv.tekdaqc.communication.message
import com.tenkiv.tekdaqc.communication.ascii.message.parsing.ASCIIDigitalOutputDataMessage
import com.tenkiv.tekdaqc.communication.ascii.message.parsing.ASCIIMessageUtils
import com.tenkiv.tekdaqc.communication.data_points.AnalogInputCountData
import com.tenkiv.tekdaqc.communication.data_points.DigitalInputData
import com.tenkiv.tekdaqc.communication.data_points.PWMInputData
import com.tenkiv.tekdaqc.hardware.AAnalogInput
import com.tenkiv.tekdaqc.hardware.ATekdaqc
import com.tenkiv.tekdaqc.hardware.DigitalInput
import com.tenkiv.tekdaqc.hardware.IInputOutputHardware
import org.tenkiv.coral.ValueInstant
import tec.units.indriya.ComparableQuantity
import tec.units.indriya.quantity.Quantities
import tec.units.indriya.unit.Units
import java.time.Instant
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import javax.measure.quantity.ElectricPotential
/**
* Class responsible for broadcasting messages received from Tekdaqcs.
* <br></br>**This class is thread safe.**
* @author Tenkiv ([email protected])
* *
* @since v1.0.0.0
*/
class MessageBroadcaster {
/**
* Map of all registered all-channel listeners.
*/
private val mFullListeners =
ConcurrentHashMap<ATekdaqc, MutableList<IMessageListener>>()
/**
* Map of all registered network listeners.
*/
private val mNetworkListeners =
ConcurrentHashMap<ATekdaqc, MutableList<INetworkListener>>()
/**
* Map of all registered count listeners.
*/
private val mAnalogCountListeners =
ConcurrentHashMap<ATekdaqc, MutableMap<Int, MutableList<ICountListener>>>()
/**
* Map of all registered voltage listeners.
*/
private val mAnalogVoltageListeners =
ConcurrentHashMap<ATekdaqc, MutableMap<Int, MutableList<IVoltageListener>>>()
/**
* Map of all registered digital listeners.
*/
private val mDigitalChannelListeners =
ConcurrentHashMap<ATekdaqc, MutableMap<Int, MutableList<IDigitalChannelListener>>>()
/**
* Map of all registered PWM Input listeners.
*/
private val mPWMChannelListeners =
ConcurrentHashMap<ATekdaqc, MutableMap<Int, MutableList<IPWMChannelListener>>>()
/**
* Map of prioritized listeners.
*/
private val mQueueListeners = ConcurrentHashMap<ATekdaqc, IMessageListener>()
/**
* Executor for handling callbacks to listeners.
*/
private var mCallbackThreadpool: Executor = Executors.newCachedThreadPool()
/**
* Sets the [Executor] that manages callbacks to [IMessageListener]s, [ICountListener]s,
* and [IDigitalChannelListener]s.
* @param callbackExecutor The new [Executor].
*/
fun setCallbackExecutor(callbackExecutor: Executor) {
mCallbackThreadpool = callbackExecutor
}
internal fun commandQueueAddListener(tekdaqc: ATekdaqc, listener: IMessageListener) {
mQueueListeners.put(tekdaqc, listener)
}
internal fun commandQueueRemoveListener(tekdaqc: ATekdaqc) {
mQueueListeners.remove(tekdaqc)
}
/**
* Register an object for message broadcasts for a particular Tekdaqc.
* @param tekdaqc [ATekdaqc] The Tekdaqc to register for.
* *
* @param listener [IMessageListener] Listener instance to receive the broadcasts.
*/
fun addMessageListener(tekdaqc: ATekdaqc, listener: IMessageListener) {
val listeners: MutableList<IMessageListener>
= mFullListeners.computeIfAbsent(tekdaqc, { ArrayList() })
synchronized(listeners) {
if (!listeners.contains(listener)) {
listeners.add(listener)
}
}
}
/**
* Register an object for network message broadcasts for a particular Tekdaqc.
* @param tekdaqc [ATekdaqc] The Tekdaqc to register for.
* *
* @param listener [IMessageListener] Listener instance to receive the broadcasts.
*/
fun addNetworkListener(tekdaqc: ATekdaqc, listener: INetworkListener) {
val listeners: MutableList<INetworkListener>
= mNetworkListeners.computeIfAbsent(tekdaqc, { ArrayList() })
synchronized(listeners) {
if (!listeners.contains(listener)) {
listeners.add(listener)
}
}
}
/**
* Un-register an object for network message broadcasts for a particular Tekdaqc.
* @param tekdaqc [ATekdaqc] The Tekdaqc to un-register for.
* *
* @param listener [IMessageListener] Listener instance to remove from broadcasts.
*/
fun removeNetworkListener(tekdaqc: ATekdaqc, listener: INetworkListener) {
val listeners = mNetworkListeners[tekdaqc]
if (listeners != null) {
synchronized(listeners) {
listeners.remove(listener)
if (listeners.size == 0) {
mNetworkListeners.remove(tekdaqc)
}
}
}
}
/**
* Register an object for PWM broadcasts for a specific channel on a particular Tekdaqc.
* @param tekdaqc [ATekdaqc] The Tekdaqc to register for.
* *
* @param input [DigitalInput] Physical number of the channel to listen for.
* *
* @param listener [IPWMChannelListener] Listener instance to receive the broadcasts.
*/
fun addPWMChannelListener(tekdaqc: ATekdaqc, input: DigitalInput, listener: IPWMChannelListener) {
val listeners: MutableMap<Int, MutableList<IPWMChannelListener>>
= mPWMChannelListeners.computeIfAbsent(tekdaqc,
{ ConcurrentHashMap() })
synchronized(listeners) {
val listenerList: MutableList<IPWMChannelListener>
= listeners.getOrPut(input.channelNumber, { ArrayList<IPWMChannelListener>() })
if (!listenerList.contains(listener)) {
listenerList.add(listener)
}
}
}
/**
* Un-register an object from PWM broadcasts for a particular Tekdaqc.
* @param tekdaqc [ATekdaqc] The Tekdaqc to un-register for.
* *
* @param input [DigitalInput] The input to unregister from
* *
* @param listener [IPWMChannelListener] Listener instance to remove from broadcasts.
*/
fun removePWMChannelListener(tekdaqc: ATekdaqc, input: DigitalInput, listener: IPWMChannelListener) {
unregisterInputListener(tekdaqc, input, listener, mPWMChannelListeners)
}
/**
* Register an object for message broadcasts for a specific channel on a particular Tekdaqc.
* @param tekdaqc [ATekdaqc] The Tekdaqc to register for.
* *
* @param input [AAnalogInput] Physical number of the channel to listen for.
* *
* @param listener [ICountListener] Listener instance to receive the broadcasts.
*/
fun addAnalogChannelListener(tekdaqc: ATekdaqc, input: AAnalogInput, listener: ICountListener) {
val listeners: MutableMap<Int, MutableList<ICountListener>>
= mAnalogCountListeners.computeIfAbsent(tekdaqc,
{ ConcurrentHashMap() })
synchronized(listeners) {
val listenerList: MutableList<ICountListener>
= listeners.getOrPut(input.channelNumber, { ArrayList() })
if (!listenerList.contains(listener)) {
listenerList.add(listener)
}
}
}
/**
* Register an object for message broadcasts for a specific channel on a particular Tekdaqc.
* @param tekdaqc [ATekdaqc] The Tekdaqc to register for.
* *
* @param input [AAnalogInput] Physical number of the channel to listen for.
* *
* @param listener [IVoltageListener] Listener instance to receive the broadcasts.
*/
fun addAnalogVoltageListener(tekdaqc: ATekdaqc, input: AAnalogInput, listener: IVoltageListener) {
val listeners: MutableMap<Int, MutableList<IVoltageListener>>
= mAnalogVoltageListeners.computeIfAbsent(tekdaqc,
{ ConcurrentHashMap() })
synchronized(listeners) {
val listenerList: MutableList<IVoltageListener>
= listeners.getOrPut(input.channelNumber, { ArrayList() })
if (!listenerList.contains(listener)) {
listenerList.add(listener)
}
}
}
/**
* Register an object for message broadcasts for a specific channel on a particular Tekdaqc.
* @param tekdaqc [ATekdaqc] The Tekdaqc to register for.
* *
* @param input [DigitalInput] Physical number of the channel to listen for.
* *
* @param listener [IDigitalChannelListener] Listener instance to receive the broadcasts.
*/
fun addDigitalChannelListener(tekdaqc: ATekdaqc, input: DigitalInput, listener: IDigitalChannelListener) {
val listeners: MutableMap<Int, MutableList<IDigitalChannelListener>>
= mDigitalChannelListeners.computeIfAbsent(tekdaqc,
{ ConcurrentHashMap() })
synchronized(listeners) {
val listenerList: MutableList<IDigitalChannelListener>
= listeners.getOrPut(input.channelNumber, { ArrayList() })
if (!listenerList.contains(listener)) {
listenerList.add(listener)
}
}
}
/**
* Un-register an object from message broadcasts for a particular Tekdaqc.
* @param tekdaqc [ATekdaqc] The Tekdaqc to un-register for.
* *
* @param listener [IMessageListener] Listener instance to remove from broadcasts.
*/
fun removeListener(tekdaqc: ATekdaqc, listener: IMessageListener) {
val listeners = mFullListeners[tekdaqc]
if (listeners != null) {
synchronized(listeners) {
listeners.remove(listener)
if (listeners.size == 0) {
mFullListeners.remove(tekdaqc)
}
}
}
}
/**
* Un-register an object from message broadcasts for a particular Tekdaqc.
* @param tekdaqc [ATekdaqc] The Tekdaqc to un-register for.
* *
* @param input [AAnalogInput] The input to unregister from
* *
* @param listener [ICountListener] Listener instance to remove from broadcasts.
*/
fun removeAnalogCountListener(tekdaqc: ATekdaqc, input: AAnalogInput, listener: ICountListener) {
unregisterInputListener(tekdaqc, input, listener, mAnalogCountListeners)
}
/**
* Un-register an object from message broadcasts for a particular Tekdaqc.
* @param tekdaqc [ATekdaqc] The Tekdaqc to un-register for.
* *
* @param input [AAnalogInput] The input to unregister from
* *
* @param listener [IVoltageListener] Listener instance to remove from broadcasts.
*/
fun removeAnalogVoltageListener(tekdaqc: ATekdaqc, input: AAnalogInput, listener: IVoltageListener) {
unregisterInputListener(tekdaqc, input, listener, mAnalogVoltageListeners)
}
/**
* Un-register an object from message broadcasts for a particular Tekdaqc.
* @param tekdaqc [ATekdaqc] The Tekdaqc to un-register for.
* *
* @param input [DigitalInput] The input to unregister from
* *
* @param listener [IDigitalChannelListener] Listener instance to remove from broadcasts.
*/
fun removeDigitalChannelListener(tekdaqc: ATekdaqc, input: DigitalInput, listener: IDigitalChannelListener) {
unregisterInputListener(tekdaqc, input, listener, mDigitalChannelListeners)
}
private fun <IT : IInputOutputHardware, LT> unregisterInputListener(tekdaqc: ATekdaqc,
input: IT,
listener: LT,
listenerMap: MutableMap<ATekdaqc,
MutableMap<Int, MutableList<LT>>>) {
val listeners = listenerMap[tekdaqc]?.get(input.channelNumber)
if (listeners != null) {
synchronized(listeners) {
listeners.remove(listener)
if (listeners.size == 0) {
listenerMap[tekdaqc]?.remove(input.channelNumber)
}
}
}
}
/**
* Broadcast a [ABoardMessage] to all registered listeners for the specified Tekdaqc.
* @param tekdaqc [ATekdaqc] The serial number string of the Tekdaqc to broadcast for.
* *
* @param message [ABoardMessage] The message to broadcast.
*/
fun broadcastMessage(tekdaqc: ATekdaqc, message: ABoardMessage) {
mCallbackThreadpool.execute(BroadcastRunnable(tekdaqc, message))
}
/**
* Broadcast a [ABoardMessage] to registered network listeners for the specified Tekdaqc.
* @param tekdaqc [ATekdaqc] The serial number string of the Tekdaqc to broadcast for.
* *
* @param message [ABoardMessage] The message to broadcast.
*/
fun broadcastNetworkError(tekdaqc: ATekdaqc, message: ABoardMessage) {
mCallbackThreadpool.execute(NetworkBroadcastRunnable(tekdaqc, message))
}
/**
* Broadcast a single [AnalogInputCountData] point to all registered listeners for the specified Tekdaqc.
* @param tekdaqc [ATekdaqc] The serial number string of the Tekdaqc to broadcast for.
* *
* @param data [AnalogInputCountData] The data point to broadcast.
*/
fun broadcastAnalogInputDataPoint(tekdaqc: ATekdaqc, data: AnalogInputCountData) {
val listeners = mFullListeners[tekdaqc]
if (listeners != null) {
synchronized(listeners) {
listeners.forEach { listener ->
listener.onAnalogInputDataReceived(tekdaqc, data)
}
}
}
if (mAnalogCountListeners.containsKey(tekdaqc)) {
if (mAnalogCountListeners[tekdaqc]?.containsKey(data.physicalInput) == true) {
val channelListeners = mAnalogCountListeners[tekdaqc]?.get(data.physicalInput)
channelListeners?.let {
synchronized(it) {
channelListeners.forEach { listener ->
listener.onAnalogDataReceived(tekdaqc.getAnalogInput(data.physicalInput), data.data)
}
}
}
}
}
if (mAnalogVoltageListeners.containsKey(tekdaqc)) {
if (mAnalogVoltageListeners[tekdaqc]?.containsKey(data.physicalInput) == true) {
val channelListeners = mAnalogVoltageListeners[tekdaqc]?.get(data.physicalInput)
channelListeners?.let {
synchronized(it) {
val quant = Quantities.getQuantity(
tekdaqc.convertAnalogInputDataToVoltage(
data,
tekdaqc.analogScale), Units.VOLT)
channelListeners.forEach { listener ->
listener.onVoltageDataReceived(
tekdaqc.getAnalogInput(data.physicalInput),
ValueInstant<ComparableQuantity<ElectricPotential>>(
quant,
Instant.ofEpochMilli(data.timestamp)))
}
}
}
}
}
}
/**
* Broadcast a single [DigitalInputData] point to all registered listeners for the specified Tekdaqc.
* @param tekdaqc [ATekdaqc] The serial number string of the Tekdaqc to broadcast for.
* *
* @param data [DigitalInputData] The data point to broadcast.
*/
fun broadcastDigitalInputDataPoint(tekdaqc: ATekdaqc, data: DigitalInputData) {
val listeners = mFullListeners[tekdaqc]
listeners?.let {
synchronized(it) {
for (listener in listeners) {
listener.onDigitalInputDataReceived(tekdaqc, data)
}
}
}
if (mDigitalChannelListeners.containsKey(tekdaqc)) {
if (mDigitalChannelListeners[tekdaqc]?.containsKey(data.physicalInput) == true) {
val channelListeners = mDigitalChannelListeners[tekdaqc]?.get(data.physicalInput)
channelListeners?.let {
synchronized(it) {
channelListeners.forEach { listener ->
listener.onDigitalDataReceived(tekdaqc.getDigitalInput(data.physicalInput), data)
}
}
}
}
}
}
/**
* Broadcast a single [DigitalInputData] point to all registered listeners for the specified Tekdaqc.
* @param tekdaqc [ATekdaqc] The serial number string of the Tekdaqc to broadcast for.
* *
* @param data [DigitalInputData] The data point to broadcast.
*/
fun broadcastPWMInputDataPoint(tekdaqc: ATekdaqc, data: PWMInputData) {
if (mPWMChannelListeners.containsKey(tekdaqc)) {
if (mPWMChannelListeners[tekdaqc]?.containsKey(data.physicalInput) == true) {
val channelListeners = mPWMChannelListeners[tekdaqc]?.get(data.physicalInput)
channelListeners?.let {
synchronized(it) {
channelListeners.forEach { listener ->
listener.onPWMDataReceived(tekdaqc.getDigitalInput(data.physicalInput), data)
}
}
}
}
}
}
/**
* Class that wraps callbacks from the [com.tenkiv.tekdaqc.communication.ascii.executors.ASCIIParsingExecutor]
* so that they are called back in a different thread.
*/
private inner class BroadcastRunnable(internal val mTekdaqc: ATekdaqc,
internal val mMessage: ABoardMessage) : Runnable {
override fun run() {
if (mMessage.type == ASCIIMessageUtils.MESSAGE_TYPE.STATUS) {
mQueueListeners[mTekdaqc]?.onStatusMessageReceived(mTekdaqc, mMessage)
} else if (mMessage.type == ASCIIMessageUtils.MESSAGE_TYPE.ERROR) {
mQueueListeners[mTekdaqc]?.onStatusMessageReceived(mTekdaqc, mMessage)
}
val listeners = mFullListeners[mTekdaqc]
if (listeners != null) {
synchronized(listeners) {
for (listener in listeners) {
when (mMessage.type) {
ASCIIMessageUtils.MESSAGE_TYPE.DEBUG ->
listener.onDebugMessageReceived(mTekdaqc, mMessage)
ASCIIMessageUtils.MESSAGE_TYPE.STATUS ->
listener.onStatusMessageReceived(mTekdaqc, mMessage)
ASCIIMessageUtils.MESSAGE_TYPE.ERROR ->
listener.onErrorMessageReceived(mTekdaqc, mMessage)
ASCIIMessageUtils.MESSAGE_TYPE.COMMAND_DATA ->
listener.onCommandDataMessageReceived(mTekdaqc, mMessage)
ASCIIMessageUtils.MESSAGE_TYPE.DIGITAL_OUTPUT_DATA -> {
listener.onDigitalOutputDataReceived(
mTekdaqc,
(mMessage as ASCIIDigitalOutputDataMessage).digitalOutputArray)
System.err.println("Unknown message type with serial: " + mTekdaqc.serialNumber)
}
else -> System.err.println("Unknown message type with serial: " + mTekdaqc.serialNumber)
}
}
}
}
}
}
private inner class NetworkBroadcastRunnable(
internal val mTekdaqc: ATekdaqc, internal val mMessage: ABoardMessage) : Runnable {
override fun run() {
val listeners = mNetworkListeners[mTekdaqc]
listeners?.forEach { listener -> listener.onNetworkConditionDetected(mTekdaqc, mMessage) }
}
}
}
| apache-2.0 | 50dbef27110ca10e70c381975164c39b | 38.817829 | 116 | 0.614377 | 5.575577 | false | false | false | false |
manami-project/manami | manami-gui/src/main/kotlin/io/github/manamiproject/manami/gui/dashboard/DashboardView.kt | 1 | 7632 | package io.github.manamiproject.manami.gui.dashboard
import io.github.manamiproject.manami.app.lists.AnimeEntry
import io.github.manamiproject.manami.app.lists.Link
import io.github.manamiproject.manami.gui.components.numberTile
import io.github.manamiproject.manami.gui.events.*
import io.github.manamiproject.modb.core.config.Hostname
import javafx.beans.property.SimpleStringProperty
import javafx.geometry.Pos.CENTER
import javafx.scene.paint.Color.*
import tornadofx.View
import tornadofx.gridpane
import tornadofx.row
import kotlin.collections.Collection
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.filter
import kotlin.collections.forEach
import kotlin.collections.groupBy
import kotlin.collections.mutableMapOf
import kotlin.collections.set
import kotlin.math.roundToInt
class DashboardView: View() {
private val animeListEntriesProperty = SimpleStringProperty("0")
private val watchListEntriesProperty = SimpleStringProperty("0")
private val ignoreListEntriesProperty = SimpleStringProperty("0")
private val metaDataProviderEntriesInLists = mutableMapOf<Hostname, Int>()
private val metaDataProviderTotalNumberOfEntries = mutableMapOf<Hostname, Int>()
private val metaDataProviderSeenStringProperties = mutableMapOf<Hostname, SimpleStringProperty>().apply {
put("myanimelist.net", SimpleStringProperty("0"))
put("kitsu.io", SimpleStringProperty("0"))
put("anime-planet.com", SimpleStringProperty("0"))
put("notify.moe", SimpleStringProperty("0"))
put("anilist.co", SimpleStringProperty("0"))
put("anidb.net", SimpleStringProperty("0"))
put("anisearch.com", SimpleStringProperty("0"))
put("livechart.me", SimpleStringProperty("0"))
}
init {
subscribe<AddAnimeListEntryGuiEvent> { event ->
val newValue = animeListEntriesProperty.get().toInt() + event.entries.size
animeListEntriesProperty.set(newValue.toString())
addNumberOfEntriesToPercentageTile(event.entries)
}
subscribe<RemoveAnimeListEntryGuiEvent> { event ->
val newValue = animeListEntriesProperty.get().toInt() - event.entries.size
animeListEntriesProperty.set(newValue.toString())
removeNumberOfEntriesToPercentageTile(event.entries)
}
subscribe<AddWatchListEntryGuiEvent> { event ->
val newValue = watchListEntriesProperty.get().toInt() + event.entries.size
watchListEntriesProperty.set(newValue.toString())
addNumberOfEntriesToPercentageTile(event.entries)
}
subscribe<RemoveWatchListEntryGuiEvent> { event ->
val newValue = watchListEntriesProperty.get().toInt() - event.entries.size
watchListEntriesProperty.set(newValue.toString())
removeNumberOfEntriesToPercentageTile(event.entries)
}
subscribe<AddIgnoreListEntryGuiEvent> { event ->
val newValue = ignoreListEntriesProperty.get().toInt() + event.entries.size
ignoreListEntriesProperty.set(newValue.toString())
addNumberOfEntriesToPercentageTile(event.entries)
}
subscribe<RemoveIgnoreListEntryGuiEvent> { event ->
val newValue = ignoreListEntriesProperty.get().toInt() - event.entries.size
ignoreListEntriesProperty.set(newValue.toString())
removeNumberOfEntriesToPercentageTile(event.entries)
}
subscribe<NumberOfEntriesPerMetaDataProviderGuiEvent> { event ->
metaDataProviderTotalNumberOfEntries.putAll(event.entries)
updateStringProperties()
}
}
override val root = gridpane {
hgap = 50.0
vgap = 50.0
alignment = CENTER
row {
alignment = CENTER
numberTile {
title = "AnimeList"
color = MEDIUMSEAGREEN
valueProperty = animeListEntriesProperty
}
numberTile {
title = "WatchList"
color = CORNFLOWERBLUE
valueProperty = watchListEntriesProperty
}
numberTile {
title = "IgnoreList"
color = INDIANRED
valueProperty = ignoreListEntriesProperty
}
}
row {
numberTile {
title = "myanimelist.net"
color = SLATEGRAY
valueProperty = metaDataProviderSeenStringProperties["myanimelist.net"]!!
}
numberTile {
title = "anime-planet.com"
color = SLATEGRAY
valueProperty = metaDataProviderSeenStringProperties["anime-planet.com"]!!
}
numberTile {
title = "kitsu.io"
color = SLATEGRAY
valueProperty = metaDataProviderSeenStringProperties["kitsu.io"]!!
}
}
row {
numberTile {
title = "anisearch.com"
color = SLATEGRAY
valueProperty = metaDataProviderSeenStringProperties["anisearch.com"]!!
}
numberTile {
title = "anilist.co"
color = SLATEGRAY
valueProperty = metaDataProviderSeenStringProperties["anilist.co"]!!
}
numberTile {
title = "notify.moe"
color = SLATEGRAY
valueProperty = metaDataProviderSeenStringProperties["notify.moe"]!!
}
}
row {
numberTile {
title = "anidb.net"
color = SLATEGRAY
valueProperty = metaDataProviderSeenStringProperties["anidb.net"]!!
}
numberTile {
title = "livechart.me"
color = SLATEGRAY
valueProperty = metaDataProviderSeenStringProperties["livechart.me"]!!
}
}
}
@Synchronized
private fun addNumberOfEntriesToPercentageTile(entries: Collection<AnimeEntry>) {
entries.filter { it.link is Link }.groupBy { it.link.asLink().uri.host }.forEach { (key, value) ->
metaDataProviderEntriesInLists[key] = (metaDataProviderEntriesInLists[key] ?: 0) + value.size
}
updateStringProperties()
}
@Synchronized
private fun removeNumberOfEntriesToPercentageTile(entries: Collection<AnimeEntry>) {
entries.filter { it.link is Link }.groupBy { it.link.asLink().uri.host }.forEach { (key, value) ->
metaDataProviderEntriesInLists[key] = (metaDataProviderEntriesInLists[key] ?: 0) - value.size
}
updateStringProperties()
}
@Synchronized
private fun updateStringProperties() {
metaDataProviderSeenStringProperties.keys.forEach {
val inList = metaDataProviderEntriesInLists[it] ?: 0
val totalNumber = metaDataProviderTotalNumberOfEntries[it] ?: 0
val progressValue = when {
inList == 0 && totalNumber == 0 -> "0"
inList == 0 && totalNumber > 0 -> "$totalNumber"
inList > 0 && totalNumber == 0 -> "$inList / ?"
else -> {
val difference = totalNumber - inList
val percent = (inList.toDouble() / totalNumber.toDouble() * 100.0).roundToInt()
"$totalNumber - $inList = $difference ($percent%)"
}
}
metaDataProviderSeenStringProperties[it]!!.set(progressValue)
}
}
} | agpl-3.0 | 9fa5a156d4e9ba48fd893e3db23b5a41 | 38.345361 | 109 | 0.623559 | 5.817073 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-locks-bukkit/src/main/kotlin/com/rpkit/locks/bukkit/messages/LocksMessages.kt | 1 | 2645 | /*
* 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.locks.bukkit.messages
import com.rpkit.core.bukkit.message.BukkitMessages
import com.rpkit.core.message.ParameterizedMessage
import com.rpkit.core.message.to
import com.rpkit.locks.bukkit.RPKLocksBukkit
import org.bukkit.Material
class LocksMessages(plugin: RPKLocksBukkit) : BukkitMessages(plugin) {
class BlockLockedMessage(private val message: ParameterizedMessage) {
fun withParameters(blockType: Material) = message.withParameters(
"block" to blockType.toString().lowercase().replace('_', ' ')
)
}
val blockLocked = getParameterized("block-locked").let(::BlockLockedMessage)
val craftingNoKeys = get("crafting-no-keys")
val keyringInvalidItem = get("keyring-invalid-item")
val lockSuccessful = get("lock-successful")
val lockInvalidAlreadyLocked = get("lock-invalid-already-locked")
val unlockSuccessful = get("unlock-successful")
val unlockInvalidNoKey = get("unlock-invalid-no-key")
val unlockInvalidNotLocked = get("unlock-invalid-not-locked")
val getKeyInvalidNotLocked = get("get-key-invalid-not-locked")
val getKeySuccessful = get("get-key-successful")
val getKeyValid = get("get-key-valid")
val unlockValid = get("unlock-valid")
val copyKeyInvalidNoKeyInHand = get("copy-key-invalid-no-key-in-hand")
val copyKeyInvalidNoMaterial = get("copy-key-invalid-no-material")
val copyKeyValid = get("copy-key-valid")
val notFromConsole = get("not-from-console")
val noCharacter = get("no-character")
val noMinecraftProfile = get("no-minecraft-profile")
val noPermissionCopyKey = get("no-permission-copy-key")
val noPermissionGetKey = get("no-permission-get-key")
val noPermissionKeyring = get("no-permission-keyring")
val noPermissionUnlock = get("no-permission-unlock")
val noMinecraftProfileService = get("no-minecraft-profile-service")
val noCharacterService = get("no-character-service")
val noLockService = get("no-lock-service")
val noKeyringService = get("no-keyring-service")
} | apache-2.0 | 8e31f7f70ebfd185da0d4db0d8cc98de | 43.847458 | 80 | 0.736484 | 3.959581 | false | false | false | false |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/data/netease/result/LoginResultBean.kt | 1 | 5489 | package tech.summerly.quiet.data.netease.result
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* author : SUMMERLY
* e-mail : [email protected]
* time : 2017/8/24
* desc :
*/
data class LoginResultBean(
@SerializedName("loginType")
@Expose
val loginType: Long? = null,
@SerializedName("code")
@Expose
val code: Long,
@SerializedName("profile")
@Expose
val profile: Profile? = null
// @SerializedName("account")
// @Expose
// var account: Account? = null,
// @SerializedName("bindings")
// @Expose
// var bindings: List<Binding>? = null
) {
data class Profile(
@SerializedName("followed")
@Expose
val followed: Boolean? = null,
@SerializedName("userId")
@Expose
val userId: Long,
@SerializedName("nickname")
@Expose
val nickname: String,
@SerializedName("avatarUrl")
@Expose
val avatarUrl: String? = null,
@SerializedName("backgroundUrl")
@Expose
val backgroundUrl: String? = null
// @SerializedName("avatarImgId")
// @Expose
// var avatarImgId: Long? = null,
// @SerializedName("backgroundImgId")
// @Expose
// var backgroundImgId: Long? = null,
// @SerializedName("detailDescription")
// @Expose
// var detailDescription: String? = null,
//
// @SerializedName("djStatus")
// @Expose
// var djStatus: Long? = null,
// @SerializedName("accountStatus")
// @Expose
// var accountStatus: Long? = null,
// @SerializedName("defaultAvatar")
// @Expose
// var defaultAvatar: Boolean? = null,
// @SerializedName("gender")
// @Expose
// var gender: Long? = null,
// @SerializedName("birthday")
// @Expose
// var birthday: Long? = null,
// @SerializedName("city")
// @Expose
// var city: Long? = null,
// @SerializedName("province")
// @Expose
// var province: Long? = null,
// @SerializedName("mutual")
// @Expose
// var mutual: Boolean? = null,
// @SerializedName("remarkName")
// @Expose
// var remarkName: Any? = null,
// @SerializedName("experts")
// @Expose
// var experts: Experts? = null,
// @SerializedName("expertTags")
// @Expose
// var expertTags: Any? = null,
// @SerializedName("userType")
// @Expose
// var userType: Long? = null,
// @SerializedName("vipType")
// @Expose
// var vipType: Long? = null,
// @SerializedName("authStatus")
// @Expose
// var authStatus: Long? = null,
// @SerializedName("description")
// @Expose
// var description: String? = null,
// @SerializedName("avatarImgIdStr")
// @Expose
// var avatarImgIdStr: String? = null,
// @SerializedName("backgroundImgIdStr")
// @Expose
// var backgroundImgIdStr: String? = null,
// @SerializedName("signature")
// @Expose
// var signature: String? = null,
// @SerializedName("authority")
// @Expose
// var authority: Long? = null
)
//data class Account(
//
// @SerializedName("id")
// @Expose
// var id: Long? = null,
// @SerializedName("userName")
// @Expose
// var userName: String? = null,
// @SerializedName("type")
// @Expose
// var type: Long? = null,
// @SerializedName("status")
// @Expose
// var status: Long? = null,
// @SerializedName("whitelistAuthority")
// @Expose
// var whitelistAuthority: Long? = null,
// @SerializedName("createTime")
// @Expose
// var createTime: Long? = null,
// @SerializedName("salt")
// @Expose
// var salt: String? = null,
// @SerializedName("tokenVersion")
// @Expose
// var tokenVersion: Long? = null,
// @SerializedName("ban")
// @Expose
// var ban: Long? = null,
// @SerializedName("baoyueVersion")
// @Expose
// var baoyueVersion: Long? = null,
// @SerializedName("donateVersion")
// @Expose
// var donateVersion: Long? = null,
// @SerializedName("vipType")
// @Expose
// var vipType: Long? = null,
// @SerializedName("viptypeVersion")
// @Expose
// var viptypeVersion: Long? = null,
// @SerializedName("anonimousUser")
// @Expose
// var anonimousUser: Boolean? = null
//
//)
//class Binding {
//
// @SerializedName("expiresIn")
// @Expose
// var expiresIn: Long? = null
// @SerializedName("refreshTime")
// @Expose
// var refreshTime: Long? = null
// @SerializedName("url")
// @Expose
// var url: String? = null
// @SerializedName("userId")
// @Expose
// var userId: Long? = null
// @SerializedName("tokenJsonStr")
// @Expose
// var tokenJsonStr: String? = null
// @SerializedName("expired")
// @Expose
// var expired: Boolean? = null
// @SerializedName("id")
// @Expose
// var id: Long? = null
// @SerializedName("type")
// @Expose
// var type: Long? = null
//
//}
} | gpl-2.0 | 1a21c5536f7cc55c55979ad1e80b58f6 | 26.313433 | 49 | 0.532155 | 3.884643 | false | false | false | false |
hblanken/Tower-v3.2.1 | Android/src/org/droidplanner/android/fragments/widget/WidgetsListPrefFragment.kt | 1 | 3630 | package org.droidplanner.android.fragments.widget
import android.app.DialogFragment
import android.app.FragmentManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.LocalBroadcastManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import org.droidplanner.android.R
import org.droidplanner.android.fragments.SettingsFragment
import org.droidplanner.android.utils.prefs.DroidPlannerPrefs
/**
* Created by Fredia Huya-Kouadio on 10/18/15.
*/
class WidgetsListPrefFragment : DialogFragment() {
override fun onCreate(savedInstanceState: Bundle?){
super.onCreate(savedInstanceState)
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.CustomDialogTheme)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_widgets_list_pref, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val widgetsListPref = view.findViewById(R.id.widgets_list_pref) as ListView?
widgetsListPref?.adapter = WidgetsAdapter(activity.applicationContext, fragmentManager)
}
class WidgetsAdapter(context: Context, val fm : FragmentManager) : ArrayAdapter<TowerWidgets>(context, 0, TowerWidgets.values()){
val appPrefs = DroidPlannerPrefs(context)
val lbm = LocalBroadcastManager.getInstance(context)
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val towerWidget = getItem(position)
val view = convertView ?: LayoutInflater.from(parent.context).inflate(R.layout.list_widgets_list_pref_item, parent, false)
var viewHolder = view.tag as ViewHolder?
if(viewHolder == null){
viewHolder = ViewHolder(view.findViewById(R.id.widget_pref_icon) as ImageView?,
view.findViewById(R.id.widget_check) as CheckBox?,
view.findViewById(R.id.widget_pref_title) as TextView?,
view.findViewById(R.id.widget_pref_summary) as TextView?,
view.findViewById(R.id.widget_pref_info))
}
viewHolder.prefIcon?.visibility = if(towerWidget.hasPreferences()) View.VISIBLE else View.INVISIBLE
viewHolder.prefIcon?.setOnClickListener { towerWidget.getPrefFragment()?.show(fm, "Widget pref dialog") }
viewHolder.prefTitle?.setText(towerWidget.labelResId)
viewHolder.prefSummary?.setText(towerWidget.descriptionResId)
viewHolder.prefCheck?.setOnCheckedChangeListener(null)
viewHolder.prefCheck?.isChecked = appPrefs.isWidgetEnabled(towerWidget)
viewHolder.prefCheck?.setOnCheckedChangeListener { compoundButton, b ->
appPrefs.enableWidget(towerWidget, b)
lbm.sendBroadcast(Intent(SettingsFragment.ACTION_WIDGET_PREFERENCE_UPDATED)
.putExtra(SettingsFragment.EXTRA_ADD_WIDGET, b)
.putExtra(SettingsFragment.EXTRA_WIDGET_PREF_KEY, towerWidget.prefKey))
}
viewHolder.prefInfo?.setOnClickListener { viewHolder?.prefCheck?.toggle() }
view.tag = viewHolder
return view
}
class ViewHolder(val prefIcon: ImageView?, val prefCheck: CheckBox?, val prefTitle : TextView?, val prefSummary: TextView?, val prefInfo: View?)
}
} | gpl-3.0 | d5a30e874b6d6857074090f65c2c39b5 | 44.3875 | 152 | 0.701377 | 4.801587 | false | false | false | false |
wayfair/gists | android/anko_blogpost/Userlist/app/src/main/java/com/wayfair/userlist/data/UsersListDataModel.kt | 1 | 417 | package com.wayfair.userlist.data
data class UsersListDataModel(
val usersList: MutableList<UserDataModel>
) {
data class UserDataModel(
val login: String = "",
val id: Int = 0,
val node_id: String = "",
val avatar_url: String = "",
val url: String = "",
val html_url: String = "",
val type: String = "",
val site_admin: Boolean = false
)
} | mit | ca80f7b0d98d7fbd28b844eeb2d16972 | 25.125 | 45 | 0.563549 | 4.009615 | false | false | false | false |
Anizoptera/Aza-Kotlin-CSS | main/azagroup/kotlin/css/Stylesheet.kt | 1 | 25298 | package azagroup.kotlin.css
import java.io.File
import java.util.ArrayList
// CSS Selector Reference
// http://www.w3schools.com/cssref/css_selectors.asp
@Suppress("unused")
class Stylesheet(
callback: (Stylesheet.()->Unit)? = null
) : ASelector
{
var selector: Selector? = null
var atRule: String? = null
val properties = ArrayList<Property>(2)
val children = ArrayList<Stylesheet>()
init { callback?.invoke(this) }
fun include(stylesheet: Stylesheet): Stylesheet {
children.add(stylesheet)
return this
}
override fun custom(selector: String, _spaceBefore: Boolean, _spaceAfter: Boolean, body: (Stylesheet.() -> Unit)?): Selector {
val stylesheet = Stylesheet()
val sel = Selector(stylesheet)
sel.custom(selector, _spaceBefore, _spaceAfter)
stylesheet.selector = sel
include(stylesheet)
body?.invoke(stylesheet)
return sel
}
fun getProperty(name: String) = properties.find { it.name == name }
fun setProperty(name: String, value: Any?) {
properties.add(Property(name, value))
}
fun moveDataTo(stylesheet: Stylesheet) {
stylesheet.properties.addAll(properties)
properties.clear()
stylesheet.children.addAll(children)
children.clear()
}
fun render() = buildString { render(this) }
fun renderTo(sb: StringBuilder) = render(sb)
fun renderToFile(file: File) {
file.delete()
file.writeText(render()) // "writeText" is a really clever helper
}
fun renderToFile(path: String) = renderToFile(File(path))
private fun render(sb: StringBuilder, selectorPrefix: CharSequence = "", _spaceBefore: Boolean = true) {
val selector = selector
val atRule = atRule
if (atRule != null)
sb.append(atRule).append('{')
if (properties.isNotEmpty()) {
val selectorStr = selector?.toString(selectorPrefix, _spaceBefore)
val hasSelector = !selectorStr.isNullOrEmpty()
if (hasSelector)
sb.append(selectorStr).append('{')
val lastIdx = properties.lastIndex
properties.forEachIndexed { i, property ->
val value = property.value
if (value != null)
sb.run {
append(property.name)
append(":")
append(if (value is Number) cssDecimalFormat.format(value.toFloat()) else value)
if (i < lastIdx)
append(";")
}
else if (i == lastIdx && sb.last() == ';')
sb.setLength(sb.length-1)
}
if (hasSelector)
sb.append("}")
}
for (child in children) {
val rows = selector?.rows
if (rows != null && rows.isNotEmpty())
rows.forEach { child.render(sb, it.toString(selectorPrefix, _spaceBefore), it.spaceAfter) }
else
child.render(sb, selectorPrefix)
}
if (atRule != null)
sb.append('}')
}
override fun toString() = "Stylesheet(sel:$selector; props:${properties.size}; childs:${children.size})"
class Property(
val name: String,
val value: Any?
) {
override fun toString() = "$name:$value"
}
//
// AT-RULES
//
fun at(rule: Any, body: (Stylesheet.()->Unit)? = null): Stylesheet {
val stylesheet = Stylesheet(body)
stylesheet.selector = Selector.createEmpty(stylesheet)
stylesheet.atRule = "@$rule"
include(stylesheet)
return stylesheet
}
fun media(vararg conditions: Any, body: (Stylesheet.()->Unit)? = null)
= at("media (${conditions.joinToString(") and (")})", body)
//
// MAIN COMMANDS
//
operator fun CharSequence.invoke(body: Stylesheet.()->Unit) = toSelector().invoke(body)
fun CharSequence.custom(selector: String, _spaceBefore: Boolean = true, _spaceAfter: Boolean = true, body: (Stylesheet.()->Unit)? = null): Selector {
return when (this) {
is ASelector -> custom(selector, _spaceBefore, _spaceAfter, body)
else -> toSelector().custom(selector, _spaceBefore, _spaceAfter, body)
}
}
fun CharSequence.pseudo(selector: String, body: (Stylesheet.()->Unit)? = null): Selector {
return when (this) {
is ASelector -> pseudo(selector, body)
else -> toSelector().pseudo(selector, body)
}
}
fun CharSequence.pseudoFn(selector: String, body: (Stylesheet.()->Unit)? = null): Selector {
return when (this) {
is ASelector -> pseudoFn(selector, body)
else -> toSelector().pseudoFn(selector, body)
}
}
infix fun CharSequence.and(obj: CharSequence): Selector {
val sel = toSelector()
when (obj) {
is Selector -> {
for (row in obj.rows)
sel.rows.add(row)
return sel
}
is Stylesheet -> {
val selector = obj.selector!!
selector.rows.addAll(0, sel.rows)
return selector
}
else -> return and(obj.toSelector())
}
}
private fun CharSequence.toSelector() = when (this) {
is Selector -> this
is Stylesheet -> this.selector!!
else -> when (this[0]) {
'.' -> [email protected](this.drop(1))
'#' -> [email protected](this.drop(1))
'@' -> [email protected](this.drop(1)).selector!!
else -> [email protected](this.toString())
}
}
//
// TRAVERSING
//
val CharSequence.children: Selector get() = custom(" ", false, false)
val CharSequence.child: Selector get() = custom(">", false, false)
val CharSequence.next: Selector get() = custom("+", false, false)
val CharSequence.nextAll: Selector get() = custom("~", false, false)
operator fun CharSequence.div(obj: CharSequence) = child.append(obj.toSelector())
operator fun CharSequence.mod(obj: CharSequence) = next.append(obj.toSelector())
operator fun CharSequence.minus(obj: CharSequence) = nextAll.append(obj.toSelector())
operator fun CharSequence.rangeTo(obj: CharSequence) = children.append(obj.toSelector())
//
// ATTRIBUTES
//
/*
TODO: Escape and add braces ?
https://mathiasbynens.be/notes/css-escapes
http://stackoverflow.com/questions/13987979/how-to-properly-escape-attribute-values-in-css-js-selector-attr-value
https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape
*/
fun CharSequence.attr(attrName: Any, body: (Stylesheet.()->Unit)? = null): Selector {
return when (this) {
is ASelector -> custom("[$attrName]", false, true, body)
else -> toSelector().attr(attrName, body)
}
}
fun CharSequence.attr(attrName: Any, attrValue: Any, body: (Stylesheet.()->Unit)? = null): Selector {
return when (this) {
is ASelector -> custom("[$attrName=${escapeAttrValue(attrValue.toString())}]", false, true, body)
else -> toSelector().attr(attrName, attrValue, body)
}
}
fun CharSequence.attr(attrName: Any, attrValue: Any, attrFiler: AttrFilter, body: (Stylesheet.()->Unit)? = null): Selector {
return when (this) {
is ASelector -> custom("[$attrName$attrFiler=${escapeAttrValue(attrValue.toString())}]", false, true, body)
else -> toSelector().attr(attrName, attrValue, attrFiler, body)
}
}
operator fun CharSequence.get(attrName: Any, body: (Stylesheet.()->Unit)? = null) = attr(attrName, body)
operator fun CharSequence.get(attrName: Any, attrValue: Any, body: (Stylesheet.()->Unit)? = null) = attr(attrName, attrValue, body)
operator fun CharSequence.get(attrName: Any, attrFiler: AttrFilter, attrValue: Any, body: (Stylesheet.()->Unit)? = null) = attr(attrName, attrValue, attrFiler, body)
private fun escapeAttrValue(str: String): String {
// http://stackoverflow.com/questions/5578845/css-attribute-selectors-the-rules-on-quotes-or-none
val isIdentifier = str.all { it >= '0' && it <= '9' || it >= 'a' && it <= 'z' || it >= 'A' && it <= 'Z' || it == '-' || it == '_' }
return if (isIdentifier) str else "\"${str.replace("\"", "\\\"")}\""
}
//
// CLASSES AND IDs
//
fun CharSequence.c(selector: Any, body: (Stylesheet.()->Unit)? = null) = custom(".$selector", false, true, body)
fun CharSequence.id(selector: Any, body: (Stylesheet.()->Unit)? = null) = custom("#$selector", false, true, body)
//
// TAGS
//
val CharSequence.any: Selector get() = custom("*")
val CharSequence.a: Selector get() = custom("a") // Defines a hyperlink.
val CharSequence.abbr: Selector get() = custom("abbr") // Defines an abbreviation or an acronym.
val CharSequence.acronym: Selector get() = custom("acronym") // Defines an acronym. Not supported in HTML5. Use <abbr> instead.
val CharSequence.address: Selector get() = custom("address") // Defines contact information for the author/owner of a document.
val CharSequence.applet: Selector get() = custom("applet") // Defines an embedded applet. Not supported in HTML5. Use <embed> or <object> instead.
val CharSequence.area: Selector get() = custom("area") // Defines an area inside an image-map.
val CharSequence.article: Selector get() = custom("article") // Defines an article.
val CharSequence.aside: Selector get() = custom("aside") // Defines content aside from the page content.
val CharSequence.audio: Selector get() = custom("audio") // Defines sound content.
val CharSequence.b: Selector get() = custom("b") // Defines bold text.
val CharSequence.base: Selector get() = custom("base") // Specifies the base URL/target for all relative URLs in a document.
val CharSequence.basefont: Selector get() = custom("basefont") // Specifies a default color, size, and font for all text in a document. Not supported in HTML5. Use CSS instead.
val CharSequence.bdi: Selector get() = custom("bdi") // Isolates a part of text that might be formatted in a different direction from other text outside it.
val CharSequence.bdo: Selector get() = custom("bdo") // Overrides the current text direction.
val CharSequence.big: Selector get() = custom("big") // Defines big text. Not supported in HTML5. Use CSS instead.
val CharSequence.blockquote: Selector get() = custom("blockquote") // Defines a section that is quoted from another source.
val CharSequence.body: Selector get() = custom("body") // Defines the document's body.
val CharSequence.br: Selector get() = custom("br") // Defines a single line break.
val CharSequence.button: Selector get() = custom("button") // Defines a clickable button.
val CharSequence.canvas: Selector get() = custom("canvas") // Used to draw graphics, on the fly, via scripting (usually JavaScript).
val CharSequence.caption: Selector get() = custom("caption") // Defines a table caption.
val CharSequence.center: Selector get() = custom("center") // Defines centered text. Not supported in HTML5. Use CSS instead.
val CharSequence.cite: Selector get() = custom("cite") // Defines the title of a work.
val CharSequence.code: Selector get() = custom("code") // Defines a piece of computer code.
val CharSequence.col: Selector get() = custom("col") // Specifies column properties for each column within a <colgroup> element.
val CharSequence.colgroup: Selector get() = custom("colgroup") // Specifies a group of one or more columns in a table for formatting.
val CharSequence.datalist: Selector get() = custom("datalist") // Specifies a list of pre-defined options for input controls.
val CharSequence.dd: Selector get() = custom("dd") // Defines a description/value of a term in a description list.
val CharSequence.del: Selector get() = custom("del") // Defines text that has been deleted from a document.
val CharSequence.details: Selector get() = custom("details") // Defines additional details that the user can view or hide.
val CharSequence.dfn: Selector get() = custom("dfn") // Represents the defining instance of a term.
val CharSequence.dialog: Selector get() = custom("dialog") // Defines a dialog box or window.
val CharSequence.dir: Selector get() = custom("dir") // Defines a directory list. Not supported in HTML5. Use <ul> instead.
val CharSequence.div: Selector get() = custom("div") // Defines a section in a document.
val CharSequence.dl: Selector get() = custom("dl") // Defines a description list.
val CharSequence.dt: Selector get() = custom("dt") // Defines a term/name in a description list.
val CharSequence.em: Selector get() = custom("em") // Defines emphasized text.
val CharSequence.embed: Selector get() = custom("embed") // Defines a container for an external (non-HTML) application.
val CharSequence.fieldset: Selector get() = custom("fieldset") // Groups related elements in a form.
val CharSequence.figcaption: Selector get() = custom("figcaption") // Defines a caption for a <figure> element.
val CharSequence.figure: Selector get() = custom("figure") // Specifies self-contained content.
val CharSequence.font: Selector get() = custom("font") // Defines font, color, and size for text. Not supported in HTML5. Use CSS instead.
val CharSequence.footer: Selector get() = custom("footer") // Defines a footer for a document or section.
val CharSequence.form: Selector get() = custom("form") // Defines an HTML form for user input.
val CharSequence.frame: Selector get() = custom("frame") // Defines a window (a frame) in a frameset. Not supported in HTML5.
val CharSequence.frameset: Selector get() = custom("frameset") // Defines a set of frames. Not supported in HTML5.
val CharSequence.h1: Selector get() = custom("h1") // Defines HTML headings.
val CharSequence.h2: Selector get() = custom("h2") // Defines HTML headings.
val CharSequence.h3: Selector get() = custom("h3") // Defines HTML headings.
val CharSequence.h4: Selector get() = custom("h4") // Defines HTML headings.
val CharSequence.h5: Selector get() = custom("h5") // Defines HTML headings.
val CharSequence.h6: Selector get() = custom("h6") // Defines HTML headings.
val CharSequence.head: Selector get() = custom("head") // Defines information about the document.
val CharSequence.header: Selector get() = custom("header") // Defines a header for a document or section.
val CharSequence.hr: Selector get() = custom("hr") // Defines a thematic change in the content.
val CharSequence.html: Selector get() = custom("html") // Defines the root of an HTML document.
val CharSequence.i: Selector get() = custom("i") // Defines a part of text in an alternate voice or mood.
val CharSequence.iframe: Selector get() = custom("iframe") // Defines an inline frame.
val CharSequence.img: Selector get() = custom("img") // Defines an image.
val CharSequence.input: Selector get() = custom("input") // Defines an input control.
val CharSequence.ins: Selector get() = custom("ins") // Defines a text that has been inserted into a document.
val CharSequence.kbd: Selector get() = custom("kbd") // Defines keyboard input.
val CharSequence.keygen: Selector get() = custom("keygen") // Defines a key-pair generator field (for forms).
val CharSequence.label: Selector get() = custom("label") // Defines a label for an <input> element.
val CharSequence.legend: Selector get() = custom("legend") // Defines a caption for a <fieldset> element.
val CharSequence.li: Selector get() = custom("li") // Defines a list item.
val CharSequence.link: Selector get() = custom("link") // Defines the relationship between a document and an external resource (most used to link to style sheets).
val CharSequence.main: Selector get() = custom("main") // Specifies the main content of a document.
val CharSequence.map: Selector get() = custom("map") // Defines a client-side image-map.
val CharSequence.mark: Selector get() = custom("mark") // Defines marked/highlighted text.
val CharSequence.menu: Selector get() = custom("menu") // Defines a list/menu of commands.
val CharSequence.menuitem: Selector get() = custom("menuitem") // Defines a command/menu item that the user can invoke from a popup menu.
val CharSequence.meta: Selector get() = custom("meta") // Defines metadata about an HTML document.
val CharSequence.meter: Selector get() = custom("meter") // Defines a scalar measurement within a known range (a gauge).
val CharSequence.nav: Selector get() = custom("nav") // Defines navigation links.
val CharSequence.noframes: Selector get() = custom("noframes") // Defines an alternate content for users that do not support frames. Not supported in HTML5.
val CharSequence.noscript: Selector get() = custom("noscript") // Defines an alternate content for users that do not support client-side scripts.
val CharSequence.`object`: Selector get() = custom("object") // Defines an embedded object.
val CharSequence.ol: Selector get() = custom("ol") // Defines an ordered list.
val CharSequence.optgroup: Selector get() = custom("optgroup") // Defines a group of related options in a drop-down list.
val CharSequence.option: Selector get() = custom("option") // Defines an option in a drop-down list.
val CharSequence.output: Selector get() = custom("output") // Defines the result of a calculation.
val CharSequence.p: Selector get() = custom("p") // Defines a paragraph.
val CharSequence.param: Selector get() = custom("param") // Defines a parameter for an object.
val CharSequence.pre: Selector get() = custom("pre") // Defines preformatted text.
val CharSequence.progress: Selector get() = custom("progress") // Represents the progress of a task.
val CharSequence.q: Selector get() = custom("q") // Defines a short quotation.
val CharSequence.rp: Selector get() = custom("rp") // Defines what to show in browsers that do not support ruby annotations.
val CharSequence.rt: Selector get() = custom("rt") // Defines an explanation/pronunciation of characters (for East Asian typography).
val CharSequence.ruby: Selector get() = custom("ruby") // Defines a ruby annotation (for East Asian typography).
val CharSequence.s: Selector get() = custom("s") // Defines text that is no longer correct.
val CharSequence.samp: Selector get() = custom("samp") // Defines sample output from a computer program.
val CharSequence.script: Selector get() = custom("script") // Defines a client-side script.
val CharSequence.section: Selector get() = custom("section") // Defines a section in a document.
val CharSequence.select: Selector get() = custom("select") // Defines a drop-down list.
val CharSequence.small: Selector get() = custom("small") // Defines smaller text.
val CharSequence.source: Selector get() = custom("source") // Defines multiple media resources for media elements (<video> and <audio>).
val CharSequence.span: Selector get() = custom("span") // Defines a section in a document.
val CharSequence.strike: Selector get() = custom("strike") // Defines strikethrough text. Not supported in HTML5. Use <del> or <s> instead.
val CharSequence.strong: Selector get() = custom("strong") // Defines important text.
val CharSequence.style: Selector get() = custom("style") // Defines style information for a document.
val CharSequence.sub: Selector get() = custom("sub") // Defines subscripted text.
val CharSequence.summary: Selector get() = custom("summary") // Defines a visible heading for a <details> element.
val CharSequence.sup: Selector get() = custom("sup") // Defines superscripted text.
val CharSequence.table: Selector get() = custom("table") // Defines a table.
val CharSequence.tbody: Selector get() = custom("tbody") // Groups the body content in a table.
val CharSequence.td: Selector get() = custom("td") // Defines a cell in a table.
val CharSequence.textarea: Selector get() = custom("textarea") // Defines a multiline input control (text area).
val CharSequence.tfoot: Selector get() = custom("tfoot") // Groups the footer content in a table.
val CharSequence.th: Selector get() = custom("th") // Defines a header cell in a table.
val CharSequence.thead: Selector get() = custom("thead") // Groups the header content in a table.
val CharSequence.time: Selector get() = custom("time") // Defines a date/time.
val CharSequence.title: Selector get() = custom("title") // Defines a title for the document.
val CharSequence.tr: Selector get() = custom("tr") // Defines a row in a table.
val CharSequence.track: Selector get() = custom("track") // Defines text tracks for media elements (<video> and <audio>).
val CharSequence.tt: Selector get() = custom("tt") // Defines teletype text. Not supported in HTML5. Use CSS instead.
val CharSequence.u: Selector get() = custom("u") // Defines text that should be stylistically different from normal text.
val CharSequence.ul: Selector get() = custom("ul") // Defines an unordered list.
val CharSequence.`var`: Selector get() = custom("var") // Defines a variable.
val CharSequence.video: Selector get() = custom("video") // Defines a video or movie.
val CharSequence.wbr: Selector get() = custom("wbr") // Defines a possible line-break.
//
// PSEUDO CLASSES AND ELEMENTS
//
val CharSequence.active: Selector get() = pseudo(":active") // (CSS1) Selects the active link
val CharSequence.after: Selector get() = pseudo(":after") // (CSS2) Insert something after the content of each <p> element
val CharSequence.before: Selector get() = pseudo(":before") // (CSS2) Insert something before the content of each <p> element
val CharSequence.checked: Selector get() = pseudo(":checked") // (CSS3) Selects every checked <input> element
val CharSequence.disabled: Selector get() = pseudo(":disabled") // (CSS3) Selects every disabled <input> element
val CharSequence.empty: Selector get() = pseudo(":empty") // (CSS3) Selects every <p> element that has no children (including text nodes)
val CharSequence.enabled: Selector get() = pseudo(":enabled") // (CSS3) Selects every enabled <input> element
val CharSequence.firstChild: Selector get() = pseudo(":first-child") // (CSS2) Selects every <p> element that is the first child of its parent
val CharSequence.firstLetter: Selector get() = pseudo(":first-letter") // (CSS1) Selects the first letter of every <p> element
val CharSequence.firstLine: Selector get() = pseudo(":first-line") // (CSS1) Selects the first line of every <p> element
val CharSequence.firstOfType: Selector get() = pseudo(":first-of-type") // (CSS3) Selects every <p> element that is the first <p> element of its parent
val CharSequence.focus: Selector get() = pseudo(":focus") // (CSS2) Selects the input element which has focus
val CharSequence.hover: Selector get() = pseudo(":hover") // (CSS1) Selects links on mouse over
val CharSequence.inRange: Selector get() = pseudo(":in-range") // (CSS3) Selects input elements with a value within a specified range
val CharSequence.invalid: Selector get() = pseudo(":invalid") // (CSS3) Selects all input elements with an invalid value
val CharSequence.lastChild: Selector get() = pseudo(":last-child") // (CSS3) Selects every <p> element that is the last child of its parent
val CharSequence.lastOfType: Selector get() = pseudo(":last-of-type") // (CSS3) Selects every <p> element that is the last <p> element of its parent
val CharSequence.onlyChild: Selector get() = pseudo(":only-child") // (CSS3) Selects every <p> element that is the only child of its parent
val CharSequence.onlyOfType: Selector get() = pseudo(":only-of-type") // (CSS3) Selects every <p> element that is the only <p> element of its parent
val CharSequence.optional: Selector get() = pseudo(":optional") // (CSS3) Selects input elements with no "required" attribute
val CharSequence.outOfRange: Selector get() = pseudo(":out-of-range") // (CSS3) Selects input elements with a value outside a specified range
val CharSequence.readOnly: Selector get() = pseudo(":read-only") // (CSS3) Selects input elements with the "readonly" attribute specified
val CharSequence.readWrite: Selector get() = pseudo(":read-write") // (CSS3) Selects input elements with the "readonly" attribute NOT specified
val CharSequence.required: Selector get() = pseudo(":required") // (CSS3) Selects input elements with the "required" attribute specified
val CharSequence.root: Selector get() = pseudo(":root") // (CSS3) Selects the document's root element
val CharSequence.selection: Selector get() = pseudo(":selection") // (Was drafted for CSS3, but removed before the Recommendation status) Selects the portion of an element that is selected by a user
val CharSequence.target: Selector get() = pseudo(":target") // (CSS3) Selects the current active #news element (clicked on a URL containing that anchor name)
val CharSequence.unvisited: Selector get() = pseudo(":link") // (CSS1) Selects all unvisited links
val CharSequence.valid: Selector get() = pseudo(":valid") // (CSS3) Selects all input elements with a valid value
val CharSequence.visited: Selector get() = pseudo(":visited") // (CSS1) Selects all visited links
fun CharSequence.lang(language: Any, body: (Stylesheet.()->Unit)? = null) = pseudoFn(":lang($language)", body) // (CSS2) Selects every <p> element with a lang attribute equal to "it" (Italian)
fun CharSequence.not(selector: Any, body: (Stylesheet.()->Unit)? = null) = pseudoFn(":not($selector)", body) // (CSS3) Selects every element that is not a <p> element
fun CharSequence.nthChild(n: Any, body: (Stylesheet.()->Unit)? = null) = pseudoFn(":nth-child($n)", body) // (CSS3) Selects every <p> element that is the second child of its parent
fun CharSequence.nthLastChild(n: Any, body: (Stylesheet.()->Unit)? = null) = pseudoFn(":nth-last-child($n)", body) // (CSS3) Selects every <p> element that is the second child of its parent, counting from the last child
fun CharSequence.nthLastOfType(n: Any, body: (Stylesheet.()->Unit)? = null) = pseudoFn(":nth-last-of-type($n)", body) // (CSS3) Selects every <p> element that is the second <p> element of its parent, counting from the last child
fun CharSequence.nthOfType(n: Any, body: (Stylesheet.()->Unit)? = null) = pseudoFn(":nth-of-type($n)", body) // (CSS3) Selects every <p> element that is the second <p> element of its parent
}
| mit | 8d0957c5dc67bd91e47ac661d984c9e8 | 58.107477 | 229 | 0.711479 | 3.827811 | false | false | false | false |
botandrose/eboshi_api_shootout | kotlin_spark/src/main/java/com/sleazyweasel/eboshi/AccountRoutes.kt | 2 | 2121 | package com.sleazyweasel.eboshi
import org.eclipse.jetty.http.HttpStatus
import org.jose4j.jwt.consumer.InvalidJwtException
import spark.Request
import spark.Response
import javax.inject.Inject
class AccountRoutes @Inject constructor(accountDataAccess: AccountDataAccess, auth: Auth) {
val create = { input: JsonApiRequest, response: Response ->
val submittedUserAttributes = input.data.attributes
val user = Account(submittedUserAttributes)
val (hashed, salt) = auth.encrypt(user.password!!)
val userReadyToSave = Account(submittedUserAttributes
.plus(listOf("crypted_password" to hashed, "password_salt" to salt))
.minus("password"))
val savedUser = accountDataAccess.insert(userReadyToSave)
response.status(HttpStatus.CREATED_201)
mapOf("data" to Account(savedUser.data.minus(listOf("crypted_password", "password_salt"))).toJsonApiObject())
}
val auth = { input: JsonApiRequest, response: Response ->
val authData = AuthData(input.data.attributes)
val account = accountDataAccess.getByEmail(authData.email!!)
if (auth.verify(authData.password, account.crypted_password)) {
val token = auth.generateToken(account)
mapOf("data" to AuthData(mapOf("email" to authData.email, "token" to token)).toJsonApiObject())
} else {
response.status(HttpStatus.UNAUTHORIZED_401)
mapOf("errors" to listOf(JsonApiError("Invalid authentication credentials")))
}
}
val get = { request: Request, response: Response ->
val authHeader = request.headers("Authorization")
val token = authHeader.substringAfter("Bearer ")
val email: String
try {
email = auth.validateToken(token)
val account = accountDataAccess.getByEmail(email)
mapOf("data" to account.toJsonApiObject())
} catch(e: InvalidJwtException) {
response.status(HttpStatus.UNAUTHORIZED_401)
mapOf("errors" to listOf(JsonApiError("Invalid authentication token")))
}
}
}
| mit | 1e863cdd79fd069128e8b77433b90156 | 42.285714 | 117 | 0.67421 | 4.580994 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/api/v1/twitch/GetTwitchInfoRoute.kt | 1 | 1716 | package net.perfectdreams.loritta.morenitta.website.routes.api.v1.twitch
import com.github.salomonbrys.kotson.jsonObject
import net.perfectdreams.loritta.morenitta.website.utils.WebsiteUtils
import net.perfectdreams.loritta.morenitta.utils.gson
import net.perfectdreams.loritta.morenitta.website.LoriWebCode
import net.perfectdreams.loritta.morenitta.website.WebsiteAPIException
import io.ktor.server.application.ApplicationCall
import io.ktor.http.HttpStatusCode
import mu.KotlinLogging
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.sequins.ktor.BaseRoute
import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondJson
class GetTwitchInfoRoute(val loritta: LorittaBot) : BaseRoute("/api/v1/twitch/channel") {
companion object {
private val logger = KotlinLogging.logger {}
}
override suspend fun onRequest(call: ApplicationCall) {
val id = call.parameters["id"]?.toLongOrNull()
val login = call.parameters["login"]
if (id != null) {
val payload = loritta.twitch.getUserLoginById(id)
?: throw WebsiteAPIException(
HttpStatusCode.NotFound,
WebsiteUtils.createErrorPayload(
loritta,
LoriWebCode.ITEM_NOT_FOUND,
"Streamer not found"
)
)
call.respondJson(gson.toJsonTree(payload))
} else if (login != null) {
val payload = loritta.twitch.getUserLogin(login)
?: throw WebsiteAPIException(
HttpStatusCode.NotFound,
WebsiteUtils.createErrorPayload(
loritta,
LoriWebCode.ITEM_NOT_FOUND,
"Streamer not found"
)
)
call.respondJson(gson.toJsonTree(payload))
} else {
call.respondJson(jsonObject(), HttpStatusCode.NotImplemented)
}
}
} | agpl-3.0 | 4afed2d236d62bf4184533e5b949a5cd | 32.019231 | 89 | 0.753497 | 4.085714 | false | false | false | false |
saru95/DSA | Kotlin/FastDoublingFibo.kt | 1 | 866 | import java.util.*
class FastDoublingFibo {
private val hm = HashMap<Integer, Integer>()
private fun fib(n: Int): Int {
if (n <= 2)
return 1
var ans = 0
if (hm.get(n) != null) {
ans = hm.get(n)
return ans
}
val half = n / 2
val a = fib(half + 1)
val b = fib(half)
if (n % 2 == 1)
ans = a * a + b * b
else
ans = 2 * a * b - b * b
hm.put(n, ans)
return ans
}
fun main(args: Array<String>) {
val sc = Scanner(System.`in`)
System.out.print("Enter n(0 to exit): ")
var n = sc.nextInt()
while (n != 0) {
val ans = fib(n)
System.out.println(ans)
System.out.print("Enter n(0 to exit): ")
n = sc.nextInt()
}
}
} | mit | f01681ef9784e4a6b9d2a049a1ef918c | 20.146341 | 52 | 0.421478 | 3.491935 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/components/ComponentContext.kt | 1 | 19420 | package net.perfectdreams.loritta.cinnamon.discord.interactions.components
import dev.kord.common.entity.ComponentType
import dev.kord.common.entity.DiscordChatComponent
import dev.kord.common.entity.DiscordPartialEmoji
import dev.kord.common.entity.Snowflake
import dev.kord.common.entity.optional.optional
import dev.kord.common.entity.optional.value
import dev.kord.core.entity.User
import net.perfectdreams.discordinteraktions.common.builder.message.actionRow
import net.perfectdreams.discordinteraktions.common.builder.message.create.InteractionOrFollowupMessageCreateBuilder
import net.perfectdreams.discordinteraktions.common.builder.message.modify.InteractionOrFollowupMessageModifyBuilder
import net.perfectdreams.discordinteraktions.common.components.ComponentContext
import net.perfectdreams.discordinteraktions.common.requests.InteractionRequestState
import net.perfectdreams.discordinteraktions.platforms.kord.utils.runIfNotMissing
import net.perfectdreams.i18nhelper.core.I18nContext
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.cinnamon.discord.interactions.InteractionContext
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.mentionUser
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.data.SingleUserComponentData
import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentDataUtils
import net.perfectdreams.loritta.cinnamon.discord.utils.LoadingEmojis
import net.perfectdreams.loritta.common.emotes.DiscordEmote
import net.perfectdreams.loritta.common.locale.BaseLocale
open class ComponentContext(
loritta: LorittaBot,
i18nContext: I18nContext,
locale: BaseLocale,
user: User,
override val interaKTionsContext: ComponentContext
) : InteractionContext(loritta, i18nContext, locale, user, interaKTionsContext) {
val data: String
get() = interaKTionsContext.data
val dataOrNull: String?
get() = interaKTionsContext.dataOrNull
suspend fun deferUpdateMessage() = interaKTionsContext.deferUpdateMessage()
suspend inline fun updateMessage(block: InteractionOrFollowupMessageModifyBuilder.() -> (Unit)) = interaKTionsContext.updateMessage(block)
/**
* Checks if the [user] has the same user ID present in the [data].
*
* If it isn't equal, the context will run [block]
*
* @see SingleUserComponentData
* @see failEphemerally
*/
fun requireUserToMatch(data: SingleUserComponentData, block: () -> (Unit)) {
if (data.userId != user.id)
block.invoke()
}
/**
* Checks if the [user] has the same user ID present in the [data].
*
* If it isn't equal, the context will [fail] or [failEphemerally], depending if the command was deferred ephemerally or not.
*
* If the command still haven't been replied or deferred, the command will default to a ephemeral fail.
*
* @see SingleUserComponentData
* @see requireUserToMatch
*/
fun requireUserToMatchOrContextuallyFail(data: SingleUserComponentData) = requireUserToMatch(data) {
val b: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {
styled(
i18nContext.get(
I18nKeysData.Commands.YouArentTheUserSingleUser(
mentionUser(data.userId, false)
)
),
Emotes.LoriRage
)
}
// We also check for "Deferred Update Message" because we can actually reply with an ephemeral message even if it was marked as a update message
if (interaKTionsContext.wasInitiallyDeferredEphemerally || interaKTionsContext.bridge.state.value == InteractionRequestState.NOT_REPLIED_YET || interaKTionsContext.bridge.state.value == InteractionRequestState.DEFERRED_UPDATE_MESSAGE)
failEphemerally(b)
else
fail(b)
}
/**
* Checks if the [user] has the same user ID present in the [data].
*
* If it isn't equal, the context will [failEphemerally], halting execution.
*
* @see SingleUserComponentData
* @see failEphemerally
*/
fun requireUserToMatchOrFail(data: SingleUserComponentData) = requireUserToMatch(data) {
fail {
styled(
i18nContext.get(
I18nKeysData.Commands.YouArentTheUserSingleUser(
mentionUser(data.userId, false)
)
),
Emotes.LoriRage
)
}
}
/**
* Checks if the [user] has the same user ID present in the [data].
*
* If it isn't equal, the context will [failEphemerally], halting execution.
*
* @see SingleUserComponentData
* @see failEphemerally
*/
fun requireUserToMatchOrFailEphemerally(data: SingleUserComponentData) = requireUserToMatch(data) {
failEphemerally {
styled(
i18nContext.get(
I18nKeysData.Commands.YouArentTheUserSingleUser(
mentionUser(data.userId, false)
)
),
Emotes.LoriRage
)
}
}
/**
* Decodes the [data] to [T].
*
* @see ComponentDataUtils
* @see failEphemerally
* @see requireUserToMatchOrFailEphemerally
*/
inline fun <reified T> decodeDataFromComponent(): T {
return ComponentDataUtils.decode<T>(data)
}
/**
* Decodes the [data] and checks if the [user] has the same user ID present in the [data].
*
* If it isn't equal, the context will [fail] or [failEphemerally], depending on the current request state, halting execution.
*
* @see SingleUserComponentData
* @see ComponentDataUtils
* @see failEphemerally
* @see requireUserToMatchOrFailEphemerally
*/
inline fun <reified T : SingleUserComponentData> decodeDataFromComponentAndRequireUserToMatch(): T {
val data = ComponentDataUtils.decode<T>(data)
requireUserToMatchOrContextuallyFail(data)
return data
}
/**
* Decodes the [data] or pulls it from the database if needed and checks if the [user] has the same user ID present in the [data].
*
* If the data is not present on the database, null will be returned.
*
* If it isn't equal, the context will [fail] or [failEphemerally], depending on the current request state, halting execution.
*
* @see SingleUserComponentData
* @see ComponentDataUtils
* @see failEphemerally
* @see requireUserToMatchOrFailEphemerally
* @see decodeDataFromComponentAndRequireUserToMatch
*/
suspend inline fun <reified T : SingleUserComponentData> decodeDataFromComponentOrFromDatabaseIfPresentAndRequireUserToMatch(): T? {
val data = loritta.decodeDataFromComponentOrFromDatabase<T>(data) ?: return null
requireUserToMatchOrContextuallyFail(data)
return data
}
/**
* Decodes the [data] or pulls it from the database if needed.
*
* If the data is not present on the database, the context will [fail] or [failEphemerally] with the [block] message, depending on the current request state, halting execution.
*
* @see SingleUserComponentData
* @see ComponentDataUtils
* @see failEphemerally
*/
suspend inline fun <reified T> decodeDataFromComponentOrFromDatabase(
block: InteractionOrFollowupMessageCreateBuilder.() -> (Unit) = {
styled(
i18nContext.get(I18nKeysData.Commands.InteractionDataIsMissingFromDatabaseGeneric),
Emotes.LoriSleeping
)
}
): T {
return loritta.decodeDataFromComponentOrFromDatabase<T>(data)
?: if (interaKTionsContext.wasInitiallyDeferredEphemerally || interaKTionsContext.bridge.state.value == InteractionRequestState.NOT_REPLIED_YET)
failEphemerally(block)
else
fail(block)
}
/**
* Updates the current message to disable all components in the message that the component is attached to, and sets the message content
* to "Loading...".
*
* On the component that the user clicked, the text in it will be replaced with "Loading..."
*
* **This should not be used if you are planning to send a follow-up message, only for when you are going to update the message where the component is attached to!**
*
* **This should not be used for components that can be used by multiple users!** (If it doesn't use [SingleUserComponentData], then you shouldn't use this!)
*
* **This should only be used after you validated that the user can use the component!** (Example: After checking with [decodeDataFromComponentAndRequireUserToMatch])
*/
suspend fun updateMessageSetLoadingState(
updateMessageContent: Boolean = true,
disableComponents: Boolean = true,
loadingEmoji: DiscordEmote = LoadingEmojis.random()
) {
updateMessage {
if (updateMessageContent)
styled(
i18nContext.get(I18nKeysData.Website.Dashboard.Loading),
loadingEmoji
)
if (disableComponents)
disableComponents(loadingEmoji, this)
}
}
/**
* Disables all components in the message that the component is attached to on the [builder].
*
* On the component that the user clicked, the text in it will be replaced with "Loading..."
*/
fun disableComponents(loadingEmoji: DiscordEmote, builder: InteractionOrFollowupMessageModifyBuilder) {
// The message property isn't null in a component interaction
interaKTionsContext.discordInteraction.message.value!!.components.value!!.forEach {
it as DiscordChatComponent // Here only a DiscordChatComponent can exist
if (it.type == ComponentType.ActionRow) {
builder.actionRow {
it.components.value!!.forEach {
it as DiscordChatComponent // Again, only a DiscordChatComponent can exist here
when (it.type) {
ComponentType.ActionRow -> error("This shouldn't exist here!")
ComponentType.Button -> {
interactionButton(
it.style.value!!, // The style shouldn't be null if it is a button
generateDisabledComponentId()
) {
disabled = true
label = it.label.value
// We want to get the *raw* custom ID, not the one that was already processed by Discord InteraKTions
if (interaKTionsContext.discordInteraction.data.customId.value == it.customId.value)
emoji = DiscordPartialEmoji(
Snowflake(loadingEmoji.id),
loadingEmoji.name,
animated = loadingEmoji.animated.optional()
)
else
emoji = it.emoji.value
}
}
ComponentType.SelectMenu -> {
selectMenu(generateDisabledComponentId()) {
val minValues = it.minValues.value ?: 1
val maxValues = it.maxValues.value ?: 1
this.disabled = true
runIfNotMissing(it.placeholder) { this.placeholder = it }
runIfNotMissing(it.options) { optionList ->
if (optionList != null) {
if (minValues == 1 && maxValues == 1) {
// We will use our own custom "Loading" option, sweet!
option(i18nContext.get(I18nKeysData.Website.Dashboard.Loading), "loading_psst_hey_u_are_cute_uwu") { // heh easter egg
this.emoji = DiscordPartialEmoji(
Snowflake(loadingEmoji.id),
loadingEmoji.name,
animated = loadingEmoji.animated.optional()
)
this.default = true
}
} else {
// If not, we will insert the current options as is, to avoiding shifting the content around
optionList.forEach {
option(it.label, it.value) {
runIfNotMissing(it.description) { this.description = it }
runIfNotMissing(it.emoji) { this.emoji = it }
// We need to get the current values list from the interaction itself, to avoid the user changing the select menu value, then when Loritta updates the message
// the selection is *gone*
this.default = it.value in (interaKTionsContext.discordInteraction.data.values.value ?: emptyList())
}
}
}
}
}
this.allowedValues = minValues..maxValues
}
}
ComponentType.TextInput -> error("This shouldn't exist here!")
is ComponentType.Unknown -> error("This shouldn't exist here!")
}
}
}
}
}
}
/**
* Disables all components in the message that the component is attached to on the [builder].
*/
fun disableComponents(builder: InteractionOrFollowupMessageModifyBuilder) {
// The message property isn't null in a component interaction
interaKTionsContext.discordInteraction.message.value!!.components.value!!.forEach {
it as DiscordChatComponent // Here only a DiscordChatComponent can exist
if (it.type == ComponentType.ActionRow) {
builder.actionRow {
it.components.value!!.forEach {
it as DiscordChatComponent // Again, only a DiscordChatComponent can exist here
when (it.type) {
ComponentType.ActionRow -> error("This shouldn't exist here!")
ComponentType.Button -> {
interactionButton(
it.style.value!!, // The style shouldn't be null if it is a button
generateDisabledComponentId()
) {
disabled = true
label = it.label.value
emoji = it.emoji.value
}
}
ComponentType.SelectMenu -> {
selectMenu(generateDisabledComponentId()) {
val minValues = it.minValues.value ?: 1
val maxValues = it.maxValues.value ?: 1
this.disabled = true
runIfNotMissing(it.placeholder) { this.placeholder = it }
runIfNotMissing(it.options) { optionList ->
optionList?.forEach {
option(it.label, it.value) {
runIfNotMissing(it.description) { this.description = it }
runIfNotMissing(it.emoji) { this.emoji = it }
// We need to get the current values list from the interaction itself, to avoid the user changing the select menu value, then when Loritta updates the message
// the selection is *gone*
this.default = it.value in (interaKTionsContext.discordInteraction.data.values.value ?: emptyList())
}
}
}
this.allowedValues = minValues..maxValues
}
}
ComponentType.TextInput -> error("This shouldn't exist here!")
is ComponentType.Unknown -> error("This shouldn't exist here!")
}
}
}
}
}
}
/**
* Decodes the [data] or pulls it from the database if needed and checks if the [user] has the same user ID present in the [data].
*
* If the data is not present on the database, the context will [fail] or [failEphemerally] with the [block] message, depending on the current request state, halting execution.
*
* If it isn't equal, the context will [fail] or [failEphemerally], depending on the current request state, halting execution.
*
* @see SingleUserComponentData
* @see ComponentDataUtils
* @see failEphemerally
* @see requireUserToMatchOrFailEphemerally
* @see decodeDataFromComponentAndRequireUserToMatch
*/
suspend inline fun <reified T : SingleUserComponentData> decodeDataFromComponentOrFromDatabaseAndRequireUserToMatch(
block: InteractionOrFollowupMessageCreateBuilder.() -> (Unit) = {
styled(
i18nContext.get(I18nKeysData.Commands.InteractionDataIsMissingFromDatabaseGeneric),
Emotes.LoriSleeping
)
}
): T {
return decodeDataFromComponentOrFromDatabaseIfPresentAndRequireUserToMatch()
?: if (interaKTionsContext.wasInitiallyDeferredEphemerally || interaKTionsContext.bridge.state.value == InteractionRequestState.NOT_REPLIED_YET)
failEphemerally(block)
else
fail(block)
}
} | agpl-3.0 | a72850dea2b79057438f1f964cbcd7e4 | 48.417303 | 242 | 0.564109 | 6.010523 | false | false | false | false |
spinnaker/spinnaker-gradle-project | spinnaker-extensions/src/main/kotlin/com/netflix/spinnaker/gradle/extension/tasks/CreatePluginInfoTask.kt | 1 | 3803 | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.gradle.extension.tasks
import com.fasterxml.jackson.module.kotlin.readValue
import com.netflix.spinnaker.gradle.extension.PluginObjectMapper
import com.netflix.spinnaker.gradle.extension.Plugins
import com.netflix.spinnaker.gradle.extension.Plugins.CHECKSUM_BUNDLE_TASK_NAME
import com.netflix.spinnaker.gradle.extension.compatibility.CompatibilityTestResult
import com.netflix.spinnaker.gradle.extension.compatibility.CompatibilityTestTask
import com.netflix.spinnaker.gradle.extension.extensions.SpinnakerBundleExtension
import com.netflix.spinnaker.gradle.extension.extensions.SpinnakerPluginExtension
import com.netflix.spinnaker.gradle.extension.getParent
import groovy.json.JsonOutput
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.TaskAction
import java.io.File
import java.lang.IllegalStateException
import java.time.Instant
/**
* TODO(rz): Need to expose release state to the world.
*/
open class CreatePluginInfoTask : DefaultTask() {
@Internal
override fun getGroup(): String = Plugins.GROUP
@Internal
val rootProjectVersion: String = project.version.toString()
@TaskAction
fun doAction() {
val allPluginExts = project
.subprojects
.mapNotNull { it.extensions.findByType(SpinnakerPluginExtension::class.java) }
.toMutableList()
val bundleExt = project.extensions.findByType(SpinnakerBundleExtension::class.java)
?: throw IllegalStateException("A 'spinnakerBundle' configuration block is required")
val requires = allPluginExts.map { it.requires ?: "${it.serviceName}>=0.0.0" }
.let {
if (Plugins.hasDeckPlugin(project)) {
it + "deck>=0.0.0"
} else {
it
}
}
.joinToString(",")
val compatibility = project
.subprojects
.flatMap { it.tasks.withType(CompatibilityTestTask::class.java) }
.map { it.result.get().asFile }
.filter { it.exists() }
.map { PluginObjectMapper.mapper.readValue<CompatibilityTestResult>(it.readBytes()) }
val pluginInfo = mapOf(
"id" to bundleExt.pluginId,
"description" to bundleExt.description,
"provider" to bundleExt.provider,
"releases" to listOf(
mapOf(
"version" to if (isVersionSpecified(bundleExt.version)) bundleExt.version else rootProjectVersion,
"date" to Instant.now().toString(),
"requires" to requires,
"sha512sum" to getChecksum(),
"preferred" to false,
"compatibility" to compatibility
)
)
)
// TODO(rz): Is it bad to put the plugin-info into the distributions build dir?
File(project.buildDir, "distributions/plugin-info.json").writeText(
JsonOutput.prettyPrint(JsonOutput.toJson(pluginInfo))
)
}
private fun isVersionSpecified(version: String): Boolean {
return version.isNotBlank() && version != Project.DEFAULT_VERSION
}
private fun getChecksum(): String {
return project.tasks
.getByName(CHECKSUM_BUNDLE_TASK_NAME)
.outputs
.files
.files
.first()
.listFiles()
.first()
.readText()
}
}
| apache-2.0 | 9fa22d9401a97d123c2f6ef2bfa4d395 | 33.261261 | 108 | 0.714699 | 4.311791 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/GivenAHaltedPlaylistEngine/AndAPlaylistIsPreparing/WhenATrackIsSwitched.kt | 1 | 2986 | package com.lasthopesoftware.bluewater.client.playback.engine.GivenAHaltedPlaylistEngine.AndAPlaylistIsPreparing
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.library.access.ILibraryStorage
import com.lasthopesoftware.bluewater.client.browsing.library.access.ISpecificLibraryProvider
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.playback.engine.PlaybackEngine.Companion.createEngine
import com.lasthopesoftware.bluewater.client.playback.engine.bootstrap.PlaylistPlaybackBootstrapper
import com.lasthopesoftware.bluewater.client.playback.engine.preparation.PreparedPlaybackQueueResourceManagement
import com.lasthopesoftware.bluewater.client.playback.file.PositionedFile
import com.lasthopesoftware.bluewater.client.playback.file.preparation.FakeDeferredPlayableFilePreparationSourceProvider
import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CompletingFileQueueProvider
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlayingRepository
import com.lasthopesoftware.bluewater.client.playback.volume.PlaylistVolumeManager
import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.joda.time.Duration
import org.junit.BeforeClass
import org.junit.Test
class WhenATrackIsSwitched {
companion object {
private var nextSwitchedFile: PositionedFile? = null
@BeforeClass
@JvmStatic
fun before() {
val fakePlaybackPreparerProvider = FakeDeferredPlayableFilePreparationSourceProvider()
val library = Library()
library.setId(1)
val libraryProvider = mockk<ISpecificLibraryProvider>()
every { libraryProvider.library } returns (Promise(library))
val libraryStorage = mockk<ILibraryStorage>()
every { libraryStorage.saveLibrary(any()) } returns Promise(library)
val playbackEngine = FuturePromise(
createEngine(
PreparedPlaybackQueueResourceManagement(
fakePlaybackPreparerProvider
) { 1 }, listOf(CompletingFileQueueProvider()),
NowPlayingRepository(libraryProvider, libraryStorage),
PlaylistPlaybackBootstrapper(PlaylistVolumeManager(1.0f))
)
).get()
playbackEngine?.startPlaylist(
mutableListOf(
ServiceFile(1),
ServiceFile(2),
ServiceFile(3),
ServiceFile(4),
ServiceFile(5)
), 0, Duration.ZERO
)
val futurePositionedFile = FuturePromise(
playbackEngine!!.changePosition(3, Duration.ZERO)
)
fakePlaybackPreparerProvider.deferredResolution.resolve()
nextSwitchedFile = futurePositionedFile.get()
}
}
@Test
fun thenTheNextFileChangeIsTheSwitchedToTheCorrectTrackPosition() {
assertThat(nextSwitchedFile!!.playlistPosition).isEqualTo(3)
}
}
| lgpl-3.0 | 43ead9a5165ef282d4692f68326f6dcd | 41.056338 | 120 | 0.821835 | 4.58679 | false | false | false | false |
harkwell/khallware | tools/src/main/kotlin/com/khallware/api/util/domain.kt | 1 | 1753 | // Copyright Kevin D.Hall 2018
package com.khallware.api.util
import java.math.BigDecimal
data class Tag(val id: Int, val name: String, val user: Int = 1,
val group: Int = 2)
{
}
data class Bookmark(val id: Int, val name: String, val url: String,
val rating: String = "good", val numtags: Int = -1,
val user: Int = 1, val group: Int = 2)
{
}
data class Location(val id: Int, val name: String, val lat: BigDecimal,
val lon: BigDecimal, val address: String, val desc: String,
val numtags: Int)
{
}
data class Contact(val id: Int, val name: String, val uid: String,
val email: String, val phone: String, val title: String,
val address: String, val organization: String,
val vcard: String, val desc: String, val numtags: Int)
{
}
data class Event(val id: Int, val name: String, val uid: String,
val duration: Int, val start: Int, val end: Int,
val ics: String, val desc: String, val numtags: Int)
{
}
data class Photo(val id: Int, val name: String, val path: String,
val md5sum: String, val desc: String, val numtags: Int = -1,
val user: Int = 1, val group: Int = 2)
{
}
data class FileItem(val id: Int, val name: String, val ext: String,
val md5sum: String, val desc: String, val mime: String,
val path: String, val numtags: Int,
val user: Int = 1, val group: Int = 2)
{
}
data class Sound(val id: Int, val name: String, val path: String,
val md5sum: String, val desc: String, val title: String,
val artist: String, val genre: String, val album: String,
val publisher: String, val numtags: Int,
val user: Int = 1, val group: Int = 2)
{
}
data class Video(val id: Int, val name: String, val path: String,
val md5sum: String, val desc: String, val numtags: Int,
val user: Int = 1, val group: Int = 2)
{
}
| gpl-3.0 | be6123364f15caa3cf6338a5a9086ee3 | 27.274194 | 71 | 0.676554 | 2.981293 | false | false | false | false |
lttng/lttng-scope | jabberwocky-lttng/src/main/kotlin/com/efficios/jabberwocky/lttng/kernel/analysis/os/handlers/SoftIrqEntryHandler.kt | 2 | 1870 | /*
* Copyright (C) 2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
* Copyright (C) 2015 Ericsson
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.lttng.kernel.analysis.os.handlers
import ca.polymtl.dorsal.libdelorean.IStateSystemWriter
import com.efficios.jabberwocky.lttng.kernel.analysis.os.StateValues
import com.efficios.jabberwocky.lttng.kernel.trace.layout.LttngKernelEventLayout
import com.efficios.jabberwocky.trace.event.FieldValue.IntegerValue
import com.efficios.jabberwocky.trace.event.TraceEvent
class SoftIrqEntryHandler(layout: LttngKernelEventLayout) : KernelEventHandler(layout) {
override fun handleEvent(ss: IStateSystemWriter, event: TraceEvent) {
val cpu = event.cpu
val timestamp = event.timestamp
val softIrqId = (event.fields[layout.fieldVec] as IntegerValue).value.toInt()
val cpuNode = ss.getCPUNode(cpu)
val currentThreadNode = ss.getCurrentThreadNode(cpu)
/* Mark this SoftIRQ as active in the resource tree. */
ss.modifyAttribute(timestamp,
StateValues.CPU_STATUS_SOFTIRQ_VALUE,
ss.getQuarkRelativeAndAdd(ss.getNodeSoftIRQs(cpu), softIrqId.toString()))
/* Change the status of the running process to interrupted */
currentThreadNode?.let {
ss.modifyAttribute(timestamp,
StateValues.PROCESS_STATUS_INTERRUPTED_VALUE,
it)
}
/* Change the status of the CPU to interrupted */
ss.modifyAttribute(timestamp,
StateValues.CPU_STATUS_SOFTIRQ_VALUE,
cpuNode)
}
}
| epl-1.0 | cb0d19beee4404a409c4fe16858b66e8 | 38.787234 | 89 | 0.709626 | 4.318707 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/settings/LearnMoreSwitchPreference.kt | 1 | 1815 | package org.mozilla.focus.settings
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.preference.PreferenceViewHolder
import androidx.preference.SwitchPreferenceCompat
import mozilla.components.browser.state.state.SessionState
import org.mozilla.focus.R
import org.mozilla.focus.ext.components
import org.mozilla.focus.state.AppAction
abstract class LearnMoreSwitchPreference(context: Context, attrs: AttributeSet?) :
SwitchPreferenceCompat(context, attrs) {
init {
layoutResource = R.layout.preference_switch_learn_more
}
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
getDescription()?.let {
val summaryView = holder.findViewById(android.R.id.summary) as TextView
summaryView.text = it
summaryView.isVisible = true
}
val learnMoreLink = holder.findViewById(R.id.link) as TextView
learnMoreLink.setOnClickListener {
val tabId = context.components.tabsUseCases.addTab(
getLearnMoreUrl(),
source = SessionState.Source.Internal.Menu,
selectTab = true,
private = true,
)
context.components.appStore.dispatch(
AppAction.OpenTab(tabId),
)
}
val backgroundDrawableArray =
context.obtainStyledAttributes(intArrayOf(R.attr.selectableItemBackground))
val backgroundDrawable = backgroundDrawableArray.getDrawable(0)
backgroundDrawableArray.recycle()
learnMoreLink.background = backgroundDrawable
}
open fun getDescription(): String? = null
abstract fun getLearnMoreUrl(): String
}
| mpl-2.0 | 4172b5237abed2d735002ff97fb0cc50 | 32.611111 | 87 | 0.69697 | 5.230548 | false | false | false | false |
FaustXVI/kotlin-koans | src/i_introduction/_4_Lambdas/Lambdas.kt | 3 | 679 | package i_introduction._4_Lambdas
import util.TODO
import util.doc4
fun example() {
val sum = { x: Int, y: Int -> x + y }
val square: (Int) -> Int = { x -> x * x }
sum(1, square(2)) == 5
}
fun todoTask4(collection: Collection<Int>): Nothing = TODO(
"""
Task 4.
Rewrite 'JavaCode4.task4()' in Kotlin using lambdas.
You can find the appropriate function to call on 'collection' through IntelliJ IDEA's code completion feature.
(Don't use the class 'Iterables').
""",
documentation = doc4(),
references = { JavaCode4().task4(collection) })
fun task4(collection: Collection<Int>): Boolean = todoTask4(collection)
| mit | 8e092015b5fa17237884ebc1cd781374 | 23.25 | 118 | 0.628866 | 3.751381 | false | false | false | false |
Caellian/Math | src/main/kotlin/hr/caellian/math/matrix/MatrixN.kt | 1 | 4470 | package hr.caellian.math.matrix
import hr.caellian.math.internal.Inverse
import hr.caellian.math.vector.Vector
import hr.caellian.math.vector.VectorN
/**
* Abstract Matrix class defining number matrix specific behaviour.
*
* @since 3.0.0
* @author Caellian
*/
abstract class MatrixN<T : Number> : Matrix<T>() {
/**
* @return this matrix.
*/
operator fun unaryPlus() = this
/**
* @return new matrix with negated values.
*/
abstract operator fun unaryMinus(): MatrixN<T>
/**
* Performs matrix addition and returns resulting matrix.
* In order to add to matrices together, they must be of same size.
*
* @param other matrix to add to this one.
* @return resulting of matrix addition.
*/
abstract operator fun plus(other: MatrixN<T>): MatrixN<T>
/**
* Performs matrix subtraction and returns resulting matrix.
* In order to subtract one matrix from another, matrices must be of same size.
*
* @param other matrix to subtract from this one.
* @return resulting of matrix subtraction.
*/
abstract operator fun minus(other: MatrixN<T>): MatrixN<T>
/**
* Performs matrix multiplication on this matrix.
* Returns C from 'C = A×B' where A is this matrix and B is the other / argument matrix.
*
* @param other matrix to multiply this matrix with.
* @return result of matrix multiplication.
*/
abstract operator fun times(other: MatrixN<T>): MatrixN<T>
/**
* Performs matrix multiplication on this matrix.
* Returns C from 'C = A×B' where A is this matrix and B is the other / argument vector.
*
* @param other vector to multiply this matrix with.
* @return result of matrix multiplication.
*/
abstract operator fun times(other: VectorN<T>): Vector<T>
/**
* Performs scalar multiplication on this matrix and returns resulting matrix.
*
* @param scalar scalar to multiply every member of this matrix with.
* @return result of scalar matrix multiplication.
*/
abstract operator fun times(scalar: T): MatrixN<T>
/**
* @return inverse matrix.
*/
override operator fun not(): Matrix<T> = inverse()
/**
* Multiplies all entries of a row with given scalar.
*
* @param row row to multiply.
* @param multiplier scalar to multiply rows entries with.
* @return resulting matrix.
*/
abstract fun multiplyRow(row: Int, multiplier: T): MatrixN<T>
/**
* Multiplies all entries of a column with given scalar.
*
* @param column column to multiply.
* @param multiplier scalar to multiply column entries with.
* @return resulting matrix.
*/
abstract fun multiplyColumn(column: Int, multiplier: T): MatrixN<T>
/**
* Adds one row from matrix to another.
*
* @param from row to add to another row.
* @param to row to add another row to; data will be stored on this row.
* @param multiplier scalar to multiply all members of added row with on addition. It equals to 1 by default.
* @return new matrix.
*/
abstract fun addRows(from: Int, to: Int, multiplier: T? = null): MatrixN<T>
/**
* Adds one column from matrix to another.
*
* @param from column to add to another column.
* @param to column to add another column to; data will be stored on this column.
* @param multiplier scalar to multiply all members of added column with on addition. It equals to 1 by default.
* @return new matrix.
*/
abstract fun addColumns(from: Int, to: Int, multiplier: T? = null): MatrixN<T>
/**
* @return inverse matrix.
*/
fun inverse(singularityThreshold: Double = 1e-11): MatrixN<T> {
@Suppress("UNCHECKED_CAST")
return withData(
Inverse.inverseMatrix(toArray() as Array<Array<Double>>,
singularityThreshold) as Array<Array<T>>) as MatrixN<T>
}
/**
* This method replaces data of this matrix with LU decomposition data.
*
* @return self.
*/
fun inverseUnsafe(singularityThreshold: Double = 1e-11): MatrixN<T> {
@Suppress("UNCHECKED_CAST")
return withData(Inverse.inverseMatrix(wrapped as Array<Array<Double>>,
singularityThreshold) as Array<Array<T>>) as MatrixN<T>
}
} | mit | 50ff4132953a0e9db00a5445b3afc98e | 33.114504 | 116 | 0.631603 | 4.380392 | false | false | false | false |
gravidence/gravifon | gravifon/src/main/kotlin/org/gravidence/gravifon/util/Stopwatch.kt | 1 | 1464 | package org.gravidence.gravifon.util
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import mu.KotlinLogging
import kotlin.time.Duration
private val logger = KotlinLogging.logger {}
class Stopwatch {
private var elapsed: Duration = Duration.ZERO
private var spanStart: Instant? = null
@Synchronized
fun count() {
// start new cycle only if measurement is NOT in progress already
if (spanStart == null) {
spanStart = Clock.System.now().also {
logger.trace { "Open stopwatch span at $it" }
}
}
}
@Synchronized
fun pause(): Duration {
// update state only if measurement is in progress
spanStart?.let { start ->
// update elapsed counter
val spanEnd = Clock.System.now().also { end ->
logger.trace { "Close stopwatch span at $end" }
}
elapsed += spanEnd.minus(start)
// reset span to mark end of a measurement cycle
spanStart = null
}
return elapsed()
}
@Synchronized
fun stop(): Duration {
// finish up measurement process and keep keep total duration
val duration = pause()
// reset elapsed counter
elapsed = Duration.ZERO
return duration
}
fun elapsed(): Duration {
return elapsed.also {
logger.trace { "Elapsed time is $it" }
}
}
} | mit | 2485e95359b417a7d217a89770112495 | 23.416667 | 73 | 0.584699 | 4.945946 | false | false | false | false |
google/horologist | media-ui/src/debug/java/com/google/android/horologist/media/ui/screens/entity/PlaylistDownloadScreenPreview.kt | 1 | 9876 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalHorologistMediaUiApi::class)
package com.google.android.horologist.media.ui.screens.entity
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MusicNote
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.wear.compose.material.rememberScalingLazyListState
import com.google.android.horologist.base.ui.util.rememberVectorPainter
import com.google.android.horologist.compose.tools.WearPreviewDevices
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import com.google.android.horologist.media.ui.state.model.DownloadMediaUiModel
import com.google.android.horologist.media.ui.state.model.PlaylistUiModel
@WearPreviewDevices
@Composable
fun PlaylistDownloadScreenPreviewLoading() {
PlaylistDownloadScreen(
playlistName = "Playlist name",
playlistDownloadScreenState = PlaylistDownloadScreenState.Loading(),
onDownloadButtonClick = { },
onCancelDownloadButtonClick = { },
onDownloadItemClick = { },
onDownloadItemInProgressClick = { },
onShuffleButtonClick = { },
onPlayButtonClick = { },
scalingLazyListState = rememberScalingLazyListState()
)
}
@WearPreviewDevices
@Composable
fun PlaylistDownloadScreenPreviewLoadedNoneDownloaded() {
PlaylistDownloadScreen(
playlistName = "Playlist name",
playlistDownloadScreenState = createPlaylistDownloadScreenStateLoaded(
playlistModel = playlistUiModel,
downloadMediaList = notDownloaded
),
onDownloadButtonClick = { },
onCancelDownloadButtonClick = { },
onDownloadItemClick = { },
onDownloadItemInProgressClick = { },
onShuffleButtonClick = { },
onPlayButtonClick = { },
scalingLazyListState = rememberScalingLazyListState(),
downloadItemArtworkPlaceholder = rememberVectorPainter(
image = Icons.Default.MusicNote,
tintColor = Color.Blue
)
)
}
@WearPreviewDevices
@Composable
fun PlaylistDownloadScreenPreviewLoadedNoneDownloadedDownloading() {
PlaylistDownloadScreen(
playlistName = "Playlist name",
playlistDownloadScreenState = createPlaylistDownloadScreenStateLoaded(
playlistModel = playlistUiModel,
downloadMediaList = notDownloadedAndDownloading
),
onDownloadButtonClick = { },
onCancelDownloadButtonClick = { },
onDownloadItemClick = { },
onDownloadItemInProgressClick = { },
onShuffleButtonClick = { },
onPlayButtonClick = { },
scalingLazyListState = rememberScalingLazyListState(),
downloadItemArtworkPlaceholder = rememberVectorPainter(
image = Icons.Default.MusicNote,
tintColor = Color.Blue
)
)
}
@WearPreviewDevices
@Composable
fun PlaylistDownloadScreenPreviewLoadedPartiallyDownloaded() {
PlaylistDownloadScreen(
playlistName = "Playlist name",
playlistDownloadScreenState = createPlaylistDownloadScreenStateLoaded(
playlistModel = playlistUiModel,
downloadMediaList = downloadedNotDownloaded
),
onDownloadButtonClick = { },
onCancelDownloadButtonClick = { },
onDownloadItemClick = { },
onDownloadItemInProgressClick = { },
onShuffleButtonClick = { },
onPlayButtonClick = { },
scalingLazyListState = rememberScalingLazyListState(),
downloadItemArtworkPlaceholder = rememberVectorPainter(
image = Icons.Default.MusicNote,
tintColor = Color.Blue
)
)
}
@WearPreviewDevices
@Composable
fun PlaylistDownloadScreenPreviewLoadedPartiallyDownloadedDownloadingUnknownSize() {
PlaylistDownloadScreen(
playlistName = "Playlist name",
playlistDownloadScreenState = createPlaylistDownloadScreenStateLoaded(
playlistModel = playlistUiModel,
downloadMediaList = downloadedAndDownloadingUnknown
),
onDownloadButtonClick = { },
onCancelDownloadButtonClick = { },
onDownloadItemClick = { },
onDownloadItemInProgressClick = { },
onShuffleButtonClick = { },
onPlayButtonClick = { },
scalingLazyListState = rememberScalingLazyListState(),
downloadItemArtworkPlaceholder = rememberVectorPainter(
image = Icons.Default.MusicNote,
tintColor = Color.Blue
)
)
}
@WearPreviewDevices
@Composable
fun PlaylistDownloadScreenPreviewLoadedPartiallyDownloadedDownloadingWaiting() {
PlaylistDownloadScreen(
playlistName = "Playlist name",
playlistDownloadScreenState = createPlaylistDownloadScreenStateLoaded(
playlistModel = playlistUiModel,
downloadMediaList = downloadedAndDownloadingWaiting
),
onDownloadButtonClick = { },
onCancelDownloadButtonClick = { },
onDownloadItemClick = { },
onDownloadItemInProgressClick = { },
onShuffleButtonClick = { },
onPlayButtonClick = { },
scalingLazyListState = rememberScalingLazyListState(),
downloadItemArtworkPlaceholder = rememberVectorPainter(
image = Icons.Default.MusicNote,
tintColor = Color.Blue
)
)
}
@WearPreviewDevices
@Composable
fun PlaylistDownloadScreenPreviewLoadedFullyDownloaded() {
PlaylistDownloadScreen(
playlistName = "Playlist name",
playlistDownloadScreenState = createPlaylistDownloadScreenStateLoaded(
playlistModel = playlistUiModel,
downloadMediaList = downloaded
),
onDownloadButtonClick = { },
onCancelDownloadButtonClick = { },
onDownloadItemClick = { },
onDownloadItemInProgressClick = { },
onShuffleButtonClick = { },
onPlayButtonClick = { },
scalingLazyListState = rememberScalingLazyListState(),
downloadItemArtworkPlaceholder = rememberVectorPainter(
image = Icons.Default.MusicNote,
tintColor = Color.Blue
)
)
}
@WearPreviewDevices
@Composable
fun PlaylistDownloadScreenPreviewFailed() {
PlaylistDownloadScreen(
playlistName = "Playlist name",
playlistDownloadScreenState = PlaylistDownloadScreenState.Failed(),
onDownloadButtonClick = { },
onCancelDownloadButtonClick = { },
onDownloadItemClick = { },
onDownloadItemInProgressClick = { },
onShuffleButtonClick = { },
onPlayButtonClick = { },
scalingLazyListState = rememberScalingLazyListState()
)
}
private val playlistUiModel = PlaylistUiModel(
id = "id",
title = "Playlist name"
)
private val notDownloaded = listOf(
DownloadMediaUiModel.NotDownloaded(
id = "id",
title = "Song name",
artist = "Artist name",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.NotDownloaded(
id = "id 2",
title = "Song name 2",
artist = "Artist name 2",
artworkUri = "artworkUri"
)
)
private val notDownloadedAndDownloading = listOf(
DownloadMediaUiModel.NotDownloaded(
id = "id",
title = "Song name",
artist = "Artist name",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.Downloading(
id = "id 2",
title = "Song name 2",
progress = DownloadMediaUiModel.Progress.InProgress(78f),
size = DownloadMediaUiModel.Size.Known(sizeInBytes = 123456L),
artworkUri = "artworkUri"
)
)
private val downloadedAndDownloadingUnknown = listOf(
DownloadMediaUiModel.Downloaded(
id = "id",
title = "Song name",
artist = "Artist name",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.Downloading(
id = "id 2",
title = "Song name 2",
progress = DownloadMediaUiModel.Progress.InProgress(78f),
size = DownloadMediaUiModel.Size.Unknown,
artworkUri = "artworkUri"
)
)
private val downloadedAndDownloadingWaiting = listOf(
DownloadMediaUiModel.Downloaded(
id = "id",
title = "Song name",
artist = "Artist name",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.Downloading(
id = "id 2",
title = "Song name 2",
progress = DownloadMediaUiModel.Progress.Waiting,
size = DownloadMediaUiModel.Size.Unknown,
artworkUri = "artworkUri"
)
)
private val downloadedNotDownloaded = listOf(
DownloadMediaUiModel.Downloaded(
id = "id",
title = "Song name",
artist = "Artist name",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.NotDownloaded(
id = "id 2",
title = "Song name 2",
artist = "Artist name 2",
artworkUri = "artworkUri"
)
)
private val downloaded = listOf(
DownloadMediaUiModel.Downloaded(
id = "id",
title = "Song name",
artist = "Artist name",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.Downloaded(
id = "id 2",
title = "Song name 2",
artist = "Artist name 2",
artworkUri = "artworkUri"
)
)
| apache-2.0 | 1a43900738c396ec2bbbff4a0f4c1c9a | 32.14094 | 84 | 0.671122 | 6.077538 | false | false | false | false |
Ekito/koin | koin-projects/koin-core/src/main/kotlin/org/koin/core/context/GlobalContext.kt | 1 | 3157 | /*
* Copyright 2017-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.koin.core.context
import org.koin.core.Koin
import org.koin.core.KoinApplication
import org.koin.core.error.KoinAppAlreadyStartedException
import org.koin.core.module.Module
import org.koin.dsl.KoinAppDeclaration
/**
* Global context - current Koin Application available globally
*
* Support to help inject automatically instances once KoinApp has been started
*
* @author Arnaud Giuliani
*/
object GlobalContext : KoinContext {
private var _koin: Koin? = null
override fun get(): Koin = _koin ?: error("KoinApplication has not been started")
override fun getOrNull(): Koin? = _koin
override fun register(koinApplication: KoinApplication) {
if (_koin != null) {
throw KoinAppAlreadyStartedException("A Koin Application has already been started")
}
_koin = koinApplication.koin
}
override fun stop() = synchronized(this) {
_koin?.close()
_koin = null
}
/**
* Start a Koin Application as StandAlone
*/
fun startKoin(koinContext: KoinContext = GlobalContext,
koinApplication: KoinApplication): KoinApplication = synchronized(this) {
koinContext.register(koinApplication)
koinApplication.createEagerInstances()
return koinApplication
}
/**
* Start a Koin Application as StandAlone
*/
fun startKoin(koinContext: KoinContext = GlobalContext,
appDeclaration: KoinAppDeclaration): KoinApplication = synchronized(this) {
val koinApplication = KoinApplication.init()
koinContext.register(koinApplication)
appDeclaration(koinApplication)
koinApplication.createEagerInstances()
return koinApplication
}
/**
* Stop current StandAlone Koin application
*/
fun stopKoin() = stop()
/**
* load Koin module in global Koin context
*/
fun loadKoinModules(module: Module) = synchronized(this) {
get().loadModules(listOf(module))
}
/**
* load Koin modules in global Koin context
*/
fun loadKoinModules(modules: List<Module>) = synchronized(this) {
get().loadModules(modules)
}
/**
* unload Koin modules from global Koin context
*/
fun unloadKoinModules(module: Module) = synchronized(this) {
get().unloadModules(listOf(module))
}
/**
* unload Koin modules from global Koin context
*/
fun unloadKoinModules(modules: List<Module>) = synchronized(this) {
get().unloadModules(modules)
}
}
| apache-2.0 | 219e183f358b23b3a786c8d2268e5604 | 29.066667 | 95 | 0.681343 | 4.697917 | false | false | false | false |
SUPERCILEX/Robot-Scouter | feature/trash/src/main/java/com/supercilex/robotscouter/feature/trash/EmptyTrashDialog.kt | 1 | 1816 | package com.supercilex.robotscouter.feature.trash
import android.content.DialogInterface
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentManager
import com.supercilex.robotscouter.core.data.emptyTrash
import com.supercilex.robotscouter.core.ui.DialogFragmentBase
import com.supercilex.robotscouter.core.unsafeLazy
internal class EmptyTrashDialog : DialogFragmentBase(), DialogInterface.OnClickListener {
private val ids by unsafeLazy { requireArguments().getStringArray(IDS_KEY).orEmpty().toList() }
private val emptyAll by unsafeLazy { requireArguments().getBoolean(EMPTY_ALL_KEY) }
override fun onCreateDialog(savedInstanceState: Bundle?) = AlertDialog.Builder(requireContext())
.setTitle(R.string.trash_empty_dialog_title)
.setMessage(resources.getQuantityString(
R.plurals.trash_empty_dialog_message, ids.size, ids.size))
.setPositiveButton(R.string.trash_empty_dialog_action, this)
.setNegativeButton(android.R.string.cancel, null)
.create()
override fun onClick(dialog: DialogInterface, which: Int) {
(requireParentFragment() as TrashFragment)
.onEmptyTrashConfirmed(ids, emptyTrash(ids.takeUnless { emptyAll }))
}
companion object {
private const val TAG = "EmptyTrashDialog"
private const val IDS_KEY = "ids"
private const val EMPTY_ALL_KEY = "empty_all"
fun show(manager: FragmentManager, ids: List<String>, emptyAll: Boolean) {
require(ids.isNotEmpty())
EmptyTrashDialog().apply {
arguments = bundleOf(IDS_KEY to ids.toTypedArray(), EMPTY_ALL_KEY to emptyAll)
}.show(manager, TAG)
}
}
}
| gpl-3.0 | 6d19ea12a3829818ec8f29bf9c2bc9bc | 43.292683 | 100 | 0.707599 | 4.644501 | false | false | false | false |
beyama/winter | winter-compiler/src/main/java/io/jentz/winter/compiler/commons.kt | 1 | 3637 | package io.jentz.winter.compiler
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.asClassName
import io.jentz.winter.inject.ApplicationScope
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Singleton
const val OPTION_GENERATED_COMPONENT_PACKAGE = "winterGeneratedComponentPackage"
val GENERATED_ANNOTATION_LEGACY_INTERFACE_NAME =
ClassName("javax.annotation", "Generated")
val GENERATED_ANNOTATION_JDK9_INTERFACE_NAME =
ClassName("javax.annotation.processing", "Generated")
val SINGLETON_ANNOTATION_CLASS_NAME = Singleton::class.asClassName()
val APPLICATION_SCOPE_CLASS_NAME = ApplicationScope::class.asClassName()
val ISO8601_FORMAT = SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'", Locale.US).apply {
timeZone = TimeZone.getTimeZone("UTC")
}
// see https://kotlinlang.org/docs/reference/java-interop.html#mapped-types
val mappedTypes: Map<TypeName, TypeName> = mapOf(
ClassName("java.lang", "Object") to ClassName("kotlin", "Any"),
ClassName("java.lang", "Cloneable") to ClassName("kotlin", "Cloneable"),
ClassName("java.lang", "Comparable") to ClassName("kotlin", "Comparable"),
ClassName("java.lang", "Enum") to ClassName("kotlin", "Enum"),
ClassName("java.lang", "Annotation") to ClassName("kotlin", "Annotation"),
ClassName("java.lang", "Deprecated") to ClassName("kotlin", "Deprecated"),
ClassName("java.lang", "CharSequence") to ClassName("kotlin", "CharSequence"),
ClassName("java.lang", "String") to ClassName("kotlin", "String"),
ClassName("java.lang", "Number") to ClassName("kotlin", "Number"),
ClassName("java.lang", "Throwable") to ClassName("kotlin", "Throwable"),
ClassName("java.lang", "Byte") to ClassName("kotlin", "Byte"),
ClassName("java.lang", "Short") to ClassName("kotlin", "Short"),
ClassName("java.lang", "Integer") to ClassName("kotlin", "Int"),
ClassName("java.lang", "Long") to ClassName("kotlin", "Long"),
ClassName("java.lang", "Character") to ClassName("kotlin", "Char"),
ClassName("java.lang", "Float") to ClassName("kotlin", "Float"),
ClassName("java.lang", "Double") to ClassName("kotlin", "Double"),
ClassName("java.lang", "Boolean") to ClassName("kotlin", "Boolean"),
// collections
ClassName("java.util", "Iterator") to Iterator::class.asClassName(),
ClassName("java.lang", "Iterable") to Iterable::class.asClassName(),
ClassName("java.util", "Collection") to Collection::class.asClassName(),
ClassName("java.util", "Set") to Set::class.asClassName(),
ClassName("java.util", "List") to List::class.asClassName(),
ClassName("java.util", "ListIterator") to ListIterator::class.asClassName(),
ClassName("java.util", "Map") to Map::class.asClassName(),
ClassName("java.util", "Map", "Entry") to Map.Entry::class.asClassName()
)
val TypeName.kotlinTypeName: TypeName get() {
if (this is ParameterizedTypeName) {
val raw = rawType.kotlinTypeName
if (raw !is ClassName) return this // should never happen
return raw.parameterizedBy(typeArguments.map { it.kotlinTypeName })
}
return mappedTypes.getOrDefault(this, this)
}
val notNullAnnotations = setOf(
"org.jetbrains.annotations.NotNull",
"javax.validation.constraints.NotNull",
"edu.umd.cs.findbugs.annotations.NonNull",
"javax.annotation.Nonnull",
"lombok.NonNull",
"android.support.annotation.NonNull",
"org.eclipse.jdt.annotation.NonNull"
)
| apache-2.0 | 28bd61c47195f7edf0b0e3c375a0bb6e | 45.628205 | 82 | 0.71625 | 4.077354 | false | false | false | false |
BitPrepared/prbm-mobile | buildSrc/src/main/java/Dependecies.kt | 1 | 691 | object Versions {
const val androidGradle = "7.3.1"
const val glide = "4.8.0"
const val kotlin = "1.7.10"
const val rxjava2 = "2.2.11"
const val rxandroid2 = "2.1.1"
}
object Libs {
const val androidGradlePlugin = "com.android.tools.build:gradle:${Versions.androidGradle}"
const val kotlinGradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}"
const val rxJava2 = "io.reactivex.rxjava2:rxjava:${Versions.rxjava2}"
const val rxAndroid2 = "io.reactivex.rxjava2:rxandroid:${Versions.rxandroid2}"
const val glide = "com.github.bumptech.glide:glide:${Versions.glide}"
const val glideCompiler = "com.github.bumptech.glide:compiler:${Versions.glide}"
} | gpl-2.0 | e893db3272f8c9d8833ccd192e0c49fe | 42.25 | 95 | 0.732272 | 3.354369 | false | false | false | false |
chris-wu2015/MoneyGiftAssistant | moneyGiftAssistant/src/main/java/com/alphago/moneypacket/fragments/CommentSettingsFragment.kt | 1 | 1959 | package com.alphago.moneypacket.fragments
import android.os.Build
import android.os.Bundle
import android.preference.Preference
import android.preference.PreferenceFragment
import android.preference.PreferenceManager
import android.widget.Toast
import com.alphago.moneypacket.R
/**
* Created by Zhongyi on 2/4/16.
*/
class CommentSettingsFragment : PreferenceFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.comment_preferences)
setPrefListeners()
}
private fun setPrefListeners() {
// val listenerEnable = findPreference(getString(R.string.dont_show_again))
// listenerEnable.onPreferenceClickListener = Preference.OnPreferenceClickListener { preference->
// preference.
// true
// }
val updatePref = findPreference("pref_comment_switch")
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
updatePref.isEnabled = false
}
Toast.makeText(activity, "该功能尚处于实验中,只能自动填充感谢语,无法直接发送.", Toast.LENGTH_LONG).show()
val commentWordsPref = findPreference("pref_comment_words")
val summary = resources.getString(R.string.pref_comment_words_summary)
val value = PreferenceManager.getDefaultSharedPreferences(activity).getString("pref_comment_words", "")
if (value!!.length > 0) commentWordsPref.summary = summary + ":" + value
commentWordsPref.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { preference, o ->
val summary = resources.getString(R.string.pref_comment_words_summary)
if (o != null && o.toString().length > 0) {
preference.summary = summary + ":" + o.toString()
} else {
preference.summary = summary
}
true
}
}
}
| apache-2.0 | 9a3e55737459b135c79932f0b0d4c623 | 38 | 111 | 0.678179 | 4.507075 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/formatter/impl/utils.kt | 2 | 4783 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.formatter.impl
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.TokenType.WHITE_SPACE
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.tree.TokenSet.orSet
import org.rust.lang.core.psi.RS_OPERATORS
import org.rust.lang.core.psi.RsAttr
import org.rust.lang.core.psi.RsElementTypes.*
import org.rust.lang.core.psi.RsExpr
import org.rust.lang.core.psi.RsStmt
import org.rust.lang.core.psi.ext.RsItemElement
import org.rust.lang.core.psi.ext.RsMod
import com.intellij.psi.tree.TokenSet.create as ts
val SPECIAL_MACRO_ARGS = ts(FORMAT_MACRO_ARGUMENT, LOG_MACRO_ARGUMENT, TRY_MACRO_ARGUMENT, VEC_MACRO_ARGUMENT, ASSERT_MACRO_ARGUMENT)
val NO_SPACE_AROUND_OPS = ts(COLONCOLON, DOT, DOTDOT)
val SPACE_AROUND_OPS = TokenSet.andNot(RS_OPERATORS, NO_SPACE_AROUND_OPS)
val UNARY_OPS = ts(MINUS, MUL, EXCL, AND, ANDAND)
val PAREN_DELIMITED_BLOCKS = orSet(ts(VALUE_PARAMETER_LIST, PAREN_EXPR, TUPLE_EXPR, TUPLE_TYPE, VALUE_ARGUMENT_LIST, PAT_TUP, TUPLE_FIELDS),
SPECIAL_MACRO_ARGS)
val PAREN_LISTS = orSet(PAREN_DELIMITED_BLOCKS, ts(PAT_ENUM))
val BRACK_DELIMITED_BLOCKS = orSet(ts(ARRAY_TYPE, ARRAY_EXPR), SPECIAL_MACRO_ARGS)
val BRACK_LISTS = orSet(BRACK_DELIMITED_BLOCKS, ts(INDEX_EXPR))
val BLOCK_LIKE = ts(BLOCK, BLOCK_FIELDS, STRUCT_LITERAL_BODY, MATCH_BODY, ENUM_BODY, MEMBERS)
val BRACE_LISTS = orSet(ts(USE_GLOB_LIST), SPECIAL_MACRO_ARGS)
val BRACE_DELIMITED_BLOCKS = orSet(BLOCK_LIKE, BRACE_LISTS)
val ANGLE_DELIMITED_BLOCKS = ts(TYPE_PARAMETER_LIST, TYPE_ARGUMENT_LIST, FOR_LIFETIMES)
val ANGLE_LISTS = orSet(ANGLE_DELIMITED_BLOCKS, ts(TYPE_QUAL))
val ATTRS = ts(OUTER_ATTR, INNER_ATTR)
val MOD_ITEMS = ts(FOREIGN_MOD_ITEM, MOD_ITEM)
val DELIMITED_BLOCKS = orSet(BRACE_DELIMITED_BLOCKS, BRACK_DELIMITED_BLOCKS,
PAREN_DELIMITED_BLOCKS, ANGLE_DELIMITED_BLOCKS)
val FLAT_BRACE_BLOCKS = orSet(MOD_ITEMS, ts(PAT_STRUCT))
val TYPES = ts(ARRAY_TYPE, REF_LIKE_TYPE, FN_POINTER_TYPE, TUPLE_TYPE, BASE_TYPE, FOR_IN_TYPE)
val FN_DECLS = ts(FUNCTION, FN_POINTER_TYPE, LAMBDA_EXPR)
val ONE_LINE_ITEMS = ts(USE_ITEM, CONSTANT, MOD_DECL_ITEM, EXTERN_CRATE_ITEM, TYPE_ALIAS, INNER_ATTR)
val PsiElement.isTopLevelItem: Boolean
get() = (this is RsItemElement || this is RsAttr) && parent is RsMod
val PsiElement.isStmtOrExpr: Boolean
get() = this is RsStmt || this is RsExpr
val ASTNode.isDelimitedBlock: Boolean
get() = elementType in DELIMITED_BLOCKS
val ASTNode.isFlatBraceBlock: Boolean
get() = elementType in FLAT_BRACE_BLOCKS
/**
* A flat block is a Rust PSI element which does not denote separate PSI
* element for its _block_ part (e.g. `{...}`), for example [MOD_ITEM].
*/
val ASTNode.isFlatBlock: Boolean
get() = isFlatBraceBlock || elementType == PAT_ENUM
fun ASTNode.isBlockDelim(parent: ASTNode?): Boolean {
if (parent == null) return false
val parentType = parent.elementType
return when (elementType) {
LBRACE, RBRACE -> parentType in BRACE_DELIMITED_BLOCKS || parent.isFlatBraceBlock
LBRACK, RBRACK -> parentType in BRACK_LISTS
LPAREN, RPAREN -> parentType in PAREN_LISTS || parentType == PAT_ENUM
LT, GT -> parentType in ANGLE_LISTS
OR -> parentType == VALUE_PARAMETER_LIST && parent.treeParent?.elementType == LAMBDA_EXPR
else -> false
}
}
fun ASTNode?.isWhitespaceOrEmpty() = this == null || textLength == 0 || elementType == WHITE_SPACE
fun ASTNode.treeNonWSPrev(): ASTNode? {
var current = this.treePrev
while (current?.elementType == WHITE_SPACE) {
current = current?.treePrev
}
return current
}
fun ASTNode.treeNonWSNext(): ASTNode? {
var current = this.treeNext
while (current?.elementType == WHITE_SPACE) {
current = current?.treeNext
}
return current
}
data class CommaList(val listElement: IElementType, val openingBrace: IElementType, val closingBrace: IElementType) {
val needsSpaceBeforeClosingBrace: Boolean get() = closingBrace == RBRACE && listElement != USE_GLOB_LIST
companion object {
fun forElement(elementType: IElementType): CommaList? {
return ALL.find { it.listElement == elementType }
}
private val ALL = listOf(
CommaList(BLOCK_FIELDS, LBRACE, RBRACE),
CommaList(STRUCT_LITERAL_BODY, LBRACE, RBRACE),
CommaList(ENUM_BODY, LBRACE, RBRACE),
CommaList(USE_GLOB_LIST, LBRACE, RBRACE),
CommaList(TUPLE_FIELDS, LPAREN, RPAREN),
CommaList(VALUE_PARAMETER_LIST, LPAREN, RPAREN),
CommaList(VALUE_ARGUMENT_LIST, LPAREN, RPAREN)
)
}
}
| mit | 657adb5f043f8f704de9bf4e622808fe | 36.661417 | 140 | 0.716705 | 3.665134 | false | false | false | false |
pabiagioli/gopro-showcase | app/src/test/java/com/aajtech/mobile/goproshowcase/MagicPacket.kt | 1 | 3366 | package com.aajtech.mobile.goproshowcase
import java.io.IOException
import java.net.*
import java.util.regex.Pattern
/**
* Created by pablo.biagioli on 7/20/16.
*/
object MagicPacket {
private val TAG = "MagicPacket"
val BROADCAST = "192.168.1.255"
val PORT = 9
val SEPARATOR = ':'
@Throws(UnknownHostException::class, SocketException::class, IOException::class, IllegalArgumentException::class)
@JvmOverloads fun send(mac: String, ip: String, port: Int = PORT): String {
// validate MAC and chop into array
val hex = validateMac(mac)
// convert to base16 bytes
val macBytes = ByteArray(6)
for (i in 0..5) {
macBytes[i] = Integer.parseInt(hex[i], 16).toByte()
}
val bytes = ByteArray(102)
// fill first 6 bytes
for (i in 0..5) {
bytes[i] = 0xff.toByte()
}
// fill remaining bytes with target MAC
var i = 6
while (i < bytes.size) {
System.arraycopy(macBytes, 0, bytes, i, macBytes.size)
i += macBytes.size
}
// create socket to IP
val address = InetAddress.getByName(ip)
val packet = DatagramPacket(bytes, bytes.size, address, port)
val socket = DatagramSocket()
socket.send(packet)
socket.close()
return hex[0] + SEPARATOR + hex[1] + SEPARATOR + hex[2] + SEPARATOR + hex[3] + SEPARATOR + hex[4] + SEPARATOR + hex[5]
}
@Throws(IllegalArgumentException::class)
fun cleanMac(mac: String): String {
val hex = validateMac(mac)
var sb = StringBuffer()
var isMixedCase = false
// check for mixed case
for (i in 0..5) {
sb.append(hex[i])
}
val testMac = sb.toString()
if (testMac.toLowerCase() == testMac == false && testMac.toUpperCase() == testMac == false) {
isMixedCase = true
}
sb = StringBuffer()
for (i in 0..5) {
// convert mixed case to lower
if (isMixedCase == true) {
sb.append(hex[i].toLowerCase())
} else {
sb.append(hex[i])
}
if (i < 5) {
sb.append(SEPARATOR)
}
}
return sb.toString()
}
@Throws(IllegalArgumentException::class)
private fun validateMac(mac: String): Array<String> {
var mac = mac
// error handle semi colons
mac = mac.replace(";", ":")
// attempt to assist the user a little
var newMac = ""
if (mac.matches("([a-zA-Z0-9]){12}".toRegex())) {
// expand 12 chars into a valid mac address
for (i in 0..mac.length - 1) {
if (i > 1 && i % 2 == 0) {
newMac += ":"
}
newMac += mac[i]
}
} else {
newMac = mac
}
// regexp pattern match a valid MAC address
val pat = Pattern.compile("((([0-9a-fA-F]){2}[-:]){5}([0-9a-fA-F]){2})")
val m = pat.matcher(newMac)
if (m.find()) {
val result = m.group()
return result.split("(\\:|\\-)".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
} else {
throw IllegalArgumentException("Invalid MAC address")
}
}
} | gpl-3.0 | 05b957ebcb2e9ca267cc4e84df960186 | 28.278261 | 126 | 0.52139 | 4.045673 | false | false | false | false |
http4k/http4k | http4k-multipart/src/main/kotlin/org/http4k/core/MultipartFormBody.kt | 1 | 5337 | package org.http4k.core
import org.http4k.core.ContentType.Companion.TEXT_HTML
import org.http4k.core.MultipartFormBody.Companion.DEFAULT_DISK_THRESHOLD
import org.http4k.lens.Header.CONTENT_TYPE
import org.http4k.lens.MultipartFormField
import org.http4k.lens.MultipartFormFile
import org.http4k.multipart.DiskLocation
import org.http4k.multipart.MultipartFormBuilder
import org.http4k.multipart.MultipartFormParser
import org.http4k.multipart.Part
import org.http4k.multipart.StreamingMultipartFormParts
import java.io.ByteArrayInputStream
import java.io.Closeable
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets.UTF_8
import java.util.*
sealed class MultipartEntity : Closeable {
abstract val name: String
internal abstract fun applyTo(builder: MultipartFormBuilder): MultipartFormBuilder
data class Field(override val name: String, val value: String, val headers: Headers = emptyList()) : MultipartEntity() {
override fun close() = Unit
override fun applyTo(builder: MultipartFormBuilder) = builder.field(name, value, headers)
}
data class File(override val name: String, val file: MultipartFormFile, val headers: Headers = emptyList()) : MultipartEntity() {
override fun close() = file.content.close()
override fun applyTo(builder: MultipartFormBuilder): MultipartFormBuilder = builder.file(name, file.filename, file.contentType.value, file.content, headers)
}
}
fun HttpMessage.multipartIterator(): Iterator<MultipartEntity> {
val boundary = CONTENT_TYPE(this)?.directives?.firstOrNull()?.second ?: ""
return StreamingMultipartFormParts.parse(boundary.toByteArray(UTF_8), body.stream, UTF_8)
.asSequence()
.map {
if (it.isFormField) MultipartEntity.Field(it.fieldName!!, it.contentsAsString, it.headers.toList())
else MultipartEntity.File(it.fieldName!!, MultipartFormFile(it.fileName!!, ContentType(it.contentType!!, TEXT_HTML.directives), it.inputStream), it.headers.toList())
}.iterator()
}
/**
* Represents a Multi-part that is backed by a stream, which should be closed after handling the content. The gotchas
* which apply to StreamBody also apply here..
**/
data class MultipartFormBody private constructor(internal val formParts: List<MultipartEntity>, val boundary: String = UUID.randomUUID().toString()) : Body, Closeable {
override val length: Long? = null
constructor(boundary: String = UUID.randomUUID().toString()) : this(emptyList(), boundary)
override fun close() = formParts.forEach(MultipartEntity::close)
fun file(name: String) = files(name).firstOrNull()
fun files(name: String) = formParts.filter { it.name == name }.mapNotNull { it as? MultipartEntity.File }.map { it.file }
fun field(name: String) = fields(name).firstOrNull()
fun fields(name: String) = formParts.filter { it.name == name }.mapNotNull { it as? MultipartEntity.Field }.map { MultipartFormField(it.value, it.headers) }
fun fieldValue(name: String) = fieldValues(name).firstOrNull()
fun fieldValues(name: String) = formParts.filter { it.name == name }.mapNotNull { it as? MultipartEntity.Field }.map { it.value }
@JvmName("plus")
operator fun plus(field: Pair<String, String>) = copy(formParts = formParts + MultipartEntity.Field(field.first, field.second))
@JvmName("plusField")
operator fun plus(field: Pair<String, MultipartFormField>) = copy(formParts = formParts + MultipartEntity.Field(field.first, field.second.value, field.second.headers))
@JvmName("plusFile")
operator fun plus(field: Pair<String, MultipartFormFile>) = copy(formParts = formParts + MultipartEntity.File(field.first, field.second))
override val stream by lazy { formParts.fold(MultipartFormBuilder(boundary.toByteArray())) { memo, next -> next.applyTo(memo) }.stream() }
override val payload: ByteBuffer by lazy { stream.use { ByteBuffer.wrap(it.readBytes()) } }
override fun toString() = String(payload.array())
companion object {
const val DEFAULT_DISK_THRESHOLD = 1000 * 1024
fun from(httpMessage: HttpMessage, diskThreshold: Int = DEFAULT_DISK_THRESHOLD, diskLocation: DiskLocation = DiskLocation.Temp()): MultipartFormBody {
val boundary = CONTENT_TYPE(httpMessage)?.directives?.firstOrNull{ it.first == "boundary" }?.second ?: ""
val inputStream = httpMessage.body.run { if (stream.available() > 0) stream else ByteArrayInputStream(payload.array()) }
val form = StreamingMultipartFormParts.parse(boundary.toByteArray(UTF_8), inputStream, UTF_8)
val parts = MultipartFormParser(UTF_8, diskThreshold, diskLocation).formParts(form).map {
if (it.isFormField) MultipartEntity.Field(it.fieldName!!, it.string(diskThreshold), it.headers.toList())
else MultipartEntity.File(it.fieldName!!, MultipartFormFile(it.fileName!!, ContentType(it.contentType!!, TEXT_HTML.directives), it.newInputStream))
}
return MultipartFormBody(parts, boundary)
}
}
}
internal fun Part.string(diskThreshold: Int = DEFAULT_DISK_THRESHOLD): String = when (this) {
is Part.DiskBacked -> throw RuntimeException("Fields configured to not be greater than $diskThreshold bytes.")
is Part.InMemory -> String(bytes, encoding)
}
| apache-2.0 | ff9ab5390ac30aaa5a18695604272ea6 | 51.841584 | 177 | 0.730185 | 4.304032 | false | false | false | false |
square/moshi | moshi/src/main/java/com/squareup/moshi/MapJsonAdapter.kt | 1 | 2645 | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.squareup.moshi
import com.squareup.moshi.internal.knownNotNull
import java.lang.reflect.Type
/**
* Converts maps with string keys to JSON objects.
*
* TODO: support maps with other key types and convert to/from strings.
*/
internal class MapJsonAdapter<K, V>(moshi: Moshi, keyType: Type, valueType: Type) : JsonAdapter<Map<K, V?>>() {
private val keyAdapter: JsonAdapter<K> = moshi.adapter(keyType)
private val valueAdapter: JsonAdapter<V> = moshi.adapter(valueType)
override fun toJson(writer: JsonWriter, value: Map<K, V?>?) {
writer.beginObject()
// Never null because we wrap in nullSafe()
for ((k, v) in knownNotNull(value)) {
if (k == null) {
throw JsonDataException("Map key is null at ${writer.path}")
}
writer.promoteValueToName()
keyAdapter.toJson(writer, k)
valueAdapter.toJson(writer, v)
}
writer.endObject()
}
override fun fromJson(reader: JsonReader): Map<K, V?> {
val result = LinkedHashTreeMap<K, V?>()
reader.beginObject()
while (reader.hasNext()) {
reader.promoteNameToValue()
val name = keyAdapter.fromJson(reader) ?: throw JsonDataException("Map key is null at ${reader.path}")
val value = valueAdapter.fromJson(reader)
val replaced = result.put(name, value)
if (replaced != null) {
throw JsonDataException(
"Map key '$name' has multiple values at path ${reader.path}: $replaced and $value"
)
}
}
reader.endObject()
return result
}
override fun toString() = "JsonAdapter($keyAdapter=$valueAdapter)"
companion object Factory : JsonAdapter.Factory {
override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? {
if (annotations.isNotEmpty()) return null
val rawType = type.rawType
if (rawType != Map::class.java) return null
val keyAndValue = Types.mapKeyAndValueTypes(type, rawType)
return MapJsonAdapter<Any, Any>(moshi, keyAndValue[0], keyAndValue[1]).nullSafe()
}
}
}
| apache-2.0 | 1d9e92c99d8cdfb227c0b201b415ef90 | 35.232877 | 111 | 0.685444 | 4.088099 | false | false | false | false |
asarkar/spring | license-report-kotlin/src/main/kotlin/org/abhijitsarkar/Application.kt | 1 | 3364 | package org.abhijitsarkar
import org.abhijitsarkar.client.GitLabClient
import org.abhijitsarkar.client.GitLabProperties
import org.abhijitsarkar.domain.License
import org.abhijitsarkar.service.GradleAgent
import org.abhijitsarkar.service.JGitAgent
import org.abhijitsarkar.service.ReportParser
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.WebApplicationType
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.builder.SpringApplicationBuilder
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.ApplicationEventPublisher
import reactor.core.publisher.Flux
import reactor.core.scheduler.Schedulers
import java.time.Duration
/**
* @author Abhijit Sarkar
*/
@SpringBootApplication
@EnableConfigurationProperties(GitLabProperties::class, ApplicationProperties::class)
class Application(
val gitLabProperties: GitLabProperties,
val applicationProperties: ApplicationProperties,
val gitLabClient: GitLabClient,
val jGitAgent: JGitAgent,
val gradleAgent: GradleAgent,
val reportParser: ReportParser,
val eventPublisher: ApplicationEventPublisher
) : CommandLineRunner {
override fun run(vararg args: String): Unit {
// Immutable view
val groups: Map<String, GitLabProperties.GroupProperties> = gitLabProperties.groups
fun isNotExcluded(projectName: String, groupName: String) =
gitLabProperties
.groups[groupName]
?.excludedProjects
?.run { !containsKey(projectName) } ?: true
fun isIncluded(projectName: String, groupName: String) =
gitLabProperties
.groups[groupName]
?.includedProjects
?.run { isEmpty() || containsKey(projectName) } ?: true
Flux.fromIterable(groups.entries)
.flatMap {
gitLabClient.projects(it.toPair())
}
.filter {
val projectName = it.second.name
val groupName = it.first
isNotExcluded(projectName, groupName) && isIncluded(projectName, groupName)
}
.parallel()
.runOn(Schedulers.parallel())
.flatMap { jGitAgent.clone(it.second, gitLabProperties.groups[it.first]) }
.filter(gradleAgent::isGradleProject)
.flatMap { gradleAgent.generateLicense(it, applicationProperties.gradle.options) }
.flatMap(reportParser::parseReport)
.sequential()
.sort(compareBy({ it.first }, { it.second.valid }, { it.second.url }))
.collectMultimap(Pair<String, License>::first, Pair<String, License>::second)
.map(::LicenseGeneratedEvent)
.doOnNext { eventPublisher.publishEvent(it) }
.block(Duration.ofMinutes(applicationProperties.timeoutMinutes))
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
SpringApplicationBuilder(Application::class.java)
.web(WebApplicationType.NONE)
.run(*args)
}
}
}
| gpl-3.0 | 6881e9f8088ea9cc8a5a41e791b09a39 | 40.530864 | 98 | 0.64893 | 5.399679 | false | false | false | false |
JetBrains/anko | anko/library/static/commons/src/main/java/dialogs/Dialogs.kt | 2 | 3588 | /*
* Copyright 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.
*/
@file:Suppress("NOTHING_TO_INLINE", "unused")
package org.jetbrains.anko
import android.app.Fragment
import android.content.Context
import android.content.DialogInterface
typealias AlertBuilderFactory<D> = (Context) -> AlertBuilder<D>
inline fun <D : DialogInterface> AnkoContext<*>.alert(
noinline factory: AlertBuilderFactory<D>,
message: String,
title: String? = null,
noinline init: (AlertBuilder<D>.() -> Unit)? = null
) = ctx.alert(factory, message, title, init)
@Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.")
inline fun <D : DialogInterface> Fragment.alert(
noinline factory: AlertBuilderFactory<D>,
message: String,
title: String? = null,
noinline init: (AlertBuilder<D>.() -> Unit)? = null
) = activity.alert(factory, message, title, init)
fun <D : DialogInterface> Context.alert(
factory: AlertBuilderFactory<D>,
message: String,
title: String? = null,
init: (AlertBuilder<D>.() -> Unit)? = null
): AlertBuilder<D> {
return factory(this).apply {
if (title != null) {
this.title = title
}
this.message = message
if (init != null) init()
}
}
inline fun <D : DialogInterface> AnkoContext<*>.alert(
noinline factory: AlertBuilderFactory<D>,
message: Int,
title: Int? = null,
noinline init: (AlertBuilder<D>.() -> Unit)? = null
) = ctx.alert(factory, message, title, init)
@Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.")
inline fun <D : DialogInterface> Fragment.alert(
noinline factory: AlertBuilderFactory<D>,
message: Int,
title: Int? = null,
noinline init: (AlertBuilder<D>.() -> Unit)? = null
) = activity.alert(factory, message, title, init)
fun <D : DialogInterface> Context.alert(
factory: AlertBuilderFactory<D>,
messageResource: Int,
titleResource: Int? = null,
init: (AlertBuilder<D>.() -> Unit)? = null
): AlertBuilder<D> {
return factory(this).apply {
if (titleResource != null) {
this.titleResource = titleResource
}
this.messageResource = messageResource
if (init != null) init()
}
}
inline fun <D : DialogInterface> AnkoContext<*>.alert(
noinline factory: AlertBuilderFactory<D>,
noinline init: AlertBuilder<D>.() -> Unit
) = ctx.alert(factory, init)
@Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.")
inline fun <D : DialogInterface> Fragment.alert(
noinline factory: AlertBuilderFactory<D>,
noinline init: AlertBuilder<D>.() -> Unit
) = activity.alert(factory, init)
fun <D : DialogInterface> Context.alert(
factory: AlertBuilderFactory<D>,
init: AlertBuilder<D>.() -> Unit
): AlertBuilder<D> = factory(this).apply { init() }
| apache-2.0 | 88ad20eab75141158c0d55cc62905564 | 34.88 | 110 | 0.663601 | 4.261283 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/toilet_availability/AddToiletAvailability.kt | 1 | 1614 | package de.westnordost.streetcomplete.quests.toilet_availability
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CITIZEN
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddToiletAvailability : OsmFilterQuestType<Boolean>() {
// only for malls, big stores and rest areas because users should not need to go inside a non-public
// place to solve the quest. (Considering malls and department stores public enough)
override val elementFilter = """
nodes, ways with
(
(shop ~ mall|department_store and name)
or highway ~ services|rest_area
)
and !toilets
"""
override val commitMessage = "Add toilet availability"
override val wikiLink = "Key:toilets"
override val icon = R.drawable.ic_quest_toilets
override val questTypeAchievements = listOf(CITIZEN)
override fun getTitle(tags: Map<String, String>) =
if (tags["highway"] == "rest_area" || tags["highway"] == "services")
R.string.quest_toiletAvailability_rest_area_title
else
R.string.quest_toiletAvailability_name_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("toilets", answer.toYesNo())
}
}
| gpl-3.0 | 8eb890ffef47867bc9c7752377c792c9 | 40.384615 | 104 | 0.733581 | 4.747059 | false | false | false | false |
sealedtx/coursework-db-kotlin | app/src/main/java/coursework/kiulian/com/freerealestate/view/activities/CreateAdvActivity.kt | 1 | 19490 | package coursework.kiulian.com.freerealestate.view.activities
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Rect
import android.os.Bundle
import android.provider.MediaStore
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
import android.view.View
import android.widget.ArrayAdapter
import android.widget.TextView
import com.raizlabs.android.dbflow.kotlinextensions.*
import coursework.kiulian.com.freerealestate.*
import coursework.kiulian.com.freerealestate.R
import coursework.kiulian.com.freerealestate.model.dbmodels.*
import coursework.kiulian.com.freerealestate.view.custom.RoundedDrawable
import coursework.kiulian.com.freerealestate.view.dialogs.DatePickDialog
import coursework.kiulian.com.freerealestate.view.dialogs.ImagePickDialog
import kotlinx.android.synthetic.main.activity_create_adv.*
import org.parceler.Parcels
import java.util.*
import java.util.concurrent.ThreadLocalRandom
class CreateAdvActivity : AppCompatActivity(), ImagePickDialog.OnAvatarPickListener {
lateinit private var datePicker: DatePickDialog
private var addedDates: ArrayList<Date> = arrayListOf()
private var adv: AdvEntity? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_adv)
toolbar.title = "Create advertisement"
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
prepareViews()
adv = Parcels.unwrap<AdvEntity>(intent.extras?.getParcelable(AdvEntity::class.java.simpleName))
loadEntities()
setViews(adv)
}
private fun loadEntities() {
adv?.load()
adv?.let {
it.contacts?.load()
it.region?.load()
it.house?.load()
it.house?.facility?.load()
it.house?.price?.load()
}
}
private fun prepareViews() {
val rect = Rect(0, 0, 1, 1)
val image = Bitmap.createBitmap(rect.width(), rect.height(), Bitmap.Config.ARGB_8888)
image.eraseColor(resources.getColor(R.color.grey_400))
val drawable = RoundedDrawable(image, 15, 0, RoundedDrawable.Type.centerCrop)
adv_image.setImageDrawable(drawable)
val types = arrayOf("Single room", "Flat", "House")
val adapter_types = ArrayAdapter(this, android.R.layout.simple_spinner_item, types)
adapter_types.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner_type.adapter = adapter_types
val foods = arrayOf("Not provided", "Breakfast+Dinner", "3 times", "All inclusive")
val adapter_foods = ArrayAdapter(this, android.R.layout.simple_spinner_item, foods)
adapter_foods.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner_food.adapter = adapter_foods
val districts = arrayOf("Center", "Sleeping district", "Suburb", "Countryside")
val adapter_districts = ArrayAdapter(this, android.R.layout.simple_spinner_item, districts)
adapter_districts.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner_district.adapter = adapter_districts
val discounts = arrayOf("No discounts", "1 month+", "2 months+", "3 months+")
val adapter_discounts = ArrayAdapter(this, android.R.layout.simple_spinner_item, discounts)
adapter_discounts.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner_discount.adapter = adapter_discounts
val payments = arrayOf("Cash", "Credit card", "PayPal", "Any")
val adapter_payments = ArrayAdapter(this, android.R.layout.simple_spinner_item, payments)
adapter_payments.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner_payment.adapter = adapter_payments
house_text.setOnTouchListener { v, event ->
if (v.id == R.id.house_text && house_text.lineCount > 3) {
v.parent.requestDisallowInterceptTouchEvent(true)
when (event.action and MotionEvent.ACTION_MASK) {
MotionEvent.ACTION_UP -> v.parent.requestDisallowInterceptTouchEvent(false)
}
}
false
}
upload_btn.setOnClickListener {
ImagePickDialog(this)
}
datePicker = DatePickDialog.getInstance(addedDates)
datePicker.setOnDateRangeListener(object : DatePickDialog.OnDateRangeListener {
override fun onDateRangePicker(dates: List<Date>) {
addedDates.addAll(dates)
addDates(dates)
}
})
add_btn.setOnClickListener {
datePicker.show(supportFragmentManager, "DatePicker")
}
}
private fun setViews(adv: AdvEntity?) {
if (adv == null)
return
adv.image?.let {
adv_image.setImageBitmap(it)
}
toolbar.title = "Edit advertisement"
adv_title.setText(adv.title)
house_text.setText(adv.house.text)
house_beds.setText(adv.house.beds.toString())
house_guests.setText(adv.house.guests.toString())
house_city.setText(adv.region.city)
house_region.setText(adv.region.region)
house_address.setText(adv.house.address)
house_price.setText(adv.house.price.price.toString())
spinner_type.setSelection(when (adv.house.type) {
HouseType.SINGLE_ROOM -> 1
HouseType.FLAT -> 2
HouseType.HOUSE -> 3
else -> 0
})
spinner_food.setSelection(when (adv.house.food) {
Food.SELF -> 1
Food.PARTLY -> 2
Food.FULL -> 3
Food.UNLIMITED -> 4
else -> 0
})
spinner_district.setSelection(when (adv.house.district) {
District.CENTER -> 1
District.SLEEPING_AREA -> 2
District.SUBURB -> 3
District.COUNTRYSIDE -> 4
else -> 0
})
spinner_discount.setSelection(when (adv.house.price.discount) {
Discount.NONE -> 1
Discount.ONE_MONTH -> 2
Discount.TWO_MONTHS -> 3
Discount.THREE_MONTHS -> 4
else -> 0
})
spinner_payment.setSelection(when (adv.house.price.payment) {
Payment.CASH -> 1
Payment.CREDIT_CARD -> 2
Payment.PAYPAL -> 3
else -> 0
})
cb_pets.isChecked = adv.house.facility.pets
cb_smoking.isChecked = adv.house.facility.smoking
// dates
addDatesRange(adv.house.myDates)
datePicker.datesRanges = adv.house.myDates
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_create_adv, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_done -> {
validateInput()
}
android.R.id.home -> onBackPressed()
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
if (requestCode == ImagePickDialog.TAKE_PHOTO || requestCode == ImagePickDialog.PICK_IMAGE) {
val encodedBitmap = getBitmapFromIntent(requestCode, data)
encodedBitmap?.let {
val drawable = RoundedDrawable(it, 15, 0, RoundedDrawable.Type.centerCrop)
adv_image.setImageDrawable(drawable)
upload_btn.visibility = View.GONE
}
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
AlertDialog.Builder(this)
.setTitle("Permission needed")
.setPositiveButton(android.R.string.ok, null)
.show()
} else {
onMethodSelected(requestCode)
}
}
override fun onMethodSelected(requestCode: Int) {
if (requestPermission(requestCode, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA))) {
if (requestCode == ImagePickDialog.TAKE_PHOTO) {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, ImagePickDialog.TAKE_PHOTO)
} else if (requestCode == ImagePickDialog.PICK_IMAGE) {
val intent = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
intent.type = "image/*"
startActivityForResult(Intent.createChooser(intent, "Select File"), ImagePickDialog.PICK_IMAGE)
}
}
}
private fun validateInput() {
if (house_beds.text.toString().isEmpty()
|| house_guests.text.toString().isEmpty()
|| adv_title.text.toString().isEmpty()
|| house_city.text.toString().isEmpty()
|| house_region.text.toString().isEmpty()
|| house_address.text.toString().isEmpty()
|| house_price.text.toString().isEmpty()
|| spinner_type.selectedItemPosition < 1)
return
if (adv == null)
createAdvertisement()
else
updateAdvertisement()
}
private fun addDates(dates: List<Date>) {
val viewGroup = layoutInflater.inflate(R.layout.dates, null)
viewGroup.tag = dates
viewGroup.findViewById(R.id.close_btn).setOnClickListener {
addedDates.removeAll(viewGroup.tag as List<*>)
freedates_layout.removeView(it.parent as View)
}
val from = Calendar.getInstance()
from.time = dates[0]
val to = Calendar.getInstance()
to.time = dates[dates.size - 1]
(viewGroup.findViewById(R.id.date_arrival) as TextView)
.text = "${from?.get(Calendar.MONTH)}.${from?.get(Calendar.DAY_OF_MONTH)}.${from?.get(Calendar.YEAR)}"
(viewGroup.findViewById(R.id.date_leaving) as TextView)
.text = "${to?.get(Calendar.MONTH)}.${to?.get(Calendar.DAY_OF_MONTH)}.${to?.get(Calendar.YEAR)}"
freedates_layout.addView(viewGroup)
}
private fun addDatesRange(dateRagnges: List<DateEntity>) {
for (range in dateRagnges) {
val viewGroup = layoutInflater.inflate(R.layout.dates, null)
viewGroup.tag = range
viewGroup.findViewById(R.id.close_btn).setOnClickListener {
val date = viewGroup.tag as DateEntity
adv?.house?.myDates?.remove(date)
val deleted = date.delete()
Log.i("DELETED", "$deleted")
freedates_layout.removeView(it.parent as View)
}
val from = Calendar.getInstance()
from.time = range.start
val to = Calendar.getInstance()
to.time = range.end
(viewGroup.findViewById(R.id.date_arrival) as TextView)
.text = "${from?.get(Calendar.MONTH)}.${from?.get(Calendar.DAY_OF_MONTH)}.${from?.get(Calendar.YEAR)}"
(viewGroup.findViewById(R.id.date_leaving) as TextView)
.text = "${to?.get(Calendar.MONTH)}.${to?.get(Calendar.DAY_OF_MONTH)}.${to?.get(Calendar.YEAR)}"
freedates_layout.addView(viewGroup)
}
}
private fun getDateRanges(house: HouseEntity): ArrayList<DateEntity> {
val dateRanges: ArrayList<DateEntity> = arrayListOf()
var i = 0
while (i < addedDates.size - 1) {
val dateRange = DateEntity()
dateRange.house = house
dateRange.start = Date(addedDates[i].time)
do {
i++
val temp1 = Calendar.getInstance()
temp1.time = addedDates[i - 1]
temp1.add(Calendar.DAY_OF_MONTH, 1)
val temp2 = Calendar.getInstance()
temp2.time = addedDates[i]
if (i == addedDates.size - 1) {
dateRange.end = Date(addedDates[i].time)
dateRanges.add(dateRange)
return dateRanges
}
} while (temp1.time == temp2.time)
dateRange.end = Date(addedDates[i - 1].time)
dateRanges.add(dateRange)
}
return dateRanges
}
// TODO: replace to AdvModule
private fun updateAdvertisement() {
adv?.house?.price?.apply {
price = house_price.text.toString().toInt()
payment = when (spinner_payment.selectedItemPosition) {
1 -> Payment.CASH
2 -> Payment.CREDIT_CARD
3 -> Payment.PAYPAL
else -> Payment.ANY
}
discount = when (spinner_discount.selectedItemPosition) {
2 -> Discount.ONE_MONTH
3 -> Discount.TWO_MONTHS
4 -> Discount.THREE_MONTHS
else -> Discount.NONE
}
}
adv?.house?.price?.async()?.update()
adv?.region?.apply {
city = house_city.text.toString().trim()
region = house_region.text.toString().trim()
cityCode = ThreadLocalRandom.current().nextInt(100, 1000).toString()
}
adv?.region?.async()?.update()
adv?.house?.facility?.apply {
pets = cb_pets.isChecked
smoking = cb_smoking.isChecked
}
adv?.house?.facility?.async()?.update()
adv?.house?.apply {
type = when (spinner_type.selectedItemPosition) {
1 -> HouseType.SINGLE_ROOM
2 -> HouseType.FLAT
3 -> HouseType.HOUSE
else -> null
}
address = house_address.text.toString().trim()
text = house_text.text.toString().trim()
guests = house_guests.text.toString().toInt()
beds = house_beds.text.toString().toInt()
food = when (spinner_food.selectedItemPosition) {
2 -> Food.PARTLY
3 -> Food.FULL
4 -> Food.UNLIMITED
else -> Food.SELF
}
district = when (spinner_district.selectedItemPosition) {
1 -> District.CENTER
2 -> District.SLEEPING_AREA
3 -> District.SUBURB
4 -> District.COUNTRYSIDE
else -> District.UNKNOWN
}
val dates = getDateRanges(this)
dates.forEach { it.save() }
}
adv?.house?.async()?.update()
adv?.apply {
title = adv_title.text.toString().trim()
if (upload_btn.visibility == View.GONE)
image = (adv_image.drawable as? RoundedDrawable)?.bitmap
}
adv?.async()?.update {
//TODO: EventBus
setResult(Activity.RESULT_OK)
finish()
}
}
private fun createAdvertisement() {
val prefs = getSharedPreferences(USER_PREF, Context.MODE_PRIVATE)
val id = prefs.getInt(USER_ID, -1)
val contactsModel = select.from(ContactsEntity::class)
.where(ContactsEntity_Table.id.eq(id))
.list[0]
val priceModel = PriceEntity().apply {
price = house_price.text.toString().toInt()
payment = when (spinner_payment.selectedItemPosition) {
1 -> Payment.CASH
2 -> Payment.CREDIT_CARD
3 -> Payment.PAYPAL
else -> Payment.ANY
}
discount = when (spinner_discount.selectedItemPosition) {
2 -> Discount.ONE_MONTH
3 -> Discount.TWO_MONTHS
4 -> Discount.THREE_MONTHS
else -> Discount.NONE
}
}
priceModel.async().save {
val regionModel = RegionEntity().apply {
city = house_city.text.toString().trim()
region = house_region.text.toString().trim()
cityCode = ThreadLocalRandom.current().nextInt(100, 1000).toString()
}
regionModel.async().save {
val facilityModel = FacilityEntity().apply {
pets = cb_pets.isChecked
smoking = cb_smoking.isChecked
}
facilityModel.async().save {
val houseModel = HouseEntity().apply {
type = when (spinner_type.selectedItemPosition) {
1 -> HouseType.SINGLE_ROOM
2 -> HouseType.FLAT
3 -> HouseType.HOUSE
else -> null
}
address = house_address.text.toString().trim()
text = house_text.text.toString().trim()
guests = house_guests.text.toString().toInt()
beds = house_beds.text.toString().toInt()
food = when (spinner_food.selectedItemPosition) {
2 -> Food.PARTLY
3 -> Food.FULL
4 -> Food.UNLIMITED
else -> Food.SELF
}
district = when (spinner_district.selectedItemPosition) {
1 -> District.CENTER
2 -> District.SLEEPING_AREA
3 -> District.SUBURB
4 -> District.COUNTRYSIDE
else -> District.UNKNOWN
}
price = priceModel
facility = facilityModel
freeDates = getDateRanges(this)
}
houseModel.async().save {
val adv = AdvEntity().apply {
title = adv_title.text.toString().trim()
contacts = contactsModel
house = houseModel
createdAt = Calendar.getInstance().time
region = regionModel
if (upload_btn.visibility == View.GONE)
image = (adv_image.drawable as? RoundedDrawable)?.bitmap
}
adv.async().save {
//TODO: EventBus
setResult(Activity.RESULT_OK)
finish()
}
}
}
}
}
}
}
| bsd-2-clause | cd813b7bc43efee8c1a65698cbaeeb6b | 39.859539 | 125 | 0.565008 | 4.860349 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | example/src/test/java/org/wordpress/android/fluxc/list/InternalPagedListDataSourceTest.kt | 1 | 4134 | package org.wordpress.android.fluxc.list
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Before
import org.junit.Test
import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId
import org.wordpress.android.fluxc.model.list.datasource.InternalPagedListDataSource
import org.wordpress.android.fluxc.model.list.datasource.ListItemDataSourceInterface
import kotlin.test.assertEquals
private const val NUMBER_OF_ITEMS = 71
private const val IS_LIST_FULLY_FETCHED = false
private val testListDescriptor = TestListDescriptor()
private val testStartAndEndPosition = Pair(5, 10)
internal class InternalPagedListDataSourceTest {
private val remoteItemIds = mock<List<RemoteId>>()
private val mockIdentifiers = mock<List<TestListIdentifier>>()
private val mockItemDataSource = mock<ListItemDataSourceInterface<TestListDescriptor, TestListIdentifier, String>>()
@Before
fun setup() {
whenever(remoteItemIds.size).thenReturn(NUMBER_OF_ITEMS)
whenever(mockIdentifiers.size).thenReturn(NUMBER_OF_ITEMS)
val mockSublist = mock<List<TestListIdentifier>>()
whenever(mockIdentifiers.subList(any(), any())).thenReturn(mockSublist)
whenever(
mockItemDataSource.getItemIdentifiers(
listDescriptor = testListDescriptor,
remoteItemIds = remoteItemIds,
isListFullyFetched = IS_LIST_FULLY_FETCHED
)
).thenReturn(mockIdentifiers)
}
/**
* Tests that item identifiers are cached when a new instance of [InternalPagedListDataSource] is created.
*
* Caching the item identifiers is how we ensure that this component will provide consistent data to
* `PositionalDataSource` so it's very important that we have this test. Since we don't have access to
* `InternalPagedListDataSource.itemIdentifiers` private property, we have to test the internal implementation
* which is more likely to break. However, in this specific case, we DO want the test to break if the internal
* implementation changes.
*/
@Test
fun `init calls getItemIdentifiers`() {
createInternalPagedListDataSource(mockItemDataSource)
verify(mockItemDataSource).getItemIdentifiers(eq(testListDescriptor), any(), any())
}
@Test
fun `total size uses getItemIdentifiers' size`() {
val internalDataSource = createInternalPagedListDataSource(mockItemDataSource)
assertEquals(
NUMBER_OF_ITEMS, internalDataSource.totalSize, "InternalPagedListDataSource should not change the" +
"number of items in a list and should propagate that to its ListItemDataSourceInterface"
)
}
@Test
fun `getItemsInRange creates the correct sublist of the identifiers`() {
val internalDataSource = createInternalPagedListDataSource(mockItemDataSource)
val (startPosition, endPosition) = testStartAndEndPosition
internalDataSource.getItemsInRange(startPosition, endPosition)
verify(mockIdentifiers).subList(startPosition, endPosition)
}
@Test
fun `getItemsInRange propagates the call to getItemsAndFetchIfNecessary correctly`() {
val internalDataSource = createInternalPagedListDataSource(dataSource = mockItemDataSource)
val (startPosition, endPosition) = testStartAndEndPosition
internalDataSource.getItemsInRange(startPosition, endPosition)
verify(mockItemDataSource).getItemsAndFetchIfNecessary(eq(testListDescriptor), any())
}
private fun createInternalPagedListDataSource(
dataSource: TestListItemDataSource
): TestInternalPagedListDataSource {
return InternalPagedListDataSource(
listDescriptor = testListDescriptor,
remoteItemIds = remoteItemIds,
isListFullyFetched = IS_LIST_FULLY_FETCHED,
itemDataSource = dataSource
)
}
}
| gpl-2.0 | 84c4bbb22d112c9873a79d6cc19e7ccc | 42.0625 | 120 | 0.731737 | 5.519359 | false | true | false | false |
raatiniemi/worker | core-test/src/main/java/me/raatiniemi/worker/domain/repository/TimeIntervalInMemoryRepository.kt | 1 | 2998 | /*
* Copyright (C) 2018 Tobias Raatiniemi
*
* 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, version 2 of the License.
*
* 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 me.raatiniemi.worker.domain.repository
import me.raatiniemi.worker.domain.model.Project
import me.raatiniemi.worker.domain.model.TimeInterval
import me.raatiniemi.worker.util.Optional
import java.util.concurrent.atomic.AtomicLong
class TimeIntervalInMemoryRepository : TimeIntervalRepository {
private val incrementedId = AtomicLong()
private val timeIntervals = mutableListOf<TimeInterval>()
override fun findAll(project: Project, milliseconds: Long): List<TimeInterval> {
return timeIntervals.filter {
it.projectId == project.id && it.startInMilliseconds >= milliseconds
}
}
override fun findById(id: Long): Optional<TimeInterval> {
val timeInterval = timeIntervals.firstOrNull { it.id == id }
return Optional.ofNullable(timeInterval)
}
override fun findActiveByProjectId(projectId: Long): Optional<TimeInterval> {
val timeInterval = timeIntervals.firstOrNull { it.projectId == projectId && it.isActive }
return Optional.ofNullable(timeInterval)
}
override fun add(timeInterval: TimeInterval): Optional<TimeInterval> {
val id = incrementedId.incrementAndGet()
val value = timeInterval.copy(id = id)
timeIntervals.add(value)
return Optional.of(value)
}
override fun update(timeInterval: TimeInterval): Optional<TimeInterval> {
val existingTimeInterval = timeIntervals.firstOrNull { it.id == timeInterval.id }
?: return Optional.empty()
val index = timeIntervals.indexOf(existingTimeInterval)
timeIntervals[index] = timeInterval
return Optional.of(timeInterval)
}
override fun update(timeIntervals: List<TimeInterval>): List<TimeInterval> {
return timeIntervals.filter { existingTimeInterval(it) }
.map { update(it) }
.filter { it.isPresent }
.map { it.get() }
}
private fun existingTimeInterval(timeInterval: TimeInterval): Boolean {
val id = timeInterval.id ?: return false
return findById(id).isPresent
}
override fun remove(id: Long) {
timeIntervals.removeIf { it.id == id }
}
override fun remove(timeIntervals: List<TimeInterval>) {
timeIntervals.mapNotNull { it.id }
.forEach { remove(it) }
}
}
| gpl-2.0 | e312e03c97bd836837f7f16ee97e4305 | 34.270588 | 97 | 0.691795 | 4.789137 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.