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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ingokegel/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/java/javaModel.kt | 7 | 2469 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.java
import java.io.File
/**
* This file contains drafts of elements a new Java project model.
*/
/** Represents a set of source files written in JVM-based languages which have the same dependencies */
interface JvmSourceSet {
val mode: Mode
val sourceRoots: List<JvmSourceRoot>
val outputRoots: List<FilePointer>
val dependencies: List<JvmDependency>
enum class Mode {
/** The actual code is available as sources, they are compiled to output roots during build (corresponds to Module in old model) */
SOURCE,
/** The actual code is available in compiled form under [outputRoots], [sourceRoots] (corresponds to Library/SDK in the old model) */
COMPILED
}
}
interface JvmSourceRoot {
val type: Type
val file: FilePointer
val generated: Boolean
/** Corresponds to package prefix for source roots */
val relativeOutputPath: String?
enum class Type {
SOURCE, RESOURCES
}
}
interface FilePointer {
val url: String
val file: File
}
interface Reference<T> {
/** Not whether we need to store unresolvable references in the model, maybe there is a better way to store incorrect elements */
val resolved: T?
/** This name is used to show error message if the reference cannot be resolved */
val displayName: String
}
interface JvmDependency {
val target: Reference<JvmSourceSet>
/** Not sure about this part */
val includedAtRuntime: Boolean
val includedForCompilation: Boolean
val exported: Boolean
}
/**
* Represents a source set which contains tests. May be contain reference to a source set which contains production code which is tested here.
*/
interface JvmTestSourceSet : JvmSourceSet {
val productionSourceSet: Reference<JvmSourceSet>?
}
/**
* Qualified name (including the project name) of a source set imported from Gradle.
*/
val JvmSourceSet.gradleQualifiedName: String
get() = TODO()
/**
* Name of a manually created module provided by user.
*/
val JvmSourceSet.moduleName: String
get() = TODO()
/**
* Returns maven coordinates if the source set is actually a library imported from a Maven repository
*/
val JvmSourceSet.mavenCoordinates: String
get() = TODO()
val JvmSourceSet.annotationRoot: List<FilePointer>
get() = TODO()
val JvmSourceSet.javadocRoot: List<FilePointer>
get() = TODO()
| apache-2.0 | d986d4b74fb714793861ff996b071d35 | 26.131868 | 142 | 0.738356 | 4.339192 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-11/app-code/app/src/main/java/dev/mfazio/abl/teams/UITeam.kt | 3 | 2638 | package dev.mfazio.abl.teams
import dev.mfazio.abl.R
data class UITeam(
val team: Team,
val logoId: Int,
val primaryColorId: Int,
val secondaryColorId: Int,
val tertiaryColorId: Int
) {
val teamId = team.id
val location = team.city
val nickname = team.nickname
val teamName = "$location $nickname"
val division = team.division
companion object {
val allTeams = listOf(
UITeam(Team.Appleton, R.drawable.fi_ic_fox, R.color.appletonPrimary, R.color.appletonSecondary, R.color.appletonTertiary),
UITeam(Team.Baraboo, R.drawable.fi_ic_circus, R.color.barabooPrimary, R.color.barabooSecondary, R.color.barabooTertiary),
UITeam(Team.EauClaire, R.drawable.fi_ic_lake, R.color.eauClairePrimary, R.color.eauClaireSecondary, R.color.eauClaireTertiary),
UITeam(Team.GreenBay, R.drawable.ic_skyline_logo, R.color.greenBayPrimary, R.color.greenBaySecondary, R.color.greenBayTertiary),
UITeam(Team.LaCrosse, R.drawable.fi_ic_heart, R.color.laCrossePrimary, R.color.laCrosseSecondary, R.color.laCrosseTertiary),
UITeam(Team.LakeDelton, R.drawable.fi_ic_sea, R.color.lakeDeltonPrimary, R.color.lakeDeltonSecondary, R.color.lakeDeltonTertiary),
UITeam(Team.Madison, R.drawable.fi_ic_snow_sharp, R.color.madisonPrimary, R.color.madisonSecondary, R.color.madisonTertiary),
UITeam(Team.Milwaukee, R.drawable.mke_flag, R.color.milwaukeePrimary, R.color.milwaukeeSecondary, R.color.milwaukeeTertiary),
UITeam(Team.Pewaukee, R.drawable.fi_ic_crown, R.color.pewaukeePrimary, R.color.pewaukeeSecondary, R.color.pewaukeeTertiary),
UITeam(Team.Shawano, R.drawable.fi_ic_swallow, R.color.shawanoPrimary, R.color.shawanoSecondary, R.color.shawanoTertiary),
UITeam(Team.SpringGreen, R.drawable.fi_ic_theater, R.color.springGreenPrimary, R.color.springGreenSecondary, R.color.springGreenTertiary),
UITeam(Team.SturgeonBay, R.drawable.fi_ic_walking_stick, R.color.sturgeonBayPrimary, R.color.sturgeonBaySecondary, R.color.sturgeonBayTertiary),
UITeam(Team.Waukesha, R.drawable.fi_ic_electric_guitar, R.color.waukeshaPrimary, R.color.waukeshaSecondary, R.color.waukeshaTertiary),
UITeam(Team.WisconsinRapids, R.drawable.fi_ic_cranberry, R.color.wiRapidsPrimary, R.color.wiRapidsSecondary, R.color.wiRapidsTertiary)
)
@JvmStatic
fun fromTeamId(teamId: String?) = allTeams.firstOrNull { uiTeam -> uiTeam.teamId == teamId }
fun fromTeamIds(vararg teamIds: String) = teamIds.map { teamId -> fromTeamId(teamId) }
}
} | apache-2.0 | 2d608884f4803b14be611a4a02a11e39 | 63.365854 | 156 | 0.72555 | 3.217073 | false | false | false | false |
hzsweers/CatchUp | app/src/debug/kotlin/io/sweers/catchup/ui/debug/NetworkVarianceAdapter.kt | 1 | 1944 | /*
* Copyright (C) 2019. Zac Sweers
*
* 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 io.sweers.catchup.ui.debug
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import io.sweers.catchup.ui.BindableAdapter
internal class NetworkVarianceAdapter(context: Context) : BindableAdapter<Int>(context) {
override fun getCount(): Int {
return VALUES.size
}
override fun getItem(position: Int): Int {
return VALUES[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun newView(inflater: LayoutInflater, position: Int, container: ViewGroup): View {
return inflater.inflate(android.R.layout.simple_spinner_item, container, false)
}
override fun bindView(item: Int, position: Int, view: View) {
val tv = view.findViewById<TextView>(android.R.id.text1)
tv.text = "±$item%"
}
override fun newDropDownView(
inflater: LayoutInflater,
position: Int,
container: ViewGroup
): View {
return inflater.inflate(android.R.layout.simple_spinner_dropdown_item, container, false)
}
companion object {
private val VALUES = intArrayOf(20, 40, 60)
fun getPositionForValue(value: Int): Int {
return VALUES.indices.firstOrNull { VALUES[it] == value }
?: 1 // Default to 40% if something changes.
}
}
}
| apache-2.0 | 07cc7dd56e8f90ff63dc142146ef0b23 | 29.359375 | 93 | 0.722079 | 4.056367 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/HeadAbstractionEntityImpl.kt | 2 | 8679 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.SymbolicEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneChildOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class HeadAbstractionEntityImpl(val dataSource: HeadAbstractionEntityData) : HeadAbstractionEntity, WorkspaceEntityBase() {
companion object {
internal val CHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(HeadAbstractionEntity::class.java, CompositeBaseEntity::class.java,
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true)
val connections = listOf<ConnectionId>(
CHILD_CONNECTION_ID,
)
}
override val data: String
get() = dataSource.data
override val child: CompositeBaseEntity?
get() = snapshot.extractOneToAbstractOneChild(CHILD_CONNECTION_ID, this)
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: HeadAbstractionEntityData?) : ModifiableWorkspaceEntityBase<HeadAbstractionEntity, HeadAbstractionEntityData>(
result), HeadAbstractionEntity.Builder {
constructor() : this(HeadAbstractionEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity HeadAbstractionEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field HeadAbstractionEntity#data should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as HeadAbstractionEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.data != dataSource.data) this.data = dataSource.data
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData(true).data = value
changedProperty.add("data")
}
override var child: CompositeBaseEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneChild(CHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
CHILD_CONNECTION_ID)] as? CompositeBaseEntity
}
else {
this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? CompositeBaseEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToAbstractOneChildOfParent(CHILD_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] = value
}
changedProperty.add("child")
}
override fun getEntityClass(): Class<HeadAbstractionEntity> = HeadAbstractionEntity::class.java
}
}
class HeadAbstractionEntityData : WorkspaceEntityData.WithCalculableSymbolicId<HeadAbstractionEntity>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<HeadAbstractionEntity> {
val modifiable = HeadAbstractionEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): HeadAbstractionEntity {
return getCached(snapshot) {
val entity = HeadAbstractionEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun symbolicId(): SymbolicEntityId<*> {
return HeadAbstractionSymbolicId(data)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return HeadAbstractionEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return HeadAbstractionEntity(data, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as HeadAbstractionEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as HeadAbstractionEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 649b00de9f8913ddb1665d7bfcda9ffe | 34.863636 | 148 | 0.706994 | 5.420987 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/scriptUtils.kt | 2 | 2094 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core.script
import com.intellij.openapi.application.Application
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.idea.core.script.configuration.cache.ScriptConfigurationSnapshot
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.NotNullableUserDataProperty
import kotlin.script.experimental.api.ScriptDiagnostic
@set: org.jetbrains.annotations.TestOnly
var Application.isScriptChangesNotifierDisabled by NotNullableUserDataProperty(
Key.create("SCRIPT_CHANGES_NOTIFIER_DISABLED"),
true
)
internal val logger = Logger.getInstance("#org.jetbrains.kotlin.idea.script")
fun scriptingDebugLog(file: KtFile, message: () -> String) {
scriptingDebugLog(file.originalFile.virtualFile, message)
}
fun scriptingDebugLog(file: VirtualFile? = null, message: () -> String) {
if (logger.isDebugEnabled) {
logger.debug("[KOTLIN_SCRIPTING] ${file?.let { file.path + " "} ?: ""}" + message())
}
}
fun scriptingInfoLog(message: String) {
logger.info("[KOTLIN_SCRIPTING] $message")
}
fun scriptingWarnLog(message: String) {
logger.warn("[KOTLIN_SCRIPTING] $message")
}
fun scriptingWarnLog(message: String, throwable: Throwable?) {
logger.warn("[KOTLIN_SCRIPTING] $message", throwable)
}
fun scriptingErrorLog(message: String, throwable: Throwable?) {
logger.error("[KOTLIN_SCRIPTING] $message", throwable)
}
fun logScriptingConfigurationErrors(file: VirtualFile, snapshot: ScriptConfigurationSnapshot) {
if (snapshot.configuration == null) {
scriptingWarnLog("Script configuration for file $file was not loaded")
for (report in snapshot.reports) {
if (report.severity >= ScriptDiagnostic.Severity.WARNING) {
scriptingWarnLog(report.message, report.exception)
}
}
}
}
| apache-2.0 | 59e34e74378f1928d185889232f23668 | 35.736842 | 158 | 0.745941 | 4.264766 | false | true | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/actions/ToggleBookmarkAction.kt | 2 | 3575 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.bookmark.actions
import com.intellij.icons.AllIcons.Actions.Checked
import com.intellij.ide.bookmark.Bookmark
import com.intellij.ide.bookmark.BookmarkBundle
import com.intellij.ide.bookmark.BookmarkType
import com.intellij.ide.bookmark.ui.GroupSelectDialog
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.editor.EditorGutter
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.SystemInfo
import java.awt.event.MouseEvent
import javax.swing.SwingUtilities
fun checkMultipleSelectionAndDisableAction(event: AnActionEvent): Boolean {
if (event.contextBookmarks != null) {
event.presentation.isEnabledAndVisible = false
return true
}
return false
}
internal class ToggleBookmarkAction : Toggleable, DumbAwareAction(BookmarkBundle.messagePointer("bookmark.toggle.action.text")) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun update(event: AnActionEvent) {
if (event.contextBookmarks != null) {
event.presentation.apply {
isEnabledAndVisible = true
text = BookmarkBundle.message("bookmark.add.multiple.action.text")
}
return
}
val manager = event.bookmarksManager
val bookmark = event.contextBookmark
val type = bookmark?.let { manager?.getType(it) }
event.presentation.apply {
isEnabledAndVisible = bookmark != null
icon = when (event.place) {
ActionPlaces.TOUCHBAR_GENERAL -> {
Toggleable.setSelected(this, type != null)
Checked
}
else -> null
}
text = when {
!ActionPlaces.isPopupPlace(event.place) -> BookmarkBundle.message("bookmark.toggle.action.text")
type != null -> BookmarkBundle.message("bookmark.delete.action.text")
else -> BookmarkBundle.message("bookmark.add.action.text")
}
}
}
override fun actionPerformed(event: AnActionEvent) {
val unexpectedGutterClick = (event.inputEvent as? MouseEvent)?.run { source is EditorGutter && isUnexpected }
if (unexpectedGutterClick == true) return
val bookmarks = event.contextBookmarks
when {
bookmarks != null -> addMultipleBookmarks(event, bookmarks)
else -> addSingleBookmark(event)
}
}
private fun addSingleBookmark(event: AnActionEvent) {
val manager = event.bookmarksManager ?: return
val bookmark = event.contextBookmark ?: return
val type = manager.getType(bookmark) ?: BookmarkType.DEFAULT
manager.toggle(bookmark, type)
val selectedText = event.getData(CommonDataKeys.EDITOR)?.selectionModel?.selectedText
if (!selectedText.isNullOrBlank()) {
manager.getGroups(bookmark).forEach { group -> group.setDescription(bookmark, selectedText) }
}
}
private fun addMultipleBookmarks(event: AnActionEvent, bookmarks: List<Bookmark>) {
val manager = event.bookmarksManager ?: return
val group = GroupSelectDialog(event.project, null, manager, manager.groups)
.showAndGetGroup(false)
?: return
bookmarks.forEach { group.add(it, BookmarkType.DEFAULT) }
}
private val MouseEvent.isUnexpected // see MouseEvent.isUnexpected in LineBookmarkProvider
get() = !SwingUtilities.isLeftMouseButton(this) || isPopupTrigger || if (SystemInfo.isMac) !isMetaDown else !isControlDown
init {
isEnabledInModalContext = true
}
}
| apache-2.0 | d84a61e767ee1861b79924c8332e71bf | 37.44086 | 158 | 0.728112 | 4.703947 | false | false | false | false |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/utilities/ArtifactoryUtilities.kt | 1 | 2295 | package org.roylance.yaclib.core.utilities
import org.roylance.yaclib.YaclibModel
object ArtifactoryUtilities {
const val UploadScriptName = "upload.sh"
const val UploadWheelScriptName = "uploadWheel.sh"
fun buildUploadWheelScript(directory: String, dependency: YaclibModel.Dependency): String {
val actualUrl = JavaUtilities.buildRepositoryUrl(dependency.pipRepository)
val wheelName = PythonUtilities.buildWheelFileName(dependency)
val initialTemplate = """#!/usr/bin/env bash
if [ -z "$${JavaUtilities.ArtifactoryUserName}" ]; then
${InitUtilities.Curl} -u -X PUT "$actualUrl/${PythonUtilities.buildWheelUrl(
dependency)}" -T $directory/$wheelName
else
${InitUtilities.Curl} -u $${JavaUtilities.ArtifactoryUserName}:$${JavaUtilities.ArtifactoryPasswordName} -X PUT "$actualUrl/${PythonUtilities.buildWheelUrl(
dependency)}" -T $directory/$wheelName
fi
"""
return initialTemplate
}
fun buildUploadTarGzScript(directory: String,
dependency: YaclibModel.Dependency): String {
val actualUrl = JavaUtilities.buildRepositoryUrl(dependency.npmRepository)
val tarFileName = buildTarFileName(dependency)
val initialTemplate = """#!/usr/bin/env bash
if [ -z "$${JavaUtilities.ArtifactoryUserName}" ]; then
${InitUtilities.Curl} -u -X PUT "$actualUrl/${buildTarUrl(
dependency)}" -T $directory/$tarFileName
else
${InitUtilities.Curl} -u $${JavaUtilities.ArtifactoryUserName}:$${JavaUtilities.ArtifactoryPasswordName} -X PUT "$actualUrl/${buildTarUrl(
dependency)}" -T $directory/$tarFileName
fi
"""
return initialTemplate
}
fun buildTarFileName(dependency: YaclibModel.Dependency): String {
return "${dependency.group}.${dependency.name}.${dependency.majorVersion}.${dependency.minorVersion}.tar.gz"
}
fun buildTarUrl(dependency: YaclibModel.Dependency): String {
return buildUrlName(dependency) + ".tar.gz"
}
fun replacePeriodWithForwardSlash(item: String): String {
val newGroup = item.replace(".", "/")
return newGroup
}
private fun buildUrlName(dependency: YaclibModel.Dependency): String {
val newGroup = replacePeriodWithForwardSlash(dependency.group)
return "$newGroup/${dependency.name}/${dependency.majorVersion}.${dependency.minorVersion}"
}
} | mit | a5ad126596b40caa0bd972718ac15099 | 36.639344 | 160 | 0.739869 | 4.535573 | false | false | false | false |
jovr/imgui | core/src/main/kotlin/imgui/classes/ListClipper.kt | 2 | 8905 | package imgui.classes
import glm_.i
import glm_.max
import imgui.ImGui
import imgui.api.g
/** Helper: Manually clip large list of items.
* If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse
* clipping based on visibility to save yourself from processing those items at all.
* The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we
* have skipped.
* (Dear ImGui already clip items based on their bounds but it needs to measure text size to do so, whereas manual
* coarse clipping before submission makes this cost and your own data fetching/submission cost almost null)
* ImGuiListClipper clipper;
* clipper.Begin(1000); // We have 1000 elements, evenly spaced.
* while (clipper.Step())
* for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
* ImGui::Text("line number %d", i);
* Generally what happens is:
* - Clipper lets you process the first element (DisplayStart = 0, DisplayEnd = 1) regardless of it being visible or not.
* - User code submit one element.
* - Clipper can measure the height of the first element
* - Clipper calculate the actual range of elements to display based on the current clipping rectangle, position the cursor before the first visible element.
* - User code submit visible elements. */
class ListClipper {
var displayStart = 0
var displayEnd = 0
val display
get() = displayStart until displayEnd
// [Internal]
var itemsCount = -1
var stepNo = 0
var itemsFrozen = 0
var itemsHeight = 0f
var startPosY = 0f
fun dispose() = assert(itemsCount == -1) { "Forgot to call End(), or to Step() until false?" }
/** Automatically called by constructor if you passed 'items_count' or by Step() in Step 1.
* Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
* Use case B: Begin() called from constructor with items_height>0
* FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still
* support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
*/
fun begin(itemsCount: Int = -1, itemsHeight: Float = -1f) {
val window = g.currentWindow!!
g.currentTable?.let { table ->
if (table.isInsideRow)
table.endRow()
}
startPosY = window.dc.cursorPos.y
this.itemsHeight = itemsHeight
this.itemsCount = itemsCount
itemsFrozen = 0
stepNo = 0
displayStart = -1
displayEnd = 0
}
/** Automatically called on the last call of Step() that returns false. */
fun end() {
if (itemsCount < 0) // Already ended
return
// In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
if (itemsCount < Int.MAX_VALUE && displayStart >= 0)
setCursorPosYAndSetupForPrevLine(startPosY + (itemsCount - itemsFrozen) * itemsHeight, itemsHeight)
itemsCount = -1
stepNo = 3
}
/** Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those
* items. */
fun step(): Boolean {
val window = g.currentWindow!!
val table = g.currentTable
if (table != null && table.isInsideRow)
table.endRow()
// Reached end of list
if (itemsCount == 0 || skipItemForListClipping) {
end()
return false
}
// Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
if (stepNo == 0) {
// While we are in frozen row state, keep displaying items one by one, unclipped
// FIXME: Could be stored as a table-agnostic state.
if (table != null && !table.isUnfrozenRows) {
displayStart = itemsFrozen
displayEnd = itemsFrozen + 1
itemsFrozen++
return true
}
startPosY = window.dc.cursorPos.y
if (itemsHeight <= 0f) {
// Submit the first item so we can measure its height (generally it is 0..1)
displayStart = itemsFrozen
displayEnd = itemsFrozen + 1
stepNo = 1
return true
}
// Already has item height (given by user in Begin): skip to calculating step
displayStart = displayEnd
stepNo = 2
}
// Step 1: the clipper infer height from first element
if (stepNo == 1) {
assert(itemsHeight <= 0f)
if (table != null) {
val posY1 = table.rowPosY1 // Using this instead of StartPosY to handle clipper straddling the frozen row
val posY2 = table.rowPosY2 // Using this instead of CursorPos.y to take account of tallest cell.
itemsHeight = posY2 - posY1
window.dc.cursorPos.y = posY2
} else
itemsHeight = window.dc.cursorPos.y - startPosY
assert(itemsHeight > 0f) { "Unable to calculate item height! First item hasn't moved the cursor vertically!" }
stepNo = 2
}
// Reached end of list
if (displayEnd >= itemsCount) {
end()
return false
}
// Step 2: calculate the actual range of elements to display, and position the cursor before the first element
if (stepNo == 2) {
assert(itemsHeight > 0f)
val alreadySubmitted = displayEnd
ImGui.calcListClipping(itemsCount - alreadySubmitted, itemsHeight)
displayStart += alreadySubmitted
displayEnd += alreadySubmitted
// Seek cursor
if (displayStart > alreadySubmitted)
setCursorPosYAndSetupForPrevLine(startPosY + (displayStart - itemsFrozen) * itemsHeight, itemsHeight)
stepNo = 3
return true
}
// Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
// Advance the cursor to the end of the list and then returns 'false' to end the loop.
if (stepNo == 3) {
// Seek cursor
if (itemsCount < Int.MAX_VALUE)
setCursorPosYAndSetupForPrevLine(startPosY + (itemsCount - itemsFrozen) * itemsHeight, itemsHeight) // advance cursor
itemsCount = -1
return false
}
error("game over")
}
companion object {
fun setCursorPosYAndSetupForPrevLine(posY: Float, lineHeight: Float) {
// Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
// FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
// The clipper should probably have a 4th step to display the last item in a regular manner.
val window = g.currentWindow!!
val offY = posY - window.dc.cursorPos.y
window.dc.cursorPos.y = posY
window.dc.cursorMaxPos.y = window.dc.cursorMaxPos.y max posY
window.dc.cursorPosPrevLine.y = window.dc.cursorPos.y - lineHeight // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
window.dc.prevLineSize.y = lineHeight - g.style.itemSpacing.y // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
window.dc.currentColumns?.let { columns ->
columns.lineMinY = window.dc.cursorPos.y // Setting this so that cell Y position are set properly
}
g.currentTable?.let { table ->
if (table.isInsideRow)
table.endRow()
table.rowPosY2 = window.dc.cursorPos.y
val rowIncrease = ((offY / lineHeight) + 0.5f).i
//table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
table.rowBgColorCounter += rowIncrease
}
}
}
}
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
val skipItemForListClipping: Boolean
get() = g.currentTable?.hostSkipItems ?: g.currentWindow!!.skipItems | mit | a4efac7c976b4b1fdf7f3fb63fbb3bb8 | 43.308458 | 256 | 0.62347 | 4.664746 | false | false | false | false |
Scavi/BrainSqueeze | src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day3TobogganTrajectory.kt | 1 | 792 | package com.scavi.brainsqueeze.adventofcode
class Day3TobogganTrajectory {
private val TREE = '#'
fun solve(map: List<String>, slopes: Array<Pair<Int, Int>>): Long {
val results = mutableListOf<Long>()
for (slope in slopes) {
var x = 0
var treeCount = 0L
for (i in map.indices step slope.second) {
var row = map[i]
// treeCount = if (row[x] == TREE) treeCount + 1 else treeCount
if (row[x] == TREE) {
treeCount += 1
}
x = (x + slope.first) % row.length
}
results.add(treeCount)
}
// [57, 252, 64, 66, 43]
// [252, 75, ...]
return results.reduce { acc, i -> acc * i }
}
}
| apache-2.0 | b9e170b402c2eb0dbce7ae00e76d6c89 | 32 | 79 | 0.472222 | 3.96 | false | false | false | false |
senyuyuan/Gluttony | gluttony/src/main/java/dao/yuan/sen/gluttony/sqlite_module/operator/sqlite_find.kt | 1 | 2393 | package dao.yuan.sen.gluttony.sqlite_module.operator
import dao.yuan.sen.gluttony.Gluttony
import dao.yuan.sen.gluttony.sqlite_module.annotation.PrimaryKey
import dao.yuan.sen.gluttony.sqlite_module.condition
import dao.yuan.sen.gluttony.sqlite_module.parser.classParser
import org.jetbrains.anko.db.SelectQueryBuilder
import org.jetbrains.anko.db.select
import kotlin.reflect.declaredMemberProperties
/**
* Created by Administrator on 2016/11/28.
*/
/**
* 根据 主键 查询数据
* */
inline fun <reified T : Any> T.findOneByKey(primaryKey: Any): T? {
val mClass = this.javaClass.kotlin
val name = "${mClass.simpleName}"
var propertyName: String? = null
mClass.declaredMemberProperties.forEach {
if (it.annotations.map {
it.annotationClass
}.contains(PrimaryKey::class)) propertyName = it.name
}
if (propertyName == null) throw Exception("$name 类型没有设置PrimaryKey")
return Gluttony.database.use {
tryDo {
select(name).apply {
limit(1)
condition { propertyName!! equalsData primaryKey }
}.parseOpt(dao.yuan.sen.gluttony.sqlite_module.parser.classParser<T>())
}.let {
when (it) {
null, "no such table" -> null
is T -> it
else -> null
}
}
}
}
inline fun <reified T : Any> T.findOne(crossinline functor: SelectQueryBuilder.() -> Unit): T? {
val name = "${this.javaClass.kotlin.simpleName}"
return Gluttony.database.use {
tryDo {
select(name).apply {
limit(1)
functor()
}.parseOpt(classParser<T>())
}.let {
when (it) {
null, "no such table" -> null
is T -> it
else -> null
}
}
}
}
inline fun <reified T : Any> T.findAll(crossinline functor: SelectQueryBuilder.() -> Unit): List<T> {
val name = "${this.javaClass.kotlin.simpleName}"
return Gluttony.database.use {
tryDo {
select(name).apply {
functor()
}.parseList(classParser<T>())
}.let {
when (it) {
null, "no such table" -> emptyList()
is List<*> -> it as List<T>
else -> emptyList()
}
}
}
}
| apache-2.0 | 353788315eade076266270208cd3cd11 | 27.493976 | 101 | 0.562368 | 4.245961 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/editorconfig/src/org/editorconfig/language/codeinsight/actions/CreateEditorConfigFileAction.kt | 11 | 1439 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.codeinsight.actions
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.CreateInDirectoryActionBase
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.application.runWriteAction
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import org.editorconfig.language.filetype.EditorConfigFileConstants
import org.editorconfig.language.messages.EditorConfigBundle
class CreateEditorConfigFileAction : CreateInDirectoryActionBase(
EditorConfigBundle.get("create.file.title"),
EditorConfigBundle.get("create.file.description"),
AllIcons.Nodes.Editorconfig
) {
@Suppress("UsePropertyAccessSyntax")
override fun actionPerformed(event: AnActionEvent) {
val view = event.getData(LangDataKeys.IDE_VIEW) ?: return
val directory = view.getOrChooseDirectory() ?: return
val file = createOrFindEditorConfig(directory)
view.selectElement(file)
}
private fun createOrFindEditorConfig(directory: PsiDirectory): PsiFile {
val name = EditorConfigFileConstants.FILE_NAME
val existing = directory.findFile(name)
if (existing != null) return existing
return runWriteAction { directory.createFile(".editorconfig") }
}
}
| apache-2.0 | 1f47e0fa3de1656da61882aa5e79fa22 | 42.606061 | 140 | 0.806115 | 4.733553 | false | true | false | false |
dahlstrom-g/intellij-community | platform/indexing-impl/src/com/intellij/psi/impl/search/helper.kt | 8 | 11725 | // 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.psi.impl.search
import com.intellij.model.search.SearchParameters
import com.intellij.model.search.Searcher
import com.intellij.model.search.impl.*
import com.intellij.openapi.progress.*
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ClassExtension
import com.intellij.openapi.util.Computable
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.SearchSession
import com.intellij.util.Processor
import com.intellij.util.Query
import com.intellij.util.SmartList
import com.intellij.util.text.StringSearcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import org.jetbrains.annotations.ApiStatus.Internal
import java.util.*
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.set
private val searchersExtension = ClassExtension<Searcher<*, *>>("com.intellij.searcher")
@Suppress("UNCHECKED_CAST")
internal fun <R : Any> searchers(parameters: SearchParameters<R>): List<Searcher<SearchParameters<R>, R>> {
return searchersExtension.forKey(parameters.javaClass) as List<Searcher<SearchParameters<R>, R>>
}
internal val indicatorOrEmpty: ProgressIndicator
get() = EmptyProgressIndicator.notNullize(ProgressIndicatorProvider.getGlobalProgressIndicator())
fun <R> runSearch(cs: CoroutineScope, project: Project, query: Query<R>): ReceiveChannel<R> {
@Suppress("EXPERIMENTAL_API_USAGE")
return cs.produce(capacity = Channel.UNLIMITED) {
runUnderIndicator {
runSearch(project, query, Processor {
require(channel.trySend(it).isSuccess)
true
})
}
}
}
@Internal
fun <R> runSearch(project: Project, query: Query<out R>, processor: Processor<in R>): Boolean {
val progress = indicatorOrEmpty
var currentQueries: Collection<Query<out R>> = listOf(query)
while (currentQueries.isNotEmpty()) {
progress.checkCanceled()
val layer = buildLayer(progress, project, currentQueries)
when (val layerResult = layer.runLayer(processor)) {
is LayerResult.Ok -> currentQueries = layerResult.subqueries
is LayerResult.Stop -> return false
}
}
return true
}
private fun <R> buildLayer(progress: ProgressIndicator, project: Project, queries: Collection<Query<out R>>): Layer<out R> {
val queue: Queue<Query<out R>> = ArrayDeque()
queue.addAll(queries)
val queryRequests = SmartList<QueryRequest<*, R>>()
val wordRequests = SmartList<WordRequest<R>>()
while (queue.isNotEmpty()) {
progress.checkCanceled()
val query: Query<out R> = queue.remove()
val primitives: Requests<R> = decompose(query)
queryRequests.addAll(primitives.queryRequests)
wordRequests.addAll(primitives.wordRequests)
for (parametersRequest in primitives.parametersRequests) {
progress.checkCanceled()
handleParamRequest(progress, parametersRequest) {
queue.offer(it)
}
}
}
return Layer(project, progress, queryRequests, wordRequests)
}
private fun <B, R> handleParamRequest(progress: ProgressIndicator,
request: ParametersRequest<B, R>,
queue: (Query<out R>) -> Unit) {
val searchRequests: Collection<Query<out B>> = collectSearchRequests(request.params)
for (query: Query<out B> in searchRequests) {
progress.checkCanceled()
queue(XQuery(query, request.transformation))
}
}
private fun <R : Any> collectSearchRequests(parameters: SearchParameters<R>): Collection<Query<out R>> {
return DumbService.getInstance(parameters.project).runReadActionInSmartMode(Computable {
if (parameters.areValid()) {
doCollectSearchRequests(parameters)
}
else {
emptyList()
}
})
}
private fun <R : Any> doCollectSearchRequests(parameters: SearchParameters<R>): Collection<Query<out R>> {
val queries = ArrayList<Query<out R>>()
queries.add(SearchersQuery(parameters))
val searchers = searchers(parameters)
for (searcher: Searcher<SearchParameters<R>, R> in searchers) {
ProgressManager.checkCanceled()
queries += searcher.collectSearchRequests(parameters)
}
return queries
}
private sealed class LayerResult<out T> {
object Stop : LayerResult<Nothing>()
class Ok<T>(val subqueries: Collection<Query<out T>>) : LayerResult<T>()
}
private class Layer<T>(
private val project: Project,
private val progress: ProgressIndicator,
private val queryRequests: Collection<QueryRequest<*, T>>,
private val wordRequests: Collection<WordRequest<T>>
) {
private val myHelper = PsiSearchHelper.getInstance(project) as PsiSearchHelperImpl
fun runLayer(processor: Processor<in T>): LayerResult<T> {
val subQueries = Collections.synchronizedList(ArrayList<Query<out T>>())
val xProcessor = Processor<XResult<T>> { result ->
when (result) {
is ValueResult -> processor.process(result.value)
is QueryResult -> {
subQueries.add(result.query)
true
}
}
}
if (!processQueryRequests(progress, queryRequests, xProcessor)) {
return LayerResult.Stop
}
if (!processWordRequests(xProcessor)) {
return LayerResult.Stop
}
return LayerResult.Ok(subQueries)
}
private fun processWordRequests(processor: Processor<in XResult<T>>): Boolean {
if (wordRequests.isEmpty()) {
return true
}
val allRequests: Collection<RequestAndProcessors> = distributeWordRequests(processor)
val globals = SmartList<RequestAndProcessors>()
val locals = SmartList<RequestAndProcessors>()
for (requestAndProcessor: RequestAndProcessors in allRequests) {
if (requestAndProcessor.request.searchScope is LocalSearchScope) {
locals += requestAndProcessor
}
else {
globals += requestAndProcessor
}
}
return processGlobalRequests(globals)
&& processLocalRequests(locals)
}
private fun distributeWordRequests(processor: Processor<in XResult<T>>): Collection<RequestAndProcessors> {
val theMap = LinkedHashMap<
WordRequestInfo,
Pair<
MutableCollection<OccurrenceProcessor>,
MutableMap<LanguageInfo, MutableCollection<OccurrenceProcessor>>
>
>()
for (wordRequest: WordRequest<T> in wordRequests) {
progress.checkCanceled()
val occurrenceProcessor: OccurrenceProcessor = wordRequest.occurrenceProcessor(processor)
val byRequest = theMap.getOrPut(wordRequest.searchWordRequest) {
Pair(SmartList(), LinkedHashMap())
}
val injectionInfo = wordRequest.injectionInfo
if (injectionInfo == InjectionInfo.NoInjection || injectionInfo == InjectionInfo.IncludeInjections) {
byRequest.first.add(occurrenceProcessor)
}
if (injectionInfo is InjectionInfo.InInjection || injectionInfo == InjectionInfo.IncludeInjections) {
val languageInfo: LanguageInfo = if (injectionInfo is InjectionInfo.InInjection) {
injectionInfo.languageInfo
}
else {
LanguageInfo.NoLanguage
}
byRequest.second.getOrPut(languageInfo) { SmartList() }.add(occurrenceProcessor)
}
}
return theMap.map { (wordRequest: WordRequestInfo, byRequest) ->
progress.checkCanceled()
val (hostProcessors, injectionProcessors) = byRequest
RequestAndProcessors(wordRequest, RequestProcessors(hostProcessors, injectionProcessors))
}
}
private fun processGlobalRequests(globals: Collection<RequestAndProcessors>): Boolean {
if (globals.isEmpty()) {
return true
}
else if (globals.size == 1) {
return processSingleRequest(globals.first())
}
val globalsIds: Map<PsiSearchHelperImpl.TextIndexQuery, List<WordRequestInfo>> = globals.groupBy(
{ (request: WordRequestInfo, _) -> PsiSearchHelperImpl.TextIndexQuery.fromWord(request.word, request.isCaseSensitive, null) },
{ (request: WordRequestInfo, _) -> progress.checkCanceled(); request }
)
return myHelper.processGlobalRequests(globalsIds, progress, scopeProcessors(globals))
}
private fun scopeProcessors(globals: Collection<RequestAndProcessors>): Map<WordRequestInfo, Processor<in PsiElement>> {
val result = HashMap<WordRequestInfo, Processor<in PsiElement>>()
for (requestAndProcessors: RequestAndProcessors in globals) {
progress.checkCanceled()
result[requestAndProcessors.request] = scopeProcessor(requestAndProcessors)
}
return result
}
private fun scopeProcessor(requestAndProcessors: RequestAndProcessors): Processor<in PsiElement> {
val (request: WordRequestInfo, processors: RequestProcessors) = requestAndProcessors
val searcher = StringSearcher(request.word, request.isCaseSensitive, true, false)
val adapted = MyBulkOccurrenceProcessor(project, processors)
return PsiSearchHelperImpl.localProcessor(searcher, adapted)
}
private fun processLocalRequests(locals: Collection<RequestAndProcessors>): Boolean {
if (locals.isEmpty()) {
return true
}
for (requestAndProcessors: RequestAndProcessors in locals) {
progress.checkCanceled()
if (!processSingleRequest(requestAndProcessors)) return false
}
return true
}
private fun processSingleRequest(requestAndProcessors: RequestAndProcessors): Boolean {
val (request: WordRequestInfo, processors: RequestProcessors) = requestAndProcessors
val options = EnumSet.of(PsiSearchHelperImpl.Options.PROCESS_ONLY_JAVA_IDENTIFIERS_IF_POSSIBLE)
if (request.isCaseSensitive) options.add(PsiSearchHelperImpl.Options.CASE_SENSITIVE_SEARCH)
return myHelper.bulkProcessElementsWithWord(
request.searchScope,
request.word,
request.searchContext,
options,
request.containerName,
SearchSession(),
MyBulkOccurrenceProcessor(project, processors)
)
}
}
private fun <R> processQueryRequests(progress: ProgressIndicator,
requests: Collection<QueryRequest<*, R>>,
processor: Processor<in XResult<R>>): Boolean {
if (requests.isEmpty()) {
return true
}
val map: Map<Query<*>, List<XTransformation<*, R>>> = requests.groupBy({ it.query }, { it.transformation })
for ((query: Query<*>, transforms: List<XTransformation<*, R>>) in map.iterator()) {
progress.checkCanceled()
@Suppress("UNCHECKED_CAST")
if (!runQueryRequest(query as Query<Any>, transforms as Collection<XTransformation<Any, R>>, processor)) {
return false
}
}
return true
}
private fun <B, R> runQueryRequest(query: Query<out B>,
transformations: Collection<Transformation<B, R>>,
processor: Processor<in R>): Boolean {
return query.forEach(fun(baseValue: B): Boolean {
for (transformation: Transformation<B, R> in transformations) {
for (resultValue: R in transformation(baseValue)) {
if (!processor.process(resultValue)) {
return false
}
}
}
return true
})
}
private data class RequestAndProcessors(
val request: WordRequestInfo,
val processors: RequestProcessors
)
internal class RequestProcessors(
val hostProcessors: Collection<OccurrenceProcessor>,
val injectionProcessors: Map<LanguageInfo, Collection<OccurrenceProcessor>>
)
| apache-2.0 | d06d9edd02a8fce98962413178cf4cc3 | 36.580128 | 158 | 0.719659 | 4.813218 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/tooltip/receipt/paymentmethods/FirstReceiptUsePaymentMethodsQuestionTooltipController.kt | 2 | 6294 | package co.smartreceipts.android.tooltip.receipt.paymentmethods
import android.content.Context
import androidx.annotation.AnyThread
import androidx.annotation.UiThread
import co.smartreceipts.analytics.Analytics
import co.smartreceipts.analytics.events.Events
import co.smartreceipts.analytics.log.Logger
import co.smartreceipts.android.R
import co.smartreceipts.android.columns.ordering.CsvColumnsOrderer
import co.smartreceipts.android.columns.ordering.PdfColumnsOrderer
import co.smartreceipts.android.model.impl.columns.receipts.ReceiptColumnDefinitions
import co.smartreceipts.android.settings.UserPreferenceManager
import co.smartreceipts.android.settings.catalog.UserPreference
import co.smartreceipts.android.tooltip.TooltipController
import co.smartreceipts.android.tooltip.TooltipView
import co.smartreceipts.android.tooltip.model.TooltipInteraction
import co.smartreceipts.android.tooltip.model.TooltipMetadata
import co.smartreceipts.android.tooltip.model.TooltipType
import co.smartreceipts.android.tooltip.receipt.FirstReceiptQuestionsUserInteractionStore
import co.smartreceipts.android.utils.rx.RxSchedulers
import co.smartreceipts.core.di.scopes.FragmentScope
import com.hadisatrio.optional.Optional
import io.reactivex.Completable
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.functions.Consumer
import javax.inject.Inject
import javax.inject.Named
/**
* An implementation of the [TooltipController] contract, which presents a question to our users
* about if they wish to enable the payment method tracking field (as this is not otherwise obvious
* to new users, since it is hidden in the settings menu).
*/
@FragmentScope
class FirstReceiptUsePaymentMethodsQuestionTooltipController @Inject constructor(private val context: Context,
private val tooltipView: TooltipView,
private val store: FirstReceiptQuestionsUserInteractionStore,
private val userPreferenceManager: UserPreferenceManager,
private val pdfColumnsOrderer: PdfColumnsOrderer,
private val csvColumnsOrderer: CsvColumnsOrderer,
private val analytics: Analytics,
@Named(RxSchedulers.IO) private val scheduler: Scheduler) : TooltipController {
@UiThread
override fun shouldDisplayTooltip(): Single<Optional<TooltipMetadata>> {
return store.hasUserInteractionWithPaymentMethodsQuestionOccurred()
.subscribeOn(scheduler)
.map { hasUserInteractionOccurred ->
if (hasUserInteractionOccurred) {
Logger.debug(this, "This user has interacted with the payment methods tracking question tooltip before. Ignoring.")
return@map Optional.absent<TooltipMetadata>()
} else {
Logger.debug(this, "The user has not seen the payment methods tracking question before. Displaying...")
return@map Optional.of(newTooltipMetadata())
}
}
}
@AnyThread
override fun handleTooltipInteraction(interaction: TooltipInteraction): Completable {
return Single.just(interaction)
.subscribeOn(scheduler)
.doOnSuccess {
Logger.info(this, "User interacted with the payment methods question: {}", interaction)
}
.flatMapCompletable {
when (interaction) {
TooltipInteraction.YesButtonClick -> {
Completable.fromAction {
userPreferenceManager[UserPreference.Receipts.UsePaymentMethods] = true
store.setInteractionWithPaymentMethodsQuestionHasOccurred(true)
analytics.record(Events.Informational.ClickedPaymentMethodsQuestionTipYes)
}
.andThen(pdfColumnsOrderer.insertColumnAfter(ReceiptColumnDefinitions.ActualDefinition.PAYMENT_METHOD, ReceiptColumnDefinitions.ActualDefinition.CATEGORY_CODE))
.andThen(csvColumnsOrderer.insertColumnAfter(ReceiptColumnDefinitions.ActualDefinition.PAYMENT_METHOD, ReceiptColumnDefinitions.ActualDefinition.CATEGORY_CODE))
}
TooltipInteraction.NoButtonClick -> Completable.fromAction {
userPreferenceManager[UserPreference.Receipts.UsePaymentMethods] = false
store.setInteractionWithPaymentMethodsQuestionHasOccurred(true)
analytics.record(Events.Informational.ClickedPaymentMethodsQuestionTipNo)
}
TooltipInteraction.CloseCancelButtonClick -> Completable.fromAction {
store.setInteractionWithPaymentMethodsQuestionHasOccurred(true)
}
else -> Completable.complete()
}
}
.doOnError {
Logger.warn(this, "Failed to handle tooltip interaction for the payment methods question. Failing silently")
}
.onErrorComplete()
}
@UiThread
override fun consumeTooltipInteraction(): Consumer<TooltipInteraction> {
return Consumer {
if (it == TooltipInteraction.CloseCancelButtonClick || it == TooltipInteraction.YesButtonClick || it == TooltipInteraction.NoButtonClick) {
tooltipView.hideTooltip()
}
}
}
private fun newTooltipMetadata() : TooltipMetadata {
return TooltipMetadata(TooltipType.FirstReceiptUsePaymentMethodsQuestion, context.getString(R.string.pref_receipt_use_payment_methods_title))
}
}
| agpl-3.0 | d44096c1a2c0c7042f1e1927abd741c4 | 56.743119 | 188 | 0.635367 | 6.415902 | false | false | false | false |
google/intellij-community | plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHCloneDialogExtensionComponentBase.kt | 3 | 16707 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.ui.cloneDialog
import com.intellij.collaboration.auth.AccountsListener
import com.intellij.collaboration.auth.ui.CompactAccountsPanelFactory
import com.intellij.collaboration.ui.CollaborationToolsUIUtil
import com.intellij.collaboration.ui.util.JListHoveredRowMaterialiser
import com.intellij.collaboration.util.ProgressIndicatorsProvider
import com.intellij.dvcs.repo.ClonePathProvider
import com.intellij.dvcs.ui.CloneDvcsValidationUtils
import com.intellij.dvcs.ui.DvcsBundle.message
import com.intellij.dvcs.ui.FilePathDocumentChildPathHandle
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.CheckoutProvider
import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtensionComponent
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.*
import com.intellij.ui.SingleSelectionModel
import com.intellij.ui.components.JBList
import com.intellij.ui.components.panels.Wrapper
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.ui.dsl.gridLayout.VerticalAlign
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.cloneDialog.AccountMenuItem
import com.intellij.util.ui.cloneDialog.VcsCloneDialogUiSpec
import git4idea.GitUtil
import git4idea.checkout.GitCheckoutProvider
import git4idea.commands.Git
import git4idea.remote.GitRememberedInputs
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.github.GithubIcons
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.ui.GHAccountsDetailsLoader
import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException
import org.jetbrains.plugins.github.exceptions.GithubMissingTokenException
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.util.*
import java.awt.event.ActionEvent
import java.nio.file.Paths
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.event.ListDataEvent
import javax.swing.event.ListDataListener
import kotlin.properties.Delegates
internal abstract class GHCloneDialogExtensionComponentBase(
private val project: Project,
private val authenticationManager: GithubAuthenticationManager,
private val executorManager: GithubApiRequestExecutorManager
) : VcsCloneDialogExtensionComponent() {
private val LOG = GithubUtil.LOG
private val githubGitHelper: GithubGitHelper = GithubGitHelper.getInstance()
// UI
private val wrapper: Wrapper = Wrapper()
private val repositoriesPanel: DialogPanel
private val repositoryList: JBList<GHRepositoryListItem>
private val searchField: SearchTextField
private val directoryField = TextFieldWithBrowseButton().apply {
val fcd = FileChooserDescriptorFactory.createSingleFolderDescriptor()
fcd.isShowFileSystemRoots = true
fcd.isHideIgnored = false
addBrowseFolderListener(message("clone.destination.directory.browser.title"),
message("clone.destination.directory.browser.description"),
project,
fcd)
}
private val cloneDirectoryChildHandle = FilePathDocumentChildPathHandle
.install(directoryField.textField.document, ClonePathProvider.defaultParentDirectoryPath(project, GitRememberedInputs.getInstance()))
// state
private val loader = GHCloneDialogRepositoryListLoaderImpl(executorManager)
private var inLoginState = false
private var selectedUrl by Delegates.observable<String?>(null) { _, _, _ -> onSelectedUrlChanged() }
protected val content: JComponent get() = wrapper.targetComponent
private val accountListModel: ListModel<GithubAccount> = createAccountsModel()
init {
repositoryList = JBList(loader.listModel).apply {
cellRenderer = GHRepositoryListCellRenderer(ErrorHandler()) { accountListModel.itemsSet }
isFocusable = false
selectionModel = loader.listSelectionModel
}.also {
val mouseAdapter = GHRepositoryMouseAdapter(it)
it.addMouseListener(mouseAdapter)
it.addMouseMotionListener(mouseAdapter)
it.addListSelectionListener { evt ->
if (evt.valueIsAdjusting) return@addListSelectionListener
updateSelectedUrl()
}
}
//TODO: fix jumping selection in the presence of filter
loader.addLoadingStateListener {
repositoryList.setPaintBusy(loader.loading)
}
searchField = SearchTextField(false).also {
it.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) = updateSelectedUrl()
})
createFocusFilterFieldAction(it)
}
CollaborationToolsUIUtil.attachSearch(repositoryList, searchField) {
when (it) {
is GHRepositoryListItem.Repo -> it.repo.fullName
is GHRepositoryListItem.Error -> ""
}
}
val indicatorsProvider = ProgressIndicatorsProvider()
@Suppress("LeakingThis")
val parentDisposable: Disposable = this
Disposer.register(parentDisposable, loader)
Disposer.register(parentDisposable, indicatorsProvider)
val accountDetailsLoader = GHAccountsDetailsLoader(indicatorsProvider) {
try {
executorManager.getExecutor(it)
}
catch (e: Exception) {
null
}
}
val accountsPanel = CompactAccountsPanelFactory(accountListModel, accountDetailsLoader)
.create(GithubIcons.DefaultAvatar, VcsCloneDialogUiSpec.Components.avatarSize, AccountsPopupConfig())
repositoriesPanel = panel {
row {
cell(searchField.textEditor)
.resizableColumn()
.verticalAlign(VerticalAlign.FILL)
.horizontalAlign(HorizontalAlign.FILL)
cell(JSeparator(JSeparator.VERTICAL))
.verticalAlign(VerticalAlign.FILL)
cell(accountsPanel)
.verticalAlign(VerticalAlign.FILL)
}
row {
scrollCell(repositoryList)
.resizableColumn()
.verticalAlign(VerticalAlign.FILL)
.horizontalAlign(HorizontalAlign.FILL)
}.resizableRow()
row(GithubBundle.message("clone.dialog.directory.field")) {
cell(directoryField)
.horizontalAlign(HorizontalAlign.FILL)
.validationOnApply {
CloneDvcsValidationUtils.checkDirectory(it.text, it.textField)
}
}
}
repositoriesPanel.border = JBEmptyBorder(UIUtil.getRegularPanelInsets())
setupAccountsListeners()
}
private inner class ErrorHandler : GHRepositoryListCellRenderer.ErrorHandler {
override fun getPresentableText(error: Throwable): @Nls String = when (error) {
is GithubMissingTokenException -> GithubBundle.message("account.token.missing")
is GithubAuthenticationException -> GithubBundle.message("credentials.invalid.auth.data", "")
else -> GithubBundle.message("clone.error.load.repositories")
}
override fun getAction(account: GithubAccount, error: Throwable) = when (error) {
is GithubAuthenticationException -> object : AbstractAction(GithubBundle.message("accounts.relogin")) {
override fun actionPerformed(e: ActionEvent?) {
switchToLogin(account)
}
}
else -> object : AbstractAction(GithubBundle.message("retry.link")) {
override fun actionPerformed(e: ActionEvent?) {
loader.clear(account)
loader.loadRepositories(account)
}
}
}
}
protected abstract fun isAccountHandled(account: GithubAccount): Boolean
protected fun getAccounts(): Set<GithubAccount> = accountListModel.itemsSet
protected abstract fun createLoginPanel(account: GithubAccount?, cancelHandler: () -> Unit): JComponent
private fun setupAccountsListeners() {
accountListModel.addListDataListener(object : ListDataListener {
private var currentList by Delegates.observable(emptySet<GithubAccount>()) { _, oldValue, newValue ->
val delta = CollectionDelta(oldValue, newValue)
for (account in delta.removedItems) {
loader.clear(account)
}
for (account in delta.newItems) {
loader.loadRepositories(account)
}
if (newValue.isEmpty()) {
switchToLogin(null)
}
else {
switchToRepositories()
}
dialogStateListener.onListItemChanged()
}
init {
currentList = accountListModel.itemsSet
}
override fun intervalAdded(e: ListDataEvent) {
currentList = accountListModel.itemsSet
}
override fun intervalRemoved(e: ListDataEvent) {
currentList = accountListModel.itemsSet
}
override fun contentsChanged(e: ListDataEvent) {
for (i in e.index0..e.index1) {
val account = accountListModel.getElementAt(i)
loader.clear(account)
loader.loadRepositories(account)
}
switchToRepositories()
dialogStateListener.onListItemChanged()
}
})
}
protected fun switchToLogin(account: GithubAccount?) {
wrapper.setContent(createLoginPanel(account) { switchToRepositories() })
wrapper.repaint()
inLoginState = true
updateSelectedUrl()
}
private fun switchToRepositories() {
wrapper.setContent(repositoriesPanel)
wrapper.repaint()
inLoginState = false
updateSelectedUrl()
}
override fun getView() = wrapper
override fun doValidateAll(): List<ValidationInfo> =
(wrapper.targetComponent as? DialogPanel)?.validationsOnApply?.values?.flatten()?.mapNotNull {
it.validate()
} ?: emptyList()
override fun doClone(checkoutListener: CheckoutProvider.Listener) {
val parent = Paths.get(directoryField.text).toAbsolutePath().parent
val destinationValidation = CloneDvcsValidationUtils.createDestination(parent.toString())
if (destinationValidation != null) {
LOG.error("Unable to create destination directory", destinationValidation.message)
GithubNotifications.showError(project,
GithubNotificationIdsHolder.CLONE_UNABLE_TO_CREATE_DESTINATION_DIR,
GithubBundle.message("clone.dialog.clone.failed"),
GithubBundle.message("clone.error.unable.to.create.dest.dir"))
return
}
val lfs = LocalFileSystem.getInstance()
var destinationParent = lfs.findFileByIoFile(parent.toFile())
if (destinationParent == null) {
destinationParent = lfs.refreshAndFindFileByIoFile(parent.toFile())
}
if (destinationParent == null) {
LOG.error("Clone Failed. Destination doesn't exist")
GithubNotifications.showError(project,
GithubNotificationIdsHolder.CLONE_UNABLE_TO_FIND_DESTINATION,
GithubBundle.message("clone.dialog.clone.failed"),
GithubBundle.message("clone.error.unable.to.find.dest"))
return
}
val directoryName = Paths.get(directoryField.text).fileName.toString()
val parentDirectory = parent.toAbsolutePath().toString()
GitCheckoutProvider.clone(project, Git.getInstance(), checkoutListener, destinationParent, selectedUrl, directoryName, parentDirectory)
}
override fun onComponentSelected() {
dialogStateListener.onOkActionNameChanged(GithubBundle.message("clone.button"))
updateSelectedUrl()
val focusManager = IdeFocusManager.getInstance(project)
getPreferredFocusedComponent()?.let { focusManager.requestFocus(it, true) }
}
override fun getPreferredFocusedComponent(): JComponent? {
return searchField
}
private fun updateSelectedUrl() {
repositoryList.emptyText.clear()
if (inLoginState) {
selectedUrl = null
return
}
val githubRepoPath = getGithubRepoPath(searchField.text)
if (githubRepoPath != null) {
selectedUrl = githubGitHelper.getRemoteUrl(githubRepoPath.serverPath,
githubRepoPath.repositoryPath.owner,
githubRepoPath.repositoryPath.repository)
repositoryList.emptyText.appendText(GithubBundle.message("clone.dialog.text", selectedUrl!!))
return
}
val selectedValue = repositoryList.selectedValue
if (selectedValue is GHRepositoryListItem.Repo) {
selectedUrl = githubGitHelper.getRemoteUrl(selectedValue.account.server,
selectedValue.repo.userName,
selectedValue.repo.name)
return
}
selectedUrl = null
}
private fun getGithubRepoPath(searchText: String): GHRepositoryCoordinates? {
val url = searchText
.trim()
.removePrefix("git clone")
.removeSuffix(".git")
.trim()
try {
var serverPath = GithubServerPath.from(url)
serverPath = GithubServerPath.from(serverPath.toUrl().removeSuffix(serverPath.suffix ?: ""))
val githubFullPath = GithubUrlUtil.getUserAndRepositoryFromRemoteUrl(url) ?: return null
return GHRepositoryCoordinates(serverPath, githubFullPath)
}
catch (e: Throwable) {
return null
}
}
private fun onSelectedUrlChanged() {
val urlSelected = selectedUrl != null
dialogStateListener.onOkActionEnabled(urlSelected)
if (urlSelected) {
val path = StringUtil.trimEnd(ClonePathProvider.relativeDirectoryPathForVcsUrl(project, selectedUrl!!), GitUtil.DOT_GIT)
cloneDirectoryChildHandle.trySetChildPath(path)
}
}
private fun createAccountsModel(): ListModel<GithubAccount> {
val model = CollectionListModel(authenticationManager.getAccounts().filter(::isAccountHandled))
authenticationManager.addListener(this, object : AccountsListener<GithubAccount> {
override fun onAccountListChanged(old: Collection<GithubAccount>, new: Collection<GithubAccount>) {
val oldList = old.filter(::isAccountHandled)
val newList = new.filter(::isAccountHandled)
val delta = CollectionDelta(oldList, newList)
model.add(delta.newItems.toList())
for (account in delta.removedItems) {
model.remove(account)
}
}
override fun onAccountCredentialsChanged(account: GithubAccount) {
if (!isAccountHandled(account)) return
model.contentsChanged(account)
}
})
return model
}
private inner class AccountsPopupConfig : CompactAccountsPanelFactory.PopupConfig<GithubAccount> {
override val avatarSize: Int = VcsCloneDialogUiSpec.Components.popupMenuAvatarSize
override fun createActions(): Collection<AccountMenuItem.Action> = createAccountMenuLoginActions(null)
}
protected abstract fun createAccountMenuLoginActions(account: GithubAccount?): Collection<AccountMenuItem.Action>
private fun createFocusFilterFieldAction(searchField: SearchTextField) {
val action = DumbAwareAction.create {
val focusManager = IdeFocusManager.getInstance(project)
if (focusManager.getFocusedDescendantFor(repositoriesPanel) != null) {
focusManager.requestFocus(searchField, true)
}
}
val shortcuts = KeymapUtil.getActiveKeymapShortcuts(IdeActions.ACTION_FIND)
action.registerCustomShortcutSet(shortcuts, repositoriesPanel, this)
}
companion object {
internal val <E> ListModel<E>.items
get() = Iterable {
object : Iterator<E> {
private var idx = -1
override fun hasNext(): Boolean = idx < size - 1
override fun next(): E {
idx++
return getElementAt(idx)
}
}
}
internal val <E> ListModel<E>.itemsSet
get() = items.toSet()
}
} | apache-2.0 | 62023c5d3f2a17731318e1b9a5404f1e | 37.765661 | 140 | 0.723768 | 5.220938 | false | false | false | false |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/ui/compose/feed/FeedScreen.kt | 1 | 21372 | package com.nononsenseapps.feeder.ui.compose.feed
import android.content.Intent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.staggeredgrid.LazyStaggeredGridState
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DoneAll
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.paging.compose.LazyPagingItems
import com.nononsenseapps.feeder.R
import com.nononsenseapps.feeder.archmodel.FeedItemStyle
import com.nononsenseapps.feeder.db.room.ID_UNSET
import com.nononsenseapps.feeder.model.LocaleOverride
import com.nononsenseapps.feeder.ui.compose.deletefeed.DeletableFeed
import com.nononsenseapps.feeder.ui.compose.deletefeed.DeleteFeedDialog
import com.nononsenseapps.feeder.ui.compose.empty.NothingToRead
import com.nononsenseapps.feeder.ui.compose.feedarticle.FeedScreenViewState
import com.nononsenseapps.feeder.ui.compose.readaloud.HideableTTSPlayer
import com.nononsenseapps.feeder.ui.compose.text.withBidiDeterminedLayoutDirection
import com.nononsenseapps.feeder.ui.compose.theme.LocalDimens
import com.nononsenseapps.feeder.ui.compose.utils.ImmutableHolder
import com.nononsenseapps.feeder.ui.compose.utils.addMargin
import com.nononsenseapps.feeder.ui.compose.utils.addMarginLayout
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.threeten.bp.Instant
@Composable
fun FeedListContent(
viewState: FeedScreenViewState,
onOpenNavDrawer: () -> Unit,
onAddFeed: () -> Unit,
markAsUnread: (Long, Boolean) -> Unit,
markBeforeAsRead: (Int) -> Unit,
markAfterAsRead: (Int) -> Unit,
onItemClick: (Long) -> Unit,
onSetPinned: (Long, Boolean) -> Unit,
onSetBookmarked: (Long, Boolean) -> Unit,
listState: LazyListState,
pagedFeedItems: LazyPagingItems<FeedListItem>,
modifier: Modifier,
) {
val coroutineScope = rememberCoroutineScope()
val context = LocalContext.current
Box(modifier = modifier) {
AnimatedVisibility(
enter = fadeIn(),
exit = fadeOut(),
visible = !viewState.haveVisibleFeedItems,
) {
// Keeping the Box behind so the scrollability doesn't override clickable
// Separate box because scrollable will ignore max size.
Box(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
)
NothingToRead(
modifier = modifier,
onOpenOtherFeed = onOpenNavDrawer,
onAddFeed = onAddFeed
)
}
val arrangement = when (viewState.feedItemStyle) {
FeedItemStyle.CARD -> Arrangement.spacedBy(LocalDimens.current.margin)
FeedItemStyle.COMPACT -> Arrangement.spacedBy(0.dp)
FeedItemStyle.SUPER_COMPACT -> Arrangement.spacedBy(0.dp)
}
AnimatedVisibility(
enter = fadeIn(),
exit = fadeOut(),
visible = viewState.haveVisibleFeedItems,
) {
LazyColumn(
state = listState,
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = arrangement,
contentPadding = if (viewState.isBottomBarVisible) PaddingValues(0.dp) else WindowInsets.navigationBars.only(
WindowInsetsSides.Bottom
).run {
when (viewState.feedItemStyle) {
FeedItemStyle.CARD -> addMargin(horizontal = LocalDimens.current.margin)
FeedItemStyle.COMPACT, FeedItemStyle.SUPER_COMPACT -> addMarginLayout(start = LocalDimens.current.margin)
}
}
.asPaddingValues(),
modifier = Modifier.fillMaxSize()
) {
/*
This is a trick to make the list stay at item 0 when updates come in IF it is
scrolled to the top.
*/
item {
Spacer(modifier = Modifier.fillMaxWidth())
}
items(
pagedFeedItems.itemCount,
key = { itemIndex ->
pagedFeedItems.itemSnapshotList.items[itemIndex].id
}
) { itemIndex ->
val previewItem = pagedFeedItems[itemIndex]
?: return@items
SwipeableFeedItemPreview(
onSwipe = { currentState ->
markAsUnread(
previewItem.id,
!currentState
)
},
swipeAsRead = viewState.swipeAsRead,
onlyUnread = viewState.onlyUnread,
item = previewItem,
showThumbnail = viewState.showThumbnails,
feedItemStyle = viewState.feedItemStyle,
onMarkAboveAsRead = {
if (itemIndex > 0) {
markBeforeAsRead(itemIndex)
if (viewState.onlyUnread) {
coroutineScope.launch {
listState.scrollToItem(0)
}
}
}
},
onMarkBelowAsRead = {
markAfterAsRead(itemIndex)
},
onShareItem = {
val intent = Intent.createChooser(
Intent(Intent.ACTION_SEND).apply {
if (previewItem.link != null) {
putExtra(Intent.EXTRA_TEXT, previewItem.link)
}
putExtra(Intent.EXTRA_TITLE, previewItem.title)
type = "text/plain"
},
null
)
context.startActivity(intent)
},
onItemClick = {
onItemClick(previewItem.id)
},
onTogglePinned = {
onSetPinned(previewItem.id, !previewItem.pinned)
},
onToggleBookmarked = {
onSetBookmarked(previewItem.id, !previewItem.bookmarked)
},
)
if (viewState.feedItemStyle != FeedItemStyle.CARD) {
if (itemIndex < pagedFeedItems.itemCount - 1) {
Divider(
modifier = Modifier
.height(1.dp)
.fillMaxWidth()
)
}
}
}
/*
This item is provide padding for the FAB
*/
if (viewState.showFab && !viewState.isBottomBarVisible) {
item {
Spacer(
modifier = Modifier
.fillMaxWidth()
.height((56 + 16).dp)
)
}
}
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun FeedGridContent(
viewState: FeedScreenViewState,
onOpenNavDrawer: () -> Unit,
onAddFeed: () -> Unit,
markBeforeAsRead: (Int) -> Unit,
markAfterAsRead: (Int) -> Unit,
onItemClick: (Long) -> Unit,
onSetPinned: (Long, Boolean) -> Unit,
onSetBookmarked: (Long, Boolean) -> Unit,
gridState: LazyStaggeredGridState,
pagedFeedItems: LazyPagingItems<FeedListItem>,
modifier: Modifier,
) {
val coroutineScope = rememberCoroutineScope()
val context = LocalContext.current
Box(modifier = modifier) {
AnimatedVisibility(
enter = fadeIn(),
exit = fadeOut(),
visible = !viewState.haveVisibleFeedItems,
) {
// Keeping the Box behind so the scrollability doesn't override clickable
// Separate box because scrollable will ignore max size.
Box(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
)
NothingToRead(
modifier = modifier,
onOpenOtherFeed = onOpenNavDrawer,
onAddFeed = onAddFeed
)
}
val arrangement = when (viewState.feedItemStyle) {
FeedItemStyle.CARD -> Arrangement.spacedBy(LocalDimens.current.gutter)
FeedItemStyle.COMPACT -> Arrangement.spacedBy(LocalDimens.current.gutter)
FeedItemStyle.SUPER_COMPACT -> Arrangement.spacedBy(LocalDimens.current.gutter)
}
val minItemWidth = when (viewState.feedItemStyle) {
// 300 - 16 - 16/2 : so that 600dp screens should get two columns
FeedItemStyle.CARD -> 276.dp
FeedItemStyle.COMPACT -> 400.dp
FeedItemStyle.SUPER_COMPACT -> 276.dp
}
AnimatedVisibility(
enter = fadeIn(),
exit = fadeOut(),
visible = viewState.haveVisibleFeedItems,
) {
LazyVerticalStaggeredGrid(
state = gridState,
columns = StaggeredGridCells.Adaptive(minItemWidth),
contentPadding = if (viewState.isBottomBarVisible) PaddingValues(0.dp) else WindowInsets.navigationBars.only(
WindowInsetsSides.Bottom
).addMargin(LocalDimens.current.margin)
.asPaddingValues(),
verticalArrangement = arrangement,
horizontalArrangement = arrangement,
modifier = Modifier.fillMaxSize(),
) {
items(
pagedFeedItems.itemCount,
key = { itemIndex ->
pagedFeedItems.itemSnapshotList.items[itemIndex].id
}
) { itemIndex ->
val previewItem = pagedFeedItems[itemIndex]
?: return@items
FixedFeedItemPreview(
item = previewItem,
showThumbnail = viewState.showThumbnails,
feedItemStyle = viewState.feedItemStyle,
onMarkAboveAsRead = {
if (itemIndex > 0) {
markBeforeAsRead(itemIndex)
if (viewState.onlyUnread) {
coroutineScope.launch {
gridState.scrollToItem(0)
}
}
}
},
onMarkBelowAsRead = {
markAfterAsRead(itemIndex)
},
onShareItem = {
val intent = Intent.createChooser(
Intent(Intent.ACTION_SEND).apply {
if (previewItem.link != null) {
putExtra(Intent.EXTRA_TEXT, previewItem.link)
}
putExtra(Intent.EXTRA_TITLE, previewItem.title)
type = "text/plain"
},
null
)
context.startActivity(intent)
},
onItemClick = {
onItemClick(previewItem.id)
},
onTogglePinned = {
onSetPinned(previewItem.id, !previewItem.pinned)
},
onToggleBookmarked = {
onSetBookmarked(previewItem.id, !previewItem.bookmarked)
},
)
}
}
}
}
}
@OptIn(
ExperimentalMaterial3Api::class, ExperimentalAnimationApi::class,
ExperimentalMaterialApi::class
)
@Composable
fun FeedScreen(
viewState: FeedScreenViewState,
onRefreshVisible: () -> Unit,
onOpenNavDrawer: () -> Unit,
onMarkAllAsRead: () -> Unit,
ttsOnPlay: () -> Unit,
ttsOnPause: () -> Unit,
ttsOnStop: () -> Unit,
ttsOnSkipNext: () -> Unit,
ttsOnSelectLanguage: (LocaleOverride) -> Unit,
onDismissDeleteDialog: () -> Unit,
onDismissEditDialog: () -> Unit,
onDelete: (Iterable<Long>) -> Unit,
onEditFeed: (Long) -> Unit,
toolbarActions: @Composable() (RowScope.() -> Unit),
modifier: Modifier = Modifier,
content: @Composable (Modifier) -> Unit,
) {
var lastMaxPoint by remember {
mutableStateOf(Instant.EPOCH)
}
val isRefreshing by remember(viewState.latestSyncTimestamp, lastMaxPoint) {
derivedStateOf {
viewState.latestSyncTimestamp.isAfter(
maxOf(
lastMaxPoint,
Instant.now().minusSeconds(20)
)
)
}
}
val pullRefreshState = rememberPullRefreshState(
refreshing = isRefreshing,
onRefresh = onRefreshVisible,
)
LaunchedEffect(viewState.latestSyncTimestamp) {
// GUI will only display refresh indicator for 10 seconds at most.
// Fixes an issue where sync was triggered but no feed needed syncing, meaning no DB updates
delay(10_000L)
lastMaxPoint = Instant.now()
}
val floatingActionButton: @Composable () -> Unit = {
FloatingActionButton(
onClick = onMarkAllAsRead,
modifier = Modifier.navigationBarsPadding(),
) {
Icon(
Icons.Default.DoneAll,
contentDescription = stringResource(R.string.mark_all_as_read)
)
}
}
val bottomBarVisibleState = remember { MutableTransitionState(viewState.isBottomBarVisible) }
LaunchedEffect(viewState.isBottomBarVisible) {
bottomBarVisibleState.targetState = viewState.isBottomBarVisible
}
Scaffold(
topBar = {
TopAppBar(
title = {
val text = viewState.feedScreenTitle.title
?: stringResource(id = R.string.all_feeds)
withBidiDeterminedLayoutDirection(paragraph = text) {
Text(
text,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
},
navigationIcon = {
IconButton(
onClick = onOpenNavDrawer
) {
Icon(
Icons.Default.Menu,
contentDescription = stringResource(R.string.navigation_drawer_open)
)
}
},
actions = toolbarActions,
)
},
bottomBar = {
HideableTTSPlayer(
visibleState = bottomBarVisibleState,
currentlyPlaying = viewState.isTTSPlaying,
onPlay = ttsOnPlay,
onPause = ttsOnPause,
onStop = ttsOnStop,
onSkipNext = ttsOnSkipNext,
onSelectLanguage = ttsOnSelectLanguage,
languages = ImmutableHolder(viewState.ttsLanguages),
floatingActionButton = when (viewState.showFab) {
true -> floatingActionButton
false -> null
}
)
},
floatingActionButton = {
if (viewState.showFab) {
AnimatedVisibility(
visible = bottomBarVisibleState.isIdle && !bottomBarVisibleState.targetState,
enter = scaleIn(animationSpec = tween(256)),
exit = scaleOut(animationSpec = tween(256)),
) {
floatingActionButton()
}
}
},
modifier = modifier
.windowInsetsPadding(WindowInsets.navigationBars.only(WindowInsetsSides.Horizontal)),
contentWindowInsets = WindowInsets.statusBars,
) { padding ->
Box(
modifier = Modifier
.pullRefresh(pullRefreshState)
) {
content(Modifier.padding(padding))
PullRefreshIndicator(
isRefreshing,
pullRefreshState,
Modifier
.padding(padding)
.align(Alignment.TopCenter)
)
}
if (viewState.showDeleteDialog) {
DeleteFeedDialog(
feeds = ImmutableHolder(
viewState.visibleFeeds.map {
DeletableFeed(it.id, it.displayTitle)
}
),
onDismiss = onDismissDeleteDialog,
onDelete = onDelete
)
}
if (viewState.showEditDialog) {
EditFeedDialog(
feeds = ImmutableHolder(
viewState.visibleFeeds.map {
DeletableFeed(
it.id,
it.displayTitle
)
}
),
onDismiss = onDismissEditDialog,
onEdit = onEditFeed
)
}
}
}
@Immutable
data class FeedOrTag(
val id: Long,
val tag: String,
)
val FeedOrTag.isFeed
get() = id > ID_UNSET
| gpl-3.0 | 028e5117cac6da04e1d375f8d6ad4e47 | 38.798883 | 129 | 0.549972 | 5.984878 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/certificate/ui/adapter/delegate/CertificatesAdapterDelegate.kt | 1 | 3463 | package org.stepik.android.view.certificate.ui.adapter.delegate
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.certificate_item.view.*
import org.stepic.droid.R
import org.stepic.droid.model.CertificateListItem
import org.stepik.android.model.Certificate
import ru.nobird.android.ui.adapterdelegates.AdapterDelegate
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
class CertificatesAdapterDelegate(
private val onItemClick: (String) -> Unit,
private val onShareButtonClick: (CertificateListItem.Data) -> Unit,
private val onChangeNameClick: (CertificateListItem.Data) -> Unit,
private val isCurrentUser: Boolean
) : AdapterDelegate<CertificateListItem, DelegateViewHolder<CertificateListItem>>() {
override fun isForViewType(position: Int, data: CertificateListItem): Boolean =
data is CertificateListItem.Data
override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CertificateListItem> =
ViewHolder(createView(parent, R.layout.certificate_item))
private inner class ViewHolder(
root: View
) : DelegateViewHolder<CertificateListItem>(root) {
private val certificateTitleView = root.certificate_title
private val certificateIcon = root.certificate_icon
private val certificateGradeView = root.certificate_grade
private val certificateDescription = root.certificate_description
private val certificateShareButton = root.certificate_share_button
private val certificateNameChangeButton = root.certificate_name_change_button
private val certificatePlaceholder =
ContextCompat.getDrawable(context, R.drawable.general_placeholder)
init {
root.setOnClickListener { (itemData as? CertificateListItem.Data)?.let { onItemClick(it.certificate.url ?: "") } }
certificateShareButton.setOnClickListener { onShareButtonClick(itemData as CertificateListItem.Data) }
certificateNameChangeButton.setOnClickListener { (itemData as? CertificateListItem.Data)?.let(onChangeNameClick) }
}
override fun onBind(data: CertificateListItem) {
data as CertificateListItem.Data
certificateTitleView.text = data.title ?: ""
certificateDescription.text =
when (data.certificate.type) {
Certificate.Type.DISTINCTION ->
context.resources.getString(R.string.certificate_distinction_with_substitution, data.title ?: "")
Certificate.Type.REGULAR ->
context.resources.getString(R.string.certificate_regular_with_substitution, data.title ?: "")
else ->
""
}
certificateGradeView.text =
context.resources.getString(R.string.certificate_result_with_substitution, data.certificate.grade ?: "")
certificateGradeView.isVisible = data.certificate.isWithScore
certificateNameChangeButton.isVisible = data.certificate.editsCount < data.certificate.allowedEditsCount && isCurrentUser
Glide.with(context)
.load(data.coverFullPath ?: "")
.placeholder(certificatePlaceholder)
.into(certificateIcon)
}
}
} | apache-2.0 | 7371797a17fd85b017d1306b71b88aa4 | 46.452055 | 133 | 0.706902 | 5.278963 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/editor/stage/SearchBar.kt | 2 | 6256 | package io.github.chrislo27.rhre3.editor.stage
import com.badlogic.gdx.Input
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import io.github.chrislo27.rhre3.editor.Editor
import io.github.chrislo27.rhre3.editor.picker.SearchFilter
import io.github.chrislo27.toolboks.ToolboksScreen
import io.github.chrislo27.toolboks.i18n.Localization
import io.github.chrislo27.toolboks.registry.AssetRegistry
import io.github.chrislo27.toolboks.ui.*
class SearchBar<S : ToolboksScreen<*, *>>(screenWidth: Float, val editor: Editor, val editorStage: EditorStage,
val palette: UIPalette, parent: UIElement<S>, camera: OrthographicCamera)
: Stage<S>(parent, camera) {
enum class Filter(val tag: String) {
GAME_NAME("gameName"),
ENTITY_NAME("entityName"),
FAVOURITES("favourites"),
USE_IN_REMIX("useInRemix"),
CALL_AND_RESPONSE("callAndResponse");
companion object {
val VALUES = values().toList()
}
val localizationKey = "editor.search.filter.$tag"
}
init {
this.location.set(screenWidth = screenWidth)
this.updatePositions()
}
private val searchFilter: SearchFilter get() = editorStage.searchFilter
val textField = object : TextField<S>(palette, this@SearchBar, this@SearchBar) {
init {
this.textWhenEmptyColor = Color.LIGHT_GRAY
}
override fun render(screen: S, batch: SpriteBatch, shapeRenderer: ShapeRenderer) {
super.render(screen, batch, shapeRenderer)
this.textWhenEmpty = Localization["picker.search"]
}
override fun onTextChange(oldText: String) {
super.onTextChange(oldText)
editorStage.updateSelected(EditorStage.DirtyType.SEARCH_DIRTY)
}
override fun onLeftClick(xPercent: Float, yPercent: Float) {
val hadFocus = hasFocus
super.onLeftClick(xPercent, yPercent)
editor.pickerSelection.filter = searchFilter
editorStage.updateSelected(
if (!hadFocus) EditorStage.DirtyType.SEARCH_DIRTY else EditorStage.DirtyType.DIRTY)
}
override fun onRightClick(xPercent: Float, yPercent: Float) {
super.onRightClick(xPercent, yPercent)
hasFocus = true
text = ""
editorStage.updateSelected(EditorStage.DirtyType.SEARCH_DIRTY)
editor.pickerSelection.filter = searchFilter
}
}
val clearButton: ClearButton = ClearButton()
val filterButton: FilterButton = FilterButton()
init {
this.updatePositions()
val height = location.realHeight
val width = percentageOfWidth(height)
filterButton.apply {
this.location.set(screenWidth = width)
this.location.set(screenX = 1f - this.location.screenWidth)
this.background = false
this.updateLabel()
}
clearButton.apply {
this.location.set(screenWidth = width)
this.location.set(screenX = filterButton.location.screenX - this.location.screenWidth)
this.background = false
this.addLabel(ImageLabel(palette, this, this.stage).apply {
this.image = TextureRegion(AssetRegistry.get<Texture>("ui_search_clear"))
this.renderType = ImageLabel.ImageRendering.ASPECT_RATIO
this.tint.a = 0.75f
})
}
textField.apply {
this.location.set(screenWidth = clearButton.location.screenX)
}
elements += textField
elements += clearButton
elements += filterButton
}
inner class FilterButton : Button<S>(palette, this, this) {
var filter: Filter = Filter.GAME_NAME
private set
private val imageLabel = ImageLabel(palette, this, this.stage).apply {
this.tint.a = 0.75f
this.background = false
this.renderType = ImageLabel.ImageRendering.ASPECT_RATIO
}
private val textures by lazy {
Filter.VALUES.associate { it to TextureRegion(AssetRegistry.get<Texture>("ui_search_filter_${it.tag}")) }
}
init {
addLabel(imageLabel)
updateLabel()
}
override var tooltipText: String?
set(_) {}
get() = Localization[filter.localizationKey]
override fun onLeftClick(xPercent: Float, yPercent: Float) {
super.onLeftClick(xPercent, yPercent)
var index = Filter.VALUES.indexOf(filter) + 1
if (index >= Filter.VALUES.size) {
index = 0
}
filter = Filter.VALUES[index]
editorStage.updateSelected(EditorStage.DirtyType.SEARCH_DIRTY)
updateLabel()
}
override fun onRightClick(xPercent: Float, yPercent: Float) {
super.onRightClick(xPercent, yPercent)
var index = Filter.VALUES.indexOf(filter) - 1
if (index < 0) {
index = Filter.VALUES.size - 1
}
filter = Filter.VALUES[index]
editorStage.updateSelected(EditorStage.DirtyType.SEARCH_DIRTY)
updateLabel()
}
fun updateLabel() {
imageLabel.image = textures[filter]
}
}
inner class ClearButton : Button<S>(palette, this, this) {
override var tooltipText: String?
set(_) {}
get() = Localization["editor.search.clear"]
override fun onLeftClick(xPercent: Float, yPercent: Float) {
super.onLeftClick(xPercent, yPercent)
textField.text = ""
textField.touchDown((textField.location.realX + textField.location.realWidth / 2).toInt(),
(textField.location.realY + textField.location.realHeight / 2).toInt(),
0, Input.Buttons.LEFT)
textField.hasFocus = true
}
}
} | gpl-3.0 | 1fdc0591ee042751ee67d0bffbaa7091 | 33.955307 | 117 | 0.618286 | 4.779221 | false | false | false | false |
glodanif/BluetoothChat | app/src/main/kotlin/com/glodanif/bluetoothchat/data/service/connection/ConnectionController.kt | 1 | 25683 | package com.glodanif.bluetoothchat.data.service.connection
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothServerSocket
import android.bluetooth.BluetoothSocket
import android.graphics.BitmapFactory
import android.os.Environment
import androidx.core.app.NotificationCompat
import androidx.core.app.Person
import com.glodanif.bluetoothchat.ChatApplication
import com.glodanif.bluetoothchat.R
import com.glodanif.bluetoothchat.data.entity.ChatMessage
import com.glodanif.bluetoothchat.data.entity.Conversation
import com.glodanif.bluetoothchat.data.model.ConversationsStorage
import com.glodanif.bluetoothchat.data.model.MessagesStorage
import com.glodanif.bluetoothchat.data.model.ProfileManager
import com.glodanif.bluetoothchat.data.model.UserPreferences
import com.glodanif.bluetoothchat.data.service.message.Contract
import com.glodanif.bluetoothchat.data.service.message.Message
import com.glodanif.bluetoothchat.data.service.message.PayloadType
import com.glodanif.bluetoothchat.data.service.message.TransferringFile
import com.glodanif.bluetoothchat.ui.view.NotificationView
import com.glodanif.bluetoothchat.ui.widget.ShortcutManager
import com.glodanif.bluetoothchat.utils.LimitedQueue
import com.glodanif.bluetoothchat.utils.Size
import kotlinx.coroutines.*
import java.io.File
import java.io.IOException
import java.util.*
import kotlin.coroutines.CoroutineContext
class ConnectionController(private val application: ChatApplication,
private val subject: ConnectionSubject,
private val view: NotificationView,
private val conversationStorage: ConversationsStorage,
private val messagesStorage: MessagesStorage,
private val preferences: UserPreferences,
private val profileManager: ProfileManager,
private val shortcutManager: ShortcutManager,
private val uiContext: CoroutineDispatcher = Dispatchers.Main,
private val bgContext: CoroutineDispatcher = Dispatchers.IO) : CoroutineScope {
private val blAppName = application.getString(R.string.bl_app_name)
private val blAppUUID = UUID.fromString(application.getString(R.string.bl_app_uuid))
private var acceptThread: AcceptJob? = null
private var connectThread: ConnectJob? = null
private var dataTransferThread: DataTransferThread? = null
@Volatile
private var connectionState: ConnectionState = ConnectionState.NOT_CONNECTED
@Volatile
private var connectionType: ConnectionType? = null
private var currentSocket: BluetoothSocket? = null
private var currentConversation: Conversation? = null
private var contract = Contract()
private var justRepliedFromNotification = false
private val imageText: String by lazy {
application.getString(R.string.chat__image_message, "\uD83D\uDCCE")
}
private val me: Person by lazy {
Person.Builder().setName(application.getString(R.string.notification__me)).build()
}
private val shallowHistory = LimitedQueue<NotificationCompat.MessagingStyle.Message>(4)
var onNewForegroundMessage: ((String) -> Unit)? = null
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + uiContext
fun createForegroundNotification(message: String) = view.getForegroundNotification(message)
@Synchronized
fun prepareForAccept() {
cancelConnections()
if (subject.isRunning()) {
acceptThread = AcceptJob()
acceptThread?.start()
onNewForegroundMessage?.invoke(application.getString(R.string.notification__ready_to_connect))
}
}
@Synchronized
fun disconnect() {
dataTransferThread?.cancel(true)
dataTransferThread = null
prepareForAccept()
}
@Synchronized
fun connect(device: BluetoothDevice) {
if (connectionState == ConnectionState.CONNECTING) {
connectThread?.cancel()
connectThread = null
}
dataTransferThread?.cancel(true)
acceptThread?.cancel()
dataTransferThread = null
acceptThread = null
currentSocket = null
currentConversation = null
contract.reset()
connectionType = null
connectThread = ConnectJob(device)
connectThread?.start()
launch { subject.handleConnectingInProgress() }
}
private fun cancelConnections() {
connectThread?.cancel()
connectThread = null
dataTransferThread?.cancel()
dataTransferThread = null
currentSocket = null
currentConversation = null
contract.reset()
connectionType = null
justRepliedFromNotification = false
}
private fun cancelAccept() {
acceptThread?.cancel()
acceptThread = null
}
private fun connectionFailed() {
currentSocket = null
currentConversation = null
contract.reset()
launch { subject.handleConnectionFailed() }
connectionState = ConnectionState.NOT_CONNECTED
prepareForAccept()
}
@Synchronized
fun stop() {
cancelConnections()
cancelAccept()
connectionState = ConnectionState.NOT_CONNECTED
job.cancel()
}
@Synchronized
fun connected(socket: BluetoothSocket, type: ConnectionType) {
cancelConnections()
connectionType = type
currentSocket = socket
cancelAccept()
val transferEventsListener = object : DataTransferThread.TransferEventsListener {
override fun onMessageReceived(message: String) {
launch {
[email protected](message)
}
}
override fun onMessageSent(message: String) {
launch {
[email protected](message)
}
}
override fun onMessageSendingFailed() {
launch {
[email protected]()
}
}
override fun onConnectionPrepared(type: ConnectionType) {
onNewForegroundMessage?.invoke(application.getString(R.string.notification__connected_to, socket.remoteDevice.name
?: "?"))
connectionState = ConnectionState.PENDING
if (type == ConnectionType.OUTCOMING) {
contract.createConnectMessage(profileManager.getUserName(), profileManager.getUserColor()).let { message ->
dataTransferThread?.write(message.getDecodedMessage())
}
}
}
override fun onConnectionCanceled() {
currentSocket = null
currentConversation = null
contract.reset()
}
override fun onConnectionLost() {
connectionLost()
}
}
val fileEventsListener = object : DataTransferThread.OnFileListener {
override fun onFileSendingStarted(file: TransferringFile) {
subject.handleFileSendingStarted(file.name, file.size)
currentConversation?.let {
val silently = application.currentChat != null && currentSocket != null &&
application.currentChat.equals(currentSocket?.remoteDevice?.address)
view.showFileTransferNotification(it.displayName, it.deviceName,
it.deviceAddress, file, 0, silently)
}
}
override fun onFileSendingProgress(file: TransferringFile, sentBytes: Long) {
launch {
subject.handleFileSendingProgress(sentBytes, file.size)
if (currentConversation != null) {
view.updateFileTransferNotification(sentBytes, file.size)
}
}
}
override fun onFileSendingFinished(uid: Long, path: String) {
contract.createFileEndMessage().let { message ->
dataTransferThread?.write(message.getDecodedMessage())
}
currentSocket?.let { socket ->
val message = ChatMessage(uid, socket.remoteDevice.address, Date(), true, "").apply {
seenHere = true
messageType = PayloadType.IMAGE
filePath = path
}
launch(bgContext) {
val size = getImageSize(path)
message.fileInfo = "${size.width}x${size.height}"
message.fileExists = true
messagesStorage.insertMessage(message)
shallowHistory.add(NotificationCompat.MessagingStyle.Message(imageText, message.date.time, me))
launch(uiContext) {
subject.handleFileSendingFinished()
subject.handleMessageSent(message)
view.dismissFileTransferNotification()
currentConversation?.let {
shortcutManager.addConversationShortcut(message.deviceAddress, it.displayName, it.color)
}
}
}
}
}
override fun onFileSendingFailed() {
launch {
subject.handleFileSendingFailed()
view.dismissFileTransferNotification()
}
}
override fun onFileReceivingStarted(file: TransferringFile) {
launch {
subject.handleFileReceivingStarted(file.size)
currentConversation?.let {
val silently = application.currentChat != null && currentSocket != null &&
application.currentChat.equals(currentSocket?.remoteDevice?.address)
view.showFileTransferNotification(it.displayName, it.deviceName,
it.deviceAddress, file, 0, silently)
}
}
}
override fun onFileReceivingProgress(file: TransferringFile, receivedBytes: Long) {
launch {
subject.handleFileReceivingProgress(receivedBytes, file.size)
if (currentConversation != null) {
view.updateFileTransferNotification(receivedBytes, file.size)
}
}
}
override fun onFileReceivingFinished(uid: Long, path: String) {
currentSocket?.remoteDevice?.let { device ->
val address = device.address
val message = ChatMessage(uid, address, Date(), false, "").apply {
messageType = PayloadType.IMAGE
filePath = path
}
val partner = Person.Builder().setName(currentConversation?.displayName
?: "?").build()
shallowHistory.add(NotificationCompat.MessagingStyle.Message(imageText, message.date.time, partner))
if (!subject.isAnybodyListeningForMessages() || application.currentChat == null || !application.currentChat.equals(address)) {
//FIXME: Fixes not appearing notification
view.dismissMessageNotification()
view.showNewMessageNotification(imageText, currentConversation?.displayName,
device.name, address, shallowHistory, preferences.isSoundEnabled())
} else {
message.seenHere = true
}
launch(bgContext) {
val size = getImageSize(path)
message.fileInfo = "${size.width}x${size.height}"
message.fileExists = true
messagesStorage.insertMessage(message)
launch(uiContext) {
subject.handleFileReceivingFinished()
subject.handleMessageReceived(message)
view.dismissFileTransferNotification()
currentConversation?.let {
shortcutManager.addConversationShortcut(address, it.displayName, it.color)
}
}
}
}
}
override fun onFileReceivingFailed() {
launch {
subject.handleFileReceivingFailed()
view.dismissFileTransferNotification()
}
}
override fun onFileTransferCanceled(byPartner: Boolean) {
launch {
subject.handleFileTransferCanceled(byPartner)
view.dismissFileTransferNotification()
}
}
}
val eventsStrategy = TransferEventStrategy()
val filesDirectory = File(Environment.getExternalStorageDirectory(), application.getString(R.string.app_name))
dataTransferThread =
object : DataTransferThread(socket, type, transferEventsListener, filesDirectory, fileEventsListener, eventsStrategy) {
override fun shouldRun(): Boolean {
return isConnectedOrPending()
}
}
dataTransferThread?.prepare()
dataTransferThread?.start()
launch { subject.handleConnected(socket.remoteDevice) }
}
fun getCurrentConversation() = currentConversation
fun getCurrentContract() = contract
fun isConnected() = connectionState == ConnectionState.CONNECTED
fun isPending() = connectionState == ConnectionState.PENDING
fun isConnectedOrPending() = isConnected() || isPending()
fun replyFromNotification(text: String) {
contract.createChatMessage(text).let { message ->
justRepliedFromNotification = true
sendMessage(message)
}
}
fun sendMessage(message: Message) {
if (isConnectedOrPending()) {
val disconnect = message.type == Contract.MessageType.CONNECTION_REQUEST && !message.flag
dataTransferThread?.write(message.getDecodedMessage(), disconnect)
if (disconnect) {
dataTransferThread?.cancel(disconnect)
dataTransferThread = null
prepareForAccept()
}
}
if (message.type == Contract.MessageType.CONNECTION_RESPONSE) {
if (message.flag) {
connectionState = ConnectionState.CONNECTED
} else {
disconnect()
}
view.dismissConnectionNotification()
}
}
fun sendFile(file: File, type: PayloadType) {
if (isConnected()) {
contract.createFileStartMessage(file, type).let { message ->
dataTransferThread?.write(message.getDecodedMessage())
dataTransferThread?.writeFile(message.uid, file)
}
}
}
fun approveConnection() {
sendMessage(contract.createAcceptConnectionMessage(
profileManager.getUserName(), profileManager.getUserColor()))
}
fun rejectConnection() {
sendMessage(contract.createRejectConnectionMessage(
profileManager.getUserName(), profileManager.getUserColor()))
}
fun getTransferringFile(): TransferringFile? {
return dataTransferThread?.getTransferringFile()
}
fun cancelFileTransfer() {
dataTransferThread?.cancelFileTransfer()
view.dismissFileTransferNotification()
}
private fun onMessageSent(messageBody: String) = currentSocket?.let { socket ->
val device = socket.remoteDevice
val message = Message(messageBody)
val sentMessage = ChatMessage(message.uid, socket.remoteDevice.address, Date(), true, message.body)
if (message.type == Contract.MessageType.MESSAGE) {
sentMessage.seenHere = true
launch(bgContext) {
messagesStorage.insertMessage(sentMessage)
shallowHistory.add(NotificationCompat.MessagingStyle.Message(sentMessage.text, sentMessage.date.time, me))
if ((!subject.isAnybodyListeningForMessages() || application.currentChat == null || !application.currentChat.equals(device.address)) && justRepliedFromNotification) {
view.showNewMessageNotification(message.body, currentConversation?.displayName,
device.name, device.address, shallowHistory, preferences.isSoundEnabled())
justRepliedFromNotification = false
}
launch(uiContext) { subject.handleMessageSent(sentMessage) }
currentConversation?.let {
shortcutManager.addConversationShortcut(sentMessage.deviceAddress, it.displayName, it.color)
}
}
}
}
private fun onMessageReceived(messageBody: String) {
val message = Message(messageBody)
if (message.type == Contract.MessageType.MESSAGE && currentSocket != null) {
handleReceivedMessage(message.uid, message.body)
} else if (message.type == Contract.MessageType.DELIVERY) {
if (message.flag) {
subject.handleMessageDelivered(message.uid)
} else {
subject.handleMessageNotDelivered(message.uid)
}
} else if (message.type == Contract.MessageType.SEEING) {
if (message.flag) {
subject.handleMessageSeen(message.uid)
}
} else if (message.type == Contract.MessageType.CONNECTION_RESPONSE) {
if (message.flag) {
handleConnectionApproval(message)
} else {
connectionState = ConnectionState.REJECTED
prepareForAccept()
subject.handleConnectionRejected()
}
} else if (message.type == Contract.MessageType.CONNECTION_REQUEST && currentSocket != null) {
if (message.flag) {
handleConnectionRequest(message)
} else {
disconnect()
subject.handleDisconnected()
}
} else if (message.type == Contract.MessageType.FILE_CANCELED) {
dataTransferThread?.cancelFileTransfer()
}
}
private fun onMessageSendingFailed() {
subject.handleMessageSendingFailed()
}
private fun handleReceivedMessage(uid: Long, text: String) = currentSocket?.let { socket ->
val device: BluetoothDevice = socket.remoteDevice
val receivedMessage = ChatMessage(uid, device.address, Date(), false, text)
val partner = Person.Builder().setName(currentConversation?.displayName ?: "?").build()
shallowHistory.add(NotificationCompat.MessagingStyle.Message(
receivedMessage.text, receivedMessage.date.time, partner))
if (!subject.isAnybodyListeningForMessages() || application.currentChat == null || !application.currentChat.equals(device.address)) {
view.showNewMessageNotification(text, currentConversation?.displayName,
device.name, device.address, shallowHistory, preferences.isSoundEnabled())
} else {
receivedMessage.seenHere = true
}
launch(bgContext) {
messagesStorage.insertMessage(receivedMessage)
launch(uiContext) { subject.handleMessageReceived(receivedMessage) }
currentConversation?.let {
shortcutManager.addConversationShortcut(device.address, it.displayName, it.color)
}
}
}
private fun handleConnectionRequest(message: Message) = currentSocket?.let { socket ->
val device: BluetoothDevice = socket.remoteDevice
val parts = message.body.split(Contract.DIVIDER)
val conversation = Conversation(device.address, device.name
?: "?", parts[0], parts[1].toInt())
launch(bgContext) { conversationStorage.insertConversation(conversation) }
currentConversation = conversation
contract setupWith if (parts.size >= 3) parts[2].trim().toInt() else 0
subject.handleConnectedIn(conversation)
if (!application.isConversationsOpened && !(application.currentChat != null && application.currentChat.equals(device.address))) {
view.showConnectionRequestNotification(
"${conversation.displayName} (${conversation.deviceName})", conversation.deviceAddress, preferences.isSoundEnabled())
}
}
private fun handleConnectionApproval(message: Message) = currentSocket?.let { socket ->
val device: BluetoothDevice = socket.remoteDevice
val parts = message.body.split(Contract.DIVIDER)
val conversation = Conversation(device.address, device.name
?: "?", parts[0], parts[1].toInt())
launch(bgContext) { conversationStorage.insertConversation(conversation) }
currentConversation = conversation
contract setupWith if (parts.size >= 3) parts[2].trim().toInt() else 0
connectionState = ConnectionState.CONNECTED
subject.handleConnectionAccepted()
subject.handleConnectedOut(conversation)
}
private fun connectionLost() {
currentSocket = null
currentConversation = null
contract.reset()
if (isConnectedOrPending()) {
launch {
if (isPending() && connectionType == ConnectionType.INCOMING) {
connectionState = ConnectionState.NOT_CONNECTED
subject.handleConnectionWithdrawn()
} else {
connectionState = ConnectionState.NOT_CONNECTED
subject.handleConnectionLost()
}
prepareForAccept()
}
} else {
prepareForAccept()
}
}
private fun getImageSize(path: String): Size {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeFile(path, options)
return Size(options.outWidth, options.outHeight)
}
private inner class AcceptJob : Thread() {
private var serverSocket: BluetoothServerSocket? = null
init {
try {
serverSocket = BluetoothAdapter.getDefaultAdapter()
?.listenUsingRfcommWithServiceRecord(blAppName, blAppUUID)
} catch (e: IOException) {
e.printStackTrace()
}
connectionState = ConnectionState.LISTENING
}
override fun run() {
while (!isConnectedOrPending()) {
try {
serverSocket?.accept()?.let { socket ->
when (connectionState) {
ConnectionState.LISTENING, ConnectionState.CONNECTING -> {
connected(socket, ConnectionType.INCOMING)
}
ConnectionState.NOT_CONNECTED, ConnectionState.CONNECTED, ConnectionState.PENDING, ConnectionState.REJECTED -> try {
socket.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
} catch (e: IOException) {
e.printStackTrace()
break
}
}
}
fun cancel() {
try {
serverSocket?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
private inner class ConnectJob(private val bluetoothDevice: BluetoothDevice) : Thread() {
private var socket: BluetoothSocket? = null
override fun run() {
try {
socket = bluetoothDevice.createRfcommSocketToServiceRecord(blAppUUID)
} catch (e: IOException) {
e.printStackTrace()
}
connectionState = ConnectionState.CONNECTING
try {
socket?.connect()
} catch (connectException: IOException) {
connectException.printStackTrace()
try {
socket?.close()
} catch (e: IOException) {
e.printStackTrace()
}
connectionFailed()
return
}
synchronized(this@ConnectionController) {
connectThread = null
}
socket?.let {
connected(it, ConnectionType.OUTCOMING)
}
}
fun cancel() {
try {
socket?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
| apache-2.0 | 34df1ee9d42c35c659291f58726cf202 | 35.071629 | 182 | 0.586692 | 6.088905 | false | false | false | false |
allotria/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/modifiers.kt | 3 | 8354 | // 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.
@file:JvmName("GrModifierListUtil")
package org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.modifiers
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiModifierListOwner
import com.intellij.psi.util.parentOfType
import org.jetbrains.annotations.NonNls
import org.jetbrains.plugins.groovy.config.GroovyConfigUtils
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier.GrModifierConstant
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierFlags
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArrayInitializer
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrEnumTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrEnumConstant
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.modifiers.GrModifierListImpl.NAME_TO_MODIFIER_FLAG_MAP
import org.jetbrains.plugins.groovy.lang.psi.impl.findDeclaredDetachedValue
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.typedef.GrTypeDefinitionImpl
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil.isInterface
import org.jetbrains.plugins.groovy.transformations.immutable.hasImmutableAnnotation
private val visibilityModifiers = setOf(PsiModifier.PUBLIC, PsiModifier.PROTECTED, PsiModifier.PACKAGE_LOCAL, PsiModifier.PRIVATE)
private const val explicitVisibilityModifiersMask = GrModifierFlags.PUBLIC_MASK or GrModifierFlags.PRIVATE_MASK or GrModifierFlags.PROTECTED_MASK
private const val packageScopeAnno = "groovy.transform.PackageScope"
private const val packageScopeTarget = "groovy.transform.PackageScopeTarget"
fun Int.hasMaskModifier(@GrModifierConstant @NonNls name: String): Boolean {
return and(NAME_TO_MODIFIER_FLAG_MAP.getInt(name)) != 0
}
internal fun hasExplicitVisibilityModifiers(modifierList: GrModifierList): Boolean {
return explicitVisibilityModifiersMask and modifierList.modifierFlags != 0
}
internal fun hasExplicitModifier(modifierList: GrModifierList, @GrModifierConstant @NonNls name: String): Boolean {
return modifierList.modifierFlags.hasMaskModifier(name)
}
@JvmOverloads
internal fun hasModifierProperty(modifierList: GrModifierList, @GrModifierConstant @NonNls name: String, includeSynthetic: Boolean = true): Boolean {
return hasExplicitModifier(modifierList, name) ||
hasImplicitModifier(modifierList, name) ||
(includeSynthetic && hasSyntheticModifier(modifierList, name))
}
private fun hasImplicitModifier(modifierList: GrModifierList, @GrModifierConstant @NonNls name: String): Boolean {
return when (name) {
PsiModifier.ABSTRACT -> modifierList.isAbstract()
PsiModifier.FINAL -> modifierList.isFinal()
PsiModifier.STATIC -> modifierList.isStatic()
else -> name in visibilityModifiers && name == getImplicitVisibility(modifierList)
}
}
internal fun hasCodeModifierProperty(owner : PsiModifierListOwner, @GrModifierConstant @NonNls modifierName : String) : Boolean {
return (owner.modifierList as? GrModifierList)?.let { hasModifierProperty(it, modifierName, false) } ?: false
}
private fun hasSyntheticModifier(modifierList: GrModifierList, name: String) : Boolean {
val containingTypeDefinition = modifierList.parentOfType<GrTypeDefinition>() as? GrTypeDefinitionImpl ?: return false
return containingTypeDefinition.getSyntheticModifiers(modifierList).contains(name)
}
private fun GrModifierList.isAbstract(): Boolean {
return when (val owner = parent) {
is GrMethod -> owner.isAbstractMethod()
is GrTypeDefinition -> owner.isAbstractClass()
else -> false
}
}
private fun GrMethod.isAbstractMethod(): Boolean =
containingClass?.let { it.isInterface && !GrTraitUtil.isTrait(it) } ?: false
private fun GrTypeDefinition.isAbstractClass(): Boolean {
if (isEnum) {
if (GroovyConfigUtils.getInstance().isVersionAtLeast(this, GroovyConfigUtils.GROOVY2_0)) {
return codeMethods.any { it.modifierList.hasExplicitModifier(PsiModifier.ABSTRACT) }
}
}
return isInterface
}
private fun GrModifierList.isFinal(): Boolean {
return when (val owner = parent) {
is GrTypeDefinition -> owner.isFinalClass()
is GrVariableDeclaration -> owner.isFinalField(this)
is GrEnumConstant -> true
else -> false
}
}
private fun GrTypeDefinition.isFinalClass(): Boolean {
return isEnum && codeFields.none { it is GrEnumConstant && it.initializingClass != null }
}
private fun GrVariableDeclaration.isFinalField(modifierList: GrModifierList): Boolean {
val containingClass = containingClass
return isInterface(containingClass)
|| !modifierList.hasExplicitVisibilityModifiers()
&& (containingClass?.let(::hasImmutableAnnotation) ?: false)
}
private fun GrModifierList.isStatic(): Boolean {
val owner = parent
val containingClass = when (owner) {
is GrTypeDefinition -> owner.containingClass
is GrVariableDeclaration -> owner.containingClass
is GrEnumConstant -> return true
else -> null
}
return containingClass != null && (owner is GrEnumTypeDefinition || isInterface(containingClass))
}
private fun getImplicitVisibility(grModifierList: GrModifierList): String? {
if (hasExplicitVisibilityModifiers(grModifierList)) return null
when (val owner = grModifierList.parent) {
is GrTypeDefinition -> return if (grModifierList.hasPackageScope(owner, "CLASS")) PsiModifier.PACKAGE_LOCAL else PsiModifier.PUBLIC
is GrMethod -> {
val containingClass = owner.containingClass as? GrTypeDefinition ?: return null
if (isInterface(containingClass)) return PsiModifier.PUBLIC
val targetName = if (owner.isConstructor) "CONSTRUCTORS" else "METHODS"
return if (grModifierList.hasPackageScope(containingClass, targetName)) PsiModifier.PACKAGE_LOCAL else PsiModifier.PUBLIC
}
is GrVariableDeclaration -> {
val containingClass = owner.containingClass ?: return null
if (isInterface(containingClass)) return PsiModifier.PUBLIC
return if (grModifierList.hasPackageScope(containingClass, "FIELDS")) PsiModifier.PACKAGE_LOCAL else PsiModifier.PRIVATE
}
is GrEnumConstant -> return PsiModifier.PUBLIC
else -> return null
}
}
private fun GrModifierList.hasPackageScope(clazz: GrTypeDefinition?, targetName: String): Boolean {
if (hasOwnEmptyPackageScopeAnnotation()) return true
val annotation = clazz?.modifierList?.findAnnotation(packageScopeAnno) as? GrAnnotation ?: return false
val value = annotation.findDeclaredDetachedValue(null) ?: return false // annotation without value
val scopeTargetEnum = JavaPsiFacade.getInstance(project).findClass(packageScopeTarget, resolveScope) ?: return false
val scopeTarget = scopeTargetEnum.findFieldByName(targetName, false) ?: return false
val resolved = when (value) {
is GrReferenceExpression -> value.resolve()?.let { listOf(it) } ?: emptyList()
is GrAnnotationArrayInitializer -> value.initializers.mapNotNull {
(it as? GrReferenceExpression)?.resolve()
}
else -> emptyList()
}
return scopeTarget in resolved
}
private fun GrModifierList.hasOwnEmptyPackageScopeAnnotation(): Boolean {
val annotation = findAnnotation(packageScopeAnno) ?: return false
val value = annotation.findDeclaredDetachedValue(null) ?: return true
return value is GrAnnotationArrayInitializer && value.initializers.isEmpty()
}
private val GrVariableDeclaration.containingClass get() = (parent as? GrTypeDefinitionBody)?.parent as? GrTypeDefinition
| apache-2.0 | 2885ba1ad1c8912df70ff1ca8063352e | 48.141176 | 149 | 0.795188 | 4.770988 | false | false | false | false |
Triple-T/gradle-play-publisher | play/plugin/src/test/kotlin/com/github/triplet/gradle/play/tasks/shared/ArtifactIntegrationTests.kt | 1 | 8416 | package com.github.triplet.gradle.play.tasks.shared
import com.github.triplet.gradle.common.utils.safeCreateNewFile
import com.github.triplet.gradle.play.helpers.SharedIntegrationTest
import com.github.triplet.gradle.play.helpers.SharedIntegrationTest.Companion.DEFAULT_TASK_VARIANT
import com.google.common.truth.Truth.assertThat
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.TaskOutcome.NO_SOURCE
import org.gradle.testkit.runner.TaskOutcome.SUCCESS
import org.gradle.testkit.runner.TaskOutcome.UP_TO_DATE
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
import org.junit.jupiter.params.provider.ValueSource
import java.io.File
interface ArtifactIntegrationTests : SharedIntegrationTest {
fun customArtifactName(name: String = "foo"): String
fun assertCustomArtifactResults(result: BuildResult, executed: Boolean = true)
@Test
fun `Rebuilding artifact on-the-fly uses cached build`() {
val result1 = execute("", taskName())
val result2 = execute("", taskName())
result1.requireTask(outcome = SUCCESS)
result2.requireTask(outcome = UP_TO_DATE)
}
@Test
fun `Using non-existent custom artifact skips build`() {
// language=gradle
val config = """
play {
artifactDir = file('${playgroundDir.escaped()}')
}
"""
val result = execute(config, taskName())
assertCustomArtifactResults(result, executed = false)
result.requireTask(outcome = NO_SOURCE)
}
@Test
fun `Using custom artifact skips on-the-fly build`() {
// language=gradle
val config = """
play {
artifactDir = file('${playgroundDir.escaped()}')
}
"""
File(playgroundDir, customArtifactName()).safeCreateNewFile()
val result = execute(config, taskName())
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(playgroundDir.name)
assertThat(result.output).contains(customArtifactName())
assertCustomArtifactResults(result)
}
@Test
fun `Using custom artifact file skips on-the-fly build`() {
val app = File(playgroundDir, customArtifactName()).safeCreateNewFile()
// language=gradle
val config = """
play {
artifactDir = file('${app.escaped()}')
}
"""
val result = execute(config, taskName())
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(playgroundDir.name)
assertThat(result.output).contains(customArtifactName())
assertCustomArtifactResults(result)
}
@ParameterizedTest
@CsvSource(value = [
"false,false,",
"false,true,",
"true,false,",
"true,true,",
"false,false,$DEFAULT_TASK_VARIANT",
"false,true,$DEFAULT_TASK_VARIANT",
"true,false,$DEFAULT_TASK_VARIANT",
"true,true,$DEFAULT_TASK_VARIANT"
])
fun `Using custom artifact file with supported 3P dep skips on-the-fly build`(
eager: Boolean,
cliParam: Boolean,
taskVariant: String?,
) {
val app = File(playgroundDir, customArtifactName()).safeCreateNewFile()
// language=gradle
File(appDir, "build.gradle").writeText("""
buildscript {
repositories.google()
dependencies.classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1'
}
plugins {
id 'com.android.application'
id 'com.github.triplet.play'
}
apply plugin: 'com.google.firebase.crashlytics'
android {
compileSdk 31
defaultConfig {
applicationId "com.supercilex.test"
minSdk 31
targetSdk 31
versionCode 1
versionName "1.0"
}
buildTypes.release {
shrinkResources true
minifyEnabled true
proguardFiles(getDefaultProguardFile("proguard-android.txt"))
}
}
play {
serviceAccountCredentials = file('creds.json')
${if (cliParam) "" else "artifactDir = file('${app.escaped()}')"}
}
${if (eager) "tasks.all {}" else ""}
$factoryInstallerStatement
""")
val result = executeGradle(expectFailure = false) {
withArguments(taskName(taskVariant.orEmpty()))
if (cliParam) {
withArguments(arguments + listOf("--artifact-dir=${app}"))
}
}
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(playgroundDir.name)
assertThat(result.output).contains(customArtifactName())
assertCustomArtifactResults(result)
}
@Test
fun `Reusing custom artifact uses cached build`() {
// language=gradle
val config = """
play {
artifactDir = file('${playgroundDir.escaped()}')
}
"""
File(playgroundDir, customArtifactName()).safeCreateNewFile()
val result1 = execute(config, taskName())
val result2 = execute(config, taskName())
result1.requireTask(outcome = SUCCESS)
result2.requireTask(outcome = UP_TO_DATE)
}
@Test
fun `Using custom artifact correctly tracks dependencies`() {
// language=gradle
val config = """
abstract class CustomTask extends DefaultTask {
@OutputDirectory
abstract DirectoryProperty getAppDir()
@TaskAction
void doStuff() {
appDir.get().file("${customArtifactName()}").asFile.createNewFile()
}
}
def c = tasks.register("myCustomTask", CustomTask) {
appDir.set(layout.projectDirectory.dir('${playgroundDir.escaped()}'))
}
play {
artifactDir = c.flatMap { it.appDir }
}
"""
val result = execute(config, taskName())
result.requireTask(":myCustomTask", outcome = SUCCESS)
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(playgroundDir.name)
assertThat(result.output).contains(customArtifactName())
assertCustomArtifactResults(result)
}
@ParameterizedTest
@ValueSource(strings = ["", DEFAULT_TASK_VARIANT])
fun `Using custom artifact CLI arg skips on-the-fly build`(taskVariant: String) {
File(playgroundDir, customArtifactName()).safeCreateNewFile()
val result = execute("", taskName(taskVariant), "--artifact-dir=${playgroundDir}")
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(playgroundDir.name)
assertThat(result.output).contains(customArtifactName())
assertCustomArtifactResults(result)
}
@Test
fun `Eagerly evaluated global CLI artifact-dir param skips on-the-fly build`() {
// language=gradle
val config = """
tasks.all {}
"""
File(playgroundDir, customArtifactName()).safeCreateNewFile()
val result = execute(
config,
taskName(/* No variant: */ ""),
"--artifact-dir=$playgroundDir"
)
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(playgroundDir.name)
assertCustomArtifactResults(result)
}
@Test
fun `Using custom artifact with multiple files uploads each one`() {
// language=gradle
val config = """
play {
artifactDir = file('${playgroundDir.escaped()}')
}
"""
File(playgroundDir, customArtifactName("1")).safeCreateNewFile()
File(playgroundDir, customArtifactName("2")).safeCreateNewFile()
val result = execute(config, taskName())
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(customArtifactName("1"))
assertThat(result.output).contains(customArtifactName("2"))
}
}
| mit | 5518e4f3475317b9b96dc86f2fd6ba4f | 32.52988 | 98 | 0.599453 | 5.243614 | false | true | false | false |
rizafu/CoachMark | coachmark/src/main/java/com/rizafu/coachmark/CoachMarkOverlay.kt | 1 | 1906 | package com.rizafu.coachmark
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
/**
* Created by RizaFu on 11/7/16.
*/
class CoachMarkOverlay : View {
private lateinit var paint: Paint
private var rectF: RectF? = null
private var radius: Int = 0
private var x: Int = 0
private var y: Int = 0
private var isCircle: Boolean = false
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
private fun init() {
isDrawingCacheEnabled = true
setLayerType(View.LAYER_TYPE_SOFTWARE, null)
}
fun addRect(x: Int, y: Int, width: Int, height: Int, radius: Int, padding: Int, isCircle: Boolean) {
this.isCircle = isCircle
this.radius = radius + padding
this.x = x
this.y = y
paint = Paint()
paint.isAntiAlias = true
paint.color = Color.TRANSPARENT
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
val r = x + width
val b = y + height
rectF = RectF((x - padding).toFloat(), (y - padding).toFloat(), (r + padding).toFloat(), (b + padding).toFloat())
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (isCircle) {
canvas.drawCircle(x.toFloat(), y.toFloat(), radius.toFloat(), paint)
} else {
rectF?.let { canvas.drawRoundRect(it, radius.toFloat(), radius.toFloat(), paint) }
}
}
}
| apache-2.0 | b8f9782d426112c64764e3c7dd98b13b | 26.228571 | 121 | 0.63851 | 4.07265 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/controlStructures/doWhileFib.kt | 5 | 204 | fun box(): String {
var fx = 1
var fy = 1
do {
var tmp = fy
fy = fx + fy
fx = tmp
} while (fy < 100)
return if (fy == 144) "OK" else "Fail $fx $fy"
}
| apache-2.0 | f5fdf43c7a5c5a112c4d91d7619dbb3c | 16 | 50 | 0.401961 | 3.238095 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/KotlinGradleImportingTestCase.kt | 1 | 11939 | // 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.codeInsight.gradle
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode
import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager
import com.intellij.openapi.externalSystem.task.TaskCallback
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.OrderEntry
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.VfsTestUtil
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.kotlin.idea.test.GradleProcessOutputInterceptor
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.test.AndroidStudioTestUtils
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.utils.addToStdlib.filterIsInstanceWithChecker
import org.jetbrains.plugins.gradle.importing.GradleImportingTestCase
import org.jetbrains.plugins.gradle.service.project.open.createLinkSettings
import org.jetbrains.plugins.gradle.settings.GradleSystemSettings
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.junit.Assume
import org.junit.runners.Parameterized
import java.io.File
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
@Suppress("ACCIDENTAL_OVERRIDE")
abstract class KotlinGradleImportingTestCase : GradleImportingTestCase() {
public override fun getModule(name: String?): Module = super.getModule(name)
protected open fun testDataDirName(): String = ""
protected open fun clearTextFromMarkup(text: String): String = text
protected open fun testDataDirectory(): File {
val baseDir = IDEA_TEST_DATA_DIR.resolve("gradle/${testDataDirName()}")
return File(baseDir, getTestName(true).substringBefore("_").substringBefore(" "))
}
override fun setUp() {
Assume.assumeFalse(AndroidStudioTestUtils.skipIncompatibleTestAgainstAndroidStudio())
super.setUp()
GradleSystemSettings.getInstance().gradleVmOptions =
"-XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${System.getProperty("user.dir")}"
GradleProcessOutputInterceptor.install(testRootDisposable)
}
protected open fun configureKotlinVersionAndProperties(text: String, properties: Map<String, String>? = null): String {
var result = text
(properties ?: defaultProperties).forEach { (key, value) ->
result = result.replace(Regex("""\{\s*\{\s*${key}\s*}\s*}"""), value)
}
return result
}
protected open val defaultProperties: Map<String, String> = mapOf("kotlin_plugin_version" to LATEST_STABLE_GRADLE_PLUGIN_VERSION)
protected open fun configureByFiles(properties: Map<String, String>? = null): List<VirtualFile> {
val rootDir = testDataDirectory()
assert(rootDir.exists()) { "Directory ${rootDir.path} doesn't exist" }
return rootDir.walk().mapNotNull {
when {
it.isDirectory -> null
!it.name.endsWith(AFTER_SUFFIX) -> {
val text = configureKotlinVersionAndProperties(
clearTextFromMarkup(FileUtil.loadFile(it, /* convertLineSeparators = */ true)),
properties
)
val virtualFile = createProjectSubFile(it.path.substringAfter(rootDir.path + File.separator), text)
// Real file with expected testdata allows to throw nicer exceptions in
// case of mismatch, as well as open interactive diff window in IDEA
virtualFile.putUserData(VfsTestUtil.TEST_DATA_FILE_PATH, it.absolutePath)
virtualFile
}
else -> null
}
}.toList()
}
protected fun createLocalPropertiesSubFileForAndroid() {
createProjectSubFile(
"local.properties",
"sdk.dir=/${KotlinTestUtils.getAndroidSdkSystemIndependentPath()}"
)
}
protected fun checkFiles(files: List<VirtualFile>) {
FileDocumentManager.getInstance().saveAllDocuments()
files.filter {
it.name == GradleConstants.DEFAULT_SCRIPT_NAME
|| it.name == GradleConstants.KOTLIN_DSL_SCRIPT_NAME
|| it.name == GradleConstants.SETTINGS_FILE_NAME
}
.forEach {
if (it.name == GradleConstants.SETTINGS_FILE_NAME && !File(testDataDirectory(), it.name + AFTER_SUFFIX).exists()) return@forEach
val actualText = configureKotlinVersionAndProperties(LoadTextUtil.loadText(it).toString())
val expectedFileName = if (File(testDataDirectory(), it.name + ".$gradleVersion" + AFTER_SUFFIX).exists()) {
it.name + ".$gradleVersion" + AFTER_SUFFIX
} else {
it.name + AFTER_SUFFIX
}
val expectedFile = File(testDataDirectory(), expectedFileName)
KotlinTestUtils.assertEqualsToFile(expectedFile, actualText) { s -> configureKotlinVersionAndProperties(s) }
}
}
override fun importProject(skipIndexing: Boolean?) {
AndroidStudioTestUtils.specifyAndroidSdk(File(projectPath))
super.importProject(skipIndexing)
}
protected fun importProjectFromTestData(): List<VirtualFile> {
val files = configureByFiles()
importProject()
return files
}
protected fun getSourceRootInfos(moduleName: String): List<Pair<String, JpsModuleSourceRootType<*>>> {
return ModuleRootManager.getInstance(getModule(moduleName)).contentEntries.flatMap { contentEntry ->
contentEntry.sourceFolders.map { sourceFolder ->
sourceFolder.url.replace(projectPath, "") to sourceFolder.rootType
}
}
}
override fun handleImportFailure(errorMessage: String, errorDetails: String?) {
val gradleOutput = GradleProcessOutputInterceptor.getInstance()?.getOutput().orEmpty()
// Typically Gradle error message consists of a line with the description of the error followed by
// a multi-line stacktrace. The idea is to cut off the stacktrace if it is already contained in
// the intercepted Gradle process output to avoid unnecessary verbosity.
val compactErrorMessage = when (val indexOfNewLine = errorMessage.indexOf('\n')) {
-1 -> errorMessage
else -> {
val compactErrorMessage = errorMessage.substring(0, indexOfNewLine)
val theRest = errorMessage.substring(indexOfNewLine + 1)
if (theRest in gradleOutput) compactErrorMessage else errorMessage
}
}
val failureMessage = buildString {
append("Gradle import failed: ").append(compactErrorMessage).append('\n')
if (!errorDetails.isNullOrBlank()) append("Error details: ").append(errorDetails).append('\n')
append("Gradle process output (BEGIN):\n")
append(gradleOutput)
if (!gradleOutput.endsWith('\n')) append('\n')
append("Gradle process output (END)")
}
fail(failureMessage)
}
protected open fun assertNoModuleDepForModule(moduleName: String, depName: String) {
assertEmpty("No dependency '$depName' was expected", collectModuleDeps<ModuleOrderEntry>(moduleName, depName))
}
protected open fun assertNoLibraryDepForModule(moduleName: String, depName: String) {
assertEmpty("No dependency '$depName' was expected", collectModuleDeps<LibraryOrderEntry>(moduleName, depName))
}
private inline fun <reified T : OrderEntry> collectModuleDeps(moduleName: String, depName: String): List<T> {
return getRootManager(moduleName).orderEntries.asList().filterIsInstanceWithChecker { it.presentableName == depName }
}
protected fun linkProject(projectFilePath: String = projectPath) {
val localFileSystem = LocalFileSystem.getInstance()
val projectFile = localFileSystem.refreshAndFindFileByPath(projectFilePath)
?: error("Failed to find projectFile: $projectFilePath")
ExternalSystemUtil.linkExternalProject(
/* externalSystemId = */ GradleConstants.SYSTEM_ID,
/* projectSettings = */ createLinkSettings(projectFile.toNioPath(), myProject),
/* project = */ myProject,
/* importResultCallback = */ null,
/* isPreviewMode = */ false,
/* progressExecutionMode = */ ProgressExecutionMode.MODAL_SYNC
)
}
protected fun runTaskAndGetErrorOutput(projectPath: String, taskName: String, scriptParameters: String = ""): String {
val taskErrOutput = StringBuilder()
val stdErrListener = object : ExternalSystemTaskNotificationListenerAdapter() {
override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) {
if (!stdOut) {
taskErrOutput.append(text)
}
}
}
val notificationManager = ExternalSystemProgressNotificationManager.getInstance()
notificationManager.addNotificationListener(stdErrListener)
try {
val settings = ExternalSystemTaskExecutionSettings()
settings.externalProjectPath = projectPath
settings.taskNames = listOf(taskName)
settings.scriptParameters = scriptParameters
settings.externalSystemIdString = GradleConstants.SYSTEM_ID.id
val future = CompletableFuture<String>()
ExternalSystemUtil.runTask(settings, DefaultRunExecutor.EXECUTOR_ID, myProject, GradleConstants.SYSTEM_ID,
object : TaskCallback {
override fun onSuccess() {
future.complete(taskErrOutput.toString())
}
override fun onFailure() {
future.complete(taskErrOutput.toString())
}
}, ProgressExecutionMode.IN_BACKGROUND_ASYNC)
return future.get(10, TimeUnit.SECONDS)
}
finally {
notificationManager.removeNotificationListener(stdErrListener)
}
}
companion object {
const val AFTER_SUFFIX = ".after"
const val MINIMAL_SUPPORTED_GRADLE_PLUGIN_VERSION = "1.3.0"
const val LATEST_STABLE_GRADLE_PLUGIN_VERSION = "1.3.70"
val SUPPORTED_GRADLE_VERSIONS: List<Array<Any>> = listOf(arrayOf("4.9"), arrayOf("5.6.4"), arrayOf("6.0.1"))
@JvmStatic
@Suppress("ACCIDENTAL_OVERRIDE")
@Parameterized.Parameters(name = "{index}: with Gradle-{0}")
fun data(): Collection<Array<Any>> = SUPPORTED_GRADLE_VERSIONS
}
}
| apache-2.0 | 2b9ea3f56b268135db0dcbc0a0ce16f6 | 47.53252 | 158 | 0.673256 | 5.436703 | false | true | false | false |
kohesive/kohesive-iac | model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/codegen/AWSModelProvider.kt | 1 | 1998 | package uy.kohesive.iac.model.aws.codegen
import com.amazonaws.codegen.model.intermediate.IntermediateModel
import com.amazonaws.codegen.utils.ModelLoaderUtils
import org.reflections.Reflections
import org.reflections.scanners.ResourcesScanner
import java.util.*
import java.util.concurrent.ConcurrentHashMap
class AWSModelProvider {
companion object {
val IntermediateFilenameRegexp = "(.*)-(\\d{4}-\\d{2}-\\d{2})-intermediate\\.json".toRegex()
}
private val intermediateFiles: Set<String>
= Reflections("models", ResourcesScanner()).getResources(IntermediateFilenameRegexp.toPattern())
// Service name -> version -> file
private val serviceShortNameToVersions: Map<String, SortedMap<String, String>> by lazy {
intermediateFiles.map { filePath ->
IntermediateFilenameRegexp.find(filePath.takeLastWhile { it != '/' })?.groupValues?.let {
val serviceName = it[1]
val apiVersion = it[2].replace("-", "")
serviceName to (apiVersion to filePath)
}
}.filterNotNull().groupBy { it.first }.mapValues {
it.value.map { it.second }.toMap().toSortedMap()
}
}
private val modelCache = ConcurrentHashMap<String, IntermediateModel>()
fun getModel(service: String, apiVersion: String? = null): IntermediateModel {
return serviceShortNameToVersions[service]?.let { versionToFilepath ->
val filePath = if (apiVersion == null) {
versionToFilepath.values.first()
} else {
versionToFilepath[apiVersion.replace("-", "").replace("_", "")] ?: versionToFilepath.values.first()
}
modelCache.getOrPut(filePath) {
ModelLoaderUtils.getRequiredResourceAsStream(filePath).use { stream ->
loadModel<IntermediateModel>(stream)
}
}
} ?: throw IllegalArgumentException("Unknown service: $service")
}
} | mit | 65c35bd2bcc4eaff37b4162951b51655 | 38.196078 | 115 | 0.644645 | 4.970149 | false | false | false | false |
leafclick/intellij-community | plugins/IntelliLang/IntelliLang-tests/test/com/intellij/psi/impl/source/tree/injected/JavaInjectedFileChangesHandlerTest.kt | 1 | 31134 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.source.tree.injected
import com.intellij.codeInsight.intention.impl.QuickEditAction
import com.intellij.lang.Language
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.lang.injection.MultiHostInjector
import com.intellij.lang.injection.MultiHostRegistrar
import com.intellij.lang.injection.MultiHostRegistrarPlaceholderHelper
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.TestDialog
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.injection.Injectable
import com.intellij.psi.util.parentOfType
import com.intellij.testFramework.UsefulTestCase
import com.intellij.testFramework.fixtures.InjectionTestFixture
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase
import com.intellij.util.SmartList
import com.intellij.util.ui.UIUtil
import junit.framework.TestCase
import org.intellij.plugins.intelliLang.StoringFixPresenter
import org.intellij.plugins.intelliLang.inject.InjectLanguageAction
import org.intellij.plugins.intelliLang.inject.UnInjectLanguageAction
import org.jetbrains.uast.expressions.UStringConcatenationsFacade
class JavaInjectedFileChangesHandlerTest : JavaCodeInsightFixtureTestCase() {
fun `test edit multiline in fragment-editor`() {
with(myFixture) {
configureByText("classA.java", """
class A {
void foo() {
String a = "{\"bca\":<caret> \n" +
"1}";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("JSON")
TestCase.assertEquals("{\"bca\": \n1}", fragmentFile.text)
fragmentFile.edit { insertString(text.indexOf(":"), "\n") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\"\n" +
": \n" +
"1}";
}
}
""".trimIndent())
}
}
fun `test temp injection survive on host death and no edit in uninjected`() {
with(myFixture) {
configureByText("classA.java", """
class A {
void foo() {
String a = "{\"bca\":<caret> \n1}";
}
}
""".trimIndent())
InjectLanguageAction.invokeImpl(project,
myFixture.editor,
myFixture.file,
Injectable.fromLanguage(Language.findLanguageByID("JSON")))
val quickEditHandler = QuickEditAction().invokeImpl(project, editor, file)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals("{\"bca\": \n1}", fragmentFile.text)
injectionTestFixture.assertInjectedLangAtCaret("JSON")
fragmentFile.edit { insertString(text.indexOf(":"), "\n") }
checkResult("""
class A {
void foo() {
String a = "{\"bca\"\n" +
": \n" +
"1}";
}
}
""".trimIndent())
injectionTestFixture.assertInjectedLangAtCaret("JSON")
UnInjectLanguageAction.invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
injectionTestFixture.assertInjectedLangAtCaret(null)
TestCase.assertFalse(quickEditHandler.isValid)
fragmentFile.edit { insertString(text.indexOf(":"), " ") }
checkResult("""
class A {
void foo() {
String a = "{\"bca\"\n" +
": \n" +
"1}";
}
}
""".trimIndent())
}
}
fun `test delete in multiple hosts`() {
with(myFixture) {
configureByText("classA.java", """
class A {
void foo() {
String a = "<html>line\n" +
"anotherline<caret>\n" +
"finalLine</html>";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("HTML")
TestCase.assertEquals("<html>line\nanotherline\nfinalLine</html>", fragmentFile.text)
fragmentFile.edit {
findAndDelete("ne\nanot")
}
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("HTML") String a = "<html>li" +
"herline\n" +
"finalLine</html>";
}
}
""".trimIndent())
}
}
fun `test edit multipart in 4 steps`() {
with(myFixture) {
configureByText("classA.java", """
class A {
void foo() {
String a = "{\"a\"<caret>: 1}";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("JSON")
TestCase.assertEquals("{\"a\": 1}", fragmentFile.text)
fragmentFile.edit { insertString(text.indexOf("a"), "bc") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\": 1}";
}
}
""".trimIndent())
injectionTestFixture.assertInjectedLangAtCaret("JSON")
fragmentFile.edit { insertString(text.indexOf("1"), "\n") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\": \n" +
"1}";
}
}
""".trimIndent(), true)
injectionTestFixture.assertInjectedLangAtCaret("JSON")
fragmentFile.edit { insertString(text.indexOf(":"), "\n") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\"\n" +
": \n" +
"1}";
}
}
""".trimIndent(), true)
injectionTestFixture.assertInjectedLangAtCaret("JSON")
TestCase.assertEquals("{\"bca\"\n: \n1}", fragmentFile.text)
fragmentFile.edit { deleteString(0, textLength) }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "";
}
}
""".trimIndent(), true)
injectionTestFixture.assertInjectedLangAtCaret("JSON")
}
}
fun `test delete-insert-delete`() {
with(myFixture) {
configureByText("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\"<caret>\n" +
": \n" +
"1}";
}
}
""".trimIndent())
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals("{\"bca\"\n: \n1}", fragmentFile.text)
fragmentFile.edit { deleteString(0, textLength) }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "";
}
}
""".trimIndent(), true)
TestCase.assertEquals("", fragmentFile.text)
fragmentFile.edit { insertString(0, "{\"bca\"\n: \n1}") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\"\n" +
": \n" +
"1}";
}
}
""".trimIndent(), true)
TestCase.assertEquals("{\"bca\"\n: \n1}", fragmentFile.text)
fragmentFile.edit { deleteString(0, textLength) }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "";
}
}
""".trimIndent(), true)
TestCase.assertEquals("", fragmentFile.text)
fragmentFile.edit { insertString(0, "{\"bca\"\n: \n1}") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\"\n" +
": \n" +
"1}";
}
}
""".trimIndent(), true)
TestCase.assertEquals("{\"bca\"\n: \n1}", fragmentFile.text)
fragmentFile.edit { deleteString(0, textLength) }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "";
}
}
""".trimIndent(), true)
}
}
fun `test complex insert-commit-broken-reformat`() {
with(myFixture) {
configureByText("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON")
String a = "{\n" +
" \"field1\": 1,\n" +
" \"innerMap1" +
"\": {\n" +
" " +
"\"field2\": 1,\n" +
" " +
" \"field3\": 3<caret>\n" +
" " +
"}\n" +
"}";
}
}
""".trimIndent())
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals("{\n" +
" \"field1\": 1,\n" +
" \"innerMap1\": {\n" +
" \"field2\": 1,\n" +
" \"field3\": 3\n" +
" }\n" +
"}",
fragmentFile.text)
fragmentFile.edit("insert json") {
val pos = text.indexAfter("\"field3\": 3")
replaceString(pos - 1, pos, "\"brokenInnerMap\": {\n" +
" \"broken1\": 1,\n" +
" \"broken2\": 2,\n" +
" \"broken3\": 3\n" +
" }")
}
PsiDocumentManager.getInstance(project).commitAllDocuments()
fragmentFile.edit("reformat") {
CodeStyleManager.getInstance(psiManager).reformatRange(
fragmentFile, 0, fragmentFile.textLength, false)
}
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON")
String a = "{\n" +
" \"field1\": 1,\n" +
" \"innerMap1" +
"\": {\n" +
" " +
"\"field2\": 1,\n" +
" " +
" \"field3\": \"brokenInnerMap\"\n" +
" : {\n" +
" \"broken1\": 1,\n" +
" \"broken2\": 2,\n" +
" \"broken3\": 3\n" +
"}\n" +
"}\n" +
"}";
}
}
""".trimIndent(), true)
TestCase.assertEquals("""
{
"field1": 1,
"innerMap1": {
"field2": 1,
"field3": "brokenInnerMap"
: {
"broken1": 1,
"broken2": 2,
"broken3": 3
}
}
}
""".trimIndent(), fragmentFile.text)
}
}
fun `test suffix-prefix-edit-reformat`() {
with(myFixture) {
configureByText("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language(value = "JSON", prefix = "{\n", suffix = "\n}\n}")
String a =
" \"field1\": 1,\n<caret>" +
" \"container\": {\n" +
" \"innerField\": 2";
}
}
""".trimIndent())
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals("""
{
"field1": 1,
"container": {
"innerField": 2
}
}
""".trimIndent(), fragmentFile.text)
openFileInEditor(fragmentFile.virtualFile)
editor.caretModel.moveToOffset(fragmentFile.text.indexAfter("\"innerField\": 2"))
type("\n\"anotherInnerField\": 3")
PsiDocumentManager.getInstance(project).commitAllDocuments()
TestCase.assertEquals("""
{
"field1": 1,
"container": {
"innerField": 2,
"anotherInnerField": 3
}
}
""".trimIndent(), fragmentFile.text)
fragmentFile.edit("reformat") {
CodeStyleManager.getInstance(psiManager).reformatRange(
fragmentFile, 0, fragmentFile.textLength, false)
}
checkResult("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language(value = "JSON", prefix = "{\n", suffix = "\n}\n}")
String a =
" \"field1\": 1,\n" +
" \"container\": {\n" +
" \"innerField\": 2,\n" +
" \"anotherInnerField\": 3";
}
}
""".trimIndent(), true)
TestCase.assertEquals("""
{
"field1": 1,
"container": {
"innerField": 2,
"anotherInnerField": 3
}
}
""".trimIndent(), fragmentFile.text)
}
}
fun `test text block trim indent`() {
with(myFixture) {
configureByText("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
@Language("HTML")
String s = ""${'"'}
<html>
<body>
<h1>title</h1>
<p>
this is a test.<caret>
</p>
</body>
</html>""${'"'};
}
""".trimIndent())
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals(
"""|<html>
| <body>
| <h1>title</h1>
| <p>
| this is a test.
| </p>
| </body>
|</html>""".trimMargin(), fragmentFile.text)
}
}
fun `test delete-commit-delete`() {
with(myFixture) {
configureByText("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON")
String a = "{\n" +
" \"field1\": 1,\n" +
" \"container\"<caret>: {\n" +
" \"innerField\": 2\n" +
" }\n" +
"}";
}
}
""".trimIndent())
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals("""
{
"field1": 1,
"container": {
"innerField": 2
}
}
""".trimIndent(), fragmentFile.text)
fragmentFile.edit("delete json") {
findAndDelete(" \"container\": {\n \"innerField\": 2\n }")
}
PsiDocumentManager.getInstance(project).commitAllDocuments()
fragmentFile.edit("delete again") {
val pos = text.indexAfter("1,\n")
deleteString(pos - 1, pos)
}
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON")
String a = "{\n" +
" \"field1\": 1,\n" +
"}";
}
}
""".trimIndent(), true)
TestCase.assertEquals("""
{
"field1": 1,
}
""".trimIndent(), fragmentFile.text)
}
}
fun `test delete empty line`() {
with(myFixture) {
configureByText("classA.java", """
class A {
void foo() {
String a = "<html>line\n<caret>" +
"\n" +
"finalLine</html>";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("HTML")
TestCase.assertEquals("<html>line\n\nfinalLine</html>", fragmentFile.text)
fragmentFile.edit {
findAndDelete("\n")
}
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("HTML") String a = "<html>line\n" +
"finalLine</html>";
}
}
""".trimIndent())
fragmentFile.edit {
findAndDelete("\n")
}
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("HTML") String a = "<html>line" +
"finalLine</html>";
}
}
""".trimIndent())
}
}
fun `test type new lines in fe then delete`() {
with(myFixture) {
val hostFile = configureByText("classA.java", """
class A {
void foo() {
String a = "<html></html><caret>";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("HTML")
TestCase.assertEquals("<html></html>", fragmentFile.text)
openFileInEditor(fragmentFile.virtualFile)
assertHostIsReachable(hostFile, file)
moveCaret(fragmentFile.text.length)
type("\n")
type("\n")
checkResult("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("HTML") String a = "<html></html>\n" +
"\n";
}
}
""".trimIndent(), true)
assertHostIsReachable(hostFile, file)
type("\b")
type("\b")
checkResult("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("HTML") String a = "<html></html>";
}
}
""".trimIndent(), true)
assertHostIsReachable(hostFile, file)
}
}
private fun assertHostIsReachable(hostFile: PsiFile, injectedFile: PsiFile) {
TestCase.assertEquals("host file should be reachable from the context",
hostFile.virtualFile,
injectedFile.context?.containingFile?.virtualFile)
}
fun `test edit with guarded blocks`() {
with(myFixture) {
myFixture.configureByText("classA.java", """
class A {
void foo(String bodyText) {
String headText = "someText1";
String concatenation = "<html><head>" + headText + "</head><caret><body>" + bodyText + "</body></html>";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("HTML")
TestCase.assertEquals("<html><head>someText1</head><body>missingValue</body></html>", fragmentFile.text)
fragmentFile.edit { insertString(text.indexOf("<body>"), "someInner") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo(String bodyText) {
String headText = "someText1";
@Language("HTML") String concatenation = "<html><head>" + headText + "</head>someInner<body>" + bodyText + "</body></html>";
}
}
""".trimIndent(), true)
fragmentFile.edit { insertString(text.indexOf("<body>") + "<body>".length, "\n") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo(String bodyText) {
String headText = "someText1";
@Language("HTML") String concatenation = "<html><head>" + headText + "</head>someInner<body>\n" + bodyText + "</body></html>";
}
}
""".trimIndent())
}
}
fun `test edit guarded blocks ending`() {
with(myFixture) {
myFixture.configureByText("classA.java", """
class A {
void foo(String bodyText) {
String bodyText = "someTextInBody";
String concatenation = "<html><head></head><caret><body>" + end + "</body></html>";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("HTML")
TestCase.assertEquals("<html><head></head><body>missingValue</body></html>", fragmentFile.text)
fragmentFile.edit { findAndDelete("</body></html>") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo(String bodyText) {
String bodyText = "someTextInBody";
@Language("HTML") String concatenation = "<html><head></head><body>" + end;
}
}
""".trimIndent(), true)
fragmentFile.edit { insertString(text.indexOf("<body>") + "<body>".length, "\n") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo(String bodyText) {
String bodyText = "someTextInBody";
@Language("HTML") String concatenation = "<html><head></head><body>\n" + end;
}
}
""".trimIndent())
}
}
fun `test sequential add in fragment editor undo-repeat`() {
with(myFixture) {
val fileName = "classA.java"
val initialText = """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\n" +
" \"begin\": true,\n" +
" \"fieldstart\": -1,\n" +
" \"end\": false\n" +
"}";
}
}
""".trimIndent()
val fiveFieldsFilled = """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\n" +
" \"begin\": true,\n" +
" \"fieldstart\": -1,\n" +
" \"field0\": 0,\n" +
" \"field1\": 1,\n" +
" \"field2\": 2,\n" +
" \"field3\": 3,\n" +
" \"field4\": 4,\n" +
" \"end\": false\n" +
"}";
}
}
""".trimIndent()
configureByText(fileName, initialText)
myFixture.editor.caretModel.moveToOffset(file.text.indexAfter("-1"))
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
injectionTestFixture.assertInjectedLangAtCaret("JSON")
openFileInEditor(fragmentFile.virtualFile)
fun fillFields(num: Int) {
var shift = fragmentFile.text.indexAfter("-1,\n")
repeat(num) {
quickEditHandler.newFile.edit("add field$it") {
val s = " \"field$it\": $it,\n"
insertString(shift, s)
shift += s.length
}
}
}
fillFields(5)
PsiDocumentManager.getInstance(project).commitAllDocuments()
checkResult(fileName, fiveFieldsFilled, true)
repeat(5) {
undo(editor)
}
checkResult(fileName, initialText, true)
fillFields(5)
PsiDocumentManager.getInstance(project).commitAllDocuments()
checkResult(fileName, fiveFieldsFilled, true)
}
}
fun `test edit inner within multiple injections`() {
with(myFixture) {
InjectedLanguageManager.getInstance(project).registerMultiHostInjector(JsonMultiInjector(), testRootDisposable)
configureByText("classA.java", """
class A {
void foo() {
String injectjson = "{\n" +
" \"html\": \"<html><caret></html>\"\n" +
"}";
}
}
""".trimIndent())
injectionTestFixture.getAllInjections().map { it.second }.distinct().let { allInjections ->
UsefulTestCase.assertContainsElements(
allInjections.map { it.text },
"{\\n \\\"html\\\": \\\"HTML\\\"\\n}",
"<html></html>")
}
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals("<html></html>", fragmentFile.text)
fragmentFile.edit { insertString(text.indexOf("</html>"), " ") }
checkResult("""
class A {
void foo() {
String injectjson = "{\n" +
" \"html\": \"<html> </html>\"\n" +
"}";
}
}
""".trimIndent())
fragmentFile.edit {
val htmlBodyEnd = text.indexOf("</html>")
deleteString(htmlBodyEnd - 1, htmlBodyEnd)
}
checkResult("""
class A {
void foo() {
String injectjson = "{\n" +
" \"html\": \"<html></html>\"\n" +
"}";
}
}
""".trimIndent())
}
}
private fun injectAndOpenInFragmentEditor(language: String): PsiFile {
with(myFixture) {
StoringFixPresenter().apply {
InjectLanguageAction.invokeImpl(project,
myFixture.editor,
myFixture.file,
Injectable.fromLanguage(Language.findLanguageByID(language)),
this
)
}.process()
val quickEditHandler = QuickEditAction().invokeImpl(project, editor, file)
return quickEditHandler.newFile
}
}
private fun undo(editor: Editor) = runWithUndoManager(editor, UndoManager::undo)
private fun redo(editor: Editor) = runWithUndoManager(editor, UndoManager::redo)
private fun runWithUndoManager(editor: Editor, action: (UndoManager, TextEditor) -> Unit) {
UIUtil.invokeAndWaitIfNeeded(Runnable {
val oldTestDialog = Messages.setTestDialog(TestDialog.OK)
try {
val undoManager = UndoManager.getInstance(project)
val textEditor = TextEditorProvider.getInstance().getTextEditor(editor)
action(undoManager, textEditor)
}
finally {
Messages.setTestDialog(oldTestDialog)
}
})
}
private fun PsiFile.edit(actionName: String = "change doc", groupId: Any = actionName, docFunction: Document.() -> Unit) {
CommandProcessor.getInstance().executeCommand(project, {
ApplicationManager.getApplication().runWriteAction {
val manager = PsiDocumentManager.getInstance(project)
val document = manager.getDocument(this) ?: throw AssertionError("document is null")
document.docFunction()
}
}, actionName, groupId)
}
private fun commit() = PsiDocumentManager.getInstance(project).commitDocument(myFixture.editor.document)
private fun moveCaret(shift: Int, columnShift: Int = 0) =
myFixture.editor.caretModel.moveCaretRelatively(shift, columnShift, false, false, false)
private fun Document.findAndDelete(substring: String) {
val start = this.text.indexOf(substring)
deleteString(start, start + substring.length)
}
private val injectionTestFixture: InjectionTestFixture get() = InjectionTestFixture(myFixture)
}
private fun String.indexAfter(string: String): Int {
val r = indexOf(string)
return if (r == -1) -1 else r + string.length
}
private class JsonMultiInjector : MultiHostInjector {
private val VAR_NAME = "injectjson"
override fun getLanguagesToInject(registrar: MultiHostRegistrar, context: PsiElement) {
val concatenationsFacade = UStringConcatenationsFacade.create(context)?.takeIf { it.uastOperands.any() } ?: return
context.parentOfType<PsiVariable>()?.takeIf { it.name == VAR_NAME } ?: return
val cssReg = """"html"\s*:\s*"(.*)"""".toRegex()
val mhRegistrar = MultiHostRegistrarPlaceholderHelper(registrar)
mhRegistrar.startInjecting(Language.findLanguageByID("JSON")!!)
val cssInjections = SmartList<Pair<PsiLanguageInjectionHost, TextRange>>()
for (host in concatenationsFacade.psiLanguageInjectionHosts) {
val manipulator = ElementManipulators.getManipulator(host)
val fullRange = manipulator.getRangeInElement(host)
val escaper = host.createLiteralTextEscaper()
val decoded: CharSequence = StringBuilder().apply { escaper.decode(fullRange, this) }
val cssRanges = cssReg.find(decoded)?.groups?.get(1)?.range
?.let { TextRange.create(it.first, it.last + 1) }
?.let { cssRangeInDecoded ->
listOf(TextRange.create(
escaper.getOffsetInHost(cssRangeInDecoded.startOffset, fullRange),
escaper.getOffsetInHost(cssRangeInDecoded.endOffset, fullRange)
))
}.orEmpty()
mhRegistrar.addHostPlaces(host, cssRanges.map { it to "HTML" })
cssInjections.addAll(cssRanges.map { host to it })
}
mhRegistrar.doneInjecting()
for ((host, cssRange) in cssInjections) {
registrar.startInjecting(Language.findLanguageByID("HTML")!!)
registrar.addPlace(null, null, host, cssRange)
registrar.doneInjecting()
}
}
override fun elementsToInjectIn() = listOf(PsiElement::class.java)
}
| apache-2.0 | 262c9f886dc4bbb2d1e4bc76cdbb8349 | 30.544073 | 140 | 0.525792 | 4.942689 | false | true | false | false |
siosio/intellij-community | plugins/devkit/devkit-core/src/actions/NewMessageBundleAction.kt | 2 | 8154 | // 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
import com.intellij.ide.actions.CreateElementActionBase
import com.intellij.ide.actions.CreateTemplateInPackageAction
import com.intellij.ide.actions.JavaCreateTemplateInPackageAction
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.UpdateInBackground
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import com.intellij.util.xml.DomManager
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.dom.IdeaPlugin
import org.jetbrains.idea.devkit.module.PluginModuleType
import org.jetbrains.idea.devkit.util.DescriptorUtil
import org.jetbrains.idea.devkit.util.PsiUtil
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.java.JavaResourceRootType
import java.util.function.Consumer
import java.util.function.Predicate
class NewMessageBundleAction : CreateElementActionBase(), UpdateInBackground {
override fun invokeDialog(project: Project, directory: PsiDirectory, elementsConsumer: Consumer<Array<PsiElement>>) {
val module = ModuleUtilCore.findModuleForPsiElement(directory) ?: return
if (module.name.endsWith(".impl") && ModuleManager.getInstance(project).findModuleByName(module.name.removeSuffix(".impl")) != null) {
Messages.showErrorDialog(project, DevKitBundle.message(
"action.DevKit.NewMessageBundle.error.message.do.not.put.bundle.to.impl.module"), errorTitle)
return
}
val validator = MyInputValidator(project, directory)
val defaultName = generateDefaultBundleName(module)
val result = Messages.showInputDialog(project, DevKitBundle.message("action.DevKit.NewMessageBundle.label.bundle.name"),
DevKitBundle.message("action.DevKit.NewMessageBundle.title.create.new.message.bundle"), null,
defaultName, validator)
if (result != null) {
elementsConsumer.accept(validator.createdElements)
}
}
override fun create(newName: String, directory: PsiDirectory): Array<PsiElement> {
val bundleClass = DevkitActionsUtil.createSingleClass(newName, "MessageBundle.java", directory)
val module = ModuleUtilCore.findModuleForPsiElement(directory) ?: return emptyArray()
val pluginXml = PluginModuleType.getPluginXml(module)
if (pluginXml != null) {
DescriptorUtil.patchPluginXml({ xmlFile, psiClass ->
val fileElement = DomManager.getDomManager(module.project).getFileElement(xmlFile,
IdeaPlugin::class.java)
if (fileElement != null) {
val resourceBundle = fileElement.rootElement.resourceBundle
if (!resourceBundle.exists()) {
resourceBundle.value = "messages.$newName"
}
}
}, bundleClass, pluginXml)
}
val resourcesRoot = getOrCreateResourcesRoot(module)
if (resourcesRoot == null) return arrayOf(bundleClass)
val propertiesFile = runWriteAction {
val messagesDirName = "messages"
val messagesDir = resourcesRoot.findSubdirectory(messagesDirName) ?: resourcesRoot.createSubdirectory(messagesDirName)
messagesDir.createFile("$newName.properties")
}
return arrayOf(bundleClass, propertiesFile)
}
private fun getOrCreateResourcesRoot(module: Module): PsiDirectory? {
fun reportError(@Nls message: String): Nothing? {
val notification =
Notification("DevKit Errors",
DevKitBundle.message("action.DevKit.NewMessageBundle.notification.title.cannot.create.resources.root.for.properties.file"),
DevKitBundle.message("action.DevKit.NewMessageBundle.notification.content.cannot.create.resources.root.for.properties.file",
message),
NotificationType.ERROR)
Notifications.Bus.notify(notification, module.project)
return null
}
fun createResourcesRoot(): VirtualFile? {
val contentRoot = ModuleRootManager.getInstance(module).contentRoots.singleOrNull()
?: return reportError(DevKitBundle.message("action.DevKit.NewMessageBundle.error.message.multiple.content.roots.for.module", module.name))
@NonNls val resourcesDirName = "resources"
if (contentRoot.findChild(resourcesDirName) != null) {
return reportError(DevKitBundle.message("action.DevKit.NewMessageBundle.error.message.folder.already.exists",
resourcesDirName, contentRoot.path))
}
if (ProjectFileIndex.getInstance(module.project).isInSource(contentRoot)) {
return reportError(DevKitBundle.message("action.DevKit.NewMessageBundle.error.message.under.sources.root", contentRoot.path))
}
return runWriteAction {
val resourcesDir = contentRoot.createChildDirectory(this, resourcesDirName)
ModuleRootModificationUtil.updateModel(module) {
it.contentEntries.single().addSourceFolder(resourcesDir, JavaResourceRootType.RESOURCE)
}
resourcesDir
}
}
val resourcesRoot = ModuleRootManager.getInstance(module).getSourceRoots(JavaResourceRootType.RESOURCE).firstOrNull()
?: createResourcesRoot()
?: return null
return PsiManager.getInstance(module.project).findDirectory(resourcesRoot)
}
override fun isAvailable(dataContext: DataContext): Boolean {
if (!super.isAvailable(dataContext)) {
return false
}
if (!PsiUtil.isIdeaProject(dataContext.getData(CommonDataKeys.PROJECT))) return false
return CreateTemplateInPackageAction.isAvailable(dataContext, JavaModuleSourceRootTypes.SOURCES,
Predicate { JavaCreateTemplateInPackageAction.doCheckPackageExists(it) })
}
override fun startInWriteAction(): Boolean {
return false
}
override fun getErrorTitle(): String {
return DevKitBundle.message("action.DevKit.NewMessageBundle.error.title.cannot.create.new.message.bundle")
}
override fun getActionName(directory: PsiDirectory?, newName: String?): String {
return DevKitBundle.message("action.DevKit.NewMessageBundle.action.name.create.new.message.bundle", newName)
}
}
@Suppress("HardCodedStringLiteral")
internal fun generateDefaultBundleName(module: Module): String {
val nameWithoutPrefix = module.name.removePrefix("intellij.").removeSuffix(".impl")
val commonGroupNames = listOf("platform", "vcs", "tools", "clouds")
val commonPrefix = commonGroupNames.find { nameWithoutPrefix.startsWith("$it.") }
val shortenedName = if (commonPrefix != null) nameWithoutPrefix.removePrefix("$commonPrefix.") else nameWithoutPrefix
return shortenedName.split(".").joinToString("") { StringUtil.capitalize(it) } + "Bundle"
}
| apache-2.0 | 28c11a49d6c2e758678d17209229278a | 52.644737 | 162 | 0.714251 | 5.193631 | false | false | false | false |
Zhouzhouzhou/AndroidDemo | app/src/main/java/com/zhou/android/kotlin/AnimRecyclerActivity.kt | 1 | 4469 | package com.zhou.android.kotlin
import android.content.Context
import android.graphics.Canvas
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import com.zhou.android.R
import com.zhou.android.common.BaseActivity
import com.zhou.android.common.CommonRecyclerAdapter
import com.zhou.android.common.PaddingItemDecoration
import kotlinx.android.synthetic.main.activity_recycler_view.*
import java.util.*
/**
* 长按拖拽 RV
* Created by mxz on 2020/5/29.
*/
class AnimRecyclerActivity : BaseActivity() {
private val data = arrayListOf<String>()
private lateinit var simpleAdapter: CommonRecyclerAdapter<String, CommonRecyclerAdapter.ViewHolder>
override fun setContentView() {
setContentView(R.layout.activity_recycler_view)
}
override fun init() {
for (i in 1..40) {
data.add("example $i")
}
simpleAdapter = object : CommonRecyclerAdapter<String, CommonRecyclerAdapter.ViewHolder>(this, data) {
override fun onBind(holder: ViewHolder, item: String, pos: Int) {
holder.getView<TextView>(R.id.text).text = item
}
override fun getViewHolder(context: Context, parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.layout_shape_text, parent, false)
return ViewHolder(view)
}
}
recyclerView.apply {
layoutManager = LinearLayoutManager(this@AnimRecyclerActivity, LinearLayoutManager.VERTICAL, false)
addItemDecoration(PaddingItemDecoration(this@AnimRecyclerActivity, 20, 12, 20, 0))
adapter = simpleAdapter
}
val itemHelper = ItemTouchHelper(object : ItemTouchHelper.Callback() {
override fun getMovementFlags(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?): Int {
return makeMovementFlags(ItemTouchHelper.UP.or(ItemTouchHelper.DOWN),
ItemTouchHelper.LEFT)
}
override fun onMove(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?): Boolean {
simpleAdapter.notifyItemMoved(viewHolder?.adapterPosition
?: 0, target?.adapterPosition ?: 0)
Collections.swap(data, viewHolder?.adapterPosition ?: 0, target?.adapterPosition
?: 0)
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder?, direction: Int) {
val p = viewHolder?.adapterPosition ?: 0
data.removeAt(p)
simpleAdapter.notifyItemRemoved(p)
}
override fun canDropOver(recyclerView: RecyclerView?, current: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?) = true
override fun isLongPressDragEnabled(): Boolean = true
override fun isItemViewSwipeEnabled(): Boolean = true
override fun clearView(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?) {
super.clearView(recyclerView, viewHolder)
viewHolder?.itemView?.apply {
scaleX = 1.0f
scaleY = 1.0f
}
}
override fun onChildDraw(c: Canvas?, recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
viewHolder?.itemView?.apply {
if (isCurrentlyActive) {
translationX = 60f
scaleX = 1.2f
scaleY = 1.2f
} else {
translationX = 0f
scaleX = 1.0f
scaleY = 1.0f
}
}
} else
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
})
itemHelper.attachToRecyclerView(recyclerView)
}
override fun addListener() {
}
} | mit | cb5bbe0bbd8d44c1c598db0b9a13d6b7 | 38.140351 | 185 | 0.613988 | 5.433618 | false | false | false | false |
siosio/intellij-community | platform/lang-impl/src/com/intellij/ide/actions/searcheverywhere/ml/SearchEverywhereMLStatisticsCollector.kt | 1 | 7526 | // 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.actions.searcheverywhere.ml
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereFoundElementInfo
import com.intellij.ide.actions.searcheverywhere.ml.SearchEverywhereMlSessionService.Companion.RECORDER_CODE
import com.intellij.ide.util.gotoByName.GotoActionModel
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.StatisticsEventLogProviderUtil
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.project.Project
import com.intellij.util.concurrency.NonUrgentExecutor
import kotlin.math.round
internal class SearchEverywhereMLStatisticsCollector {
private val loggerProvider = StatisticsEventLogProviderUtil.getEventLogProvider(RECORDER_CODE)
fun onItemSelected(project: Project?, seSessionId: Int, searchIndex: Int,
experimentGroup: Int, orderByMl: Boolean,
elementIdProvider: SearchEverywhereMlItemIdProvider,
context: SearchEverywhereMLContextInfo,
cache: SearchEverywhereMlSearchState,
selectedIndices: IntArray,
closePopup: Boolean,
elementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
val data = arrayListOf<Pair<String, Any>>(
CLOSE_POPUP_KEY to closePopup,
EXPERIMENT_GROUP to experimentGroup,
ORDER_BY_ML_GROUP to orderByMl
)
reportElements(project, SESSION_FINISHED, seSessionId, searchIndex, elementIdProvider, context, cache, data, selectedIndices, elementsProvider)
}
fun onSearchFinished(project: Project?, seSessionId: Int, searchIndex: Int,
experimentGroup: Int, orderByMl: Boolean,
elementIdProvider: SearchEverywhereMlItemIdProvider,
context: SearchEverywhereMLContextInfo,
cache: SearchEverywhereMlSearchState,
elementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
val additional = listOf(
CLOSE_POPUP_KEY to true,
EXPERIMENT_GROUP to experimentGroup,
ORDER_BY_ML_GROUP to orderByMl
)
reportElements(project, SESSION_FINISHED, seSessionId, searchIndex, elementIdProvider, context, cache, additional, EMPTY_ARRAY, elementsProvider)
}
fun onSearchRestarted(project: Project?, seSessionId: Int, searchIndex: Int,
elementIdProvider: SearchEverywhereMlItemIdProvider,
context: SearchEverywhereMLContextInfo,
cache: SearchEverywhereMlSearchState,
elementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
reportElements(project, SEARCH_RESTARTED, seSessionId, searchIndex, elementIdProvider, context, cache, emptyList(), EMPTY_ARRAY, elementsProvider)
}
private fun reportElements(project: Project?, eventId: String,
seSessionId: Int, searchIndex: Int,
elementIdProvider: SearchEverywhereMlItemIdProvider,
context: SearchEverywhereMLContextInfo,
state: SearchEverywhereMlSearchState,
additional: List<Pair<String, Any>>,
selectedElements: IntArray,
elementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
val elements = elementsProvider.invoke()
NonUrgentExecutor.getInstance().execute {
val data = hashMapOf<String, Any>()
data[PROJECT_OPENED_KEY] = project != null
data[SESSION_ID_LOG_DATA_KEY] = seSessionId
data[SEARCH_INDEX_DATA_KEY] = searchIndex
data[TOTAL_NUMBER_OF_ITEMS_DATA_KEY] = elements.size
data[SE_TAB_ID_KEY] = state.tabId
data[SEARCH_START_TIME_KEY] = state.searchStartTime
data[TYPED_SYMBOL_KEYS] = state.keysTyped
data[TYPED_BACKSPACES_DATA_KEY] = state.backspacesTyped
data[REBUILD_REASON_KEY] = state.searchStartReason
data.putAll(additional)
data.putAll(context.features)
if (selectedElements.isNotEmpty()) {
data[SELECTED_INDEXES_DATA_KEY] = selectedElements.map { it.toString() }
data[SELECTED_ELEMENTS_DATA_KEY] = selectedElements.map {
if (it < elements.size) {
val element = elements[it].element
if (element is GotoActionModel.MatchedValue) {
return@map elementIdProvider.getId(element)
}
}
return@map -1
}
}
val actionManager = ActionManager.getInstance()
data[COLLECTED_RESULTS_DATA_KEY] = elements.take(REPORTED_ITEMS_LIMIT).map {
val result: HashMap<String, Any> = hashMapOf(
CONTRIBUTOR_ID_KEY to it.contributor.searchProviderId
)
if (it.element is GotoActionModel.MatchedValue) {
val elementId = elementIdProvider.getId(it.element)
val itemInfo = state.getElementFeatures(elementId, it.element, it.contributor, state.queryLength)
if (itemInfo.features.isNotEmpty()) {
result[FEATURES_DATA_KEY] = itemInfo.features
}
state.getMLWeightIfDefined(elementId)?.let { score ->
result[ML_WEIGHT_KEY] = roundDouble(score)
}
itemInfo.id.let { id ->
result[ID_KEY] = id
}
if (it.element.value is GotoActionModel.ActionWrapper) {
val action = it.element.value.action
result[ACTION_ID_KEY] = actionManager.getId(action) ?: action.javaClass.name
}
}
result
}
loggerProvider.logger.logAsync(GROUP, eventId, data, false)
}
}
companion object {
private val GROUP = EventLogGroup("mlse.log", 5)
private val EMPTY_ARRAY = IntArray(0)
private const val REPORTED_ITEMS_LIMIT = 100
// events
private const val SESSION_FINISHED = "sessionFinished"
private const val SEARCH_RESTARTED = "searchRestarted"
private const val ORDER_BY_ML_GROUP = "orderByMl"
private const val EXPERIMENT_GROUP = "experimentGroup"
// context fields
private const val PROJECT_OPENED_KEY = "projectOpened"
private const val SE_TAB_ID_KEY = "seTabId"
private const val CLOSE_POPUP_KEY = "closePopup"
private const val SEARCH_START_TIME_KEY = "startTime"
private const val REBUILD_REASON_KEY = "rebuildReason"
private const val SESSION_ID_LOG_DATA_KEY = "sessionId"
private const val SEARCH_INDEX_DATA_KEY = "searchIndex"
private const val TYPED_SYMBOL_KEYS = "typedSymbolKeys"
private const val TOTAL_NUMBER_OF_ITEMS_DATA_KEY = "totalItems"
private const val TYPED_BACKSPACES_DATA_KEY = "typedBackspaces"
private const val COLLECTED_RESULTS_DATA_KEY = "collectedItems"
private const val SELECTED_INDEXES_DATA_KEY = "selectedIndexes"
private const val SELECTED_ELEMENTS_DATA_KEY = "selectedIds"
// item fields
internal const val ID_KEY = "id"
internal const val ACTION_ID_KEY = "actionId"
internal const val FEATURES_DATA_KEY = "features"
internal const val CONTRIBUTOR_ID_KEY = "contributorId"
internal const val ML_WEIGHT_KEY = "mlWeight"
private fun roundDouble(value: Double): Double {
if (!value.isFinite()) return -1.0
return round(value * 100000) / 100000
}
}
} | apache-2.0 | 82ed837242ee5e14a0bc6dd8b3bd864c | 45.177914 | 158 | 0.675658 | 4.821268 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/database/models/Manga.kt | 1 | 3062 | package eu.kanade.tachiyomi.data.database.models
import java.io.Serializable
interface Manga : Serializable {
var id: Long?
var source: String
var url: String
var title: String
var artist: String?
var author: String?
var description: String?
var genre: String?
var status: Int
var thumbnail_url: String?
var favorite: Boolean
var last_update: Long
var initialized: Boolean
var viewer: Int
var chapter_flags: Int
var unread: Int
var category: Int
fun copyFrom(other: Manga) {
if (other.author != null)
author = other.author
if (other.artist != null)
artist = other.artist
if (other.description != null)
description = other.description
if (other.genre != null)
genre = other.genre
if (other.thumbnail_url != null)
thumbnail_url = other.thumbnail_url
status = other.status
initialized = true
}
fun setChapterOrder(order: Int) {
setFlags(order, SORT_MASK)
}
private fun setFlags(flag: Int, mask: Int) {
chapter_flags = chapter_flags and mask.inv() or (flag and mask)
}
fun sortDescending(): Boolean {
return chapter_flags and SORT_MASK == SORT_DESC
}
// Used to display the chapter's title one way or another
var displayMode: Int
get() = chapter_flags and DISPLAY_MASK
set(mode) = setFlags(mode, DISPLAY_MASK)
var readFilter: Int
get() = chapter_flags and READ_MASK
set(filter) = setFlags(filter, READ_MASK)
var downloadedFilter: Int
get() = chapter_flags and DOWNLOADED_MASK
set(filter) = setFlags(filter, DOWNLOADED_MASK)
var sorting: Int
get() = chapter_flags and SORTING_MASK
set(sort) = setFlags(sort, SORTING_MASK)
companion object {
const val UNKNOWN = 0
const val ONGOING = 1
const val COMPLETED = 2
const val LICENSED = 3
const val SORT_DESC = 0x00000000
const val SORT_ASC = 0x00000001
const val SORT_MASK = 0x00000001
// Generic filter that does not filter anything
const val SHOW_ALL = 0x00000000
const val SHOW_UNREAD = 0x00000002
const val SHOW_READ = 0x00000004
const val READ_MASK = 0x00000006
const val SHOW_DOWNLOADED = 0x00000008
const val SHOW_NOT_DOWNLOADED = 0x00000010
const val DOWNLOADED_MASK = 0x00000018
const val SORTING_SOURCE = 0x00000000
const val SORTING_NUMBER = 0x00000100
const val SORTING_MASK = 0x00000100
const val DISPLAY_NAME = 0x00000000
const val DISPLAY_NUMBER = 0x00100000
const val DISPLAY_MASK = 0x00100000
fun create(source: String): Manga = MangaImpl().apply {
this.source = source
}
fun create(pathUrl: String, source: String = "TEST"): Manga = MangaImpl().apply {
url = pathUrl
this.source = source
}
}
} | gpl-3.0 | c51547570f5fbfb15e80f9a4ca36124a | 22.381679 | 89 | 0.609732 | 4.324859 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/TrailingCommaInspection.kt | 1 | 10953 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.application.options.CodeStyle
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.formatter.TrailingCommaVisitor
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaContext
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaHelper
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaState
import org.jetbrains.kotlin.idea.formatter.trailingComma.addTrailingCommaIsAllowedFor
import org.jetbrains.kotlin.idea.formatter.trailingCommaAllowedInModule
import org.jetbrains.kotlin.idea.util.isComma
import org.jetbrains.kotlin.idea.util.isLineBreak
import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import javax.swing.JComponent
import kotlin.properties.Delegates
class TrailingCommaInspection(
@JvmField
var addCommaWarning: Boolean = false
) : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : TrailingCommaVisitor() {
override val recursively: Boolean = false
private var useTrailingComma by Delegates.notNull<Boolean>()
override fun process(trailingCommaContext: TrailingCommaContext) {
val element = trailingCommaContext.ktElement
val kotlinCustomSettings = element.containingKtFile.kotlinCustomSettings
useTrailingComma = kotlinCustomSettings.addTrailingCommaIsAllowedFor(element)
when (trailingCommaContext.state) {
TrailingCommaState.MISSING, TrailingCommaState.EXISTS -> {
checkCommaPosition(element)
checkLineBreaks(element)
}
else -> Unit
}
checkTrailingComma(trailingCommaContext)
}
private fun checkLineBreaks(commaOwner: KtElement) {
val first = TrailingCommaHelper.elementBeforeFirstElement(commaOwner)
if (first?.nextLeaf(true)?.isLineBreak() == false) {
first.nextSibling?.let {
registerProblemForLineBreak(commaOwner, it, ProblemHighlightType.INFORMATION)
}
}
val last = TrailingCommaHelper.elementAfterLastElement(commaOwner)
if (last?.prevLeaf(true)?.isLineBreak() == false) {
registerProblemForLineBreak(
commaOwner,
last,
if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION,
)
}
}
private fun checkCommaPosition(commaOwner: KtElement) {
for (invalidComma in TrailingCommaHelper.findInvalidCommas(commaOwner)) {
reportProblem(
invalidComma,
KotlinBundle.message("inspection.trailing.comma.comma.loses.the.advantages.in.this.position"),
KotlinBundle.message("inspection.trailing.comma.fix.comma.position")
)
}
}
private fun checkTrailingComma(trailingCommaContext: TrailingCommaContext) {
val commaOwner = trailingCommaContext.ktElement
val trailingCommaOrLastElement = TrailingCommaHelper.trailingCommaOrLastElement(commaOwner) ?: return
when (trailingCommaContext.state) {
TrailingCommaState.MISSING -> {
if (!trailingCommaAllowedInModule(commaOwner)) return
reportProblem(
trailingCommaOrLastElement,
KotlinBundle.message("inspection.trailing.comma.missing.trailing.comma"),
KotlinBundle.message("inspection.trailing.comma.add.trailing.comma"),
if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION,
)
}
TrailingCommaState.REDUNDANT -> {
reportProblem(
trailingCommaOrLastElement,
KotlinBundle.message("inspection.trailing.comma.useless.trailing.comma"),
KotlinBundle.message("inspection.trailing.comma.remove.trailing.comma"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
checkTrailingCommaSettings = false,
)
}
else -> Unit
}
}
private fun reportProblem(
commaOrElement: PsiElement,
message: String,
fixMessage: String,
highlightType: ProblemHighlightType = ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
checkTrailingCommaSettings: Boolean = true,
) {
val commaOwner = commaOrElement.parent as KtElement
// case for KtFunctionLiteral, where PsiWhiteSpace after KtTypeParameterList isn't included in this list
val problemOwner = commonParent(commaOwner, commaOrElement)
val highlightTypeWithAppliedCondition = highlightType.applyCondition(!checkTrailingCommaSettings || useTrailingComma)
// INFORMATION shouldn't be reported in batch mode
if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) {
holder.registerProblem(
problemOwner,
message,
highlightTypeWithAppliedCondition,
commaOrElement.textRangeOfCommaOrSymbolAfter.shiftLeft(problemOwner.startOffset),
createQuickFix(fixMessage, commaOwner),
)
}
}
private fun registerProblemForLineBreak(
commaOwner: KtElement,
elementForTextRange: PsiElement,
highlightType: ProblemHighlightType,
) {
val problemElement = commonParent(commaOwner, elementForTextRange)
val highlightTypeWithAppliedCondition = highlightType.applyCondition(useTrailingComma)
// INFORMATION shouldn't be reported in batch mode
if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) {
holder.registerProblem(
problemElement,
KotlinBundle.message("inspection.trailing.comma.missing.line.break"),
highlightTypeWithAppliedCondition,
TextRange.from(elementForTextRange.startOffset, 1).shiftLeft(problemElement.startOffset),
createQuickFix(KotlinBundle.message("inspection.trailing.comma.add.line.break"), commaOwner),
)
}
}
private fun commonParent(commaOwner: PsiElement, elementForTextRange: PsiElement): PsiElement =
PsiTreeUtil.findCommonParent(commaOwner, elementForTextRange)
?: throw KotlinExceptionWithAttachments("Common parent not found")
.withAttachment("commaOwner", commaOwner.text)
.withAttachment("commaOwnerRange", commaOwner.textRange)
.withAttachment("elementForTextRange", elementForTextRange.text)
.withAttachment("elementForTextRangeRange", elementForTextRange.textRange)
.withAttachment("parent", commaOwner.parent.text)
.withAttachment("parentRange", commaOwner.parent.textRange)
private fun ProblemHighlightType.applyCondition(condition: Boolean): ProblemHighlightType = when {
ApplicationManager.getApplication().isUnitTestMode -> ProblemHighlightType.GENERIC_ERROR_OR_WARNING
condition -> this
else -> ProblemHighlightType.INFORMATION
}
private fun createQuickFix(
fixMessage: String,
commaOwner: KtElement,
): LocalQuickFix = object : LocalQuickFix {
val commaOwnerPointer = commaOwner.createSmartPointer()
override fun getFamilyName(): String = fixMessage
override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) {
val element = commaOwnerPointer.element ?: return
val range = createFormatterTextRange(element)
val settings = CodeStyleSettingsManager.getInstance(project).cloneSettings(CodeStyle.getSettings(element.containingKtFile))
settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA = true
settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA_ON_CALL_SITE = true
CodeStyle.doWithTemporarySettings(project, settings, Runnable {
CodeStyleManager.getInstance(project).reformatRange(element, range.startOffset, range.endOffset)
})
}
}
private fun createFormatterTextRange(commaOwner: KtElement): TextRange {
val startElement = TrailingCommaHelper.elementBeforeFirstElement(commaOwner) ?: commaOwner
val endElement = TrailingCommaHelper.elementAfterLastElement(commaOwner) ?: commaOwner
return TextRange.create(startElement.startOffset, endElement.endOffset)
}
private val PsiElement.textRangeOfCommaOrSymbolAfter: TextRange
get() {
val textRange = textRange
if (isComma) return textRange
return nextLeaf()?.leafIgnoringWhitespaceAndComments(false)?.endOffset?.takeIf { it > 0 }?.let {
TextRange.create(it - 1, it).intersection(textRange)
} ?: TextRange.create(textRange.endOffset - 1, textRange.endOffset)
}
}
override fun createOptionsPanel(): JComponent = SingleCheckboxOptionsPanel(
KotlinBundle.message("inspection.trailing.comma.report.also.a.missing.comma"),
this,
"addCommaWarning",
)
}
| apache-2.0 | b68b966c387e58176c2a6370ded34a80 | 50.422535 | 158 | 0.672419 | 6.349565 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/JavaCollectionsStaticMethodInspection.kt | 1 | 6188 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
class JavaCollectionsStaticMethodInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return dotQualifiedExpressionVisitor(fun(expression) {
val (methodName, firstArg) = getTargetMethodOnMutableList(expression) ?: return
holder.registerProblem(
expression,
KotlinBundle.message("java.collections.static.method.call.should.be.replaced.with.kotlin.stdlib"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceWithStdLibFix(methodName, firstArg.text)
)
})
}
companion object {
fun getTargetMethodOnImmutableList(expression: KtDotQualifiedExpression) =
getTargetMethod(expression) { isListOrSubtype() && !isMutableListOrSubtype() }
private fun getTargetMethodOnMutableList(expression: KtDotQualifiedExpression) =
getTargetMethod(expression) { isMutableListOrSubtype() }
private fun getTargetMethod(
expression: KtDotQualifiedExpression,
isValidFirstArgument: KotlinType.() -> Boolean
): Pair<String, KtValueArgument>? {
val callExpression = expression.callExpression ?: return null
val args = callExpression.valueArguments
val firstArg = args.firstOrNull() ?: return null
val context = expression.analyze(BodyResolveMode.PARTIAL)
if (firstArg.getArgumentExpression()?.getType(context)?.isValidFirstArgument() != true) return null
val descriptor = expression.getResolvedCall(context)?.resultingDescriptor as? JavaMethodDescriptor ?: return null
val fqName = descriptor.importableFqName?.asString() ?: return null
if (!canReplaceWithStdLib(expression, fqName, args)) return null
val methodName = fqName.split(".").last()
return methodName to firstArg
}
private fun canReplaceWithStdLib(expression: KtDotQualifiedExpression, fqName: String, args: List<KtValueArgument>): Boolean {
if (!fqName.startsWith("java.util.Collections.")) return false
val size = args.size
return when (fqName) {
"java.util.Collections.fill" -> checkApiVersion(ApiVersion.KOTLIN_1_2, expression) && size == 2
"java.util.Collections.reverse" -> size == 1
"java.util.Collections.shuffle" -> checkApiVersion(ApiVersion.KOTLIN_1_2, expression) && (size == 1 || size == 2)
"java.util.Collections.sort" -> {
size == 1 || (size == 2 && args.getOrNull(1)?.getArgumentExpression() is KtLambdaExpression)
}
else -> false
}
}
private fun checkApiVersion(requiredVersion: ApiVersion, expression: KtDotQualifiedExpression): Boolean {
val module = ModuleUtilCore.findModuleForPsiElement(expression) ?: return true
return module.languageVersionSettings.apiVersion >= requiredVersion
}
}
}
private fun KotlinType.isMutableList() =
constructor.declarationDescriptor?.fqNameSafe == StandardNames.FqNames.mutableList
private fun KotlinType.isMutableListOrSubtype(): Boolean {
return isMutableList() || constructor.supertypes.reversed().any { it.isMutableList() }
}
private fun KotlinType.isList() =
constructor.declarationDescriptor?.fqNameSafe == StandardNames.FqNames.list
private fun KotlinType.isListOrSubtype(): Boolean {
return isList() || constructor.supertypes.reversed().any { it.isList() }
}
private class ReplaceWithStdLibFix(private val methodName: String, private val receiver: String) : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.std.lib.fix.text", receiver, methodName)
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement as? KtDotQualifiedExpression ?: return
val callExpression = expression.callExpression ?: return
val valueArguments = callExpression.valueArguments
val firstArg = valueArguments.getOrNull(0)?.getArgumentExpression() ?: return
val secondArg = valueArguments.getOrNull(1)?.getArgumentExpression()
val factory = KtPsiFactory(project)
val newExpression = if (secondArg != null) {
if (methodName == "sort") {
factory.createExpressionByPattern("$0.sortWith(Comparator $1)", firstArg, secondArg.text)
} else {
factory.createExpressionByPattern("$0.$methodName($1)", firstArg, secondArg)
}
} else {
factory.createExpressionByPattern("$0.$methodName()", firstArg)
}
expression.replace(newExpression)
}
}
| apache-2.0 | 28f14fc11d36f2a22dfeb9399077092c | 48.903226 | 158 | 0.713154 | 5.320722 | false | false | false | false |
ncoe/rosetta | Next_highest_int_from_digits/Kotlin/src/NextHighestIntFromDigits.kt | 1 | 3409 | import java.math.BigInteger
import java.text.NumberFormat
fun main() {
for (s in arrayOf(
"0",
"9",
"12",
"21",
"12453",
"738440",
"45072010",
"95322020",
"9589776899767587796600",
"3345333"
)) {
println("${format(s)} -> ${format(next(s))}")
}
testAll("12345")
testAll("11122")
}
private val FORMAT = NumberFormat.getNumberInstance()
private fun format(s: String): String {
return FORMAT.format(BigInteger(s))
}
private fun testAll(str: String) {
var s = str
println("Test all permutations of: $s")
val sOrig = s
var sPrev = s
var count = 1
// Check permutation order. Each is greater than the last
var orderOk = true
val uniqueMap: MutableMap<String, Int> = HashMap()
uniqueMap[s] = 1
while (next(s).also { s = it }.compareTo("0") != 0) {
count++
if (s.toLong() < sPrev.toLong()) {
orderOk = false
}
uniqueMap.merge(s, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
sPrev = s
}
println(" Order: OK = $orderOk")
// Test last permutation
val reverse = StringBuilder(sOrig).reverse().toString()
println(" Last permutation: Actual = $sPrev, Expected = $reverse, OK = ${sPrev.compareTo(reverse) == 0}")
// Check permutations unique
var unique = true
for (key in uniqueMap.keys) {
if (uniqueMap[key]!! > 1) {
unique = false
}
}
println(" Permutations unique: OK = $unique")
// Check expected count.
val charMap: MutableMap<Char, Int> = HashMap()
for (c in sOrig.toCharArray()) {
charMap.merge(c, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
}
var permCount = factorial(sOrig.length.toLong())
for (c in charMap.keys) {
permCount /= factorial(charMap[c]!!.toLong())
}
println(" Permutation count: Actual = $count, Expected = $permCount, OK = ${count.toLong() == permCount}")
}
private fun factorial(n: Long): Long {
var fact: Long = 1
for (num in 2..n) {
fact *= num
}
return fact
}
private fun next(s: String): String {
val sb = StringBuilder()
var index = s.length - 1
// Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.
while (index > 0 && s[index - 1] >= s[index]) {
index--
}
// Reached beginning. No next number.
if (index == 0) {
return "0"
}
// Find digit on the right that is both more than it, and closest to it.
var index2 = index
for (i in index + 1 until s.length) {
if (s[i] < s[index2] && s[i] > s[index - 1]) {
index2 = i
}
}
// Found data, now build string
// Beginning of String
if (index > 1) {
sb.append(s.subSequence(0, index - 1))
}
// Append found, place next
sb.append(s[index2])
// Get remaining characters
val chars: MutableList<Char> = ArrayList()
chars.add(s[index - 1])
for (i in index until s.length) {
if (i != index2) {
chars.add(s[i])
}
}
// Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right.
chars.sort()
for (c in chars) {
sb.append(c)
}
return sb.toString()
}
| mit | 1cab598465306a6d0d9c3ef10b33e9ed | 26.055556 | 132 | 0.553241 | 3.489253 | false | false | false | false |
actions-on-google/actions-shortcut-convert | src/main/kotlin/com/google/assistant/actions/model/actions/ActionsModel.kt | 1 | 3276 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.assistant.actions.model.actions
import javax.xml.bind.annotation.XmlAttribute
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlRootElement
@XmlRootElement(name="actions")
data class ActionsRoot(
@set:XmlElement(name="action")
var actions: List<Action> = mutableListOf(),
@set:XmlElement(name="entity-set")
var entitySets: List<EntitySet> = mutableListOf(),
)
//
// Children of ActionsRoot
//
data class Action(
@set:XmlAttribute(required = true)
var intentName: String? = null,
@set:XmlAttribute
var queryPatterns: String? = null,
@set:XmlElement(name="fulfillment", required = true)
var fulfillments: List<Fulfillment> = mutableListOf(),
@set:XmlElement(name="parameter", required = true)
var parameters: List<Parameter> = mutableListOf(),
@set:XmlElement(name="entity-set", required = false)
var entitySets: List<EntitySet> = mutableListOf(),
)
data class EntitySet(
@set:XmlAttribute(required = true)
var entitySetId: String? = null,
@set:XmlElement(name="entity", required = true)
var entities: List<Entity> = mutableListOf(),
)
//
// Children of Action
//
data class Fulfillment(
@set:XmlAttribute(required = true)
var urlTemplate: String? = null,
@set:XmlAttribute
var fulfillmentMode: String? = null,
@set:XmlAttribute
var requiredForegroundActivity: String? = null,
@set:XmlElement(name="parameter-mapping")
var parameterMappings: List<ParameterMapping> = mutableListOf(),
)
data class Parameter(
@set:XmlAttribute(required = true)
var name: String? = null,
@set:XmlAttribute
var type: String? = null,
@set:XmlElement(name = "entity-set-reference")
var entitySetReference: EntitySetReference? = null,
)
//
// Children of Fulfillment
//
data class ParameterMapping(
@set:XmlAttribute(required = true)
var intentParameter: String? = null,
@set:XmlAttribute(required = true)
var urlParameter: String? = null,
@set:XmlAttribute
var required: String? = null,
@set:XmlAttribute
var entityMatchRequired: String? = null,
)
//
// Children of Parameter
//
data class EntitySetReference(
@set:XmlAttribute
var entitySetId: String? = null,
@set:XmlAttribute
var urlFilter: String? = null,
)
//
// Children of EntitySet
//
data class Entity(
@set:XmlAttribute
var name: String? = null,
@set:XmlAttribute
var alternateName: String? = null,
@set:XmlAttribute
var sameAs: String? = null,
@set:XmlAttribute
var identifier: String? = null,
@set:XmlAttribute
var url: String? = null,
)
| apache-2.0 | 9a4a7e746c584c0f2d7c2120a14011f1 | 21.438356 | 75 | 0.696276 | 4.00489 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/MutableCodeToInline.kt | 1 | 4759 | // 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.codeInliner
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.core.copied
import org.jetbrains.kotlin.psi.BuilderByPattern
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.ImportPath
private val POST_INSERTION_ACTION: Key<(KtElement) -> Unit> = Key("POST_INSERTION_ACTION")
private val PRE_COMMIT_ACTION: Key<(KtElement) -> Unit> = Key("PRE_COMMIT_ACTION_KEY")
internal class MutableCodeToInline(
var mainExpression: KtExpression?,
val statementsBefore: MutableList<KtExpression>,
val fqNamesToImport: MutableCollection<ImportPath>,
val alwaysKeepMainExpression: Boolean,
var extraComments: CommentHolder?,
) {
fun <TElement : KtElement> addPostInsertionAction(element: TElement, action: (TElement) -> Unit) {
assert(element in this)
@Suppress("UNCHECKED_CAST")
element.putCopyableUserData(POST_INSERTION_ACTION, action as (KtElement) -> Unit)
}
fun <TElement : KtElement> addPreCommitAction(element: TElement, action: (TElement) -> Unit) {
@Suppress("UNCHECKED_CAST")
element.putCopyableUserData(PRE_COMMIT_ACTION, action as (KtElement) -> Unit)
}
fun performPostInsertionActions(elements: Collection<PsiElement>) {
for (element in elements) {
element.forEachDescendantOfType<KtElement> { performAction(it, POST_INSERTION_ACTION) }
}
}
fun addExtraComments(commentHolder: CommentHolder) {
extraComments = extraComments?.merge(commentHolder) ?: commentHolder
}
fun BuilderByPattern<KtExpression>.appendExpressionsFromCodeToInline(postfixForMainExpression: String = "") {
for (statement in statementsBefore) {
appendExpression(statement)
appendFixedText("\n")
}
if (mainExpression != null) {
appendExpression(mainExpression)
appendFixedText(postfixForMainExpression)
}
}
fun replaceExpression(oldExpression: KtExpression, newExpression: KtExpression): KtExpression {
assert(oldExpression in this)
if (oldExpression == mainExpression) {
mainExpression = newExpression
return newExpression
}
val index = statementsBefore.indexOf(oldExpression)
if (index >= 0) {
statementsBefore[index] = newExpression
return newExpression
}
return oldExpression.replace(newExpression) as KtExpression
}
val expressions: Collection<KtExpression>
get() = statementsBefore + listOfNotNull(mainExpression)
operator fun contains(element: PsiElement): Boolean = expressions.any { it.isAncestor(element) }
}
internal fun CodeToInline.toMutable(): MutableCodeToInline = MutableCodeToInline(
mainExpression?.copied(),
statementsBefore.asSequence().map { it.copied() }.toMutableList(),
fqNamesToImport.toMutableSet(),
alwaysKeepMainExpression,
extraComments,
)
private fun performAction(element: KtElement, actionKey: Key<(KtElement) -> Unit>) {
val action = element.getCopyableUserData(actionKey)
if (action != null) {
element.putCopyableUserData(actionKey, null)
action.invoke(element)
}
}
private fun performPreCommitActions(expressions: Collection<KtExpression>) = expressions.asSequence()
.flatMap { it.collectDescendantsOfType<KtElement> { element -> element.getCopyableUserData(PRE_COMMIT_ACTION) != null } }
.sortedWith(compareByDescending(KtElement::startOffset).thenBy(PsiElement::getTextLength))
.forEach { performAction(it, PRE_COMMIT_ACTION) }
internal fun MutableCodeToInline.toNonMutable(): CodeToInline {
performPreCommitActions(expressions)
return CodeToInline(
mainExpression,
statementsBefore,
fqNamesToImport,
alwaysKeepMainExpression,
extraComments
)
}
internal inline fun <reified T : PsiElement> MutableCodeToInline.collectDescendantsOfType(noinline predicate: (T) -> Boolean = { true }): List<T> {
return expressions.flatMap { it.collectDescendantsOfType({ true }, predicate) }
}
internal inline fun <reified T : PsiElement> MutableCodeToInline.forEachDescendantOfType(noinline action: (T) -> Unit) {
expressions.forEach { it.forEachDescendantOfType(action) }
}
| apache-2.0 | 6d0d9f2098913c077b43d0d6e9ef02f6 | 38.008197 | 147 | 0.727254 | 4.916322 | false | false | false | false |
androidx/androidx | emoji2/emoji2-emojipicker/src/main/java/androidx/emoji2/emojipicker/BundledEmojiListLoader.kt | 3 | 5054 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.emoji2.emojipicker
import android.content.Context
import android.content.res.TypedArray
import androidx.core.content.res.use
import androidx.emoji2.emojipicker.utils.FileCache
import androidx.emoji2.emojipicker.utils.UnicodeRenderableManager
import androidx.emoji2.text.EmojiCompat
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
/**
* A data loader that loads the following objects either from file based caches or from resources.
*
* @property categorizedEmojiData: a list that holds bundled emoji separated by category, filtered
* by renderability check. This is the data source for EmojiPickerView.
*
* @property emojiVariantsLookup: a map of emoji variants in bundled emoji, keyed by the base
* emoji. This allows faster variants lookup.
*/
internal object BundledEmojiListLoader {
private var categorizedEmojiData: List<EmojiDataCategory>? = null
private var emojiVariantsLookup: Map<String, List<String>>? = null
private var primaryEmojiLookup: Map<String, String>? = null
private var deferred: List<Deferred<EmojiDataCategory>>? = null
internal suspend fun load(context: Context) {
val categoryNames = context.resources.getStringArray(R.array.category_names)
val resources = if (UnicodeRenderableManager.isEmoji12Supported())
R.array.emoji_by_category_raw_resources_gender_inclusive
else
R.array.emoji_by_category_raw_resources
val emojiFileCache = FileCache.getInstance(context)
deferred = context.resources
.obtainTypedArray(resources)
.use { ta -> loadEmojiAsync(ta, categoryNames, emojiFileCache, context) }
}
internal suspend fun getCategorizedEmojiData() =
categorizedEmojiData ?: deferred?.awaitAll()?.also {
categorizedEmojiData = it
} ?: throw IllegalStateException("BundledEmojiListLoader.load is not called")
internal suspend fun getEmojiVariantsLookup() =
emojiVariantsLookup ?: getCategorizedEmojiData()
.flatMap { it.emojiDataList }
.filter { it.variants.isNotEmpty() }
.associate { it.emoji to it.variants }
.also { emojiVariantsLookup = it }
internal suspend fun getPrimaryEmojiLookup() =
primaryEmojiLookup ?: getCategorizedEmojiData()
.flatMap { it.emojiDataList }
.filter { it.variants.isNotEmpty() }
.flatMap { it.variants.associateWith { _ -> it.emoji }.entries }
.associate { it.toPair() }
.also { primaryEmojiLookup = it }
private suspend fun loadEmojiAsync(
ta: TypedArray,
categoryNames: Array<String>,
emojiFileCache: FileCache,
context: Context
): List<Deferred<EmojiDataCategory>> = coroutineScope {
(0 until ta.length()).map {
async {
emojiFileCache.getOrPut(getCacheFileName(it)) {
loadSingleCategory(context, ta.getResourceId(it, 0))
}.let { data -> EmojiDataCategory(categoryNames[it], data) }
}
}
}
private fun loadSingleCategory(
context: Context,
resId: Int,
): List<EmojiViewItem> =
context.resources
.openRawResource(resId)
.bufferedReader()
.useLines { it.toList() }
.map { filterRenderableEmojis(it.split(",")) }
.filter { it.isNotEmpty() }
.map { EmojiViewItem(it.first(), it.drop(1)) }
private fun getCacheFileName(categoryIndex: Int) =
StringBuilder().append("emoji.v1.")
.append(if (EmojiCompat.isConfigured()) 1 else 0)
.append(".")
.append(categoryIndex)
.append(".")
.append(if (UnicodeRenderableManager.isEmoji12Supported()) 1 else 0)
.toString()
/**
* To eliminate 'Tofu' (the fallback glyph when an emoji is not renderable), check the
* renderability of emojis and keep only when they are renderable on the current device.
*/
private fun filterRenderableEmojis(emojiList: List<String>) =
emojiList.filter {
UnicodeRenderableManager.isEmojiRenderable(it)
}.toList()
internal data class EmojiDataCategory(
val categoryName: String,
val emojiDataList: List<EmojiViewItem>
)
} | apache-2.0 | 69ae26113d1c885ac26f315af2d2a0b4 | 38.492188 | 98 | 0.675109 | 4.701395 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/projectView/actions/MarkAsContentRootAction.kt | 5 | 2042 | /*
* 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.ide.projectView.actions
import com.intellij.ide.projectView.impl.ProjectRootsUtil
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
class MarkAsContentRootAction : DumbAwareAction() {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
val files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)
val module = MarkRootActionBase.getModule(e, files)
if (module == null || files == null) {
e.presentation.isEnabledAndVisible = false
return
}
val fileIndex = ProjectRootManager.getInstance(module.project).fileIndex
e.presentation.isEnabledAndVisible = files.all {
it.isDirectory && fileIndex.isExcluded(it) && ProjectRootsUtil.findExcludeFolder(module, it) == null
}
}
override fun actionPerformed(e: AnActionEvent) {
val files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return
val module = MarkRootActionBase.getModule(e, files) ?: return
val model = ModuleRootManager.getInstance(module).modifiableModel
files.forEach {
model.addContentEntry(it)
}
MarkRootActionBase.commitModel(module, model)
}
}
| apache-2.0 | 3f939fa18f900cc0bab93be6182bb541 | 38.269231 | 106 | 0.763467 | 4.458515 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-idea/tests/test/org/jetbrains/kotlin/idea/scripting/gradle/KotlinDslScriptModelTest.kt | 1 | 1469 | // 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.scripting.gradle
import org.gradle.api.internal.file.IdentityFileResolver
import org.gradle.groovy.scripts.TextResourceScriptSource
import org.gradle.internal.exceptions.LocationAwareException
import org.gradle.internal.resource.UriTextResource
import org.jetbrains.kotlin.idea.scripting.gradle.importing.parsePositionFromException
import org.junit.Test
import kotlin.io.path.*
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class KotlinDslScriptModelTest {
@OptIn(ExperimentalPathApi::class)
@Test
fun testExceptionPositionParsing() {
val file = createTempDirectory("kotlinDslTest") / "build.gradle.kts"
val line = 10
val mockScriptSource = TextResourceScriptSource(UriTextResource("build file", file.toFile(), IdentityFileResolver()))
val mockException = LocationAwareException(RuntimeException(), mockScriptSource, line)
val fromException = parsePositionFromException(mockException.stackTraceToString())
assertNotNull(fromException, "Position should be parsed")
assertEquals(fromException.first, file.toAbsolutePath().toString(), "Wrong file name parsed")
assertEquals(fromException.second.line, line, "Wrong line number parsed")
file.parent.deleteExisting()
}
} | apache-2.0 | aaafb5002d5b55a5959d66e2d0d21f5f | 46.419355 | 158 | 0.780803 | 4.648734 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/highlighter/visitors/TypeHighlightingVisitor.kt | 1 | 2996 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.fir.highlighter.visitors
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.highlighter.isAnnotationClass
import org.jetbrains.kotlin.idea.highlighter.textAttributesKeyForTypeDeclaration
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.idea.highlighter.NameHighlighter
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors as Colors
internal class TypeHighlightingVisitor(
analysisSession: KtAnalysisSession,
holder: AnnotationHolder
) : FirAfterResolveHighlightingVisitor(analysisSession, holder) {
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
if (!NameHighlighter.namesHighlightingEnabled) return
if (expression.isCalleeExpression()) return
val parent = expression.parent
if (parent is KtInstanceExpressionWithLabel) {
// Do nothing: 'super' and 'this' are highlighted as a keyword
return
}
val target = expression.mainReference.resolve() ?: return
if (isAnnotationCall(expression, target)) {
// higlighted by AnnotationEntryHiglightingVisitor
return
}
textAttributesKeyForTypeDeclaration(target)?.let { key ->
if (expression.isConstructorCallReference() && key != Colors.ANNOTATION) {
// Do not highlight constructor call as class reference
return@let
}
highlightName(expression.textRange, key)
}
}
private fun isAnnotationCall(expression: KtSimpleNameExpression, target: PsiElement): Boolean {
val expressionRange = expression.textRange
val isKotlinAnnotation = target is KtPrimaryConstructor && target.parent.isAnnotationClass()
if (!isKotlinAnnotation && !target.isAnnotationClass()) return false
val annotationEntry = PsiTreeUtil.getParentOfType(
expression, KtAnnotationEntry::class.java, /* strict = */false, KtValueArgumentList::class.java
)
return annotationEntry?.atSymbol != null
}
}
private fun KtSimpleNameExpression.isCalleeExpression() =
(parent as? KtCallExpression)?.calleeExpression == this
private fun KtSimpleNameExpression.isConstructorCallReference(): Boolean {
val type = parent as? KtUserType ?: return false
val typeReference = type.parent as? KtTypeReference ?: return false
val constructorCallee = typeReference.parent as? KtConstructorCalleeExpression ?: return false
return constructorCallee.constructorReferenceExpression == this
} | apache-2.0 | cbb65baf6ac2203e69c6454c6da2b443 | 45.107692 | 158 | 0.74466 | 5.330961 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/native/src/org/jetbrains/kotlin/ide/konan/analyzer/NativeResolverForModuleFactory.kt | 4 | 3377 | // 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.ide.konan.analyzer
import org.jetbrains.kotlin.analyzer.*
import org.jetbrains.kotlin.caches.resolve.resolution
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.container.get
import org.jetbrains.kotlin.context.ModuleContext
import org.jetbrains.kotlin.descriptors.impl.CompositePackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.frontend.di.createContainerForLazyResolve
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.idePlatformKind
import org.jetbrains.kotlin.platform.konan.NativePlatforms
import org.jetbrains.kotlin.resolve.CodeAnalyzerInitializer
import org.jetbrains.kotlin.resolve.SealedClassInheritorsProvider
import org.jetbrains.kotlin.resolve.TargetEnvironment
import org.jetbrains.kotlin.resolve.konan.platform.NativePlatformAnalyzerServices
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactoryService.Companion.createDeclarationProviderFactory
class NativeResolverForModuleFactory(
private val platformAnalysisParameters: PlatformAnalysisParameters,
private val targetEnvironment: TargetEnvironment,
private val targetPlatform: TargetPlatform
) : ResolverForModuleFactory() {
override fun <M : ModuleInfo> createResolverForModule(
moduleDescriptor: ModuleDescriptorImpl,
moduleContext: ModuleContext,
moduleContent: ModuleContent<M>,
resolverForProject: ResolverForProject<M>,
languageVersionSettings: LanguageVersionSettings,
sealedInheritorsProvider: SealedClassInheritorsProvider
): ResolverForModule {
val declarationProviderFactory = createDeclarationProviderFactory(
moduleContext.project,
moduleContext.storageManager,
moduleContent.syntheticFiles,
moduleContent.moduleContentScope,
moduleContent.moduleInfo
)
val container = createContainerForLazyResolve(
moduleContext,
declarationProviderFactory,
CodeAnalyzerInitializer.getInstance(moduleContext.project).createTrace(),
moduleDescriptor.platform!!,
NativePlatformAnalyzerServices,
targetEnvironment,
languageVersionSettings
)
var packageFragmentProvider = container.get<ResolveSession>().packageFragmentProvider
val klibPackageFragmentProvider =
NativePlatforms.unspecifiedNativePlatform.idePlatformKind.resolution.createKlibPackageFragmentProvider(
moduleContent.moduleInfo,
moduleContext.storageManager,
languageVersionSettings,
moduleDescriptor
)
if (klibPackageFragmentProvider != null) {
packageFragmentProvider = CompositePackageFragmentProvider(
listOf(packageFragmentProvider, klibPackageFragmentProvider),
"CompositeProvider@NativeResolver for $moduleDescriptor"
)
}
return ResolverForModule(packageFragmentProvider, container)
}
}
| apache-2.0 | ad08c7fe46a412b1a52e5f3276b9c016 | 44.635135 | 158 | 0.763696 | 6.173675 | false | false | false | false |
smmribeiro/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/autoimport/ProjectAware.kt | 9 | 4550 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project.autoimport
import com.intellij.ide.impl.isTrusted
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.externalSystem.ExternalSystemAutoImportAware
import com.intellij.openapi.externalSystem.autoimport.*
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType.RESOLVE_PROJECT
import com.intellij.openapi.externalSystem.service.internal.ExternalSystemProcessingManager
import com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask
import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import java.io.File
import java.util.concurrent.atomic.AtomicReference
class ProjectAware(
private val project: Project,
override val projectId: ExternalSystemProjectId,
private val autoImportAware: ExternalSystemAutoImportAware
) : ExternalSystemProjectAware {
private val systemId = projectId.systemId
private val projectPath = projectId.externalProjectPath
override val settingsFiles: Set<String>
get() {
val pathMacroManager = PathMacroManager.getInstance(project)
return externalProjectFiles.map {
val path = FileUtil.toCanonicalPath(it.path)
// The path string can be changed after serialization and deserialization inside persistent component state.
// To avoid that we resolve the path using IDE path macros configuration.
val collapsedPath = pathMacroManager.collapsePath(path)
val expandedPath = pathMacroManager.expandPath(collapsedPath)
expandedPath
}.toSet()
}
private val externalProjectFiles: List<File>
get() = autoImportAware.getAffectedExternalProjectFiles(projectPath, project)
override fun subscribe(listener: ExternalSystemProjectListener, parentDisposable: Disposable) {
val progressManager = ExternalSystemProgressNotificationManager.getInstance()
progressManager.addNotificationListener(TaskNotificationListener(listener), parentDisposable)
}
override fun reloadProject(context: ExternalSystemProjectReloadContext) {
val importSpec = ImportSpecBuilder(project, systemId)
if (!context.isExplicitReload) {
importSpec.dontReportRefreshErrors()
importSpec.dontNavigateToError()
}
if (!project.isTrusted()) {
importSpec.usePreviewMode()
}
ExternalSystemUtil.refreshProject(projectPath, importSpec)
}
private inner class TaskNotificationListener(
val delegate: ExternalSystemProjectListener
) : ExternalSystemTaskNotificationListenerAdapter() {
var externalSystemTaskId = AtomicReference<ExternalSystemTaskId?>(null)
override fun onStart(id: ExternalSystemTaskId, workingDir: String?) {
if (id.type != RESOLVE_PROJECT) return
if (!FileUtil.pathsEqual(workingDir, projectPath)) return
val task = ApplicationManager.getApplication().getService(ExternalSystemProcessingManager::class.java).findTask(id)
if (task is ExternalSystemResolveProjectTask) {
if (!autoImportAware.isApplicable(task.resolverPolicy)) {
return
}
}
externalSystemTaskId.set(id)
delegate.onProjectReloadStart()
}
private fun afterProjectRefresh(id: ExternalSystemTaskId, status: ExternalSystemRefreshStatus) {
if (id.type != RESOLVE_PROJECT) return
if (!externalSystemTaskId.compareAndSet(id, null)) return
delegate.onProjectReloadFinish(status)
}
override fun onSuccess(id: ExternalSystemTaskId) {
afterProjectRefresh(id, ExternalSystemRefreshStatus.SUCCESS)
}
override fun onFailure(id: ExternalSystemTaskId, e: Exception) {
afterProjectRefresh(id, ExternalSystemRefreshStatus.FAILURE)
}
override fun onCancel(id: ExternalSystemTaskId) {
afterProjectRefresh(id, ExternalSystemRefreshStatus.CANCEL)
}
}
} | apache-2.0 | 67bb08864ff24bc32d49060efd25bb23 | 43.617647 | 158 | 0.792088 | 5.495169 | false | false | false | false |
tomatrocho/insapp-material | app/src/main/java/fr/insapp/insapp/fragments/CommentsEventFragment.kt | 2 | 10253 | package fr.insapp.insapp.fragments
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.bumptech.glide.request.RequestOptions
import fr.insapp.insapp.R
import fr.insapp.insapp.activities.EventActivity
import fr.insapp.insapp.adapters.CommentRecyclerViewAdapter
import fr.insapp.insapp.http.ServiceGenerator
import fr.insapp.insapp.models.Comment
import fr.insapp.insapp.models.Event
import fr.insapp.insapp.utility.Utils
import kotlinx.android.synthetic.main.activity_event.*
import kotlinx.android.synthetic.main.fragment_event_comments.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
/**
* Created by thomas on 25/02/2017.
*/
class CommentsEventFragment : Fragment() {
private lateinit var commentAdapter: CommentRecyclerViewAdapter
private var event: Event? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// arguments
val bundle = arguments
if (bundle != null) {
this.event = bundle.getParcelable("event")
}
// adapter
event.let {
commentAdapter = CommentRecyclerViewAdapter(event!!.comments, Glide.with(this))
commentAdapter.setOnCommentItemLongClickListener(EventCommentLongClickListener(context, event!!, commentAdapter))
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_event_comments, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// edit comment
comment_event_input.setupComponent()
comment_event_input.setOnEditorActionListener(TextView.OnEditorActionListener { textView, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEND) {
// hide keyboard
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(textView.windowToken, 0)
val content = comment_event_input.text.toString()
comment_event_input.text.clear()
if (content.isNotBlank()) {
val user = Utils.user
user?.let {
val comment = Comment(null, user.id, content, null, comment_event_input.tags)
ServiceGenerator.client.commentEvent(event!!.id, comment)
.enqueue(object : Callback<Event> {
override fun onResponse(call: Call<Event>, response: Response<Event>) {
if (response.isSuccessful) {
commentAdapter.addComment(comment)
comment_event_input.tags.clear()
Toast.makeText(activity, resources.getText(R.string.write_comment_success), Toast.LENGTH_LONG).show()
} else {
Toast.makeText(activity, "CommentEditText", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Event>, t: Throwable) {
Toast.makeText(activity, "CommentEditText", Toast.LENGTH_LONG).show()
}
})
}
}
return@OnEditorActionListener true
}
false
})
// recycler view
recyclerview_comments_event?.setHasFixedSize(true)
recyclerview_comments_event?.isNestedScrollingEnabled = false
val layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
recyclerview_comments_event?.layoutManager = layoutManager
recyclerview_comments_event?.adapter = commentAdapter
// retrieve the avatar of the user
val user = Utils.user
val id = resources.getIdentifier(Utils.drawableProfileName(user?.promotion, user?.gender), "drawable", context!!.packageName)
Glide
.with(context!!)
.load(id)
.apply(RequestOptions.circleCropTransform())
.transition(withCrossFade())
.into(comment_event_username_avatar)
// animation on focus
comment_event_input?.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
(activity as EventActivity).appbar_event.setExpanded(false, true)
(activity as EventActivity).fab_participate_event.hideMenu(false)
} else {
val atm = Calendar.getInstance().time
if (event!!.dateEnd.time >= atm.time) {
val handler = Handler()
handler.postDelayed({
val eventActivity = activity as EventActivity?
eventActivity?.fab_participate_event?.showMenu(true)
}, 500)
}
}
}
}
class EventCommentLongClickListener(
private val context: Context?,
private val event: Event,
private val adapter: CommentRecyclerViewAdapter
): CommentRecyclerViewAdapter.OnCommentItemLongClickListener {
override fun onCommentItemLongClick(comment: Comment) {
if (context != null) {
val alertDialogBuilder = AlertDialog.Builder(context)
val user = Utils.user
// delete comment
if (user != null) {
if (user.id == comment.user) {
alertDialogBuilder
.setTitle(context.resources.getString(R.string.delete_comment_action))
.setMessage(R.string.delete_comment_are_you_sure)
.setCancelable(true)
.setPositiveButton(context.getString(R.string.positive_button)) { _: DialogInterface, _: Int ->
val call = ServiceGenerator.client.uncommentEvent(event.id, comment.id!!)
call.enqueue(object : Callback<Event> {
override fun onResponse(call: Call<Event>, response: Response<Event>) {
val event = response.body()
if (response.isSuccessful && event != null) {
adapter.setComments(event.comments)
} else {
Toast.makeText(context, "EventCommentLongClickListener", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Event>, t: Throwable) {
Toast.makeText(context, "EventCommentLongClickListener", Toast.LENGTH_LONG).show()
}
})
}
.setNegativeButton(context.getString(R.string.negative_button)) { dialogAlert: DialogInterface, _: Int ->
dialogAlert.cancel()
}
.create().show()
}
// report comment
else {
alertDialogBuilder
.setTitle(context.getString(R.string.report_comment_action))
.setMessage(R.string.report_comment_are_you_sure)
.setCancelable(true)
.setPositiveButton(context.getString(R.string.positive_button)) { _: DialogInterface, _: Int ->
val call = ServiceGenerator.client.reportComment(event.id, comment.id!!)
call.enqueue(object : Callback<Void> {
override fun onResponse(call: Call<Void>, response: Response<Void>) {
if (response.isSuccessful) {
Toast.makeText(context, context.getString(R.string.report_comment_success), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "EventCommentLongClickListener", Toast.LENGTH_LONG).show();
}
}
override fun onFailure(call: Call<Void>, t: Throwable) {
Toast.makeText(context, "EventCommentLongClickListener", Toast.LENGTH_LONG).show();
}
})
}
.setNegativeButton(context.getString(R.string.negative_button)) { dialogAlert: DialogInterface, _: Int ->
dialogAlert.cancel()
}
.create().show()
}
}
}
}
}
}
| mit | 7549ad0a8fea1c6395272747bf76e8ab | 43.578261 | 151 | 0.532137 | 5.978426 | false | false | false | false |
googlearchive/android-instant-apps | aab-simple/app/src/main/java/com/google/android/instantapps/samples/instantenabledandroidappbundle/MainActivity.kt | 1 | 1369 | /*
* 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 com.google.android.instantapps.samples.instantenabledandroidappbundle
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
class MainActivity : AppCompatActivity() {
private var count = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<View>(R.id.button).setOnClickListener {
// On button click, update the counter and refresh the UI
if (count == 0) {
findViewById<TextView>(R.id.statictext).text = "Kittens fed:"
}
findViewById<TextView>(R.id.text).text = (++count).toString()
}
}
}
| apache-2.0 | b6e3639e4c8129857f47e231a6ac1776 | 34.102564 | 77 | 0.704164 | 4.346032 | false | false | false | false |
ZoranPandovski/al-go-rithms | data_structures/Graphs/graph/Kotlin/DjikstraAlgorithm.kt | 1 | 6114 | import java.util.ArrayList
import java.util.Collections
import java.util.HashMap
import java.util.HashSet
import java.util.LinkedList
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class DijkstraAlgorithm(graph: Graph) {
private val nodes: List<Vertex>
private val edges: List<Edge>
private var settledNodes: MutableSet<Vertex>? = null
private var unSettledNodes: MutableSet<Vertex>? = null
private var predecessors: MutableMap<Vertex, Vertex>? = null
private var distance: MutableMap<Vertex, Int>? = null
init {
// create a copy of the array so that we can operate on this array
this.nodes = ArrayList<Vertex>(graph.vertexes)
this.edges = ArrayList<Edge>(graph.edges)
}
fun execute(source: Vertex) {
settledNodes = HashSet()
unSettledNodes = HashSet()
distance = HashMap()
predecessors = HashMap()
distance!![source] = 0
unSettledNodes!!.add(source)
while (unSettledNodes!!.size > 0) {
val node = getMinimum(unSettledNodes!!)
settledNodes!!.add(node!!)
unSettledNodes!!.remove(node)
findMinimalDistances(node)
}
}
private fun findMinimalDistances(node: Vertex?) {
val adjacentNodes = getNeighbors(node)
for (target in adjacentNodes) {
if (getShortestDistance(target) > getShortestDistance(node) + getDistance(node, target)) {
distance!![target] = getShortestDistance(node) + getDistance(node, target)
predecessors!![target] = node!!
unSettledNodes!!.add(target)
}
}
}
private fun getDistance(node: Vertex?, target: Vertex): Int {
for (edge in edges) {
if (edge.source == node && edge.destination == target) {
return edge.weight
}
}
throw RuntimeException("Should not happen")
}
private fun getNeighbors(node: Vertex?): List<Vertex> {
val neighbors = ArrayList<Vertex>()
for (edge in edges) {
if (edge.source == node && !isSettled(edge.destination)) {
neighbors.add(edge.destination)
}
}
return neighbors
}
private fun getMinimum(vertexes: Set<Vertex>): Vertex? {
var minimum: Vertex? = null
for (vertex in vertexes) {
if (minimum == null) {
minimum = vertex
} else {
if (getShortestDistance(vertex) < getShortestDistance(minimum)) {
minimum = vertex
}
}
}
return minimum
}
private fun isSettled(vertex: Vertex): Boolean {
return settledNodes!!.contains(vertex)
}
private fun getShortestDistance(destination: Vertex?): Int {
val d = distance!![destination]
return d ?: Integer.MAX_VALUE
}
/*
* This method returns the path from the source to the selected target and
* NULL if no path exists
*/
fun getPath(target: Vertex): LinkedList<Vertex>? {
val path = LinkedList<Vertex>()
var step = target
// check if a path exists
if (predecessors!![step] == null) {
return null
}
path.add(step)
while (predecessors!![step] != null) {
step = predecessors!![step]!!
path.add(step)
}
// Put it into the correct order
Collections.reverse(path)
return path
}
}
class Edge(val id: String, val source: Vertex, val destination: Vertex, val weight: Int) {
override fun toString(): String {
return source.toString() + " " + destination.toString()
}
}
class Graph(val vertexes: List<Vertex>, val edges: List<Edge>)
class Vertex(val id: String?, val name: String) {
override fun hashCode(): Int {
val prime = 31
var result = 1
result = prime * result + (id?.hashCode() ?: 0)
return result
}
override fun equals(obj: Any?): Boolean {
if (this === obj)
return true
if (obj == null)
return false
if (javaClass != obj.javaClass)
return false
val other = obj as Vertex?
if (id == null) {
if (other!!.id != null)
return false
} else if (id != other!!.id)
return false
return true
}
override fun toString(): String {
return name
}
}
class TestDijkstraAlgorithm {
companion object {
private lateinit var nodes: MutableList<Vertex>
private lateinit var edges: MutableList<Edge>
@JvmStatic
fun main(args : Array<String>) {
nodes = ArrayList()
edges = ArrayList()
for (i in 0..10) {
val location = Vertex("Node_$i", "Node_$i")
nodes.add(location)
}
addLane("Edge_0", 0, 1, 85)
addLane("Edge_1", 0, 2, 217)
addLane("Edge_2", 0, 4, 173)
addLane("Edge_3", 2, 6, 186)
addLane("Edge_4", 2, 7, 103)
addLane("Edge_5", 3, 7, 183)
addLane("Edge_6", 5, 8, 250)
addLane("Edge_7", 8, 9, 84)
addLane("Edge_8", 7, 9, 167)
addLane("Edge_9", 4, 9, 502)
addLane("Edge_10", 9, 10, 40)
addLane("Edge_11", 1, 10, 600)
// Lets check from location Loc_1 to Loc_10
val graph = Graph(nodes, edges)
val dijkstra = DijkstraAlgorithm(graph)
dijkstra.execute(nodes[0])
val path = dijkstra.getPath(nodes[10])
assertNotNull(path)
assertTrue(path!!.size > 0)
for (vertex in path) {
System.out.println(vertex)
}
}
private fun addLane(laneId: String, sourceLocNo: Int, destLocNo: Int,
duration: Int) {
val lane = Edge(laneId, nodes[sourceLocNo], nodes[destLocNo], duration)
edges.add(lane)
}
}
} | cc0-1.0 | ee85a0c940989734ad93eef85e5939ea | 29.575 | 102 | 0.550376 | 4.443314 | false | false | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/pageselect/PageSelectAdapter.kt | 2 | 3224 | package com.quran.labs.androidquran.pageselect
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.quran.labs.androidquran.R
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import java.lang.ref.WeakReference
class PageSelectAdapter(val inflater: LayoutInflater,
val width: Int,
private val selectionHandler: (String) -> Unit) : PagerAdapter() {
private val items : MutableList<PageTypeItem> = mutableListOf()
private val compositeDisposable = CompositeDisposable()
private val listener = View.OnClickListener { v ->
val tag = (v.parent as View).tag
if (tag != null) {
selectionHandler(tag.toString())
}
}
fun replaceItems(updates: List<PageTypeItem>, pager: ViewPager) {
items.clear()
items.addAll(updates)
items.forEach {
val view : View? = pager.findViewWithTag(it.pageType)
if (view != null) {
updateView(view, it)
}
}
notifyDataSetChanged()
}
override fun getCount() = items.size
override fun isViewFromObject(view: View, obj: Any): Boolean {
return obj === view
}
private fun updateView(view: View, data: PageTypeItem) {
view.findViewById<TextView>(R.id.title).setText(data.title)
view.findViewById<TextView>(R.id.description).setText(data.description)
view.findViewById<FloatingActionButton>(R.id.fab).setOnClickListener(listener)
val image = view.findViewById<ImageView>(R.id.preview)
val progressBar = view.findViewById<ProgressBar>(R.id.progress_bar)
if (data.previewImage != null) {
progressBar.visibility = View.GONE
readImage(data.previewImage.path, WeakReference(image))
} else {
progressBar.visibility = View.VISIBLE
image.setImageBitmap(null)
}
}
private fun readImage(path: String, imageRef: WeakReference<ImageView>) {
compositeDisposable.add(
Maybe.fromCallable {
val options = BitmapFactory.Options().apply { inPreferredConfig = Bitmap.Config.ALPHA_8 }
BitmapFactory.decodeFile(path, options)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { imageRef.get()?.setImageBitmap(it) }
)
}
fun cleanUp() {
compositeDisposable.clear()
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val view = inflater.inflate(R.layout.page_select_page, container, false)
val item = items[position]
updateView(view, item)
view.tag = item.pageType
container.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, o: Any) {
container.removeView(o as View)
}
}
| gpl-3.0 | 0f7c6961b9a57398844a37fcfc3ab22a | 32.237113 | 99 | 0.720223 | 4.368564 | false | false | false | false |
Dissem/Jabit-Server | src/main/kotlin/ch/dissem/bitmessage/server/Utils.kt | 1 | 4290 | /*
* Copyright 2015 Christian Basler
*
* 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 ch.dissem.bitmessage.server
import ch.dissem.bitmessage.entity.BitmessageAddress
import com.google.zxing.WriterException
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import com.google.zxing.qrcode.encoder.Encoder
import com.google.zxing.qrcode.encoder.QRCode
import org.slf4j.LoggerFactory
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileWriter
import java.nio.file.Files
import java.util.*
object Utils {
private val LOG = LoggerFactory.getLogger(Utils::class.java)
fun readOrCreateList(filename: String, content: String): MutableSet<String> {
val file = File(filename).apply {
if (!exists()) {
if (createNewFile()) {
FileWriter(this).use { fw -> fw.write(content) }
}
}
}
return readList(file)
}
fun saveList(filename: String, content: Collection<String>) {
FileWriter(filename).use { fw ->
content.forEach { l ->
fw.write(l)
fw.write(System.lineSeparator())
}
}
}
fun readList(file: File) = Files.readAllLines(file.toPath())
.map { it.trim { it <= ' ' } }
.filter { it.startsWith("BM-") }
.toMutableSet()
fun getURL(address: BitmessageAddress, includeKey: Boolean): String {
val attributes = mutableListOf<String>()
if (address.alias != null) {
attributes.add("label=${address.alias}")
}
if (includeKey) {
address.pubkey?.let { pubkey ->
val out = ByteArrayOutputStream()
pubkey.writer().writeUnencrypted(out)
attributes.add("pubkey=${Base64.getUrlEncoder().encodeToString(out.toByteArray())}")
}
}
return if (attributes.isEmpty()) {
"bitmessage:${address.address}"
} else {
"bitmessage:${address.address}?${attributes.joinToString(separator = "&")}"
}
}
fun qrCode(address: BitmessageAddress): String {
val code: QRCode
try {
code = Encoder.encode(getURL(address, false), ErrorCorrectionLevel.L, null)
} catch (e: WriterException) {
LOG.error(e.message, e)
return ""
}
val matrix = code.matrix
val result = StringBuilder()
for (i in 0..1) {
for (j in 0 until matrix.width + 8) {
result.append('█')
}
result.append('\n')
}
run {
var i = 0
while (i < matrix.height) {
result.append("████")
for (j in 0 until matrix.width) {
if (matrix.get(i, j) > 0) {
if (matrix.height > i + 1 && matrix.get(i + 1, j) > 0) {
result.append(' ')
} else {
result.append('▄')
}
} else {
if (matrix.height > i + 1 && matrix.get(i + 1, j) > 0) {
result.append('▀')
} else {
result.append('█')
}
}
}
result.append("████\n")
i += 2
}
}
for (i in 0..1) {
for (j in 0 until matrix.width + 8) {
result.append('█')
}
result.append('\n')
}
return result.toString()
}
fun zero(nonce: ByteArray) = nonce.none { it.toInt() != 0 }
}
| apache-2.0 | 6c6e680a68f680359782f0d115be30a4 | 32.054264 | 100 | 0.523921 | 4.45559 | false | false | false | false |
Litote/kmongo | kmongo-coroutine-core/src/main/kotlin/org/litote/kmongo/coroutine/CoroutineCollection.kt | 1 | 84166 | /*
* Copyright (C) 2016/2022 Litote
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.litote.kmongo.coroutine
import com.mongodb.MongoCommandException
import com.mongodb.MongoNamespace
import com.mongodb.ReadConcern
import com.mongodb.ReadPreference
import com.mongodb.WriteConcern
import com.mongodb.bulk.BulkWriteResult
import com.mongodb.client.model.BulkWriteOptions
import com.mongodb.client.model.CountOptions
import com.mongodb.client.model.CreateIndexOptions
import com.mongodb.client.model.DeleteOptions
import com.mongodb.client.model.DropIndexOptions
import com.mongodb.client.model.EstimatedDocumentCountOptions
import com.mongodb.client.model.FindOneAndDeleteOptions
import com.mongodb.client.model.FindOneAndReplaceOptions
import com.mongodb.client.model.FindOneAndUpdateOptions
import com.mongodb.client.model.IndexModel
import com.mongodb.client.model.IndexOptions
import com.mongodb.client.model.InsertManyOptions
import com.mongodb.client.model.InsertOneOptions
import com.mongodb.client.model.RenameCollectionOptions
import com.mongodb.client.model.ReplaceOptions
import com.mongodb.client.model.UpdateOptions
import com.mongodb.client.model.WriteModel
import com.mongodb.client.result.DeleteResult
import com.mongodb.client.result.InsertManyResult
import com.mongodb.client.result.InsertOneResult
import com.mongodb.client.result.UpdateResult
import com.mongodb.reactivestreams.client.ClientSession
import com.mongodb.reactivestreams.client.MongoCollection
import kotlinx.coroutines.reactive.awaitFirstOrNull
import kotlinx.coroutines.reactive.awaitSingle
import org.bson.BsonDocument
import org.bson.codecs.configuration.CodecRegistry
import org.bson.conversions.Bson
import org.litote.kmongo.EMPTY_BSON
import org.litote.kmongo.SetTo
import org.litote.kmongo.and
import org.litote.kmongo.ascending
import org.litote.kmongo.excludeId
import org.litote.kmongo.fields
import org.litote.kmongo.include
import org.litote.kmongo.path
import org.litote.kmongo.reactivestreams.map
import org.litote.kmongo.set
import org.litote.kmongo.util.KMongoUtil
import org.litote.kmongo.util.KMongoUtil.EMPTY_JSON
import org.litote.kmongo.util.KMongoUtil.extractId
import org.litote.kmongo.util.KMongoUtil.idFilterQuery
import org.litote.kmongo.util.KMongoUtil.setModifier
import org.litote.kmongo.util.KMongoUtil.toBson
import org.litote.kmongo.util.KMongoUtil.toBsonModifier
import org.litote.kmongo.util.PairProjection
import org.litote.kmongo.util.SingleProjection
import org.litote.kmongo.util.TripleProjection
import org.litote.kmongo.util.UpdateConfiguration
import org.litote.kmongo.util.pairProjectionCodecRegistry
import org.litote.kmongo.util.singleProjectionCodecRegistry
import org.litote.kmongo.util.tripleProjectionCodecRegistry
import kotlin.reflect.KProperty
import kotlin.reflect.KProperty1
/**
* Gets coroutine version of [MongoCollection].
*/
val <T : Any> MongoCollection<T>.coroutine: CoroutineCollection<T> get() = CoroutineCollection(this)
/**
* A wrapper around [MongoCollection].
* Provides coroutine methods for [Reactive Streams driver](https://mongodb.github.io/mongo-java-driver-reactivestreams/).
*/
class CoroutineCollection<T : Any>(val collection: MongoCollection<T>) {
/**
* Gets the namespace of this collection.
*
* @return the namespace
*/
val namespace: MongoNamespace get() = collection.namespace
/**
* Get the class of documents stored in this collection.
*
* @return the class
*/
val documentClass: Class<T> get() = collection.documentClass
/**
* Get the codec registry for the MongoCollection.
*
* @return the [org.bson.codecs.configuration.CodecRegistry]
*/
val codecRegistry: CodecRegistry get() = collection.codecRegistry
/**
* Get the read preference for the MongoCollection.
*
* @return the [com.mongodb.ReadPreference]
*/
val readPreference: ReadPreference get() = collection.readPreference
/**
* Get the write concern for the MongoCollection.
*
* @return the [com.mongodb.WriteConcern]
*/
val writeConcern: WriteConcern get() = collection.writeConcern
/**
* Get the read concern for the MongoCollection.
*
* @return the [com.mongodb.ReadConcern]
* @mongodb.server.release 3.2
* @since 1.2
*/
val readConcern: ReadConcern get() = collection.readConcern
/**
* Create a new MongoCollection instance with a different default class to cast any documents returned from the database into..
*
* @param <NewT> The type that the new collection will encode documents from and decode documents to
* @return a new MongoCollection instance with the different default class
*/
inline fun <reified NewT : Any> withDocumentClass(): CoroutineCollection<NewT> =
collection.withDocumentClass(NewT::class.java).coroutine
/**
* Create a new MongoCollection instance with a different codec registry.
*
* @param codecRegistry the new [org.bson.codecs.configuration.CodecRegistry] for the collection
* @return a new MongoCollection instance with the different codec registry
*/
fun withCodecRegistry(codecRegistry: CodecRegistry): CoroutineCollection<T> =
collection.withCodecRegistry(codecRegistry).coroutine
/**
* Create a new MongoCollection instance with a different read preference.
*
* @param readPreference the new [com.mongodb.ReadPreference] for the collection
* @return a new MongoCollection instance with the different readPreference
*/
fun withReadPreference(readPreference: ReadPreference): CoroutineCollection<T> =
collection.withReadPreference(readPreference).coroutine
/**
* Create a new MongoCollection instance with a different write concern.
*
* @param writeConcern the new [com.mongodb.WriteConcern] for the collection
* @return a new MongoCollection instance with the different writeConcern
*/
fun withWriteConcern(writeConcern: WriteConcern): CoroutineCollection<T> =
collection.withWriteConcern(writeConcern).coroutine
/**
* Create a new MongoCollection instance with a different read concern.
*
* @param readConcern the new [ReadConcern] for the collection
* @return a new MongoCollection instance with the different ReadConcern
* @mongodb.server.release 3.2
* @since 1.2
*/
fun withReadConcern(readConcern: ReadConcern): CoroutineCollection<T> =
collection.withReadConcern(readConcern).coroutine
/**
* Gets an estimate of the count of documents in a collection using collection metadata.
*
* @param options the options describing the count
* @since 1.9
*/
suspend fun estimatedDocumentCount(options: EstimatedDocumentCountOptions = EstimatedDocumentCountOptions()): Long =
collection.estimatedDocumentCount(options).awaitSingle()
/**
* Counts the number of documents in the collection according to the given options.
*
*
*
* Note: When migrating from `count()` to `countDocuments()` the following query operators must be replaced:
*
* <pre>
*
* +-------------+--------------------------------+
* | Operator | Replacement |
* +=============+================================+
* | $where | $expr |
* +-------------+--------------------------------+
* | $near | $geoWithin with $center |
* +-------------+--------------------------------+
* | $nearSphere | $geoWithin with $centerSphere |
* +-------------+--------------------------------+
</pre> *
*
* @param filter the query filter
* @param options the options describing the count
* @since 1.9
*/
suspend fun countDocuments(filter: Bson = EMPTY_BSON, options: CountOptions = CountOptions()): Long =
collection.countDocuments(filter, options).awaitSingle()
/**
* Counts the number of documents in the collection according to the given options.
*
*
*
* Note: When migrating from `count()` to `countDocuments()` the following query operators must be replaced:
*
* <pre>
*
* +-------------+--------------------------------+
* | Operator | Replacement |
* +=============+================================+
* | $where | $expr |
* +-------------+--------------------------------+
* | $near | $geoWithin with $center |
* +-------------+--------------------------------+
* | $nearSphere | $geoWithin with $centerSphere |
* +-------------+--------------------------------+
</pre> *
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter
* @param options the options describing the count
* @mongodb.server.release 3.6
* @since 1.9
*/
suspend fun countDocuments(
clientSession: ClientSession,
filter: Bson = EMPTY_BSON,
options: CountOptions = CountOptions()
): Long =
collection.countDocuments(clientSession, filter, options).awaitSingle()
/**
* Gets the distinct values of the specified field name.
*
* @param fieldName the field name
* @param filter the query filter
* @param <T> the target type of the iterable.
* @mongodb.driver.manual reference/command/distinct/ Distinct
*/
inline fun <reified T : Any> distinct(
fieldName: String,
filter: Bson = EMPTY_BSON
): CoroutineDistinctPublisher<T> =
collection.distinct(fieldName, filter, T::class.java).coroutine
/**
* Gets the distinct values of the specified field name.
*
* @param clientSession the client session with which to associate this operation
* @param fieldName the field name
* @param filter the query filter
* @param <T> the target type of the iterable.
* @mongodb.driver.manual reference/command/distinct/ Distinct
* @mongodb.server.release 3.6
* @since 1.7
*/
inline fun <reified T : Any> distinct(
clientSession: ClientSession,
fieldName: String,
filter: Bson
): CoroutineDistinctPublisher<T> =
collection.distinct(clientSession, fieldName, filter, T::class.java).coroutine
/**
* Finds all documents in the collection.
*
* @param filter the query filter
* @mongodb.driver.manual tutorial/query-documents/ Find
*/
fun find(filter: Bson = EMPTY_BSON): CoroutineFindPublisher<T> = collection.find(filter).coroutine
/**
* Finds all documents in the collection.
*
* @param filter the query filter
* @param <T> the target document type of the iterable.
* @mongodb.driver.manual tutorial/query-documents/ Find
*/
inline fun <reified T : Any> findAndCast(filter: Bson = EMPTY_BSON): CoroutineFindPublisher<T> =
collection.find(filter, T::class.java).coroutine
/**
* Finds all documents in the collection.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter
* @mongodb.driver.manual tutorial/query-documents/ Find
* @mongodb.server.release 3.6
* @since 1.7
*/
fun find(clientSession: ClientSession, filter: Bson = EMPTY_BSON): CoroutineFindPublisher<T> =
collection.find(clientSession, filter).coroutine
/**
* Finds all documents in the collection.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter
* @param <T> the target document type of the iterable.
* @mongodb.driver.manual tutorial/query-documents/ Find
* @mongodb.server.release 3.6
* @since 1.7
*/
inline fun <reified T : Any> findAndCast(
clientSession: ClientSession,
filter: Bson
): CoroutineFindPublisher<T> = collection.find(clientSession, filter, T::class.java).coroutine
/**
* Aggregates documents according to the specified aggregation pipeline.
*
* @param pipeline the aggregate pipeline
* @param <T> the target document type of the iterable.
* @return a publisher containing the result of the aggregation operation
* @mongodb.driver.manual aggregation/ Aggregation
*/
inline fun <reified T : Any> aggregate(pipeline: List<Bson>): CoroutineAggregatePublisher<T> =
collection.aggregate(pipeline, T::class.java).coroutine
/**
* Aggregates documents according to the specified aggregation pipeline.
*
* @param clientSession the client session with which to associate this operation
* @param pipeline the aggregate pipeline
* @param <T> the target document type of the iterable.
* @return a publisher containing the result of the aggregation operation
* @mongodb.driver.manual aggregation/ Aggregation
* @mongodb.server.release 3.6
* @since 1.7
*/
inline fun <reified T : Any> aggregate(
clientSession: ClientSession,
pipeline: List<Bson>
): CoroutineAggregatePublisher<T> =
collection.aggregate(clientSession, pipeline, T::class.java).coroutine
/**
* Creates a change stream for this collection.
*
* @param pipeline the aggregation pipeline to apply to the change stream
* @param <T> the target document type of the iterable.
* @return the change stream iterable
* @mongodb.driver.manual reference/operator/aggregation/changeStream $changeStream
* @since 1.6
*/
inline fun <reified T : Any> watch(pipeline: List<Bson> = emptyList()): CoroutineChangeStreamPublisher<T> =
collection.watch(pipeline, T::class.java).coroutine
/**
* Creates a change stream for this collection.
*
* @param clientSession the client session with which to associate this operation
* @param pipeline the aggregation pipeline to apply to the change stream
* @param <T> the target document type of the iterable.
* @return the change stream iterable
* @mongodb.driver.manual reference/operator/aggregation/changeStream $changeStream
* @mongodb.server.release 3.6
* @since 1.7
*/
inline fun <reified T : Any> watch(
clientSession: ClientSession,
pipeline: List<Bson>
): CoroutineChangeStreamPublisher<T> =
collection.watch(clientSession, pipeline, T::class.java).coroutine
/**
* Aggregates documents according to the specified map-reduce function.
*
* @param mapFunction A JavaScript function that associates or "maps" a value with a key and emits the key and value pair.
* @param reduceFunction A JavaScript function that "reduces" to a single object all the values associated with a particular key.
* @param <T> the target document type of the iterable.
* @return a publisher containing the result of the map-reduce operation
* @mongodb.driver.manual reference/command/mapReduce/ map-reduce
*/
inline fun <reified T : Any> mapReduce(
mapFunction: String,
reduceFunction: String
): CoroutineMapReducePublisher<T> = collection.mapReduce(mapFunction, reduceFunction, T::class.java).coroutine
/**
* Aggregates documents according to the specified map-reduce function.
*
* @param clientSession the client session with which to associate this operation
* @param mapFunction A JavaScript function that associates or "maps" a value with a key and emits the key and value pair.
* @param reduceFunction A JavaScript function that "reduces" to a single object all the values associated with a particular key.
* @param <T> the target document type of the iterable.
* @return a publisher containing the result of the map-reduce operation
* @mongodb.driver.manual reference/command/mapReduce/ map-reduce
* @mongodb.server.release 3.6
* @since 1.7
*/
inline fun <reified T : Any> mapReduce(
clientSession: ClientSession, mapFunction: String, reduceFunction: String
): CoroutineMapReducePublisher<T> =
collection.mapReduce(clientSession, mapFunction, reduceFunction, T::class.java).coroutine
/**
* Executes a mix of inserts, updates, replaces, and deletes.
*
* @param requests the writes to execute
* @param options the options to apply to the bulk write operation
* @return the BulkWriteResult
*/
suspend fun bulkWrite(
requests: List<WriteModel<out T>>,
options: BulkWriteOptions = BulkWriteOptions()
): BulkWriteResult = collection.bulkWrite(requests, options).awaitSingle()
/**
* Executes a mix of inserts, updates, replaces, and deletes.
*
* @param clientSession the client session with which to associate this operation
* @param requests the writes to execute
* @param options the options to apply to the bulk write operation
* @return the BulkWriteResult
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun bulkWrite(
clientSession: ClientSession, requests: List<WriteModel<out T>>,
options: BulkWriteOptions = BulkWriteOptions()
): BulkWriteResult = collection.bulkWrite(clientSession, requests, options).awaitSingle()
/**
* Inserts the provided document. If the document is missing an identifier, the driver should generate one.
*
* @param document the document to insert
* @param options the options to apply to the operation
* com.mongodb.DuplicateKeyException or com.mongodb.MongoException
* @since 1.2
*/
suspend fun insertOne(document: T, options: InsertOneOptions = InsertOneOptions()): InsertOneResult =
collection.insertOne(document, options).awaitSingle()
/**
* Inserts the provided document. If the document is missing an identifier, the driver should generate one.
*
* @param clientSession the client session with which to associate this operation
* @param document the document to insert
* @param options the options to apply to the operation
* com.mongodb.DuplicateKeyException or com.mongodb.MongoException
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun insertOne(
clientSession: ClientSession,
document: T,
options: InsertOneOptions = InsertOneOptions()
): InsertOneResult = collection.insertOne(clientSession, document, options).awaitSingle()
/**
* Inserts a batch of documents. The preferred way to perform bulk inserts is to use the BulkWrite API. However, when talking with a
* server < 2.6, using this method will be faster due to constraints in the bulk API related to error handling.
*
* @param documents the documents to insert
* @param options the options to apply to the operation
* com.mongodb.DuplicateKeyException or com.mongodb.MongoException
*/
suspend fun insertMany(documents: List<T>, options: InsertManyOptions = InsertManyOptions()): InsertManyResult =
collection.insertMany(documents, options).awaitSingle()
/**
* Inserts a batch of documents. The preferred way to perform bulk inserts is to use the BulkWrite API. However, when talking with a
* server < 2.6, using this method will be faster due to constraints in the bulk API related to error handling.
*
* @param clientSession the client session with which to associate this operation
* @param documents the documents to insert
* @param options the options to apply to the operation
* com.mongodb.DuplicateKeyException or com.mongodb.MongoException
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun insertMany(
clientSession: ClientSession,
documents: List<T>,
options: InsertManyOptions = InsertManyOptions()
): InsertManyResult =
collection.insertMany(clientSession, documents, options).awaitSingle()
/**
* Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not
* modified.
*
* @param filter the query filter to apply the the delete operation
* @param options the options to apply to the delete operation
* @return the DeleteResult or an com.mongodb.MongoException
* @since 1.5
*/
suspend fun deleteOne(filter: Bson, options: DeleteOptions = DeleteOptions()): DeleteResult =
collection.deleteOne(filter, options).awaitSingle()
/**
* Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not
* modified.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter to apply the the delete operation
* @param options the options to apply to the delete operation
* @return the DeleteResult or an com.mongodb.MongoException
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun deleteOne(
clientSession: ClientSession,
filter: Bson,
options: DeleteOptions = DeleteOptions()
): DeleteResult =
collection.deleteOne(clientSession, filter, options).awaitSingle()
/**
* Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified.
*
* @param filter the query filter to apply the the delete operation
* @param options the options to apply to the delete operation
* @return the DeleteResult or an com.mongodb.MongoException
* @since 1.5
*/
suspend fun deleteMany(filter: Bson, options: DeleteOptions = DeleteOptions()): DeleteResult =
collection.deleteMany(filter, options).awaitSingle()
/**
* Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter to apply the the delete operation
* @param options the options to apply to the delete operation
* @return the DeleteResult or an com.mongodb.MongoException
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun deleteMany(
clientSession: ClientSession,
filter: Bson,
options: DeleteOptions = DeleteOptions()
): DeleteResult =
collection.deleteMany(clientSession, filter, options).awaitSingle()
/**
* Replace a document in the collection according to the specified arguments.
*
* @param filter the query filter to apply the the replace operation
* @param replacement the replacement document
* @param options the options to apply to the replace operation
* @return he UpdateResult
* @mongodb.driver.manual tutorial/modify-documents/#replace-the-document Replace
* @since 1.8
*/
suspend fun replaceOne(filter: Bson, replacement: T, options: ReplaceOptions = ReplaceOptions()): UpdateResult =
collection.replaceOne(filter, replacement, options).awaitSingle()
/**
* Replace a document in the collection according to the specified arguments.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter to apply the the replace operation
* @param replacement the replacement document
* @param options the options to apply to the replace operation
* @return the UpdateResult
* @mongodb.driver.manual tutorial/modify-documents/#replace-the-document Replace
* @mongodb.server.release 3.6
* @since 1.8
*/
suspend fun replaceOne(
clientSession: ClientSession,
filter: Bson,
replacement: T,
options: ReplaceOptions = ReplaceOptions()
): UpdateResult =
collection.replaceOne(clientSession, filter, replacement, options).awaitSingle()
/**
* Update a single document in the collection according to the specified arguments.
*
* @param filter a document describing the query filter, which may not be null.
* @param update a document describing the update, which may not be null. The update to apply must include only update operators.
* @param options the options to apply to the update operation
* @return the UpdateResult
* @mongodb.driver.manual tutorial/modify-documents/ Updates
* @mongodb.driver.manual reference/operator/update/ Update Operators
*/
suspend fun updateOne(filter: Bson, update: Bson, options: UpdateOptions = UpdateOptions()): UpdateResult =
collection.updateOne(filter, update, options).awaitSingle()
/**
* Update a single document in the collection according to the specified arguments.
*
* @param clientSession the client session with which to associate this operation
* @param filter a document describing the query filter, which may not be null.
* @param update a document describing the update, which may not be null. The update to apply must include only update operators.
* @param options the options to apply to the update operation
* @return the UpdateResult
* @mongodb.driver.manual tutorial/modify-documents/ Updates
* @mongodb.driver.manual reference/operator/update/ Update Operators
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun updateOne(
clientSession: ClientSession,
filter: Bson,
update: Bson,
options: UpdateOptions = UpdateOptions()
): UpdateResult =
collection.updateOne(clientSession, filter, update, options).awaitSingle()
/**
* Update all documents in the collection according to the specified arguments.
*
* @param filter a document describing the query filter, which may not be null.
* @param update a document describing the update, which may not be null. The update to apply must include only update operators.
* @param options the options to apply to the update operation
* @return the UpdateResult
* @mongodb.driver.manual tutorial/modify-documents/ Updates
* @mongodb.driver.manual reference/operator/update/ Update Operators
*/
suspend fun updateMany(filter: Bson, update: Bson, options: UpdateOptions = UpdateOptions()): UpdateResult =
collection.updateMany(filter, update, options).awaitSingle()
/**
* Update all documents in the collection according to the specified arguments.
*
* @param clientSession the client session with which to associate this operation
* @param filter a document describing the query filter, which may not be null.
* @param update a document describing the update, which may not be null. The update to apply must include only update operators.
* @param options the options to apply to the update operation
* @return the UpdateResult
* @mongodb.driver.manual tutorial/modify-documents/ Updates
* @mongodb.driver.manual reference/operator/update/ Update Operators
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun updateMany(
clientSession: ClientSession,
filter: Bson,
update: Bson,
options: UpdateOptions = UpdateOptions()
): UpdateResult =
collection.updateMany(clientSession, filter, update, options).awaitSingle()
/**
* Atomically find a document and remove it.
*
* @param filter the query filter to find the document with
* @param options the options to apply to the operation
* @return the document that was removed. If no documents matched the query filter, then null will be
* returned
*/
suspend fun findOneAndDelete(filter: Bson, options: FindOneAndDeleteOptions = FindOneAndDeleteOptions()): T? =
collection.findOneAndDelete(filter, options).awaitFirstOrNull()
/**
* Atomically find a document and remove it.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter to find the document with
* @param options the options to apply to the operation
* @return a publisher with a single element the document that was removed. If no documents matched the query filter, then null will be
* returned
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun findOneAndDelete(
clientSession: ClientSession,
filter: Bson,
options: FindOneAndDeleteOptions = FindOneAndDeleteOptions()
): T? = collection.findOneAndDelete(clientSession, filter, options).awaitFirstOrNull()
/**
* Atomically find a document and replace it.
*
* @param filter the query filter to apply the the replace operation
* @param replacement the replacement document
* @param options the options to apply to the operation
* @return the document that was replaced. Depending on the value of the `returnOriginal`
* property, this will either be the document as it was before the update or as it is after the update. If no documents matched the
* query filter, then null will be returned
*/
suspend fun findOneAndReplace(
filter: Bson,
replacement: T,
options: FindOneAndReplaceOptions = FindOneAndReplaceOptions()
): T? = collection.findOneAndReplace(filter, replacement, options).awaitFirstOrNull()
/**
* Atomically find a document and replace it.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter to apply the the replace operation
* @param replacement the replacement document
* @param options the options to apply to the operation
* @return the document that was replaced. Depending on the value of the `returnOriginal`
* property, this will either be the document as it was before the update or as it is after the update. If no documents matched the
* query filter, then null will be returned
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun findOneAndReplace(
clientSession: ClientSession, filter: Bson, replacement: T,
options: FindOneAndReplaceOptions = FindOneAndReplaceOptions()
): T? = collection.findOneAndReplace(clientSession, filter, replacement, options).awaitFirstOrNull()
/**
* Atomically find a document and update it.
*
* @param filter a document describing the query filter, which may not be null.
* @param update a document describing the update, which may not be null. The update to apply must include only update operators.
* @param options the options to apply to the operation
* @return the document that was updated. Depending on the value of the `returnOriginal`
* property, this will either be the document as it was before the update or as it is after the update. If no documents matched the
* query filter, then null will be returned
*/
suspend fun findOneAndUpdate(
filter: Bson,
update: Bson,
options: FindOneAndUpdateOptions = FindOneAndUpdateOptions()
): T? =
collection.findOneAndUpdate(filter, update, options).awaitFirstOrNull()
/**
* Atomically find a document and update it.
*
* @param clientSession the client session with which to associate this operation
* @param filter a document describing the query filter, which may not be null.
* @param update a document describing the update, which may not be null. The update to apply must include only update operators.
* @param options the options to apply to the operation
* @return a publisher with a single element the document that was updated. Depending on the value of the `returnOriginal`
* property, this will either be the document as it was before the update or as it is after the update. If no documents matched the
* query filter, then null will be returned
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun findOneAndUpdate(
clientSession: ClientSession,
filter: Bson,
update: Bson,
options: FindOneAndUpdateOptions = FindOneAndUpdateOptions()
): T? = collection.findOneAndUpdate(clientSession, filter, update, options).awaitFirstOrNull()
/**
* Drops this collection from the Database.
*
* @mongodb.driver.manual reference/command/drop/ Drop Collection
*/
suspend fun drop() = collection.drop().awaitFirstOrNull()
/**
* Drops this collection from the Database.
*
* @param clientSession the client session with which to associate this operation
* @mongodb.driver.manual reference/command/drop/ Drop Collection
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun drop(clientSession: ClientSession) = collection.drop(clientSession).awaitFirstOrNull()
/**
* Creates an index.
*
* @param key an object describing the index key(s), which may not be null.
* @param options the options for the index
* @return a single element indicating when the operation has completed
* @mongodb.driver.manual reference/method/db.collection.ensureIndex Ensure Index
*/
suspend fun createIndex(key: Bson, options: IndexOptions = IndexOptions()): String =
collection.createIndex(key, options).awaitSingle()
/**
* Creates an index.
*
* @param clientSession the client session with which to associate this operation
* @param key an object describing the index key(s), which may not be null.
* @param options the options for the index
* @return a single element indicating when the operation has completed
* @mongodb.driver.manual reference/method/db.collection.ensureIndex Ensure Index
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun createIndex(clientSession: ClientSession, key: Bson, options: IndexOptions = IndexOptions()): String =
collection.createIndex(clientSession, key, options).awaitSingle()
/**
* Create multiple indexes.
*
* @param indexes the list of indexes
* @param createIndexOptions options to use when creating indexes
* @return a list of elements indicating index creation operation completion
* @mongodb.driver.manual reference/command/createIndexes Create indexes
* @mongodb.server.release 2.6
* @since 1.7
*/
suspend fun createIndexes(
indexes: List<IndexModel>,
createIndexOptions: CreateIndexOptions = CreateIndexOptions()
): List<String> =
collection.createIndexes(indexes, createIndexOptions).toList()
/**
* Create multiple indexes.
*
* @param clientSession the client session with which to associate this operation
* @param indexes the list of indexes
* @param createIndexOptions options to use when creating indexes
* @return a list of elements indicating index creation operation completion
* @mongodb.driver.manual reference/command/createIndexes Create indexes
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun createIndexes(
clientSession: ClientSession,
indexes: List<IndexModel>,
createIndexOptions: CreateIndexOptions = CreateIndexOptions()
): List<String> =
collection.createIndexes(clientSession, indexes, createIndexOptions).toList()
/**
* Get all the indexes in this collection.
*
* @param <T> the target document type of the iterable.
* @return the fluent list indexes interface
* @mongodb.driver.manual reference/command/listIndexes/ listIndexes
*/
inline fun <reified T : Any> listIndexes(): CoroutineListIndexesPublisher<T> =
collection.listIndexes(T::class.java).coroutine
/**
* Get all the indexes in this collection.
*
* @param clientSession the client session with which to associate this operation
* @param <T> the target document type of the iterable.
* @return the fluent list indexes interface
* @mongodb.driver.manual reference/command/listIndexes/ listIndexes
* @mongodb.server.release 3.6
* @since 1.7
*/
inline fun <reified T : Any> listIndexes(
clientSession: ClientSession
): CoroutineListIndexesPublisher<T> = collection.listIndexes(clientSession, T::class.java).coroutine
/**
* Drops the given index.
*
* @param indexName the name of the index to remove
* @param dropIndexOptions options to use when dropping indexes
* @return a single element indicating when the operation has completed
* @mongodb.driver.manual reference/command/dropIndexes/ Drop Indexes
* @since 1.7
*/
suspend fun dropIndex(indexName: String, dropIndexOptions: DropIndexOptions = DropIndexOptions()) =
collection.dropIndex(indexName, dropIndexOptions).awaitFirstOrNull()
/**
* Drops the index given the keys used to create it.
*
* @param keys the keys of the index to remove
* @param dropIndexOptions options to use when dropping indexes
* @return a single element indicating when the operation has completed
* @mongodb.driver.manual reference/command/dropIndexes/ Drop indexes
* @since 1.7
*/
suspend fun dropIndex(keys: Bson, dropIndexOptions: DropIndexOptions = DropIndexOptions()) =
collection.dropIndex(keys, dropIndexOptions).awaitFirstOrNull()
/**
* Drops the given index.
*
* @param clientSession the client session with which to associate this operation
* @param indexName the name of the index to remove
* @param dropIndexOptions options to use when dropping indexes
* @return a single element indicating when the operation has completed
* @mongodb.driver.manual reference/command/dropIndexes/ Drop Indexes
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun dropIndex(
clientSession: ClientSession,
indexName: String,
dropIndexOptions: DropIndexOptions = DropIndexOptions()
) = collection.dropIndex(clientSession, indexName, dropIndexOptions).awaitFirstOrNull()
/**
* Drops the index given the keys used to create it.
*
* @param clientSession the client session with which to associate this operation
* @param keys the keys of the index to remove
* @param dropIndexOptions options to use when dropping indexes
* @return a single element indicating when the operation has completed
* @mongodb.driver.manual reference/command/dropIndexes/ Drop indexes
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun dropIndex(
clientSession: ClientSession,
keys: Bson,
dropIndexOptions: DropIndexOptions = DropIndexOptions()
) = collection.dropIndex(clientSession, keys, dropIndexOptions).awaitFirstOrNull()
/**
* Drop all the indexes on this collection, except for the default on _id.
*
* @param dropIndexOptions options to use when dropping indexes
* @return a single element indicating when the operation has completed
* @mongodb.driver.manual reference/command/dropIndexes/ Drop Indexes
* @since 1.7
*/
suspend fun dropIndexes(dropIndexOptions: DropIndexOptions = DropIndexOptions()) =
collection.dropIndexes(dropIndexOptions).awaitFirstOrNull()
/**
* Drop all the indexes on this collection, except for the default on _id.
*
* @param clientSession the client session with which to associate this operation
* @param dropIndexOptions options to use when dropping indexes
* @return a single element indicating when the operation has completed
* @mongodb.driver.manual reference/command/dropIndexes/ Drop Indexes
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun dropIndexes(
clientSession: ClientSession,
dropIndexOptions: DropIndexOptions = DropIndexOptions()
) = collection.dropIndexes(clientSession, dropIndexOptions).awaitFirstOrNull()
/**
* Rename the collection with oldCollectionName to the newCollectionName.
*
* @param newCollectionNamespace the name the collection will be renamed to
* @param options the options for renaming a collection
* @return a single element indicating when the operation has completed
* @mongodb.driver.manual reference/commands/renameCollection Rename collection
*/
suspend fun renameCollection(
newCollectionNamespace: MongoNamespace,
options: RenameCollectionOptions = RenameCollectionOptions()
) = collection.renameCollection(newCollectionNamespace, options).awaitFirstOrNull()
/**
* Rename the collection with oldCollectionName to the newCollectionName.
*
* @param clientSession the client session with which to associate this operation
* @param newCollectionNamespace the name the collection will be renamed to
* @param options the options for renaming a collection
* @return a single element indicating when the operation has completed
* @mongodb.driver.manual reference/commands/renameCollection Rename collection
* @mongodb.server.release 3.6
* @since 1.7
*/
suspend fun renameCollection(
clientSession: ClientSession, newCollectionNamespace: MongoNamespace,
options: RenameCollectionOptions = RenameCollectionOptions()
) = collection.renameCollection(clientSession, newCollectionNamespace, options).awaitFirstOrNull()
/** KMongo extensions **/
/**
* Counts the number of documents in the collection according to the given options.
*
* @param filter the query filter
* @return count of filtered collection
*/
suspend fun countDocuments(filter: String, options: CountOptions = CountOptions()): Long =
countDocuments(toBson(filter), options)
/**
* Counts the number of documents in the collection according to the given options.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter
* @param options optional parameter, the options describing the count * @return count of filtered collection
*/
suspend fun countDocuments(
clientSession: ClientSession,
filter: String,
options: CountOptions = CountOptions()
): Long = countDocuments(clientSession, toBson(filter), options)
/**
* Gets the distinct values of the specified field name.
*
* @param fieldName the field name
* @param filter the query filter
* @param <Type> the target type of the iterable
*/
inline fun <reified Type : Any> distinct(
fieldName: String,
filter: String
): CoroutineDistinctPublisher<Type> = distinct(fieldName, toBson(filter))
/**
* Gets the distinct values of the specified field.
*
* @param field the field
* @param filter the query filter
* @param <Type> the target type of the iterable.
*/
inline fun <reified Type : Any> distinct(
field: KProperty1<T, Type>,
filter: Bson = EMPTY_BSON
): CoroutineDistinctPublisher<Type> = distinct(field.path(), filter)
/**
* Finds all documents that match the filter in the collection.
*
* @param filter the query filter
* @return the find iterable interface
*/
fun find(filter: String): CoroutineFindPublisher<T> = find(toBson(filter))
/**
* Finds all documents in the collection.
*
* @param filters the query filters
* @return the find iterable interface
*/
fun find(vararg filters: Bson?): CoroutineFindPublisher<T> = find(and(*filters))
/**
* Finds the first document that match the filter in the collection.
*
* @param filter the query filter
*/
suspend fun findOne(filter: String = KMongoUtil.EMPTY_JSON): T? = find(filter).first()
/**
* Finds the first document that match the filter in the collection.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter
*/
suspend fun findOne(
clientSession: ClientSession,
filter: String = KMongoUtil.EMPTY_JSON
): T? = find(clientSession, toBson(filter)).first()
/**
* Finds the first document that match the filter in the collection.
*
* @param filter the query filter
*/
suspend fun findOne(filter: Bson): T? = find(filter).first()
/**
* Finds the first document that match the filter in the collection.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter
*/
suspend fun findOne(clientSession: ClientSession, filter: Bson = EMPTY_BSON): T? =
find(clientSession, filter).first()
/**
* Finds the first document that match the filters in the collection.
*
* @param filters the query filters
* @return the first item returned or null
*/
suspend fun findOne(vararg filters: Bson?): T? = find(*filters).first()
/**
* Finds the document that match the id parameter.
*
* @param id the object id
*/
suspend fun findOneById(id: Any): T? = findOne(idFilterQuery(id))
/**
* Finds the document that match the id parameter.
*
* @param id the object id
* @param clientSession the client session with which to associate this operation
*/
suspend fun findOneById(id: Any, clientSession: ClientSession): T? {
return findOne(clientSession, idFilterQuery(id))
}
/**
* Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not
* modified.
*
* @param filter the query filter to apply the the delete operation
*
* @return the result of the remove one operation
*/
suspend fun deleteOne(
filter: String,
deleteOptions: DeleteOptions = DeleteOptions()
): DeleteResult = deleteOne(toBson(filter), deleteOptions)
/**
* Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not
* modified.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter to apply the the delete operation
*
* @return the result of the remove one operation
*/
suspend fun deleteOne(
clientSession: ClientSession,
filter: String,
deleteOptions: DeleteOptions = DeleteOptions()
): DeleteResult = deleteOne(clientSession, toBson(filter), deleteOptions)
/**
* Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not
* modified.
*
* @param filters the query filters to apply the the delete operation
*
* @return the result of the remove one operation
*/
suspend fun deleteOne(
vararg filters: Bson?,
deleteOptions: DeleteOptions = DeleteOptions()
): DeleteResult = deleteOne(and(*filters), deleteOptions)
/**
* Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not
* modified.
* @param clientSession the client session with which to associate this operation
* @param filters the query filters to apply the the delete operation
*
* @return the result of the remove one operation
*/
suspend fun deleteOne(
clientSession: ClientSession,
vararg filters: Bson?,
deleteOptions: DeleteOptions = DeleteOptions()
): DeleteResult = deleteOne(clientSession, and(*filters), deleteOptions)
/**
* Removes at most one document from the id parameter. If no documents match, the collection is not
* modified.
*
* @param id the object id
*/
suspend fun deleteOneById(id: Any): DeleteResult =
deleteOne(idFilterQuery(id))
/**
* Removes at most one document from the id parameter. If no documents match, the collection is not
* modified.
*
* @param clientSession the client session with which to associate this operation
* @param id the object id
*/
suspend fun deleteOneById(clientSession: ClientSession, id: Any): DeleteResult =
deleteOne(clientSession, idFilterQuery(id))
/**
* Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified.
* @param filter the query filter to apply the the delete operation
* @param options the options to apply to the delete operation
*
* @return the result of the remove many operation
*/
suspend fun deleteMany(
filter: String = EMPTY_JSON,
options: DeleteOptions = DeleteOptions()
): DeleteResult = deleteMany(toBson(filter), options)
/**
* Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter to apply the the delete operation
* @param options the options to apply to the delete operation
*
* @return the result of the remove many operation
*/
suspend fun deleteMany(
clientSession: ClientSession,
filter: String = EMPTY_JSON,
options: DeleteOptions = DeleteOptions()
): DeleteResult = deleteMany(clientSession, toBson(filter), options)
/**
* Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified.
*
* @param filters the query filters to apply the the delete operation
* @param options the options to apply to the delete operation
*
* @return the result of the remove many operation
*/
suspend fun deleteMany(
vararg filters: Bson?,
options: DeleteOptions = DeleteOptions()
): DeleteResult = deleteMany(and(*filters), options)
/**
* Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified.
*
* @param clientSession the client session with which to associate this operation
* @param filters the query filters to apply the the delete operation
* @param options the options to apply to the delete operation
*
* @return the result of the remove many operation
*/
suspend fun deleteMany(
clientSession: ClientSession,
vararg filters: Bson?,
options: DeleteOptions = DeleteOptions()
): DeleteResult = deleteMany(clientSession, and(*filters), options)
/**
* Save the document.
* If the document has no id field, or if the document has a null id value, insert the document.
* Otherwise, call [replaceOneById] with upsert true.
*
* @param document the document to save
*/
suspend fun save(document: T): UpdateResult? {
val id = KMongoUtil.getIdValue(document)
return if (id != null) {
replaceOneById(id, document, ReplaceOptions().upsert(true))
} else {
insertOne(document)
null
}
}
/**
* Save the document.
* If the document has no id field, or if the document has a null id value, insert the document.
* Otherwise, call [replaceOneById] with upsert true.
*
* @param clientSession the client session with which to associate this operation
* @param document the document to save
*/
suspend fun save(clientSession: ClientSession, document: T): UpdateResult? {
val id = KMongoUtil.getIdValue(document)
return if (id != null) {
replaceOneById(clientSession, id, document, ReplaceOptions().upsert(true))
} else {
insertOne(clientSession, document)
null
}
}
/**
* Replace a document in the collection according to the specified arguments.
*
* @param id the object id
* @param replacement the replacement document
* @param options the options to apply to the replace operation
*
* @return the result of the replace one operation
*/
suspend fun <T : Any> replaceOneById(
id: Any,
replacement: T,
options: ReplaceOptions = ReplaceOptions()
): UpdateResult = replaceOneWithoutId<T>(idFilterQuery(id), replacement, options)
/**
* Replace a document in the collection according to the specified arguments.
*
* @param clientSession the client session with which to associate this operation
* @param id the object id
* @param replacement the replacement document
* @param options the options to apply to the replace operation
*
* @return the result of the replace one operation
*/
suspend fun replaceOneById(
clientSession: ClientSession,
id: Any,
replacement: T,
options: ReplaceOptions = ReplaceOptions()
): UpdateResult = replaceOneWithoutId(clientSession, idFilterQuery(id), replacement, options)
/**
* Replace a document in the collection according to the specified arguments.
*
* @param filter the query filter to apply to the replace operation
* @param replacement the replacement document
* @param options the options to apply to the replace operation
*
* @return the result of the replace one operation
*/
suspend fun replaceOne(
filter: String,
replacement: T,
options: ReplaceOptions = ReplaceOptions()
): UpdateResult = replaceOne(toBson(filter), replacement, options)
/**
* Replace a document in the collection according to the specified arguments.
* The id of the provided document is not used, in order to avoid updated id error.
* You may have to use [UpdateResult.getUpsertedId] in order to retrieve the generated id.
*
* @param filter the query filter to apply to the replace operation
* @param replacement the replacement document
* @param options the options to apply to the replace operation
*
* @return the result of the replace one operation
*/
suspend fun <T : Any> replaceOneWithoutId(
filter: Bson,
replacement: T,
options: ReplaceOptions = ReplaceOptions()
): UpdateResult =
withDocumentClass<BsonDocument>().replaceOne(
filter,
KMongoUtil.filterIdToBson(replacement),
options
)
/**
* Replace a document in the collection according to the specified arguments.
* The id of the provided document is not used, in order to avoid updated id error.
* You may have to use [UpdateResult.getUpsertedId] in order to retrieve the generated id.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter to apply to the replace operation
* @param replacement the replacement document
* @param options the options to apply to the replace operation
*
* @return the result of the replace one operation
*/
suspend fun replaceOneWithoutId(
clientSession: ClientSession,
filter: Bson,
replacement: T,
options: ReplaceOptions = ReplaceOptions()
): UpdateResult =
withDocumentClass<BsonDocument>().replaceOne(
clientSession,
filter,
KMongoUtil.filterIdToBson(replacement),
options
)
/**
* Update a single document in the collection according to the specified arguments.
*
* @param filter a document describing the query filter
* @param update a document describing the update. The update to apply must include only update operators.
* @param options the options to apply to the update operation
*
* @return the result of the update one operation
*/
suspend fun updateOne(
filter: String,
update: String,
options: UpdateOptions = UpdateOptions()
): UpdateResult = updateOne(toBson(filter), toBson(update), options)
/**
* Update a single document in the collection according to the specified arguments.
*
* @param clientSession the client session with which to associate this operation
* @param filter a document describing the query filter
* @param update a document describing the update. The update to apply must include only update operators.
* @param options the options to apply to the update operation
*
* @return the result of the update one operation
*/
suspend fun updateOne(
clientSession: ClientSession,
filter: String,
update: String,
options: UpdateOptions = UpdateOptions()
): UpdateResult =
updateOne(
clientSession,
toBson(filter),
toBson(update),
options
)
/**
* Update a single document in the collection according to the specified arguments.
*
* @param filter a document describing the query filter
* @param update the update object
* @param options the options to apply to the update operation
* @param updateOnlyNotNullProperties if true do not change null properties
*
* @return the result of the update one operation
*/
suspend fun updateOne(
filter: String,
update: Any,
options: UpdateOptions = UpdateOptions(),
updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties
): UpdateResult = updateOne(toBson(filter), setModifier(update, updateOnlyNotNullProperties), options)
/**
* Update a single document in the collection according to the specified arguments.
*
* @param clientSession the client session with which to associate this operation
* @param filter a document describing the query filter
* @param update the update object
* @param options the options to apply to the update operation
* @param updateOnlyNotNullProperties if true do not change null properties
*
* @return the result of the update one operation
*/
suspend fun updateOne(
clientSession: ClientSession,
filter: String,
update: Any,
options: UpdateOptions = UpdateOptions(),
updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties
): UpdateResult = updateOne(
clientSession,
toBson(filter),
setModifier(update, updateOnlyNotNullProperties),
options
)
/**
* Update a single document in the collection according to the specified arguments.
*
* @param filter a document describing the query filter
* @param target the update object - must have an non null id
* @param options the options to apply to the update operation
* @param updateOnlyNotNullProperties if true do not change null properties
*
* @return the result of the update one operation
*/
suspend fun updateOne(
filter: Bson,
target: T,
options: UpdateOptions = UpdateOptions(),
updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties
): UpdateResult = updateOne(filter, toBsonModifier(target, updateOnlyNotNullProperties), options)
/**
* Update a single document in the collection according to the specified arguments.
*
* @param clientSession the client session with which to associate this operation
* @param filter a document describing the query filter
* @param target the update object - must have an non null id
* @param options the options to apply to the update operation
* @param updateOnlyNotNullProperties if true do not change null properties
*
* @return the result of the update one operation
*/
suspend fun updateOne(
clientSession: ClientSession,
filter: Bson,
target: T,
options: UpdateOptions = UpdateOptions(),
updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties
): UpdateResult =
updateOne(clientSession, filter, toBsonModifier(target, updateOnlyNotNullProperties), options)
/**
* Update a single document in the collection according to the specified arguments.
*
* @param id the object id
* @param update the update object
* @param options the options to apply to the update operation
* @param updateOnlyNotNullProperties if true do not change null properties
*
* @return the result of the update one operation
*/
suspend fun updateOneById(
id: Any,
update: Any,
options: UpdateOptions = UpdateOptions(),
updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties
): UpdateResult =
updateOne(
idFilterQuery(id),
toBsonModifier(update, updateOnlyNotNullProperties),
options
)
/**
* Update a single document in the collection according to the specified arguments.
*
* @param clientSession the client session with which to associate this operation
* @param id the object id
* @param update the update object
* @param options the options to apply to the update operation
* @param updateOnlyNotNullProperties if true do not change null properties
*
* @return the result of the update one operation
*/
suspend fun updateOneById(
clientSession: ClientSession,
id: Any,
update: Any,
options: UpdateOptions = UpdateOptions(),
updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties
): UpdateResult =
updateOne(
clientSession,
idFilterQuery(id),
toBsonModifier(update, updateOnlyNotNullProperties),
options
)
/**
* Update all documents in the collection according to the specified arguments.
*
* @param filter a document describing the query filter
* @param update a document describing the update. The update to apply must include only update operators.
* @param updateOptions the options to apply to the update operation
*
* @return the result of the update many operation
*/
suspend fun updateMany(
filter: String,
update: String,
updateOptions: UpdateOptions = UpdateOptions()
): UpdateResult = updateMany(toBson(filter), toBson(update), updateOptions)
/**
* Update all documents in the collection according to the specified arguments.
*
* @param clientSession the client session with which to associate this operation
* @param filter a document describing the query filter
* @param update a document describing the update. The update to apply must include only update operators.
* @param updateOptions the options to apply to the update operation
*
* @return the result of the update many operation
*/
suspend fun updateMany(
clientSession: ClientSession,
filter: String,
update: String,
updateOptions: UpdateOptions = UpdateOptions()
): UpdateResult =
updateMany(
clientSession,
toBson(filter),
toBson(update),
updateOptions
)
/**
* Update all documents in the collection according to the specified arguments.
*
* @param filter a document describing the query filter
* @param update a document describing the update. The update to apply must include only update operators.
* @param updateOptions the options to apply to the update operation
*
* @return the result of the update many operation
*/
suspend fun updateMany(
filter: Bson,
vararg updates: SetTo<*>,
updateOptions: UpdateOptions = UpdateOptions()
): UpdateResult = updateMany(filter, set(*updates), updateOptions)
/**
* Update all documents in the collection according to the specified arguments.
*
* @param clientSession the client session with which to associate this operation
* @param filter a document describing the query filter
* @param update a document describing the update. The update to apply must include only update operators.
* @param updateOptions the options to apply to the update operation
*
* @return the result of the update many operation
*/
suspend fun updateMany(
clientSession: ClientSession,
filter: Bson,
vararg updates: SetTo<*>,
updateOptions: UpdateOptions = UpdateOptions()
): UpdateResult = updateMany(clientSession, filter, set(*updates), updateOptions)
/**
* Atomically find a document and remove it.
*
* @param filter the query filter to find the document with
* @param options the options to apply to the operation
*
* @return the document that was removed. If no documents matched the query filter, then null will be returned
*/
suspend fun findOneAndDelete(
filter: String,
options: FindOneAndDeleteOptions = FindOneAndDeleteOptions()
): T? = findOneAndDelete(toBson(filter), options)
/**
* Atomically find a document and remove it.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter to find the document with
* @param options the options to apply to the operation
*
* @return the document that was removed. If no documents matched the query filter, then null will be returned
*/
suspend fun findOneAndDelete(
clientSession: ClientSession,
filter: String,
options: FindOneAndDeleteOptions = FindOneAndDeleteOptions()
): T? = findOneAndDelete(clientSession, toBson(filter), options)
/**
* Atomically find a document and replace it.
*
* @param filter the query filter to apply the the replace operation
* @param replacement the replacement document
* @param options the options to apply to the operation
*
* @return the document that was replaced. Depending on the value of the `returnOriginal` property, this will either be the
* document as it was before the update or as it is after the update. If no documents matched the query filter, then null will be
* returned
*/
suspend fun findOneAndReplace(
filter: String,
replacement: T,
options: FindOneAndReplaceOptions = FindOneAndReplaceOptions()
): T? = findOneAndReplace(toBson(filter), replacement, options)
/**
* Atomically find a document and replace it.
*
* @param clientSession the client session with which to associate this operation
* @param filter the query filter to apply the the replace operation
* @param replacement the replacement document
* @param options the options to apply to the operation
*
* @return the document that was replaced. Depending on the value of the `returnOriginal` property, this will either be the
* document as it was before the update or as it is after the update. If no documents matched the query filter, then null will be
* returned
*/
suspend fun findOneAndReplace(
clientSession: ClientSession,
filter: String,
replacement: T,
options: FindOneAndReplaceOptions = FindOneAndReplaceOptions()
): T? =
findOneAndReplace(
clientSession,
toBson(filter),
replacement,
options
)
/**
* Atomically find a document and update it.
*
* @param filter a document describing the query filter
* @param update a document describing the update. The update to apply must include only update operators.
* @param options the options to apply to the operation
*
* @return the document that was updated. Depending on the value of the `returnOriginal` property, this will either be the
* document as it was before the update or as it is after the update. If no documents matched the query filter, then null will be
* returned
*/
suspend fun findOneAndUpdate(
filter: String,
update: String,
options: FindOneAndUpdateOptions = FindOneAndUpdateOptions()
): T? = findOneAndUpdate(toBson(filter), toBson(update), options)
/**
* Atomically find a document and update it.
*
* @param clientSession the client session with which to associate this operation
* @param filter a document describing the query filter
* @param update a document describing the update. The update to apply must include only update operators.
* @param options the options to apply to the operation
*
* @return the document that was updated. Depending on the value of the `returnOriginal` property, this will either be the
* document as it was before the update or as it is after the update. If no documents matched the query filter, then null will be
* returned
*/
suspend fun findOneAndUpdate(
clientSession: ClientSession,
filter: String,
update: String,
options: FindOneAndUpdateOptions = FindOneAndUpdateOptions()
): T? =
findOneAndUpdate(
clientSession,
toBson(filter),
toBson(update),
options
)
/**
* Creates an index. If successful, the callback will be executed with the name of the created index as the result.
*
* @param key an object describing the index key(s)
* @param options the options for the index
* @return the index name
*/
suspend fun createIndex(
key: String,
options: IndexOptions = IndexOptions()
): String = createIndex(toBson(key), options)
/**
* Create an index with the given keys and options.
* If the creation of the index is not doable because an index with the same keys but with different [IndexOptions]
* already exists, then drop the existing index and create a new one.
*
* @param keys an object describing the index key(s)
* @param indexOptions the options for the index
* @return the index name
*/
suspend fun ensureIndex(
keys: String,
indexOptions: IndexOptions = IndexOptions()
): String? =
try {
createIndex(keys, indexOptions)
} catch (e: MongoCommandException) {
//there is an exception if the parameters of an existing index are changed.
//then drop the index and create a new one
dropIndex(keys)
createIndex(keys, indexOptions)
}
/**
* Create an index with the given keys and options.
* If the creation of the index is not doable because an index with the same keys but with different [IndexOptions]
* already exists, then drop the existing index and create a new one.
*
* @param keys an object describing the index key(s)
* @param indexOptions the options for the index
* @return the index name
*/
suspend fun ensureIndex(
keys: Bson,
indexOptions: IndexOptions = IndexOptions()
): String? =
try {
createIndex(keys, indexOptions)
} catch (e: MongoCommandException) {
//there is an exception if the parameters of an existing index are changed.
//then drop the index and create a new one
dropIndex(keys)
createIndex(keys, indexOptions)
}
/**
* Create an index with the given keys and options.
* If the creation of the index is not doable because an index with the same keys but with different [IndexOptions]
* already exists, then drop the existing index and create a new one.
*
* @param properties the properties, which must contain at least one
* @param indexOptions the options for the index
* @return the index name
*/
suspend fun ensureIndex(
vararg properties: KProperty<*>,
indexOptions: IndexOptions = IndexOptions()
): String? = ensureIndex(ascending(*properties), indexOptions)
/**
* Create an [IndexOptions.unique] index with the given keys and options.
* If the creation of the index is not doable because an index with the same keys but with different [IndexOptions]
* already exists, then drop the existing index and create a new one.
*
* @param properties the properties, which must contain at least one
* @param indexOptions the options for the index
* @return the index name
*/
suspend fun ensureUniqueIndex(
vararg properties: KProperty<*>,
indexOptions: IndexOptions = IndexOptions()
): String? = ensureIndex(ascending(*properties), indexOptions.unique(true))
/**
* Executes a mix of inserts, updates, replaces, and deletes.
*
* @param requests the writes to execute
* @param options the options to apply to the bulk write operation
*
* @return the result of the bulk write
*/
suspend inline fun bulkWrite(
vararg requests: WriteModel<T>,
options: BulkWriteOptions = BulkWriteOptions()
): BulkWriteResult = bulkWrite(requests.toList(), options)
}
//extensions
/**
* Inserts the provided document. If the document is missing an identifier, the driver should generate one.
*
* @param document the document to insert
* @param options the options to apply to the operation
*/
suspend inline fun <reified T : Any> CoroutineCollection<T>.insertOne(
document: String,
options: InsertOneOptions = InsertOneOptions()
): InsertOneResult =
withDocumentClass<BsonDocument>().insertOne(
toBson(document, T::class),
options
)
/**
* Inserts the provided document. If the document is missing an identifier, the driver should generate one.
* @param clientSession the client session with which to associate this operation
* @param document the document to insert
* @param options the options to apply to the operation
*/
suspend inline fun <reified T : Any> CoroutineCollection<T>.insertOne(
clientSession: ClientSession,
document: String,
options: InsertOneOptions = InsertOneOptions()
): InsertOneResult =
withDocumentClass<BsonDocument>().insertOne(
clientSession,
toBson(document, T::class),
options
)
/**
* Replace a document in the collection according to the specified arguments.
*
* @param replacement the document to replace - must have an non null id
* @param options the options to apply to the replace operation
*
* @return the result of the replace one operation
*/
suspend inline fun <reified T : Any> CoroutineCollection<T>.replaceOne(
replacement: T,
options: ReplaceOptions = ReplaceOptions()
): UpdateResult = replaceOneById(extractId(replacement, T::class), replacement, options)
/**
* Update a single document in the collection according to the specified arguments.
*
* @param target the update object - must have an non null id
* @param options the options to apply to the update operation
* @param updateOnlyNotNullProperties if true do not change null properties
*
* @return the result of the update one operation
*/
suspend inline fun <reified T : Any> CoroutineCollection<T>.updateOne(
target: T,
options: UpdateOptions = UpdateOptions(),
updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties
): UpdateResult = updateOneById(extractId(target, T::class), target, options, updateOnlyNotNullProperties)
/**
* Update a single document in the collection according to the specified arguments.
*
* @param clientSession the client session with which to associate this operation
* @param target the update object - must have an non null id
* @param options the options to apply to the update operation
* @param updateOnlyNotNullProperties if true do not change null properties
*
* @return the result of the update one operation
*/
suspend inline fun <reified T : Any> CoroutineCollection<T>.updateOne(
clientSession: ClientSession,
target: T,
options: UpdateOptions = UpdateOptions(),
updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties
): UpdateResult {
return updateOneById(
clientSession,
extractId(target, T::class),
target,
options,
updateOnlyNotNullProperties
)
}
/**
* Executes a mix of inserts, updates, replaces, and deletes.
*
* @param clientSession the client session with which to associate this operation
* @param requests the writes to execute
* @param options the options to apply to the bulk write operation
*
* @return the result of the bulk write
*/
suspend inline fun <reified T : Any> CoroutineCollection<T>.bulkWrite(
clientSession: ClientSession,
vararg requests: String,
options: BulkWriteOptions = BulkWriteOptions()
): BulkWriteResult =
withDocumentClass<BsonDocument>().bulkWrite(
clientSession,
KMongoUtil.toWriteModel(
requests,
codecRegistry,
T::class
),
options
)
/**
* Executes a mix of inserts, updates, replaces, and deletes.
*
* @param requests the writes to execute
* @param options the options to apply to the bulk write operation
*
* @return the result of the bulk write
*/
suspend inline fun <reified T : Any> CoroutineCollection<T>.bulkWrite(
vararg requests: String,
options: BulkWriteOptions = BulkWriteOptions()
): BulkWriteResult =
withDocumentClass<BsonDocument>().bulkWrite(
KMongoUtil.toWriteModel(
requests,
codecRegistry,
T::class
),
options
)
/**
* Aggregates documents according to the specified aggregation pipeline. If the pipeline ends with a $out stage, the returned
* iterable will be a query of the collection that the aggregation was written to. Note that in this case the pipeline will be
* executed even if the iterable is never iterated.
*
* @param pipeline the aggregate pipeline
* @param <T> the target document type of the iterable
*/
inline fun <reified T : Any> CoroutineCollection<*>.aggregate(vararg pipeline: String): CoroutineAggregatePublisher<T> =
aggregate(KMongoUtil.toBsonList(pipeline, codecRegistry))
/**
* Aggregates documents according to the specified aggregation pipeline. If the pipeline ends with a $out stage, the returned
* iterable will be a query of the collection that the aggregation was written to. Note that in this case the pipeline will be
* executed even if the iterable is never iterated.
*
* @param pipeline the aggregate pipeline
* @param <T> the target document type of the iterable
*/
inline fun <reified T : Any> CoroutineCollection<*>.aggregate(vararg pipeline: Bson): CoroutineAggregatePublisher<T> =
aggregate(pipeline.toList())
/**
* Returns the specified field for all matching documents.
*
* @param property the property to return
* @param query the optional find query
* @param options the optional [CoroutineFindPublisher] modifiers
* @return a property value CoroutineFindPublisher
*/
inline fun <reified F : Any> CoroutineCollection<*>.projection(
property: KProperty<F?>,
query: Bson = EMPTY_BSON,
options: (CoroutineFindPublisher<SingleProjection<F>>) -> CoroutineFindPublisher<SingleProjection<F>> = { it }
): CoroutineFindPublisher<F> =
CoroutineFindPublisher(
withDocumentClass<SingleProjection<F>>()
.withCodecRegistry(singleProjectionCodecRegistry(property.path(), F::class, codecRegistry))
.find(query)
.let { options(it) }
.projection(fields(excludeId(), include(property)))
.publisher
.map { it?.field }
)
/**
* Returns the specified two fields for all matching documents.
*
* @param property1 the first property to return
* @param property2 the second property to return
* @param query the optional find query
* @param options the optional [CoroutineFindPublisher] modifiers
* @return a pair of property values CoroutineFindPublisher
*/
inline fun <reified F1 : Any, reified F2 : Any> CoroutineCollection<*>.projection(
property1: KProperty<F1?>,
property2: KProperty<F2?>,
query: Bson = EMPTY_BSON,
options: (CoroutineFindPublisher<PairProjection<F1, F2>>) -> CoroutineFindPublisher<PairProjection<F1, F2>> = { it }
): CoroutineFindPublisher<Pair<F1?, F2?>> =
CoroutineFindPublisher(
withDocumentClass<PairProjection<F1, F2>>()
.withCodecRegistry(
pairProjectionCodecRegistry(
property1.path(),
F1::class,
property2.path(),
F2::class,
codecRegistry
)
)
.find(query)
.let { options(it) }
.projection(fields(excludeId(), include(property1), include(property2)))
.publisher
.map { it?.field1 to it?.field2 }
)
/**
* Returns the specified three fields for all matching documents.
*
* @param property1 the first property to return
* @param property2 the second property to return
* @param property3 the third property to return
* @param query the optional find query
* @param options the optional [CoroutineFindPublisher] modifiers
* @return a triple of property values CoroutineFindPublisher
*/
inline fun <reified F1 : Any, reified F2 : Any, reified F3 : Any> CoroutineCollection<*>.projection(
property1: KProperty<F1?>,
property2: KProperty<F2?>,
property3: KProperty<F3?>,
query: Bson = EMPTY_BSON,
options: (CoroutineFindPublisher<TripleProjection<F1, F2, F3>>) -> CoroutineFindPublisher<TripleProjection<F1, F2, F3>> = { it }
): CoroutineFindPublisher<Triple<F1?, F2?, F3?>> =
CoroutineFindPublisher(
withDocumentClass<TripleProjection<F1, F2, F3>>()
.withCodecRegistry(
tripleProjectionCodecRegistry(
property1.path(),
F1::class,
property2.path(),
F2::class,
property3.path(),
F3::class,
codecRegistry
)
)
.find(query)
.let { options(it) }
.projection(fields(excludeId(), include(property1), include(property2), include(property3)))
.publisher
.map { Triple(it?.field1, it?.field2, it?.field3) }
)
| apache-2.0 | 7ceb77c7cb5fcd21903384562dce6963 | 39.837458 | 140 | 0.680037 | 5.007199 | false | false | false | false |
EMResearch/EvoMaster | e2e-tests/spring-rest-openapi-v3/src/main/kotlin/com/foo/rest/examples/spring/openapi/v3/expectations/ExpectationObjects.kt | 1 | 582 | package com.foo.rest.examples.spring.openapi.v3.expectations
open class GenericObject
open class ExampleObject(
var ident: Int? = null,
var name : String? = "Unnamed",
var description : String? = "Indescribable"
) : GenericObject() {
fun setId(id: Int? = null){
ident = id
}
fun getId() : Int{
return when (ident) {
null -> 0
else -> ident!!
}
}
}
open class OtherExampleObject(
var id : Int? = null,
var namn : String? = "Unnamed",
var category : String = "None"
): GenericObject()
| lgpl-3.0 | 0f7c1d0938e34ef49d3547c38435bfe4 | 22.28 | 60 | 0.573883 | 3.707006 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/gene/optional/ChoiceGene.kt | 1 | 8085 | package org.evomaster.core.search.gene.optional
import org.evomaster.core.logging.LoggingUtil
import org.evomaster.core.output.OutputFormat
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.root.CompositeFixedGene
import org.evomaster.core.search.gene.utils.GeneUtils
import org.evomaster.core.search.service.AdaptiveParameterControl
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.service.mutator.MutationWeightControl
import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo
import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* A gene that holds many potenial genes (genotype) but
* only one is active at any time (phenotype). The list
* of gene choices cannot be empty.
*/
class ChoiceGene<T>(
name: String,
private val geneChoices: List<T>,
activeChoice: Int = 0
) : CompositeFixedGene(name, geneChoices) where T : Gene {
companion object {
private val log: Logger = LoggerFactory.getLogger(ChoiceGene::class.java)
}
var activeGeneIndex: Int = activeChoice
private set
init {
if (geneChoices.isEmpty()) {
throw IllegalArgumentException("The list of gene choices cannot be empty")
}
if (activeChoice < 0 || activeChoice >= geneChoices.size) {
throw IllegalArgumentException("Active choice must be between 0 and ${geneChoices.size - 1}")
}
}
override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) {
activeGeneIndex = randomness.nextInt(geneChoices.size)
/*
Even the non-selected genes need to be randomized, otherwise could be let in
a inconsistent state
*/
if(!initialized){
geneChoices
.filter { it.isMutable() }
.forEach { it.randomize(randomness, tryToForceNewValue) }
} else {
val g = geneChoices[activeGeneIndex]
if(g.isMutable()){
g.randomize(randomness, tryToForceNewValue)
}
}
}
/**
* TODO This method must be implemented to reflect usage
* of the selectionStrategy and the additionalGeneMutationInfo
*/
override fun mutablePhenotypeChildren(): List<Gene> {
return listOf(geneChoices[activeGeneIndex])
}
override fun <T> getWrappedGene(klass: Class<T>) : T? where T : Gene{
if(this.javaClass == klass){
return this as T
}
return geneChoices[activeGeneIndex].getWrappedGene(klass)
}
override fun shallowMutate(randomness: Randomness, apc: AdaptiveParameterControl, mwc: MutationWeightControl, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo?): Boolean {
// TODO
// select another disjunction based on impact
// if (enableAdaptiveGeneMutation || selectionStrategy == SubsetGeneSelectionStrategy.ADAPTIVE_WEIGHT){
// additionalGeneMutationInfo?:throw IllegalStateException("")
// if (additionalGeneMutationInfo.impact != null && additionalGeneMutationInfo.impact is DisjunctionListRxGeneImpact){
// val candidates = disjunctions.filterIndexed { index, _ -> index != activeDisjunction }
// val impacts = candidates.map {
// additionalGeneMutationInfo.impact.disjunctions[disjunctions.indexOf(it)]
// }
//
// val selected = mwc.selectSubGene(
// candidateGenesToMutate = candidates,
// impacts = impacts,
// targets = additionalGeneMutationInfo.targets,
// forceNotEmpty = true,
// adaptiveWeight = true
// )
// activeDisjunction = disjunctions.indexOf(randomness.choose(selected))
// return true
// }
// //throw IllegalArgumentException("mismatched gene impact")
// }
//activate the next disjunction
activeGeneIndex = (activeGeneIndex + 1) % geneChoices.size
return true
}
override fun customShouldApplyShallowMutation(
randomness: Randomness,
selectionStrategy: SubsetGeneMutationSelectionStrategy,
enableAdaptiveGeneMutation: Boolean,
additionalGeneMutationInfo: AdditionalGeneMutationInfo?
): Boolean {
return randomness.nextBoolean(0.1) //TODO check for proper value
}
/**
* Returns the value of the active gene as a printable string
*/
override fun getValueAsPrintableString(
previousGenes: List<Gene>,
mode: GeneUtils.EscapeMode?,
targetFormat: OutputFormat?,
extraCheck: Boolean
): String {
return geneChoices[activeGeneIndex]
.getValueAsPrintableString(previousGenes, mode, targetFormat, extraCheck)
}
/**
* Returns the value of the active gene as a raw string
*/
override fun getValueAsRawString(): String {
return geneChoices[activeGeneIndex]
.getValueAsRawString()
}
/**
* Copies the value of the other gene. The other gene
* has to be a [ChoiceGene] with the same number
* of gene choices. The value of each gene choice
* is also copied.
*/
override fun copyValueFrom(other: Gene) {
if (other !is ChoiceGene<*>) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
} else if (geneChoices.size != other.geneChoices.size) {
throw IllegalArgumentException("Cannot copy value from another choice gene with ${other.geneChoices.size} choices (current gene has ${geneChoices.size} choices)")
} else {
this.activeGeneIndex = other.activeGeneIndex
for (i in geneChoices.indices) {
this.geneChoices[i].copyValueFrom(other.geneChoices[i])
}
}
}
/**
* Checks that the other gene is another ChoiceGene,
* the active gene index is the same, and the gene choices are the same.
*/
override fun containsSameValueAs(other: Gene): Boolean {
if (other !is ChoiceGene<*>) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
if (this.activeGeneIndex != other.activeGeneIndex) {
return false
}
return this.geneChoices[activeGeneIndex]
.containsSameValueAs(other.geneChoices[activeGeneIndex])
}
/**
* Binds this gene to another [ChoiceGene<T>] with the same number of
* gene choices, one gene choice to the corresponding gene choice in
* the other gene.
*/
override fun bindValueBasedOn(gene: Gene): Boolean {
if (gene is ChoiceGene<*> && gene.geneChoices.size == geneChoices.size) {
var result = true
geneChoices.indices.forEach { i ->
val r = geneChoices[i].bindValueBasedOn(gene.geneChoices[i])
if (!r)
LoggingUtil.uniqueWarn(log, "cannot bind disjunctions (name: ${geneChoices[i].name}) at index $i")
result = result && r
}
activeGeneIndex = gene.activeGeneIndex
return result
}
LoggingUtil.uniqueWarn(log, "cannot bind ChoiceGene with ${gene::class.java.simpleName}")
return false
}
/**
* Returns a copy of this gene choice by copying
* all gene choices.
*/
override fun copyContent(): Gene = ChoiceGene(
name,
activeChoice = this.activeGeneIndex,
geneChoices = this.geneChoices.map { it.copy() }.toList()
)
/**
* Checks that the active gene is the one locally valid
*/
override fun isLocallyValid() = geneChoices.all { it.isLocallyValid() }
override fun isPrintable() = this.geneChoices[activeGeneIndex].isPrintable()
} | lgpl-3.0 | 15306479e582d2264d2ceca6e26f930a | 35.922374 | 274 | 0.649227 | 5.146404 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/tv/contact/TVContactPresenter.kt | 1 | 4136 | /*
* Copyright (C) 2004-2018 Savoir-faire Linux Inc.
*
* Author: Hadrien De Sousa <[email protected]>
* Author: Adrien Béraud <[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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.tv.contact
import cx.ring.utils.ConversationPath
import ezvcard.VCard
import io.reactivex.rxjava3.core.Scheduler
import net.jami.daemon.Blob
import net.jami.services.ConversationFacade
import net.jami.model.Call
import net.jami.model.Uri
import net.jami.mvp.RootPresenter
import net.jami.services.AccountService
import net.jami.services.VCardService
import net.jami.smartlist.ConversationItemViewModel
import net.jami.utils.VCardUtils.vcardToString
import javax.inject.Inject
import javax.inject.Named
class TVContactPresenter @Inject constructor(
private val mAccountService: AccountService,
private val mConversationService: ConversationFacade,
@param:Named("UiScheduler") private val mUiScheduler: Scheduler,
private val mVCardService: VCardService
) : RootPresenter<TVContactView>() {
private var mAccountId: String? = null
private var mUri: Uri? = null
fun setContact(path: ConversationPath) {
mAccountId = path.accountId
mUri = path.conversationUri
mCompositeDisposable.clear()
mCompositeDisposable.add(mConversationService.observeConversation(path.accountId, path.conversationUri, true)
.observeOn(mUiScheduler)
.subscribe { c: ConversationItemViewModel -> view?.showContact(c) })
}
fun contactClicked() {
mAccountService.getAccount(mAccountId)?.let { account ->
val conversation = account.getByUri(mUri)!!
val conf = conversation.currentCall
val call = conf?.firstCall
if (call != null && call.callStatus !== Call.CallStatus.INACTIVE && call.callStatus !== Call.CallStatus.FAILURE) {
view?.goToCallActivity(conf.id)
} else {
if (conversation.isSwarm) {
view?.callContact(account.accountId, conversation.uri, conversation.contact!!.uri)
} else {
view?.callContact(account.accountId, conversation.uri, conversation.uri)
}
}
}
}
fun onAddContact() {
mAccountId?.let { accountId -> mUri?.let { uri ->
sendTrustRequest(accountId, uri)
} }
view?.switchToConversationView()
}
private fun sendTrustRequest(accountId: String, conversationUri: Uri) {
val conversation = mAccountService.getAccount(accountId)!!.getByUri(conversationUri)
mVCardService.loadSmallVCardWithDefault(accountId, VCardService.MAX_SIZE_REQUEST)
.subscribe({ vCard: VCard ->
mAccountService.sendTrustRequest(conversation!!, conversationUri, Blob.fromString(vcardToString(vCard))) })
{ mAccountService.sendTrustRequest(conversation!!, conversationUri, null) }
}
fun acceptTrustRequest() {
mConversationService.acceptRequest(mAccountId!!, mUri!!)
view?.switchToConversationView()
}
fun refuseTrustRequest() {
mConversationService.discardRequest(mAccountId!!, mUri!!)
view?.finishView()
}
fun blockTrustRequest() {
mConversationService.discardRequest(mAccountId!!, mUri!!)
mAccountService.removeContact(mAccountId!!, mUri!!.rawRingId, true)
view?.finishView()
}
} | gpl-3.0 | ee59cce1bb47968d80f793dadf496a1d | 39.15534 | 126 | 0.696493 | 4.569061 | false | false | false | false |
xwiki-contrib/android-authenticator | app/src/main/java/org/xwiki/android/sync/activities/SyncSettingsActivity.kt | 1 | 28490 | package org.xwiki.android.sync.activities
import android.accounts.Account
import android.accounts.AccountManager
import android.app.Activity
import android.content.ComponentName
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.work.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.xwiki.android.sync.*
import org.xwiki.android.sync.R
import org.xwiki.android.sync.ViewModel.SyncSettingsViewModel
import org.xwiki.android.sync.ViewModel.SyncSettingsViewModelFactory
import org.xwiki.android.sync.activities.Notifications.NotificationsActivity
import org.xwiki.android.sync.bean.ObjectSummary
import org.xwiki.android.sync.bean.SearchResults.CustomObjectsSummariesContainer
import org.xwiki.android.sync.bean.XWikiGroup
import org.xwiki.android.sync.contactdb.UserAccount
import org.xwiki.android.sync.contactdb.clearOldAccountContacts
import org.xwiki.android.sync.databinding.ActivitySyncSettingsBinding
import org.xwiki.android.sync.notifications.NotificationWorker
import org.xwiki.android.sync.rest.BaseApiManager
import org.xwiki.android.sync.utils.GroupsListChangeListener
import org.xwiki.android.sync.utils.getAppVersionName
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1
import rx.schedulers.Schedulers
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Tag which will be used for logging.
*/
private val TAG = SyncSettingsActivity::class.java.simpleName
/**
* Open market with application page.
*
* @param context Context to know where from to open market
*/
private fun openAppMarket(context: Context) {
val rateIntent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.packageName))
var marketFound = false
// find all applications able to handle our rateIntent
val otherApps = context.packageManager.queryIntentActivities(rateIntent, 0)
for (otherApp in otherApps) {
// look for Google Play application
if (otherApp.activityInfo.applicationInfo.packageName == "com.android.vending") {
val otherAppActivity = otherApp.activityInfo
val componentName = ComponentName(
otherAppActivity.applicationInfo.packageName,
otherAppActivity.name
)
rateIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
rateIntent.component = componentName
context.startActivity(rateIntent)
marketFound = true
break
}
}
// if GooglePlay not present on device, open web browser
if (!marketFound) {
val webIntent = Intent(
Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=" + context.packageName)
)
context.startActivity(webIntent)
}
}
class SyncSettingsActivity : AppCompatActivity(), GroupsListChangeListener {
/**
* DataBinding for accessing layout variables.
*/
lateinit var binding : ActivitySyncSettingsBinding
/**
* Adapter for groups
*/
private lateinit var mGroupAdapter: GroupListAdapter
/**
* Adapter for users.
*/
private lateinit var mUsersAdapter: UserListAdapter
/**
* List of received groups.
*/
private val groups: MutableList<XWikiGroup> = mutableListOf()
/**
* List of received all users.
*/
private val allUsers: MutableList<ObjectSummary> = mutableListOf()
/**
* Currently chosen sync type.
*/
private var chosenSyncType: Int? = SYNC_TYPE_NO_NEED_SYNC
/**
* Flag of currently loading groups.
*/
@Volatile
private var groupsAreLoading: Boolean = false
/**
* Flag of currently loading all users.
*/
@Volatile
private var allUsersAreLoading: Boolean = false
private lateinit var currentUserAccountName : String
private lateinit var currentUserAccountType : String
private lateinit var userAccount : UserAccount
private lateinit var syncSettingsViewModel: SyncSettingsViewModel
private lateinit var apiManager: BaseApiManager
private var selectedStrings = ArrayList<String>()
private lateinit var context: LifecycleOwner
private lateinit var layoutManager: LinearLayoutManager
private var isLoading = false
private var initialUsersListLoading = true
private var currentPage = 0
private var lastVisiblePosition = 0
private lateinit var toolbar: androidx.appcompat.widget.Toolbar
private lateinit var dataSavingCheckbox: MenuItem
/**
* Init all views and other activity objects
*
* @param savedInstanceState
*
* @since 1.0
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
context = this
binding = DataBindingUtil.setContentView(this, R.layout.activity_sync_settings)
binding.versionCheck.text = String.format(
getString(R.string.versionTemplate),
getAppVersionName(this)
)
val extras = intent.extras
currentUserAccountName = if (extras ?.get("account") != null) {
val intentAccount : Account = extras.get("account") as Account
intentAccount.name
} else {
intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME) ?: error("Can't get account name from intent - it is absent")
}
toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
mGroupAdapter = GroupListAdapter(groups, this)
mUsersAdapter = UserListAdapter(allUsers, this)
layoutManager = binding.recyclerView.layoutManager as LinearLayoutManager
binding.recyclerView.adapter = mUsersAdapter
binding.recyclerView.addOnScrollListener(recyclerViewOnScrollListener)
binding.selectSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
binding.syncTypeGetErrorContainer.visibility = View.GONE
when(position) {
0 -> {
if (allUsers.isEmpty() && allUsersAreLoading) {
binding.syncTypeGetErrorContainer.visibility = View.VISIBLE
}
}
1 -> {
if (groups.isEmpty()) {
binding.syncTypeGetErrorContainer.visibility = View.VISIBLE
}
}
2 -> {
binding.syncTypeGetErrorContainer.visibility = View.GONE
}
}
if (userAccount.syncType == position) {
binding.nextButton.alpha = 0.8F
} else {
binding.nextButton.alpha = 1F
}
chosenSyncType = position
initialUsersListLoading = true
currentPage = 0
updateListView(false)
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
binding.rvChangeSelectedAccount.setOnClickListener {
val intent : Intent = Intent(this, SelectAccountActivity::class.java)
startActivityForResult(intent, 1000)
}
binding.btTryAgain.setOnClickListener {
appCoroutineScope.launch {
when(chosenSyncType) {
SYNC_TYPE_ALL_USERS -> {loadAllUsers()}
SYNC_TYPE_SELECTED_GROUPS -> {loadSyncGroups()}
}
}
}
binding.versionCheck.setOnClickListener { v -> openAppMarket(v.context) }
binding.nextButton.setOnClickListener { syncSettingComplete(it) }
initData()
callNotificationWorker()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.sync_setting_view_menu, menu)
dataSavingCheckbox = menu!!.findItem(R.id.action_data_saving)
if (appContext.dataSaverModeEnabled) {
dataSavingCheckbox.setChecked(true)
} else {
dataSavingCheckbox.setChecked(false)
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_data_saving -> {
if (item.isChecked) {
item.setChecked(false)
appContext.dataSaverModeEnabled = false
} else {
item.setChecked(true)
appContext.dataSaverModeEnabled = true
}
true
}
R.id.action_notifications -> {
if (this.hasNetworkConnection()) {
val intent = Intent(this, NotificationsActivity::class.java)
intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, currentUserAccountName)
startActivity(intent)
} else
Toast.makeText(applicationContext, R.string.error_no_internet, Toast.LENGTH_SHORT).show()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private val recyclerViewOnScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
val totalItemCount = layoutManager.itemCount
if (!isLoading && layoutManager.findLastCompletelyVisibleItemPosition() >= totalItemCount/2) {
lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition()
loadMoreUsers()
}
}
}
}
// TODO:: Test case for pagination of loading MoreUsers
private fun loadMoreUsers () {
isLoading = true
showLoadMoreProgressBar()
apiManager.xwikiServicesApi.getAllUsersListByOffset(currentPage, PAGE_SIZE)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
Action1 {
if (it.objectSummaries.isNotEmpty()) {
currentPage += PAGE_SIZE
allUsers.addAll(it.objectSummaries)
updateListView(true)
syncSettingsViewModel.updateAllUsersCache(
allUsers,
userAccount.id
)
}
initialUsersListLoading = false
allUsersAreLoading = false
isLoading = false
hideLoadMoreProgressBar()
},
Action1 {
allUsersAreLoading = false
isLoading = false
hideLoadMoreProgressBar()
}
)
}
fun scrollToCurrentPosition() {
if (!initialUsersListLoading) {
binding.recyclerView.scrollToPosition(lastVisiblePosition - 3)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, intent)
if (requestCode == 1000) {
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
currentUserAccountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME)
currentUserAccountType = data.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE)
binding.tvSelectedSyncAcc.text = currentUserAccountName
binding.tvSelectedSyncType.text = currentUserAccountType
currentPage = 0
initData()
}
}
}
}
private fun hideRecyclerView() {
runOnUiThread{
enableShimmer()
binding.syncTypeGetErrorContainer.visibility = View.GONE
binding.recyclerView.visibility = View.GONE
}
}
//this progress bar appears when more data is loaded into recycler view
private fun showLoadMoreProgressBar() {
runOnUiThread {
binding.loadMoreProgressBar.visibility = View.VISIBLE
}
}
private fun hideLoadMoreProgressBar() {
runOnUiThread {
binding.loadMoreProgressBar.visibility = View.INVISIBLE
}
}
private fun showRecyclerView() {
runOnUiThread {
disableShimmer()
binding.recyclerView.visibility = View.VISIBLE
}
}
/**
* Load data to groups and all users lists.
*
* @since 0.4
*/
private fun initData() {
if (!intent.getBooleanExtra("Test", false)) {
hideRecyclerView()
}
appCoroutineScope.launch {
userAccount = userAccountsRepo.findByAccountName(currentUserAccountName) ?: return@launch
chosenSyncType = userAccount.syncType
apiManager = resolveApiManager(userAccount)
selectedStrings.clear()
selectedStrings = userAccount.selectedGroupsList as ArrayList<String>
withContext(Dispatchers.Main) {
binding.tvSelectedSyncAcc.text = userAccount.accountName
binding.tvSelectedSyncType.text = userAccount.serverAddress
syncSettingsViewModel = ViewModelProviders.of(
this@SyncSettingsActivity,
SyncSettingsViewModelFactory (application)
).get(SyncSettingsViewModel::class.java)
chosenSyncType = userAccount.syncType
}
initSyncList()
}
}
// TODO:: Test case for both allUsers and SyncGroups
private fun initSyncList () {
loadSyncGroups()
loadAllUsers()
}
// Initial loading of all users.
private fun loadAllUsers() {
allUsersAreLoading = true
val users = syncSettingsViewModel.getAllUsersCache(userAccount.id) ?: emptyList()
if (users.isEmpty()) {
hideRecyclerView()
} else {
allUsers.clear()
allUsers.addAll(users)
updateListView(false)
}
apiManager.xwikiServicesApi.getAllUsersListByOffset( currentPage, PAGE_SIZE)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ summaries ->
val objectSummary = summaries.objectSummaries
if (objectSummary.isNullOrEmpty()) {
runOnUiThread {
binding.syncTypeGetErrorContainer.visibility = View.VISIBLE
showRecyclerView()
}
} else {
currentPage = PAGE_SIZE
runOnUiThread {
binding.syncTypeGetErrorContainer.visibility = View.GONE
}
allUsersAreLoading = false
allUsers.clear()
allUsers.addAll(summaries.objectSummaries)
syncSettingsViewModel.updateAllUsersCache(
summaries.objectSummaries,
userAccount.id
)
updateListView(true)
}
},
{
allUsersAreLoading = false
runOnUiThread {
Toast.makeText(
this@SyncSettingsActivity,
R.string.cantGetAllUsers,
Toast.LENGTH_SHORT
).show()
if (allUsers.size <= 0) {
binding.syncTypeGetErrorContainer.visibility = View.VISIBLE
}
}
showRecyclerView()
}
)
}
private fun loadSyncGroups() {
val groupsCache = syncSettingsViewModel.getGroupsCache(userAccount.id) ?: emptyList()
if (groupsCache.isEmpty()) {
hideRecyclerView()
} else {
groups.clear()
groups.addAll(groupsCache)
updateListView(false)
}
groupsAreLoading = true
apiManager.xwikiServicesApi.availableGroups(
LIMIT_MAX_SYNC_USERS
)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ xWikiGroupCustomSearchResultContainer ->
groupsAreLoading = false
val searchResults = xWikiGroupCustomSearchResultContainer.searchResults
showRecyclerView()
if (searchResults.isNullOrEmpty()) {
runOnUiThread {
if (chosenSyncType == SYNC_TYPE_SELECTED_GROUPS) {
binding.syncTypeGetErrorContainer.visibility = View.VISIBLE
}
}
} else {
runOnUiThread {
binding.syncTypeGetErrorContainer.visibility = View.GONE
}
groups.clear()
groups.addAll(searchResults)
syncSettingsViewModel.updateGroupsCache(
searchResults,
userAccount.id
)
updateListView(false)
}
},
{
groupsAreLoading = false
runOnUiThread {
Toast.makeText(
this@SyncSettingsActivity,
R.string.cantGetGroups,
Toast.LENGTH_SHORT
).show()
if (groups.size <= 0) {
binding.syncTypeGetErrorContainer.visibility = View.VISIBLE
}
}
showRecyclerView()
}
)
}
// Load all users at once, does not support pagination.
private fun updateSyncAllUsers() {
val users = syncSettingsViewModel.getAllUsersCache(userAccount.id) ?: emptyList()
if (users.isEmpty()) {
allUsersAreLoading = true
apiManager.xwikiServicesApi.allUsersPreview
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
Action1<CustomObjectsSummariesContainer<ObjectSummary>> { summaries ->
runOnUiThread {
binding.syncTypeGetErrorContainer.visibility = View.GONE
}
allUsersAreLoading = false
allUsers.clear()
allUsers.addAll(summaries.objectSummaries)
syncSettingsViewModel.updateAllUsersCache(
summaries.objectSummaries,
userAccount.id
)
updateListView(true)
},
Action1<Throwable> {
allUsersAreLoading = false
runOnUiThread {
Toast.makeText(
this@SyncSettingsActivity,
R.string.cantGetAllUsers,
Toast.LENGTH_SHORT
).show()
binding.syncTypeGetErrorContainer.visibility = View.VISIBLE
}
showRecyclerView()
}
)
} else {
allUsers.clear()
allUsers.addAll(users)
updateListView(false)
}
}
/**
* @return true if currently selected to sync groups or false otherwise
*/
private fun syncGroups(): Boolean {
return chosenSyncType == SYNC_TYPE_SELECTED_GROUPS
}
/**
* @return true if currently selected to sync all users or false otherwise
*/
private fun syncAllUsers(): Boolean {
return chosenSyncType == SYNC_TYPE_ALL_USERS
}
/**
* @return true if currently selected to sync not or false otherwise
*/
private fun syncNothing(): Boolean {
return chosenSyncType == SYNC_TYPE_NO_NEED_SYNC
}
/**
* Update list view and hide/show view from [.getListViewContainer]
*/
private fun updateListView(hideProgressBar: Boolean) {
appCoroutineScope.launch(Dispatchers.Main) {
if (syncNothing()) {
binding.recyclerView.visibility = View.GONE
disableShimmer()
} else {
binding.recyclerView.visibility = View.VISIBLE
if (syncGroups()) {
binding.recyclerView.adapter = mGroupAdapter
mGroupAdapter.refresh(groups, userAccount.selectedGroupsList)
} else {
binding.recyclerView.adapter = mUsersAdapter
mUsersAdapter.refresh(allUsers)
}
binding.recyclerView.layoutManager?.scrollToPosition(0)
mUsersAdapter.refresh(allUsers)
if (hideProgressBar) {
showRecyclerView()
}
}
}
}
/**
* Save settings of synchronization.
*/
fun syncSettingComplete(v: View) {
val oldSyncType = userAccount.syncType
if (oldSyncType == chosenSyncType && !syncGroups()) {
binding.nextButton.alpha = 0.8F
Toast.makeText(this, "Nothing has changed since your last sync", Toast.LENGTH_SHORT).show()
return
}
val mAccountManager = AccountManager.get(applicationContext)
val availableAccounts = mAccountManager.getAccountsByType(ACCOUNT_TYPE)
var account: Account = availableAccounts[0]
for (acc in availableAccounts) {
if (acc.name.equals(currentUserAccountName)) {
account = acc
}
}
clearOldAccountContacts(
contentResolver,
account
)
//if has changes, set sync
if (syncNothing()) {
userAccount.syncType = SYNC_TYPE_NO_NEED_SYNC
userAccount.selectedGroupsList = mutableListOf()
userAccount.let { syncSettingsViewModel.updateUser(it) }
setSync(false)
finish()
} else if (syncAllUsers()) {
userAccount.syncType = SYNC_TYPE_ALL_USERS
userAccount.selectedGroupsList = mutableListOf()
userAccount.let { syncSettingsViewModel.updateUser(it) }
setSync(true)
finish()
} else if (syncGroups()) {
//compare to see if there are some changes.
if (oldSyncType == chosenSyncType && compareSelectGroups()) {
Toast.makeText(this, "Nothing has changed since your last sync", Toast.LENGTH_SHORT).show()
return
}
userAccount.selectedGroupsList.clear()
userAccount.selectedGroupsList.addAll(mGroupAdapter.saveSelectedGroups())
userAccount.syncType = SYNC_TYPE_SELECTED_GROUPS
appCoroutineScope.launch {
userAccountsRepo.updateAccount(userAccount)
setSync(true)
finish()
}
}
}
/**
* Enable/disable synchronization depending on syncEnabled.
*
* @param syncEnabled Flag to enable (if true) / disable (if false) synchronization
*/
private fun setSync(syncEnabled: Boolean) {
val mAccountManager = AccountManager.get(applicationContext)
val availableAccounts = mAccountManager.getAccountsByType(ACCOUNT_TYPE)
var account : Account = availableAccounts[0]
for (acc in availableAccounts) {
if (acc.name.equals(currentUserAccountName)) {
account = acc
}
}
if (syncEnabled) {
mAccountManager.setUserData(account, SYNC_MARKER_KEY, null)
ContentResolver.cancelSync(account, ContactsContract.AUTHORITY)
ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1)
ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true)
ContentResolver.addPeriodicSync(
account,
ContactsContract.AUTHORITY,
Bundle.EMPTY,
SYNC_INTERVAL.toLong()
)
ContentResolver.requestSync(account, ContactsContract.AUTHORITY, Bundle.EMPTY)
} else {
ContentResolver.cancelSync(account, ContactsContract.AUTHORITY)
ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0)
}
}
/**
* @return true if old list equal to new list of groups
*/
private fun compareSelectGroups(): Boolean {
//new
val newList = mGroupAdapter.selectGroups
//old
val oldList = userAccount.selectedGroupsList
if (newList.isEmpty() && oldList.isEmpty()) {
return false
}
if (newList.size != oldList.size) {
return false
} else {
for (item in newList) {
if (!oldList.contains(item.id)) {
return false
}
}
return true
}
}
override fun onChangeListener() {
if (compareSelectGroups()) {
binding.nextButton.alpha = 0.8F
} else {
binding.nextButton.alpha = 1F
}
}
fun Context.hasNetworkConnection(): Boolean {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return cm.activeNetworkInfo?.isConnected ?: false
}
private fun callNotificationWorker() {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresCharging(false)
.build()
val workData = Data.Builder().putString("username", currentUserAccountName).build()
val request: PeriodicWorkRequest.Builder =
PeriodicWorkRequest.Builder(NotificationWorker::class.java, 15, TimeUnit.MINUTES)
.setConstraints(constraints)
.setInputData(workData)
val workRequest: PeriodicWorkRequest = request.build()
WorkManager.getInstance(applicationContext)
.enqueueUniquePeriodicWork("XwikiNotificationTag", ExistingPeriodicWorkPolicy.KEEP, workRequest)
}
override fun onResume() {
super.onResume()
binding.shimmerSyncUsers.startShimmer()
}
override fun onPause() {
binding.shimmerSyncUsers.stopShimmer()
super.onPause()
}
private fun enableShimmer() {
binding.shimmerSyncUsers.startShimmer()
binding.shimmerSyncUsers.visibility = View.VISIBLE
}
private fun disableShimmer() {
binding.shimmerSyncUsers.stopShimmer()
binding.shimmerSyncUsers.visibility = View.GONE
}
}
| lgpl-2.1 | cfe8f486235dd4a25d243289774f173c | 34.92686 | 128 | 0.582239 | 5.93418 | false | false | false | false |
daemontus/Distributed-CTL-Model-Checker | src/main/kotlin/com/github/sybila/checker/operator/NextOperator.kt | 3 | 3445 | package com.github.sybila.checker.operator
import com.github.sybila.checker.Channel
import com.github.sybila.checker.CheckerStats
import com.github.sybila.checker.Operator
import com.github.sybila.checker.eval
import com.github.sybila.checker.map.mutable.HashStateMap
import com.github.sybila.huctl.DirectionFormula
class ExistsNextOperator<out Params: Any>(
timeFlow: Boolean, direction: DirectionFormula,
inner: Operator<Params>, partition: Channel<Params>
) : LazyOperator<Params>(partition, {
val storage = (0 until partitionCount).map { newLocalMutableMap(it) }
val i = inner.compute()
CheckerStats.setOperator("ExistsNext")
//distribute data from inner formula
for ((state, value) in i.entries()) {
for ((predecessor, dir, bound) in state.predecessors(timeFlow)) {
if (direction.eval(dir)) {
val witness = value and bound
if (witness.canSat()) {
storage[predecessor.owner()].setOrUnion(predecessor, witness)
}
}
}
}
//gather data from everyone else
val received = mapReduce(storage.prepareTransmission(partitionId))
received?.forEach { storage[partitionId].setOrUnion(it.first, it.second) }
storage[partitionId]
})
class AllNextOperator<out Params : Any>(
timeFlow: Boolean, direction: DirectionFormula,
inner: Operator<Params>, partition: Channel<Params>
) : LazyOperator<Params>(partition, {
val satisfied = (0 until partitionCount).map { HashStateMap(ff) }
val candidates = (0 until partitionCount).map { newLocalMutableMap(it) }
val mySatisfied = satisfied[partitionId]
val myCandidates = candidates[partitionId]
val i = inner.compute()
CheckerStats.setOperator("AllNext")
//distribute data so that everyone sees their successors that are satisfied in the inner formula
//and also mark all such states as candidates (candidate essentially means EX phi holds)
for ((state, value) in i.entries()) {
for ((predecessor, dir, bound) in state.predecessors(timeFlow)) {
if (direction.eval(dir)) { //if direction is false, predecessor will be false for the entire bound
val candidate = value and bound
if (candidate.canSat()) {
satisfied[predecessor.owner()].setOrUnion(state, candidate)
candidates[predecessor.owner()].setOrUnion(predecessor, candidate)
}
}
}
}
mapReduce(satisfied.prepareTransmission(partitionId))?.forEach {
mySatisfied.setOrUnion(it.first, it.second)
}
mapReduce(candidates.prepareTransmission(partitionId))?.forEach {
myCandidates.setOrUnion(it.first, it.second)
}
val result = newLocalMutableMap(partitionId)
for ((state, value) in candidates[partitionId].entries()) {
var witness = value
for ((successor, dir, bound) in state.successors(timeFlow)) {
if (!witness.canSat()) break //fail fast
if (!direction.eval(dir)) {
witness = witness and bound.not()
} else {
//either the transition is not there (bound.not()) or successor is satisfied
witness = witness and (mySatisfied[successor] or bound.not())
}
}
if (witness.canSat()) result.setOrUnion(state, witness)
}
result
}) | gpl-3.0 | 32360432f6f559774642a9891235b5f0 | 35.659574 | 111 | 0.651959 | 4.617962 | false | false | false | false |
intellij-rust/intellij-toml | src/main/kotlin/org/toml/ide/TomlHighlighter.kt | 1 | 1741 | package org.toml.ide
import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.tree.IElementType
import gnu.trove.THashMap
import org.toml.lang.core.lexer.TomlLexer
import org.toml.lang.core.psi.TomlTypes
class TomlHighlighter : SyntaxHighlighterBase() {
override fun getHighlightingLexer(): Lexer =
TomlLexer()
override fun getTokenHighlights(tokenType: IElementType?): Array<out TextAttributesKey> =
pack(tokenType?.let { tokenMap[it] })
private val tokenMap: Map<IElementType, TextAttributesKey> = makeTokenMap()
}
private fun makeTokenMap(): Map<IElementType, TextAttributesKey> {
val result = THashMap<IElementType, TextAttributesKey>()
result[TomlTypes.KEY] =
TextAttributesKey.createTextAttributesKey("TOML_KEY", DefaultLanguageHighlighterColors.KEYWORD)
result[TomlTypes.COMMENT] =
TextAttributesKey.createTextAttributesKey("TOML_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT)
result[TomlTypes.STRING] =
TextAttributesKey.createTextAttributesKey("TOML_STRING", DefaultLanguageHighlighterColors.STRING)
result[TomlTypes.NUMBER] =
TextAttributesKey.createTextAttributesKey("TOML_NUMBER", DefaultLanguageHighlighterColors.NUMBER)
result[TomlTypes.BOOLEAN] =
TextAttributesKey.createTextAttributesKey("TOML_BOOLEAN", DefaultLanguageHighlighterColors.PREDEFINED_SYMBOL)
result[TomlTypes.DATE] =
TextAttributesKey.createTextAttributesKey("TOML_DATE", DefaultLanguageHighlighterColors.PREDEFINED_SYMBOL)
return result;
}
| mit | df3f4fb79cefa9cbaef679e899b72513 | 36.042553 | 117 | 0.789202 | 5.340491 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/leagues/League.kt | 1 | 24074 | package ca.josephroque.bowlingcompanion.leagues
import android.content.ContentValues
import android.content.Context
import android.content.DialogInterface
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.os.Parcel
import android.support.v7.app.AlertDialog
import android.support.v7.preference.PreferenceManager
import android.util.Log
import android.widget.NumberPicker
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.bowlers.Bowler
import ca.josephroque.bowlingcompanion.common.interfaces.INameAverage
import ca.josephroque.bowlingcompanion.common.interfaces.KParcelable
import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator
import ca.josephroque.bowlingcompanion.common.interfaces.readBoolean
import ca.josephroque.bowlingcompanion.common.interfaces.writeBoolean
import ca.josephroque.bowlingcompanion.database.Annihilator
import ca.josephroque.bowlingcompanion.database.Contract.GameEntry
import ca.josephroque.bowlingcompanion.database.Contract.LeagueEntry
import ca.josephroque.bowlingcompanion.database.Contract.SeriesEntry
import ca.josephroque.bowlingcompanion.database.DatabaseManager
import ca.josephroque.bowlingcompanion.games.Game
import ca.josephroque.bowlingcompanion.scoring.Average
import ca.josephroque.bowlingcompanion.series.Series
import ca.josephroque.bowlingcompanion.utils.BCError
import ca.josephroque.bowlingcompanion.utils.Preferences
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.async
import java.lang.ref.WeakReference
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* Copyright (C) 2018 Joseph Roque
*
* A single League, which has a set of series.
*/
data class League(
val bowler: Bowler,
override val id: Long,
override val name: String,
override val average: Double,
val isEvent: Boolean,
val gamesPerSeries: Int,
val additionalPinfall: Int,
val additionalGames: Int,
val gameHighlight: Int,
val seriesHighlight: Int
) : INameAverage, KParcelable {
private var _isDeleted: Boolean = false
override val isDeleted: Boolean
get() = _isDeleted
val isPractice: Boolean
get() = name == PRACTICE_LEAGUE_NAME
// MARK: Constructors
private constructor(p: Parcel): this(
bowler = p.readParcelable<Bowler>(Bowler::class.java.classLoader)!!,
id = p.readLong(),
name = p.readString()!!,
average = p.readDouble(),
isEvent = p.readBoolean(),
gamesPerSeries = p.readInt(),
additionalPinfall = p.readInt(),
additionalGames = p.readInt(),
gameHighlight = p.readInt(),
seriesHighlight = p.readInt()
)
constructor(league: League): this(
bowler = league.bowler,
id = league.id,
name = league.name,
average = league.average,
isEvent = league.isEvent,
gamesPerSeries = league.gamesPerSeries,
additionalPinfall = league.additionalPinfall,
additionalGames = league.additionalGames,
gameHighlight = league.gameHighlight,
seriesHighlight = league.seriesHighlight
)
// MARK: Parcelable
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeParcelable(bowler, 0)
writeLong(id)
writeString(name)
writeDouble(average)
writeBoolean(isEvent)
writeInt(gamesPerSeries)
writeInt(additionalPinfall)
writeInt(additionalGames)
writeInt(gameHighlight)
writeInt(seriesHighlight)
}
// MARK: League
fun fetchSeries(context: Context): Deferred<MutableList<Series>> {
return Series.fetchAll(context, this)
}
fun createNewSeries(context: Context, openDatabase: SQLiteDatabase? = null, numberOfPracticeGamesOverride: Int? = null): Deferred<Pair<Series?, BCError?>> {
val numberOfGames = if (isPractice) {
numberOfPracticeGamesOverride ?: gamesPerSeries
} else {
gamesPerSeries
}
return async(CommonPool) {
return@async Series.save(
context = context,
league = this@League,
id = -1,
date = Date(),
numberOfGames = numberOfGames,
scores = IntArray(numberOfGames).toList(),
matchPlay = ByteArray(numberOfGames).toList(),
openDatabase = openDatabase
).await()
}
}
// MARK: IDeletable
override fun markForDeletion(): League {
val newInstance = League(this)
newInstance._isDeleted = true
return newInstance
}
override fun cleanDeletion(): League {
val newInstance = League(this)
newInstance._isDeleted = false
return newInstance
}
override fun delete(context: Context): Deferred<Unit> {
return async(CommonPool) {
if (id < 0) {
return@async
}
Annihilator.instance.delete(
weakContext = WeakReference(context),
tableName = LeagueEntry.TABLE_NAME,
whereClause = "${LeagueEntry._ID}=?",
whereArgs = arrayOf(id.toString())
)
}
}
companion object {
@Suppress("unused")
private const val TAG = "League"
@Suppress("unused")
@JvmField val CREATOR = parcelableCreator(::League)
private val REGEX_NAME = Bowler.REGEX_NAME
@Deprecated("Replaced with PRACTICE_LEAGUE_NAME")
const val OPEN_LEAGUE_NAME = "Open"
const val PRACTICE_LEAGUE_NAME = "Practice"
const val MAX_NUMBER_OF_GAMES = 20
const val MIN_NUMBER_OF_GAMES = 1
const val DEFAULT_NUMBER_OF_GAMES = 1
const val DEFAULT_GAME_HIGHLIGHT = 300
val DEFAULT_SERIES_HIGHLIGHT = intArrayOf(250, 500, 750, 1000, 1250, 1500, 1750, 2000, 2250, 2500, 2750, 3000, 3250, 3500, 3750, 4000, 4250, 4500, 4750, 5000)
enum class Sort {
Alphabetically,
LastModified;
companion object {
private val map = Sort.values().associateBy(Sort::ordinal)
fun fromInt(type: Int) = map[type]
}
}
fun showPracticeGamesPicker(context: Context, completionHandler: (Int) -> Unit) {
val numberPicker = NumberPicker(context)
numberPicker.maxValue = League.MAX_NUMBER_OF_GAMES
numberPicker.minValue = 1
numberPicker.wrapSelectorWheel = false
val listener = DialogInterface.OnClickListener { dialog, which ->
if (which == DialogInterface.BUTTON_POSITIVE) {
completionHandler(numberPicker.value)
}
dialog.dismiss()
}
AlertDialog.Builder(context)
.setTitle(R.string.how_many_practice_games)
.setView(numberPicker)
.setPositiveButton(R.string.bowl, listener)
.setNegativeButton(R.string.cancel, listener)
.create()
.show()
}
private fun isLeagueNameValid(name: String): Boolean = REGEX_NAME.matches(name)
private fun nameMatchesPracticeLeague(name: String): Boolean = PRACTICE_LEAGUE_NAME.toLowerCase().equals(name.toLowerCase())
private fun isLeagueNameUnique(context: Context, name: String, id: Long = -1): Deferred<Boolean> {
return async(CommonPool) {
val database = DatabaseManager.getReadableDatabase(context).await()
var cursor: Cursor? = null
try {
cursor = database.query(
LeagueEntry.TABLE_NAME,
arrayOf(LeagueEntry.COLUMN_LEAGUE_NAME),
"${LeagueEntry.COLUMN_LEAGUE_NAME}=? AND ${LeagueEntry._ID}!=?",
arrayOf(name, id.toString()),
"",
"",
""
)
if ((cursor?.count ?: 0) > 0) {
return@async false
}
} finally {
if (cursor != null && !cursor.isClosed) {
cursor.close()
}
}
true
}
}
private fun validateSavePreconditions(
context: Context,
id: Long,
name: String,
isEvent: Boolean,
gamesPerSeries: Int,
additionalPinfall: Int,
additionalGames: Int,
gameHighlight: Int,
seriesHighlight: Int
): Deferred<BCError?> {
return async(CommonPool) {
val errorTitle = if (isEvent) R.string.issue_saving_event else R.string.issue_saving_league
val errorMessage: Int?
if (nameMatchesPracticeLeague(name)) {
errorMessage = R.string.error_league_name_is_practice
} else if (!isLeagueNameValid(name)) {
errorMessage = if (isEvent) R.string.error_event_name_invalid else R.string.error_league_name_invalid
} else if (!isLeagueNameUnique(context, name, id).await()) {
errorMessage = R.string.error_league_name_in_use
} else if (name == PRACTICE_LEAGUE_NAME) {
errorMessage = R.string.error_cannot_edit_practice_league
} else if (
(isEvent && (additionalPinfall != 0 || additionalGames != 0)) ||
(additionalPinfall < 0 || additionalGames < 0) ||
(additionalPinfall > 0 && additionalGames == 0) ||
(additionalPinfall.toDouble() / additionalGames.toDouble() > 450)
) {
errorMessage = R.string.error_league_additional_info_unbalanced
} else if (
gameHighlight < 0 || gameHighlight > Game.MAX_SCORE ||
seriesHighlight < 0 || seriesHighlight > Game.MAX_SCORE * gamesPerSeries
) {
errorMessage = R.string.error_league_highlight_invalid
} else if (gamesPerSeries < MIN_NUMBER_OF_GAMES || gamesPerSeries > MAX_NUMBER_OF_GAMES) {
errorMessage = R.string.error_league_number_of_games_invalid
} else {
errorMessage = null
}
return@async if (errorMessage != null) {
BCError(errorTitle, errorMessage, BCError.Severity.Warning)
} else {
null
}
}
}
fun save(
context: Context,
bowler: Bowler,
id: Long,
name: String,
isEvent: Boolean,
gamesPerSeries: Int,
additionalPinfall: Int,
additionalGames: Int,
gameHighlight: Int,
seriesHighlight: Int,
average: Double = 0.0
): Deferred<Pair<League?, BCError?>> {
return if (id < 0) {
createNewAndSave(context, bowler, name, isEvent, gamesPerSeries, additionalPinfall, additionalGames, gameHighlight, seriesHighlight)
} else {
update(context, bowler, id, name, average, isEvent, gamesPerSeries, additionalPinfall, additionalGames, gameHighlight, seriesHighlight)
}
}
private fun createNewAndSave(
context: Context,
bowler: Bowler,
name: String,
isEvent: Boolean,
gamesPerSeries: Int,
additionalPinfall: Int,
additionalGames: Int,
gameHighlight: Int,
seriesHighlight: Int
): Deferred<Pair<League?, BCError?>> {
return async(CommonPool) {
val error = validateSavePreconditions(
context = context,
id = -1,
name = name,
isEvent = isEvent,
gamesPerSeries = gamesPerSeries,
additionalPinfall = additionalPinfall,
additionalGames = additionalGames,
gameHighlight = gameHighlight,
seriesHighlight = seriesHighlight
).await()
if (error != null) {
return@async Pair(null, error)
}
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CANADA)
val currentDate = dateFormat.format(Date())
val values = ContentValues().apply {
put(LeagueEntry.COLUMN_LEAGUE_NAME, name)
put(LeagueEntry.COLUMN_DATE_MODIFIED, currentDate)
put(LeagueEntry.COLUMN_BOWLER_ID, bowler.id)
put(LeagueEntry.COLUMN_ADDITIONAL_PINFALL, additionalPinfall)
put(LeagueEntry.COLUMN_ADDITIONAL_GAMES, additionalGames)
put(LeagueEntry.COLUMN_NUMBER_OF_GAMES, gamesPerSeries)
put(LeagueEntry.COLUMN_IS_EVENT, isEvent)
put(LeagueEntry.COLUMN_GAME_HIGHLIGHT, gameHighlight)
put(LeagueEntry.COLUMN_SERIES_HIGHLIGHT, seriesHighlight)
}
val league: League
val database = DatabaseManager.getWritableDatabase(context).await()
database.beginTransaction()
try {
val leagueId = database.insert(LeagueEntry.TABLE_NAME, null, values)
league = League(
bowler = bowler,
id = leagueId,
name = name,
average = 0.0,
isEvent = isEvent,
gamesPerSeries = gamesPerSeries,
additionalPinfall = additionalPinfall,
additionalGames = additionalGames,
gameHighlight = gameHighlight,
seriesHighlight = seriesHighlight
)
if (league.id != -1L && isEvent) {
/*
* If the new entry is an event, its series is also created at this time
* since there is only a single series to an event
*/
val (series, seriesError) = league.createNewSeries(context, database).await()
if (seriesError != null || (series?.id ?: -1L) == -1L) {
throw IllegalStateException("Series was not saved.")
}
}
database.setTransactionSuccessful()
} catch (ex: Exception) {
Log.e(TAG, "Could not create a new league")
return@async Pair(
null,
BCError(R.string.error_saving_league, R.string.error_league_not_saved)
)
} finally {
database.endTransaction()
}
Pair(league, null)
}
}
fun update(
context: Context,
bowler: Bowler,
id: Long,
name: String,
average: Double,
isEvent: Boolean,
gamesPerSeries: Int,
additionalPinfall: Int,
additionalGames: Int,
gameHighlight: Int,
seriesHighlight: Int
): Deferred<Pair<League?, BCError?>> {
return async(CommonPool) {
val error = validateSavePreconditions(
context = context,
id = id,
name = name,
isEvent = isEvent,
gamesPerSeries = gamesPerSeries,
additionalPinfall = additionalPinfall,
additionalGames = additionalGames,
gameHighlight = gameHighlight,
seriesHighlight = seriesHighlight
).await()
if (error != null) {
return@async Pair(null, error)
}
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CANADA)
val currentDate = dateFormat.format(Date())
val values = ContentValues().apply {
put(LeagueEntry.COLUMN_LEAGUE_NAME, name)
put(LeagueEntry.COLUMN_ADDITIONAL_PINFALL, additionalPinfall)
put(LeagueEntry.COLUMN_ADDITIONAL_GAMES, additionalGames)
put(LeagueEntry.COLUMN_GAME_HIGHLIGHT, gameHighlight)
put(LeagueEntry.COLUMN_SERIES_HIGHLIGHT, seriesHighlight)
put(LeagueEntry.COLUMN_DATE_MODIFIED, currentDate)
}
val database = DatabaseManager.getWritableDatabase(context).await()
database.beginTransaction()
try {
database.update(LeagueEntry.TABLE_NAME, values, LeagueEntry._ID + "=?", arrayOf(id.toString()))
database.setTransactionSuccessful()
} catch (ex: Exception) {
Log.e(TAG, "Error updating league/event details ($name, $additionalPinfall, $additionalGames)", ex)
} finally {
database.endTransaction()
}
Pair(League(
bowler = bowler,
id = id,
name = name,
average = average,
isEvent = isEvent,
gamesPerSeries = gamesPerSeries,
additionalPinfall = additionalPinfall,
additionalGames = additionalGames,
gameHighlight = gameHighlight,
seriesHighlight = seriesHighlight
), null)
}
}
fun fetchAll(
context: Context,
bowler: Bowler,
includeLeagues: Boolean = true,
includeEvents: Boolean = false
): Deferred<MutableList<League>> {
return async(CommonPool) {
val leagues: MutableList<League> = ArrayList()
val database = DatabaseManager.getReadableDatabase(context).await()
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
val sortBy = Sort.fromInt(preferences.getInt(Preferences.LEAGUE_SORT_ORDER, Sort.Alphabetically.ordinal))
val orderQueryBy = if (sortBy == Sort.Alphabetically) {
"ORDER BY league.${LeagueEntry.COLUMN_LEAGUE_NAME} "
} else {
"ORDER BY league.${LeagueEntry.COLUMN_DATE_MODIFIED} DESC "
}
val rawLeagueEventQuery = ("SELECT " +
"league.${LeagueEntry._ID} AS lid, " +
"${LeagueEntry.COLUMN_LEAGUE_NAME}, " +
"${LeagueEntry.COLUMN_IS_EVENT}, " +
"${LeagueEntry.COLUMN_ADDITIONAL_PINFALL}, " +
"${LeagueEntry.COLUMN_ADDITIONAL_GAMES}, " +
"${LeagueEntry.COLUMN_GAME_HIGHLIGHT}, " +
"${LeagueEntry.COLUMN_SERIES_HIGHLIGHT}, " +
"${LeagueEntry.COLUMN_NUMBER_OF_GAMES}, " +
"${GameEntry.COLUMN_SCORE} " +
"FROM ${LeagueEntry.TABLE_NAME} AS league " +
"LEFT JOIN ${SeriesEntry.TABLE_NAME} AS series " +
"ON league.${LeagueEntry._ID}=series.${SeriesEntry.COLUMN_LEAGUE_ID} " +
"LEFT JOIN ${GameEntry.TABLE_NAME} AS game " +
"ON series.${SeriesEntry._ID}=game.${GameEntry.COLUMN_SERIES_ID} " +
"WHERE ${LeagueEntry.COLUMN_BOWLER_ID}=? " +
orderQueryBy)
val cursor = database.rawQuery(rawLeagueEventQuery, arrayOf(bowler.id.toString()))
var lastId: Long = -1
var leagueNumberOfGames = 0
var leagueTotal = 0
fun isCurrentLeagueEvent(cursor: Cursor): Boolean {
return cursor.getInt(cursor.getColumnIndex(LeagueEntry.COLUMN_IS_EVENT)) == 1
}
fun buildLeagueFromCursor(cursor: Cursor): League {
val id = cursor.getLong(cursor.getColumnIndex("lid"))
val name = cursor.getString(cursor.getColumnIndex(LeagueEntry.COLUMN_LEAGUE_NAME))
val additionalPinfall = cursor.getInt(cursor.getColumnIndex(LeagueEntry.COLUMN_ADDITIONAL_PINFALL))
val additionalGames = cursor.getInt(cursor.getColumnIndex(LeagueEntry.COLUMN_ADDITIONAL_GAMES))
val gameHighlight = cursor.getInt(cursor.getColumnIndex(LeagueEntry.COLUMN_GAME_HIGHLIGHT))
val seriesHighlight = cursor.getInt(cursor.getColumnIndex(LeagueEntry.COLUMN_SERIES_HIGHLIGHT))
val gamesPerSeries = cursor.getInt(cursor.getColumnIndex(LeagueEntry.COLUMN_NUMBER_OF_GAMES))
val average = Average.getAdjustedAverage(leagueTotal, leagueNumberOfGames, additionalPinfall, additionalGames)
val isEvent = isCurrentLeagueEvent(cursor)
return League(
bowler,
id,
name,
average,
isEvent,
gamesPerSeries,
additionalPinfall,
additionalGames,
gameHighlight,
seriesHighlight
)
}
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast) {
val newId = cursor.getLong(cursor.getColumnIndex("lid"))
if (newId != lastId && lastId != -1L) {
cursor.moveToPrevious()
val isEvent = isCurrentLeagueEvent(cursor)
if ((includeEvents && isEvent) || (includeLeagues && !isEvent)) {
leagues.add(buildLeagueFromCursor(cursor))
}
leagueTotal = 0
leagueNumberOfGames = 0
cursor.moveToNext()
}
val score = cursor.getShort(cursor.getColumnIndex(GameEntry.COLUMN_SCORE))
if (score > 0) {
leagueTotal += score.toInt()
leagueNumberOfGames++
}
lastId = newId
cursor.moveToNext()
}
cursor.moveToPrevious()
val isEvent = isCurrentLeagueEvent(cursor)
if ((includeEvents && isEvent) || (includeLeagues && !isEvent)) {
leagues.add(buildLeagueFromCursor(cursor))
}
}
cursor.close()
leagues
}
}
}
}
| mit | 03050605d833202a366c4a78337dd990 | 40.506897 | 166 | 0.532275 | 5.703388 | false | false | false | false |
universum-studios/gradle_github_plugin | plugin/src/core/kotlin/universum/studios/gradle/github/task/specification/TaskSpecification.kt | 1 | 2641 | /*
* *************************************************************************************************
* Copyright 2017 Universum Studios
* *************************************************************************************************
* 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 universum.studios.gradle.github.task.specification
import org.gradle.api.Task
/**
* Class describing a simple task used by the GitHub Release plugin.
*
* @author Martin Albedinsky
* @since 1.0
*
* @property type Type of the task.
* @property name Name of the task.
* @property description Description of the task.
* @property dependsOn List of the tasks that the plugin task depends on.
* @constructor Creates a new instance of TaskSpecification with the specified name and description.
*/
data class TaskSpecification<T : Task> (
val group: String = TaskSpecification.GROUP,
val type: Class<T>,
val name: String,
val description: String = "",
val dependsOn: List<Task> = emptyList()) {
/**
*/
companion object Contract {
/**
* Name of the **group** property of a task.
*/
const val TASK_GROUP = "group"
/**
* Name of the **type** property of a task.
*/
const val TASK_TYPE = "type"
/**
* Name of the **name** property of a task.
*/
const val TASK_NAME = "name"
/**
* Name of the **description** property of a task.
*/
const val TASK_DESCRIPTION = "description"
/**
* Name of the **dependsOn** property of a task.
*/
const val TASK_DEPENDS_ON = "dependsOn"
/**
* Name of the group where all Gradle tasks provided by the GitHub plugin are placed by
* default.
*/
const val GROUP = "github"
}
} | apache-2.0 | b5177abdf3b54d9863133fdd674eebb0 | 33.311688 | 101 | 0.518743 | 5.128155 | false | false | false | false |
FantAsylum/Floor--13 | core/src/com/floor13/game/screens/GameScreen.kt | 1 | 4145 | package com.floor13.game.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.ScreenAdapter
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.utils.viewport.ExtendViewport
import com.badlogic.gdx.InputMultiplexer
import com.badlogic.gdx.InputAdapter
import com.badlogic.gdx.Input
import com.floor13.game.core.World
import com.floor13.game.actors.MapActor
import com.floor13.game.actors.CreatureActor
import com.floor13.game.core.actions.MoveAction
import com.floor13.game.core.actions.OpenDoorAction
import com.floor13.game.core.Position
import com.floor13.game.core.creatures.Creature
import com.floor13.game.core.map.Door
class GameScreen(val world: World) : ScreenAdapter() {
val levelStage = Stage(ExtendViewport(
Gdx.graphics.width.toFloat(),
Gdx.graphics.height.toFloat()
))
val hudStage = Stage() // TODO: pick viewport
val mapScroller = object: InputAdapter() {
var x = 0
var y = 0
override fun touchDown(x: Int, y: Int, pointer: Int, button: Int): Boolean {
this.x = x
this.y = y
return true
}
override fun touchDragged(x: Int, y: Int, pointer: Int): Boolean {
val dx = this.x - x
val dy = this.y - y
this.x = x
this.y = y
levelStage.camera.translate(dx.toFloat(), -dy.toFloat(), 0f)
return true
}
}
val keyboardProcessor = object: InputAdapter() {
fun scheduleMoveOrDoorOpening(position: Position) {
val tile = world.currentFloor[position]
val action =
if (tile is Door && !tile.opened) {
OpenDoorAction(world, world.mainCharacter, position)
} else {
MoveAction(world, world.mainCharacter, position)
}
if (action.isValid)
world.mainCharacter.nextAction = action
}
override fun keyUp(keycode: Int) =
when (keycode) {
Input.Keys.UP -> {
scheduleMoveOrDoorOpening(world.mainCharacter.position.translated(0, 1))
true
}
Input.Keys.DOWN -> {
scheduleMoveOrDoorOpening(world.mainCharacter.position.translated(0, -1))
true
}
Input.Keys.RIGHT -> {
scheduleMoveOrDoorOpening(world.mainCharacter.position.translated(1, 0))
true
}
Input.Keys.LEFT -> {
scheduleMoveOrDoorOpening(world.mainCharacter.position.translated(-1, 0))
true
}
else -> false
}
}
private val creatureActors = mutableMapOf<Creature, CreatureActor>()
init {
levelStage.addActor(MapActor(world.currentFloor))
for (creature in world.creatures) {
val actor = CreatureActor(creature)
levelStage.addActor(actor)
creatureActors.put(creature, actor)
}
Gdx.input.inputProcessor = InputMultiplexer(
mapScroller,
keyboardProcessor
)
levelStage.camera.position.x = world.mainCharacter.position.x * 64f
levelStage.camera.position.y = world.mainCharacter.position.y * 64f
}
override fun render(delta: Float) {
while (world.mainCharacter.nextAction != null) {
for (action in world.tick())
when (action) {
is MoveAction -> {
creatureActors[action.creature]?.updateBounds()
?: Gdx.app.error(TAG, "Invalid creature in move action")
}
}
cameraFollowPlayer()
}
levelStage.act(delta)
levelStage.draw()
}
companion object {
val TAG = GameScreen::class.java.simpleName
}
fun cameraFollowPlayer() { // TODO: check
val cameraX = levelStage.camera.position.x
val cameraY = levelStage.camera.position.y
val playerX = world.mainCharacter.position.x * 64f
val playerY = world.mainCharacter.position.y * 64f
val maxDistance = 64f
if (cameraX > playerX) {
if (cameraX - playerX > maxDistance)
levelStage.camera.translate(-64f, 0f, 0f)
} else {
if (playerX - cameraX > maxDistance)
levelStage.camera.translate(64f, 0f, 0f)
}
if (cameraY > playerY) {
if (cameraY - playerY > maxDistance)
levelStage.camera.translate(0f, -64f, 0f)
} else {
if (playerY - cameraY > maxDistance)
levelStage.camera.translate(0f, 64f, 0f)
}
}
}
| mit | b70f2b6844378cf86c3c100b60f21dee | 28.397163 | 84 | 0.665621 | 3.607485 | false | false | false | false |
angcyo/RLibrary | uiview/src/main/java/com/angcyo/uiview/widget/StatusButton.kt | 1 | 2322 | package com.angcyo.uiview.widget
import android.content.Context
import android.util.AttributeSet
import com.angcyo.uiview.R
import com.angcyo.uiview.kotlin.getColor
import com.angcyo.uiview.kotlin.getDimensionPixelOffset
import com.angcyo.uiview.resources.ResUtil
import com.angcyo.uiview.skin.SkinHelper
/**
* Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved.
* 项目名称:
* 类的描述:
* 创建人员:Robi
* 创建时间:2017/09/12 17:16
* 修改人员:Robi
* 修改时间:2017/09/12 17:16
* 修改备注:
* Version: 1.0.0
*/
open class StatusButton(context: Context, attributeSet: AttributeSet? = null) : Button(context, attributeSet) {
companion object {
/**正常状态, 灰色背景, 黑色字体*/
val STATUS_NORMAL = 1
/**主体颜色字体, 白色字体*/
val STATUS_PRESS = 2
val STATUS_CHECK = 3
val STATUS_ENABLE = 4
/**消极*/
val STATUS_DISABLE = 5
}
var buttonStatus = STATUS_NORMAL
set(value) {
field = value
refreshButton()
}
init {
}
override fun initView() {
super.initView()
isClickable = false
buttonStatus = STATUS_NORMAL
}
private fun refreshButton() {
when (buttonStatus) {
STATUS_NORMAL -> {
setTextColor(getColor(R.color.base_text_color))
background = ResUtil.createDrawable(getColor(R.color.default_base_line),
getDimensionPixelOffset(R.dimen.base_round_little_radius).toFloat())
}
STATUS_DISABLE -> {
setTextColor(getColor(R.color.base_white))
background = ResUtil.createDrawable(getColor(R.color.base_text_color_dark),
getDimensionPixelOffset(R.dimen.base_round_little_radius).toFloat())
}
STATUS_PRESS, STATUS_CHECK, STATUS_ENABLE -> {
setTextColor(getColor(R.color.base_white))
background = ResUtil.createDrawable(SkinHelper.getSkin().themeSubColor,
getDimensionPixelOffset(R.dimen.base_round_little_radius).toFloat())
}
}
}
} | apache-2.0 | f7781d051783292fd5f9607744435b6d | 28.647887 | 111 | 0.588776 | 4.27112 | false | false | false | false |
STUDIO-apps/GeoShare_Android | mobile/src/main/java/uk/co/appsbystudio/geoshare/friends/manager/pages/pending/FriendsPendingInteractorImpl.kt | 1 | 3162 | package uk.co.appsbystudio.geoshare.friends.manager.pages.pending
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import uk.co.appsbystudio.geoshare.friends.manager.FriendsManager
import uk.co.appsbystudio.geoshare.utils.firebase.AddFriendsInfo
import uk.co.appsbystudio.geoshare.utils.firebase.FirebaseHelper
class FriendsPendingInteractorImpl: FriendsPendingInteractor {
private var requestRef: DatabaseReference? = null
private lateinit var requestListener: ChildEventListener
override fun getRequests(listener: FriendsPendingInteractor.OnFirebaseListener) {
val user = FirebaseAuth.getInstance().currentUser
if (user != null) {
requestRef = FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/${user.uid}")
requestRef?.keepSynced(true)
requestListener = object : ChildEventListener {
override fun onChildAdded(dataSnapshot: DataSnapshot, s: String?) {
listener.add(dataSnapshot.key, dataSnapshot.getValue(AddFriendsInfo::class.java))
//TODO: Get name first!
}
override fun onChildChanged(dataSnapshot: DataSnapshot, s: String?) {
}
override fun onChildRemoved(dataSnapshot: DataSnapshot) {
listener.remove(dataSnapshot.key, dataSnapshot.getValue(AddFriendsInfo::class.java))
}
override fun onChildMoved(dataSnapshot: DataSnapshot, s: String?) {
}
override fun onCancelled(databaseError: DatabaseError) {
listener.error(databaseError.message)
}
}
requestRef?.addChildEventListener(requestListener)
}
}
override fun acceptRequest(uid: String) {
FriendsManager.pendingUid.remove(uid)
val user = FirebaseAuth.getInstance().currentUser
FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.FRIENDS}/${user?.uid}/$uid").setValue(true)
FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.FRIENDS}/$uid/${user?.uid}").setValue(true)
FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/${user?.uid}/$uid").removeValue()
FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/$uid/${user?.uid}").removeValue()
}
override fun rejectRequest(uid: String) {
FriendsManager.pendingUid.remove(uid)
val user = FirebaseAuth.getInstance().currentUser
FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/${user?.uid}/$uid").removeValue()
FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/$uid/${user?.uid}").removeValue()
FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/${user?.uid}/$uid").removeValue()
FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/$uid/${user?.uid}").removeValue()
}
override fun removeListener() {
requestRef?.removeEventListener(requestListener)
}
} | apache-2.0 | 6bed758b4002603816b5fbce95f8e82e | 43.549296 | 116 | 0.682796 | 5.43299 | false | false | false | false |
christophpickl/kpotpourri | common4k/src/main/kotlin/com/github/christophpickl/kpotpourri/common/time/time.kt | 1 | 1059 | package com.github.christophpickl.kpotpourri.common.time
import com.github.christophpickl.kpotpourri.common.numbers.format
/**
* Create a readable representation of milliseconds in a given format.
*/
fun Long.timify(format: MsTimification) = format.timify(this)
/**
* Available formats for milliseconds representation.
*/
enum class MsTimification {
/**
* Format as "1.234 seconds".
*/
Seconds {
override fun timify(ms: Long) = (ms / 1000.0).format(3) + " seconds"
},
/**
* Format as "1 minute and 23 seconds".
*/
MinutesAndSeconds {
override fun timify(ms: Long): String {
val totalSeconds = (ms / 1000.0).toInt()
val mins = (totalSeconds / 60)
val secs = totalSeconds - (mins * 60)
val pluralSeconds = if (secs == 1) "" else "s"
val pluralMinutes = if (mins == 1) "" else "s"
return "$mins minute$pluralMinutes and $secs second$pluralSeconds"
}
}
;
internal abstract fun timify(ms: Long): String
}
| apache-2.0 | 7b367993fecf3582fd09865770e08565 | 26.153846 | 78 | 0.610009 | 3.936803 | false | false | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/api/QueueApiController.kt | 1 | 3113 | package org.openapitools.api
import org.openapitools.model.Queue
import io.swagger.v3.oas.annotations.*
import io.swagger.v3.oas.annotations.enums.*
import io.swagger.v3.oas.annotations.media.*
import io.swagger.v3.oas.annotations.responses.*
import io.swagger.v3.oas.annotations.security.*
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.validation.annotation.Validated
import org.springframework.web.context.request.NativeWebRequest
import org.springframework.beans.factory.annotation.Autowired
import javax.validation.Valid
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import kotlin.collections.List
import kotlin.collections.Map
@RestController
@Validated
@RequestMapping("\${api.base-path:}")
class QueueApiController() {
@Operation(
summary = "",
operationId = "getQueue",
description = "Retrieve queue details",
responses = [
ApiResponse(responseCode = "200", description = "Successfully retrieved queue details", content = [Content(schema = Schema(implementation = Queue::class))]),
ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"),
ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ],
security = [ SecurityRequirement(name = "jenkins_auth") ]
)
@RequestMapping(
method = [RequestMethod.GET],
value = ["/queue/api/json"],
produces = ["application/json"]
)
fun getQueue(): ResponseEntity<Queue> {
return ResponseEntity(HttpStatus.NOT_IMPLEMENTED)
}
@Operation(
summary = "",
operationId = "getQueueItem",
description = "Retrieve queued item details",
responses = [
ApiResponse(responseCode = "200", description = "Successfully retrieved queued item details", content = [Content(schema = Schema(implementation = Queue::class))]),
ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"),
ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ],
security = [ SecurityRequirement(name = "jenkins_auth") ]
)
@RequestMapping(
method = [RequestMethod.GET],
value = ["/queue/item/{number}/api/json"],
produces = ["application/json"]
)
fun getQueueItem(@Parameter(description = "Queue number", required = true) @PathVariable("number") number: kotlin.String): ResponseEntity<Queue> {
return ResponseEntity(HttpStatus.NOT_IMPLEMENTED)
}
}
| mit | e236de53e2196835640706d99d065d54 | 41.643836 | 175 | 0.725667 | 4.709531 | false | false | false | false |
jiangkang/KTools | tools/src/main/java/com/jiangkang/tools/utils/SensorUtils.kt | 1 | 750 | package com.jiangkang.tools.utils
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorManager
import com.jiangkang.tools.King.applicationContext
/**
* Created by jiangkang on 2017/12/4.
* description:
*/
object SensorUtils {
/*
* 判断设备是否支持计步器
* */
val isSupportStepSensor: Boolean
get() {
val sensorManager = applicationContext!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager
val counterSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
val detectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR)
return counterSensor != null || detectorSensor != null
}
} | mit | 281509b7254b5222fd852a98864676c7 | 30.608696 | 110 | 0.716253 | 4.566038 | false | false | false | false |
jitsi/jitsi-videobridge | jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/transform/node/outgoing/HeaderExtStripper.kt | 1 | 1867 | /*
* Copyright @ 2018 - Present, 8x8 Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj.transform.node.outgoing
import org.jitsi.nlj.PacketInfo
import org.jitsi.nlj.rtp.RtpExtensionType
import org.jitsi.nlj.transform.node.ModifierNode
import org.jitsi.nlj.util.ReadOnlyStreamInformationStore
import org.jitsi.rtp.rtp.RtpPacket
/**
* Strip all hop-by-hop header extensions. Currently this leaves only ssrc-audio-level and video-orientation.
*/
class HeaderExtStripper(
streamInformationStore: ReadOnlyStreamInformationStore
) : ModifierNode("Strip header extensions") {
private var retainedExts: Set<Int> = emptySet()
init {
retainedExtTypes.forEach { rtpExtensionType ->
streamInformationStore.onRtpExtensionMapping(rtpExtensionType) {
it?.let { retainedExts = retainedExts.plus(it) }
}
}
}
override fun modify(packetInfo: PacketInfo): PacketInfo {
val rtpPacket = packetInfo.packetAs<RtpPacket>()
rtpPacket.removeHeaderExtensionsExcept(retainedExts)
return packetInfo
}
override fun trace(f: () -> Unit) = f.invoke()
companion object {
private val retainedExtTypes: Set<RtpExtensionType> = setOf(
RtpExtensionType.SSRC_AUDIO_LEVEL, RtpExtensionType.VIDEO_ORIENTATION
)
}
}
| apache-2.0 | 4a6a78e7070070cb9b25e6d0322f1fdd | 32.945455 | 110 | 0.717729 | 4.34186 | false | false | false | false |
ze-pequeno/okhttp | mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt | 2 | 12555 | /*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 mockwebserver3
import java.util.concurrent.TimeUnit
import mockwebserver3.internal.duplex.DuplexResponseBody
import okhttp3.Headers
import okhttp3.WebSocketListener
import okhttp3.internal.addHeaderLenient
import okhttp3.internal.http2.Settings
import okio.Buffer
/** A scripted response to be replayed by the mock web server. */
class MockResponse : Cloneable {
var inTunnel = false
private set
var informationalResponses: List<MockResponse> = listOf()
private set
/** Returns the HTTP response line, such as "HTTP/1.1 200 OK". */
@set:JvmName("status")
var status: String = ""
val code: Int
get() {
val statusParts = status.split(' ', limit = 3)
require(statusParts.size >= 2) { "Unexpected status: $status" }
return statusParts[1].toInt()
}
val message: String
get() {
val statusParts = status.split(' ', limit = 3)
require(statusParts.size >= 2) { "Unexpected status: $status" }
return statusParts[2]
}
private var headersBuilder = Headers.Builder()
private var trailersBuilder = Headers.Builder()
/** The HTTP headers, such as "Content-Length: 0". */
@set:JvmName("headers")
var headers: Headers
get() = headersBuilder.build()
set(value) {
this.headersBuilder = value.newBuilder()
}
@set:JvmName("trailers")
var trailers: Headers
get() = trailersBuilder.build()
set(value) {
this.trailersBuilder = value.newBuilder()
}
private var body: Buffer? = null
var throttleBytesPerPeriod: Long = Long.MAX_VALUE
private set
private var throttlePeriodAmount = 1L
private var throttlePeriodUnit = TimeUnit.SECONDS
@set:JvmName("socketPolicy")
var socketPolicy: SocketPolicy = SocketPolicy.KEEP_OPEN
/**
* Sets the [HTTP/2 error code](https://tools.ietf.org/html/rfc7540#section-7) to be
* returned when resetting the stream.
* This is only valid with [SocketPolicy.RESET_STREAM_AT_START] and
* [SocketPolicy.DO_NOT_READ_REQUEST_BODY].
*/
@set:JvmName("http2ErrorCode")
var http2ErrorCode: Int = -1
private var bodyDelayAmount = 0L
private var bodyDelayUnit = TimeUnit.MILLISECONDS
private var headersDelayAmount = 0L
private var headersDelayUnit = TimeUnit.MILLISECONDS
private var promises = mutableListOf<PushPromise>()
var settings: Settings = Settings()
private set
var webSocketListener: WebSocketListener? = null
private set
var duplexResponseBody: DuplexResponseBody? = null
private set
val isDuplex: Boolean
get() = duplexResponseBody != null
/** Returns the streams the server will push with this response. */
val pushPromises: List<PushPromise>
get() = promises
/** Creates a new mock response with an empty body. */
init {
setResponseCode(200)
setHeader("Content-Length", 0L)
}
public override fun clone(): MockResponse {
val result = super.clone() as MockResponse
result.headersBuilder = headersBuilder.build().newBuilder()
result.promises = promises.toMutableList()
return result
}
@JvmName("-deprecated_getStatus")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(expression = "status"),
level = DeprecationLevel.ERROR)
fun getStatus(): String = status
/**
* Sets the status and returns this.
*
* This was deprecated in OkHttp 4.0 in favor of the [status] val. In OkHttp 4.3 it is
* un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains
* deprecated).
*/
fun setStatus(status: String) = apply {
this.status = status
}
fun setResponseCode(code: Int): MockResponse {
val reason = when (code) {
in 100..199 -> "Informational"
in 200..299 -> "OK"
in 300..399 -> "Redirection"
in 400..499 -> "Client Error"
in 500..599 -> "Server Error"
else -> "Mock Response"
}
return apply { status = "HTTP/1.1 $code $reason" }
}
/**
* Removes all HTTP headers including any "Content-Length" and "Transfer-encoding" headers that
* were added by default.
*/
fun clearHeaders() = apply {
headersBuilder = Headers.Builder()
}
/**
* Adds [header] as an HTTP header. For well-formed HTTP [header] should contain a
* name followed by a colon and a value.
*/
fun addHeader(header: String) = apply {
headersBuilder.add(header)
}
/**
* Adds a new header with the name and value. This may be used to add multiple headers with the
* same name.
*/
fun addHeader(name: String, value: Any) = apply {
headersBuilder.add(name, value.toString())
}
/**
* Adds a new header with the name and value. This may be used to add multiple headers with the
* same name. Unlike [addHeader] this does not validate the name and
* value.
*/
fun addHeaderLenient(name: String, value: Any) = apply {
addHeaderLenient(headersBuilder, name, value.toString())
}
/**
* Removes all headers named [name], then adds a new header with the name and value.
*/
fun setHeader(name: String, value: Any) = apply {
removeHeader(name)
addHeader(name, value)
}
/** Removes all headers named [name]. */
fun removeHeader(name: String) = apply {
headersBuilder.removeAll(name)
}
/** Returns a copy of the raw HTTP payload. */
fun getBody(): Buffer? = body?.clone()
fun setBody(body: Buffer) = apply {
setHeader("Content-Length", body.size)
this.body = body.clone() // Defensive copy.
}
/** Sets the response body to the UTF-8 encoded bytes of [body]. */
fun setBody(body: String): MockResponse = setBody(Buffer().writeUtf8(body))
fun setBody(duplexResponseBody: DuplexResponseBody) = apply {
this.duplexResponseBody = duplexResponseBody
}
/**
* Sets the response body to [body], chunked every [maxChunkSize] bytes.
*/
fun setChunkedBody(body: Buffer, maxChunkSize: Int) = apply {
removeHeader("Content-Length")
headersBuilder.add(CHUNKED_BODY_HEADER)
val bytesOut = Buffer()
while (!body.exhausted()) {
val chunkSize = minOf(body.size, maxChunkSize.toLong())
bytesOut.writeHexadecimalUnsignedLong(chunkSize)
bytesOut.writeUtf8("\r\n")
bytesOut.write(body, chunkSize)
bytesOut.writeUtf8("\r\n")
}
bytesOut.writeUtf8("0\r\n") // Last chunk. Trailers follow!
this.body = bytesOut
}
/**
* Sets the response body to the UTF-8 encoded bytes of [body],
* chunked every [maxChunkSize] bytes.
*/
fun setChunkedBody(body: String, maxChunkSize: Int): MockResponse =
setChunkedBody(Buffer().writeUtf8(body), maxChunkSize)
@JvmName("-deprecated_getHeaders")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(expression = "headers"),
level = DeprecationLevel.ERROR)
fun getHeaders(): Headers = headers
/**
* Sets the headers and returns this.
*
* This was deprecated in OkHttp 4.0 in favor of the [headers] val. In OkHttp 4.3 it is
* un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains
* deprecated).
*/
fun setHeaders(headers: Headers) = apply { this.headers = headers }
@JvmName("-deprecated_getTrailers")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(expression = "trailers"),
level = DeprecationLevel.ERROR)
fun getTrailers(): Headers = trailers
/**
* Sets the trailers and returns this.
*
* This was deprecated in OkHttp 4.0 in favor of the [trailers] val. In OkHttp 4.3 it is
* un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains
* deprecated).
*/
fun setTrailers(trailers: Headers) = apply { this.trailers = trailers }
@JvmName("-deprecated_getSocketPolicy")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(expression = "socketPolicy"),
level = DeprecationLevel.ERROR)
fun getSocketPolicy(): SocketPolicy = socketPolicy
/**
* Sets the socket policy and returns this.
*
* This was deprecated in OkHttp 4.0 in favor of the [socketPolicy] val. In OkHttp 4.3 it is
* un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains
* deprecated).
*/
fun setSocketPolicy(socketPolicy: SocketPolicy) = apply {
this.socketPolicy = socketPolicy
}
@JvmName("-deprecated_getHttp2ErrorCode")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(expression = "http2ErrorCode"),
level = DeprecationLevel.ERROR)
fun getHttp2ErrorCode(): Int = http2ErrorCode
/**
* Sets the HTTP/2 error code and returns this.
*
* This was deprecated in OkHttp 4.0 in favor of the [http2ErrorCode] val. In OkHttp 4.3 it is
* un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains
* deprecated).
*/
fun setHttp2ErrorCode(http2ErrorCode: Int) = apply {
this.http2ErrorCode = http2ErrorCode
}
/**
* Throttles the request reader and response writer to sleep for the given period after each
* series of [bytesPerPeriod] bytes are transferred. Use this to simulate network behavior.
*/
fun throttleBody(bytesPerPeriod: Long, period: Long, unit: TimeUnit) = apply {
throttleBytesPerPeriod = bytesPerPeriod
throttlePeriodAmount = period
throttlePeriodUnit = unit
}
fun getThrottlePeriod(unit: TimeUnit): Long =
unit.convert(throttlePeriodAmount, throttlePeriodUnit)
/**
* Set the delayed time of the response body to [delay]. This applies to the response body
* only; response headers are not affected.
*/
fun setBodyDelay(delay: Long, unit: TimeUnit) = apply {
bodyDelayAmount = delay
bodyDelayUnit = unit
}
fun getBodyDelay(unit: TimeUnit): Long =
unit.convert(bodyDelayAmount, bodyDelayUnit)
fun setHeadersDelay(delay: Long, unit: TimeUnit) = apply {
headersDelayAmount = delay
headersDelayUnit = unit
}
fun getHeadersDelay(unit: TimeUnit): Long =
unit.convert(headersDelayAmount, headersDelayUnit)
/**
* When [protocols][MockWebServer.protocols] include [HTTP_2][okhttp3.Protocol], this attaches a
* pushed stream to this response.
*/
fun withPush(promise: PushPromise) = apply {
promises.add(promise)
}
/**
* When [protocols][MockWebServer.protocols] include [HTTP_2][okhttp3.Protocol], this pushes
* [settings] before writing the response.
*/
fun withSettings(settings: Settings) = apply {
this.settings = settings
}
/**
* Attempts to perform a web socket upgrade on the connection.
* This will overwrite any previously set status or body.
*/
fun withWebSocketUpgrade(listener: WebSocketListener) = apply {
status = "HTTP/1.1 101 Switching Protocols"
setHeader("Connection", "Upgrade")
setHeader("Upgrade", "websocket")
body = null
webSocketListener = listener
}
/**
* Configures this response to be served as a response to an HTTP CONNECT request, either for
* doing HTTPS through an HTTP proxy, or HTTP/2 prior knowledge through an HTTP proxy.
*
* When a new connection is received, all in-tunnel responses are served before the connection is
* upgraded to HTTPS or HTTP/2.
*/
fun inTunnel() = apply {
removeHeader("Content-Length")
inTunnel = true
}
/**
* Adds an HTTP 1xx response to precede this response. Note that this response's
* [headers delay][setHeadersDelay] applies after this response is transmitted. Set a
* headers delay on that response to delay its transmission.
*/
fun addInformationalResponse(response: MockResponse) = apply {
informationalResponses += response
}
fun add100Continue() = apply {
addInformationalResponse(
MockResponse()
.setResponseCode(100)
)
}
override fun toString(): String = status
companion object {
private const val CHUNKED_BODY_HEADER = "Transfer-encoding: chunked"
}
}
| apache-2.0 | 73c22d0582ad315e473be72b347191ce | 30.309227 | 99 | 0.690243 | 4.244422 | false | false | false | false |
loxal/muctool | whois/src/main/kotlin/net/loxal/muctool/whois/main.kt | 1 | 6437 | /*
* MUCtool Web Toolkit
*
* Copyright 2019 Alexander Orlov <[email protected]>. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//@file:JsQualifier("mylib.pkg2")
//@file:JsModule("Whois")
package net.loxal.muctool.whois
import org.w3c.dom.HTMLDListElement
import org.w3c.dom.HTMLDivElement
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.events.Event
import org.w3c.xhr.XMLHttpRequest
import kotlin.browser.document
import kotlin.browser.window
import kotlin.js.Json
import kotlin.js.Promise
private fun main() {
document.addEventListener("InitContainer", {
Whois()
})
document.addEventListener("DOMContentLoaded", {
Whois()
})
}
class Whois {
private fun clearPreviousWhoisView() {
(document.getElementById("whois") as HTMLDivElement).innerHTML = ""
}
private val isDebugView = window.location.search.contains("debug-view")
private fun log(msg: Any?) {
if (isDebugView) {
println(msg)
}
}
private fun traverse(dlE: HTMLDListElement, obj: Json = JSON.parse(""), process: () -> HTMLElement) {
fun process(dlE: HTMLDListElement, key: String, value: String, jsonEntryEnd: String): Promise<HTMLElement> {
fun showAsQueryIpAddress(key: String, value: String) {
if (key === "ip") {
ipAddressContainer.value = value
}
}
val dtE = document.createElement("dt") as HTMLElement
dtE.setAttribute("style", "display: inline-block; text-indent: 1em;")
val ddE = document.createElement("dd") as HTMLElement
ddE.setAttribute("style", "display: inline-block; text-indent: -2.5em;")
dtE.textContent = "\"$key\":"
showAsQueryIpAddress(key, value)
if (jsTypeOf(value) !== "object") {
val ddEcontent: String =
if (jsTypeOf(value) === "string") {
"\"$value\""
} else {
value
}
ddE.textContent = "$ddEcontent$jsonEntryEnd"
}
dlE.appendChild(dtE)
dlE.appendChild(ddE)
val blockBreak = document.createElement("dd") as HTMLElement
blockBreak.setAttribute("style", "display: block;")
dlE.appendChild(blockBreak)
return Promise.resolve(ddE)
}
val beginContainer = document.createElement("dt") as HTMLElement
beginContainer.textContent = "{"
dlE.appendChild(beginContainer)
log(obj)
val objEntries = js("Object.entries(obj);") as Array<Array<String>>
log(objEntries)
objEntries.forEachIndexed { index, entry: Array<dynamic> ->
val parentDdE: Promise<HTMLElement> =
process(dlE, entry[0] as String, entry[1], if (objEntries.size == index + 1) "" else ",")
if (entry[1] !== null && jsTypeOf(entry[1]) === "object") {
val subDl = document.createElement("dl") as HTMLDListElement
parentDdE.then { element: HTMLElement ->
element.appendChild(subDl)
traverse(subDl, entry[1], process)
}
}
}
val endContainer = document.createElement("dd") as HTMLElement
endContainer.setAttribute("style", "display: block; text-indent: -3.0em;")
endContainer.textContent = "}"
dlE.appendChild(endContainer)
}
private fun whoisLookup(ipAddress: String = ""): XMLHttpRequest {
val xhr = XMLHttpRequest()
xhr.open("GET", "$apiUrl/whois?clientId=f5c88067-88f8-4a5b-b43e-bf0e10a8b857&queryIP=$ipAddress")
xhr.send()
return xhr
}
@JsName("autoWhoisOnEntry")
internal fun autoWhoisOnEntry() {
whoisLookup().onload = {
val whoisResponse: XMLHttpRequest = it.target as XMLHttpRequest
if (whoisResponse.status.equals(200)) {
showWhois(whoisResponse)
} else {
whoisCustomWithDefaultFallback()
}
}
}
private var ipAddressContainer: HTMLInputElement = document.getElementById("ipAddress") as HTMLInputElement
@JsName("whoisCustomWithDefaultFallback")
internal fun whoisCustomWithDefaultFallback() {
val ipAddress = ipAddressContainer.value
whoisLookup(ipAddress).onload = {
val whoisIpResponse: XMLHttpRequest = it.target as XMLHttpRequest
if (whoisIpResponse.status.equals(200)) {
showWhois(whoisIpResponse)
} else {
whoisDefault()
}
}
}
private fun whoisDefault() {
ipAddressContainer.value = demoIPv6
ipAddressContainer.dispatchEvent(Event("change"))
(document.getElementById("status") as HTMLDivElement).textContent =
"Your IP address was not found. Another, known IP address was used."
}
private fun showWhois(whoisRequest: XMLHttpRequest) {
val whoisInfo = JSON.parse<Json>(whoisRequest.responseText)
clearPreviousWhoisView()
val whoisContainer = document.createElement("dl") as HTMLDListElement
(document.getElementById("whois") as HTMLDivElement).appendChild(whoisContainer)
traverse(whoisContainer, whoisInfo, js("whois.net.loxal.muctool.whois.process"))
}
companion object Whois {
internal const val apiUrl = "https://api.muctool.de"
const val demoIPv6 = "2001:a61:346c:8e00:41ff:1b13:28d4:1"
}
init {
ipAddressContainer.addEventListener("change", {
whoisCustomWithDefaultFallback()
})
autoWhoisOnEntry()
}
} | agpl-3.0 | 76f21fb635c79bb1ff05684b616350cc | 35.579545 | 116 | 0.623116 | 4.390859 | false | false | false | false |
square/leakcanary | shark-hprof/src/main/java/shark/HprofPrimitiveArrayStripper.kt | 2 | 4685 | package shark
import okio.BufferedSink
import okio.Okio
import shark.HprofRecord.HeapDumpEndRecord
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.BooleanArrayDump
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.ByteArrayDump
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.CharArrayDump
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.DoubleArrayDump
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.FloatArrayDump
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.IntArrayDump
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.LongArrayDump
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.ShortArrayDump
import shark.StreamingRecordReaderAdapter.Companion.asStreamingRecordReader
import java.io.File
/**
* Converts a Hprof file to another file with all primitive arrays replaced with arrays of zeroes,
* which can be useful to remove PII. Char arrays are handled slightly differently because 0 would
* be the null character so instead these become arrays of '?'.
*/
class HprofPrimitiveArrayStripper {
/**
* @see HprofPrimitiveArrayStripper
*/
fun stripPrimitiveArrays(
inputHprofFile: File,
/**
* Optional output file. Defaults to a file in the same directory as [inputHprofFile], with
* the same name and "-stripped" prepended before the ".hprof" extension. If the file extension
* is not ".hprof", then "-stripped" is added at the end of the file.
*/
outputHprofFile: File = File(
inputHprofFile.parent, inputHprofFile.name.replace(
".hprof", "-stripped.hprof"
).let { if (it != inputHprofFile.name) it else inputHprofFile.name + "-stripped" })
): File {
stripPrimitiveArrays(
hprofSourceProvider = FileSourceProvider(inputHprofFile),
hprofSink = Okio.buffer(Okio.sink(outputHprofFile.outputStream()))
)
return outputHprofFile
}
/**
* @see HprofPrimitiveArrayStripper
*/
fun stripPrimitiveArrays(
hprofSourceProvider: StreamingSourceProvider,
hprofSink: BufferedSink
) {
val header = hprofSourceProvider.openStreamingSource().use { HprofHeader.parseHeaderOf(it) }
val reader =
StreamingHprofReader.readerFor(hprofSourceProvider, header).asStreamingRecordReader()
HprofWriter.openWriterFor(
hprofSink,
hprofHeader = header
)
.use { writer ->
reader.readRecords(setOf(HprofRecord::class),
OnHprofRecordListener { _,
record ->
// HprofWriter automatically emits HeapDumpEndRecord, because it flushes
// all continuous heap dump sub records as one heap dump record.
if (record is HeapDumpEndRecord) {
return@OnHprofRecordListener
}
writer.write(
when (record) {
is BooleanArrayDump -> BooleanArrayDump(
record.id, record.stackTraceSerialNumber,
BooleanArray(record.array.size)
)
is CharArrayDump -> CharArrayDump(
record.id, record.stackTraceSerialNumber,
CharArray(record.array.size) {
'?'
}
)
is FloatArrayDump -> FloatArrayDump(
record.id, record.stackTraceSerialNumber,
FloatArray(record.array.size)
)
is DoubleArrayDump -> DoubleArrayDump(
record.id, record.stackTraceSerialNumber,
DoubleArray(record.array.size)
)
is ByteArrayDump -> ByteArrayDump(
record.id, record.stackTraceSerialNumber,
ByteArray(record.array.size) {
// Converts to '?' in UTF-8 for byte backed strings
63
}
)
is ShortArrayDump -> ShortArrayDump(
record.id, record.stackTraceSerialNumber,
ShortArray(record.array.size)
)
is IntArrayDump -> IntArrayDump(
record.id, record.stackTraceSerialNumber,
IntArray(record.array.size)
)
is LongArrayDump -> LongArrayDump(
record.id, record.stackTraceSerialNumber,
LongArray(record.array.size)
)
else -> {
record
}
}
)
})
}
}
}
| apache-2.0 | 9f84561203b525b41fac0b44ca4c7c85 | 39.387931 | 99 | 0.642049 | 5.590692 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2021/Day15.kt | 1 | 2827 | package com.s13g.aoc.aoc2021
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 15: Chiton ---
* https://adventofcode.com/2021/day/15
*/
class Day15 : Solver {
override fun solve(lines: List<String>): Result {
val width = lines[0].length
val height = lines.size
val data = IntArray(lines.size * lines[0].length)
for (y in lines.indices) {
for (x in lines[y].indices) {
data[width * y + x] = lines[y][x].toString().toInt()
}
}
val partA = Board(data, width, height).calc()
val partB = Board(expandForPartB(data, width, height), width * 5, height * 5).calc()
return Result("$partA", "$partB")
}
private fun expandForPartB(data: IntArray, width: Int, height: Int): IntArray {
val newData = IntArray(width * height * 5 * 5)
var idx = 0
for (y in 0 until height) {
for (i in 0..4) {
for (x in 0 until width) newData[idx++] = roundIt(data[y * width + x] + i)
}
}
val newWidth = width * 5
for (i in 1..4) {
for (y in 0 until height) {
for (x in 0 until newWidth) newData[idx++] = roundIt(newData[y * newWidth + x] + i)
}
}
return newData
}
private fun roundIt(num: Int) = if (num >= 10) num - 9 else num
private class Board(val data: IntArray, val width: Int, val height: Int) {
// Index (width/height) and cheapest cost.
val visited = mutableMapOf<Int, Int>()
var activeRoutes = mutableSetOf<Route>()
val goal = idxAt(width - 1, height - 1)
fun calc(): Int {
activeRoutes.add(Route(0, 0))
visited[0] = 0
while (activeRoutes.count { it.lastIdx != goal } > 0) {
for (route in activeRoutes.toList()) {
if (route.lastIdx == goal) continue
activeRoutes.remove(route)
if (costAt(route.lastIdx) < route.cost) continue
val end = route.lastIdx
val options = findNextOptions(end)
for (opt in options) {
val totalCost = data[opt] + route.cost
if (costAt(opt) > totalCost) {
activeRoutes.add(Route(opt, totalCost))
visited[opt] = totalCost
}
}
}
}
return activeRoutes.sortedBy { it.cost }.first().cost
}
fun costAt(pos: Int) = if (visited.containsKey(pos)) visited[pos]!! else Int.MAX_VALUE
fun idxAt(x: Int, y: Int) = y * width + x
fun findNextOptions(pos: Int): Set<Int> {
val x = pos % width
val y = pos / width
val result = mutableSetOf<Int>()
if (x > 0) result.add(idxAt(x - 1, y))
if (x < width - 1) result.add(idxAt(x + 1, y))
if (y > 0) result.add(idxAt(x, y - 1))
if (y < height - 1) result.add(idxAt(x, y + 1))
return result
}
}
private data class Route(val lastIdx: Int, val cost: Int);
} | apache-2.0 | 77b271b84e06e0fb095842103d0ba0aa | 28.154639 | 91 | 0.571984 | 3.426667 | false | false | false | false |
Shashi-Bhushan/General | cp-trials/src/main/kotlin/in/shabhushan/cp_trials/dsbook/methods/decrease-and-conquer/celebrityProblem.kt | 1 | 788 | package `in`.shabhushan.cp_trials.dsbook.methods.`decrease-and-conquer`
import java.util.Stack
fun isCelebrity(
matrix: Array<Array<Int>>
): Int {
val stack = Stack<Int>()
matrix.indices.forEach { index ->
stack.push(index)
}
while (stack.size != 1) {
val a = stack.pop()
val b = stack.pop()
// if A knows B, A is not the celebrity
if (matrix[a][b] == 1) {
stack.push(b)
} else {
stack.push(a)
}
}
// Only one left at this point
val celebrity = stack.pop()
matrix.indices.forEach { personIndex ->
// if celebrity knows the person or person doesn't know celebrity
if (personIndex != celebrity && (matrix[celebrity][personIndex] == 1 || matrix[personIndex][celebrity] == 0))
return -1
}
return celebrity
}
| gpl-2.0 | 18e74a349f581d430364d2fc2481c1a7 | 20.888889 | 113 | 0.624365 | 3.45614 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/objects/Box.kt | 1 | 1078 | package net.dinkla.raytracer.objects
import net.dinkla.raytracer.math.*
import net.dinkla.raytracer.objects.compound.Compound
class Box(var p0: Point3D, a: Vector3D, b: Vector3D, c: Vector3D) : Compound() {
// private var p1: Point3D
// private get
// val boundingBox by lazy {
//
// }
init {
// point at the "top left front"
//Rectangle rBottom = new Rectangle(p0, b, a);
val rBottom = Rectangle(p0, a, b, true)
val rTop = Rectangle(p0.plus(c), a, b)
val rFront = Rectangle(p0, a, c)
// Rectangle rBehind = new Rectangle(p0.plus(b), c, a);
val rBehind = Rectangle(p0.plus(b), a, c, true)
// Rectangle rLeft = new Rectangle(p0, c, b);
val rLeft = Rectangle(p0, b, c, true)
val rRight = Rectangle(p0.plus(a), b, c)
objects.add(rBottom)
objects.add(rTop)
objects.add(rBehind)
objects.add(rLeft)
objects.add(rRight)
objects.add(rFront)
val p1 = p0 + a + b + c
boundingBox = BBox(p0, p1)
}
}
| apache-2.0 | 9522137192ecb4688edd33945baa8344 | 27.368421 | 80 | 0.573284 | 3.115607 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/NotificationManager.kt | 1 | 2644 | package app.lawnchair
import android.content.Context
import android.content.pm.PackageManager
import android.service.notification.StatusBarNotification
import app.lawnchair.util.checkPackagePermission
import com.android.launcher3.notification.NotificationListener
import com.android.launcher3.util.MainThreadInitializedObject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class NotificationManager(@Suppress("UNUSED_PARAMETER") context: Context) {
private val scope = MainScope()
private val notificationsMap = mutableMapOf<String, StatusBarNotification>()
private val _notifications = MutableStateFlow(emptyList<StatusBarNotification>())
val notifications: Flow<List<StatusBarNotification>> get() = _notifications
fun onNotificationPosted(sbn: StatusBarNotification) {
notificationsMap[sbn.key] = sbn
onChange()
}
fun onNotificationRemoved(sbn: StatusBarNotification) {
notificationsMap.remove(sbn.key)
onChange()
}
fun onNotificationFullRefresh() {
scope.launch(Dispatchers.IO) {
val tmpMap = NotificationListener.getInstanceIfConnected()
?.activeNotifications?.associateBy { it.key }
withContext(Dispatchers.Main) {
notificationsMap.clear()
if (tmpMap != null) {
notificationsMap.putAll(tmpMap)
}
onChange()
}
}
}
private fun onChange() {
_notifications.value = notificationsMap.values.toList()
}
companion object {
@JvmField val INSTANCE = MainThreadInitializedObject(::NotificationManager)
}
}
private const val PERM_SUBSTITUTE_APP_NAME = "android.permission.SUBSTITUTE_NOTIFICATION_APP_NAME"
private const val EXTRA_SUBSTITUTE_APP_NAME = "android.substName"
fun StatusBarNotification.getAppName(context: Context): CharSequence {
val subName = notification.extras.getString(EXTRA_SUBSTITUTE_APP_NAME)
if (subName != null) {
if (context.checkPackagePermission(packageName, PERM_SUBSTITUTE_APP_NAME)) {
return subName
}
}
return context.getAppName(packageName)
}
fun Context.getAppName(name: String): CharSequence {
try {
return packageManager.getApplicationLabel(
packageManager.getApplicationInfo(name, PackageManager.GET_META_DATA))
} catch (ignored: PackageManager.NameNotFoundException) {
}
return name
}
| gpl-3.0 | ddb95aec7b5884ccaabef30be2cfd2f8 | 33.337662 | 98 | 0.716717 | 5.084615 | false | false | false | false |
yshrsmz/monotweety | app/src/main/java/net/yslibrary/monotweety/appdata/user/local/UserTable.kt | 1 | 1593 | package net.yslibrary.monotweety.appdata.user.local
import com.pushtorefresh.storio3.sqlite.queries.DeleteQuery
import com.pushtorefresh.storio3.sqlite.queries.InsertQuery
import com.pushtorefresh.storio3.sqlite.queries.Query
import com.pushtorefresh.storio3.sqlite.queries.UpdateQuery
class UserTable {
companion object {
const val TABLE = "user"
const val COLUMN_ID = "id"
const val COLUMN_NAME = "name"
const val COLUMN_SCREEN_NAME = "screen_name"
const val COLUMN_PROFILE_IMAGE_URL = "profile_image_url"
const val COLUMN__UPDATED_AT = "_updated_at"
const val CREATE_TABLE =
"CREATE TABLE $TABLE(" +
"$COLUMN_ID INTEGER NOT NULL PRIMARY KEY, " +
"$COLUMN_NAME TEXT NOT NULL, " +
"$COLUMN_SCREEN_NAME TEXT NOT NULL, " +
"$COLUMN_PROFILE_IMAGE_URL TEXT NOT NULL, " +
"$COLUMN__UPDATED_AT INTEGER NOT NULL" +
");"
fun queryById(id: Long) = Query.builder()
.table(TABLE)
.where("$COLUMN_ID = ?")
.whereArgs(id)
.build()
fun deleteById(id: Long) = DeleteQuery.builder()
.table(TABLE)
.where("$COLUMN_ID = ?")
.whereArgs(id)
.build()
fun insertQuery() = InsertQuery.builder()
.table(TABLE)
.build()
fun updateById(id: Long) = UpdateQuery.builder()
.table(TABLE)
.where("$COLUMN_ID = ?")
.whereArgs(id)
.build()
}
}
| apache-2.0 | 95abe7dd79c7e21bf0fce4b53285cd98 | 30.86 | 64 | 0.559322 | 4.214286 | false | false | false | false |
bachhuberdesign/deck-builder-gwent | app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/stattrack/Match.kt | 1 | 2930 | package com.bachhuberdesign.deckbuildergwent.features.stattrack
import android.database.Cursor
import com.bachhuberdesign.deckbuildergwent.util.getIntFromColumn
import com.bachhuberdesign.deckbuildergwent.util.getLongFromColumn
import com.bachhuberdesign.deckbuildergwent.util.getStringFromColumn
import io.reactivex.functions.Function
import rx.functions.Func1
import java.util.*
/**
* @author Eric Bachhuber
* @version 1.0.0
* @since 1.0.0
*/
data class Match(var id: Int = 0,
var deckId: Int = 0,
var outcome: Int = 0,
var opponentFaction: Int = 0,
var opponentLeader: Int = 0,
var notes: String = "",
var playedDate: Date = Date(),
var createdDate: Date = Date(),
var lastUpdate: Date = Date()) {
companion object {
@JvmStatic val TAG: String = Match::class.java.name
const val TABLE = "matches"
const val ID = "_id"
const val DECK_ID = "deck_id"
const val OUTCOME = "outcome"
const val OPPONENT_FACTION = "opponent_faction"
const val OPPONENT_LEADER = "opponent_leader"
const val NOTES = "notes"
const val PLAYED_DATE = "played_date"
const val CREATED_DATE = "created_date"
const val LAST_UPDATE = "last_update"
val MAPPER = Function<Cursor, Match> { cursor ->
val match = Match()
match.id = cursor.getIntFromColumn(Match.ID)
match.deckId = cursor.getIntFromColumn(Match.DECK_ID)
match.outcome = cursor.getIntFromColumn(Match.OUTCOME)
match.opponentFaction = cursor.getIntFromColumn(Match.OPPONENT_FACTION)
match.opponentLeader = cursor.getIntFromColumn(Match.OPPONENT_LEADER)
match.notes = cursor.getStringFromColumn(Match.NOTES)
match.playedDate = Date(cursor.getLongFromColumn(Match.PLAYED_DATE))
match.createdDate = Date(cursor.getLongFromColumn(Match.CREATED_DATE))
match.lastUpdate = Date(cursor.getLongFromColumn(Match.LAST_UPDATE))
match
}
val MAP1 = Func1<Cursor, Match> { cursor ->
val match = Match()
match.id = cursor.getIntFromColumn(Match.ID)
match.deckId = cursor.getIntFromColumn(Match.DECK_ID)
match.outcome = cursor.getIntFromColumn(Match.OUTCOME)
match.opponentFaction = cursor.getIntFromColumn(Match.OPPONENT_FACTION)
match.opponentLeader = cursor.getIntFromColumn(Match.OPPONENT_LEADER)
match.notes = cursor.getStringFromColumn(Match.NOTES)
match.playedDate = Date(cursor.getLongFromColumn(Match.PLAYED_DATE))
match.createdDate = Date(cursor.getLongFromColumn(Match.CREATED_DATE))
match.lastUpdate = Date(cursor.getLongFromColumn(Match.LAST_UPDATE))
match
}
}
} | apache-2.0 | 3217b4cb1b4df559fd7ae22d262bb5f3 | 39.150685 | 83 | 0.643003 | 4.592476 | false | false | false | false |
hidroh/materialistic | app/src/main/java/io/github/hidroh/materialistic/data/android/Cache.kt | 1 | 1987 | /*
* Copyright (c) 2018 Ha Duy Trung
*
* 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 io.github.hidroh.materialistic.data.android
import io.github.hidroh.materialistic.DataModule
import io.github.hidroh.materialistic.data.LocalCache
import io.github.hidroh.materialistic.data.MaterialisticDatabase
import rx.Observable
import rx.Scheduler
import javax.inject.Inject
import javax.inject.Named
class Cache @Inject constructor(
private val database: MaterialisticDatabase,
private val savedStoriesDao: MaterialisticDatabase.SavedStoriesDao,
private val readStoriesDao: MaterialisticDatabase.ReadStoriesDao,
private val readableDao: MaterialisticDatabase.ReadableDao,
@Named(DataModule.MAIN_THREAD) private val mainScheduler: Scheduler) : LocalCache {
override fun getReadability(itemId: String?) = readableDao.selectByItemId(itemId)?.content
override fun putReadability(itemId: String?, content: String?) {
readableDao.insert(MaterialisticDatabase.Readable(itemId, content))
}
override fun isViewed(itemId: String?) = readStoriesDao.selectByItemId(itemId) != null
override fun setViewed(itemId: String?) {
readStoriesDao.insert(MaterialisticDatabase.ReadStory(itemId))
Observable.just(itemId)
.map { database.createReadUri(it) }
.observeOn(mainScheduler)
.subscribe { database.setLiveValue(it) }
}
override fun isFavorite(itemId: String?) = savedStoriesDao.selectByItemId(itemId) != null
}
| apache-2.0 | 08c009d4bc2ab7f0255e618cd651175b | 37.960784 | 92 | 0.770508 | 4.218684 | false | false | false | false |
ntemplon/legends-of-omterra | core/src/com/jupiter/europa/screen/OverlayableScreen.kt | 1 | 5147 | /*
* The MIT License
*
* Copyright 2015 Nathan Templon.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.jupiter.europa.screen
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.InputMultiplexer
import com.badlogic.gdx.InputProcessor
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.Camera
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.utils.Disposable
import com.jupiter.europa.screen.overlay.Overlay
import com.jupiter.ganymede.event.Listener
import com.jupiter.ganymede.property.Property
import java.util.LinkedHashSet
/**
* @author Nathan Templon
*/
public abstract class OverlayableScreen : Screen, InputProcessor {
// Fields
public val overlayCamera: Camera
private val overlays = LinkedHashSet<Overlay>()
public val multiplexer: InputMultiplexer = InputMultiplexer()
public val overlayBatch: Batch = SpriteBatch()
private val tint = Property(Color.WHITE)
public fun getOverlays(): Set<Overlay> {
return this.overlays
}
public fun getTint(): Color {
return this.tint.get() ?: Color.WHITE
}
public fun setTint(tint: Color) {
this.tint.set(tint)
}
init {
this.overlayCamera = OrthographicCamera(Gdx.graphics.getWidth().toFloat(), Gdx.graphics.getHeight().toFloat())
}
// Public Methods
override fun show() {
}
override fun hide() {
}
override fun dispose() {
for (overlay in this.overlays) {
if (overlay is Disposable) {
overlay.dispose()
}
}
}
override fun resize(width: Int, height: Int) {
this.overlayCamera.viewportWidth = width.toFloat()
this.overlayCamera.viewportHeight = height.toFloat()
this.overlayCamera.update()
}
public fun renderOverlays() {
this.overlayCamera.update()
this.overlayBatch.setProjectionMatrix(this.overlayCamera.combined)
this.overlayBatch.begin()
for (overlay in this.overlays) {
overlay.render()
}
this.overlayBatch.end()
}
public fun addOverlay(overlay: Overlay) {
this.overlays.add(overlay)
this.multiplexer.addProcessor(0, overlay)
overlay.added(this)
}
public fun removeOverlay(overlay: Overlay): Boolean {
val wasPresent = this.overlays.remove(overlay)
if (wasPresent) {
this.multiplexer.removeProcessor(overlay)
overlay.removed()
}
return wasPresent
}
public fun addTintChangedListener(listener: Listener<Property.PropertyChangedArgs<Color>>): Boolean {
return this.tint.addPropertyChangedListener(listener)
}
public fun addTintChangedListener(listener: (Property.PropertyChangedArgs<Color>) -> Unit): Boolean = this.tint.addPropertyChangedListener(listener)
public fun removeTintChangedListener(listener: Listener<Property.PropertyChangedArgs<Color>>): Boolean {
return this.tint.removePropertyChangedListener(listener)
}
// InputProcessor Implementation
override fun keyDown(i: Int): Boolean {
return this.multiplexer.keyDown(i)
}
override fun keyUp(i: Int): Boolean {
return this.multiplexer.keyUp(i)
}
override fun keyTyped(c: Char): Boolean {
return this.multiplexer.keyTyped(c)
}
override fun touchDown(i: Int, i1: Int, i2: Int, i3: Int): Boolean {
return this.multiplexer.touchDown(i, i1, i2, i3)
}
override fun touchUp(i: Int, i1: Int, i2: Int, i3: Int): Boolean {
return this.multiplexer.touchUp(i, i1, i2, i3)
}
override fun touchDragged(i: Int, i1: Int, i2: Int): Boolean {
return this.multiplexer.touchDragged(i, i1, i2)
}
override fun mouseMoved(i: Int, i1: Int): Boolean {
return this.multiplexer.mouseMoved(i, i1)
}
override fun scrolled(i: Int): Boolean {
return this.multiplexer.scrolled(i)
}
}
| mit | 11e2130abfec22e810975f44852afd2f | 30.006024 | 152 | 0.693025 | 4.264292 | false | false | false | false |
GlimpseFramework/glimpse-framework | api/src/test/kotlin/glimpse/models/ModelTransformationSpec.kt | 1 | 2426 | package glimpse.models
import glimpse.Angle
import glimpse.Vector
import glimpse.test.GlimpseSpec
import glimpse.translationMatrix
class ModelTransformationSpec : GlimpseSpec() {
init {
"Model translation" should {
"give results consistent with sum of vectors" {
forAll(vectors, vectors) { vector, translation ->
Model(mesh { }).transform {
translate(translation)
}.transformation() * vector isRoughly vector + translation
}
forAll(vectors, vectors) { vector, translation ->
Model(mesh { }).transform(translationMatrix(translation)).transformation() * vector isRoughly vector + translation
}
}
"change over time" {
var translation = Vector.X_UNIT
val model = Model(mesh { }).transform {
translate(translation)
}
model.transformation() * Vector.NULL shouldBeRoughly Vector.X_UNIT
translation = Vector.Z_UNIT
model.transformation() * Vector.NULL shouldBeRoughly Vector.Z_UNIT
}
"keep mesh transformation changes over time" {
var translation = Vector.X_UNIT
val model = mesh {
}.transform {
translate(translation)
}.transform {
translate(Vector.Y_UNIT)
}
model.transformation() * Vector.NULL shouldBeRoughly Vector(1f, 1f, 0f)
translation = Vector.Z_UNIT
model.transformation() * Vector.NULL shouldBeRoughly Vector(0f, 1f, 1f)
}
}
"Composition of a translation and a rotation" should {
"first translate and then rotate" {
Model(mesh { }).transform {
translate(Vector.X_UNIT)
rotateZ(Angle.RIGHT)
}.transformation() * Vector.X_UNIT shouldBeRoughly Vector.Y_UNIT * 2f
}
}
"Composition of a rotation and a translation" should {
"first rotate and then translate" {
Model(mesh { }).transform {
rotateZ(Angle.RIGHT)
translate(Vector.X_UNIT)
}.transformation() * Vector.X_UNIT shouldBeRoughly Vector.Y_UNIT + Vector.X_UNIT
}
}
"Composition of a translation and a scaling" should {
"first translate and then scale" {
Model(mesh { }).transform {
translate(Vector.X_UNIT)
scale(2f)
}.transformation() * Vector.X_UNIT shouldBeRoughly Vector.X_UNIT * 4f
}
}
"Composition of a scaling and a translation" should {
"first scale and then translate" {
Model(mesh { }).transform {
scale(2f)
translate(Vector.X_UNIT)
}.transformation() * Vector.X_UNIT shouldBeRoughly Vector.X_UNIT * 3f
}
}
}
}
| apache-2.0 | a35c4bdb9df39af35460dd6cd958f2e3 | 28.228916 | 119 | 0.678895 | 3.675758 | false | false | false | false |
microg/android_packages_apps_GmsCore | play-services-core/src/main/kotlin/org/microg/gms/chimera/ServiceProvider.kt | 1 | 3020 | /*
* SPDX-FileCopyrightText: 2020, microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package org.microg.gms.chimera
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.database.MatrixCursor
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.core.os.bundleOf
import org.microg.gms.DummyService
import org.microg.gms.common.GmsService
import org.microg.gms.common.RemoteListenerProxy
class ServiceProvider : ContentProvider() {
override fun onCreate(): Boolean {
Log.d(TAG, "onCreate")
return true
}
override fun call(method: String, arg: String?, extras: Bundle?): Bundle? {
when (method) {
"serviceIntentCall" -> {
val serviceAction = extras?.getString("serviceActionBundleKey") ?: return null
val ourServiceAction = GmsService.byAction(serviceAction)?.takeIf { it.SERVICE_ID > 0 }?.ACTION
val context = context!!
val intent = Intent(ourServiceAction).apply { `package` = context.packageName }
val resolveInfo = context.packageManager.resolveService(intent, 0)
if (resolveInfo != null) {
intent.setClassName(resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name)
} else {
intent.setClass(context, DummyService::class.java)
}
Log.d(TAG, "$method: $serviceAction -> $intent")
return bundleOf(
"serviceResponseIntentKey" to intent
)
}
else -> {
Log.d(TAG, "$method: $arg, $extras")
return super.call(method, arg, extras)
}
}
}
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
val cursor = MatrixCursor(COLUMNS)
Log.d(TAG, "query: $uri")
return cursor
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
Log.d(TAG, "insert: $uri, $values")
return uri
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {
Log.d(TAG, "update: $uri, $values, $selection, $selectionArgs")
return 0
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
Log.d(TAG, "delete: $uri, $selection, $selectionArgs")
return 0
}
override fun getType(uri: Uri): String {
Log.d(TAG, "getType: $uri")
return "vnd.android.cursor.item/com.google.android.gms.chimera"
}
companion object {
private const val TAG = "ChimeraServiceProvider"
private val COLUMNS = arrayOf("version", "apkPath", "loaderPath", "apkDescStr")
}
}
| apache-2.0 | 34e2ba37837a20f467277964c0cf8c70 | 34.952381 | 150 | 0.625166 | 4.357864 | false | false | false | false |
xiaopansky/Sketch | sample/src/main/java/me/panpf/sketch/sample/util/AnimationUtils.kt | 1 | 6555 | package me.panpf.sketch.sample.util
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
object AnimationUtils {
/**
* 将给定视图渐渐显示出来(view.setVisibility(View.VISIBLE))
* @param view 被处理的视图
* *
* @param durationMillis 持续时间,毫秒
* *
* @param isBanClick 在执行动画的过程中是否禁止点击
* *
* @param animationListener 动画监听器
*/
@JvmStatic @JvmOverloads fun visibleViewByAlpha(view: View, durationMillis: Long = 400, isBanClick: Boolean = true, animationListener: Animation.AnimationListener? = null) {
if (view.visibility != View.VISIBLE) {
view.visibility = View.VISIBLE
val showAlphaAnimation = getShowAlphaAnimation(durationMillis)
showAlphaAnimation.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
if (isBanClick) {
view.isClickable = false
}
animationListener?.onAnimationStart(animation)
}
override fun onAnimationRepeat(animation: Animation) {
animationListener?.onAnimationRepeat(animation)
}
override fun onAnimationEnd(animation: Animation) {
if (isBanClick) {
view.isClickable = true
}
animationListener?.onAnimationEnd(animation)
}
})
view.startAnimation(showAlphaAnimation)
}
}
/**
* 将给定视图渐渐隐去最后从界面中移除(view.setVisibility(View.GONE))
* @param view 被处理的视图
* *
* @param durationMillis 持续时间,毫秒
* *
* @param isBanClick 在执行动画的过程中是否禁止点击
* *
* @param animationListener 动画监听器
*/
@JvmStatic @JvmOverloads fun goneViewByAlpha(view: View, durationMillis: Long = 400, isBanClick: Boolean = true, animationListener: Animation.AnimationListener? = null) {
if (view.visibility != View.GONE) {
val hiddenAlphaAnimation = getHiddenAlphaAnimation(durationMillis)
hiddenAlphaAnimation.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
if (isBanClick) {
view.isClickable = false
}
animationListener?.onAnimationStart(animation)
}
override fun onAnimationRepeat(animation: Animation) {
animationListener?.onAnimationRepeat(animation)
}
override fun onAnimationEnd(animation: Animation) {
if (isBanClick) {
view.isClickable = true
}
view.visibility = View.GONE
animationListener?.onAnimationEnd(animation)
}
})
view.startAnimation(hiddenAlphaAnimation)
}
}
/**
* 将给定视图渐渐隐去最后从界面中移除(view.setVisibility(View.GONE))
* @param view 被处理的视图
* *
* @param durationMillis 持续时间,毫秒
* *
* @param isBanClick 在执行动画的过程中是否禁止点击
* *
* @param animationListener 动画监听器
*/
@JvmStatic @JvmOverloads fun invisibleViewByAlpha(view: View, durationMillis: Long = 400, isBanClick: Boolean = true, animationListener: Animation.AnimationListener? = null) {
if (view.visibility != View.INVISIBLE) {
val hiddenAlphaAnimation = getHiddenAlphaAnimation(durationMillis)
hiddenAlphaAnimation.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
if (isBanClick) {
view.isClickable = false
}
animationListener?.onAnimationStart(animation)
}
override fun onAnimationRepeat(animation: Animation) {
animationListener?.onAnimationRepeat(animation)
}
override fun onAnimationEnd(animation: Animation) {
if (isBanClick) {
view.isClickable = true
}
view.visibility = View.INVISIBLE
animationListener?.onAnimationEnd(animation)
}
})
view.startAnimation(hiddenAlphaAnimation)
}
}
/**
* 获取一个由完全显示变为不可见的透明度渐变动画
* @param durationMillis 持续时间
* *
* @param animationListener 动画监听器
* *
* @return 一个由完全显示变为不可见的透明度渐变动画
*/
@JvmStatic @JvmOverloads fun getHiddenAlphaAnimation(durationMillis: Long, animationListener: Animation.AnimationListener? = null): AlphaAnimation {
return getAlphaAnimation(1.0f, 0.0f, durationMillis, animationListener)
}
/**
* 获取一个透明度渐变动画
* @param fromAlpha 开始时的透明度
* *
* @param toAlpha 结束时的透明度都
* *
* @param durationMillis 持续时间
* *
* @param animationListener 动画监听器
* *
* @return 一个透明度渐变动画
*/
@JvmStatic fun getAlphaAnimation(fromAlpha: Float, toAlpha: Float, durationMillis: Long, animationListener: Animation.AnimationListener?): AlphaAnimation {
val alphaAnimation = AlphaAnimation(fromAlpha, toAlpha)
alphaAnimation.duration = durationMillis
if (animationListener != null) {
alphaAnimation.setAnimationListener(animationListener)
}
return alphaAnimation
}
/**
* 获取一个由不可见变为完全显示的透明度渐变动画
* @param durationMillis 持续时间
* *
* @return 一个由不可见变为完全显示的透明度渐变动画
*/
@JvmStatic fun getShowAlphaAnimation(durationMillis: Long): AlphaAnimation {
return getAlphaAnimation(0.0f, 1.0f, durationMillis, null)
}
}
| apache-2.0 | 9ac143c4e88734f75361dc5b502b5483 | 34.553571 | 179 | 0.584129 | 5.415231 | false | false | false | false |
alashow/music-android | modules/navigation/src/main/java/tm/alashow/navigation/Navigator.kt | 1 | 1234 | /*
* Copyright (C) 2021, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.navigation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.hilt.navigation.compose.hiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
val LocalNavigator = staticCompositionLocalOf<Navigator> {
error("No LocalNavigator given")
}
@Composable
fun NavigatorHost(
viewModel: NavigatorViewModel = hiltViewModel(),
content: @Composable () -> Unit
) {
CompositionLocalProvider(LocalNavigator provides viewModel.navigator, content = content)
}
sealed class NavigationEvent(open val route: String) {
object Back : NavigationEvent("Back")
data class Destination(override val route: String) : NavigationEvent(route)
}
class Navigator {
private val navigationQueue = Channel<NavigationEvent>(Channel.CONFLATED)
fun navigate(route: String) {
navigationQueue.trySend(NavigationEvent.Destination(route))
}
fun back() {
navigationQueue.trySend(NavigationEvent.Back)
}
val queue = navigationQueue.receiveAsFlow()
}
| apache-2.0 | 0210547fcd3e903779e3eebed50f6e27 | 27.697674 | 92 | 0.770665 | 4.656604 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/utils/ExtendedFragmentFactory.kt | 1 | 3017 | /*
Copyright (c) 2021 Tarek Mohamed Abdalla <[email protected]>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.utils
import androidx.annotation.CallSuper
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentFactory
import androidx.fragment.app.FragmentManager
/**
* A factory that enable extending another [FragmentFactory].
*
* This should be useful if you want to add extra instantiations without overriding the instantiations in an old factory
*/
abstract class ExtendedFragmentFactory : FragmentFactory {
private var mBaseFactory: FragmentFactory? = null
/**
* Create an extended factory from a base factory
*/
constructor(baseFactory: FragmentFactory) {
mBaseFactory = baseFactory
}
/**
* Create a factory with no base, you can assign a base factory later using [.setBaseFactory]
*/
constructor() {}
/**
* Typically you want to return the result of a super call as the last result, so if the passed class couldn't be
* instantiated by the extending factory, the base factory should instantiate it.
*/
@CallSuper
override fun instantiate(classLoader: ClassLoader, className: String): Fragment {
return mBaseFactory?.instantiate(classLoader, className)
?: super.instantiate(classLoader, className)
}
/**
* Sets a base factory to be used as a fallback
*/
fun setBaseFactory(baseFactory: FragmentFactory?) {
mBaseFactory = baseFactory
}
/**
* Attaches the factory to an activity by setting the current activity fragment factory as the base factory
* and updating the activity with the extended factory
*/
inline fun <reified F : ExtendedFragmentFactory?> attachToActivity(activity: AppCompatActivity): F {
return attachToFragmentManager<ExtendedFragmentFactory>(activity.supportFragmentManager) as F
}
/**
* Attaches the factory to a fragment manager by setting the current fragment factory as the base factory
* and updating the fragment manager with the extended factory
*/
fun <F : ExtendedFragmentFactory?> attachToFragmentManager(fragmentManager: FragmentManager): F {
mBaseFactory = fragmentManager.fragmentFactory
fragmentManager.fragmentFactory = this
@Suppress("UNCHECKED_CAST")
return this as F
}
}
| gpl-3.0 | a6ac672b994d047888d679a7563c76db | 37.189873 | 120 | 0.731853 | 5.070588 | false | false | false | false |
JetBrains/anko | anko/library/static/commons/src/main/java/SharedPreferences.kt | 2 | 1486 |
/*
* 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.
*/
package org.jetbrains.anko
import android.content.SharedPreferences
/**
* Opens the [SharedPreferences.Editor], applies the [modifer] to it and then applies the changes asynchronously
*/
@Deprecated(message = "Use the Android KTX version", replaceWith = ReplaceWith("edit(modifier)", "androidx.core.content.edit"))
inline fun SharedPreferences.apply(modifier: SharedPreferences.Editor.() -> Unit) {
val editor = this.edit()
editor.modifier()
editor.apply()
}
/**
* Opens the [SharedPreferences.Editor], applies the [modifer] to it and then applies the changes synchronously
*/
@Deprecated(message = "Use the Android KTX version", replaceWith = ReplaceWith("edit(true, modifier)", "androidx.core.content.edit"))
inline fun SharedPreferences.commit(modifier: SharedPreferences.Editor.() -> Unit) {
val editor = this.edit()
editor.modifier()
editor.commit()
}
| apache-2.0 | c52a557a6c78761265fa00b9c9a8c506 | 36.15 | 133 | 0.73755 | 4.174157 | false | false | false | false |
ebraminio/DroidPersianCalendar | PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/preferences/interfacecalendar/InterfaceCalendarFragment.kt | 1 | 2064 | package com.byagowi.persiancalendar.ui.preferences.interfacecalendar
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import com.byagowi.persiancalendar.R
import com.byagowi.persiancalendar.ui.preferences.interfacecalendar.calendarsorder.CalendarPreferenceDialog
import com.byagowi.persiancalendar.utils.askForCalendarPermission
class InterfaceCalendarFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.preferences_interface_calendar)
findPreference<ListPreference>("Theme")?.summaryProvider =
ListPreference.SimpleSummaryProvider.getInstance()
findPreference<ListPreference>("WeekStart")?.summaryProvider =
ListPreference.SimpleSummaryProvider.getInstance()
val switchPreference = findPreference<SwitchPreferenceCompat>("showDeviceCalendarEvents")
val activity = activity ?: return
switchPreference?.setOnPreferenceChangeListener { _, _ ->
if (ActivityCompat.checkSelfPermission(
activity, Manifest.permission.READ_CALENDAR
) != PackageManager.PERMISSION_GRANTED
) {
askForCalendarPermission(activity)
switchPreference.isChecked = false
} else {
switchPreference.isChecked = !switchPreference.isChecked
}
false
}
}
override fun onPreferenceTreeClick(preference: Preference?): Boolean =
if (preference?.key == "calendars_priority") {
parentFragmentManager.apply {
CalendarPreferenceDialog().show(this, "CalendarPreferenceDialog")
}
true
} else super.onPreferenceTreeClick(preference)
}
| gpl-3.0 | 952acef692fa1c758cff4e9556c81fdd | 41.122449 | 107 | 0.723837 | 6.142857 | false | false | false | false |
openMF/self-service-app | app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingsWithAssociations.kt | 1 | 2864 | package org.mifos.mobile.models.accounts.savings
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
import org.mifos.mobile.models.client.DepositType
import java.util.ArrayList
/**
* @author Vishwajeet
* @since 22/06/16
*/
@Parcelize
data class SavingsWithAssociations(
@SerializedName("id")
var id: Long? = null,
@SerializedName("accountNo")
var accountNo: String,
@SerializedName("depositType")
var depositType: DepositType? = null,
@SerializedName("externalId")
var externalId: String,
@SerializedName("clientId")
var clientId: Int? = null,
@SerializedName("clientName")
var clientName: String,
@SerializedName("savingsProductId")
var savingsProductId: Int? = null,
@SerializedName("savingsProductName")
var savingsProductName: String,
@SerializedName("fieldOfficerId")
var fieldOfficerId: Int? = null,
@SerializedName("status")
var status: Status,
@SerializedName("timeline")
var timeline: TimeLine,
@SerializedName("currency")
var currency: Currency,
@SerializedName("nominalAnnualInterestRate")
internal var nominalAnnualInterestRate: Double? = null,
@SerializedName("minRequiredOpeningBalance")
var minRequiredOpeningBalance: Double? = null,
@SerializedName("lockinPeriodFrequency")
var lockinPeriodFrequency: Double? = null,
@SerializedName("withdrawalFeeForTransfers")
var withdrawalFeeForTransfers: Boolean? = null,
@SerializedName("allowOverdraft")
var allowOverdraft: Boolean? = null,
@SerializedName("enforceMinRequiredBalance")
var enforceMinRequiredBalance: Boolean? = null,
@SerializedName("withHoldTax")
var withHoldTax: Boolean? = null,
@SerializedName("lastActiveTransactionDate")
var lastActiveTransactionDate: List<Int>,
@SerializedName("isDormancyTrackingActive")
var dormancyTrackingActive: Boolean? = null,
@SerializedName("summary")
var summary: Summary,
@SerializedName("transactions")
var transactions: List<Transactions> = ArrayList()
) : Parcelable {
fun isRecurring() : Boolean {
return this.depositType != null && this.depositType!!.isRecurring()
}
fun setNominalAnnualInterestRate(nominalAnnualInterestRate: Double?) {
this.nominalAnnualInterestRate = nominalAnnualInterestRate
}
fun getNominalAnnualInterestRate(): Double {
return nominalAnnualInterestRate!!
}
fun setNominalAnnualInterestRate(nominalAnnualInterestRate: Double) {
this.nominalAnnualInterestRate = nominalAnnualInterestRate
}
} | mpl-2.0 | 68febb545e6375cd2dbe1afe510775b2 | 25.775701 | 75 | 0.677723 | 5.024561 | false | false | false | false |
WijayaPrinting/wp-javafx | openpss-client/src/com/hendraanggrian/openpss/api/CustomersApi.kt | 1 | 1861 | package com.hendraanggrian.openpss.api
import com.hendraanggrian.openpss.data.Page
import com.hendraanggrian.openpss.nosql.StringId
import com.hendraanggrian.openpss.schema.Customer
import com.hendraanggrian.openpss.schema.Customers
import com.hendraanggrian.openpss.schema.Employee
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.http.HttpMethod
interface CustomersApi : Api {
suspend fun getCustomers(search: CharSequence, page: Int, count: Int): Page<Customer> =
client.get {
apiUrl(Customers.schemaName)
parameters(
"search" to search,
"page" to page,
"count" to count
)
}
suspend fun addCustomer(customer: Customer): Customer = client.post {
apiUrl(Customers.schemaName)
jsonBody(customer)
}
suspend fun getCustomer(id: StringId<*>): Customer = client.get {
apiUrl("${Customers.schemaName}/$id")
}
suspend fun editCustomer(login: Employee, id: StringId<*>, customer: Customer): Boolean =
client.requestStatus(HttpMethod.Put) {
apiUrl("${Customers.schemaName}/$id")
jsonBody(customer)
parameters("login" to login.name)
}
suspend fun addContact(id: StringId<*>, contact: Customer.Contact): Customer.Contact =
client.post {
apiUrl("${Customers.schemaName}/$id/${Customers.Contacts.schemaName}")
jsonBody(contact)
}
suspend fun deleteContact(
login: Employee,
id: StringId<*>,
contact: Customer.Contact
): Boolean =
client.requestStatus(HttpMethod.Delete) {
apiUrl("${Customers.schemaName}/$id/${Customers.Contacts.schemaName}")
jsonBody(contact)
parameters("employee" to login.name)
}
}
| apache-2.0 | 460700c85ec92e143eca459c78329f49 | 32.232143 | 93 | 0.642665 | 4.66416 | false | false | false | false |
xiaoniaojun/SecondHandToy | app/src/main/java/cn/xiaoniaojun/secondhandtoy/mvvm/V/ui/activity/LoginActivity.kt | 1 | 34404 | package cn.xiaoniaojun.secondhandtoy.mvvm.V.ui.activity
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.CardView
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.Transformation
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import cn.xiaoniaojun.secondhandtoy.R
import it.sephiroth.android.library.easing.Back
import it.sephiroth.android.library.easing.EasingManager
class LoginActivity : AppCompatActivity() {
private var rootLayout: ViewGroup? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_main_login)
rootLayout = findViewById(R.id.main_container) as ViewGroup
val email = findViewById(R.id.email) as EditText
val password = findViewById(R.id.password) as EditText
val emailS = findViewById(R.id.email_singup) as EditText
val passwordS = findViewById(R.id.password_singup) as EditText
val passwordC = findViewById(R.id.password_confirm) as EditText
val tvLogin = findViewById(R.id.login_tv) as TextView
tvLogin.setOnClickListener {
val intent = Intent(this@LoginActivity, HomeActivity::class.java)
startActivity(intent)
finish()
}
// 为输入框聚焦事件设置动画
val focuslistene = View.OnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
animateOnFocus(v)
} else {
animateOnFocusLost(v)
}
}
email.onFocusChangeListener = focuslistene
password.onFocusChangeListener = focuslistene
emailS.onFocusChangeListener = focuslistene
passwordS.onFocusChangeListener = focuslistene
passwordC.onFocusChangeListener = focuslistene
}
fun showSingUp(view: View) {
val animationCircle = findViewById(R.id.animation_circle) as CardView
val animationFirstArist = findViewById(R.id.animation_first_arist)
val animationSecondArist = findViewById(R.id.animation_second_arist)
val animationSquare = findViewById(R.id.animation_square)
val squareParent = animationSquare.parent as LinearLayout
val animationTV = findViewById(R.id.animation_tv) as TextView
val twitterImageView = findViewById(R.id.twitter_img) as ImageView
val instagramImageView = findViewById(R.id.instagram_img) as ImageView
val facebokImageView = findViewById(R.id.facebook_img) as ImageView
val singupFormContainer = findViewById(R.id.signup_form_container)
val loginFormContainer = findViewById(R.id.login_form_container)
val backgroundColor = ContextCompat.getColor(this, R.color.colorPrimary)
val singupTV = findViewById(R.id.singup_big_tv) as TextView
val scale = resources.displayMetrics.density
val circle_curr_margin = (82 * scale + 0.5f).toInt()
val circle_target_margin = rootLayout!!.width - (70 * scale + 0.5f).toInt()
val first_curr_width = (120 * scale + 0.5f).toInt()
val first_target_width = (rootLayout!!.height * 1.3).toInt()
val first_curr_height = (70 * scale + 0.5f).toInt()
val first_target_height = rootLayout!!.width
val first_curr_margin = (40 * scale + 0.5f).toInt()
val first_target_margin = (35 * scale + 0.5f).toInt()
val first_expand_margin = first_curr_margin - first_target_height
val square_target_width = rootLayout!!.width
val square_target_height = (80 * scale + 0.5f).toInt()
val tv_curr_x = findViewById(R.id.singup_tv).x + findViewById(R.id.singup_button).x
val tv_curr_y = findViewById(R.id.singup_tv).y + findViewById(R.id.buttons_container).y + findViewById(R.id.singup_container).y
val tv_target_x = findViewById(R.id.singup_big_tv).x
val tv_target_y = findViewById(R.id.singup_big_tv).y
val tv_curr_size = 16f
val tv_target_size = 56f
val tv_curr_color = Color.parseColor("#ffffff")
val tv_target_color = Color.parseColor("#ccffffff")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val window = window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = ContextCompat.getColor(this, R.color.colorAccentDark)
}
squareParent.gravity = Gravity.END
animationTV.setText(R.string.sign_up)
val a = object : Animation() {
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
var diff_margin = circle_curr_margin - circle_target_margin
var margin = circle_target_margin + (diff_margin - diff_margin * interpolatedTime).toInt()
val params_circle = animationCircle.layoutParams as RelativeLayout.LayoutParams
params_circle.setMargins(0, 0, margin, (40 * scale + 0.5f).toInt())
animationCircle.requestLayout()
//----------------------------------------------------------
// 1号变换块
// 宽度变为高度
val diff_width = first_curr_width - first_target_width
val width = first_target_width + (diff_width - diff_width * interpolatedTime).toInt()
val diff_height = first_curr_height - first_target_height
val height = first_target_height + (diff_height - (diff_height - first_target_margin) * interpolatedTime).toInt()
diff_margin = first_curr_margin - first_expand_margin
margin = first_expand_margin + (diff_margin - diff_margin * interpolatedTime).toInt()
val margin_r = (-(first_target_width - rootLayout!!.width) * interpolatedTime).toInt()
val params_first = animationFirstArist.layoutParams as RelativeLayout.LayoutParams
params_first.setMargins(0, 0, margin_r, margin)
params_first.width = width
params_first.height = height
animationFirstArist.requestLayout()
animationFirstArist.pivotX = 0f
animationFirstArist.pivotY = 0f
animationFirstArist.rotation = -90 * interpolatedTime
//-----------------------------------------------------------
margin = first_curr_margin + (first_target_margin * interpolatedTime).toInt()
val params_second = animationSecondArist.layoutParams as RelativeLayout.LayoutParams
params_second.setMargins(0, 0, margin_r, margin)
params_second.width = width
animationSecondArist.requestLayout()
animationSecondArist.pivotX = 0f
animationSecondArist.pivotY = animationSecondArist.height.toFloat()
animationSecondArist.rotation = 90 * interpolatedTime
animationSquare.layoutParams.width = (square_target_width.toDouble() * interpolatedTime.toDouble() * 1.4).toInt()
animationSquare.requestLayout()
val diff_x = tv_curr_x - tv_target_x
val x = tv_target_x + (diff_x - diff_x * interpolatedTime)
val diff_y = tv_curr_y - tv_target_y
val y = tv_target_y + (diff_y - diff_y * interpolatedTime)
animationTV.x = x
animationTV.y = y
animationTV.requestLayout()
// 变换社交图标颜色
if (interpolatedTime >= 0.2f && interpolatedTime < 0.3f) {
twitterImageView.setImageResource(R.drawable.ic_qq_pink)
} else if (interpolatedTime >= 0.45f && interpolatedTime < 0.55f) {
instagramImageView.setImageResource(R.drawable.ic_wechat_pink)
} else if (interpolatedTime >= 0.65f && interpolatedTime < 0.75f) {
facebokImageView.setImageResource(R.drawable.ic_weibo_pink)
}
singupFormContainer.alpha = interpolatedTime
loginFormContainer.alpha = 1 - interpolatedTime
}
override fun willChangeBounds(): Boolean {
return true
}
}
a.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(arg0: Animation) {
findViewById(R.id.singup_container).visibility = View.INVISIBLE
animationFirstArist.visibility = View.VISIBLE
animationSecondArist.visibility = View.VISIBLE
animationSquare.visibility = View.VISIBLE
animationTV.visibility = View.VISIBLE
singupFormContainer.visibility = View.VISIBLE
animationFirstArist.bringToFront()
squareParent.bringToFront()
animationSecondArist.bringToFront()
animationCircle.bringToFront()
findViewById(R.id.buttons_container).bringToFront()
singupFormContainer.bringToFront()
singupTV.bringToFront()
animationTV.bringToFront()
animationFirstArist.setBackgroundColor(backgroundColor)
animationSecondArist.setBackgroundColor(backgroundColor)
animationCircle.setCardBackgroundColor(backgroundColor)
animationSquare.setBackgroundColor(backgroundColor)
}
override fun onAnimationRepeat(arg0: Animation) {}
override fun onAnimationEnd(arg0: Animation) {
Handler().postDelayed({
animationFirstArist.visibility = View.GONE
animationSecondArist.visibility = View.GONE
animationTV.visibility = View.GONE
animationSquare.visibility = View.GONE
findViewById(R.id.singup_big_tv).visibility = View.VISIBLE
}, 100)
rootLayout!!.setBackgroundColor(ContextCompat.getColor(this@LoginActivity, R.color.colorPrimary))
(animationSquare.parent as View).setBackgroundColor(ContextCompat.getColor(this@LoginActivity, R.color.colorPrimary))
findViewById(R.id.login_form_container).visibility = View.GONE
findViewById(R.id.login_tv).visibility = View.GONE
showLoginButton()
}
})
val a2 = object : Animation() {
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
animationSquare.layoutParams.height = (square_target_height.toDouble() * interpolatedTime.toDouble() * 1.4).toInt()
animationSquare.requestLayout()
}
override fun willChangeBounds(): Boolean {
return true
}
}
val a3 = ValueAnimator.ofFloat(tv_curr_size, tv_target_size)
a3.addUpdateListener { animation ->
val animatedValue = animation.animatedValue as Float
animationTV.textSize = animatedValue
}
val a4 = ValueAnimator.ofInt(tv_curr_color, tv_target_color)
a4.setEvaluator(ArgbEvaluator())
a4.addUpdateListener { animation ->
val animatedValue = animation.animatedValue as Int
animationTV.setTextColor(animatedValue)
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
val a5 = ValueAnimator.ofInt(Color.argb(255, 249, 164, 221), Color.argb(255, 19, 26, 86))
a5.setEvaluator(ArgbEvaluator())
a5.addUpdateListener { animation ->
val animatedValue = animation.animatedValue as Int
rootLayout!!.setBackgroundColor(animatedValue)
(animationSquare.parent as View).setBackgroundColor(animatedValue)
}
a5.duration = 400
a5.start()
}
a.duration = 400
a2.duration = 172
a3.duration = 400
a4.duration = 400
a4.start()
a3.start()
animationSquare.startAnimation(a2)
animationCircle.startAnimation(a)
singupFormContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_form))
}
fun showLogIn(view: View) {
val animationCircle = findViewById(R.id.animation_circle) as CardView
val animationFirstArist = findViewById(R.id.animation_first_arist)
val animationSecondArist = findViewById(R.id.animation_second_arist)
val animationSquare = findViewById(R.id.animation_square)
val squareParent = animationSquare.parent as LinearLayout
val animationTV = findViewById(R.id.animation_tv) as TextView
val twitterImageView = findViewById(R.id.twitter_img) as ImageView
val instagramImageView = findViewById(R.id.instagram_img) as ImageView
val facebokImageView = findViewById(R.id.facebook_img) as ImageView
val singupFormContainer = findViewById(R.id.signup_form_container)
val loginFormContainer = findViewById(R.id.login_form_container)
val loginTV = findViewById(R.id.login_tv) as TextView
val backgrounColor = ContextCompat.getColor(this, R.color.colorAccent)
val scale = resources.displayMetrics.density
val circle_curr_margin = rootLayout!!.width - (view.width.toFloat() - view.x - animationCircle.width.toFloat()).toInt()
val circle_target_margin = 0
val first_curr_width = (108 * scale + 0.5f).toInt()
val first_target_width = rootLayout!!.height * 2
val first_curr_height = (70 * scale + 0.5f).toInt()
val first_target_height = rootLayout!!.width
val first_curr_margin = (40 * scale + 0.5f).toInt()
val first_target_margin = (35 * scale + 0.5f).toInt()
val first_expand_margin = first_curr_margin - first_target_height
val first_curr_margin_r = rootLayout!!.width - first_curr_width
val square_target_width = rootLayout!!.width
val square_target_height = (80 * scale + 0.5f).toInt()
val tv_curr_x = findViewById(R.id.login_small_tv).x + findViewById(R.id.login_button).x
val tv_curr_y = findViewById(R.id.login_small_tv).y + findViewById(R.id.buttons_container).y + findViewById(R.id.login_container).y
val tv_target_x = findViewById(R.id.login_tv).x
val tv_target_y = findViewById(R.id.login_tv).y
val tv_curr_size = 16f
val tv_target_size = 56f
val tv_curr_color = Color.parseColor("#ffffff")
val tv_target_color = Color.parseColor("#ccffffff")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val window = window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = ContextCompat.getColor(this, R.color.colorPrimaryDark)
}
squareParent.gravity = Gravity.START
animationTV.setText(R.string.log_in)
val a = object : Animation() {
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
var diff_margin = circle_curr_margin - circle_target_margin
var margin = circle_target_margin + (diff_margin - diff_margin * interpolatedTime).toInt()
val params_circle = animationCircle.layoutParams as RelativeLayout.LayoutParams
params_circle.setMargins(0, 0, margin, (40 * scale + 0.5f).toInt())
animationCircle.requestLayout()
val diff_width = first_curr_width - first_target_width
val width = first_target_width + (diff_width - diff_width * interpolatedTime).toInt()
val diff_height = first_curr_height - first_target_height
val height = first_target_height + (diff_height - (diff_height - first_target_margin) * interpolatedTime).toInt()
diff_margin = first_curr_margin - first_expand_margin
margin = first_expand_margin + (diff_margin - diff_margin * interpolatedTime).toInt()
val margin_r = first_curr_margin_r - (first_curr_margin_r * interpolatedTime).toInt()
val margin_l = if (rootLayout!!.width - width < 0) rootLayout!!.width - width else 0
val params_first = animationFirstArist.layoutParams as RelativeLayout.LayoutParams
params_first.setMargins(margin_l, 0, margin_r, margin)
params_first.width = width
params_first.height = height
animationFirstArist.requestLayout()
animationFirstArist.pivotX = animationFirstArist.width.toFloat()
animationFirstArist.pivotY = 0f
animationFirstArist.rotation = 90 * interpolatedTime
margin = first_curr_margin + (first_target_margin * interpolatedTime).toInt()
val params_second = animationSecondArist.layoutParams as RelativeLayout.LayoutParams
params_second.setMargins(0, 0, margin_r, margin)
params_second.width = width
animationSecondArist.requestLayout()
animationSecondArist.pivotX = animationSecondArist.width.toFloat()
animationSecondArist.pivotY = animationSecondArist.height.toFloat()
animationSecondArist.rotation = -(90 * interpolatedTime)
animationSquare.layoutParams.width = (square_target_width * interpolatedTime).toInt()
animationSquare.requestLayout()
val diff_x = tv_curr_x - tv_target_x
val x = tv_target_x + (diff_x - diff_x * interpolatedTime)
val diff_y = tv_curr_y - tv_target_y
val y = tv_target_y + (diff_y - diff_y * interpolatedTime)
animationTV.x = x
animationTV.y = y
animationTV.requestLayout()
if (interpolatedTime >= 0.2f && interpolatedTime < 0.3f) {
facebokImageView.setImageResource(R.drawable.ic_qq_blue)
} else if (interpolatedTime >= 0.45f && interpolatedTime < 0.55f) {
instagramImageView.setImageResource(R.drawable.ic_wechat_blue)
} else if (interpolatedTime >= 0.65f && interpolatedTime < 0.75f) {
twitterImageView.setImageResource(R.drawable.ic_weibo_blue)
}
loginFormContainer.alpha = interpolatedTime
singupFormContainer.alpha = 1 - interpolatedTime
}
override fun willChangeBounds(): Boolean {
return true
}
}
a.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(arg0: Animation) {
animationFirstArist.setBackgroundColor(backgrounColor)
animationSecondArist.setBackgroundColor(backgrounColor)
animationSquare.setBackgroundColor(backgrounColor)
animationFirstArist.visibility = View.VISIBLE
findViewById(R.id.login_container).visibility = View.INVISIBLE
animationSecondArist.visibility = View.VISIBLE
animationSquare.visibility = View.VISIBLE
animationTV.visibility = View.VISIBLE
loginFormContainer.visibility = View.VISIBLE
loginTV.visibility = View.INVISIBLE
animationFirstArist.bringToFront()
squareParent.bringToFront()
animationSecondArist.bringToFront()
animationCircle.bringToFront()
findViewById(R.id.buttons_container).bringToFront()
loginFormContainer.bringToFront()
loginTV.bringToFront()
animationTV.bringToFront()
}
override fun onAnimationRepeat(arg0: Animation) {}
override fun onAnimationEnd(arg0: Animation) {
Handler().postDelayed({
animationFirstArist.visibility = View.GONE
animationSecondArist.visibility = View.GONE
animationTV.visibility = View.GONE
animationSquare.visibility = View.GONE
findViewById(R.id.login_tv).visibility = View.VISIBLE
findViewById(R.id.login_tv).bringToFront()
}, 100)
rootLayout!!.setBackgroundColor(ContextCompat.getColor(this@LoginActivity, R.color.colorAccent))
(animationSquare.parent as View).setBackgroundColor(ContextCompat.getColor(this@LoginActivity, R.color.colorAccent))
findViewById(R.id.signup_form_container).visibility = View.GONE
findViewById(R.id.singup_big_tv).visibility = View.GONE
showSignUpButton()
}
})
val a2 = object : Animation() {
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
animationSquare.layoutParams.height = (square_target_height * interpolatedTime).toInt()
animationSquare.requestLayout()
}
override fun willChangeBounds(): Boolean {
return true
}
}
val a3 = ValueAnimator.ofFloat(tv_curr_size, tv_target_size)
a3.addUpdateListener { animation ->
val animatedValue = animation.animatedValue as Float
animationTV.textSize = animatedValue
}
val a4 = ValueAnimator.ofInt(tv_curr_color, tv_target_color)
a4.setEvaluator(ArgbEvaluator())
a4.addUpdateListener { animation ->
val animatedValue = animation.animatedValue as Int
animationTV.setTextColor(animatedValue)
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
val a5 = ValueAnimator.ofInt(Color.argb(255, 19, 26, 86), Color.argb(255, 249, 164, 221))
a5.setEvaluator(ArgbEvaluator())
a5.addUpdateListener { animation ->
val animatedValue = animation.animatedValue as Int
rootLayout!!.setBackgroundColor(animatedValue)
(animationSquare.parent as View).setBackgroundColor(animatedValue)
}
a5.duration = 400
a5.start()
}
a.duration = 400
a2.duration = 172
a3.duration = 400
a4.duration = 400
a4.start()
a3.start()
animationSquare.startAnimation(a2)
animationCircle.startAnimation(a)
loginFormContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_form_reverse))
}
private fun showLoginButton() {
val singupButton = findViewById(R.id.singup_button) as CardView
val loginButton = findViewById(R.id.login_button)
loginButton.visibility = View.VISIBLE
loginButton.measure(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
findViewById(R.id.login_container).visibility = View.VISIBLE
val scale = resources.displayMetrics.density
val curr_singup_margin = (-35 * scale + 0.5f).toInt()
val target_singup_margin = -singupButton.width
val curr_login_margin = -loginButton.measuredWidth
val target_login_margin = (-35 * scale + 0.5f).toInt()
val manager = EasingManager(object : EasingManager.EasingCallback {
override fun onEasingValueChanged(value: Double, oldValue: Double) {
var diff_margin = curr_singup_margin - target_singup_margin
var margin = target_singup_margin + (diff_margin - diff_margin * value).toInt()
var layoutParams = singupButton.layoutParams as LinearLayout.LayoutParams
layoutParams.setMargins(0, 0, margin, 0)
singupButton.requestLayout()
diff_margin = curr_login_margin - target_login_margin
margin = target_login_margin + (diff_margin - diff_margin * value).toInt()
layoutParams = loginButton.layoutParams as LinearLayout.LayoutParams
layoutParams.leftMargin = margin
loginButton.requestLayout()
}
override fun onEasingStarted(value: Double) {
var diff_margin = curr_singup_margin - target_singup_margin
var margin = target_singup_margin + (diff_margin - diff_margin * value).toInt()
var layoutParams = singupButton.layoutParams as LinearLayout.LayoutParams
layoutParams.setMargins(0, 0, margin, 0)
singupButton.requestLayout()
diff_margin = curr_login_margin - target_login_margin
margin = target_login_margin + (diff_margin - diff_margin * value).toInt()
layoutParams = loginButton.layoutParams as LinearLayout.LayoutParams
layoutParams.setMargins(margin, 0, 0, 0)
loginButton.requestLayout()
}
override fun onEasingFinished(value: Double) {
var layoutParams = singupButton.layoutParams as LinearLayout.LayoutParams
layoutParams.setMargins(0, 0, target_singup_margin, 0)
singupButton.requestLayout()
layoutParams = loginButton.layoutParams as LinearLayout.LayoutParams
layoutParams.setMargins(target_login_margin, 0, 0, 0)
loginButton.requestLayout()
singupButton.visibility = View.GONE
}
})
manager.start(Back::class.java, EasingManager.EaseType.EaseOut, 0.0, 1.0, 600)
}
private fun showSignUpButton() {
val singupButton = findViewById(R.id.singup_button) as CardView
val loginButton = findViewById(R.id.login_button)
singupButton.visibility = View.VISIBLE
singupButton.measure(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
findViewById(R.id.singup_container).visibility = View.VISIBLE
val scale = resources.displayMetrics.density
val curr_singup_margin = -singupButton.width
val target_singup_margin = (-35 * scale + 0.5f).toInt()
val curr_login_margin = (-35 * scale + 0.5f).toInt()
val target_login_margin = -loginButton.measuredWidth
val manager = EasingManager(object : EasingManager.EasingCallback {
override fun onEasingValueChanged(value: Double, oldValue: Double) {
var diff_margin = curr_singup_margin - target_singup_margin
var margin = target_singup_margin + (diff_margin - diff_margin * value).toInt()
var layoutParams = singupButton.layoutParams as LinearLayout.LayoutParams
layoutParams.setMargins(0, 0, margin, 0)
singupButton.requestLayout()
diff_margin = curr_login_margin - target_login_margin
margin = target_login_margin + (diff_margin - diff_margin * value).toInt()
layoutParams = loginButton.layoutParams as LinearLayout.LayoutParams
layoutParams.leftMargin = margin
loginButton.requestLayout()
}
override fun onEasingStarted(value: Double) {
var diff_margin = curr_singup_margin - target_singup_margin
var margin = target_singup_margin + (diff_margin - diff_margin * value).toInt()
var layoutParams = singupButton.layoutParams as LinearLayout.LayoutParams
layoutParams.setMargins(0, 0, margin, 0)
singupButton.requestLayout()
diff_margin = curr_login_margin - target_login_margin
margin = target_login_margin + (diff_margin - diff_margin * value).toInt()
layoutParams = loginButton.layoutParams as LinearLayout.LayoutParams
layoutParams.setMargins(margin, 0, 0, 0)
loginButton.requestLayout()
}
override fun onEasingFinished(value: Double) {
var layoutParams = singupButton.layoutParams as LinearLayout.LayoutParams
layoutParams.setMargins(0, 0, target_singup_margin, 0)
singupButton.requestLayout()
layoutParams = loginButton.layoutParams as LinearLayout.LayoutParams
layoutParams.setMargins(target_login_margin, 0, 0, 0)
loginButton.requestLayout()
loginButton.visibility = View.GONE
}
})
manager.start(Back::class.java, EasingManager.EaseType.EaseOut, 0.0, 1.0, 600)
}
private fun animateOnFocus(v: View) {
val first_container = v.parent as CardView
val second_container = first_container.parent as CardView
val first_curr_radius = resources.getDimension(R.dimen.first_card_radius).toInt()
val first_target_radius = resources.getDimension(R.dimen.first_card_radius_on_focus).toInt()
val second_curr_radius = resources.getDimension(R.dimen.second_card_radius).toInt()
val second_target_radius = resources.getDimension(R.dimen.second_card_radius_on_focus).toInt()
val first_curr_color = ContextCompat.getColor(this, android.R.color.transparent)
val first_target_color = (rootLayout!!.background as ColorDrawable).color
val second_curr_color = ContextCompat.getColor(this, R.color.backgroundEditText)
val second_target_color = ContextCompat.getColor(this, android.R.color.white)
val first_anim = ValueAnimator()
first_anim.setIntValues(first_curr_color, first_target_color)
first_anim.setEvaluator(ArgbEvaluator())
first_anim.addUpdateListener { animation -> first_container.setCardBackgroundColor(animation.animatedValue as Int) }
val second_anim = ValueAnimator()
second_anim.setIntValues(second_curr_color, second_target_color)
second_anim.setEvaluator(ArgbEvaluator())
second_anim.addUpdateListener { animation -> second_container.setCardBackgroundColor(animation.animatedValue as Int) }
val a = object : Animation() {
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
var diff_radius = first_curr_radius - first_target_radius
var radius = first_target_radius + (diff_radius * (1 - interpolatedTime)).toInt()
first_container.radius = radius.toFloat()
first_container.requestLayout()
diff_radius = second_curr_radius - second_target_radius
radius = second_target_radius + (diff_radius * (1 - interpolatedTime)).toInt()
second_container.radius = radius.toFloat()
second_container.requestLayout()
}
override fun willChangeBounds(): Boolean {
return true
}
}
a.duration = 200
first_anim.duration = 200
second_anim.duration = 200
first_anim.start()
second_anim.start()
first_container.startAnimation(a)
}
private fun animateOnFocusLost(v: View) {
val first_container = v.parent as CardView
val second_container = first_container.parent as CardView
val first_curr_radius = resources.getDimension(R.dimen.first_card_radius_on_focus).toInt()
val first_target_radius = resources.getDimension(R.dimen.first_card_radius).toInt()
val second_curr_radius = resources.getDimension(R.dimen.second_card_radius_on_focus).toInt()
val second_target_radius = resources.getDimension(R.dimen.second_card_radius).toInt()
val first_curr_color = (rootLayout!!.background as ColorDrawable).color
val first_target_color = ContextCompat.getColor(this, android.R.color.transparent)
val second_curr_color = ContextCompat.getColor(this, android.R.color.white)
val second_target_color = ContextCompat.getColor(this, R.color.backgroundEditText)
val first_anim = ValueAnimator()
first_anim.setIntValues(first_curr_color, first_target_color)
first_anim.setEvaluator(ArgbEvaluator())
first_anim.addUpdateListener { animation -> first_container.setCardBackgroundColor(animation.animatedValue as Int) }
val second_anim = ValueAnimator()
second_anim.setIntValues(second_curr_color, second_target_color)
second_anim.setEvaluator(ArgbEvaluator())
second_anim.addUpdateListener { animation -> second_container.setCardBackgroundColor(animation.animatedValue as Int) }
val a = object : Animation() {
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
var diff_radius = first_curr_radius - first_target_radius
var radius = first_target_radius + (diff_radius - diff_radius * interpolatedTime).toInt()
first_container.radius = radius.toFloat()
first_container.requestLayout()
diff_radius = second_curr_radius - second_target_radius
radius = second_target_radius + (diff_radius - diff_radius * interpolatedTime).toInt()
second_container.radius = radius.toFloat()
second_container.requestLayout()
}
override fun willChangeBounds(): Boolean {
return true
}
}
a.duration = 200
first_anim.duration = 200
second_anim.duration = 200
first_anim.start()
second_anim.start()
first_container.startAnimation(a)
}
}
| mit | 8642ae52d51692f1520a881d671eec3a | 44.549072 | 139 | 0.633357 | 4.925283 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/entitymapper/SeasonMapper.kt | 1 | 3894 | /*
* Copyright (C) 2018 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.entitymapper
import android.database.Cursor
import net.simonvt.cathode.common.data.MappedCursorLiveData
import net.simonvt.cathode.common.database.getBoolean
import net.simonvt.cathode.common.database.getFloat
import net.simonvt.cathode.common.database.getInt
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.common.database.getStringOrNull
import net.simonvt.cathode.entity.Season
import net.simonvt.cathode.provider.DatabaseContract.SeasonColumns
object SeasonMapper : MappedCursorLiveData.CursorMapper<Season> {
override fun map(cursor: Cursor): Season? {
return if (cursor.moveToFirst()) mapSeason(cursor) else null
}
fun mapSeason(cursor: Cursor): Season {
val id = cursor.getLong(SeasonColumns.ID)
val showId = cursor.getLong(SeasonColumns.SHOW_ID)
val season = cursor.getInt(SeasonColumns.SEASON)
val tvdbId = cursor.getInt(SeasonColumns.TVDB_ID)
val tmdbId = cursor.getInt(SeasonColumns.TMDB_ID)
val tvrageId = cursor.getLong(SeasonColumns.TVRAGE_ID)
val userRating = cursor.getInt(SeasonColumns.USER_RATING)
val ratedAt = cursor.getLong(SeasonColumns.RATED_AT)
val rating = cursor.getFloat(SeasonColumns.RATING)
val votes = cursor.getInt(SeasonColumns.VOTES)
val hiddenWatched = cursor.getBoolean(SeasonColumns.HIDDEN_WATCHED)
val hiddenCollected = cursor.getBoolean(SeasonColumns.HIDDEN_COLLECTED)
val watchedCount = cursor.getInt(SeasonColumns.WATCHED_COUNT)
val airdateCount = cursor.getInt(SeasonColumns.AIRDATE_COUNT)
val inCollectionCount = cursor.getInt(SeasonColumns.IN_COLLECTION_COUNT)
val inWatchlistCount = cursor.getInt(SeasonColumns.IN_WATCHLIST_COUNT)
val showTitle = cursor.getStringOrNull(SeasonColumns.SHOW_TITLE)
val airedCount = cursor.getInt(SeasonColumns.AIRED_COUNT)
val unairedCount = cursor.getInt(SeasonColumns.UNAIRED_COUNT)
val watchedAiredCount = cursor.getInt(SeasonColumns.WATCHED_AIRED_COUNT)
val collectedAiredCount = cursor.getInt(SeasonColumns.COLLECTED_AIRED_COUNT)
val episodeCount = cursor.getInt(SeasonColumns.EPISODE_COUNT)
return Season(
id,
showId,
season,
tvdbId,
tmdbId,
tvrageId,
userRating,
ratedAt,
rating,
votes,
hiddenWatched,
hiddenCollected,
watchedCount,
airdateCount,
inCollectionCount,
inWatchlistCount,
showTitle,
airedCount,
unairedCount,
watchedAiredCount,
collectedAiredCount,
episodeCount
)
}
val projection = arrayOf(
SeasonColumns.ID,
SeasonColumns.SHOW_ID,
SeasonColumns.SEASON,
SeasonColumns.TVDB_ID,
SeasonColumns.TMDB_ID,
SeasonColumns.TVRAGE_ID,
SeasonColumns.USER_RATING,
SeasonColumns.RATED_AT,
SeasonColumns.RATING,
SeasonColumns.VOTES,
SeasonColumns.HIDDEN_WATCHED,
SeasonColumns.HIDDEN_COLLECTED,
SeasonColumns.WATCHED_COUNT,
SeasonColumns.AIRDATE_COUNT,
SeasonColumns.IN_COLLECTION_COUNT,
SeasonColumns.IN_WATCHLIST_COUNT,
SeasonColumns.SHOW_TITLE,
SeasonColumns.AIRED_COUNT,
SeasonColumns.UNAIRED_COUNT,
SeasonColumns.WATCHED_AIRED_COUNT,
SeasonColumns.COLLECTED_AIRED_COUNT,
SeasonColumns.EPISODE_COUNT
)
}
| apache-2.0 | 16fc6a6ab053aa09a2a4da295a667642 | 34.724771 | 80 | 0.749358 | 4.341137 | false | false | false | false |
cfig/Android_boot_image_editor | bbootimg/src/main/kotlin/avb/blob/AuthBlob.kt | 1 | 3151 | // Copyright 2021 [email protected]
//
// 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 avb.blob
import avb.alg.Algorithms
import cfig.helper.CryptoHelper
import cfig.helper.Helper
import cc.cfig.io.Struct
import org.slf4j.LoggerFactory
import java.nio.file.Files
import java.nio.file.Paths
import java.security.MessageDigest
import java.security.PrivateKey
data class AuthBlob(
var offset: Long = 0,
var size: Long = 0,
var hash: String? = null,
var signature: String? = null
) {
companion object {
fun calcHash(
header_data_blob: ByteArray,
aux_data_blob: ByteArray,
algorithm_name: String
): ByteArray {
val alg = Algorithms.get(algorithm_name)!!
return if (alg.name == "NONE") {
log.debug("calc hash: NONE")
byteArrayOf()
} else {
MessageDigest.getInstance(CryptoHelper.Hasher.pyAlg2java(alg.hash_name)).apply {
update(header_data_blob)
update(aux_data_blob)
}.digest().apply {
log.debug("calc hash = " + Helper.toHexString(this))
}
}
}
private fun calcSignature(hash: ByteArray, algorithm_name: String): ByteArray {
val alg = Algorithms.get(algorithm_name)!!
return if (alg.name == "NONE") {
byteArrayOf()
} else {
val k = CryptoHelper.KeyBox.parse4(Files.readAllBytes(Paths.get(alg.defaultKey.replace(".pem", ".pk8"))))
CryptoHelper.Signer.rawRsa(k.key as PrivateKey, Helper.join(alg.padding, hash))
}
}
fun createBlob(
header_data_blob: ByteArray,
aux_data_blob: ByteArray,
algorithm_name: String
): ByteArray {
val alg = Algorithms.get(algorithm_name)!!
val authBlockSize = Helper.round_to_multiple((alg.hash_num_bytes + alg.signature_num_bytes).toLong(), 64)
if (0L == authBlockSize) {
log.info("No auth blob for algorithm " + alg.name)
return byteArrayOf()
}
//hash & signature
val binaryHash = calcHash(header_data_blob, aux_data_blob, algorithm_name)
val binarySignature = calcSignature(binaryHash, algorithm_name)
val authData = Helper.join(binaryHash, binarySignature)
return Helper.join(authData, Struct("${authBlockSize - authData.size}x").pack(0))
}
private val log = LoggerFactory.getLogger(AuthBlob::class.java)
}
}
| apache-2.0 | 5ecf038c89f325ef42c91293396ed13d | 36.511905 | 121 | 0.6106 | 4.310534 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/intentions/LatexInlineDisplayToggle.kt | 1 | 3134 | package nl.hannahsten.texifyidea.intentions
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.psi.LatexDisplayMath
import nl.hannahsten.texifyidea.psi.LatexInlineMath
import nl.hannahsten.texifyidea.util.*
import nl.hannahsten.texifyidea.util.files.isLatexFile
/**
* @author Hannah Schellekens
*/
open class LatexInlineDisplayToggle : TexifyIntentionBase("Toggle inline/display math mode") {
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
if (editor == null || file == null || !file.isLatexFile()) {
return false
}
val element = file.findElementAt(editor.caretModel.offset) ?: return false
return element.hasParent(LatexInlineMath::class) || element.hasParent(LatexDisplayMath::class)
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (editor == null || file == null || !file.isLatexFile()) {
return
}
val element = file.findElementAt(editor.caretModel.offset) ?: return
val inline = element.parentOfType(LatexInlineMath::class)
if (inline != null) {
applyForInlineMath(editor, inline)
}
else {
applyForDisplayMath(editor, element.parentOfType(LatexDisplayMath::class) ?: return)
}
}
private fun applyForInlineMath(editor: Editor, inline: LatexInlineMath) {
val document = editor.document
val indent = document.lineIndentationByOffset(inline.textOffset)
val endLength = inline.inlineMathEnd?.textLength ?: 0
val text = inline.text.trimRange(inline.inlineMathStart.textLength, endLength).trim()
runWriteAction {
val extra = if (document.getText(TextRange.from(inline.endOffset(), 1)) == " ") {
1
}
else 0
val result = "\n\\[\n $text\n\\]\n".replace("\n", "\n$indent")
document.replaceString(inline.textOffset, inline.endOffset() + extra, result)
editor.caretModel.moveToOffset(inline.textOffset + result.length)
}
}
private fun applyForDisplayMath(editor: Editor, display: LatexDisplayMath) {
val document = editor.document
val indent = document.lineIndentationByOffset(display.textOffset)
val whitespace = indent.length + 1
val text = display.text.trimRange(2, 2).trim()
runWriteAction {
val leading = if (document.getText(TextRange.from(display.textOffset - whitespace - 1, 1)) != " ") " " else ""
val trailing = if (document.getText(TextRange.from(display.endOffset() + whitespace, 1)) != " ") " " else ""
val result = "$leading${'$'}$text${'$'}$trailing"
.replace("\n", " ")
.replace(Regex("\\s+"), " ")
document.replaceString(display.textOffset - whitespace, display.endOffset() + whitespace, result)
}
}
}
| mit | 0bf6e4e6f865a048cf282c2ef1a23043 | 40.236842 | 122 | 0.650606 | 4.548621 | false | false | false | false |
QiBaobin/clean-architecture | domain/src/test/kotlin/bob/clean/domain/manager/AsyncUseCaseImplTest.kt | 1 | 1522 | package bob.clean.domain.manager
import bob.clean.domain.interactor.UseCase
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import io.reactivex.Scheduler
import io.reactivex.schedulers.Schedulers
import org.junit.Before
import org.junit.Test
import java.util.concurrent.TimeUnit
import kotlin.test.assertTrue
class AsyncUseCaseImplTest {
val param = "params"
val result = "result"
val useCase = mock<UseCase<String, String>>()
val scheduler: Scheduler = Schedulers.trampoline()
val asyncUseCase = AsyncUseCaseImpl(scheduler, useCase)
@Before
fun setup() {
whenever(useCase.execute(param)).thenReturn(result)
}
@Test
fun testDelegation() {
asyncUseCase.execute(param)
verify(useCase).execute(param)
}
@Test
fun testAsync() {
val observer = TestObserver()
asyncUseCase.asyncExecute(param, observer)
val testObserver = observer.testObserver
testObserver.awaitDone(5, TimeUnit.SECONDS)
testObserver.assertNoTimeout()
verify(useCase).execute(param)
testObserver.assertValue(result)
testObserver.assertComplete()
}
@Test
fun testDispose() {
val observer = TestObserver()
asyncUseCase.asyncExecute(param, observer)
observer.testObserver.awaitDone(5, TimeUnit.SECONDS).assertNoTimeout()
asyncUseCase.dispose()
assertTrue(observer.isDisposed)
}
}
| apache-2.0 | ad0563736d850904b6e9a521ccd54b7b | 26.178571 | 78 | 0.70565 | 4.570571 | false | true | false | false |
thm-projects/arsnova-backend | authz/src/test/kotlin/de/thm/arsnova/service/authservice/handler/RoomAccessHandlerTest.kt | 1 | 5049 | package de.thm.arsnova.service.authservice.handler
import de.thm.arsnova.service.authservice.model.RoomAccess
import de.thm.arsnova.service.authservice.model.RoomAccessEntry
import de.thm.arsnova.service.authservice.model.RoomAccessSyncTracker
import de.thm.arsnova.service.authservice.model.command.RequestRoomAccessSyncCommand
import de.thm.arsnova.service.authservice.model.command.SyncRoomAccessCommand
import de.thm.arsnova.service.authservice.model.event.RoomAccessSyncRequest
import de.thm.arsnova.service.authservice.persistence.RoomAccessRepository
import de.thm.arsnova.service.authservice.persistence.RoomAccessSyncTrackerRepository
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.ArgumentCaptor
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.junit.jupiter.MockitoExtension
import org.springframework.amqp.rabbit.core.RabbitTemplate
import java.util.Optional
@ExtendWith(MockitoExtension::class)
class RoomAccessHandlerTest {
@Mock
private lateinit var rabbitTemplate: RabbitTemplate
@Mock
private lateinit var roomAccessRepository: RoomAccessRepository
@Mock
private lateinit var roomAccessSyncTrackerRepository: RoomAccessSyncTrackerRepository
private lateinit var roomAccessHandler: RoomAccessHandler
val SOME_ROOM_ID = "23e7c082c533e49963b96d7a0500105f"
val SOME_REV = "1-93b09a4699769e6abd3bf5b2ff341e5d"
val SOME_NEWER_REV = "2-93b09a4699769e6abd3bf5b2ff341e5e"
val SOME_EVEN_NEWER_REV = "3-93b09a4699769e6abd3bf5b2ff341e5f"
val SOME_USER_ID = "23e7c082c533e49963b96d7a05000d0e"
val SOME_OTHER_USER_ID = "aaaac082c533e49963b96d7a05000d0f"
val SOME_MODERATOR_ID = "bbbbc082c533e49963b96d7a05000d0f"
val CREATOR_STRING = "CREATOR"
val EXECUTIVE_MODERATOR_STRING = "EXECUTIVE_MODERATOR"
@BeforeEach
fun setUp() {
roomAccessHandler =
RoomAccessHandler(rabbitTemplate, roomAccessRepository, roomAccessSyncTrackerRepository)
}
@Test
fun testStartSyncOnCommand() {
val command = RequestRoomAccessSyncCommand(
SOME_ROOM_ID,
2
)
val expected = RoomAccessSyncRequest(
SOME_ROOM_ID
)
Mockito.`when`(roomAccessSyncTrackerRepository.findById(command.roomId))
.thenReturn(
Optional.of(
RoomAccessSyncTracker(
SOME_ROOM_ID,
SOME_REV
)
)
)
val keyCaptor = ArgumentCaptor.forClass(String::class.java)
val eventCaptor = ArgumentCaptor.forClass(RoomAccessSyncRequest::class.java)
roomAccessHandler.handleRequestRoomAccessSyncCommand(command)
verify(rabbitTemplate, times(1))
.convertAndSend(keyCaptor.capture(), eventCaptor.capture())
assertEquals(keyCaptor.value, "backend.event.room.access.sync.request")
assertEquals(eventCaptor.value, expected)
}
@Test
fun testHandleSyncRoomAccessCommand() {
val command = SyncRoomAccessCommand(
SOME_NEWER_REV,
SOME_ROOM_ID,
listOf(
RoomAccessEntry(SOME_OTHER_USER_ID, CREATOR_STRING)
)
)
val expectedDelete = RoomAccess(
SOME_ROOM_ID,
SOME_USER_ID,
SOME_REV,
CREATOR_STRING,
null,
null
)
val expectedCreate = RoomAccess(
SOME_ROOM_ID,
SOME_OTHER_USER_ID,
SOME_NEWER_REV,
CREATOR_STRING,
null,
null
)
val expectedTracker = RoomAccessSyncTracker(
SOME_ROOM_ID,
SOME_NEWER_REV
)
Mockito.`when`(roomAccessSyncTrackerRepository.findById(command.roomId))
.thenReturn(
Optional.of(
RoomAccessSyncTracker(
SOME_ROOM_ID,
SOME_REV
)
)
)
Mockito.`when`(roomAccessSyncTrackerRepository.save(expectedTracker))
.thenReturn(expectedTracker)
Mockito.`when`(roomAccessRepository.findByRoomId(command.roomId))
.thenReturn(
listOf(
// Do not delete this one
RoomAccess(
SOME_ROOM_ID,
SOME_MODERATOR_ID,
SOME_EVEN_NEWER_REV,
EXECUTIVE_MODERATOR_STRING,
null,
null
),
// This is old and should get deleted
expectedDelete
)
)
roomAccessHandler.handleSyncRoomAccessCommand(command)
verify(roomAccessRepository, times(1)).deleteAll(listOf(expectedDelete))
verify(roomAccessRepository, times(1)).saveAll(listOf(expectedCreate))
verify(roomAccessSyncTrackerRepository, times(1)).save(expectedTracker)
}
@Test
fun testDoNotUpdateOnOldInfo() {
val command = SyncRoomAccessCommand(
SOME_REV,
SOME_ROOM_ID,
listOf(
RoomAccessEntry(SOME_USER_ID, CREATOR_STRING)
)
)
val trackerCaptor = ArgumentCaptor.forClass(RoomAccessSyncTracker::class.java)
verify(roomAccessSyncTrackerRepository, times(0)).save(trackerCaptor.capture())
}
}
| gpl-3.0 | 337895be88700449ba2e2f31f195a14d | 30.360248 | 94 | 0.722717 | 4.104878 | false | false | false | false |
arturbosch/detekt | detekt-rules-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/ReturnCount.kt | 1 | 4525 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.SplitPattern
import io.gitlab.arturbosch.detekt.api.config
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import io.gitlab.arturbosch.detekt.api.internal.Configuration
import io.gitlab.arturbosch.detekt.rules.parentsOfTypeUntil
import io.gitlab.arturbosch.detekt.rules.yieldStatementsSkippingGuardClauses
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
/**
* Restrict the number of return methods allowed in methods.
*
* Having many exit points in a function can be confusing and impacts readability of the
* code.
*
* <noncompliant>
* fun foo(i: Int): String {
* when (i) {
* 1 -> return "one"
* 2 -> return "two"
* else -> return "other"
* }
* }
* </noncompliant>
*
* <compliant>
* fun foo(i: Int): String {
* return when (i) {
* 1 -> "one"
* 2 -> "two"
* else -> "other"
* }
* }
* </compliant>
*/
@ActiveByDefault(since = "1.0.0")
class ReturnCount(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(
javaClass.simpleName,
Severity.Style,
"Restrict the number of return statements in methods.",
Debt.TEN_MINS
)
@Configuration("define the maximum number of return statements allowed per function")
private val max: Int by config(2)
@Configuration("define functions to be ignored by this check")
private val excludedFunctions: SplitPattern by config("equals") { SplitPattern(it) }
@Configuration("if labeled return statements should be ignored")
private val excludeLabeled: Boolean by config(false)
@Configuration("if labeled return from a lambda should be ignored")
private val excludeReturnFromLambda: Boolean by config(true)
@Configuration("if true guard clauses at the beginning of a method should be ignored")
private val excludeGuardClauses: Boolean by config(false)
override fun visitNamedFunction(function: KtNamedFunction) {
super.visitNamedFunction(function)
if (!shouldBeIgnored(function)) {
val numberOfReturns = countReturnStatements(function)
if (numberOfReturns > max) {
report(
CodeSmell(
issue,
Entity.atName(function),
"Function ${function.name} has $numberOfReturns return statements " +
"which exceeds the limit of $max."
)
)
}
}
}
private fun shouldBeIgnored(function: KtNamedFunction) = excludedFunctions.contains(function.name)
private fun countReturnStatements(function: KtNamedFunction): Int {
fun KtReturnExpression.isExcluded(): Boolean = when {
excludeLabeled && labeledExpression != null -> true
excludeReturnFromLambda && isNamedReturnFromLambda() -> true
else -> false
}
val statements = if (excludeGuardClauses) {
function.yieldStatementsSkippingGuardClauses<KtReturnExpression>()
} else {
function.bodyBlockExpression?.statements?.asSequence().orEmpty()
}
return statements.flatMap { it.collectDescendantsOfType<KtReturnExpression>().asSequence() }
.filterNot { it.isExcluded() }
.count { it.getParentOfType<KtNamedFunction>(true) == function }
}
private fun KtReturnExpression.isNamedReturnFromLambda(): Boolean {
val label = this.labeledExpression
if (label != null) {
return this.parentsOfTypeUntil<KtCallExpression, KtNamedFunction>()
.map { it.calleeExpression }
.filterIsInstance<KtNameReferenceExpression>()
.map { it.text }
.any { it in label.text }
}
return false
}
}
| apache-2.0 | 8d7bdf641065444f71cc411140efb47f | 35.491935 | 102 | 0.669613 | 4.693983 | false | true | false | false |
nemerosa/ontrack | ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/support/MutationInputValidationException.kt | 1 | 844 | package net.nemerosa.ontrack.graphql.support
import net.nemerosa.ontrack.graphql.schema.UserError
import net.nemerosa.ontrack.model.exceptions.InputException
import javax.validation.ConstraintViolation
class MutationInputValidationException(
val violations: Set<ConstraintViolation<*>>
) : InputException(
asString(violations)
) {
companion object {
fun asString(violations: Set<ConstraintViolation<*>?>): String =
violations.filterNotNull().joinToString(", ") { cv ->
"${cv.propertyPath}: ${cv.message}"
}
fun asUserError(cv: ConstraintViolation<*>) = UserError(
message = cv.message,
exception = MutationInputValidationException::class.java.name,
location = cv.propertyPath.toString()
)
}
}
| mit | 9a71a0d61cc407610b86f20f76607446 | 34.166667 | 78 | 0.651659 | 5.177914 | false | false | false | false |
wiltonlazary/kotlin-native | tools/kotlin-native-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/konan/KonanCompileConfig.kt | 1 | 6774 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.gradle.plugin.konan
import groovy.lang.Closure
import org.gradle.api.Task
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.project.ProjectInternal
import org.jetbrains.kotlin.gradle.plugin.tasks.*
import org.jetbrains.kotlin.konan.target.Family
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.konan.target.KonanTarget.WASM32
import java.io.File
abstract class KonanCompileConfig<T: KonanCompileTask>(name: String,
type: Class<T>,
project: ProjectInternal,
targets: Iterable<String>)
: KonanBuildingConfig<T>(name, type, project, targets), KonanCompileSpec {
protected abstract val typeForDescription: String
override fun generateTaskDescription(task: T) =
"Build the Kotlin/Native $typeForDescription '${task.name}' for target '${task.konanTarget}'"
override fun generateAggregateTaskDescription(task: Task) =
"Build the Kotlin/Native $typeForDescription '${task.name}' for all supported and declared targets"
override fun generateTargetAliasTaskDescription(task: Task, targetName: String) =
"Build the Kotlin/Native $typeForDescription '${task.name}' for target '$targetName'"
override fun srcDir(dir: Any) = forEach { it.srcDir(dir) }
override fun srcFiles(vararg files: Any) = forEach { it.srcFiles(*files) }
override fun srcFiles(files: Collection<Any>) = forEach { it.srcFiles(files) }
override fun nativeLibrary(lib: Any) = forEach { it.nativeLibrary(lib) }
override fun nativeLibraries(vararg libs: Any) = forEach { it.nativeLibraries(*libs) }
override fun nativeLibraries(libs: FileCollection) = forEach { it.nativeLibraries(libs) }
@Deprecated("Use commonSourceSets instead", ReplaceWith("commonSourceSets(sourceSetName)"))
override fun commonSourceSet(sourceSetName: String) = forEach { it.commonSourceSets(sourceSetName) }
override fun commonSourceSets(vararg sourceSetNames: String) = forEach { it.commonSourceSets(*sourceSetNames) }
override fun enableMultiplatform(flag: Boolean) = forEach { it.enableMultiplatform(flag) }
override fun linkerOpts(values: List<String>) = forEach { it.linkerOpts(values) }
override fun linkerOpts(vararg values: String) = forEach { it.linkerOpts(*values) }
override fun enableDebug(flag: Boolean) = forEach { it.enableDebug(flag) }
override fun noStdLib(flag: Boolean) = forEach { it.noStdLib(flag) }
override fun noMain(flag: Boolean) = forEach { it.noMain(flag) }
override fun enableOptimizations(flag: Boolean) = forEach { it.enableOptimizations(flag) }
override fun enableAssertions(flag: Boolean) = forEach { it.enableAssertions(flag) }
override fun entryPoint(entryPoint: String) = forEach { it.entryPoint(entryPoint) }
override fun measureTime(flag: Boolean) = forEach { it.measureTime(flag) }
override fun dependencies(closure: Closure<Unit>) = forEach { it.dependencies(closure) }
}
open class KonanProgram(name: String,
project: ProjectInternal,
targets: Iterable<String> = project.konanExtension.targets
) : KonanCompileConfig<KonanCompileProgramTask>(name,
KonanCompileProgramTask::class.java,
project,
targets
) {
override val typeForDescription: String
get() = "executable"
override val defaultBaseDir: File
get() = project.konanBinBaseDir
}
open class KonanDynamic(name: String,
project: ProjectInternal,
targets: Iterable<String> = project.konanExtension.targets)
: KonanCompileConfig<KonanCompileDynamicTask>(name,
KonanCompileDynamicTask::class.java,
project,
targets
) {
override val typeForDescription: String
get() = "dynamic library"
override val defaultBaseDir: File
get() = project.konanBinBaseDir
override fun targetIsSupported(target: KonanTarget): Boolean = target != WASM32
}
open class KonanFramework(name: String,
project: ProjectInternal,
targets: Iterable<String> = project.konanExtension.targets)
: KonanCompileConfig<KonanCompileFrameworkTask>(name,
KonanCompileFrameworkTask::class.java,
project,
targets
) {
override val typeForDescription: String
get() = "framework"
override val defaultBaseDir: File
get() = project.konanBinBaseDir
override fun targetIsSupported(target: KonanTarget): Boolean =
target.family.isAppleFamily
}
open class KonanLibrary(name: String,
project: ProjectInternal,
targets: Iterable<String> = project.konanExtension.targets)
: KonanCompileConfig<KonanCompileLibraryTask>(name,
KonanCompileLibraryTask::class.java,
project,
targets
) {
override val typeForDescription: String
get() = "library"
override val defaultBaseDir: File
get() = project.konanLibsBaseDir
}
open class KonanBitcode(name: String,
project: ProjectInternal,
targets: Iterable<String> = project.konanExtension.targets)
: KonanCompileConfig<KonanCompileBitcodeTask>(name,
KonanCompileBitcodeTask::class.java,
project,
targets
) {
override val typeForDescription: String
get() = "bitcode"
override fun generateTaskDescription(task: KonanCompileBitcodeTask) =
"Generates bitcode for the artifact '${task.name}' and target '${task.konanTarget}'"
override fun generateAggregateTaskDescription(task: Task) =
"Generates bitcode for the artifact '${task.name}' for all supported and declared targets'"
override fun generateTargetAliasTaskDescription(task: Task, targetName: String) =
"Generates bitcode for the artifact '${task.name}' for '$targetName'"
override val defaultBaseDir: File
get() = project.konanBitcodeBaseDir
} | apache-2.0 | efa6ba1f1a362a7ac975a35eef1b6f5a | 40.820988 | 115 | 0.689844 | 4.852436 | false | false | false | false |
bailuk/AAT | aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/map/control/NodeInfo.kt | 1 | 1725 | package ch.bailu.aat_gtk.view.map.control
import ch.bailu.aat_gtk.app.GtkAppContext
import ch.bailu.aat_gtk.config.Layout
import ch.bailu.aat_gtk.config.Strings
import ch.bailu.aat_gtk.lib.extensions.margin
import ch.bailu.aat_gtk.lib.extensions.setMarkup
import ch.bailu.aat_lib.gpx.GpxInformation
import ch.bailu.aat_lib.gpx.GpxPointNode
import ch.bailu.aat_lib.html.MarkupBuilderGpx
import ch.bailu.gtk.GTK
import ch.bailu.gtk.gtk.*
import ch.bailu.gtk.type.Str
class NodeInfo {
private val markupBuilder = MarkupBuilderGpx(GtkAppContext.storage, PangoMarkupConfig)
private val label = Label(Str.NULL).apply {
margin(Layout.margin)
}
private val scrolled = ScrolledWindow().apply {
child = label
setSizeRequest(Layout.windowWidth-Layout.barSize*2-Layout.margin*2,Layout.windowHeight/5)
}
val box = Box(Orientation.VERTICAL,0).apply {
addCssClass(Strings.mapControl)
margin(Layout.margin)
append(scrolled)
valign = Align.START
halign = Align.CENTER
visible = GTK.FALSE
}
fun showCenter() {
box.halign = Align.CENTER
box.visible = GTK.TRUE
}
fun showLeft() {
box.halign = Align.START
box.visible = GTK.TRUE
}
fun showRight() {
box.halign = Align.END
box.visible = GTK.TRUE
}
fun hide() {
box.visible = GTK.FALSE
}
fun displayNode(info: GpxInformation, node: GpxPointNode, index: Int) {
markupBuilder.appendInfo(info, index)
markupBuilder.appendNode(node, info)
markupBuilder.appendAttributes(node.attributes)
label.setMarkup(markupBuilder.toString())
markupBuilder.clear()
}
}
| gpl-3.0 | 6f58b815096cbad25b2eb374741d3655 | 26.380952 | 97 | 0.677681 | 3.717672 | false | false | false | false |
vondear/RxTools | RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityTLoadingView.kt | 1 | 2123 | package com.tamsiree.rxdemo.activity
import android.annotation.SuppressLint
import android.os.AsyncTask
import android.os.Bundle
import com.tamsiree.rxdemo.R
import com.tamsiree.rxui.activity.ActivityBase
import kotlinx.android.synthetic.main.activity_tloading_view.*
class ActivityTLoadingView : ActivityBase() {
private val WAIT_DURATION = 5000
private var dummyWait: DummyWait? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tloading_view)
}
override fun initView() {
rxTitle.setLeftFinish(this)
btn_reset.setOnClickListener { resetLoader() }
}
override fun initData() {
loadData()
}
private fun loadData() {
if (dummyWait != null) {
dummyWait!!.cancel(true)
}
dummyWait = DummyWait()
dummyWait!!.execute()
}
private fun postLoadData() {
txt_name.text = "神秘商人"
txt_title.text = "只有有缘人能够相遇"
txt_phone.text = "时限 24 小时"
txt_email.text = "说着一口苦涩难懂的语言 ddjhklfsalkjhghjkl"
image_icon.setImageResource(R.drawable.circle_dialog)
}
private fun resetLoader() {
txt_name.resetLoader()
txt_title.resetLoader()
txt_phone.resetLoader()
txt_email.resetLoader()
image_icon.resetLoader()
loadData()
}
@SuppressLint("StaticFieldLeak")
internal inner class DummyWait : AsyncTask<Void?, Void?, Void?>() {
override fun doInBackground(vararg params: Void?): Void? {
try {
Thread.sleep(WAIT_DURATION.toLong())
} catch (e: InterruptedException) {
e.printStackTrace()
}
return null
}
override fun onPostExecute(result: Void?) {
super.onPostExecute(result)
postLoadData()
}
}
override fun onDestroy() {
super.onDestroy()
if (dummyWait != null) {
dummyWait!!.cancel(true)
}
}
} | apache-2.0 | 42470d9bea2920edadc24912cdaf541e | 25.857143 | 71 | 0.610547 | 4.31524 | false | false | false | false |
vondear/RxTools | RxKit/src/main/java/com/tamsiree/rxkit/RxServiceTool.kt | 1 | 984 | package com.tamsiree.rxkit
import android.app.ActivityManager
import android.content.Context
/**
* @author tamsiree
* @date 2016/9/24
*/
object RxServiceTool {
/**
* 获取服务是否开启
*
* @param context 上下文
* @param className 完整包名的服务类名
* @return `true`: 是<br></br>`false`: 否
*/
@JvmStatic
fun isRunningService(context: Context, className: String): Boolean {
// 进程的管理者,活动的管理者
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
// 获取正在运行的服务,最多获取1000个
val runningServices = activityManager.getRunningServices(1000)
// 遍历集合
for (runningServiceInfo in runningServices) {
val service = runningServiceInfo.service
if (className == service.className) {
return true
}
}
return false
}
} | apache-2.0 | 9b475841ee057d6f0ea34c2377b08b76 | 25.636364 | 99 | 0.621868 | 4.221154 | false | false | false | false |
BilledTrain380/sporttag-psa | app/shared/src/main/kotlin/ch/schulealtendorf/psa/shared/rulebook/TargetThrowingRuleSet.kt | 1 | 3419 | /*
* Copyright (c) 2019 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.shared.rulebook
import ch.schulealtendorf.psa.dto.participation.GenderDto
import ch.schulealtendorf.psa.dto.participation.athletics.BALLZIELWURF
import ch.schulealtendorf.psa.shared.rulebook.rules.RuleSet
/**
* Defines all the rules that can be applied to a target throwing.
*
* @author nmaerchy
* @version 1.0.0
*/
class TargetThrowingRuleSet : RuleSet<FormulaModel, Int>() {
/**
* @return true if the rules of this rule set can be used, otherwise false
*/
override val whenever: (FormulaModel) -> Boolean = { it.discipline == BALLZIELWURF }
init {
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (4.4 * ((it - 0) pow 1.27)).toInt() }
override val whenever: (FormulaModel) -> Boolean =
{ it.gender == GenderDto.FEMALE && it.distance == "4m" }
}
)
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (5.3 * ((it - 0) pow 1.27)).toInt() }
override val whenever: (FormulaModel) -> Boolean =
{ it.gender == GenderDto.FEMALE && it.distance == "5m" }
}
)
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (4.3 * ((it - 0) pow 1.25)).toInt() }
override val whenever: (FormulaModel) -> Boolean =
{ it.gender == GenderDto.MALE && it.distance == "4m" }
}
)
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (5.3 * ((it - 0) pow 1.25)).toInt() }
override val whenever: (FormulaModel) -> Boolean =
{ it.gender == GenderDto.MALE && it.distance == "5m" }
}
)
}
}
| gpl-3.0 | bcc6f2b7e940613b9d8738a1c594e59e | 33.785714 | 95 | 0.628337 | 4.26125 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/talk/UserTalkPopupHelper.kt | 1 | 7171 | package org.wikipedia.talk
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.menu.MenuBuilder
import androidx.appcompat.view.menu.MenuPopupHelper
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.analytics.eventplatform.EditHistoryInteractionEvent
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.history.HistoryEntry
import org.wikipedia.page.ExclusiveBottomSheetPresenter
import org.wikipedia.page.Namespace
import org.wikipedia.page.PageActivity
import org.wikipedia.page.PageTitle
import org.wikipedia.page.linkpreview.LinkPreviewDialog
import org.wikipedia.staticdata.UserTalkAliasData
import org.wikipedia.usercontrib.UserContribListActivity
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.ResourceUtil
import org.wikipedia.util.log.L
@SuppressLint("RestrictedApi")
object UserTalkPopupHelper {
fun show(activity: AppCompatActivity, bottomSheetPresenter: ExclusiveBottomSheetPresenter,
title: PageTitle, anon: Boolean, anchorView: View,
invokeSource: Constants.InvokeSource, historySource: Int, revisionId: Long? = null, pageId: Int? = null) {
val pos = IntArray(2)
anchorView.getLocationInWindow(pos)
show(activity, bottomSheetPresenter, title, anon, pos[0], pos[1], invokeSource, historySource, revisionId = revisionId, pageId = pageId)
}
fun show(activity: AppCompatActivity, bottomSheetPresenter: ExclusiveBottomSheetPresenter,
title: PageTitle, anon: Boolean, x: Int, y: Int, invokeSource: Constants.InvokeSource,
historySource: Int, showContribs: Boolean = true, revisionId: Long? = null, pageId: Int? = null) {
if (title.namespace() == Namespace.USER_TALK || title.namespace() == Namespace.TALK) {
activity.startActivity(TalkTopicsActivity.newIntent(activity, title, invokeSource))
} else if (title.namespace() == Namespace.USER) {
val rootView = activity.window.decorView
val anchorView = View(activity)
anchorView.x = (x - rootView.left).toFloat()
anchorView.y = (y - rootView.top).toFloat()
(rootView as ViewGroup).addView(anchorView)
val helper = getPopupHelper(activity, title, anon, anchorView, invokeSource, historySource,
showContribs, revisionId = revisionId, pageId = pageId)
helper.setOnDismissListener {
rootView.removeView(anchorView)
}
helper.show()
} else {
bottomSheetPresenter.show(activity.supportFragmentManager,
LinkPreviewDialog.newInstance(HistoryEntry(title, historySource), null))
}
}
private fun showThankDialog(activity: Activity, title: PageTitle, revisionId: Long, pageId: Int) {
val parent = FrameLayout(activity)
val editHistoryInteractionEvent = EditHistoryInteractionEvent(title.wikiSite.dbName(), pageId)
val dialog =
AlertDialog.Builder(activity)
.setView(parent)
.setPositiveButton(R.string.thank_dialog_positive_button_text) { _, _ ->
sendThanks(activity, title.wikiSite, revisionId, title, editHistoryInteractionEvent)
}
.setNegativeButton(R.string.thank_dialog_negative_button_text) { _, _ ->
editHistoryInteractionEvent.logThankCancel()
}
.create()
dialog.layoutInflater.inflate(R.layout.view_thank_dialog, parent)
dialog.setOnShowListener {
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ResourceUtil.getThemedColor(activity, R.attr.secondary_text_color))
}
dialog.show()
}
private fun sendThanks(activity: Activity, wikiSite: WikiSite, revisionId: Long?, title: PageTitle,
editHistoryInteractionEvent: EditHistoryInteractionEvent) {
CoroutineScope(Dispatchers.Default).launch(CoroutineExceptionHandler { _, throwable ->
L.e(throwable)
editHistoryInteractionEvent.logThankFail()
}) {
val token = ServiceFactory.get(wikiSite).getToken().query?.csrfToken()
if (revisionId != null && token != null) {
ServiceFactory.get(wikiSite).postThanksToRevision(revisionId, token)
FeedbackUtil.showMessage(activity, activity.getString(R.string.thank_success_message, title.text))
editHistoryInteractionEvent.logThankSuccess()
}
}
}
private fun getPopupHelper(activity: Activity, title: PageTitle, anon: Boolean,
anchorView: View, invokeSource: Constants.InvokeSource,
historySource: Int, showContribs: Boolean = true,
revisionId: Long? = null, pageId: Int? = null): MenuPopupHelper {
val builder = MenuBuilder(activity)
activity.menuInflater.inflate(R.menu.menu_user_talk_popup, builder)
builder.setCallback(object : MenuBuilder.Callback {
override fun onMenuItemSelected(menu: MenuBuilder, item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_user_profile_page -> {
val entry = HistoryEntry(title, historySource)
activity.startActivity(PageActivity.newIntentForNewTab(activity, entry, title))
}
R.id.menu_user_talk_page -> {
val newTitle = PageTitle(UserTalkAliasData.valueFor(title.wikiSite.languageCode), title.text, title.wikiSite)
activity.startActivity(TalkTopicsActivity.newIntent(activity, newTitle, invokeSource))
}
R.id.menu_user_contributions_page -> {
activity.startActivity(UserContribListActivity.newIntent(activity, title.text))
}
R.id.menu_user_thank -> {
if (pageId != null && revisionId != null) {
showThankDialog(activity, title, revisionId, pageId)
}
}
}
return true
}
override fun onMenuModeChange(menu: MenuBuilder) { }
})
builder.findItem(R.id.menu_user_profile_page).isVisible = !anon
builder.findItem(R.id.menu_user_contributions_page).isVisible = showContribs
builder.findItem(R.id.menu_user_thank).isVisible = revisionId != null && !anon
val helper = MenuPopupHelper(activity, builder, anchorView)
helper.setForceShowIcon(true)
return helper
}
}
| apache-2.0 | 5f730a6f75e30bc4439a2b81f6e37a25 | 48.798611 | 144 | 0.661553 | 5.11119 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/cache/JsonCache.kt | 1 | 2324 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util.cache
import com.bumptech.glide.disklrucache.DiskLruCache
import de.vanita5.twittnuker.BuildConfig
import de.vanita5.twittnuker.util.DebugLog
import de.vanita5.twittnuker.util.JsonSerializer
import java.io.File
import java.io.IOException
class JsonCache(cacheDir: File) {
private val cache: DiskLruCache? by lazy {
try {
return@lazy DiskLruCache.open(cacheDir, BuildConfig.VERSION_CODE, 1, 100 * 1048576)
} catch (e: IOException) {
DebugLog.w(tr = e)
return@lazy null
}
}
fun <T> getList(key: String, cls: Class<T>): List<T>? {
val value = cache?.get(key) ?: return null
return try {
value.getFile(0)?.inputStream()?.use {
JsonSerializer.parseList(it, cls)
}
} catch (e: IOException) {
DebugLog.w(tr = e)
null
}
}
fun <T> saveList(key: String, list: List<T>?, cls: Class<T>) {
if (list == null) {
cache?.remove(key)
return
}
val editor = cache?.edit(key) ?: return
try {
editor.getFile(0)?.outputStream()?.use {
JsonSerializer.serialize(list, it, cls)
}
editor.commit()
} catch (e: IOException) {
DebugLog.w(tr = e)
} finally {
editor.abortUnlessCommitted()
}
}
} | gpl-3.0 | afc6070d9a27457781a84125099c048b | 30.849315 | 95 | 0.626076 | 4.062937 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/utils/ItemBuildingUtil.kt | 1 | 10221 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.utils
import com.google.common.collect.Multimap
import com.google.common.collect.MultimapBuilder
import com.tealcube.minecraft.bukkit.mythicdrops.MythicDropsPlugin
import com.tealcube.minecraft.bukkit.mythicdrops.api.MythicDrops
import com.tealcube.minecraft.bukkit.mythicdrops.api.enchantments.MythicEnchantment
import com.tealcube.minecraft.bukkit.mythicdrops.api.relations.Relation
import com.tealcube.minecraft.bukkit.mythicdrops.api.relations.RelationManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.tiers.Tier
import com.tealcube.minecraft.bukkit.mythicdrops.safeRandom
import com.tealcube.minecraft.bukkit.mythicdrops.stripColors
import io.pixeloutlaw.minecraft.spigot.hilt.getDisplayName
import org.bukkit.attribute.Attribute
import org.bukkit.attribute.AttributeModifier
import org.bukkit.enchantments.Enchantment
import org.bukkit.inventory.ItemStack
import kotlin.math.max
import kotlin.math.min
object ItemBuildingUtil {
private val mythicDrops: MythicDrops by lazy {
MythicDropsPlugin.getInstance()
}
private val spaceRegex = " ".toRegex()
fun getSafeEnchantments(
isSafe: Boolean,
enchantments: Collection<MythicEnchantment>,
itemStack: ItemStack
): Collection<MythicEnchantment> {
return enchantments.filter {
if (isSafe) {
it.enchantment.canEnchantItem(itemStack)
} else {
true
}
}
}
fun getBaseEnchantments(itemStack: ItemStack, tier: Tier): Map<Enchantment, Int> {
if (tier.enchantments.baseEnchantments.isEmpty()) {
return emptyMap()
}
val safeEnchantments = getSafeEnchantments(
tier.enchantments.isSafeBaseEnchantments,
tier.enchantments.baseEnchantments,
itemStack
)
return safeEnchantments.map { mythicEnchantment ->
val enchantment = mythicEnchantment.enchantment
val isAllowHighEnchantments = tier.enchantments.isAllowHighBaseEnchantments
val levelRange = getEnchantmentLevelRange(isAllowHighEnchantments, mythicEnchantment, enchantment)
when {
!tier.enchantments.isSafeBaseEnchantments -> enchantment to levelRange.safeRandom()
tier.enchantments.isAllowHighBaseEnchantments -> {
enchantment to levelRange.safeRandom()
}
else -> enchantment to getAcceptableEnchantmentLevel(
enchantment,
levelRange.safeRandom()
)
}
}.toMap()
}
fun getBonusEnchantments(itemStack: ItemStack, tier: Tier): Map<Enchantment, Int> {
if (tier.enchantments.bonusEnchantments.isEmpty()) {
return emptyMap()
}
val bonusEnchantmentsToAdd =
(tier.enchantments.minimumBonusEnchantments..tier.enchantments.maximumBonusEnchantments).random()
var tierBonusEnchantments =
getSafeEnchantments(
tier.enchantments.isSafeBonusEnchantments,
tier.enchantments.bonusEnchantments, itemStack
)
val bonusEnchantments = mutableMapOf<Enchantment, Int>()
repeat(bonusEnchantmentsToAdd) {
if (tierBonusEnchantments.isEmpty()) {
return@repeat
}
val mythicEnchantment = tierBonusEnchantments.random()
if (mythicDrops.settingsManager.configSettings.options.isOnlyRollBonusEnchantmentsOnce) {
tierBonusEnchantments -= mythicEnchantment
}
val enchantment = mythicEnchantment.enchantment
val randomizedLevelOfEnchantment =
bonusEnchantments[enchantment]?.let {
min(
mythicEnchantment.maximumLevel,
it + mythicEnchantment.getRandomLevel()
)
}
?: mythicEnchantment.getRandomLevel()
val trimmedLevel = if (!tier.enchantments.isAllowHighBonusEnchantments) {
getAcceptableEnchantmentLevel(enchantment, randomizedLevelOfEnchantment)
} else {
randomizedLevelOfEnchantment
}
bonusEnchantments[enchantment] = trimmedLevel
}
return bonusEnchantments.toMap()
}
fun getRelations(itemStack: ItemStack, relationManager: RelationManager): List<Relation> {
val name = itemStack.getDisplayName() ?: "" // empty string has no relations
return name.stripColors().split(spaceRegex).dropLastWhile { it.isEmpty() }
.mapNotNull { relationManager.getById(it) }
}
fun getRelationEnchantments(
itemStack: ItemStack,
tier: Tier,
relationManager: RelationManager
): Map<Enchantment, Int> {
val relationMythicEnchantments = getRelations(itemStack, relationManager).flatMap { it.enchantments }
val safeEnchantments =
getSafeEnchantments(tier.enchantments.isSafeRelationEnchantments, relationMythicEnchantments, itemStack)
if (safeEnchantments.isEmpty()) {
return emptyMap()
}
val relationEnchantments = mutableMapOf<Enchantment, Int>()
safeEnchantments.forEach { mythicEnchantment ->
val enchantment = mythicEnchantment.enchantment
val randomizedLevelOfEnchantment = relationEnchantments[enchantment]?.let {
min(
mythicEnchantment.maximumLevel,
it + mythicEnchantment.getRandomLevel()
)
} ?: mythicEnchantment.getRandomLevel()
val trimmedLevel = if (!tier.enchantments.isAllowHighRelationEnchantments) {
getAcceptableEnchantmentLevel(enchantment, randomizedLevelOfEnchantment)
} else {
randomizedLevelOfEnchantment
}
relationEnchantments[enchantment] = trimmedLevel
}
return relationEnchantments.toMap()
}
@Suppress("UnstableApiUsage")
fun getBaseAttributeModifiers(tier: Tier): Multimap<Attribute, AttributeModifier> {
val baseAttributeModifiers: Multimap<Attribute, AttributeModifier> =
MultimapBuilder.hashKeys().arrayListValues().build()
if (tier.attributes.baseAttributes.isEmpty()) {
return baseAttributeModifiers
}
tier.attributes.baseAttributes.forEach {
val (attribute, attributeModifier) = it.toAttributeModifier()
baseAttributeModifiers.put(attribute, attributeModifier)
}
return baseAttributeModifiers
}
@Suppress("UnstableApiUsage")
fun getBonusAttributeModifiers(tier: Tier): Multimap<Attribute, AttributeModifier> {
val bonusAttributeModifiers: Multimap<Attribute, AttributeModifier> =
MultimapBuilder.hashKeys().arrayListValues().build()
if (tier.attributes.bonusAttributes.isEmpty()) {
return bonusAttributeModifiers
}
val bonusAttributes = tier.attributes.bonusAttributes.toMutableSet()
val bonusAttributesToAdd =
(tier.attributes.minimumBonusAttributes..tier.attributes.maximumBonusAttributes).random()
repeat(bonusAttributesToAdd) {
if (bonusAttributes.isEmpty()) {
return@repeat
}
val mythicAttribute = bonusAttributes.random()
if (mythicDrops.settingsManager.configSettings.options.isOnlyRollBonusAttributesOnce) {
bonusAttributes -= mythicAttribute
}
val (attribute, attributeModifier) = mythicAttribute.toAttributeModifier()
bonusAttributeModifiers.put(attribute, attributeModifier)
}
return bonusAttributeModifiers
}
private fun getEnchantmentLevelRange(
isAllowHighEnchantments: Boolean,
mythicEnchantment: MythicEnchantment,
enchantment: Enchantment
): IntRange {
val minimumLevel = if (isAllowHighEnchantments) {
max(mythicEnchantment.minimumLevel.coerceAtLeast(1), enchantment.startLevel)
} else {
mythicEnchantment.minimumLevel.coerceAtLeast(1).coerceAtMost(enchantment.startLevel)
}
val maximumLevel = if (isAllowHighEnchantments) {
mythicEnchantment.maximumLevel.coerceAtLeast(1)
.coerceAtMost(MythicEnchantment.HIGHEST_ENCHANTMENT_LEVEL)
} else {
mythicEnchantment.maximumLevel.coerceAtLeast(1).coerceAtMost(enchantment.maxLevel)
}
// we need to do this calculation below because sometimes minimumLevel and maximumLevel can
// not match up :^)
return min(minimumLevel, maximumLevel)..max(minimumLevel, maximumLevel)
}
private fun getAcceptableEnchantmentLevel(enchantment: Enchantment, level: Int): Int =
level.coerceAtLeast(enchantment.startLevel).coerceAtMost(enchantment.maxLevel)
}
| mit | 501eb51207f4dd7213865ff3e9b524c2 | 44.426667 | 116 | 0.680364 | 5.665743 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/focus/RequestFocusTest.kt | 3 | 18379 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.focus
import androidx.compose.foundation.layout.Box
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusStateImpl.Active
import androidx.compose.ui.focus.FocusStateImpl.ActiveParent
import androidx.compose.ui.focus.FocusStateImpl.Captured
import androidx.compose.ui.focus.FocusStateImpl.Deactivated
import androidx.compose.ui.focus.FocusStateImpl.DeactivatedParent
import androidx.compose.ui.focus.FocusStateImpl.Inactive
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
class RequestFocusTest {
@get:Rule
val rule = createComposeRule()
@Test
fun active_isUnchanged() {
// Arrange.
val focusModifier = FocusModifier(Active)
rule.setFocusableContent {
Box(Modifier.focusTarget(focusModifier))
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(focusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun captured_isUnchanged() {
// Arrange.
val focusModifier = FocusModifier(Captured)
rule.setFocusableContent {
Box(Modifier.focusTarget(focusModifier))
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(focusModifier.focusState).isEqualTo(Captured)
}
}
@Test
fun deactivated_isUnchanged() {
// Arrange.
val focusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier
.focusProperties { canFocus = false }
.focusTarget(focusModifier)
)
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(focusModifier.focusState).isEqualTo(Deactivated)
}
}
@Test(expected = IllegalArgumentException::class)
fun activeParent_withNoFocusedChild_throwsException() {
// Arrange.
val focusModifier = FocusModifier(ActiveParent)
rule.setFocusableContent {
Box(Modifier.focusTarget(focusModifier))
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
}
@Test
fun activeParent_propagateFocus() {
// Arrange.
val focusModifier = FocusModifier(ActiveParent)
val childFocusModifier = FocusModifier(Active)
rule.setFocusableContent {
Box(Modifier.focusTarget(focusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
rule.runOnIdle {
focusModifier.focusedChild = childFocusModifier
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(focusModifier.focusState).isEqualTo(Active)
assertThat(focusModifier.focusedChild).isNull()
assertThat(childFocusModifier.focusState).isEqualTo(Inactive)
}
}
@Test(expected = IllegalArgumentException::class)
fun deactivatedParent_withNoFocusedChild_throwsException() {
// Arrange.
val focusModifier = FocusModifier(DeactivatedParent)
rule.setFocusableContent {
Box(Modifier.focusTarget(focusModifier))
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
}
@Test
fun deactivatedParent_propagateFocus() {
// Arrange.
val focusModifier = FocusModifier(ActiveParent)
val childFocusModifier = FocusModifier(Active)
rule.setFocusableContent {
Box(Modifier
.focusProperties { canFocus = false }
.focusTarget(focusModifier)
) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
rule.runOnIdle {
focusModifier.focusedChild = childFocusModifier
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
// Unchanged.
assertThat(focusModifier.focusState).isEqualTo(DeactivatedParent)
assertThat(childFocusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun deactivatedParent_activeChild_propagateFocus() {
// Arrange.
val focusModifier = FocusModifier(ActiveParent)
val childFocusModifier = FocusModifier(Active)
val grandchildFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier
.focusProperties { canFocus = false }
.focusTarget(focusModifier)
) {
Box(Modifier.focusTarget(childFocusModifier)) {
Box(Modifier.focusTarget(grandchildFocusModifier))
}
}
}
rule.runOnIdle {
focusModifier.focusedChild = childFocusModifier
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(focusModifier.focusState).isEqualTo(DeactivatedParent)
assertThat(childFocusModifier.focusState).isEqualTo(Active)
assertThat(childFocusModifier.focusedChild).isNull()
assertThat(grandchildFocusModifier.focusState).isEqualTo(Inactive)
}
}
@Test
fun inactiveRoot_propagateFocusSendsRequestToOwner_systemCanGrantFocus() {
// Arrange.
val rootFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(rootFocusModifier))
}
// Act.
rule.runOnIdle {
rootFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(rootFocusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun inactiveRootWithChildren_propagateFocusSendsRequestToOwner_systemCanGrantFocus() {
// Arrange.
val rootFocusModifier = FocusModifier(Inactive)
val childFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(rootFocusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
// Act.
rule.runOnIdle {
rootFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(rootFocusModifier.focusState).isEqualTo(Active)
assertThat(childFocusModifier.focusState).isEqualTo(Inactive)
}
}
@Test
fun inactiveNonRootWithChildren() {
// Arrange.
val parentFocusModifier = FocusModifier(Active)
val focusModifier = FocusModifier(Inactive)
val childFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(focusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(ActiveParent)
assertThat(focusModifier.focusState).isEqualTo(Active)
assertThat(childFocusModifier.focusState).isEqualTo(Inactive)
}
}
@Test
fun rootNode() {
// Arrange.
val rootFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(rootFocusModifier))
}
// Act.
rule.runOnIdle {
rootFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(rootFocusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun rootNodeWithChildren() {
// Arrange.
val rootFocusModifier = FocusModifier(Inactive)
val childFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(rootFocusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
// Act.
rule.runOnIdle {
rootFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(rootFocusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun parentNodeWithNoFocusedAncestor() {
// Arrange.
val grandParentFocusModifier = FocusModifier(Inactive)
val parentFocusModifier = FocusModifier(Inactive)
val childFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(grandParentFocusModifier)) {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
}
// Act.
rule.runOnIdle {
parentFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun parentNodeWithNoFocusedAncestor_childRequestsFocus() {
// Arrange.
val grandParentFocusModifier = FocusModifier(Inactive)
val parentFocusModifier = FocusModifier(Inactive)
val childFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(grandParentFocusModifier)) {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
}
// Act.
rule.runOnIdle {
childFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(ActiveParent)
}
}
@Test
fun childNodeWithNoFocusedAncestor() {
// Arrange.
val grandParentFocusModifier = FocusModifier(Inactive)
val parentFocusModifier = FocusModifier(Inactive)
val childFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(grandParentFocusModifier)) {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
}
// Act.
rule.runOnIdle {
childFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(childFocusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun requestFocus_parentIsFocused() {
// Arrange.
val parentFocusModifier = FocusModifier(Active)
val focusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(focusModifier))
}
}
// After executing requestFocus, siblingNode will be 'Active'.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(ActiveParent)
assertThat(focusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun requestFocus_childIsFocused() {
// Arrange.
val parentFocusModifier = FocusModifier(ActiveParent)
val focusModifier = FocusModifier(Active)
rule.setFocusableContent {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(focusModifier))
}
}
rule.runOnIdle {
parentFocusModifier.focusedChild = focusModifier
}
// Act.
rule.runOnIdle {
parentFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(Active)
assertThat(focusModifier.focusState).isEqualTo(Inactive)
}
}
@Test
fun requestFocus_childHasCapturedFocus() {
// Arrange.
val parentFocusModifier = FocusModifier(ActiveParent)
val focusModifier = FocusModifier(Captured)
rule.setFocusableContent {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(focusModifier))
}
}
rule.runOnIdle {
parentFocusModifier.focusedChild = focusModifier
}
// Act.
rule.runOnIdle {
parentFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(ActiveParent)
assertThat(focusModifier.focusState).isEqualTo(Captured)
}
}
@Test
fun requestFocus_siblingIsFocused() {
// Arrange.
val parentFocusModifier = FocusModifier(ActiveParent)
val focusModifier = FocusModifier(Inactive)
val siblingModifier = FocusModifier(Active)
rule.setFocusableContent {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(focusModifier))
Box(Modifier.focusTarget(siblingModifier))
}
}
rule.runOnIdle {
parentFocusModifier.focusedChild = siblingModifier
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(ActiveParent)
assertThat(focusModifier.focusState).isEqualTo(Active)
assertThat(siblingModifier.focusState).isEqualTo(Inactive)
}
}
@Test
fun requestFocus_siblingHasCapturedFocused() {
// Arrange.
val parentFocusModifier = FocusModifier(ActiveParent)
val focusModifier = FocusModifier(Inactive)
val siblingModifier = FocusModifier(Captured)
rule.setFocusableContent {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(focusModifier))
Box(Modifier.focusTarget(siblingModifier))
}
}
rule.runOnIdle {
parentFocusModifier.focusedChild = siblingModifier
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(ActiveParent)
assertThat(focusModifier.focusState).isEqualTo(Inactive)
assertThat(siblingModifier.focusState).isEqualTo(Captured)
}
}
@Test
fun requestFocus_cousinIsFocused() {
// Arrange.
val grandParentModifier = FocusModifier(ActiveParent)
val parentModifier = FocusModifier(Inactive)
val focusModifier = FocusModifier(Inactive)
val auntModifier = FocusModifier(ActiveParent)
val cousinModifier = FocusModifier(Active)
rule.setFocusableContent {
Box(Modifier.focusTarget(grandParentModifier)) {
Box(Modifier.focusTarget(parentModifier)) {
Box(Modifier.focusTarget(focusModifier))
}
Box(Modifier.focusTarget(auntModifier)) {
Box(Modifier.focusTarget(cousinModifier))
}
}
}
rule.runOnIdle {
grandParentModifier.focusedChild = auntModifier
auntModifier.focusedChild = cousinModifier
}
// Verify Setup.
rule.runOnIdle {
assertThat(cousinModifier.focusState).isEqualTo(Active)
assertThat(focusModifier.focusState).isEqualTo(Inactive)
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(cousinModifier.focusState).isEqualTo(Inactive)
assertThat(focusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun requestFocus_grandParentIsFocused() {
// Arrange.
val grandParentModifier = FocusModifier(Active)
val parentModifier = FocusModifier(Inactive)
val focusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(grandParentModifier)) {
Box(Modifier.focusTarget(parentModifier)) {
Box(Modifier.focusTarget(focusModifier))
}
}
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(grandParentModifier.focusState).isEqualTo(ActiveParent)
assertThat(parentModifier.focusState).isEqualTo(ActiveParent)
assertThat(focusModifier.focusState).isEqualTo(Active)
}
}
} | apache-2.0 | 957fa29fa8959afac2d7c564bdbb5777 | 29.380165 | 90 | 0.605528 | 5.864391 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/imageloader/ImageLoaderModule.kt | 2 | 3791 | package abi42_0_0.expo.modules.imageloader
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.AsyncTask
import androidx.annotation.NonNull
import androidx.annotation.Nullable
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.facebook.common.references.CloseableReference
import com.facebook.datasource.DataSource
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber
import com.facebook.imagepipeline.image.CloseableImage
import com.facebook.imagepipeline.request.ImageRequest
import abi42_0_0.expo.modules.interfaces.imageloader.ImageLoaderInterface
import abi42_0_0.org.unimodules.core.interfaces.InternalModule
import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
class ImageLoaderModule(val context: Context) : InternalModule, ImageLoaderInterface {
override fun getExportedInterfaces(): List<Class<*>>? {
return listOf(ImageLoaderInterface::class.java)
}
override fun loadImageForDisplayFromURL(url: String): Future<Bitmap> {
val future = SimpleSettableFuture<Bitmap>()
loadImageForDisplayFromURL(
url,
object : ImageLoaderInterface.ResultListener {
override fun onSuccess(bitmap: Bitmap) = future.set(bitmap)
override fun onFailure(@Nullable cause: Throwable?) = future.setException(ExecutionException(cause))
}
)
return future
}
override fun loadImageForDisplayFromURL(url: String, resultListener: ImageLoaderInterface.ResultListener) {
val imageRequest = ImageRequest.fromUri(url)
val imagePipeline = Fresco.getImagePipeline()
val dataSource = imagePipeline.fetchDecodedImage(imageRequest, context)
dataSource.subscribe(
object : BaseBitmapDataSubscriber() {
override fun onNewResultImpl(bitmap: Bitmap?) {
bitmap?.let {
resultListener.onSuccess(bitmap)
return
}
resultListener.onFailure(Exception("Loaded bitmap is null"))
}
override fun onFailureImpl(@NonNull dataSource: DataSource<CloseableReference<CloseableImage>>) {
resultListener.onFailure(dataSource.failureCause)
}
},
AsyncTask.THREAD_POOL_EXECUTOR
)
}
override fun loadImageForManipulationFromURL(@NonNull url: String): Future<Bitmap> {
val future = SimpleSettableFuture<Bitmap>()
loadImageForManipulationFromURL(
url,
object : ImageLoaderInterface.ResultListener {
override fun onSuccess(bitmap: Bitmap) = future.set(bitmap)
override fun onFailure(@NonNull cause: Throwable?) = future.setException(ExecutionException(cause))
}
)
return future
}
override fun loadImageForManipulationFromURL(url: String, resultListener: ImageLoaderInterface.ResultListener) {
val normalizedUrl = normalizeAssetsUrl(url)
Glide.with(context)
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.load(normalizedUrl)
.into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
resultListener.onSuccess(resource)
}
override fun onLoadFailed(errorDrawable: Drawable?) {
resultListener.onFailure(Exception("Loading bitmap failed"))
}
})
}
private fun normalizeAssetsUrl(url: String): String {
var actualUrl = url
if (url.startsWith("asset:///")) {
actualUrl = "file:///android_asset/" + url.split("/").last()
}
return actualUrl
}
}
| bsd-3-clause | a8b5bf207dc56f1519049256feb067be | 34.764151 | 114 | 0.739647 | 4.955556 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/parser/RustParserUtil.kt | 2 | 31559 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.parser
import com.intellij.lang.LighterASTNode
import com.intellij.lang.PsiBuilder
import com.intellij.lang.PsiBuilderUtil
import com.intellij.lang.WhitespacesAndCommentsBinder
import com.intellij.lang.parser.GeneratedParserUtilBase
import com.intellij.lexer.Lexer
import com.intellij.openapi.util.Key
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import com.intellij.util.BitUtil
import com.intellij.util.containers.Stack
import org.rust.lang.core.parser.RustParserDefinition.Companion.EOL_COMMENT
import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_BLOCK_DOC_COMMENT
import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_EOL_DOC_COMMENT
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.RsElementTypes.*
import org.rust.stdext.makeBitMask
import kotlin.math.max
@Suppress("UNUSED_PARAMETER")
object RustParserUtil : GeneratedParserUtilBase() {
enum class PathParsingMode {
/**
* Accepts paths like `Foo::<i32>`
* Should be used to parse references to values
*/
VALUE,
/**
* Accepts paths like `Foo<i32>`, `Foo::<i32>`, Fn(i32) -> i32 and Fn::(i32) -> i32
* Should be used to parse type and trait references
*/
TYPE,
/**
* Accepts paths like `Foo`
* Should be used to parse paths where type args cannot be specified: `use` items, macro calls, etc.
*/
NO_TYPE_ARGS
}
enum class TypeQualsMode { ON, OFF }
enum class StructLiteralsMode { ON, OFF }
/**
* Controls the difference between
*
* ```
* // bit and
* let _ = {1} & x;
* ```
* and
*
* ```
* // two statements: block expression {1} and unary reference expression &x
* {1} & x;
* ```
*
* See `Restrictions::RESTRICTION_STMT_EXPR` in libsyntax
*/
enum class StmtMode { ON, OFF }
enum class RestrictedConstExprMode { ON, OFF }
enum class ConditionMode { ON, OFF }
enum class MacroCallParsingMode(
val attrsAndVis: Boolean,
val semicolon: Boolean,
val pin: Boolean,
val forbidExprSpecialMacros: Boolean
) {
ITEM(attrsAndVis = false, semicolon = true, pin = true, forbidExprSpecialMacros = false),
BLOCK(attrsAndVis = true, semicolon = true, pin = false, forbidExprSpecialMacros = true),
EXPR(attrsAndVis = true, semicolon = false, pin = true, forbidExprSpecialMacros = false)
}
private val FLAGS: Key<Int> = Key("RustParserUtil.FLAGS")
private var PsiBuilder.flags: Int
get() = getUserData(FLAGS) ?: DEFAULT_FLAGS
set(value) = putUserData(FLAGS, value)
private val FLAG_STACK: Key<Stack<Int>> = Key("RustParserUtil.FLAG_STACK")
private var PsiBuilder.flagStack: Stack<Int>
get() = getUserData(FLAG_STACK) ?: Stack<Int>(0)
set(value) = putUserData(FLAG_STACK, value)
private fun PsiBuilder.pushFlag(flag: Int, mode: Boolean) {
val stack = flagStack
stack.push(flags)
flagStack = stack
flags = BitUtil.set(flags, flag, mode)
}
private fun PsiBuilder.pushFlags(vararg flagsAndValues: Pair<Int, Boolean>) {
val stack = flagStack
stack.push(flags)
flagStack = stack
for (flagAndValue in flagsAndValues) {
flags = BitUtil.set(flags, flagAndValue.first, flagAndValue.second)
}
}
private fun PsiBuilder.popFlag() {
flags = flagStack.pop()
}
private fun Int.setFlag(flag: Int, mode: Boolean): Int =
BitUtil.set(this, flag, mode)
private val STRUCT_ALLOWED: Int = makeBitMask(1)
private val TYPE_QUAL_ALLOWED: Int = makeBitMask(2)
private val STMT_EXPR_MODE: Int = makeBitMask(3)
private val PATH_MODE_VALUE: Int = makeBitMask(4)
private val PATH_MODE_TYPE: Int = makeBitMask(5)
private val PATH_MODE_NO_TYPE_ARGS: Int = makeBitMask(6)
private val MACRO_BRACE_PARENS: Int = makeBitMask(7)
private val MACRO_BRACE_BRACKS: Int = makeBitMask(8)
private val MACRO_BRACE_BRACES: Int = makeBitMask(9)
private val RESTRICTED_CONST_EXPR_MODE: Int = makeBitMask(10)
private val CONDITION_MODE: Int = makeBitMask(11)
private fun setPathMod(flags: Int, mode: PathParsingMode): Int {
val flag = when (mode) {
PathParsingMode.VALUE -> PATH_MODE_VALUE
PathParsingMode.TYPE -> PATH_MODE_TYPE
PathParsingMode.NO_TYPE_ARGS -> PATH_MODE_NO_TYPE_ARGS
}
return flags and (PATH_MODE_VALUE or PATH_MODE_TYPE or PATH_MODE_NO_TYPE_ARGS).inv() or flag
}
private fun getPathMod(flags: Int): PathParsingMode = when {
BitUtil.isSet(flags, PATH_MODE_VALUE) -> PathParsingMode.VALUE
BitUtil.isSet(flags, PATH_MODE_TYPE) -> PathParsingMode.TYPE
BitUtil.isSet(flags, PATH_MODE_NO_TYPE_ARGS) -> PathParsingMode.NO_TYPE_ARGS
else -> error("Path parsing mode not set")
}
private fun setMacroBraces(flags: Int, mode: MacroBraces): Int {
val flag = when (mode) {
MacroBraces.PARENS -> MACRO_BRACE_PARENS
MacroBraces.BRACKS -> MACRO_BRACE_BRACKS
MacroBraces.BRACES -> MACRO_BRACE_BRACES
}
return flags and (MACRO_BRACE_PARENS or MACRO_BRACE_BRACKS or MACRO_BRACE_BRACES).inv() or flag
}
private fun getMacroBraces(flags: Int): MacroBraces? = when {
BitUtil.isSet(flags, MACRO_BRACE_PARENS) -> MacroBraces.PARENS
BitUtil.isSet(flags, MACRO_BRACE_BRACKS) -> MacroBraces.BRACKS
BitUtil.isSet(flags, MACRO_BRACE_BRACES) -> MacroBraces.BRACES
else -> null
}
private val DEFAULT_FLAGS: Int = STRUCT_ALLOWED or TYPE_QUAL_ALLOWED
@JvmField
val ADJACENT_LINE_COMMENTS = WhitespacesAndCommentsBinder { tokens, _, getter ->
var candidate = tokens.size
for (i in 0 until tokens.size) {
val token = tokens[i]
if (OUTER_BLOCK_DOC_COMMENT == token || OUTER_EOL_DOC_COMMENT == token) {
candidate = minOf(candidate, i)
break
}
if (EOL_COMMENT == token) {
candidate = minOf(candidate, i)
}
if (TokenType.WHITE_SPACE == token && "\n\n" in getter[i]) {
candidate = tokens.size
}
}
candidate
}
private val LEFT_BRACES = tokenSetOf(LPAREN, LBRACE, LBRACK)
private val RIGHT_BRACES = tokenSetOf(RPAREN, RBRACE, RBRACK)
//
// Helpers
//
@JvmStatic
fun checkStructAllowed(b: PsiBuilder, level: Int): Boolean = BitUtil.isSet(b.flags, STRUCT_ALLOWED)
@JvmStatic
fun checkTypeQualAllowed(b: PsiBuilder, level: Int): Boolean = BitUtil.isSet(b.flags, TYPE_QUAL_ALLOWED)
@JvmStatic
fun checkBraceAllowed(b: PsiBuilder, level: Int): Boolean =
b.tokenType != LBRACE || checkStructAllowed(b, level)
@JvmStatic
fun checkGtAllowed(b: PsiBuilder, level: Int): Boolean =
!BitUtil.isSet(b.flags, RESTRICTED_CONST_EXPR_MODE)
@JvmStatic
fun checkLetExprAllowed(b: PsiBuilder, level: Int): Boolean =
BitUtil.isSet(b.flags, CONDITION_MODE)
@JvmStatic
fun withRestrictedConstExprMode(b: PsiBuilder, level: Int, mode: RestrictedConstExprMode, parser: Parser): Boolean {
val oldFlags = b.flags
val newFlags = oldFlags.setFlag(RESTRICTED_CONST_EXPR_MODE, mode == RestrictedConstExprMode.ON)
b.flags = newFlags
val result = parser.parse(b, level)
b.flags = oldFlags
return result
}
@JvmStatic
fun withConditionMode(b: PsiBuilder, level: Int, mode: ConditionMode, parser: Parser): Boolean {
val oldFlags = b.flags
val newFlags = oldFlags.setFlag(CONDITION_MODE, mode == ConditionMode.ON)
b.flags = newFlags
val result = parser.parse(b, level)
b.flags = oldFlags
return result
}
@JvmStatic
fun enterBlockExpr(b: PsiBuilder, level: Int, parser: Parser): Boolean {
val oldFlags = b.flags
val newFlags = oldFlags
.setFlag(RESTRICTED_CONST_EXPR_MODE, false)
.setFlag(CONDITION_MODE, false)
b.flags = newFlags
val result = parser.parse(b, level)
b.flags = oldFlags
return result
}
@JvmStatic
fun setStmtMode(b: PsiBuilder, level: Int, mode: StmtMode): Boolean {
b.pushFlag(STMT_EXPR_MODE, mode == StmtMode.ON)
return true
}
@JvmStatic
fun setLambdaExprMode(b: PsiBuilder, level: Int): Boolean {
b.pushFlags(
STMT_EXPR_MODE to false,
CONDITION_MODE to false
)
return true
}
@JvmStatic
fun resetFlags(b: PsiBuilder, level: Int): Boolean {
b.popFlag()
return true
}
@JvmStatic
fun exprMode(
b: PsiBuilder,
level: Int,
structLiterals: StructLiteralsMode,
stmtMode: StmtMode,
parser: Parser
): Boolean {
val oldFlags = b.flags
val newFlags = oldFlags
.setFlag(STRUCT_ALLOWED, structLiterals == StructLiteralsMode.ON)
.setFlag(STMT_EXPR_MODE, stmtMode == StmtMode.ON)
b.flags = newFlags
val result = parser.parse(b, level)
b.flags = oldFlags
return result
}
@JvmStatic
fun isCompleteBlockExpr(b: PsiBuilder, level: Int): Boolean =
isBlock(b, level) && BitUtil.isSet(b.flags, STMT_EXPR_MODE)
@JvmStatic
fun isIncompleteBlockExpr(b: PsiBuilder, level: Int): Boolean =
!isCompleteBlockExpr(b, level)
@JvmStatic
fun isBlock(b: PsiBuilder, level: Int): Boolean {
val m = b.latestDoneMarker ?: return false
return m.tokenType in RS_BLOCK_LIKE_EXPRESSIONS || m.isBracedMacro(b)
}
@JvmStatic
fun pathMode(b: PsiBuilder, level: Int, mode: PathParsingMode, typeQualsMode: TypeQualsMode, parser: Parser): Boolean {
val oldFlags = b.flags
val newFlags = setPathMod(BitUtil.set(oldFlags, TYPE_QUAL_ALLOWED, typeQualsMode == TypeQualsMode.ON), mode)
b.flags = newFlags
check(getPathMod(b.flags) == mode)
// A hack that reduces the growth rate of `level`. This actually allows a deeper path nesting.
val prevPathFrame = ErrorState.get(b).currentFrame?.parentFrame?.ancestorOfTypeOrSelf(PATH)
val nextLevel = if (prevPathFrame != null) {
max(prevPathFrame.level + 2, level - 9)
} else {
level
}
val result = parser.parse(b, nextLevel)
b.flags = oldFlags
return result
}
@JvmStatic
fun isPathMode(b: PsiBuilder, level: Int, mode: PathParsingMode): Boolean =
mode == getPathMod(b.flags)
/**
* `FLOAT_LITERAL` is never produced during lexing. We construct it during parsing from one or
* several `INTEGER_LITERAL` tokens. We need this in order to support nested tuple fields
* access syntax (see https://github.com/intellij-rust/intellij-rust/issues/6029)
*
* Here we collapse these sequences of tokes:
* 1. `INTEGER_LITERAL`, `DOT`, `INTEGER_LITERAL`. Like `0.0`
* 2. `INTEGER_LITERAL`, `DOT` (but **not** `INTEGER_LITERAL`, `DOT`, `IDENTIFIER`). Like `0.`
* 3. Single `INTEGER_LITERAL`, if it has float suffix (`f32`/`f64`) or scientific suffix (`1e3`, `3e-4`)
*/
@JvmStatic
fun parseFloatLiteral(b: PsiBuilder, level: Int): Boolean {
return when (b.tokenType) {
INTEGER_LITERAL -> {
// Works with `0.0`, `0.`, but not `0.foo` (identifier is not accepted after `.`)
if (b.rawLookup(1) == DOT) {
val (collapse, size) = when (b.rawLookup(2)) {
INTEGER_LITERAL, FLOAT_LITERAL -> true to 3
IDENTIFIER -> false to 0
else -> true to 2
}
if (collapse) {
val marker = b.mark()
PsiBuilderUtil.advance(b, size)
marker.collapse(FLOAT_LITERAL)
return true
}
}
// Works with floats without `.` like `1f32`, `1e3`, `3e-4`
val text = b.tokenText
val isFloat = text != null &&
(text.contains("f") || text.contains("e", ignoreCase = true) && !text.endsWith("e"))
&& !text.startsWith("0x")
if (isFloat) {
b.remapCurrentToken(FLOAT_LITERAL)
b.advanceLexer()
}
isFloat
}
// Can be already remapped
FLOAT_LITERAL -> {
b.advanceLexer()
true
}
else -> false
}
}
// !("union" identifier | "async" fn) identifier | self | super | 'Self' | crate
@JvmStatic
fun parsePathIdent(b: PsiBuilder, level: Int): Boolean {
val tokenType = b.tokenType
val result = when (tokenType) {
SELF, SUPER, CSELF, CRATE -> true
IDENTIFIER -> {
val tokenText = b.tokenText
!(tokenText == "union" && b.lookAhead(1) == IDENTIFIER || tokenText == "async" && b.lookAhead(1) == FN)
}
else -> {
// error message
val consumed = consumeToken(b, IDENTIFIER)
check(!consumed)
false
}
}
if (result) {
consumeToken(b, tokenType)
}
return result
}
@JvmStatic
fun unpairedToken(b: PsiBuilder, level: Int): Boolean =
when (b.tokenType) {
LBRACE, RBRACE,
LPAREN, RPAREN,
LBRACK, RBRACK -> false
null -> false // EOF
else -> {
collapsedTokenType(b)?.let { (tokenType, size) ->
val marker = b.mark()
PsiBuilderUtil.advance(b, size)
marker.collapse(tokenType)
} ?: b.advanceLexer()
true
}
}
@JvmStatic
fun macroBindingGroupSeparatorToken(b: PsiBuilder, level: Int): Boolean =
when (b.tokenType) {
PLUS, MUL, Q -> false
else -> unpairedToken(b, level)
}
@JvmStatic
fun macroSemicolon(b: PsiBuilder, level: Int): Boolean {
val m = b.latestDoneMarker ?: return false
b.tokenText
if (b.originalText[m.endOffset - b.offset - 1] == '}') return true
return consumeToken(b, SEMICOLON)
}
@JvmStatic
fun macroIdentifier(b: PsiBuilder, level: Int): Boolean =
when (b.tokenType) {
IDENTIFIER, in RS_KEYWORDS, BOOL_LITERAL -> {
b.advanceLexer()
true
}
else -> false
}
@JvmStatic
fun pathOrTraitType(
b: PsiBuilder,
level: Int,
pathP: Parser,
implicitTraitTypeP: Parser,
traitTypeUpperP: Parser
): Boolean {
val pathOrTraitType = enter_section_(b)
val polybound = enter_section_(b)
val bound = enter_section_(b)
val traitRef = enter_section_(b)
if (!pathP.parse(b, level) || nextTokenIs(b, EXCL)) {
// May be it is lifetime `'a` or `for<'a>` or `foo!()`
exit_section_(b, traitRef, null, false)
exit_section_(b, bound, null, false)
exit_section_(b, polybound, null, false)
exit_section_(b, pathOrTraitType, null, false)
return implicitTraitTypeP.parse(b, level)
}
if (!nextTokenIs(b, PLUS)) {
exit_section_(b, traitRef, null, true)
exit_section_(b, bound, null, true)
exit_section_(b, polybound, null, true)
exit_section_(b, pathOrTraitType, PATH_TYPE, true)
return true
}
exit_section_(b, traitRef, TRAIT_REF, true)
exit_section_(b, bound, BOUND, true)
exit_section_(b, polybound, POLYBOUND, true)
val result = traitTypeUpperP.parse(b, level)
exit_section_(b, pathOrTraitType, TRAIT_TYPE, result)
return result
}
@Suppress("DuplicatedCode")
@JvmStatic
fun typeReferenceOrAssocTypeBinding(
b: PsiBuilder,
level: Int,
pathP: Parser,
assocTypeBindingUpperP: Parser,
typeReferenceP: Parser,
traitTypeUpperP: Parser,
): Boolean {
if (b.tokenType == DYN || b.tokenType == IDENTIFIER && b.tokenText == "dyn" && b.lookAhead(1) != EXCL) {
return typeReferenceP.parse(b, level)
}
val typeOrAssoc = enter_section_(b)
val polybound = enter_section_(b)
val bound = enter_section_(b)
val traitRef = enter_section_(b)
if (!pathP.parse(b, level) || nextTokenIsFast(b, EXCL)) {
exit_section_(b, traitRef, null, false)
exit_section_(b, bound, null, false)
exit_section_(b, polybound, null, false)
exit_section_(b, typeOrAssoc, null, false)
return typeReferenceP.parse(b, level)
}
if (nextTokenIsFast(b, PLUS) ) {
exit_section_(b, traitRef, TRAIT_REF, true)
exit_section_(b, bound, BOUND, true)
exit_section_(b, polybound, POLYBOUND, true)
val result = traitTypeUpperP.parse(b, level)
exit_section_(b, typeOrAssoc, TRAIT_TYPE, result)
return result
}
exit_section_(b, traitRef, null, true)
exit_section_(b, bound, null, true)
exit_section_(b, polybound, null, true)
if (!nextTokenIsFast(b, EQ) && !nextTokenIsFast(b, COLON)) {
exit_section_(b, typeOrAssoc, PATH_TYPE, true)
return true
}
val result = assocTypeBindingUpperP.parse(b, level)
exit_section_(b, typeOrAssoc, ASSOC_TYPE_BINDING, result)
return result
}
private val SPECIAL_MACRO_PARSERS: Map<String, (PsiBuilder, Int) -> Boolean>
private val SPECIAL_EXPR_MACROS: Set<String>
init {
val specialParsers = hashMapOf<String, (PsiBuilder, Int) -> Boolean>()
val exprMacros = hashSetOf<String>()
SPECIAL_MACRO_PARSERS = specialParsers
SPECIAL_EXPR_MACROS = exprMacros
fun put(parser: (PsiBuilder, Int) -> Boolean, isExpr: Boolean, vararg keys: String) {
for (name in keys) {
check(name !in specialParsers) { "$name was already added" }
specialParsers[name] = parser
if (isExpr) {
exprMacros += name
}
}
}
put(RustParser::ExprMacroArgument, true, "dbg")
put(
RustParser::FormatMacroArgument, true, "format", "format_args", "format_args_nl", "write", "writeln",
"print", "println", "eprint", "eprintln", "panic", "unimplemented", "unreachable", "todo"
)
put(
RustParser::AssertMacroArgument, true, "assert", "debug_assert", "assert_eq", "assert_ne",
"debug_assert_eq", "debug_assert_ne"
)
put(RustParser::VecMacroArgument, true, "vec")
put(RustParser::IncludeMacroArgument, true, "include_str", "include_bytes")
put(RustParser::IncludeMacroArgument, false, "include")
put(RustParser::ConcatMacroArgument, true, "concat")
put(RustParser::EnvMacroArgument, true, "env")
put(RustParser::AsmMacroArgument, true, "asm")
}
fun isSpecialMacro(name: String): Boolean =
name in SPECIAL_MACRO_PARSERS
@JvmStatic
fun parseMacroCall(b: PsiBuilder, level: Int, mode: MacroCallParsingMode): Boolean {
if (mode.attrsAndVis && !RustParser.AttrsAndVis(b, level + 1)) return false
if (!RustParser.PathWithoutTypeArgs(b, level + 1) || !consumeToken(b, EXCL)) {
return false
}
val macroName = getMacroName(b, -2)
if (mode.forbidExprSpecialMacros && macroName in SPECIAL_EXPR_MACROS) return false
// foo! bar {}
// ^ this ident
val hasIdent = consumeTokenFast(b, IDENTIFIER)
val braceKind = b.tokenType?.let { MacroBraces.fromToken(it) }
if (macroName != null && !hasIdent && braceKind != null) { // try special macro
val specialParser = SPECIAL_MACRO_PARSERS[macroName]
if (specialParser != null && specialParser(b, level + 1)) {
if (braceKind.needsSemicolon && mode.semicolon && !consumeToken(b, SEMICOLON)) {
b.error("`;` expected, got '${b.tokenText}'")
return mode.pin
}
return true
}
}
if (braceKind == null || !parseMacroArgumentLazy(b, level + 1)) {
b.error("<macro argument> expected, got '${b.tokenText}'")
return mode.pin
}
if (braceKind.needsSemicolon && mode.semicolon && !consumeToken(b, SEMICOLON)) {
b.error("`;` expected, got '${b.tokenText}'")
return mode.pin
}
return true
}
// qualifier::foo ! ();
// ^ this name
@Suppress("SameParameterValue")
private fun getMacroName(b: PsiBuilder, nameTokenIndex: Int): String? {
require(nameTokenIndex < 0) {
"`getMacroName` assumes that path with macro name is already parsed and the name token is behind of current position"
}
var steps = 0
var meaningfulSteps = 0
while (meaningfulSteps > nameTokenIndex) {
steps--
val elementType = b.rawLookup(steps) ?: return null
if (!isWhitespaceOrComment(b, elementType)) {
meaningfulSteps--
}
}
return if (b.rawLookup(steps) == IDENTIFIER) {
b.rawLookupText(steps).toString()
} else {
null
}
}
@JvmStatic
fun gtgteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, GTGTEQ, GT, GT, EQ)
@JvmStatic
fun gtgtImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, GTGT, GT, GT)
@JvmStatic
fun gteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, GTEQ, GT, EQ)
@JvmStatic
fun ltlteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, LTLTEQ, LT, LT, EQ)
@JvmStatic
fun ltltImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, LTLT, LT, LT)
@JvmStatic
fun lteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, LTEQ, LT, EQ)
@JvmStatic
fun ororImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, OROR, OR, OR)
@JvmStatic
fun andandImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, ANDAND, AND, AND)
private val DEFAULT_NEXT_ELEMENTS: TokenSet = tokenSetOf(EXCL)
private val ASYNC_NEXT_ELEMENTS: TokenSet = tokenSetOf(LBRACE, MOVE, OR)
private val TRY_NEXT_ELEMENTS: TokenSet = tokenSetOf(LBRACE)
@JvmStatic
fun defaultKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeyword(b, "default", DEFAULT)
@JvmStatic
fun unionKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeyword(b, "union", UNION)
@JvmStatic
fun autoKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeyword(b, "auto", AUTO)
@JvmStatic
fun dynKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeyword(b, "dyn", DYN)
@JvmStatic
fun asyncKeyword(b: PsiBuilder, level: Int): Boolean =
contextualKeyword(b, "async", ASYNC)
@JvmStatic
fun asyncBlockKeyword(b: PsiBuilder, level: Int): Boolean =
contextualKeyword(b, "async", ASYNC) { it in ASYNC_NEXT_ELEMENTS }
@JvmStatic
fun tryKeyword(b: PsiBuilder, level: Int): Boolean =
contextualKeyword(b, "try", TRY) { it in TRY_NEXT_ELEMENTS }
@JvmStatic
fun rawKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeywordWithRollback(b, "raw", RAW)
@JvmStatic
private fun collapse(b: PsiBuilder, tokenType: IElementType, vararg parts: IElementType): Boolean {
// We do not want whitespace between parts, so firstly we do raw lookup for each part,
// and when we make sure that we have desired token, we consume and collapse it.
parts.forEachIndexed { i, tt ->
if (b.rawLookup(i) != tt) return false
}
val marker = b.mark()
PsiBuilderUtil.advance(b, parts.size)
marker.collapse(tokenType)
return true
}
/** Collapses contextual tokens (like &&) to a single token */
fun collapsedTokenType(b: PsiBuilder): Pair<IElementType, Int>? {
return when (b.tokenType) {
GT -> when (b.rawLookup(1)) {
GT -> when (b.rawLookup(2)) {
EQ -> GTGTEQ to 3
else -> GTGT to 2
}
EQ -> GTEQ to 2
else -> null
}
LT -> when (b.rawLookup(1)) {
LT -> when (b.rawLookup(2)) {
EQ -> LTLTEQ to 3
else -> LTLT to 2
}
EQ -> LTEQ to 2
else -> null
}
OR -> when (b.rawLookup(1)) {
OR -> OROR to 2
else -> null
}
AND -> when (b.rawLookup(1)) {
AND -> ANDAND to 2
else -> null
}
// See `parseFloatLiteral`
INTEGER_LITERAL -> when (b.rawLookup(1)) {
DOT -> when (b.rawLookup(2)) {
INTEGER_LITERAL, FLOAT_LITERAL -> FLOAT_LITERAL to 3
IDENTIFIER -> null
else -> FLOAT_LITERAL to 2
}
else -> null
}
else -> null
}
}
private fun LighterASTNode.isBracedMacro(b: PsiBuilder): Boolean {
if (tokenType != MACRO_EXPR) return false
val offset = b.offset
val text = b.originalText.subSequence(startOffset - offset, endOffset - offset)
return '}' == text.findLast { it == '}' || it == ']' || it == ')' }
}
/**
* Non-zero if [PsiBuilder] is created with `LighterLazyParseableNode` chameleon.
* (Used this way in implementations of ILightLazyParseableElementType)
*/
private val PsiBuilder.offset: Int
get() {
val firstMarker = (this as Builder).productions?.firstOrNull() ?: return 0
return firstMarker.startOffset
}
private fun contextualKeyword(
b: PsiBuilder,
keyword: String,
elementType: IElementType,
nextElementPredicate: (IElementType?) -> Boolean = { it !in DEFAULT_NEXT_ELEMENTS }
): Boolean {
// Tricky: the token can be already remapped by some previous rule that was backtracked
if (b.tokenType == elementType ||
b.tokenType == IDENTIFIER && b.tokenText == keyword && nextElementPredicate(b.lookAhead(1))) {
b.remapCurrentToken(elementType)
b.advanceLexer()
return true
}
return false
}
private fun contextualKeywordWithRollback(b: PsiBuilder, keyword: String, elementType: IElementType): Boolean {
if (b.tokenType == IDENTIFIER && b.tokenText == keyword) {
val marker = b.mark()
b.advanceLexer()
marker.collapse(elementType)
return true
}
return false
}
@JvmStatic
fun parseMacroArgumentLazy(builder: PsiBuilder, level: Int): Boolean =
parseTokenTreeLazy(builder, level, MACRO_ARGUMENT)
@JvmStatic
fun parseMacroBodyLazy(builder: PsiBuilder, level: Int): Boolean =
parseTokenTreeLazy(builder, level, MACRO_BODY)
@JvmStatic
fun parseTokenTreeLazy(builder: PsiBuilder, level: Int, tokenTypeToCollapse: IElementType): Boolean {
val firstToken = builder.tokenType
if (firstToken == null || firstToken !in LEFT_BRACES) return false
val rightBrace = MacroBraces.fromTokenOrFail(firstToken).closeToken
PsiBuilderUtil.parseBlockLazy(builder, firstToken, rightBrace, tokenTypeToCollapse)
return true
}
fun hasProperTokenTreeBraceBalance(text: CharSequence, lexer: Lexer): Boolean {
lexer.start(text)
val firstToken = lexer.tokenType
if (firstToken == null || firstToken !in LEFT_BRACES) return false
val rightBrace = MacroBraces.fromTokenOrFail(firstToken).closeToken
return PsiBuilderUtil.hasProperBraceBalance(text, lexer, firstToken, rightBrace)
}
@JvmStatic
fun parseAnyBraces(b: PsiBuilder, level: Int, param: Parser): Boolean {
val firstToken = b.tokenType ?: return false
if (firstToken !in LEFT_BRACES) return false
val leftBrace = MacroBraces.fromTokenOrFail(firstToken)
val pos = b.mark()
b.advanceLexer() // Consume '{' or '(' or '['
return b.withRootBrace(leftBrace) { rootBrace ->
if (!param.parse(b, level + 1)) {
pos.rollbackTo()
return false
}
val lastToken = b.tokenType
if (lastToken == null || lastToken !in RIGHT_BRACES) {
b.error("'${leftBrace.closeText}' expected")
return pos.close(lastToken == null)
}
var rightBrace = MacroBraces.fromToken(lastToken)
if (rightBrace == leftBrace) {
b.advanceLexer() // Consume '}' or ')' or ']'
} else {
b.error("'${leftBrace.closeText}' expected")
if (leftBrace == rootBrace) {
// Recovery loop. Consume everything until [rightBrace] is [leftBrace]
while (rightBrace != leftBrace && !b.eof()) {
b.advanceLexer()
val tokenType = b.tokenType ?: break
rightBrace = MacroBraces.fromToken(tokenType)
}
b.advanceLexer()
}
}
pos.drop()
return true
}
}
/** Saves [currentBrace] as root brace if it is not set yet; applies the root brace to [f] */
private inline fun PsiBuilder.withRootBrace(currentBrace: MacroBraces, f: (MacroBraces) -> Boolean): Boolean {
val oldFlags = flags
val oldRootBrace = getMacroBraces(oldFlags)
if (oldRootBrace == null) {
flags = setMacroBraces(oldFlags, currentBrace)
}
try {
return f(oldRootBrace ?: currentBrace)
} finally {
flags = oldFlags
}
}
@JvmStatic
fun parseCodeBlockLazy(builder: PsiBuilder, level: Int): Boolean {
return PsiBuilderUtil.parseBlockLazy(builder, LBRACE, RBRACE, BLOCK) != null
}
@JvmStatic
fun parseSimplePat(builder: PsiBuilder): Boolean {
return RustParser.SimplePat(builder, 0)
}
private tailrec fun Frame.ancestorOfTypeOrSelf(elementType: IElementType): Frame? {
return if (this.elementType == elementType) {
this
} else {
parentFrame?.ancestorOfTypeOrSelf(elementType)
}
}
}
| mit | 2f83b116b18be74a831f1282431bab7d | 34.8625 | 129 | 0.586267 | 4.354167 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.