repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JetBrains/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/TableUtils.kt | 1 | 7357 | // 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.intellij.plugins.markdown.editor.tables
import com.intellij.application.options.CodeStyle
import com.intellij.openapi.editor.Document
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiUtilCore
import com.intellij.psi.util.parentOfType
import com.intellij.psi.util.parents
import com.intellij.psi.util.siblings
import com.intellij.refactoring.suggested.startOffset
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTable
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableCell
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableRow
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableSeparatorRow
import org.intellij.plugins.markdown.lang.psi.util.hasType
import org.intellij.plugins.markdown.settings.MarkdownSettings
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Experimental
object TableUtils {
@JvmStatic
fun findCell(file: PsiFile, offset: Int): MarkdownTableCell? {
val element = PsiUtilCore.getElementAtOffset(file, offset)
if (element.hasType(MarkdownTokenTypes.TABLE_SEPARATOR) && element !is MarkdownTableSeparatorRow &&
element.text == TableProps.SEPARATOR_CHAR.toString()) {
return element.prevSibling as? MarkdownTableCell
}
return findCell(element)
}
@JvmStatic
fun findCell(element: PsiElement): MarkdownTableCell? {
return element.parentOfType(withSelf = true)
}
@JvmStatic
fun findTable(file: PsiFile, offset: Int): MarkdownTable? {
val element = PsiUtilCore.getElementAtOffset(file, offset)
return findTable(element)
}
@JvmStatic
fun findTable(element: PsiElement): MarkdownTable? {
return element.parentOfType(withSelf = true)
}
@JvmStatic
fun findSeparatorRow(file: PsiFile, offset: Int): MarkdownTableSeparatorRow? {
val element = PsiUtilCore.getElementAtOffset(file, offset)
return findSeparatorRow(element)
}
@JvmStatic
fun findSeparatorRow(element: PsiElement): MarkdownTableSeparatorRow? {
return element.parentOfType(withSelf = true)
}
@JvmStatic
fun findRow(file: PsiFile, offset: Int): MarkdownTableRow? {
val element = PsiUtilCore.getElementAtOffset(file, offset)
return findRow(element)
}
@JvmStatic
fun findRow(element: PsiElement): MarkdownTableRow? {
return element.parentOfType(withSelf = true)
}
@JvmStatic
fun findRowOrSeparator(file: PsiFile, offset: Int): PsiElement? {
val row = findRow(file, offset)
return row ?: findSeparatorRow(file, offset)
}
@JvmStatic
fun findRowOrSeparator(element: PsiElement): PsiElement? {
return findRow(element) ?: findSeparatorRow(element)
}
/**
* Find cell index for content or separator cells.
*/
@JvmStatic
fun findCellIndex(file: PsiFile, offset: Int): Int? {
val element = PsiUtilCore.getElementAtOffset(file, offset)
if (element.hasType(MarkdownTokenTypes.TABLE_SEPARATOR) && element !is MarkdownTableSeparatorRow &&
element.text == TableProps.SEPARATOR_CHAR.toString()) {
return (element.prevSibling as? MarkdownTableCell)?.columnIndex
}
val parent = element.parents(withSelf = true).find {
it.hasType(MarkdownElementTypes.TABLE_CELL) || it is MarkdownTableSeparatorRow
}
return when (parent) {
is MarkdownTableSeparatorRow -> parent.getColumnIndexFromOffset(offset)
is MarkdownTableCell -> parent.columnIndex
else -> null
}
}
fun MarkdownTable.getColumnCells(index: Int, withHeader: Boolean = true): List<MarkdownTableCell> {
return getRows(withHeader).mapNotNull { it.getCell(index) }
}
fun MarkdownTable.getColumnTextRanges(index: Int): List<TextRange> {
val cells = getColumnCells(index, withHeader = true).map { it.textRange }
val result = ArrayList<TextRange>(cells.size + 1)
result.addAll(cells)
separatorRow?.let { result.add(it.textRange) }
return result
}
val MarkdownTable.separatorRow: MarkdownTableSeparatorRow?
get() = firstChild.siblings(forward = true, withSelf = true).filterIsInstance<MarkdownTableSeparatorRow>().firstOrNull()
val MarkdownTableRow.isHeaderRow
get() = siblings(forward = false, withSelf = false).find { it is MarkdownTableRow } == null
val MarkdownTableRow.isLast
get() = siblings(forward = true, withSelf = false).find { it is MarkdownTableRow } == null
val MarkdownTableRow.columnsCount
get() = firstChild?.siblings(forward = true, withSelf = true)?.count { it is MarkdownTableCell } ?: 0
val MarkdownTable.columnsCount
get() = headerRow?.columnsCount ?: 0
val MarkdownTable.columnsIndices
get() = 0 until columnsCount
val MarkdownTableRow.columnsIndices
get() = 0 until columnsCount
fun MarkdownTable.getColumnAlignment(columnIndex: Int): MarkdownTableSeparatorRow.CellAlignment {
return separatorRow?.getCellAlignment(columnIndex)!!
}
val MarkdownTableCell.firstNonWhitespaceOffset
get() = startOffset + text.indexOfFirst { it != ' ' }.coerceAtLeast(0)
val MarkdownTableCell.lastNonWhitespaceOffset
get() = startOffset + text.indexOfLast { it != ' ' }.coerceAtLeast(0)
@JvmStatic
fun isProbablyInsideTableCell(document: Document, caretOffset: Int): Boolean {
if (caretOffset == 0) {
return false
}
val text = document.charsSequence
val lineNumber = document.getLineNumber(caretOffset)
val lineStartOffset = document.getLineStartOffset(lineNumber)
val lineEndOffset = document.getLineEndOffset(lineNumber)
var leftBarFound = false
for (offset in (caretOffset - 1) downTo lineStartOffset) {
if (text[offset] == TableProps.SEPARATOR_CHAR) {
leftBarFound = true
break
}
}
for (offset in caretOffset until lineEndOffset) {
if (text[offset] == TableProps.SEPARATOR_CHAR) {
return leftBarFound
}
}
return false
}
internal fun isFormattingEnabledForTables(file: PsiFile): Boolean {
return isTableSupportEnabled() &&
MarkdownSettings.getInstance(file.project).isEnhancedEditingEnabled &&
file !in CodeStyle.getSettings(file).excludedFiles
}
/**
* This is a quick fix for calculating the correct text range of table separator row.
* Currently, if the table is indented, the table separator element will contain line indentation as well.
* The problem only occurs with table separator row - regular rows elements don't include leading indents.
*/
internal fun MarkdownTableSeparatorRow.calculateActualTextRange(): TextRange {
val text = text
val first = text.indexOfFirst { !it.isWhitespace() && it != '>'}
val last = text.indexOfLast { !it.isWhitespace() }
val end = when (last) {
-1 -> this.textLength
else -> last + 1
}
return TextRange(first.coerceAtLeast(0), end).shiftRight(startOffset)
}
internal fun isTableSupportEnabled(): Boolean {
return Registry.`is`("markdown.tables.editing.support.enable", true)
}
}
| apache-2.0 | f6a1abbb691af8443f16a631c0ea4cd5 | 36.156566 | 158 | 0.739976 | 4.561066 | false | false | false | false |
StephaneBg/ScoreIt | data/src/main/kotlin/com/sbgapps/scoreit/data/solver/BeloteSolver.kt | 1 | 5134 | /*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.data.solver
import com.sbgapps.scoreit.data.model.BeloteBonus
import com.sbgapps.scoreit.data.model.BeloteBonusValue
import com.sbgapps.scoreit.data.model.BeloteLap
import com.sbgapps.scoreit.data.model.PlayerPosition
import com.sbgapps.scoreit.data.solver.BeloteSolver.Companion.POINTS_CAPOT
import com.sbgapps.scoreit.data.solver.BeloteSolver.Companion.POINTS_TOTAL
import com.sbgapps.scoreit.data.source.DataStore
class BeloteSolver(private val dataStore: DataStore) {
fun getResults(lap: BeloteLap): Pair<List<Int>, Boolean> {
val (results, isWon) = computeResults(lap)
if (!isWon) {
results[lap.taker.index] = 0
results[lap.counter().index] = POINTS_TOTAL
addBonuses(results, lap.bonuses, lap.counter())
}
return results.toList() to isWon
}
fun getDisplayResults(lap: BeloteLap): Pair<List<String>, Boolean> {
val (results, isWon) = getResults(lap)
return results.toList().mapIndexed { index, points ->
listOfNotNull(
getPointsForDisplay(points).toString(),
"♛".takeIf { lap.bonuses.find { it.bonus == BeloteBonusValue.BELOTE && it.player.index == index } != null },
"★".takeIf { lap.bonuses.find { it.bonus != BeloteBonusValue.BELOTE && it.player.index == index } != null }
).joinToString(" ")
} to isWon
}
private fun computeResults(lap: BeloteLap): Pair<IntArray, Boolean> {
val takerIndex = lap.taker.index
val counterIndex = lap.counter().index
val results = IntArray(2)
if (POINTS_TOTAL == lap.points) {
results[takerIndex] = POINTS_CAPOT
results[counterIndex] = 0
} else {
results[takerIndex] = lap.points
results[counterIndex] = lap.counterPoints()
}
addBonuses(results, lap.bonuses)
val isWon = results[takerIndex] >= results[counterIndex]
return results to isWon
}
private fun addBonuses(
results: IntArray,
bonuses: List<BeloteBonus>,
counter: PlayerPosition = PlayerPosition.NONE
) {
if (counter != PlayerPosition.NONE) {
for ((player, bonus) in bonuses) {
if (bonus == BeloteBonusValue.BELOTE) results[player.index] += bonus.points
else results[counter.index] += bonus.points
}
} else {
for ((player, bonus) in bonuses) results[player.index] += bonus.points
}
}
fun computeScores(laps: List<BeloteLap>): List<Int> {
val scores = MutableList(2) { 0 }
laps.forEachIndexed { index, lap ->
val (points, _) = getResults(lap)
if (isLitigation(points)) {
val counter = lap.counter()
scores[counter.index] += points[counter.index]
} else {
for (player in 0 until 2) scores[player] += points[player]
}
if (index > 0) {
val previousLap = laps[index - 1]
val (previousPoints, _) = getResults(previousLap)
if (isLitigation(previousPoints)) {
val winner =
if (points[PlayerPosition.ONE.index] > points[PlayerPosition.TWO.index]) PlayerPosition.ONE.index
else PlayerPosition.TWO.index
scores[winner] += previousPoints[winner]
}
}
}
return scores.map { getPointsForDisplay(it) }
}
fun isLitigation(points: List<Int>): Boolean =
(81 == points[PlayerPosition.ONE.index] && 81 == points[PlayerPosition.TWO.index]) ||
(91 == points[PlayerPosition.ONE.index] && 91 == points[PlayerPosition.TWO.index])
private fun roundPoint(score: Int): Int = when (score) {
POINTS_TOTAL -> 160
POINTS_CAPOT -> 250
else -> (score + 5) / 10 * 10
}
private fun getPointsForDisplay(points: Int): Int =
if (dataStore.isBeloteScoreRounded()) roundPoint(points) else points
companion object {
const val POINTS_TOTAL = 162
const val POINTS_CAPOT = 252
}
}
fun BeloteLap.counterPoints(): Int = when (points) {
0 -> POINTS_CAPOT
POINTS_CAPOT -> 0
else -> POINTS_TOTAL - points
}
fun BeloteLap.counter(): PlayerPosition = taker.counter()
fun PlayerPosition.counter(): PlayerPosition =
if (this == PlayerPosition.ONE) PlayerPosition.TWO else PlayerPosition.ONE | apache-2.0 | a925a67e51d16d63e23e0566fed10c08 | 37.571429 | 124 | 0.620589 | 4.007031 | false | false | false | false |
nielsutrecht/adventofcode | src/main/kotlin/com/nibado/projects/advent/y2017/Day13.kt | 1 | 647 | package com.nibado.projects.advent.y2017
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.resourceLines
object Day13 : Day {
private val input = resourceLines(2017, 13).map { it.split(": ") }.map { Pair(it[0].toInt(), it[1].toInt()) }.toMap()
override fun part1() = input.entries
.map { if (it.key % (2 * (it.value - 1)) == 0) it.key * it.value else 0 }
.sum().toString()
override fun part2(): String {
var delay = 0
while (input.entries.filter { (it.key + delay) % (2 * (it.value - 1)) == 0 }.isNotEmpty())
delay++
return delay.toString()
}
} | mit | e9eba0c03ee9430bb1cbe1cf317a51f6 | 31.4 | 121 | 0.585781 | 3.42328 | false | false | false | false |
JetBrains/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/Parent.kt | 1 | 5487 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.WorkspaceEntity
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
import kotlin.jvm.JvmStatic
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
interface XParentEntity : WorkspaceEntity {
val parentProperty: String
val children: List<@Child XChildEntity>
val optionalChildren: List<@Child XChildWithOptionalParentEntity>
val childChild: List<@Child XChildChildEntity>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : XParentEntity, WorkspaceEntity.Builder<XParentEntity>, ObjBuilder<XParentEntity> {
override var entitySource: EntitySource
override var parentProperty: String
override var children: List<XChildEntity>
override var optionalChildren: List<XChildWithOptionalParentEntity>
override var childChild: List<XChildChildEntity>
}
companion object : Type<XParentEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(parentProperty: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): XParentEntity {
val builder = builder()
builder.parentProperty = parentProperty
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: XParentEntity, modification: XParentEntity.Builder.() -> Unit) = modifyEntity(
XParentEntity.Builder::class.java, entity, modification)
//endregion
data class DataClassX(val stringProperty: String, val parent: EntityReference<XParentEntity>)
interface XChildEntity : WorkspaceEntity {
val childProperty: String
val dataClass: DataClassX?
val parentEntity: XParentEntity
val childChild: List<@Child XChildChildEntity>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : XChildEntity, WorkspaceEntity.Builder<XChildEntity>, ObjBuilder<XChildEntity> {
override var entitySource: EntitySource
override var childProperty: String
override var dataClass: DataClassX?
override var parentEntity: XParentEntity
override var childChild: List<XChildChildEntity>
}
companion object : Type<XChildEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(childProperty: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): XChildEntity {
val builder = builder()
builder.childProperty = childProperty
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: XChildEntity, modification: XChildEntity.Builder.() -> Unit) = modifyEntity(
XChildEntity.Builder::class.java, entity, modification)
//endregion
interface XChildWithOptionalParentEntity : WorkspaceEntity {
val childProperty: String
val optionalParent: XParentEntity?
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : XChildWithOptionalParentEntity, WorkspaceEntity.Builder<XChildWithOptionalParentEntity>, ObjBuilder<XChildWithOptionalParentEntity> {
override var entitySource: EntitySource
override var childProperty: String
override var optionalParent: XParentEntity?
}
companion object : Type<XChildWithOptionalParentEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(childProperty: String,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): XChildWithOptionalParentEntity {
val builder = builder()
builder.childProperty = childProperty
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: XChildWithOptionalParentEntity,
modification: XChildWithOptionalParentEntity.Builder.() -> Unit) = modifyEntity(
XChildWithOptionalParentEntity.Builder::class.java, entity, modification)
//endregion
interface XChildChildEntity : WorkspaceEntity {
val parent1: XParentEntity
val parent2: XChildEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : XChildChildEntity, WorkspaceEntity.Builder<XChildChildEntity>, ObjBuilder<XChildChildEntity> {
override var entitySource: EntitySource
override var parent1: XParentEntity
override var parent2: XChildEntity
}
companion object : Type<XChildChildEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): XChildChildEntity {
val builder = builder()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: XChildChildEntity, modification: XChildChildEntity.Builder.() -> Unit) = modifyEntity(
XChildChildEntity.Builder::class.java, entity, modification)
//endregion
| apache-2.0 | b27f32f070006bf90b5c469545f820a7 | 32.457317 | 155 | 0.755422 | 5.358398 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/PresentationFactory.kt | 2 | 17338 | // 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.codeInsight.hints.presentation
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInsight.hint.HintManagerImpl
import com.intellij.codeInsight.hint.HintUtil
import com.intellij.codeInsight.hints.InlayPresentationFactory
import com.intellij.codeInsight.hints.InlayPresentationFactory.*
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.CodeInsightColors
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiElement
import com.intellij.ui.LightweightHint
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Contract
import java.awt.Color
import java.awt.Component
import java.awt.Cursor
import java.awt.Point
import java.awt.event.MouseEvent
import java.util.*
import javax.swing.Icon
import kotlin.math.max
/**
* Contains non-stable and not well-designed API. Will be changed in 2020.2
*/
@ApiStatus.Experimental
class PresentationFactory(private val editor: EditorImpl) : InlayPresentationFactory {
private val textMetricsStorage = InlayTextMetricsStorage(editor)
private val offsetFromTopProvider = object : InsetValueProvider {
override val top: Int
get() = textMetricsStorage.getFontMetrics(true).offsetFromTop()
}
@Contract(pure = true)
override fun smallText(text: String): InlayPresentation {
val textWithoutBox = InsetPresentation(TextInlayPresentation(textMetricsStorage, true, text), top = 1, down = 1)
return withInlayAttributes(textWithoutBox)
}
fun smallTextWithoutBackground(text: String): InlayPresentation {
val textWithoutBox = InsetPresentation(TextInlayPresentation(textMetricsStorage, true, text), top = 1, down = 1)
return AttributesTransformerPresentation(textWithoutBox) {
it.withDefault(attributesOf(DefaultLanguageHighlighterColors.INLAY_TEXT_WITHOUT_BACKGROUND))
}
}
override fun container(
presentation: InlayPresentation,
padding: Padding?,
roundedCorners: RoundedCorners?,
background: Color?,
backgroundAlpha: Float
): InlayPresentation {
return ContainerInlayPresentation(presentation, padding, roundedCorners, background, backgroundAlpha)
}
override fun mouseHandling(base: InlayPresentation, clickListener: ClickListener?, hoverListener: HoverListener?): InlayPresentation {
return MouseHandlingPresentation(base, clickListener, hoverListener)
}
@ApiStatus.Experimental
@Contract(pure = true)
fun textSpacePlaceholder(length: Int, isSmall: Boolean) : InlayPresentation {
return TextPlaceholderPresentation(length, textMetricsStorage, isSmall)
}
@Contract(pure = true)
@Deprecated(message = "Bad API for Java, use mouseHandling with ClickListener")
@ApiStatus.ScheduledForRemoval(inVersion = "2021.2")
fun mouseHandling(
base: InlayPresentation,
clickListener: ((MouseEvent, Point) -> Unit)?,
hoverListener: HoverListener?
): InlayPresentation {
val adapter = if (clickListener != null) {
ClickListener { event, translated -> clickListener.invoke(event, translated) }
}
else {
null
}
return mouseHandling(base, adapter, hoverListener)
}
@Contract(pure = true)
override fun text(text: String): InlayPresentation {
return withInlayAttributes(TextInlayPresentation(textMetricsStorage, false, text))
}
/**
* Adds inlay background and rounding with insets.
* Intended to be used with [smallText]
*/
@Contract(pure = true)
fun roundWithBackground(base: InlayPresentation): InlayPresentation {
val rounding = withInlayAttributes(RoundWithBackgroundPresentation(
InsetPresentation(
base,
left = 7,
right = 7,
top = 0,
down = 0
),
8,
8
))
return DynamicInsetPresentation(rounding, offsetFromTopProvider)
}
@Contract(pure = true)
fun roundWithBackgroundAndSmallInset(base: InlayPresentation): InlayPresentation {
val rounding = withInlayAttributes(RoundWithBackgroundPresentation(
InsetPresentation(
base,
left = 3,
right = 3,
top = 0,
down = 0
),
8,
8
))
return DynamicInsetPresentation(rounding, offsetFromTopProvider)
}
@Contract(pure = true)
override fun icon(icon: Icon): IconPresentation = IconPresentation(icon, editor.component)
@Contract(pure = true)
override fun smallScaledIcon(icon: Icon): InlayPresentation
{
val iconWithoutBox = InsetPresentation(ScaledIconPresentation(textMetricsStorage, true, icon, editor.component), top = 1, down = 1)
return withInlayAttributes(iconWithoutBox)
}
@Contract(pure = true)
fun folding(placeholder: InlayPresentation, unwrapAction: () -> InlayPresentation): InlayPresentation {
return ChangeOnClickPresentation(changeOnHover(placeholder, onHover = {
attributes(placeholder) {
it.with(attributesOf(EditorColors.FOLDED_TEXT_ATTRIBUTES))
}
}), onClick = unwrapAction)
}
@Contract(pure = true)
fun inset(base: InlayPresentation, left: Int = 0, right: Int = 0, top: Int = 0, down: Int = 0): InsetPresentation {
return InsetPresentation(base, left, right, top, down)
}
/**
* Creates node, that can be collapsed/expanded by clicking on prefix/suffix.
* If presentation is collapsed, clicking to content will expand it.
*/
@Contract(pure = true)
fun collapsible(
prefix: InlayPresentation,
collapsed: InlayPresentation,
expanded: () -> InlayPresentation,
suffix: InlayPresentation,
startWithPlaceholder: Boolean = true): InlayPresentation {
val (matchingPrefix, matchingSuffix) = matchingBraces(prefix, suffix)
var presentationToChange: BiStatePresentation? = null
val content = BiStatePresentation(first = {
onClick(collapsed, MouseButton.Left,
onClick = { _, _ ->
presentationToChange?.flipState()
})
}, second = { expanded() }, initiallyFirstEnabled = startWithPlaceholder)
presentationToChange = content
class ContentFlippingPresentation(base: InlayPresentation) : StaticDelegatePresentation(base) {
override fun mouseClicked(event: MouseEvent, translated: Point) {
content.flipState()
}
}
val prefixExposed = ContentFlippingPresentation(matchingPrefix)
val suffixExposed = ContentFlippingPresentation(matchingSuffix)
return seq(prefixExposed, content, suffixExposed)
}
@Contract(pure = true)
fun matchingBraces(left: InlayPresentation, right: InlayPresentation): Pair<InlayPresentation, InlayPresentation> {
val (leftMatching, rightMatching) = matching(listOf(left, right))
return leftMatching to rightMatching
}
@Contract(pure = true)
fun matching(presentations: List<InlayPresentation>): List<InlayPresentation> = synchronousOnHover(presentations) { presentation ->
attributes(presentation) { base ->
base.with(attributesOf(CodeInsightColors.MATCHED_BRACE_ATTRIBUTES))
}
}
/**
* On hover of any of [presentations] changes all the presentations with a given decorator.
* This presentation is stateless.
*/
@Contract(pure = true)
fun synchronousOnHover(presentations: List<InlayPresentation>,
decorator: (InlayPresentation) -> InlayPresentation): List<InlayPresentation> {
val forwardings = presentations.map { DynamicDelegatePresentation(it) }
return forwardings.map {
onHover(it, object : HoverListener {
override fun onHover(event: MouseEvent, translated: Point) {
for ((index, forwarding) in forwardings.withIndex()) {
forwarding.delegate = decorator(presentations[index])
}
}
override fun onHoverFinished() {
for ((index, forwarding) in forwardings.withIndex()) {
forwarding.delegate = presentations[index]
}
}
})
}
}
/**
* @see OnHoverPresentation
*/
@Contract(pure = true)
fun onHover(base: InlayPresentation, onHoverListener: HoverListener): InlayPresentation =
OnHoverPresentation(base, onHoverListener)
/**
* @see OnClickPresentation
*/
@Contract(pure = true)
fun onClick(base: InlayPresentation, button: MouseButton, onClick: (MouseEvent, Point) -> Unit): InlayPresentation {
return OnClickPresentation(base) { e, p ->
if (button == e.mouseButton) {
onClick(e, p)
}
}
}
/**
* @see OnClickPresentation
*/
@Contract(pure = true)
fun onClick(base: InlayPresentation, buttons: EnumSet<MouseButton>, onClick: (MouseEvent, Point) -> Unit): InlayPresentation {
return OnClickPresentation(base) { e, p ->
if (e.mouseButton in buttons) {
onClick(e, p)
}
}
}
/**
* @see ChangeOnHoverPresentation
*/
@Contract(pure = true)
fun changeOnHover(
base: InlayPresentation,
onHover: () -> InlayPresentation,
onHoverPredicate: (MouseEvent) -> Boolean = { true }
): InlayPresentation = ChangeOnHoverPresentation(base, onHover, onHoverPredicate)
@Contract(pure = true)
fun reference(base: InlayPresentation, onClickAction: () -> Unit): InlayPresentation {
return reference(
base = base,
onClickAction = Runnable { onClickAction() },
clickButtonsWithoutHover = EnumSet.of(MouseButton.Middle),
clickButtonsWithHover = EnumSet.of(MouseButton.Left, MouseButton.Middle),
hoverPredicate = { isControlDown(it) }
)
}
@Contract(pure = true)
fun referenceOnHover(base: InlayPresentation, clickListener: ClickListener): InlayPresentation {
val delegate = DynamicDelegatePresentation(base)
val hovered = onClick(
base = withReferenceAttributes(base),
buttons = EnumSet.of(MouseButton.Left, MouseButton.Middle),
onClick = { e, p ->
clickListener.onClick(e, p)
}
)
return OnHoverPresentation(delegate, object : HoverListener {
override fun onHover(event: MouseEvent, translated: Point) {
val handCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
editor.setCustomCursor(this@PresentationFactory, handCursor)
delegate.delegate = hovered
}
override fun onHoverFinished() {
delegate.delegate = base
editor.setCustomCursor(this@PresentationFactory, null)
}
})
}
@Contract(pure = true)
private fun reference(
base: InlayPresentation,
onClickAction: Runnable,
clickButtonsWithoutHover: EnumSet<MouseButton>,
clickButtonsWithHover: EnumSet<MouseButton>,
hoverPredicate: (MouseEvent) -> Boolean
): InlayPresentation {
val noHighlightReference = onClick(base, clickButtonsWithoutHover) { _, _ ->
onClickAction.run()
}
return changeOnHover(noHighlightReference, {
return@changeOnHover onClick(withReferenceAttributes(noHighlightReference), clickButtonsWithHover) { _, _ ->
onClickAction.run()
}
}, hoverPredicate)
}
private fun withReferenceAttributes(noHighlightReference: InlayPresentation): AttributesTransformerPresentation {
return attributes(noHighlightReference) {
val attributes = attributesOf(EditorColors.REFERENCE_HYPERLINK_COLOR)
attributes.effectType = null // With underlined looks weird
it.with(attributes)
}
}
@Contract(pure = true)
fun psiSingleReference(base: InlayPresentation, resolve: () -> PsiElement?): InlayPresentation =
reference(base) { navigateInternal(resolve) }
@Contract(pure = true)
fun seq(vararg presentations: InlayPresentation): InlayPresentation {
return when (presentations.size) {
0 -> SpacePresentation(0, 0)
1 -> presentations.first()
else -> SequencePresentation(presentations.toList())
}
}
fun join(presentations: List<InlayPresentation>, separator: () -> InlayPresentation): InlayPresentation {
val seq = mutableListOf<InlayPresentation>()
var first = true
for (presentation in presentations) {
if (!first) {
seq.add(separator())
}
seq.add(presentation)
first = false
}
return SequencePresentation(seq)
}
fun button(default: InlayPresentation, clicked: InlayPresentation, clickListener: ClickListener?, hoverListener: HoverListener?) : InlayPresentation {
val defaultOrClicked: BiStatePresentation = object : BiStatePresentation({ default }, { clicked }, false) {
override val width: Int
get() = max(default.width, clicked.width)
override val height: Int
get() = max(default.height, clicked.height)
}
return object : StaticDelegatePresentation(defaultOrClicked) {
override fun mouseClicked(event: MouseEvent, translated: Point) {
clickListener?.onClick(event, translated)
defaultOrClicked.flipState()
}
override fun mouseMoved(event: MouseEvent, translated: Point) {
hoverListener?.onHover(event, translated)
}
override fun mouseExited() {
hoverListener?.onHoverFinished()
}
}
}
private fun attributes(base: InlayPresentation, transformer: (TextAttributes) -> TextAttributes): AttributesTransformerPresentation =
AttributesTransformerPresentation(base, transformer)
private fun withInlayAttributes(base: InlayPresentation): InlayPresentation {
return AttributesTransformerPresentation(base) {
it.withDefault(attributesOf(DefaultLanguageHighlighterColors.INLAY_DEFAULT))
}
}
private fun isControlDown(e: MouseEvent): Boolean = (SystemInfo.isMac && e.isMetaDown) || e.isControlDown
@Contract(pure = true)
fun withTooltip(@NlsContexts.HintText tooltip: String, base: InlayPresentation): InlayPresentation = when {
tooltip.isEmpty() -> base
else -> {
var hint: LightweightHint? = null
onHover(base, object : HoverListener {
override fun onHover(event: MouseEvent, translated: Point) {
if (hint?.isVisible != true) {
hint = showTooltip(editor, event, tooltip)
}
}
override fun onHoverFinished() {
hint?.hide()
hint = null
}
})
}
}
private fun showTooltip(editor: Editor, e: MouseEvent, @NlsContexts.HintText text: String): LightweightHint {
val hint = run {
val label = HintUtil.createInformationLabel(text)
label.border = JBUI.Borders.empty(6, 6, 5, 6)
LightweightHint(label)
}
val constraint = HintManager.ABOVE
val point = run {
val pointOnEditor = locationAt(e, editor.contentComponent)
val p = HintManagerImpl.getHintPosition(hint, editor, editor.xyToVisualPosition(pointOnEditor), constraint)
p.x = e.xOnScreen - editor.contentComponent.topLevelAncestor.locationOnScreen.x
p
}
HintManagerImpl.getInstanceImpl().showEditorHint(hint, editor, point,
HintManager.HIDE_BY_ANY_KEY
or HintManager.HIDE_BY_TEXT_CHANGE
or HintManager.HIDE_BY_SCROLLING,
0,
false,
HintManagerImpl.createHintHint(editor, point, hint, constraint).setContentActive(false)
)
return hint
}
private fun locationAt(e: MouseEvent, component: Component): Point {
val pointOnScreen = component.locationOnScreen
return Point(e.xOnScreen - pointOnScreen.x, e.yOnScreen - pointOnScreen.y)
}
private fun attributesOf(key: TextAttributesKey) = editor.colorsScheme.getAttributes(key) ?: TextAttributes()
private fun navigateInternal(resolve: () -> PsiElement?) {
val target = resolve()
if (target is Navigatable) {
CommandProcessor.getInstance().executeCommand(target.project, { target.navigate(true) }, null, null)
}
}
}
private fun TextAttributes.with(other: TextAttributes): TextAttributes {
val result = this.clone()
other.foregroundColor?.let { result.foregroundColor = it }
other.backgroundColor?.let { result.backgroundColor = it }
other.fontType.let { result.fontType = it }
other.effectType?.let { result.effectType = it }
other.effectColor?.let { result.effectColor = it }
return result
}
private fun TextAttributes.withDefault(other: TextAttributes): TextAttributes {
val result = this.clone()
if (result.foregroundColor == null) {
result.foregroundColor = other.foregroundColor
}
if (result.backgroundColor == null) {
result.backgroundColor = other.backgroundColor
}
if (result.effectType == null) {
result.effectType = other.effectType
}
if (result.effectColor == null) {
result.effectColor = other.effectColor
}
return result
} | apache-2.0 | 8c27d750dfcb8856cd21c54f729f185a | 35.047817 | 152 | 0.701984 | 4.677097 | false | false | false | false |
allotria/intellij-community | java/java-impl/src/com/intellij/java/refactoring/suggested/JavaSuggestedRefactoringAvailability.kt | 4 | 6788 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.refactoring.suggested
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.OverridingMethodsSearch
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiUtil
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.suggested.*
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Parameter
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Signature
class JavaSuggestedRefactoringAvailability(refactoringSupport: SuggestedRefactoringSupport) :
SuggestedRefactoringAvailability(refactoringSupport) {
private val HAS_OVERRIDES = Key<Boolean>("JavaSuggestedRefactoringAvailability.HAS_OVERRIDES")
private val HAS_USAGES = Key<Boolean>("JavaSuggestedRefactoringAvailability.HAS_USAGES")
// disable refactoring suggestion for method which overrides another method
override fun shouldSuppressRefactoringForDeclaration(state: SuggestedRefactoringState): Boolean {
if (state.declaration !is PsiMethod) return false
val restoredDeclarationCopy = state.restoredDeclarationCopy()
return restoredDeclarationCopy is PsiMethod && restoredDeclarationCopy.findSuperMethods().isNotEmpty()
}
override fun amendStateInBackground(state: SuggestedRefactoringState): Iterator<SuggestedRefactoringState> {
return iterator {
if (state.additionalData[HAS_OVERRIDES] == null) {
val method = state.declaration as? PsiMethod
if (method != null && method.canHaveOverrides(state.oldSignature)) {
val restoredMethod = state.restoredDeclarationCopy() as PsiMethod
val hasOverrides = OverridingMethodsSearch.search(restoredMethod, false).findFirst() != null
yield(state.withAdditionalData(HAS_OVERRIDES, hasOverrides))
}
}
if (state.additionalData[HAS_USAGES] == null) {
val declarationCopy = state.restoredDeclarationCopy()
val useScope = declarationCopy.useScope
if (useScope is LocalSearchScope) {
val hasUsages = ReferencesSearch.search(declarationCopy, useScope).findFirst() != null
yield(state.withAdditionalData(HAS_USAGES, hasUsages))
}
}
}
}
// we use resolve to filter out annotations that we don't want to spread over hierarchy
override fun refineSignaturesWithResolve(state: SuggestedRefactoringState): SuggestedRefactoringState {
val declaration = state.declaration as? PsiMethod ?: return state
val restoredDeclarationCopy = state.restoredDeclarationCopy() as PsiMethod
val psiFile = declaration.containingFile
return state
.withOldSignature(extractAnnotationsWithResolve(state.oldSignature, restoredDeclarationCopy, psiFile))
.withNewSignature(extractAnnotationsWithResolve(state.newSignature, declaration, psiFile))
}
override fun detectAvailableRefactoring(state: SuggestedRefactoringState): SuggestedRefactoringData? {
val declaration = state.declaration
val oldSignature = state.oldSignature
val newSignature = state.newSignature
if (declaration !is PsiMethod) {
if (state.additionalData[HAS_USAGES] == false) return null
return SuggestedRenameData(declaration as PsiNamedElement, oldSignature.name)
}
val canHaveOverrides = declaration.canHaveOverrides(oldSignature) && state.additionalData[HAS_OVERRIDES] != false
if (state.additionalData[HAS_USAGES] == false && !canHaveOverrides) return null
val updateUsagesData = SuggestedChangeSignatureData.create(state, RefactoringBundle.message("suggested.refactoring.usages"))
if (hasParameterAddedRemovedOrReordered(oldSignature, newSignature)) return updateUsagesData
val updateOverridesData = if (canHaveOverrides)
updateUsagesData.copy(nameOfStuffToUpdate = if (declaration.hasModifierProperty(PsiModifier.ABSTRACT)) RefactoringBundle.message(
"suggested.refactoring.implementations")
else RefactoringBundle.message("suggested.refactoring.overrides"))
else
null
val (nameChanges, renameData) = nameChanges(oldSignature, newSignature, declaration, declaration.parameterList.parameters.asList())
val methodNameChanged = oldSignature.name != newSignature.name
if (hasTypeChanges(oldSignature, newSignature) || oldSignature.visibility != newSignature.visibility) {
return if (methodNameChanged || nameChanges > 0 && declaration.body != null) updateUsagesData else updateOverridesData
}
return when {
renameData != null -> renameData
nameChanges > 0 -> if (methodNameChanged || declaration.body != null) updateUsagesData else updateOverridesData
else -> null
}
}
private fun PsiMethod.canHaveOverrides(oldSignature: Signature): Boolean {
return PsiUtil.canBeOverridden(this) && oldSignature.visibility != PsiModifier.PRIVATE
}
override fun hasTypeChanges(oldSignature: Signature, newSignature: Signature): Boolean {
return super.hasTypeChanges(oldSignature, newSignature)
|| oldSignature.annotations != newSignature.annotations
|| oldSignature.exceptionTypes != newSignature.exceptionTypes
}
override fun hasParameterTypeChanges(oldParam: Parameter, newParam: Parameter): Boolean {
return super.hasParameterTypeChanges(oldParam, newParam) || oldParam.annotations != newParam.annotations
}
// Annotations were extracted without use of resolve. We must extract them again using more precise method.
private fun extractAnnotationsWithResolve(signature: Signature, declaration: PsiMethod, psiFile: PsiFile): Signature {
val psiParameters = declaration.parameterList.parameters
require(signature.parameters.size == psiParameters.size)
return Signature.create(
signature.name,
signature.type,
signature.parameters.zip(psiParameters.asList()).map { (parameter, psiParameter) ->
val annotations = extractAnnotations(psiParameter.type, psiParameter, psiFile)
parameter.copy(additionalData = JavaParameterAdditionalData(annotations))
},
JavaSignatureAdditionalData(
signature.visibility,
extractAnnotations(declaration.returnType, declaration, psiFile),
signature.exceptionTypes
)
)!!
}
private fun extractAnnotations(type: PsiType?, owner: PsiModifierListOwner, psiFile: PsiFile): String {
if (type == null) return ""
return JavaSuggestedRefactoringSupport.extractAnnotationsToCopy(type, owner, psiFile)
.joinToString(separator = " ") { it.text } //TODO: strip comments and line breaks
}
} | apache-2.0 | 750a2cf12424b94cb9bd576cb5a63335 | 48.919118 | 140 | 0.767236 | 5.311424 | false | false | false | false |
leafclick/intellij-community | platform/vcs-impl/src/com/intellij/vcs/log/VcsUserEditor.kt | 1 | 1611 | // 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.vcs.log
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.util.textCompletion.DefaultTextCompletionValueDescriptor.StringValueDescriptor
import com.intellij.util.textCompletion.TextCompletionProvider
import com.intellij.util.textCompletion.TextFieldWithCompletion
import com.intellij.util.textCompletion.ValuesCompletionProvider.ValuesCompletionProviderDumbAware
private fun createCompletionProvider(values: List<String>): TextCompletionProvider =
ValuesCompletionProviderDumbAware(StringValueDescriptor(), values)
class VcsUserEditor(project: Project, values: List<String> = getAllUsers(project)) :
TextFieldWithCompletion(project, createCompletionProvider(values), "", true, true, true) {
var user: VcsUser?
get() = VcsUserParser.parse(project, text)
set(value) = setText(value?.toString())
override fun updateUI() {
// When switching from Darcula to IntelliJ `getBackground()` has `UIUtil.getTextFieldBackground()` value which is `UIResource`.
// `LookAndFeel.installColors()` (called from `updateUI()`) calls `setBackground()` and sets panel background (gray) to be used.
// So we clear background to allow default behavior (use background from color scheme).
background = null
super.updateUI()
}
companion object {
fun getAllUsers(project: Project): List<String> = project.service<VcsUserRegistry>().users.map { it.toString() }
}
} | apache-2.0 | 79c53a27eac7f2b48a02091228b6b74f | 49.375 | 140 | 0.783985 | 4.550847 | false | false | false | false |
vvondra/rsd-map | api/src/main/kotlin/cz/vojtechvondra/rsd/DataController.kt | 1 | 1272 | package cz.vojtechvondra.rsd
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
@RestController
class DataController(val provider: DataProvider) {
@GetMapping("/api/projects")
fun data(
@RequestParam("region", required = false) region: List<String>?,
@RequestParam("poiType", required = false) poiType: String?,
@RequestParam("road", required = false) road: List<String>?,
@RequestParam("status", required = false) status: List<String>?
) = provider.toGeoJson(provider.findData(
region ?: emptyList(),
poiType,
road ?: emptyList(),
status ?: emptyList()
))
@GetMapping("/api/roads")
fun roads() = provider.roads
@GetMapping("/api/regions")
fun regions() = provider.regions
@GetMapping("/api/plans")
fun plans() = provider.plans
@GetMapping("/api/projects/{id}")
fun project(@PathVariable("id") id: String) = provider.getProject(id)
@GetMapping("/api/statuses")
fun statuses() = provider.findData().mapNotNull { t -> t.construction?.status }.distinct()
}
| gpl-3.0 | afe308c2c389a523d2eaf8413cb878d4 | 31.615385 | 94 | 0.683962 | 4.211921 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-integration/src/main/kotlin/slatekit/integration/apis/QueueApi.kt | 1 | 3578 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.integration.apis
import slatekit.apis.Api
import slatekit.apis.Action
import slatekit.apis.AuthModes
import slatekit.apis.Verbs
import slatekit.apis.support.FileSupport
import slatekit.context.Context
import slatekit.common.Sources
import slatekit.common.types.ContentFile
import slatekit.common.crypto.Encryptor
import slatekit.common.log.Logger
import slatekit.core.queues.AsyncQueue
import slatekit.results.Try
@Api(area = "cloud", name = "queues", desc = "api info about the application and host",
auth = AuthModes.KEYED, roles = ["admin"], verb = Verbs.AUTO, sources = [Sources.ALL])
class QueueApi(val queue: AsyncQueue<String>, override val context: Context) : FileSupport {
override val encryptor: Encryptor? = context.enc
override val logger: Logger? = context.logs.getLogger()
@Action(desc = "close the queue")
suspend fun close() {
return queue.close()
}
@Action(desc = "get the total items in the queue")
suspend fun count(): Int {
return queue.count()
}
@Action(desc = "get the next item in the queue")
suspend fun next(complete: Boolean): Any? {
val item = queue.next()
if (complete) {
queue.done(item)
}
return item
}
@Action(desc = "get the next set of items in the queue")
suspend fun nextBatch(size: Int = 10, complete: Boolean): List<Any> {
val items = queue.next(size)
items?.let { all ->
for (item in items) {
if (complete) {
queue.done(item)
}
}
}
return items ?: listOf()
}
@Action(desc = "gets next item and saves it to file")
suspend fun nextToFile(complete: Boolean, fileNameLocal: String): Any? {
val item = queue.next()
if (complete) {
queue.done(item)
}
return writeToFile(item, fileNameLocal, 0) { m -> item?.getValue() ?: "" }
}
@Action(desc = "gets next set of items and saves them to files")
suspend fun nextBatchToFiles(size: Int = 10, complete: Boolean, fileNameLocal: String): List<String?> {
val items = queue.next(size)
val result = items?.let { all ->
val res= all.mapIndexed { index, entry ->
val content = entry.getValue() ?: ""
writeToFile(all[index], fileNameLocal, index) { content }
content
}
res
} ?: listOf<String?>("No items available")
return result
}
@Action(desc = "sends a message to the queue")
suspend fun send(msg: String, tagName: String = "", tagValue: String = ""): Try<String> {
return queue.send(msg, tagName, tagValue)
}
@Action(desc = "sends a message to queue using content from file")
suspend fun sendFromFile(uri: String, tagName: String = "", tagValue: String = ""): Try<String> {
return queue.sendFromFile(uri, tagName, tagValue)
}
@Action(desc = "sends a message to queue using content from file")
suspend fun sendFromDoc(doc: ContentFile, tagName: String = "", tagValue: String = ""): Try<String> {
return queue.send(String(doc.data), tagName, tagValue)
}
}
| apache-2.0 | 985c7fd5b9a64b0a51e629861e98115b | 32.754717 | 107 | 0.627725 | 4.042938 | false | false | false | false |
smmribeiro/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/properties/PropertiesFiled.kt | 1 | 2991 | // 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.ui.properties
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.CustomShortcutSet
import com.intellij.openapi.externalSystem.service.ui.properties.PropertiesTable.Property
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.observable.properties.AtomicLazyProperty
import com.intellij.openapi.observable.properties.comap
import com.intellij.openapi.observable.properties.transform
import com.intellij.openapi.observable.util.bind
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.ui.components.fields.ExtendableTextComponent
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.util.execution.ParametersListUtil
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import javax.swing.KeyStroke
class PropertiesFiled(project: Project, info: PropertiesInfo) : ExtendableTextField() {
private val commandLinePropertiesProperty = AtomicLazyProperty { "" }
private val propertiesProperty = commandLinePropertiesProperty
.transform(map = ::parseProperties, comap = ::joinProperties)
var commandLineProperties by commandLinePropertiesProperty
var properties by propertiesProperty
private fun parseProperties(propertiesString: String): List<Property> {
return ParametersListUtil.parse(propertiesString, false, true)
.map { parseProperty(it) }
}
private fun parseProperty(propertyString: String): Property {
val name = propertyString.substringBefore('=')
val value = propertyString.substringAfter('=')
return Property(name, value)
}
private fun joinProperties(properties: List<Property>): String {
return properties.joinToString(" ") { joinProperty(it) }
}
private fun joinProperty(property: Property): String {
val value = ParametersListUtil.escape(property.value)
return property.name + "=" + value
}
init {
bind(commandLinePropertiesProperty.comap { it.trim() })
}
init {
val action = Runnable {
val dialog = PropertiesDialog(project, info)
dialog.properties = properties
dialog.whenOkButtonPressed {
properties = dialog.properties
}
dialog.show()
}
val anAction = DumbAwareAction.create { action.run() }
val keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK)
anAction.registerCustomShortcutSet(CustomShortcutSet(keyStroke), this, null)
val keystrokeText = KeymapUtil.getKeystrokeText(keyStroke)
val tooltip = info.dialogTooltip + " ($keystrokeText)"
val browseExtension = ExtendableTextComponent.Extension.create(
AllIcons.General.InlineVariables, AllIcons.General.InlineVariablesHover, tooltip, action)
addExtension(browseExtension)
}
} | apache-2.0 | c0d9b457df3030c482448ef57f3b1b95 | 40.555556 | 158 | 0.781678 | 4.622875 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/service/IdeaBuildSystemAvailabilityWizardService.kt | 6 | 1149 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.wizard.service
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.extensions.PluginId
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.core.service.BuildSystemAvailabilityWizardService
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.isGradle
class IdeaBuildSystemAvailabilityWizardService : BuildSystemAvailabilityWizardService, IdeaWizardService {
override fun isAvailable(buildSystemType: BuildSystemType): Boolean = when {
buildSystemType.isGradle -> isPluginEnabled("org.jetbrains.plugins.gradle")
buildSystemType == BuildSystemType.Maven -> isPluginEnabled("org.jetbrains.idea.maven")
else -> true
}
private fun isPluginEnabled(@NonNls id: String) =
PluginManagerCore.getPlugin(PluginId.getId(id))?.isEnabled == true
} | apache-2.0 | eca684a1863b82cc21991576016bc07d | 53.761905 | 158 | 0.807659 | 4.889362 | false | false | false | false |
kohesive/kohesive-iac | model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/CloudFormation.kt | 1 | 2559 | package uy.kohesive.iac.model.aws.cloudformation.resources
import uy.kohesive.iac.model.aws.cloudformation.ResourceProperties
import uy.kohesive.iac.model.aws.cloudformation.CloudFormationType
import uy.kohesive.iac.model.aws.cloudformation.CloudFormationTypes
@CloudFormationTypes
object CloudFormation {
@CloudFormationType("AWS::CloudFormation::ResourceTag")
data class ResourceTag(
val Key: String,
val Value: String
) : ResourceProperties
@CloudFormationType("AWS::CloudFormation::Authentication")
data class Authentication(
val accessKeyId: String? = null,
val buckets: List<String>? = null,
val password: String? = null,
val secretKey: String? = null,
val type: String,
val uris: List<String>? = null,
val username: String? = null,
val roleName: String? = null
) : ResourceProperties
@CloudFormationType("AWS::CloudFormation::CustomResource")
data class CustomResource(
val ServiceToken: String
) : ResourceProperties
@CloudFormationType("AWS::CloudFormation::Init")
class Init : ResourceProperties
@CloudFormationType("AWS::CloudFormation::Interface")
data class Interface(
val ParameterGroups: Interface.ParameterGroupProperty? = null,
val ParameterLabels: Interface.ParameterLabelProperty? = null
) : ResourceProperties {
data class ParameterGroupProperty(
val Label: Interface.ParameterGroupProperty.LabelProperty? = null,
val Parameters: List<String>? = null
) {
data class LabelProperty(
val default: String? = null
)
}
data class ParameterLabelProperty(
val ParameterLogicalID: Interface.ParameterGroupProperty.LabelProperty? = null
)
}
@CloudFormationType("AWS::CloudFormation::Stack")
data class Stack(
val NotificationARNs: List<String>? = null,
val Parameters: Any? = null,
val Tags: List<CloudFormation.ResourceTag>? = null,
val TemplateURL: String,
val TimeoutInMinutes: String? = null
) : ResourceProperties {
class ParameterProperty
}
@CloudFormationType("AWS::CloudFormation::WaitCondition")
data class WaitCondition(
val Count: String? = null,
val Handle: String,
val Timeout: String
) : ResourceProperties
@CloudFormationType("AWS::CloudFormation::WaitConditionHandle")
class WaitConditionHandle : ResourceProperties
} | mit | 60984c96165993095111ae6291411b0c | 29.47619 | 90 | 0.67331 | 4.902299 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/util/TouchGestureEvaluator.kt | 1 | 5830 | package de.fabmax.kool.util
import de.fabmax.kool.InputManager
import de.fabmax.kool.KoolContext
import de.fabmax.kool.math.MutableVec2d
import de.fabmax.kool.math.Vec2d
/**
* Evaluates standard touch gestures (pinch-to-zoom, two-finger drag)
*/
open class TouchGestureEvaluator {
var currentGesture = Gesture()
protected set
private val activePointers = mutableListOf<InputManager.Pointer>()
private val tmpVec1 = MutableVec2d()
private val tmpVec2 = MutableVec2d()
protected val startPositions = mutableMapOf<Int, Vec2d>()
protected var screenDpi = 96f
fun evaluate(pointerState: InputManager.PointerState, ctx: KoolContext) {
screenDpi = ctx.windowScale * 96f
pointerState.getActivePointers(activePointers)
if (activePointers.size > 1) {
when (currentGesture.type) {
INVALID -> onGestureInit(activePointers)
INDETERMINATE -> onDetermineGesture(activePointers)
PINCH -> handleGesture(activePointers)
TWO_FINGER_DRAG -> handleGesture(activePointers)
}
} else {
// not enough valid pointers for a multi-touch gesture
currentGesture.type = INVALID
startPositions.clear()
}
}
protected open fun onGestureInit(pointers: MutableList<InputManager.Pointer>) {
pointers.forEach { startPositions[it.id] = Vec2d(it.x, it.y) }
currentGesture.type = INDETERMINATE
}
protected open fun onDetermineGesture(pointers: MutableList<InputManager.Pointer>) {
// remove any missing pointer
startPositions.keys.removeAll { ptrId -> pointers.find { it.id == ptrId } == null }
// add any new pointer
pointers.filter { !startPositions.containsKey(it.id) }
.forEach { startPositions[it.id] = Vec2d(it.x, it.y) }
// try to match gesture
when {
isPinch(pointers) -> currentGesture.type = PINCH
isTwoFingerDrag(pointers) -> currentGesture.type = TWO_FINGER_DRAG
}
}
protected open fun isPinch(pointers: MutableList<InputManager.Pointer>): Boolean {
// two pointers moving in opposing direction
if (pointers.size == 2) {
tmpVec1.set(pointers[0].x, pointers[0].y).subtract(startPositions[pointers[0].id]!!)
tmpVec2.set(pointers[1].x, pointers[1].y).subtract(startPositions[pointers[1].id]!!)
tmpVec1.scale(96.0 / screenDpi)
tmpVec2.scale(96.0 / screenDpi)
if (tmpVec1.length() > 5.0 && tmpVec2.length() > 5.0 && tmpVec1 * tmpVec2 < 0.0) {
tmpVec1.set(startPositions[pointers[0].id]!!)
tmpVec2.set(startPositions[pointers[1].id]!!)
currentGesture.init(PINCH, tmpVec1, tmpVec2, screenDpi)
handleGesture(pointers)
return true
}
}
return false
}
protected open fun isTwoFingerDrag(pointers: MutableList<InputManager.Pointer>): Boolean {
// two pointers moving in same direction
if (pointers.size == 2) {
tmpVec1.set(pointers[0].x, pointers[0].y).subtract(startPositions[pointers[0].id]!!)
tmpVec2.set(pointers[1].x, pointers[1].y).subtract(startPositions[pointers[1].id]!!)
tmpVec1.scale(96.0 / screenDpi)
tmpVec2.scale(96.0 / screenDpi)
if (tmpVec1.length() > 5.0 && tmpVec2.length() > 5.0 && tmpVec1 * tmpVec2 > 0.0) {
tmpVec1.set(startPositions[pointers[0].id]!!)
tmpVec2.set(startPositions[pointers[1].id]!!)
currentGesture.init(TWO_FINGER_DRAG, tmpVec1, tmpVec2, screenDpi)
handleGesture(pointers)
return true
}
}
return false
}
protected open fun handleGesture(pointers: MutableList<InputManager.Pointer>) {
if (pointers.size == 2) {
tmpVec1.set(pointers[0].x, pointers[0].y)
tmpVec2.set(pointers[1].x, pointers[1].y)
currentGesture.update(tmpVec1, tmpVec2, screenDpi)
pointers[0].consume()
pointers[1].consume()
} else {
currentGesture.type = INVALID
}
}
companion object {
const val INVALID = 0
const val INDETERMINATE = -1
const val PINCH = 1
const val TWO_FINGER_DRAG = 2
}
open class Gesture {
val centerStart = MutableVec2d()
val centerCurrent = MutableVec2d()
val centerShift = MutableVec2d()
val dCenter = MutableVec2d()
var pinchAmountStart = 0.0
var pinchAmountCurrent = 0.0
var dPinchAmount = 0.0
val pinchAmountRel: Double
get() = (pinchAmountCurrent - pinchAmountStart) / pinchAmountStart + 1f
var type = INVALID
var numUpdates = 0
internal fun init(type: Int, ptr1: Vec2d, ptr2: Vec2d, dpi: Float) {
this.type = type
centerStart.set(ptr1).add(ptr2).scale(0.5)
centerCurrent.set(centerStart)
centerShift.set(Vec2d.ZERO)
dCenter.set(Vec2d.ZERO)
pinchAmountStart = ptr1.distance(ptr2) * 96.0 / dpi
pinchAmountCurrent = pinchAmountStart
dPinchAmount = 0.0
numUpdates = 0
}
internal fun update(ptr1: Vec2d, ptr2: Vec2d, dpi: Float) {
dCenter.set(ptr1).add(ptr2).scale(0.5).subtract(centerCurrent)
centerCurrent.set(ptr1).add(ptr2).scale(0.5)
centerShift.set(centerCurrent).subtract(centerStart)
val pinch = ptr1.distance(ptr2) * 96.0 / dpi
dPinchAmount = pinch - pinchAmountCurrent
pinchAmountCurrent = pinch
numUpdates++
}
}
}
| apache-2.0 | 16ba7e6b3754f7aedfd47992785a8dcd | 33.702381 | 96 | 0.604117 | 3.960598 | false | false | false | false |
Pattonville-App-Development-Team/Android-App | app/src/main/java/org/pattonvillecs/pattonvilleapp/view/ui/calendar/CalendarFragment.kt | 1 | 5462 | /*
* Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District
*
* 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 org.pattonvillecs.pattonvilleapp.view.ui.calendar
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.util.Log
import android.view.*
import com.firebase.jobdispatcher.FirebaseJobDispatcher
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_calendar.*
import org.pattonvillecs.pattonvilleapp.R
import org.pattonvillecs.pattonvilleapp.view.ui.MainActivity
import org.pattonvillecs.pattonvilleapp.view.ui.calendar.events.CalendarEventsFragment
import org.pattonvillecs.pattonvilleapp.view.ui.calendar.month.CalendarMonthFragment
import org.pattonvillecs.pattonvilleapp.view.ui.calendar.pinned.CalendarPinnedFragment
import org.pattonvillecs.pattonvilleapp.viewmodel.calendar.CalendarFragmentViewModel
import org.pattonvillecs.pattonvilleapp.viewmodel.getViewModel
import javax.inject.Inject
/**
* This Fragment manages the three calendar views and their connection to the tab bar. It also contains the common refresh menu functionality.
*
* @author Mitchell Skaggs
* @since 1.0.0
*/
class CalendarFragment : DaggerFragment() {
private var tabLayout: TabLayout? = null
private lateinit var viewModel: CalendarFragmentViewModel
@field:Inject
lateinit var firebaseJobDispatcher: FirebaseJobDispatcher
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.action_refresh -> {
viewModel.refreshCalendar()
true
}
else -> super.onOptionsItemSelected(item)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_calendar_action_bar_menu_main, menu)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Log.i(TAG, "onActivityCreated called")
activity?.setTitle(R.string.title_fragment_calendar)
tabLayout = (activity as MainActivity?)?.tabLayout
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.i(TAG, "onCreate called")
setHasOptionsMenu(true)
viewModel = getViewModel()
viewModel.firebaseJobDispatcher = firebaseJobDispatcher
viewModel.currentPage.observe(this::getLifecycle) { page -> page?.let { pager_calendar.setCurrentItem(it, false) } }
}
override fun onStart() {
super.onStart()
Log.i(TAG, "onStart called")
tabLayout?.visibility = View.VISIBLE
tabLayout?.setupWithViewPager(pager_calendar)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
inflater.inflate(R.layout.fragment_calendar, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
pager_calendar.offscreenPageLimit = 2
pager_calendar.adapter = object : FragmentPagerAdapter(childFragmentManager) {
internal val fragments = listOf(
CalendarMonthFragment.newInstance(),
CalendarEventsFragment.newInstance(),
CalendarPinnedFragment.newInstance()
)
override fun getItem(position: Int): Fragment = fragments[position]
override fun getPageTitle(position: Int): CharSequence = when (position) {
0 -> "Month"
1 -> "Events"
2 -> "Pinned"
else -> throw IllegalStateException("Invalid position!")
}
override fun getCount(): Int = fragments.size
}
pager_calendar.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
viewModel.setCurrentPage(position)
}
})
}
override fun onStop() {
super.onStop()
Log.d(TAG, "onStop called")
tabLayout?.visibility = View.GONE
tabLayout?.setupWithViewPager(null)
}
companion object {
private val TAG = "CalendarFragment"
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment CalendarFragment.
*/
@JvmStatic
fun newInstance(): CalendarFragment = CalendarFragment()
}
}
| gpl-3.0 | 7f7edf57efa5bd0f19997bdae150a170 | 36.156463 | 142 | 0.702307 | 5.015611 | false | false | false | false |
jotomo/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Temporary_Basal.kt | 1 | 1292 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
open class DanaRS_Packet_Basal_Set_Temporary_Basal(
injector: HasAndroidInjector,
private var temporaryBasalRatio: Int = 0,
private var temporaryBasalDuration: Int = 0
) : DanaRS_Packet(injector) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__SET_TEMPORARY_BASAL
aapsLogger.debug(LTag.PUMPCOMM, "Setting temporary basal of $temporaryBasalRatio% for $temporaryBasalDuration hours")
}
override fun getRequestParams(): ByteArray {
val request = ByteArray(2)
request[0] = (temporaryBasalRatio and 0xff).toByte()
request[1] = (temporaryBasalDuration and 0xff).toByte()
return request
}
override fun handleMessage(data: ByteArray) {
val result = intFromBuff(data, 0, 1)
if (result == 0) {
aapsLogger.debug(LTag.PUMPCOMM, "Result OK")
failed = false
} else {
aapsLogger.error("Result Error: $result")
failed = true
}
}
override fun getFriendlyName(): String {
return "BASAL__SET_TEMPORARY_BASAL"
}
} | agpl-3.0 | 8fd52b5dfef73eaaec9cd37964b3d537 | 32.153846 | 125 | 0.675697 | 4.58156 | false | false | false | false |
siosio/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/PackageSearchUI.kt | 1 | 7038 | package com.jetbrains.packagesearch.intellij.plugin.ui
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.Gray
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.components.BrowsableLinkLabel
import org.jetbrains.annotations.Nls
import java.awt.CardLayout
import java.awt.Color
import java.awt.Component
import java.awt.Dimension
import java.awt.FlowLayout
import java.awt.Rectangle
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.BorderFactory
import javax.swing.BoxLayout
import javax.swing.Icon
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JMenuItem
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.KeyStroke
import javax.swing.Scrollable
internal object PackageSearchUI {
private val MAIN_BG_COLOR: Color = JBColor.namedColor("Plugins.background", UIUtil.getListBackground())
internal val GRAY_COLOR: Color = JBColor.namedColor("Label.infoForeground", JBColor(Gray._120, Gray._135))
internal val HeaderBackgroundColor = MAIN_BG_COLOR
internal val SectionHeaderBackgroundColor = JBColor.namedColor("Plugins.SectionHeader.background", JBColor(0xF7F7F7, 0x3C3F41))
internal val UsualBackgroundColor = MAIN_BG_COLOR
internal val ListRowHighlightBackground = JBColor(0xF2F5F9, 0x4C5052)
internal val InfoBannerBackground = JBColor(0xE6EEF7, 0x1C3956)
internal const val MediumHeaderHeight = 30
internal const val SmallHeaderHeight = 24
@Suppress("MagicNumber") // Thanks, Swing
internal fun headerPanel(init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() {
init {
border = JBEmptyBorder(2, 0, 2, 12)
}
override fun getBackground() = HeaderBackgroundColor
}.apply(init)
internal fun cardPanel(cards: List<JPanel> = emptyList(), backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) =
object : JPanel() {
init {
layout = CardLayout()
cards.forEach { add(it) }
}
override fun getBackground() = backgroundColor
}.apply(init)
internal fun borderPanel(backgroundColor: Color = UsualBackgroundColor, init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() {
override fun getBackground() = backgroundColor
}.apply(init)
internal fun boxPanel(axis: Int = BoxLayout.Y_AXIS, backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) =
object : JPanel() {
init {
layout = BoxLayout(this, axis)
}
override fun getBackground() = backgroundColor
}.apply(init)
internal fun flowPanel(backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) = object : JPanel() {
init {
layout = FlowLayout(FlowLayout.LEFT)
}
override fun getBackground() = backgroundColor
}.apply(init)
internal fun checkBox(@Nls title: String) = object : JCheckBox(title) {
override fun getBackground() = UsualBackgroundColor
}
internal fun menuItem(@Nls title: String, icon: Icon?, handler: () -> Unit): JMenuItem {
if (icon != null) {
return JMenuItem(title, icon).apply { addActionListener { handler() } }
}
return JMenuItem(title).apply { addActionListener { handler() } }
}
internal fun createLabel(init: JLabel.() -> Unit = {}) = JLabel().apply {
font = UIUtil.getLabelFont()
init()
}
internal fun createLabelWithLink(init: BrowsableLinkLabel.() -> Unit = {}) = BrowsableLinkLabel().apply {
font = UIUtil.getLabelFont()
init()
}
internal fun getTextColorPrimary(isSelected: Boolean = false): Color = when {
isSelected -> JBColor { UIUtil.getListSelectionForeground(true) }
else -> JBColor { UIUtil.getListForeground() }
}
internal fun getTextColorSecondary(isSelected: Boolean = false): Color = when {
isSelected -> getTextColorPrimary(isSelected)
else -> GRAY_COLOR
}
internal fun setHeight(component: JComponent, height: Int, keepWidth: Boolean = false, scale: Boolean = true) {
val scaledHeight = if (scale) JBUI.scale(height) else height
component.apply {
preferredSize = Dimension(if (keepWidth) preferredSize.width else 0, scaledHeight)
minimumSize = Dimension(if (keepWidth) minimumSize.width else 0, scaledHeight)
maximumSize = Dimension(if (keepWidth) maximumSize.width else Int.MAX_VALUE, scaledHeight)
}
}
internal fun verticalScrollPane(c: Component) = object : JScrollPane(
VerticalScrollPanelWrapper(c),
VERTICAL_SCROLLBAR_AS_NEEDED,
HORIZONTAL_SCROLLBAR_NEVER
) {
init {
border = BorderFactory.createEmptyBorder()
viewport.background = UsualBackgroundColor
}
}
internal fun overrideKeyStroke(c: JComponent, stroke: String, action: () -> Unit) = overrideKeyStroke(c, stroke, stroke, action)
internal fun overrideKeyStroke(c: JComponent, key: String, stroke: String, action: () -> Unit) {
val inputMap = c.getInputMap(JComponent.WHEN_FOCUSED)
inputMap.put(KeyStroke.getKeyStroke(stroke), key)
c.actionMap.put(
key,
object : AbstractAction() {
override fun actionPerformed(arg: ActionEvent) {
action()
}
}
)
}
private class VerticalScrollPanelWrapper(content: Component) : JPanel(), Scrollable {
init {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
add(content)
}
override fun getPreferredScrollableViewportSize(): Dimension = preferredSize
override fun getScrollableUnitIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 10
override fun getScrollableBlockIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 100
override fun getScrollableTracksViewportWidth() = true
override fun getScrollableTracksViewportHeight() = false
override fun getBackground() = UsualBackgroundColor
}
}
internal class ComponentActionWrapper(private val myComponentCreator: () -> JComponent) : DumbAwareAction(), CustomComponentAction {
override fun createCustomComponent(presentation: Presentation, place: String) = myComponentCreator()
override fun actionPerformed(e: AnActionEvent) {
// No-op
}
}
internal fun JComponent.updateAndRepaint() {
invalidate()
repaint()
}
| apache-2.0 | 17b45282ccb391f0a6cc3dbda567ff04 | 37.459016 | 144 | 0.690679 | 4.86722 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinUsesAndInterfacesDependencyMemberInfoModel.kt | 6 | 1853 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.memberInfo
import com.intellij.psi.PsiNamedElement
import com.intellij.refactoring.classMembers.ANDCombinedMemberInfoModel
import com.intellij.refactoring.classMembers.DelegatingMemberInfoModel
import com.intellij.refactoring.classMembers.MemberInfoBase
import com.intellij.refactoring.classMembers.MemberInfoModel
import com.intellij.refactoring.util.classMembers.UsesDependencyMemberInfoModel
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtNamedDeclaration
open class KotlinUsesAndInterfacesDependencyMemberInfoModel<T : KtNamedDeclaration, M : MemberInfoBase<T>>(
klass: KtClassOrObject,
superClass: PsiNamedElement?,
recursive: Boolean,
interfaceContainmentVerifier: (T) -> Boolean = { false }
) : DelegatingMemberInfoModel<T, M>(
ANDCombinedMemberInfoModel(
object : KotlinUsesDependencyMemberInfoModel<T, M>(klass, superClass, recursive) {
override fun checkForProblems(memberInfo: M): Int {
val problem = super.checkForProblems(memberInfo)
if (problem == MemberInfoModel.OK) return MemberInfoModel.OK
val member = memberInfo.member
if (interfaceContainmentVerifier(member)) return MemberInfoModel.OK
return problem
}
},
KotlinInterfaceDependencyMemberInfoModel<T, M>(klass)
)
) {
@Suppress("UNCHECKED_CAST")
fun setSuperClass(superClass: PsiNamedElement) {
((delegatingTarget as ANDCombinedMemberInfoModel<T, M>).model1 as UsesDependencyMemberInfoModel<T, PsiNamedElement, M>).setSuperClass(
superClass
)
}
}
| apache-2.0 | 115ff98a7664bcacac84e113f2f34b7e | 44.195122 | 158 | 0.745818 | 5.062842 | false | false | false | false |
vincentvalenlee/nineshop | src/main/kotlin/org/open/openstore/file/contributors/AbstractFileObject.kt | 1 | 27593 | package org.open.openstore.file.contributors
import org.open.openstore.file.*
import org.open.openstore.file.FileObject.Companion.EMPTY_CHILDREN
import org.open.openstore.file.FileObject.Companion.EMPTY_LIST
import org.open.openstore.file.internal.AbstractFileName
import org.open.openstore.file.internal.DefaultFileOperations
import org.open.openstore.file.internal.selector.Selectors
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import org.open.openstore.file.FileType
import org.open.openstore.file.FileObject.Companion.EMPTY_OUT
import java.net.URL
import java.security.PrivilegedActionException
import org.open.openstore.file.FilePlatform.UriParser
import java.security.PrivilegedExceptionAction
import java.security.AccessController
/**
* 抽象类型的文件对象,他实现部分文件对象功能。子类实现其模板方法
*/
abstract class AbstractFileObject<AFS: AbstractFileSystem>(var fileName:AbstractFileName, val fs:AFS): FileObject {
companion object {
val logger:Logger = LoggerFactory.getLogger(AbstractFileObject::class.java)
/**
*根据选择器,深度或广度访问指定的文件集合
*/
private fun traverse(fileInfo:DefaultFileInfo, selector:FileSelector, depthwise:Boolean, selected: MutableList<FileObject> ) {
val file:FileObject = fileInfo.file
val index = selected.size
// 如果文件是目录则继续访问
if (file.type().hasChildren() && selector.visitFile(fileInfo)) {
val curDepth = fileInfo.depth
fileInfo.depth = curDepth + 1
// 访问子文件
file.children().forEach {
fileInfo.file = it
traverse(fileInfo, selector, depthwise, selected)
}
fileInfo.file = file
fileInfo.depth = curDepth
}
if (selector.selectFile(fileInfo)) {
if (depthwise) {
//深度优先
selected + file
} else {
//广度优先
selected.add(index, file)
}
}
}
}
private val INITIAL_LIST_SIZE = 5
// private var fileName: AbstractFileName? = null
// private var fs: AFS? = null
private var accessor: FileAccessor? = null
private var attached: Boolean = false
private var type: FileType? = null
private var parent: FileObject? = null
private var children: List<IFileName> = EMPTY_CHILDREN
private var objects: List<Any> = EMPTY_LIST
/**
* 文件额外操作
*/
private var operations: FileOperations? = null
init {
//处理的文件引用增加
fs.fileObjectHanded(this)
}
/**
* 关联文件资源
*/
private fun attach() {
synchronized (fs) {
if (!attached) {
try {
// 实际执行资源关联
doAttach()
attached = true
} catch (e: Exception) {
throw FileSystemException("get-type.error", e, info = arrayOf(fileName))
}
}
}
}
/**
* 关联文件对象到其实际的文件资源。子类可以重写此方法,执行特定的行为,如:懒加载资源等
*/
open protected fun doAttach() {}
override fun canRenameTo(newfile: FileObject): Boolean = newfile.fileSystem() == this
/**
* 子文件改变的通知,children删除或添加已改变的文件,然后调用子类重写的通知模板方法
* @param childName 子文件名称
* @param newType 子文件类型
*/
open protected fun childrenChanged(childName:IFileName, newType: FileType) {
children?.let {
if (newType == FileType.IMAGINARY) {
children -= childName
} else {
children += childName
}
}
onChildrenChanged(childName, newType)
}
/**
* 当此文件对象的子文件改变时执行的模板方法,子类可以重写(刷新此文件的子文件的缓存)
*/
open protected fun onChildrenChanged(child: IFileName, newType: FileType) {}
override fun close() {
//关闭访问器
var exc: FileSystemException? = null
accessor?.let {
try {
it.close()
accessor = null
} catch (e:FileSystemException) {
exc = e
}
}
try {
detach()
} catch (e: Exception) {
exc = FileSystemException("close.error", e, info = arrayOf(fileName))
}
if (exc != null) {
throw exc!!
}
}
private fun detach() {
synchronized(fs) {
if (attached) {
try {
doDetach()
} finally {
attached = false
parent = null
removeChildrenCache()
}
}
}
}
private fun removeChildrenCache() {
children = EMPTY_CHILDREN
}
/**
* 接触底层资源关联,当关闭时调用。子类重写
*/
open protected fun doDetach() {}
override operator fun compareTo(file: FileObject): Int = this.toString().compareTo(file.toString(), ignoreCase = true)
/**
* 拷贝其他文件
*/
override fun copyFrom(srcFile: FileObject, selector: FileSelector) {
if (srcFile.exists()) {
var files = srcFile.findFiles(selector, false)
files.forEach {
val relPath = srcFile.name().getRelativeName(it.name())
val destFile = resolveFile(relPath, NameScope.DESCENDENT_OR_SELF)
//目标文件已经存在,但类型不同
if (destFile.exists() && destFile.type() != it.type()) {
destFile.deleteAll()
}
try {
if (it.type().hasContent()) {
destFile.copyContentFrom(srcFile)
} else if (it.type().hasChildren()) {
destFile.create(true) //创建文件夹
}
} catch (e: IOException) {
throw FileSystemException("copy-file.error", throwable = e, info = arrayOf(it, destFile))
}
}
}
}
private fun createFile() {
synchronized (fs) {
try {
// 文件已存在
if (exists() && !isFile()) {
throw FileSystemException("create-file.error", info = arrayOf(fileName))
}
if (!exists()) { //文件不存在,准备输出流写入
prepareWriting().close()
endOutput()
}
} catch (e: Exception) {
throw FileSystemException("create-file.error", e, info = arrayOf(fileName))
}
}
}
/**
* 当此文件的输出流关闭时调用,子类应该实现handleCreate以及onChange模板事件方法
*/
open protected fun endOutput() {
if (type() == FileType.IMAGINARY) {
//文件新建
handleCreate(FileType.FILE)
} else {
// 文件改变
onChange()
}
}
/**
* 返回输入流准备将内容实际写入此文件。调用此方法时,文件以及其父目录必须存在。子类应该重写getOutputStream实际
* 获取文件对象内部的输出流对象
* @param append 是否以追加模式写入
* @return 要写入文件新内容的输入流
* @throws FileSystemException 如果发生错误则抛出异常,例如:append为true,但底层文件系统不支持追加
*/
fun prepareWriting(append: Boolean = false):OutputStream {
val fileAttrStore = this.getAdapter(FileAttributeStore::class) as FileAttributeStore
if (append && !(fileAttrStore.getAttr(this, MetaOptions.__APPEND_CONTENT.name) as Boolean)) {
//文件不支持追加模式
throw FileSystemException("write-append-not-supported.error", info = arrayOf(fileName))
}
if (type() == FileType.IMAGINARY) {
//文件不真实存在,创建父目录
parent()?.let {
it.create(true)
}
}
// 获取原始的输出流,子类实际实现
return try {
getOutputStream(append)
} catch (e: Exception) {
throw FileSystemException("write.error", e, info = arrayOf(fileName))
}
}
/**
* 子类需要实现的创建要写入文件内容的输出流(默认返回空输出流,不支持写)。仅仅在下面条件下调用:
* 1.doIsWriteable返回true
* 2.doGetType为File类型或者IMAGINARY不存在状态,且父对象存在或者为目录
*/
open protected fun doGetOutputStream(bAppend: Boolean): OutputStream = EMPTY_OUT
/**
* 准备写这个文件。 确保它是一个文件或其父文件夹存在。 返回用于将文件内容写入的输出流
* @throws FileSystemException
*/
open protected fun getOutputStream(append: Boolean = false): OutputStream {
val fileAttrStore = this.getAdapter(FileAttributeStore::class) as FileAttributeStore
if (append && !(fileAttrStore.getAttr(this, MetaOptions.__APPEND_CONTENT.name) as Boolean)) {
throw FileSystemException("write-append-not-supported.error", info= arrayOf(fileName))
}
if (type() === FileType.IMAGINARY) {
parent()?.let {
it.create(true)
}
}
try {
return doGetOutputStream(append)
} catch (re: RuntimeException) {
throw re
} catch (exc: Exception) {
throw FileSystemException("vfs.provider/write.error", exc, arrayOf(fileName))
}
}
private fun createFolder() {
synchronized (fs) {
// 不存在时才创建目录
if (type().hasChildren()) {
// 已经存在,无需做任何事
return
}
if (type() != FileType.IMAGINARY) {
throw FileSystemException("create-folder-mismatched-type.error", info = arrayOf(fileName))
}
parent()?.let {
it.create(true) //父目录必须存在
}
try {
//实际创建目录
doCreateFolder()
// 更新引用
handleCreate(FileType.FOLDER)
} catch(e: Exception) {
throw FileSystemException("create-folder.error", e, info = arrayOf(fileName))
}
}
}
/**
* 当文件(目录)新建时触发的处理方法。默认将缓存信息以及通知父对象和文件系统
*/
open protected fun handleCreate(newType: FileType) {
synchronized(fs) {
if (attached) { //文件已经关联实际资源
//设置文件名封装对象类型
changeType(newType)
//清除子对象缓存
removeChildrenCache()
// 通知改变
onChange()
}
// 通知父对象
notifyParent(this.name(), newType)
// 通知文件系统此文件已经创建
fs.fireFileCreated(this)
}
}
/**
* 默认直接设置文件名类型,子类可重写
*/
open protected fun changeType(fileType: FileType) {
setFileType(fileType)
}
private fun setFileType(type: FileType) {
if (type != null && type != FileType.IMAGINARY) {
try {
fileName.setType(type)
} catch (e:FileSystemException) {
throw RuntimeException(e.message)
}
}
this.type = type
}
/**
* 当子对象创建或删除、改变时,通知父对象的方法
* @param childName 改变的子对象
* @param newType 改变的新类型
*/
private fun notifyParent(childName: IFileName, newType:FileType) {
if (parent == null) {
fileName.getParent()?.let {
parent = fs.getFileFromCache(it)
}
}
parent?.let {
parent!!.getProxyedAbstractFileObject()?.let {
it.childrenChanged(childName, newType)
}
}
}
/**
* 子类需要重写实现的,实际创建目录的方法(默认为空)
*/
open protected fun doCreateFolder() {
//do nothing
}
override fun create(isFold: Boolean) {
when (isFold) {
false -> {
createFile()
}
else -> {
createFolder()
}
}
}
/**
* 文件类型或者内容改变时触发的事件,子类需要重写实现,默认为空
*/
open protected fun onChange() {}
override fun delete(selector: FileSelector): Int {
var nuofDeleted = 0
//定位要删除的文件
val files:Array<FileObject> = findFiles(selector, true)
files.filter {
//不能删除具有子元素的文件
!it.type().hasChildren() || it.children().size == 0
}.forEach {
if ((it as AbstractFileObject<*>).deleteSelf())
nuofDeleted++
}
return nuofDeleted
}
override fun delete(): Boolean {
return delete(Selectors.SELECT_SELF) > 0
}
override fun deleteAll(): Int {
return delete(Selectors.SELECT_ALL)
}
/**
* 实际删除此文件的方法,子类需要重写doDelete模板方法执行实际的删除
*/
private fun deleteSelf():Boolean {
synchronized (fs) {
try {
// 模板方法中子类根据需要判断是否删除权限
doDelete()
// 处理删除事件
handleDelete()
} catch (e: Exception) {
throw FileSystemException("delete.error", e, arrayOf(fileName))
}
return true
}
}
/**
* 实际删除文件的方法,子类需要重写(默认不执行任何动作),仅仅在以下条件下实际删除:
* 1. doGetType不为FileType.IMAGINARY
* 2. doIsWriteable返回true
*/
open protected fun doDelete() {
//do noting
}
/**
* 删除之后的事件处理
*/
protected fun handleDelete() {
if (attached) {
changeType(FileType.IMAGINARY)
removeChildrenCache()
// 触发通知
onChange()
}
//通知父对象
notifyParent(this.name(), FileType.IMAGINARY)
fs.fireFileDeleted(this)
}
/**
* 实际创建文件访问器
*/
open protected fun doCreateFileAssessor(): FileAccessor {
return getFileContentInfoFactory().create(this)
}
/**
* 从文件系统中获取文件访问器工厂
*/
open protected fun getFileContentInfoFactory(): FileAccessorInfoFactory {
return fs.getFileSystemManager().getFileAccessorInfoFactory()
}
override fun contentAccessor(): FileAccessor {
synchronized (fs) {
attach()
if (accessor == null) {
accessor = doCreateFileAssessor()
}
return accessor!!
}
}
/**
* 获取文件对象大小,抽象方法,子类必须实现
*/
protected abstract fun doGetContentSize(): Long
/**
* 创建一个文件输入流用于读取文件内容。抽象方法,子类必须实现
*/
protected abstract fun doGetInputStream(): InputStream
/**
* 获取文件的最后修改时间
*/
open protected fun doGetLastModifiedTime(): Long = getAttribute(FileObject.META_LAST_MODIFIED_CONTENT_TIME) as Long? ?:0L
/**
* 获取文件类型(注:FileType并非文件内容类型如DOC、pdf等)
*/
protected abstract fun doGetType(): FileType
/**
* 创建文件的随机访问器,子类必须实现的抽象方法
*/
abstract protected fun doGetRandomAccessor(mode: String): FileAccessor.RandomAccessor
/**
* 文件是否可运行
*/
open protected fun doIsExecutable(): Boolean = false
/**
* 文件是否隐藏
*/
open protected fun doIsHidden(): Boolean = false
/**
* 文件是否可读
*/
open protected fun doIsReadable(): Boolean = true
/**
* 判断两个文件是否相同,例如不区分大小写的windows文件
*/
open protected fun doIsSameFile(destFile: FileObject): Boolean = false
/**
* 文件是否可写
*/
protected fun doIsWriteable(): Boolean = true
/**
* 获取子文件名,子类必须实现的抽象方法
*/
protected abstract fun doListChildren(): Array<String>
/**
* 获取子文件,并解析为文件对象。这个方法非常耗时,因此实现需要缓冲返回的列表
*/
protected fun doListChildrenResolved(): Array<FileObject> {
return emptyArray()
}
/**
* 实际重命名文件,子类重写,默认为空
*/
open protected fun doRename(newFile: FileObject) {
//do nothing
}
/**
* 设置最后修改时间
*/
open protected fun doSetLastModifiedTime(modtime: Long): Boolean {
return try {
setAttribute(FileObject.META_LAST_MODIFIED_CONTENT_TIME, modtime)
true
} catch (e: Exception){
logger.error("set last modified time attr error!", e)
false
}
}
private fun setPrivilige(privilige:FilePrivilige):Boolean {
return try {
val scope = when(privilige.scope) {
PriviligeScope.OWNER -> FileObject.META_OWNER_RIVILIGE
PriviligeScope.GROUP -> FileObject.META_GROUP_RIVILIGE
PriviligeScope.ANY -> FileObject.META_ANY_RIVILIGE
else -> FileObject.META_ANY_RIVILIGE
}
setAttribute(scope, privilige.value)
true
} catch (e: Exception){
logger.error("set privilige attr error!", e)
false
}
}
private fun getPrivilige(scope: PriviligeScope): Int {
val scope = when(scope) {
PriviligeScope.OWNER -> FileObject.META_OWNER_RIVILIGE
PriviligeScope.GROUP -> FileObject.META_GROUP_RIVILIGE
PriviligeScope.ANY -> FileObject.META_ANY_RIVILIGE
else -> FileObject.META_ANY_RIVILIGE
}
return getAttribute(scope) as Int? ?: FilePrivilige.EMPTY_PRIVILIGE.value
}
/**
* 设置文件可运行属性
*/
open protected fun doSetExecutable(executable: Boolean, ownerOnly: Boolean): Boolean {
var s: Int = if (ownerOnly) getPrivilige(PriviligeScope.OWNER) else getPrivilige(PriviligeScope.ANY)
s = if (executable) s or FilePrivilige.PRIVILIGE_X else s and FilePrivilige.PRIVILIGE_X.inv()
val property = if (ownerOnly) FileObject.META_OWNER_RIVILIGE else FileObject.META_ANY_RIVILIGE
setAttribute(property, s)
return true
}
/**
* 设置文件可读属性
*/
open protected fun doSetReadable(readable: Boolean, ownerOnly: Boolean): Boolean {
var s: Int = if (ownerOnly) getPrivilige(PriviligeScope.OWNER) else getPrivilige(PriviligeScope.ANY)
s = if (readable) s or FilePrivilige.PRIVILIGE_R else s and FilePrivilige.PRIVILIGE_R.inv()
val property = if (ownerOnly) FileObject.META_OWNER_RIVILIGE else FileObject.META_ANY_RIVILIGE
setAttribute(property, s)
return true
}
/**
* 设置文件可写属性
*/
protected fun doSetWritable(writable: Boolean, ownerOnly: Boolean): Boolean {
var s: Int = if (ownerOnly) getPrivilige(PriviligeScope.OWNER) else getPrivilige(PriviligeScope.ANY)
s = if (writable) s or FilePrivilige.PRIVILIGE_W else s and FilePrivilige.PRIVILIGE_W.inv()
val property = if (ownerOnly) FileObject.META_OWNER_RIVILIGE else FileObject.META_ANY_RIVILIGE
setAttribute(property, s)
return true
}
override fun exists(): Boolean = type() != FileType.IMAGINARY
private fun extractNames(files: Array<FileObject>): Array<IFileName> = files.map {
it.name()
}.toTypedArray()
protected fun finalize() {
fs.fileObjectDestroyed(this)
}
override fun findFiles(selector: FileSelector, depthwise: Boolean): Array<FileObject> {
return try {
var list:MutableList<FileObject> = mutableListOf()
if (exists()) {
val info = DefaultFileInfo(this, this, 0)
traverse(info, selector, depthwise, list)
}
list.toTypedArray()
} catch (e:Exception) {
throw FileSystemException("find-files.error", e, arrayOf(fileName))
}
}
private fun resolveFile(child: IFileName): FileObject {
return fs.resolveFile(child)
}
override fun resolveFile(name: String, scope: NameScope): FileObject {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
private fun resolveFiles(children: Array<IFileName>): Array<FileObject> {
if (children == null) {
return emptyArray()
}
return children.map {
resolveFile(it)
}.toTypedArray()
}
override fun child(name: String): FileObject? {
children().forEach {
if (it.name().getBaseName() == name) {
return resolveFile(it as IFileName)
}
}
return null
}
override fun children(): Array<FileObject> {
synchronized (fs) {
val fileAttrStore = this.getAdapter(FileAttributeStore::class) as FileAttributeStore
if (!(fileAttrStore.getAttr(this, MetaOptions.__LIST_CHILDREN.name) as Boolean)) {
//文件不支持列举
throw FileSystemException("file-not-list", info = arrayOf(fileName))
}
attach()
if (children != null) {
return resolveFiles(children.toTypedArray())
}
try {
val childrenObjects = doListChildrenResolved()
children = extractNames(childrenObjects).toList()
if (childrenObjects.size > 0) {
return childrenObjects
}
val files = doListChildren()
if (files == null) {
throw FileNotFolderException(fileName)
} else if (files.size == 0) {
children = EMPTY_CHILDREN
} else {
var cache: MutableList<IFileName> = mutableListOf()
files.forEach {
fs.getRepository().resolveName(fileName, it, NameScope.CHILD)
}
children = cache
}
return resolveFiles(children.toTypedArray())
} catch (exc:Exception) {
throw FileSystemException("list-children.error", exc, arrayOf(fileName))
}
}
}
override fun fileOperations(): FileOperations {
if (this.operations == null){
this.operations = DefaultFileOperations(this)
}
return this.operations!!
}
override fun fileSystem(): FileSystem = fs
/**
* 用户读取文件内容的原始输入流
* @throws FileSystemException 如果发生错误
*/
fun getInputStream(): InputStream = try {
doGetInputStream()
} catch (exc: org.open.openstore.file.FileNotFoundException) {
throw org.open.openstore.file.FileNotFoundException(fileName, exc)
} catch (exc: java.io.FileNotFoundException) {
throw org.open.openstore.file.FileNotFoundException(fileName, exc)
} catch (exc: FileSystemException) {
throw exc
} catch (exc: Exception) {
throw FileSystemException("read.error", exc, arrayOf(fileName))
}
override fun name(): IFileName = this.fileName
override fun publicuri(): String = this.fileName.getFriendlyURI()
override fun parent(): FileObject? {
if (this.compareTo(fs.getRoot()) == 0)
{
return fs.getParentLayer()?.parent()
}
synchronized (fs) {
// Locate the parent of this file
if (parent == null) {
val name = fileName.getParent()
name?.let {
parent = fs.resolveFile(name)
}?: return null
}
return parent
}
}
/**
* 返回随机读写器
* @param mode 通常为r-读,w-写
*/
open fun getRandomAccessContent(mode: String): FileAccessor.RandomAccessor {
val fileAttrStore = this.getAdapter(FileAttributeStore::class) as FileAttributeStore
if (mode == "r") {
if (!(fileAttrStore.getAttr(this, MetaOptions.__RANDOM_ACCESS_READ.name) as Boolean)) {
throw FileSystemException("random-access-read-not-supported.error")
}
if (!isReadable()) {
throw FileSystemException("vread-not-readable.error", info = arrayOf(fileName))
}
}
if (mode == "w") {
if (!(fileAttrStore.getAttr(this, MetaOptions.__RANDOM_ACCESS_READ.name) as Boolean)) {
throw FileSystemException("random-access-write-not-supported.error")
}
if (!isWriteable()) {
throw FileSystemException("write-read-only.error", info = arrayOf(fileName))
}
}
return try {
doGetRandomAccessor(mode)
} catch (exc: Exception) {
throw FileSystemException("vfs.provider/random-access.error", exc, info = arrayOf(fileName))
}
}
override fun type(): FileType {
synchronized(fs) {
attach()
return try {
if (type == null) {
doGetType()?.let {
setFileType(it)
}?: setFileType(FileType.IMAGINARY)
}
type!!
} catch (e: Exception) {
throw FileSystemException("get-type.error", e, info = arrayOf(fileName))
}
}
}
override fun url(): URL {
try {
return AccessController.doPrivileged(PrivilegedExceptionAction {
val buf = StringBuilder()
val scheme = UriParser.extractScheme(fileName.getURI(), buf)
URL(scheme!!, "", -1, buf.toString(), DefaultURLStreamHandler(fs.getRepository(), fs.getFileSystemOptions()))
})
} catch (e: PrivilegedActionException) {
throw FileSystemException("get-url.error", e.exception, info = arrayOf(fileName))
}
}
} | gpl-3.0 | 69bfc75a1247532ffce1369a2056abbc | 28.949761 | 135 | 0.553701 | 4.326421 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/service/webrtc/AndroidCallConnection.kt | 1 | 4013 | package org.thoughtcrime.securesms.service.webrtc
import android.content.Context
import android.content.Intent
import android.telecom.CallAudioState
import android.telecom.Connection
import androidx.annotation.RequiresApi
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.WebRtcCallActivity
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.permissions.Permissions
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.webrtc.CallNotificationBuilder
import org.thoughtcrime.securesms.webrtc.audio.AudioManagerCommand
import org.thoughtcrime.securesms.webrtc.audio.SignalAudioManager
/**
* Signal implementation for the telecom system connection. Provides an interaction point for the system to
* inform us about changes in the telecom system. Created and returned by [AndroidCallConnectionService].
*/
@RequiresApi(26)
class AndroidCallConnection(
private val context: Context,
private val recipientId: RecipientId,
isOutgoing: Boolean,
isVideoCall: Boolean
) : Connection() {
private var needToResetAudioRoute = isOutgoing && !isVideoCall
private var initialAudioRoute: SignalAudioManager.AudioDevice? = null
init {
connectionProperties = PROPERTY_SELF_MANAGED
connectionCapabilities = CAPABILITY_SUPPORTS_VT_LOCAL_BIDIRECTIONAL or
CAPABILITY_SUPPORTS_VT_REMOTE_BIDIRECTIONAL or
CAPABILITY_MUTE
}
override fun onShowIncomingCallUi() {
Log.i(TAG, "onShowIncomingCallUi()")
WebRtcCallService.update(context, CallNotificationBuilder.TYPE_INCOMING_CONNECTING, recipientId)
setRinging()
}
override fun onCallAudioStateChanged(state: CallAudioState) {
Log.i(TAG, "onCallAudioStateChanged($state)")
val activeDevice = state.route.toDevices().firstOrNull() ?: SignalAudioManager.AudioDevice.EARPIECE
val availableDevices = state.supportedRouteMask.toDevices()
ApplicationDependencies.getSignalCallManager().onAudioDeviceChanged(activeDevice, availableDevices)
if (needToResetAudioRoute) {
if (initialAudioRoute == null) {
initialAudioRoute = activeDevice
} else if (activeDevice == SignalAudioManager.AudioDevice.SPEAKER_PHONE) {
Log.i(TAG, "Resetting audio route from SPEAKER_PHONE to $initialAudioRoute")
AndroidTelecomUtil.selectAudioDevice(recipientId, initialAudioRoute!!)
needToResetAudioRoute = false
}
}
}
override fun onAnswer(videoState: Int) {
Log.i(TAG, "onAnswer($videoState)")
if (Permissions.hasAll(context, android.Manifest.permission.RECORD_AUDIO)) {
ApplicationDependencies.getSignalCallManager().acceptCall(false)
} else {
val intent = Intent(context, WebRtcCallActivity::class.java)
intent.action = WebRtcCallActivity.ANSWER_ACTION
intent.flags = intent.flags or Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
}
}
override fun onSilence() {
WebRtcCallService.sendAudioManagerCommand(context, AudioManagerCommand.SilenceIncomingRinger())
}
override fun onReject() {
Log.i(TAG, "onReject()")
WebRtcCallService.denyCall(context)
}
override fun onDisconnect() {
Log.i(TAG, "onDisconnect()")
WebRtcCallService.hangup(context)
}
companion object {
private val TAG: String = Log.tag(AndroidCallConnection::class.java)
}
}
private fun Int.toDevices(): Set<SignalAudioManager.AudioDevice> {
val devices = mutableSetOf<SignalAudioManager.AudioDevice>()
if (this and CallAudioState.ROUTE_BLUETOOTH != 0) {
devices += SignalAudioManager.AudioDevice.BLUETOOTH
}
if (this and CallAudioState.ROUTE_EARPIECE != 0) {
devices += SignalAudioManager.AudioDevice.EARPIECE
}
if (this and CallAudioState.ROUTE_WIRED_HEADSET != 0) {
devices += SignalAudioManager.AudioDevice.WIRED_HEADSET
}
if (this and CallAudioState.ROUTE_SPEAKER != 0) {
devices += SignalAudioManager.AudioDevice.SPEAKER_PHONE
}
return devices
}
| gpl-3.0 | 652a6baa981c9b1df82842dbacac4ff4 | 33.895652 | 107 | 0.766758 | 4.463849 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/expectactual/ExpectActualUtils.kt | 1 | 19748 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.expectactual
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaDirectoryService
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester
import org.jetbrains.kotlin.idea.base.psi.isInlineOrValue
import org.jetbrains.kotlin.idea.base.psi.mustHaveValOrVar
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.names.FqNames
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToBeShortenedDescendantsToWaitingSet
import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor
import org.jetbrains.kotlin.idea.core.findOrCreateDirectoryForPackage
import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix
import org.jetbrains.kotlin.idea.core.overrideImplement.BodyType.EmptyOrTemplate
import org.jetbrains.kotlin.idea.core.overrideImplement.BodyType.NoBody
import org.jetbrains.kotlin.idea.core.overrideImplement.MemberGenerateMode
import org.jetbrains.kotlin.idea.core.overrideImplement.OverrideMemberChooserObject.Companion.create
import org.jetbrains.kotlin.idea.core.overrideImplement.generateMember
import org.jetbrains.kotlin.idea.core.overrideImplement.makeNotActual
import org.jetbrains.kotlin.idea.core.toDescriptor
import org.jetbrains.kotlin.idea.quickfix.TypeAccessibilityChecker
import org.jetbrains.kotlin.idea.refactoring.createKotlinFile
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.refactoring.introduce.showErrorHint
import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import com.intellij.openapi.application.runWriteAction
import org.jetbrains.kotlin.idea.util.isEffectivelyActual
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.checkers.OptInNames
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.multiplatform.OptionalAnnotationUtil
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
fun createFileForDeclaration(module: Module, declaration: KtNamedDeclaration): KtFile? {
val fileName = declaration.name ?: return null
val originalDir = declaration.containingFile.containingDirectory
val containerPackage = JavaDirectoryService.getInstance().getPackage(originalDir)
val packageDirective = declaration.containingKtFile.packageDirective
val directory = findOrCreateDirectoryForPackage(
module, containerPackage?.qualifiedName ?: ""
) ?: return null
return runWriteAction {
val fileNameWithExtension = "$fileName.kt"
val existingFile = directory.findFile(fileNameWithExtension)
val packageName =
if (packageDirective?.packageNameExpression == null) directory.getFqNameWithImplicitPrefix()?.asString()
else packageDirective.fqName.asString()
if (existingFile is KtFile) {
val existingPackageDirective = existingFile.packageDirective
if (existingFile.declarations.isNotEmpty() &&
existingPackageDirective?.fqName != packageDirective?.fqName
) {
val newName = Fe10KotlinNameSuggester.suggestNameByName(fileName) {
directory.findFile("$it.kt") == null
} + ".kt"
createKotlinFile(newName, directory, packageName)
} else {
existingFile
}
} else {
createKotlinFile(fileNameWithExtension, directory, packageName)
}
}
}
fun KtPsiFactory.createClassHeaderCopyByText(originalClass: KtClassOrObject): KtClassOrObject {
val text = originalClass.text
return when (originalClass) {
is KtObjectDeclaration -> if (originalClass.isCompanion()) {
createCompanionObject(text)
} else {
createObject(text)
}
is KtEnumEntry -> createEnumEntry(text)
else -> createClass(text)
}.apply {
declarations.forEach(KtDeclaration::delete)
primaryConstructor?.delete()
}
}
fun KtNamedDeclaration?.getTypeDescription(): String = when (this) {
is KtObjectDeclaration -> KotlinBundle.message("text.object")
is KtClass -> when {
isInterface() -> KotlinBundle.message("text.interface")
isEnum() -> KotlinBundle.message("text.enum.class")
isAnnotation() -> KotlinBundle.message("text.annotation.class")
else -> KotlinBundle.message("text.class")
}
is KtProperty, is KtParameter -> KotlinBundle.message("text.property")
is KtFunction -> KotlinBundle.message("text.function")
else -> KotlinBundle.message("text.declaration")
}
internal fun KtPsiFactory.generateClassOrObject(
project: Project,
generateExpectClass: Boolean,
originalClass: KtClassOrObject,
checker: TypeAccessibilityChecker
): KtClassOrObject {
val generatedClass = createClassHeaderCopyByText(originalClass)
val context = originalClass.analyzeWithContent()
val superNames = repairSuperTypeList(
generatedClass,
originalClass,
generateExpectClass,
checker,
context
)
generatedClass.annotationEntries.zip(originalClass.annotationEntries).forEach { (generatedEntry, originalEntry) ->
val annotationDescriptor = context.get(BindingContext.ANNOTATION, originalEntry)
if (annotationDescriptor?.isValidInModule(checker) != true) {
generatedEntry.delete()
}
}
if (generateExpectClass) {
if (originalClass.isTopLevel()) {
generatedClass.addModifier(KtTokens.EXPECT_KEYWORD)
} else {
generatedClass.makeNotActual()
}
generatedClass.removeModifier(KtTokens.DATA_KEYWORD)
} else {
if (generatedClass !is KtEnumEntry) {
generatedClass.addModifier(KtTokens.ACTUAL_KEYWORD)
}
}
val existingFqNamesWithSuperTypes = (checker.existingTypeNames + superNames).toSet()
declLoop@ for (originalDeclaration in originalClass.declarations) {
val descriptor = originalDeclaration.toDescriptor() ?: continue
if (generateExpectClass && !originalDeclaration.isEffectivelyActual(false)) continue
val generatedDeclaration: KtDeclaration = when (originalDeclaration) {
is KtClassOrObject -> generateClassOrObject(
project,
generateExpectClass,
originalDeclaration,
checker
)
is KtFunction, is KtProperty -> checker.runInContext(existingFqNamesWithSuperTypes) {
generateCallable(
project,
generateExpectClass,
originalDeclaration as KtCallableDeclaration,
descriptor as CallableMemberDescriptor,
generatedClass,
this
)
}
else -> continue@declLoop
}
generatedClass.addDeclaration(generatedDeclaration)
}
if (!originalClass.isAnnotation() && originalClass.safeAs<KtClass>()?.isInlineOrValue() == false) {
for (originalProperty in originalClass.primaryConstructorParameters) {
if (!originalProperty.hasValOrVar() || !originalProperty.hasActualModifier()) continue
val descriptor = originalProperty.toDescriptor() as? PropertyDescriptor ?: continue
checker.runInContext(existingFqNamesWithSuperTypes) {
val generatedProperty = generateCallable(
project,
generateExpectClass,
originalProperty,
descriptor,
generatedClass,
this
)
generatedClass.addDeclaration(generatedProperty)
}
}
}
val originalPrimaryConstructor = originalClass.primaryConstructor
if (
generatedClass is KtClass
&& originalPrimaryConstructor != null
&& (!generateExpectClass || originalPrimaryConstructor.hasActualModifier())
) {
val descriptor = originalPrimaryConstructor.toDescriptor()
if (descriptor is FunctionDescriptor) {
checker.runInContext(existingFqNamesWithSuperTypes) {
val expectedPrimaryConstructor = generateCallable(
project,
generateExpectClass,
originalPrimaryConstructor,
descriptor,
generatedClass,
this
)
generatedClass.createPrimaryConstructorIfAbsent().replace(expectedPrimaryConstructor)
}
}
}
return generatedClass
}
private fun KtPsiFactory.repairSuperTypeList(
generated: KtClassOrObject,
original: KtClassOrObject,
generateExpectClass: Boolean,
checker: TypeAccessibilityChecker,
context: BindingContext
): Collection<String> {
val superNames = linkedSetOf<String>()
val typeParametersFqName = context[BindingContext.DECLARATION_TO_DESCRIPTOR, original]
?.safeAs<ClassDescriptor>()
?.declaredTypeParameters?.mapNotNull { it.fqNameOrNull()?.asString() }.orEmpty()
checker.runInContext(checker.existingTypeNames + typeParametersFqName) {
generated.superTypeListEntries.zip(original.superTypeListEntries).forEach { (generatedEntry, originalEntry) ->
val superType = context[BindingContext.TYPE, originalEntry.typeReference]
val superClassDescriptor = superType?.constructor?.declarationDescriptor as? ClassDescriptor ?: return@forEach
if (generateExpectClass && !checker.checkAccessibility(superType)) {
generatedEntry.delete()
return@forEach
}
superType.fqName?.shortName()?.asString()?.let { superNames += it }
if (generateExpectClass) {
if (generatedEntry !is KtSuperTypeCallEntry) return@forEach
} else {
if (generatedEntry !is KtSuperTypeEntry) return@forEach
}
if (superClassDescriptor.kind == ClassKind.CLASS || superClassDescriptor.kind == ClassKind.ENUM_CLASS) {
val entryText = IdeDescriptorRenderers.SOURCE_CODE.renderType(superType)
val newGeneratedEntry = if (generateExpectClass) {
createSuperTypeEntry(entryText)
} else {
createSuperTypeCallEntry("$entryText()")
}
generatedEntry.replace(newGeneratedEntry).safeAs<KtElement>()?.addToBeShortenedDescendantsToWaitingSet()
}
}
}
if (generated.superTypeListEntries.isEmpty()) generated.getSuperTypeList()?.delete()
return superNames
}
private val forbiddenAnnotationFqNames = setOf(
OptionalAnnotationUtil.OPTIONAL_EXPECTATION_FQ_NAME,
FqName("kotlin.ExperimentalMultiplatform"),
OptInNames.OPT_IN_FQ_NAME,
FqNames.OptInFqNames.OLD_USE_EXPERIMENTAL_FQ_NAME
)
internal fun generateCallable(
project: Project,
generateExpect: Boolean,
originalDeclaration: KtDeclaration,
descriptor: CallableMemberDescriptor,
generatedClass: KtClassOrObject? = null,
checker: TypeAccessibilityChecker
): KtCallableDeclaration {
descriptor.checkAccessibility(checker)
val memberChooserObject = create(
originalDeclaration, descriptor, descriptor,
if (generateExpect || descriptor.modality == Modality.ABSTRACT) NoBody else EmptyOrTemplate
)
return memberChooserObject.generateMember(
targetClass = generatedClass,
copyDoc = true,
project = project,
mode = if (generateExpect) MemberGenerateMode.EXPECT else MemberGenerateMode.ACTUAL
).apply {
repair(generatedClass, descriptor, checker)
}
}
private fun CallableMemberDescriptor.checkAccessibility(checker: TypeAccessibilityChecker) {
val errors = checker.incorrectTypes(this).ifEmpty { return }
throw KotlinTypeInaccessibleException(errors.toSet())
}
private fun KtCallableDeclaration.repair(
generatedClass: KtClassOrObject?,
descriptor: CallableDescriptor,
checker: TypeAccessibilityChecker
) {
if (generatedClass != null) repairOverride(descriptor, checker)
repairAnnotationEntries(this, descriptor, checker)
}
private fun KtCallableDeclaration.repairOverride(descriptor: CallableDescriptor, checker: TypeAccessibilityChecker) {
if (!hasModifier(KtTokens.OVERRIDE_KEYWORD)) return
val superDescriptor = descriptor.overriddenDescriptors.firstOrNull()?.containingDeclaration
if (superDescriptor?.fqNameOrNull()?.shortName()?.asString() !in checker.existingTypeNames) {
removeModifier(KtTokens.OVERRIDE_KEYWORD)
}
}
private fun repairAnnotationEntries(
target: KtModifierListOwner,
descriptor: DeclarationDescriptorNonRoot,
checker: TypeAccessibilityChecker
) {
repairAnnotations(checker, target, descriptor.annotations)
when (descriptor) {
is ValueParameterDescriptor -> {
if (target !is KtParameter) return
val typeReference = target.typeReference ?: return
repairAnnotationEntries(typeReference, descriptor.type, checker)
}
is TypeParameterDescriptor -> {
if (target !is KtTypeParameter) return
val extendsBound = target.extendsBound ?: return
for (upperBound in descriptor.upperBounds) {
repairAnnotationEntries(extendsBound, upperBound, checker)
}
}
is CallableDescriptor -> {
val extension = descriptor.extensionReceiverParameter
val receiver = target.safeAs<KtCallableDeclaration>()?.receiverTypeReference
if (extension != null && receiver != null) {
repairAnnotationEntries(receiver, extension, checker)
}
val callableDeclaration = target.safeAs<KtCallableDeclaration>() ?: return
callableDeclaration.typeParameters.zip(descriptor.typeParameters).forEach { (typeParameter, typeParameterDescriptor) ->
repairAnnotationEntries(typeParameter, typeParameterDescriptor, checker)
}
callableDeclaration.valueParameters.zip(descriptor.valueParameters).forEach { (valueParameter, valueParameterDescriptor) ->
repairAnnotationEntries(valueParameter, valueParameterDescriptor, checker)
}
}
}
}
private fun repairAnnotationEntries(
typeReference: KtTypeReference,
type: KotlinType,
checker: TypeAccessibilityChecker
) {
repairAnnotations(checker, typeReference, type.annotations)
typeReference.typeElement?.typeArgumentsAsTypes?.zip(type.arguments)?.forEach { (reference, projection) ->
repairAnnotationEntries(reference, projection.type, checker)
}
}
private fun repairAnnotations(checker: TypeAccessibilityChecker, target: KtModifierListOwner, annotations: Annotations) {
for (annotation in annotations) {
if (annotation.isValidInModule(checker)) {
checkAndAdd(annotation, checker, target)
}
}
}
private fun checkAndAdd(annotationDescriptor: AnnotationDescriptor, checker: TypeAccessibilityChecker, target: KtModifierListOwner) {
if (annotationDescriptor.isValidInModule(checker)) {
val entry = annotationDescriptor.source.safeAs<KotlinSourceElement>()?.psi.safeAs<KtAnnotationEntry>() ?: return
target.addAnnotationEntry(entry)
}
}
private fun AnnotationDescriptor.isValidInModule(checker: TypeAccessibilityChecker): Boolean {
return fqName !in forbiddenAnnotationFqNames && checker.checkAccessibility(type)
}
class KotlinTypeInaccessibleException(fqNames: Collection<FqName?>) : Exception() {
override val message: String = KotlinBundle.message(
"type.0.1.is.not.accessible.from.target.module",
fqNames.size,
TypeAccessibilityChecker.typesToString(fqNames)
)
}
fun KtNamedDeclaration.isAlwaysActual(): Boolean = safeAs<KtParameter>()?.parent?.parent?.safeAs<KtPrimaryConstructor>()
?.mustHaveValOrVar() ?: false
fun TypeAccessibilityChecker.isCorrectAndHaveAccessibleModifiers(declaration: KtNamedDeclaration, showErrorHint: Boolean = false): Boolean {
if (declaration.anyInaccessibleModifier(INACCESSIBLE_MODIFIERS, showErrorHint)) return false
if (declaration is KtFunction && declaration.hasBody() && declaration.containingClassOrObject?.isInterfaceClass() == true) {
if (showErrorHint) showInaccessibleDeclarationError(
declaration,
KotlinBundle.message("the.function.declaration.shouldn.t.have.a.default.implementation")
)
return false
}
if (!showErrorHint) return checkAccessibility(declaration)
val types = incorrectTypes(declaration).ifEmpty { return true }
showInaccessibleDeclarationError(
declaration,
KotlinBundle.message(
"some.types.are.not.accessible.from.0.1",
targetModule.name,
TypeAccessibilityChecker.typesToString(types)
)
)
return false
}
private val INACCESSIBLE_MODIFIERS = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.CONST_KEYWORD, KtTokens.LATEINIT_KEYWORD)
private fun KtModifierListOwner.anyInaccessibleModifier(modifiers: Collection<KtModifierKeywordToken>, showErrorHint: Boolean): Boolean {
for (modifier in modifiers) {
if (hasModifier(modifier)) {
if (showErrorHint) showInaccessibleDeclarationError(this, KotlinBundle.message("the.declaration.has.0.modifier", modifier))
return true
}
}
return false
}
fun showInaccessibleDeclarationError(element: PsiElement, message: String, editor: Editor? = element.findExistingEditor()) {
editor?.let {
showErrorHint(element.project, editor, escapeXml(message), KotlinBundle.message("inaccessible.declaration"))
}
}
fun TypeAccessibilityChecker.Companion.typesToString(types: Collection<FqName?>, separator: CharSequence = "\n"): String {
return types.toSet().joinToString(separator = separator) {
it?.shortName()?.asString() ?: "<Unknown>"
}
}
fun TypeAccessibilityChecker.findAndApplyExistingClasses(elements: Collection<KtNamedDeclaration>): Set<String> {
var classes = elements.filterIsInstance<KtClassOrObject>()
while (classes.isNotEmpty()) {
val existingNames = classes.mapNotNull { it.fqName?.asString() }.toHashSet()
existingTypeNames = existingNames
val newExistingClasses = classes.filter { isCorrectAndHaveAccessibleModifiers(it) }
if (classes.size == newExistingClasses.size) return existingNames
classes = newExistingClasses
}
return existingTypeNames
}
| apache-2.0 | e357ddf3f10868e8391ba0c871b75327 | 42.307018 | 158 | 0.713287 | 5.480988 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/advertiser/OnDemandPluginFeatureEnablerImpl.kt | 2 | 3194 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.plugins.advertiser
import com.intellij.ide.IdeBundle
import com.intellij.ide.plugins.*
import com.intellij.notification.NotificationType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.UnknownFeaturesCollector
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.notificationGroup
import com.intellij.util.concurrency.annotations.RequiresEdt
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus
import kotlin.coroutines.coroutineContext
private val LOG get() = logger<OnDemandPluginFeatureEnablerImpl>()
@ApiStatus.Experimental
private class OnDemandPluginFeatureEnablerImpl(private val project: Project) : PluginFeatureEnabler,
Disposable {
private val coroutineScope = CoroutineScope(SupervisorJob())
override suspend fun enableSuggested(): Boolean {
val application = ApplicationManager.getApplication()
LOG.assertTrue(!application.isReadAccessAllowed
|| application.isUnitTestMode)
if (!IdeaPluginDescriptorImpl.isOnDemandEnabled) {
return false
}
coroutineContext.ensureActive()
val featureService = PluginFeatureService.instance
val pluginEnabler = PluginEnabler.getInstance() as? DynamicPluginEnabler
?: return false
val pluginSet = PluginManagerCore.getPluginSet()
val descriptors = UnknownFeaturesCollector.getInstance(project)
.getUnknownFeaturesOfType(DEPENDENCY_SUPPORT_FEATURE)
.asSequence()
.mapNotNull { unknownFeature ->
featureService.getPluginForFeature(
unknownFeature.featureType,
unknownFeature.implementationName,
)
}.map { it.pluginData.pluginId }
.filterNot { pluginEnabler.isDisabled(it) }
.filterNot { pluginSet.isPluginEnabled(it) }
.mapNotNull { pluginSet.findInstalledPlugin(it) }
.filter { it.isOnDemand }
.toList()
if (descriptors.isEmpty()) {
return false
}
return withContext(Dispatchers.EDT) {
val result = pluginEnabler.enable(descriptors, project)
if (!application.isUnitTestMode) {
notifyUser(descriptors)
}
result
}
}
override fun scheduleEnableSuggested() {
coroutineScope.launch(Dispatchers.IO) {
enableSuggested()
}
}
override fun dispose() {
coroutineScope.cancel()
}
@RequiresEdt
private fun notifyUser(descriptors: List<IdeaPluginDescriptorImpl>) {
val message = IdeBundle.message(
"plugins.advertiser.enabled.on.demand",
descriptors.size,
descriptors.map { it.name },
)
notificationGroup.createNotification(message, NotificationType.INFORMATION)
.setDisplayId("advertiser.enable.on.demand")
.notify(project)
}
} | apache-2.0 | e4a345156a377864b84f7ff1b1022e9c | 32.631579 | 120 | 0.726049 | 5.085987 | false | false | false | false |
rei-m/HBFav_material | app/src/main/kotlin/me/rei_m/hbfavmaterial/infra/network/response/EntryRssXml.kt | 1 | 919 | /*
* Copyright (c) 2017. Rei Matsushita
*
* 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 me.rei_m.hbfavmaterial.infra.network.response
import org.simpleframework.xml.ElementList
import org.simpleframework.xml.Root
@Root(name = "rdf:RDF", strict = false)
class EntryRssXml {
@set:ElementList(inline = true)
@get:ElementList(inline = true)
var list: MutableList<EntryRssItemXml> = arrayListOf()
}
| apache-2.0 | 0ca03be32fb8fde4752c85bbfac1aa5c | 37.291667 | 112 | 0.751904 | 3.961207 | false | false | false | false |
bjansen/pebble-intellij | src/main/kotlin/com/github/bjansen/intellij/pebble/ext/SpringExtension.kt | 1 | 7982 | package com.github.bjansen.intellij.pebble.ext
import com.github.bjansen.intellij.pebble.psi.PebbleFile
import com.github.bjansen.intellij.pebble.psi.PebbleIdentifier
import com.github.bjansen.intellij.pebble.psi.PebbleReferencesHelper.buildPsiTypeLookups
import com.github.bjansen.intellij.pebble.psi.PebbleReferencesHelper.findMembersByName
import com.github.bjansen.intellij.pebble.psi.PebbleReferencesHelper.findQualifyingMember
import com.github.bjansen.intellij.pebble.utils.ResourceUtil
import com.intellij.codeInsight.completion.PrioritizedLookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.TextRange
import com.intellij.patterns.PlatformPatterns
import com.intellij.pom.PomTargetPsiElement
import com.intellij.psi.*
import com.intellij.psi.PsiElementResolveResult.createResults
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiTypesUtil
import com.intellij.spring.SpringManager
import com.intellij.spring.contexts.model.SpringModel
import com.intellij.spring.model.CommonSpringBean
import com.intellij.spring.model.jam.JamPsiClassSpringBean
import com.intellij.spring.model.jam.JamPsiMethodSpringBean
import com.intellij.spring.model.pom.SpringBeanPomTargetUtils
import com.intellij.spring.model.utils.SpringModelSearchers
import com.intellij.spring.model.xml.AbstractDomSpringBean
import com.intellij.util.ProcessingContext
import javax.swing.Icon
object SpringExtension {
private val key = Key.create<PsiClass>("PEBBLE_SPRING_CLASS")
private fun getPebbleSpringClass(project: Project): PsiClass? {
return ResourceUtil.loadPsiClassFromFile("/implicitCode/PebbleSpring.java", key, project)
}
fun getImplicitVariables(file: PebbleFile): List<PsiVariable> {
if (isPebbleSpringAvailable(file) || ApplicationManager.getApplication().isUnitTestMode) {
val clazz = getPebbleSpringClass(file.project)
if (clazz != null) {
return clazz.fields.asList()
}
}
return emptyList()
}
fun getImplicitFunctions(file: PebbleFile): List<PsiMethod> {
if (isPebbleSpringAvailable(file) || ApplicationManager.getApplication().isUnitTestMode) {
val clazz = getPebbleSpringClass(file.project)
if (clazz != null) {
return clazz.methods.asList()
}
}
return emptyList()
}
private fun getSearchScope(file: PsiFile): GlobalSearchScope? {
val module = ModuleUtil.findModuleForPsiElement(file)
return module?.getModuleWithDependenciesAndLibrariesScope(false)
}
internal fun isPebbleSpringAvailable(file: PsiFile): Boolean {
val scope = getSearchScope(file)
if (scope != null) {
val spring3 = JavaPsiFacade.getInstance(file.project)
.findClass("com.mitchellbosecke.pebble.spring.PebbleView", scope)
val spring4 = JavaPsiFacade.getInstance(file.project)
.findClass("com.mitchellbosecke.pebble.spring4.PebbleView", scope)
val spring5 = JavaPsiFacade.getInstance(file.project)
.findClass("com.mitchellbosecke.pebble.spring.servlet.PebbleView", scope)
return spring3 != null || spring4 != null || spring5 != null
}
return false
}
}
class PebbleSpringReferenceContributor : PsiReferenceContributor() {
override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) {
registrar.registerReferenceProvider(
PlatformPatterns.psiElement(PebbleIdentifier::class.java),
PebbleSpringReferenceProvider()
)
}
}
/**
* Provides references to Spring beans in expressions like `beans.myBean`.
*/
class PebbleSpringReferenceProvider : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> {
return if (SpringExtension.isPebbleSpringAvailable(element.containingFile)) {
arrayOf(PebbleSpringReference(element, TextRange.from(0, element.node.textLength)))
} else {
emptyArray()
}
}
}
class PebbleSpringReference(private val psi: PsiElement, private val range: TextRange)
: PsiPolyVariantReferenceBase<PsiElement>(psi, range) {
val springBeanIcon: Icon? by lazy {
var clazz: Class<*>?
try {
clazz = Class.forName("icons.SpringApiIcons")
} catch (e: ClassNotFoundException) {
clazz = Class.forName("com.intellij.spring.SpringApiIcons")
}
clazz?.getField("SpringBean")?.get(clazz) as Icon
}
private fun isBeansField(field: PsiField) =
field.name == "beans" && field.containingClass?.qualifiedName == "PebbleSpring"
private fun getSpringModel(context: PsiElement): SpringModel? {
val module = ModuleUtil.findModuleForPsiElement(context)
if (module != null) {
return SpringManager.getInstance(context.project).getCombinedModel(module)
}
return null
}
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
val qualifyingMember = findQualifyingMember(psi)
val referenceText = range.substring(psi.text)
if (qualifyingMember is PsiField && isBeansField(qualifyingMember)) {
val model = getSpringModel(psi)
if (model != null) {
val bean = SpringModelSearchers.findBean(model, referenceText)
if (bean != null) {
return createResults(bean.psiElement)
}
}
} else if (qualifyingMember is PomTargetPsiElement) {
val springBeanType = getBeanType(SpringBeanPomTargetUtils.getSpringBean(qualifyingMember))
if (springBeanType is PsiClassType) {
return createResults(findMembersByName(springBeanType.resolve(), referenceText))
}
}
return emptyArray()
}
override fun getVariants(): Array<Any> {
val qualifyingMember = findQualifyingMember(psi)
if (qualifyingMember is PsiField && isBeansField(qualifyingMember)) {
val model = getSpringModel(psi)
if (model != null) {
return model.allCommonBeans
.filter { getBeanType(it.springBean) != null }
.mapNotNull {
val lookup = LookupElementBuilder.create(it.name ?: "?")
.withTypeText(it.beanClass?.name)
.withIcon(springBeanIcon)
PrioritizedLookupElement.withPriority(lookup, 1.0)
}
.toTypedArray()
}
} else if (qualifyingMember is PomTargetPsiElement) {
val springBeanType = getBeanType(SpringBeanPomTargetUtils.getSpringBean(qualifyingMember))
if (springBeanType is PsiClassType) {
return buildPsiTypeLookups(springBeanType)
}
}
return emptyArray()
}
/**
* Workaround for com.intellij.spring.model.CommonSpringBean.getBeanType() which is not in IDEA 15
*/
private fun getBeanType(springBean: CommonSpringBean?): PsiType? {
return when (springBean) {
is AbstractDomSpringBean -> {
val clazz = springBean.getBeanClass(null, true)
return if (clazz == null) null else PsiTypesUtil.getClassType(clazz)
}
is JamPsiClassSpringBean -> PsiTypesUtil.getClassType(springBean.psiElement)
is JamPsiMethodSpringBean -> springBean.psiElement.returnType
else -> null
}
}
}
| mit | 2e8baf24865c5a033da0416c693b53a3 | 39.72449 | 111 | 0.677149 | 4.825877 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddForLoopIndicesIntention.kt | 3 | 4833 | // 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.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.idea.codeinsight.utils.ChooseStringExpression
class AddForLoopIndicesIntention : SelfTargetingRangeIntention<KtForExpression>(
KtForExpression::class.java,
KotlinBundle.lazyMessage("add.indices.to.for.loop"),
), LowPriorityAction {
override fun applicabilityRange(element: KtForExpression): TextRange? {
if (element.loopParameter == null) return null
if (element.loopParameter?.destructuringDeclaration != null) return null
val loopRange = element.loopRange ?: return null
val bindingContext = element.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
val resolvedCall = loopRange.getResolvedCall(bindingContext)
if (resolvedCall?.resultingDescriptor?.fqNameUnsafe?.asString() in WITH_INDEX_FQ_NAMES) return null // already withIndex() call
val potentialExpression = createWithIndexExpression(loopRange, reformat = false)
val newBindingContext = potentialExpression.analyzeAsReplacement(loopRange, bindingContext)
val newResolvedCall = potentialExpression.getResolvedCall(newBindingContext) ?: return null
if (newResolvedCall.resultingDescriptor.fqNameUnsafe.asString() !in WITH_INDEX_FQ_NAMES) return null
return TextRange(element.startOffset, element.body?.startOffset ?: element.endOffset)
}
override fun applyTo(element: KtForExpression, editor: Editor?) {
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val loopRange = element.loopRange!!
val loopParameter = element.loopParameter!!
val psiFactory = KtPsiFactory(element)
loopRange.replace(createWithIndexExpression(loopRange, reformat = true))
var multiParameter = (psiFactory.createExpressionByPattern(
"for((index, $0) in x){}",
loopParameter.text
) as KtForExpression).destructuringDeclaration!!
multiParameter = loopParameter.replaced(multiParameter)
val indexVariable = multiParameter.entries[0]
editor.caretModel.moveToOffset(indexVariable.startOffset)
runTemplate(editor, element, indexVariable)
}
private fun runTemplate(editor: Editor, forExpression: KtForExpression, indexVariable: KtDestructuringDeclarationEntry) {
PsiDocumentManager.getInstance(forExpression.project).doPostponedOperationsAndUnblockDocument(editor.document)
val templateBuilder = TemplateBuilderImpl(forExpression)
templateBuilder.replaceElement(indexVariable, ChooseStringExpression(listOf("index", "i")))
when (val body = forExpression.body) {
is KtBlockExpression -> {
val statement = body.statements.firstOrNull()
if (statement != null) {
templateBuilder.setEndVariableBefore(statement)
} else {
templateBuilder.setEndVariableAfter(body.lBrace)
}
}
null -> forExpression.rightParenthesis.let { templateBuilder.setEndVariableAfter(it) }
else -> templateBuilder.setEndVariableBefore(body)
}
templateBuilder.run(editor, true)
}
private fun createWithIndexExpression(originalExpression: KtExpression, reformat: Boolean): KtExpression =
KtPsiFactory(originalExpression).createExpressionByPattern(
"$0.$WITH_INDEX_NAME()", originalExpression,
reformat = reformat
)
companion object {
private val WITH_INDEX_NAME = "withIndex"
private val WITH_INDEX_FQ_NAMES: Set<String> by lazy {
sequenceOf("collections", "sequences", "text", "ranges").map { "kotlin.$it.$WITH_INDEX_NAME" }.toSet()
}
}
}
| apache-2.0 | ea14cb788b214c2751c6cc89232b5930 | 45.92233 | 158 | 0.737016 | 5.185622 | false | false | false | false |
BenWoodworth/FastCraft | fastcraft-bukkit/bukkit-1.7/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/recipe/CraftingInventoryViewFactory_1_7.kt | 1 | 3351 | package net.benwoodworth.fastcraft.bukkit.recipe
import org.bukkit.Material
import org.bukkit.Server
import org.bukkit.entity.Player
import org.bukkit.event.inventory.InventoryType
import org.bukkit.inventory.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class CraftingInventoryViewFactory_1_7 @Inject constructor(
private val server: Server,
) : CraftingInventoryViewFactory {
override fun create(
player: Player,
inventoryHolder: InventoryHolder?,
recipe: Recipe?,
): InventoryView {
return CustomInventoryView(
player = player,
topInventory = CustomCraftingInventory(inventoryHolder, recipe)
)
}
private class CustomInventoryView(
private val player: Player,
private val topInventory: Inventory,
) : InventoryView() {
override fun getPlayer(): Player {
return player
}
override fun getType(): InventoryType {
return topInventory.type
}
override fun getBottomInventory(): Inventory {
return player.inventory
}
override fun getTopInventory(): Inventory {
return topInventory
}
}
private inner class CustomCraftingInventory private constructor(
private val recipe: Recipe?,
private val baseInventory: Inventory,
) : CraftingInventory, Inventory by baseInventory {
constructor(inventoryHolder: InventoryHolder?, recipe: Recipe?) : this(
recipe = recipe,
baseInventory = server.createInventory(inventoryHolder, InventoryType.WORKBENCH)
)
private fun air() = ItemStack(Material.AIR)
override fun getItem(index: Int): ItemStack? {
return baseInventory.getItem(index) ?: air()
}
override fun getContents(): Array<ItemStack> {
val contents = baseInventory.contents
for (i in contents.indices) {
contents[i] = contents[i] ?: air()
}
return contents
}
override fun getRecipe(): Recipe? {
return recipe
}
override fun getMatrix(): Array<ItemStack?> {
return Array(size - 1) { slot -> getItem(slot) }
}
override fun setMatrix(contents: Array<out ItemStack>) {
if (contents.size > baseInventory.size - 1) {
throw IllegalArgumentException("matrix contents too large")
}
setContents(contents)
}
override fun getResult(): ItemStack? {
return getItem(9)
}
override fun setResult(newResult: ItemStack?) {
setItem(size - 1, newResult)
}
override fun iterator(index: Int): MutableListIterator<ItemStack> {
val baseIterator = baseInventory.iterator(index)
return object : MutableListIterator<ItemStack> by baseIterator {
override fun next(): ItemStack {
return baseIterator.next() ?: air()
}
override fun previous(): ItemStack {
return baseIterator.previous() ?: air()
}
}
}
override fun iterator(): MutableListIterator<ItemStack> {
return iterator(0)
}
}
}
| gpl-3.0 | 2a651ce1ff3212e7caa153b4779f9fde | 28.919643 | 92 | 0.598627 | 5.293839 | false | false | false | false |
BenWoodworth/FastCraft | fastcraft-bukkit/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/tools/MaterialItemIdFinder.kt | 1 | 5653 | package net.benwoodworth.fastcraft.bukkit.tools
import net.benwoodworth.fastcraft.bukkit.util.BukkitVersion
import org.bukkit.Bukkit
import org.bukkit.Material
import java.io.File
internal object MaterialItemIdFinder {
private val nmsVersion = Bukkit.getServer()::class.java.`package`.name.substring("org.bukkit.craftbukkit.".length)
private val nms = "net.minecraft.server.$nmsVersion"
private val obc = "org.bukkit.craftbukkit.$nmsVersion"
private abstract class ClassCompanion(`class`: String) {
@get:JvmName("class")
val `class`: Class<*> = Class.forName(`class`)
}
private data class NamespacedId(val namespacedId: Any) {
val namespace: String
get() = toString().split(":", limit = 2).first()
val id: String
get() = toString().split(":", limit = 2)[1]
override fun toString(): String = namespacedId.toString()
}
private data class Item(val item: Any) {
companion object : ClassCompanion("$nms.Item") {
val REGISTRY: RegistryMaterials
get() = `class`
.getDeclaredField("REGISTRY")
.apply { isAccessible = true }
.get(null)
.let { RegistryMaterials(it) }
fun getId(item: Item): Int =
`class`
.getDeclaredMethod("getId", `class`)
.invoke(null, item.item) as Int
}
fun getName(): String =
`class`
.getDeclaredMethod("getName")
.invoke(item) as String
fun getVariantName(itemStack: ItemStack): String =
`class`
.getDeclaredMethod(
when (nmsVersion) {
"v1_7_R4" -> "a"
"v1_8_R3" -> "e_"
"v1_9_R2", "v1_10_R1" -> "f_"
"v1_11_R1", "v1_12_R1" -> "a"
else -> error(nmsVersion)
},
ItemStack.`class`,
)
.invoke(item, itemStack.itemStack) as String
}
private data class RegistryMaterials(val registry: Any) {
companion object : ClassCompanion("$nms.RegistryMaterials")
fun getIdItems(): Map<NamespacedId, Item> =
`class`.superclass
.getDeclaredField("c")
.apply { isAccessible = true }
.get(registry)
.let { it as Map<*, *> }
.mapKeys { (key, _) -> NamespacedId(key!!) }
.mapValues { (_, value) -> Item(value!!) }
}
private data class ItemStack(val itemStack: Any) {
companion object : ClassCompanion("$nms.ItemStack")
constructor(item: Item, data: Int) : this(
`class`
.getConstructor(Item.`class`, Int::class.java)
.newInstance(item.item, data)
)
fun setData(data: Int) {
`class`
.getDeclaredMethod("setData", Int::class.java)
.invoke(itemStack, data)
}
}
private fun Item.getVariantNames(): List<String>? {
val itemStack = ItemStack(this, 0)
val result = (0..255)
.map { data ->
itemStack.setData(data)
getVariantName(itemStack)
}
.toMutableList()
while (result.size > 1 && result.last() == result.first()) {
result.removeAt(result.lastIndex)
}
return result
.takeUnless { it.isEmpty() }
?.takeUnless { it.size == 1 && it.first() == getName() }
}
/**
* For use with CraftBukkit 1.7-1.12
*
* Lists materials and their minecraft item ids
*/
@Suppress("DEPRECATION")
fun generate(outDir: File) {
val registryIdItems = Item.REGISTRY.getIdItems()
val materialItemIds = registryIdItems
.map { (key, item) -> Item.getId(item) to key.id }
.flatMap { (intId, itemId) ->
enumValues<Material>()
.filter { it.id == intId }
.map { it to itemId }
}
.sortedBy { (material, _) -> material.name }
val materialItems = registryIdItems.values
.flatMap { item ->
enumValues<Material>()
.filter { it.id == Item.getId(item) }
.map { it to item }
}
.sortedBy { (material, _) -> material.name }
val materialItemNames = materialItems
.map { (material, item) -> material to item.getName() }
val materialItemVariantNames = materialItems
.map { (material, item) -> material to item.getVariantNames() }
.filter { (_, item) -> item != null }
val version = BukkitVersion
.parse(Bukkit.getBukkitVersion())
.run { "$major.$minor" }
val out = File(outDir, "$version.yml")
out.writer().buffered().use { writer ->
writer.append("item-ids:\n")
materialItemIds.forEach { (material, itemId) ->
writer.append(" ${material.name}: ${itemId}\n")
}
writer.append("item-names:\n")
materialItemNames.forEach { (material, itemName) ->
writer.append(" ${material.name}: ${itemName}\n")
}
writer.append("item-variant-names:\n")
materialItemVariantNames.forEach { (material, itemName) ->
writer.append(" ${material.name}: ${itemName}\n")
}
}
}
}
| gpl-3.0 | 8fd6c00d599c8fb137e65c1b01ed0a93 | 33.054217 | 118 | 0.511764 | 4.540562 | false | false | false | false |
insogroup/utils | src/main/kotlin/com/github/insanusmokrassar/utils/IOC/strategies/CacheIOCStrategy.kt | 1 | 1592 | package com.github.insanusmokrassar.utils.IOC.strategies
import com.github.insanusmokrassar.utils.ClassExtractor.exceptions.ClassExtractException
import com.github.insanusmokrassar.utils.ClassExtractor.extract
import com.github.insanusmokrassar.utils.IOC.exceptions.ResolveStrategyException
import com.github.insanusmokrassar.utils.IOC.interfaces.IOCStrategy
import java.util.HashMap
class CacheIOCStrategy(protected var targetClassPath: String) : IOCStrategy {
protected var instances: MutableMap<String, Any> = HashMap()
/**
* Return cached instance of object
* @param args not used
* *
* @return Instance that was generated in constructor
* *
* @throws ResolveStrategyException Throw when in constructor was not created object
*/
@Throws(ResolveStrategyException::class)
override fun <T> getInstance(vararg args: Any): T {
if (args.size == 0) {
return getInstance("")
}
val name = args[0] as String
if (instances.containsKey(name)) {
return instances[name]!! as T
}
val constructorArgs = arrayOfNulls<Any>(args.size - 1)//first argument is classpath
System.arraycopy(args, 1, constructorArgs, 0, constructorArgs.size)
try {
val instance = extract<Any>(targetClassPath, *constructorArgs)
instances.put(name, instance)
return instance as T
} catch (e: ClassExtractException) {
throw ResolveStrategyException("Can't find variable for this name and create new instance", e)
}
}
}
| mit | dcd481f73f6bf4fdea391fe02dd62214 | 36.904762 | 106 | 0.690955 | 4.574713 | false | false | false | false |
testIT-LivingDoc/livingdoc2 | livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/scenarios/matching/StepTemplate.kt | 2 | 5243 | package org.livingdoc.engine.execution.examples.scenarios.matching
/**
* Represents a template specified by a fixture developer for scenario steps. Used for matching scenario
* steps to methods in a fixture. A valid `StepTemplate` consists of a sequence of fragments (text and variables).
* The sequence of fragments is never empty and does not contain two consecutive fragments of the same type.
*
* Variables can be quoted with optional `quotationCharacters` (e.g. single quotation marks). A matching step
* *must* contain exactly the same quotation characters. By default, no quotation characters are used.
*/
internal class StepTemplate(
val fragments: List<Fragment>,
val quotationCharacters: Set<Char>
) {
init {
assert(fragments.isNotEmpty())
assertAlternatingSequenceOfFragments()
}
private fun assertAlternatingSequenceOfFragments() {
var wasTextFragment = fragments.first() !is Text
fragments.forEach { fragment ->
assert(wasTextFragment xor (fragment is Text))
wasTextFragment = fragment is Text
}
}
/**
* Returns a Matching of the template and the specified scenario step.
*/
fun alignWith(step: String, maxLevelOfStemming: Float = 3.0f) = RegMatching(this, step, maxLevelOfStemming)
override fun toString(): String = fragments.joinToString(separator = "") { fragment ->
when (fragment) {
is Text -> fragment.content
is Variable -> "{${fragment.name}}"
}
}
companion object {
/**
* Reads a template for a scenario step description from a string. Optionally takes a set of quotation
* characters for variable separation.
*
* @return a valid `StepTemplate`
* @throws IllegalFormatException if the specified template string is malformed
*/
fun parse(templateAsString: String, quotationCharacters: Set<Char> = emptySet()) =
StepTemplate(parseString(templateAsString), quotationCharacters)
private fun parseString(templateAsString: String): List<Fragment> {
if (templateAsString.isEmpty()) {
throw IllegalFormatException("StepTemplates cannot be empty!")
}
return split(templateAsString).map { createFragment(it) }.toList()
}
private fun split(templateAsString: String): List<String> {
val tokens = mutableListOf<String>()
var lastIndex = 0
var isVariable = false
var isPreceededByVariable = false
for ((i, c) in templateAsString.withIndex()) {
if (c == '{' && !isEscaped(templateAsString, i)) {
validateVariables(isVariable, i, templateAsString, isPreceededByVariable)
isVariable = true
if (lastIndex < i) {
tokens.add(templateAsString.substring(lastIndex, i))
}
lastIndex = i
} else if (c == '}' && !isEscaped(templateAsString, i)) {
if (!isVariable) {
throw IllegalFormatException(
"Illegal closing curly brace at position $i!\nOffending string was: $templateAsString"
)
}
isPreceededByVariable = true
isVariable = false
tokens.add(templateAsString.substring(lastIndex, i + 1))
lastIndex = i + 1
} else {
isPreceededByVariable = false
}
}
if (lastIndex < templateAsString.length) {
tokens.add(templateAsString.substring(lastIndex))
}
return tokens
}
private fun validateVariables(
isVariable: Boolean,
i: Int,
templateAsString: String,
isPreceededByVariable: Boolean
) {
if (isVariable) {
throw IllegalFormatException(
"Illegal opening curly brace at position $i!\nOffending string was: $templateAsString"
)
}
if (isPreceededByVariable) {
throw IllegalFormatException(
"Consecutive variables at position $i! " +
"StepTemplate must contain an intervening text fragment to keep them apart.\n" +
"Offending string was: $templateAsString"
)
}
}
private fun isEscaped(s: String, i: Int) = (i > 0 && s[i - 1] == '\\')
private fun createFragment(fragmentAsString: String): Fragment {
return if (fragmentAsString.startsWith('{') && fragmentAsString.endsWith('}'))
Variable(fragmentAsString.substring(1, fragmentAsString.length - 1))
else
Text(fragmentAsString)
}
}
}
internal class IllegalFormatException(msg: String) : IllegalArgumentException(msg)
internal sealed class Fragment
internal data class Text(val content: String) : Fragment()
internal data class Variable(val name: String) : Fragment()
| apache-2.0 | bccb70a4b78c3f2abedcd858bee0e987 | 38.719697 | 114 | 0.589357 | 5.405155 | false | false | false | false |
myunusov/maxur-mserv | maxur-mserv-core/src/test/kotlin/org/maxur/mserv/frame/service/MicroServiceRunnerSpec.kt | 1 | 17776 | package org.maxur.mserv.frame.service
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Condition
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import org.maxur.mserv.frame.LocatorImpl
import org.maxur.mserv.frame.TestLocatorHolder
import org.maxur.mserv.frame.kotlin.Locator
import org.maxur.mserv.frame.relativePathByResourceName
import org.maxur.mserv.frame.runner.Java
import org.maxur.mserv.frame.runner.Kotlin.runner
import org.maxur.mserv.frame.runner.PredefinedPropertiesBuilder
import org.maxur.mserv.frame.runner.PropertiesBuilder
import org.maxur.mserv.frame.runner.hocon
import org.maxur.mserv.frame.runner.json
import org.maxur.mserv.frame.runner.yaml
import org.maxur.mserv.frame.service.properties.Properties
import org.maxur.mserv.frame.service.properties.PropertiesSource
import java.net.URL
import java.util.function.Predicate
import kotlin.test.assertFailsWith
val properties: Properties? get() = Locator.bean(Properties::class)
val source: PropertiesSource? get() = Locator.bean(Properties::class)?.sources?.firstOrNull()
@RunWith(JUnitPlatform::class)
class MicroServiceRunnerSpec : Spek({
val function: Map<String, (PredefinedPropertiesBuilder.() -> Unit) -> PropertiesBuilder> = mapOf(
"Hocon" to ::hocon,
"Json" to ::json,
"Yaml" to ::yaml
)
describe("Build empty micro-service") {
beforeEachTest {
LocatorImpl.holder = TestLocatorHolder
}
afterEachTest {
Locator.stop()
}
context("without properties") {
it("should return new micro-service") {
val service = runner {
withoutProperties()
}.build()
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
}
it("should return new micro-service for java client") {
val service =
// tag::withoutproperties[]
Java.runner()
.withoutProperties() // <1>
.build()
// end::withoutproperties[]
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
}
}
context("with properties object") {
it("should return new micro-service") {
val service = runner {
properties += "name" to "Test Service"
properties += "url" to URL("file:///")
properties += "count" to 0
}.build()
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
val properties = properties
assertThat(properties).isNotNull()
assertThat(properties!!.asString("name")).isEqualTo("Test Service")
assertThat(properties.read("url", URL::class)).isEqualTo(URL("file:///"))
assertThat(properties.asInteger("count")).isEqualTo(0)
assertThat(properties.asString("none")).isNull()
}
it("should return new micro-service for java client") {
val service =
Java.runner()
.properties("name", "Test Service")
.properties("url", URL("file:///"))
.properties("count", 0)
.build()
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
val properties = properties
assertThat(properties).isNotNull()
assertThat(properties!!.asString("name")).isEqualTo("Test Service")
assertThat(properties.read("url", URL::class)).isEqualTo(URL("file:///"))
assertThat(properties.asInteger("count")).isEqualTo(0)
assertThat(properties.asString("none")).isNull()
}
}
context("with properties without configuration") {
listOf(
Triple("Hocon", "DEFAULTS", "conf"),
Triple("Yaml", "/", "yaml"),
Triple("Json", "/", "json")
)
.forEach { (name, root, ext) ->
describe("With '$name' properties") {
it("should return new micro-service with named properties source") {
val service = runner {
properties += function[name]!!.invoke({})
}.build()
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
source!!.apply {
assertThat(format).isEqualTo(name)
assertThat(rootKey).isEqualTo(root)
assertThat(uri.toString()).endsWith("application.$ext")
}
Locator.stop()
}
it("should return new micro-service with default properties source") {
val service = runner {
properties += file { format = name }
}.build()
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
source!!.apply {
assertThat(format).isEqualTo(name)
assertThat(rootKey).isEqualTo(root)
assertThat(uri.toString()).endsWith("application.$ext")
}
Locator.stop()
}
it("should return new micro-service with default properties source for java client") {
val service = Java.runner()
.properties(name)
.build()
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
source!!.apply {
assertThat(format).isEqualTo(name)
assertThat(rootKey).isEqualTo(root)
assertThat(uri.toString()).endsWith("application.$ext")
}
Locator.stop()
}
}
}
}
context("with properties file by url") {
listOf(
Triple("Hocon", "DEFAULTS", "conf"),
Triple("Yaml", "/", "yaml"),
Triple("Json", "/", "json")
)
.forEach { (name, root, ext) ->
describe("With '$name' properties") {
val propertyFile = relativePathByResourceName("/application.$ext") ?:
throw IllegalStateException("file application.$ext is not found")
it("should return new micro-service with named properties source") {
val service = runner {
properties += function[name]!!.invoke({
url = propertyFile
})
}.build()
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
source!!.apply {
assertThat(format).isEqualTo(name)
assertThat(rootKey).isEqualTo(root)
assertThat(uri.toString()).endsWith("application.$ext")
}
Locator.stop()
}
it("should return new micro-service with properties") {
val service = runner {
properties += file {
format = name
url = propertyFile
}
}.build()
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
source!!.apply {
assertThat(format).isEqualTo(name)
assertThat(rootKey).isEqualTo(root)
assertThat(uri.toString()).endsWith("application.$ext")
}
Locator.stop()
}
it("should return new micro-service with properties for java client") {
val service = Java.runner()
.properties(name)
.url(propertyFile)
.build()
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
source!!.apply {
assertThat(format).isEqualTo(name)
assertThat(rootKey).isEqualTo(root)
assertThat(uri.toString()).endsWith("application.$ext")
}
Locator.stop()
}
}
}
}
context("with properties file with rootKey") {
listOf(
Triple("Hocon", "USER", "conf"),
Triple("Yaml", "USER", "yaml"),
Triple("Json", "USER", "json")
)
.forEach { (name, root, ext) ->
describe("With '$name' properties") {
it("should return new micro-service with named properties source") {
val service = runner {
properties += function[name]!!.invoke({
rootKey = "USER"
})
}.build()
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
source!!.apply {
assertThat(format).isEqualTo(name)
assertThat(rootKey).isEqualTo(root)
assertThat(uri.toString()).endsWith("application.$ext")
}
Locator.stop()
}
it("should return new micro-service with properties") {
val service = runner {
properties += file {
format = name
rootKey = "USER"
}
}.build()
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
source!!.apply {
assertThat(format).isEqualTo(name)
assertThat(rootKey).isEqualTo(root)
assertThat(uri.toString()).endsWith("application.$ext")
}
Locator.stop()
}
it("should return new micro-service with properties for java client") {
val service = Java.runner()
.properties(name)
.rootKey("USER")
.build()
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
source!!.apply {
assertThat(format).isEqualTo(name)
assertThat(rootKey).isEqualTo(root)
assertThat(uri.toString()).endsWith("application.$ext")
}
Locator.stop()
}
}
}
}
context("with properties file with invalid configuration") {
listOf("Hocon", "Yaml", "Json").forEach { name ->
describe("With '$name' properties") {
it("should throw error on unknown format") {
assertFailsWith<IllegalStateException> {
runner {
properties += file {
format = "Error"
url = "file:///file.cfg"
}
}
Locator.bean(Properties::class)
}
}
it("should throw error on unknown url scheme") {
assertFailsWith<IllegalStateException> {
runner {
properties += file {
format = name
url = "error:///file.cfg"
}
}
Locator.bean(Properties::class)
}
}
it("should throw error on unknown url scheme for java client") {
assertFailsWith<IllegalStateException> {
Java.runner()
.properties(name)
.url("error:///file.cfg")
.build()
Locator.bean(Properties::class)
}
}
it("should throw error on unknown file") {
assertFailsWith<IllegalStateException> {
runner {
properties += file {
format = name
url = "file:///error.cfg"
}
}
Locator.bean(Properties::class)
}
}
it("should throw error on unknown file for java client") {
assertFailsWith<IllegalStateException> {
Java.runner()
.properties(name)
.url("file:///error.cfg")
.build()
Locator.bean(Properties::class)
}
}
it("should throw error on unknown root key") {
assertFailsWith<IllegalStateException> {
runner {
properties += file {
format = name
rootKey = "ERROR"
}
}
Locator.bean(Properties::class)
}
}
it("should throw error on unknown root key for java client") {
assertFailsWith<IllegalStateException> {
Java.runner()
.properties(name)
.rootKey("ERROR")
.build()
Locator.bean(Properties::class)
}
}
}
}
}
val supportedFormat = condition(
{ it in arrayOf("Hocon", "Yaml", "Json") }, "supported format"
)
context("Build micro-service with default properties") {
it("should return new micro-service") {
val service = runner { }.build()
assertThat(service).isNotNull()
val source = source
assertThat(source).isNotNull()
assertThat(source!!.format).isNotNull()
assertThat(source.format).`is`(supportedFormat)
}
}
}
describe("a rest micro-service") {
it("should return new micro-service") {
val service = runner {
withoutProperties()
rest { }
}
assertThat(service).isNotNull()
}
}
})
private fun condition(function: (String) -> Boolean, description: String): Condition<String>
= Condition(Predicate(function), description)
| apache-2.0 | 6d67fce8deee481bb09154129355d697 | 42.891358 | 110 | 0.41556 | 6.675178 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/Base64EncodeActionType.kt | 1 | 712 | package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.http_shortcuts.scripting.ActionAlias
import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO
class Base64EncodeActionType : BaseActionType() {
override val type = TYPE
override fun fromDTO(actionDTO: ActionDTO) = Base64EncodeAction(
text = actionDTO.getByteArray(0) ?: ByteArray(0),
)
override fun getAlias() = ActionAlias(
functionName = FUNCTION_NAME,
functionNameAliases = setOf("base64Encode", "btoa"),
parameters = 1,
)
companion object {
private const val TYPE = "base64encode"
private const val FUNCTION_NAME = "base64encode"
}
}
| mit | 3eac3b02ddafba1bb3d4729d7139102f | 28.666667 | 68 | 0.702247 | 4.045455 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | java/java-tests/testSrc/com/intellij/java/psi/codeStyle/IndentOptionsCacheDropTest.kt | 5 | 4473 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.psi.codeStyle
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.codeStyle.CommonCodeStyleSettings.IndentOptions
import com.intellij.psi.codeStyle.DetectableIndentOptionsProvider
import com.intellij.psi.codeStyle.TimeStampedIndentOptions
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import org.assertj.core.api.Assertions.assertThat
class IndentOptionsCacheDropTest: LightCodeInsightFixtureTestCase() {
override fun setUp() {
super.setUp()
val instance = DetectableIndentOptionsProvider.getInstance()
instance?.setEnabledInTest(true)
}
override fun tearDown() {
val instance = DetectableIndentOptionsProvider.getInstance()
instance?.setEnabledInTest(false)
super.tearDown()
}
val code = """
class Test {
public void test() {<caret>
int a = 2;
}
}
"""
fun `test store valid timestamped options in document when detecting indents`() {
val file = PsiFileFactory.getInstance(project).createFileFromText("Test.java", JavaFileType.INSTANCE, code, 0, true)
val detectableOptionsProvider = object : DetectableIndentOptionsProvider() {
override fun scheduleDetectionInBackground(project: Project, document: Document, indentOptions: TimeStampedIndentOptions) {
//just do nothing, so default indent options will be kept (same as very long indent detection calculation)
}
}
detectableOptionsProvider.setEnabledInTest(true)
val settings = CodeStyleSettingsManager.getSettings(project)
val options = detectableOptionsProvider.getIndentOptions(settings, file)
val document = PsiDocumentManager.getInstance(project).getDocument(file)!!
val indentOptions = detectableOptionsProvider.getValidCachedIndentOptions(file, document)!!
assert(options == indentOptions && options === indentOptions)
}
fun testDropIndentOptions_WhenTabSizeChanged() {
val current = CodeStyleSettingsManager.getInstance(project).currentSettings
val options = current.getCommonSettings(JavaLanguage.INSTANCE).indentOptions!!
myFixture.configureByText(JavaFileType.INSTANCE, code)
val tabSize = myFixture.editor.settings.getTabSize(project)
assertThat(tabSize).isEqualTo(options.TAB_SIZE)
options.TAB_SIZE = 14
reinitEditorSettings()
val newTabSize = myFixture.editor.settings.getTabSize(project)
assertThat(newTabSize).isEqualTo(14)
}
fun testIndentOptionsCache_NotDroppedOnReinit() {
myFixture.configureByText(JavaFileType.INSTANCE, code)
val before: IndentOptions = IndentOptions.retrieveFromAssociatedDocument(file)!!
reinitEditorSettings()
assertThat(before === IndentOptions.retrieveFromAssociatedDocument(file)).isTrue()
}
fun testIndentOptionsCache_NotDroppedOnChange() {
myFixture.configureByText(JavaFileType.INSTANCE, code)
val before: IndentOptions = IndentOptions.retrieveFromAssociatedDocument(file)!!
myFixture.type(" abracadabra")
assertThat(before === IndentOptions.retrieveFromAssociatedDocument(file)).isTrue()
}
fun testIndentOptionsDrop_OnDocumentChangeAndReinit() {
myFixture.configureByText(JavaFileType.INSTANCE, code)
val before: IndentOptions = IndentOptions.retrieveFromAssociatedDocument(file)!!
myFixture.type(" abracadabra")
reinitEditorSettings()
assertThat(before === IndentOptions.retrieveFromAssociatedDocument(file)).isFalse()
}
private fun reinitEditorSettings() = (myFixture.editor as EditorImpl).reinitSettings()
} | apache-2.0 | 6460a9d42bcff459d3dfab662153e78f | 36.283333 | 129 | 0.775542 | 4.733333 | false | true | false | false |
ThiagoGarciaAlves/intellij-community | java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ContractInferenceIndex.kt | 1 | 3736 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection.dataFlow
import com.intellij.lang.LighterAST
import com.intellij.lang.LighterASTNode
import com.intellij.psi.impl.source.JavaLightStubBuilder
import com.intellij.psi.impl.source.PsiMethodImpl
import com.intellij.psi.impl.source.tree.JavaElementType.*
import com.intellij.psi.impl.source.tree.LightTreeUtil
import com.intellij.psi.impl.source.tree.RecursiveLighterASTNodeWalkingVisitor
import com.intellij.psi.stub.JavaStubImplUtil
import com.intellij.util.gist.GistManager
import java.util.*
/**
* @author peter
*/
private val gist = GistManager.getInstance().newPsiFileGist("contractInference", 5, MethodDataExternalizer) { file ->
indexFile(file.node.lighterAST)
}
private fun indexFile(tree: LighterAST): Map<Int, MethodData> {
val result = HashMap<Int, MethodData>()
object : RecursiveLighterASTNodeWalkingVisitor(tree) {
var methodIndex = 0
override fun visitNode(element: LighterASTNode) {
if (element.tokenType === METHOD) {
calcData(tree, element)?.let { data -> result[methodIndex] = data }
methodIndex++
}
if (JavaLightStubBuilder.isCodeBlockWithoutStubs(element)) return
super.visitNode(element)
}
}.visitNode(tree.root)
return result
}
private fun calcData(tree: LighterAST, method: LighterASTNode): MethodData? {
val body = LightTreeUtil.firstChildOfType(tree, method, CODE_BLOCK) ?: return null
val statements = ContractInferenceInterpreter.getStatements(body, tree)
val contracts = ContractInferenceInterpreter(tree, method, body).inferContracts(statements)
val nullityVisitor = NullityInference.NullityInferenceVisitor(tree, body)
val purityVisitor = PurityInference.PurityInferenceVisitor(tree, body)
for (statement in statements) {
walkMethodBody(tree, statement) { nullityVisitor.visitNode(it); purityVisitor.visitNode(it) }
}
val notNullParams = inferNotNullParameters(tree, method, statements)
return createData(body, contracts, nullityVisitor.result, purityVisitor.result, notNullParams)
}
private fun walkMethodBody(tree: LighterAST, root: LighterASTNode, processor: (LighterASTNode) -> Unit) {
object : RecursiveLighterASTNodeWalkingVisitor(tree) {
override fun visitNode(element: LighterASTNode) {
val type = element.tokenType
if (type === CLASS || type === FIELD || type === METHOD || type === ANNOTATION_METHOD || type === LAMBDA_EXPRESSION) return
processor(element)
super.visitNode(element)
}
}.visitNode(root)
}
private fun createData(body: LighterASTNode,
contracts: List<PreContract>,
nullity: NullityInferenceResult?,
purity: PurityInferenceResult?,
notNullParams: BitSet): MethodData? {
if (nullity == null && purity == null && contracts.isEmpty() && notNullParams.isEmpty) return null
return MethodData(nullity, purity, contracts, notNullParams, body.startOffset, body.endOffset)
}
fun getIndexedData(method: PsiMethodImpl): MethodData? = gist.getFileData(method.containingFile)?.get(JavaStubImplUtil.getMethodStubIndex(method)) | apache-2.0 | bf4198cf860f1028483025b8234181a5 | 37.927083 | 146 | 0.742505 | 4.484994 | false | false | false | false |
myunusov/maxur-mserv | maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/service/properties/PropertiesSource.kt | 1 | 1390 | @file:Suppress("unused")
package org.maxur.mserv.frame.service.properties
import org.maxur.mserv.core.fold
import org.maxur.mserv.frame.kotlin.Locator
import java.net.URI
/**
* Represent the Properties source configuration.
*
* @author myunusov
* @version 1.0
* @since <pre>24.06.2017</pre>
*/
abstract class PropertiesSource {
abstract val format: String
abstract val uri: URI
abstract val rootKey: String
val sources: List<PropertiesSource> = listOf(this)
companion object {
fun default(): Properties {
Locator.beans(PropertiesFactory::class).map {
it.make().fold({ }, { return it })
}
return NullProperties
}
fun nothing(): Properties = NullProperties
}
}
object NullProperties : PropertiesSource(), Properties {
override val format = "undefined"
override val uri = URI("")
override val rootKey: String = ""
override fun asString(key: String): String? = error(key)
override fun asLong(key: String): Long? = error(key)
override fun asInteger(key: String): Int? = error(key)
override fun asURI(key: String): URI? = error(key)
override fun <P> read(key: String, clazz: Class<P>): P? = error(key)
private fun <T> error(key: String): T =
throw IllegalStateException("Service Configuration is not found. Key '$key' unresolved")
}
| apache-2.0 | a03e52591d84600f36042a03e278e2c4 | 27.958333 | 100 | 0.656115 | 4.005764 | false | false | false | false |
glorantq/KalanyosiRamszesz | src/glorantq/ramszesz/memes/ThinkingMeme.kt | 1 | 1773 | package glorantq.ramszesz.memes
import com.cloudinary.utils.ObjectUtils
import glorantq.ramszesz.cloudinary
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent
import sx.blah.discord.handle.obj.IUser
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.File
import java.net.URL
import java.net.URLConnection
import javax.imageio.ImageIO
/**
* Created by glora on 2017. 07. 27..
*/
class ThinkingMeme : IMeme {
override val name: String
get() = "thinking"
override var parameters: ArrayList<MemeParameter> = arrayListOf(MemeParameter(MemeParameter.Companion.Type.USER))
override fun execute(event: MessageReceivedEvent) {
val user: IUser = parameters[0].value as IUser
val profileImage: BufferedImage = downloadProfileImage(user)
val thinking: BufferedImage = ImageIO.read(File("./assets/thinking.png"))
val combined: BufferedImage = BufferedImage(profileImage.width, profileImage.height, BufferedImage.TYPE_INT_ARGB)
val graphics: Graphics = combined.graphics
graphics.drawImage(profileImage, 0, 0, null)
val thinkHeight: Int = profileImage.height / 2
val thinkWidth: Int = profileImage.width / 2
graphics.drawImage(thinking, thinkWidth / 4, profileImage.height - thinkHeight - (thinkHeight / 4), thinkWidth, thinkHeight, null)
graphics.dispose()
val imageFile: File = File.createTempFile("thinking-meme-${event.author.name}", ".png")
imageFile.deleteOnExit()
ImageIO.write(combined, "png", imageFile)
val url: String = cloudinary.uploader().upload(imageFile, ObjectUtils.emptyMap())["secure_url"].toString()
deliverMeme(event, url)
imageFile.delete()
}
} | gpl-3.0 | b5c9a6755ff779427d92a2738ae36ffa | 38.422222 | 138 | 0.723632 | 4.282609 | false | false | false | false |
JiangKlijna/framework-learning | java/hibernate-test/src/main/kotlin/com/jiangklijna/hibernate/Run.kt | 1 | 1438 | package com.jiangklijna.hibernate
import com.jiangklijna.Run
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
import org.hibernate.SessionFactory
import org.hibernate.cfg.Configuration
@Entity
@Table(name = "orm_user")
class User(@Id var id: Long, var name: String) {
override fun toString() = "User@${hashCode()}(id=$id, name='$name')"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as User
if (id != other.id) return false
if (name != other.name) return false
return true
}
}
class HibernateRun : Run {
private val sessionFactory: SessionFactory = (fun(): SessionFactory {
val cfg = Configuration()
cfg.configure("hibernate.cfg.xml")
return cfg.buildSessionFactory()
})()
override fun start() {
val id = System.currentTimeMillis()
val session = sessionFactory.openSession()
val tx = session.beginTransaction()
val u1 = User(id, "save1")
val u2 = User(id + 1, "save2")
session.save(u1)
session.save(u2)
session.delete(u2)
session.update(u1.apply { name = "update1" })
val u = session[User::class.java, u1.id]
println("u1=$u1, u=$u, u==u1:${u == u1}, u===u1:${u === u1}")
tx.commit()
session.close()
}
}
| apache-2.0 | 2f1f2ed406c3e89d8304637adfcbb719 | 29.595745 | 73 | 0.617524 | 3.735065 | false | true | false | false |
android/uamp | common/src/main/java/com/example/android/uamp/media/UampNotificationManager.kt | 2 | 5472 | /*
* Copyright 2020 Google Inc. All rights reserved.
*
* 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.example.android.uamp.media
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.MediaSessionCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.ui.PlayerNotificationManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
const val NOW_PLAYING_CHANNEL_ID = "com.example.android.uamp.media.NOW_PLAYING"
const val NOW_PLAYING_NOTIFICATION_ID = 0xb339 // Arbitrary number used to identify our notification
/**
* A wrapper class for ExoPlayer's PlayerNotificationManager. It sets up the notification shown to
* the user during audio playback and provides track metadata, such as track title and icon image.
*/
internal class UampNotificationManager(
private val context: Context,
sessionToken: MediaSessionCompat.Token,
notificationListener: PlayerNotificationManager.NotificationListener
) {
private var player: Player? = null
private val serviceJob = SupervisorJob()
private val serviceScope = CoroutineScope(Dispatchers.Main + serviceJob)
private val notificationManager: PlayerNotificationManager
private val platformNotificationManager: NotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
init {
val mediaController = MediaControllerCompat(context, sessionToken)
val builder = PlayerNotificationManager.Builder(context, NOW_PLAYING_NOTIFICATION_ID, NOW_PLAYING_CHANNEL_ID)
with (builder) {
setMediaDescriptionAdapter(DescriptionAdapter(mediaController))
setNotificationListener(notificationListener)
setChannelNameResourceId(R.string.notification_channel)
setChannelDescriptionResourceId(R.string.notification_channel_description)
}
notificationManager = builder.build()
notificationManager.setMediaSessionToken(sessionToken)
notificationManager.setSmallIcon(R.drawable.ic_notification)
notificationManager.setUseRewindAction(false)
notificationManager.setUseFastForwardAction(false)
}
fun hideNotification() {
notificationManager.setPlayer(null)
}
fun showNotificationForPlayer(player: Player){
notificationManager.setPlayer(player)
}
private inner class DescriptionAdapter(private val controller: MediaControllerCompat) :
PlayerNotificationManager.MediaDescriptionAdapter {
var currentIconUri: Uri? = null
var currentBitmap: Bitmap? = null
override fun createCurrentContentIntent(player: Player): PendingIntent? =
controller.sessionActivity
override fun getCurrentContentText(player: Player) =
controller.metadata.description.subtitle.toString()
override fun getCurrentContentTitle(player: Player) =
controller.metadata.description.title.toString()
override fun getCurrentLargeIcon(
player: Player,
callback: PlayerNotificationManager.BitmapCallback
): Bitmap? {
val iconUri = controller.metadata.description.iconUri
return if (currentIconUri != iconUri || currentBitmap == null) {
// Cache the bitmap for the current song so that successive calls to
// `getCurrentLargeIcon` don't cause the bitmap to be recreated.
currentIconUri = iconUri
serviceScope.launch {
currentBitmap = iconUri?.let {
resolveUriAsBitmap(it)
}
currentBitmap?.let { callback.onBitmap(it) }
}
null
} else {
currentBitmap
}
}
private suspend fun resolveUriAsBitmap(uri: Uri): Bitmap? {
return withContext(Dispatchers.IO) {
// Block on downloading artwork.
Glide.with(context).applyDefaultRequestOptions(glideOptions)
.asBitmap()
.load(uri)
.submit(NOTIFICATION_LARGE_ICON_SIZE, NOTIFICATION_LARGE_ICON_SIZE)
.get()
}
}
}
}
const val NOTIFICATION_LARGE_ICON_SIZE = 144 // px
private val glideOptions = RequestOptions()
.fallback(R.drawable.default_art)
.diskCacheStrategy(DiskCacheStrategy.DATA)
private const val MODE_READ_ONLY = "r"
| apache-2.0 | 1848ea1482832da6bdacad38c34c8841 | 38.652174 | 117 | 0.708882 | 5.142857 | false | false | false | false |
paoloach/zdomus | ZTopology/app/src/main/java/it/achdjian/paolo/ztopology/activities/NodeActivity.kt | 1 | 3022 | package it.achdjian.paolo.ztopology.activities
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import it.achdjian.paolo.ztopology.DeviceCallback
import it.achdjian.paolo.ztopology.DomusEngine
import it.achdjian.paolo.ztopology.EndpointCallback
import it.achdjian.paolo.ztopology.R
import it.achdjian.paolo.ztopology.activities.node.ClusterTabSelectedListener
import it.achdjian.paolo.ztopology.activities.node.EndpointAdapter
import it.achdjian.paolo.ztopology.activities.node.SelectedEndpointListener
import it.achdjian.paolo.ztopology.zigbee.Topology
import kotlinx.android.synthetic.main.activity_node.*
import kotlinx.android.synthetic.main.activity_node.view.*
class NodeActivity : AppCompatActivity() {
companion object {
val TOPOLOGY = "topology"
val ENDPOINT = "endpoint"
}
private lateinit var topology: Topology
lateinit var endpointAdapter: EndpointAdapter
lateinit var endpointListener: SelectedEndpointListener
override fun onDestroy() {
super.onDestroy()
DomusEngine.removeCallback(endpointAdapter as DeviceCallback)
DomusEngine.removeCallback(endpointAdapter as EndpointCallback)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (intent != null){
topology = intent.getSerializableExtra(TOPOLOGY) as Topology
}
setContentView(R.layout.activity_node)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
endpointAdapter = EndpointAdapter(toolbar.context, topology.nwkAddress)
DomusEngine.addCallback(endpointAdapter as DeviceCallback)
DomusEngine.addCallback(endpointAdapter as EndpointCallback)
val clusterTabSelectedListener = ClusterTabSelectedListener(supportFragmentManager)
endpointListener = SelectedEndpointListener(clusterTab, clusterTabSelectedListener)
clusterTab.addOnTabSelectedListener(clusterTabSelectedListener)
// Setup spinner
spinner.adapter =endpointAdapter;
spinner.onItemSelectedListener = endpointListener
nwkValue.text = topology.nwkAddress.toString(16)
lqiValue.text = topology.lqi.toString()
macValue.text = topology.extendedAddr
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_node, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
if (id == R.id.action_settings) {
return true
}
return super.onOptionsItemSelected(item)
}
}
| gpl-2.0 | 7ed6a37d1015eaa6228fd9fbfcd42a62 | 36.775 | 91 | 0.741893 | 4.897893 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/service/mutator/genemutation/AdditionalGeneMutationInfo.kt | 1 | 3875 | package org.evomaster.core.search.service.mutator.genemutation
import org.evomaster.core.Lazy
import org.evomaster.core.search.EvaluatedIndividual
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.impact.impactinfocollection.GeneImpact
import org.evomaster.core.search.impact.impactinfocollection.GeneMutationSelectionMethod
import org.evomaster.core.search.service.mutator.EvaluatedMutation
/**
* created by manzh on 2020-05-25
*
* the class contains additional info for gene mutation, e.g., archive-based gene mutation
* @property evi the evaluated individual contains an evolution of the gene with fitness values
* @property selection how to select genes to mutate if the gen contains more than one genes(e.g., ObjectGene) or other characteristics(e.g., size of ArrayGene)
* @property impact info of impact of the gene if it has, but in some case impact might be null, e.g., an element at ArrayGene
* @property geneReference a reference (i.e., id generated) to find a gene in this history, which always refers to 'root' gene in the [evi]
* @property archiveGeneSelector mutate genes using archive-based methods if the method is enabled or supports this type of the gene.
* @property targets are related to the mutation
* @property fromInitialization whether the gene is from InitializationAction
* @property position indicates an index of an action that contains the gene
*/
data class AdditionalGeneMutationInfo (
val selection: GeneMutationSelectionMethod,
val impact: GeneImpact?, //null is only allowed when the gene is root.
val geneReference: String?, // null is only allowed when selection is NONE
val archiveGeneSelector: ArchiveImpactSelector,
val archiveGeneMutator: ArchiveGeneMutator,
val evi: EvaluatedIndividual<*>,
val targets: Set<Int>,
val fromInitialization : Boolean = false,
val position : Int = -1,
val localId : String?,
val rootGene : Gene,
val effectiveHistory: MutableList<Gene> = mutableListOf(),
val history: MutableList<Pair<Gene, EvaluatedInfo>> = mutableListOf()
){
fun copyFoInnerGene(impact: GeneImpact?): AdditionalGeneMutationInfo{
return AdditionalGeneMutationInfo(
selection,
impact, geneReference, archiveGeneSelector, archiveGeneMutator, evi, targets, rootGene = rootGene, localId = localId,
effectiveHistory = effectiveHistory, history = history
)
}
fun copyFoInnerGene(impact: GeneImpact?, gene : Gene): AdditionalGeneMutationInfo{
Lazy.assert {
effectiveHistory.size == this.effectiveHistory.size &&
history.size == this.history.size
}
return AdditionalGeneMutationInfo(
selection,
impact, geneReference, archiveGeneSelector, archiveGeneMutator, evi, targets, rootGene = rootGene, localId = localId,
effectiveHistory = effectiveHistory.mapNotNull {
it.getViewOfChildren().find { g-> g.possiblySame(gene) } }.toMutableList(),
history = history.filter { it.first.getViewOfChildren().any { g-> g.possiblySame(gene) }}.map {
it.first.getViewOfChildren().find { g-> g.possiblySame(gene) }!! to it.second
}.toMutableList()
)
}
fun emptyHistory() = effectiveHistory.isEmpty() && history.isEmpty()
//fun hasImpactInfo() : Boolean = impact != null
fun hasHistory() : Boolean = history.any { targets.isEmpty() || (it.second.targets.any { t -> targets.contains(t) } && it.second.result?.isImpactful() ?: true) }
}
/**
* a history for a gene
*/
data class EvaluatedInfo(
val index : Int,
val result : EvaluatedMutation?,
val targets: Set<Int>,
val specificTargets: Set<Int>
) | lgpl-3.0 | 7289be01593861ede35492cae300c0c3 | 48.063291 | 165 | 0.695226 | 4.60761 | false | false | false | false |
facebook/fresco | vito/renderer/src/main/java/com/facebook/fresco/vito/renderer/CanvasTransformationHandler.kt | 2 | 844 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.renderer
import android.graphics.Matrix
import android.graphics.Rect
class CanvasTransformationHandler(var canvasTransformation: CanvasTransformation? = null) {
private val tempMatrix = Matrix()
private var drawMatrix: Matrix? = null
fun getMatrix(): Matrix? = drawMatrix
fun configure(bounds: Rect, childWidth: Int, childHeight: Int) {
// We only scale the model if its dimensions are > 0
if (childWidth <= 0 || childHeight <= 0) {
drawMatrix = null
return
}
drawMatrix =
canvasTransformation?.calculateTransformation(tempMatrix, bounds, childWidth, childHeight)
}
}
| mit | 3d3da619c52e40b88ef4969fabbaa30f | 27.133333 | 98 | 0.721564 | 4.328205 | false | false | false | false |
Doist/TodoistPojos | src/main/java/com/todoist/pojo/Reminder.kt | 1 | 1393 | package com.todoist.pojo
open class Reminder<D : Due> @JvmOverloads constructor(
id: String,
open var v2Id: String? = null,
open var type: String?,
/** Exclusive to reminders of type [.TYPE_ABSOLUTE]. */
open var due: D?,
/** Exclusive to reminders of type [.TYPE_RELATIVE]. */
open var minuteOffset: Int?,
/** Exclusive to reminders of type [.TYPE_LOCATION]. */
open var name: String?,
/** Exclusive to reminders of type [.TYPE_LOCATION]. */
open var locLat: Double?,
/** Exclusive to reminders of type [.TYPE_LOCATION]. */
open var locLong: Double?,
/** Exclusive to reminders of type [.TYPE_LOCATION]. */
open var radius: Int?,
/** Exclusive to reminders of type [.TYPE_LOCATION]. */
open var locTrigger: String?,
open var notifyUid: String?,
open var itemId: String,
isDeleted: Boolean = false
) : Model(id, isDeleted) {
open val isAbsolute get() = TYPE_ABSOLUTE == type
open val isRelative get() = TYPE_RELATIVE == type
open val isLocation get() = TYPE_LOCATION == type
companion object {
const val TYPE_ABSOLUTE = "absolute"
const val TYPE_RELATIVE = "relative"
const val TYPE_LOCATION = "location"
const val DEFAULT_MINUTE_OFFSET = 30
const val LOC_TRIGGER_ON_ENTER = "on_enter"
const val LOC_TRIGGER_ON_LEAVE = "on_leave"
}
}
| mit | 57278957b51fdebfdad310941d55397e | 34.717949 | 60 | 0.633884 | 4.014409 | false | false | false | false |
LvWind/NotRunningInBg | app/src/main/java/com/lvwind/notrunninginbg/PrefUtils.kt | 1 | 2494 | /*
* Copyright (c) 2017. Jason Shaw <[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 com.lvwind.notrunninginbg
import android.content.Context
import android.preference.PreferenceManager
object PrefUtils {
val KEY_ENABLED = "enabled"
fun getString(context: Context, key: String, defValue: String): String? {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.getString(key, defValue)
}
fun putString(context: Context, key: String, value: String) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.putString(key, value)
editor.apply()
}
fun getLong(context: Context, key: String, defValue: Long): Long {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.getLong(key, defValue)
}
fun putLong(context: Context, key: String, value: Long) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.putLong(key, value)
editor.apply()
}
fun getBool(context: Context, key: String, defValue: Boolean): Boolean {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.getBoolean(key, defValue)
}
fun putBool(context: Context, key: String, value: Boolean) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.putBoolean(key, value)
editor.apply()
}
fun exists(context: Context, key: String): Boolean {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.contains(key)
}
fun remove(context: Context, key: String) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.remove(key)
editor.apply()
}
} | apache-2.0 | 7c47c3285d38caea037b5541dd44fb69 | 32.266667 | 77 | 0.690056 | 4.461538 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-economy-bukkit/src/main/kotlin/com/rpkit/economy/bukkit/database/table/RPKWalletTable.kt | 1 | 7694 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.economy.bukkit.database.table
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.characters.bukkit.character.RPKCharacterId
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.core.service.Services
import com.rpkit.economy.bukkit.RPKEconomyBukkit
import com.rpkit.economy.bukkit.currency.RPKCurrency
import com.rpkit.economy.bukkit.database.create
import com.rpkit.economy.bukkit.database.jooq.Tables.RPKIT_WALLET
import com.rpkit.economy.bukkit.wallet.RPKWallet
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.runAsync
import java.util.logging.Level
import java.util.logging.Level.SEVERE
/**
* Represents the wallet table.
*/
class RPKWalletTable(
private val database: Database,
private val plugin: RPKEconomyBukkit
) : Table {
private data class CharacterCurrencyCacheKey(
val characterId: Int,
val currencyName: String
)
private val cache = if (plugin.config.getBoolean("caching.rpkit_wallet.character_id.enabled")) {
database.cacheManager.createCache(
"rpk-economy-bukkit.rpkit_wallet.character_id",
CharacterCurrencyCacheKey::class.java,
RPKWallet::class.java,
plugin.config.getLong("caching.rpkit_wallet.character_id.size")
)
} else {
null
}
fun insert(entity: RPKWallet): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
val currencyName = entity.currency.name
return runAsync {
database.create
.insertInto(
RPKIT_WALLET,
RPKIT_WALLET.CHARACTER_ID,
RPKIT_WALLET.CURRENCY_NAME,
RPKIT_WALLET.BALANCE
)
.values(
characterId.value,
currencyName.value,
entity.balance
)
.execute()
cache?.set(CharacterCurrencyCacheKey(characterId.value, currencyName.value), entity)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to insert wallet", exception)
throw exception
}
}
fun update(entity: RPKWallet): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
val currencyName = entity.currency.name
return runAsync {
database.create
.update(RPKIT_WALLET)
.set(RPKIT_WALLET.BALANCE, entity.balance)
.where(RPKIT_WALLET.CHARACTER_ID.eq(characterId.value))
.and(RPKIT_WALLET.CURRENCY_NAME.eq(currencyName.value))
.execute()
cache?.set(CharacterCurrencyCacheKey(characterId.value, currencyName.value), entity)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to update wallet", exception)
throw exception
}
}
fun get(character: RPKCharacter, currency: RPKCurrency): CompletableFuture<RPKWallet?> {
val characterId = character.id ?: return CompletableFuture.completedFuture(null)
val currencyName = currency.name
val cacheKey = CharacterCurrencyCacheKey(characterId.value, currencyName.value)
if (cache?.containsKey(cacheKey) == true) {
return CompletableFuture.completedFuture(cache[cacheKey])
}
return CompletableFuture.supplyAsync {
val result = database.create
.select(RPKIT_WALLET.BALANCE)
.from(RPKIT_WALLET)
.where(RPKIT_WALLET.CHARACTER_ID.eq(characterId.value))
.and(RPKIT_WALLET.CURRENCY_NAME.eq(currencyName.value))
.fetchOne() ?: return@supplyAsync null
val wallet = RPKWallet(
character,
currency,
result[RPKIT_WALLET.BALANCE]
)
cache?.set(cacheKey, wallet)
return@supplyAsync wallet
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to get wallet", exception)
throw exception
}
}
fun getTop(amount: Int = 5, currency: RPKCurrency): CompletableFuture<List<RPKWallet>> {
return CompletableFuture.supplyAsync {
val currencyName = currency.name
val results = database.create
.select(
RPKIT_WALLET.CHARACTER_ID,
RPKIT_WALLET.BALANCE
)
.from(RPKIT_WALLET)
.where(RPKIT_WALLET.CURRENCY_NAME.eq(currencyName.value))
.orderBy(RPKIT_WALLET.BALANCE.desc())
.limit(amount)
.fetch()
val characterService = Services[RPKCharacterService::class.java] ?: return@supplyAsync emptyList()
return@supplyAsync results
.mapNotNull { result ->
val characterId = result[RPKIT_WALLET.CHARACTER_ID]
val character =
characterService.getCharacter(RPKCharacterId(characterId)).join() ?: return@mapNotNull null
val wallet = RPKWallet(
character,
currency,
result[RPKIT_WALLET.BALANCE]
)
cache?.set(CharacterCurrencyCacheKey(characterId, currencyName.value), wallet)
return@mapNotNull wallet
}
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to get top balances", exception)
throw exception
}
}
fun delete(entity: RPKWallet): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
val currencyName = entity.currency.name
return runAsync {
database.create
.deleteFrom(RPKIT_WALLET)
.where(RPKIT_WALLET.CHARACTER_ID.eq(characterId.value))
.and(RPKIT_WALLET.CURRENCY_NAME.eq(currencyName.value))
.execute()
cache?.remove(CharacterCurrencyCacheKey(characterId.value, currencyName.value))
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to delete wallet", exception)
throw exception
}
}
fun delete(characterId: RPKCharacterId): CompletableFuture<Void> = runAsync {
database.create
.deleteFrom(RPKIT_WALLET)
.where(RPKIT_WALLET.CHARACTER_ID.eq(characterId.value))
.execute()
cache?.removeMatching { it.character.id?.value == characterId.value }
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to delete wallets for character id", exception)
throw exception
}
} | apache-2.0 | 7e619bef0ba6b3e34edeed617295d303 | 40.149733 | 115 | 0.625682 | 4.928892 | false | false | false | false |
commons-app/apps-android-commons | app/src/main/java/fr/free/nrw/commons/explore/media/PageableMediaFragment.kt | 2 | 2914 | package fr.free.nrw.commons.explore.media
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import fr.free.nrw.commons.Media
import fr.free.nrw.commons.R
import fr.free.nrw.commons.category.CategoryImagesCallback
import fr.free.nrw.commons.databinding.FragmentSearchPaginatedBinding
import fr.free.nrw.commons.explore.paging.BasePagingFragment
import fr.free.nrw.commons.media.MediaDetailPagerFragment.MediaDetailProvider
abstract class PageableMediaFragment : BasePagingFragment<Media>(), MediaDetailProvider {
/**
* ViewBinding
*/
private var _binding: FragmentSearchPaginatedBinding? = null
private val binding get() = _binding
override val pagedListAdapter by lazy {
PagedMediaAdapter(categoryImagesCallback::onMediaClicked)
}
override val errorTextId: Int = R.string.error_loading_images
override fun getEmptyText(query: String) = getString(R.string.no_images_found)
lateinit var categoryImagesCallback: CategoryImagesCallback
override fun onAttach(context: Context) {
super.onAttach(context)
if (parentFragment != null) {
categoryImagesCallback = (parentFragment as CategoryImagesCallback)
} else {
categoryImagesCallback = (activity as CategoryImagesCallback)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentSearchPaginatedBinding.inflate(inflater, container, false)
return binding?.root
}
private val simpleDataObserver =
SimpleDataObserver { categoryImagesCallback.viewPagerNotifyDataSetChanged() }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
pagedListAdapter.registerAdapterDataObserver(simpleDataObserver)
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
pagedListAdapter.unregisterAdapterDataObserver(simpleDataObserver)
}
override fun getMediaAtPosition(position: Int): Media? =
pagedListAdapter.currentList?.get(position)?.takeIf { it.filename != null }
.also {
pagedListAdapter.currentList?.loadAround(position)
binding?.paginatedSearchResultsList?.scrollToPosition(position)
}
override fun getTotalMediaCount(): Int = pagedListAdapter.itemCount
override fun getContributionStateAt(position: Int) = null
/**
* Reload media detail fragment once media is nominated
*
* @param index item position that has been nominated
*/
override fun refreshNominatedMedia(index: Int) {
activity?.onBackPressed()
categoryImagesCallback.onMediaClicked(index)
}
}
| apache-2.0 | 0929ded1c27ace41dd2b681420e7fb71 | 33.282353 | 89 | 0.722718 | 4.955782 | false | false | false | false |
FWDekker/intellij-randomness | src/test/kotlin/com/fwdekker/randomness/GenericTypeMatcherHelper.kt | 1 | 1004 | package com.fwdekker.randomness
import org.assertj.swing.core.GenericTypeMatcher
import java.awt.Component
/**
* Creates a [GenericTypeMatcher] with a lambda.
*
* @param T the type of matcher to return
* @param klass the class to be matched
* @param matcher the matcher that returns `true` if the desired component is found
* @return a [GenericTypeMatcher] with a lambda.
*/
fun <T : Component> matcher(klass: Class<T>, matcher: (T) -> Boolean) =
object : GenericTypeMatcher<T>(klass) {
override fun isMatching(component: T) = matcher(component)
}
/**
* Returns a [GenericTypeMatcher] for returning the first component that is named [name].
*
* @param T the type of matcher to return
* @param klass the type to match an instance of
* @param name the name to return a matcher for
* @return a [GenericTypeMatcher] for returning the first component that is named [name]
*/
fun <T : Component> nameMatcher(klass: Class<T>, name: String) = matcher(klass) { it.name == name }
| mit | 881e5170af8b56269794b83be2561015 | 34.857143 | 99 | 0.717131 | 3.921875 | false | false | false | false |
dreamkas/start-utils | versions-utils/src/main/java/ru/dreamkas/semver/prerelease/PreReleaseStringId.kt | 1 | 654 | package ru.dreamkas.semver.prerelease
class PreReleaseStringId(val id: String) : PreReleaseId {
override fun compareTo(other: PreReleaseId): Int {
return if (other is PreReleaseNumericId) 1
else id.compareTo((other as PreReleaseStringId).id, ignoreCase = true)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as PreReleaseStringId
if (id.toLowerCase() != other.id.toLowerCase()) return false
return true
}
override fun hashCode(): Int {
return id.toLowerCase().hashCode()
}
} | mit | 175933f4f6d4479ae3c456e26f596ad4 | 26.291667 | 78 | 0.652905 | 4.389262 | false | false | false | false |
androidx/constraintlayout | demoProjects/ComposeMail/app/src/main/java/com/example/composemail/ui/components/CheapText.kt | 2 | 2392 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.composemail.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.width
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
/**
* [Text] Composable constrained to one line for better animation performance.
*/
@Suppress("NOTHING_TO_INLINE")
@Composable
inline fun CheapText(
text: String,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
style: TextStyle = LocalTextStyle.current,
overflow: TextOverflow = TextOverflow.Clip
) {
Text(
text = text,
modifier = modifier,
color = color,
style = style,
maxLines = 1,
overflow = overflow,
)
}
@Preview
@Composable
private fun CheapTextPreview() {
Column(Modifier.fillMaxSize()) {
Text(text = "Normal")
Column(
Modifier
.width(40.dp)
.background(Color.LightGray)
) {
Text(text = "Hello \nWorld!")
Text(text = "This is a very very long text")
}
Text(text = "Cheap")
Column(
Modifier
.width(40.dp)
.background(Color.LightGray)
) {
CheapText(text = "Hello \nWorld!")
CheapText(text = "This is a very very long text")
}
}
} | apache-2.0 | b92bb74463860830a88945e2ca52f3d6 | 29.679487 | 78 | 0.678094 | 4.241135 | false | false | false | false |
MichaelRocks/lightsaber | samples/injection-test/src/test/java/io/michaelrocks/lightsaber/QualifiedInjectionTest.kt | 1 | 36032 | /*
* Copyright 2019 Michael Rozumyanskiy
*
* 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.michaelrocks.lightsaber
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.AnnotationArrayQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.AnnotationQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.BooleanArrayQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.BooleanQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.ByteArrayQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.ByteQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.CharArrayQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.CharQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.ClassArrayQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.ClassQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.DoubleArrayQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.DoubleQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.EmptyQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.EnumArrayQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.EnumQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.FloatArrayQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.FloatQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.IntArrayQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.IntQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.LongArrayQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.LongQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.ShortArrayQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.ShortQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.StringArrayQualifier
import io.michaelrocks.lightsaber.QualifiedInjectionTest.Qualifiers.StringQualifier
import org.junit.Assert.assertEquals
import org.junit.Test
import javax.inject.Inject
import javax.inject.Qualifier
import kotlin.reflect.KClass
class QualifiedInjectionTest {
@Test
fun testConstructionInjection() {
val injector = Lightsaber.Builder().build().createInjector(QualifiedComponent())
val container = injector.getInstance<ConstructorInjectionContainer>()
validateContainer(QualifiedModule(), container)
}
@Test
fun testFieldInjection() {
val injector = Lightsaber.Builder().build().createInjector(QualifiedComponent())
val container = FieldInjectionContainer()
injector.injectMembers(container)
validateContainer(QualifiedModule(), container)
}
@Test
fun testMethodInjection() {
val injector = Lightsaber.Builder().build().createInjector(QualifiedComponent())
val container = MethodInjectionContainer()
injector.injectMembers(container)
validateContainer(QualifiedModule(), container)
}
private fun validateContainer(module: QualifiedModule, container: Container) {
assertEquals(module.provideNoQualifier(), container.noQualifier)
assertEquals(module.provideEmptyQualifier(), container.emptyQualifier)
assertEquals(module.provideBooleanQualifier(), container.booleanQualifier)
assertEquals(module.provideBooleanQualifierExplicit(), container.booleanQualifierExplicit)
assertEquals(module.provideByteQualifier(), container.byteQualifier)
assertEquals(module.provideByteQualifierExplicit(), container.byteQualifierExplicit)
assertEquals(module.provideCharQualifier(), container.charQualifier)
assertEquals(module.provideCharQualifierExplicit(), container.charQualifierExplicit)
assertEquals(module.provideFloatQualifier(), container.floatQualifier)
assertEquals(module.provideFloatQualifierExplicit(), container.floatQualifierExplicit)
assertEquals(module.provideDoubleQualifier(), container.doubleQualifier)
assertEquals(module.provideDoubleQualifierExplicit(), container.doubleQualifierExplicit)
assertEquals(module.provideIntQualifier(), container.intQualifier)
assertEquals(module.provideIntQualifierExplicit(), container.intQualifierExplicit)
assertEquals(module.provideLongQualifier(), container.longQualifier)
assertEquals(module.provideLongQualifierExplicit(), container.longQualifierExplicit)
assertEquals(module.provideShortQualifier(), container.shortQualifier)
assertEquals(module.provideShortQualifierExplicit(), container.shortQualifierExplicit)
assertEquals(module.provideStringQualifier(), container.stringQualifier)
assertEquals(module.provideStringQualifierExplicit(), container.stringQualifierExplicit)
assertEquals(module.provideEnumQualifier(), container.enumQualifier)
assertEquals(module.provideEnumQualifierExplicit(), container.enumQualifierExplicit)
assertEquals(module.provideClassQualifier(), container.classQualifier)
assertEquals(module.provideClassQualifierExplicit(), container.classQualifierExplicit)
assertEquals(module.provideAnnotationQualifier(), container.annotationQualifier)
assertEquals(module.provideAnnotationQualifierExplicit(), container.annotationQualifierExplicit)
assertEquals(module.provideBooleanArrayQualifier(), container.booleanArrayQualifier)
assertEquals(module.provideBooleanArrayQualifierExplicit(), container.booleanArrayQualifierExplicit)
assertEquals(module.provideByteArrayQualifier(), container.byteArrayQualifier)
assertEquals(module.provideByteArrayQualifierExplicit(), container.byteArrayQualifierExplicit)
assertEquals(module.provideCharArrayQualifier(), container.charArrayQualifier)
assertEquals(module.provideCharArrayQualifierExplicit(), container.charArrayQualifierExplicit)
assertEquals(module.provideFloatArrayQualifier(), container.floatArrayQualifier)
assertEquals(module.provideFloatArrayQualifierExplicit(), container.floatArrayQualifierExplicit)
assertEquals(module.provideDoubleArrayQualifier(), container.doubleArrayQualifier)
assertEquals(module.provideDoubleArrayQualifierExplicit(), container.doubleArrayQualifierExplicit)
assertEquals(module.provideIntArrayQualifier(), container.intArrayQualifier)
assertEquals(module.provideIntArrayQualifierExplicit(), container.intArrayQualifierExplicit)
assertEquals(module.provideLongArrayQualifier(), container.longArrayQualifier)
assertEquals(module.provideLongArrayQualifierExplicit(), container.longArrayQualifierExplicit)
assertEquals(module.provideShortArrayQualifier(), container.shortArrayQualifier)
assertEquals(module.provideShortArrayQualifierExplicit(), container.shortArrayQualifierExplicit)
assertEquals(module.provideStringArrayQualifier(), container.stringArrayQualifier)
assertEquals(module.provideStringArrayQualifierExplicit(), container.stringArrayQualifierExplicit)
assertEquals(module.provideEnumArrayQualifier(), container.enumArrayQualifier)
assertEquals(module.provideEnumArrayQualifierExplicit(), container.enumArrayQualifierExplicit)
assertEquals(module.provideClassArrayQualifier(), container.classArrayQualifier)
assertEquals(module.provideClassArrayQualifierExplicit(), container.classArrayQualifierExplicit)
assertEquals(module.provideAnnotationArrayQualifier(), container.annotationArrayQualifier)
assertEquals(module.provideAnnotationArrayQualifierExplicit(), container.annotationArrayQualifierExplicit)
}
@Module
private class QualifiedModule {
@Provide
fun provideNoQualifier(): String = "NoQualifier"
@Provide
@EmptyQualifier
fun provideEmptyQualifier(): String = "EmptyQualifier"
@Provide
@BooleanQualifier
fun provideBooleanQualifier(): String = "BooleanQualifier"
@Provide
@BooleanQualifier(false)
fun provideBooleanQualifierExplicit(): String = "BooleanQualifierExplicit"
@Provide
@ByteQualifier
fun provideByteQualifier(): String = "ByteQualifier"
@Provide
@ByteQualifier(-42)
fun provideByteQualifierExplicit(): String = "ByteQualifierExplicit"
@Provide
@CharQualifier
fun provideCharQualifier(): String = "CharQualifier"
@Provide
@CharQualifier('y')
fun provideCharQualifierExplicit(): String = "CharQualifierExplicit"
@Provide
@FloatQualifier
fun provideFloatQualifier(): String = "FloatQualifier"
@Provide
@FloatQualifier(-0.0f)
fun provideFloatQualifierExplicit(): String = "FloatQualifierExplicit"
@Provide
@DoubleQualifier
fun provideDoubleQualifier(): String = "DoubleQualifier"
@Provide
@DoubleQualifier(-0.0)
fun provideDoubleQualifierExplicit(): String = "DoubleQualifierExplicit"
@Provide
@IntQualifier
fun provideIntQualifier(): String = "IntQualifier"
@Provide
@IntQualifier(-42)
fun provideIntQualifierExplicit(): String = "IntQualifierExplicit"
@Provide
@LongQualifier
fun provideLongQualifier(): String = "LongQualifier"
@Provide
@LongQualifier(-42L)
fun provideLongQualifierExplicit(): String = "LongQualifierExplicit"
@Provide
@ShortQualifier
fun provideShortQualifier(): String = "ShortQualifier"
@Provide
@ShortQualifier(-42)
fun provideShortQualifierExplicit(): String = "ShortQualifierExplicit"
@Provide
@StringQualifier
fun provideStringQualifier(): String = "StringQualifier"
@Provide
@StringQualifier("ExplicitValue")
fun provideStringQualifierExplicit(): String = "StringQualifierExplicit"
@Provide
@EnumQualifier
fun provideEnumQualifier(): String = "EnumQualifier"
@Provide
@EnumQualifier(AnnotationRetention.BINARY)
fun provideEnumQualifierExplicit(): String = "EnumQualifierExplicit"
@Provide
@ClassQualifier
fun provideClassQualifier(): String = "ClassQualifier"
@Provide
@ClassQualifier(String::class)
fun provideClassQualifierExplicit(): String = "ClassQualifierExplicit"
@Provide
@AnnotationQualifier
fun provideAnnotationQualifier(): String = "AnnotationQualifier"
@Provide
@AnnotationQualifier(IntQualifier(-42))
fun provideAnnotationQualifierExplicit(): String = "AnnotationQualifierExplicit"
@Provide
@BooleanArrayQualifier
fun provideBooleanArrayQualifier(): String = "BooleanArrayQualifier"
@Provide
@BooleanArrayQualifier(false)
fun provideBooleanArrayQualifierExplicit(): String = "BooleanArrayQualifierExplicit"
@Provide
@ByteArrayQualifier
fun provideByteArrayQualifier(): String = "ByteArrayQualifier"
@Provide
@ByteArrayQualifier(-42)
fun provideByteArrayQualifierExplicit(): String = "ByteArrayQualifierExplicit"
@Provide
@CharArrayQualifier
fun provideCharArrayQualifier(): String = "CharArrayQualifier"
@Provide
@CharArrayQualifier('y')
fun provideCharArrayQualifierExplicit(): String = "CharArrayQualifierExplicit"
@Provide
@FloatArrayQualifier
fun provideFloatArrayQualifier(): String = "FloatArrayQualifier"
@Provide
@FloatArrayQualifier(-0.0f)
fun provideFloatArrayQualifierExplicit(): String = "FloatArrayQualifierExplicit"
@Provide
@DoubleArrayQualifier
fun provideDoubleArrayQualifier(): String = "DoubleArrayQualifier"
@Provide
@DoubleArrayQualifier(-0.0)
fun provideDoubleArrayQualifierExplicit(): String = "DoubleArrayQualifierExplicit"
@Provide
@IntArrayQualifier
fun provideIntArrayQualifier(): String = "IntArrayQualifier"
@Provide
@IntArrayQualifier(-42)
fun provideIntArrayQualifierExplicit(): String = "IntArrayQualifierExplicit"
@Provide
@LongArrayQualifier
fun provideLongArrayQualifier(): String = "LongArrayQualifier"
@Provide
@LongArrayQualifier(-42L)
fun provideLongArrayQualifierExplicit(): String = "LongArrayQualifierExplicit"
@Provide
@ShortArrayQualifier
fun provideShortArrayQualifier(): String = "ShortArrayQualifier"
@Provide
@ShortArrayQualifier(-42)
fun provideShortArrayQualifierExplicit(): String = "ShortArrayQualifierExplicit"
@Provide
@StringArrayQualifier
fun provideStringArrayQualifier(): String = "StringArrayQualifier"
@Provide
@StringArrayQualifier("ExplicitValue")
fun provideStringArrayQualifierExplicit(): String = "StringArrayQualifierExplicit"
@Provide
@EnumArrayQualifier
fun provideEnumArrayQualifier(): String = "EnumArrayQualifier"
@Provide
@EnumArrayQualifier(AnnotationRetention.BINARY)
fun provideEnumArrayQualifierExplicit(): String = "EnumArrayQualifierExplicit"
@Provide
@ClassArrayQualifier
fun provideClassArrayQualifier(): String = "ClassArrayQualifier"
@Provide
@ClassArrayQualifier(String::class)
fun provideClassArrayQualifierExplicit(): String = "ClassArrayQualifierExplicit"
@Provide
@AnnotationArrayQualifier
fun provideAnnotationArrayQualifier(): String = "AnnotationArrayQualifier"
@Provide
@AnnotationArrayQualifier(IntQualifier(-42))
fun provideAnnotationArrayQualifierExplicit(): String = "AnnotationArrayQualifierExplicit"
}
@Component
private class QualifiedComponent {
@Import
fun importQualifiedModule(): QualifiedModule = QualifiedModule()
}
private interface Container {
val noQualifier: String
val emptyQualifier: String
val booleanQualifier: String
val booleanQualifierExplicit: String
val byteQualifier: String
val byteQualifierExplicit: String
val charQualifier: String
val charQualifierExplicit: String
val floatQualifier: String
val floatQualifierExplicit: String
val doubleQualifier: String
val doubleQualifierExplicit: String
val intQualifier: String
val intQualifierExplicit: String
val longQualifier: String
val longQualifierExplicit: String
val shortQualifier: String
val shortQualifierExplicit: String
val stringQualifier: String
val stringQualifierExplicit: String
val enumQualifier: String
val enumQualifierExplicit: String
val classQualifier: String
val classQualifierExplicit: String
val annotationQualifier: String
val annotationQualifierExplicit: String
val booleanArrayQualifier: String
val booleanArrayQualifierExplicit: String
val byteArrayQualifier: String
val byteArrayQualifierExplicit: String
val charArrayQualifier: String
val charArrayQualifierExplicit: String
val floatArrayQualifier: String
val floatArrayQualifierExplicit: String
val doubleArrayQualifier: String
val doubleArrayQualifierExplicit: String
val intArrayQualifier: String
val intArrayQualifierExplicit: String
val longArrayQualifier: String
val longArrayQualifierExplicit: String
val shortArrayQualifier: String
val shortArrayQualifierExplicit: String
val stringArrayQualifier: String
val stringArrayQualifierExplicit: String
val enumArrayQualifier: String
val enumArrayQualifierExplicit: String
val classArrayQualifier: String
val classArrayQualifierExplicit: String
val annotationArrayQualifier: String
val annotationArrayQualifierExplicit: String
}
@ProvidedBy(QualifiedModule::class)
private class ConstructorInjectionContainer @Inject constructor(
override val noQualifier: String,
@EmptyQualifier
override val emptyQualifier: String,
@BooleanQualifier
override val booleanQualifier: String,
@BooleanQualifier(false)
override val booleanQualifierExplicit: String,
@ByteQualifier
override val byteQualifier: String,
@ByteQualifier(-42)
override val byteQualifierExplicit: String,
@CharQualifier
override val charQualifier: String,
@CharQualifier('y')
override val charQualifierExplicit: String,
@FloatQualifier
override val floatQualifier: String,
@FloatQualifier(-0.0f)
override val floatQualifierExplicit: String,
@DoubleQualifier
override val doubleQualifier: String,
@DoubleQualifier(-0.0)
override val doubleQualifierExplicit: String,
@IntQualifier
override val intQualifier: String,
@IntQualifier(-42)
override val intQualifierExplicit: String,
@LongQualifier
override val longQualifier: String,
@LongQualifier(-42L)
override val longQualifierExplicit: String,
@ShortQualifier
override val shortQualifier: String,
@ShortQualifier(-42)
override val shortQualifierExplicit: String,
@StringQualifier
override val stringQualifier: String,
@StringQualifier("ExplicitValue")
override val stringQualifierExplicit: String,
@EnumQualifier
override val enumQualifier: String,
@EnumQualifier(AnnotationRetention.BINARY)
override val enumQualifierExplicit: String,
@ClassQualifier
override val classQualifier: String,
@ClassQualifier(String::class)
override val classQualifierExplicit: String,
@AnnotationQualifier
override val annotationQualifier: String,
@AnnotationQualifier(IntQualifier(-42))
override val annotationQualifierExplicit: String,
@BooleanArrayQualifier
override val booleanArrayQualifier: String,
@BooleanArrayQualifier(false)
override val booleanArrayQualifierExplicit: String,
@ByteArrayQualifier
override val byteArrayQualifier: String,
@ByteArrayQualifier(-42)
override val byteArrayQualifierExplicit: String,
@CharArrayQualifier
override val charArrayQualifier: String,
@CharArrayQualifier('y')
override val charArrayQualifierExplicit: String,
@FloatArrayQualifier
override val floatArrayQualifier: String,
@FloatArrayQualifier(-0.0f)
override val floatArrayQualifierExplicit: String,
@DoubleArrayQualifier
override val doubleArrayQualifier: String,
@DoubleArrayQualifier(-0.0)
override val doubleArrayQualifierExplicit: String,
@IntArrayQualifier
override val intArrayQualifier: String,
@IntArrayQualifier(-42)
override val intArrayQualifierExplicit: String,
@LongArrayQualifier
override val longArrayQualifier: String,
@LongArrayQualifier(-42L)
override val longArrayQualifierExplicit: String,
@ShortArrayQualifier
override val shortArrayQualifier: String,
@ShortArrayQualifier(-42)
override val shortArrayQualifierExplicit: String,
@StringArrayQualifier
override val stringArrayQualifier: String,
@StringArrayQualifier("ExplicitValue")
override val stringArrayQualifierExplicit: String,
@EnumArrayQualifier
override val enumArrayQualifier: String,
@EnumArrayQualifier(AnnotationRetention.BINARY)
override val enumArrayQualifierExplicit: String,
@ClassArrayQualifier
override val classArrayQualifier: String,
@ClassArrayQualifier(String::class)
override val classArrayQualifierExplicit: String,
@AnnotationArrayQualifier
override val annotationArrayQualifier: String,
@AnnotationArrayQualifier(IntQualifier(-42))
override val annotationArrayQualifierExplicit: String
) : Container
private class FieldInjectionContainer : Container {
@Inject
override lateinit var noQualifier: String
@Inject
@EmptyQualifier
override lateinit var emptyQualifier: String
@Inject
@BooleanQualifier
override lateinit var booleanQualifier: String
@Inject
@BooleanQualifier(false)
override lateinit var booleanQualifierExplicit: String
@Inject
@ByteQualifier
override lateinit var byteQualifier: String
@Inject
@ByteQualifier(-42)
override lateinit var byteQualifierExplicit: String
@Inject
@CharQualifier
override lateinit var charQualifier: String
@Inject
@CharQualifier('y')
override lateinit var charQualifierExplicit: String
@Inject
@FloatQualifier
override lateinit var floatQualifier: String
@Inject
@FloatQualifier(-0.0f)
override lateinit var floatQualifierExplicit: String
@Inject
@DoubleQualifier
override lateinit var doubleQualifier: String
@Inject
@DoubleQualifier(-0.0)
override lateinit var doubleQualifierExplicit: String
@Inject
@IntQualifier
override lateinit var intQualifier: String
@Inject
@IntQualifier(-42)
override lateinit var intQualifierExplicit: String
@Inject
@LongQualifier
override lateinit var longQualifier: String
@Inject
@LongQualifier(-42L)
override lateinit var longQualifierExplicit: String
@Inject
@ShortQualifier
override lateinit var shortQualifier: String
@Inject
@ShortQualifier(-42)
override lateinit var shortQualifierExplicit: String
@Inject
@StringQualifier
override lateinit var stringQualifier: String
@Inject
@StringQualifier("ExplicitValue")
override lateinit var stringQualifierExplicit: String
@Inject
@EnumQualifier
override lateinit var enumQualifier: String
@Inject
@EnumQualifier(AnnotationRetention.BINARY)
override lateinit var enumQualifierExplicit: String
@Inject
@ClassQualifier
override lateinit var classQualifier: String
@Inject
@ClassQualifier(String::class)
override lateinit var classQualifierExplicit: String
@Inject
@AnnotationQualifier
override lateinit var annotationQualifier: String
@Inject
@AnnotationQualifier(IntQualifier(-42))
override lateinit var annotationQualifierExplicit: String
@Inject
@BooleanArrayQualifier
override lateinit var booleanArrayQualifier: String
@Inject
@BooleanArrayQualifier(false)
override lateinit var booleanArrayQualifierExplicit: String
@Inject
@ByteArrayQualifier
override lateinit var byteArrayQualifier: String
@Inject
@ByteArrayQualifier(-42)
override lateinit var byteArrayQualifierExplicit: String
@Inject
@CharArrayQualifier
override lateinit var charArrayQualifier: String
@Inject
@CharArrayQualifier('y')
override lateinit var charArrayQualifierExplicit: String
@Inject
@FloatArrayQualifier
override lateinit var floatArrayQualifier: String
@Inject
@FloatArrayQualifier(-0.0f)
override lateinit var floatArrayQualifierExplicit: String
@Inject
@DoubleArrayQualifier
override lateinit var doubleArrayQualifier: String
@Inject
@DoubleArrayQualifier(-0.0)
override lateinit var doubleArrayQualifierExplicit: String
@Inject
@IntArrayQualifier
override lateinit var intArrayQualifier: String
@Inject
@IntArrayQualifier(-42)
override lateinit var intArrayQualifierExplicit: String
@Inject
@LongArrayQualifier
override lateinit var longArrayQualifier: String
@Inject
@LongArrayQualifier(-42L)
override lateinit var longArrayQualifierExplicit: String
@Inject
@ShortArrayQualifier
override lateinit var shortArrayQualifier: String
@Inject
@ShortArrayQualifier(-42)
override lateinit var shortArrayQualifierExplicit: String
@Inject
@StringArrayQualifier
override lateinit var stringArrayQualifier: String
@Inject
@StringArrayQualifier("ExplicitValue")
override lateinit var stringArrayQualifierExplicit: String
@Inject
@EnumArrayQualifier
override lateinit var enumArrayQualifier: String
@Inject
@EnumArrayQualifier(AnnotationRetention.BINARY)
override lateinit var enumArrayQualifierExplicit: String
@Inject
@ClassArrayQualifier
override lateinit var classArrayQualifier: String
@Inject
@ClassArrayQualifier(String::class)
override lateinit var classArrayQualifierExplicit: String
@Inject
@AnnotationArrayQualifier
override lateinit var annotationArrayQualifier: String
@Inject
@AnnotationArrayQualifier(IntQualifier(-42))
override lateinit var annotationArrayQualifierExplicit: String
}
private class MethodInjectionContainer : Container {
@set:Inject
override lateinit var noQualifier: String
@set:Inject
@setparam:EmptyQualifier
override lateinit var emptyQualifier: String
@set:Inject
@setparam:BooleanQualifier
override lateinit var booleanQualifier: String
@set:Inject
@setparam:BooleanQualifier(false)
override lateinit var booleanQualifierExplicit: String
@set:Inject
@setparam:ByteQualifier
override lateinit var byteQualifier: String
@set:Inject
@setparam:ByteQualifier(-42)
override lateinit var byteQualifierExplicit: String
@set:Inject
@setparam:CharQualifier
override lateinit var charQualifier: String
@set:Inject
@setparam:CharQualifier('y')
override lateinit var charQualifierExplicit: String
@set:Inject
@setparam:FloatQualifier
override lateinit var floatQualifier: String
@set:Inject
@setparam:FloatQualifier(-0.0f)
override lateinit var floatQualifierExplicit: String
@set:Inject
@setparam:DoubleQualifier
override lateinit var doubleQualifier: String
@set:Inject
@setparam:DoubleQualifier(-0.0)
override lateinit var doubleQualifierExplicit: String
@set:Inject
@setparam:IntQualifier
override lateinit var intQualifier: String
@set:Inject
@setparam:IntQualifier(-42)
override lateinit var intQualifierExplicit: String
@set:Inject
@setparam:LongQualifier
override lateinit var longQualifier: String
@set:Inject
@setparam:LongQualifier(-42L)
override lateinit var longQualifierExplicit: String
@set:Inject
@setparam:ShortQualifier
override lateinit var shortQualifier: String
@set:Inject
@setparam:ShortQualifier(-42)
override lateinit var shortQualifierExplicit: String
@set:Inject
@setparam:StringQualifier
override lateinit var stringQualifier: String
@set:Inject
@setparam:StringQualifier("ExplicitValue")
override lateinit var stringQualifierExplicit: String
@set:Inject
@setparam:EnumQualifier
override lateinit var enumQualifier: String
@set:Inject
@setparam:EnumQualifier(AnnotationRetention.BINARY)
override lateinit var enumQualifierExplicit: String
@set:Inject
@setparam:ClassQualifier
override lateinit var classQualifier: String
@set:Inject
@setparam:ClassQualifier(String::class)
override lateinit var classQualifierExplicit: String
@set:Inject
@setparam:AnnotationQualifier
override lateinit var annotationQualifier: String
@set:Inject
@setparam:AnnotationQualifier(IntQualifier(-42))
override lateinit var annotationQualifierExplicit: String
@set:Inject
@setparam:BooleanArrayQualifier
override lateinit var booleanArrayQualifier: String
@set:Inject
@setparam:BooleanArrayQualifier(false)
override lateinit var booleanArrayQualifierExplicit: String
@set:Inject
@setparam:ByteArrayQualifier
override lateinit var byteArrayQualifier: String
@set:Inject
@setparam:ByteArrayQualifier(-42)
override lateinit var byteArrayQualifierExplicit: String
@set:Inject
@setparam:CharArrayQualifier
override lateinit var charArrayQualifier: String
@set:Inject
@setparam:CharArrayQualifier('y')
override lateinit var charArrayQualifierExplicit: String
@set:Inject
@setparam:FloatArrayQualifier
override lateinit var floatArrayQualifier: String
@set:Inject
@setparam:FloatArrayQualifier(-0.0f)
override lateinit var floatArrayQualifierExplicit: String
@set:Inject
@setparam:DoubleArrayQualifier
override lateinit var doubleArrayQualifier: String
@set:Inject
@setparam:DoubleArrayQualifier(-0.0)
override lateinit var doubleArrayQualifierExplicit: String
@set:Inject
@setparam:IntArrayQualifier
override lateinit var intArrayQualifier: String
@set:Inject
@setparam:IntArrayQualifier(-42)
override lateinit var intArrayQualifierExplicit: String
@set:Inject
@setparam:LongArrayQualifier
override lateinit var longArrayQualifier: String
@set:Inject
@setparam:LongArrayQualifier(-42L)
override lateinit var longArrayQualifierExplicit: String
@set:Inject
@setparam:ShortArrayQualifier
override lateinit var shortArrayQualifier: String
@set:Inject
@setparam:ShortArrayQualifier(-42)
override lateinit var shortArrayQualifierExplicit: String
@set:Inject
@setparam:StringArrayQualifier
override lateinit var stringArrayQualifier: String
@set:Inject
@setparam:StringArrayQualifier("ExplicitValue")
override lateinit var stringArrayQualifierExplicit: String
@set:Inject
@setparam:EnumArrayQualifier
override lateinit var enumArrayQualifier: String
@set:Inject
@setparam:EnumArrayQualifier(AnnotationRetention.BINARY)
override lateinit var enumArrayQualifierExplicit: String
@set:Inject
@setparam:ClassArrayQualifier
override lateinit var classArrayQualifier: String
@set:Inject
@setparam:ClassArrayQualifier(String::class)
override lateinit var classArrayQualifierExplicit: String
@set:Inject
@setparam:AnnotationArrayQualifier
override lateinit var annotationArrayQualifier: String
@set:Inject
@setparam:AnnotationArrayQualifier(IntQualifier(-42))
override lateinit var annotationArrayQualifierExplicit: String
}
interface Qualifiers {
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class EmptyQualifier
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class BooleanQualifier(val value: Boolean = true)
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class ByteQualifier(val value: Byte = 42)
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class CharQualifier(val value: Char = 'x')
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class FloatQualifier(val value: Float = Math.E.toFloat())
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class DoubleQualifier(val value: Double = Math.PI)
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class IntQualifier(val value: Int = 42)
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class LongQualifier(val value: Long = 42L)
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class ShortQualifier(val value: Short = 42)
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class StringQualifier(val value: String = "Value")
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class EnumQualifier(val value: AnnotationRetention = AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class ClassQualifier(val value: KClass<*> = Any::class)
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class AnnotationQualifier(val value: IntQualifier = IntQualifier())
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class BooleanArrayQualifier(vararg val value: Boolean = booleanArrayOf(true))
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class ByteArrayQualifier(vararg val value: Byte = byteArrayOf(42))
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class CharArrayQualifier(vararg val value: Char = charArrayOf('x'))
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class FloatArrayQualifier(vararg val value: Float = floatArrayOf(0.0f))
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class DoubleArrayQualifier(vararg val value: Double = doubleArrayOf(0.0))
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class IntArrayQualifier(vararg val value: Int = intArrayOf(42))
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class LongArrayQualifier(vararg val value: Long = longArrayOf(42L))
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class ShortArrayQualifier(vararg val value: Short = shortArrayOf(42))
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class StringArrayQualifier(vararg val value: String = arrayOf("Value"))
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class EnumArrayQualifier(vararg val value: AnnotationRetention = arrayOf(AnnotationRetention.RUNTIME))
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class ClassArrayQualifier(vararg val value: KClass<*> = arrayOf(Any::class))
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class AnnotationArrayQualifier(vararg val value: IntQualifier = arrayOf(IntQualifier()))
}
}
| apache-2.0 | 10011cbfea056d9ebba44663cc5f7d3b | 34.290891 | 117 | 0.780667 | 5.212963 | false | false | false | false |
google/xplat | kmpbench/kotlin/com/google/j2cl/benchmarking/framework/CollectionUtilizer.kt | 1 | 2435 | /*
* Copyright 2014 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 com.google.j2cl.benchmarking.framework
// This is a Kotlin port of the corresponding J2cl Java class in
// google3/third_party/java_src/j2cl/benchmarking/java/com/google/j2cl/benchmarking/framework/
/** Ensures multiple versions of the collections are alive to prevent special case optimizations. */
object CollectionUtilizer {
fun dependOnAllCollections() {
utilizeMap(mutableMapOf<String, String>())
utilizeList(mutableListOf<String>())
// TODO(b/230841155): Some of the more complex utilization code that doesn't translate 1:1 to
// native Kotlin was removed here. Before spending effort, clarify with J2cl benchmark owners
// why it was considered necessary
}
private fun utilizeMap(map: MutableMap<String, String>) {
if (addGet(map) && iterate(map) && remove(map)) {
return
}
throw AssertionError()
}
private fun addGet(map: MutableMap<String, String>): Boolean {
map["input"] = "output"
return "output" == map.get("input") && map.size == 1
}
private fun iterate(map: Map<String, String>): Boolean {
var result = ""
for (entry in map.entries) {
result += entry.key + entry.value
}
return result.length > 0
}
private fun remove(map: MutableMap<String, String>) = "output" == map.remove("input")
private fun utilizeList(list: MutableList<String>) {
if (addGet(list) && iterate(list) && remove(list)) {
return
}
throw AssertionError()
}
private fun addGet(list: MutableList<String>): Boolean {
list.add("input")
return "input" == list[0] && list.size == 1
}
private fun remove(list: MutableList<String>) = "input" == list.removeAt(0)
private fun iterate(list: List<String>): Boolean {
var result = ""
for (entry in list) {
result += entry
}
return result.length > 0
}
}
| apache-2.0 | 09d55e2e2d53520132148554538a7f5d | 31.039474 | 100 | 0.685832 | 3.902244 | false | false | false | false |
NuclearCoder/nuclear-bot | src/nuclearbot/gui/commands/UserCommandManager.kt | 1 | 7129 | package nuclearbot.gui.commands
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken
import nuclearbot.gui.NuclearBotGUI
import nuclearbot.util.Logger
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.io.IOException
import javax.swing.JComboBox
/*
* Copyright (C) 2017 NuclearCoder
*
* 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/>.
*/
/**
* Manager for user-defined commands.<br></br>
* <br></br>
* NuclearBot (https://github.com/NuclearCoder/nuclear-bot/)<br></br>
* @author NuclearCoder (contact on the GitHub repo)
*/
class UserCommandManager(private val gui: NuclearBotGUI, private val combo: JComboBox<String>) {
private val commands = mutableMapOf<String, CommandInfo>()
// contains the commands that failed to register to the client
private val failedRegister = mutableSetOf<String>()
private val dialogs = gui.dialogs
private val file = File(FILE_NAME).also {
if (!it.exists() && it.mkdirs() && it.delete()) {
try {
if (it.createNewFile()) {
FileWriter(it, false).use { it.write("[]") }
}
} catch (e: IOException) {
Logger.warning("(uCmd) Could not create \"$FILE_NAME\" for persistence.")
Logger.warning("(uCmd) User-defined commands will only last one lifetime.")
Logger.printStackTrace(e)
}
}
}
fun createUserCommand(name: String, usage: String, description: String, response: String, silent: Boolean) {
if (commands.containsKey(name)) {
Logger.info("(uCmd) Updating command \"$name\"...")
if (gui.isClientRunning) {
gui.client.unregisterCommand(name)
}
commands.remove(name)
combo.removeItem(name)
} else {
Logger.info("(uCmd) Creating command \"$name\"...")
}
if (gui.isClientRunning) {
if (!gui.client.isCommandRegistered(name)) {
gui.client.registerCommand(name, UserCommand(response)).apply {
this.usage = usage
this.description = description
}
failedRegister.remove(name)
} else {
Logger.warning("(uCmd) Command \"$name\" is already registered.")
if (!silent) {
dialogs.warning("Command \"$name\" has already been registered.", "Command already registered")
}
failedRegister.add(name)
}
} else {
Logger.warning("(uCmd) Command \"$name\" will be registered when the client starts.")
if (!silent) {
dialogs.warning("Command \"$name\" will be registered when the client starts.", "Client is not running")
}
}
commands.put(name, CommandInfo(name, usage, description, response))
combo.addItem(name)
saveCommands(silent)
Logger.info("(uCmd) Command \"$name\" created successfully.")
if (!silent) {
dialogs.info("Command \"$name\" created.", "Command created")
}
}
private fun saveCommands(silent: Boolean) {
try {
FileWriter(file, false).use { Gson().toJson(commands.values, Collection::class.java, it) }
} catch (e: IOException) {
Logger.error("(uCmd) Couldn't save persistent user command:")
Logger.printStackTrace(e)
if (!silent) {
dialogs.error("Couldn't save persistent user command. Check console for details.", "Couldn't save config")
}
}
}
fun loadCommands() {
commands.clear()
try {
FileReader(file).use { reader ->
Gson().fromJson<List<CommandInfo>>(reader, object : TypeToken<List<CommandInfo>>() {}.type).forEach {
createUserCommand(it.name, it.usage, it.description, it.response, true)
}
}
} catch (e: JsonSyntaxException) {
Logger.error("(uCmd) Error while loading user commands:")
Logger.printStackTrace(e)
dialogs.error("Error in the user commands configuration. Check console for details.", "JSON syntax error")
} catch (e: IOException) {
Logger.error("(uCmd) Error while loading user commands:")
Logger.printStackTrace(e)
dialogs.error("Error in the user commands configuration. Check console for details.", "JSON syntax error")
}
}
fun getCommand(name: String): CommandInfo? {
return commands[name]
}
fun removeCommand(name: String, silent: Boolean) {
if (commands.containsKey(name)) {
if (gui.isClientRunning && !failedRegister.contains(name))
gui.client.unregisterCommand(name)
commands.remove(name)
combo.removeItem(name)
if (!silent) {
Logger.info("(uCmd) Command \"$name\" removed successfully.")
dialogs.info("Command \"$name\" removed successfully.", "Command removed")
}
} else {
if (!silent) {
Logger.info("(uCmd) Command \"$name\" is not a user command.")
dialogs.warning("Command \"$name\" is not a user command.", "Not a user command")
}
}
}
operator fun contains(command: String): Boolean {
return commands.containsKey(command)
}
fun registerCommands() {
failedRegister.clear()
commands.forEach { name, command ->
val executor = UserCommand(command.response)
try {
gui.client.registerCommand(command.name, executor).apply {
usage = command.usage
description = command.description
}
} catch (e: IllegalArgumentException) {
Logger.warning("(uCmd) User command \"${command.name}\" was already registered by something else.")
dialogs.warning("User command \"${command.name}\" was already registered by something else.", "Command already registered")
failedRegister.add(name)
}
}
}
class CommandInfo(val name: String, val usage: String, val description: String, val response: String)
companion object {
private const val FILE_NAME = "commands.json"
}
}
| agpl-3.0 | 435e4cd12c3deb9dddd1e954398ae4c6 | 36.719577 | 139 | 0.595736 | 4.702507 | false | false | false | false |
carlphilipp/chicago-commutes | android-app/src/main/kotlin/fr/cph/chicago/core/adapter/BusMapSnippetAdapter.kt | 1 | 2485 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.core.adapter
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import fr.cph.chicago.R
import fr.cph.chicago.core.model.BusArrival
/**
* Adapter that will handle bus map
*
* @author Carl-Philipp Harmant
* @version 1
*/
class BusMapSnippetAdapter(private val arrivals: List<BusArrival>) : BaseAdapter() {
override fun getCount(): Int {
return arrivals.size
}
override fun getItem(position: Int): Any {
return arrivals[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
var view = convertView
val arrival = getItem(position) as BusArrival
val viewHolder: ViewHolder
if (view == null) {
val vi = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
view = vi.inflate(R.layout.list_map_train, parent, false)
viewHolder = ViewHolder(
view.findViewById(R.id.station_name),
view.findViewById(R.id.time)
)
view.tag = viewHolder
} else {
viewHolder = view.tag as ViewHolder
}
viewHolder.stationName.text = arrival.stopName
if (position == (arrivals.size - 1) && "No service" == arrival.timeLeftDueDelay) {
viewHolder.stationName.gravity = Gravity.CENTER
} else {
viewHolder.time.text = arrival.timeLeftDueDelay
viewHolder.stationName.gravity = Gravity.START
}
return view
}
private class ViewHolder(val stationName: TextView, val time: TextView)
}
| apache-2.0 | f5cb098abd344a82449d9ad02ba2ba56 | 30.858974 | 103 | 0.676056 | 4.344406 | false | false | false | false |
collinx/susi_android | app/src/main/java/org/fossasia/susi/ai/helper/StartSnapHelper.kt | 1 | 3517 | package org.fossasia.susi.ai.helper
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.LinearSnapHelper
import android.support.v7.widget.OrientationHelper
import android.support.v7.widget.RecyclerView
import android.view.View
/**
* Created by robinkamboj on 04/01/18.
*/
class StartSnapHelper : LinearSnapHelper() {
private var mVerticalHelper: OrientationHelper? = null
private var mHorizontalHelper: OrientationHelper? = null
@Throws(IllegalStateException::class)
override fun attachToRecyclerView(recyclerView: RecyclerView?) {
super.attachToRecyclerView(recyclerView)
}
override fun calculateDistanceToFinalSnap(layoutManager: RecyclerView.LayoutManager,
targetView: View): IntArray? {
val out = IntArray(2)
if (layoutManager.canScrollHorizontally()) {
out[0] = distanceToStart(targetView, getHorizontalHelper(layoutManager))
} else {
out[0] = 0
}
if (layoutManager.canScrollVertically()) {
out[1] = distanceToStart(targetView, getVerticalHelper(layoutManager))
} else {
out[1] = 0
}
return out
}
override fun findSnapView(layoutManager: RecyclerView.LayoutManager): View? {
return if (layoutManager is LinearLayoutManager) {
if (layoutManager.canScrollHorizontally()) {
getStartView(layoutManager, getHorizontalHelper(layoutManager))
} else {
getStartView(layoutManager, getVerticalHelper(layoutManager))
}
} else super.findSnapView(layoutManager)
}
private fun distanceToStart(targetView: View, helper: OrientationHelper): Int {
return helper.getDecoratedStart(targetView) - helper.startAfterPadding
}
private fun getStartView(layoutManager: RecyclerView.LayoutManager,
helper: OrientationHelper): View? {
if (layoutManager is LinearLayoutManager) {
val firstChild = layoutManager.findFirstVisibleItemPosition()
val isLastItem = layoutManager
.findLastCompletelyVisibleItemPosition() == layoutManager.getItemCount() - 1
if (firstChild == RecyclerView.NO_POSITION || isLastItem) {
return null
}
val child = layoutManager.findViewByPosition(firstChild)
return if (helper.getDecoratedEnd(child) >= helper.getDecoratedMeasurement(child) / 2 && helper.getDecoratedEnd(child) > 0) {
child
} else {
if (layoutManager.findLastCompletelyVisibleItemPosition() == layoutManager.getItemCount() - 1) {
null
} else {
layoutManager.findViewByPosition(firstChild + 1)
}
}
}
return super.findSnapView(layoutManager)
}
private fun getVerticalHelper(layoutManager: RecyclerView.LayoutManager): OrientationHelper {
if (mVerticalHelper == null) {
mVerticalHelper = OrientationHelper.createVerticalHelper(layoutManager)
}
return mVerticalHelper!!
}
private fun getHorizontalHelper(layoutManager: RecyclerView.LayoutManager): OrientationHelper {
if (mHorizontalHelper == null) {
mHorizontalHelper = OrientationHelper.createHorizontalHelper(layoutManager)
}
return mHorizontalHelper!!
}
} | apache-2.0 | a22dc875b6c98948d029edb74d1d7261 | 33.831683 | 137 | 0.649986 | 5.495313 | false | false | false | false |
vhromada/Catalog-Spring | src/main/kotlin/cz/vhromada/catalog/web/mapper/impl/EpisodeMapperImpl.kt | 1 | 1148 | package cz.vhromada.catalog.web.mapper.impl
import cz.vhromada.catalog.entity.Episode
import cz.vhromada.catalog.web.fo.EpisodeFO
import cz.vhromada.catalog.web.mapper.EpisodeMapper
import cz.vhromada.catalog.web.mapper.TimeMapper
import org.springframework.stereotype.Component
/**
* A class represents implementation of mapper for episodes.
*
* @author Vladimir Hromada
*/
@Component("webEpisodeMapper")
class EpisodeMapperImpl(private val timeMapper: TimeMapper) : EpisodeMapper {
override fun map(source: Episode): EpisodeFO {
return EpisodeFO(id = source.id,
number = source.number!!.toString(),
length = timeMapper.map(source.length!!),
name = source.name,
note = source.note,
position = source.position)
}
override fun mapBack(source: EpisodeFO): Episode {
return Episode(id = source.id,
number = source.number!!.toInt(),
length = timeMapper.mapBack(source.length!!),
name = source.name,
note = source.note,
position = source.position)
}
}
| mit | b5082c1126f8928e283c7794966fdf18 | 31.8 | 77 | 0.643728 | 4.365019 | false | false | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/util/FileExtensions.kt | 1 | 2227 | package com.jetbrains.rider.plugins.unity.util
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.rider.ideaInterop.fileTypes.msbuild.CsprojFileType
import com.jetbrains.rider.ideaInterop.fileTypes.sln.SolutionFileType
import com.jetbrains.rider.plugins.unity.css.uss.UssFileType
import com.jetbrains.rider.plugins.unity.ideaInterop.fileTypes.uxml.UxmlFileType
import java.util.*
private val nonEditableExtensions = getExtensions()
@Suppress("SpellCheckingInspection")
private fun getExtensions(): Set<String> {
return setOf(
"asset",
"prefab",
"unity",
"meta",
// From Unity's Create menu
"anim", // Animation
"brush",
"controller", // Animator controller
"cubemap",
"flare", // Lens flare
"fontsettings", // Custom font
"giparams", // Lightmap parameters
"guiskin",
"mask", // Avatar mask
"mat", // Material
"mixer", // Audio mixer
"physicMaterial",
"physicsMaterial2D",
"playable", // E.g. Timeline
"overrideController", // Animation override controller
"renderTexture",
"signal", // Timeline signal
"spriteatlas",
"terrainlayer"
)
}
fun isNonEditableUnityFile(file: VirtualFile) = isNonEditableUnityFileExtension(file.extension)
fun isNonEditableUnityFileExtension(extension: String?) = extension != null && nonEditableExtensions.contains(extension.lowercase(Locale.getDefault()))
fun isGeneratedUnityFile(file: VirtualFile): Boolean {
val fileTypeRegistry = FileTypeRegistry.getInstance()
return fileTypeRegistry.isFileOfType(file, CsprojFileType) || fileTypeRegistry.isFileOfType(file, SolutionFileType)
}
fun isUxmlFile(file: VirtualFile) = FileTypeRegistry.getInstance().isFileOfType(file, UxmlFileType)
fun isUssFile(file: VirtualFile) = FileTypeRegistry.getInstance().isFileOfType(file, UssFileType)
| apache-2.0 | e82e25140053313ae9a93b7bde5baa49 | 41.018868 | 151 | 0.639425 | 4.698312 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer | data/src/main/kotlin/de/ph1b/audiobook/data/repo/internals/migrations/Migration24to25.kt | 1 | 9147 | package de.ph1b.audiobook.data.repo.internals.migrations
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.os.Environment
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.sqlite.db.SupportSQLiteQueryBuilder
import de.ph1b.audiobook.data.repo.internals.moveToNextLoop
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import timber.log.Timber
import java.io.File
import java.io.IOException
import java.util.ArrayList
import java.util.InvalidPropertiesFormatException
/**
* Migrate the database so they will be stored as json objects
*/
@SuppressLint("Recycle")
class Migration24to25(
private val context: Context
) : IncrementalMigration(24) {
override fun migrate(db: SupportSQLiteDatabase) {
val copyBookTableName = "TABLE_BOOK_COPY"
val copyChapterTableName = "TABLE_CHAPTERS_COPY"
db.execSQL("ALTER TABLE TABLE_BOOK RENAME TO $copyBookTableName")
db.execSQL("ALTER TABLE TABLE_CHAPTERS RENAME TO $copyChapterTableName")
val newBookTable = "TABLE_BOOK"
val createBookTable =
"""CREATE TABLE $newBookTable (
|BOOK_ID INTEGER PRIMARY KEY AUTOINCREMENT, BOOK_JSON TEXT NOT NULL)""".trimMargin()
db.execSQL(createBookTable)
val bookCursor = db.query(
copyBookTableName,
arrayOf("BOOK_ID", "BOOK_ROOT", "BOOK_TYPE")
)
bookCursor.moveToNextLoop {
val bookId = bookCursor.getLong(0)
val root = bookCursor.getString(1)
val type = bookCursor.getString(2)
val mediaCursor = db.query(
SupportSQLiteQueryBuilder.builder("copyChapterTableName")
.columns(arrayOf("CHAPTER_PATH", "CHAPTER_DURATION", "CHAPTER_NAME"))
.selection("BOOK_ID" + "=?", arrayOf(bookId))
.create()
)
val chapterNames = ArrayList<String>(mediaCursor.count)
val chapterDurations = ArrayList<Int>(mediaCursor.count)
val chapterPaths = ArrayList<String>(mediaCursor.count)
mediaCursor.moveToNextLoop {
chapterPaths.add(mediaCursor.getString(0))
chapterDurations.add(mediaCursor.getInt(1))
chapterNames.add(mediaCursor.getString(2))
}
val configFile = when (type) {
"COLLECTION_FILE", "SINGLE_FILE" -> File(root, "." + chapterNames[0] + "-map.json")
"COLLECTION_FOLDER", "SINGLE_FOLDER" -> File(root, "." + (File(root).name) + "-map.json")
else -> throw InvalidPropertiesFormatException("Upgrade failed due to unknown type=$type")
}
val backupFile = File(configFile.absolutePath + ".backup")
val configFileValid = configFile.exists() && configFile.canRead() && configFile.length() > 0
val backupFileValid = backupFile.exists() && backupFile.canRead() && backupFile.length() > 0
var playingInformation: JSONObject? = null
try {
if (configFileValid) {
configFile.readText(Charsets.UTF_8)
val retString = configFile.readText(Charsets.UTF_8)
if (retString.isNotEmpty()) {
playingInformation = JSONObject(retString)
}
}
} catch (e: JSONException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
try {
if (playingInformation == null && backupFileValid) {
val retString = backupFile.readText(Charsets.UTF_8)
playingInformation = JSONObject(retString)
}
} catch (e: IOException) {
e.printStackTrace()
} catch (e: JSONException) {
e.printStackTrace()
}
if (playingInformation == null) {
throw InvalidPropertiesFormatException("Could not fetch information")
}
val jsonTime = "time"
val jsonBookmarkTime = "time"
val jsonBookmarkTitle = "title"
val jsonSpeed = "speed"
val jsonName = "name"
val jsonBookmarks = "bookmarks"
val jsonRelPath = "relPath"
val jsonBookmarkRelPath = "relPath"
val jsonUseCoverReplacement = "useCoverReplacement"
var currentTime = 0
try {
currentTime = playingInformation.getInt(jsonTime)
} catch (e: JSONException) {
e.printStackTrace()
}
val bookmarkRelPathsUnsafe = ArrayList<String>()
val bookmarkTitlesUnsafe = ArrayList<String>()
val bookmarkTimesUnsafe = ArrayList<Int>()
try {
val bookmarksJ = playingInformation.getJSONArray(jsonBookmarks)
for (i in 0 until bookmarksJ.length()) {
val bookmarkJ = bookmarksJ.get(i) as JSONObject
bookmarkTimesUnsafe.add(bookmarkJ.getInt(jsonBookmarkTime))
bookmarkTitlesUnsafe.add(bookmarkJ.getString(jsonBookmarkTitle))
bookmarkRelPathsUnsafe.add(bookmarkJ.getString(jsonBookmarkRelPath))
}
} catch (e: JSONException) {
e.printStackTrace()
bookmarkRelPathsUnsafe.clear()
bookmarkTitlesUnsafe.clear()
bookmarkTimesUnsafe.clear()
}
val bookmarkRelPathsSafe = ArrayList<String>()
val bookmarkTitlesSafe = ArrayList<String>()
val bookmarkTimesSafe = ArrayList<Int>()
for (i in bookmarkRelPathsUnsafe.indices) {
val bookmarkExists = chapterPaths.any { it == bookmarkRelPathsUnsafe[i] }
if (bookmarkExists) {
bookmarkRelPathsSafe.add(bookmarkRelPathsUnsafe[i])
bookmarkTitlesSafe.add(bookmarkTitlesUnsafe[i])
bookmarkTimesSafe.add(bookmarkTimesUnsafe[i])
}
}
var currentPath = ""
try {
currentPath = playingInformation.getString(jsonRelPath)
} catch (e: JSONException) {
e.printStackTrace()
}
val relPathExists = chapterPaths.contains(currentPath)
if (!relPathExists) {
currentPath = chapterPaths.first()
currentTime = 0
}
var speed = 1.0f
try {
speed = java.lang.Float.valueOf(playingInformation.getString(jsonSpeed))
} catch (e: JSONException) {
e.printStackTrace()
} catch (e: NumberFormatException) {
e.printStackTrace()
}
var name = ""
try {
name = playingInformation.getString(jsonName)
} catch (e: JSONException) {
e.printStackTrace()
}
if (name.isEmpty()) {
name = if (chapterPaths.size == 1) {
val chapterPath = chapterPaths.first()
chapterPath.substring(0, chapterPath.lastIndexOf("."))
} else {
File(root).name
}
}
var useCoverReplacement = false
try {
useCoverReplacement = playingInformation.getBoolean(jsonUseCoverReplacement)
} catch (e: JSONException) {
e.printStackTrace()
}
try {
val chapters = JSONArray()
for (i in chapterPaths.indices) {
val chapter = JSONObject()
chapter.put("path", root + File.separator + chapterPaths[i])
chapter.put("duration", chapterDurations[i])
chapters.put(chapter)
}
val bookmarks = JSONArray()
for (i in bookmarkRelPathsSafe.indices) {
val bookmark = JSONObject()
bookmark.put("mediaPath", root + File.separator + bookmarkRelPathsSafe[i])
bookmark.put("title", bookmarkTitlesSafe[i])
bookmark.put("time", bookmarkTimesSafe[i])
bookmarks.put(bookmark)
}
val book = JSONObject()
book.put("root", root)
book.put("name", name)
book.put("chapters", chapters)
book.put("currentMediaPath", root + File.separator + currentPath)
book.put("type", type)
book.put("bookmarks", bookmarks)
book.put("useCoverReplacement", useCoverReplacement)
book.put("time", currentTime)
book.put("playbackSpeed", speed.toDouble())
Timber.d("upgrade24 restored book=$book")
val cv = ContentValues()
cv.put("BOOK_JSON", book.toString())
val newBookId = db.insert(newBookTable, SQLiteDatabase.CONFLICT_FAIL, cv)
book.put("id", newBookId)
// move cover file if possible
val coverFile = if (chapterPaths.size == 1) {
val fileName = "." + chapterNames.first() + ".jpg"
File(root, fileName)
} else {
val fileName = "." + (File(root).name) + ".jpg"
File(root, fileName)
}
if (coverFile.exists() && coverFile.canWrite()) {
try {
val externalStoragePath = Environment.getExternalStorageDirectory().absolutePath
val newCoverFile = File(
"$externalStoragePath/Android/data/${context.packageName}",
"$newBookId.jpg"
)
if (!coverFile.parentFile.exists()) {
//noinspection ResultOfMethodCallIgnored
coverFile.parentFile.mkdirs()
}
coverFile.copyTo(newCoverFile)
coverFile.delete()
} catch (e: IOException) {
e.printStackTrace()
}
}
} catch (e: JSONException) {
throw InvalidPropertiesFormatException(e)
}
}
}
}
| lgpl-3.0 | a9a5a48561bd91a0997c438ecb129364 | 33.647727 | 98 | 0.63529 | 4.440291 | false | false | false | false |
facebook/litho | litho-widget-kotlin/src/main/kotlin/com/facebook/litho/kotlin/widget/ExperimentalCardShadow.kt | 1 | 4425 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho.kotlin.widget
import android.content.Context
import com.facebook.litho.MeasureScope
import com.facebook.litho.MountableComponent
import com.facebook.litho.MountableComponentScope
import com.facebook.litho.MountableRenderResult
import com.facebook.litho.SimpleMountable
import com.facebook.litho.Style
import com.facebook.litho.widget.CardShadowDrawable
import com.facebook.rendercore.MeasureResult
/**
* A component that is able to render the card's shadow.
*
* @param shadowStartColor Start color for the shadow.
* @param shadowEndColor End color for the shadow.
* @param cornerRadius Corner radius for the card that shows the shadow.
* @param shadowSize Size of the shadow.
* @param shadowDx The x offset of the shadow.
* @param shadowDy The y offset of the shadow.
*/
class ExperimentalCardShadow(
private val shadowStartColor: Int? = null,
private val shadowEndColor: Int? = null,
private val cornerRadius: Float? = null,
private val shadowSize: Float? = null,
private val shadowDx: Float = CardShadowDrawable.UNDEFINED,
private val shadowDy: Float = CardShadowDrawable.UNDEFINED,
private val hideTopShadow: Boolean = false,
private val hideBottomShadow: Boolean = false,
private val shadowLeftSizeOverride: Float = CardShadowDrawable.UNDEFINED,
private val shadowRightSizeOverride: Float = CardShadowDrawable.UNDEFINED,
private val style: Style? = null
) : MountableComponent() {
override fun MountableComponentScope.render(): MountableRenderResult {
return MountableRenderResult(
CardShadowMountable(
shadowStartColor = shadowStartColor,
shadowEndColor = shadowEndColor,
cornerRadius = cornerRadius,
shadowSize = shadowSize,
shadowDx = shadowDx,
shadowDy = shadowDy,
hideTopShadow = hideTopShadow,
hideBottomShadow = hideBottomShadow,
shadowLeftSizeOverride = shadowLeftSizeOverride,
shadowRightSizeOverride = shadowRightSizeOverride),
style)
}
}
internal class CardShadowMountable(
private val shadowStartColor: Int?,
private val shadowEndColor: Int?,
private val cornerRadius: Float?,
private val shadowSize: Float?,
private val shadowDx: Float,
private val shadowDy: Float,
private val hideTopShadow: Boolean,
private val hideBottomShadow: Boolean,
private val shadowLeftSizeOverride: Float,
private val shadowRightSizeOverride: Float,
) : SimpleMountable<CardShadowDrawable>(RenderType.DRAWABLE) {
override fun createContent(context: Context): CardShadowDrawable = CardShadowDrawable()
override fun mount(c: Context, content: CardShadowDrawable, layoutData: Any?) {
shadowStartColor?.let { content.setShadowStartColor(shadowStartColor) }
shadowEndColor?.let { content.setShadowEndColor(shadowEndColor) }
cornerRadius?.let { content.setCornerRadius(cornerRadius) }
shadowSize?.let { content.setShadowSize(shadowSize) }
content.setHideTopShadow(hideTopShadow)
content.setHideBottomShadow(hideBottomShadow)
content.setShadowLeftSizeOverride(shadowLeftSizeOverride)
content.setShadowRightSizeOverride(shadowRightSizeOverride)
content.setShadowDx(shadowDx)
content.setShadowDy(shadowDy)
}
override fun unmount(c: Context, content: CardShadowDrawable, layoutData: Any?) {
content.setCornerRadius(0f)
content.setShadowSize(0f)
content.setHideTopShadow(false)
content.setHideBottomShadow(false)
content.setShadowLeftSizeOverride(0f)
content.setShadowRightSizeOverride(0f)
content.setShadowDx(0f)
content.setShadowDy(0f)
}
override fun MeasureScope.measure(widthSpec: Int, heightSpec: Int): MeasureResult =
fromSpecs(widthSpec, heightSpec)
}
| apache-2.0 | 042625f975c346bb809ad77c750f9b2e | 38.864865 | 89 | 0.752994 | 4.39424 | false | false | false | false |
anton-okolelov/intellij-rust | src/test/kotlin/org/rust/cargo/runconfig/RunConfigurationTestCase.kt | 2 | 3295 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.runconfig
import com.intellij.execution.configurations.ConfigurationTypeUtil
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.process.*
import com.intellij.execution.runners.ExecutionEnvironmentBuilder
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import org.rust.cargo.RustWithToolchainTestBase
import org.rust.cargo.runconfig.command.CargoCommandConfiguration
import org.rust.cargo.runconfig.command.CargoCommandConfigurationType
import org.rust.fileTree
class RunConfigurationTestCase : RustWithToolchainTestBase() {
fun `test application configuration`() {
fileTree {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
authors = []
""")
dir("src") {
rust("main.rs", """
fn main() {
println!("Hello, world!");
}
""")
}
}.create()
val configuration = createConfiguration()
val result = execute(configuration)
check("Hello, world!" in result.stdout)
}
private fun createConfiguration(): CargoCommandConfiguration {
val configurationType = ConfigurationTypeUtil.findConfigurationType(CargoCommandConfigurationType::class.java)
val factory = configurationType.factory
return factory.createTemplateConfiguration(myModule.project) as CargoCommandConfiguration
}
private fun execute(configuration: RunConfiguration): ProcessOutput {
val executor = DefaultRunExecutor.getRunExecutorInstance()
val state = ExecutionEnvironmentBuilder
.create(executor, configuration)
.build()
.state!!
val result = state.execute(executor, RsRunner())!!
val listener = AnsiAwareCapturingProcessAdapter()
with(result.processHandler) {
addProcessListener(listener)
startNotify()
waitFor()
}
Disposer.dispose(result.executionConsole)
return listener.output
}
}
/**
* Capturing adapter that removes ANSI escape codes from the output
*/
class AnsiAwareCapturingProcessAdapter : ProcessAdapter(), AnsiEscapeDecoder.ColoredTextAcceptor {
val output = ProcessOutput()
private val decoder = object : AnsiEscapeDecoder() {
override fun getCurrentOutputAttributes(outputType: Key<*>) = outputType
}
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) =
decoder.escapeText(event.text, outputType, this)
private fun addToOutput(text: String, outputType: Key<*>) {
if (outputType === ProcessOutputTypes.STDERR) {
output.appendStderr(text)
} else {
output.appendStdout(text)
}
}
override fun processTerminated(event: ProcessEvent) {
output.exitCode = event.exitCode
}
override fun coloredTextAvailable(text: String, attributes: Key<*>) =
addToOutput(text, attributes)
}
| mit | bf8aa36de05e505ce35cd93f847bc172 | 32.622449 | 118 | 0.664947 | 5.36645 | false | true | false | false |
huoguangjin/MultiHighlight | src/main/java/com/github/huoguangjin/multihighlight/config/NamedTextAttr.kt | 1 | 1372 | package com.github.huoguangjin.multihighlight.config
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.util.castSafelyTo
import org.jdom.Element
class NamedTextAttr : TextAttributes {
var name: String
constructor(name: String, ta: TextAttributes) : super() {
this.name = name
copyFrom(ta)
}
constructor(element: Element) : super(element) {
val attribute = element.getAttribute(ATTR_NAME)
name = attribute?.value ?: ""
}
override fun writeExternal(element: Element) {
super.writeExternal(element)
element.setAttribute(ATTR_NAME, name)
}
override fun clone(): NamedTextAttr = NamedTextAttr(name, this)
override fun equals(other: Any?): Boolean {
val o = other.castSafelyTo<NamedTextAttr>() ?: return false
return name == o.name && super.equals(o)
}
override fun hashCode(): Int = 31 * name.hashCode() + super.hashCode()
override fun toString(): String = "NamedTextAttr{" + name + "=" + super.toString() + '}'
companion object {
private const val ATTR_NAME = "name"
@JvmField
val IDE_DEFAULT = NamedTextAttr(
"IDE default",
EditorColorsManager.getInstance().globalScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)
)
}
}
| gpl-3.0 | ebfaaca56d6fa0dbbee6effe0b3bd5fc | 27 | 105 | 0.716472 | 4.107784 | false | false | false | false |
EyeBody/EyeBody | EyeBody2/app/src/main/java/com/example/android/eyebody/management/exercise/ExerciseManagementFragment.kt | 1 | 1798 | package com.example.android.eyebody.management.exercise
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.android.eyebody.R
import com.example.android.eyebody.management.BasePageFragment
/**
* Created by YOON on 2017-11-11
*/
class ExerciseManagementFragment : BasePageFragment() {
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if(isVisibleToUser) {
/* fragment가 visible 해질 때 action을 부여하고 싶은 경우 */
} else {
/* fragment가 visible 하지 않지만 load되어 있는 경우 */
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_management_exercise, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) {
pageNumber = arguments.getInt(ARG_PAGE_NUMBER)
}
}
companion object {
private val ARG_PAGE_NUMBER = "param1"
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param pn PageNumber (Int)
* @return A new instance of fragment ExerciseManagementFragment.
*/
fun newInstance(pn : Int) : ExerciseManagementFragment {
val fragment = ExerciseManagementFragment()
val args = Bundle()
args.putInt(ARG_PAGE_NUMBER, pn)
fragment.arguments = args
return fragment
}
}
}// Required empty public constructor
| mit | ec82c1a7bd5bff24943d0b022a0885f8 | 30.214286 | 117 | 0.657323 | 4.71159 | false | false | false | false |
wuseal/JsonToKotlinClass | src/test/kotlin/extensions/wu/seal/ForceInitDefaultValueWithOriginJsonValueSupportTest.kt | 1 | 1566 | package extensions.wu.seal
import com.winterbe.expekt.should
import org.junit.Before
import org.junit.Test
import wu.seal.jsontokotlin.generateKotlinDataClass
import wu.seal.jsontokotlin.test.TestConfig
class ForceInitDefaultValueWithOriginJsonValueSupportTest {
val json = """{"a":1}"""
val expectResult = """data class Test(
val a: Int = 1 // 1
)"""
var escapedCharacterJson = """{"key": "value with \"quote\""}"""
val escapedCharacterExpectResult = """data class Test(
val key: String = ""${'"'}value with "quote""${'"'}${'"'} // value with "quote"
)"""
val configKey = "wu.seal.force_init_default_value_with_origin_json_value"
@Before
fun setUp() {
TestConfig.setToTestInitState()
}
@Test
fun intercept() {
ForceInitDefaultValueWithOriginJsonValueSupport.getTestHelper().setConfig(configKey, true.toString())
val dataClass =
json.generateKotlinDataClass("Test").applyInterceptor(ForceInitDefaultValueWithOriginJsonValueSupport)
val resultCode = dataClass.getCode()
resultCode.should.be.equal(expectResult)
}
@Test
fun interceptWithEscapeCharacter(){
ForceInitDefaultValueWithOriginJsonValueSupport.getTestHelper().setConfig(configKey, true.toString())
val dataClass =
escapedCharacterJson.generateKotlinDataClass("Test").applyInterceptor(ForceInitDefaultValueWithOriginJsonValueSupport)
val resultCode = dataClass.getCode()
resultCode.should.be.equal(escapedCharacterExpectResult)
}
} | gpl-3.0 | 1b7b9db5ee141f32e30d51d6c5f36039 | 32.340426 | 134 | 0.704981 | 4.578947 | false | true | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/intentions/MoveGuardToMatchArmIntention.kt | 2 | 1609 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsExpr
import org.rust.lang.core.psi.RsIfExpr
import org.rust.lang.core.psi.RsMatchArmGuard
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.ext.parentMatchArm
import org.rust.lang.core.psi.ext.parentOfType
class MoveGuardToMatchArmIntention : RsElementBaseIntentionAction<MoveGuardToMatchArmIntention.Context>() {
override fun getText(): String = "Move guard inside the match arm"
override fun getFamilyName(): String = text
data class Context(
val guard: RsMatchArmGuard,
val armBody: RsExpr
)
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val guard = element.parentOfType<RsMatchArmGuard>() ?: return null
val armBody = guard.parentMatchArm.expr ?: return null
return Context(guard, armBody)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val (guard, oldBody) = ctx
val caretOffsetInGuard = editor.caretModel.offset - guard.textOffset
val psiFactory = RsPsiFactory(project)
var newBody = psiFactory.createIfExpression(guard.expr, oldBody)
newBody = oldBody.replace(newBody) as RsIfExpr
guard.delete()
editor.caretModel.moveToOffset(newBody.textOffset + caretOffsetInGuard)
}
}
| mit | c59011a9b234b5850ce47d20f41850ed | 37.309524 | 107 | 0.737104 | 4.245383 | false | false | false | false |
NordicSemiconductor/Android-nRF-Toolbox | profile_cgms/src/main/java/no/nordicsemi/android/cgms/viewmodel/CGMViewModel.kt | 1 | 4663 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.cgms.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import no.nordicsemi.android.analytics.AppAnalytics
import no.nordicsemi.android.analytics.Profile
import no.nordicsemi.android.analytics.ProfileConnectedEvent
import no.nordicsemi.android.cgms.data.CGMS_SERVICE_UUID
import no.nordicsemi.android.cgms.data.CGMServiceCommand
import no.nordicsemi.android.cgms.repository.CGMRepository
import no.nordicsemi.android.cgms.view.*
import no.nordicsemi.android.navigation.*
import no.nordicsemi.android.service.ConnectedResult
import no.nordicsemi.android.utils.exhaustive
import no.nordicsemi.android.utils.getDevice
import no.nordicsemi.ui.scanner.ScannerDestinationId
import javax.inject.Inject
@HiltViewModel
internal class CGMViewModel @Inject constructor(
private val repository: CGMRepository,
private val navigationManager: NavigationManager,
private val analytics: AppAnalytics
) : ViewModel() {
private val _state = MutableStateFlow<CGMViewState>(NoDeviceState)
val state = _state.asStateFlow()
init {
viewModelScope.launch {
if (repository.isRunning.firstOrNull() == false) {
requestBluetoothDevice()
}
}
repository.data.onEach {
_state.value = WorkingState(it)
(it as? ConnectedResult)?.let {
analytics.logEvent(ProfileConnectedEvent(Profile.CGMS))
}
}.launchIn(viewModelScope)
}
fun onEvent(event: CGMViewEvent) {
when (event) {
DisconnectEvent -> disconnect()
is OnWorkingModeSelected -> onCommandReceived(event.workingMode)
NavigateUp -> navigationManager.navigateUp()
OpenLoggerEvent -> repository.openLogger()
}.exhaustive
}
private fun requestBluetoothDevice() {
navigationManager.navigateTo(ScannerDestinationId, UUIDArgument(CGMS_SERVICE_UUID))
navigationManager.recentResult.onEach {
if (it.destinationId == ScannerDestinationId) {
handleArgs(it)
}
}.launchIn(viewModelScope)
}
private fun handleArgs(args: DestinationResult) {
when (args) {
is CancelDestinationResult -> navigationManager.navigateUp()
is SuccessDestinationResult -> repository.launch(args.getDevice())
}.exhaustive
}
private fun onCommandReceived(workingMode: CGMServiceCommand) {
when (workingMode) {
CGMServiceCommand.REQUEST_ALL_RECORDS -> repository.requestAllRecords()
CGMServiceCommand.REQUEST_LAST_RECORD -> repository.requestLastRecord()
CGMServiceCommand.REQUEST_FIRST_RECORD -> repository.requestFirstRecord()
CGMServiceCommand.DISCONNECT -> disconnect()
}.exhaustive
}
private fun disconnect() {
repository.release()
navigationManager.navigateUp()
}
}
| bsd-3-clause | c7dcdbe565efd827925cfe60954c3c77 | 38.516949 | 91 | 0.729144 | 4.837137 | false | false | false | false |
outadoc/Twistoast-android | twistoast/src/main/kotlin/fr/outadev/twistoast/extensions/ContextExtensions.kt | 1 | 1601 | /*
* Twistoast - ContextExtensions.kt
* Copyright (C) 2013-2016 Baptiste Candellier
*
* Twistoast 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.
*
* Twistoast 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 fr.outadev.twistoast.extensions
import android.content.Context
import android.support.annotation.AttrRes
import android.util.TypedValue
import fr.outadev.twistoast.R
/**
* Miscellaneous methods used to manipulate colours.
*
* @author outadoc
*/
fun Context.getColorPrimary(): Int = getColorFromAttribute(this, R.attr.colorPrimary)
fun Context.getColorPrimaryDark(): Int = getColorFromAttribute(this, R.attr.colorPrimaryDark)
fun Context.getColorAccent(): Int = getColorFromAttribute(this, R.attr.colorAccent)
private fun getColorFromAttribute(context: Context, @AttrRes attr: Int): Int {
val a = TypedValue()
context.theme.resolveAttribute(attr, a, true)
if (a.type >= TypedValue.TYPE_FIRST_COLOR_INT && a.type <= TypedValue.TYPE_LAST_COLOR_INT) {
return a.data
}
throw RuntimeException("Attribute is not a color.")
}
| gpl-3.0 | 2d4c8e4169325b1e203531f884a4aabb | 32.354167 | 96 | 0.748907 | 3.992519 | false | false | false | false |
Yubyf/QuoteLock | app/src/main/java/com/crossbowffs/quotelock/utils/Md5Utils.kt | 1 | 1613 | @file:JvmName("Md5Utils")
package com.crossbowffs.quotelock.utils
import androidx.annotation.Size
import java.io.File
import java.io.FileInputStream
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
@Size(16)
@Throws(Exception::class)
private fun File.md5(): ByteArray {
FileInputStream(this).use {
val buffer = ByteArray(1024)
val complete = MessageDigest.getInstance("MD5")
var numRead: Int
do {
numRead = it.read(buffer)
if (numRead > 0) {
complete.update(buffer, 0, numRead)
}
} while (numRead != -1)
return complete.digest()
}
}
private fun ByteArray.hexString(): String {
val result = StringBuilder()
this.forEach { value ->
result.append(Integer.toHexString(0x000000FF and value.toInt() or -0x100).substring(6))
}
return result.toString()
}
@Throws(Exception::class)
fun File.md5String(): String = md5().hexString()
fun String.md5(): String {
try {
// Create MD5 Hash
val digest = MessageDigest
.getInstance("MD5")
digest.update(toByteArray())
val messageDigest = digest.digest()
// Create Hex String
val hexString = StringBuilder()
messageDigest.forEach {
var h = Integer.toHexString(0xFF and it.toInt())
while (h.length < 2) {
h = "0$h"
}
hexString.append(h)
}
return hexString.toString()
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
}
return ""
} | mit | bad0728bfadeff6406d369a8da8c8b2c | 25.459016 | 95 | 0.605704 | 4.178756 | false | false | false | false |
czyzby/gdx-setup | src/main/kotlin/com/github/czyzby/setup/views/platforms.kt | 1 | 2370 | package com.github.czyzby.setup.views
import com.badlogic.gdx.scenes.scene2d.ui.Button
import com.badlogic.gdx.scenes.scene2d.utils.Disableable
import com.badlogic.gdx.utils.ObjectSet
import com.github.czyzby.autumn.annotation.Processor
import com.github.czyzby.autumn.context.Context
import com.github.czyzby.autumn.context.ContextDestroyer
import com.github.czyzby.autumn.context.ContextInitializer
import com.github.czyzby.autumn.processor.AbstractAnnotationProcessor
import com.github.czyzby.lml.annotation.LmlActor
import com.github.czyzby.setup.data.platforms.Core
import com.github.czyzby.setup.data.platforms.Platform
/**
* Handles platform-related input.
* @author MJ
*/
@Processor
class PlatformsData : AbstractAnnotationProcessor<GdxPlatform>() {
val platforms = mutableMapOf<String, Platform>()
@LmlActor("androidSdk") private lateinit var androidSdk: Disableable
@LmlActor("androidSdkButton") private lateinit var androidSdkButton: Disableable
@LmlActor("\$platforms") private lateinit var platformButtons: ObjectSet<Button>
fun toggleAndroidPlatform(active: Boolean) {
androidSdk.isDisabled = !active
androidSdkButton.isDisabled = !active
}
fun toggleClientPlatforms() = platformButtons.filter { platforms[it.name]!!.isGraphical }
.forEach { it.isChecked = !it.isChecked }
fun togglePlatforms() = platformButtons.filter { it.name != Core.ID }
.forEach { it.isChecked = !it.isChecked }
operator fun get(platformId: String): Platform = platforms[platformId]!!
fun getSelectedPlatforms(): Map<String, Platform> =
platformButtons.filter { it.isChecked }.map { platforms[it.name]!! }.associateBy { it.id }
// Automatic scanning of platforms:
override fun getSupportedAnnotationType(): Class<GdxPlatform> = GdxPlatform::class.java
override fun isSupportingTypes(): Boolean = true
override fun processType(type: Class<*>, annotation: GdxPlatform, component: Any, context: Context,
initializer: ContextInitializer, contextDestroyer: ContextDestroyer) {
val platform = component as Platform
platforms[platform.id] = platform
}
}
/**
* Should annotate all LibGDX platforms.
* @author MJ
*/
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class GdxPlatform
| unlicense | 1971190fdfb0ea929ef82598397e8ad4 | 37.852459 | 103 | 0.746835 | 4.31694 | false | false | false | false |
emilybache/Tennis-Refactoring-Kata | kotlin/src/main/kotlin/TennisGame4.kt | 1 | 3351 | class TennisGame4(val server: String, val receiver: String) : TennisGame {
internal var serverScore = 0
internal var receiverScore = 0
override fun wonPoint(playerName: String) {
if (server == playerName) serverScore += 1 else receiverScore += 1
}
override fun getScore(): String {
val result: TennisResult = Deuce(
this, GameServer(
this, GameReceiver(
this, AdvantageServer(
this, AdvantageReceiver(
this, DefaultResult(this)
)
)
)
)
).result
return result.format()
}
internal fun receiverHasAdvantage(): Boolean {
return receiverScore >= 4 && receiverScore - serverScore == 1
}
internal fun serverHasAdvantage(): Boolean {
return serverScore >= 4 && serverScore - receiverScore == 1
}
internal fun receiverHasWon(): Boolean {
return receiverScore >= 4 && receiverScore - serverScore >= 2
}
internal fun serverHasWon(): Boolean {
return serverScore >= 4 && serverScore - receiverScore >= 2
}
internal fun isDeuce(): Boolean {
return serverScore >= 3 && receiverScore >= 3 && serverScore == receiverScore
}
}
internal class TennisResult(var serverScore: String, var receiverScore: String) {
fun format(): String {
if ("" == receiverScore) return serverScore
return if (serverScore == receiverScore) "$serverScore-All" else serverScore + "-" + receiverScore
}
}
internal interface ResultProvider {
val result: TennisResult
}
internal class Deuce(private val game: TennisGame4, private val nextResult: ResultProvider) : ResultProvider {
override val result: TennisResult
get() = if (game.isDeuce()) TennisResult("Deuce", "") else nextResult.result
}
internal class GameServer(private val game: TennisGame4, private val nextResult: ResultProvider) : ResultProvider {
override val result: TennisResult
get() = if (game.serverHasWon()) TennisResult("Win for " + game.server, "") else nextResult.result
}
internal class GameReceiver(private val game: TennisGame4, private val nextResult: ResultProvider) : ResultProvider {
override val result: TennisResult
get() = if (game.receiverHasWon()) TennisResult("Win for " + game.receiver, "") else nextResult.result
}
internal class AdvantageServer(private val game: TennisGame4, private val nextResult: ResultProvider) : ResultProvider {
override val result: TennisResult
get() = if (game.serverHasAdvantage()) TennisResult("Advantage " + game.server, "") else nextResult.result
}
internal class AdvantageReceiver(private val game: TennisGame4, private val nextResult: ResultProvider) :
ResultProvider {
override val result: TennisResult
get() = if (game.receiverHasAdvantage()) TennisResult("Advantage " + game.receiver, "") else nextResult.result
}
internal class DefaultResult(private val game: TennisGame4) : ResultProvider {
override val result: TennisResult
get() = TennisResult(
scores[game.serverScore], scores[game.receiverScore]
)
internal companion object {
private val scores = arrayOf("Love", "Fifteen", "Thirty", "Forty")
}
}
| mit | 803f718df1cf049d684dba148e40b941 | 33.193878 | 120 | 0.655924 | 4.323871 | false | false | false | false |
FirebaseExtended/auth-without-play-services | app/src/main/java/com/google/firebase/nongmsauth/FirebaseRestAuthUser.kt | 1 | 1149 | /**
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.nongmsauth
import com.google.firebase.nongmsauth.utils.IdTokenParser
class FirebaseRestAuthUser(
val idToken: String,
val refreshToken: String
) {
val userId: String
val expirationTime: Long
init {
val claims = IdTokenParser.parseIdToken(this.idToken)
this.userId = claims["user_id"].toString()
this.expirationTime = claims["exp"].toString().toLong()
}
override fun toString(): String {
return "RestAuthUser(userId=$userId, expiresAt=${expirationTime})"
}
}
| apache-2.0 | 55390f226e13745746ffbe37de5fc27b | 28.461538 | 75 | 0.713664 | 4.148014 | false | false | false | false |
Mithrandir21/Duopoints | app/src/main/java/com/duopoints/android/utils/UiUtils.kt | 1 | 3058 | package com.duopoints.android.utils
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.support.annotation.AttrRes
import android.support.annotation.ColorRes
import android.support.annotation.DrawableRes
import android.support.v4.content.ContextCompat
import android.support.v4.graphics.drawable.DrawableCompat
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.MenuItem
import com.duopoints.android.App
import com.duopoints.android.R
import com.duopoints.android.rest.models.enums.user.UserGender
object UiUtils {
/**
* This method converts dp unit to equivalent pixels, depending on device density.
*
* @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
*
* @return A float value to represent px equivalent to dp depending on device density
*/
fun convertDpToPixel(dp: Float): Float {
val resources = App.get().resources
val metrics = resources.displayMetrics
return dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}
/**
* This method converts device specific pixels to density independent pixels.
*
* @param px A value in px (pixels) unit. Which we need to convert into db
*
* @return A float value to represent dp equivalent to px value
*/
fun convertPixelsToDp(px: Float): Float {
val resources = App.get().resources
val metrics = resources.displayMetrics
return px / (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}
/**
* Get uri to drawable
*
* @param context - context
* @param drawableId - drawable res id
*
* @return Uri to any give drawable.
*/
fun getUriToDrawable(context: Context, @DrawableRes drawableId: Int): Uri {
return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://" + context.resources.getResourcePackageName(drawableId)
+ '/'.toString() + context.resources.getResourceTypeName(drawableId)
+ '/'.toString() + context.resources.getResourceEntryName(drawableId))
}
/**
* @param context
* @param item
* @param color
*/
fun tintMenuIcon(context: Context, item: MenuItem, @ColorRes color: Int) {
val normalDrawable = item.icon
val wrapDrawable = DrawableCompat.wrap(normalDrawable)
DrawableCompat.setTint(wrapDrawable, ContextCompat.getColor(context, color))
item.icon = wrapDrawable
}
@DrawableRes
fun getStockUserAvatar(gender: UserGender): Int = when (gender) {
UserGender.M -> R.drawable.user_male
UserGender.F -> R.drawable.user_female
else -> R.drawable.star_full
}
@ColorRes
fun getResId(context: Context, @AttrRes attributeId: Int): Int {
val typedValue = TypedValue()
context.theme.resolveAttribute(attributeId, typedValue, true)
return typedValue.resourceId
}
}
| gpl-3.0 | f1addae69e2122c328149ca1f9b2c98f | 32.977778 | 102 | 0.687704 | 4.543834 | false | false | false | false |
Geobert/radis | app/src/main/kotlin/fr/geobert/radis/ui/editor/AccountEditFragment.kt | 1 | 10757 | package fr.geobert.radis.ui.editor
import android.content.Context
import android.database.Cursor
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.LoaderManager
import android.support.v4.content.Loader
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.Spinner
import fr.geobert.radis.R
import fr.geobert.radis.data.Account
import fr.geobert.radis.db.AccountTable
import fr.geobert.radis.tools.CorrectCommaWatcher
import fr.geobert.radis.tools.ProjectionDateController
import fr.geobert.radis.tools.extractSumFromStr
import fr.geobert.radis.tools.formatSum
import fr.geobert.radis.tools.getGroupSeparator
import fr.geobert.radis.tools.getSumSeparator
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.properties.Delegates
public class AccountEditFragment : Fragment(), LoaderManager.LoaderCallbacks<Cursor> {
private var edit_account_name: EditText by Delegates.notNull()
private var edit_account_start_sum: EditText by Delegates.notNull()
private var edit_account_desc: EditText by Delegates.notNull()
private var currency_spinner: Spinner by Delegates.notNull()
private var custom_currency: EditText by Delegates.notNull()
private val mProjectionController by lazy(LazyThreadSafetyMode.NONE) { ProjectionDateController(activity) }
private var customCurrencyIdx = -1
private var mOnRestore: Boolean = false
var mAccount: Account by Delegates.notNull()
private set
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val c = inflater.inflate(R.layout.account_editor, container, false)
edit_account_name = c.findViewById(R.id.edit_account_name) as EditText
edit_account_start_sum = c.findViewById(R.id.edit_account_start_sum) as EditText
edit_account_desc = c.findViewById(R.id.edit_account_desc) as EditText
currency_spinner = c.findViewById(R.id.currency_spinner) as Spinner
custom_currency = c.findViewById(R.id.custom_currency) as EditText
return c
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mProjectionController // trigger lazy access
val act = activity as AccountEditor
if (act.isNewAccount()) {
mAccount = Account()
}
val w = CorrectCommaWatcher(getSumSeparator(), getGroupSeparator(), edit_account_start_sum)
w.setAutoNegate(false)
edit_account_start_sum.addTextChangedListener(w)
edit_account_start_sum.onFocusChangeListener = object : View.OnFocusChangeListener {
override fun onFocusChange(v: View, hasFocus: Boolean) {
if (hasFocus) {
(v as EditText).selectAll()
}
}
}
fillCurrencySpinner()
if (savedInstanceState != null)
onRestoreInstanceState(savedInstanceState)
}
private fun fillCurrencySpinner() {
val mCurrAdapter = ArrayAdapter.createFromResource(activity, R.array.all_currencies, android.R.layout.simple_spinner_item)
mCurrAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
currency_spinner.adapter = mCurrAdapter
currency_spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(arg0: AdapterView<*>?, arg1: View?, pos: Int, id: Long) {
custom_currency.visibility = if (pos == getCustomCurrencyIdx(activity)) View.VISIBLE else View.GONE
}
override fun onNothingSelected(arg0: AdapterView<*>?) {
}
}
}
// check the form and fill mAccount
fun isFormValid(errMsg: StringBuilder): Boolean {
val name = edit_account_name.text.toString()
var res = true
if (name.length == 0) {
errMsg.append(R.string.empty_account_name)
res = false
}
if (edit_account_start_sum.text.length == 0) {
edit_account_start_sum.setText("0")
}
// check if currency is correct
if (currency_spinner.selectedItemPosition == getCustomCurrencyIdx(activity)) {
val currency = custom_currency.text.toString().trim().toUpperCase()
try {
Currency.getInstance(currency)
} catch (e: IllegalArgumentException) {
if (errMsg.length > 0)
errMsg.append("\n")
errMsg.append(getString(R.string.bad_format_for_currency))
res = false
}
}
// check projection date format
if (mProjectionController.mProjectionDate.visibility == View.VISIBLE) {
// && mProjectionController.getDate().trim().length() == 0) {
try {
val format: SimpleDateFormat =
if (mProjectionController.getMode() == AccountTable.PROJECTION_DAY_OF_NEXT_MONTH) {
SimpleDateFormat("dd")
} else {
SimpleDateFormat("dd/MM/yyyy")
}
val d = format.parse(mProjectionController.getDate().trim())
mProjectionController.mProjectionDate.setText(format.format(d))
} catch (e: ParseException) {
e.printStackTrace()
if (errMsg.length > 0)
errMsg.append("\n")
errMsg.append(getString(R.string.bad_format_for_date))
res = false
}
}
return res
}
fun populateFields(account: Account) {
edit_account_name.setText(account.name)
edit_account_desc.setText(account.description)
edit_account_start_sum.setText((account.startSum / 100.0).formatSum())
var currencyStr = account.currency
if (currencyStr.length == 0) {
currencyStr = Currency.getInstance(Locale.getDefault()).currencyCode
}
initCurrencySpinner(currencyStr)
mProjectionController.populateFields(account)
}
private fun getCustomCurrencyIdx(ctx: Context): Int {
if (customCurrencyIdx == -1) {
val res = ctx.resources
val allCurrencies = res.getStringArray(R.array.all_currencies)
customCurrencyIdx = allCurrencies.size - 1
}
return customCurrencyIdx
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("name", edit_account_name.text.toString())
outState.putString("startSum", edit_account_start_sum.text.toString())
outState.putInt("currency", currency_spinner.selectedItemPosition)
val customCurIdx = getCustomCurrencyIdx(activity)
outState.putInt("customCurrencyIdx", customCurIdx)
if (currency_spinner.selectedItemPosition == customCurIdx) {
outState.putString("customCurrency", custom_currency.text.toString())
}
outState.putString("desc", edit_account_desc.text.toString())
mProjectionController.onSaveInstanceState(outState)
outState.putParcelable("mAccount", mAccount)
mOnRestore = true
}
private fun onRestoreInstanceState(state: Bundle) {
edit_account_name.setText(state.getString("name"))
edit_account_start_sum.setText(state.getString("startSum"))
currency_spinner.setSelection(state.getInt("currency"))
customCurrencyIdx = state.getInt("customCurrencyIdx")
if (currency_spinner.selectedItemPosition == getCustomCurrencyIdx(activity)) {
custom_currency.setText(state.getString("customCurrency"))
custom_currency.isEnabled = true
} else {
custom_currency.isEnabled = false
}
edit_account_desc.setText(state.getString("desc"))
mProjectionController.onRestoreInstanceState(state)
mAccount = state.getParcelable("mAccount")
mOnRestore = true
}
override fun onResume() {
super.onResume()
val act = activity as AccountEditor
if (!mOnRestore && !act.isNewAccount()) {
act.supportLoaderManager.initLoader<Cursor>(AccountEditor.GET_ACCOUNT, Bundle(), this)
} else {
mOnRestore = false
}
if ((activity as AccountEditor).isNewAccount()) {
initCurrencySpinner()
}
}
fun initCurrencySpinner() {
try {
initCurrencySpinner(Currency.getInstance(Locale.getDefault()).currencyCode)
} catch (ex: IllegalArgumentException) {
initCurrencySpinner(Currency.getInstance(Locale("fr", "FR")).currencyCode)
}
}
protected fun initCurrencySpinner(currencyStr: String) {
val allCurrencies = resources.getStringArray(R.array.all_currencies)
val pos = Arrays.binarySearch(allCurrencies, currencyStr)
if (pos >= 0) {
currency_spinner.setSelection(pos)
custom_currency.isEnabled = false
} else {
currency_spinner.setSelection(getCustomCurrencyIdx(activity))
custom_currency.isEnabled = true
}
}
fun fillAccount(): Account {
mAccount.name = edit_account_name.text.toString().trim()
mAccount.description = edit_account_desc.text.toString().trim()
try {
mAccount.startSum = edit_account_start_sum.text.toString().extractSumFromStr()
mAccount.currency = if (currency_spinner.selectedItemPosition == getCustomCurrencyIdx(activity)) {
custom_currency.text.toString().trim().toUpperCase()
} else {
currency_spinner.selectedItem.toString()
}
mAccount.projMode = mProjectionController.getMode()
mAccount.projDate = mProjectionController.getDate()
} catch (e: ParseException) {
e.printStackTrace()
}
return mAccount
}
override fun onCreateLoader(id: Int, args: Bundle): Loader<Cursor> {
val act = activity as AccountEditor
return AccountTable.getAccountLoader(act, act.mRowId)
}
override fun onLoadFinished(arg0: Loader<Cursor>, data: Cursor) {
if (data.moveToFirst()) {
AccountTable.initProjectionDate(data)
mAccount = Account(data)
populateFields(mAccount)
}
}
override fun onLoaderReset(arg0: Loader<Cursor>) {
}
}
| gpl-2.0 | 0b3b3490474ee0e06929dba1fa40f2bc | 39.592453 | 130 | 0.651762 | 4.740855 | false | false | false | false |
maxplanck76er/vertx-kafka-client | src/main/kotlin/io/vertx/kotlin/kafka/client/common/PartitionInfo.kt | 1 | 1415 | package io.vertx.kotlin.kafka.client.common
import io.vertx.kafka.client.common.PartitionInfo
import io.vertx.kafka.client.common.Node
/**
* A function providing a DSL for building [io.vertx.kafka.client.common.PartitionInfo] objects.
*
* Information about a specific Kafka topic partition
*
* @param inSyncReplicas Set the subset of the replicas that are in sync
* @param leader Set the node id of the node currently acting as a leader
* @param partition Set the partition id
* @param replicas Set the complete set of replicas for this partition
* @param topic Set the topic name
*
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.kafka.client.common.PartitionInfo original] using Vert.x codegen.
*/
fun PartitionInfo(
inSyncReplicas: Iterable<io.vertx.kafka.client.common.Node>? = null,
leader: io.vertx.kafka.client.common.Node? = null,
partition: Int? = null,
replicas: Iterable<io.vertx.kafka.client.common.Node>? = null,
topic: String? = null): PartitionInfo = io.vertx.kafka.client.common.PartitionInfo().apply {
if (inSyncReplicas != null) {
this.setInSyncReplicas(inSyncReplicas.toList())
}
if (leader != null) {
this.setLeader(leader)
}
if (partition != null) {
this.setPartition(partition)
}
if (replicas != null) {
this.setReplicas(replicas.toList())
}
if (topic != null) {
this.setTopic(topic)
}
}
| apache-2.0 | 37e808b742cf0b88a4e3d3029aed00ea | 31.906977 | 140 | 0.720848 | 3.528678 | false | false | false | false |
NextFaze/dev-fun | devfun/src/main/java/com/nextfaze/devfun/invoke/Extensions.kt | 1 | 7714 | /**
* Various extension functions to assist with function invocation.
*
* __These are somewhat internal/experimental.__
*/
package com.nextfaze.devfun.invoke
import com.nextfaze.devfun.core.DevFun
import com.nextfaze.devfun.core.devFun
import com.nextfaze.devfun.function.FunctionArgs
import com.nextfaze.devfun.function.FunctionDefinition
import com.nextfaze.devfun.function.FunctionItem
import com.nextfaze.devfun.inject.InstanceProvider
import com.nextfaze.devfun.internal.reflect.*
import java.lang.reflect.Method
import kotlin.reflect.KClass
/**
* Get the receiver class for this function definition.
*
* @see FunctionItem.receiverClass
* @see Method.receiverClass
* @see FunctionDefinition.receiverClassForInvocation
*/
inline val FunctionDefinition.receiverClass: KClass<*> get() = method.declaringClass.kotlin
/**
* Get the receiver class for this function definition if you intend to invoke it. That is, it will return `null` if the type isn't needed.
*
* @see FunctionDefinition.receiverClass
* @see FunctionItem.receiverClassForInvocation
*/
inline val FunctionDefinition.receiverClassForInvocation: KClass<*>?
get() = when {
method.isProperty -> receiverClass
method.isStatic -> null
else -> receiverClass
}
/**
* Get the receiver instance for this function definition to be used for invocation.
*
* @see FunctionItem.receiverInstance
* @see Method.receiverInstance
*/
fun FunctionDefinition.receiverInstance(instanceProvider: InstanceProvider = devFun.instanceProviders) =
receiverClassForInvocation?.let { instanceProvider[it] }
/**
* Get the parameter instances for this function definition for invocation.
*
* @see FunctionItem.parameterInstances
* @see DevFun.instanceProviders
*/
fun FunctionDefinition.parameterInstances(instanceProvider: InstanceProvider = devFun.instanceProviders, args: FunctionArgs) =
method.parameterTypes.mapIndexed { index: Int, clazz: Class<*> ->
args.getNonNullOrElse(index) { instanceProvider[clazz.kotlin] }
}
/**
* Get the receiver class for this function item.
*
* @see FunctionDefinition.receiverClass
* @see Method.receiverClass
* @see FunctionItem.receiverClassForInvocation
*/
inline val FunctionItem.receiverClass get() = function.receiverClass
/**
* Get the receiver class for this function item if you intend to invoke it. That is, it will return `null` if the type isn't needed.
*
* @see FunctionItem.receiverClass
* @see FunctionDefinition.receiverClassForInvocation
*/
inline val FunctionItem.receiverClassForInvocation: KClass<*>? get() = function.receiverClassForInvocation
/**
* Get the receiver instance for this function item to be used for invocation.
*
* @see FunctionDefinition.receiverInstance
* @see Method.receiverInstance
*/
fun FunctionItem.receiverInstance(instanceProvider: InstanceProvider = devFun.instanceProviders) =
receiverClassForInvocation?.let { instanceProvider[it] }
/**
* Get the parameter instances for this function item for invocation.
*
* @see FunctionDefinition.parameterInstances
* @see DevFun.instanceProviders
*/
fun FunctionItem.parameterInstances(instanceProvider: InstanceProvider = devFun.instanceProviders) =
function.method.parameterTypes.mapIndexed { index: Int, clazz: Class<*> ->
args.getNonNullOrElse(index) { instanceProvider[clazz.kotlin] }
}
/**
* Get the receiver class for this method.
*
* @see FunctionDefinition.receiverClass
* @see FunctionItem.receiverClass
* @see Method.receiverClassForInvocation
*/
inline val Method.receiverClass: KClass<*> get() = declaringClass.kotlin
private val Annotation.getKind: Annotation.() -> Int by lazy {
val method = Class.forName("kotlin.Metadata").getDeclaredMethod("k")
return@lazy { annotation: Annotation -> method.invoke(annotation) as Int }
}
private val Annotation.isKtFile get() = getKind() == 2
private val ktFileClassCache = mutableMapOf<KClass<*>, Boolean>()
private val Method.isReceiverClassKtFile
get() = ktFileClassCache.getOrPut(receiverClass) {
declaringClass.annotations.firstOrNull { it.annotationClass.toString().endsWith("Metadata") }
?.isKtFile == true
}
/**
* Get the receiver class for this function definition if you intend to invoke it. That is, it will return `null` if the type isn't needed.
*
* @see Method.receiverClass
* @see FunctionDefinition.receiverClassForInvocation
* @see FunctionItem.receiverClassForInvocation
*/
inline val Method.receiverClassForInvocation: KClass<*>?
get() {
// not ideal but cannot perform reflection on top-level entities: UnsupportedOperationException
if (isProperty && receiverClass.simpleName!!.endsWith("Kt")) {
@Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE")
if (isReceiverClassKtFile) return null
}
return when {
isProperty -> receiverClass
isStatic -> null
else -> receiverClass
}
}
/**
* Get the receiver instance for this method to be used for invocation.
*
* @see FunctionDefinition.receiverInstance
* @see FunctionItem.receiverInstance
*/
fun Method.receiverInstance(instanceProvider: InstanceProvider = devFun.instanceProviders) =
receiverClassForInvocation?.let { instanceProvider[it] }
/**
* Get the parameter instances for this method for invocation.
*
* Be aware; this is intended for working with the method directly, a `null` value means no arguments.
*
* The [FunctionItem.invoke] and [FunctionDefinition.invoke] handle 0 or more arguments automatically - i.e. they return an empty list to
* signify no arguments. However when invoking using [Method] directly, passing an empty list/array will be seen as an argument instead.
*
* Thus a return of `null` from here means no arguments, which requires calling `method.invoke(receiver)` rather than `method.invoke(receiver, args)`.
*
* If you just want to invoke the method then use the [doInvoke] extension function.
*
* @param instanceProvider The instance provider to use for parameters instances. _(default=`devFun.instanceProviders`)_
* @param suppliedArgs User-provided arguments (source-defined order). Elements that are `null` or out of bounds will fallback to [instanceProvider].
*
* @see FunctionDefinition.parameterInstances
* @see FunctionItem.parameterInstances
*/
fun Method.parameterInstances(
instanceProvider: InstanceProvider = devFun.instanceProviders,
suppliedArgs: FunctionArgs = null
): FunctionArgs =
parameterTypes.takeIf { it.isNotEmpty() }?.mapIndexed { index: Int, clazz: Class<*> ->
suppliedArgs.getNonNullOrElse(index) { instanceProvider[clazz.kotlin] }
}
private inline fun <reified T : Any?> List<Any?>?.getNonNullOrElse(i: Int, defaultValue: (Int) -> T) =
this?.getOrElse(i, defaultValue).takeUnless { it === Unit } as? T ?: defaultValue(i)
/**
* Invokes a Method using DevFun to source instances.
*
* Automatically handles static and args etc.
*
* @param instanceProvider The instance provider to use for parameters instances. _(default=`devFun.instanceProviders`)_
* @param suppliedArgs User-provided arguments (source-defined order). Elements that are `null` or out of bounds will fallback to [instanceProvider].
*
* @see Method.receiverInstance
* @see Method.parameterInstances
*/
fun Method.doInvoke(instanceProvider: InstanceProvider = devFun.instanceProviders, suppliedArgs: FunctionArgs = null): Any? {
val args = parameterInstances(instanceProvider, suppliedArgs)
return when (args) {
null -> invoke(receiverInstance(instanceProvider))
else -> invoke(receiverInstance(instanceProvider), *args.toTypedArray())
}
}
| apache-2.0 | 47682509b662edb91c41f14646b3e5c4 | 37.959596 | 150 | 0.749157 | 4.402968 | false | false | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/common/WakeOnLanTask.kt | 1 | 6001 | package org.tvheadend.tvhclient.ui.common
import android.content.Context
import androidx.lifecycle.LifecycleCoroutineScope
import org.tvheadend.data.entity.Connection
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.util.extensions.executeAsyncTask
import org.tvheadend.tvhclient.util.extensions.sendSnackbarMessage
import timber.log.Timber
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.net.URI
import java.util.regex.Pattern
class WakeOnLanTask(lifecycleScope: LifecycleCoroutineScope, context: Context, private val connection: Connection) {
private var sendWakeOnLanPacket = SendWakeOnLanPacket(connection)
init {
lifecycleScope.executeAsyncTask(onPreExecute = {
// ... runs in Main Thread
Timber.d("onPreExecute")
}, doInBackground = {
Timber.d("doInBackground")
val status: Int = sendWakeOnLanPacket.prepareAndSend()
status // send data to "onPostExecute"
}, onPostExecute = {
// runs in Main Thread
Timber.d("onPostExecute")
// ... here "it" is the data returned from "doInBackground"
val message: String
when (it) {
WOL_SEND -> {
Timber.d("Successfully sent WOL packet to ${connection.wolMacAddress}:${connection.port}")
message = context.getString(R.string.wol_send, "${connection.wolMacAddress}:${connection.port}")
}
WOL_SEND_BROADCAST -> {
Timber.d("Successfully sent WOL packet as a broadcast to ${connection.wolMacAddress}")
message = context.getString(R.string.wol_send_broadcast, connection.wolMacAddress)
}
WOL_INVALID_MAC -> {
Timber.d("Can't send WOL packet, the MAC-address is not valid")
message = context.getString(R.string.wol_address_invalid)
}
else -> {
Timber.d("Error sending WOL packet to ${connection.wolMacAddress}:${connection.port}")
message = context.getString(R.string.wol_error, "${connection.wolMacAddress}:${connection.port}", sendWakeOnLanPacket.exception?.localizedMessage)
}
}
context.sendSnackbarMessage(message)
})
}
companion object {
const val WOL_SEND = 0
const val WOL_SEND_BROADCAST = 1
const val WOL_INVALID_MAC = 2
const val WOL_ERROR = 3
}
}
class SendWakeOnLanPacket(val connection: Connection) {
var exception: Exception? = null
fun prepareAndSend(): Int {
// ... runs in Worker(Background) Thread
// Exit if the MAC address is not ok, this should never happen because
// it is already validated in the settings
if (!validateMacAddress(connection.wolMacAddress)) {
return WakeOnLanTask.WOL_INVALID_MAC
} else {
// Get the MAC address parts from the string
val macBytes = getMacBytes(connection.wolMacAddress ?: "")
// Assemble the byte array that the WOL consists of
val bytes = ByteArray(6 + 16 * macBytes.size)
for (i in 0..5) {
bytes[i] = 0xff.toByte()
}
// Copy the elements from macBytes to i
var i = 6
while (i < bytes.size) {
System.arraycopy(macBytes, 0, bytes, i, macBytes.size)
i += macBytes.size
}
try {
val uri = URI(connection.serverUrl)
val address: InetAddress
if (!connection.isWolUseBroadcast) {
address = InetAddress.getByName(uri.host)
Timber.d("Sending WOL packet to $address")
} else {
// Replace the last number by 255 to send the packet as a broadcast
val ipAddress = InetAddress.getByName(uri.host).address
ipAddress[3] = 255.toByte()
address = InetAddress.getByAddress(ipAddress)
Timber.d("Sending WOL packet as broadcast to $address")
}
val packet = DatagramPacket(bytes, bytes.size, address, connection.wolPort)
val socket = DatagramSocket()
socket.send(packet)
socket.close()
return if (!connection.isWolUseBroadcast) {
WakeOnLanTask.WOL_SEND
} else {
WakeOnLanTask.WOL_SEND_BROADCAST
}
} catch (e: Exception) {
this.exception = e
return WakeOnLanTask.WOL_ERROR
}
}
}
/**
* Checks if the given MAC address is correct.
*
* @param macAddress The MAC address that shall be validated
* @return True if the MAC address is correct, false otherwise
*/
private fun validateMacAddress(macAddress: String?): Boolean {
if (macAddress == null) {
return false
}
// Check if the MAC address is valid
val pattern = Pattern.compile("([0-9a-fA-F]{2}(?::|-|$)){6}")
val matcher = pattern.matcher(macAddress)
return matcher.matches()
}
/**
* Splits the given MAC address into it's parts and saves it in the bytes
* array
*
* @param macAddress The MAC address that shall be split
* @return The byte array that holds the MAC address parts
*/
private fun getMacBytes(macAddress: String): ByteArray {
val macBytes = ByteArray(6)
// Parse the MAC address elements into the array.
val hex = macAddress.split("([:\\-])".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (i in 0..5) {
macBytes[i] = Integer.parseInt(hex[i], 16).toByte()
}
return macBytes
}
} | gpl-3.0 | dbbec9fe9e8f5423a722680285958a58 | 38.228758 | 166 | 0.581736 | 4.755151 | false | false | false | false |
lindelea/lindale | app/src/main/java/org/lindelin/lindale/activities/ui/task/MyTaskRecyclerViewAdapter.kt | 1 | 3088 | package org.lindelin.lindale.activities.ui.task
import android.annotation.SuppressLint
import androidx.recyclerview.widget.RecyclerView
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 org.lindelin.lindale.R
import org.lindelin.lindale.activities.ui.task.TaskFragment.OnListFragmentInteractionListener
import org.lindelin.lindale.activities.ui.task.dummy.DummyContent.DummyItem
import kotlinx.android.synthetic.main.fragment_task.view.*
import org.lindelin.lindale.models.Task
import org.lindelin.lindale.supports.onProgressChanged
import org.lindelin.lindale.supports.setImageFromUrl
import org.w3c.dom.Text
/**
* [RecyclerView.Adapter] that can display a [DummyItem] and makes a call to the
* specified [OnListFragmentInteractionListener].
* TODO: Replace the implementation with code for your data type.
*/
class MyTaskRecyclerViewAdapter(
private val mValues: List<Task>,
private val mListener: OnListFragmentInteractionListener?
) : RecyclerView.Adapter<MyTaskRecyclerViewAdapter.ViewHolder>() {
private val mOnClickListener: View.OnClickListener
init {
mOnClickListener = View.OnClickListener { v ->
val item = v.tag as Task
// Notify the active callbacks interface (the activity, if the fragment is attached to
// one) that an item has been selected.
mListener?.onListFragmentInteraction(item)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.fragment_task, parent, false)
return ViewHolder(view)
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = mValues[position]
holder.userPhotoView.setImageFromUrl(item.user?.photo)
holder.userNameText.text = item.user?.name
holder.statusText.text = item.status
holder.titleText.text = item.title
holder.progressText.text = "${item.progress}% Completed"
holder.progressStatusText.text = item.subTaskStatus
holder.progressBar.onProgressChanged(item.progress)
with(holder.mView) {
tag = item
setOnClickListener(mOnClickListener)
}
}
override fun getItemCount(): Int = mValues.size
inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) {
val userPhotoView: ImageView = mView.userPhotoView
val userNameText: TextView = mView.userNameText
val statusText: TextView = mView.statusText
val titleText: TextView = mView.titleText
val progressText: TextView = mView.progressText
val progressStatusText: TextView = mView.progressStatusText
val progressBar: ProgressBar = mView.progressBar
override fun toString(): String {
return super.toString() + " '" + titleText.text + "'"
}
}
}
| mit | ab1e00246b918b97f84c11835a4f7100 | 36.658537 | 98 | 0.724093 | 4.568047 | false | false | false | false |
wiltonlazary/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/OutputFiles.kt | 1 | 2634 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.util.prefixBaseNameIfNot
import org.jetbrains.kotlin.util.removeSuffixIfPresent
import org.jetbrains.kotlin.util.suffixIfNot
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.konan.target.CompilerOutputKind
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.konan.util.visibleName
import kotlin.random.Random
/**
* Creates and stores terminal compiler outputs.
*/
class OutputFiles(outputPath: String?, target: KonanTarget, val produce: CompilerOutputKind) {
private val prefix = produce.prefix(target)
private val suffix = produce.suffix(target)
val outputName = outputPath?.removeSuffixIfPresent(suffix) ?: produce.visibleName
/**
* Header file for dynamic library.
*/
val cAdapterHeader by lazy { File("${outputName}_api.h") }
val cAdapterDef by lazy { File("${outputName}.def") }
/**
* Main compiler's output file.
*/
val mainFile =
if (produce.isCache)
outputName
else
outputName.fullOutputName()
val tempCacheDirectory =
if (produce.isCache)
File(outputName + Random.nextLong().toString())
else null
val nativeBinaryFile =
if (produce.isCache)
tempCacheDirectory!!.child(File(outputName.fullOutputName()).absoluteFile.name).absolutePath
else mainFile
val symbolicInfoFile = "$nativeBinaryFile.dSYM"
val bitcodeDependenciesFile =
if (produce.isCache)
tempCacheDirectory!!.child(CachedLibraries.BITCODE_DEPENDENCIES_FILE_NAME).absolutePath
else null
private fun String.fullOutputName() = prefixBaseNameIfNeeded(prefix).suffixIfNeeded(suffix)
private fun String.prefixBaseNameIfNeeded(prefix: String) =
if (produce.isCache)
prefixBaseNameAlways(prefix)
else prefixBaseNameIfNot(prefix)
private fun String.suffixIfNeeded(prefix: String) =
if (produce.isCache)
suffixAlways(prefix)
else suffixIfNot(prefix)
private fun String.prefixBaseNameAlways(prefix: String): String {
val file = File(this).absoluteFile
val name = file.name
val directory = file.parent
return "$directory/$prefix$name"
}
private fun String.suffixAlways(suffix: String) = "$this$suffix"
} | apache-2.0 | 12eed64493658a987400025d9c08d967 | 32.35443 | 108 | 0.680714 | 4.557093 | false | false | false | false |
masahide318/Croudia-for-Android | app/src/main/kotlin/t/masahide/android/croudia/api/CroudiaAPIService.kt | 1 | 6456 | package t.masahide.android.croudia.api
import com.squareup.okhttp.RequestBody
import retrofit.http.*
import rx.Observable
import t.masahide.android.croudia.constant.CroudiaConstants
import t.masahide.android.croudia.entitiy.AccessToken
import t.masahide.android.croudia.entitiy.Status
import t.masahide.android.croudia.entitiy.User
import t.masahide.android.croudia.service.AccessTokenService
interface CroudiaAPIService {
val accessTokenService: AccessTokenService
get() = AccessTokenService()
val authorization: String
get() = " Bearer " + accessTokenService.getAccessToken().accessToken
val refreshToken: String
get() = accessTokenService.getAccessToken().refreshToken
@FormUrlEncoded
@POST("/oauth/token")
fun createToken(
@Field("code") code: String,
@Field("client_id") clientId: String = CroudiaConstants.CONSUMER_KEY,
@Field("client_secret") clientSecret: String = CroudiaConstants.CONSUMER_SECRET,
@Field("grant_type") grantType: String = "authorization_code"
): Observable<AccessToken>
@FormUrlEncoded
@POST("/oauth/token")
fun refreshToken(
@Header("Authorization") authorization: String = authorization,
@Field("refresh_token") refreshToken: String = refreshToken,
@Field("client_id") clientId: String = CroudiaConstants.CONSUMER_KEY,
@Field("client_secret") clientSecret: String = CroudiaConstants.CONSUMER_SECRET,
@Field("grant_type") grantType: String = "refresh_token"
): Observable<AccessToken>
@GET("/account/verify_credentials.json")
fun verifyCredentials(
@Header("Authorization") authorization: String = authorization
): Observable<User>
@FormUrlEncoded
@POST("/2/statuses/update.json")
fun postStatus(
@Header("Authorization") authorization: String = authorization,
@Field("status") status: String,
@Field("in_reply_to_status_id") replyStatusId: String = ""
): Observable<Status>
@Multipart
@POST("/2/statuses/update_with_media.json")
fun postStatusWithImage(
@Header("Authorization") authorization: String = authorization,
@Part("media") media: RequestBody,
@Part("status") status: RequestBody,
@Part("in_reply_to_status_id") replyStatusId: RequestBody? = null
): Observable<Status>
@FormUrlEncoded
@POST("/2/statuses/spread/{status_id}.json")
fun spreadStatus(
@Header("Authorization") authorization: String = authorization,
@Path("status_id") status: String,
@Field("status_id") dummy: String = ""
): Observable<Status>
@GET("/2/statuses/public_timeline.json")
fun publicTimeLine(
@Header("Authorization") authorization: String = authorization,
@Query("since_id") sinceId: String = "",
@Query("max_id") maxId: String = "",
@Query("count") count: Int = 30
): Observable<MutableList<Status>>
@GET("/2/statuses/home_timeline.json")
fun homeTimeLine(
@Header("Authorization") authorization: String = authorization,
@Query("since_id") sinceId: String = "",
@Query("max_id") maxId: String = "",
@Query("count") count: Int = 30
): Observable<MutableList<Status>>
@GET("/favorites.json")
fun favoriteTimeLine(
@Header("Authorization") authorization: String = authorization,
@Query("since_id") sinceId: String = "",
@Query("max_id") maxId: String = "",
@Query("count") count: Int = 30
): Observable<MutableList<Status>>
@GET("/2/statuses/mentions.json")
fun mentionsTimeLine(
@Header("Authorization") authorization: String = authorization,
@Query("since_id") sinceId: String = "",
@Query("max_id") maxId: String = "",
@Query("count") count: Int = 30
): Observable<MutableList<Status>>
@GET("/2/statuses/user_timeline.json")
fun userTimeLine(
@Header("Authorization") authorization: String = authorization,
@Query("since_id") sinceId: String = "",
@Query("max_id") maxId: String = "",
@Query("count") count: Int = 30
): Observable<MutableList<Status>>
@GET("/followers/list.json")
fun followers(
@Header("Authorization") authorization: String = authorization,
@Query("count") count: Int = 100
): Observable<MutableList<User>>
@GET("/friends/list.json")
fun friends(
@Header("Authorization") authorization: String = authorization,
@Query("count") count: Int = 30
): Observable<MutableList<User>>
@FormUrlEncoded
@POST("/friendships/create.json")
fun friendshipsCreate(
@Header("Authorization") authorization: String = authorization,
@Query("user_id") UserId: String
): Observable<User>
@FormUrlEncoded
@POST("/friendships/destroy.json")
fun friendshipsDestroy(
@Header("Authorization") authorization: String = authorization,
@Field("user_id") UserId: String,
@Field("user_id") dummy: String = ""
): Observable<User>
@FormUrlEncoded
@POST("/2/statuses/destroy/{status_id}.json")
fun destroyStatus(
@Header("Authorization") authorization: String = authorization,
@Path("status_id") statusId: String,
@Field("status_id") dummy: String = ""
): Observable<Status>
@FormUrlEncoded
@POST("/2/favorites/create/{status_id}.json")
fun favoriteCreate(
@Header("Authorization") authorization: String = authorization,
@Path("status_id") statusId: String,
@Field("status_id") dummy: String = ""
): Observable<Status>
@FormUrlEncoded
@POST("/2/favorites/destroy/{status_id}.json")
fun favoriteDestroy(
@Header("Authorization") authorization: String = authorization,
@Path("status_id") statusId: String,
@Field("status_id") dummy: String = ""
): Observable<Status>
@FormUrlEncoded
@POST("/account/update_profile.json")
fun updateProfile(
@Header("Authorization") authorization: String = authorization,
@Field("name") name: String,
@Field("description") description: String
): Observable<User>
} | apache-2.0 | 0a984ccdf7338bf24dc69516309bc8f6 | 36.982353 | 92 | 0.628408 | 4.483333 | false | false | false | false |
jeksor/Language-Detector | app/src/main/java/com/esorokin/lantector/ui/plugin/AlertMessagePlugin.kt | 1 | 1104 | package com.esorokin.lantector.ui.plugin
import android.content.Context
import android.support.v7.app.AlertDialog
import com.esorokin.lantector.R
import com.esorokin.lantector.ui.plugin.base.BasePlugin
class AlertMessagePlugin(private val contextProvider: () -> Context) : BasePlugin() {
private var dialog: AlertDialog? = null
override fun onDestroy() {
super.onDestroy()
hideMessage()
}
fun showMessage(message: String? = null,
title: String? = null,
okText: String = contextProvider.invoke().getString(R.string.ok),
hideListener: () -> Unit = {}) {
hideMessage()
val builder = AlertDialog.Builder(contextProvider.invoke())
title?.let { builder.setTitle(it) }
message?.let { builder.setMessage(it) }
builder.setPositiveButton(okText, { _, _ -> hideListener.invoke() })
builder.setCancelable(true)
builder.setOnCancelListener { hideListener.invoke() }
dialog = builder.show()
}
fun hideMessage() {
dialog?.dismiss()
}
} | mit | 479534656071fdbaaa8aee0c066103b9 | 29.694444 | 85 | 0.634964 | 4.469636 | false | false | false | false |
kiruto/kotlin-android-mahjong | app/src/main/java/dev/yuriel/mahjan/actor/OppoTilePlaceHolderActor.kt | 1 | 2051 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* 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 dev.yuriel.mahjan.actor
import com.badlogic.gdx.graphics.g2d.Batch
import dev.yuriel.kotmvp.Dev
import dev.yuriel.kotmvp.SMALL_TILE_HEIGHT
import dev.yuriel.kotmvp.SMALL_TILE_WIDTH
/**
* Created by yuriel on 8/7/16.
*/
class OppoTilePlaceHolderActor(private var position: Int, isTsumo: Boolean = false): TileActor(isTsumo) {
override fun getTileSize() = Pair(SMALL_TILE_WIDTH * Dev.U, SMALL_TILE_HEIGHT * Dev.U)
override fun getTileOrigin() = Pair(- (position + getOffset()) * width, 0F)
override fun getTilePosition(): Int = position
override fun setTilePosition(value: Int) {
position = value
}
override fun onDraw(batch: Batch?, parentAlpha: Float) {
if (null == obverse) return
batch?.draw(obverse, originX, originY, width, height)
}
private fun getOffset(): Float {
return if (isTsumo) 0.5F else 0F
}
} | mit | 3cb6129eb164e52ef5e94e10ec098b18 | 39.235294 | 105 | 0.728425 | 4.021569 | false | false | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/heart/RxHeartLayout.kt | 1 | 2440 | /*
* Copyright (C) 2015 tyrantgit
*
* 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.tamsiree.rxui.view.heart
import android.content.Context
import android.util.AttributeSet
import android.widget.RelativeLayout
import com.tamsiree.rxui.R
import com.tamsiree.rxui.animation.RxAbstractPathAnimator
import com.tamsiree.rxui.animation.RxAbstractPathAnimator.Config.Companion.fromTypeArray
import com.tamsiree.rxui.animation.RxPathAnimator
/**
* @author tamsiree
*/
class RxHeartLayout : RelativeLayout {
private var mAnimator: RxAbstractPathAnimator? = null
constructor(context: Context?) : super(context) {
init(null, 0)
}
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
init(attrs, 0)
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(attrs, defStyleAttr)
}
private fun init(attrs: AttributeSet?, defStyleAttr: Int) {
val a = context.obtainStyledAttributes(
attrs, R.styleable.RxHeartLayout, defStyleAttr, 0)
mAnimator = RxPathAnimator(fromTypeArray(a))
a.recycle()
}
var animator: RxAbstractPathAnimator?
get() = mAnimator
set(animator) {
clearAnimation()
mAnimator = animator
}
override fun clearAnimation() {
for (i in 0 until childCount) {
getChildAt(i).clearAnimation()
}
removeAllViews()
}
fun addHeart(color: Int) {
val rxHeartView = RxHeartView(context)
rxHeartView.setColor(color)
mAnimator!!.start(rxHeartView, this)
}
fun addHeart(color: Int, heartResId: Int, heartBorderResId: Int) {
val rxHeartView = RxHeartView(context)
rxHeartView.setColorAndDrawables(color, heartResId, heartBorderResId)
mAnimator!!.start(rxHeartView, this)
}
} | apache-2.0 | 69565458f21b99f361a0bcfdaa7ff3ba | 31.118421 | 115 | 0.690984 | 4.243478 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/adapter/AccountSelectorAdapter.kt | 1 | 5546 | /*
* 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.adapter
import android.content.SharedPreferences
import android.view.LayoutInflater
import android.view.ViewGroup
import com.bumptech.glide.RequestManager
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.constant.profileImageStyleKey
import de.vanita5.twittnuker.fragment.AccountsDashboardFragment
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.view.holder.AccountProfileImageViewHolder
import de.vanita5.twittnuker.view.transformer.AccountsSelectorTransformer
import java.util.*
class AccountSelectorAdapter(
private val inflater: LayoutInflater,
preferences: SharedPreferences,
val requestManager: RequestManager
) : RecyclerPagerAdapter() {
internal var profileImageStyle: Int = preferences[profileImageStyleKey]
var listener: Listener? = null
var accounts: Array<AccountDetails>? = null
set(value) {
if (value != null) {
val previousAccounts = accounts
if (previousAccounts != null) {
val tmpList = arrayListOf(*value)
val tmpResult = ArrayList<AccountDetails>()
previousAccounts.forEach { previousAccount ->
val prefIndexOfTmp = tmpList.indexOfFirst { previousAccount == it }
if (prefIndexOfTmp >= 0) {
tmpResult.add(tmpList.removeAt(prefIndexOfTmp))
}
}
tmpResult.addAll(tmpList)
field = tmpResult.toTypedArray()
} else {
field = value
}
} else {
field = null
}
notifyPagesChanged(invalidateCache = true)
}
fun getAdapterAccount(position: Int): AccountDetails? {
return accounts?.getOrNull(position - accountStart + 1)
}
var selectedAccount: AccountDetails?
get() {
return accounts?.firstOrNull()
}
set(account) {
val from = account ?: return
val to = selectedAccount ?: return
swap(from, to)
}
val ITEM_VIEW_TYPE_SPACE = 1
val ITEM_VIEW_TYPE_ICON = 2
override fun onCreateViewHolder(container: ViewGroup, position: Int, itemViewType: Int): ViewHolder {
when (itemViewType) {
ITEM_VIEW_TYPE_SPACE -> {
val view = inflater.inflate(R.layout.adapter_item_dashboard_account_space, container, false)
return AccountsDashboardFragment.AccountSpaceViewHolder(view)
}
ITEM_VIEW_TYPE_ICON -> {
val view = inflater.inflate(AccountProfileImageViewHolder.layoutResource, container, false)
return AccountProfileImageViewHolder(this, view)
}
}
throw UnsupportedOperationException()
}
override fun onBindViewHolder(holder: ViewHolder, position: Int, itemViewType: Int) {
when (itemViewType) {
ITEM_VIEW_TYPE_ICON -> {
val account = getAdapterAccount(position)!!
(holder as AccountProfileImageViewHolder).display(account)
}
}
}
override fun getItemViewType(position: Int): Int {
if (position < accountStart) {
return ITEM_VIEW_TYPE_SPACE
}
return ITEM_VIEW_TYPE_ICON
}
override fun getCount(): Int {
return Math.max(3, accountsCount)
}
val accountStart: Int
get() = Math.max(0, 3 - accountsCount)
val accountsCount: Int
get() {
val accounts = this.accounts ?: return 0
return Math.max(0, accounts.size - 1)
}
override fun getPageWidth(position: Int): Float {
return 1f / AccountsSelectorTransformer.selectorAccountsCount
}
fun dispatchItemSelected(holder: AccountProfileImageViewHolder) {
listener?.onAccountSelected(holder, getAdapterAccount(holder.position)!!)
}
private fun swap(from: AccountDetails, to: AccountDetails) {
val accounts = accounts ?: return
val fromIdx = accounts.indexOfFirst { it == from }
val toIdx = accounts.indexOfFirst { it == to }
if (fromIdx < 0 || toIdx < 0) return
val temp = accounts[toIdx]
accounts[toIdx] = accounts[fromIdx]
accounts[fromIdx] = temp
notifyPagesChanged(invalidateCache = false)
}
interface Listener {
fun onAccountSelected(holder: AccountProfileImageViewHolder, details: AccountDetails)
}
} | gpl-3.0 | baa0efdec2627a3c5905a76fe22b55b3 | 34.557692 | 108 | 0.638118 | 4.789292 | false | false | false | false |
usmansaleem/kt-vertx | src/test/kotlin/info/usmans/blog/tests.kt | 1 | 1879 | package info.usmans.blog
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import info.usmans.blog.model.BlogItem
import info.usmans.blog.vertx.checkoutGist
import info.usmans.blog.vertx.commitGist
import info.usmans.blog.vertx.gitPushStatus
import io.vertx.core.json.Json
import org.junit.Before
import org.junit.Test
import java.io.File
import kotlin.test.assertEquals
class TestSource {
@Before
fun setUp() {
Json.mapper.apply {
registerKotlinModule()
}
Json.prettyMapper.apply {
registerKotlinModule()
}
}
@Test
fun testGistCheckout() {
val checkoutDir = checkoutGist("https://gist.github.com/5fd0a9ee89d72544cf50128ba8e8e012.git")
//read and change the file and commit ...
val blogItemList: List<info.usmans.blog.model.BlogItem> = Json.mapper.readValue(File(checkoutDir, "data.json").readText())
val sortedBlogItemsList = blogItemList.sortedBy { it.id }
val blogItem = BlogItem(sortedBlogItemsList.last().id + 1,
"commit_from_jgit",
"JGit","Commit from jgit to gist",
"This will contain fullbody")
//add to list
val updatedList = sortedBlogItemsList.toMutableList()
updatedList.add(blogItem)
assertEquals(blogItemList.size + 1, updatedList.size)
//convert to json and write it to file in repository
val jsonData = Json.encodePrettily(updatedList)
println(jsonData)
//write to file in repository
File(checkoutDir, "data.json").writeText(jsonData)
val revCommit = commitGist(checkoutDir)
assertEquals("commit from jgit", revCommit.fullMessage)
gitPushStatus(checkoutDir)
//pushGist(checkoutDir, gitCredentialProvider(""))
}
} | mit | 72656ff6bedda51ec792c00dbbcf1235 | 31.413793 | 130 | 0.681746 | 4.093682 | false | true | false | false |
DarrenAtherton49/android-kotlin-base | app/src/main/kotlin/com/atherton/sample/presentation/main/MainViewModel.kt | 1 | 3614 | package com.atherton.sample.presentation.main
import android.os.Parcelable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.atherton.sample.presentation.base.AppViewModel
import com.atherton.sample.presentation.base.BaseViewEffect
import com.atherton.sample.presentation.features.settings.licenses.License
import com.atherton.sample.presentation.util.extension.preventMultipleClicks
import com.atherton.sample.util.injection.PerView
import com.atherton.sample.util.threading.RxSchedulers
import com.ww.roxie.BaseAction
import com.ww.roxie.BaseState
import io.reactivex.Observable.mergeArray
import io.reactivex.rxkotlin.ofType
import io.reactivex.rxkotlin.plusAssign
import kotlinx.android.parcel.Parcelize
import timber.log.Timber
import javax.inject.Inject
class MainViewModel @Inject constructor(
initialState: MainState?,
private val schedulers: RxSchedulers
) : AppViewModel<MainAction, MainState, MainViewEffect>() {
override val initialState = initialState ?: MainState()
init {
bindActions()
}
private fun bindActions() {
val settingsActionClickedViewEffect = actions.ofType<MainAction.SettingsActionClicked>()
.subscribeOn(schedulers.io)
.map { MainViewEffect.Navigation.ShowSettingsScreen }
val openSourceLicensesClickedViewEffect = actions.ofType<MainAction.SettingsAction.OpenSourceLicensesClicked>()
.subscribeOn(schedulers.io)
.preventMultipleClicks()
.map { MainViewEffect.Navigation.Settings.ShowLicensesScreen }
val licenseClickedViewEffect = actions.ofType<MainAction.LicenseClicked>()
.subscribeOn(schedulers.io)
.preventMultipleClicks()
.map { action -> MainViewEffect.Navigation.ShowLicenseInBrowser(action.license.url) }
val viewEffectChanges = mergeArray(
settingsActionClickedViewEffect,
openSourceLicensesClickedViewEffect,
licenseClickedViewEffect
)
disposables += viewEffectChanges
.observeOn(schedulers.main)
.subscribe(viewEffects::accept, Timber::e)
}
}
//================================================================================
// MVI
//================================================================================
sealed class MainAction : BaseAction {
object SettingsActionClicked : MainAction()
sealed class SettingsAction : MainAction() {
object OpenSourceLicensesClicked : SettingsAction()
}
data class LicenseClicked(val license: License) : MainAction()
}
@Parcelize
data class MainState(val isIdle: Boolean = true): BaseState, Parcelable
sealed class MainViewEffect : BaseViewEffect {
sealed class Navigation : MainViewEffect() {
object ShowSettingsScreen : Navigation()
sealed class Settings : Navigation() {
object ShowLicensesScreen : Settings()
}
data class ShowLicenseInBrowser(val url: String) : Navigation()
}
}
//================================================================================
// Factory
//================================================================================
@PerView
class MainViewModelFactory(
private val initialState: MainState?,
private val schedulers: RxSchedulers
) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T = MainViewModel(
initialState,
schedulers) as T
companion object {
const val NAME = "MainViewModelFactory"
}
}
| mit | 0b1a90a6d0f373bbd8cabe23f91bb8f6 | 34.087379 | 119 | 0.664084 | 5.2 | false | false | false | false |
alexcustos/linkasanote | app/src/main/java/com/bytesforge/linkasanote/sync/SyncItem.kt | 1 | 14778 | /*
* LaaNo Android application
*
* @author Aleksandr Borisenko <[email protected]>
* Copyright (C) 2017 Aleksandr Borisenko
*
* 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.bytesforge.linkasanote.sync
import android.database.sqlite.SQLiteConstraintException
import android.util.Log
import androidx.annotation.VisibleForTesting
import com.bytesforge.linkasanote.data.Item
import com.bytesforge.linkasanote.data.source.cloud.CloudItem
import com.bytesforge.linkasanote.data.source.local.LocalContract.SyncResultEntry
import com.bytesforge.linkasanote.data.source.local.LocalItems
import com.bytesforge.linkasanote.sync.files.JsonFile
import com.bytesforge.linkasanote.utils.CommonUtils
import com.owncloud.android.lib.common.OwnCloudClient
import com.owncloud.android.lib.common.operations.RemoteOperationResult
class SyncItem<T : Item?>(
private val ocClient: OwnCloudClient,
private val localItems: LocalItems<T>, private val cloudItem: CloudItem<T>,
private val syncNotifications: SyncNotifications, private val notificationAction: String,
private val uploadToEmpty: Boolean, private val protectLocal: Boolean,
private val started: Long
) {
private var uploaded: Int
private var downloaded: Int
private var syncResult: SyncItemResult
fun sync(): SyncItemResult {
val dataStorageETag = cloudItem.getDataSourceETag(ocClient)
?: return SyncItemResult(SyncItemResult.Status.SOURCE_NOT_READY)
val isCloudChanged = cloudItem.isCloudDataSourceChanged(dataStorageETag)
syncItems(isCloudChanged)
if (syncResult.isSuccess) {
cloudItem.updateLastSyncedETag(dataStorageETag)
}
return syncResult
}
private fun syncItems(isCloudChanged: Boolean) {
if (!isCloudChanged) {
localItems.unsynced
.subscribe(
{ item: T -> syncItem(item, item!!.eTag) }
) { throwable: Throwable? -> setDbAccessError() }
return
}
val cloudDataSourceMap = cloudItem.getDataSourceMap(ocClient)
if (cloudDataSourceMap.isEmpty() && uploadToEmpty) {
val numRows = localItems.resetSyncState().blockingGet()
if (numRows > 0) {
Log.d(TAG, "Cloud storage loss is detected, starting to upload [$numRows]")
}
}
// Sync Local
localItems.all
.subscribe({ item: T ->
val cloudETag = cloudDataSourceMap[item!!.id]
syncItem(item, cloudETag)
}) { throwable: Throwable? ->
CommonUtils.logStackTrace(TAG_E, throwable!!)
setDbAccessError()
}
if (syncResult.isDbAccessError) return
// OPTIMIZATION: Local Map can be taken from previous step
val localIds: MutableSet<String> = HashSet()
localItems.ids
.subscribe(
{ e: String -> localIds.add(e) }
) { throwable: Throwable? -> setDbAccessError() }
if (syncResult.isDbAccessError) return
// New cloud records
// OPTIMIZATION: Cloud Map can be updated in the previous step
val cloudIds: Set<String> = cloudItem.getDataSourceMap(ocClient).keys
for (cloudId in cloudIds) {
if (localIds.contains(cloudId)) {
continue
}
val cloudItem = download(cloudId) ?: continue
syncNotifications.sendSyncBroadcast(
notificationAction,
SyncNotifications.STATUS_DOWNLOADED, cloudId, ++downloaded
)
val notifyChanged = save(cloudItem)
if (notifyChanged) {
syncNotifications.sendSyncBroadcast(
notificationAction,
SyncNotifications.STATUS_CREATED, cloudId
)
}
}
}
private fun syncItem(item: T, cloudETag: String?) {
// NOTE: some updates on the conflicted state may cause constraint violation, so let it be resolved first
if (item!!.isConflicted) return
val itemId = item.id
val itemETag = item.eTag
var notifyChanged = false
var statusChanged: Int = SyncNotifications.STATUS_UPDATED
if (itemETag == null) { // New
// duplicated && conflicted can be ignored
if (item.isDeleted) {
// DELETE local
Log.e(TAG, "The records never synced must be deleted immediately [$itemId]")
notifyChanged = deleteLocal(item)
statusChanged = SyncNotifications.STATUS_DELETED
} else { // synced is ignored (!synced)
// UPLOAD
// NOTE: local unsynced will replace cloud with the same ID (acceptable behaviour)
notifyChanged = upload(item)
}
} else if (itemETag == cloudETag) { // Green light
// conflicted can be ignored
if (!item.isSynced) {
if (item.isDeleted) {
// DELETE cloud
notifyChanged = deleteCloud(item)
statusChanged = SyncNotifications.STATUS_DELETED
} else if (!item.isDuplicated) {
// UPLOAD
notifyChanged = upload(item)
}
}
} else if (cloudETag == null) { // Was deleted on cloud
if (item.isSynced) {
if (protectLocal) {
// SET conflicted (as if it has been changed)
val state = SyncState(SyncState.State.CONFLICTED_UPDATE)
notifyChanged = update(item, state)
} else {
// DELETE local
notifyChanged = deleteLocal(item)
statusChanged = SyncNotifications.STATUS_DELETED
}
} else {
if (item.isDeleted) {
// DELETE local
notifyChanged = deleteLocal(item)
statusChanged = SyncNotifications.STATUS_DELETED
} else {
// SET conflicted
val state = SyncState(SyncState.State.CONFLICTED_UPDATE)
notifyChanged = update(item, state)
}
}
} else { // Was changed on cloud
// duplicated && conflicted can be ignored
// DOWNLOAD (with synced state by default)
val cloudItem = download(itemId)
if (cloudItem != null) {
syncNotifications.sendSyncBroadcast(
notificationAction,
SyncNotifications.STATUS_DOWNLOADED, itemId, ++downloaded
)
if (item.isSynced && !item.isDeleted) {
// SAVE local
notifyChanged = save(cloudItem)
} else { // !synced || deleted
if (item == cloudItem) {
if (item.isDeleted) {
// DELETE cloud
notifyChanged = deleteCloud(item)
statusChanged = SyncNotifications.STATUS_DELETED
} else {
// UPDATE state
assert(cloudItem.eTag != null)
val state = SyncState(
cloudItem.eTag!!, SyncState.State.SYNCED
)
// NOTE: record may be in conflicted state
notifyChanged = update(item, state)
}
} else {
// SET (or confirm) conflicted
val state: SyncState = if (item.isDeleted) {
SyncState(SyncState.State.CONFLICTED_DELETE)
} else {
SyncState(SyncState.State.CONFLICTED_UPDATE)
}
notifyChanged = update(item, state)
}
}
}
}
if (notifyChanged) {
syncNotifications.sendSyncBroadcast(notificationAction, statusChanged, itemId)
}
}
// NOTE: any cloud item can violate the DB constraints
private fun save(item: T): Boolean { // downloaded
checkNotNull(item)
val itemId = item.id
// Primary record
try {
val success = localItems.save(item).blockingGet()
if (success) {
localItems.logSyncResult(started, itemId,
SyncResultEntry.Result.DOWNLOADED).blockingGet()
val relatedId = item.relatedId
if (relatedId != null) {
localItems.logSyncResult(started, relatedId,
SyncResultEntry.Result.RELATED).blockingGet()
}
}
return success
} catch (e: NullPointerException) {
logError(itemId)
return false
} catch (e: SQLiteConstraintException) {
// NOTE: will try to resolve it further
}
// Duplicated record
try {
val success = localItems.saveDuplicated(item).blockingGet()
if (success) {
localItems.logSyncResult(started, itemId,
SyncResultEntry.Result.DOWNLOADED).blockingGet()
val relatedId = item.relatedId
if (relatedId != null) {
localItems.logSyncResult(started, relatedId,
SyncResultEntry.Result.RELATED).blockingGet()
}
}
return success
} catch (e: NullPointerException) {
logError(itemId)
} catch (e: SQLiteConstraintException) {
logError(itemId)
}
return false
}
private fun deleteLocal(item: T): Boolean {
checkNotNull(item)
val itemId = item.id
val relatedId = item.relatedId
Log.d(TAG, "$itemId: DELETE local")
val success = localItems.delete(itemId).blockingGet()
if (success) {
localItems.logSyncResult(started, itemId,
SyncResultEntry.Result.DELETED).blockingGet()
if (relatedId != null) {
localItems.logSyncResult(started, relatedId,
SyncResultEntry.Result.RELATED).blockingGet()
}
}
return success
}
private fun deleteCloud(item: T): Boolean {
checkNotNull(item)
val itemId = item.id
Log.d(TAG, "$itemId: DELETE cloud")
val result = cloudItem.delete(itemId, ocClient).blockingGet()
return result.isSuccess && deleteLocal(item)
}
private fun update(item: T, state: SyncState): Boolean {
checkNotNull(item)
val itemId = item.id
val relatedId = item.relatedId
Log.d(TAG, "$itemId: UPDATE")
val success = localItems.update(itemId, state).blockingGet()
if (success) {
val result: SyncResultEntry.Result = if (state.isConflicted) {
SyncResultEntry.Result.CONFLICT
} else {
SyncResultEntry.Result.SYNCED
}
localItems.logSyncResult(started, itemId, result).blockingGet()
if (relatedId != null) {
localItems.logSyncResult(started, relatedId,
SyncResultEntry.Result.RELATED).blockingGet()
}
}
return success
}
private fun upload(item: T): Boolean {
checkNotNull(item)
val itemId = item.id
val relatedId = item.relatedId
Log.d(TAG, item.id + ": UPLOAD")
var success = false
val result = cloudItem.upload(item, ocClient).blockingGet()
if (result == null) {
logError(itemId)
return false
}
if (result.isSuccess) {
syncNotifications.sendSyncBroadcast(
notificationAction,
SyncNotifications.STATUS_UPLOADED, itemId, ++uploaded
)
val jsonFile = result.data[0] as JsonFile
val state = SyncState(jsonFile.eTag!!, SyncState.State.SYNCED)
success = localItems.update(itemId, state).blockingGet()
if (success) {
localItems.logSyncResult(started, itemId,
SyncResultEntry.Result.UPLOADED).blockingGet()
if (relatedId != null) {
localItems.logSyncResult(started, relatedId,
SyncResultEntry.Result.RELATED).blockingGet()
}
}
} else if (result.code == RemoteOperationResult.ResultCode.SYNC_CONFLICT) {
val state = SyncState(SyncState.State.CONFLICTED_UPDATE)
success = update(item, state)
}
return success
}
private fun logError(itemId: String) {
syncResult.incFailsCount()
localItems.logSyncResult(started, itemId,
SyncResultEntry.Result.ERROR).blockingGet()
}
private fun download(itemId: String): T? {
Log.d(TAG, "$itemId: DOWNLOAD")
return try {
// Note: will be logged in save() or update()
cloudItem.download(itemId, ocClient).blockingGet()
} catch (e: NullPointerException) {
logError(itemId)
null
} catch (e: NoSuchElementException) {
// NOTE: unexpected error, file has to be in place already
logError(itemId)
null
}
}
private fun setDbAccessError() {
syncResult = SyncItemResult(SyncItemResult.Status.DB_ACCESS_ERROR)
}
@get:VisibleForTesting
val failsCount: Int
get() = syncResult.failsCount
companion object {
private val TAG = SyncItem::class.java.simpleName
private val TAG_E = SyncItem::class.java.canonicalName
}
init {
syncResult = SyncItemResult(SyncItemResult.Status.FAILS_COUNT)
uploaded = 0
downloaded = 0
}
} | gpl-3.0 | 6bb65c954a6c3edcd01d1cf13cc4199c | 38.201592 | 113 | 0.564894 | 5.136601 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/imagepicker/exporters/CropImageExporter.kt | 2 | 1625 | package abi44_0_0.expo.modules.imagepicker.exporters
import android.graphics.Rect
import android.net.Uri
import abi44_0_0.expo.modules.imagepicker.exporters.ImageExporter.Listener
import org.apache.commons.io.IOUtils
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException
class CropImageExporter(
private val mRotation: Int,
private val mCropRect: Rect,
private val mBase64: Boolean
) : ImageExporter {
// Note: Crop activity saves the result to the output file. So, we don't need to do it.
override fun export(source: Uri, output: File, exporterListener: Listener) {
val width: Int
val height: Int
var rot = mRotation % 360
if (rot < 0) {
rot += 360
}
if (rot == 0 || rot == 180) { // Rotation is right-angled only
width = mCropRect.width()
height = mCropRect.height()
} else {
width = mCropRect.height()
height = mCropRect.width()
}
if (mBase64) {
ByteArrayOutputStream().use { base64Stream ->
try {
FileInputStream(source.path!!).use { input ->
// `CropImage` nullifies the `result.getBitmap()` after it writes out to a file, so
// we have to read back.
IOUtils.copy(input, base64Stream)
exporterListener.onResult(base64Stream, width, height)
}
} catch (e: NullPointerException) {
exporterListener.onFailure(e)
} catch (e: IOException) {
exporterListener.onFailure(e)
}
}
return
}
exporterListener.onResult(null, width, height)
}
}
| bsd-3-clause | 2f03e41ab407c66a2fdb5b3861c31553 | 28.545455 | 95 | 0.651077 | 4.032258 | false | false | false | false |
AndroidX/androidx | camera/integration-tests/timingtestapp/src/main/java/androidx/camera/integration/antelope/SettingsDialog.kt | 3 | 5886 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.integration.antelope
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.camera.integration.antelope.databinding.SettingsDialogBinding
import androidx.fragment.app.DialogFragment
/**
* DialogFragment that backs the configuration for both single tests and multiple tests
*/
internal class SettingsDialog : DialogFragment() {
private var _binding: SettingsDialogBinding? = null
private val binding get() = _binding!!
override fun onStart() {
// If we show a dialog with a title, it doesn't take up the whole screen
// Adjust the window to take up the full screen
dialog?.window?.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
super.onStart()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Set the dialog style so we get a title bar
setStyle(DialogFragment.STYLE_NORMAL, R.style.SettingsDialogTheme)
}
/** Set up the dialog depending on the dialog type */
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val args = arguments
val type = args?.getString(DIALOG_TYPE)
val title = args?.getString(DIALOG_TITLE)
val cameraNames = args?.getStringArray(CAMERA_NAMES)
val cameraIds = args?.getStringArray(CAMERA_IDS)
dialog?.setTitle(title)
_binding = SettingsDialogBinding.inflate(inflater, container, false)
if (null != cameraIds && null != cameraNames) {
when (type) {
DIALOG_TYPE_MULTI -> {
val settingsFragment = MultiTestSettingsFragment()
val childFragmentManager = childFragmentManager
val fragmentTransaction = childFragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.scroll_settings_dialog, settingsFragment)
fragmentTransaction.commit()
}
else -> {
val settingsFragment = SingleTestSettingsFragment(cameraNames, cameraIds)
val childFragmentManager = childFragmentManager
val fragmentTransaction = childFragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.scroll_settings_dialog, settingsFragment)
fragmentTransaction.commit()
}
}
}
return binding.root
}
/** When view is created, set up action buttons */
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val args = arguments
val type = args?.getString(DIALOG_TYPE)
when (type) {
DIALOG_TYPE_MULTI -> {
binding.buttonStart.text = getString(R.string.settings_multi_go)
binding.buttonCancel.text = getString(R.string.settings_multi_cancel)
binding.buttonStart.setOnClickListener {
(activity as MainActivity).startMultiTest()
this.dismiss()
}
binding.buttonCancel.setOnClickListener { this.dismiss() }
}
else -> {
binding.buttonStart.text = getString(R.string.settings_single_go)
binding.buttonCancel.text = getString(R.string.settings_single_cancel)
binding.buttonStart.setOnClickListener {
(activity as MainActivity).startSingleTest()
this.dismiss()
}
binding.buttonCancel.setOnClickListener { this.dismiss() }
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
private const val DIALOG_TYPE = "DIALOG_TYPE"
private const val DIALOG_TITLE = "DIALOG_TITLE"
private const val CAMERA_NAMES = "CAMERA_NAMES"
private const val CAMERA_IDS = "CAMERA_IDS"
internal const val DIALOG_TYPE_SINGLE = "DIALOG_TYPE_SINGLE"
internal const val DIALOG_TYPE_MULTI = "DIALOG_TYPE_MULTI"
/**
* Create a new Settings dialog to configure a test run
*
* @param type Dialog type (DIALOG_TYPE_MULTI or DIALOG_TYPE_SINGLE)
* @param title Dialog title
* @param cameraNames Human readable array of camera names
* @param cameraIds Array of camera ids
*/
fun newInstance(
type: String,
title: String,
cameraNames: Array<String>,
cameraIds: Array<String>
): SettingsDialog {
val args = Bundle()
args.putString(DIALOG_TYPE, type)
args.putString(DIALOG_TITLE, title)
args.putStringArray(CAMERA_NAMES, cameraNames)
args.putStringArray(CAMERA_IDS, cameraIds)
val settingsDialog = SettingsDialog()
settingsDialog.arguments = args
return settingsDialog
}
}
} | apache-2.0 | 668eebb8588fc247ed4a32db8d849234 | 35.79375 | 94 | 0.626741 | 5.154116 | false | false | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/issues/actions/HelpAction.kt | 1 | 892 | package com.github.jk1.ytplugin.issues.actions
import com.github.jk1.ytplugin.whenActive
import com.intellij.icons.AllIcons
import com.intellij.ide.browsers.BrowserLauncher
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
class HelpAction : IssueAction() {
override val text = "Help"
override val description = "Learn more about the YouTrack Integration plugin"
override val icon = AllIcons.Actions.Help
override val shortcut = "control shift H"
override fun actionPerformed(event: AnActionEvent) {
event.whenActive {
val url = "https://www.jetbrains.com/help/youtrack/standalone/YouTrack-Integration-Plugin.html"
ApplicationManager.getApplication().getService(BrowserLauncher::class.java).open(url)
}
}
} | apache-2.0 | bb144a481871efa4d8bcd965abeb52f9 | 37.826087 | 107 | 0.765695 | 4.46 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/todo/RsTodoSearcher.kt | 2 | 2777 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.todo
import com.intellij.openapi.application.QueryExecutorBase
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.cache.TodoCacheManager
import com.intellij.psi.search.IndexPattern
import com.intellij.psi.search.IndexPatternOccurrence
import com.intellij.psi.search.searches.IndexPatternSearch
import com.intellij.util.Processor
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.RsMacroCall
import org.rust.lang.core.psi.RsRecursiveVisitor
import org.rust.lang.core.psi.ext.endOffset
import org.rust.lang.core.psi.ext.macroName
import org.rust.lang.core.psi.ext.startOffset
class RsTodoSearcher : QueryExecutorBase<IndexPatternOccurrence, IndexPatternSearch.SearchParameters>(true) {
override fun processQuery(queryParameters: IndexPatternSearch.SearchParameters, consumer: Processor<in IndexPatternOccurrence>) {
var pattern = queryParameters.pattern
if (pattern != null && !pattern.isTodoPattern) return
if (pattern == null) {
pattern = queryParameters.patternProvider.indexPatterns.firstOrNull(IndexPattern::isTodoPattern) ?: return
}
val file = queryParameters.file as? RsFile ?: return
val cacheManager = TodoCacheManager.getInstance(file.project)
val patternProvider = queryParameters.patternProvider
val count = if (patternProvider != null) {
cacheManager.getTodoCount(file.virtualFile, patternProvider)
} else {
cacheManager.getTodoCount(file.virtualFile, pattern)
}
if (count == 0) return
file.accept(object : RsRecursiveVisitor() {
override fun visitMacroCall(call: RsMacroCall) {
super.visitMacroCall(call)
if (call.macroName == "todo") {
val startOffset = call.path.referenceNameElement?.startOffset ?: return
val endOffset = call.semicolon?.startOffset ?: call.endOffset
val range = TextRange(startOffset, endOffset)
consumer.process(RsTodoOccurrence(file, range, pattern))
}
}
})
}
}
// It's hacky way to check that pattern is used to find TODOs without real computation
val IndexPattern.isTodoPattern: Boolean get() = patternString.contains("TODO", true)
data class RsTodoOccurrence(
val _file: RsFile,
val _textRange: TextRange,
val _pattern: IndexPattern
) : IndexPatternOccurrence {
override fun getFile(): PsiFile = _file
override fun getTextRange(): TextRange = _textRange
override fun getPattern(): IndexPattern = _pattern
}
| mit | 32899b409e5b97cb86c8dbd22413299e | 39.838235 | 133 | 0.709399 | 4.530179 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/actions/RsJoinLinesHandler.kt | 3 | 2791 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.codeInsight.editorActions.JoinLinesHandlerDelegate
import com.intellij.codeInsight.editorActions.JoinLinesHandlerDelegate.CANNOT_JOIN
import com.intellij.openapi.editor.Document
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.util.text.CharSequenceSubSequence
import org.rust.ide.formatter.impl.CommaList
import org.rust.ide.typing.endsWithUnescapedBackslash
import org.rust.lang.core.psi.RS_STRING_LITERALS
import org.rust.lang.core.psi.RsElementTypes.COMMA
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.ext.elementType
class RsJoinLinesHandler : JoinLinesHandlerDelegate {
/**
* Fixup lines **after** they have been joined.
* See [RsJoinRawLinesHandler]
*/
override fun tryJoinLines(document: Document, file: PsiFile, offsetNear: Int, end: Int): Int {
if (file !is RsFile) return CANNOT_JOIN
val leftPsi = file.findElementAt(offsetNear) ?: return CANNOT_JOIN
val rightPsi = file.findElementAt(end) ?: return CANNOT_JOIN
val tryJoinCommaList = joinCommaList(document, leftPsi, rightPsi)
if (tryJoinCommaList != CANNOT_JOIN) return tryJoinCommaList
if (leftPsi != rightPsi) return CANNOT_JOIN
return when (leftPsi.elementType) {
in RS_STRING_LITERALS ->
joinStringLiteral(document, offsetNear, end)
else -> CANNOT_JOIN
}
}
private fun joinCommaList(document: Document, leftPsi: PsiElement, rightPsi: PsiElement): Int {
if (leftPsi.elementType != COMMA) return CANNOT_JOIN
val parentType = leftPsi.parent?.elementType ?: return CANNOT_JOIN
val rightType = rightPsi.elementType
val list = CommaList.forElement(parentType) ?: return CANNOT_JOIN
if (rightType == list.closingBrace) {
val replaceWith = if (list.needsSpaceBeforeClosingBrace) " " else ""
document.replaceString(leftPsi.textOffset, rightPsi.textOffset, replaceWith)
return leftPsi.textOffset
}
return CANNOT_JOIN
}
private fun joinStringLiteral(document: Document, offsetNear: Int, end: Int): Int {
val text = document.charsSequence
var start = offsetNear
// Strip newline escape
if (CharSequenceSubSequence(text, 0, start + 1).endsWithUnescapedBackslash()) {
start--
while (start >= 0 && (text[start] == ' ' || text[start] == '\t')) {
start--
}
}
document.deleteString(start + 1, end)
document.insertString(start + 1, " ")
return start + 1
}
}
| mit | 2a46a70fa0928f27d83dbe3bf4e429e7 | 35.246753 | 99 | 0.679685 | 4.530844 | false | false | false | false |
michael71/LanbahnPanel | app/src/main/java/de/blankedv/lanbahnpanel/loco/LocoControlArea.kt | 1 | 8295 | package de.blankedv.lanbahnpanel.loco
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color.*
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.util.Log
import de.blankedv.lanbahnpanel.model.*
import de.blankedv.lanbahnpanel.util.LanbahnBitmaps.bitmaps
import de.blankedv.lanbahnpanel.view.Dialogs
/**
* handles the display of the top 20% of the display, the "LOCO CONTROL AREA"
* one loco can be controlled (out of the ones defined in "locos-xyz.xml" File)
*
* @author mblank
*/
class LocoControlArea(internal var ctx: Context) {
private val stopBtn: LocoButton
private val lampBtn: LocoButton // F0
private val addressBtn: LocoButton
private val functionBtn: LocoButton //F1
private val leftBtn: LocoButton // speed to left
private val rightBtn: LocoButton // speed to right
private var paintText = Paint()
private var paintLargeTxt = Paint()
private var paintTextDisabled = Paint()
private var green = Paint()
private var white = Paint()
private var editPaint = Paint()
private var sliderXoff = bitmaps.get("slider")?.getWidth()!! / 2
private var sliderYoff = bitmaps.get("slider")?.getHeight()!! / 2
init {
val metrics = ctx.resources.displayMetrics
val width = metrics.widthPixels
val height = metrics.heightPixels
// define some paints for the loco controls and texts
paintLargeTxt.color = WHITE
paintLargeTxt.textSize = calcTextSize(width)
paintText.color = WHITE
paintText.textSize = paintLargeTxt.textSize * 0.7f
paintTextDisabled.color = LTGRAY
paintTextDisabled.textSize = paintLargeTxt.textSize * 0.7f
editPaint.color = RED
editPaint.textSize = calcTextSize(width)
editPaint.typeface = Typeface.DEFAULT_BOLD
green.color = GREEN
white.color = WHITE
addressBtn = LocoButton(0.09f, 0.5f) // only text.
addressBtn.name = "addr"
stopBtn = LocoButton(0.18f, 0.5f) // only text
stopBtn.name = "stop"
lampBtn = LocoButton(0.848f, 0.5f,
bitmaps?.get("lamp1")!!, // bitmap for "on" state
bitmaps?.get("lamp0")!!) // bitmap for "off" state
lampBtn.name = "lamp"
functionBtn = LocoButton(0.796f, 0.5f,
bitmaps?.get("func1")!!,
bitmaps?.get("func0")!!)
functionBtn.name = "func"
leftBtn = LocoButton(0.03f, 0.5f, bitmaps?.get("left")!!, bitmaps?.get("left")!!)
leftBtn.name = "left"
rightBtn = LocoButton(0.97f, 0.5f, bitmaps?.get("right")!!)
rightBtn.name = "right"
}
private fun drawSlider(canvas: Canvas) {
}
fun draw(canvas: Canvas) {
// Done in activity regularly
// selectedLoco?.updateLocoFromSX() // to be able to display actual states of this loco
// draw "buttons" and states
if (selectedLoco != null) {
leftBtn.doDraw(canvas, true)
rightBtn.doDraw(canvas, true)
addressBtn.doDraw(canvas, "A:" + selectedLoco?.adr!!.toString(), paintLargeTxt)
lampBtn.doDraw(canvas, selectedLoco?.lamp_to_be!!)
functionBtn.doDraw(canvas, selectedLoco?.function_to_be!!)
if (selectedLoco?.speed_act !== 0) {
stopBtn.doDraw(canvas, "STOP", paintText)
} else {
stopBtn.doDraw(canvas, "(stop)", paintTextDisabled)
}
} else {
addressBtn.doDraw(canvas, "??", paintLargeTxt)
}
// draw slider for speed selection
sxmin = (canvas.width * (X_LOCO_MID - X_LOCO_RANGE)).toInt()
sxmax = (canvas.width * (X_LOCO_MID + X_LOCO_RANGE)).toInt()
val speedLine = Rect(sxmin, (ySpeed - 1).toInt(), sxmax, ySpeed.toInt() + 1)
canvas.drawRect(speedLine, white)
val zeroLine = Rect((sxmin + sxmax) / 2 - 1, (ySpeed - ZERO_LINE_HALFLENGTH).toInt(),
(sxmin + sxmax) / 2 + 1, (ySpeed + ZERO_LINE_HALFLENGTH).toInt())
canvas.drawRect(zeroLine, white)
canvasWidth = canvas.width.toFloat()
if (selectedLoco != null) {
xSpeedAct = canvasWidth * sxSpeed() // grey slider on bottom
xSpeedToBe = canvasWidth * speedToBe() // orange slider on top
canvas.drawBitmap(bitmaps.get("slider_grey"), xSpeedAct - sliderXoff, ySpeed - sliderYoff, null)
canvas.drawBitmap(bitmaps.get("slider"), xSpeedToBe - sliderXoff, ySpeed - sliderYoff, null)
var xtext = (canvasWidth * (X_LOCO_MID + X_LOCO_RANGE * 0.9f)).toInt()
canvas.drawText(locoSpeed(), xtext.toFloat(), ySpeed + 32, paintText)
xtext = (canvasWidth * (X_LOCO_MID - X_LOCO_RANGE * 0.9f)).toInt()
canvas.drawText(selectedLoco?.shortString(), xtext.toFloat(), ySpeed + 32, paintText)
}
}
private fun sxSpeed(): Float {
if (selectedLoco == null) {
return 0.toFloat()
} else {
val s = selectedLoco?.speed_from_sx
return X_LOCO_RANGE * s?.toFloat()!! / 31.0f + X_LOCO_MID
}
}
private fun speedToBe(): Float {
if (selectedLoco == null) return 0.toFloat()
val s = selectedLoco?.speed_to_be
return X_LOCO_RANGE * s?.toFloat()!! / 31.0f + X_LOCO_MID
}
private fun locoSpeed(): String {
if (selectedLoco == null) return ""
val s = selectedLoco?.speed_from_sx
return "" + s
}
fun checkSpeedMove(xt: Float, yt: Float) {
if (selectedLoco == null) return
// check slider
//if (DEBUG) Log.d(TAG,"check slider touch xt="+xt+" yt="+yt+" xSpeed="+xSpeed+" sliderXoff="+sliderXoff+" ySpeed="+ySpeed+" sliderYoff="+sliderYoff);
if (xt > (X_LOCO_MID - X_LOCO_RANGE) * canvasWidth
&& xt < (X_LOCO_MID + X_LOCO_RANGE) * canvasWidth
&& yt > ySpeed - sliderYoff
&& yt < ySpeed + sliderYoff) {
lastSpeedCheckMove = System.currentTimeMillis()
lastXt = xt
val s = Math.round(31.0f / X_LOCO_RANGE * (xt - X_LOCO_MID * canvasWidth) / canvasWidth)
if (DEBUG) Log.d(TAG, "slider, speed set to be = $s")
selectedLoco?.setSpeed(s) // will be sent only when different to currently known speed.
}
}
/**
* check, if the control area was touched at the Button positions or at the speed slider
*
* @param x
* @param y
*/
fun checkTouch(x: Float, y: Float) {
if (selectedLoco != null) {
if (stopBtn.isTouched(x, y)) {
selectedLoco?.stopLoco()
} else if (lampBtn.isTouched(x, y)) {
selectedLoco?.toggleLocoLamp()
} else if (functionBtn.isTouched(x, y)) {
selectedLoco?.toggleFunc()
} else if (addressBtn.isTouched(x, y)) {
Dialogs.selectLoco()
} else if (leftBtn.isTouched(x, y)) {
selectedLoco?.decrLocoSpeed()
} else if (rightBtn.isTouched(x, y)) {
selectedLoco?.incrLocoSpeed()
}
} else {
if (addressBtn.isTouched(x, y)) {
Dialogs.selectLoco()
}
}
}
fun recalcGeometry() {
stopBtn.recalcXY()
lampBtn.recalcXY()
addressBtn.recalcXY()
functionBtn.recalcXY()
leftBtn.recalcXY()
rightBtn.recalcXY()
ySpeed = (controlAreaRect?.bottom!!.toFloat() - controlAreaRect?.top!!) / 2 // mid of control area range.
}
private fun calcTextSize(w: Int): Float {
// text size = 30 for width=1024
return 30.0f * w / 1024
}
companion object {
private val X_LOCO_MID = 0.5f
private val X_LOCO_RANGE = 0.25f
private var ySpeed = 50f
private var xSpeedAct = 0f
private var xSpeedToBe = 0f
private val ZERO_LINE_HALFLENGTH = 15f //
private var canvasWidth = 100f
private var sxmin = 0
private var sxmax = 0
private var lastSpeedCheckMove = 0L
private var lastXt = X_LOCO_MID
}
}
| gpl-3.0 | 978568b3b370f6333cb02e928e6553b6 | 33.5625 | 159 | 0.587824 | 3.763612 | false | false | false | false |
laurenyew/KotlinSampleApp | WeatherApp/app/src/main/java/laurenyew/weatherapp/data/DayForecastTable.kt | 1 | 310 | package laurenyew.weatherapp.data
/**
* Created by laurenyew on 1/10/18.
*/
object DayForecastTable {
val NAME = "DayForecast"
val ID = "_id"
val DATE = "date"
val DESCRIPTION = "description"
val HIGH = "high"
val LOW = "low"
val ICON_URL = "iconUrl"
val CITY_ID = "cityId"
} | mit | a31906dce5e8cece7c6ad1a696ffc1ac | 19.733333 | 35 | 0.612903 | 3.195876 | false | false | false | false |
androidx/androidx | camera/integration-tests/diagnosetestapp/src/main/java/androidx/camera/integration/diagnose/MainActivity.kt | 3 | 15564 | /*
* 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.camera.integration.diagnose
import android.Manifest
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.util.Size
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.annotation.OptIn
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.video.MediaStoreOutputOptions
import androidx.camera.video.Recording
import androidx.camera.video.VideoRecordEvent
import androidx.camera.view.CameraController
import androidx.camera.view.CameraController.IMAGE_CAPTURE
import androidx.camera.view.CameraController.VIDEO_CAPTURE
import androidx.camera.view.LifecycleCameraController
import androidx.camera.view.PreviewView
import androidx.camera.view.video.AudioConfig
import androidx.camera.view.video.ExperimentalVideo
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.concurrent.ExecutorService
import androidx.camera.mlkit.vision.MlKitAnalyzer
import androidx.camera.view.CameraController.IMAGE_ANALYSIS
import androidx.core.util.Preconditions
import androidx.lifecycle.lifecycleScope
import com.google.android.material.tabs.TabLayout
import com.google.mlkit.vision.barcode.BarcodeScanner
import com.google.mlkit.vision.barcode.BarcodeScanning
import java.io.IOException
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import kotlinx.coroutines.ExecutorCoroutineDispatcher
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@OptIn(ExperimentalVideo::class)
@SuppressLint("NullAnnotationGroup", "MissingPermission")
class MainActivity : AppCompatActivity() {
private lateinit var cameraController: LifecycleCameraController
private lateinit var activeRecording: Recording
private lateinit var previewView: PreviewView
private lateinit var overlayView: OverlayView
private lateinit var executor: Executor
private lateinit var tabLayout: TabLayout
private lateinit var diagnosis: Diagnosis
private lateinit var barcodeScanner: BarcodeScanner
private lateinit var analyzer: MlKitAnalyzer
private lateinit var diagnoseBtn: Button
private lateinit var imageCaptureBtn: Button
private lateinit var videoCaptureBtn: Button
private lateinit var calibrationExecutor: ExecutorService
private var calibrationThreadId: Long = -1
private lateinit var diagnosisDispatcher: ExecutorCoroutineDispatcher
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
previewView = findViewById(R.id.preview_view)
overlayView = findViewById(R.id.overlay_view)
overlayView.visibility = View.INVISIBLE
cameraController = LifecycleCameraController(this)
previewView.controller = cameraController
executor = ContextCompat.getMainExecutor(this)
tabLayout = findViewById(R.id.tabLayout_view)
diagnosis = Diagnosis()
barcodeScanner = BarcodeScanning.getClient()
diagnoseBtn = findViewById(R.id.diagnose_btn)
imageCaptureBtn = findViewById(R.id.image_capture_btn)
imageCaptureBtn.visibility = View.INVISIBLE
videoCaptureBtn = findViewById(R.id.video_capture_btn)
videoCaptureBtn.visibility = View.INVISIBLE
calibrationExecutor = Executors.newSingleThreadExecutor() { runnable ->
val thread = Executors.defaultThreadFactory().newThread(runnable)
thread.name = "CalibrationThread"
calibrationThreadId = thread.id
return@newSingleThreadExecutor thread
}
diagnosisDispatcher = Executors.newFixedThreadPool(1).asCoroutineDispatcher()
// Request CAMERA permission and fail gracefully if not granted.
if (allPermissionsGranted()) {
startCamera()
} else {
ActivityCompat.requestPermissions(
this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS
)
}
// Setting up Tabs
val photoTab = tabLayout.newTab().setText("Photo")
photoTab.view.id = R.id.image_capture
tabLayout.addTab(photoTab)
val videoTab = tabLayout.newTab().setText("Video")
videoTab.view.id = R.id.video_capture
tabLayout.addTab(videoTab)
val diagnoseTab = tabLayout.newTab().setText("Diagnose")
diagnoseTab.view.id = R.id.diagnose
tabLayout.addTab(diagnoseTab)
// Setup UI events
tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab?) {
Log.d(TAG, "tab selected id:${tab?.view?.id}")
selectMode(tab?.view?.id)
}
override fun onTabReselected(tab: TabLayout.Tab?) {
Log.d(TAG, "tab reselected:${tab?.view?.id}")
selectMode(tab?.view?.id)
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
Log.d(TAG, "tab unselected:${tab?.view?.id}")
deselectMode(tab?.view?.id)
}
})
imageCaptureBtn.setOnClickListener {
val name = SimpleDateFormat(FILENAME_FORMAT, Locale.US)
.format(System.currentTimeMillis())
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, name)
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/CameraX-Image")
}
}
// Create output options object which contains file + metadata
val outputOptions = ImageCapture.OutputFileOptions
.Builder(
contentResolver,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
contentValues
)
.build()
// Set up image capture listener, which is triggered after photo has
// been taken
cameraController.takePicture(
outputOptions,
executor,
object : ImageCapture.OnImageSavedCallback {
override fun onError(exc: ImageCaptureException) {
val msg = "Photo capture failed: ${exc.message}"
showToast(msg)
}
override fun onImageSaved(output: ImageCapture.OutputFileResults) {
val msg = "Photo capture succeeded: ${output.savedUri}"
showToast(msg)
}
}
)
}
videoCaptureBtn.setOnClickListener {
// determine whether the onclick is to start recording or stop recording
if (cameraController.isRecording) {
activeRecording.stop()
videoCaptureBtn.setText(R.string.start_video_capture)
val msg = "video stopped recording"
showToast(msg)
} else {
// building file output
val name = SimpleDateFormat(FILENAME_FORMAT, Locale.US)
.format(System.currentTimeMillis())
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, name)
put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4")
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/CameraX-Video")
}
}
val outputOptions = MediaStoreOutputOptions
.Builder(contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
.setContentValues(contentValues)
.build()
Log.d(TAG, "finished composing video name")
val audioConfig = AudioConfig.create(true)
// start recording
try {
activeRecording = cameraController.startRecording(
outputOptions, audioConfig, executor
) { event ->
if (event is VideoRecordEvent.Finalize) {
val uri = event.outputResults.outputUri
if (event.error == VideoRecordEvent.Finalize.ERROR_NONE) {
val msg = "Video record succeeded: $uri"
showToast(msg)
} else {
Log.e(TAG, "Video saving failed: ${event.cause}")
}
}
}
videoCaptureBtn.setText(R.string.stop_video_capture)
val msg = "video recording"
showToast(msg)
} catch (exception: RuntimeException) {
Log.e(TAG, "Video failed to record: " + exception.message)
}
}
}
diagnoseBtn.setOnClickListener {
lifecycleScope.launch {
try {
val reportFile = withContext(diagnosisDispatcher) {
// creating tasks to diagnose
val taskList = mutableListOf<DiagnosisTask>()
taskList.add(CollectDeviceInfoTask())
taskList.add(ImageCaptureTask())
val isAggregated = true
Log.i(TAG, "dispatcher: ${Thread.currentThread().name}")
diagnosis.diagnose(baseContext, taskList, cameraController, isAggregated)
}
val msg: String = if (reportFile != null) {
"Successfully collected diagnosis to ${reportFile.path}"
} else {
"Diagnosis failed: No file"
}
showToast(msg)
} catch (e: IOException) {
val msg = "Failed to collect information"
showToast(msg)
Log.e(TAG, "IOException caught: ${e.message}")
}
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_CODE_PERMISSIONS) {
if (allPermissionsGranted()) {
startCamera()
} else {
val msg = "Permissions not granted by the user"
showToast(msg)
// TODO: fail gracefully
finish()
}
}
}
private fun startCamera() {
// Setup CameraX
cameraController.bindToLifecycle(this)
Log.d(TAG, "started camera")
}
private fun selectMode(id: Int?) {
when (id) {
R.id.image_capture -> photoMode()
R.id.video_capture -> videoMode()
R.id.diagnose -> diagnose()
}
}
private fun deselectMode(id: Int?) {
when (id) {
R.id.image_capture -> imageCaptureBtn.visibility = View.INVISIBLE
R.id.video_capture -> videoCaptureBtn.visibility = View.INVISIBLE
R.id.diagnose -> {
// disable overlay
overlayView.visibility = View.INVISIBLE
// unbind MLKit analyzer
cameraController.clearImageAnalysisAnalyzer()
}
}
}
private fun photoMode() {
cameraController.setEnabledUseCases(IMAGE_CAPTURE)
imageCaptureBtn.visibility = View.VISIBLE
}
private fun videoMode() {
cameraController.setEnabledUseCases(VIDEO_CAPTURE)
videoCaptureBtn.visibility = View.VISIBLE
}
private fun diagnose() {
// enable overlay and diagnose button
overlayView.visibility = View.VISIBLE
// enable image analysis use case
cameraController.setEnabledUseCases(IMAGE_ANALYSIS)
val calibrate = Calibration(
Size(previewView.width, previewView.height))
analyzer = MlKitAnalyzer(
listOf(barcodeScanner),
CameraController.COORDINATE_SYSTEM_VIEW_REFERENCED,
calibrationExecutor
) { result ->
// validating thread
checkCalibrationThread()
val barcodes = result.getValue(barcodeScanner)
if (barcodes != null && barcodes.size > 0) {
calibrate.analyze(barcodes)
// run UI on main thread
lifecycleScope.launch {
// gives overlayView access to Calibration
overlayView.setCalibrationResult(calibrate)
// enable diagnose button when alignment is successful
diagnoseBtn.isEnabled = calibrate.isAligned
overlayView.invalidate()
}
}
}
cameraController.setImageAnalysisAnalyzer(
calibrationExecutor, analyzer)
}
private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
ContextCompat.checkSelfPermission(
baseContext, it
) == PackageManager.PERMISSION_GRANTED
}
private fun checkCalibrationThread() {
Preconditions.checkState(calibrationThreadId == Thread.currentThread().id,
"Not working on Calibration Thread")
}
private fun showToast(msg: String) {
Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
Log.d(TAG, msg)
}
override fun onDestroy() {
super.onDestroy()
calibrationExecutor.shutdown()
diagnosisDispatcher.close()
}
companion object {
private const val TAG = "DiagnoseApp"
private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS"
private const val REQUEST_CODE_PERMISSIONS = 10
private val REQUIRED_PERMISSIONS =
mutableListOf(
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO
).apply {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
}.toTypedArray()
}
} | apache-2.0 | a3bc0187f7e5d7aa22ff4505439b5c89 | 39.115979 | 97 | 0.612824 | 5.251012 | false | false | false | false |
androidx/androidx | room/room-common/src/main/java/androidx/room/AutoMigration.kt | 3 | 4121 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room
import kotlin.reflect.KClass
/**
* Declares an automatic migration on a Database.
*
* An automatic migration is a [androidx.room.migration.Migration] that is generated
* via the use of database schema files at two versions of a [androidx.room.RoomDatabase].
* Room automatically detects changes on the database between these two schemas,
* and constructs a [androidx.room.migration.Migration] to migrate between the
* two versions. In case of ambiguous scenarios (e.g. column/table rename/deletes), additional
* information is required, and can be provided via the
* [androidx.room.migration.AutoMigrationSpec] property.
*
* An auto migration must define the 'from' and 'to' versions of the schema for which a migration
* implementation will be generated. A class that implements AutoMigrationSpec can be declared in
* the [androidx.room.migration.AutoMigrationSpec] property to either
* provide more information for ambiguous scenarios or execute callbacks during the migration.
*
* If there are any column/table renames/deletes between the two versions of the database
* provided then it is said that there are ambiguous scenarios in the migration. In
* such scenarios then an [androidx.room.migration.AutoMigrationSpec] is
* required and the class provided must be annotated with the relevant change annotation(s):
* [RenameColumn], [RenameTable], [DeleteColumn] or [DeleteTable]. When
* no ambiguous scenario is present, then the [androidx.room.migration.AutoMigrationSpec]
* property is optional.
*
* If an auto migration is defined for a database, then [androidx.room.Database.exportSchema]
* must be set to true.
*
* Example:
*
* ```
* @Database(
* version = MusicDatabase.LATEST_VERSION,
* entities = [
* Song.class,
* Artist.class
* ],
* autoMigrations = [
* @AutoMigration (
* from = 1,
* to = 2
* ),
* @AutoMigration (
* from = 2,
* to = 3,
* spec = MusicDatabase.MyExampleAutoMigration::class
* )
* ],
* exportSchema = true
* )
* abstract class MusicDatabase : RoomDatabase() {
* const val LATEST_VERSION = 3
*
* @DeleteTable(deletedTableName = "Album")
* @RenameTable(fromTableName = "Singer", toTableName = "Artist")
* @RenameColumn(
* tableName = "Song",
* fromColumnName = "songName",
* toColumnName = "songTitle"
* )
* @DeleteColumn(fromTableName = "Song", deletedColumnName = "genre")
* class MyExampleAutoMigration : AutoMigrationSpec {
* @Override
* override fun onPostMigrate(db: SupportSQLiteDatabase) {
* // Invoked once auto migration is done
* }
* }
* }
* ```
*
* @see [androidx.room.RoomDatabase]
* @see [androidx.room.migration.AutoMigrationSpec]
*/
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.BINARY)
public annotation class AutoMigration(
/**
* Version of the database schema to migrate from.
*
* @return Version number of the database to migrate from.
*/
val from: Int,
/**
* Version of the database schema to migrate to.
*
* @return Version number of the database to migrate to.
*/
val to: Int,
/**
* User implemented custom auto migration spec.
*
* @return The auto migration specification or none if the user has not implemented a spec
*/
val spec: KClass<*> = Any::class
)
| apache-2.0 | 61931dba34d993908c8ea36e9cfafd59 | 33.923729 | 97 | 0.683572 | 4.183756 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/formatter/settings/ElmCodeStyleSettingsProvider.kt | 1 | 2233 | package org.elm.ide.formatter.settings
import com.intellij.application.options.CodeStyleAbstractConfigurable
import com.intellij.application.options.CodeStyleAbstractPanel
import com.intellij.application.options.IndentOptionsEditor
import com.intellij.application.options.TabbedLanguageCodeStylePanel
import com.intellij.psi.codeStyle.*
import org.elm.lang.core.ElmLanguage
class ElmCodeStyleSettingsProvider : CodeStyleSettingsProvider() {
override fun getConfigurableDisplayName() = ElmLanguage.displayName
override fun createConfigurable(settings: CodeStyleSettings, modelSettings: CodeStyleSettings): CodeStyleConfigurable {
return object : CodeStyleAbstractConfigurable(settings, modelSettings, configurableDisplayName) {
override fun createPanel(settings: CodeStyleSettings): CodeStyleAbstractPanel =
ElmCodeStyleMainPanel(currentSettings, settings)
}
}
private class ElmCodeStyleMainPanel(currentSettings: CodeStyleSettings, settings: CodeStyleSettings) :
TabbedLanguageCodeStylePanel(ElmLanguage, currentSettings, settings) {
override fun initTabs(settings: CodeStyleSettings?) {
addIndentOptionsTab(settings)
}
}
}
class ElmLanguageCodeStyleSettingsProvider : LanguageCodeStyleSettingsProvider() {
override fun getLanguage() = ElmLanguage
// No sample, since we don't have a formatter.
// An empty string causes an NPE, so we use a zero-width space instead.
override fun getCodeSample(settingsType: SettingsType) = "\u200B"
// no setting other than indent yet
override fun customizeSettings(consumer: CodeStyleSettingsCustomizable, settingsType: SettingsType) {}
// If we ever add formatting support, we'll probably want to return a plain
// `SmartIndentOptionsEditor()` rather than this custom one.
override fun getIndentOptionsEditor(): IndentOptionsEditor? = ElmOptionsEditor()
}
private class ElmOptionsEditor : IndentOptionsEditor() {
// Only expose the indent field. Setting this in `customizeSettings` doesn't seem to have an
// effect.
override fun addComponents() {
super.addComponents()
showStandardOptions("INDENT_SIZE")
}
}
| mit | 295b5d184b7f81275cc55374a6f2c512 | 41.132075 | 123 | 0.763547 | 5.27896 | false | true | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/lang/core/psi/elements/ElmFieldAccessorFunctionExpr.kt | 1 | 1405 | package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.ElmAtomTag
import org.elm.lang.core.psi.ElmFunctionCallTargetTag
import org.elm.lang.core.psi.ElmPsiElementImpl
import org.elm.lang.core.psi.ElmTypes
import org.elm.lang.core.resolve.ElmReferenceElement
import org.elm.lang.core.resolve.reference.ElmReference
import org.elm.lang.core.resolve.reference.RecordFieldReference
import org.elm.lang.core.types.Ty
import org.elm.lang.core.types.TyFunction
import org.elm.lang.core.types.findTy
/**
* A function expression that will access a field in a record.
*
* e.g. `.x` in `List.map .x [{x=1}]`
*/
class ElmFieldAccessorFunctionExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmReferenceElement, ElmFunctionCallTargetTag, ElmAtomTag {
/** The name of the field being accessed */
val identifier: PsiElement
get() = findNotNullChildByType(ElmTypes.LOWER_CASE_IDENTIFIER)
override val referenceNameElement: PsiElement
get() = identifier
override val referenceName: String
get() = identifier.text
override fun getReference(): ElmReference {
return object : RecordFieldReference<ElmFieldAccessorFunctionExpr>(this@ElmFieldAccessorFunctionExpr) {
override fun getTy(): Ty? = (element.findTy() as? TyFunction)?.parameters?.singleOrNull()
}
}
}
| mit | b7d2f47a3a063faba6a662c27c31d2eb | 36.972973 | 136 | 0.756584 | 3.902778 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/inspection/overwrite/OverwriteAuthorInspection.kt | 1 | 3017 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.inspection.overwrite
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.javadoc.PsiDocComment
class OverwriteAuthorInspection : OverwriteInspection() {
override fun getStaticDescription() =
"For maintainability reasons, the Sponge project requires @Overwrite methods to declare an @author JavaDoc tag."
override fun visitOverwrite(holder: ProblemsHolder, method: PsiMethod, overwrite: PsiAnnotation) {
val javadoc = method.docComment
if (javadoc == null) {
registerMissingTags(holder, method)
return
}
val authorTag = javadoc.findTagByName("author")
if (authorTag == null) {
registerMissingTag(holder, javadoc, "author")
}
val reasonTag = javadoc.findTagByName("reason")
if (reasonTag == null) {
registerMissingTag(holder, javadoc, "reason")
}
}
private fun registerMissingTag(holder: ProblemsHolder, element: PsiElement, tag: String) {
holder.registerProblem(
element,
"@Overwrite methods must have an associated JavaDoc with a filled in @$tag tag",
QuickFix(tag)
)
}
private fun registerMissingTags(holder: ProblemsHolder, element: PsiElement) {
holder.registerProblem(
element,
"@Overwrite methods must have an associated JavaDoc with filled in @author and @reason tags",
QuickFix()
)
}
private class QuickFix(val tag: String? = null) : LocalQuickFix {
override fun getFamilyName() = "Add missing Javadoc tag"
override fun getName(): String = if (tag == null) "Add all missing Javadoc tags" else "Add @$tag Javadoc tag"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
val method = element as? PsiMethod ?: (element as PsiDocComment).owner as PsiMethod
val javadoc = method.docComment
if (javadoc == null) {
// Create new Javadoc comment
method.addBefore(
JavaPsiFacade.getElementFactory(project)
.createDocCommentFromText("/**\n * @author \n * @reason \n */"),
method.modifierList
)
return
}
// Create new Javadoc tag
val tag = JavaPsiFacade.getElementFactory(project).createDocTagFromText("@$tag")
javadoc.addAfter(tag, null)
}
}
}
| mit | 2fdbbe404efdcb422357e92dd014bbc8 | 33.284091 | 120 | 0.644349 | 5.028333 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/account/MyAccountBuilder.kt | 1 | 14154 | /*
* Copyright (C) 2010-2019 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.account
import android.accounts.Account
import io.vavr.control.Try
import org.andstatus.app.R
import org.andstatus.app.context.MyContext
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.data.DataUpdater
import org.andstatus.app.data.converter.DatabaseConverterController
import org.andstatus.app.net.http.ConnectionException
import org.andstatus.app.net.http.StatusCode
import org.andstatus.app.net.social.Actor
import org.andstatus.app.net.social.Connection
import org.andstatus.app.origin.Origin
import org.andstatus.app.origin.OriginConfig
import org.andstatus.app.timeline.meta.TimelineSaver
import org.andstatus.app.util.JsonUtils
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.StringUtil
import org.andstatus.app.util.Taggable
import org.andstatus.app.util.TaggedInstance
import org.andstatus.app.util.TriState
/** Companion class used to load/create/change/delete [MyAccount]'s data */
class MyAccountBuilder private constructor(
myAccountIn: MyAccount,
taggedInstance: TaggedInstance = TaggedInstance(MyAccountBuilder::class)
) : Taggable by taggedInstance {
var myAccount = myAccountIn
private set
private fun fixInconsistenciesWithChangedEnvironmentSilently() {
var changed = false
if (isPersistent() && myAccount.actor.actorId == 0L) {
changed = true
assignActorId()
MyLog.i(
this, "MyAccount '" + myAccount.getAccountName()
+ "' was not connected to the Actor table. actorId=" + myAccount.actor.actorId
)
}
if (!myAccount.getCredentialsPresent()
&& myAccount.credentialsVerified == CredentialsVerificationStatus.SUCCEEDED
) {
MyLog.i(this, "Account's credentials were lost?! Fixing...")
setCredentialsVerificationStatus(CredentialsVerificationStatus.NEVER)
changed = true
}
if (changed && isPersistent()) {
saveSilently()
}
}
private fun logLoadResult(method: String?) {
if (myAccount.isValid) {
MyLog.v(this) { "$method Loaded $this" }
} else {
MyLog.i(this, "$method Load failed: Invalid account; $this \n${MyLog.currentStackTrace}")
}
}
fun setOrigin(origin: Origin) {
rebuildMyAccount(origin, getUniqueName())
}
fun setUniqueName(uniqueName: String) {
rebuildMyAccount(myAccount.origin, uniqueName)
}
fun setOAuth(isOauthBoolean: Boolean): MyAccountBuilder {
val isOauth = if (isOauthBoolean == myAccount.origin.isOAuthDefault()) TriState.UNKNOWN
else TriState.fromBoolean(isOauthBoolean)
myAccount.setOAuth(isOauth)
return this
}
fun rebuildMyAccount(myContext: MyContext) {
rebuildMyAccount(myContext.origins.fromName(myAccount.origin.name), getUniqueName())
}
private fun rebuildMyAccount(origin: Origin, uniqueName: String) {
rebuildMyAccount(AccountName.fromOriginAndUniqueName(origin, uniqueName))
}
fun rebuildMyAccount(accountName: AccountName) {
val ma = myAccount.myContext.accounts.fromAccountName(accountName.name)
myAccount = if (ma.isValid) ma else MyAccount(myAccount.data.withAccountName(accountName))
}
fun getOrigin(): Origin {
return myAccount.origin
}
fun getUniqueName(): String {
return myAccount.getOAccountName().getUniqueName()
}
fun getPassword(): String {
return myAccount.getPassword()
}
fun isOAuth(): Boolean {
return myAccount.isOAuth()
}
/**
* @return Is this object persistent
*/
fun isPersistent(): Boolean {
return myAccount.isPersistent()
}
/**
* Delete all Account's data
* @return true = success
*/
fun deleteData(): Boolean {
setAndroidAccountDeleted()
return true
}
private fun setAndroidAccountDeleted() {
myAccount.data.setDataBoolean(MyAccount.KEY_DELETED, true)
}
fun setSyncedAutomatically(syncedAutomatically: Boolean) {
myAccount.isSyncedAutomatically = syncedAutomatically
}
fun setOrder(order: Int) {
myAccount.order = order
}
fun save() {
if (saveSilently().getOrElse(false) && myAccount.myContext.isReady) {
MyPreferences.onPreferencesChanged()
}
}
/** Save this MyAccount to AccountManager */
fun saveSilently(): Try<Boolean> {
return if (myAccount.isValid) {
myAccount.getNewOrExistingAndroidAccount()
.onSuccess { account: Account -> myAccount.data.updateFrom(myAccount) }
.flatMap { account: Account -> myAccount.data.saveIfChanged(account) }
.onFailure { e: Throwable -> myAccount.data.setPersistent(false) }
.onSuccess { result1: Boolean ->
MyLog.v(this) {
(if (result1) " Saved " else " Didn't change ") +
this.toString()
}
myAccount.myContext.accounts.addIfAbsent(myAccount)
if (myAccount.myContext.isReady && !myAccount.hasAnyTimelines()) {
TimelineSaver().setAddDefaults(true).setAccount(myAccount).execute(myAccount.myContext)
}
}
.onFailure { e: Throwable ->
MyLog.v(this) {
"Failed to save " + this.toString() +
"; Error: " + e.message
}
}
} else {
MyLog.v(this) { "Didn't save invalid account: $myAccount" }
Try.failure(Exception())
}
}
fun getOriginConfig(): Try<MyAccountBuilder> {
return getConnection().getConfig().map { config: OriginConfig ->
if (config.nonEmpty) {
val originBuilder = Origin.Builder(myAccount.origin)
originBuilder.save(config)
MyLog.v(this, "Get Origin config succeeded $config")
}
this
}
}
fun onCredentialsVerified(actor: Actor): Try<MyAccountBuilder> {
var ok = actor.nonEmpty && !actor.oid.isEmpty() && actor.isUsernameValid()
val errorSettingUsername = !ok
var credentialsOfOtherAccount = false
// We are comparing usernames ignoring case, but we fix correct case
// as the Originating system tells us.
if (ok && myAccount.username.isNotEmpty()
&& myAccount.data.accountName.username.compareTo(actor.getUsername(), ignoreCase = true) != 0) {
// Credentials belong to other Account ??
ok = false
credentialsOfOtherAccount = true
}
if (ok) {
setCredentialsVerificationStatus(CredentialsVerificationStatus.SUCCEEDED)
actor.lookupActorId()
actor.lookupUser()
actor.user.isMyUser = TriState.TRUE
actor.setUpdatedDate(MyLog.uniqueCurrentTimeMS)
myAccount.actor = actor
if (DatabaseConverterController.isUpgrading()) {
MyLog.v(this, "Upgrade in progress")
myAccount.actor.actorId = myAccount.data.getDataLong(MyAccount.KEY_ACTOR_ID, myAccount.actor.actorId)
} else {
DataUpdater(myAccount).onActivity(actor.update(actor))
}
if (!isPersistent()) {
// Now we know the name (or proper case of the name) of this Account!
val sameName = myAccount.data.accountName.getUniqueName() == actor.uniqueName
if (!sameName) {
MyLog.i(
this, "name changed from " + myAccount.data.accountName.getUniqueName() +
" to " + actor.uniqueName
)
myAccount.data.updateFrom(myAccount)
val newData = myAccount.data.withAccountName(
AccountName.fromOriginAndUniqueName(myAccount.origin, actor.uniqueName)
)
myAccount = loadFromAccountData(newData, "onCredentialsVerified").myAccount
}
save()
}
}
if (!ok || !myAccount.getCredentialsPresent()) {
setCredentialsVerificationStatus(CredentialsVerificationStatus.FAILED)
}
save()
if (credentialsOfOtherAccount) {
MyLog.w(
this, myAccount.myContext.context.getText(R.string.error_credentials_of_other_user).toString() + ": " +
actor.getUniqueNameWithOrigin() +
" account name: " + myAccount.getAccountName() +
" vs username: " + actor.getUsername()
)
return Try.failure(
ConnectionException(
StatusCode.CREDENTIALS_OF_OTHER_ACCOUNT,
actor.getUniqueNameWithOrigin()
)
)
}
if (errorSettingUsername) {
val msg = myAccount.myContext.context.getText(R.string.error_set_username).toString() + " " + actor.getUsername()
MyLog.w(this, msg)
return Try.failure(ConnectionException(StatusCode.AUTHENTICATION_ERROR, msg))
}
return Try.success(this)
}
fun setUserTokenWithSecret(token: String?, secret: String?) {
getConnection().setUserTokenWithSecret(token, secret)
}
fun setCredentialsVerificationStatus(cv: CredentialsVerificationStatus) {
myAccount.credentialsVerified = cv
if (cv != CredentialsVerificationStatus.SUCCEEDED) {
getConnection().clearAuthInformation()
}
}
fun registerClient(): Try<Unit> {
MyLog.v(this) { "Registering client application for " + myAccount.username }
myAccount.setConnection()
return getConnection().registerClientForAccount()
}
fun getConnection(): Connection {
return if (myAccount.connection.isEmpty)
Connection.fromOrigin(myAccount.origin, TriState.fromBoolean(isOAuth()))
else myAccount.connection
}
fun setPassword(password: String?) {
if (StringUtil.notEmpty(password, "").compareTo(getConnection().getPassword()) != 0) {
setCredentialsVerificationStatus(CredentialsVerificationStatus.NEVER)
getConnection().setPassword(password)
}
}
private fun assignActorId() {
myAccount.actor.actorId = myAccount.origin.usernameToId(myAccount.username)
if (myAccount.actor.actorId == 0L) {
try {
DataUpdater(myAccount).onActivity(myAccount.actor.update(myAccount.actor))
} catch (e: Exception) {
MyLog.e(this, "assignUserId to $myAccount", e)
}
}
}
override fun toString(): String {
return myAccount.toString()
}
fun clearClientKeys() {
myAccount.connection.clearClientKeys()
}
fun setSyncFrequencySeconds(syncFrequencySeconds: Long) {
myAccount.syncFrequencySeconds = syncFrequencySeconds
}
fun toJsonString(): String = myAccount.toJson().toString()
companion object {
val EMPTY = MyAccountBuilder(MyAccount.EMPTY)
/**
* If MyAccount with this name didn't exist yet, new temporary MyAccount will be created.
*/
fun fromAccountName(accountName: AccountName): MyAccountBuilder {
return fromMyAccount(myAccountFromName(accountName))
}
/**
* If MyAccount with this name didn't exist yet, new temporary MyAccount will be created.
*/
private fun myAccountFromName(accountName: AccountName): MyAccount {
if (accountName.myContext.isEmpty) return MyAccount.EMPTY
val persistentAccount = accountName.myContext.accounts.fromAccountName(accountName)
return if (persistentAccount.isValid) persistentAccount else MyAccount(accountName)
}
/** Loads existing account from Persistence */
fun loadFromAndroidAccount(myContext: MyContext, account: Account): MyAccountBuilder {
return loadFromAccountData(AccountData.fromAndroidAccount(myContext, account), "fromAndroidAccount")
}
fun fromJsonString(myContext: MyContext, jsonString: String?): MyAccountBuilder =
JsonUtils.toJsonObject(jsonString)
.map { jso ->
if (myContext.isEmpty) EMPTY
else AccountData.fromJson(myContext, jso, false)
.let { loadFromAccountData(it, "") }
}.getOrElse(EMPTY)
fun loadFromAccountData(accountData: AccountData, method: String?): MyAccountBuilder {
val myAccount = MyAccount(accountData)
val builder = fromMyAccount(myAccount)
if (! MyContextHolder.myContextHolder.isOnRestore()) builder.fixInconsistenciesWithChangedEnvironmentSilently()
builder.logLoadResult(method)
return builder
}
fun fromMyAccount(ma: MyAccount): MyAccountBuilder {
return MyAccountBuilder(ma)
}
}
}
| apache-2.0 | 8d10f3f75e9f55dbace2894f931029a4 | 37.884615 | 125 | 0.618765 | 5.010265 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | tools/src/main/kotlin/csense/android/tools/tracker/ActivityTracker.kt | 1 | 2182 | @file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate")
package csense.android.tools.tracker
import android.app.*
import android.os.*
import com.commonsense.android.kotlin.system.base.interfaceBases.*
import csense.android.tools.tracker.ActivityTrackerEvents.*
/**
* A tracker for tracking activity events, and recording those.
*
*/
class ActivityTracker(val application: Application) : BaseActivityLifecycleCallbacks {
private val eventList: MutableList<ActivityTrackerEvents> = mutableListOf()
override fun onActivityResumed(activity: Activity?) {
val lastEvent = eventList.lastOrNull()
if (activity == null || lastEvent == null) {
return
}
if (lastEvent.data.activityName == activity::class.java.simpleName
&& lastEvent is Stops) {
eventList.add(ReturnsTo(activity.getTrackingData()))
}
}
override fun onActivityDestroyed(activity: Activity?) {
val act = activity ?: return
eventList.add(Closes(act.getTrackingData()))
}
override fun onActivityStopped(activity: Activity?) {
val act = activity ?: return
eventList.add(Stops(act.getTrackingData()))
}
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
val act = activity ?: return
eventList.add(GoesTo(act.getTrackingData()))
}
fun register() = application.registerActivityLifecycleCallbacks(this)
fun deregister() = application.unregisterActivityLifecycleCallbacks(this)
}
sealed class ActivityTrackerEvents(val data: ActivityTrackingData) {
class GoesTo(data: ActivityTrackingData) : ActivityTrackerEvents(data)
class ReturnsTo(data: ActivityTrackingData) : ActivityTrackerEvents(data)
class Closes(data: ActivityTrackingData) : ActivityTrackerEvents(data)
class Stops(data: ActivityTrackingData) : ActivityTrackerEvents(data)
}
data class ActivityTrackingData(
val activityName: String,
val eventAtNanoTime: Long)
fun Activity.getTrackingData(): ActivityTrackingData {
return ActivityTrackingData(this::class.java.simpleName, System.nanoTime())
} | mit | 63817f7df53ca982648267ff01fb36db | 32.584615 | 86 | 0.721815 | 4.774617 | false | false | false | false |
bazelbuild/rules_kotlin | src/main/kotlin/io/bazel/kotlin/plugin/jdeps/JdepsGenExtension.kt | 1 | 15144 | package io.bazel.kotlin.plugin.jdeps
import com.google.devtools.build.lib.view.proto.Deps
import com.intellij.mock.MockProject
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import io.bazel.kotlin.builder.utils.jars.JarOwner
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.container.StorageComponentContainer
import org.jetbrains.kotlin.container.useInstance
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.ParameterDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaPropertyDescriptor
import org.jetbrains.kotlin.load.java.sources.JavaSourceElement
import org.jetbrains.kotlin.load.java.structure.impl.classFiles.BinaryJavaClass
import org.jetbrains.kotlin.load.java.structure.impl.classFiles.BinaryJavaField
import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinarySourceElement
import org.jetbrains.kotlin.load.kotlin.VirtualFileKotlinClass
import org.jetbrains.kotlin.load.kotlin.getContainingKotlinJvmBinaryClass
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.FunctionImportedFromObject
import org.jetbrains.kotlin.resolve.PropertyImportedFromObject
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject
import org.jetbrains.kotlin.resolve.checkers.DeclarationChecker
import org.jetbrains.kotlin.resolve.checkers.DeclarationCheckerContext
import org.jetbrains.kotlin.resolve.jvm.extensions.AnalysisHandlerExtension
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.types.typeUtil.supertypes
import java.io.BufferedOutputStream
import java.io.File
import java.nio.file.Paths
/**
* Kotlin compiler extension that tracks classes (and corresponding classpath jars) needed to
* compile current kotlin target. Tracked data should include all classes whose changes could
* affect target's compilation out : direct class dependencies (i.e. external classes directly
* used), but also their superclass, interfaces, etc.
* The primary use of this extension is to improve Kotlin module compilation avoidance in build
* systems (like Buck).
*
* Tracking of classes and their ancestors is done via modules and class
* descriptors that got generated during analysis/resolve phase of Kotlin compilation.
*
* Note: annotation processors dependencies may need to be tracked separately (and may not need
* per-class ABI change tracking)
*
* @param project the current compilation project
* @param configuration the current compilation configuration
*/
class JdepsGenExtension(
val project: MockProject,
val configuration: CompilerConfiguration,
) :
AnalysisHandlerExtension, StorageComponentContainerContributor {
companion object {
/**
* Returns the path of the jar archive file corresponding to the provided descriptor.
*
* @descriptor the descriptor, typically obtained from compilation analyze phase
* @return the path corresponding to the JAR where this class was loaded from, or null.
*/
fun getClassCanonicalPath(descriptor: DeclarationDescriptorWithSource): String? {
return when (val sourceElement: SourceElement = descriptor.source) {
is JavaSourceElement ->
if (sourceElement.javaElement is BinaryJavaClass) {
(sourceElement.javaElement as BinaryJavaClass).virtualFile.canonicalPath
} else if (sourceElement.javaElement is BinaryJavaField) {
val containingClass = (sourceElement.javaElement as BinaryJavaField).containingClass
if (containingClass is BinaryJavaClass) {
containingClass.virtualFile.canonicalPath
} else {
null
}
} else {
// Ignore Java source local to this module.
null
}
is KotlinJvmBinarySourceElement ->
(sourceElement.binaryClass as VirtualFileKotlinClass).file.canonicalPath
else -> null
}
}
fun getClassCanonicalPath(typeConstructor: TypeConstructor): String? {
return (typeConstructor.declarationDescriptor as? DeclarationDescriptorWithSource)?.let {
getClassCanonicalPath(
it,
)
}
}
}
private val explicitClassesCanonicalPaths = mutableSetOf<String>()
private val implicitClassesCanonicalPaths = mutableSetOf<String>()
override fun registerModuleComponents(
container: StorageComponentContainer,
platform: TargetPlatform,
moduleDescriptor: ModuleDescriptor,
) {
container.useInstance(
ClasspathCollectingChecker(explicitClassesCanonicalPaths, implicitClassesCanonicalPaths),
)
}
class ClasspathCollectingChecker(
private val explicitClassesCanonicalPaths: MutableSet<String>,
private val implicitClassesCanonicalPaths: MutableSet<String>,
) : CallChecker, DeclarationChecker {
override fun check(
resolvedCall: ResolvedCall<*>,
reportOn: PsiElement,
context: CallCheckerContext,
) {
when (val resultingDescriptor = resolvedCall.resultingDescriptor) {
is FunctionImportedFromObject -> {
collectTypeReferences(resultingDescriptor.containingObject.defaultType)
}
is PropertyImportedFromObject -> {
collectTypeReferences(resultingDescriptor.containingObject.defaultType)
}
is JavaMethodDescriptor -> {
getClassCanonicalPath(
(resultingDescriptor.containingDeclaration as ClassDescriptor).typeConstructor,
)?.let { explicitClassesCanonicalPaths.add(it) }
}
is FunctionDescriptor -> {
resultingDescriptor.returnType?.let { addImplicitDep(it) }
resultingDescriptor.valueParameters.forEach { valueParameter ->
collectTypeReferences(valueParameter.type, isExplicit = false)
}
val virtualFileClass =
resultingDescriptor.getContainingKotlinJvmBinaryClass() as? VirtualFileKotlinClass
?: return
explicitClassesCanonicalPaths.add(virtualFileClass.file.path)
}
is ParameterDescriptor -> {
getClassCanonicalPath(resultingDescriptor)?.let { explicitClassesCanonicalPaths.add(it) }
}
is FakeCallableDescriptorForObject -> {
collectTypeReferences(resultingDescriptor.type)
}
is JavaPropertyDescriptor -> {
getClassCanonicalPath(resultingDescriptor)?.let { explicitClassesCanonicalPaths.add(it) }
}
is PropertyDescriptor -> {
when (resultingDescriptor.containingDeclaration) {
is ClassDescriptor -> collectTypeReferences(
(resultingDescriptor.containingDeclaration as ClassDescriptor).defaultType,
)
else -> {
val virtualFileClass =
(resultingDescriptor).getContainingKotlinJvmBinaryClass() as? VirtualFileKotlinClass
?: return
explicitClassesCanonicalPaths.add(virtualFileClass.file.path)
}
}
addImplicitDep(resultingDescriptor.type)
}
else -> return
}
}
override fun check(
declaration: KtDeclaration,
descriptor: DeclarationDescriptor,
context: DeclarationCheckerContext,
) {
when (descriptor) {
is ClassDescriptor -> {
descriptor.typeConstructor.supertypes.forEach {
collectTypeReferences(it)
}
}
is FunctionDescriptor -> {
descriptor.returnType?.let { collectTypeReferences(it) }
descriptor.valueParameters.forEach { valueParameter ->
collectTypeReferences(valueParameter.type)
}
descriptor.annotations.forEach { annotation ->
collectTypeReferences(annotation.type)
}
descriptor.extensionReceiverParameter?.value?.type?.let {
collectTypeReferences(it)
}
}
is PropertyDescriptor -> {
collectTypeReferences(descriptor.type)
descriptor.annotations.forEach { annotation ->
collectTypeReferences(annotation.type)
}
descriptor.backingField?.annotations?.forEach { annotation ->
collectTypeReferences(annotation.type)
}
}
is LocalVariableDescriptor -> {
collectTypeReferences(descriptor.type)
}
}
}
private fun addImplicitDep(it: KotlinType) {
getClassCanonicalPath(it.constructor)?.let { implicitClassesCanonicalPaths.add(it) }
}
private fun addExplicitDep(it: KotlinType) {
getClassCanonicalPath(it.constructor)?.let { explicitClassesCanonicalPaths.add(it) }
}
/**
* Records direct and indirect references for a given type. Direct references are explicitly
* used in the code, e.g: a type declaration or a generic type declaration. Indirect references
* are other types required for compilation such as supertypes and interfaces of those explicit
* types.
*/
private fun collectTypeReferences(
kotlinType: KotlinType,
isExplicit: Boolean = true,
) {
if (isExplicit) {
addExplicitDep(kotlinType)
} else {
addImplicitDep(kotlinType)
}
kotlinType.supertypes().forEach {
addImplicitDep(it)
}
collectTypeArguments(kotlinType, isExplicit)
}
private fun collectTypeArguments(
kotlinType: KotlinType,
isExplicit: Boolean,
visitedKotlinTypes: MutableSet<KotlinType> = mutableSetOf(),
) {
visitedKotlinTypes.add(kotlinType)
kotlinType.arguments.map { it.type }.forEach { typeArgument ->
if (isExplicit) {
addExplicitDep(typeArgument)
} else {
addImplicitDep(typeArgument)
}
typeArgument.supertypes().forEach { addImplicitDep(it) }
if (!visitedKotlinTypes.contains(typeArgument)) {
collectTypeArguments(typeArgument, isExplicit, visitedKotlinTypes)
}
}
}
}
override fun analysisCompleted(
project: Project,
module: ModuleDescriptor,
bindingTrace: BindingTrace,
files: Collection<KtFile>,
): AnalysisResult? {
val directDeps = configuration.getList(JdepsGenConfigurationKeys.DIRECT_DEPENDENCIES)
val targetLabel = configuration.getNotNull(JdepsGenConfigurationKeys.TARGET_LABEL)
val explicitDeps = createDepsMap(explicitClassesCanonicalPaths)
doWriteJdeps(directDeps, targetLabel, explicitDeps)
doStrictDeps(configuration, targetLabel, directDeps, explicitDeps)
return super.analysisCompleted(project, module, bindingTrace, files)
}
/**
* Returns a map of jars to classes loaded from those jars.
*/
private fun createDepsMap(classes: Set<String>): Map<String, List<String>> {
val jarsToClasses = mutableMapOf<String, MutableList<String>>()
classes.forEach {
val parts = it.split("!/")
val jarPath = parts[0]
if (jarPath.endsWith(".jar")) {
jarsToClasses.computeIfAbsent(jarPath) { ArrayList() }.add(parts[1])
}
}
return jarsToClasses
}
private fun doWriteJdeps(
directDeps: MutableList<String>,
targetLabel: String,
explicitDeps: Map<String, List<String>>,
) {
val implicitDeps = createDepsMap(implicitClassesCanonicalPaths)
// Build and write out deps.proto
val jdepsOutput = configuration.getNotNull(JdepsGenConfigurationKeys.OUTPUT_JDEPS)
val rootBuilder = Deps.Dependencies.newBuilder()
rootBuilder.success = true
rootBuilder.ruleLabel = targetLabel
val unusedDeps = directDeps.subtract(explicitDeps.keys)
unusedDeps.forEach { jarPath ->
val dependency = Deps.Dependency.newBuilder()
dependency.kind = Deps.Dependency.Kind.UNUSED
dependency.path = jarPath
rootBuilder.addDependency(dependency)
}
explicitDeps.forEach { (jarPath, _) ->
val dependency = Deps.Dependency.newBuilder()
dependency.kind = Deps.Dependency.Kind.EXPLICIT
dependency.path = jarPath
rootBuilder.addDependency(dependency)
}
implicitDeps.keys.subtract(explicitDeps.keys).forEach {
val dependency = Deps.Dependency.newBuilder()
dependency.kind = Deps.Dependency.Kind.IMPLICIT
dependency.path = it
rootBuilder.addDependency(dependency)
}
BufferedOutputStream(File(jdepsOutput).outputStream()).use {
it.write(rootBuilder.build().toByteArray())
}
}
private fun doStrictDeps(
compilerConfiguration: CompilerConfiguration,
targetLabel: String,
directDeps: MutableList<String>,
explicitDeps: Map<String, List<String>>,
) {
when (compilerConfiguration.getNotNull(JdepsGenConfigurationKeys.STRICT_KOTLIN_DEPS)) {
"warn" -> checkStrictDeps(explicitDeps, directDeps, targetLabel)
"error" -> {
if (checkStrictDeps(explicitDeps, directDeps, targetLabel)) {
error(
"Strict Deps Violations - please fix",
)
}
}
}
}
/**
* Prints strict deps warnings and returns true if violations were found.
*/
private fun checkStrictDeps(
result: Map<String, List<String>>,
directDeps: List<String>,
targetLabel: String,
): Boolean {
val missingStrictDeps = result.keys
.filter { !directDeps.contains(it) }
.map { JarOwner.readJarOwnerFromManifest(Paths.get(it)) }
if (missingStrictDeps.isNotEmpty()) {
val missingStrictLabels = missingStrictDeps.mapNotNull { it.label }
val open = "\u001b[35m\u001b[1m"
val close = "\u001b[0m"
var command =
"""
$open ** Please add the following dependencies:$close
${
missingStrictDeps.map { it.label ?: it.jar }.joinToString(" ")
} to $targetLabel
"""
if (missingStrictLabels.isNotEmpty()) {
command += """$open ** You can use the following buildozer command:$close
buildozer 'add deps ${
missingStrictLabels.joinToString(" ")
}' $targetLabel
"""
}
println(command.trimIndent())
return true
}
return false
}
}
| apache-2.0 | 0ada8064349faddb6e119dc9f974907d | 36.578164 | 100 | 0.712625 | 5.105866 | false | false | false | false |
collaction/freehkkai-android | app/src/main/java/hk/collaction/freehkkai/ui/main/MainFragment.kt | 1 | 10834 | package hk.collaction.freehkkai.ui.main
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Bitmap
import android.os.Bundle
import android.speech.RecognizerIntent
import android.speech.tts.TextToSpeech
import android.text.Editable
import android.text.TextWatcher
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.res.ResourcesCompat
import androidx.preference.PreferenceManager
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.list.listItemsSingleChoice
import com.github.javiersantos.appupdater.AppUpdater
import com.github.javiersantos.appupdater.enums.Display
import hk.collaction.freehkkai.BuildConfig
import hk.collaction.freehkkai.databinding.FragmentMainBinding
import hk.collaction.freehkkai.ui.base.BaseFragment
import hk.collaction.freehkkai.ui.settings.SettingsActivity
import hk.collaction.freehkkai.util.Utils.PREF_FONT_VERSION
import hk.collaction.freehkkai.util.Utils.PREF_FONT_VERSION_ALERT
import hk.collaction.freehkkai.util.Utils.getBitmapFromView
import hk.collaction.freehkkai.util.Utils.getCurrentFontName
import hk.collaction.freehkkai.util.Utils.getFontID
import hk.collaction.freehkkai.util.Utils.saveImage
import hk.collaction.freehkkai.util.Utils.snackbar
import hk.collaction.freehkkai.util.ext.px2sp
import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEvent
import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEventListener
import java.util.Locale
/**
* @author Himphen
*/
class MainFragment : BaseFragment<FragmentMainBinding>() {
override fun getViewBinding(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = FragmentMainBinding.inflate(inflater, container, false)
private val sizeChange = 8
private lateinit var sharedPreferences: SharedPreferences
private lateinit var tts: TextToSpeech
private var isFirst = true
private var isTTSReady = false
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
AppUpdater(context)
.showEvery(4)
.setDisplay(Display.NOTIFICATION)
.start()
updateFontPath()
tts = TextToSpeech(context) { status -> isTTSReady = status == TextToSpeech.SUCCESS }
viewBinding?.inputEt?.addTextChangedListener(object : TextWatcher {
override fun onTextChanged(cs: CharSequence, arg1: Int, arg2: Int, arg3: Int) {}
override fun beforeTextChanged(s: CharSequence, arg1: Int, arg2: Int, arg3: Int) {}
override fun afterTextChanged(s: Editable) {
viewBinding?.resultTv?.text = s.toString()
}
})
activity?.let { activity ->
KeyboardVisibilityEvent.setEventListener(
activity,
viewLifecycleOwner,
object : KeyboardVisibilityEventListener {
override fun onVisibilityChanged(isOpen: Boolean) {
if (activity.isFinishing) return
viewBinding?.buttonContainer?.visibility = when {
isOpen -> View.GONE
else -> View.VISIBLE
}
}
}
)
}
if (BuildConfig.IS_BETA) {
viewBinding?.resultTv?.text = "(測試人員版本)\n" + viewBinding?.resultTv?.text
}
viewBinding?.scrollView?.setOnClickListener {
hideKeyboard()
}
viewBinding?.fontSizeToggleBtn?.setOnClickListener {
when (viewBinding?.fontSizeContainer?.visibility) {
View.VISIBLE -> viewBinding?.fontSizeContainer?.visibility = View.GONE
else -> viewBinding?.fontSizeContainer?.visibility = View.VISIBLE
}
}
viewBinding?.fontSizeIncreaseBtn?.setOnClickListener {
viewBinding?.let { viewBinding ->
val size = viewBinding.resultTv.textSize.px2sp()
if (size < 200) {
viewBinding.resultTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, size + sizeChange)
}
}
}
viewBinding?.fontSizeDecreaseBtn?.setOnClickListener {
viewBinding?.let { viewBinding ->
val size = viewBinding.resultTv.textSize.px2sp()
if (size > 16) {
viewBinding.resultTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, size - sizeChange)
}
}
}
viewBinding?.screenCapBtn?.setOnClickListener {
onClickScreenCap()
}
viewBinding?.speechToTextBtn?.setOnClickListener {
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
intent.putExtra(
RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
)
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "zh-HK")
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10)
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "請說出你的句子")
try {
ttsLauncher.launch(intent)
} catch (a: ActivityNotFoundException) {
Toast.makeText(context, "此設備不支援語音轉文字輸入", Toast.LENGTH_SHORT).show()
}
}
viewBinding?.helpBtn?.setOnClickListener {
onClickHelp()
}
viewBinding?.ttsBtn?.setOnClickListener {
onClickTTS()
}
}
override fun onPause() {
super.onPause()
if (tts.isSpeaking) {
tts.stop()
}
}
private fun onClickScreenCap() {
hideKeyboard()
activity?.let { activity ->
viewBinding?.llView?.let { llView ->
try {
snackbar(view, "截圖中⋯⋯")?.show()
// Capture the layout rather then over screen
// context.getWindow().getDecorView().getRootView();
getBitmapFromView(activity, llView) { bitmap ->
onGotScreenBitmap(bitmap)
}
} catch (e: Exception) {
e.printStackTrace()
Toast.makeText(context, "此設備無法截圖,請報告此問題讓我們改進。", Toast.LENGTH_LONG).show()
}
}
}
}
private fun onGotScreenBitmap(bitmap: Bitmap) {
context?.let { context ->
val uri = saveImage(context, bitmap)
val intent = Intent(Intent.ACTION_SEND).apply {
type = "image/jpeg"
putExtra(Intent.EXTRA_STREAM, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
startActivity(Intent.createChooser(intent, "選擇程式"))
}
}
private fun onClickHelp() {
hideKeyboard()
context?.let { context ->
settingLauncher.launch(Intent(context, SettingsActivity::class.java))
}
}
private fun onClickTTS() {
if (isTTSReady) {
val yueHKLocale = Locale("yue", "HK")
if (tts.isLanguageAvailable(yueHKLocale) != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
snackbar(view, "請先安裝 Google 廣東話(香港)文字轉語音檔案。")?.show()
val installIntent = Intent()
installIntent.action = TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA
startActivity(installIntent)
} else {
tts.language = yueHKLocale
tts.speak(viewBinding?.resultTv?.text, TextToSpeech.QUEUE_FLUSH, null, null)
}
} else {
snackbar(view, "此設備不支援文字轉語音輸出")?.show()
}
}
private fun hideKeyboard() {
activity?.let { activity ->
val inputManager =
activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(
activity.currentFocus?.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS
)
}
}
private fun updateFontPath() {
context?.let { context ->
val fontVersion = sharedPreferences.getString(PREF_FONT_VERSION, "4700")
viewBinding?.resultTv?.typeface =
ResourcesCompat.getFont(context, getFontID(fontVersion))
val fontName: String = getCurrentFontName(context, fontVersion)
val isShowAlert = sharedPreferences.getBoolean(PREF_FONT_VERSION_ALERT, true)
if (isShowAlert) {
snackbar(view, "你正在使用$fontName")?.setAction("設定") { onClickHelp() }?.show()
}
}
}
private val ttsLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult
context?.let { context ->
val ttsResult = result.data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
MaterialDialog(context)
.title(text = "請選擇句子")
.listItemsSingleChoice(
items = ttsResult,
waitForPositiveButton = false
) { dialog, _, text ->
if (isFirst) {
isFirst = false
viewBinding?.inputEt?.setText(text.toString())
} else {
viewBinding?.inputEt?.setText(viewBinding?.inputEt?.text?.toString() + " " + text.toString())
}
dialog.dismiss()
}
.negativeButton(text = "取消")
.show()
}
}
private val settingLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult
updateFontPath()
}
} | gpl-3.0 | 2ebca749c7172b1dddc2369c97396e27 | 37.096774 | 121 | 0.612345 | 4.84412 | false | false | false | false |
mike-neck/kuickcheck | core/src/main/kotlin/org/mikeneck/kuickcheck/generator/collection/ListGenerator.kt | 1 | 1482 | /*
* Copyright 2016 Shinya Mochida
*
* Licensed under the Apache License,Version2.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.mikeneck.kuickcheck.generator.collection
import org.mikeneck.kuickcheck.Generator
import org.mikeneck.kuickcheck.generator.internal.FixedSizeGenerator
import org.mikeneck.kuickcheck.generator.internal.SizeGenerator
internal class ListGenerator<out T>(
val elementGenerator: Generator<T>,
override val size: Int = 20, override val sizeFixed: Boolean = false) : ContainerGenerator<List<T>> {
val sizeGenerator: SizeGenerator = if (sizeFixed) FixedSizeGenerator(size)
else ContainerGenerator.sizeGenerator(size)
override fun overrideSize(newSize: Int): Generator<List<T>> =
ListGenerator(elementGenerator, newSize, false)
override fun fix(newSize: Int): Generator<List<T>> =
ListGenerator(elementGenerator, newSize, true)
override fun invoke(): List<T> {
return sizeGenerator.of { elementGenerator() }
}
}
| apache-2.0 | 722db4190595fad5a0ef37cb6f0660b2 | 38 | 109 | 0.744939 | 4.333333 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/data/prefs/PrefsHelperImpl.kt | 1 | 3367 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.data.prefs
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Bitmap
import com.squareup.picasso.Picasso
import giuliolodi.gitnav.di.scope.AppContext
import giuliolodi.gitnav.di.scope.PreferenceInfo
import giuliolodi.gitnav.utils.ImageSaver
import org.eclipse.egit.github.core.User
import javax.inject.Inject
/**
* Created by giulio on 12/05/2017.
*/
class PrefsHelperImpl : PrefsHelper {
private val PREF_KEY_ACCESS_TOKEN = "PREF_KEY_ACCESS_TOKEN"
private val PREF_KEY_FULLNAME= "PREF_KEY_FULLNAME"
private val PREF_KEY_USERNAME = "PREF_KEY_USERNAME"
private val PREF_KEY_EMAIL = "PREF_KEY_EMAIL"
private val PREF_KEY_THEME = "PREF_KEY_THEME"
private val mContext: Context
private val mPrefs: SharedPreferences
@Inject
constructor(@AppContext context: Context, @PreferenceInfo prefFileName: String) {
mContext = context
mPrefs = context.getSharedPreferences(prefFileName, Context.MODE_PRIVATE)
}
override fun storeAccessToken(token: String) {
mPrefs.edit().putString(PREF_KEY_ACCESS_TOKEN, token).apply()
}
override fun getToken(): String {
var token = ""
if (mPrefs.getString(PREF_KEY_ACCESS_TOKEN, null) != null)
token = mPrefs.getString(PREF_KEY_ACCESS_TOKEN, null)
return token
}
override fun storeUser(user: User) {
mPrefs.edit().putString(PREF_KEY_USERNAME, user.login).apply()
if (user.name != null && !user.name.isEmpty())
mPrefs.edit().putString(PREF_KEY_FULLNAME, user.name).apply()
if (user.email != null && !user.email.isEmpty())
mPrefs.edit().putString(PREF_KEY_EMAIL, user.email).apply()
else
mPrefs.edit().putString(PREF_KEY_EMAIL, "No public email address").apply()
val profilePic: Bitmap = Picasso.with(mContext).load(user.avatarUrl).get()
ImageSaver(mContext).setFileName("thumbnail.png").setDirectoryName("images").save(profilePic)
}
override fun getUsername(): String {
return mPrefs.getString(PREF_KEY_USERNAME, null)
}
override fun getFullname(): String? {
return mPrefs.getString(PREF_KEY_FULLNAME, null)
}
override fun getEmail(): String? {
return mPrefs.getString(PREF_KEY_EMAIL, null)
}
override fun getPic(): Bitmap {
return ImageSaver(mContext).setFileName("thumbnail.png").setDirectoryName("images").load()
}
override fun setTheme(theme: String) {
if (theme == "light" || theme == "dark") {
mPrefs.edit().putString(PREF_KEY_THEME, theme).apply()
}
}
override fun getTheme(): String {
return mPrefs.getString(PREF_KEY_THEME, null)
}
}
| apache-2.0 | 289b1635c79dbe153d79e3647b42e2fc | 33.357143 | 101 | 0.685477 | 4.066425 | false | false | false | false |
InsertKoinIO/koin | core/koin-core/src/commonTest/kotlin/org/koin/core/OpenCloseScopeInstanceTest.kt | 1 | 2695 | package org.koin.core
import kotlin.test.assertEquals
import kotlin.test.fail
import kotlin.test.Test
import org.koin.Simple
import org.koin.core.error.NoBeanDefFoundException
import org.koin.core.qualifier.named
import org.koin.dsl.koinApplication
import org.koin.dsl.module
class OpenCloseScopeInstanceTest {
val scopeName = named("MY_SCOPE")
@Test
fun `get definition from a scope`() {
val koin = koinApplication {
modules(
module {
scope(scopeName) {
scoped { Simple.ComponentA() }
}
}
)
}.koin
val scope = koin.createScope("myScope", scopeName)
assertEquals(scope.get<Simple.ComponentA>(), scope.get<Simple.ComponentA>())
}
@Test
fun `can't get definition from another scope`() {
val koin = koinApplication {
modules(
module {
scope(scopeName) {
scoped { Simple.ComponentA() }
}
}
)
}.koin
try {
val scope = koin.createScope("myScope", named("otherName"))
scope.get<Simple.ComponentA>()
fail()
} catch (e: Exception) {
e.printStackTrace()
}
}
@Test
fun `get definition from scope and out of scope`() {
val koin = koinApplication {
modules(
module {
scope(scopeName) {
scoped { Simple.ComponentA() }
scoped { Simple.ComponentB(get()) }
}
}
)
}.koin
val scope = koin.createScope("myScope", scopeName)
val a = scope.get<Simple.ComponentA>()
val b = scope.get<Simple.ComponentB>()
assertEquals(a, b.a)
}
@Test
fun `can't get definition from wrong scope`() {
val scope1Name = named("SCOPE_1")
val koin = koinApplication {
modules(
module {
scope(scope1Name) {
scoped { B() }
}
scope(named("SCOPE_2")) {
scoped { Simple.ComponentA() }
}
}
)
}.koin
val scope = koin.createScope("myScope", scope1Name)
try {
scope.get<Simple.ComponentA>()
fail()
} catch (e: NoBeanDefFoundException) {
e.printStackTrace()
}
}
} | apache-2.0 | 5a1b67b2ed4ac6911787dfb5cba14743 | 26.793814 | 84 | 0.461224 | 5.182692 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.