repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
smmribeiro/intellij-community
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/util/GroovyIndexPatternBuilder.kt
|
13
|
1595
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.util
import com.intellij.lexer.Lexer
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.search.IndexPatternBuilder
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import org.jetbrains.plugins.groovy.lang.groovydoc.parser.GroovyDocElementTypes.GROOVY_DOC_COMMENT
import org.jetbrains.plugins.groovy.lang.lexer.GroovyLexer
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes
import org.jetbrains.plugins.groovy.lang.lexer.TokenSets
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.ML_COMMENT
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.SL_COMMENT
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
class GroovyIndexPatternBuilder : IndexPatternBuilder {
override fun getIndexingLexer(file: PsiFile): Lexer? {
return if (file is GroovyFile) GroovyLexer() else null
}
override fun getCommentTokenSet(file: PsiFile): TokenSet? {
return TokenSets.ALL_COMMENT_TOKENS
}
override fun getCommentStartDelta(tokenType: IElementType): Int {
return if (tokenType == SL_COMMENT) 2 else 0
}
override fun getCommentEndDelta(tokenType: IElementType): Int {
return if (tokenType === GroovyTokenTypes.mML_COMMENT) 2 else 0
}
override fun getCharsAllowedInContinuationPrefix(tokenType: IElementType): String {
return if (tokenType == ML_COMMENT || tokenType == GROOVY_DOC_COMMENT) "*" else ""
}
}
|
apache-2.0
|
f635d209edee663fcb9dd2d764c17e8f
| 40.973684 | 140 | 0.794357 | 4.079284 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/editor/LazyElementTypeTestBase.kt
|
6
|
1664
|
// 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.editor
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.testFramework.EditorTestUtil.performTypingAction
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCaseBase
import org.junit.Assert
abstract class LazyElementTypeTestBase<T>(private val lazyElementClass: Class<T>) :
KotlinLightCodeInsightFixtureTestCaseBase() where T : PsiElement {
protected fun reparse(text: String, char: Char): Unit = doTest(text, char, true)
protected fun noReparse(text: String, char: Char): Unit = doTest(text, char, false)
fun doTest(text: String, char: Char, reparse: Boolean) {
val file = myFixture.configureByText("a.kt", text.trimMargin())
val expressionBefore = PsiTreeUtil.findChildOfType(file, lazyElementClass)
performTypingAction(myFixture.editor, char)
PsiDocumentManager.getInstance(project).commitDocument(myFixture.getDocument(file))
val expressionAfter = PsiTreeUtil.findChildOfType(file, lazyElementClass)
val actualReparse = expressionAfter != expressionBefore
Assert.assertEquals("Lazy element behaviour was unexpected", reparse, actualReparse)
}
protected fun inIf(then: String) = "val t: Unit = if (true) $then else {}"
override fun getProjectDescriptor() = LightProjectDescriptor.EMPTY_PROJECT_DESCRIPTOR
}
|
apache-2.0
|
7590489406fb9b616d3df4c4f50e94c3
| 44 | 158 | 0.773438 | 4.687324 | false | true | false | false |
siosio/intellij-community
|
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/ExpectedInfos.kt
|
1
|
35746
|
// 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.core
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.builtins.getReturnTypeFromFunctionType
import org.jetbrains.kotlin.builtins.isFunctionOrSuspendFunctionType
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.ideService
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
import org.jetbrains.kotlin.resolve.calls.CallTransformer
import org.jetbrains.kotlin.resolve.calls.callUtil.allArgumentsMapped
import org.jetbrains.kotlin.resolve.calls.callUtil.getCall
import org.jetbrains.kotlin.resolve.calls.components.hasDefaultValue
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.DelegatingCall
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.*
import java.util.*
enum class Tail {
COMMA,
RPARENTH,
RBRACKET,
ELSE,
RBRACE
}
data class ItemOptions(val starPrefix: Boolean) {
companion object {
val DEFAULT = ItemOptions(false)
val STAR_PREFIX = ItemOptions(true)
}
}
interface ByTypeFilter {
fun matchingSubstitutor(descriptorType: FuzzyType): TypeSubstitutor?
val fuzzyType: FuzzyType?
get() = null
val multipleFuzzyTypes: Collection<FuzzyType>
get() = listOfNotNull(fuzzyType)
object All : ByTypeFilter {
override fun matchingSubstitutor(descriptorType: FuzzyType) = TypeSubstitutor.EMPTY
}
object None : ByTypeFilter {
override fun matchingSubstitutor(descriptorType: FuzzyType) = null
}
}
class ByExpectedTypeFilter(override val fuzzyType: FuzzyType) : ByTypeFilter {
override fun matchingSubstitutor(descriptorType: FuzzyType) = descriptorType.checkIsSubtypeOf(fuzzyType)
override fun equals(other: Any?) = other is ByExpectedTypeFilter && fuzzyType == other.fuzzyType
override fun hashCode() = fuzzyType.hashCode()
}
data /* for copy() */
class ExpectedInfo(
val filter: ByTypeFilter,
val expectedName: String?,
val tail: Tail?,
val itemOptions: ItemOptions = ItemOptions.DEFAULT,
val additionalData: AdditionalData? = null
) {
// just a marker interface
interface AdditionalData {}
constructor(
fuzzyType: FuzzyType,
expectedName: String?,
tail: Tail?,
itemOptions: ItemOptions = ItemOptions.DEFAULT,
additionalData: AdditionalData? = null
) : this(ByExpectedTypeFilter(fuzzyType), expectedName, tail, itemOptions, additionalData)
constructor(
type: KotlinType,
expectedName: String?,
tail: Tail?,
itemOptions: ItemOptions = ItemOptions.DEFAULT,
additionalData: AdditionalData? = null
) : this(type.toFuzzyType(emptyList()), expectedName, tail, itemOptions, additionalData)
fun matchingSubstitutor(descriptorType: FuzzyType): TypeSubstitutor? = filter.matchingSubstitutor(descriptorType)
fun matchingSubstitutor(descriptorType: KotlinType): TypeSubstitutor? = matchingSubstitutor(descriptorType.toFuzzyType(emptyList()))
companion object {
fun createForArgument(
type: KotlinType,
expectedName: String?,
tail: Tail?,
argumentData: ArgumentPositionData,
itemOptions: ItemOptions = ItemOptions.DEFAULT
): ExpectedInfo {
return ExpectedInfo(type.toFuzzyType(argumentData.function.typeParameters), expectedName, tail, itemOptions, argumentData)
}
fun createForNamedArgumentExpected(argumentData: ArgumentPositionData): ExpectedInfo {
return ExpectedInfo(ByTypeFilter.None, null, null/*TODO?*/, ItemOptions.DEFAULT, argumentData)
}
fun createForReturnValue(type: KotlinType?, callable: CallableDescriptor): ExpectedInfo {
val filter = if (type != null) ByExpectedTypeFilter(type.toFuzzyType(emptyList())) else ByTypeFilter.All
return ExpectedInfo(filter, callable.name.asString(), null, additionalData = ReturnValueAdditionalData(callable))
}
}
}
val ExpectedInfo.fuzzyType: FuzzyType?
get() = filter.fuzzyType
val ExpectedInfo.multipleFuzzyTypes: Collection<FuzzyType>
get() = filter.multipleFuzzyTypes
sealed class ArgumentPositionData(val function: FunctionDescriptor, val callType: Call.CallType) : ExpectedInfo.AdditionalData {
class Positional(
function: FunctionDescriptor,
callType: Call.CallType,
val argumentIndex: Int,
val isFunctionLiteralArgument: Boolean,
val namedArgumentCandidates: Collection<ParameterDescriptor>
) : ArgumentPositionData(function, callType)
class Named(function: FunctionDescriptor, callType: Call.CallType, val argumentName: Name) : ArgumentPositionData(function, callType)
}
class ReturnValueAdditionalData(val callable: CallableDescriptor) : ExpectedInfo.AdditionalData
class WhenEntryAdditionalData(val whenWithSubject: Boolean) : ExpectedInfo.AdditionalData
object IfConditionAdditionalData : ExpectedInfo.AdditionalData
object PropertyDelegateAdditionalData : ExpectedInfo.AdditionalData
class ComparisonOperandAdditionalData(val suppressNullLiteral: Boolean) : ExpectedInfo.AdditionalData
class ExpectedInfos(
private val bindingContext: BindingContext,
private val resolutionFacade: ResolutionFacade,
private val indicesHelper: KotlinIndicesHelper?,
private val useHeuristicSignatures: Boolean = true,
private val useOuterCallsExpectedTypeCount: Int = 0
) {
fun calculate(expressionWithType: KtExpression): Collection<ExpectedInfo> {
val expectedInfos = calculateForArgument(expressionWithType)
?: calculateForFunctionLiteralArgument(expressionWithType)
?: calculateForIndexingArgument(expressionWithType)
?: calculateForEqAndAssignment(expressionWithType)
?: calculateForIf(expressionWithType)
?: calculateForElvis(expressionWithType)
?: calculateForBlockExpression(expressionWithType)
?: calculateForWhenEntryValue(expressionWithType)
?: calculateForExclOperand(expressionWithType)
?: calculateForInitializer(expressionWithType)
?: calculateForExpressionBody(expressionWithType)
?: calculateForReturn(expressionWithType)
?: calculateForLoopRange(expressionWithType)
?: calculateForInOperatorArgument(expressionWithType)
?: calculateForPropertyDelegate(expressionWithType)
?: getFromBindingContext(expressionWithType)
?: return emptyList()
return expectedInfos.filterNot { it.fuzzyType?.type?.isError ?: false }
}
private fun calculateForArgument(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val argument = expressionWithType.parent as? KtValueArgument ?: return null
val argumentList = argument.parent as? KtValueArgumentList ?: return null
val callElement = argumentList.parent as? KtCallElement ?: return null
return calculateForArgument(callElement, argument)
}
private fun calculateForFunctionLiteralArgument(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val functionLiteralArgument = expressionWithType.parent as? KtLambdaArgument
val callExpression = functionLiteralArgument?.parent as? KtCallExpression ?: return null
val literalArgument = callExpression.lambdaArguments.firstOrNull() ?: return null
if (literalArgument.getArgumentExpression() != expressionWithType) return null
return calculateForArgument(callExpression, literalArgument)
}
private fun calculateForIndexingArgument(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val containerNode = expressionWithType.parent as? KtContainerNode ?: return null
val arrayAccessExpression = containerNode.parent as? KtArrayAccessExpression ?: return null
if (containerNode != arrayAccessExpression.indicesNode) return null
val call = arrayAccessExpression.getCall(bindingContext) ?: return null
val argument = call.valueArguments.firstOrNull { it.getArgumentExpression() == expressionWithType } ?: return null
return calculateForArgument(call, argument)
}
private fun calculateForArgument(callElement: KtCallElement, argument: ValueArgument): Collection<ExpectedInfo>? {
val call = callElement.getCall(bindingContext) ?: return null
// sometimes we get wrong call (see testEA70945) TODO: refactor resolve so that it does not happen
if (call.callElement != callElement) return null
return calculateForArgument(call, argument)
}
fun calculateForArgument(call: Call, argument: ValueArgument): Collection<ExpectedInfo> {
val results = calculateForArgument(call, TypeUtils.NO_EXPECTED_TYPE, argument)
fun makesSenseToUseOuterCallExpectedType(info: ExpectedInfo): Boolean {
val data = info.additionalData as ArgumentPositionData
return info.fuzzyType != null
&& info.fuzzyType!!.freeParameters.isNotEmpty()
&& data.function.fuzzyReturnType()?.freeParameters?.isNotEmpty() ?: false
}
if (useOuterCallsExpectedTypeCount > 0 && results.any(::makesSenseToUseOuterCallExpectedType)) {
val callExpression = (call.callElement as? KtExpression)?.getQualifiedExpressionForSelectorOrThis() ?: return results
val expectedFuzzyTypes =
ExpectedInfos(bindingContext, resolutionFacade, indicesHelper, useHeuristicSignatures, useOuterCallsExpectedTypeCount - 1)
.calculate(callExpression)
.mapNotNull { it.fuzzyType }
if (expectedFuzzyTypes.isEmpty() || expectedFuzzyTypes.any { it.freeParameters.isNotEmpty() }) return results
return expectedFuzzyTypes
.map { it.type }
.toSet()
.flatMap { calculateForArgument(call, it, argument) }
}
return results
}
private fun calculateForArgument(call: Call, callExpectedType: KotlinType, argument: ValueArgument): Collection<ExpectedInfo> {
if (call is CallTransformer.CallForImplicitInvoke)
return calculateForArgument(call.outerCall, callExpectedType, argument)
val argumentIndex = call.valueArguments.indexOf(argument)
assert(argumentIndex >= 0) {
"Could not find argument '$argument(${argument.asElement()
.text})' among arguments of call: $call. Call element text: '${call.callElement.text}'"
}
// leave only arguments before the current one
val truncatedCall = object : DelegatingCall(call) {
val arguments = call.valueArguments.subList(0, argumentIndex)
override fun getValueArguments() = arguments
override fun getFunctionLiteralArguments() = emptyList<LambdaArgument>()
override fun getValueArgumentList() = null
}
val candidates = truncatedCall.resolveCandidates(bindingContext, resolutionFacade, callExpectedType)
val expectedInfos = ArrayList<ExpectedInfo>()
for (candidate in candidates) {
expectedInfos.addExpectedInfoForCandidate(candidate, call, argument, argumentIndex, checkPrevArgumentsMatched = true)
}
if (expectedInfos.isEmpty()) { // if no candidates have previous arguments matched, try with no type checking for them
for (candidate in candidates) {
expectedInfos.addExpectedInfoForCandidate(candidate, call, argument, argumentIndex, checkPrevArgumentsMatched = false)
}
}
return expectedInfos
}
private fun MutableCollection<ExpectedInfo>.addExpectedInfoForCandidate(
candidate: ResolvedCall<FunctionDescriptor>,
call: Call,
argument: ValueArgument,
argumentIndex: Int,
checkPrevArgumentsMatched: Boolean
) {
// check that all arguments before the current has mappings to parameters
if (!candidate.allArgumentsMapped()) return
// check that all arguments before the current one matched
if (checkPrevArgumentsMatched && !candidate.allArgumentsMatched()) return
var descriptor = candidate.resultingDescriptor
if (descriptor.valueParameters.isEmpty()) return
val argumentToParameter = call.mapArgumentsToParameters(descriptor)
var parameter = argumentToParameter[argument]
var parameterType = parameter?.type
if (parameterType != null && parameterType.containsError()) {
val originalParameter = descriptor.original.valueParameters[parameter!!.index]
parameter = originalParameter
descriptor = descriptor.original
parameterType = fixSubstitutedType(parameterType, originalParameter.type)
}
val argumentName = argument.getArgumentName()?.asName
val isFunctionLiteralArgument = argument is LambdaArgument
val callType = call.callType
val isArrayAccess = callType == Call.CallType.ARRAY_GET_METHOD || callType == Call.CallType.ARRAY_SET_METHOD
val rparenthTail = if (isArrayAccess) Tail.RBRACKET else Tail.RPARENTH
val argumentPositionData = if (argumentName != null) {
ArgumentPositionData.Named(descriptor, callType, argumentName)
} else {
val namedArgumentCandidates = if (!isFunctionLiteralArgument && !isArrayAccess && descriptor.hasStableParameterNames()) {
val usedParameters = argumentToParameter.filter { it.key != argument }.map { it.value }.toSet()
descriptor.valueParameters.filter { it !in usedParameters }
} else {
emptyList()
}
ArgumentPositionData.Positional(descriptor, callType, argumentIndex, isFunctionLiteralArgument, namedArgumentCandidates)
}
var parameters = descriptor.valueParameters
if (callType == Call.CallType.ARRAY_SET_METHOD) { // last parameter in set is used for value assigned
if (parameter == parameters.last()) {
parameter = null
parameterType = null
}
parameters = parameters.dropLast(1)
}
if (parameter == null) {
if (argumentPositionData is ArgumentPositionData.Positional && argumentPositionData.namedArgumentCandidates.isNotEmpty()) {
add(ExpectedInfo.createForNamedArgumentExpected(argumentPositionData))
}
return
}
parameterType!!
val expectedName = if (descriptor.hasSynthesizedParameterNames()) null else parameter.name.asString()
fun needCommaForParameter(parameter: ValueParameterDescriptor): Boolean {
if (parameter.hasDefaultValue()) return false // parameter is optional
if (parameter.varargElementType != null) return false // vararg arguments list can be empty
// last parameter of functional type can be placed outside parenthesis:
if (!isArrayAccess && parameter == parameters.last() && parameter.type.isFunctionType) return false
return true
}
val tail = if (argumentName == null) {
when {
parameter == parameters.last() -> rparenthTail
parameters.dropWhile { it != parameter }.drop(1).any(::needCommaForParameter) -> Tail.COMMA
else -> null
}
} else {
namedArgumentTail(argumentToParameter, argumentName, descriptor)
}
val alreadyHasStar = argument.getSpreadElement() != null
val varargElementType = parameter.varargElementType
if (varargElementType != null) {
if (isFunctionLiteralArgument) return
val varargTail = if (argumentName == null && tail == rparenthTail)
null /* even if it's the last parameter, there can be more arguments for the same parameter */
else
tail
if (!alreadyHasStar) {
add(ExpectedInfo.createForArgument(varargElementType, expectedName?.unpluralize(), varargTail, argumentPositionData))
}
val starOptions = if (!alreadyHasStar) ItemOptions.STAR_PREFIX else ItemOptions.DEFAULT
add(ExpectedInfo.createForArgument(parameterType, expectedName, varargTail, argumentPositionData, starOptions))
} else {
if (alreadyHasStar) return
if (isFunctionLiteralArgument) {
if (parameterType.isFunctionOrSuspendFunctionType) {
add(ExpectedInfo.createForArgument(parameterType, expectedName, null, argumentPositionData))
}
} else {
add(ExpectedInfo.createForArgument(parameterType, expectedName, tail, argumentPositionData))
}
}
}
private fun fixSubstitutedType(substitutedType: KotlinType, originalType: KotlinType): KotlinType {
if (substitutedType.isError) return originalType
if (substitutedType.arguments.size != originalType.arguments.size) return originalType
val newTypeArguments = substitutedType.arguments.zip(originalType.arguments).map { (argument, originalArgument) ->
if (argument.type.containsError()) originalArgument else argument
}
return substitutedType.replace(newTypeArguments)
}
private fun <D : CallableDescriptor> ResolvedCall<D>.allArgumentsMatched() = call.valueArguments
.none { argument -> getArgumentMapping(argument).isError() && !argument.hasError() /* ignore arguments that has error type */ }
private fun ValueArgument.hasError() = getArgumentExpression()?.let { bindingContext.getType(it) }?.isError ?: true
private fun namedArgumentTail(
argumentToParameter: Map<ValueArgument, ValueParameterDescriptor>,
argumentName: Name,
descriptor: FunctionDescriptor
): Tail? {
val usedParameterNames = (argumentToParameter.values.map { it.name } + listOf(argumentName)).toSet()
val notUsedParameters = descriptor.valueParameters.filter { it.name !in usedParameterNames }
return when {
notUsedParameters.isEmpty() -> Tail.RPARENTH // named arguments no supported for []
notUsedParameters.all { it.hasDefaultValue() } -> null
else -> Tail.COMMA
}
}
private fun calculateForEqAndAssignment(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val binaryExpression = expressionWithType.parent as? KtBinaryExpression
if (binaryExpression != null) {
val operationToken = binaryExpression.operationToken
if (operationToken == KtTokens.EQ || operationToken in COMPARISON_TOKENS) {
val otherOperand = if (expressionWithType == binaryExpression.right) binaryExpression.left else binaryExpression.right
if (otherOperand != null) {
var expectedType = bindingContext.getType(otherOperand) ?: return null
val expectedName = expectedNameFromExpression(otherOperand)
if (expectedType.isNullableNothing()) { // other operand is 'null'
return listOf(ExpectedInfo(NullableTypesFilter, expectedName, null))
}
var additionalData: ExpectedInfo.AdditionalData? = null
if (operationToken in COMPARISON_TOKENS) {
// if we complete argument of == or !=, make types in expected info's nullable to allow items of nullable type too
additionalData =
ComparisonOperandAdditionalData(suppressNullLiteral = expectedType.nullability() == TypeNullability.NOT_NULL)
expectedType = expectedType.makeNullable()
}
return listOf(ExpectedInfo(expectedType, expectedName, null, additionalData = additionalData))
}
}
}
return null
}
private object NullableTypesFilter : ByTypeFilter {
override fun matchingSubstitutor(descriptorType: FuzzyType) =
if (descriptorType.type.nullability() != TypeNullability.NOT_NULL) TypeSubstitutor.EMPTY else null
}
private fun calculateForIf(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val ifExpression = (expressionWithType.parent as? KtContainerNode)?.parent as? KtIfExpression ?: return null
when (expressionWithType) {
ifExpression.condition -> return listOf(
ExpectedInfo(
resolutionFacade.moduleDescriptor.builtIns.booleanType,
null,
Tail.RPARENTH,
additionalData = IfConditionAdditionalData
)
)
ifExpression.then -> return calculate(ifExpression).map { ExpectedInfo(it.filter, it.expectedName, Tail.ELSE) }
ifExpression.`else` -> {
val ifExpectedInfos = calculate(ifExpression)
val thenType = ifExpression.then?.let { bindingContext.getType(it) }
if (ifExpectedInfos.any { it.fuzzyType != null }) {
val filteredInfo = if (thenType != null && !thenType.isError)
ifExpectedInfos.filter { it.matchingSubstitutor(thenType) != null }
else
ifExpectedInfos
return filteredInfo.copyWithNoAdditionalData()
} else if (thenType != null) {
return listOf(ExpectedInfo(thenType, null, null))
}
}
}
return null
}
private fun calculateForElvis(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val binaryExpression = expressionWithType.parent as? KtBinaryExpression
if (binaryExpression != null) {
val operationToken = binaryExpression.operationToken
if (operationToken == KtTokens.ELVIS && expressionWithType == binaryExpression.right) {
val leftExpression = binaryExpression.left ?: return null
val leftType = bindingContext.getType(leftExpression)
val leftTypeNotNullable = leftType?.makeNotNullable()
val expectedInfos = calculate(binaryExpression)
if (expectedInfos.any { it.fuzzyType != null }) {
val filteredInfo = if (leftTypeNotNullable != null)
expectedInfos.filter { it.matchingSubstitutor(leftTypeNotNullable) != null }
else
expectedInfos
return filteredInfo.copyWithNoAdditionalData()
} else if (leftTypeNotNullable != null) {
return listOf(ExpectedInfo(leftTypeNotNullable, null, null))
}
}
}
return null
}
private fun calculateForBlockExpression(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val block = expressionWithType.parent as? KtBlockExpression ?: return null
if (expressionWithType != block.statements.last()) return null
val functionLiteral = block.parent as? KtFunctionLiteral
return if (functionLiteral != null) {
val literalExpression = functionLiteral.parent as KtLambdaExpression
calculate(literalExpression)
.mapNotNull { it.fuzzyType }
.filter { it.type.isFunctionOrSuspendFunctionType }
.map {
val returnType = it.type.getReturnTypeFromFunctionType()
ExpectedInfo(returnType.toFuzzyType(it.freeParameters), null, Tail.RBRACE)
}
} else {
calculate(block).map { ExpectedInfo(it.filter, it.expectedName, null) }
}
}
private fun calculateForWhenEntryValue(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val condition = expressionWithType.parent as? KtWhenConditionWithExpression ?: return null
val entry = condition.parent as KtWhenEntry
val whenExpression = entry.parent as KtWhenExpression
val subject = whenExpression.subjectExpression
if (subject != null) {
val subjectType = bindingContext.getType(subject) ?: return null
return listOf(ExpectedInfo(subjectType, null, null, additionalData = WhenEntryAdditionalData(whenWithSubject = true)))
} else {
return listOf(
ExpectedInfo(
resolutionFacade.moduleDescriptor.builtIns.booleanType,
null,
null,
additionalData = WhenEntryAdditionalData(whenWithSubject = false)
)
)
}
}
private fun calculateForExclOperand(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val prefixExpression = expressionWithType.parent as? KtPrefixExpression ?: return null
if (prefixExpression.operationToken != KtTokens.EXCL) return null
return listOf(ExpectedInfo(resolutionFacade.moduleDescriptor.builtIns.booleanType, null, null))
}
private fun calculateForInitializer(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val property = expressionWithType.parent as? KtProperty ?: return null
if (expressionWithType != property.initializer) return null
val propertyDescriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, property] as? VariableDescriptor ?: return null
val expectedName = propertyDescriptor.name.asString()
val returnTypeToUse = returnTypeToUse(propertyDescriptor, hasExplicitReturnType = property.typeReference != null)
val expectedInfo = if (returnTypeToUse != null)
ExpectedInfo(returnTypeToUse, expectedName, null)
else
ExpectedInfo(ByTypeFilter.All, expectedName, null) // no explicit type or type from base - only expected name known
return listOf(expectedInfo)
}
private fun calculateForExpressionBody(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val declaration = expressionWithType.parent as? KtDeclarationWithBody ?: return null
if (expressionWithType != declaration.bodyExpression || declaration.hasBlockBody()) return null
val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] as? FunctionDescriptor ?: return null
return listOfNotNull(functionReturnValueExpectedInfo(descriptor, hasExplicitReturnType = declaration.hasDeclaredReturnType()))
}
private fun calculateForReturn(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val returnExpression = expressionWithType.parent as? KtReturnExpression ?: return null
val descriptor = returnExpression.getTargetFunctionDescriptor(bindingContext) ?: return null
return listOfNotNull(functionReturnValueExpectedInfo(descriptor, hasExplicitReturnType = true))
}
private fun functionReturnValueExpectedInfo(descriptor: FunctionDescriptor, hasExplicitReturnType: Boolean): ExpectedInfo? {
return when (descriptor) {
is SimpleFunctionDescriptor -> {
ExpectedInfo.createForReturnValue(returnTypeToUse(descriptor, hasExplicitReturnType), descriptor)
}
is PropertyGetterDescriptor -> {
val property = descriptor.correspondingProperty
ExpectedInfo.createForReturnValue(returnTypeToUse(property, hasExplicitReturnType), property)
}
else -> null
}
}
private fun returnTypeToUse(descriptor: CallableDescriptor, hasExplicitReturnType: Boolean): KotlinType? {
return if (hasExplicitReturnType)
descriptor.returnType
else
descriptor.overriddenDescriptors.singleOrNull()?.returnType
}
private fun calculateForLoopRange(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val forExpression = (expressionWithType.parent as? KtContainerNode)?.parent as? KtForExpression ?: return null
if (expressionWithType != forExpression.loopRange) return null
val loopVar = forExpression.loopParameter
val loopVarType = if (loopVar?.typeReference != null)
(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, loopVar] as VariableDescriptor).type.takeUnless { it.isError }
else
null
val scope = expressionWithType.getResolutionScope(bindingContext, resolutionFacade)
val iterableDetector = resolutionFacade.ideService<IterableTypesDetection>().createDetector(scope)
val byTypeFilter = object : ByTypeFilter {
override fun matchingSubstitutor(descriptorType: FuzzyType): TypeSubstitutor? {
return if (iterableDetector.isIterable(descriptorType, loopVarType)) TypeSubstitutor.EMPTY else null
}
}
return listOf(ExpectedInfo(byTypeFilter, null, Tail.RPARENTH))
}
private fun calculateForInOperatorArgument(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val binaryExpression = expressionWithType.parent as? KtBinaryExpression ?: return null
val operationToken = binaryExpression.operationToken
if (operationToken != KtTokens.IN_KEYWORD && operationToken != KtTokens.NOT_IN || expressionWithType != binaryExpression.right) return null
val leftOperandType = binaryExpression.left?.let { bindingContext.getType(it) } ?: return null
val scope = expressionWithType.getResolutionScope(bindingContext, resolutionFacade)
val detector = TypesWithContainsDetector(scope, indicesHelper, leftOperandType)
val byTypeFilter = object : ByTypeFilter {
override fun matchingSubstitutor(descriptorType: FuzzyType): TypeSubstitutor? {
return detector.findOperator(descriptorType)?.second
}
}
return listOf(ExpectedInfo(byTypeFilter, null, null))
}
private fun calculateForPropertyDelegate(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val delegate = expressionWithType.parent as? KtPropertyDelegate ?: return null
val propertyDeclaration = delegate.parent as? KtProperty ?: return null
val property = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, propertyDeclaration] as? PropertyDescriptor ?: return null
val scope = expressionWithType.getResolutionScope(bindingContext, resolutionFacade)
val propertyOwnerType = property.fuzzyExtensionReceiverType()
?: property.dispatchReceiverParameter?.type?.toFuzzyType(emptyList())
?: property.builtIns.nullableNothingType.toFuzzyType(emptyList())
val explicitPropertyType = property.fuzzyReturnType()?.takeIf { propertyDeclaration.typeReference != null }
?: property.overriddenDescriptors.singleOrNull()
?.fuzzyReturnType() // for override properties use super property type as explicit (if not specified)
val typesWithGetDetector = TypesWithGetValueDetector(scope, indicesHelper, propertyOwnerType, explicitPropertyType)
val typesWithSetDetector = if (property.isVar) TypesWithSetValueDetector(scope, indicesHelper, propertyOwnerType) else null
val byTypeFilter = object : ByTypeFilter {
override fun matchingSubstitutor(descriptorType: FuzzyType): TypeSubstitutor? {
val (getValueOperator, getOperatorSubstitutor) = typesWithGetDetector.findOperator(descriptorType) ?: return null
if (typesWithSetDetector == null) return getOperatorSubstitutor
val substitutedType =
getOperatorSubstitutor.substitute(descriptorType.type, Variance.INVARIANT)!!.toFuzzyType(descriptorType.freeParameters)
val (setValueOperator, setOperatorSubstitutor) = typesWithSetDetector.findOperator(substitutedType) ?: return null
val propertyType = explicitPropertyType ?: getValueOperator.fuzzyReturnType()!!
val setParamType = setValueOperator.valueParameters.last().type.toFuzzyType(setValueOperator.typeParameters)
val setParamTypeSubstitutor = setParamType.checkIsSuperTypeOf(propertyType) ?: return null
return getOperatorSubstitutor
.combineIfNoConflicts(setOperatorSubstitutor, descriptorType.freeParameters)
?.combineIfNoConflicts(setParamTypeSubstitutor, descriptorType.freeParameters)
}
override val multipleFuzzyTypes: Collection<FuzzyType> by lazy {
val result = ArrayList<FuzzyType>()
for (classDescriptor in typesWithGetDetector.classesWithMemberOperators) {
val type = classDescriptor.defaultType
val typeParameters = classDescriptor.declaredTypeParameters
val substitutor = matchingSubstitutor(type.toFuzzyType(typeParameters)) ?: continue
result.add(substitutor.substitute(type, Variance.INVARIANT)!!.toFuzzyType(typeParameters))
}
for (extensionOperator in typesWithGetDetector.extensionOperators) {
val receiverType = extensionOperator.fuzzyExtensionReceiverType()!!
val substitutor = matchingSubstitutor(receiverType) ?: continue
result.add(substitutor.substitute(receiverType.type, Variance.INVARIANT)!!.toFuzzyType(receiverType.freeParameters))
}
result
}
}
return listOf(ExpectedInfo(byTypeFilter, null, null, additionalData = PropertyDelegateAdditionalData))
}
private fun getFromBindingContext(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
val expectedType = bindingContext[BindingContext.EXPECTED_EXPRESSION_TYPE, expressionWithType] ?: return null
return listOf(ExpectedInfo(expectedType, null, null))
}
private fun expectedNameFromExpression(expression: KtExpression?): String? {
return when (expression) {
is KtSimpleNameExpression -> expression.getReferencedName()
is KtQualifiedExpression -> expectedNameFromExpression(expression.selectorExpression)
is KtCallExpression -> expectedNameFromExpression(expression.calleeExpression)
is KtArrayAccessExpression -> expectedNameFromExpression(expression.arrayExpression)?.unpluralize()
else -> null
}
}
private fun String.unpluralize() = StringUtil.unpluralize(this)
private fun Collection<ExpectedInfo>.copyWithNoAdditionalData() = map {
it.copy(additionalData = null, itemOptions = ItemOptions.DEFAULT)
}
}
val COMPARISON_TOKENS = setOf(KtTokens.EQEQ, KtTokens.EXCLEQ, KtTokens.EQEQEQ, KtTokens.EXCLEQEQEQ)
|
apache-2.0
|
5ea78482418f1207c38fda021a5499e1
| 48.854951 | 158 | 0.692105 | 6.055565 | false | false | false | false |
ThePreviousOne/Untitled
|
app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadHolder.kt
|
2
|
3686
|
package eu.kanade.tachiyomi.ui.recently_read
import android.support.v7.widget.RecyclerView
import android.view.View
import com.afollestad.materialdialogs.MaterialDialog
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.MangaChapterHistory
import kotlinx.android.synthetic.main.dialog_remove_recently.view.*
import kotlinx.android.synthetic.main.item_recently_read.view.*
import java.text.DateFormat
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*
/**
* Holder that contains recent manga item
* Uses R.layout.item_recently_read.
* UI related actions should be called from here.
*
* @param view the inflated view for this holder.
* @param adapter the adapter handling this holder.
* @constructor creates a new recent chapter holder.
*/
class RecentlyReadHolder(view: View, private val adapter: RecentlyReadAdapter)
: RecyclerView.ViewHolder(view) {
/**
* DecimalFormat used to display correct chapter number
*/
private val decimalFormat = DecimalFormat("#.###", DecimalFormatSymbols().apply { decimalSeparator = '.' })
private val df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
/**
* Set values of view
*
* @param item item containing history information
*/
fun onSetValues(item: MangaChapterHistory) {
// Retrieve objects
val manga = item.manga
val chapter = item.chapter
val history = item.history
// Set manga title
itemView.manga_title.text = manga.title
// Set source + chapter title
val formattedNumber = decimalFormat.format(chapter.chapter_number.toDouble())
itemView.manga_source.text = itemView.context.getString(R.string.recent_manga_source)
.format(adapter.sourceManager.get(manga.source)?.name, formattedNumber)
// Set last read timestamp title
itemView.last_read.text = df.format(Date(history.last_read))
// Set cover
if (!manga.thumbnail_url.isNullOrEmpty()) {
Glide.with(itemView.context)
.load(manga)
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.centerCrop()
.into(itemView.cover)
}
// Set remove clickListener
itemView.remove.setOnClickListener {
MaterialDialog.Builder(itemView.context)
.title(R.string.action_remove)
.customView(R.layout.dialog_remove_recently, true)
.positiveText(R.string.action_remove)
.negativeText(android.R.string.cancel)
.onPositive { materialDialog, dialogAction ->
// Check if user wants all chapters reset
if (materialDialog.customView?.removeAll?.isChecked as Boolean) {
adapter.fragment.removeAllFromHistory(manga.id!!)
} else {
adapter.fragment.removeFromHistory(history)
}
}
.onNegative { materialDialog, dialogAction ->
materialDialog.dismiss()
}
.show()
}
// Set continue reading clickListener
itemView.resume.setOnClickListener {
adapter.fragment.openChapter(chapter, manga)
}
// Set open manga info clickListener
itemView.cover.setOnClickListener {
adapter.fragment.openMangaInfo(manga)
}
}
}
|
gpl-3.0
|
ab53e96687178b9648612fcab2f6826e
| 36.232323 | 111 | 0.634292 | 4.974359 | false | false | false | false |
feelfreelinux/WykopMobilny
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/InputToolbar.kt
|
1
|
10959
|
package io.github.feelfreelinux.wykopmobilny.ui.widgets
import android.content.Context
import android.net.Uri
import android.os.Parcel
import android.os.Parcelable
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.SparseArray
import android.util.TypedValue
import android.view.View
import android.view.inputmethod.InputMethodManager
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.api.WykopImageFile
import io.github.feelfreelinux.wykopmobilny.api.suggest.SuggestApi
import io.github.feelfreelinux.wykopmobilny.ui.suggestions.HashTagsSuggestionsAdapter
import io.github.feelfreelinux.wykopmobilny.ui.suggestions.UsersSuggestionsAdapter
import io.github.feelfreelinux.wykopmobilny.ui.suggestions.WykopSuggestionsTokenizer
import io.github.feelfreelinux.wykopmobilny.ui.widgets.markdown_toolbar.MarkdownToolbarListener
import io.github.feelfreelinux.wykopmobilny.utils.getActivityContext
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import io.github.feelfreelinux.wykopmobilny.utils.textview.removeHtml
import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi
import kotlinx.android.synthetic.main.input_toolbar.view.*
const val ZERO_WIDTH_SPACE = "\u200B\u200B\u200B\u200B\u200B"
interface InputToolbarListener {
fun sendPhoto(photo: WykopImageFile, body: String, containsAdultContent: Boolean)
fun sendPhoto(photo: String?, body: String, containsAdultContent: Boolean)
fun openGalleryImageChooser()
fun openCamera(uri: Uri)
}
class InputToolbar @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : androidx.constraintlayout.widget.ConstraintLayout(context, attrs, defStyleAttr), MarkdownToolbarListener {
override var selectionStart: Int
get() = body.selectionStart
set(value) = body.setSelection(value)
override var selectionEnd: Int
get() = body.selectionEnd
set(value) = body.setSelection(value)
override var textBody: String
get() = body.text.toString()
set(value) = body.setText(value)
lateinit var userManager: UserManagerApi
lateinit var suggestApi: SuggestApi
var defaultText = ""
var showToolbar = false
var inputToolbarListener: InputToolbarListener? = null
var isCommentingPossible = true
private val usersSuggestionAdapter by lazy { UsersSuggestionsAdapter(context, suggestApi) }
private val hashTagsSuggestionAdapter by lazy { HashTagsSuggestionsAdapter(context, suggestApi) }
init {
val typedValue = TypedValue()
val theme = context.theme
theme.resolveAttribute(R.attr.itemBackgroundColor, typedValue, true)
setBackgroundColor(typedValue.data)
// Inflate view
View.inflate(context, R.layout.input_toolbar, this)
markdownToolbar.markdownListener = this
markdownToolbar.floatingImageView = floatingImageView
markdownToolbar.remoteImageInserted = {
enableSendButton()
}
// Setup listeners
body.setOnFocusChangeListener { _, focused ->
if (focused && !hasUserEditedContent()) {
textBody = defaultText
showMarkdownToolbar()
}
}
body.setTokenizer(WykopSuggestionsTokenizer({
if (body.adapter !is UsersSuggestionsAdapter)
body.setAdapter(usersSuggestionAdapter)
}, {
if (body.adapter !is HashTagsSuggestionsAdapter)
body.setAdapter(hashTagsSuggestionAdapter)
}))
body.threshold = 3
body.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if ((textBody.length > 2 || markdownToolbar.photo != null || markdownToolbar.photoUrl != null)) {
if (!send.isEnabled) {
enableSendButton()
}
} else if (textBody.length < 3) {
disableSendButton()
}
}
})
send.setOnClickListener {
showProgress(true)
val wykopImageFile = markdownToolbar.getWykopImageFile()
if (wykopImageFile != null) {
inputToolbarListener?.sendPhoto(
wykopImageFile,
if (body.text.toString().isNotEmpty()) body.text.toString() else ZERO_WIDTH_SPACE,
markdownToolbar.containsAdultContent
)
} else {
inputToolbarListener?.sendPhoto(
markdownToolbar.photoUrl,
if (body.text.toString().isNotEmpty()) body.text.toString() else ZERO_WIDTH_SPACE,
markdownToolbar.containsAdultContent
)
}
}
disableSendButton()
if (showToolbar) showMarkdownToolbar()
else closeMarkdownToolbar()
}
override fun setSelection(start: Int, end: Int) = body.setSelection(start, end)
override fun openCamera(uri: Uri) {
inputToolbarListener?.openCamera(uri)
}
override fun openGalleryImageChooser() {
inputToolbarListener?.openGalleryImageChooser()
}
fun setPhoto(photo: Uri?) {
enableSendButton()
markdownToolbar.photo = photo
}
fun setup(userManagerApi: UserManagerApi, suggestionApi: SuggestApi) {
userManager = userManagerApi
suggestApi = suggestionApi
show()
}
private fun showMarkdownToolbar() {
if (!hasUserEditedContent()) textBody = defaultText
markdownToolbar.isVisible = true
separatorButton.isVisible = true
send.isVisible = true
showToolbar = true
}
private fun closeMarkdownToolbar() {
markdownToolbar.isVisible = false
separatorButton.isVisible = false
send.isVisible = false
showToolbar = false
}
fun showProgress(shouldShowProgress: Boolean) {
progressBar.isVisible = shouldShowProgress
send.isVisible = !shouldShowProgress
}
fun resetState() {
getActivityContext()?.currentFocus?.apply {
val imm = getActivityContext()?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(windowToken, 0)
}
textBody = ""
selectionStart = textBody.length
markdownToolbar.apply {
photo = null
photoUrl = null
containsAdultContent = false
}
if (textBody.length < 3 && !(markdownToolbar.photo != null || markdownToolbar.photoUrl != null)) disableSendButton()
closeMarkdownToolbar()
body.isFocusableInTouchMode = false
body.isFocusable = false
body.isFocusableInTouchMode = true
body.isFocusable = true
}
fun setDefaultAddressant(user: String) {
if (userManager.isUserAuthorized() && userManager.getUserCredentials()!!.login != user) {
defaultText = "@$user: "
}
}
fun addAddressant(user: String) {
defaultText = ""
body.requestFocus()
textBody += "@$user: "
if (textBody.length > 2 || markdownToolbar.photo != null || markdownToolbar.photoUrl != null) enableSendButton()
selectionStart = textBody.length
showKeyboard()
}
fun addQuoteText(quote: String, quoteAuthor: String) {
defaultText = ""
body.requestFocus()
if (textBody.length > 0) textBody += "\n\n"
textBody += "> ${quote.removeHtml().replace("\n", "\n> ")}\n@$quoteAuthor: "
selectionStart = textBody.length
if (textBody.length > 2 || markdownToolbar.photo != null || markdownToolbar.photoUrl != null) enableSendButton()
showKeyboard()
}
fun setCustomHint(hint: String) {
body.hint = hint
}
fun hasUserEditedContent() = textBody != defaultText && markdownToolbar.hasUserEditedContent()
fun hide() {
isVisible = false
}
fun disableSendButton() {
send.alpha = 0.3f
send.isEnabled = false
}
fun enableSendButton() {
send.alpha = 1f
send.isEnabled = true
}
private fun showKeyboard() {
val imm = getActivityContext()!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(body, InputMethodManager.SHOW_IMPLICIT)
}
fun setIfIsCommentingPossible(value: Boolean) {
isCommentingPossible = value
}
fun show() {
// Only show if user's logged in and has permissions to do it
// If OP blacklisted user, then user cannot respond to his entries
isVisible = userManager.isUserAuthorized() && isCommentingPossible
}
override fun onRestoreInstanceState(state: Parcelable?) {
val savedState = state as? SavedState
savedState?.let {
textBody = savedState.text
if (savedState.isOpened) {
showMarkdownToolbar()
} else {
closeMarkdownToolbar()
}
}
super.onRestoreInstanceState(savedState?.superState)
}
override fun onSaveInstanceState(): Parcelable {
val superState = super.onSaveInstanceState()
return SavedState(superState!!, showToolbar, textBody)
}
override fun dispatchSaveInstanceState(container: SparseArray<Parcelable>?) {
super.dispatchFreezeSelfOnly(container)
}
override fun dispatchRestoreInstanceState(container: SparseArray<Parcelable>?) {
super.dispatchThawSelfOnly(container)
}
class SavedState : View.BaseSavedState {
val isOpened: Boolean
val text: String
constructor(superState: Parcelable, opened: Boolean, body: String) : super(superState) {
isOpened = opened
text = body
}
constructor(`in`: Parcel) : super(`in`) {
isOpened = `in`.readInt() == 1
text = `in`.readString()!!
}
override fun writeToParcel(destination: Parcel, flags: Int) {
super.writeToParcel(destination, flags)
destination.writeInt(if (isOpened) 1 else 0)
destination.writeString(text)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<SavedState> {
override fun createFromParcel(parcel: Parcel): SavedState {
return SavedState(parcel)
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
}
|
mit
|
295516a4934640e894b6de7e28f75cff
| 33.574132 | 124 | 0.649238 | 5.283992 | false | false | false | false |
JetBrains/kotlin-native
|
build-tools/src/main/kotlin/org/jetbrains/kotlin/PlatformInfo.kt
|
2
|
1934
|
package org.jetbrains.kotlin
import org.jetbrains.kotlin.konan.target.*
import org.jetbrains.kotlin.konan.util.*
import org.gradle.api.Project
object PlatformInfo {
@JvmStatic
fun isMac() = HostManager.hostIsMac
@JvmStatic
fun isWindows() = HostManager.hostIsMingw
@JvmStatic
fun isLinux() = HostManager.hostIsLinux
@JvmStatic
fun isAppleTarget(project: Project): Boolean {
val target = getTarget(project)
return target.family.isAppleFamily
}
@JvmStatic
fun isAppleTarget(target: KonanTarget): Boolean {
return target.family.isAppleFamily
}
@JvmStatic
fun isWindowsTarget(project: Project) = getTarget(project).family == Family.MINGW
@JvmStatic
fun isWasmTarget(project: Project) =
getTarget(project).family == Family.WASM
@JvmStatic
fun getTarget(project: Project): KonanTarget {
val platformManager = project.rootProject.platformManager
val targetName = project.project.testTarget.name
return platformManager.targetManager(targetName).target
}
@JvmStatic
fun checkXcodeVersion(project: Project) {
val properties = PropertiesProvider(project)
val requiredMajorVersion = properties.xcodeMajorVersion
if (!DependencyProcessor.isInternalSeverAvailable
&& properties.checkXcodeVersion
&& requiredMajorVersion != null
) {
val currentXcodeVersion = Xcode.current.version
val currentMajorVersion = currentXcodeVersion.splitToSequence('.').first()
if (currentMajorVersion != requiredMajorVersion) {
throw IllegalStateException(
"Incorrect Xcode version: ${currentXcodeVersion}. Required major Xcode version is ${requiredMajorVersion}."
)
}
}
}
fun unsupportedPlatformException() = TargetSupportException()
}
|
apache-2.0
|
a6f7e9ff5de98efaf251437002efb9e2
| 31.25 | 131 | 0.675801 | 5.313187 | false | false | false | false |
hotpodata/redchain
|
mobile/src/main/java/com/hotpodata/redchain/view/XView.kt
|
1
|
7283
|
package com.hotpodata.redchain.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.hotpodata.redchain.R
import timber.log.Timber
/**
* Created by jdrotos on 10/5/15.
*/
public class XView : View {
var xColor = Color.RED;
var xColorSecondary = Color.BLUE;
var xWidth = 16f
var xPaint: Paint? = null
var boxToXPercentage: Float = 0f
get
set(percentage: Float) {
field = percentage
Timber.d("setBoxToPErcentage:" + percentage)
postInvalidate()
}
public constructor(context: Context) : super(context) {
init(context, null)
}
public constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context, attrs)
}
public constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
init(context, attrs)
}
public constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
init(context, attrs)
}
@Suppress("DEPRECATION")
private fun init(context: Context, attrs: AttributeSet?) {
if (attrs != null) {
val a = context.obtainStyledAttributes(attrs, R.styleable.XView)
if (a != null) {
if (a.hasValue(R.styleable.XView_boxToXPercentage)) {
boxToXPercentage = a.getFloat(R.styleable.XView_boxToXPercentage, boxToXPercentage)
}
a.recycle()
}
}
xColor = context.resources.getColor(R.color.primary)
xColorSecondary = context.resources.getColor(R.color.accent)
xWidth = context.resources.getDimensionPixelSize(R.dimen.row_x_thickness).toFloat()
xPaint = createFreshXPaint()
}
fun setColors(primColor: Int, secondaryColor: Int) {
xColor = primColor;
xColorSecondary = secondaryColor;
}
fun createFreshXPaint(): Paint {
val paint = Paint()
paint.isAntiAlias = true
paint.color = xColor
paint.style = Paint.Style.STROKE
paint.strokeCap = Paint.Cap.ROUND
paint.strokeWidth = xWidth
return paint
}
public fun setBox(boxMode: Boolean) {
boxToXPercentage = if (boxMode) 0f else 1f
invalidate()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
for (i in 0..1) {
//This for loop is for the weird shadow effect
if (xPaint != null && width > 0 && height > 0) {
if (i == 0) {
xPaint?.color = xColorSecondary
canvas.save()
canvas.translate(xWidth / 2f, xWidth / 2f)
} else {
xPaint?.color = xColor
canvas.restore()
}
var minLeft = xWidth + paddingLeft
var maxRight = width.toFloat() - xWidth - paddingRight
var minTop = xWidth + paddingTop
var maxBottom = height.toFloat() - xWidth - paddingBottom
if (boxToXPercentage == 0f) {
canvas.drawLine(minLeft, minTop, maxRight, minTop, xPaint)
canvas.drawLine(maxRight, minTop, maxRight, maxBottom, xPaint)
canvas.drawLine(maxRight, maxBottom, minLeft, maxBottom, xPaint)
canvas.drawLine(minLeft, maxBottom, minLeft, minTop, xPaint)
} else if (boxToXPercentage == 1f) {
canvas.drawLine(minLeft, minTop, maxRight, maxBottom, xPaint)
canvas.drawLine(minLeft, maxBottom, maxRight, minTop, xPaint)
} else {
if (boxToXPercentage < 0.5f) {
//In this case we are shrinking the box
var boxShowingPercentage = (0.5f - boxToXPercentage) / 0.5f;
Timber.d("boxShowingPercentage:" + boxShowingPercentage)
//First we draw the full portions of the box
if (boxShowingPercentage > 0.75f) {
canvas.drawLine(maxRight, minTop, maxRight, maxBottom, xPaint)
}
if (boxShowingPercentage > 0.5f) {
canvas.drawLine(maxRight, maxBottom, minLeft, maxBottom, xPaint)
}
if (boxShowingPercentage > 0.25f) {
canvas.drawLine(minLeft, maxBottom, minLeft, minTop, xPaint)
}
//Then we draw whatever partial portion of the box we need to
var portionPerc = 1f - ((Math.floor(boxShowingPercentage * 100.0) % 25) / 25f).toFloat() //(((Math.floor(boxShowingPercentage * 100.0) % 25)/100f)).toFloat()/0.25f;
Timber.d("portionPerc:" + portionPerc)
if (boxShowingPercentage > 0.75f) {
canvas.drawLine(minLeft + (portionPerc * (maxRight - minLeft)), minTop, maxRight, minTop, xPaint)
} else if (boxShowingPercentage > 0.5f) {
canvas.drawLine(maxRight, minTop + (portionPerc * (maxBottom - minTop)), maxRight, maxBottom, xPaint)
} else if (boxShowingPercentage > 0.25f) {
canvas.drawLine(maxRight - (portionPerc * (maxRight - minLeft)), maxBottom, minLeft, maxBottom, xPaint)
} else {
canvas.drawLine(minLeft, maxBottom - (portionPerc * (maxBottom - minTop)), minLeft, minTop, xPaint)
}
} else {
var xShowingPercentage = (boxToXPercentage - 0.5f) / 0.5f;
Timber.d("xShowingPercentage:" + xShowingPercentage)
canvas.drawLine(minLeft, minTop, minLeft + (xShowingPercentage * (maxRight - minLeft)), minTop + ( xShowingPercentage * (maxBottom - minTop)), xPaint)
//In this case we are growing the X
if (xShowingPercentage > 0.5f) {
var xHalfShowingPercentage = (xShowingPercentage - 0.5f) / 0.5f;
Timber.d("xHalfShowingPercentage:" + xHalfShowingPercentage)
var centerX = (maxRight - minLeft) / 2f + xWidth;
var centerY = (maxBottom - minTop) / 2f + xWidth;
canvas.drawLine(centerX, centerY, centerX + xHalfShowingPercentage * (maxRight - centerX), centerY - xHalfShowingPercentage * (centerY - minTop), xPaint)
canvas.drawLine(centerX, centerY, centerX - xHalfShowingPercentage * (centerX - minLeft), centerY + xHalfShowingPercentage * (maxBottom - centerY), xPaint)
}
}
}
}
}
}
}
|
apache-2.0
|
f6ac95bc25aad83b5fca86ba359bda19
| 41.847059 | 188 | 0.552108 | 5.022759 | false | false | false | false |
androidx/androidx
|
glance/glance-appwidget/integration-tests/demos/src/main/java/androidx/glance/appwidget/demos/ResizingAppWidget.kt
|
3
|
4962
|
/*
* 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.glance.appwidget.demos
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.glance.GlanceModifier
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import androidx.glance.appwidget.SizeMode
import androidx.glance.background
import androidx.glance.layout.Column
import androidx.glance.layout.Row
import androidx.glance.layout.fillMaxSize
import androidx.glance.layout.fillMaxWidth
import androidx.glance.layout.height
import androidx.glance.layout.padding
import androidx.glance.layout.width
import androidx.glance.text.Text
import androidx.glance.text.TextAlign
import androidx.glance.text.TextDecoration
import androidx.glance.text.TextStyle
import androidx.glance.action.clickable
import androidx.glance.ImageProvider
import android.content.Context
import androidx.glance.appwidget.action.actionRunCallback
import androidx.glance.GlanceId
import androidx.glance.action.ActionParameters
import androidx.glance.appwidget.action.ActionCallback
class ResizingAppWidget : GlanceAppWidget() {
override val sizeMode: SizeMode = SizeMode.Single
@Composable
override fun Content() {
Column(modifier = GlanceModifier.fillMaxSize().padding(16.dp).background(Color.LightGray)) {
Row(modifier = GlanceModifier.fillMaxWidth()) {
Text(
"first",
modifier = GlanceModifier
.width(50.dp)
.background(Color(0xFFBBBBBB))
.clickable(actionRunCallback<NoopAction>()),
style = TextStyle(textAlign = TextAlign.Start)
)
Text(
"second",
style = TextStyle(
textDecoration = TextDecoration.LineThrough,
textAlign = TextAlign.Center,
),
modifier = GlanceModifier.defaultWeight().height(50.dp)
)
Text(
"third",
modifier = GlanceModifier
.width(50.dp)
.background(Color(0xFFBBBBBB))
.clickable(actionRunCallback<NoopAction>()),
style = TextStyle(textAlign = TextAlign.End)
)
}
Text(
"middle",
modifier = GlanceModifier
.defaultWeight()
.fillMaxWidth()
.clickable(actionRunCallback<NoopAction>())
.background(ImageProvider(R.drawable.compose)),
style = TextStyle(textAlign = TextAlign.Center)
)
Column(modifier = GlanceModifier.fillMaxWidth().background(Color.LightGray)) {
Text(
"left",
style = TextStyle(textAlign = TextAlign.Left),
modifier = GlanceModifier.fillMaxWidth()
)
Text(
"right",
style = TextStyle(textAlign = TextAlign.Right),
modifier = GlanceModifier.fillMaxWidth()
)
Text(
"start",
style = TextStyle(textAlign = TextAlign.Start),
modifier = GlanceModifier.fillMaxWidth()
)
Text(
"end",
style = TextStyle(textAlign = TextAlign.End),
modifier = GlanceModifier.fillMaxWidth()
)
}
Row(modifier = GlanceModifier.fillMaxWidth()) {
Text("", modifier = GlanceModifier.defaultWeight())
Text("bottom center")
Text("", modifier = GlanceModifier.defaultWeight())
}
}
}
}
class ResizingAppWidgetReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = ResizingAppWidget()
}
class NoopAction : ActionCallback {
override suspend fun onAction(
context: Context,
glanceId: GlanceId,
parameters: ActionParameters
) {
android.util.Log.e("GlanceAppWidget", "Action called")
}
}
|
apache-2.0
|
4135c9a342572ccb3aa6ab79693851b7
| 36.598485 | 100 | 0.601975 | 5.417031 | false | false | false | false |
itachi1706/DroidEggs
|
app/src/main/java/com/itachi1706/droideggs/PieEgg/EasterEgg/paint/ToolbarView.kt
|
1
|
1367
|
/*
* Copyright (C) 2018 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.itachi1706.droideggs.PieEgg.EasterEgg.paint
import android.content.Context
import android.view.WindowInsets
import android.widget.FrameLayout
import androidx.annotation.RequiresApi
import com.itachi1706.droideggs.compat.ScreenMetricsCompat
@RequiresApi(21)
class ToolbarView(context: Context) : FrameLayout(context) {
override fun onApplyWindowInsets(insets: WindowInsets?): WindowInsets {
val lp = layoutParams as LayoutParams?
if (lp != null && insets != null) {
val metric = ScreenMetricsCompat.getInsetsMetric(insets)
lp.topMargin = metric.top
lp.bottomMargin = metric.bottom
layoutParams = lp
}
return super.onApplyWindowInsets(insets)
}
}
|
apache-2.0
|
8a00d65fe8ead7bd996e2888ff444395
| 35.972973 | 75 | 0.727871 | 4.409677 | false | false | false | false |
Briseus/Lurker
|
app/src/main/java/torille/fi/lurkforreddit/comments/CommentPresenter.kt
|
1
|
3933
|
package torille.fi.lurkforreddit.comments
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import torille.fi.lurkforreddit.data.RedditRepository
import torille.fi.lurkforreddit.data.models.view.Comment
import torille.fi.lurkforreddit.data.models.view.Post
import torille.fi.lurkforreddit.data.models.view.PostAndComments
import java.util.*
import javax.inject.Inject
class CommentPresenter @Inject
internal constructor(
private val redditRepository: RedditRepository,
val post: Post,
private val isSingleCommentThread: Boolean
) : CommentContract.Presenter {
private lateinit var commentsView: CommentContract.View
private val disposables = CompositeDisposable()
private var firstLoad = true
override fun loadComments(permaLinkUrl: String, isSingleCommentThread: Boolean) {
Timber.d("Loading comments for permalink $permaLinkUrl")
commentsView.setProgressIndicator(true)
disposables.add(redditRepository.getCommentsForPost(permaLinkUrl, isSingleCommentThread)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableObserver<PostAndComments>() {
override fun onNext(postAndComments: PostAndComments) {
val comments = ArrayList<Any>(postAndComments.comments.size + 1)
Timber.d("Hmm ${postAndComments.originalPost}")
comments.add(postAndComments.originalPost)
comments.addAll(postAndComments.comments)
commentsView.showComments(comments)
}
override fun onError(e: Throwable) {
Timber.e(e)
commentsView.setProgressIndicator(false)
commentsView.showError(e.toString())
}
override fun onComplete() {
Timber.d("Fetched comments")
commentsView.setProgressIndicator(false)
}
})
)
}
override fun loadMoreCommentsAt(parentComment: Comment, linkId: String, position: Int) {
val level = parentComment.commentLevel
commentsView.showProgressbarAt(position, level)
val childCommentIds = parentComment.childCommentIds
if (childCommentIds != null) {
disposables.add(redditRepository.getMoreCommentsForPostAt(
childCommentIds,
linkId,
parentComment.commentLevel
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableObserver<List<Comment>>() {
override fun onNext(comments: List<Comment>) {
commentsView.hideProgressbarAt(position)
commentsView.addCommentsAt(comments, position)
}
override fun onError(e: Throwable) {
Timber.e(e)
commentsView.showErrorAt(position)
}
override fun onComplete() {
Timber.d("Fetching more comments completed")
}
})
)
} else {
commentsView.showError("How did you get here?")
}
}
override fun takeView(view: CommentContract.View) {
commentsView = view
if (firstLoad) {
loadComments(post.permaLink, isSingleCommentThread)
firstLoad = false
}
}
override fun dropView() {
disposables.dispose()
}
}
|
mit
|
09b3a2ba6610038979ab43117c2bd09d
| 37.727273 | 96 | 0.60539 | 5.675325 | false | false | false | false |
BijoySingh/Quick-Note-Android
|
scarlet/src/main/java/com/bijoysingh/quicknote/firebase/activity/FirebaseLoginActivity.kt
|
1
|
5005
|
package com.bijoysingh.quicknote.firebase.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import com.bijoysingh.quicknote.R
import com.bijoysingh.quicknote.firebase.activity.DataPolicyActivity.Companion.hasAcceptedThePolicy
import com.bijoysingh.quicknote.firebase.initFirebaseDatabase
import com.bijoysingh.quicknote.scarlet.sFirebaseKilled
import com.facebook.litho.Component
import com.facebook.litho.ComponentContext
import com.facebook.litho.LithoView
import com.github.bijoysingh.starter.util.IntentUtils
import com.github.bijoysingh.starter.util.ToastHelper
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.common.api.Scope
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.api.services.drive.DriveScopes
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppPreferences
import com.maubis.scarlet.base.main.recycler.KEY_FORCE_SHOW_SIGN_IN
import com.maubis.scarlet.base.support.ui.ThemedActivity
import com.maubis.scarlet.base.support.utils.maybeThrow
import java.util.concurrent.atomic.AtomicBoolean
class FirebaseLoginActivity : ThemedActivity() {
private val RC_SIGN_IN = 31245
lateinit var context: Context
lateinit var googleSignInClient: GoogleSignInClient
lateinit var firebaseAuth: FirebaseAuth
lateinit var component: Component
lateinit var componentContext: ComponentContext
var loggingIn = AtomicBoolean(false)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
context = this
componentContext = ComponentContext(context)
setButton(false)
setupGoogleLogin()
firebaseAuth = FirebaseAuth.getInstance()
notifyThemeChange()
}
private fun setButton(state: Boolean) {
loggingIn.set(state)
component = FirebaseRootView.create(componentContext)
.onClick {
if (!hasAcceptedThePolicy()) {
IntentUtils.startActivity(this, DataPolicyActivity::class.java)
return@onClick
}
if (!loggingIn.get()) {
setButton(true)
sFirebaseKilled = false
signIn()
}
}
.loggingIn(state)
.build()
setContentView(LithoView.create(componentContext, component))
}
private fun setupGoogleLogin() {
val gso = GoogleSignInOptions.Builder(
GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Scope(DriveScopes.DRIVE_FILE))
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
}
private fun signIn() {
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
override fun onBackPressed() {
if (!loggingIn.get()) {
super.onBackPressed()
}
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)
}
}
private fun handleSignInResult(task: Task<GoogleSignInAccount>) {
try {
val account = task.getResult(ApiException::class.java)
if (account !== null) {
firebaseAuthWithGoogle(account)
return
}
} catch (exception: Exception) {
maybeThrow(this, exception)
}
onLoginFailure()
}
private fun firebaseAuthWithGoogle(account: GoogleSignInAccount) {
val credential = GoogleAuthProvider.getCredential(account.idToken, null)
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, object : OnCompleteListener<AuthResult> {
override fun onComplete(task: Task<AuthResult>) {
if (task.isSuccessful()) {
val user = firebaseAuth.currentUser
onLoginSuccess(user)
} else {
Log.e("Firebase", "Failed")
onLoginFailure()
}
}
})
}
private fun onLoginSuccess(user: FirebaseUser?) {
if (user === null || user.uid.isEmpty()) {
return
}
sAppPreferences.put(KEY_FORCE_SHOW_SIGN_IN, true)
setButton(false)
initFirebaseDatabase(context, user.uid)
finish()
}
private fun onLoginFailure() {
ToastHelper.show(context, R.string.login_to_google_failed)
setButton(false)
}
override fun notifyThemeChange() {
setSystemTheme()
}
}
|
gpl-3.0
|
94e0c5b52d3e54b3e82098e34d4df83b
| 31.290323 | 99 | 0.735864 | 4.429204 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/inspections/KotlinInspectionSuppressor.kt
|
1
|
1681
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.InspectionSuppressor
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.SuppressQuickFix
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.highlighter.createSuppressWarningActions
class KotlinInspectionSuppressor : InspectionSuppressor {
override fun getSuppressActions(element: PsiElement?, toolId: String): Array<SuppressQuickFix> {
element ?: return emptyArray()
return createSuppressWarningActions(element, Severity.WARNING, toolId).map {
object : SuppressQuickFix {
override fun getFamilyName() = it.familyName
override fun getName() = it.text
override fun applyFix(project: Project, descriptor: ProblemDescriptor) = it.invoke(project, null, descriptor.psiElement)
override fun isAvailable(project: Project, context: PsiElement) = it.isAvailable(project, null, context)
override fun isSuppressAll() = it.isSuppressAll
}
}.toTypedArray()
}
override fun isSuppressedFor(element: PsiElement, toolId: String): Boolean = KotlinCacheService.getInstance(element.project)
.getSuppressionCache()
.isSuppressed(element, element.containingFile, toolId, Severity.WARNING)
}
|
apache-2.0
|
6df6c83147af75f563cf52a1d695ae82
| 47.028571 | 158 | 0.750149 | 5.093939 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/jvm-debugger/test/testData/stepping/stepOut/stepOutSeveralInlineFunctions.kt
|
13
|
314
|
package stepOutSeveralInlineFunctions
fun main(args: Array<String>) {
f1 {
test(2)
}
test(3)
}
inline fun f1(f: () -> Unit) {
//Breakpoint!
val a = 1
f2 {
f()
}
val b = 2
}
inline fun f2(f: () -> Unit) {
val a = 1
f()
val b = 2
}
fun test(i: Int) = 1
|
apache-2.0
|
13a3bd3e1d2e1def651a8f6cff52633d
| 11.6 | 37 | 0.471338 | 2.754386 | false | true | false | false |
magmaOffenburg/RoboViz
|
src/main/kotlin/org/magmaoffenburg/roboviz/gui/menus/ConnectionMenu.kt
|
1
|
4103
|
package org.magmaoffenburg.roboviz.gui.menus
import org.magmaoffenburg.roboviz.configuration.Config.Networking
import org.magmaoffenburg.roboviz.etc.ConfigChangeListener
import org.magmaoffenburg.roboviz.rendering.Renderer
import java.awt.Component
import java.awt.event.KeyEvent
import java.net.InetAddress
import java.net.UnknownHostException
import javax.swing.*
/**
* the connection menu depends on swing more than other menus,
* therefore it does not have a separate actions class
*/
class ConnectionMenu(private val parent: Component) : MenuBase(), ConfigChangeListener {
private val group = ButtonGroup()
init {
initializeMenu()
}
private fun initializeMenu() {
text = "Connection"
addServerItems()
addSeparator()
addItem("Connect to...", KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK) { connectTo() }
}
private fun addServerItems() {
Networking.servers.forEach { pair ->
val item = JRadioButtonMenuItem("${pair.first}:${pair.second}")
item.isSelected = pair.first == Networking.currentHost && pair.second == Networking.currentPort
item.addActionListener {
changeServer(pair.first, pair.second)
}
group.add(item)
add(item)
}
}
private fun connectTo() {
val hostsComboBox = JComboBox<String>()
hostsComboBox.isEditable = true
Networking.servers.forEachIndexed { index, pair ->
hostsComboBox.addItem("${pair.first}:${pair.second}")
// select the current host
if (pair.first == Networking.currentHost && pair.second == Networking.currentPort) {
hostsComboBox.selectedIndex = index
}
}
SwingUtilities.invokeLater(hostsComboBox::requestFocusInWindow)
val saveCheckBox = JCheckBox("Add to config file")
val result = JOptionPane.showConfirmDialog(
parent,
arrayOf<Any>(hostsComboBox, saveCheckBox),
"Connect to...",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE
)
if (result == JOptionPane.OK_OPTION) {
hostsComboBox.selectedItem?.toString()?.let {
connectToHost(it, saveCheckBox.isSelected)
}
}
}
private fun connectToHost(raw: String, save: Boolean) {
var host = Networking.defaultServerHost
var port = Networking.defaultServerPort
if (raw.contains(":")) {
host = raw.substringBefore(":")
try {
port = raw.substringAfter(":").toInt()
} catch (ex: NumberFormatException) {
showErrorDialog("Invalid port", "The entered port ${raw.substringAfter(":")} is invalid")
return
}
}
// make sure the host is valid
try {
InetAddress.getByName(host)
} catch (ex: UnknownHostException) {
showErrorDialog("Invalid host", "The entered host $host is invalid")
return
}
if (save) {
Networking.servers.add(Pair(host, port)) // currently save is called on exit
}
// add server to menu and select it
val server = JRadioButtonMenuItem("$host:$port")
group.add(server)
add(server, itemCount - 2)
// change server
changeServer(host, port)
}
private fun showErrorDialog(title: String, message: String) {
JOptionPane.showMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE)
}
private fun changeServer(host: String, port: Int) {
// update selection
group.elements.toList().forEach {
it.isSelected = it.text == "$host:$port"
}
Renderer.drawings.clearAllShapeSets()
Renderer.netManager.server.changeConnection(host, port)
Networking.currentHost = host
Networking.currentPort = port
}
override fun onConfigChanged() {
removeAll()
initializeMenu()
}
}
|
apache-2.0
|
1d8bf524f7e03ec4ce84fa2f96fd6870
| 30.813953 | 107 | 0.60931 | 4.997564 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataDecompiler.kt
|
1
|
5928
|
// 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.decompiler.common
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiManager
import com.intellij.psi.compiled.ClassFileDecompilers
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.decompiler.KotlinDecompiledFileViewProvider
import org.jetbrains.kotlin.idea.decompiler.KtDecompiledFile
import org.jetbrains.kotlin.idea.decompiler.textBuilder.DecompiledText
import org.jetbrains.kotlin.idea.decompiler.textBuilder.buildDecompiledText
import org.jetbrains.kotlin.idea.decompiler.textBuilder.defaultDecompilerRendererOptions
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
import org.jetbrains.kotlin.metadata.deserialization.NameResolverImpl
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.serialization.SerializerExtensionProtocol
import org.jetbrains.kotlin.serialization.deserialization.ClassDeserializer
import org.jetbrains.kotlin.serialization.deserialization.FlexibleTypeDeserializer
import org.jetbrains.kotlin.serialization.deserialization.getClassId
import org.jetbrains.kotlin.utils.addIfNotNull
import java.io.IOException
abstract class KotlinMetadataDecompiler<out V : BinaryVersion>(
private val fileType: FileType,
private val serializerProtocol: () -> SerializerExtensionProtocol,
private val flexibleTypeDeserializer: FlexibleTypeDeserializer,
private val expectedBinaryVersion: () -> V,
private val invalidBinaryVersion: () -> V,
stubVersion: Int
) : ClassFileDecompilers.Full() {
private val metadataStubBuilder: KotlinMetadataStubBuilder =
KotlinMetadataStubBuilder(stubVersion, fileType, serializerProtocol, ::readFileSafely)
private val renderer: DescriptorRenderer by lazy {
DescriptorRenderer.withOptions { defaultDecompilerRendererOptions() }
}
abstract fun readFile(bytes: ByteArray, file: VirtualFile): FileWithMetadata?
override fun accepts(file: VirtualFile) = FileTypeRegistry.getInstance().isFileOfType(file, fileType)
override fun getStubBuilder() = metadataStubBuilder
override fun createFileViewProvider(file: VirtualFile, manager: PsiManager, physical: Boolean): FileViewProvider {
return KotlinDecompiledFileViewProvider(manager, file, physical) { provider ->
val virtualFile = provider.virtualFile
readFileSafely(virtualFile)?.let { fileWithMetadata ->
KtDecompiledFile(provider) {
check(it == virtualFile) {
"Unexpected file $it, expected ${virtualFile.fileType}"
}
buildDecompiledText(fileWithMetadata)
}
}
}
}
@TestOnly
fun readFile(file: VirtualFile) = readFileSafely(file)
private fun readFileSafely(file: VirtualFile, content: ByteArray? = null): FileWithMetadata? {
if (!file.isValid) return null
return try {
readFile(content ?: file.contentsToByteArray(false), file)
} catch (e: IOException) {
// This is needed because sometimes we're given VirtualFile instances that point to non-existent .jar entries.
// Such files are valid (isValid() returns true), but an attempt to read their contents results in a FileNotFoundException.
// Note that although calling "refresh()" instead of catching an exception would seem more correct here,
// it's not always allowed and also is likely to degrade performance
null
}
}
private fun buildDecompiledText(file: FileWithMetadata): DecompiledText {
return when (file) {
is FileWithMetadata.Incompatible -> {
createIncompatibleAbiVersionDecompiledText(expectedBinaryVersion(), file.version)
}
is FileWithMetadata.Compatible -> {
val packageFqName = file.packageFqName
val resolver = KotlinMetadataDeserializerForDecompiler(
packageFqName, file.proto, file.nameResolver, file.version,
serializerProtocol(), flexibleTypeDeserializer
)
val declarations = arrayListOf<DeclarationDescriptor>()
declarations.addAll(resolver.resolveDeclarationsInFacade(packageFqName))
for (classProto in file.classesToDecompile) {
val classId = file.nameResolver.getClassId(classProto.fqName)
declarations.addIfNotNull(resolver.resolveTopLevelClass(classId))
}
buildDecompiledText(packageFqName, declarations, renderer)
}
}
}
}
sealed class FileWithMetadata {
class Incompatible(val version: BinaryVersion) : FileWithMetadata()
open class Compatible(
val proto: ProtoBuf.PackageFragment,
val version: BinaryVersion,
serializerProtocol: SerializerExtensionProtocol
) : FileWithMetadata() {
val nameResolver = NameResolverImpl(proto.strings, proto.qualifiedNames)
val packageFqName = FqName(nameResolver.getPackageFqName(proto.`package`.getExtension(serializerProtocol.packageFqName)))
open val classesToDecompile: List<ProtoBuf.Class> =
proto.class_List.filter { proto ->
val classId = nameResolver.getClassId(proto.fqName)
!classId.isNestedClass && classId !in ClassDeserializer.BLACK_LIST
}
}
}
|
apache-2.0
|
39dba194d4eaabe12dd3d2b8f4fb4d3e
| 47.590164 | 158 | 0.724022 | 5.592453 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/resolve/references/KotlinPropertyWithGetterAndSetterAssignment.kt
|
12
|
588
|
class A {
var something: Int
set(value) {}
get() = 10
}
fun A.foo(a: A) {
print(a.<caret>something)
a.<caret>something = 1
a.<caret>something += 1
a.<caret>something++
--a.<caret>something
<caret>something++
(<caret>something)++
(<caret>something) = 1
(a.<caret>something) = 1
}
// MULTIRESOLVE
// REF1: (in A).something
// REF2: (in A).something
// REF3: (in A).something
// REF4: (in A).something
// REF5: (in A).something
// REF6: (in A).something
// REF7: (in A).something
// REF8: (in A).something
// REF9: (in A).something
|
apache-2.0
|
455b063ead22ccdecc9812db9c7b92db
| 19.275862 | 29 | 0.578231 | 2.925373 | false | false | false | false |
smmribeiro/intellij-community
|
platform/platform-impl/src/com/intellij/workspaceModel/ide/impl/WorkspaceModelRecoveryAction.kt
|
1
|
2176
|
// 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.workspaceModel.ide.impl
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.cache.AsyncRecoveryResult
import com.intellij.ide.actions.cache.ProjectRecoveryScope
import com.intellij.ide.actions.cache.RecoveryScope
import com.intellij.ide.actions.cache.RecoveryAction
import com.intellij.ide.impl.ProjectUtil
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.platform.PlatformProjectOpenProcessor
import java.nio.file.Files
import java.nio.file.Paths
import java.util.concurrent.CompletableFuture
class WorkspaceModelRecoveryAction : RecoveryAction {
override val performanceRate: Int
get() = 4000
override val presentableName: String
get() = IdeBundle.message("invalidate.workspace.model.recovery.action.presentable.name")
override val actionKey: String
get() = "reload-workspace-model"
override fun perform(recoveryScope: RecoveryScope): CompletableFuture<AsyncRecoveryResult> {
val project = recoveryScope.project
val file = Paths.get(project.basePath!!)
WorkspaceModelCacheImpl.invalidateCaches()
ApplicationManager.getApplication().invokeAndWait {
ProjectManagerEx.getInstanceEx().closeAndDispose(project)
}
val result = CompletableFuture<AsyncRecoveryResult>()
ApplicationManager.getApplication().invokeLater({
val projectFuture = ProjectUtil.openOrImportAsync(file, PlatformProjectOpenProcessor.createOptionsToOpenDotIdeaOrCreateNewIfNotExists(file, null))
projectFuture.handle { r, th -> if (th == null) result.complete(AsyncRecoveryResult(ProjectRecoveryScope(r!!), emptyList())) else result.completeExceptionally(th)};
}, ModalityState.NON_MODAL)
return result
}
override fun canBeApplied(recoveryScope: RecoveryScope): Boolean = recoveryScope is ProjectRecoveryScope && recoveryScope.project.basePath?.let { Files.isDirectory(Paths.get(it)) } == true
}
|
apache-2.0
|
3485f6fa937861cb708a90ddc6bdac50
| 50.833333 | 190 | 0.804228 | 4.649573 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/common/src/org/jetbrains/kotlin/idea/util/CallType.kt
|
1
|
17036
|
// 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.util
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.resolve.getDataFlowValueFactory
import org.jetbrains.kotlin.idea.resolve.getLanguageVersionSettings
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getReceiverExpression
import org.jetbrains.kotlin.psi.psiUtil.isImportDirectiveExpression
import org.jetbrains.kotlin.psi.psiUtil.isPackageDirectiveExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.DslMarkerUtils
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.resolve.calls.smartcasts.SmartCastManager
import org.jetbrains.kotlin.resolve.descriptorUtil.classValueType
import org.jetbrains.kotlin.resolve.descriptorUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindExclude
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.receivers.*
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS
import org.jetbrains.kotlin.util.isJavaDescriptor
import org.jetbrains.kotlin.util.supertypesWithAny
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.util.*
sealed class CallType<TReceiver : KtElement?>(val descriptorKindFilter: DescriptorKindFilter) {
object UNKNOWN : CallType<Nothing?>(DescriptorKindFilter.ALL)
object DEFAULT : CallType<Nothing?>(DescriptorKindFilter.ALL)
object DOT : CallType<KtExpression>(DescriptorKindFilter.ALL)
object SAFE : CallType<KtExpression>(DescriptorKindFilter.ALL)
object SUPER_MEMBERS : CallType<KtSuperExpression>(
DescriptorKindFilter.CALLABLES exclude DescriptorKindExclude.Extensions exclude AbstractMembersExclude
)
object INFIX : CallType<KtExpression>(DescriptorKindFilter.FUNCTIONS exclude NonInfixExclude)
object OPERATOR : CallType<KtExpression>(DescriptorKindFilter.FUNCTIONS exclude NonOperatorExclude)
object CALLABLE_REFERENCE : CallType<KtExpression?>(DescriptorKindFilter.CALLABLES exclude CallableReferenceExclude)
object IMPORT_DIRECTIVE : CallType<KtExpression?>(DescriptorKindFilter.ALL)
object PACKAGE_DIRECTIVE : CallType<KtExpression?>(DescriptorKindFilter.PACKAGES)
object TYPE : CallType<KtExpression?>(
DescriptorKindFilter(DescriptorKindFilter.CLASSIFIERS_MASK or DescriptorKindFilter.PACKAGES_MASK)
exclude DescriptorKindExclude.EnumEntry
)
object DELEGATE : CallType<KtExpression?>(DescriptorKindFilter.FUNCTIONS exclude NonOperatorExclude)
object ANNOTATION : CallType<KtExpression?>(
DescriptorKindFilter(DescriptorKindFilter.CLASSIFIERS_MASK or DescriptorKindFilter.PACKAGES_MASK)
exclude NonAnnotationClassifierExclude
)
private object NonInfixExclude : DescriptorKindExclude() {
override fun excludes(descriptor: DeclarationDescriptor) =
!(descriptor is SimpleFunctionDescriptor && descriptor.isInfix)
override val fullyExcludedDescriptorKinds: Int
get() = 0
}
private object NonOperatorExclude : DescriptorKindExclude() {
override fun excludes(descriptor: DeclarationDescriptor) =
!(descriptor is SimpleFunctionDescriptor && descriptor.isOperator)
override val fullyExcludedDescriptorKinds: Int
get() = 0
}
private object CallableReferenceExclude : DescriptorKindExclude() {
override fun excludes(descriptor: DeclarationDescriptor) /* currently not supported for locals and synthetic */ =
descriptor !is CallableMemberDescriptor || descriptor.kind == CallableMemberDescriptor.Kind.SYNTHESIZED
override val fullyExcludedDescriptorKinds: Int
get() = 0
}
private object NonAnnotationClassifierExclude : DescriptorKindExclude() {
override fun excludes(descriptor: DeclarationDescriptor): Boolean {
if (descriptor !is ClassifierDescriptor) return false
return descriptor !is ClassDescriptor || descriptor.kind != ClassKind.ANNOTATION_CLASS
}
override val fullyExcludedDescriptorKinds: Int get() = 0
}
private object AbstractMembersExclude : DescriptorKindExclude() {
override fun excludes(descriptor: DeclarationDescriptor) =
descriptor is CallableMemberDescriptor && descriptor.modality == Modality.ABSTRACT
override val fullyExcludedDescriptorKinds: Int
get() = 0
}
}
sealed class CallTypeAndReceiver<TReceiver : KtElement?, out TCallType : CallType<TReceiver>>(
val callType: TCallType,
val receiver: TReceiver
) {
object UNKNOWN : CallTypeAndReceiver<Nothing?, CallType.UNKNOWN>(CallType.UNKNOWN, null)
object DEFAULT : CallTypeAndReceiver<Nothing?, CallType.DEFAULT>(CallType.DEFAULT, null)
class DOT(receiver: KtExpression) : CallTypeAndReceiver<KtExpression, CallType.DOT>(CallType.DOT, receiver)
class SAFE(receiver: KtExpression) : CallTypeAndReceiver<KtExpression, CallType.SAFE>(CallType.SAFE, receiver)
class SUPER_MEMBERS(receiver: KtSuperExpression) : CallTypeAndReceiver<KtSuperExpression, CallType.SUPER_MEMBERS>(
CallType.SUPER_MEMBERS, receiver
)
class INFIX(receiver: KtExpression) : CallTypeAndReceiver<KtExpression, CallType.INFIX>(CallType.INFIX, receiver)
class OPERATOR(receiver: KtExpression) : CallTypeAndReceiver<KtExpression, CallType.OPERATOR>(CallType.OPERATOR, receiver)
class CALLABLE_REFERENCE(receiver: KtExpression?) : CallTypeAndReceiver<KtExpression?, CallType.CALLABLE_REFERENCE>(
CallType.CALLABLE_REFERENCE, receiver
)
class IMPORT_DIRECTIVE(receiver: KtExpression?) : CallTypeAndReceiver<KtExpression?, CallType.IMPORT_DIRECTIVE>(
CallType.IMPORT_DIRECTIVE, receiver
)
class PACKAGE_DIRECTIVE(receiver: KtExpression?) :
CallTypeAndReceiver<KtExpression?, CallType.PACKAGE_DIRECTIVE>(CallType.PACKAGE_DIRECTIVE, receiver)
class TYPE(receiver: KtExpression?) : CallTypeAndReceiver<KtExpression?, CallType.TYPE>(CallType.TYPE, receiver)
class DELEGATE(receiver: KtExpression?) : CallTypeAndReceiver<KtExpression?, CallType.DELEGATE>(CallType.DELEGATE, receiver)
class ANNOTATION(receiver: KtExpression?) : CallTypeAndReceiver<KtExpression?, CallType.ANNOTATION>(CallType.ANNOTATION, receiver)
companion object {
fun detect(expression: KtSimpleNameExpression): CallTypeAndReceiver<*, *> {
val parent = expression.parent
if (parent is KtCallableReferenceExpression && expression == parent.callableReference) {
return CALLABLE_REFERENCE(parent.receiverExpression)
}
val receiverExpression = expression.getReceiverExpression()
if (expression.isImportDirectiveExpression()) {
return IMPORT_DIRECTIVE(receiverExpression)
}
if (expression.isPackageDirectiveExpression()) {
return PACKAGE_DIRECTIVE(receiverExpression)
}
if (parent is KtUserType) {
val constructorCallee = (parent.parent as? KtTypeReference)?.parent as? KtConstructorCalleeExpression
if (constructorCallee != null && constructorCallee.parent is KtAnnotationEntry) {
return ANNOTATION(receiverExpression)
}
return TYPE(receiverExpression)
}
when (expression) {
is KtOperationReferenceExpression -> {
if (receiverExpression == null) {
return UNKNOWN // incomplete code
}
return when (parent) {
is KtBinaryExpression -> {
if (parent.operationToken == KtTokens.IDENTIFIER)
INFIX(receiverExpression)
else
OPERATOR(receiverExpression)
}
is KtUnaryExpression -> OPERATOR(receiverExpression)
else -> error("Unknown parent for JetOperationReferenceExpression: $parent with text '${parent.text}'")
}
}
is KtNameReferenceExpression -> {
if (receiverExpression == null) {
return DEFAULT
}
if (receiverExpression is KtSuperExpression) {
return SUPER_MEMBERS(receiverExpression)
}
return when (parent) {
is KtCallExpression -> {
if ((parent.parent as KtQualifiedExpression).operationSign == KtTokens.SAFE_ACCESS)
SAFE(receiverExpression)
else
DOT(receiverExpression)
}
is KtQualifiedExpression -> {
if (parent.operationSign == KtTokens.SAFE_ACCESS)
SAFE(receiverExpression)
else
DOT(receiverExpression)
}
else -> error("Unknown parent for JetNameReferenceExpression with receiver: $parent")
}
}
else -> return UNKNOWN
}
}
}
}
data class ReceiverType(
val type: KotlinType,
val receiverIndex: Int,
val implicitValue: ReceiverValue? = null
) {
val implicit: Boolean get() = implicitValue != null
fun extractDslMarkers() =
implicitValue?.let(DslMarkerUtils::extractDslMarkerFqNames)?.all()
?: DslMarkerUtils.extractDslMarkerFqNames(type)
}
fun CallTypeAndReceiver<*, *>.receiverTypes(
bindingContext: BindingContext,
contextElement: PsiElement,
moduleDescriptor: ModuleDescriptor,
resolutionFacade: ResolutionFacade,
stableSmartCastsOnly: Boolean
): List<KotlinType>? {
return receiverTypesWithIndex(bindingContext, contextElement, moduleDescriptor, resolutionFacade, stableSmartCastsOnly)?.map { it.type }
}
fun CallTypeAndReceiver<*, *>.receiverTypesWithIndex(
bindingContext: BindingContext,
contextElement: PsiElement,
moduleDescriptor: ModuleDescriptor,
resolutionFacade: ResolutionFacade,
stableSmartCastsOnly: Boolean,
withImplicitReceiversWhenExplicitPresent: Boolean = false
): List<ReceiverType>? {
val languageVersionSettings = resolutionFacade.getLanguageVersionSettings()
val receiverExpression: KtExpression?
when (this) {
is CallTypeAndReceiver.CALLABLE_REFERENCE -> {
if (receiver != null) {
return when (val lhs = bindingContext[BindingContext.DOUBLE_COLON_LHS, receiver] ?: return emptyList()) {
is DoubleColonLHS.Type -> listOf(ReceiverType(lhs.type, 0))
is DoubleColonLHS.Expression -> {
val receiverValue = ExpressionReceiver.create(receiver, lhs.type, bindingContext)
receiverValueTypes(
receiverValue, lhs.dataFlowInfo, bindingContext,
moduleDescriptor, stableSmartCastsOnly,
resolutionFacade
).map { ReceiverType(it, 0) }
}
}
} else {
return emptyList()
}
}
is CallTypeAndReceiver.DEFAULT -> receiverExpression = null
is CallTypeAndReceiver.DOT -> receiverExpression = receiver
is CallTypeAndReceiver.SAFE -> receiverExpression = receiver
is CallTypeAndReceiver.INFIX -> receiverExpression = receiver
is CallTypeAndReceiver.OPERATOR -> receiverExpression = receiver
is CallTypeAndReceiver.DELEGATE -> receiverExpression = receiver
is CallTypeAndReceiver.SUPER_MEMBERS -> {
val qualifier = receiver.superTypeQualifier
return if (qualifier != null) {
listOfNotNull(bindingContext.getType(receiver)).map { ReceiverType(it, 0) }
} else {
val resolutionScope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
val classDescriptor =
resolutionScope.ownerDescriptor.parentsWithSelf.firstIsInstanceOrNull<ClassDescriptor>() ?: return emptyList()
classDescriptor.typeConstructor.supertypesWithAny().map { ReceiverType(it, 0) }
}
}
is CallTypeAndReceiver.IMPORT_DIRECTIVE,
is CallTypeAndReceiver.PACKAGE_DIRECTIVE,
is CallTypeAndReceiver.TYPE,
is CallTypeAndReceiver.ANNOTATION,
is CallTypeAndReceiver.UNKNOWN ->
return null
}
val resolutionScope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
fun extractReceiverTypeFrom(descriptor: ClassDescriptor): KotlinType? = descriptor.classValueType
fun tryExtractReceiver(context: BindingContext) = context.get(BindingContext.QUALIFIER, receiverExpression)
fun tryExtractClassDescriptor(context: BindingContext): ClassDescriptor? =
(tryExtractReceiver(context) as? ClassQualifier)?.descriptor
fun tryExtractClassDescriptorFromAlias(context: BindingContext): ClassDescriptor? =
(tryExtractReceiver(context) as? TypeAliasQualifier)?.classDescriptor
fun extractReceiverTypeFrom(context: BindingContext, receiverExpression: KtExpression): KotlinType? {
return context.getType(receiverExpression) ?: tryExtractClassDescriptor(context)?.let { extractReceiverTypeFrom(it) }
?: tryExtractClassDescriptorFromAlias(context)?.let { extractReceiverTypeFrom(it) }
}
val expressionReceiver = receiverExpression?.let {
val receiverType = extractReceiverTypeFrom(bindingContext, receiverExpression) ?: return emptyList()
ExpressionReceiver.create(receiverExpression, receiverType, bindingContext)
}
val implicitReceiverValues = resolutionScope.getImplicitReceiversWithInstance(
excludeShadowedByDslMarkers = languageVersionSettings.supportsFeature(LanguageFeature.DslMarkersSupport)
).map { it.value }
val dataFlowInfo = bindingContext.getDataFlowInfoBefore(contextElement)
val result = ArrayList<ReceiverType>()
var receiverIndex = 0
fun addReceiverType(receiverValue: ReceiverValue, implicit: Boolean) {
val types = receiverValueTypes(
receiverValue, dataFlowInfo, bindingContext, moduleDescriptor, stableSmartCastsOnly,
resolutionFacade
)
types.mapTo(result) { type -> ReceiverType(type, receiverIndex, receiverValue.takeIf { implicit }) }
receiverIndex++
}
if (withImplicitReceiversWhenExplicitPresent || expressionReceiver == null) {
implicitReceiverValues.forEach { addReceiverType(it, true) }
}
if (expressionReceiver != null) {
addReceiverType(expressionReceiver, false)
}
return result
}
@OptIn(FrontendInternals::class)
private fun receiverValueTypes(
receiverValue: ReceiverValue,
dataFlowInfo: DataFlowInfo,
bindingContext: BindingContext,
moduleDescriptor: ModuleDescriptor,
stableSmartCastsOnly: Boolean,
resolutionFacade: ResolutionFacade
): List<KotlinType> {
val languageVersionSettings = resolutionFacade.getLanguageVersionSettings()
val dataFlowValueFactory = resolutionFacade.getDataFlowValueFactory()
val smartCastManager = resolutionFacade.frontendService<SmartCastManager>()
val dataFlowValue = dataFlowValueFactory.createDataFlowValue(receiverValue, bindingContext, moduleDescriptor)
return if (dataFlowValue.isStable || !stableSmartCastsOnly) { // we don't include smart cast receiver types for "unstable" receiver value to mark members grayed
smartCastManager.getSmartCastVariantsWithLessSpecificExcluded(
receiverValue,
bindingContext,
moduleDescriptor,
dataFlowInfo,
languageVersionSettings,
dataFlowValueFactory
)
} else {
listOf(receiverValue.type)
}
}
|
apache-2.0
|
2f10d5fdbe09592f170396b3141a5771
| 43.949868 | 164 | 0.697229 | 6.260933 | false | false | false | false |
pajato/Argus
|
app/src/androidTest/java/com/pajato/argus/StringExtensionsUnitTest.kt
|
1
|
1967
|
package com.pajato.argus
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class StringExtensionsUnitTest {
/** Test that stripping white-space from the middle of a string works properly. */
@Test fun testStripMiddle() {
val testString = "a string with embedded white-space."
val actual = testString.stripMiddle()
val expected = testString.replace(Regex("\\s+"), " ")
assertEquals("The string was not stripped correctly!", expected, actual)
}
/** Test that stripping white-space from the start of a string works properly. */
@Test fun testStripLeft() {
val testString = " a string with leading white-space."
val actual = testString.stripLeft()
val expected = testString.replace(Regex("^\\s+"), "")
assertEquals("The string was not stripped correctly!", expected, actual)
}
/** Test that stripping white-space from the end of a string works properly. */
@Test fun testStripRight() {
val testString = "a string with trailing white-space. "
val actual = testString.stripRight()
val expected = testString.replace(Regex("\\s+$"), "")
assertEquals("The string was not stripped correctly!", expected, actual)
}
/** Test that stripping all white-space from a string works properly. */
@Test fun testStrip() {
val testString = " a string with leading, trailing and embedded white-space."
val actual = testString.strip()
val exp1 = testString.replace(Regex("^\\s+"), "")
val exp2 = exp1.replace(Regex("\\s+$"), "")
val expected = exp2.replace(Regex("\\s+"), " ")
assertEquals("The string was not stripped correctly!", expected, actual)
}
}
|
gpl-3.0
|
2e706e432d4cf39aeab54688037c3e94
| 40.851064 | 99 | 0.624301 | 4.490868 | false | true | false | false |
testIT-LivingDoc/livingdoc2
|
livingdoc-tests/src/test/kotlin/org/livingdoc/example/CalculatorGherkinHtml.kt
|
2
|
2308
|
package org.livingdoc.example
import org.assertj.core.api.Assertions.assertThat
import org.livingdoc.api.documents.ExecutableDocument
import org.livingdoc.api.fixtures.scenarios.Binding
import org.livingdoc.api.fixtures.scenarios.ScenarioFixture
import org.livingdoc.api.fixtures.scenarios.Step
import org.livingdoc.api.tagging.Tag
@Tag("gherkin")
@ExecutableDocument("local://CalculatorGherkin.html")
class CalculatorGherkinHtml {
@ScenarioFixture
class CalculatorScenario {
private var lastResult: Float? = null
private lateinit var cut: Calculator
@Step("a calculator")
fun `initialize calculator`() {
cut = Calculator()
}
@Step("I add {lhs} and {rhs}")
fun `add two numbers`(@Binding("lhs") lhs: Float, @Binding("rhs") rhs: Float) {
lastResult = cut.sum(lhs, rhs)
}
@Step("I get {result}")
fun `check last result`(@Binding("result") result: Float) {
assertThat(lastResult).isEqualTo(result)
}
@Step("result is less than {result}")
fun `check last result less than`(@Binding("result") result: Float) {
assertThat(lastResult).isLessThan(result)
}
@Step("result is greater than {result}")
fun `check last result greater than`(@Binding("result") result: Float) {
assertThat(lastResult).isGreaterThan(result)
}
}
@ScenarioFixture
class CoffeMachineScenario {
private lateinit var cm: CoffeeMachine
@Step("there are {n} coffees left in the machine")
fun `left coffees`(@Binding("n") n: Int) {
cm = CoffeeMachine()
cm.setLeftCoffees(n)
}
@Step("I have deposited {n} dollar")
fun `deposited money`(@Binding("n") n: Float) {
cm.depositMoney(n)
}
@Step("I press the coffee button")
fun `press button`() {
cm.triggered = true
}
@Step("I should {not} be served a coffee")
fun `expected output`(
@Binding("not") not: String?
) {
if (not.isNullOrBlank()) {
assertThat(cm.getCoffee()).isTrue()
} else {
assertThat(cm.getCoffee()).isFalse()
}
}
}
}
|
apache-2.0
|
28f3e6fb1996a53224e248bab540217a
| 30.189189 | 87 | 0.591854 | 4.39619 | false | false | false | false |
leesocrates/remind
|
app/src/main/java/com/lee/socrates/remind/util/UserInfoManager.kt
|
1
|
742
|
package com.lee.socrates.remind.util
import com.lee.socrates.remind.entity.User
/**
* Created by lee on 2017/6/27.
*/
object UserInfoManager {
var userMap: HashMap<String, User> = HashMap()
var currentUserName: String = ""
fun hasLoginUser(): Boolean {
return getCurrentUser().isLogin
}
fun addUser(user: User?) {
if (user !== null) {
currentUserName = user.userAccount
userMap.put(user.userAccount, user)
}
}
fun getCurrentUser(): User {
var user: User? =null
if (currentUserName.isNotEmpty()){
user = userMap[currentUserName]
}
if(user === null){
user = User()
}
return user
}
}
|
gpl-3.0
|
2ae265e8c269e3ecfc63ff60b18cbd09
| 19.638889 | 50 | 0.566038 | 4.054645 | false | false | false | false |
kerubistan/kerub
|
src/main/kotlin/com/github/kerubistan/kerub/utils/junix/ssh/openssh/OpenSsh.kt
|
2
|
4586
|
package com.github.kerubistan.kerub.utils.junix.ssh.openssh
import com.github.kerubistan.kerub.host.appendToFile
import com.github.kerubistan.kerub.host.checkFileExists
import com.github.kerubistan.kerub.host.executeOrDie
import com.github.kerubistan.kerub.host.getFileContents
import com.github.kerubistan.kerub.utils.getLogger
import org.apache.sshd.client.session.ClientSession
import org.apache.sshd.client.subsystem.sftp.SftpClient
import org.apache.sshd.common.subsystem.sftp.SftpConstants
import java.math.BigInteger
/**
* junix utility wrapper to manipulate the configuration files of openssh client and server
*/
object OpenSsh {
private val logger = getLogger()
private const val knownHosts = ".ssh/known_hosts"
private const val authorizedKeys = ".ssh/authorized_keys"
private val ddOutputRecordsLineFormat = "\\d+\\+\\d+ records out".toRegex()
private val ddInputRecordsLineFormat = "\\d+\\+\\d+ records in".toRegex()
private val copyBlockDeviceErrorMatcher = mapOf(
0 to ddInputRecordsLineFormat,
1 to ddOutputRecordsLineFormat,
3 to ddInputRecordsLineFormat,
4 to ddOutputRecordsLineFormat
)
fun verifySshConnection(session: ClientSession, targetAddress: String) {
session.executeOrDie("""bash -c "ssh -o BatchMode=true $targetAddress echo connected" """)
}
fun keyGen(session: ClientSession, password: String? = null): String =
session.createSftpClient().use {
checkSShDir(it, session)
if (it.checkFileExists("/root/.ssh/id_rsa.pub")) {
logger.warn("The file already exists, skipping generation")
} else {
session.executeOrDie(
"ssh-keygen -t rsa -N '${password ?: ""}' -f /root/.ssh/id_rsa ")
}
it.getFileContents("/root/.ssh/id_rsa.pub")
}
fun authorize(session: ClientSession, pubkey: String) {
//synchronized to make sure multiple threads do not overwrite each other's results
synchronized(session) {
session.createSftpClient().use {
checkSShDir(it, session)
logger.debug("{}: installing public key", session)
it.appendToFile(authorizedKeys, "\n$pubkey")
val stat = it.stat(authorizedKeys)
logger.debug("{}: setting permissions", session)
it.setStat(authorizedKeys, stat.perms(SftpConstants.S_IRUSR or SftpConstants.S_IWUSR))
}
}
}
fun unauthorize(session: ClientSession, pubkey: String) {
synchronized(session) {
session.createSftpClient().use {
val filtered = it.read(authorizedKeys).reader(Charsets.US_ASCII).readLines()
.filterNot { it.contains(pubkey) }.joinToString("\n")
it.write(authorizedKeys).writer(Charsets.US_ASCII).write(filtered)
}
}
}
private fun checkSShDir(it: SftpClient, session: ClientSession) {
if (!it.checkFileExists(".ssh")) {
logger.debug("{}: creating .ssh directory", session)
it.mkdir(".ssh")
}
}
fun addKnownHost(session: ClientSession, hostAddress: String, pubKey: String) {
synchronized(session) {
session.createSftpClient().use {
checkSShDir(it, session)
it.appendToFile(
knownHosts,
"$hostAddress $pubKey\n"
)
val stat = it.stat(knownHosts)
it.setStat(knownHosts, stat.perms(SftpConstants.S_IRUSR or SftpConstants.S_IWUSR))
}
}
}
fun removeKnownHost(session: ClientSession, hostAddress: String) {
synchronized(session) {
session.createSftpClient().use {
val filtered = it.read(authorizedKeys).reader(Charsets.US_ASCII).readLines()
.filterNot { it.startsWith("$hostAddress ssh-rsa") }.joinToString("\n")
it.write(authorizedKeys).writer(Charsets.US_ASCII).write(filtered)
}
}
}
private val String?.pipeIn get() = if (this == null) "" else "| $this"
private val String?.pipeOut get() = if (this == null) "" else "$this |"
private fun Any?.flag(paramName: String) = if (this == null) {
""
} else {
"$paramName=$this"
}
fun copyBlockDevice(
session: ClientSession,
sourceDevice: String,
targetAddress: String,
targetDevice: String,
filters: Pair<String, String>? = null,
bytes: BigInteger? = null
) {
session.executeOrDie(
"""
bash -c "
dd if=$sourceDevice ${bytes.flag("count")} ${filters?.first.pipeIn}
${if (bytes != null) "iflag=count_bytes" else ""}
| ssh -o BatchMode=true $targetAddress ${filters?.second.pipeOut} dd of=$targetDevice
" """.trimIndent().replace("\n", ""),
isError = {
it.isNotBlank() &&
it.trim().lines().filter(String::isNotBlank).let { lines ->
lines.size != 6
!copyBlockDeviceErrorMatcher.all { (lineNr, regexp) ->
lines[lineNr].matches(regexp)
}
}
}
)
}
}
|
apache-2.0
|
95f9a3fe6857f2ae4557225fb561a5ab
| 31.992806 | 92 | 0.696904 | 3.53858 | false | false | false | false |
quran/quran_android
|
app/src/main/java/com/quran/labs/androidquran/ui/fragment/JuzListFragment.kt
|
2
|
6344
|
package com.quran.labs.androidquran.ui.fragment
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.quran.data.core.QuranInfo
import com.quran.labs.androidquran.QuranApplication
import com.quran.labs.androidquran.R
import com.quran.labs.androidquran.data.Constants
import com.quran.labs.androidquran.data.QuranDisplayData
import com.quran.labs.androidquran.data.QuranFileConstants
import com.quran.labs.androidquran.presenter.data.JuzListPresenter
import com.quran.labs.androidquran.ui.QuranActivity
import com.quran.labs.androidquran.ui.helpers.QuranListAdapter
import com.quran.labs.androidquran.ui.helpers.QuranRow
import com.quran.labs.androidquran.ui.helpers.QuranRow.Builder
import com.quran.labs.androidquran.util.QuranSettings
import com.quran.labs.androidquran.util.QuranUtils
import com.quran.labs.androidquran.view.JuzView
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.observers.DisposableSingleObserver
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* Fragment that displays a list of all Juz (using [QuranListAdapter], each divided into
* 8 parts (with headings for each Juz).
* When a Juz part is selected (or a Juz heading), [QuranActivity.jumpTo] is called to
* jump to that page.
*/
class JuzListFragment : Fragment() {
private var recyclerView: RecyclerView? = null
private var disposable: Disposable? = null
private var adapter: QuranListAdapter? = null
private val mainScope: CoroutineScope = MainScope()
@Inject
lateinit var quranInfo: QuranInfo
@Inject
lateinit var quranDisplayData: QuranDisplayData
@Inject
lateinit var juzListPresenter: JuzListPresenter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.quran_list, container, false)
val context = requireContext()
val recyclerView = view.findViewById<RecyclerView>(R.id.recycler_view).apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(context)
itemAnimator = DefaultItemAnimator()
}
val adapter = QuranListAdapter(context, recyclerView, emptyArray(), false)
recyclerView.adapter = adapter
this.recyclerView = recyclerView
this.adapter = adapter
return view
}
override fun onDestroyView() {
adapter = null
recyclerView = null
super.onDestroyView()
}
override fun onAttach(context: Context) {
super.onAttach(context)
(context.applicationContext as QuranApplication).applicationComponent.inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mainScope.launch {
fetchJuz2List()
}
}
override fun onPause() {
disposable?.dispose()
super.onPause()
}
override fun onResume() {
val activity = requireActivity()
if (activity is QuranActivity) {
disposable = activity.latestPageObservable
.first(Constants.NO_PAGE)
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableSingleObserver<Int>() {
override fun onSuccess(recentPage: Int) {
if (recentPage != Constants.NO_PAGE) {
val juz = quranInfo.getJuzFromPage(recentPage)
val position = (juz - 1) * 9
recyclerView?.scrollToPosition(position)
}
}
override fun onError(e: Throwable) {}
})
}
val settings = QuranSettings.getInstance(activity)
if (settings.isArabicNames) {
updateScrollBarPositionHoneycomb()
}
super.onResume()
}
private fun updateScrollBarPositionHoneycomb() {
recyclerView?.verticalScrollbarPosition = View.SCROLLBAR_POSITION_LEFT
}
private suspend fun fetchJuz2List() {
val quarters = if (QuranFileConstants.FETCH_QUARTER_NAMES_FROM_DATABASE) {
juzListPresenter.quarters().toTypedArray()
} else {
val context = context
if (context != null) {
val res = context.resources
res.getStringArray(R.array.quarter_prefix_array)
} else {
emptyArray<String>()
}
}
if (isAdded && quarters.isNotEmpty()) {
updateJuz2List(quarters)
}
}
private fun updateJuz2List(quarters: Array<String>) {
val activity: Activity = activity ?: return
val elements = arrayOfNulls<QuranRow>(Constants.JUZ2_COUNT * (8 + 1))
var ctr = 0
for (i in 0 until 8 * Constants.JUZ2_COUNT) {
val pos = quranInfo.getQuarterByIndex(i)
val page = quranInfo.getPageFromSuraAyah(pos.sura, pos.ayah)
if (i % 8 == 0) {
val juz = 1 + i / 8
val juzTitle = activity.getString(
R.string.juz2_description,
QuranUtils.getLocalizedNumber(activity, juz)
)
val builder = Builder()
.withType(QuranRow.HEADER)
.withText(juzTitle)
.withPage(quranInfo.getStartingPageForJuz(juz))
elements[ctr++] = builder.build()
}
val metadata = getString(
R.string.sura_ayah_notification_str,
quranDisplayData.getSuraName(activity, pos.sura, false), pos.ayah
)
val builder = Builder()
.withText(quarters[i])
.withMetadata(metadata)
.withPage(page)
.withJuzType(ENTRY_TYPES[i % 4])
if (i % 4 == 0) {
val overlayText = QuranUtils.getLocalizedNumber(activity, 1 + i / 4)
builder.withJuzOverlayText(overlayText)
}
elements[ctr++] = builder.build()
}
adapter?.setElements(elements.filterNotNull().toTypedArray())
}
companion object {
private val ENTRY_TYPES = intArrayOf(
JuzView.TYPE_JUZ, JuzView.TYPE_QUARTER,
JuzView.TYPE_HALF, JuzView.TYPE_THREE_QUARTERS
)
fun newInstance(): JuzListFragment {
return JuzListFragment()
}
}
}
|
gpl-3.0
|
4de920eefb3bccd0307e4723a456b915
| 31.203046 | 88 | 0.709647 | 4.357143 | false | false | false | false |
orgzly/orgzly-android
|
app/src/main/java/com/orgzly/android/ui/repo/webdav/WebdavRepoViewModel.kt
|
1
|
2189
|
package com.orgzly.android.ui.repo.webdav
import android.net.Uri
import androidx.lifecycle.MutableLiveData
import com.orgzly.R
import com.orgzly.android.App
import com.orgzly.android.data.DataRepository
import com.orgzly.android.repos.WebdavRepo
import com.orgzly.android.ui.repo.RepoViewModel
import com.thegrizzlylabs.sardineandroid.impl.SardineException
class WebdavRepoViewModel(
dataRepository: DataRepository,
override var repoId: Long
) : RepoViewModel(dataRepository, repoId) {
var certificates: MutableLiveData<String?> = MutableLiveData(null)
sealed class ConnectionResult {
data class InProgress(val msg: Int): ConnectionResult()
data class Success(val bookCount: Int): ConnectionResult()
data class Error(val msg: Any): ConnectionResult()
}
val connectionTestStatus: MutableLiveData<ConnectionResult> = MutableLiveData()
fun testConnection(uriString: String, username: String, password: String, certificates: String?) {
App.EXECUTORS.networkIO().execute {
try {
connectionTestStatus.postValue(ConnectionResult.InProgress(R.string.connecting))
val uri = Uri.parse(uriString)
val bookCount = WebdavRepo(repoId, uri, username, password, certificates).run {
books.size
}
connectionTestStatus.postValue(ConnectionResult.Success(bookCount))
} catch (e: Exception) {
e.printStackTrace()
val result = when (e) {
is SardineException -> {
when (e.statusCode) {
401 -> // Unauthorized
ConnectionResult.Error(R.string.webdav_test_error_auth)
else ->
ConnectionResult.Error("${e.statusCode}: ${e.responsePhrase}: ${e.localizedMessage}")
}
}
else -> ConnectionResult.Error(e.message ?: R.string.webdav_test_error_unknown)
}
connectionTestStatus.postValue(result)
}
}
}
}
|
gpl-3.0
|
072d9384b40c4d681673d25935170da1
| 35.5 | 117 | 0.610324 | 5.090698 | false | true | false | false |
markusfisch/BinaryEye
|
app/src/main/kotlin/de/markusfisch/android/binaryeye/net/ScanSender.kt
|
1
|
3227
|
package de.markusfisch.android.binaryeye.net
import de.markusfisch.android.binaryeye.content.toHexString
import de.markusfisch.android.binaryeye.database.Scan
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.ProtocolException
import java.net.URL
fun Scan.sendAsync(
url: String,
type: String,
callback: (Int?, String?) -> Unit
) {
CoroutineScope(Dispatchers.IO).launch(Dispatchers.IO) {
val response = send(url, type)
withContext(Dispatchers.Main) {
callback(response.code, response.body)
}
}
}
private fun Scan.send(url: String, type: String): Response {
return when (type) {
"1" -> request(
url + "?" + asUrlArguments()
)
"2" -> request(url) { con ->
con.requestMethod = "POST"
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
con.outputStream.apply {
write(asUrlArguments().toByteArray())
close()
}
}
"3" -> request(url) { con ->
con.requestMethod = "POST"
con.setRequestProperty("Content-Type", "application/json")
con.outputStream.apply {
write(asJson().toString().toByteArray())
close()
}
}
else -> request(
url + content.urlEncode()
)
}
}
private fun Scan.asUrlArguments(): String = getMap().map { (k, v) ->
"${k}=${v.urlEncode()}"
}.joinToString("&")
private fun Scan.asJson() = JSONObject().apply {
getMap().forEach { (k, v) -> put(k, v) }
}
private fun Scan.getMap(): Map<String, String> = mapOf(
"content" to content,
"raw" to raw?.toHexString(),
"format" to format,
"errorCorrectionLevel" to errorCorrectionLevel,
"versionNumber" to versionNumber.toString(),
"sequenceSize" to sequenceSize.toString(),
"sequenceIndex" to sequenceIndex.toString(),
"sequenceId" to sequenceId,
"country" to country,
"addOn" to addOn,
"price" to price,
"issueNumber" to issueNumber,
"timestamp" to dateTime
).filterNullValues()
private fun Map<String, String?>.filterNullValues() =
filterValues { it != null }.mapValues { it.value as String }
private fun request(
url: String,
writer: ((HttpURLConnection) -> Any)? = null
): Response {
var con: HttpURLConnection? = null
return try {
con = URL(url).openConnection() as HttpURLConnection
con.connectTimeout = 5000
writer?.invoke(con)
val body = con.inputStream.readHead()
Response(con.responseCode, body)
} catch (e: ProtocolException) {
Response(null, e.message)
} catch (e: IOException) {
try {
val body = con?.errorStream?.readHead() ?: e.message
Response(con?.responseCode, body)
} catch (e: IOException) {
Response(null, e.message)
}
} finally {
con?.disconnect()
}
}
private fun InputStream.readHead(): String {
val sb = StringBuilder()
val br = BufferedReader(InputStreamReader(this))
var line = br.readLine()
var i = 0
while (line != null && sb.length < 240) {
sb.append(line)
line = br.readLine()
++i
}
br.close()
return sb.toString()
}
private data class Response(val code: Int?, val body: String?)
|
mit
|
7249d0962e01ce58ce51ab71b75529ed
| 25.024194 | 78 | 0.704369 | 3.368476 | false | false | false | false |
davidbuzz/ardupilot
|
libraries/AP_HAL_ESP32/utils/profile/LinkerScriptGenerator.kt
|
18
|
2803
|
import java.io.File
import java.io.FileOutputStream
import java.nio.charset.Charset
import java.util.*
import java.util.regex.Pattern
import kotlin.collections.ArrayList
data class Func(
var symbol: String,
var place: String,
var address: Int,
var size: Int,
var count: Int
)
val p = Pattern.compile(" (?:\\.iram1|\\.text)+\\.(\\S*)\\s*(0x.{16})\\s*(0x\\S*)\\s*(\\S*)")
val placep = Pattern.compile("[^(]*\\(([^.]*)")
fun generateLinkerScript(mapFileName: String, profileFileName: String, scriptFileName: String) {
var addressToFunction = TreeMap<Int, Func>()
fun parseMap() {
val s = File(mapFileName).readText(Charset.defaultCharset())
val m = p.matcher(s)
while (m.find()) {
val symbol = m.group(1)
val address = Integer.decode(m.group(2))
val size = Integer.decode(m.group(3))
var place = m.group(4)
if (address == 0) {
continue
}
var placem = placep.matcher(place)
if (placem.find()) {
place = placem.group(1)
}
var f = Func(symbol, place, address, size, 0)
addressToFunction[f.address] = f
}
}
fun parseProfile() {
Scanner(File(profileFileName)).use { scanner ->
while (scanner.hasNext()) {
val address = Integer.decode(scanner.next())
val count = Integer.decode(scanner.next())
for(f in addressToFunction.values) {
if(f.address <= address && address < f.address + f.size) {
f.count = count
}
}
}
}
}
fun writeScript() {
var excl = listOf( "_ZN12NavEKF2_core15readRangeFinderEv",
"_ZN12NavEKF2_core18SelectRngBcnFusionEv","_ZN12NavEKF2_core14readRngBcnDataEv")
var lst = ArrayList(addressToFunction.values.filter { it.count > 5000 && !excl.contains(it.symbol) })
lst.sortWith(kotlin.Comparator { o1, o2 -> o2.count - o1.count })
var s = 0
for (a in lst) {
System.out.format(
"0x%016x\t%8d\t%8d\t%s:%s\n",
a.address,
a.size,
a.count,
a.place,
a.symbol
)
s += a.size
}
FileOutputStream(scriptFileName).use {
for (a in lst) {
it.write(String.format("%s:%s\n", a.place, a.symbol).toByteArray())
}
}
System.out.format("total: %d\n", s)
}
parseMap()
parseProfile()
writeScript()
}
fun main(args: Array<String>) {
generateLinkerScript(
"arduplane.map",
"PROF000.TXT",
"functions.list"
)
}
|
gpl-3.0
|
99e0b8d0b13e2ea6eb3e753f5f020486
| 29.478261 | 109 | 0.521941 | 3.747326 | false | false | false | false |
samthor/intellij-community
|
platform/script-debugger/protocol/protocol-reader/src/ReaderRoot.kt
|
33
|
2914
|
package org.jetbrains.protocolReader
import gnu.trove.THashSet
import org.jetbrains.io.JsonReaderEx
import org.jetbrains.jsonProtocol.JsonParseMethod
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType
import java.util.Arrays
import java.util.Comparator
import java.util.LinkedHashMap
class ReaderRoot<R>(public val type: Class<R>, private val typeToTypeHandler: LinkedHashMap<Class<*>, TypeWriter<*>>) {
private val visitedInterfaces = THashSet<Class<*>>(1)
val methodMap = LinkedHashMap<Method, ReadDelegate>();
init {
readInterfaceRecursive(type)
}
private fun readInterfaceRecursive(clazz: Class<*>) {
if (visitedInterfaces.contains(clazz)) {
return
}
visitedInterfaces.add(clazz)
// todo sort by source location
val methods = clazz.getMethods()
Arrays.sort<Method>(methods, object : Comparator<Method> {
override fun compare(o1: Method, o2: Method): Int {
return o1.getName().compareTo(o2.getName())
}
})
for (m in methods) {
val jsonParseMethod = m.getAnnotation<JsonParseMethod>(javaClass<JsonParseMethod>())
if (jsonParseMethod == null) {
continue
}
val exceptionTypes = m.getExceptionTypes()
if (exceptionTypes.size() > 1) {
throw JsonProtocolModelParseException("Too many exception declared in " + m)
}
var returnType = m.getGenericReturnType()
var isList = false
if (returnType is ParameterizedType) {
val parameterizedType = returnType
if (parameterizedType.getRawType() == javaClass<List<Any>>()) {
isList = true
returnType = parameterizedType.getActualTypeArguments()[0]
}
}
//noinspection SuspiciousMethodCalls
var typeWriter: TypeWriter<*>? = typeToTypeHandler.get(returnType)
if (typeWriter == null) {
typeWriter = createHandler(typeToTypeHandler, m.getReturnType())
}
val arguments = m.getGenericParameterTypes()
if (arguments.size() > 2) {
throw JsonProtocolModelParseException("Exactly one argument is expected in " + m)
}
val argument = arguments[0]
if (argument == javaClass<JsonReaderEx>() || argument == javaClass<Any>()) {
methodMap.put(m, ReadDelegate(typeWriter, isList, arguments.size() != 1))
}
else {
throw JsonProtocolModelParseException("Unrecognized argument type in " + m)
}
}
for (baseType in clazz.getGenericInterfaces()) {
if (baseType !is Class<*>) {
throw JsonProtocolModelParseException("Base interface must be class in " + clazz)
}
readInterfaceRecursive(baseType)
}
}
public fun writeStaticMethodJava(scope: ClassScope) {
val out = scope.output
for (entry in methodMap.entrySet()) {
out.newLine()
entry.getValue().write(scope, entry.getKey(), out)
out.newLine()
}
}
}
|
apache-2.0
|
b6693e45a066e139df384477e42a48b4
| 31.388889 | 119 | 0.670899 | 4.777049 | false | false | false | false |
ibinti/intellij-community
|
platform/testGuiFramework/src/com/intellij/testGuiFramework/cellReader/ExtendedJTreeCellReader.kt
|
3
|
2862
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.cellReader
import com.intellij.ui.SimpleColoredComponent
import org.fest.swing.cell.JTreeCellReader
import org.fest.swing.core.BasicRobot
import org.fest.swing.core.GenericTypeMatcher
import org.fest.swing.driver.BasicJTreeCellReader
import org.fest.swing.exception.ComponentLookupException
import java.awt.Component
import java.awt.Container
import java.util.*
import javax.swing.JLabel
import javax.swing.JTree
/**
* @author Sergey Karashevich
*/
class ExtendedJTreeCellReader : BasicJTreeCellReader(), JTreeCellReader {
override fun valueAt(tree: JTree, modelValue: Any?): String? {
if (modelValue == null) return null
val cellRendererComponent = tree.cellRenderer.getTreeCellRendererComponent(tree, modelValue, false, false, false, 0, false)
when (cellRendererComponent) {
is JLabel -> return cellRendererComponent.text
is SimpleColoredComponent -> return cellRendererComponent.getText()
else -> return cellRendererComponent.findText()
}
}
private fun SimpleColoredComponent.getText(): String?
= this.iterator().asSequence().joinToString()
private fun Component.findText(): String? {
try {
assert(this is Container)
val container = this as Container
val resultList = ArrayList<String>()
resultList.addAll(
findAllWithRobot(container, JLabel::class.java)
.filter { !it.text.isNullOrEmpty() }
.map { it.text }
)
resultList.addAll(
findAllWithRobot(container, SimpleColoredComponent::class.java)
.filter { !it.getText().isNullOrEmpty() }
.map { it.getText()!! }
)
return resultList.filter { !it.isNullOrEmpty() }.firstOrNull()
}
catch (ignored: ComponentLookupException) {
return null
}
}
fun <ComponentType : Component> findAllWithRobot(container: Container, clazz: Class<ComponentType>): List<ComponentType> {
val robot = BasicRobot.robotWithCurrentAwtHierarchyWithoutScreenLock()
val result = robot.finder().findAll(container, object : GenericTypeMatcher<ComponentType>(clazz) {
override fun isMatching(component: ComponentType) = true
})
robot.cleanUpWithoutDisposingWindows()
return result.toList()
}
}
|
apache-2.0
|
d47795c9fc882d85d40ba22f2646282b
| 34.775 | 127 | 0.728162 | 4.586538 | false | false | false | false |
sad2project/-ob-in-ject
|
src/main/kotlin/progjake/obinject/tuples.kt
|
1
|
5621
|
package progjake.obinject
fun <P1, P2> Provider<P1>.and(second: Provider<P2>): Tuple2<P1, P2> = Tuple2(this, second)
class Tuple2<out P1, out P2>(private val _first: Provider<P1>, private val _second: Provider<P2>) {
val first: P1 get() = _first()
val second: P2 get() = _second()
fun <P3> and(third: Provider<P3>): Tuple3<P1, P2, P3> = Tuple3(_first, _second, third)
}
class Tuple3<out P1, out P2, out P3>(private val _first: Provider<P1>, private val _second: Provider<P2>, private val _third: Provider<P3>) {
val first: P1 get() = _first()
val second: P2 get() = _second()
val third: P3 get() = _third()
fun <P4> and(fourth: Provider<P4>): Tuple4<P1, P2, P3, P4> = Tuple4(_first, _second, _third, fourth)
}
class Tuple4<out P1, out P2, out P3, out P4>(private val _first: Provider<P1>, private val _second: Provider<P2>, private val _third: Provider<P3>, private val _fourth: Provider<P4>) {
val first: P1 get() = _first()
val second: P2 get() = _second()
val third: P3 get() = _third()
val fourth: P4 get() = _fourth()
fun <P5> and(fifth: Provider<P5>): Tuple5<P1, P2, P3, P4, P5> = Tuple5(_first, _second, _third, _fourth, fifth)
}
class Tuple5<out P1, out P2, out P3, out P4, out P5>(private val _first: Provider<P1>, private val _second: Provider<P2>, private val _third: Provider<P3>, private val _fourth: Provider<P4>, private val _fifth: Provider<P5>) {
val first: P1 get() = _first()
val second: P2 get() = _second()
val third: P3 get() = _third()
val fourth: P4 get() = _fourth()
val fifth: P5 get() = _fifth()
fun <P6> and(sixth: Provider<P6>): Tuple6<P1, P2, P3, P4, P5, P6> = Tuple6(_first, _second, _third, _fourth, _fifth, sixth)
}
class Tuple6<out P1, out P2, out P3, out P4, out P5, out P6>(private val _first: Provider<P1>, private val _second: Provider<P2>, private val _third: Provider<P3>, private val _fourth: Provider<P4>, private val _fifth: Provider<P5>, private val _sixth: Provider<P6>) {
val first: P1 get() = _first()
val second: P2 get() = _second()
val third: P3 get() = _third()
val fourth: P4 get() = _fourth()
val fifth: P5 get() = _fifth()
val sixth: P6 get() = _sixth()
fun <P7> and(seventh: Provider<P7>): Tuple7<P1, P2, P3, P4, P5, P6, P7> = Tuple7(_first, _second, _third, _fourth, _fifth, _sixth, seventh)
}
class Tuple7<out P1, out P2, out P3, out P4, out P5, out P6, out P7>(private val _first: Provider<P1>, private val _second: Provider<P2>, private val _third: Provider<P3>, private val _fourth: Provider<P4>, private val _fifth: Provider<P5>, private val _sixth: Provider<P6>, private val _seventh: Provider<P7>) {
val first: P1 get() = _first()
val second: P2 get() = _second()
val third: P3 get() = _third()
val fourth: P4 get() = _fourth()
val fifth: P5 get() = _fifth()
val sixth: P6 get() = _sixth()
val seventh: P7 get() = _seventh()
fun <P8> and(eighth: Provider<P8>): Tuple8<P1, P2, P3, P4, P5, P6, P7, P8> = Tuple8(_first, _second, _third, _fourth, _fifth, _sixth, _seventh, eighth)
}
class Tuple8<out P1, out P2, out P3, out P4, out P5, out P6, out P7, out P8>(private val _first: Provider<P1>, private val _second: Provider<P2>, private val _third: Provider<P3>, private val _fourth: Provider<P4>, private val _fifth: Provider<P5>, private val _sixth: Provider<P6>, private val _seventh: Provider<P7>, private val _eighth: Provider<P8>) {
val first: P1 get() = _first()
val second: P2 get() = _second()
val third: P3 get() = _third()
val fourth: P4 get() = _fourth()
val fifth: P5 get() = _fifth()
val sixth: P6 get() = _sixth()
val seventh: P7 get() = _seventh()
val eighth: P8 get() = _eighth()
fun <P9> and(ninth: Provider<P9>): Tuple9<P1, P2, P3, P4, P5, P6, P7, P8, P9> = Tuple9(_first, _second, _third, _fourth, _fifth, _sixth, _seventh, _eighth, ninth)
}
class Tuple9<out P1, out P2, out P3, out P4, out P5, out P6, out P7, out P8, out P9>(private val _first: Provider<P1>, private val _second: Provider<P2>, private val _third: Provider<P3>, private val _fourth: Provider<P4>, private val _fifth: Provider<P5>, private val _sixth: Provider<P6>, private val _seventh: Provider<P7>, private val _eighth: Provider<P8>, private val _ninth: Provider<P9>) {
val first: P1 get() = _first()
val second: P2 get() = _second()
val third: P3 get() = _third()
val fourth: P4 get() = _fourth()
val fifth: P5 get() = _fifth()
val sixth: P6 get() = _sixth()
val seventh: P7 get() = _seventh()
val eighth: P8 get() = _eighth()
val ninth: P9 get() = _ninth()
fun <P10> and(tenth: Provider<P10>): Tuple10<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10> = Tuple10(_first, _second, _third, _fourth, _fifth, _sixth, _seventh, _eighth, _ninth, tenth)
}
class Tuple10<out P1, out P2, out P3, out P4, out P5, out P6, out P7, out P8, out P9, out P10>(private val _first: Provider<P1>, private val _second: Provider<P2>, private val _third: Provider<P3>, private val _fourth: Provider<P4>, private val _fifth: Provider<P5>, private val _sixth: Provider<P6>, private val _seventh: Provider<P7>, private val _eighth: Provider<P8>, private val _ninth: Provider<P9>, private val _tenth: Provider<P10>) {
val first: P1 get() = _first()
val second: P2 get() = _second()
val third: P3 get() = _third()
val fourth: P4 get() = _fourth()
val fifth: P5 get() = _fifth()
val sixth: P6 get() = _sixth()
val seventh: P7 get() = _seventh()
val eighth: P8 get() = _eighth()
val ninth: P9 get() = _ninth()
val tenth: P10 get() = _tenth()
}
|
cc0-1.0
|
37f7d438454fd94c7437e4a7387a5c6a
| 55.22 | 442 | 0.629781 | 2.79235 | false | false | false | false |
gradle/gradle
|
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/ProjectExtensionsTest.kt
|
2
|
6116
|
package org.gradle.kotlin.dsl
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.inOrder
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.NamedDomainObjectFactory
import org.gradle.api.Project
import org.gradle.api.UnknownDomainObjectException
import org.gradle.api.plugins.Convention
import org.gradle.api.reflect.TypeOf
import org.junit.Assert.fail
import org.junit.Test
@Suppress("deprecation")
class ProjectExtensionsTest {
abstract class CustomConvention
@Test
fun `can get generic project extension by type`() {
val project = mock<Project>()
val convention = mock<Convention>()
val extension = mock<NamedDomainObjectContainer<List<String>>>()
val extensionType = typeOf<NamedDomainObjectContainer<List<String>>>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.findByType(eq(extensionType)))
.thenReturn(extension)
project.the<NamedDomainObjectContainer<List<String>>>()
inOrder(convention) {
verify(convention).findByType(eq(extensionType))
verifyNoMoreInteractions()
}
}
@Test
fun `can configure generic project extension by type`() {
val project = mock<Project>()
val convention = mock<Convention>()
val extension = mock<NamedDomainObjectContainer<List<String>>>()
val extensionType = typeOf<NamedDomainObjectContainer<List<String>>>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.findByType(eq(extensionType)))
.thenReturn(extension)
project.configure<NamedDomainObjectContainer<List<String>>> {}
inOrder(convention) {
verify(convention).findByType(eq(extensionType))
verifyNoMoreInteractions()
}
}
@Test
fun `can get convention by type`() {
val project = mock<Project>()
val convention = mock<Convention>()
val javaConvention = mock<CustomConvention>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.findPlugin(eq(CustomConvention::class.java)))
.thenReturn(javaConvention)
project.the<CustomConvention>()
inOrder(convention) {
verify(convention).findByType(any<TypeOf<CustomConvention>>())
verify(convention).findPlugin(eq(CustomConvention::class.java))
verifyNoMoreInteractions()
}
}
@Test
fun `can configure convention by type`() {
val project = mock<Project>()
val convention = mock<Convention>()
val javaConvention = mock<CustomConvention>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.findByType(any<TypeOf<*>>()))
.thenReturn(null)
whenever(convention.findPlugin(eq(CustomConvention::class.java)))
.thenReturn(javaConvention)
project.configure<CustomConvention> {}
inOrder(convention) {
verify(convention).findByType(any<TypeOf<CustomConvention>>())
verify(convention).findPlugin(eq(CustomConvention::class.java))
verifyNoMoreInteractions()
}
}
@Test
fun `the() falls back to throwing getByType when not found`() {
val project = mock<Project>()
val convention = mock<Convention>()
val conventionType = typeOf<CustomConvention>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.getByType(eq(conventionType)))
.thenThrow(UnknownDomainObjectException::class.java)
try {
project.the<CustomConvention>()
fail("UnknownDomainObjectException not thrown")
} catch (ex: UnknownDomainObjectException) {
// expected
}
inOrder(convention) {
verify(convention).findByType(eq(conventionType))
verify(convention).findPlugin(eq(CustomConvention::class.java))
verify(convention).getByType(eq(conventionType))
verifyNoMoreInteractions()
}
}
@Test
fun `configure() falls back to throwing configure when not found`() {
val project = mock<Project>()
val convention = mock<Convention>()
val conventionType = typeOf<CustomConvention>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.configure(eq(conventionType), any<Action<CustomConvention>>()))
.thenThrow(UnknownDomainObjectException::class.java)
try {
project.configure<CustomConvention> {}
fail("UnknownDomainObjectException not thrown")
} catch (ex: UnknownDomainObjectException) {
// expected
}
inOrder(convention) {
verify(convention).findByType(eq(conventionType))
verify(convention).findPlugin(eq(CustomConvention::class.java))
verify(convention).configure(eq(conventionType), any<Action<CustomConvention>>())
verifyNoMoreInteractions()
}
}
@Test
fun container() {
val project = mock<Project> {
on { container(any<Class<String>>()) } doReturn mock<NamedDomainObjectContainer<String>>()
on { container(any<Class<String>>(), any<NamedDomainObjectFactory<String>>()) } doReturn mock<NamedDomainObjectContainer<String>>()
}
project.container<String>()
inOrder(project) {
verify(project).container(String::class.java)
verifyNoMoreInteractions()
}
project.container { "some" }
inOrder(project) {
verify(project).container(any<Class<String>>(), any<NamedDomainObjectFactory<String>>())
verifyNoMoreInteractions()
}
}
}
|
apache-2.0
|
cf973d69471f4f6b45ccdd1ad7be8050
| 31.359788 | 143 | 0.650589 | 5.327526 | false | false | false | false |
FutureioLab/FastPeak
|
app/src/main/java/com/binlly/fastpeak/repo/RemoteRepo.kt
|
1
|
2008
|
package com.binlly.fastpeak.repo
import com.binlly.fastpeak.repo.service.RemoteService
import com.binlly.fastpeak.base.PREFERENCE_NAME_REMOTE_CONFIG
import com.binlly.fastpeak.base.Preference
import com.binlly.fastpeak.base.net.ReqParams
import com.binlly.fastpeak.base.net.RetrofitManager
import com.binlly.fastpeak.base.rx.IoTransformer
import com.binlly.fastpeak.service.Services
import com.binlly.fastpeak.service.remoteconfig.RemoteMockModel
import io.reactivex.Observer
import retrofit2.Retrofit
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* Created by yy on 2017/10/10.
*/
object RemoteRepo {
private val TAG = RemoteRepo::class.java.simpleName
const val PREFERENCE_KEY_HOST = "host"
var mockHost: String by MockHostDelegate()
var mRetrofit: Retrofit = RetrofitManager.createRetrofit(mockHost)
var mService = mRetrofit.create(RemoteService::class.java)
fun requestMock(observer: Observer<RemoteMockModel>) {
val params = ReqParams(TAG)
try {
mService.requestMock(params.getFieldMap()).compose(IoTransformer()).subscribe(observer)
} catch (e: Exception) {
e.printStackTrace()
}
}
class MockHostDelegate: ReadWriteProperty<Any?, String> {
private var host: String by Preference(Services.app, PREFERENCE_NAME_REMOTE_CONFIG,
RemoteRepo.PREFERENCE_KEY_HOST, "http://127.0.0.1")
override fun getValue(thisRef: Any?, property: KProperty<*>): String {
return host
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
if (host == value) return
host = value
RemoteRepo.mRetrofit = RetrofitManager.createRetrofit(host)
RemoteRepo.mService = RemoteRepo.mRetrofit.create(
RemoteService::class.java)
Services.remoteConfig().pullMockConfig({}) //改变地址之后重新拉取并更新mock配置
}
}
}
|
mit
|
cf4983d07b250b8a97663f2959a6b4dc
| 34.321429 | 99 | 0.70273 | 4.3 | false | true | false | false |
AlmasB/FXGL
|
fxgl/src/main/kotlin/com/almasb/fxgl/dsl/components/view/GenericBarViewComponent.kt
|
1
|
1648
|
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.dsl.components.view
import com.almasb.fxgl.ui.Position
import com.almasb.fxgl.ui.ProgressBar
import javafx.beans.property.DoubleProperty
import javafx.scene.paint.Color
/**
* A general bar view component to display properties like health, mana, or energy.
* Can be fully customized using its [bar] property.
* @author Marvin Buff ([email protected])
*/
open class GenericBarViewComponent @JvmOverloads constructor(
x: Double,
y: Double,
color: Color,
initialValue: Double,
maxValue: Double = initialValue,
width: Double = 100.0,
height: Double = 10.0
) : ChildViewComponent(x, y, false) {
/**
* Utility constructor to setup the [GenericBarViewComponent] bound to the given [property].
*/
constructor(x: Double, y: Double, color: Color, property: DoubleProperty, width: Double, height: Double
) : this(x, y, color, property.value, property.value, width, height) {
valueProperty().bind(property)
}
val bar = ProgressBar()
init {
bar.setMinValue(0.0)
bar.setMaxValue(maxValue)
bar.setWidth(width)
bar.setHeight(height)
bar.isLabelVisible = false
bar.setLabelPosition(Position.RIGHT)
bar.setFill(color)
bar.currentValue = initialValue
viewRoot.children.add(bar)
}
fun valueProperty(): DoubleProperty = bar.currentValueProperty()
fun maxValueProperty(): DoubleProperty = bar.maxValueProperty()
}
|
mit
|
4941281553e34443ecf744c371a5f304
| 29.537037 | 107 | 0.675971 | 4.12 | false | false | false | false |
elect86/modern-jogl-examples
|
src/main/kotlin/glNext/tut15/manyImages.kt
|
2
|
9010
|
package glNext.tut15
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL2ES3.*
import com.jogamp.opengl.GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV
import com.jogamp.opengl.GL3
import com.jogamp.opengl.util.texture.spi.DDSImage
import glNext.*
import glm.*
import main.framework.Framework
import main.framework.Semantic
import main.framework.component.Mesh
import uno.buffer.*
import uno.glm.MatrixStack
import uno.glsl.programOf
import uno.time.Timer
import java.io.File
import java.nio.ByteBuffer
import glm.mat.Mat4
import glm.vec._3.Vec3
/**
* Created by GBarbieri on 31.03.2017.
*/
fun main(args: Array<String>) {
ManyImages_Next().setup("Tutorial 15 - Many Images")
}
class ManyImages_Next : Framework() {
lateinit var program: ProgramData
lateinit var plane: Mesh
lateinit var corridor: Mesh
val projBufferName = intBufferBig(1)
object Texture {
val Checker = 0
val MipmapTest = 1
val MAX = 2
}
val textureName = intBufferBig(Texture.MAX)
val samplerName = intBufferBig(Sampler.MAX)
val camTimer = Timer(Timer.Type.Loop, 5f)
var useMipmapTexture = false
var currSampler = 0
var drawCorridor = false
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
plane = Mesh(gl, javaClass, "tut15/BigPlane.xml")
corridor = Mesh(gl, javaClass, "tut15/Corridor.xml")
cullFace {
enable()
cullFace = back
frontFace = cw
}
val depthZNear = 0f
val depthZFar = 1f
depth {
test = true
mask = true
func = lEqual
rangef = depthZNear..depthZFar
clamp = true
}
//Setup our Uniform Buffers
initUniformBuffer(projBufferName) {
data(Mat4.SIZE, GL_DYNAMIC_DRAW)
range(Semantic.Uniform.PROJECTION, 0, Mat4.SIZE)
}
// Generate all the texture names
glGenTextures(textureName)
loadCheckerTexture(gl)
loadMipmapTexture(gl)
createSamplers(gl)
}
fun initializeProgram(gl: GL3) {
program = ProgramData(gl, "pt.vert", "tex.frag")
}
fun loadCheckerTexture(gl: GL3) = with(gl) {
val file = File(javaClass.getResource("/tut15/checker.dds").toURI())
val ddsImage = DDSImage.read(file)
withTexture2d(textureName[Texture.Checker]) {
repeat(ddsImage.numMipMaps) { mipmapLevel ->
val mipmap = ddsImage.getMipMap(mipmapLevel)
image(mipmapLevel, GL_RGB8, mipmap.width, mipmap.height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, mipmap.data)
}
levels = 0 until ddsImage.numMipMaps
}
}
fun loadMipmapTexture(gl: GL3) = with(gl) {
withTexture2d(textureName[Texture.MipmapTest]) {
val oldAlign = glGetInteger(GL_UNPACK_ALIGNMENT)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
for (mipmapLevel in 0..7) {
val width = 128 shr mipmapLevel
val height = 128 shr mipmapLevel
val currColor = mipmapColors[mipmapLevel]
val buffer = fillWithColors(currColor, width, height)
image(mipmapLevel, GL_RGB8, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer)
buffer.destroy()
}
glPixelStorei(GL_UNPACK_ALIGNMENT, oldAlign)
levels = 0..7
}
}
val mipmapColors = arrayOf(
byteArrayOf(0xFF.b, 0xFF.b, 0x00.b),
byteArrayOf(0xFF.b, 0x00.b, 0xFF.b),
byteArrayOf(0x00.b, 0xFF.b, 0xFF.b),
byteArrayOf(0xFF.b, 0x00.b, 0x00.b),
byteArrayOf(0x00.b, 0xFF.b, 0x00.b),
byteArrayOf(0x00.b, 0x00.b, 0xFF.b),
byteArrayOf(0x00.b, 0x00.b, 0x00.b),
byteArrayOf(0xFF.b, 0xFF.b, 0xFF.b))
fun fillWithColors(color: ByteArray, width: Int, height: Int): ByteBuffer {
val numTexels = width * height
val buffer = byteBufferBig(numTexels * 3)
val (red, green, blue) = color
while (buffer.hasRemaining())
buffer
.put(red)
.put(green)
.put(blue)
buffer.position(0)
return buffer
}
fun createSamplers(gl: GL3) = with(gl) {
initSamplers(samplerName) {
for (i in 0 until Sampler.MAX)
at(i) {
wrapS = repeat
wrapT = repeat
}
at(Sampler.Nearest) {
magFilter = nearest
minFilter = nearest
}
at(Sampler.Linear) {
magFilter = linear
minFilter = linear
}
at(Sampler.Linear_MipMap_Nearest) {
magFilter = linear_mmNearest
minFilter = linear_mmNearest
}
at(Sampler.Linear_MipMap_Linear) {
magFilter = linear_mmLinear
minFilter = linear_mmLinear
}
at(Sampler.LowAnisotropy) {
magFilter = linear
minFilter = linear_mmLinear
maxAnisotropy = 4.0f
}
val maxAniso = caps.limits.MAX_TEXTURE_MAX_ANISOTROPY_EXT // TODO float?
println("Maximum anisotropy: " + maxAniso)
at(Sampler.MaxAnisotropy) {
magFilter = linear
minFilter = linear_mmLinear
maxAnisotropy = maxAniso.f
}
}
}
override fun display(gl: GL3) = with(gl) {
clear {
color(0.75f, 0.75f, 1.0f, 1.0f)
depth()
}
camTimer.update()
val cyclicAngle = camTimer.getAlpha() * 6.28f
val hOffset = glm.cos(cyclicAngle) * .25f
val vOffset = glm.sin(cyclicAngle) * .25f
val modelMatrix = MatrixStack()
val worldToCamMat = glm.lookAt(
Vec3(hOffset, 1f, -64f),
Vec3(hOffset, -5f + vOffset, -44f),
Vec3(0f, 1f, 0f))
modelMatrix.applyMatrix(worldToCamMat) run {
usingProgram(program.theProgram) {
program.modelToCameraMatrixUL.mat4 = top()
val texture = textureName[if (useMipmapTexture) Texture.MipmapTest else Texture.Checker]
withTexture2d(Semantic.Sampler.DIFFUSE, texture, samplerName[currSampler]) {
if (drawCorridor)
corridor.render(gl, "tex")
else
plane.render(gl, "tex")
}
}
}
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
val persMatrix = MatrixStack()
persMatrix.perspective(90f, w / h.f, 1f, 1000f)
withUniformBuffer(projBufferName) { subData(persMatrix.top()) }
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl) {
plane.dispose(gl)
corridor.dispose(gl)
glDeleteProgram(program.theProgram)
glDeleteBuffer(projBufferName)
glDeleteTextures(textureName)
glDeleteSamplers(samplerName)
destroyBuffers(projBufferName, textureName, samplerName)
}
override fun keyPressed(ke: KeyEvent) {
when (ke.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_SPACE -> useMipmapTexture = !useMipmapTexture
KeyEvent.VK_Y -> drawCorridor = !drawCorridor
KeyEvent.VK_P -> camTimer.togglePause()
}
if (ke.keyCode in KeyEvent.VK_1..KeyEvent.VK_9) {
val number = ke.keyCode - KeyEvent.VK_1
if (number < Sampler.MAX) {
println("Sampler: " + samplerNames[number])
currSampler = number
}
}
}
object Sampler {
val Nearest = 0
val Linear = 1
val Linear_MipMap_Nearest = 2
val Linear_MipMap_Linear = 3
val LowAnisotropy = 4
val MaxAnisotropy = 5
val MAX = 6
}
val samplerNames = arrayOf("Nearest", "Linear", "Linear with nearest mipmaps", "Linear with linear mipmaps", "Low anisotropic", "Max anisotropic")
class ProgramData(gl: GL3, vertex: String, fragment: String) {
val theProgram = programOf(gl, javaClass, "tut15", vertex, fragment)
val modelToCameraMatrixUL = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix")
init {
with(gl) {
glUniformBlockBinding(
theProgram,
glGetUniformBlockIndex(theProgram, "Projection"),
Semantic.Uniform.PROJECTION)
glUseProgram(theProgram)
glUniform1i(
glGetUniformLocation(theProgram, "colorTexture"),
Semantic.Sampler.DIFFUSE)
glUseProgram()
}
}
}
}
|
mit
|
e2423f847a6967fd42df5e4c39327116
| 26.811728 | 150 | 0.558713 | 4.311005 | false | false | false | false |
ujpv/intellij-rust
|
src/main/kotlin/org/rust/ide/intentions/RemoveCurlyBracesIntention.kt
|
1
|
2769
|
package org.rust.ide.intentions
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RustPsiFactory
import org.rust.lang.core.psi.RustUseGlobElement
import org.rust.lang.core.psi.RustUseItemElement
import org.rust.lang.core.psi.util.parentOfType
/**
* Removes the curly braces on singleton imports, changing from this
*
* ```
* import std::{mem};
* ```
*
* to this:
*
* ```
* import std::mem;
* ```
*/
class RemoveCurlyBracesIntention : PsiElementBaseIntentionAction() {
override fun getText() = "Remove curly braces"
override fun getFamilyName() = text
override fun startInWriteAction() = true
override fun invoke(project: Project, editor: Editor, element: PsiElement) {
// Get our hands on the various parts of the use item:
val useItem = element.parentOfType<RustUseItemElement>() ?: return
val path = useItem.path ?: return
val globList = useItem.useGlobList ?: return
val identifier = globList.children[0]
// Save the cursor position, adjusting for curly brace removal
val caret = editor.caretModel.offset
val newOffset = when {
caret < identifier.textOffset -> caret
caret < identifier.textOffset + identifier.textLength -> caret - 1
else -> caret - 2
}
// Conjure up a new use item to make a new path containing the
// identifier we want; then grab the relevant parts
val newUseItem = RustPsiFactory(project).createUseItem("dummy::${identifier.text}")
val newPath = newUseItem.path ?: return
val newSubPath = newPath.path ?: return
val newAlias = newUseItem.alias
// Attach the identifier to the old path, then splice that path into
// the use item. Delete the old glob list and attach the alias, if any.
newSubPath.replace(path.copy())
path.replace(newPath)
useItem.coloncolon?.delete()
globList.delete()
newAlias?.let { it -> useItem.addBefore(it, useItem.semicolon) }
editor.caretModel.moveToOffset(newOffset)
}
override fun isAvailable(project: Project, editor: Editor?, element: PsiElement): Boolean {
if (!element.isWritable) return false
val useItem = element.parentOfType<RustUseItemElement>() ?: return false
val list = useItem.useGlobList ?: return false
if (list.children.size != 1) return false
val listItem = list.children[0]
if (listItem is RustUseGlobElement) {
return listItem.self == null
} else {
return false
}
}
}
|
mit
|
371378a37d9b568837c185455a2f09fd
| 34.961039 | 95 | 0.669556 | 4.487844 | false | false | false | false |
proxer/ProxerAndroid
|
src/main/kotlin/me/proxer/app/profile/topten/TopTenFragment.kt
|
1
|
5469
|
package me.proxer.app.profile.topten
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import io.reactivex.Observable
import kotterknife.bindView
import me.proxer.app.GlideApp
import me.proxer.app.R
import me.proxer.app.base.BaseContentFragment
import me.proxer.app.media.MediaActivity
import me.proxer.app.profile.ProfileActivity
import me.proxer.app.profile.topten.TopTenViewModel.ZippedTopTenResult
import me.proxer.app.util.DeviceUtils
import me.proxer.app.util.ErrorUtils.ErrorAction
import me.proxer.app.util.ErrorUtils.ErrorAction.Companion.ACTION_MESSAGE_HIDE
import me.proxer.app.util.extension.multilineSnackbar
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import kotlin.properties.Delegates
/**
* @author Ruben Gees
*/
class TopTenFragment : BaseContentFragment<ZippedTopTenResult>(R.layout.fragment_top_ten) {
companion object {
fun newInstance() = TopTenFragment().apply {
arguments = bundleOf()
}
}
override val viewModel by viewModel<TopTenViewModel> { parametersOf(userId, username) }
override val hostingActivity: ProfileActivity
get() = activity as ProfileActivity
private val profileActivity
get() = activity as ProfileActivity
private val userId: String?
get() = profileActivity.userId
private val username: String?
get() = profileActivity.username
private var animeAdapter by Delegates.notNull<TopTenAdapter>()
private var mangaAdapter by Delegates.notNull<TopTenAdapter>()
private val animeContainer: ViewGroup by bindView(R.id.animeContainer)
private val mangaContainer: ViewGroup by bindView(R.id.mangaContainer)
private val animeRecyclerView: RecyclerView by bindView(R.id.animeRecyclerView)
private val mangaRecyclerView: RecyclerView by bindView(R.id.mangaRecyclerView)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
animeAdapter = TopTenAdapter()
mangaAdapter = TopTenAdapter()
Observable.merge(animeAdapter.clickSubject, mangaAdapter.clickSubject)
.autoDisposable(this.scope())
.subscribe { (view, item) ->
if (item is LocalTopTenEntry.Ucp) {
MediaActivity.navigateTo(requireActivity(), item.entryId, item.name, item.category, view)
} else {
MediaActivity.navigateTo(requireActivity(), item.id, item.name, item.category, view)
}
}
Observable.merge(animeAdapter.deleteSubject, mangaAdapter.deleteSubject)
.autoDisposable(this.scope())
.subscribe { viewModel.addItemToDelete(it) }
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val spanCount = DeviceUtils.calculateSpanAmount(requireActivity()) + 1
animeAdapter.glide = GlideApp.with(this)
mangaAdapter.glide = GlideApp.with(this)
animeRecyclerView.isNestedScrollingEnabled = false
animeRecyclerView.layoutManager = GridLayoutManager(context, spanCount)
animeRecyclerView.adapter = animeAdapter
mangaRecyclerView.isNestedScrollingEnabled = false
mangaRecyclerView.layoutManager = GridLayoutManager(context, spanCount)
mangaRecyclerView.adapter = mangaAdapter
viewModel.itemDeletionError.observe(
viewLifecycleOwner,
Observer {
it?.let {
hostingActivity.multilineSnackbar(
getString(R.string.error_topten_entry_removal, getString(it.message)),
Snackbar.LENGTH_LONG,
it.buttonMessage,
it.toClickListener(hostingActivity)
)
}
}
)
}
override fun onDestroyView() {
animeRecyclerView.layoutManager = null
animeRecyclerView.adapter = null
mangaRecyclerView.layoutManager = null
mangaRecyclerView.adapter = null
super.onDestroyView()
}
override fun showData(data: ZippedTopTenResult) {
super.showData(data)
animeAdapter.swapDataAndNotifyWithDiffing(data.animeEntries)
mangaAdapter.swapDataAndNotifyWithDiffing(data.mangaEntries)
when (animeAdapter.isEmpty()) {
true -> animeContainer.isGone = true
false -> animeContainer.isVisible = true
}
when (mangaAdapter.isEmpty()) {
true -> mangaContainer.isGone = true
false -> mangaContainer.isVisible = true
}
if (animeAdapter.isEmpty() && mangaAdapter.isEmpty()) {
showError(ErrorAction(R.string.error_no_data_top_ten, ACTION_MESSAGE_HIDE))
}
}
override fun hideData() {
animeAdapter.swapDataAndNotifyWithDiffing(emptyList())
mangaAdapter.swapDataAndNotifyWithDiffing(emptyList())
super.hideData()
}
}
|
gpl-3.0
|
81e7202f1fffec9328a12c0a30ab230f
| 34.745098 | 109 | 0.69702 | 5.096925 | false | false | false | false |
google-home/sample-app-for-matter-android
|
app/src/main/java/com/google/homesampleapp/screens/shared/SelectedDeviceViewModel.kt
|
1
|
2076
|
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.homesampleapp.screens.shared
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.homesampleapp.Device
import com.google.homesampleapp.screens.home.DeviceUiModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
/** Class responsible for the information related to the currently selected device. */
@HiltViewModel
class SelectedDeviceViewModel @Inject constructor() : ViewModel() {
// The deviceId currently selected, made available as LiveData.
// TODO: Since we are using Flows and StateFlows elsewhere, recommendation is to use them here as
// well for consistency (and because LiveData is falling out of fashion anyway).
private val _selectedDeviceIdLiveData = MutableLiveData(-1L)
val selectedDeviceIdLiveData: LiveData<Long> = _selectedDeviceIdLiveData
// The device currently selected, made available as LiveData.
private val _selectedDeviceLiveData =
MutableLiveData(DeviceUiModel(Device.getDefaultInstance(), isOnline = false, isOn = false))
val selectedDeviceLiveData: LiveData<DeviceUiModel> = _selectedDeviceLiveData
fun setSelectedDevice(deviceUiModel: DeviceUiModel) {
_selectedDeviceIdLiveData.value = deviceUiModel.device.deviceId
_selectedDeviceLiveData.value = deviceUiModel
}
fun resetSelectedDevice() {
_selectedDeviceIdLiveData.value = -1L
_selectedDeviceLiveData.value = null
}
}
|
apache-2.0
|
511365d83d4f92a8d94a4cdd64255205
| 39.705882 | 99 | 0.782274 | 4.739726 | false | false | false | false |
EmmanuelMess/Simple-Accounting
|
SimpleAccounting/app/src/main/java/com/emmanuelmess/simpleaccounting/PPrintDocumentAdapter.kt
|
1
|
8760
|
package com.emmanuelmess.simpleaccounting
import android.content.Context
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import android.os.Bundle
import android.os.CancellationSignal
import android.os.ParcelFileDescriptor
import android.print.PageRange
import android.print.PrintAttributes
import android.print.PrintDocumentAdapter
import android.print.PrintDocumentInfo
import android.print.pdf.PrintedPdfDocument
import android.view.View
import android.widget.TableLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.emmanuelmess.simpleaccounting.activities.MainActivity
import com.emmanuelmess.simpleaccounting.data.Session
import com.emmanuelmess.simpleaccounting.utils.Utils
import com.emmanuelmess.simpleaccounting.utils.get
import java.io.FileOutputStream
import java.io.IOException
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
class PPrintDocumentAdapter(
private val context: Context,
private val table: TableLayout,
private val session: Session,
private val updateDate: IntArray
) : PrintDocumentAdapter() {
companion object {
//IN 1/72"
private const val DISTANCE_BETWEEN_LINES = 30
private const val TOP_MARGIN = 100
fun areAllTrue(array: BooleanArray): Boolean {
for (b in array) if (!b) return false
return true
}
}
private lateinit var rawToPrint: List<List<String>>
private lateinit var pdfDocument: PrintedPdfDocument
private lateinit var title: String
private var oldLinesPerPage = -1
private var oldAmountOfPages = -1
private var linesPerPage: Int = 0
private var amountOfPages: Int = 0
private lateinit var writtenPages: BooleanArray
override fun onStart() {
super.onStart()
val raw = mutableListOf<List<String>>()
for (i in 0 until (table.childCount - 1)) {
val row = table.get<View>(i + 1)!!//+1 to account for the header
val list = mutableListOf<String>()
for (j in 0..3) {
if (row.findViewById<View>(MainActivity.TEXT_IDS[j]) == null) {
list.add("")
continue
}
list.add(row.findViewById<TextView>(MainActivity.TEXT_IDS[j]).text.toString())
}
if(row.findViewById<View>(R.id.textBalance) == null) {
list.add("")
continue
}
list.add(row.findViewById<TextView>(R.id.textBalance).text.toString())
raw.add(list)
}
rawToPrint = raw
}
override fun onLayout(oldAttributes: PrintAttributes, newAttributes: PrintAttributes,
cancellationSignal: CancellationSignal, layoutResultCallback: PrintDocumentAdapter.LayoutResultCallback,
bundle: Bundle) {
try {
pdfDocument = PrintedPdfDocument(context, newAttributes)
if (cancellationSignal.isCanceled) {
layoutResultCallback.onLayoutCancelled()
return
}
linesPerPage = Math.ceil(((pdfDocument.pageHeight - 2 * TOP_MARGIN).toFloat() / DISTANCE_BETWEEN_LINES).toDouble()).toInt()
amountOfPages = Math.ceil((rawToPrint.size / linesPerPage.toFloat()).toDouble()).toInt()
writtenPages = BooleanArray(amountOfPages)
title = Utils.getTitle(context, session, updateDate)
val info = PrintDocumentInfo.Builder(title + ".pdf")
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(amountOfPages)
.build()
val layoutChanged = !(oldLinesPerPage == linesPerPage && oldAmountOfPages == amountOfPages)
oldLinesPerPage = linesPerPage
oldAmountOfPages = amountOfPages
layoutResultCallback.onLayoutFinished(info, layoutChanged)
} catch (e: Exception) {
layoutResultCallback.onLayoutFailed(e.localizedMessage)
}
}
override fun onWrite(pageRanges: Array<PageRange>, parcelFileDescriptor: ParcelFileDescriptor,
cancellationSignal: CancellationSignal, writeResultCallback: PrintDocumentAdapter.WriteResultCallback) {
val clipW = pdfDocument.pageContentRect.left
val clipH = pdfDocument.pageContentRect.top
val end = getEnd(pageRanges)
//WARNING && i < writtenPages.length is a workaround because Android gives impossible PageRange (check 31 items in A2 page)
var i = getStart(pageRanges)
while (i <= end && i < writtenPages.size) {
if (isPageInRange(pageRanges, i) && !writtenPages[i]) {
val page = pdfDocument.startPage(i)
if (cancellationSignal.isCanceled) {
writeResultCallback.onWriteCancelled()
pdfDocument.close()
return
}
val canvasEnd = pdfDocument.pageContentRect.right
val c = page.canvas
val p = Paint()
p.color = Color.BLACK
p.textSize = 10f
p.textAlign = Paint.Align.CENTER
c.drawText(
title + " (" + context.getString(R.string.page) + " " + (i + 1) + "/" + amountOfPages + ")",
(c.width / 2).toFloat(), clipH + TOP_MARGIN / 2f, p)//TODO correct centration
p.textAlign = Paint.Align.CENTER
c.drawText(this.context.getString(R.string.date), (clipW + 100).toFloat(), (clipH + TOP_MARGIN).toFloat(), p)
p.textAlign = Paint.Align.LEFT
c.drawText(this.context.getString(R.string.reference), (clipW + 150).toFloat(), (clipH + TOP_MARGIN).toFloat(), p)
p.textAlign = Paint.Align.CENTER
c.drawText(this.context.getString(R.string.credit), (canvasEnd - 300).toFloat(), (clipH + TOP_MARGIN).toFloat(), p)
c.drawText(this.context.getString(R.string.debit), (canvasEnd - 200).toFloat(), (clipH + TOP_MARGIN).toFloat(), p)
c.drawText(this.context.getString(R.string.balance), (canvasEnd - 100).toFloat(), (clipH + TOP_MARGIN).toFloat(), p)
var j = i * linesPerPage
var k = 1
while (j < rawToPrint.size && k <= linesPerPage) {
p.textAlign = Paint.Align.CENTER
c.drawText(rawToPrint[j][0], (clipW + 100).toFloat(), (clipH + TOP_MARGIN + DISTANCE_BETWEEN_LINES * k).toFloat(), p)
p.textAlign = Paint.Align.LEFT
c.drawText(rawToPrint[j][1], (clipW + 150).toFloat(), (clipH + TOP_MARGIN + DISTANCE_BETWEEN_LINES * k).toFloat(), p)
p.textAlign = Paint.Align.CENTER
c.drawText(rawToPrint[j][2], (canvasEnd - 300).toFloat(),
(clipH + TOP_MARGIN + DISTANCE_BETWEEN_LINES * k).toFloat(), p)
c.drawText(rawToPrint[j][3], (canvasEnd - 200).toFloat(),
(clipH + TOP_MARGIN + DISTANCE_BETWEEN_LINES * k).toFloat(), p)
c.drawText(rawToPrint[j][4], (canvasEnd - 100).toFloat(),
(clipH + TOP_MARGIN + DISTANCE_BETWEEN_LINES * k).toFloat(), p)
j++
k++
}
pdfDocument.finishPage(page)
writtenPages[i] = true
}
i++
}
// Write PDF document to file
try {
pdfDocument.writeTo(FileOutputStream(parcelFileDescriptor.fileDescriptor))
} catch (e: IOException) {
writeResultCallback.onWriteFailed(e.toString())
return
} finally {
if (areAllTrue(writtenPages))
pdfDocument.close()
}
// Signal the print framework the document is complete
writeResultCallback.onWriteFinished(pageRanges)
}
private fun getStart(p: Array<PageRange>): Int {
var page = amountOfPages//always bigger than the biggest as the biggest in p will be 0 index
for (pr in p)
if (pr.start < page)
page = pr.start
return page
}
private fun getEnd(p: Array<PageRange>): Int {
var page = -1//smaller than smallest possible value in p
for (pr in p)
if (pr.end > page)
page = pr.end
return page
}
private fun isPageInRange(p: Array<PageRange>, page: Int): Boolean {
for (pr in p)
if (pr.start <= page && page <= pr.end)
return true
return false
}
}
|
gpl-3.0
|
bfe9334f5e5dac4ef723de177630b3f6
| 37.425439 | 137 | 0.596461 | 4.805266 | false | false | false | false |
RyanAndroidTaylor/Rapido
|
app/src/main/java/com/dtp/sample/common/database/Person.kt
|
1
|
1714
|
package com.dtp.sample.common.database
import android.content.ContentValues
import android.database.Cursor
import com.izeni.rapidosqlite.DataConnection
import com.izeni.rapidosqlite.addAll
import com.izeni.rapidosqlite.get
import com.izeni.rapidosqlite.item_builder.ItemBuilder
import com.izeni.rapidosqlite.query.QueryBuilder
import com.izeni.rapidosqlite.table.Column
import com.izeni.rapidosqlite.table.ParentDataTable
/**
* Created by ner on 2/8/17.
*/
data class Person(val uuid: String, val name: String, val age: Int, val pets: List<Pet>) : ParentDataTable {
companion object {
val TABLE_NAME = "Person"
val UUID = Column(String::class.java, "Uuid", notNull = true, unique = true)
val NAME = Column(String::class.java, "Name", notNull = true)
val AGE = Column(Int::class.java, "Age", notNull = true, defaultValue = 38)
val COLUMNS = arrayOf(UUID, NAME, AGE)
val BUILDER = Builder()
}
override fun tableName() = TABLE_NAME
override fun id() = uuid
override fun idColumn() = UUID
override fun contentValues() = ContentValues().addAll(COLUMNS, uuid, name, age)
override fun getChildren() = pets
class Builder : ItemBuilder<Person> {
override fun buildItem(cursor: Cursor, dataConnection: DataConnection): Person {
val personUuid = cursor.get<String>(UUID)
val petQuery = QueryBuilder
.with(Pet.TABLE_NAME)
.whereEquals(Pet.PERSON_UUID, personUuid)
.build()
val pets = dataConnection.findAll(Pet.BUILDER, petQuery)
return Person(personUuid, cursor.get(NAME), cursor.get(AGE), pets)
}
}
}
|
mit
|
2249b964e6c4b28ad7eca765fd7a6a14
| 31.358491 | 108 | 0.670362 | 4.170316 | false | false | false | false |
lttng/lttng-scope
|
jabberwocky-lttng/src/main/kotlin/com/efficios/jabberwocky/lttng/kernel/trace/layout/LttngKernel27EventLayout.kt
|
2
|
7454
|
/*
* Copyright (C) 2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
* Copyright (C) 2015 Ericsson
* Copyright (C) 2015 École Polytechnique de Montréal
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.lttng.kernel.trace.layout
/**
* This file defines all the known event and field names for LTTng kernel
* traces, for versions of lttng-modules 2.7 and above.
*/
open class LttngKernel27EventLayout protected constructor() : LttngKernel26EventLayout() {
companion object {
val instance = LttngKernel27EventLayout()
private const val X86_IRQ_VECTORS_LOCAL_TIMER_ENTRY = "x86_irq_vectors_local_timer_entry"
private const val X86_IRQ_VECTORS_LOCAL_TIMER_EXIT = "x86_irq_vectors_local_timer_exit"
private const val X86_IRQ_VECTORS_RESCHEDULE_ENTRY = "x86_irq_vectors_reschedule_entry"
private const val X86_IRQ_VECTORS_RESCHEDULE_EXIT = "x86_irq_vectors_reschedule_exit"
private const val X86_IRQ_VECTORS_SPURIOUS_ENTRY = "x86_irq_vectors_spurious_apic_entry"
private const val X86_IRQ_VECTORS_SPURIOUS_EXIT = "x86_irq_vectors_spurious_apic_exit"
private const val X86_IRQ_VECTORS_ERROR_APIC_ENTRY = "x86_irq_vectors_error_apic_entry"
private const val X86_IRQ_VECTORS_ERROR_APIC_EXIT = "x86_irq_vectors_error_apic_exit"
private const val X86_IRQ_VECTORS_IPI_ENTRY = "x86_irq_vectors_ipi_entry"
private const val X86_IRQ_VECTORS_IPI_EXIT = "x86_irq_vectors_ipi_exit"
private const val X86_IRQ_VECTORS_IRQ_WORK_ENTRY = "x86_irq_vectors_irq_work_entry"
private const val X86_IRQ_VECTORS_IRQ_WORK_EXIT = "x86_irq_vectors_irq_work_exit"
private const val X86_IRQ_VECTORS_CALL_FUNCTION_ENTRY = "x86_irq_vectors_call_function_entry"
private const val X86_IRQ_VECTORS_CALL_FUNCTION_EXIT = "x86_irq_vectors_call_function_exit"
private const val X86_IRQ_VECTORS_CALL_FUNCTION_SINGLE_ENTRY = "x86_irq_vectors_call_function_single_entry"
private const val X86_IRQ_VECTORS_CALL_FUNCTION_SINGLE_EXIT = "x86_irq_vectors_call_function_single_exit"
private const val X86_IRQ_VECTORS_THRESHOLD_APIC_ENTRY = "x86_irq_vectors_threshold_apic_entry"
private const val X86_IRQ_VECTORS_THRESHOLD_APIC_EXIT = "x86_irq_vectors_threshold_apic_exit"
private const val X86_IRQ_VECTORS_DEFERRED_ERROR_APIC_ENTRY = "x86_irq_vectors_deferred_error_apic_entry"
private const val X86_IRQ_VECTORS_DEFERRED_ERROR_APIC_EXIT = "x86_irq_vectors_deferred_error_apic_exit"
private const val X86_IRQ_VECTORS_THERMAL_APIC_ENTRY = "x86_irq_vectors_thermal_apic_entry"
private const val X86_IRQ_VECTORS_THERMAL_APIC_EXIT = "x86_irq_vectors_thermal_apic_exit"
}
// ------------------------------------------------------------------------
// Updated event definitions in LTTng 2.7
// ------------------------------------------------------------------------
override val eventHRTimerStart = "timer_hrtimer_start"
override val eventHRTimerCancel = "timer_hrtimer_cancel"
override val eventHRTimerExpireEntry = "timer_hrtimer_expire_entry"
override val eventHRTimerExpireExit = "timer_hrtimer_expire_exit"
override val eventSoftIrqRaise = "irq_softirq_raise"
override val eventSoftIrqEntry = "irq_softirq_entry"
override val eventSoftIrqExit = "irq_softirq_exit"
override val eventKmemPageAlloc = "kmem_mm_page_alloc"
override val eventKmemPageFree = "kmem_mm_page_free"
override val eventsNetworkReceive = listOf("net_if_receive_skb")
override val eventsKVMEntry = listOf("kvm_x86_entry")
override val eventsKVMExit = listOf("kvm_x86_exit")
override val ipiIrqVectorsEntries = listOf(
X86_IRQ_VECTORS_LOCAL_TIMER_ENTRY,
X86_IRQ_VECTORS_RESCHEDULE_ENTRY,
X86_IRQ_VECTORS_SPURIOUS_ENTRY,
X86_IRQ_VECTORS_ERROR_APIC_ENTRY,
X86_IRQ_VECTORS_IPI_ENTRY,
X86_IRQ_VECTORS_IRQ_WORK_ENTRY,
X86_IRQ_VECTORS_CALL_FUNCTION_ENTRY,
X86_IRQ_VECTORS_CALL_FUNCTION_SINGLE_ENTRY,
X86_IRQ_VECTORS_THRESHOLD_APIC_ENTRY,
X86_IRQ_VECTORS_DEFERRED_ERROR_APIC_ENTRY,
X86_IRQ_VECTORS_THERMAL_APIC_ENTRY)
override val ipiIrqVectorsExits = listOf(
X86_IRQ_VECTORS_LOCAL_TIMER_EXIT,
X86_IRQ_VECTORS_RESCHEDULE_EXIT,
X86_IRQ_VECTORS_SPURIOUS_EXIT,
X86_IRQ_VECTORS_ERROR_APIC_EXIT,
X86_IRQ_VECTORS_IPI_EXIT,
X86_IRQ_VECTORS_IRQ_WORK_EXIT,
X86_IRQ_VECTORS_CALL_FUNCTION_EXIT,
X86_IRQ_VECTORS_CALL_FUNCTION_SINGLE_EXIT,
X86_IRQ_VECTORS_THRESHOLD_APIC_EXIT,
X86_IRQ_VECTORS_DEFERRED_ERROR_APIC_EXIT,
X86_IRQ_VECTORS_THERMAL_APIC_EXIT)
// ------------------------------------------------------------------------
// New event definitions
// ------------------------------------------------------------------------
open val x86IrqVectorsLocalTimerEntry = X86_IRQ_VECTORS_LOCAL_TIMER_ENTRY
open val x86IrqVectorsLocalTimerExit = X86_IRQ_VECTORS_LOCAL_TIMER_EXIT
open val x86IrqVectorsRescheduleEntry = X86_IRQ_VECTORS_RESCHEDULE_ENTRY
open val x86IrqVectorsRescheduleExit = X86_IRQ_VECTORS_RESCHEDULE_EXIT
open val x86IrqVectorsSpuriousApicEntry = X86_IRQ_VECTORS_SPURIOUS_ENTRY
open val x86IrqVectorsSpuriousApicExit = X86_IRQ_VECTORS_SPURIOUS_EXIT
open val x86IrqVectorsErrorApicEntry = X86_IRQ_VECTORS_ERROR_APIC_ENTRY
open val x86IrqVectorsErrorApicExit = X86_IRQ_VECTORS_ERROR_APIC_EXIT
open val x86IrqVectorsIpiEntry = X86_IRQ_VECTORS_IPI_ENTRY
open val x86IrqVectorsIpiExit = X86_IRQ_VECTORS_IPI_EXIT
open val x86IrqVectorsIrqWorkEntry = X86_IRQ_VECTORS_IRQ_WORK_ENTRY
open val x86IrqVectorsIrqWorkExit = X86_IRQ_VECTORS_IRQ_WORK_EXIT
open val x86IrqVectorsCallFunctionEntry = X86_IRQ_VECTORS_CALL_FUNCTION_ENTRY
open val x86IrqVectorsCallFunctionExit = X86_IRQ_VECTORS_CALL_FUNCTION_EXIT
open val x86IrqVectorsCallFunctionSingleEntry = X86_IRQ_VECTORS_CALL_FUNCTION_SINGLE_ENTRY
open val x86IrqVectorsCallFunctionSingleExit = X86_IRQ_VECTORS_CALL_FUNCTION_SINGLE_EXIT
open val x86IrqVectorsThresholdApicEntry = X86_IRQ_VECTORS_THRESHOLD_APIC_ENTRY
open val x86IrqVectorsThresholdApicExit = X86_IRQ_VECTORS_THRESHOLD_APIC_EXIT
open val x86IrqVectorsDeferredErrorApicEntry = X86_IRQ_VECTORS_DEFERRED_ERROR_APIC_ENTRY
open val x86IrqVectorsDeferredErrorApicExit = X86_IRQ_VECTORS_DEFERRED_ERROR_APIC_EXIT
open val x86IrqVectorsThermalApicEntry = X86_IRQ_VECTORS_THERMAL_APIC_ENTRY
open val x86IrqVectorsThermalApicExit = X86_IRQ_VECTORS_THERMAL_APIC_EXIT
// ------------------------------------------------------------------------
// New field definitions in LTTng 2.7
// ------------------------------------------------------------------------
open val fieldParentNSInum = "parent_ns_inum"
open val fieldChildNSInum = "child_ns_inum"
open val fieldChildVTids = "vtids"
open val fieldNSInum = "ns_inum"
open val fieldVTid = "vtid"
open val fieldPPid = "ppid"
open val fieldNSLevel = "ns_level"
}
|
epl-1.0
|
dddd14b2d33164ff8632723b25acefc5
| 55.454545 | 115 | 0.683441 | 3.709308 | false | false | false | false |
wangjiegulu/AndroidKotlinBucket
|
library/src/main/kotlin/com/wangjie/androidkotlinbucket/library/AKBMVPExt.kt
|
1
|
3403
|
package com.wangjie.androidkotlinbucket.library
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.util.Log
import android.util.SparseArray
import android.view.View
import android.widget.Toast
/**
* Author: wangjie
* Email: [email protected]
* Date: 11/9/15.
*/
/**
* MVP的View层,UI相关,Activity需要实现该interface
* 它会包含一个Presenter的引用,当有事件发生(比如按钮点击后),会调用Presenter层的方法
*/
public interface KIViewer {
// val onClickListener: ((view: View) -> Unit)?
val mContext: Context?;
fun toast(message: String, duration: Int = Toast.LENGTH_SHORT) {
mContext?.lets { Toast.makeText(this, message, duration).show() }
}
fun dialog(title: String? = null,
message: String?,
okText: String? = "OK",
cancelText: String? = null,
positiveClickListener: ((DialogInterface, Int) -> Unit)? = null,
negativeClickListener: ((DialogInterface, Int) -> Unit)? = null
) {
mContext?.lets {
AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(okText, positiveClickListener)
.setNegativeButton(cancelText, negativeClickListener)
.show()
}
}
fun showLoading(message: String) {
Log.w(KIViewer::class.java.simpleName, "loadingDialog should impl by subclass")
}
fun cancelLoading() {
Log.w(KIViewer::class.java.simpleName, "cancelLoadingDialog should impl by subclass")
}
fun <T : View> findView(resId: Int): T;
}
/**
* MVP的Presenter层,作为沟通View和Model的桥梁,它从Model层检索数据后,返回给View层,它也可以决定与View层的交互操作。
* 它包含一个View层的引用和一个Model层的引用
*/
public interface KIPresenter {
public fun closeAll()
}
public open class KPresenter<V : KIViewer>(var viewer: V) : KIPresenter {
override public fun closeAll() {
Log.w(KIViewer::class.java.simpleName, "closeAll in KPresenter should impl by subclass")
}
}
/**
* Controller,用于派发View中的事件,它在根据不同的事件调用Presenter
*/
public interface KIController {
/**
* 注册事件
*/
fun bindEvents()
fun <T : View> getView(resId: Int): T;
fun closeAll()
// /**
// * 界面对用户显示(onResume)
// */
// fun onUserVisible() {
// }
//
// /**
// * 界面对用户隐藏(onPause)
// */
// fun onUserInvisible() {
// }
//
// /**
// * 界面销毁时回调,需要在BaseActivity或者BaseFragment等组件中调用
// */
// fun onDestroy() {
// }
}
public abstract class KController<KV : KIViewer, KP : KPresenter<*>>(val viewer: KV, presenterCreate: () -> KP) : KIController {
protected val presenter: KP by _lazy { presenterCreate() }
private val viewCache: SparseArray<View> = SparseArray();
public override fun <T : View> getView(resId: Int): T {
val view: View? = viewCache.get(resId)
return view as T? ?: viewer.findView<T>(resId).apply {
viewCache.put(resId, this)
}
}
public override fun closeAll() = presenter.closeAll()
}
|
apache-2.0
|
c2036f177af110459c134b2f4005f18f
| 24.528926 | 128 | 0.622855 | 3.673008 | false | false | false | false |
anton-okolelov/intellij-rust
|
src/test/kotlin/org/rust/ide/intentions/AddElseIntentionTest.kt
|
3
|
2132
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
class AddElseIntentionTest : RsIntentionTestBase(AddElseIntention()) {
fun test1() = doUnavailableTest("""
fn main() {
42/*caret*/;
}
""")
fun `test full if else`() = doUnavailableTest("""
fn foo(a: i32, b: i32) {
if a == b {
println!("Equally");/*caret*/
} else {
println!("Not equally");
}
}
""")
fun `test simple`() = doAvailableTest("""
fn foo(a: i32, b: i32) {
if a == b {
println!("Equally");/*caret*/
}
}
""", """
fn foo(a: i32, b: i32) {
if a == b {
println!("Equally");
} else {/*caret*/}
}
""")
fun `test caret after brace`() = doAvailableTest("""
fn foo() {
if true {
()
}/*caret*/
}
""", """
fn foo() {
if true {
()
} else {/*caret*/}
}
""")
fun `test nested 1`() = doAvailableTest("""
fn main() {
if true {
if true {
42
/*caret*/}
}
}
""", """
fn main() {
if true {
if true {
42
} else {/*caret*/}
}
}
""")
fun `test nested 2`() = doAvailableTest("""
fn main() {
if true {
if true {
42
}/*caret*/
}
}
""", """
fn main() {
if true {
if true {
42
}
} else {/*caret*/}
}
""")
fun `test reformat`() = doAvailableTest("""
fn main() {
if true {
/*caret*/
}
}
""", """
fn main() {
if true {} else {/*caret*/}
}
""")
}
|
mit
|
51f0462f079820515b32322c160473fa
| 20.108911 | 70 | 0.328799 | 4.878719 | false | true | false | false |
fython/PackageTracker
|
mobile/src/main/kotlin/info/papdt/express/helper/view/VerticalStepLineView.kt
|
1
|
2101
|
package info.papdt.express.helper.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import android.util.AttributeSet
import android.view.View
import info.papdt.express.helper.R
import info.papdt.express.helper.support.ScreenUtils
class VerticalStepLineView @JvmOverloads
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) {
private var mPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var mBounds: RectF? = null
private val lineWidth: Float
private var pointOffsetY = 0f
@ColorInt private var lineColor = Color.GRAY
private var shouldDrawTopLine = true
private var shouldDrawBottomLine = true
init {
lineWidth = ScreenUtils.dpToPx(context, 2f)
init()
lineColor = ContextCompat.getColor(context, R.color.blue_grey_500)
}
private fun init() {
mPaint.style = Paint.Style.FILL_AND_STROKE
mPaint.strokeWidth = lineWidth
}
fun setLineShouldDraw(top: Boolean, bottom: Boolean) {
shouldDrawTopLine = top
shouldDrawBottomLine = bottom
}
fun setLineColor(@ColorInt color: Int) {
lineColor = color
}
fun setLineColorResource(@ColorRes resId: Int) {
lineColor = ContextCompat.getColor(context, resId)
}
fun setPointOffsetY(pointOffsetY: Float) {
this.pointOffsetY = pointOffsetY
}
override fun onSizeChanged(w: Int, h: Int, oldW: Int, oldH: Int) {
super.onSizeChanged(w, h, oldW, oldH)
mBounds = RectF(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat())
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (shouldDrawTopLine) {
mPaint.color = lineColor
mBounds?.run { canvas.drawLine(centerX(), centerY() + pointOffsetY, centerX(), top, mPaint) }
}
if (shouldDrawBottomLine) {
mPaint.color = lineColor
mBounds?.run { canvas.drawLine(centerX(), centerY() + pointOffsetY, centerX(), bottom, mPaint) }
}
}
}
|
gpl-3.0
|
050945cf4fb48697c926e2c258ee39a8
| 25.935897 | 120 | 0.752499 | 3.585324 | false | false | false | false |
jdinkla/groovy-java-ray-tracer
|
src/main/kotlin/net/dinkla/raytracer/lights/AmbientOccluder.kt
|
1
|
1704
|
package net.dinkla.raytracer.lights
import net.dinkla.raytracer.colors.Color
import net.dinkla.raytracer.hits.Shade
import net.dinkla.raytracer.math.Basis
import net.dinkla.raytracer.math.Ray
import net.dinkla.raytracer.math.Vector3D
import net.dinkla.raytracer.samplers.Sampler
import net.dinkla.raytracer.worlds.World
/**
* Da war shared state drin. Böse bei der Parallelisierung
*/
class AmbientOccluder(
val minAmount: Color,
val sampler: Sampler,
val numSamples: Int
) : Ambient() {
constructor(sampler: Sampler, numSamples: Int) : this(Color.WHITE, sampler, numSamples) {}
override fun L(world: World, sr: Shade): Color {
val w = Vector3D(sr.normal)
// jitter up vector in case normal is vertical
val v = w cross (Vector3D.JITTER).normalize()
val u = v cross w
var numHits = 0
for (i in 0 until numSamples) {
val p = sampler.sampleHemisphere()
val dir = (u * p.x) + (v * p.y) + (w * p.z)
val shadowRay = Ray(sr.hitPoint, dir)
if (inShadow(world, shadowRay, sr)) {
numHits++
}
}
val ratio = 1.0 - 1.0 * numHits / numSamples
return color * (ls * ratio)
}
override fun getDirection(sr: Shade): Vector3D {
val p = sampler.sampleHemisphere()
val w = Vector3D(sr.normal)
val v = w cross (Vector3D.JITTER).normalize()
val u = v cross w
return Basis(u, v, w) * p
// return (u * p.x) + (v * p.y) + (w * p.z)
}
override fun inShadow(world: World, ray: Ray, sr: Shade): Boolean {
return world.inShadow(ray, sr, java.lang.Double.MAX_VALUE)
}
}
|
apache-2.0
|
08c2b3d90e489b6af225a6e6587a28c4
| 31.132075 | 94 | 0.608338 | 3.47551 | false | false | false | false |
corenting/EDCompanion
|
app/src/main/java/fr/corenting/edcompanion/services/FirebaseMessagingService.kt
|
1
|
2486
|
package fr.corenting.edcompanion.services
import android.app.PendingIntent
import android.content.Intent
import android.graphics.BitmapFactory
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.google.firebase.messaging.RemoteMessage
import com.google.gson.JsonParser
import fr.corenting.edcompanion.R
import fr.corenting.edcompanion.activities.MainActivity
import fr.corenting.edcompanion.utils.NotificationsUtils
class FirebaseMessagingService : com.google.firebase.messaging.FirebaseMessagingService() {
override fun onNewToken(s: String) {
super.onNewToken(s)
NotificationsUtils.refreshPushSubscriptions(this)
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
// Ignore empty messages
if (remoteMessage.data.isEmpty()) {
return
}
try {
handlePushMessage(remoteMessage)
} catch (e: Exception) {
Log.i("Firebase", "${e.message} when handling push message")
}
}
private fun handlePushMessage(remoteMessage: RemoteMessage) {
val type = remoteMessage.from?.substring(8)
val json = JsonParser.parseString(remoteMessage.data["goal"]).asJsonObject
val goalTitle = json.get("title").asString
val currentTier = json.get("tier_progress").asJsonObject.get("current").asInt
val channelId = NotificationsUtils.createNotificationChannel(this, type)
// Intent to launch app
val intent = Intent(this, MainActivity::class.java)
val contentIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT)
val largeIcon = BitmapFactory.decodeResource(resources,
R.drawable.ic_notification)
val mBuilder = NotificationCompat.Builder(this, channelId)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setLargeIcon(largeIcon)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(goalTitle)
.setAutoCancel(true)
.setContentText(NotificationsUtils.getNotificationContent(this, type, currentTier))
.setContentIntent(contentIntent)
val notificationManager = NotificationManagerCompat.from(this)
notificationManager.notify(goalTitle.hashCode(), mBuilder.build())
}
}
|
mit
|
c79ed2b16c2168d0acaf6560081b7334
| 36.666667 | 99 | 0.701931 | 5.200837 | false | false | false | false |
AerisG222/maw_photos_android
|
MaWPhotos/src/main/java/us/mikeandwan/photos/ui/controls/categorylist/CategoryListFragment.kt
|
1
|
2188
|
package us.mikeandwan.photos.ui.controls.categorylist
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import dagger.hilt.android.AndroidEntryPoint
import us.mikeandwan.photos.databinding.FragmentCategoryListBinding
import us.mikeandwan.photos.domain.models.PhotoCategory
import us.mikeandwan.photos.ui.controls.imagegrid.ImageGridFragment
@AndroidEntryPoint
class CategoryListFragment : Fragment() {
companion object {
fun newInstance() = ImageGridFragment()
}
private val _clickHandlerForwarder = CategoryListRecyclerAdapter.ClickListener { _clickHandler?.onClick(it) }
private var _clickHandler: CategoryListRecyclerAdapter.ClickListener? = null
private lateinit var binding: FragmentCategoryListBinding
val viewModel by viewModels<CategoryListViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentCategoryListBinding.inflate(inflater)
binding.lifecycleOwner = viewLifecycleOwner
binding.viewModel = viewModel
binding.categoryListRecyclerView.setHasFixedSize(true)
val adapter = CategoryListRecyclerAdapter(_clickHandlerForwarder)
adapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
binding.categoryListRecyclerView.adapter = adapter
val decoration = DividerItemDecoration(binding.categoryListRecyclerView.context, DividerItemDecoration.VERTICAL)
binding.categoryListRecyclerView.addItemDecoration(decoration)
return binding.root
}
fun setClickHandler(handler: CategoryListRecyclerAdapter.ClickListener) {
_clickHandler = handler
}
fun setCategories(categories: List<PhotoCategory>) {
viewModel.setCategories(categories)
}
fun setShowYear(doShow: Boolean) {
viewModel.setShowYear(doShow)
}
}
|
mit
|
31dea3f6c6309b900c688eec438cc30a
| 35.483333 | 120 | 0.778793 | 5.595908 | false | false | false | false |
Kotlin/dokka
|
plugins/base/src/test/kotlin/content/signatures/ContentForSignaturesTest.kt
|
1
|
17057
|
package content.signatures
import matchers.content.*
import org.jetbrains.dokka.DokkaConfiguration
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.model.doc.Text
import org.jetbrains.dokka.pages.*
import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest
import org.junit.jupiter.api.Test
import utils.ParamAttributes
import utils.bareSignature
import utils.propertySignature
import utils.typealiasSignature
class ContentForSignaturesTest : BaseAbstractTest() {
private val testConfiguration = dokkaConfiguration {
sourceSets {
sourceSet {
sourceRoots = listOf("src/")
analysisPlatform = "jvm"
documentedVisibilities = setOf(
DokkaConfiguration.Visibility.PUBLIC,
DokkaConfiguration.Visibility.PRIVATE,
DokkaConfiguration.Visibility.PROTECTED,
DokkaConfiguration.Visibility.INTERNAL,
)
}
}
}
@Test
fun `function`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|fun function(abc: String): String {
| return "Hello, " + abc
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(),
"",
"",
emptySet(),
"function",
"String",
"abc" to ParamAttributes(emptyMap(), emptySet(), "String")
)
}
}
}
}
}
}
}
@Test
fun `private function`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|private fun function(abc: String): String {
| return "Hello, " + abc
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(),
"private",
"",
emptySet(),
"function",
"String",
"abc" to ParamAttributes(emptyMap(), emptySet(), "String")
)
}
}
}
}
}
}
}
@Test
fun `open function`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|open fun function(abc: String): String {
| return "Hello, " + abc
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(),
"",
"open",
emptySet(),
"function",
"String",
"abc" to ParamAttributes(emptyMap(), emptySet(), "String")
)
}
}
}
}
}
}
}
@Test
fun `function without parameters`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|fun function(): String {
| return "Hello"
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
annotations = emptyMap(),
visibility = "",
modifier = "",
keywords = emptySet(),
name = "function",
returnType = "String",
)
}
}
}
}
}
}
}
@Test
fun `suspend function`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|suspend fun function(abc: String): String {
| return "Hello, " + abc
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(),
"",
"",
setOf("suspend"),
"function",
"String",
"abc" to ParamAttributes(emptyMap(), emptySet(), "String")
)
}
}
}
}
}
}
}
@Test
fun `protected open suspend function`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|protected open suspend fun function(abc: String): String {
| return "Hello, " + abc
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(),
"protected",
"open",
setOf("suspend"),
"function",
"String",
"abc" to ParamAttributes(emptyMap(), emptySet(), "String")
)
}
}
}
}
}
}
}
@Test
fun `protected open suspend inline function`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|protected open suspend inline fun function(abc: String): String {
| return "Hello, " + abc
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(),
"protected",
"open",
setOf("inline", "suspend"),
"function",
"String",
"abc" to ParamAttributes(emptyMap(), emptySet(), "String")
)
}
}
}
}
}
}
}
@Test
fun `property`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|val property: Int = 6
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" } as PackagePageNode
page.content.assertNode {
propertySignature(emptyMap(), "", "", emptySet(), "val", "property", "Int", "6")
}
}
}
}
@Test
fun `const property`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|const val property: Int = 6
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" } as PackagePageNode
page.content.assertNode {
propertySignature(emptyMap(), "", "", setOf("const"), "val", "property", "Int", "6")
}
}
}
}
@Test
fun `protected property`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|protected val property: Int = 6
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" } as PackagePageNode
page.content.assertNode {
propertySignature(emptyMap(), "protected", "", emptySet(), "val", "property", "Int", "6")
}
}
}
}
@Test
fun `protected lateinit property`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|protected lateinit var property: Int = 6
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" } as PackagePageNode
page.content.assertNode {
propertySignature(emptyMap(), "protected", "", setOf("lateinit"), "var", "property", "Int", null)
}
}
}
}
@Test
fun `should not display default value for mutable property`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|var property: Int = 6
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" } as PackagePageNode
page.content.assertNode {
propertySignature(
annotations = emptyMap(),
visibility = "",
modifier = "",
keywords = setOf(),
preposition = "var",
name = "property",
type = "Int",
value = null
)
}
}
}
}
@Test
fun `typealias to String`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|typealias Alias = String
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" } as PackagePageNode
page.content.assertNode {
typealiasSignature("Alias", "String")
}
}
}
}
@Test
fun `typealias to Int`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|typealias Alias = Int
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" } as PackagePageNode
page.content.assertNode {
typealiasSignature("Alias", "Int")
}
}
}
}
@Test
fun `typealias to type in same package`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|typealias Alias = X
|class X
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" } as PackagePageNode
page.content.assertNode {
typealiasSignature("Alias", "X")
}
}
}
}
@Test
fun `typealias to type in different package`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|import other.X
|typealias Alias = X
|
|/src/main/kotlin/test/source2.kt
|package other
|class X
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" } as PackagePageNode
page.content.assertNode {
typealiasSignature("Alias", "X")
}
}
}
}
@Test
fun `typealias to type in different package with same name`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|typealias Alias = other.Alias
|
|/src/main/kotlin/test/source2.kt
|package other
|class Alias
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" } as PackagePageNode
page.content.assertNode {
typealiasSignature("Alias", "other.Alias")
}
}
}
}
}
|
apache-2.0
|
0f505e5a2f0cac269975756ef5b41d01
| 32.314453 | 117 | 0.385238 | 6.357436 | false | true | false | false |
yyued/CodeX-UIKit-Android
|
library/src/main/java/com/yy/codex/uikit/UIViewAnimator.kt
|
1
|
20443
|
package com.yy.codex.uikit
import android.animation.Animator
import android.animation.ValueAnimator
import com.facebook.rebound.Spring
import com.facebook.rebound.SpringConfig
import com.facebook.rebound.SpringListener
import com.facebook.rebound.SpringSystem
import java.util.HashMap
/**
* Created by cuiminghui on 2017/1/16.
*/
object UIViewAnimator {
private var animationState: HashMap<UIView, HashMap<String, UIViewAnimatorState<*>>>? = null
fun addAnimationState(view: UIView, aKey: String, originValue: Double, finalValue: Double) {
val animationState = animationState ?: return
if (originValue == finalValue) {
return
}
if (animationState[view] == null) {
animationState.put(view, HashMap<String, UIViewAnimatorState<*>>())
}
val log: UIViewAnimatorState<Number>? = animationState[view]?.get(aKey) as? UIViewAnimatorState<Number>
if (log != null) {
log.finalValue = finalValue
}
else {
val newLog = UIViewAnimatorState<Number>()
newLog.valueType = 1
newLog.originValue = originValue
newLog.finalValue = finalValue
animationState[view]?.let {
it.put(aKey, newLog)
}
}
}
private fun resetAnimationState() {
animationState = hashMapOf()
}
fun linear(animations: Runnable): UIViewAnimation {
return linear(0.25, animations, null)
}
fun linear(duration: Double, animations: Runnable, completion: Runnable?): UIViewAnimation {
val animation = UIViewAnimation()
animation.completion = completion
resetAnimationState()
animations.run()
val animationState = animationState ?: return animation
this.animationState = null
val aniCount = intArrayOf(0)
for ((key, value) in animationState) {
for ((key1, log) in value) {
if (log.valueType == 1) {
aniCount[0]++
key.animate(key1, (log.originValue as Double).toFloat())
val animator = ValueAnimator.ofFloat((log.originValue as Double).toFloat(), (log.finalValue as Double).toFloat())
animator.duration = (duration * 1000).toLong()
animator.addUpdateListener(ValueAnimator.AnimatorUpdateListener { valueAnimator ->
if (animation.cancelled) {
return@AnimatorUpdateListener
}
val currentValue = valueAnimator.animatedValue as Float
key.animate(key1, currentValue)
})
animator.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animator: Animator) {
}
override fun onAnimationEnd(animator: Animator) {
if (animation.cancelled) {
return
}
aniCount[0]--
if (aniCount[0] <= 0) {
animation.markFinished()
}
if (aniCount[0] <= 0 && completion != null) {
completion.run()
}
}
override fun onAnimationCancel(animator: Animator) {
}
override fun onAnimationRepeat(animator: Animator) {
}
})
animator.setTarget(key)
animator.start()
}
}
}
if (aniCount[0] <= 0) {
animation.markFinished()
completion?.run()
}
return animation
}
fun spring(animations: Runnable): UIViewAnimation {
return spring(animations, null)
}
fun spring(animations: Runnable, completion: Runnable? = null): UIViewAnimation {
val animation = UIViewAnimation()
animation.completion = completion
resetAnimationState()
animations.run()
val animationState = animationState ?: return animation
this.animationState = null
val aniCount = intArrayOf(0)
val system = SpringSystem.create()
for ((key, value) in animationState) {
for ((key1, log) in value) {
if (log.valueType == 1) {
aniCount[0]++
key.animate(key1, (log.originValue as Double).toFloat())
val spring = system.createSpring()
spring.currentValue = (log.originValue as Double).toFloat().toDouble()
spring.addListener(object : SpringListener {
override fun onSpringUpdate(spring: Spring) {
if (animation.cancelled) {
return
}
val currentValue = spring.currentValue.toFloat()
key.animate(key1, currentValue)
}
override fun onSpringAtRest(spring: Spring) {
if (animation.cancelled) {
return
}
val currentValue = spring.currentValue.toFloat()
key.animate(key1, currentValue)
aniCount[0]--
if (aniCount[0] <= 0 && completion != null) {
completion.run()
}
}
override fun onSpringActivate(spring: Spring) {}
override fun onSpringEndStateChange(spring: Spring) {}
})
spring.endValue = (log.finalValue as Double).toFloat().toDouble()
}
}
}
if (aniCount[0] <= 0) {
animation.markFinished()
completion?.run()
}
return animation
}
fun springWithOptions(tension: Double, friction: Double, animations: Runnable, completion: Runnable?): UIViewAnimation {
val animation = UIViewAnimation()
animation.completion = completion
resetAnimationState()
animations.run()
val animationState = animationState ?: return animation
this.animationState = null
val aniCount = intArrayOf(0)
val system = SpringSystem.create()
for ((key, value) in animationState) {
for ((key1, log) in value) {
if (log.valueType == 1) {
aniCount[0]++
key.animate(key1, (log.originValue as Double).toFloat())
val spring = system.createSpring()
spring.currentValue = (log.originValue as Double).toFloat().toDouble()
val config = SpringConfig(tension, friction)
spring.springConfig = config
spring.addListener(object : SpringListener {
override fun onSpringUpdate(spring: Spring) {
if (animation.cancelled) {
return
}
val currentValue = spring.currentValue.toFloat()
key.animate(key1, currentValue)
}
override fun onSpringAtRest(spring: Spring) {
if (animation.cancelled) {
return
}
val currentValue = spring.currentValue.toFloat()
key.animate(key1, currentValue)
aniCount[0]--
if (aniCount[0] <= 0) {
animation.markFinished()
}
if (aniCount[0] <= 0 && completion != null) {
completion.run()
}
}
override fun onSpringActivate(spring: Spring) {}
override fun onSpringEndStateChange(spring: Spring) {}
})
spring.endValue = (log.finalValue as Double).toFloat().toDouble()
}
}
}
if (aniCount[0] <= 0) {
animation.markFinished()
completion?.run()
}
return animation
}
fun springWithBounciness(bounciness: Double, speed: Double, animations: Runnable, completion: Runnable?): UIViewAnimation {
val animation = UIViewAnimation()
animation.completion = completion
resetAnimationState()
animations.run()
val animationState = animationState ?: return animation
this.animationState = null
val aniCount = intArrayOf(0)
val system = SpringSystem.create()
for ((key, value) in animationState) {
for ((key1, log) in value) {
if (log.valueType == 1) {
aniCount[0]++
key.animate(key1, (log.originValue as Double).toFloat())
val spring = system.createSpring()
spring.currentValue = (log.originValue as Double).toFloat().toDouble()
val config = SpringConfig.fromBouncinessAndSpeed(bounciness, speed)
spring.springConfig = config
spring.addListener(object : SpringListener {
override fun onSpringUpdate(spring: Spring) {
if (animation.cancelled) {
return
}
val currentValue = spring.currentValue.toFloat()
key.animate(key1, currentValue)
}
override fun onSpringAtRest(spring: Spring) {
if (animation.cancelled) {
return
}
val currentValue = spring.currentValue.toFloat()
key.animate(key1, currentValue)
aniCount[0]--
if (aniCount[0] <= 0) {
animation.markFinished()
}
if (aniCount[0] <= 0 && completion != null) {
completion.run()
}
}
override fun onSpringActivate(spring: Spring) {}
override fun onSpringEndStateChange(spring: Spring) {}
})
spring.endValue = (log.finalValue as Double).toFloat().toDouble()
}
}
}
if (aniCount[0] <= 0) {
animation.markFinished()
completion?.run()
}
return animation
}
var decayDeceleration = 0.997
fun decay(animationView: UIView, animationKey: String, fromValue: Double, velocity: Double, completion: Runnable?): UIViewAnimation {
val animation = UIViewAnimation()
animation.completion = completion
val startTime = System.currentTimeMillis()
val deceleration = decayDeceleration
val finalValue = fromValue + velocity / (1.0 - deceleration) * (1 - Math.exp(-(1 - deceleration) * 999999999))
val valueAnimator = ValueAnimator.ofInt(0, 1)
valueAnimator.duration = 16
valueAnimator.repeatCount = 9999999
valueAnimator.addUpdateListener(ValueAnimator.AnimatorUpdateListener { valueAnimator ->
if (animation.cancelled) {
valueAnimator.cancel()
return@AnimatorUpdateListener
}
val now = System.currentTimeMillis()
val value = fromValue + velocity / (1.0 - deceleration) * (1 - Math.exp(-(1 - deceleration) * (now - startTime)))
animationView.animate(animationKey, value.toFloat())
if (Math.abs(finalValue - value) < 1.0) {
valueAnimator.cancel()
animation.markFinished()
completion?.run()
}
})
valueAnimator.start()
return animation
}
fun decayToValue(animationView: UIView, animationKey: String, fromValue: Double, toValue: Double, completion: Runnable?): UIViewAnimation {
val deceleration = decayDeceleration
val velocity = (toValue / (1 - Math.exp(-(1 - deceleration) * 999999999)) - fromValue) * (1.0 - deceleration)
return decay(animationView, animationKey, fromValue, velocity, completion)
}
class UIViewAnimationDecayBoundsOptions {
var fromValue: Double = 0.toDouble()
var velocity: Double = 0.toDouble()
var allowBounds = true
var alwaysBounds = false
var topBounds: Double = 0.toDouble()
var bottomBounds: Double = 0.toDouble()
var viewBounds: Double = 0.toDouble()
}
fun decayBounds(animationView: UIView, animationKey: String, options: UIViewAnimationDecayBoundsOptions, completion: Runnable?): UIViewAnimation {
if (!options.allowBounds && (options.fromValue <= options.topBounds || options.fromValue >= options.bottomBounds)) {
return UIViewAnimation()
}
if ((options.bottomBounds + options.viewBounds) - options.topBounds < options.viewBounds) {
if (options.allowBounds && options.alwaysBounds) {
options.bottomBounds = options.topBounds
} else {
return UIViewAnimation()
}
}
val deceleration = decayDeceleration
val finalValue = options.fromValue + options.velocity / (1.0 - deceleration) * (1 - Math.exp(-(1 - deceleration) * 999999999))
var backStartValue: Double
val backStarted = BooleanArray(1)
val backEndValue: Double
if (finalValue < options.topBounds) {
var tmpFinalValue = finalValue
if (options.fromValue < options.topBounds) {
tmpFinalValue = options.topBounds + options.velocity / (1.0 - deceleration) * (1 - Math.exp(-(1 - deceleration) * 999999999))
}
backStartValue = options.topBounds - (options.topBounds - tmpFinalValue) / 12.0
if (options.fromValue < options.topBounds) {
backStartValue += options.fromValue - options.topBounds
}
backEndValue = options.topBounds
if (options.fromValue < options.topBounds && Math.abs(options.velocity) < 1.0) {
backStarted[0] = true
}
} else if (finalValue > options.bottomBounds) {
var tmpFinalValue = finalValue
if (options.fromValue > options.bottomBounds) {
tmpFinalValue = options.bottomBounds + options.velocity / (1.0 - deceleration) * (1 - Math.exp(-(1 - deceleration) * 999999999))
}
backStartValue = (tmpFinalValue - options.bottomBounds) / 12.0 + options.bottomBounds
if (options.fromValue > options.bottomBounds) {
backStartValue += options.fromValue - options.bottomBounds
}
backEndValue = options.bottomBounds
if (options.fromValue > options.bottomBounds && Math.abs(options.velocity) < 1.0) {
backStarted[0] = true
}
} else {
return decay(animationView, animationKey, options.fromValue, options.velocity, completion)
}
val startTime = System.currentTimeMillis()
val animation = UIViewAnimation()
animation.completion = completion
val valueAnimator = ValueAnimator.ofInt(0, 1)
valueAnimator.duration = 16
valueAnimator.repeatCount = 9999999
val finalBackStartValue = backStartValue
val finalBackEndValue = backEndValue
valueAnimator.addUpdateListener(ValueAnimator.AnimatorUpdateListener { valueAnimator ->
if (animation.cancelled) {
valueAnimator.cancel()
return@AnimatorUpdateListener
}
var decayValue = options.fromValue + options.velocity / (1.0 - deceleration) * (1 - Math.exp(-(1 - deceleration) * (System.currentTimeMillis() - startTime)))
if (options.fromValue < options.topBounds) {
decayValue = options.topBounds + options.velocity / (1.0 - deceleration) * (1 - Math.exp(-(1 - deceleration) * (System.currentTimeMillis() - startTime)))
}
if (options.fromValue > options.bottomBounds) {
decayValue = options.bottomBounds + options.velocity / (1.0 - deceleration) * (1 - Math.exp(-(1 - deceleration) * (System.currentTimeMillis() - startTime)))
}
if (decayValue < options.topBounds) {
decayValue = options.topBounds - (options.topBounds - decayValue) / 3
if (options.fromValue < options.topBounds) {
decayValue -= options.topBounds - options.fromValue
}
} else if (decayValue > options.bottomBounds) {
decayValue = (decayValue - options.bottomBounds) / 3 + options.bottomBounds
if (options.fromValue > options.bottomBounds) {
decayValue += options.fromValue - options.bottomBounds
}
}
if (!options.allowBounds) {
if (decayValue <= options.topBounds) {
animationView.animate(animationKey, options.topBounds.toFloat())
valueAnimator.cancel()
animation.markFinished()
return@AnimatorUpdateListener
} else if (decayValue >= options.bottomBounds) {
animationView.animate(animationKey, options.bottomBounds.toFloat())
valueAnimator.cancel()
animation.markFinished()
return@AnimatorUpdateListener
}
} else if (backStarted[0]) {
val system = SpringSystem.create()
val spring = system.createSpring()
spring.currentValue = finalBackStartValue
val config = SpringConfig(120.0, 20.0)
var fValue = 0.0f
spring.springConfig = config
spring.addListener(object : SpringListener {
override fun onSpringUpdate(spring: Spring) {
if (animation.cancelled) {
return
}
val currentValue = spring.currentValue.toFloat()
if (Math.abs(fValue - currentValue) < 1.0) {
onSpringAtRest(spring)
return
}
fValue = currentValue
animationView.animate(animationKey, currentValue)
}
override fun onSpringAtRest(spring: Spring) {
if (animation.cancelled) {
return
}
completion?.run()
}
override fun onSpringActivate(spring: Spring) {
}
override fun onSpringEndStateChange(spring: Spring) {
}
})
spring.endValue = finalBackEndValue
valueAnimator.cancel()
} else if (!backStarted[0]) {
if (finalValue < options.topBounds && decayValue < finalBackStartValue && !backStarted[0]) {
backStarted[0] = true
} else if (finalValue > options.bottomBounds && decayValue > finalBackStartValue && !backStarted[0]) {
backStarted[0] = true
}
}
animationView.animate(animationKey, decayValue.toFloat())
})
valueAnimator.start()
return animation
}
}
|
gpl-3.0
|
6fe28c7bc7a26207fadd424516bdc152
| 42.869099 | 172 | 0.52101 | 5.867681 | false | false | false | false |
talhacohen/android
|
app/src/main/java/com/etesync/syncadapter/syncadapter/TasksSyncManager.kt
|
1
|
3866
|
/*
* Copyright © Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.syncadapter
import android.accounts.Account
import android.content.Context
import android.content.SyncResult
import android.os.Bundle
import at.bitfire.ical4android.Task
import com.etesync.syncadapter.AccountSettings
import com.etesync.syncadapter.App
import com.etesync.syncadapter.Constants
import com.etesync.syncadapter.R
import com.etesync.syncadapter.journalmanager.JournalEntryManager
import com.etesync.syncadapter.model.CollectionInfo
import com.etesync.syncadapter.model.SyncEntry
import com.etesync.syncadapter.resource.LocalTask
import com.etesync.syncadapter.resource.LocalTaskList
import okhttp3.HttpUrl
import java.io.StringReader
/**
* Synchronization manager for CalDAV collections; handles tasks (VTODO)
*/
class TasksSyncManager(
context: Context,
account: Account,
accountSettings: AccountSettings,
extras: Bundle,
authority: String,
syncResult: SyncResult,
taskList: LocalTaskList,
private val remote: HttpUrl
): SyncManager<LocalTask>(context, account, accountSettings, extras, authority, syncResult, taskList.url!!, CollectionInfo.Type.TASKS, account.name) {
override val syncErrorTitle: String
get() = context.getString(R.string.sync_error_tasks, account.name)
override val syncSuccessfullyTitle: String
get() = context.getString(R.string.sync_successfully_tasks, info.displayName,
account.name)
init {
localCollection = taskList
}
override fun notificationId(): Int {
return Constants.NOTIFICATION_TASK_SYNC
}
override fun prepare(): Boolean {
if (!super.prepare())
return false
journal = JournalEntryManager(httpClient, remote, localTaskList().url!!)
return true
}
// helpers
private fun localTaskList(): LocalTaskList {
return localCollection as LocalTaskList
}
override fun processSyncEntry(cEntry: SyncEntry) {
val inputReader = StringReader(cEntry.content)
val tasks = Task.fromReader(inputReader)
if (tasks.size == 0) {
App.log.warning("Received VCard without data, ignoring")
return
} else if (tasks.size > 1) {
App.log.warning("Received multiple VCALs, using first one")
}
val event = tasks[0]
val local = localCollection!!.findByUid(event.uid!!)
if (cEntry.isAction(SyncEntry.Actions.ADD) || cEntry.isAction(SyncEntry.Actions.CHANGE)) {
processTask(event, local)
} else {
if (local != null) {
App.log.info("Removing local record #" + local.id + " which has been deleted on the server")
local.delete()
} else {
App.log.warning("Tried deleting a non-existent record: " + event.uid)
}
}
}
private fun processTask(newData: Task, _localTask: LocalTask?): LocalTask {
var localTask = _localTask
// delete local Task, if it exists
if (localTask != null) {
App.log.info("Updating " + newData.uid + " in local calendar")
localTask.eTag = newData.uid
localTask.update(newData)
syncResult.stats.numUpdates++
} else {
App.log.info("Adding " + newData.uid + " to local calendar")
localTask = LocalTask(localTaskList(), newData, newData.uid, newData.uid)
localTask.add()
syncResult.stats.numInserts++
}
return localTask
}
}
|
gpl-3.0
|
da547c99daeedc2ff0192ae4da29a59b
| 32.912281 | 150 | 0.664942 | 4.563164 | false | false | false | false |
canou/Simple-Commons
|
commons/src/main/kotlin/com/simplemobiletools/commons/asynctasks/CopyMoveTask.kt
|
1
|
4097
|
package com.simplemobiletools.commons.asynctasks
import android.os.AsyncTask
import android.support.v4.provider.DocumentFile
import android.support.v4.util.Pair
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.*
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.io.OutputStream
import java.lang.ref.WeakReference
import java.util.*
class CopyMoveTask(val activity: BaseSimpleActivity, val copyOnly: Boolean = false, val copyMediaOnly: Boolean,
listener: CopyMoveTask.CopyMoveListener) : AsyncTask<Pair<ArrayList<File>, File>, Void, Boolean>() {
private var mListener: WeakReference<CopyMoveListener>? = null
private var mMovedFiles: ArrayList<File> = ArrayList()
private var mDocument: DocumentFile? = null
lateinit var mFiles: ArrayList<File>
init {
mListener = WeakReference(listener)
}
override fun doInBackground(vararg params: Pair<ArrayList<File>, File>): Boolean? {
if (params.isEmpty())
return false
val pair = params[0]
mFiles = pair.first
for (file in mFiles) {
try {
val curFile = File(pair.second, file.name)
if (curFile.exists())
continue
copy(file, curFile)
} catch (e: Exception) {
activity.toast(e.toString())
return false
}
}
if (!copyOnly) {
activity.deleteFiles(mMovedFiles) {}
}
activity.scanFiles(mFiles) {}
return true
}
private fun copy(source: File, destination: File) {
if (source.isDirectory) {
copyDirectory(source, destination)
} else {
copyFile(source, destination)
}
}
private fun copyDirectory(source: File, destination: File) {
if (!activity.createDirectorySync(destination)) {
val error = String.format(activity.getString(R.string.could_not_create_folder), destination.absolutePath)
activity.showErrorToast(error)
return
}
val children = source.list()
for (child in children) {
val newFile = File(destination, child)
if (newFile.exists())
continue
val oldFile = File(source, child)
copy(oldFile, newFile)
}
mMovedFiles.add(source)
}
private fun copyFile(source: File, destination: File) {
if (copyMediaOnly && !source.absolutePath.isImageVideoGif())
return
val directory = destination.parentFile
if (!activity.createDirectorySync(directory)) {
val error = String.format(activity.getString(R.string.could_not_create_folder), directory.absolutePath)
activity.showErrorToast(error)
return
}
var inputStream: InputStream? = null
var out: OutputStream? = null
try {
if (mDocument == null && activity.needsStupidWritePermissions(destination.absolutePath)) {
mDocument = activity.getFileDocument(destination.parent)
}
out = activity.getFileOutputStreamSync(destination.absolutePath, source.getMimeType(), mDocument)
inputStream = FileInputStream(source)
inputStream.copyTo(out!!)
activity.scanFile(destination) {}
if (source.length() == destination.length())
mMovedFiles.add(source)
} finally {
inputStream?.close()
out?.close()
}
}
override fun onPostExecute(success: Boolean) {
val listener = mListener?.get() ?: return
if (success) {
listener.copySucceeded(copyOnly, mMovedFiles.size >= mFiles.size)
} else {
listener.copyFailed()
}
}
interface CopyMoveListener {
fun copySucceeded(copyOnly: Boolean, copiedAll: Boolean)
fun copyFailed()
}
}
|
apache-2.0
|
a03105ea9b060e34c18901541d0884c5
| 31.007813 | 119 | 0.616793 | 4.877381 | false | false | false | false |
iluu/algs-progfun
|
src/main/kotlin/com/hackerrank/BetweenTwoSets.kt
|
1
|
718
|
package com.hackerrank
import java.util.*
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val n = scan.nextInt()
val m = scan.nextInt()
val a = Array(n, { scan.nextLong() })
val b = Array(m, { scan.nextLong() })
print(countBetweenSets(a, b))
}
fun countBetweenSets(a: Array<Long>, b: Array<Long>): Int {
val l = a.reduce { i, j -> i * (j / gcd(i, j)) }
val g = b.reduce { i, j -> gcd(i, j) }
var result = 0
var multiple = 1
for (i in l..g step l * multiple) {
if (g % i == 0L) {
result++
}
multiple++
}
return result
}
fun gcd(a: Long, b: Long): Long {
if (b == 0L) return a
return gcd(b, a % b)
}
|
mit
|
3f947195688d68529e25f27094fab02a
| 19.514286 | 59 | 0.520891 | 2.966942 | false | false | false | false |
openMF/android-client
|
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/clientdetails/ClientDetailsPresenter.kt
|
1
|
4707
|
package com.mifos.mifosxdroid.online.clientdetails
import com.mifos.api.datamanager.DataManagerClient
import com.mifos.api.datamanager.DataManagerDataTable
import com.mifos.mifosxdroid.base.BasePresenter
import com.mifos.objects.zipmodels.ClientAndClientAccounts
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import rx.Observable
import rx.Subscriber
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.File
import javax.inject.Inject
/**
* Created by Rajan Maurya on 07/06/16.
*/
class ClientDetailsPresenter @Inject constructor(private val mDataManagerDataTable: DataManagerDataTable,
private val mDataManagerClient: DataManagerClient) : BasePresenter<ClientDetailsMvpView?>() {
private var mSubscription: Subscription? = null
override fun attachView(mvpView: ClientDetailsMvpView?) {
super.attachView(mvpView)
}
override fun detachView() {
super.detachView()
if (mSubscription != null) mSubscription!!.unsubscribe()
}
fun uploadImage(id: Int, pngFile: File) {
checkViewAttached()
val imagePath = pngFile.absolutePath
// create RequestBody instance from file
val requestFile = RequestBody.create(MediaType.parse("image/png"), pngFile)
// MultipartBody.Part is used to send also the actual file name
val body = MultipartBody.Part.createFormData("file", pngFile.name, requestFile)
mvpView!!.showUploadImageProgressbar(true)
if (mSubscription != null) mSubscription!!.unsubscribe()
mSubscription = mDataManagerClient.uploadClientImage(id, body)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(object : Subscriber<ResponseBody?>() {
override fun onCompleted() {
mvpView!!.showUploadImageProgressbar(false)
}
override fun onError(e: Throwable) {
mvpView!!.showUploadImageFailed("Unable to update image")
}
override fun onNext(response: ResponseBody?) {
mvpView!!.showUploadImageProgressbar(false)
mvpView!!.showUploadImageSuccessfully(response, imagePath)
}
})
}
fun deleteClientImage(clientId: Int) {
checkViewAttached()
if (mSubscription != null) mSubscription!!.unsubscribe()
mSubscription = mDataManagerClient.deleteClientImage(clientId)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(object : Subscriber<ResponseBody?>() {
override fun onCompleted() {}
override fun onError(e: Throwable) {
mvpView!!.showFetchingError("Failed to delete image")
}
override fun onNext(response: ResponseBody?) {
mvpView!!.showClientImageDeletedSuccessfully()
}
})
}
fun loadClientDetailsAndClientAccounts(clientId: Int) {
checkViewAttached()
mvpView!!.showProgressbar(true)
if (mSubscription != null) mSubscription!!.unsubscribe()
mSubscription = Observable.zip(
mDataManagerClient.getClientAccounts(clientId),
mDataManagerClient.getClient(clientId)
) { clientAccounts, client ->
val clientAndClientAccounts = ClientAndClientAccounts()
clientAndClientAccounts.client = client
clientAndClientAccounts.clientAccounts = clientAccounts
clientAndClientAccounts
}
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(object : Subscriber<ClientAndClientAccounts?>() {
override fun onCompleted() {}
override fun onError(e: Throwable) {
mvpView!!.showProgressbar(false)
mvpView!!.showFetchingError("Client not found.")
}
override fun onNext(clientAndClientAccounts: ClientAndClientAccounts?) {
mvpView!!.showProgressbar(false)
mvpView!!.showClientAccount(clientAndClientAccounts!!.clientAccounts)
mvpView!!.showClientInformation(clientAndClientAccounts.client)
}
})
}
}
|
mpl-2.0
|
efa5ddccb207eccc980f046cc6b4ef7e
| 41.035714 | 142 | 0.620353 | 6.177165 | false | false | false | false |
openMF/android-client
|
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/collectionsheet/CollectionSheetPresenter.kt
|
1
|
2693
|
package com.mifos.mifosxdroid.online.collectionsheet
import com.mifos.api.DataManager
import com.mifos.api.model.CollectionSheetPayload
import com.mifos.api.model.Payload
import com.mifos.mifosxdroid.base.BasePresenter
import com.mifos.objects.db.CollectionSheet
import com.mifos.objects.response.SaveResponse
import retrofit2.adapter.rxjava.HttpException
import rx.Subscriber
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import javax.inject.Inject
/**
* Created by Rajan Maurya on 7/6/16.
*/
class CollectionSheetPresenter @Inject constructor(private val mDataManager: DataManager) : BasePresenter<CollectionSheetMvpView?>() {
private var mSubscription: Subscription? = null
override fun attachView(mvpView: CollectionSheetMvpView?) {
super.attachView(mvpView)
}
override fun detachView() {
super.detachView()
if (mSubscription != null) mSubscription!!.unsubscribe()
}
fun loadCollectionSheet(id: Long, payload: Payload?) {
checkViewAttached()
if (mSubscription != null) mSubscription!!.unsubscribe()
mSubscription = mDataManager.getCollectionSheet(id, payload)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(object : Subscriber<CollectionSheet?>() {
override fun onCompleted() {}
override fun onError(e: Throwable) {
mvpView!!.showFetchingError("Failed to fetch CollectionSheet")
}
override fun onNext(collectionSheet: CollectionSheet?) {
collectionSheet?.let { mvpView!!.showCollectionSheet(it) }
}
})
}
fun saveCollectionSheet(id: Int, payload: CollectionSheetPayload?) {
checkViewAttached()
if (mSubscription != null) mSubscription!!.unsubscribe()
mSubscription = mDataManager.saveCollectionSheetAsync(id, payload)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(object : Subscriber<SaveResponse?>() {
override fun onCompleted() {}
override fun onError(e: Throwable) {
if (e is HttpException) {
mvpView!!.showFailedToSaveCollectionSheet(e)
}
}
override fun onNext(saveResponse: SaveResponse?) {
mvpView!!.showCollectionSheetSuccessfullySaved(saveResponse)
}
})
}
}
|
mpl-2.0
|
492acce2bbeef08f44241fd5425a88cc
| 38.617647 | 134 | 0.628296 | 5.622129 | false | false | false | false |
themasterapp/master-app-android
|
MasterApp/app/src/main/java/br/com/ysimplicity/masterapp/helper/SessionManager.kt
|
1
|
959
|
package br.com.ysimplicity.masterapp.helper
import android.content.Context
import android.preference.PreferenceManager
/**
* Created by Ghost on 14/11/2017.
*/
class SessionManager {
companion object {
private val auth_token = "AUTH_TOKEN"
fun saveToken(context: Context, token: String) {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
val editor = prefs.edit()
editor.putString(auth_token, token)
editor.apply()
}
fun isUserSignedIn(context: Context): Boolean {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
return prefs.getString(auth_token, "").isNotEmpty()
}
fun logoutUser(context: Context) {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
val editor = prefs.edit()
editor.clear()
editor.apply()
}
}
}
|
mit
|
ac7b8897e31e814eb444f889549f1b3a
| 28.090909 | 78 | 0.632951 | 4.917949 | false | false | false | false |
czyzby/gdx-setup
|
src/main/kotlin/com/github/czyzby/setup/views/dialogs/generationPrompt.kt
|
2
|
3783
|
package com.github.czyzby.setup.views.dialogs
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.scenes.scene2d.ui.Button
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane
import com.badlogic.gdx.scenes.scene2d.ui.Window
import com.badlogic.gdx.utils.ObjectSet
import com.github.czyzby.autumn.annotation.Destroy
import com.github.czyzby.autumn.annotation.Inject
import com.github.czyzby.autumn.mvc.component.i18n.LocaleService
import com.github.czyzby.autumn.mvc.component.ui.controller.ViewDialogShower
import com.github.czyzby.autumn.mvc.stereotype.ViewDialog
import com.github.czyzby.kiwi.util.common.Exceptions
import com.github.czyzby.lml.annotation.LmlActor
import com.github.czyzby.setup.data.project.ProjectLogger
import com.github.czyzby.setup.views.MainView
import com.kotcrab.vis.ui.widget.VisTextArea
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.Executors
import java.util.concurrent.ThreadFactory
import java.util.concurrent.atomic.AtomicLong
/**
* Displayed after generation request was sent.
* @author MJ
*/
@ViewDialog(id = "generation", value = "templates/dialogs/generation.lml", cacheInstance = false)
class GenerationPrompt : ViewDialogShower, ProjectLogger {
@Inject private lateinit var locale: LocaleService;
@Inject private lateinit var mainView: MainView
@LmlActor("close", "exit") private lateinit var buttons: ObjectSet<Button>
@LmlActor("console") private lateinit var console: VisTextArea
@LmlActor("scroll") private lateinit var scrollPane: ScrollPane
private val executor = Executors.newSingleThreadExecutor(PrefixedThreadFactory("ProjectGenerator"))
private val loggingBuffer = ConcurrentLinkedQueue<String>()
override fun doBeforeShow(dialog: Window) {
dialog.invalidate()
executor.execute {
try {
logNls("copyStart")
val project = mainView.createProject()
project.generate()
logNls("copyEnd")
mainView.revalidateForm()
project.includeGradleWrapper(this)
logNls("generationEnd")
} catch(exception: Exception) {
log(exception.javaClass.name + ": " + exception.message)
exception.stackTrace.forEach { log(" at $it") }
exception.printStackTrace()
logNls("generationFail")
} finally {
buttons.forEach { it.isDisabled = false }
}
}
}
override fun logNls(bundleLine: String) = log(locale.i18nBundle.get(bundleLine))
override fun log(message: String) {
loggingBuffer.offer(message)
Gdx.app.postRunnable {
while (loggingBuffer.isNotEmpty()) {
if (console.text.isNotBlank()) console.text += '\n'
console.text += loggingBuffer.poll()
}
Gdx.app.postRunnable {
console.invalidateHierarchy()
scrollPane.layout()
scrollPane.scrollPercentY = 1f
}
}
}
@Destroy()
fun shutdownExecutor() {
try {
executor.shutdownNow()
} catch(exception: Exception) {
Exceptions.ignore(exception)
}
}
}
/**
* Generates sane thread names for [Executors].
* @author Kotcrab
*/
private class PrefixedThreadFactory(threadPrefix: String) : ThreadFactory {
private val count = AtomicLong(0)
private val threadPrefix: String
init {
this.threadPrefix = threadPrefix + "-"
}
override fun newThread(runnable: Runnable): Thread {
val thread = Executors.defaultThreadFactory().newThread(runnable)
thread.name = threadPrefix + count.andIncrement
return thread
}
}
|
unlicense
|
54d4c198a6d8fc56cd3787b72a0e71e6
| 35.375 | 103 | 0.674333 | 4.503571 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android
|
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/product/ProductRestClient.kt
|
1
|
80146
|
package org.wordpress.android.fluxc.network.rest.wpcom.wc.product
import android.content.Context
import com.android.volley.RequestQueue
import com.google.gson.JsonArray
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.action.WCProductAction
import org.wordpress.android.fluxc.generated.WCProductActionBuilder
import org.wordpress.android.fluxc.generated.endpoint.WOOCOMMERCE
import org.wordpress.android.fluxc.generated.endpoint.WPCOMREST
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.WCProductCategoryModel
import org.wordpress.android.fluxc.model.WCProductImageModel
import org.wordpress.android.fluxc.model.WCProductModel
import org.wordpress.android.fluxc.model.WCProductReviewModel
import org.wordpress.android.fluxc.model.WCProductShippingClassModel
import org.wordpress.android.fluxc.model.WCProductTagModel
import org.wordpress.android.fluxc.model.WCProductVariationModel
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest.WPComGsonNetworkError
import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequest
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackError
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackSuccess
import org.wordpress.android.fluxc.network.rest.wpcom.post.PostWPComRestResponse
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload
import org.wordpress.android.fluxc.network.rest.wpcom.wc.toWooError
import org.wordpress.android.fluxc.store.WCProductStore
import org.wordpress.android.fluxc.store.WCProductStore.Companion.DEFAULT_CATEGORY_SORTING
import org.wordpress.android.fluxc.store.WCProductStore.Companion.DEFAULT_PRODUCT_CATEGORY_PAGE_SIZE
import org.wordpress.android.fluxc.store.WCProductStore.Companion.DEFAULT_PRODUCT_PAGE_SIZE
import org.wordpress.android.fluxc.store.WCProductStore.Companion.DEFAULT_PRODUCT_SHIPPING_CLASS_PAGE_SIZE
import org.wordpress.android.fluxc.store.WCProductStore.Companion.DEFAULT_PRODUCT_SORTING
import org.wordpress.android.fluxc.store.WCProductStore.Companion.DEFAULT_PRODUCT_TAGS_PAGE_SIZE
import org.wordpress.android.fluxc.store.WCProductStore.Companion.DEFAULT_PRODUCT_VARIATIONS_PAGE_SIZE
import org.wordpress.android.fluxc.store.WCProductStore.FetchProductReviewsResponsePayload
import org.wordpress.android.fluxc.store.WCProductStore.ProductCategorySorting
import org.wordpress.android.fluxc.store.WCProductStore.ProductCategorySorting.NAME_DESC
import org.wordpress.android.fluxc.store.WCProductStore.ProductError
import org.wordpress.android.fluxc.store.WCProductStore.ProductErrorType
import org.wordpress.android.fluxc.store.WCProductStore.ProductErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.store.WCProductStore.ProductFilterOption
import org.wordpress.android.fluxc.store.WCProductStore.ProductSorting
import org.wordpress.android.fluxc.store.WCProductStore.ProductSorting.DATE_ASC
import org.wordpress.android.fluxc.store.WCProductStore.ProductSorting.DATE_DESC
import org.wordpress.android.fluxc.store.WCProductStore.ProductSorting.TITLE_ASC
import org.wordpress.android.fluxc.store.WCProductStore.ProductSorting.TITLE_DESC
import org.wordpress.android.fluxc.store.WCProductStore.RemoteAddProductCategoryResponsePayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteAddProductPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteAddProductTagsResponsePayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteDeleteProductPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteProductCategoriesPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteProductListPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteProductPasswordPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteProductPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteProductReviewPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteProductShippingClassListPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteProductShippingClassPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteProductSkuAvailabilityPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteProductTagsPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteProductVariationsPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteSearchProductsPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteUpdateProductImagesPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteUpdateProductPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteUpdateVariationPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteUpdatedProductPasswordPayload
import org.wordpress.android.fluxc.store.WCProductStore.RemoteVariationPayload
import org.wordpress.android.fluxc.utils.handleResult
import org.wordpress.android.fluxc.utils.putIfNotEmpty
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
@Suppress("LargeClass")
@Singleton
class ProductRestClient @Inject constructor(
appContext: Context,
private val dispatcher: Dispatcher,
@Named("regular") requestQueue: RequestQueue,
accessToken: AccessToken,
userAgent: UserAgent,
private val jetpackTunnelGsonRequestBuilder: JetpackTunnelGsonRequestBuilder
) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) {
/**
* Makes a GET request to `/wp-json/wc/v3/products/shipping_classes/[remoteShippingClassId]`
* to fetch a single product shipping class
*
* Dispatches a WCProductAction.FETCHED_SINGLE_PRODUCT_SHIPPING_CLASS action with the result
*
* @param [remoteShippingClassId] Unique server id of the shipping class to fetch
*/
fun fetchSingleProductShippingClass(site: SiteModel, remoteShippingClassId: Long) {
val url = WOOCOMMERCE.products.shipping_classes.id(remoteShippingClassId).pathV3
val responseType = object : TypeToken<ProductShippingClassApiResponse>() {}.type
val params = emptyMap<String, String>()
val request = JetpackTunnelGsonRequest.buildGetRequest(url, site.siteId, params, responseType,
{ response: ProductShippingClassApiResponse? ->
response?.let {
val newModel = productShippingClassResponseToProductShippingClassModel(
it, site
).apply { localSiteId = site.id }
val payload = RemoteProductShippingClassPayload(newModel, site)
dispatcher.dispatch(WCProductActionBuilder.newFetchedSingleProductShippingClassAction(payload))
}
},
{ networkError ->
val productError = networkErrorToProductError(networkError)
val payload = RemoteProductShippingClassPayload(
productError,
WCProductShippingClassModel().apply { this.remoteShippingClassId = remoteShippingClassId },
site
)
dispatcher.dispatch(WCProductActionBuilder.newFetchedSingleProductShippingClassAction(payload))
},
{ request: WPComGsonRequest<*> -> add(request) })
add(request)
}
/**
* Makes a GET request to `GET /wp-json/wc/v3/products/shipping_classes` to fetch
* product shipping classes for a site
*
* Dispatches a WCProductAction.FETCHED_PRODUCT_SHIPPING_CLASS_LIST action with the result
*
* @param [site] The site to fetch product shipping class list for
*/
fun fetchProductShippingClassList(
site: SiteModel,
pageSize: Int = DEFAULT_PRODUCT_SHIPPING_CLASS_PAGE_SIZE,
offset: Int = 0
) {
val url = WOOCOMMERCE.products.shipping_classes.pathV3
val responseType = object : TypeToken<List<ProductShippingClassApiResponse>>() {}.type
val params = mutableMapOf(
"per_page" to pageSize.toString(),
"offset" to offset.toString()
)
val request = JetpackTunnelGsonRequest.buildGetRequest(url, site.siteId, params, responseType,
{ response: List<ProductShippingClassApiResponse>? ->
val shippingClassList = response?.map {
productShippingClassResponseToProductShippingClassModel(it, site)
}.orEmpty()
val loadedMore = offset > 0
val canLoadMore = shippingClassList.size == pageSize
val payload = RemoteProductShippingClassListPayload(
site, shippingClassList, offset, loadedMore, canLoadMore
)
dispatcher.dispatch(WCProductActionBuilder.newFetchedProductShippingClassListAction(payload))
},
{ networkError ->
val productError = networkErrorToProductError(networkError)
val payload = RemoteProductShippingClassListPayload(productError, site)
dispatcher.dispatch(WCProductActionBuilder.newFetchedProductShippingClassListAction(payload))
},
{ request: WPComGsonRequest<*> -> add(request) })
add(request)
}
/**
* Makes a GET request to `GET /wp-json/wc/v3/products/tags` to fetch
* product tags for a site
*
* Dispatches a WCProductAction.FETCHED_PRODUCT_TAGS action with the result
*
* @param [site] The site to fetch product shipping class list for
* @param [pageSize] The size of the tags needed from the API response
* @param [offset] The page number passed to the API
*/
fun fetchProductTags(
site: SiteModel,
pageSize: Int = DEFAULT_PRODUCT_TAGS_PAGE_SIZE,
offset: Int = 0,
searchQuery: String? = null
) {
val url = WOOCOMMERCE.products.tags.pathV3
val responseType = object : TypeToken<List<ProductTagApiResponse>>() {}.type
val params = mutableMapOf(
"per_page" to pageSize.toString(),
"offset" to offset.toString()
).putIfNotEmpty("search" to searchQuery)
val request = JetpackTunnelGsonRequest.buildGetRequest(url, site.siteId, params, responseType,
{ response: List<ProductTagApiResponse>? ->
val tags = response?.map {
productTagApiResponseToProductTagModel(it, site)
}.orEmpty()
val loadedMore = offset > 0
val canLoadMore = tags.size == pageSize
val payload = RemoteProductTagsPayload(site, tags, offset, loadedMore, canLoadMore, searchQuery)
dispatcher.dispatch(WCProductActionBuilder.newFetchedProductTagsAction(payload))
},
{ networkError ->
val productError = networkErrorToProductError(networkError)
val payload = RemoteProductTagsPayload(productError, site)
dispatcher.dispatch(WCProductActionBuilder.newFetchedProductTagsAction(payload))
},
{ request: WPComGsonRequest<*> -> add(request) })
add(request)
}
/**
* Makes a POST request to `POST /wp-json/wc/v3/products/tags/batch` to add
* product tags for a site
*
* Dispatches a [WCProductAction.ADDED_PRODUCT_TAGS] action with the result
*
* @param [site] The site to fetch product shipping class list for
* @param [tags] The list of tag names that needed to be added to the site
*/
fun addProductTags(
site: SiteModel,
tags: List<String>
) {
val url = WOOCOMMERCE.products.tags.batch.pathV3
val responseType = object : TypeToken<BatchAddProductTagApiResponse>() {}.type
val params = mutableMapOf(
"create" to tags.map { mapOf("name" to it) }
)
val request = JetpackTunnelGsonRequest.buildPostRequest(url, site.siteId, params, responseType,
{ response: BatchAddProductTagApiResponse? ->
val addedTags = response?.addedTags?.map {
productTagApiResponseToProductTagModel(it, site)
}.orEmpty()
val payload = RemoteAddProductTagsResponsePayload(site, addedTags)
dispatcher.dispatch(WCProductActionBuilder.newAddedProductTagsAction(payload))
},
{ networkError ->
val productError = networkErrorToProductError(networkError)
val payload = RemoteAddProductTagsResponsePayload(productError, site)
dispatcher.dispatch(WCProductActionBuilder.newAddedProductTagsAction(payload))
})
add(request)
}
/**
* Makes a GET request to `/wp-json/wc/v3/products/[remoteProductId]` to fetch a single product
*
* Dispatches a WCProductAction.FETCHED_SINGLE_PRODUCT action with the result
*
* @param [remoteProductId] Unique server id of the product to fetch
*/
suspend fun fetchSingleProduct(site: SiteModel, remoteProductId: Long): RemoteProductPayload {
val url = WOOCOMMERCE.products.id(remoteProductId).pathV3
val response = jetpackTunnelGsonRequestBuilder.syncGetRequest(
this,
site,
url,
emptyMap(),
ProductApiResponse::class.java
)
return when (response) {
is JetpackSuccess -> {
response.data?.let {
val newModel = it.asProductModel().apply {
localSiteId = site.id
}
RemoteProductPayload(newModel, site)
} ?: RemoteProductPayload(
ProductError(GENERIC_ERROR, "Success response with empty data"),
WCProductModel().apply { this.remoteProductId = remoteProductId },
site
)
}
is JetpackError -> {
val productError = networkErrorToProductError(response.error)
RemoteProductPayload(
productError,
WCProductModel().apply { this.remoteProductId = remoteProductId },
site
)
}
}
}
/**
* Makes a GET request to `/wp-json/wc/v3/products/[remoteProductId]/variations/[remoteVariationId]` to fetch
* a single product variation
*
*
* @param [remoteProductId] Unique server id of the product to fetch
* @param [remoteVariationId] Unique server id of the variation to fetch
*/
suspend fun fetchSingleVariation(
site: SiteModel,
remoteProductId: Long,
remoteVariationId: Long
): RemoteVariationPayload {
val url = WOOCOMMERCE.products.id(remoteProductId).variations.variation(remoteVariationId).pathV3
val params = emptyMap<String, String>()
val response = jetpackTunnelGsonRequestBuilder.syncGetRequest(
this, site, url, params, ProductVariationApiResponse::class.java
)
return when (response) {
is JetpackSuccess -> {
val productData = response.data
if (productData != null) {
RemoteVariationPayload(
productData.asProductVariationModel().apply {
this.remoteProductId = remoteProductId
localSiteId = site.id
},
site
)
} else {
RemoteVariationPayload(
ProductError(GENERIC_ERROR, "Success response with empty data"),
WCProductVariationModel().apply {
this.remoteProductId = remoteProductId
this.remoteVariationId = remoteVariationId
},
site
)
}
}
is JetpackError -> {
RemoteVariationPayload(
networkErrorToProductError(response.error),
WCProductVariationModel().apply {
this.remoteProductId = remoteProductId
this.remoteVariationId = remoteVariationId
},
site
)
}
}
}
/**
* Makes a GET call to `/wc/v3/products` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* retrieving a list of products for the given WooCommerce [SiteModel].
*
* Dispatches a [WCProductAction.FETCHED_PRODUCTS] action with the resulting list of products.
*/
@Suppress("LongMethod")
fun fetchProducts(
site: SiteModel,
pageSize: Int = DEFAULT_PRODUCT_PAGE_SIZE,
offset: Int = 0,
sortType: ProductSorting = DEFAULT_PRODUCT_SORTING,
searchQuery: String? = null,
isSkuSearch: Boolean = false,
includedProductIds: List<Long>? = null,
filterOptions: Map<ProductFilterOption, String>? = null,
excludedProductIds: List<Long>? = null
) {
val url = WOOCOMMERCE.products.pathV3
val responseType = object : TypeToken<List<ProductApiResponse>>() {}.type
val params = buildProductParametersMap(
pageSize = pageSize,
sortType = sortType,
offset = offset,
searchQuery = searchQuery,
isSkuSearch = isSkuSearch,
includedProductIds = includedProductIds,
excludedProductIds = excludedProductIds,
filterOptions = filterOptions
)
val request = JetpackTunnelGsonRequest.buildGetRequest(url, site.siteId, params, responseType,
{ response: List<ProductApiResponse>? ->
val productModels = response?.map {
it.asProductModel().apply { localSiteId = site.id }
}.orEmpty()
val loadedMore = offset > 0
val canLoadMore = productModels.size == pageSize
if (searchQuery == null) {
val payload = RemoteProductListPayload(
site,
productModels,
offset,
loadedMore,
canLoadMore,
includedProductIds,
excludedProductIds
)
dispatcher.dispatch(WCProductActionBuilder.newFetchedProductsAction(payload))
} else {
val payload = RemoteSearchProductsPayload(
site = site,
searchQuery = searchQuery,
isSkuSearch = isSkuSearch,
products = productModels,
offset = offset,
loadedMore = loadedMore,
canLoadMore = canLoadMore
)
dispatcher.dispatch(WCProductActionBuilder.newSearchedProductsAction(payload))
}
},
{ networkError ->
val productError = networkErrorToProductError(networkError)
if (searchQuery == null) {
val payload = RemoteProductListPayload(productError, site)
dispatcher.dispatch(WCProductActionBuilder.newFetchedProductsAction(payload))
} else {
val payload = RemoteSearchProductsPayload(
error = productError,
site = site,
query = searchQuery,
skuSearch = isSkuSearch
)
dispatcher.dispatch(WCProductActionBuilder.newSearchedProductsAction(payload))
}
},
{ request: WPComGsonRequest<*> -> add(request) })
add(request)
}
fun searchProducts(
site: SiteModel,
searchQuery: String,
isSkuSearch: Boolean = false,
pageSize: Int = DEFAULT_PRODUCT_PAGE_SIZE,
offset: Int = 0,
sorting: ProductSorting = DEFAULT_PRODUCT_SORTING,
excludedProductIds: List<Long>? = null
) {
fetchProducts(
site = site,
pageSize = pageSize,
offset = offset,
sortType = sorting,
searchQuery = searchQuery,
isSkuSearch = isSkuSearch,
excludedProductIds = excludedProductIds)
}
/**
* Makes a GET call to `/wc/v3/products` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* retrieving a list of products for the given WooCommerce [SiteModel].
*
* but requiring this call to be suspended so the return call be synced within the coroutine job
*/
suspend fun fetchProductsWithSyncRequest(
site: SiteModel,
pageSize: Int = DEFAULT_PRODUCT_PAGE_SIZE,
offset: Int = 0,
sortType: ProductSorting = DEFAULT_PRODUCT_SORTING,
includedProductIds: List<Long>? = null,
excludedProductIds: List<Long>? = null,
searchQuery: String? = null,
isSkuSearch: Boolean = false,
filterOptions: Map<ProductFilterOption, String>? = null
): WooPayload<List<WCProductModel>> {
val params = buildProductParametersMap(
pageSize = pageSize,
sortType = sortType,
offset = offset,
searchQuery = searchQuery,
isSkuSearch = isSkuSearch,
includedProductIds = includedProductIds,
excludedProductIds = excludedProductIds,
filterOptions = filterOptions
)
return WOOCOMMERCE.products.pathV3.requestProductTo(site, params).handleResultFrom(site)
}
private suspend fun String.requestProductTo(
site: SiteModel,
params: Map<String, String>
) = jetpackTunnelGsonRequestBuilder.syncGetRequest(
this@ProductRestClient,
site,
this,
params,
Array<ProductApiResponse>::class.java
)
private fun JetpackResponse<Array<ProductApiResponse>>.handleResultFrom(site: SiteModel) =
when (this) {
is JetpackSuccess -> {
data
?.map {
it.asProductModel()
.apply { localSiteId = site.id }
}
.orEmpty()
.let { WooPayload(it.toList()) }
}
is JetpackError -> {
WooPayload(error.toWooError())
}
}
/**
* Makes a GET call to `/wc/v3/products/categories` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* retrieving a list of product categories for the given WooCommerce [SiteModel].
*
* but requiring this call to be suspended so the return call be synced within the coroutine job
*/
suspend fun fetchProductsCategoriesWithSyncRequest(
site: SiteModel,
includedCategoryIds: List<Long> = emptyList(),
excludedCategoryIds: List<Long> = emptyList(),
searchQuery: String? = null,
pageSize: Int = DEFAULT_PRODUCT_CATEGORY_PAGE_SIZE,
productCategorySorting: ProductCategorySorting = DEFAULT_CATEGORY_SORTING,
offset: Int = 0
): WooPayload<List<WCProductCategoryModel>> {
val sortOrder = when (productCategorySorting) {
NAME_DESC -> "desc"
else -> "asc"
}
val params = mutableMapOf(
"per_page" to pageSize.toString(),
"offset" to offset.toString(),
"order" to sortOrder,
"orderby" to "name"
).putIfNotEmpty("search" to searchQuery)
if (includedCategoryIds.isNotEmpty()) {
params["include"] = includedCategoryIds.map { it }.joinToString()
}
if (excludedCategoryIds.isNotEmpty()) {
params["exclude"] = excludedCategoryIds.map { it }.joinToString()
}
return WOOCOMMERCE.products.categories.pathV3
.requestCategoryTo(site, params)
.handleResultFrom(site)
}
@JvmName("handleResultFromProductCategoryApiResponse")
private fun JetpackResponse<Array<ProductCategoryApiResponse>>.handleResultFrom(site: SiteModel) =
when (this) {
is JetpackSuccess -> {
data
?.map {
it.asProductCategoryModel()
.apply { localSiteId = site.id }
}
.orEmpty()
.let { WooPayload(it.toList()) }
}
is JetpackError -> {
WooPayload(error.toWooError())
}
}
@JvmName("handleResultFromProductVariationApiResponse")
private fun JetpackResponse<Array<ProductVariationApiResponse>>.handleResultFrom(
site: SiteModel,
productId: Long
) =
when (this) {
is JetpackSuccess -> {
data
?.map {
it.asProductVariationModel()
.apply {
localSiteId = site.id
remoteProductId = productId
}
}
.orEmpty()
.let { WooPayload(it.toList()) }
}
is JetpackError -> {
WooPayload(error.toWooError())
}
}
private suspend fun String.requestCategoryTo(
site: SiteModel,
params: Map<String, String>
) = jetpackTunnelGsonRequestBuilder.syncGetRequest(
this@ProductRestClient,
site,
this,
params,
Array<ProductCategoryApiResponse>::class.java
)
private fun buildProductParametersMap(
pageSize: Int,
sortType: ProductSorting,
offset: Int,
searchQuery: String?,
isSkuSearch: Boolean,
includedProductIds: List<Long>? = null,
excludedProductIds: List<Long>? = null,
filterOptions: Map<ProductFilterOption, String>? = null
): MutableMap<String, String> {
val params = mutableMapOf(
"per_page" to pageSize.toString(),
"orderby" to sortType.asOrderByParameter(),
"order" to sortType.asSortOrderParameter(),
"offset" to offset.toString()
)
includedProductIds?.let { includedIds ->
params.putIfNotEmpty("include" to includedIds.map { it }.joinToString())
}
excludedProductIds?.let { excludedIds ->
params.putIfNotEmpty("exclude" to excludedIds.map { it }.joinToString())
}
filterOptions?.let { options ->
params.putAll(options.map { it.key.toString() to it.value })
}
if (searchQuery.isNullOrEmpty().not()) {
if (isSkuSearch) {
params["sku"] = searchQuery!! // full SKU match
params["search_sku"] = searchQuery // partial SKU match, added in core v6.6
} else {
params["search"] = searchQuery!!
}
}
return params
}
private fun buildVariationParametersMap(
pageSize: Int,
offset: Int,
searchQuery: String?,
ids: List<Long>,
excludedProductIds: List<Long>
) = mutableMapOf(
"per_page" to pageSize.toString(),
"orderby" to "date",
"order" to "asc",
"offset" to offset.toString()
).putIfNotEmpty("search" to searchQuery)
.putIfNotEmpty("include" to ids.map { it }.joinToString())
.putIfNotEmpty("exclude" to excludedProductIds.map { it }.joinToString())
private fun ProductSorting.asOrderByParameter() = when (this) {
TITLE_ASC, TITLE_DESC -> "title"
DATE_ASC, DATE_DESC -> "date"
}
private fun ProductSorting.asSortOrderParameter() = when (this) {
TITLE_ASC, DATE_ASC -> "asc"
TITLE_DESC, DATE_DESC -> "desc"
}
/**
* Makes a GET call to `/wc/v3/products` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* for a given [SiteModel] and [sku] to check if this [sku] already exists on the site
*
* Dispatches a [WCProductAction.FETCHED_PRODUCT_SKU_AVAILABILITY] action with the availability for the [sku].
*/
fun fetchProductSkuAvailability(
site: SiteModel,
sku: String
) {
val url = WOOCOMMERCE.products.pathV3
val responseType = object : TypeToken<List<ProductApiResponse>>() {}.type
val params = mutableMapOf("sku" to sku, "_fields" to "sku")
val request = JetpackTunnelGsonRequest.buildGetRequest(url, site.siteId, params, responseType,
{ response: List<ProductApiResponse>? ->
val available = response?.isEmpty() ?: false
val payload = RemoteProductSkuAvailabilityPayload(site, sku, available)
dispatcher.dispatch(WCProductActionBuilder.newFetchedProductSkuAvailabilityAction(payload))
},
{ networkError ->
val productError = networkErrorToProductError(networkError)
// If there is a network error of some sort that prevents us from knowing if a sku is available
// then just consider sku as available
val payload = RemoteProductSkuAvailabilityPayload(productError, site, sku, true)
dispatcher.dispatch(WCProductActionBuilder.newFetchedProductSkuAvailabilityAction(payload))
},
{ request: WPComGsonRequest<*> -> add(request) })
add(request)
}
/**
* Makes a WP.COM GET request to `/sites/$site/posts/$post_ID` to fetch just the password for a product
*/
fun fetchProductPassword(site: SiteModel, remoteProductId: Long) {
val url = WPCOMREST.sites.site(site.siteId).posts.post(remoteProductId).urlV1_1
val params = mutableMapOf("fields" to "password")
val request = WPComGsonRequest.buildGetRequest(url,
params,
PostWPComRestResponse::class.java,
{ response ->
val payload = RemoteProductPasswordPayload(remoteProductId, site, response.password ?: "")
dispatcher.dispatch(WCProductActionBuilder.newFetchedProductPasswordAction(payload))
}
) { networkError ->
val payload = RemoteProductPasswordPayload(remoteProductId, site, "")
payload.error = networkErrorToProductError(networkError)
dispatcher.dispatch(WCProductActionBuilder.newFetchedProductPasswordAction(payload))
}
add(request)
}
/**
* Makes a WP.COM POST request to `/sites/$site/posts/$post_ID` to update just the password for a product
*/
fun updateProductPassword(site: SiteModel, remoteProductId: Long, password: String) {
val url = WPCOMREST.sites.site(site.siteId).posts.post(remoteProductId).urlV1_2
val body = mapOf(
"password" to password
)
val request = WPComGsonRequest.buildPostRequest(url,
body,
PostWPComRestResponse::class.java,
{ response ->
val payload = RemoteUpdatedProductPasswordPayload(remoteProductId, site, response.password ?: "")
dispatcher.dispatch(WCProductActionBuilder.newUpdatedProductPasswordAction(payload))
}
) { networkError ->
val payload = RemoteUpdatedProductPasswordPayload(remoteProductId, site, "")
payload.error = networkErrorToProductError(networkError)
dispatcher.dispatch(WCProductActionBuilder.newUpdatedProductPasswordAction(payload))
}
request.addQueryParameter("context", "edit")
request.addQueryParameter("fields", "password")
add(request)
}
/**
* Makes a GET request to `POST /wp-json/wc/v3/products/[productId]/variations` to fetch
* variations for a product
*
* @param [productId] Unique server id of the product
*
* Variations by default are sorted by `menu_order` with sorting order = desc.
* i.e. `orderby` = `menu_order` and `order` = `desc`
*
* We do not pass `orderby` field in the request here because the API does not support `orderby`
* with `menu_order` as value. But we still need to pass `order` field to the API request in order to
* preserve the sorting order when fetching multiple pages of variations.
*
*/
suspend fun fetchProductVariations(
site: SiteModel,
productId: Long,
pageSize: Int = DEFAULT_PRODUCT_VARIATIONS_PAGE_SIZE,
offset: Int = 0
): RemoteProductVariationsPayload {
val url = WOOCOMMERCE.products.id(productId).variations.pathV3
val params = mutableMapOf(
"per_page" to pageSize.toString(),
"offset" to offset.toString(),
"order" to "asc",
"orderby" to "date"
)
val response = jetpackTunnelGsonRequestBuilder.syncGetRequest(
this, site, url, params, Array<ProductVariationApiResponse>::class.java
)
when (response) {
is JetpackSuccess -> {
val variationModels = response.data?.map {
it.asProductVariationModel().apply {
localSiteId = site.id
remoteProductId = productId
}
}.orEmpty()
val loadedMore = offset > 0
val canLoadMore = variationModels.size == pageSize
return RemoteProductVariationsPayload(
site, productId, variationModels, offset, loadedMore, canLoadMore
)
}
is JetpackError -> {
val productError = networkErrorToProductError(response.error)
return RemoteProductVariationsPayload(
productError,
site,
productId
)
}
}
}
/**
* Makes a GET call to `/wp-json/wc/v3/products/[productId]/variations` via the Jetpack tunnel
* (see [JetpackTunnelGsonRequest]), retrieving a list of variations for the given WooCommerce [SiteModel]
* and product.
*
* @param [productId] Unique server id of the product
*
* but requiring this call to be suspended so the return call be synced within the coroutine job
*
*/
suspend fun fetchProductVariationsWithSyncRequest(
site: SiteModel,
productId: Long,
pageSize: Int,
offset: Int,
includedVariationIds: List<Long> = emptyList(),
searchQuery: String? = null,
excludedVariationIds: List<Long> = emptyList()
): WooPayload<List<WCProductVariationModel>> {
val params = buildVariationParametersMap(
pageSize,
offset,
searchQuery,
includedVariationIds,
excludedVariationIds
)
return WOOCOMMERCE.products.id(productId).variations.pathV3
.requestProductVariationTo(site, params)
.handleResultFrom(site, productId)
}
private suspend fun String.requestProductVariationTo(
site: SiteModel,
params: Map<String, String>
) = jetpackTunnelGsonRequestBuilder.syncGetRequest(
this@ProductRestClient,
site,
this,
params,
Array<ProductVariationApiResponse>::class.java
)
/**
* Makes a PUT request to `/wp-json/wc/v3/products/remoteProductId` to update a product
*
* Dispatches a WCProductAction.UPDATED_PRODUCT action with the result
*
* @param [site] The site to fetch product reviews for
* @param [storedWCProductModel] the stored model to compare with the [updatedProductModel]
* @param [updatedProductModel] the product model that contains the update
*/
fun updateProduct(
site: SiteModel,
storedWCProductModel: WCProductModel?,
updatedProductModel: WCProductModel
) {
val remoteProductId = updatedProductModel.remoteProductId
val url = WOOCOMMERCE.products.id(remoteProductId).pathV3
val responseType = object : TypeToken<ProductApiResponse>() {}.type
val body = productModelToProductJsonBody(storedWCProductModel, updatedProductModel)
val request = JetpackTunnelGsonRequest.buildPutRequest(url, site.siteId, body, responseType,
{ response: ProductApiResponse? ->
response?.let {
val newModel = it.asProductModel().apply {
localSiteId = site.id
}
val payload = RemoteUpdateProductPayload(site, newModel)
dispatcher.dispatch(WCProductActionBuilder.newUpdatedProductAction(payload))
}
},
{ networkError ->
val productError = networkErrorToProductError(networkError)
val payload = RemoteUpdateProductPayload(
productError,
site,
WCProductModel().apply { this.remoteProductId = remoteProductId }
)
dispatcher.dispatch(WCProductActionBuilder.newUpdatedProductAction(payload))
})
add(request)
}
/**
* Makes a PUT request to `/wp-json/wc/v3/products/remoteProductId` to update a product
*
* @param [site] The site to fetch product reviews for
* @param [storedWCProductVariationModel] the stored model to compare with the [updatedProductVariationModel]
* @param [updatedProductVariationModel] the product model that contains the update
*/
suspend fun updateVariation(
site: SiteModel,
storedWCProductVariationModel: WCProductVariationModel?,
updatedProductVariationModel: WCProductVariationModel
): RemoteUpdateVariationPayload {
val remoteProductId = updatedProductVariationModel.remoteProductId
val remoteVariationId = updatedProductVariationModel.remoteVariationId
val url = WOOCOMMERCE.products.id(remoteProductId).variations.variation(remoteVariationId).pathV3
val body = variantModelToProductJsonBody(storedWCProductVariationModel, updatedProductVariationModel)
val response = jetpackTunnelGsonRequestBuilder.syncPutRequest(
this, site, url, body, ProductVariationApiResponse::class.java
)
return when (response) {
is JetpackSuccess -> {
response.data?.let {
val newModel = it.asProductVariationModel().apply {
this.remoteProductId = remoteProductId
localSiteId = site.id
}
RemoteUpdateVariationPayload(site, newModel)
} ?: RemoteUpdateVariationPayload(
ProductError(GENERIC_ERROR, "Success response with empty data"),
site,
WCProductVariationModel().apply {
this.remoteProductId = remoteProductId
this.remoteVariationId = remoteVariationId
}
)
}
is JetpackError -> {
val productError = networkErrorToProductError(response.error)
RemoteUpdateVariationPayload(
productError,
site,
WCProductVariationModel().apply {
this.remoteProductId = remoteProductId
this.remoteVariationId = remoteVariationId
}
)
}
}
}
/**
* Makes a POST request to `/wp-json/wc/v3/products/[WCProductModel.remoteProductId]/variations/batch`
* to batch update product variations.
*
* @param productId Id of the product.
* @param variationsIds Ids of variations that are going to be updated.
* @param modifiedProperties Map of the properties of variation that are going to be updated.
* Keys correspond to the names of variation properties. Values are the updated properties values.
*
* @return Instance of [BatchProductVariationsUpdateApiResponse].
*/
suspend fun batchUpdateVariations(
site: SiteModel,
productId: Long,
variationsIds: Collection<Long>,
modifiedProperties: Map<String, Any>
): WooPayload<BatchProductVariationsUpdateApiResponse> = WOOCOMMERCE.products.id(productId).variations.batch.pathV3
.let { url ->
val variationsUpdates: List<Map<String, Any>> = variationsIds.map { variationId ->
modifiedProperties.toMutableMap()
.also { properties -> properties["id"] = variationId }
}
jetpackTunnelGsonRequestBuilder.syncPostRequest(
this@ProductRestClient,
site,
url,
mapOf("update" to variationsUpdates),
BatchProductVariationsUpdateApiResponse::class.java
).handleResult()
}
/**
* Makes a POST request to `/wp-json/wc/v3/products` to create
* a empty variation to a given variable product
*
* @param [site] The site containing the product
* @param [productId] the ID of the variable product to create the empty variation
*/
suspend fun generateEmptyVariation(
site: SiteModel,
productId: Long,
attributesJson: String
) = WOOCOMMERCE.products.id(productId).variations.pathV3
.let { url ->
jetpackTunnelGsonRequestBuilder.syncPostRequest(
this@ProductRestClient,
site,
url,
mapOf("attributes" to JsonParser().parse(attributesJson).asJsonArray),
ProductVariationApiResponse::class.java
).handleResult()
}
/**
* Makes a DELETE request to `/wp-json/wc/v3/products/<id>` to delete a product
*
* @param [site] The site containing the product
* @param [productId] the ID of the variable product who holds the variation to be deleted
* @param [variationId] the ID of the variation model to delete
*
* Force delete option is not available as Variation doesn't support trashing
*/
suspend fun deleteVariation(
site: SiteModel,
productId: Long,
variationId: Long
) = WOOCOMMERCE.products.id(productId).variations.variation(variationId).pathV3
.let { url ->
jetpackTunnelGsonRequestBuilder.syncDeleteRequest(
this@ProductRestClient,
site,
url,
ProductVariationApiResponse::class.java
).handleResult()
}
/**
* Makes a PUT request to
* `/wp-json/wc/v3/products/[WCProductModel.remoteProductId]/variations/[WCProductVariationModel.remoteVariationId]`
* to replace a variation's attributes with [WCProductVariationModel.attributes]
*
* Returns a WooPayload with the Api response as result
*
* @param [site] The site to update the given variation attributes
* @param [attributesJson] Locally updated product variation to be sent
*/
suspend fun updateVariationAttributes(
site: SiteModel,
productId: Long,
variationId: Long,
attributesJson: String
) = WOOCOMMERCE.products.id(productId).variations.variation(variationId).pathV3
.let { url ->
jetpackTunnelGsonRequestBuilder.syncPutRequest(
this@ProductRestClient,
site,
url,
mapOf("attributes" to JsonParser().parse(attributesJson).asJsonArray),
ProductVariationApiResponse::class.java
).handleResult()
}
/**
* Makes a PUT request to `/wp-json/wc/v3/products/[WCProductModel.remoteProductId]`
* to replace a product's attributes with [WCProductModel.attributes]
*
* Returns a WooPayload with the Api response as result
*
* @param [site] The site to update the given product attributes
*/
suspend fun updateProductAttributes(
site: SiteModel,
productId: Long,
attributesJson: String
) = WOOCOMMERCE.products.id(productId).pathV3
.let { url ->
jetpackTunnelGsonRequestBuilder.syncPutRequest(
this,
site,
url,
mapOf("attributes" to JsonParser().parse(attributesJson).asJsonArray),
ProductApiResponse::class.java
).handleResult()
}
/**
* Makes a PUT request to `/wp-json/wc/v3/products/[remoteProductId]` to replace a product's images
* with the passed media list
*
* Dispatches a WCProductAction.UPDATED_PRODUCT_IMAGES action with the result
*
* @param [site] The site to fetch product reviews for
* @param [remoteProductId] Unique server id of the product to update
* @param [imageList] list of product images to assign to the product
*/
fun updateProductImages(site: SiteModel, remoteProductId: Long, imageList: List<WCProductImageModel>) {
val url = WOOCOMMERCE.products.id(remoteProductId).pathV3
val responseType = object : TypeToken<ProductApiResponse>() {}.type
// build json list of images
val jsonBody = JsonArray()
for (image in imageList) {
jsonBody.add(image.toJson())
}
val body = HashMap<String, Any>()
body["id"] = remoteProductId
body["images"] = jsonBody
val request = JetpackTunnelGsonRequest.buildPutRequest(url, site.siteId, body, responseType,
{ response: ProductApiResponse? ->
response?.let {
val newModel = it.asProductModel().apply {
localSiteId = site.id
}
val payload = RemoteUpdateProductImagesPayload(site, newModel)
dispatcher.dispatch(WCProductActionBuilder.newUpdatedProductImagesAction(payload))
}
},
{ networkError ->
val productError = networkErrorToProductError(networkError)
val payload = RemoteUpdateProductImagesPayload(
productError,
site,
WCProductModel().apply { this.remoteProductId = remoteProductId }
)
dispatcher.dispatch(WCProductActionBuilder.newUpdatedProductImagesAction(payload))
})
add(request)
}
/**
* Makes a GET call to `/wc/v3/products/categories` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* retrieving a list of product categories for a given WooCommerce [SiteModel].
*
* The number of categories to fetch is defined in [WCProductStore.DEFAULT_PRODUCT_CATEGORY_PAGE_SIZE],
* and retrieving older categories is done by passing an [offset].
*
* Dispatches a [WCProductAction.FETCHED_PRODUCT_CATEGORIES]
*
* @param [site] The site to fetch product categories for
* @param [offset] The offset to use for the fetch
* @param [productCategorySorting] Optional. The sorting type of the categories
*/
fun fetchProductCategories(
site: SiteModel,
pageSize: Int = DEFAULT_PRODUCT_CATEGORY_PAGE_SIZE,
offset: Int = 0,
productCategorySorting: ProductCategorySorting? = DEFAULT_CATEGORY_SORTING
) {
val sortOrder = when (productCategorySorting) {
NAME_DESC -> "desc"
else -> "asc"
}
val url = WOOCOMMERCE.products.categories.pathV3
val responseType = object : TypeToken<List<ProductCategoryApiResponse>>() {}.type
val params = mutableMapOf(
"per_page" to pageSize.toString(),
"offset" to offset.toString(),
"order" to sortOrder,
"orderby" to "name"
)
val request = JetpackTunnelGsonRequest.buildGetRequest(url, site.siteId, params, responseType,
{ response: List<ProductCategoryApiResponse>? ->
response?.let {
val categories = it.map { category ->
category.asProductCategoryModel().apply { localSiteId = site.id }
}
val canLoadMore = categories.size == pageSize
val loadedMore = offset > 0
val payload = RemoteProductCategoriesPayload(
site, categories, offset, loadedMore, canLoadMore
)
dispatcher.dispatch(WCProductActionBuilder.newFetchedProductCategoriesAction(payload))
}
},
{ networkError ->
val productCategoryError = networkErrorToProductError(networkError)
val payload = RemoteProductCategoriesPayload(productCategoryError, site)
dispatcher.dispatch(WCProductActionBuilder.newFetchedProductCategoriesAction(payload))
},
{ request: WPComGsonRequest<*> -> add(request) })
add(request)
}
/**
* Posts a new Add Category record to the API for a category.
*
* Makes a POST call `/wc/v3/products/categories/id` to save a Category record via the Jetpack tunnel.
* Returns a [WCProductCategoryModel] on successful response.
*
* Dispatches [WCProductAction.ADDED_PRODUCT_CATEGORY] action with the results.
*/
fun addProductCategory(
site: SiteModel,
category: WCProductCategoryModel
) {
val url = WOOCOMMERCE.products.categories.pathV3
val responseType = object : TypeToken<ProductCategoryApiResponse>() {}.type
val params = mutableMapOf(
"name" to category.name,
"parent" to category.parent.toString()
)
val request = JetpackTunnelGsonRequest.buildPostRequest(url, site.siteId, params, responseType,
{ response: ProductCategoryApiResponse? ->
val categoryResponse = response?.let {
it.asProductCategoryModel().apply {
localSiteId = site.id
}
}
val payload = RemoteAddProductCategoryResponsePayload(site, categoryResponse)
dispatcher.dispatch(WCProductActionBuilder.newAddedProductCategoryAction(payload))
},
{ networkError ->
val productCategorySaveError = networkErrorToProductError(networkError)
val payload = RemoteAddProductCategoryResponsePayload(productCategorySaveError, site, category)
dispatcher.dispatch(WCProductActionBuilder.newAddedProductCategoryAction(payload))
})
add(request)
}
/**
* Makes a GET call to `/wc/v3/products/reviews` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* retrieving a list of product reviews for a given WooCommerce [SiteModel].
*
* The number of reviews to fetch is defined in [WCProductStore.NUM_REVIEWS_PER_FETCH], and retrieving older
* reviews is done by passing an [offset].
*
* @param [site] The site to fetch product reviews for
* @param [offset] The offset to use for the fetch
* @param [reviewIds] Optional. A list of remote product review ID's to fetch
* @param [productIds] Optional. A list of remote product ID's to fetch product reviews for
* @param [filterByStatus] Optional. A list of product review statuses to fetch
*/
suspend fun fetchProductReviews(
site: SiteModel,
offset: Int,
reviewIds: List<Long>? = null,
productIds: List<Long>? = null,
filterByStatus: List<String>? = null
): FetchProductReviewsResponsePayload {
val statusFilter = filterByStatus?.joinToString { it } ?: "all"
val url = WOOCOMMERCE.products.reviews.pathV3
val params = mutableMapOf(
"per_page" to WCProductStore.NUM_REVIEWS_PER_FETCH.toString(),
"offset" to offset.toString(),
"status" to statusFilter
)
reviewIds?.let { ids ->
params.put("include", ids.map { it }.joinToString())
}
productIds?.let { ids ->
params.put("product", ids.map { it }.joinToString())
}
val response = jetpackTunnelGsonRequestBuilder.syncGetRequest(
this,
site,
url,
params,
Array<ProductReviewApiResponse>::class.java
)
return when (response) {
is JetpackSuccess -> {
val productData = response.data
if (productData != null) {
val reviews = productData.map { review ->
productReviewResponseToProductReviewModel(review).apply { localSiteId = site.id }
}
FetchProductReviewsResponsePayload(
site,
reviews,
productIds,
filterByStatus,
offset > 0,
reviews.size == WCProductStore.NUM_REVIEWS_PER_FETCH
)
} else {
FetchProductReviewsResponsePayload(
ProductError(
GENERIC_ERROR,
"Success response with empty data"
),
site
)
}
}
is JetpackError -> {
FetchProductReviewsResponsePayload(
networkErrorToProductError(response.error),
site
)
}
}
}
/**
* Makes a GET call to `/wc/v3/products/reviews/<id>` via the Jetpack tunnel (see [JetpackTunnelGsonRequestBuilder])
* retrieving a product review by it's remote ID for a given WooCommerce [SiteModel].
*
*
* @param [site] The site to fetch product reviews for
* @param [remoteReviewId] The remote id of the review to fetch
*/
suspend fun fetchProductReviewById(site: SiteModel, remoteReviewId: Long): RemoteProductReviewPayload {
val url = WOOCOMMERCE.products.reviews.id(remoteReviewId).pathV3
val response = jetpackTunnelGsonRequestBuilder.syncGetRequest(
this,
site,
url,
emptyMap(),
ProductReviewApiResponse::class.java
)
return when (response) {
is JetpackSuccess -> {
response.data?.let {
val review = productReviewResponseToProductReviewModel(it).apply {
localSiteId = site.id
}
RemoteProductReviewPayload(site, review)
} ?: RemoteProductReviewPayload(
error = ProductError(GENERIC_ERROR, "Success response with empty data"),
site = site
)
}
is JetpackError -> {
val productReviewError = networkErrorToProductError(response.error)
RemoteProductReviewPayload(error = productReviewError, site = site)
}
}
}
/**
* Makes a PUT call to `/wc/v3/products/reviews/<id>` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* updating the status for the given product review to [newStatus].
*
*
* @param [site] The site to fetch product reviews for
* @param [remoteReviewId] The remote ID of the product review to be updated
* @param [newStatus] The new status to update the product review to
*
* @return [WooPayload] with the updated [WCProductReviewModel]
*/
suspend fun updateProductReviewStatus(
site: SiteModel,
remoteReviewId: Long,
newStatus: String
): WooPayload<WCProductReviewModel> {
val url = WOOCOMMERCE.products.reviews.id(remoteReviewId).pathV3
val params = mapOf("status" to newStatus)
val response = jetpackTunnelGsonRequestBuilder.syncPutRequest(
restClient = this,
site = site,
url = url,
body = params,
clazz = ProductReviewApiResponse::class.java
)
return when (response) {
is JetpackSuccess -> {
response.data?.let {
val review = productReviewResponseToProductReviewModel(it).apply {
localSiteId = site.id
}
WooPayload(review)
} ?: WooPayload(
error = WooError(
type = WooErrorType.GENERIC_ERROR,
original = GenericErrorType.UNKNOWN,
message = "Success response with empty data"
)
)
}
is JetpackError -> WooPayload(error = response.error.toWooError())
}
}
/**
* Makes a POST request to `/wp-json/wc/v3/products` to add a product
*
* Dispatches a [WCProductAction.ADDED_PRODUCT] action with the result
*
* @param [site] The site to fetch product reviews for
* @param [productModel] the new product model
*/
fun addProduct(
site: SiteModel,
productModel: WCProductModel
) {
val url = WOOCOMMERCE.products.pathV3
val responseType = object : TypeToken<ProductApiResponse>() {}.type
val params = productModelToProductJsonBody(null, productModel)
val request = JetpackTunnelGsonRequest.buildPostRequest(
wpApiEndpoint = url,
siteId = site.siteId,
body = params,
type = responseType,
listener = { response: ProductApiResponse? ->
// success
response?.let { product ->
val newModel = product.asProductModel().apply {
id = product.id?.toInt() ?: 0
localSiteId = site.id
}
val payload = RemoteAddProductPayload(site, newModel)
dispatcher.dispatch(WCProductActionBuilder.newAddedProductAction(payload))
}
},
errorListener = { networkError ->
// error
val productError = networkErrorToProductError(networkError)
val payload = RemoteAddProductPayload(
productError,
site,
WCProductModel()
)
dispatcher.dispatch(WCProductActionBuilder.newAddedProductAction(payload))
}
)
add(request)
}
/**
* Makes a DELETE request to `/wp-json/wc/v3/products/<id>` to delete a product
*
* Dispatches a [WCProductAction.DELETED_PRODUCT] action with the result
*
* @param [site] The site containing the product
* @param [remoteProductId] the ID of the product model to delete
* @param [forceDelete] whether to permanently delete the product (will be sent to trash if false)
*/
fun deleteProduct(
site: SiteModel,
remoteProductId: Long,
forceDelete: Boolean = false
) {
val url = WOOCOMMERCE.products.id(remoteProductId).pathV3
val responseType = object : TypeToken<ProductApiResponse>() {}.type
val params = mapOf("force" to forceDelete.toString())
val request = JetpackTunnelGsonRequest.buildDeleteRequest(url, site.siteId, params, responseType,
{ response: ProductApiResponse? ->
response?.let {
val payload = RemoteDeleteProductPayload(site, remoteProductId)
dispatcher.dispatch(WCProductActionBuilder.newDeletedProductAction(payload))
}
},
{ networkError ->
val productError = networkErrorToProductError(networkError)
val payload = RemoteDeleteProductPayload(
productError,
site,
remoteProductId
)
dispatcher.dispatch(WCProductActionBuilder.newDeletedProductAction(payload))
}
)
add(request)
}
/**
* Build json body of product items to be updated to the backend.
*
* This method checks if there is a cached version of the product stored locally.
* If not, it generates a new product model for the same product ID, with default fields
* and verifies that the [updatedProductModel] has fields that are different from the default
* fields of [productModel]. This is to ensure that we do not update product fields that do not contain any changes
*/
@Suppress("LongMethod", "ComplexMethod", "SwallowedException", "TooGenericExceptionCaught")
private fun productModelToProductJsonBody(
productModel: WCProductModel?,
updatedProductModel: WCProductModel
): HashMap<String, Any> {
val body = HashMap<String, Any>()
val storedWCProductModel = productModel ?: WCProductModel().apply {
remoteProductId = updatedProductModel.remoteProductId
}
if (storedWCProductModel.description != updatedProductModel.description) {
body["description"] = updatedProductModel.description
}
if (storedWCProductModel.name != updatedProductModel.name) {
body["name"] = updatedProductModel.name
}
if (storedWCProductModel.type != updatedProductModel.type) {
body["type"] = updatedProductModel.type
}
if (storedWCProductModel.sku != updatedProductModel.sku) {
body["sku"] = updatedProductModel.sku
}
if (storedWCProductModel.status != updatedProductModel.status) {
body["status"] = updatedProductModel.status
}
if (storedWCProductModel.catalogVisibility != updatedProductModel.catalogVisibility) {
body["catalog_visibility"] = updatedProductModel.catalogVisibility
}
if (storedWCProductModel.slug != updatedProductModel.slug) {
body["slug"] = updatedProductModel.slug
}
if (storedWCProductModel.featured != updatedProductModel.featured) {
body["featured"] = updatedProductModel.featured
}
if (storedWCProductModel.manageStock != updatedProductModel.manageStock) {
body["manage_stock"] = updatedProductModel.manageStock
}
if (storedWCProductModel.externalUrl != updatedProductModel.externalUrl) {
body["external_url"] = updatedProductModel.externalUrl
}
if (storedWCProductModel.buttonText != updatedProductModel.buttonText) {
body["button_text"] = updatedProductModel.buttonText
}
// only allowed to change the following params if manageStock is enabled
if (updatedProductModel.manageStock) {
if (storedWCProductModel.stockQuantity != updatedProductModel.stockQuantity) {
// Conversion/rounding down because core API only accepts Int value for stock quantity.
// On the app side, make sure it only allows whole decimal quantity when updating, so that
// there's no undesirable conversion effect.
body["stock_quantity"] = updatedProductModel.stockQuantity.toInt()
}
if (storedWCProductModel.backorders != updatedProductModel.backorders) {
body["backorders"] = updatedProductModel.backorders
}
}
if (storedWCProductModel.stockStatus != updatedProductModel.stockStatus) {
body["stock_status"] = updatedProductModel.stockStatus
}
if (storedWCProductModel.soldIndividually != updatedProductModel.soldIndividually) {
body["sold_individually"] = updatedProductModel.soldIndividually
}
if (storedWCProductModel.regularPrice != updatedProductModel.regularPrice) {
body["regular_price"] = updatedProductModel.regularPrice
}
if (storedWCProductModel.salePrice != updatedProductModel.salePrice) {
body["sale_price"] = updatedProductModel.salePrice
}
if (storedWCProductModel.dateOnSaleFromGmt != updatedProductModel.dateOnSaleFromGmt) {
body["date_on_sale_from_gmt"] = updatedProductModel.dateOnSaleFromGmt
}
if (storedWCProductModel.dateOnSaleToGmt != updatedProductModel.dateOnSaleToGmt) {
body["date_on_sale_to_gmt"] = updatedProductModel.dateOnSaleToGmt
}
if (storedWCProductModel.taxStatus != updatedProductModel.taxStatus) {
body["tax_status"] = updatedProductModel.taxStatus
}
if (storedWCProductModel.taxClass != updatedProductModel.taxClass) {
body["tax_class"] = updatedProductModel.taxClass
}
if (storedWCProductModel.weight != updatedProductModel.weight) {
body["weight"] = updatedProductModel.weight
}
val dimensionsBody = mutableMapOf<String, String>()
if (storedWCProductModel.height != updatedProductModel.height) {
dimensionsBody["height"] = updatedProductModel.height
}
if (storedWCProductModel.width != updatedProductModel.width) {
dimensionsBody["width"] = updatedProductModel.width
}
if (storedWCProductModel.length != updatedProductModel.length) {
dimensionsBody["length"] = updatedProductModel.length
}
if (dimensionsBody.isNotEmpty()) {
body["dimensions"] = dimensionsBody
}
if (storedWCProductModel.shippingClass != updatedProductModel.shippingClass) {
body["shipping_class"] = updatedProductModel.shippingClass
}
if (storedWCProductModel.shortDescription != updatedProductModel.shortDescription) {
body["short_description"] = updatedProductModel.shortDescription
}
if (!storedWCProductModel.hasSameImages(updatedProductModel)) {
val updatedImages = updatedProductModel.getImageListOrEmpty()
body["images"] = JsonArray().also {
for (image in updatedImages) {
it.add(image.toJson())
}
}
}
if (storedWCProductModel.reviewsAllowed != updatedProductModel.reviewsAllowed) {
body["reviews_allowed"] = updatedProductModel.reviewsAllowed
}
if (storedWCProductModel.virtual != updatedProductModel.virtual) {
body["virtual"] = updatedProductModel.virtual
}
if (storedWCProductModel.purchaseNote != updatedProductModel.purchaseNote) {
body["purchase_note"] = updatedProductModel.purchaseNote
}
if (storedWCProductModel.menuOrder != updatedProductModel.menuOrder) {
body["menu_order"] = updatedProductModel.menuOrder
}
if (!storedWCProductModel.hasSameCategories(updatedProductModel)) {
val updatedCategories = updatedProductModel.getCategoryList()
body["categories"] = JsonArray().also {
for (category in updatedCategories) {
it.add(category.toJson())
}
}
}
if (!storedWCProductModel.hasSameTags(updatedProductModel)) {
val updatedTags = updatedProductModel.getTagList()
body["tags"] = JsonArray().also {
for (tag in updatedTags) {
it.add(tag.toJson())
}
}
}
if (storedWCProductModel.groupedProductIds != updatedProductModel.groupedProductIds) {
body["grouped_products"] = updatedProductModel.getGroupedProductIdList()
}
if (storedWCProductModel.crossSellIds != updatedProductModel.crossSellIds) {
body["cross_sell_ids"] = updatedProductModel.getCrossSellProductIdList()
}
if (storedWCProductModel.upsellIds != updatedProductModel.upsellIds) {
body["upsell_ids"] = updatedProductModel.getUpsellProductIdList()
}
if (storedWCProductModel.downloadable != updatedProductModel.downloadable) {
body["downloadable"] = updatedProductModel.downloadable
}
if (storedWCProductModel.downloadLimit != updatedProductModel.downloadLimit) {
body["download_limit"] = updatedProductModel.downloadLimit
}
if (storedWCProductModel.downloadExpiry != updatedProductModel.downloadExpiry) {
body["download_expiry"] = updatedProductModel.downloadExpiry
}
if (!storedWCProductModel.hasSameDownloadableFiles(updatedProductModel)) {
val updatedFiles = updatedProductModel.getDownloadableFiles()
body["downloads"] = JsonArray().apply {
updatedFiles.forEach { file ->
add(file.toJson())
}
}
}
if (!storedWCProductModel.hasSameAttributes(updatedProductModel)) {
JsonParser().apply {
body["attributes"] = try {
parse(updatedProductModel.attributes).asJsonArray
} catch (ex: Exception) {
JsonArray()
}
}
}
return body
}
/**
* Build json body of product items to be updated to the backend.
*
* This method checks if there is a cached version of the product stored locally.
* If not, it generates a new product model for the same product ID, with default fields
* and verifies that the [updatedVariationModel] has fields that are different from the default
* fields of [variationModel]. This is to ensure that we do not update product fields that do not contain any
* changes.
*/
@Suppress("ForbiddenComment", "LongMethod", "ComplexMethod", "SwallowedException", "TooGenericExceptionCaught")
private fun variantModelToProductJsonBody(
variationModel: WCProductVariationModel?,
updatedVariationModel: WCProductVariationModel
): HashMap<String, Any> {
val body = HashMap<String, Any>()
val storedVariationModel = variationModel ?: WCProductVariationModel().apply {
remoteProductId = updatedVariationModel.remoteProductId
remoteVariationId = updatedVariationModel.remoteVariationId
}
if (storedVariationModel.description != updatedVariationModel.description) {
body["description"] = updatedVariationModel.description
}
if (storedVariationModel.sku != updatedVariationModel.sku) {
body["sku"] = updatedVariationModel.sku
}
if (storedVariationModel.status != updatedVariationModel.status) {
body["status"] = updatedVariationModel.status
}
if (storedVariationModel.manageStock != updatedVariationModel.manageStock) {
body["manage_stock"] = updatedVariationModel.manageStock
}
// only allowed to change the following params if manageStock is enabled
if (updatedVariationModel.manageStock) {
if (storedVariationModel.stockQuantity != updatedVariationModel.stockQuantity) {
// Conversion/rounding down because core API only accepts Int value for stock quantity.
// On the app side, make sure it only allows whole decimal quantity when updating, so that
// there's no undesirable conversion effect.
body["stock_quantity"] = updatedVariationModel.stockQuantity.toInt()
}
if (storedVariationModel.backorders != updatedVariationModel.backorders) {
body["backorders"] = updatedVariationModel.backorders
}
}
if (storedVariationModel.stockStatus != updatedVariationModel.stockStatus) {
body["stock_status"] = updatedVariationModel.stockStatus
}
if (storedVariationModel.regularPrice != updatedVariationModel.regularPrice) {
body["regular_price"] = updatedVariationModel.regularPrice
}
if (storedVariationModel.salePrice != updatedVariationModel.salePrice) {
body["sale_price"] = updatedVariationModel.salePrice
}
if (storedVariationModel.dateOnSaleFromGmt != updatedVariationModel.dateOnSaleFromGmt) {
body["date_on_sale_from_gmt"] = updatedVariationModel.dateOnSaleFromGmt
}
if (storedVariationModel.dateOnSaleToGmt != updatedVariationModel.dateOnSaleToGmt) {
body["date_on_sale_to_gmt"] = updatedVariationModel.dateOnSaleToGmt
}
if (storedVariationModel.taxStatus != updatedVariationModel.taxStatus) {
body["tax_status"] = updatedVariationModel.taxStatus
}
if (storedVariationModel.taxClass != updatedVariationModel.taxClass) {
body["tax_class"] = updatedVariationModel.taxClass
}
if (storedVariationModel.weight != updatedVariationModel.weight) {
body["weight"] = updatedVariationModel.weight
}
val dimensionsBody = mutableMapOf<String, String>()
if (storedVariationModel.height != updatedVariationModel.height) {
dimensionsBody["height"] = updatedVariationModel.height
}
if (storedVariationModel.width != updatedVariationModel.width) {
dimensionsBody["width"] = updatedVariationModel.width
}
if (storedVariationModel.length != updatedVariationModel.length) {
dimensionsBody["length"] = updatedVariationModel.length
}
if (dimensionsBody.isNotEmpty()) {
body["dimensions"] = dimensionsBody
}
if (storedVariationModel.shippingClass != updatedVariationModel.shippingClass) {
body["shipping_class"] = updatedVariationModel.shippingClass
}
// TODO: Once removal is supported, we can remove the extra isNotBlank() condition
if (storedVariationModel.image != updatedVariationModel.image && updatedVariationModel.image.isNotBlank()) {
body["image"] = updatedVariationModel.getImageModel()?.toJson() ?: ""
}
if (storedVariationModel.menuOrder != updatedVariationModel.menuOrder) {
body["menu_order"] = updatedVariationModel.menuOrder
}
if (storedVariationModel.attributes != updatedVariationModel.attributes) {
JsonParser().apply {
body["attributes"] = try {
parse(updatedVariationModel.attributes).asJsonArray
} catch (ex: Exception) {
JsonArray()
}
}
}
return body
}
private fun productTagApiResponseToProductTagModel(
response: ProductTagApiResponse,
site: SiteModel
): WCProductTagModel {
return WCProductTagModel().apply {
remoteTagId = response.id
localSiteId = site.id
name = response.name ?: ""
slug = response.slug ?: ""
description = response.description ?: ""
count = response.count
}
}
private fun productShippingClassResponseToProductShippingClassModel(
response: ProductShippingClassApiResponse,
site: SiteModel
): WCProductShippingClassModel {
return WCProductShippingClassModel().apply {
remoteShippingClassId = response.id
localSiteId = site.id
name = response.name ?: ""
slug = response.slug ?: ""
description = response.description ?: ""
}
}
private fun productReviewResponseToProductReviewModel(response: ProductReviewApiResponse): WCProductReviewModel {
return WCProductReviewModel().apply {
remoteProductReviewId = response.id
remoteProductId = response.product_id
dateCreated = response.date_created_gmt?.let { "${it}Z" } ?: ""
status = response.status ?: ""
reviewerName = response.reviewer ?: ""
reviewerEmail = response.reviewer_email ?: ""
review = response.review ?: ""
rating = response.rating
verified = response.verified
reviewerAvatarsJson = response.reviewer_avatar_urls?.toString() ?: ""
}
}
private fun networkErrorToProductError(wpComError: WPComGsonNetworkError): ProductError {
val productErrorType = when (wpComError.apiError) {
"woocommerce_rest_product_invalid_id" -> ProductErrorType.INVALID_PRODUCT_ID
"rest_invalid_param" -> ProductErrorType.INVALID_PARAM
"woocommerce_rest_review_invalid_id" -> ProductErrorType.INVALID_REVIEW_ID
"woocommerce_product_invalid_image_id" -> ProductErrorType.INVALID_IMAGE_ID
"product_invalid_sku" -> ProductErrorType.DUPLICATE_SKU
"term_exists" -> ProductErrorType.TERM_EXISTS
"woocommerce_variation_invalid_image_id" -> ProductErrorType.INVALID_VARIATION_IMAGE_ID
else -> ProductErrorType.fromString(wpComError.apiError)
}
return ProductError(productErrorType, wpComError.message)
}
}
|
gpl-2.0
|
f24784b73e89f8dc10af6696bd1af29a
| 44.000561 | 130 | 0.613056 | 5.865486 | false | false | false | false |
WijayaPrinting/wp-javafx
|
openpss-client-javafx/src/com/hendraanggrian/openpss/EitherStringFx.kt
|
1
|
445
|
package com.hendraanggrian.openpss
import ktfx.dialogs.errorAlert
inline fun <V> EitherString<V>.foldError(
onError: (String) -> Unit = { errorAlert(content = it) },
onSuccess: (V) -> Unit
): Unit = fold(onError, onSuccess)
inline fun <V> EitherString<V>.foldErrorAlert(
crossinline onErrorPresent: () -> Unit,
onSuccess: (V) -> Unit
): Unit = foldError({ errorAlert(content = it).ifPresent { onErrorPresent() } }, onSuccess)
|
apache-2.0
|
e27e8bd7f3acc2587bb2727c6d4d84b9
| 33.230769 | 91 | 0.692135 | 3.617886 | false | false | false | false |
raatiniemi/worker
|
app/src/androidTest/java/me/raatiniemi/worker/data/projects/TimeIntervalEntityBuilder.kt
|
1
|
1491
|
/*
* Copyright (C) 2018 Tobias Raatiniemi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.raatiniemi.worker.data.projects
internal data class TimeIntervalEntityBuilder(
var id: Long = 0,
var projectId: Long = 1,
var startInMilliseconds: Long = 1,
var stopInMilliseconds: Long = 2,
var registered: Boolean = false
)
internal fun timeIntervalEntity(
configure: (TimeIntervalEntityBuilder.() -> Unit)? = null
): TimeIntervalEntity {
val builder = TimeIntervalEntityBuilder()
configure?.let { builder.it() }
return TimeIntervalEntity(
id = builder.id,
projectId = builder.projectId,
startInMilliseconds = builder.startInMilliseconds,
stopInMilliseconds = builder.stopInMilliseconds,
registered = if (builder.registered) {
1L
} else {
0L
}
)
}
|
gpl-2.0
|
a325d805c64a1e6a2efaf3dee1df2d08
| 32.886364 | 72 | 0.667337 | 4.794212 | false | false | false | false |
Geobert/radis
|
app/src/main/kotlin/fr/geobert/radis/db/DbContentProvider.kt
|
1
|
11273
|
package fr.geobert.radis.db
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.content.UriMatcher
import android.database.Cursor
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri
import android.util.Log
import java.util.*
class DbContentProvider : ContentProvider() {
override fun onCreate(): Boolean {
mDbHelper = DbHelper.getInstance(context)
return false
}
fun deleteDatabase(ctx: Context): Boolean {
Log.d(TAG, "deleteDatabase from ContentProvider")
DbHelper.delete()
val res = ctx.deleteDatabase(DbHelper.DATABASE_NAME)
mDbHelper = DbHelper.getInstance(ctx)
return res
}
private fun switchToTable(uri: Uri): String {
val uriType = sURIMatcher.match(uri)
// Log.d(TAG, "begin switch to table : " + uri + "/#" + uriType);
val table: String
when (uriType) {
ACCOUNT, ACCOUNT_ID -> table = AccountTable.DATABASE_ACCOUNT_TABLE
OPERATION, OPERATION_ID -> table = OperationTable.DATABASE_OPERATIONS_TABLE
OPERATION_JOINED, OPERATION_JOINED_ID -> table = OperationTable.DATABASE_OP_TABLE_JOINTURE
SCHEDULED_OP, SCHEDULED_OP_ID -> table = ScheduledOperationTable.DATABASE_SCHEDULED_TABLE
SCHEDULED_JOINED_OP, SCHEDULED_JOINED_OP_ID -> table = ScheduledOperationTable.DATABASE_SCHEDULED_TABLE_JOINTURE
THIRD_PARTY, THIRD_PARTY_ID -> table = InfoTables.DATABASE_THIRD_PARTIES_TABLE
MODES, MODES_ID -> table = InfoTables.DATABASE_MODES_TABLE
TAGS, TAGS_ID -> table = InfoTables.DATABASE_TAGS_TABLE
PREFS, PREFS_ACCOUNT -> table = PreferenceTable.DATABASE_PREFS_TABLE
STATS, STATS_ID -> table = StatisticTable.STAT_TABLE
else -> throw IllegalArgumentException("Unknown URI: " + uri)
}
return table
}
@Synchronized
override fun query(uri: Uri, projection: Array<String>,
selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor {
val queryBuilder = SQLiteQueryBuilder()
val uriType = sURIMatcher.match(uri)
when (uriType) {
ACCOUNT_ID, OPERATION_ID, SCHEDULED_OP_ID, THIRD_PARTY_ID, MODES_ID, TAGS_ID, STATS_ID -> queryBuilder.appendWhere("_id=" + uri.lastPathSegment)
OPERATION_JOINED_ID -> queryBuilder.appendWhere("ops._id=" + uri.lastPathSegment)
SCHEDULED_JOINED_OP_ID -> queryBuilder.appendWhere("sch._id=" + uri.lastPathSegment)
PREFS_ACCOUNT -> queryBuilder.appendWhere(PreferenceTable.KEY_PREFS_ACCOUNT + "=" + uri.lastPathSegment)
else -> {
}
}
val table = switchToTable(uri)
queryBuilder.tables = table
val db = mDbHelper!!.writableDatabase
val cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder)
cursor.setNotificationUri(context.contentResolver, uri)
return cursor
}
@Synchronized override fun delete(uri: Uri, selection: String?, a: Array<String>?): Int {
var selectionArgs = a
val uriType = sURIMatcher.match(uri)
val db = mDbHelper!!.writableDatabase
val rowsDeleted: Int
val table = switchToTable(uri)
var id: String? = null
when (uriType) {
ACCOUNT_ID, OPERATION_ID, OPERATION_JOINED_ID, SCHEDULED_OP_ID, SCHEDULED_JOINED_OP_ID, THIRD_PARTY_ID,
MODES_ID, TAGS_ID, STATS_ID -> // no need for PREFS_ACCOUNT, trigger takes care of it
id = uri.lastPathSegment
else -> {
}
}
if (id != null) {
if (selection == null || selection.trim().length == 0) {
rowsDeleted = db.delete(table, "_id=?", arrayOf(id))
} else {
if (selectionArgs != null) {
val args = ArrayList<String>(selectionArgs.size + 1)
args.add(id)
Collections.addAll(args, *selectionArgs)
selectionArgs = args.toArray<String>(arrayOfNulls<String>(args.size))
} else {
selectionArgs = arrayOf(id)
}
rowsDeleted = db.delete(table, "_id=? and " + selection, selectionArgs)
}
} else {
rowsDeleted = db.delete(table, selection, selectionArgs)
}
return rowsDeleted
}
override fun getType(arg0: Uri): String? {
return null
}
@Synchronized override fun insert(uri: Uri, values: ContentValues): Uri {
val uriType = sURIMatcher.match(uri)
val db = mDbHelper!!.writableDatabase
val id: Long
val table = switchToTable(uri)
val baseUrl: String
when (uriType) {
ACCOUNT -> baseUrl = ACCOUNTS_PATH
OPERATION -> baseUrl = OPERATIONS_PATH
OPERATION_JOINED -> baseUrl = OPERATIONS_JOINED_PATH
SCHEDULED_OP -> baseUrl = SCHEDULED_OPS_PATH
SCHEDULED_JOINED_OP -> baseUrl = SCHEDULED_JOINED_OPS_PATH
THIRD_PARTY -> baseUrl = THIRD_PARTIES_PATH
MODES -> baseUrl = MODES_PATH
TAGS -> baseUrl = TAGS_PATH
PREFS -> baseUrl = PREFS_PATH
STATS -> baseUrl = STATS_PATH
else -> throw IllegalArgumentException("Unknown URI: " + uri)
}
id = db.insert(table, null, values)
if (id > 0) {
context.contentResolver.notifyChange(uri, null)
}
return Uri.parse(baseUrl + "/" + id)
}
@Synchronized override fun update(uri: Uri, values: ContentValues, selection: String?, a: Array<String>?): Int {
var selectionArgs = a
val uriType = sURIMatcher.match(uri)
val db = mDbHelper!!.writableDatabase
var rowsUpdated: Int
val table = switchToTable(uri)
var id: String? = null
var idKey = "_id"
when (uriType) {
PREFS_ACCOUNT -> {
idKey = PreferenceTable.KEY_PREFS_ACCOUNT
id = uri.lastPathSegment
}
ACCOUNT_ID, OPERATION_ID, OPERATION_JOINED_ID, SCHEDULED_OP_ID, SCHEDULED_JOINED_OP_ID, THIRD_PARTY_ID,
MODES_ID, TAGS_ID, STATS_ID -> id = uri.lastPathSegment
else -> {
}
}
if (id != null) {
if (selection == null || selection.trim().length == 0) {
rowsUpdated = db.update(table, values, idKey + "=?", arrayOf(id))
} else {
if (selectionArgs != null) {
val args = ArrayList<String>(selectionArgs.size + 1)
args.add(id)
Collections.addAll(args, *selectionArgs)
selectionArgs = args.toArray<String>(arrayOfNulls<String>(args.size))
} else {
selectionArgs = arrayOf(id)
}
rowsUpdated = db.update(table, values, idKey + "=? and " + selection, selectionArgs)
}
} else {
rowsUpdated = db.update(table, values, selection, selectionArgs)
}
return rowsUpdated
}
companion object {
private val AUTHORITY = "fr.geobert.radis.db"
private val ACCOUNTS_PATH = "accounts"
private val OPERATIONS_PATH = "operations"
private val OPERATIONS_JOINED_PATH = "operations_joined"
private val SCHEDULED_OPS_PATH = "scheduled_ops"
private val SCHEDULED_JOINED_OPS_PATH = "scheduled_joined_ops"
private val THIRD_PARTIES_PATH = "third_parties"
private val TAGS_PATH = "tags"
private val MODES_PATH = "modes"
private val PREFS_PATH = "preferences"
private val STATS_PATH = "statistics"
private val TAG = "DbContentProvider"
private val BASE_URI = "content://" + AUTHORITY
val ACCOUNT_URI = Uri.parse(BASE_URI + "/" + ACCOUNTS_PATH)
val OPERATION_URI = Uri.parse(BASE_URI + "/" + OPERATIONS_PATH)
val OPERATION_JOINED_URI = Uri.parse(BASE_URI + "/" + OPERATIONS_JOINED_PATH)
val SCHEDULED_OP_URI = Uri.parse(BASE_URI + "/" + SCHEDULED_OPS_PATH)
val SCHEDULED_JOINED_OP_URI = Uri.parse(BASE_URI + "/" + SCHEDULED_JOINED_OPS_PATH)
val THIRD_PARTY_URI = Uri.parse(BASE_URI + "/" + THIRD_PARTIES_PATH)
val TAGS_URI = Uri.parse(BASE_URI + "/" + TAGS_PATH)
val MODES_URI = Uri.parse(BASE_URI + "/" + MODES_PATH)
val PREFS_URI = Uri.parse(BASE_URI + "/" + PREFS_PATH)
val STATS_URI = Uri.parse(BASE_URI + "/" + STATS_PATH)
private val ACCOUNT = 10
private val OPERATION = 20
private val OPERATION_JOINED = 21
private val SCHEDULED_OP = 30
private val SCHEDULED_JOINED_OP = 31
private val THIRD_PARTY = 40
private val TAGS = 50
private val MODES = 60
private val PREFS = 70
private val STATS = 80
private val ACCOUNT_ID = 15
private val OPERATION_ID = 25
private val OPERATION_JOINED_ID = 26
private val SCHEDULED_OP_ID = 35
private val SCHEDULED_JOINED_OP_ID = 36
private val THIRD_PARTY_ID = 45
private val TAGS_ID = 55
private val MODES_ID = 65
private val STATS_ID = 85
private val PREFS_ACCOUNT = 75
private val sURIMatcher = UriMatcher(UriMatcher.NO_MATCH)
init {
sURIMatcher.addURI(AUTHORITY, ACCOUNTS_PATH, ACCOUNT)
sURIMatcher.addURI(AUTHORITY, OPERATIONS_PATH, OPERATION)
sURIMatcher.addURI(AUTHORITY, OPERATIONS_JOINED_PATH, OPERATION_JOINED)
sURIMatcher.addURI(AUTHORITY, SCHEDULED_OPS_PATH, SCHEDULED_OP)
sURIMatcher.addURI(AUTHORITY, SCHEDULED_JOINED_OPS_PATH, SCHEDULED_JOINED_OP)
sURIMatcher.addURI(AUTHORITY, THIRD_PARTIES_PATH, THIRD_PARTY)
sURIMatcher.addURI(AUTHORITY, TAGS_PATH, TAGS)
sURIMatcher.addURI(AUTHORITY, MODES_PATH, MODES)
sURIMatcher.addURI(AUTHORITY, PREFS_PATH, PREFS)
sURIMatcher.addURI(AUTHORITY, STATS_PATH, STATS)
sURIMatcher.addURI(AUTHORITY, ACCOUNTS_PATH + "/#", ACCOUNT_ID)
sURIMatcher.addURI(AUTHORITY, OPERATIONS_PATH + "/#", OPERATION_ID)
sURIMatcher.addURI(AUTHORITY, OPERATIONS_JOINED_PATH + "/#", OPERATION_JOINED_ID)
sURIMatcher.addURI(AUTHORITY, SCHEDULED_OPS_PATH + "/#", SCHEDULED_OP_ID)
sURIMatcher.addURI(AUTHORITY, SCHEDULED_JOINED_OPS_PATH + "/#", SCHEDULED_JOINED_OP_ID)
sURIMatcher.addURI(AUTHORITY, THIRD_PARTIES_PATH + "/#", THIRD_PARTY_ID)
sURIMatcher.addURI(AUTHORITY, TAGS_PATH + "/#", TAGS_ID)
sURIMatcher.addURI(AUTHORITY, MODES_PATH + "/#", MODES_ID)
sURIMatcher.addURI(AUTHORITY, STATS_PATH + "/#", STATS_ID)
sURIMatcher.addURI(AUTHORITY, PREFS_PATH + "/#", PREFS_ACCOUNT)
}
private var mDbHelper: DbHelper? = null
fun reinit(ctx: Context) {
mDbHelper = DbHelper.getInstance(ctx)
}
fun close() {
DbHelper.delete()
}
}
}
|
gpl-2.0
|
374de44bb8e89f15806dbaf8d843813d
| 42.521236 | 156 | 0.60149 | 4.545161 | false | false | false | false |
Ray-Eldath/Avalon
|
src/main/kotlin/avalon/tool/system/RunningData.kt
|
1
|
1567
|
package avalon.tool.system
import org.json.JSONObject
import org.json.JSONTokener
import org.slf4j.LoggerFactory
import java.io.Closeable
import java.sql.DriverManager
import java.sql.SQLException
import java.sql.Statement
/**
* @author Ray Eldath
* @since v1.2.3
* 全功能测试通过。2018.2.8
*/
object RunningData : Closeable {
private val logger = LoggerFactory.getLogger(RunningData::class.java)
private var jsonObject: JSONObject? = null
private var empty: Boolean = true
private lateinit var statement: Statement
private val default = JSONObject().let {
it.put("group_id", 0)
it.put("friend_id", 0)
}
init {
try {
Class.forName("org.h2.Driver")
statement = DriverManager.getConnection("jdbc:h2:./data/data;IFEXISTS=TRUE").createStatement()
val resultSet = statement.executeQuery("SELECT * FROM DATA_")
resultSet.next()
val any = JSONTokener(resultSet.getString("data")).nextValue()
// init
empty = any == JSONObject.NULL
jsonObject = if (empty) default else any as JSONObject
} catch (e: Exception) {
logger.error("fatal error while load H2 database driver: `${e.localizedMessage}`")
Runtime.getRuntime().halt(-1)
}
}
fun save() {
try {
statement.execute("UPDATE data_ SET data='${jsonObject.toString()}'")
} catch (e: SQLException) {
logger.warn("exception thrown while writing running data: `${e.localizedMessage}`")
}
}
fun set(key: String, value: Any) = jsonObject!!.put(key, value)!!
fun get(key: String) = jsonObject!!.get(key)!!
override fun close() = statement.close()
}
|
agpl-3.0
|
47b2886d1164232ef95ddd0fa5e556b3
| 26.22807 | 97 | 0.707286 | 3.469799 | false | false | false | false |
d3xter/bo-android
|
app/src/main/java/org/blitzortung/android/map/overlay/PopupOverlay.kt
|
1
|
2291
|
/*
Copyright 2015 Andreas Würl
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.blitzortung.android.map.overlay
import android.graphics.drawable.Drawable
import android.view.ViewGroup
import android.widget.TextView
import com.google.android.maps.GeoPoint
import com.google.android.maps.ItemizedOverlay
import com.google.android.maps.MapView
import com.google.android.maps.OverlayItem
import org.blitzortung.android.app.R
import org.blitzortung.android.map.OwnMapActivity
abstract class PopupOverlay<Item : OverlayItem>(val activity: OwnMapActivity, defaultMarker: Drawable) : ItemizedOverlay<Item>(defaultMarker) {
internal var popupShown: Boolean = false
init {
popupShown = false
}
protected fun showPopup(location: GeoPoint, text: String) {
val map = activity.mapView
val popUp = map.popup
map.removeView(popUp)
with(popUp.findViewById(R.id.popup_text) as TextView) {
setBackgroundColor(-2013265920)
setPadding(5, 5, 5, 5)
setText(text)
}
val mapParams = MapView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
location, 0, 0, MapView.LayoutParams.BOTTOM_CENTER)
map.addView(popUp, mapParams)
popupShown = true
}
fun clearPopup(): Boolean {
val map = activity.mapView
val popUp = map.popup
map.removeView(popUp)
val popupShownStatus = popupShown
popupShown = false
return popupShownStatus
}
override fun onTap(arg0: GeoPoint?, arg1: MapView?): Boolean {
val eventHandled = super.onTap(arg0, arg1)
if (!eventHandled) {
clearPopup()
}
return eventHandled
}
}
|
apache-2.0
|
2954b6a2ba3482335721c96e12ade6fa
| 28.358974 | 143 | 0.695197 | 4.4294 | false | false | false | false |
rickgit/AndroidWidget
|
uipatterns/PermissionReq/src/main/java/edu/ptu/footerreyclerview/MainActivity.kt
|
1
|
3338
|
package edu.ptu.footerreyclerview
import android.Manifest
import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.RecyclerView.Adapter
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.activity_main.*
import android.content.Intent
import android.net.Uri
import android.widget.Toast
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
rv.layoutManager=LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
rv.adapter =object :Adapter<ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
return object :ViewHolder( LayoutInflater.from(parent?.context).inflate(R.layout.item_block,null) ){}
}
override fun getItemCount(): Int {
return 2
}
override fun getItemViewType(position: Int): Int {
if (position==1)
return 1;
return super.getItemViewType(position)
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
// TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
holder?.itemView?.setBackgroundColor(0xff00ffcc.toInt())
}
}
rv.addOnScrollListener(object :RecyclerView.OnScrollListener(){
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
print(recyclerView.toString()+" 移动位置 "+dx+" :" +dy)
}
override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
}
})
permission_btn.setOnClickListener{
MPermissionUtils.requestPermissionsResult(this@MainActivity,1, arrayOf(Manifest.permission.CALL_PHONE) ,object :MPermissionUtils.OnPermissionListener{
override fun onNeverAskAgain() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
@SuppressLint("MissingPermission")
override fun onPermissionGranted() {
// TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
val intent = Intent(Intent.ACTION_CALL)
val data = Uri.parse("tel:13076950595")
intent.data = data
startActivity(intent)
}
override fun onPermissionDenied() {
Toast.makeText(this@MainActivity,"授权失败!",Toast.LENGTH_LONG).show() //To change body of created functions use File | Settings | File Templates.
}
})
}
}
}
|
apache-2.0
|
eb23dedfe0bf1005e02a2f59fbffb8cd
| 39.987654 | 162 | 0.640663 | 5.15528 | false | false | false | false |
chrislo27/Baristron
|
src/chrislo27/oldbot/bots/WidgetBot.kt
|
1
|
4451
|
/*
* 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 chrislo27.oldbot.bots
import chrislo27.oldbot.bots.baristabot2.CommandHandler
import chrislo27.oldbot.bots.baristabot2.Permission
import chrislo27.oldbot.bots.baristabot2.Userdata
import chrislo27.oldbot.bots.baristabot2.commands.admin.LeaveServerCommand
import chrislo27.oldbot.bots.baristabot2.commands.admin.NicknameCommand
import chrislo27.oldbot.bots.baristabot2.commands.admin.UsernameCommand
import chrislo27.oldbot.bots.baristabot2.commands.javadoc.JavadocCommand
import chrislo27.oldbot.bots.baristabot2.commands.normal.CommandsCommand
import chrislo27.oldbot.bots.baristabot2.commands.normal.HelpCommand
import chrislo27.oldbot.command.Commands
import sx.blah.discord.api.events.EventSubscriber
import sx.blah.discord.handle.impl.events.MessageReceivedEvent
import sx.blah.discord.handle.obj.IGuild
import java.util.*
class WidgetBot(args: Map<String, String>) : Bot(args) {
private val cmdHandler: CommandHandler<WidgetBot> = CommandHandler(this)
var cmds = Commands<WidgetBot>()
init {
cmds.add(CommandsCommand(Permission.NORMAL, "commands", "cmds"))
cmds.add(HelpCommand(Permission.NORMAL, "help", "?"))
cmds.add(JavadocCommand(Permission.NORMAL, "javadoc", "javadocs"))
cmds.add(LeaveServerCommand(Permission.ADMIN, "leaveserver"))
cmds.add(NicknameCommand(Permission.ADMIN, "nickname"))
cmds.add(UsernameCommand(Permission.ADMIN, "username"))
}
@EventSubscriber
fun onMessage(event: MessageReceivedEvent) {
val messageObj = event.message
val channel = messageObj.channel
var message = messageObj.content
val author = messageObj.author
// guild must be approved by me first
if (!channel.isPrivate && Userdata.getLong("guildApprovalStatus_" + channel.guild.id, 0) < 2 &&
Userdata.getPermissions(author.id).ordinal < Permission.ADMIN.ordinal) {
// return
}
var embedded = false
val PREFIX = getPrefixForGuild(channel.guild)
val EMBED_PREFIX = getEmbeddedPrefixForGuild(channel.guild)
val lowerMessage = message.toLowerCase(Locale.ROOT)
val lowerPrefix = PREFIX.toLowerCase(Locale.ROOT)
val lowerEmbedPrefix = EMBED_PREFIX.toLowerCase(Locale.ROOT)
// if an embedded command is found
if (lowerMessage.contains(lowerEmbedPrefix) && !lowerMessage.startsWith(lowerPrefix) &&
!lowerMessage.startsWith(lowerEmbedPrefix)) {
val i = message.toLowerCase(Locale.ROOT).lastIndexOf(EMBED_PREFIX.toLowerCase(Locale.ROOT))
message = message.substring(i + EMBED_PREFIX.length - 1)
embedded = true
}
if (author.isBot)
return
if (!lowerMessage.startsWith(lowerPrefix) && !embedded) {
return
}
val substring = message.substring(PREFIX.length).trim()
val args = substring.split("[^\\S\\n]+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
var command = args[0].toLowerCase(Locale.ROOT)
var commandArgs = Arrays.copyOfRange(args, 1, args.size)
val content = substring.substring(substring.indexOf(args[0]) + args[0].length).trim()
if (command.isEmpty() && commandArgs.isNotEmpty()) {
command = commandArgs[0].toLowerCase(Locale.ROOT)
commandArgs = Arrays.copyOfRange(commandArgs, 1, commandArgs.size)
}
val response = cmdHandler
.onCommand(command, commandArgs, content, messageObj, channel, author, embedded)
if (response != null) {
val oldContent = response.content
Bot.sendMessage(
response.withContent(author.mention() + " **The command failed:** ").appendContent(oldContent))
}
System.gc()
}
override fun getPrefixForGuild(guild: IGuild?): String {
return "hey widget,"
}
override fun getEmbeddedPrefixForGuild(guild: IGuild?): String {
return getPrefixForGuild(guild) + getPrefixForGuild(guild) + getPrefixForGuild(guild)
}
override fun getCommands(): Commands<out Bot> {
return cmds
}
}
|
gpl-3.0
|
2fd671a20d3251ef8712d162778ae958
| 37.051282 | 101 | 0.753763 | 3.820601 | false | false | false | false |
arturbosch/detekt
|
detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/CollapsibleIfStatementsSpec.kt
|
1
|
3256
|
package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class CollapsibleIfStatementsSpec : Spek({
val subject by memoized { CollapsibleIfStatements(Config.empty) }
describe("CollapsibleIfStatements rule") {
it("reports if statements which can be merged") {
val code = """
fun f() {
if (true) {
if (1 == 1) {}
// a comment
}
}
"""
assertThat(subject.compileAndLint(code)).hasSize(1)
}
it("reports nested if statements which can be merged") {
val code = """
fun f() {
if (true) {
if (1 == 1) {
if (2 == 2) {}
}
println()
}
}
"""
assertThat(subject.compileAndLint(code)).hasSize(1)
}
it("does not report else-if") {
val code = """
fun f() {
if (true) {}
else if (1 == 1) {
if (true) {}
}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("does not report if-else") {
val code = """
fun f() {
if (true) {
if (1 == 1) {}
} else {}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("does not report if-elseif-else") {
val code = """
fun f() {
if (true) {
if (1 == 1) {}
} else if (false) {}
else {}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("does not report if with statements in the if body") {
val code = """
fun f() {
if (true) {
if (1 == 1) ;
println()
}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("does not report nested if-else") {
val code = """
fun f() {
if (true) {
if (1 == 1) {
} else {}
}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("does not report nested if-elseif") {
val code = """
fun f() {
if (true) {
if (1 == 1) {
} else if (2 == 2) {}
}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
}
})
|
apache-2.0
|
b99a332922c7679ddb21426054222a94
| 28.333333 | 69 | 0.36855 | 5.285714 | false | false | false | false |
mobilejazz/Colloc
|
server/src/main/kotlin/com/mobilejazz/colloc/ext/StringExtensions.kt
|
1
|
966
|
package com.mobilejazz.colloc.ext
import java.net.URL
fun String.toFullImportedFileURL() = URL("https://docs.google.com/spreadsheets/d/${this}/export?format=csv")
private val questionMarkAtStartRegex by lazy { "^(\\?)".toRegex() }
private val referenceAtStartRegex by lazy { "^(@)".toRegex() }
private val tagOpenRegex by lazy { "^(<)".toRegex() }
private val tagCloseRegex by lazy { "^(>)".toRegex() }
private val lineSeparatorRegex by lazy { "[\r\n]".toRegex() }
internal fun String.removeLineSeparators() = replace(lineSeparatorRegex, "")
internal fun String.encodeAndroidLiterals(): String =
replace("%@", "%s")
.replace(referenceAtStartRegex, "\\\\@")
.replace(questionMarkAtStartRegex, "\\\\?")
.replace("'", "\\'")
.replace("&", "&")
.replace(tagOpenRegex, "<")
.replace(tagCloseRegex, ">")
.replace("\"", "\\\"")
internal fun String.encodeIOSLiterals(): String =
replace("%s", "%@")
.replace("\"", "\\\"")
|
apache-2.0
|
a4396d94130567c2535f9cb4df875463
| 34.777778 | 108 | 0.650104 | 3.833333 | false | false | false | false |
rsiebert/TVHClient
|
data/src/main/java/org/tvheadend/data/entity/TagAndChannel.kt
|
1
|
1000
|
package org.tvheadend.data.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
data class TagAndChannel(
var tagId: Int = 0,
var channelId: Int = 0,
var connectionId: Int = 0
)
@Entity(tableName = "tags_and_channels", primaryKeys = ["tag_id", "channel_id", "connection_id"])
internal data class TagAndChannelEntity(
@ColumnInfo(name = "tag_id")
var tagId: Int = 0,
@ColumnInfo(name = "channel_id")
var channelId: Int = 0,
@ColumnInfo(name = "connection_id")
var connectionId: Int = 0
) {
companion object {
fun from(tagAndChannel: TagAndChannel): TagAndChannelEntity {
return TagAndChannelEntity(
tagAndChannel.tagId,
tagAndChannel.channelId,
tagAndChannel.connectionId)
}
}
@Suppress("unused")
fun toTagAndChannel(): TagAndChannel {
return TagAndChannel(tagId, channelId, connectionId)
}
}
|
gpl-3.0
|
5ffc8520d8fde813aa0613b2d3d79797
| 26.777778 | 97 | 0.615 | 4.587156 | false | false | false | false |
blakelee/CoinProfits
|
app/src/main/java/net/blakelee/coinprofits/models/ERC20.kt
|
1
|
2429
|
package net.blakelee.coinprofits.models
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class Error {
@SerializedName("code") @Expose var code: Int? = null
@SerializedName("message") @Expose var message: String? = null
}
class ETH {
@SerializedName("balance") @Expose var balance: Int? = null
@SerializedName("totalIn") @Expose var totalIn: Int? = null
@SerializedName("totalOut") @Expose var totalOut: Int? = null
}
class Price {
@SerializedName("rate") @Expose var rate: Double? = null
@SerializedName("diff") @Expose var diff: Double? = null
@SerializedName("ts") @Expose var ts: Int? = null
@SerializedName("currency") @Expose var currency: String? = null
}
class Token {
@SerializedName("tokenInfo") @Expose var tokenInfo: TokenInfo? = null
@SerializedName("balance") @Expose var balance: Double? = null
@SerializedName("totalIn") @Expose var totalIn: Double? = null
@SerializedName("totalOut") @Expose var totalOut: Int? = null
@SerializedName("lastUpdated") @Expose var lastUpdated: Int? = null
}
class TokenInfo {
@SerializedName("address") @Expose var address: String? = null
@SerializedName("name") @Expose var name: String? = null
@SerializedName("decimals") @Expose var decimals: String? = null
@SerializedName("symbol") @Expose var symbol: String? = null
@SerializedName("totalSupply") @Expose var totalSupply: String? = null
@SerializedName("owner") @Expose var owner: String? = null
@SerializedName("totalIn") @Expose var totalIn: Double? = null
@SerializedName("totalOut") @Expose var totalOut: Double? = null
@SerializedName("createdAt") @Expose var createdAt: Int? = null
@SerializedName("createdTx") @Expose var createdTx: String? = null
@SerializedName("last_updated") @Expose var lastUpdated: Int? = null
@SerializedName("issuancesCount") @Expose var issuancesCount: Int? = null
@SerializedName("holdersCount") @Expose var holdersCount: Int? = null
@SerializedName("price") @Expose var price: Price? = null
}
class ERC20 {
@SerializedName("address") @Expose var address: String? = null
@SerializedName("ETH") @Expose var eTH: ETH? = null
@SerializedName("countTxs") @Expose var countTxs: Int? = null
@SerializedName("tokens") @Expose var tokens: List<Token>? = null
@SerializedName("error") @Expose var error: Error? = null
}
|
mit
|
4fa2d977606ce727fd669714af560da8
| 43.181818 | 77 | 0.702758 | 4.014876 | false | false | false | false |
icapps/niddler-ui
|
niddler-ui/src/main/kotlin/com/icapps/niddler/ui/form/components/impl/SwingStackTraceComponent.kt
|
1
|
1739
|
package com.icapps.niddler.ui.form.components.impl
import com.icapps.niddler.ui.form.components.StackTraceComponent
import java.awt.Color
import java.awt.Component
import java.awt.Font
import javax.swing.BoxLayout
import javax.swing.JPanel
import javax.swing.JTextPane
import javax.swing.UIManager
import javax.swing.text.Style
import javax.swing.text.StyleConstants
class SwingStackTraceComponent : StackTraceComponent {
private val panelContainer = JPanel().also { it.layout = BoxLayout(it, BoxLayout.Y_AXIS) }
private val normalFont = Font("Monospaced", 0, 12)
private val textArea: JTextPane = JTextPane()
private val document = textArea.styledDocument
private val style: Style
override val asComponent: Component = panelContainer
init {
textArea.font = normalFont
textArea.isEditable = false
textArea.border = null
textArea.foreground = UIManager.getColor("Label.foreground")
textArea.background = null
style = textArea.addStyle("Style", null)
StyleConstants.setForeground(style, UIManager.getColor("link.foreground") ?: Color.blue)
StyleConstants.setUnderline(style, true)
}
override fun setStackTrace(stackTrace: List<String>?) {
document.remove(0, document.length)
if (stackTrace == null) {
return
}
stackTrace.forEachIndexed { index, element ->
if (index > 0) {
document.insertString(document.length, "\n", null)
}
document.insertString(document.length, element, style)
}
}
override fun invalidate() {
asComponent.invalidate()
}
override fun repaint() {
asComponent.repaint()
}
}
|
apache-2.0
|
3b98a3791f98db5075dc73b974c1a8a8
| 29 | 96 | 0.680851 | 4.528646 | false | false | false | false |
icapps/niddler-ui
|
niddler-ui/src/main/kotlin/com/icapps/niddler/ui/form/components/BinaryView.kt
|
1
|
7957
|
package com.icapps.niddler.ui.form.components
import com.icapps.niddler.ui.setFixedWidth
import java.awt.BorderLayout
import java.awt.Component
import java.io.File
import java.util.*
import javax.swing.*
import javax.swing.table.AbstractTableModel
import javax.swing.table.DefaultTableColumnModel
import javax.swing.table.TableCellRenderer
import javax.swing.table.TableColumn
/**
* @author Nicola Verbeeck
* @date 14/11/2017.
*/
class BinaryView : JPanel(BorderLayout()) {
private val table = JTable()
init {
val columnModel = ColumnModel()
val model = BinaryTableModel(table, columnModel.labelRenderer)
table.background = UIManager.getColor("EditorPane.background")
table.model = model
table.autoCreateColumnsFromModel = false
table.columnModel = columnModel
table.rowMargin = 0
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
model.bytes = File("/Users/nicolaverbeeck/bad_request.har").readBytes()
table.autoResizeMode = JTable.AUTO_RESIZE_OFF
table.cellSelectionEnabled = true
add(table, BorderLayout.CENTER)
}
}
private const val LABEL_WIDTH = 60
private const val ENTRY_WIDTH = 30
private const val TEXTUAL_WIDTH = 30
private class LabelCellRenderer : TableCellRenderer {
private val label = JLabel()
private val cell = JPanel(BorderLayout())
init {
cell.background = UIManager.getColor("ToolBar.background")
cell.isOpaque = true
cell.border = BorderFactory.createMatteBorder(0, 0, 0, 1, cell.background.darker())
label.setFixedWidth(LABEL_WIDTH)
label.horizontalAlignment = SwingConstants.RIGHT
label.font = UIManager.getFont("EditorPane.font")
cell.add(label, BorderLayout.CENTER)
}
override fun getTableCellRendererComponent(table: JTable, value: Any?, isSelected: Boolean, hasFocus: Boolean,
row: Int, column: Int): Component {
if (value == null) {
label.text = ""
return label
}
label.text = value.toString()
return cell
}
fun setLargestIndex(index: Int) {
val width = label.getFontMetrics(label.font).stringWidth(index.toString())
label.setFixedWidth(width)
label.setSize(width, label.height)
}
}
private val hexArray = Array<String>(256) {
String.format("%02X", it)
}
private val textArray = Array<String>(256) {
String(byteArrayOf(it.toByte(), 0))
}
private class BinaryItemCellRenderer : TableCellRenderer {
private val label = JLabel()
init {
label.apply {
horizontalAlignment = SwingConstants.CENTER
font = UIManager.getFont("EditorPane.font")
setFixedWidth(ENTRY_WIDTH)
}
}
override fun getTableCellRendererComponent(table: JTable?, value: Any?, isSelected: Boolean,
hasFocus: Boolean, row: Int, column: Int): Component {
if (value == null) {
label.text = ""
return label
}
label.text = hexArray[value as Int]
return label
}
}
private class TextualCellRenderer : TableCellRenderer {
private val label = JLabel()
private val normalBg = UIManager.getColor("EditorPane.background")
private val selectedBg = UIManager.getColor("EditorPane.selectionBackground")
private val normalTextColor = UIManager.getColor("EditorPane.foreground")
private val selectedTextColor = UIManager.getColor("EditorPane.selectionForeground")
init {
label.apply {
isOpaque = true
horizontalAlignment = SwingConstants.CENTER
font = UIManager.getFont("EditorPane.font")
background = normalBg
foreground = normalTextColor
setFixedWidth(TEXTUAL_WIDTH)
}
}
override fun getTableCellRendererComponent(table: JTable?, value: Any?, isSelected: Boolean,
hasFocus: Boolean, row: Int, column: Int): Component {
if (value == null) {
label.text = ""
return label
}
label.text = textArray[value as Int]
if (isSelected) {
label.apply {
background = selectedBg
foreground = selectedTextColor
}
} else {
label.apply {
background = normalBg
foreground = normalTextColor
}
}
return label
}
}
private class ColumnModel : DefaultTableColumnModel() {
private val labelCol = TableColumn()
private val binaryCol = TableColumn()
private val textualCol = TableColumn()
val labelRenderer = LabelCellRenderer()
init {
labelCol.apply {
width = LABEL_WIDTH
maxWidth = LABEL_WIDTH
minWidth = LABEL_WIDTH
cellRenderer = labelRenderer
}
binaryCol.apply {
width = ENTRY_WIDTH
maxWidth = ENTRY_WIDTH
minWidth = ENTRY_WIDTH
cellRenderer = BinaryItemCellRenderer()
}
textualCol.apply {
width = TEXTUAL_WIDTH
maxWidth = TEXTUAL_WIDTH
minWidth = TEXTUAL_WIDTH
cellRenderer = TextualCellRenderer()
}
}
override fun getColumnSelectionAllowed(): Boolean = true
override fun setColumnSelectionAllowed(flag: Boolean) {
//Ignore
}
override fun setColumnMargin(newMargin: Int) {
//Ignore
}
override fun addColumn(aColumn: TableColumn?) {
//Ignore
throw IllegalStateException("No manual column adding allowed")
}
override fun getColumns(): Enumeration<TableColumn> {
return object : Enumeration<TableColumn> {
private var index = 0
override fun nextElement(): TableColumn {
return getColumn(index++)
}
override fun hasMoreElements(): Boolean {
return (index < columnCount)
}
}
}
override fun getColumnMargin(): Int = 0
override fun getColumnCount(): Int = 17
override fun getTotalColumnWidth(): Int = labelCol.width + (8 * ENTRY_WIDTH) + (8 * TEXTUAL_WIDTH)
override fun getColumn(columnIndex: Int): TableColumn {
if (columnIndex == 0)
return labelCol
if (columnIndex <= 8) {
binaryCol.modelIndex = columnIndex
return binaryCol
}
textualCol.modelIndex = columnIndex
return textualCol
}
}
private class BinaryTableModel(private val table: JTable,
private val labelCellRenderer: LabelCellRenderer) : AbstractTableModel() {
private var lastRowCount = -1
var bytes: ByteArray = ByteArray(0)
set(value) {
field = value
fireTableStructureChanged()
}
override fun getRowCount(): Int {
val numDataCols = 8
var base = bytes.size / numDataCols
if ((bytes.size % numDataCols) > 0)
++base
if (base != lastRowCount) {
labelCellRenderer.setLargestIndex(base)
lastRowCount = base
}
return base
}
override fun getColumnCount(): Int = table.columnModel.columnCount
override fun getValueAt(rowIndex: Int, columnIndex: Int): Any {
val numDataCols = 8
if (columnIndex == 0) {
return rowIndex * numDataCols
}
var index = (rowIndex * numDataCols)
if (columnIndex > numDataCols)
index += (columnIndex - numDataCols - 1)
else
index += (columnIndex - 1)
if (index >= bytes.size) return ""
return bytes[index].toInt()
}
override fun isCellEditable(rowIndex: Int, columnIndex: Int): Boolean {
return false
}
}
|
apache-2.0
|
5a4b83c400f6d7d358c3f4b03ca28a0a
| 27.219858 | 114 | 0.608898 | 5.029709 | false | false | false | false |
Karma-Maker/gyg_test
|
app/src/main/java/space/serenity/berlinviewer/ui/LaunchActivity.kt
|
1
|
1593
|
package space.serenity.berlinviewer.ui
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_launch.*
import space.serenity.berlinviewer.R
import space.serenity.berlinviewer.ui.adapters.ReviewsAdapter
import space.serenity.berlinviewer.ui.providers.ReviewsProvider
class LaunchActivity : AppCompatActivity() {
val provider = ReviewsProvider()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_launch)
//menu
setSupportActionBar(toolbar)
// list
list.layoutManager = LinearLayoutManager(this)
list.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
val adapter = ReviewsAdapter(provider)
list.adapter = adapter
provider.dataSetChangeListener = {
refresh.isRefreshing = false
adapter.notifyDataSetChanged()
}
refresh.setOnRefreshListener { provider.init() }
// fab
val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener { view -> SubmitReviewDialog.show(this) }
}
override fun onStart() {
super.onStart()
provider.init();
}
override fun onStop() {
super.onStop()
provider.clear();
refresh.isRefreshing = false
}
}
|
mit
|
8b40c4182f7029b46eb13e89167d4589
| 28.5 | 91 | 0.710609 | 5.057143 | false | false | false | false |
QingMings/flashair
|
src/test/com/iezview/flashair/Test1.kt
|
1
|
2301
|
package com.iezview.flashair
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.*
/**
* Created by shishifanbuxie on 2017/4/20.
*/
object Test1 {
@JvmStatic fun main(args: Array<String>) {
val fattime = 1251218286
val year = (0xFE000000.toInt() and fattime shr 25) + 1980
val mouth = 0x1e00000 and fattime shr 21
val day = 0x001F0000 and fattime shr 16
val H = 0xf800 and fattime shr 11
val m = 0x07E0 and fattime shr 5
val s = (0x001F and fattime) * 2
var sb = StringBuilder()
sb.append(year)
.append("-")
.append(if (mouth.toString().length>1) mouth else "0"+mouth.toString())
.append("-")
.append(if(day.toString().length>1) day else "0"+day.toString())
.append(" ")
.append(if (H.toString().length>1) H else "0"+H.toString() )
.append(":")
.append(if (m.toString().length>1) m else "0"+H.toString())
.append(":")
.append(if (s.toString().length>1) m else "0"+s.toString())
var format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
var date = LocalDateTime.parse(sb.toString(),format)
var localDateTime= LocalDateTime.of(year,mouth,day,H,m,s)
var javadate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant())
// print(date::class)
// println(localDateTime::class)
// print(javadate::class)
var ref_year=((year-1980)shl 25)
var ref_mouth=(mouth shl 21)
val ref_day = (day shl 16)
val ref_H = H shl 11
val ref_m =m shl 5
val ref_s= (s / 2)
println(ref_year)
println(ref_mouth)
println(ref_day)
println(ref_H)
println(ref_m)
println(ref_s)
println(ref_year+ref_mouth+ref_day+ref_H+ref_m+ref_s)
println(System.currentTimeMillis())
var instant= Instant.ofEpochMilli(1492676258)
var localtime= LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
localtime.year
println(localtime.year)
}
}
|
mit
|
3b98de3fb5080377c4eb73ed09d06429
| 33.863636 | 95 | 0.571925 | 3.741463 | false | false | false | false |
exponent/exponent
|
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/facedetector/ExpoFaceDetector.kt
|
2
|
6820
|
package abi44_0_0.expo.modules.facedetector
import android.content.Context
import android.net.Uri
import android.os.Bundle
import androidx.arch.core.util.Function
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.firebase.ml.vision.common.FirebaseVisionImage
import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata
import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions
import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetector
import com.google.firebase.ml.vision.face.FirebaseVisionFace
import com.google.firebase.ml.vision.FirebaseVision
import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata.ROTATION_0
import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata.ROTATION_180
import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata.ROTATION_270
import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata.ROTATION_90
import abi44_0_0.expo.modules.facedetector.FaceDetectorUtils.serializeFace
import abi44_0_0.expo.modules.facedetector.FaceDetectorUtils.rotateFaceX
import abi44_0_0.expo.modules.interfaces.facedetector.FaceDetectorInterface
import abi44_0_0.expo.modules.interfaces.facedetector.FacesDetectionCompleted
import abi44_0_0.expo.modules.interfaces.facedetector.FaceDetectionError
import abi44_0_0.expo.modules.interfaces.facedetector.FaceDetectionSkipped
import abi44_0_0.expo.modules.interfaces.facedetector.FaceDetectionUnspecifiedError
import java.io.IOException
import java.util.ArrayList
private const val DETECT_LANDMARKS_KEY = "detectLandmarks"
private const val MIN_INTERVAL_MILLIS_KEY = "minDetectionInterval"
private const val MODE_KEY = "mode"
private const val RUN_CLASSIFICATIONS_KEY = "runClassifications"
private const val TRACKING_KEY = "tracking"
class ExpoFaceDetector(private val context: Context) : FaceDetectorInterface {
private var faceDetector: FirebaseVisionFaceDetector? = null
private val minFaceSize = 0.15f
private var minDetectionInterval: Long = 0
private var lastDetectionMillis: Long = 0
private var tracking = false
set(value) {
if (field != value) {
release()
field = value
}
}
private var landmarkType = NO_LANDMARKS
set(value) {
if (field != value) {
release()
field = value
}
}
private var classificationType = NO_CLASSIFICATIONS
set(value) {
if (field != value) {
release()
field = value
}
}
private var mode = FAST_MODE
set(value) {
if (field != value) {
release()
field = value
}
}
// Public API
@Throws(IOException::class)
override fun detectFaces(filePath: Uri, complete: FacesDetectionCompleted, error: FaceDetectionError) {
if (faceDetector == null) {
createFaceDetector()
}
val image = FirebaseVisionImage.fromFilePath(context, filePath)
faceDetector?.detectInImage(image)
?.addOnCompleteListener(
faceDetectionHandler(FaceDetectorUtils::serializeFace, complete, error)
)
}
override fun detectFaces(
imageData: ByteArray,
width: Int,
height: Int,
rotation: Int,
mirrored: Boolean,
scaleX: Double,
scaleY: Double,
complete: FacesDetectionCompleted,
error: FaceDetectionError,
skipped: FaceDetectionSkipped
) {
if (faceDetector == null) {
createFaceDetector()
}
val firRotation = getFirRotation(rotation)
val metadata = FirebaseVisionImageMetadata.Builder()
.setWidth(width)
.setHeight(height)
.setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
.setRotation(firRotation)
.build()
val image = FirebaseVisionImage.fromByteArray(imageData, metadata)
if (minDetectionInterval <= 0 || minIntervalPassed()) {
lastDetectionMillis = System.currentTimeMillis()
faceDetector?.detectInImage(image)
?.addOnCompleteListener(
faceDetectionHandler(
{ face ->
var result = serializeFace(face, scaleX, scaleY)
if (mirrored) {
result = if (firRotation == ROTATION_270 || firRotation == ROTATION_90) {
rotateFaceX(result, height, scaleX)
} else {
rotateFaceX(result, width, scaleX)
}
}
result
},
complete, error
)
)
} else {
skipped.onSkipped("Skipped frame due to time interval.")
}
}
private fun getFirRotation(rotation: Int) = when ((rotation + 360) % 360) {
90 -> ROTATION_90
180 -> ROTATION_180
270 -> ROTATION_270
else -> ROTATION_0
}
private fun faceDetectionHandler(transformer: Function<FirebaseVisionFace, Bundle>, complete: FacesDetectionCompleted, error: FaceDetectionError): OnCompleteListener<List<FirebaseVisionFace>?> =
OnCompleteListener { task: Task<List<FirebaseVisionFace>?> ->
if (task.isComplete && task.isSuccessful) {
val facesArray = ArrayList<Bundle>().apply {
val faces = task.result
faces?.forEach { face -> add(transformer.apply(face)) }
}
complete.detectionCompleted(facesArray)
} else {
error.onError(FaceDetectionUnspecifiedError())
}
}
private fun minIntervalPassed() = lastDetectionMillis + minDetectionInterval < System.currentTimeMillis()
override fun setSettings(settings: Map<String, Any>) {
if (settings[MODE_KEY] is Number) {
mode = (settings[MODE_KEY] as Number).toInt()
}
if (settings[DETECT_LANDMARKS_KEY] is Number) {
landmarkType = (settings[DETECT_LANDMARKS_KEY] as Number).toInt()
}
if (settings[TRACKING_KEY] is Boolean) {
tracking = (settings[TRACKING_KEY] as Boolean)
}
if (settings[RUN_CLASSIFICATIONS_KEY] is Number) {
classificationType = (settings[RUN_CLASSIFICATIONS_KEY] as Number).toInt()
}
minDetectionInterval = if (settings[MIN_INTERVAL_MILLIS_KEY] is Number) {
(settings[MIN_INTERVAL_MILLIS_KEY] as Number).toInt().toLong()
} else {
0
}
}
override fun release() {
releaseFaceDetector()
}
// Lifecycle methods
private fun releaseFaceDetector() {
faceDetector = null
}
private fun createFaceDetector() {
faceDetector = FirebaseVision.getInstance().getVisionFaceDetector(createOptions())
}
private fun createOptions(): FirebaseVisionFaceDetectorOptions {
val builder = FirebaseVisionFaceDetectorOptions.Builder()
.setClassificationMode(classificationType)
.setLandmarkMode(landmarkType)
.setPerformanceMode(mode)
.setMinFaceSize(minFaceSize)
if (tracking) {
builder.enableTracking()
}
return builder.build()
}
}
|
bsd-3-clause
|
2222f4832519e98cffcdfc3f06ec3d0b
| 33.271357 | 196 | 0.703079 | 4.417098 | false | false | false | false |
JoachimR/Bible2net
|
app/src/main/java/de/reiss/bible2net/theword/main/viewpager/ViewPagerRepository.kt
|
1
|
6828
|
package de.reiss.bible2net.theword.main.viewpager
import androidx.annotation.WorkerThread
import androidx.lifecycle.MutableLiveData
import de.reiss.bible2net.theword.architecture.AsyncLoad
import de.reiss.bible2net.theword.database.BibleItem
import de.reiss.bible2net.theword.database.BibleItemDao
import de.reiss.bible2net.theword.database.TheWordItem
import de.reiss.bible2net.theword.database.TheWordItemDao
import de.reiss.bible2net.theword.downloader.file.DownloadProgressListener
import de.reiss.bible2net.theword.downloader.file.FileDownloader
import de.reiss.bible2net.theword.downloader.list.ListDownloader
import de.reiss.bible2net.theword.downloader.list.Twd11
import de.reiss.bible2net.theword.logger.logInfo
import de.reiss.bible2net.theword.logger.logWarn
import de.reiss.bible2net.theword.twdparser.TwdItem
import de.reiss.bible2net.theword.twdparser.TwdParser
import de.reiss.bible2net.theword.util.extensions.amountOfDaysInRange
import de.reiss.bible2net.theword.util.extensions.asDateString
import de.reiss.bible2net.theword.util.extensions.extractYear
import de.reiss.bible2net.theword.util.extensions.withZeroDayTime
import de.reiss.bible2net.theword.widget.triggerWidgetRefresh
import java.util.Date
import java.util.concurrent.Executor
import javax.inject.Inject
open class ViewPagerRepository @Inject constructor(
private val executor: Executor,
private val listDownloader: ListDownloader,
private val fileDownloader: FileDownloader,
private val theWordItemDao: TheWordItemDao,
private val bibleItemDao: BibleItemDao
) {
open fun getItemsFor(
bible: String,
fromDate: Date,
toDate: Date,
result: MutableLiveData<AsyncLoad<String>>
) {
// set value instead of post value on purpose
// otherwise the fragment might invoke this twice
result.value = AsyncLoad.loading(bible)
executor.execute {
val from = fromDate.withZeroDayTime()
val until = toDate.withZeroDayTime()
val storedItems = readStoredItems(bible, from, until)
val expectedAmountOfDays = from.amountOfDaysInRange(until)
if (storedItems == null || storedItems.size < expectedAmountOfDays) {
logWarn {
"Not enough items found (actual:${storedItems?.size ?: 0}, " +
"expected:$expectedAmountOfDays) for bible '$bible' in date range: " +
from.asDateString() + " - " + until.asDateString() +
". Will try to download and store items"
}
val databaseUpdated = downloadAndStoreItems(bible, from, until)
// always return success, we only tried update
result.postValue(AsyncLoad.success(bible))
if (databaseUpdated) {
triggerWidgetRefresh()
}
} else {
result.postValue(AsyncLoad.success(bible))
}
}
}
private fun readStoredItems(
bible: String,
fromDate: Date,
toDate: Date
): List<TheWordItem>? {
return bibleItemDao.find(bible)?.id?.let { bibleId ->
getForRange(bibleId, fromDate, toDate)
}
}
@WorkerThread
private fun downloadAndStoreItems(
bible: String,
fromDate: Date,
toDate: Date
): Boolean {
listDownloader.downloadList()?.let { jsonList ->
return downloadAndStore(
bible = bible,
fromYear = fromDate.extractYear(),
toYear = toDate.extractYear(),
jsonList = jsonList
)
}
return false
}
private fun downloadAndStore(
bible: String,
fromYear: Int,
toYear: Int,
jsonList: List<Twd11>
): Boolean {
var updated = false
val allTwdUrls = jsonList
.filter {
it.bible == bible && (it.year == fromYear || it.year == toYear)
}
.map {
it.twdFileUrl
}
if (allTwdUrls.isNotEmpty()) {
val listener: DownloadProgressListener = object : DownloadProgressListener {
override fun onUpdateProgress(
url: String,
readBytes: Long,
allBytes: Long
) {
logInfo { "downloading $url ... ${(readBytes * 100 / allBytes).toInt()}%" }
}
override fun onError(
url: String,
message: String?
) {
logWarn { "$url download error" }
}
override fun onFinished(
url: String,
twdData: String
) {
logInfo { "$url downloaded successfully" }
if (writeTwdToDatabase(twdData)) {
updated = true
}
}
}
for (url in allTwdUrls) {
fileDownloader.download(url, listener)
}
}
return updated
}
@WorkerThread
fun writeTwdToDatabase(twdData: String): Boolean {
val parsed = TwdParser.parse(twdData)
val twd = parsed.first()
if (bibleItemDao.find(twd.bible) == null) {
bibleItemDao.insert(BibleItem(twd.bible, twd.bibleName, twd.bibleLanguageCode))
}
val bibleItemId = bibleItemDao.find(twd.bible)?.id
?: throw IllegalStateException("Bible ${twd.bible} not found in database")
val items = parsed.map {
asDatabaseItem(bibleItemId, it)
}.toTypedArray()
val inserted = theWordItemDao.insertOrReplace(*items)
return inserted.isNotEmpty()
}
private fun getForRange(bibleId: Int, fromDate: Date, toDate: Date) =
theWordItemDao.range(bibleId, fromDate.withZeroDayTime(), toDate.withZeroDayTime())
private fun asDatabaseItem(bibleId: Int, twd: TwdItem) =
TheWordItem().apply {
this.bibleId = bibleId
this.date = twd.date.withZeroDayTime()
this.book1 = twd.parol1.book
this.chapter1 = twd.parol1.chapter
this.verse1 = twd.parol1.verse
this.id1 = twd.parol1.id
this.intro1 = twd.parol1.intro
this.text1 = twd.parol1.text
this.ref1 = twd.parol1.ref
this.book2 = twd.parol2.book
this.chapter2 = twd.parol2.chapter
this.verse2 = twd.parol2.verse
this.id2 = twd.parol2.id
this.intro2 = twd.parol2.intro
this.text2 = twd.parol2.text
this.ref2 = twd.parol2.ref
}
}
|
gpl-3.0
|
b372f8d64fc8b2c5e1079d989dbe1084
| 32.635468 | 95 | 0.596075 | 4.644898 | false | false | false | false |
pdvrieze/darwin-android-auth
|
src/main/java/uk/ac/bournemouth/darwin/auth/DarwinAuthenticator.kt
|
1
|
24299
|
/*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 2.1 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package uk.ac.bournemouth.darwin.auth
import android.accounts.*
import android.content.Context
import android.content.Intent
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.Bundle
import android.os.Process
import android.support.annotation.RequiresApi
import android.support.annotation.StringRes
import android.util.Base64
import android.util.Log
import java.io.IOException
import java.math.BigInteger
import java.net.HttpURLConnection
import java.net.URI
import java.nio.ByteBuffer
import java.nio.channels.Channels
import java.security.KeyFactory
import java.security.NoSuchAlgorithmException
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.security.spec.KeySpec
import java.security.spec.RSAPrivateKeySpec
import java.util.*
import javax.crypto.Cipher
/**
* An authenticator taht authenticates against the darwin system.
* @constructor Create a new authenticator.
* @param context The context used to resolve context dependent values.
*/
class DarwinAuthenticator(private val context: Context) : AbstractAccountAuthenticator(context) {
private class ChallengeInfo(val responseUri: URI, val data: ByteArray?, val version: Int)
private class StaleCredentialsException : Exception()// The exception itself is enough
private data class AuthenticatorKeyInfo(val keyId: Long, val privateKey: RSAPrivateKey)
init {
PRNGFixes.ensureApplied()
}
override fun editProperties(response: AccountAuthenticatorResponse, accountType: String): Bundle? {
response.onError(ERROR_UNSUPPORTED_OPERATION, ERRORMSG_UNSUPPORTED_OPERATION)
return null
}
private fun errorResult(@StringRes message: Int) = context.getString(message).toErrorBundle()
@Throws(NetworkErrorException::class)
override fun addAccount(response: AccountAuthenticatorResponse,
accountType: String,
authTokenType: String?,
requiredFeatures: Array<String>?,
options: Bundle): Bundle {
Log.i(TAG,
"addAccount() called with: response = [$response], accountType = [$accountType], authTokenType = [$authTokenType], requiredFeatures = [${Arrays.toString(
requiredFeatures)}], options = [$options]")
if (!(authTokenType == null || DWN_ACCOUNT_TOKEN_TYPE == authTokenType)) {
return errorResult(R.string.error_invalid_tokenType)
}
return context.darwinAuthenticatorActivity(null, options.authBase, response = response).toResultBundle()
}
@Throws(NetworkErrorException::class)
override fun confirmCredentials(response: AccountAuthenticatorResponse, account: Account, options: Bundle): Bundle {
val am = AccountManager.get(context)
val intent = context.darwinAuthenticatorActivity(account,
am.getUserData(account, KEY_AUTH_BASE),
true,
am.getUserData(account, KEY_KEYID).toLongOrNull() ?: -1L,
response)
return intent.toResultBundle()
}
@Throws(NetworkErrorException::class)
override fun getAuthToken(response: AccountAuthenticatorResponse,
account: Account,
authTokenType: String,
options: Bundle): Bundle? {
Log.d(TAG,
"getAuthToken() called with: response = [$response], account = [$account], authTokenType = [$authTokenType], options = [${toString(
options)}]")
if (authTokenType != DWN_ACCOUNT_TOKEN_TYPE) {
response.onError(ERRNO_INVALID_TOKENTYPE, "invalid authTokenType")
return null // the response has the error
}
val am = AccountManager.get(context)
if (am.accounts.none { it == account }) {
response.onError(ERROR_INVALID_ACCOUNT, "The account '$account' does not exist")
}
// if(! hasAccount(am, account)) {
// throw new IllegalArgumentException("The provided account does not exist");
// }
if (!isAuthTokenAllowed(response, account, options)) {
return requestAuthTokenPermission(response, account, options)
}
val authBaseUrl: String = getAuthBase(am, account)
try {
val authKeyInfo = getAuthKeyInfo(account)
if (authKeyInfo == null || authKeyInfo.keyId < 0) {
// We are in an invalid state. We no longer have a private key. Redo authentication.
return initiateUpdateCredentials(account, authBaseUrl)
}
for (tries in 0 until AUTHTOKEN_RETRIEVE_TRY_COUNT) {
// Get challenge
try {
val challenge = readChallenge(authBaseUrl, authKeyInfo)
if (challenge?.data == null) {
return initiateUpdateCredentials(account, authBaseUrl)
}
val responseBuffer = base64encode(
encrypt(challenge.data, authKeyInfo.privateKey, challenge.version))
val conn = challenge.responseUri.toURL().openConnection() as HttpURLConnection
try {
writeResponse(conn, responseBuffer)
try {
Channels.newChannel(conn.inputStream).use { inChannel ->
val buffer = ByteBuffer.allocate(MAX_TOKEN_SIZE)
val count = inChannel.read(buffer)
if (count < 0 || count >= MAX_TOKEN_SIZE) {
response.onError(ERROR_INVALID_TOKEN_SIZE,
"The token size is not in a supported range")
return null // the response has the error
// Can't handle that
}
val cookie = ByteArray(buffer.position())
buffer.rewind()
buffer.get(cookie)
for (b in cookie) {
val c = b.toChar()
if (!(c in 'A'..'Z' || c in 'a'..'z' ||
c in '0'..'9' || c == '+' || c == '/' ||
c == '=' || c == ' ' || c == '-' || c == '_' || c == ':')) {
response.onError(ERROR_INVALID_TOKEN,
"The token contains illegal characters (${String(cookie)}]")
return null
}
}
return createResultBundle(account, cookie)
}
} catch (e: IOException) {
if (conn.responseCode != HttpURLConnection.HTTP_UNAUTHORIZED) {
val intent = context.darwinAuthenticatorActivity(null, authBaseUrl, response = response)
// reauthenticate
return intent.toResultBundle()
} else if (conn.responseCode != HttpURLConnection.HTTP_NOT_FOUND) { // We try again if we didn't get the right code.
val result = Bundle()
result.putInt(AccountManager.KEY_ERROR_CODE, conn.responseCode)
result.putString(AccountManager.KEY_ERROR_MESSAGE, e.message)
return result
}
throw e
}
} finally {
conn.disconnect()
}
} catch (e: IOException) {
throw NetworkErrorException(e)
}
}
return errorResult(R.string.err_unable_to_get_auth_key)
} catch (e: StaleCredentialsException) {
return context.darwinAuthenticatorActivity(account, authBaseUrl).toResultBundle()
}
}
private fun initiateUpdateCredentials(account: Account, authBaseUrl: String): Bundle {
return context.darwinAuthenticatorActivity(account, authBaseUrl).toResultBundle()
}
private fun requestAuthTokenPermission(response: AccountAuthenticatorResponse,
account: Account,
options: Bundle): Bundle {
val intent = context.authTokenPermissionActivity(account,
options.getInt(AccountManager.KEY_CALLER_UID),
options.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME))
return intent.toResultBundle().also { response.onResult(it) }
}
private fun isAuthTokenAllowed(response: AccountAuthenticatorResponse, account: Account, options: Bundle): Boolean {
Log.d(TAG,
"isAuthTokenAllowed() called with: " + "response = [" + response + "], account = [" + account + "], options = " + options + ", myUid=[" + Process.myUid() +
']'.toString())
if (!options.containsKey(AccountManager.KEY_CALLER_UID)) {
return true /* customTokens disabled */
}
val callerUid = options.getInt(AccountManager.KEY_CALLER_UID, -1)
val callerPackage: String? = when {
VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH
-> options.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME)
else -> null
}
if (Process.myUid() == callerUid) {
return true
}
val am = AccountManager.get(context)
return isAllowedUid(am, account, callerUid, callerPackage)
}
private fun getAuthKeyInfo(account: Account): AuthenticatorKeyInfo? {
val am = AccountManager.get(context)
val privateKeyString = am.getUserData(account, KEY_PRIVATEKEY) ?: return null
val privateKey = getPrivateKey(privateKeyString) ?: return null
val keyId = am.getUserData(account, KEY_KEYID)?.toLongOrNull() ?: return null
return AuthenticatorKeyInfo(keyId, privateKey)
}
override fun getAuthTokenLabel(authTokenType: String): String? {
Log.i(TAG, "Getting token label")
return when (authTokenType) {
DWN_ACCOUNT_TOKEN_TYPE -> null
else -> context.getString(R.string.authtoken_label)
}
}
@Throws(NetworkErrorException::class)
override fun updateCredentials(response: AccountAuthenticatorResponse,
account: Account,
authTokenType: String,
options: Bundle): Bundle {
val am = AccountManager.get(context)
val authbase = am.getUserData(account, KEY_AUTH_BASE)
val keyid = am.getUserData(account, KEY_KEYID).toLong()
val intent = context.darwinAuthenticatorActivity(account, authbase, false, keyid, response)
return intent.toResultBundle()
}
@Throws(NetworkErrorException::class)
override fun hasFeatures(response: AccountAuthenticatorResponse,
account: Account,
features: Array<String?>): Bundle {
Log.i(TAG,
"hasFeatures() called with: response = [$response], account = [$account], features = ${features.contentDeepToString()}")
val hasFeature = if (features.size == 1) {
val am = AccountManager.get(context)
if (am.accounts.none { it == account }) {
false
} else {
val authbase = am.getUserData(account, KEY_AUTH_BASE)
if (authbase == null) {
features[0] == null || DEFAULT_AUTH_BASE_URL == features[0]
} else {
authbase == features[0] || features[0] == null && DEFAULT_AUTH_BASE_URL == authbase
}
}
} else {
false
}
return Bundle(1)
.also {
it.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, hasFeature)
Log.i(TAG, "hasFeatures() returned: $it -> $hasFeature")
}
}
companion object {
/** The argument name used to specify the base url for authentication. */
const val KEY_AUTH_BASE = "authbase"
const val DEFAULT_AUTH_BASE_URL = "https://darwin.bournemouth.ac.uk/accountmgr/"
const val KEY_PRIVATEKEY = "privatekey"
const val KEY_KEYID = "keyid"
const val KEY_ACCOUNT = "account"
private const val CIPHERSUITE_V2 = "RSA/ECB/PKCS1Padding"
private const val CIPHERSUITE_V1 = "RSA/NONE/NOPADDING"
private const val CHALLENGE_VERSION_V2 = "2"
private const val CHALLENGE_VERSION_V1 = "1"
private const val HEADER_CHALLENGE_VERSION = "X-Challenge-version"
const val KEY_ALGORITHM = "RSA"
private const val AUTHTOKEN_RETRIEVE_TRY_COUNT = 5
private const val TAG = "DarwinAuthenticator"
private const val CHALLENGE_MAX = 4096
private const val HEADER_RESPONSE = "X-Darwin-Respond"
private const val MAX_TOKEN_SIZE = 1024
private const val BASE64_FLAGS = Base64.URL_SAFE or Base64.NO_WRAP
private const val ERRNO_INVALID_TOKENTYPE = AccountManager.ERROR_CODE_BAD_ARGUMENTS
private const val ERROR_INVALID_TOKEN_SIZE = AccountManager.ERROR_CODE_REMOTE_EXCEPTION
private const val ERROR_INVALID_TOKEN = AccountManager.ERROR_CODE_REMOTE_EXCEPTION
private const val ERROR_INVALID_ACCOUNT = AccountManager.ERROR_CODE_BAD_ARGUMENTS
private const val ERRORMSG_UNSUPPORTED_OPERATION = "Editing properties is not supported"
private const val ERROR_UNSUPPORTED_OPERATION = AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION
private const val KEY_ALLOWED_UIDS = "allowedUids"
@JvmStatic
fun toString(options: Bundle): String {
return options
.keySet()
.joinToString(", ", "[", "]") { key -> "$key=${options[key]}" }
}
@JvmStatic
fun isAllowedUid(am: AccountManager, account: Account, uid: Int, callerPackage: String?): Boolean {
val allowedUidsString = am.getUserData(account, KEY_ALLOWED_UIDS)
Log.d(TAG,
"isAllowedUid() called with: am = [$am], account = [$account], uid = [$uid], callerPackage = [$callerPackage], allowedUidString=[$allowedUidsString]")
if (allowedUidsString.isNullOrEmpty()) return false
return allowedUidsString
.split(',')
.any { it.trim().toInt() == uid }
.also { Log.d(TAG, "isAllowedUid() returned: $it") }
}
@JvmStatic
fun addAllowedUid(am: AccountManager, account: Account, uid: Int) {
val oldAllowedUids: String? = am.getUserData(account, KEY_ALLOWED_UIDS)
val newAllowedUids: String = when {
oldAllowedUids == null || oldAllowedUids.isEmpty()
-> Integer.toString(uid)
else -> {
if (oldAllowedUids.split(',').any { it.trim().toInt() == uid }) return
"$oldAllowedUids,$uid"
}
}
am.setUserData(account, KEY_ALLOWED_UIDS, newAllowedUids)
}
@JvmStatic
fun removeAllowedUid(am: AccountManager, account: Account, uid: Int) {
val allowedUidsString = am.getUserData(account, KEY_ALLOWED_UIDS)
val uidString = uid.toString()
Log.d(TAG,
"removeAllowedUid() called with: am = [$am], account = [$account], uid = [$uid], allowedUids=[$allowedUidsString], uidString=[$uidString]")
if (allowedUidsString != null && !allowedUidsString.isEmpty()) {
val newString = allowedUidsString
.splitToSequence(',')
.map { it.trim() }
.filter { it == uidString }
.joinToString(",")
.let { if (it.isEmpty()) null else it }
am.setUserData(account, KEY_ALLOWED_UIDS, newString)
Log.d(TAG, "removeAllowedUid($uid) stored: $newString was:$allowedUidsString")
}
}
private fun encrypt(challenge: ByteArray?, privateKey: RSAPrivateKey, version: Int): ByteArray {
val cipher = Cipher.getInstance(if (version == 1) CIPHERSUITE_V1 else CIPHERSUITE_V2)
cipher.init(Cipher.ENCRYPT_MODE, privateKey)
return cipher.doFinal(challenge)
}
@Throws(IOException::class)
private fun writeResponse(conn: HttpURLConnection, response: ByteArray) {
conn.doOutput = true
conn.requestMethod = "POST"
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf8")
conn.outputStream.use { out ->
out.write("response=".toByteArray())
out.write(response)
}
}
private fun base64encode(input: ByteArray?): ByteArray {
return Base64.encode(input, BASE64_FLAGS)
}
@Throws(IOException::class, StaleCredentialsException::class)
private fun readChallenge(authBaseUrl: String, authenticatorKeyInfo: AuthenticatorKeyInfo): ChallengeInfo? {
val challengeUrl = URI.create("${getChallengeUrl(authBaseUrl)}?keyid=${authenticatorKeyInfo.keyId}")
val connection = challengeUrl.toURL().openConnection() as HttpURLConnection
try {
connection.instanceFollowRedirects = false// We should get the response url.
val responseUrl: URI = connection.getHeaderField(HEADER_RESPONSE)?.let { URI.create(it) }
?: challengeUrl
val version = when (connection.getHeaderField(HEADER_CHALLENGE_VERSION)) {
CHALLENGE_VERSION_V1 -> 1
CHALLENGE_VERSION_V2 -> 2
else -> -1
}
val responseCode = connection.responseCode
if (responseCode == HttpURLConnection.HTTP_FORBIDDEN || responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
return null
} else if (responseCode >= 400) {
throw HttpResponseException(connection)
}
val inBuffer = ByteArray(CHALLENGE_MAX * 4 / 3)
val readCount: Int = connection.inputStream.use { it.read(inBuffer) }
val challengeBytes: ByteArray
challengeBytes = if (version != 1) {
Base64.decode(inBuffer, 0, readCount, Base64.URL_SAFE)
} else {
Arrays.copyOf(inBuffer, readCount)
}
return ChallengeInfo(responseUrl, challengeBytes, version)
} finally {
connection.disconnect()
}
}
private fun getChallengeUrl(authBaseUrl: String): URI {
return URI.create("${authBaseUrl}challenge")
}
@JvmStatic
fun getAuthenticateUrl(authBaseUrl: String?): URI {
return URI.create("${if (authBaseUrl.isNullOrEmpty()) DEFAULT_AUTH_BASE_URL else authBaseUrl}regkey")
}
@JvmStatic
fun encodePrivateKey(privateKey: RSAPrivateKey): String {
val result = StringBuilder()
result.append(privateKey.modulus)
result.append(':')
result.append(privateKey.privateExponent)
return result.toString()
}
@JvmStatic
fun encodePublicKey(publicKey: RSAPublicKey): String {
return buildString {
append(Base64.encodeToString(publicKey.modulus.toByteArray(), BASE64_FLAGS))
append(':')
append(Base64.encodeToString(publicKey.publicExponent.toByteArray(), BASE64_FLAGS))
}.also {
Log.d(TAG, "Registering public key: (${publicKey.modulus}, ${publicKey.publicExponent}) $it")
}
}
}
private fun getPrivateKey(privateKeyString: String): RSAPrivateKey? {
val keyfactory: KeyFactory
try {
keyfactory = KeyFactory.getInstance(KEY_ALGORITHM)
} catch (e: NoSuchAlgorithmException) {
Log.e(TAG, "The RSA algorithm isn't supported on your system", e)
return null
}
val keyspec: KeySpec = run {
val end = privateKeyString.indexOf(':')
val modulus = BigInteger(privateKeyString.substring(0, end))
val start = end + 1
val privateExponent = BigInteger(privateKeyString.substring(start))
RSAPrivateKeySpec(modulus, privateExponent)
}
return keyfactory.generatePrivate(keyspec) as RSAPrivateKey
}
}
private const val EXPIRY_TIMEOUT = (1000 * 60 * 30).toLong() // 30 minutes
var Bundle.accountName: String?
get() = getString(AccountManager.KEY_ACCOUNT_NAME)
set(value) = putString(AccountManager.KEY_ACCOUNT_NAME, value)
var Bundle.accountType: String?
get() = getString(AccountManager.KEY_ACCOUNT_TYPE)
set(value) = putString(AccountManager.KEY_ACCOUNT_TYPE, value)
var Bundle.authToken: String?
get() = getString(AccountManager.KEY_AUTHTOKEN)
set(value) = putString(AccountManager.KEY_AUTHTOKEN, value)
var Bundle.customTokenExpiry: Long
@RequiresApi(VERSION_CODES.M)
get() = getLong(AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, -1L)
@RequiresApi(VERSION_CODES.M)
set(value) = putLong(AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, value)
var Bundle.authBase: String
get() = getString(DarwinAuthenticator.KEY_AUTH_BASE, DarwinAuthenticator.DEFAULT_AUTH_BASE_URL)
set(value) = putString(DarwinAuthenticator.KEY_AUTH_BASE, value)
private fun createResultBundle(account: Account, cookie: ByteArray): Bundle {
return Bundle(4).apply {
accountName = account.name
accountType = DWN_ACCOUNT_TOKEN_TYPE
authToken = String(cookie, UTF8)
if (VERSION.SDK_INT >= VERSION_CODES.M) {
customTokenExpiry = System.currentTimeMillis() + EXPIRY_TIMEOUT
}
}
}
fun getAuthBase(am: AccountManager, account: Account) =
am.getUserData(account, DarwinAuthenticator.KEY_AUTH_BASE) ?: DarwinAuthenticator.DEFAULT_AUTH_BASE_URL
fun Intent.toResultBundle() = Bundle(1).apply { putParcelable(AccountManager.KEY_INTENT, this@toResultBundle) }
private fun String.toErrorBundle() =
Bundle(1).apply { putString(AccountManager.KEY_ERROR_MESSAGE, this@toErrorBundle) }
/** The account type supported by the authenticator. */
const val DWN_ACCOUNT_TYPE = "uk.ac.bournemouth.darwin.account"
/** The token type for darwin accounts. For now there is only this type. */
const val DWN_ACCOUNT_TOKEN_TYPE = "uk.ac.bournemouth.darwin.auth"
|
lgpl-2.1
|
6fc7856d455ea0b137422a5608ca923e
| 43.021739 | 169 | 0.585497 | 5.123129 | false | false | false | false |
HabitRPG/habitrpg-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/skills/SkillTasksRecyclerViewFragment.kt
|
1
|
3109
|
package com.habitrpg.android.habitica.ui.fragments.skills
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.TaskRepository
import com.habitrpg.android.habitica.databinding.FragmentRecyclerviewBinding
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.android.habitica.models.tasks.TaskType
import com.habitrpg.android.habitica.modules.AppModule
import com.habitrpg.android.habitica.ui.adapter.SkillTasksRecyclerViewAdapter
import com.habitrpg.android.habitica.ui.fragments.BaseFragment
import io.reactivex.rxjava3.core.BackpressureStrategy
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.subjects.PublishSubject
import javax.inject.Inject
import javax.inject.Named
class SkillTasksRecyclerViewFragment : BaseFragment<FragmentRecyclerviewBinding>() {
@Inject
lateinit var taskRepository: TaskRepository
@field:[Inject Named(AppModule.NAMED_USER_ID)]
lateinit var userId: String
var taskType: TaskType? = null
override var binding: FragmentRecyclerviewBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentRecyclerviewBinding {
return FragmentRecyclerviewBinding.inflate(inflater, container, false)
}
var adapter: SkillTasksRecyclerViewAdapter = SkillTasksRecyclerViewAdapter()
internal var layoutManager: LinearLayoutManager? = null
private val taskSelectionEvents = PublishSubject.create<Task>()
fun getTaskSelectionEvents(): Flowable<Task> {
return taskSelectionEvents.toFlowable(BackpressureStrategy.DROP)
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val layoutManager = LinearLayoutManager(context)
binding?.recyclerView?.layoutManager = layoutManager
adapter = SkillTasksRecyclerViewAdapter()
compositeSubscription.add(
adapter.getTaskSelectionEvents().subscribe(
{
taskSelectionEvents.onNext(it)
},
RxErrorHandler.handleEmptyError()
)
)
binding?.recyclerView?.adapter = adapter
}
override fun onResume() {
super.onResume()
var tasks = taskRepository.getTasks(taskType ?: TaskType.HABIT)
.map { it.filter { it.challengeID == null && it.group == null } }
if (taskType == TaskType.TODO) {
tasks = tasks.map { it.filter { !it.completed } }
}
compositeSubscription.add(
tasks.subscribe(
{
adapter.data = it
},
RxErrorHandler.handleEmptyError()
)
)
}
}
|
gpl-3.0
|
a1a8dcf4420a2d9f2fc85890e2ffa033
| 36.011905 | 110 | 0.718881 | 5.260575 | false | false | false | false |
HabitRPG/habitrpg-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/LoginActivity.kt
|
1
|
19637
|
package com.habitrpg.android.habitica.ui.activities
import android.accounts.AccountManager
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.app.Activity
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.text.InputType
import android.text.SpannableString
import android.text.method.LinkMovementMethod
import android.text.style.UnderlineSpan
import android.view.MenuItem
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.LinearLayout
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.preference.PreferenceManager
import com.google.firebase.analytics.FirebaseAnalytics
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ApiClient
import com.habitrpg.android.habitica.databinding.ActivityLoginBinding
import com.habitrpg.android.habitica.extensions.addCancelButton
import com.habitrpg.android.habitica.extensions.addOkButton
import com.habitrpg.android.habitica.extensions.updateStatusBarColor
import com.habitrpg.android.habitica.helpers.AmplitudeManager
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.auth.UserAuthResponse
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.helpers.dismissKeyboard
import com.habitrpg.android.habitica.ui.viewmodels.AuthenticationViewModel
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import javax.inject.Inject
class LoginActivity : BaseActivity() {
private lateinit var viewModel: AuthenticationViewModel
private lateinit var binding: ActivityLoginBinding
@Inject
lateinit var apiClient: ApiClient
@Inject
lateinit var sharedPrefs: SharedPreferences
@Inject
lateinit var configManager: AppConfigManager
private var isRegistering: Boolean = false
private var isShowingForm: Boolean = false
private val loginClick = View.OnClickListener {
binding.PBAsyncTask.visibility = View.VISIBLE
if (isRegistering) {
val username: String = binding.username.text.toString().trim { it <= ' ' }
val email: String = binding.email.text.toString().trim { it <= ' ' }
val password: String = binding.password.text.toString()
val confirmPassword: String = binding.confirmPassword.text.toString()
if (username.isEmpty() || password.isEmpty() || email.isEmpty() || confirmPassword.isEmpty()) {
showValidationError(R.string.login_validation_error_fieldsmissing)
return@OnClickListener
}
if (password.length < configManager.minimumPasswordLength()) {
showValidationError(getString(R.string.password_too_short, configManager.minimumPasswordLength()))
return@OnClickListener
}
apiClient.registerUser(username, email, password, confirmPassword)
.subscribe(
{ handleAuthResponse(it) },
{
hideProgress()
RxErrorHandler.reportError(it)
}
)
} else {
val username: String = binding.username.text.toString().trim { it <= ' ' }
val password: String = binding.password.text.toString()
if (username.isEmpty() || password.isEmpty()) {
showValidationError(R.string.login_validation_error_fieldsmissing)
return@OnClickListener
}
apiClient.connectUser(username, password).subscribe(
{ handleAuthResponse(it) },
{
hideProgress()
RxErrorHandler.reportError(it)
}
)
}
}
override fun getLayoutResId(): Int {
window.requestFeature(Window.FEATURE_ACTION_BAR)
return R.layout.activity_login
}
override fun getContentView(): View {
binding = ActivityLoginBinding.inflate(layoutInflater)
return binding.root
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = AuthenticationViewModel()
supportActionBar?.hide()
// Set default values to avoid null-responses when requesting unedited settings
PreferenceManager.setDefaultValues(this, R.xml.preferences_fragment, false)
viewModel.setupFacebookLogin {
handleAuthResponse(it)
}
binding.loginBtn.setOnClickListener(loginClick)
val content = SpannableString(binding.forgotPassword.text)
content.setSpan(UnderlineSpan(), 0, content.length, 0)
binding.forgotPassword.text = content
binding.privacyPolicy.movementMethod = LinkMovementMethod.getInstance()
this.isRegistering = true
val additionalData = HashMap<String, Any>()
additionalData["page"] = this.javaClass.simpleName
binding.backgroundContainer.post { binding.backgroundContainer.scrollTo(0, binding.backgroundContainer.bottom) }
binding.backgroundContainer.isScrollable = false
window.statusBarColor = ContextCompat.getColor(this, R.color.black_20_alpha)
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
binding.newGameButton.setOnClickListener { newGameButtonClicked() }
binding.showLoginButton.setOnClickListener { showLoginButtonClicked() }
binding.backButton.setOnClickListener { backButtonClicked() }
binding.forgotPassword.setOnClickListener { onForgotPasswordClicked() }
binding.fbLoginButton.setOnClickListener { viewModel.handleFacebookLogin(this) }
binding.googleLoginButton.setOnClickListener { viewModel.handleGoogleLogin(this, pickAccountResult) }
binding.appleLoginButton.setOnClickListener {
viewModel.connectApple(supportFragmentManager) {
handleAuthResponse(it)
}
}
}
override fun loadTheme(sharedPreferences: SharedPreferences, forced: Boolean) {
super.loadTheme(sharedPreferences, forced)
window.updateStatusBarColor(R.color.black_20_alpha, false)
}
override fun onBackPressed() {
if (isShowingForm) {
hideForm()
} else {
super.onBackPressed()
}
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
private fun resetLayout() {
if (this.isRegistering) {
if (binding.email.visibility == View.GONE) {
show(binding.email)
}
if (binding.confirmPassword.visibility == View.GONE) {
show(binding.confirmPassword)
}
} else {
if (binding.email.visibility == View.VISIBLE) {
hide(binding.email)
}
if (binding.confirmPassword.visibility == View.VISIBLE) {
hide(binding.confirmPassword)
}
}
}
private fun startMainActivity() {
val intent = Intent(this@LoginActivity, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
private fun startSetupActivity() {
val intent = Intent(this@LoginActivity, SetupActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
private fun toggleRegistering() {
this.isRegistering = (!this.isRegistering)
this.setRegistering()
}
private fun setRegistering() {
if (this.isRegistering) {
binding.loginBtn.text = getString(R.string.register_btn)
binding.username.setHint(R.string.username)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
binding.username.setAutofillHints("newUsername")
binding.password.setAutofillHints("newPassword")
}
binding.password.imeOptions = EditorInfo.IME_ACTION_NEXT
binding.fbLoginButton.visibility = View.GONE
binding.googleLoginButton.setText(R.string.register_btn_google)
} else {
binding.loginBtn.text = getString(R.string.login_btn)
binding.username.setHint(R.string.email_username)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
binding.username.setAutofillHints("username")
binding.password.setAutofillHints("password")
}
binding.password.imeOptions = EditorInfo.IME_ACTION_DONE
binding.fbLoginButton.setText(R.string.login_btn_fb)
binding.fbLoginButton.visibility = View.VISIBLE
binding.googleLoginButton.setText(R.string.login_btn_google)
}
this.resetLayout()
}
private fun handleAuthResponse(response: UserAuthResponse) {
viewModel.handleAuthResponse(response)
compositeSubscription.add(
userRepository.retrieveUser(true)
.subscribe({
handleAuthResponse(it, response.newUser)
}, RxErrorHandler.handleEmptyError())
)
}
private fun handleAuthResponse(user: User, isNew: Boolean) {
hideProgress()
dismissKeyboard()
if (isRegistering) {
FirebaseAnalytics.getInstance(this).logEvent("user_registered", null)
}
compositeSubscription.add(
userRepository.retrieveUser(withTasks = true, forced = true)
.subscribe(
{
if (isNew) {
this.startSetupActivity()
} else {
this.startMainActivity()
AmplitudeManager.sendEvent("login", AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR, AmplitudeManager.EVENT_HITTYPE_EVENT)
}
},
RxErrorHandler.handleEmptyError()
)
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
viewModel.onActivityResult(requestCode, resultCode, data) {
handleAuthResponse(it)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_toggleRegistering -> toggleRegistering()
}
return super.onOptionsItemSelected(item)
}
private fun hideProgress() {
runOnUiThread {
binding.PBAsyncTask.visibility = View.GONE
}
}
private fun showValidationError(resourceMessageString: Int) {
showValidationError(getString(resourceMessageString))
}
private fun showValidationError(message: String) {
binding.PBAsyncTask.visibility = View.GONE
val alert = HabiticaAlertDialog(this)
alert.setTitle(R.string.login_validation_error_title)
alert.setMessage(message)
alert.addOkButton()
alert.show()
}
private val pickAccountResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
viewModel.googleEmail = it?.data?.getStringExtra(AccountManager.KEY_ACCOUNT_NAME)
viewModel.handleGoogleLoginResult(this, recoverFromPlayServicesErrorResult) { user, isNew ->
handleAuthResponse(user, isNew)
}
}
}
private val recoverFromPlayServicesErrorResult = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
if (it.resultCode != Activity.RESULT_CANCELED) {
viewModel.handleGoogleLoginResult(this, null) { user, isNew ->
handleAuthResponse(user, isNew)
}
}
}
private fun newGameButtonClicked() {
isRegistering = true
showForm()
setRegistering()
}
private fun showLoginButtonClicked() {
isRegistering = false
showForm()
setRegistering()
}
private fun backButtonClicked() {
if (isShowingForm) {
hideForm()
}
}
private fun showForm() {
isShowingForm = true
val panAnimation = ObjectAnimator.ofInt(binding.backgroundContainer, "scrollY", 0).setDuration(1000)
val newGameAlphaAnimation = ObjectAnimator.ofFloat(binding.newGameButton, View.ALPHA, 0.toFloat())
val showLoginAlphaAnimation = ObjectAnimator.ofFloat(binding.showLoginButton, View.ALPHA, 0.toFloat())
val scaleLogoAnimation = ValueAnimator.ofInt(binding.logoView.measuredHeight, (binding.logoView.measuredHeight * 0.75).toInt())
scaleLogoAnimation.addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as? Int ?: 0
val layoutParams = binding.logoView.layoutParams
layoutParams.height = value
binding.logoView.layoutParams = layoutParams
}
if (isRegistering) {
newGameAlphaAnimation.startDelay = 600
newGameAlphaAnimation.duration = 400
showLoginAlphaAnimation.duration = 400
newGameAlphaAnimation.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
binding.newGameButton.visibility = View.GONE
binding.showLoginButton.visibility = View.GONE
binding.loginScrollview.visibility = View.VISIBLE
binding.loginScrollview.alpha = 1f
}
})
} else {
showLoginAlphaAnimation.startDelay = 600
showLoginAlphaAnimation.duration = 400
newGameAlphaAnimation.duration = 400
showLoginAlphaAnimation.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
binding.newGameButton.visibility = View.GONE
binding.showLoginButton.visibility = View.GONE
binding.loginScrollview.visibility = View.VISIBLE
binding.loginScrollview.alpha = 1f
}
})
}
val backAlphaAnimation = ObjectAnimator.ofFloat(binding.backButton, View.ALPHA, 1.toFloat()).setDuration(800)
val showAnimation = AnimatorSet()
showAnimation.playTogether(panAnimation, newGameAlphaAnimation, showLoginAlphaAnimation, scaleLogoAnimation)
showAnimation.play(backAlphaAnimation).after(panAnimation)
for (i in 0 until binding.formWrapper.childCount) {
val view = binding.formWrapper.getChildAt(i)
view.alpha = 0f
val animator = ObjectAnimator.ofFloat(view, View.ALPHA, 1.toFloat()).setDuration(400)
animator.startDelay = (100 * i).toLong()
showAnimation.play(animator).after(panAnimation)
}
showAnimation.start()
}
private fun hideForm() {
isShowingForm = false
val panAnimation = ObjectAnimator.ofInt(binding.backgroundContainer, "scrollY", binding.backgroundContainer.bottom).setDuration(1000)
val newGameAlphaAnimation = ObjectAnimator.ofFloat(binding.newGameButton, View.ALPHA, 1.toFloat()).setDuration(700)
val showLoginAlphaAnimation = ObjectAnimator.ofFloat(binding.showLoginButton, View.ALPHA, 1.toFloat()).setDuration(700)
val scaleLogoAnimation = ValueAnimator.ofInt(binding.logoView.measuredHeight, (binding.logoView.measuredHeight * 1.333333).toInt())
scaleLogoAnimation.addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as? Int
val layoutParams = binding.logoView.layoutParams
layoutParams.height = value ?: 0
binding.logoView.layoutParams = layoutParams
}
showLoginAlphaAnimation.startDelay = 300
val scrollViewAlphaAnimation = ObjectAnimator.ofFloat(binding.loginScrollview, View.ALPHA, 0.toFloat()).setDuration(800)
scrollViewAlphaAnimation.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
binding.newGameButton.visibility = View.VISIBLE
binding.showLoginButton.visibility = View.VISIBLE
binding.loginScrollview.visibility = View.INVISIBLE
}
})
val backAlphaAnimation = ObjectAnimator.ofFloat(binding.backButton, View.ALPHA, 0.toFloat()).setDuration(800)
val showAnimation = AnimatorSet()
showAnimation.playTogether(panAnimation, scrollViewAlphaAnimation, backAlphaAnimation, scaleLogoAnimation)
showAnimation.play(newGameAlphaAnimation).after(scrollViewAlphaAnimation)
showAnimation.play(showLoginAlphaAnimation).after(scrollViewAlphaAnimation)
showAnimation.start()
dismissKeyboard()
}
private fun onForgotPasswordClicked() {
val input = EditText(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
input.setAutofillHints(EditText.AUTOFILL_HINT_EMAIL_ADDRESS)
}
input.inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
input.layoutParams = lp
val alertDialog = HabiticaAlertDialog(this)
alertDialog.setTitle(R.string.forgot_password_title)
alertDialog.setMessage(R.string.forgot_password_description)
alertDialog.setAdditionalContentView(input)
alertDialog.addButton(R.string.send, true) { _, _ ->
userRepository.sendPasswordResetEmail(input.text.toString()).subscribe({ showPasswordEmailConfirmation() }, RxErrorHandler.handleEmptyError())
}
alertDialog.addCancelButton()
alertDialog.show()
}
private fun showPasswordEmailConfirmation() {
val alert = HabiticaAlertDialog(this)
alert.setMessage(R.string.forgot_password_confirmation)
alert.addOkButton()
alert.show()
}
override fun finish() {
dismissKeyboard()
super.finish()
}
companion object {
internal const val REQUEST_CODE_PICK_ACCOUNT = 1000
fun show(v: View) {
v.visibility = View.VISIBLE
}
fun hide(v: View) {
v.visibility = View.GONE
}
}
}
|
gpl-3.0
|
fc09a9eb40de1da10828d2eebc339a53
| 40.412527 | 154 | 0.648368 | 5.502101 | false | false | false | false |
nrizzio/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/ConversationSettingsFragment.kt
|
1
|
34585
|
package org.thoughtcrime.securesms.components.settings.conversation
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.graphics.Rect
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.view.doOnPreDraw
import androidx.fragment.app.viewModels
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import app.cash.exhaustive.Exhaustive
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import org.signal.core.util.DimensionUnit
import org.thoughtcrime.securesms.AvatarPreviewActivity
import org.thoughtcrime.securesms.BlockUnblockDialog
import org.thoughtcrime.securesms.InviteActivity
import org.thoughtcrime.securesms.MuteDialog
import org.thoughtcrime.securesms.PushContactSelectionActivity
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.badges.BadgeImageView
import org.thoughtcrime.securesms.badges.Badges
import org.thoughtcrime.securesms.badges.Badges.displayBadges
import org.thoughtcrime.securesms.badges.models.Badge
import org.thoughtcrime.securesms.badges.view.ViewBadgeBottomSheetDialogFragment
import org.thoughtcrime.securesms.components.AvatarImageView
import org.thoughtcrime.securesms.components.recyclerview.OnScrollAnimationHelper
import org.thoughtcrime.securesms.components.settings.DSLConfiguration
import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment
import org.thoughtcrime.securesms.components.settings.DSLSettingsIcon
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.components.settings.NO_TINT
import org.thoughtcrime.securesms.components.settings.configure
import org.thoughtcrime.securesms.components.settings.conversation.preferences.AvatarPreference
import org.thoughtcrime.securesms.components.settings.conversation.preferences.BioTextPreference
import org.thoughtcrime.securesms.components.settings.conversation.preferences.ButtonStripPreference
import org.thoughtcrime.securesms.components.settings.conversation.preferences.GroupDescriptionPreference
import org.thoughtcrime.securesms.components.settings.conversation.preferences.InternalPreference
import org.thoughtcrime.securesms.components.settings.conversation.preferences.LargeIconClickPreference
import org.thoughtcrime.securesms.components.settings.conversation.preferences.LegacyGroupPreference
import org.thoughtcrime.securesms.components.settings.conversation.preferences.RecipientPreference
import org.thoughtcrime.securesms.components.settings.conversation.preferences.SharedMediaPreference
import org.thoughtcrime.securesms.components.settings.conversation.preferences.Utils.formatMutedUntil
import org.thoughtcrime.securesms.contacts.ContactsCursorLoader
import org.thoughtcrime.securesms.conversation.ConversationIntents
import org.thoughtcrime.securesms.groups.ParcelableGroupId
import org.thoughtcrime.securesms.groups.ui.GroupErrors
import org.thoughtcrime.securesms.groups.ui.GroupLimitDialog
import org.thoughtcrime.securesms.groups.ui.LeaveGroupDialog
import org.thoughtcrime.securesms.groups.ui.addmembers.AddMembersActivity
import org.thoughtcrime.securesms.groups.ui.addtogroup.AddToGroupsActivity
import org.thoughtcrime.securesms.groups.ui.invitesandrequests.ManagePendingAndRequestingMembersActivity
import org.thoughtcrime.securesms.groups.ui.managegroup.dialogs.GroupDescriptionDialog
import org.thoughtcrime.securesms.groups.ui.managegroup.dialogs.GroupInviteSentDialog
import org.thoughtcrime.securesms.groups.ui.managegroup.dialogs.GroupsLearnMoreBottomSheetDialogFragment
import org.thoughtcrime.securesms.groups.ui.migration.GroupsV1MigrationInitiationBottomSheetDialogFragment
import org.thoughtcrime.securesms.mediaoverview.MediaOverviewActivity
import org.thoughtcrime.securesms.mediapreview.MediaIntentFactory
import org.thoughtcrime.securesms.profiles.edit.EditProfileActivity
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientExporter
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.recipients.ui.bottomsheet.RecipientBottomSheetDialogFragment
import org.thoughtcrime.securesms.stories.Stories
import org.thoughtcrime.securesms.stories.StoryViewerArgs
import org.thoughtcrime.securesms.stories.dialogs.StoryDialogs
import org.thoughtcrime.securesms.stories.viewer.StoryViewerActivity
import org.thoughtcrime.securesms.util.CommunicationActions
import org.thoughtcrime.securesms.util.ContextUtil
import org.thoughtcrime.securesms.util.ExpirationUtil
import org.thoughtcrime.securesms.util.Material3OnScrollHelper
import org.thoughtcrime.securesms.util.ViewUtil
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.navigation.safeNavigate
import org.thoughtcrime.securesms.util.views.SimpleProgressDialog
import org.thoughtcrime.securesms.verify.VerifyIdentityActivity
import org.thoughtcrime.securesms.wallpaper.ChatWallpaperActivity
private const val REQUEST_CODE_VIEW_CONTACT = 1
private const val REQUEST_CODE_ADD_CONTACT = 2
private const val REQUEST_CODE_ADD_MEMBERS_TO_GROUP = 3
private const val REQUEST_CODE_RETURN_FROM_MEDIA = 4
class ConversationSettingsFragment : DSLSettingsFragment(
layoutId = R.layout.conversation_settings_fragment,
menuId = R.menu.conversation_settings
) {
private val alertTint by lazy { ContextCompat.getColor(requireContext(), R.color.signal_alert_primary) }
private val blockIcon by lazy {
ContextUtil.requireDrawable(requireContext(), R.drawable.ic_block_tinted_24).apply {
colorFilter = PorterDuffColorFilter(alertTint, PorterDuff.Mode.SRC_IN)
}
}
private val unblockIcon by lazy {
ContextUtil.requireDrawable(requireContext(), R.drawable.ic_block_tinted_24)
}
private val leaveIcon by lazy {
ContextUtil.requireDrawable(requireContext(), R.drawable.ic_leave_tinted_24).apply {
colorFilter = PorterDuffColorFilter(alertTint, PorterDuff.Mode.SRC_IN)
}
}
private val viewModel by viewModels<ConversationSettingsViewModel>(
factoryProducer = {
val args = ConversationSettingsFragmentArgs.fromBundle(requireArguments())
val groupId = args.groupId as? ParcelableGroupId
ConversationSettingsViewModel.Factory(
recipientId = args.recipientId,
groupId = ParcelableGroupId.get(groupId),
repository = ConversationSettingsRepository(requireContext())
)
}
)
private lateinit var callback: Callback
private lateinit var toolbar: Toolbar
private lateinit var toolbarAvatarContainer: FrameLayout
private lateinit var toolbarAvatar: AvatarImageView
private lateinit var toolbarBadge: BadgeImageView
private lateinit var toolbarTitle: TextView
private lateinit var toolbarBackground: View
private val navController get() = Navigation.findNavController(requireView())
override fun onAttach(context: Context) {
super.onAttach(context)
callback = context as Callback
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
toolbar = view.findViewById(R.id.toolbar)
toolbarAvatarContainer = view.findViewById(R.id.toolbar_avatar_container)
toolbarAvatar = view.findViewById(R.id.toolbar_avatar)
toolbarBadge = view.findViewById(R.id.toolbar_badge)
toolbarTitle = view.findViewById(R.id.toolbar_title)
toolbarBackground = view.findViewById(R.id.toolbar_background)
val args: ConversationSettingsFragmentArgs = ConversationSettingsFragmentArgs.fromBundle(requireArguments())
if (args.recipientId != null) {
layoutManagerProducer = Badges::createLayoutManagerForGridWithBadges
}
super.onViewCreated(view, savedInstanceState)
recyclerView?.addOnScrollListener(ConversationSettingsOnUserScrolledAnimationHelper(toolbarAvatarContainer, toolbarTitle, toolbarBackground))
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
REQUEST_CODE_ADD_MEMBERS_TO_GROUP -> if (data != null) {
val selected: List<RecipientId> = requireNotNull(data.getParcelableArrayListExtra(PushContactSelectionActivity.KEY_SELECTED_RECIPIENTS))
val progress: SimpleProgressDialog.DismissibleDialog = SimpleProgressDialog.showDelayed(requireContext())
viewModel.onAddToGroupComplete(selected) {
progress.dismiss()
}
}
REQUEST_CODE_RETURN_FROM_MEDIA -> viewModel.refreshSharedMedia()
REQUEST_CODE_ADD_CONTACT -> viewModel.refreshRecipient()
REQUEST_CODE_VIEW_CONTACT -> viewModel.refreshRecipient()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return if (item.itemId == R.id.action_edit) {
val args = ConversationSettingsFragmentArgs.fromBundle(requireArguments())
val groupId = args.groupId as ParcelableGroupId
startActivity(EditProfileActivity.getIntentForGroupProfile(requireActivity(), requireNotNull(ParcelableGroupId.get(groupId))))
true
} else {
super.onOptionsItemSelected(item)
}
}
override fun getMaterial3OnScrollHelper(toolbar: Toolbar?): Material3OnScrollHelper {
return object : Material3OnScrollHelper(requireActivity(), toolbar!!) {
override val inactiveColorSet = ColorSet(
toolbarColorRes = R.color.signal_colorBackground_0,
statusBarColorRes = R.color.signal_colorBackground
)
}
}
override fun bindAdapter(adapter: MappingAdapter) {
val args = ConversationSettingsFragmentArgs.fromBundle(requireArguments())
BioTextPreference.register(adapter)
AvatarPreference.register(adapter)
ButtonStripPreference.register(adapter)
LargeIconClickPreference.register(adapter)
SharedMediaPreference.register(adapter)
RecipientPreference.register(adapter)
InternalPreference.register(adapter)
GroupDescriptionPreference.register(adapter)
LegacyGroupPreference.register(adapter)
val recipientId = args.recipientId
if (recipientId != null) {
Badge.register(adapter) { badge, _, _ ->
ViewBadgeBottomSheetDialogFragment.show(parentFragmentManager, recipientId, badge)
}
}
viewModel.state.observe(viewLifecycleOwner) { state ->
if (state.recipient != Recipient.UNKNOWN) {
toolbarAvatar.buildOptions()
.withQuickContactEnabled(false)
.withUseSelfProfileAvatar(false)
.withFixedSize(ViewUtil.dpToPx(80))
.load(state.recipient)
if (!state.recipient.isSelf) {
toolbarBadge.setBadgeFromRecipient(state.recipient)
}
state.withRecipientSettingsState {
toolbarTitle.text = if (state.recipient.isSelf) getString(R.string.note_to_self) else state.recipient.getDisplayName(requireContext())
}
state.withGroupSettingsState {
toolbarTitle.text = it.groupTitle
toolbar.menu.findItem(R.id.action_edit).isVisible = it.canEditGroupAttributes
}
}
adapter.submitList(getConfiguration(state).toMappingModelList()) {
if (state.isLoaded) {
(view?.parent as? ViewGroup)?.doOnPreDraw {
callback.onContentWillRender()
}
}
}
}
viewModel.events.observe(viewLifecycleOwner) { event ->
@Exhaustive
when (event) {
is ConversationSettingsEvent.AddToAGroup -> handleAddToAGroup(event)
is ConversationSettingsEvent.AddMembersToGroup -> handleAddMembersToGroup(event)
ConversationSettingsEvent.ShowGroupHardLimitDialog -> showGroupHardLimitDialog()
is ConversationSettingsEvent.ShowAddMembersToGroupError -> showAddMembersToGroupError(event)
is ConversationSettingsEvent.ShowGroupInvitesSentDialog -> showGroupInvitesSentDialog(event)
is ConversationSettingsEvent.ShowMembersAdded -> showMembersAdded(event)
is ConversationSettingsEvent.InitiateGroupMigration -> GroupsV1MigrationInitiationBottomSheetDialogFragment.showForInitiation(parentFragmentManager, event.recipientId)
}
}
}
private fun getConfiguration(state: ConversationSettingsState): DSLConfiguration {
return configure {
if (state.recipient == Recipient.UNKNOWN) {
return@configure
}
customPref(
AvatarPreference.Model(
recipient = state.recipient,
storyViewState = state.storyViewState,
onAvatarClick = { avatar ->
val viewAvatarIntent = AvatarPreviewActivity.intentFromRecipientId(requireContext(), state.recipient.id)
val viewAvatarTransitionBundle = AvatarPreviewActivity.createTransitionBundle(requireActivity(), avatar)
if (Stories.isFeatureEnabled() && avatar.hasStory()) {
val viewStoryIntent = StoryViewerActivity.createIntent(
requireContext(),
StoryViewerArgs(
recipientId = state.recipient.id,
isInHiddenStoryMode = state.recipient.shouldHideStory(),
isFromQuote = true
)
)
StoryDialogs.displayStoryOrProfileImage(
context = requireContext(),
onViewStory = { startActivity(viewStoryIntent) },
onViewAvatar = { startActivity(viewAvatarIntent, viewAvatarTransitionBundle) }
)
} else if (!state.recipient.isSelf) {
startActivity(viewAvatarIntent, viewAvatarTransitionBundle)
}
},
onBadgeClick = { badge ->
ViewBadgeBottomSheetDialogFragment.show(parentFragmentManager, state.recipient.id, badge)
}
)
)
state.withRecipientSettingsState {
customPref(BioTextPreference.RecipientModel(recipient = state.recipient))
}
state.withGroupSettingsState { groupState ->
val groupMembershipDescription = if (groupState.groupId.isV1) {
String.format("%s · %s", groupState.membershipCountDescription, getString(R.string.ManageGroupActivity_legacy_group))
} else if (!groupState.canEditGroupAttributes && groupState.groupDescription.isNullOrEmpty()) {
groupState.membershipCountDescription
} else {
null
}
customPref(
BioTextPreference.GroupModel(
groupTitle = groupState.groupTitle,
groupMembershipDescription = groupMembershipDescription
)
)
if (groupState.groupId.isV2) {
customPref(
GroupDescriptionPreference.Model(
groupId = groupState.groupId,
groupDescription = groupState.groupDescription,
descriptionShouldLinkify = groupState.groupDescriptionShouldLinkify,
canEditGroupAttributes = groupState.canEditGroupAttributes,
onEditGroupDescription = {
startActivity(EditProfileActivity.getIntentForGroupProfile(requireActivity(), groupState.groupId))
},
onViewGroupDescription = {
GroupDescriptionDialog.show(childFragmentManager, groupState.groupId, null, groupState.groupDescriptionShouldLinkify)
}
)
)
} else if (groupState.legacyGroupState != LegacyGroupPreference.State.NONE) {
customPref(
LegacyGroupPreference.Model(
state = groupState.legacyGroupState,
onLearnMoreClick = { GroupsLearnMoreBottomSheetDialogFragment.show(parentFragmentManager) },
onUpgradeClick = { viewModel.initiateGroupUpgrade() },
onMmsWarningClick = { startActivity(Intent(requireContext(), InviteActivity::class.java)) }
)
)
}
}
if (state.displayInternalRecipientDetails) {
customPref(
InternalPreference.Model(
recipient = state.recipient,
onInternalDetailsClicked = {
val action = ConversationSettingsFragmentDirections.actionConversationSettingsFragmentToInternalDetailsSettingsFragment(state.recipient.id)
navController.safeNavigate(action)
}
)
)
}
customPref(
ButtonStripPreference.Model(
state = state.buttonStripState,
onVideoClick = {
if (state.recipient.isPushV2Group && state.requireGroupSettingsState().isAnnouncementGroup && !state.requireGroupSettingsState().isSelfAdmin) {
MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.ConversationActivity_cant_start_group_call)
.setMessage(R.string.ConversationActivity_only_admins_of_this_group_can_start_a_call)
.setPositiveButton(android.R.string.ok) { d, _ -> d.dismiss() }
.show()
} else {
CommunicationActions.startVideoCall(requireActivity(), state.recipient)
}
},
onAudioClick = {
CommunicationActions.startVoiceCall(requireActivity(), state.recipient)
},
onMuteClick = {
if (!state.buttonStripState.isMuted) {
MuteDialog.show(requireContext(), viewModel::setMuteUntil)
} else {
MaterialAlertDialogBuilder(requireContext())
.setMessage(state.recipient.muteUntil.formatMutedUntil(requireContext()))
.setPositiveButton(R.string.ConversationSettingsFragment__unmute) { dialog, _ ->
viewModel.unmute()
dialog.dismiss()
}
.setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() }
.show()
}
},
onSearchClick = {
val intent = ConversationIntents.createBuilder(requireContext(), state.recipient.id, state.threadId)
.withSearchOpen(true)
.build()
startActivity(intent)
requireActivity().finish()
}
)
)
dividerPref()
val summary = DSLSettingsText.from(formatDisappearingMessagesLifespan(state.disappearingMessagesLifespan))
val icon = if (state.disappearingMessagesLifespan <= 0 || state.recipient.isBlocked) {
R.drawable.ic_update_timer_disabled_16
} else {
R.drawable.ic_update_timer_16
}
var enabled = !state.recipient.isBlocked
state.withGroupSettingsState {
enabled = it.canEditGroupAttributes && !state.recipient.isBlocked
}
if (!state.recipient.isReleaseNotes && !state.recipient.isBlocked) {
clickPref(
title = DSLSettingsText.from(R.string.ConversationSettingsFragment__disappearing_messages),
summary = summary,
icon = DSLSettingsIcon.from(icon),
isEnabled = enabled,
onClick = {
val action = ConversationSettingsFragmentDirections.actionConversationSettingsFragmentToAppSettingsExpireTimer()
.setInitialValue(state.disappearingMessagesLifespan)
.setRecipientId(state.recipient.id)
.setForResultMode(false)
navController.safeNavigate(action)
}
)
}
if (!state.recipient.isReleaseNotes) {
clickPref(
title = DSLSettingsText.from(R.string.preferences__chat_color_and_wallpaper),
icon = DSLSettingsIcon.from(R.drawable.ic_color_24),
onClick = {
startActivity(ChatWallpaperActivity.createIntent(requireContext(), state.recipient.id))
}
)
}
if (!state.recipient.isSelf) {
clickPref(
title = DSLSettingsText.from(R.string.ConversationSettingsFragment__sounds_and_notifications),
icon = DSLSettingsIcon.from(R.drawable.ic_speaker_24),
onClick = {
val action = ConversationSettingsFragmentDirections.actionConversationSettingsFragmentToSoundsAndNotificationsSettingsFragment(state.recipient.id)
navController.safeNavigate(action)
}
)
}
state.withRecipientSettingsState { recipientState ->
when (recipientState.contactLinkState) {
ContactLinkState.OPEN -> {
@Suppress("DEPRECATION")
clickPref(
title = DSLSettingsText.from(R.string.ConversationSettingsFragment__contact_details),
icon = DSLSettingsIcon.from(R.drawable.ic_profile_circle_24),
onClick = {
startActivityForResult(Intent(Intent.ACTION_VIEW, state.recipient.contactUri), REQUEST_CODE_VIEW_CONTACT)
}
)
}
ContactLinkState.ADD -> {
@Suppress("DEPRECATION")
clickPref(
title = DSLSettingsText.from(R.string.ConversationSettingsFragment__add_as_a_contact),
icon = DSLSettingsIcon.from(R.drawable.ic_plus_24),
onClick = {
try {
startActivityForResult(RecipientExporter.export(state.recipient).asAddContactIntent(), REQUEST_CODE_ADD_CONTACT)
} catch (e: ActivityNotFoundException) {
Toast.makeText(context, R.string.ConversationSettingsFragment__contacts_app_not_found, Toast.LENGTH_SHORT).show()
}
}
)
}
ContactLinkState.NONE -> {
}
}
if (recipientState.identityRecord != null) {
clickPref(
title = DSLSettingsText.from(R.string.ConversationSettingsFragment__view_safety_number),
icon = DSLSettingsIcon.from(R.drawable.ic_safety_number_24),
onClick = {
startActivity(VerifyIdentityActivity.newIntent(requireActivity(), recipientState.identityRecord))
}
)
}
}
if (state.sharedMedia != null && state.sharedMedia.count > 0) {
dividerPref()
sectionHeaderPref(R.string.recipient_preference_activity__shared_media)
@Suppress("DEPRECATION")
customPref(
SharedMediaPreference.Model(
mediaCursor = state.sharedMedia,
mediaIds = state.sharedMediaIds,
onMediaRecordClick = { mediaRecord, isLtr ->
startActivityForResult(
MediaIntentFactory.intentFromMediaRecord(requireContext(), mediaRecord, isLtr, allMediaInRail = true),
REQUEST_CODE_RETURN_FROM_MEDIA
)
}
)
)
clickPref(
title = DSLSettingsText.from(R.string.ConversationSettingsFragment__see_all),
onClick = {
startActivity(MediaOverviewActivity.forThread(requireContext(), state.threadId))
}
)
}
state.withRecipientSettingsState { recipientSettingsState ->
if (state.recipient.badges.isNotEmpty()) {
dividerPref()
sectionHeaderPref(R.string.ManageProfileFragment_badges)
displayBadges(requireContext(), state.recipient.badges)
textPref(
summary = DSLSettingsText.from(
R.string.ConversationSettingsFragment__get_badges
)
)
}
if (recipientSettingsState.selfHasGroups && !state.recipient.isReleaseNotes) {
dividerPref()
val groupsInCommonCount = recipientSettingsState.allGroupsInCommon.size
sectionHeaderPref(
DSLSettingsText.from(
if (groupsInCommonCount == 0) {
getString(R.string.ManageRecipientActivity_no_groups_in_common)
} else {
resources.getQuantityString(
R.plurals.ManageRecipientActivity_d_groups_in_common,
groupsInCommonCount,
groupsInCommonCount
)
}
)
)
if (!state.recipient.isBlocked) {
customPref(
LargeIconClickPreference.Model(
title = DSLSettingsText.from(R.string.ConversationSettingsFragment__add_to_a_group),
icon = DSLSettingsIcon.from(R.drawable.add_to_a_group, NO_TINT),
onClick = {
viewModel.onAddToGroup()
}
)
)
}
for (group in recipientSettingsState.groupsInCommon) {
customPref(
RecipientPreference.Model(
recipient = group,
onClick = {
CommunicationActions.startConversation(requireActivity(), group, null)
requireActivity().finish()
}
)
)
}
if (recipientSettingsState.canShowMoreGroupsInCommon) {
customPref(
LargeIconClickPreference.Model(
title = DSLSettingsText.from(R.string.ConversationSettingsFragment__see_all),
icon = DSLSettingsIcon.from(R.drawable.show_more, NO_TINT),
onClick = {
viewModel.revealAllMembers()
}
)
)
}
}
}
state.withGroupSettingsState { groupState ->
val memberCount = groupState.allMembers.size
if (groupState.canAddToGroup || memberCount > 0) {
dividerPref()
sectionHeaderPref(DSLSettingsText.from(resources.getQuantityString(R.plurals.ContactSelectionListFragment_d_members, memberCount, memberCount)))
}
if (groupState.canAddToGroup) {
customPref(
LargeIconClickPreference.Model(
title = DSLSettingsText.from(R.string.ConversationSettingsFragment__add_members),
icon = DSLSettingsIcon.from(R.drawable.add_to_a_group, NO_TINT),
onClick = {
viewModel.onAddToGroup()
}
)
)
}
for (member in groupState.members) {
customPref(
RecipientPreference.Model(
recipient = member.member,
isAdmin = member.isAdmin,
onClick = {
RecipientBottomSheetDialogFragment.create(member.member.id, groupState.groupId).show(parentFragmentManager, "BOTTOM")
}
)
)
}
if (groupState.canShowMoreGroupMembers) {
customPref(
LargeIconClickPreference.Model(
title = DSLSettingsText.from(R.string.ConversationSettingsFragment__see_all),
icon = DSLSettingsIcon.from(R.drawable.show_more, NO_TINT),
onClick = {
viewModel.revealAllMembers()
}
)
)
}
if (state.recipient.isPushV2Group) {
dividerPref()
clickPref(
title = DSLSettingsText.from(R.string.ConversationSettingsFragment__group_link),
summary = DSLSettingsText.from(if (groupState.groupLinkEnabled) R.string.preferences_on else R.string.preferences_off),
icon = DSLSettingsIcon.from(R.drawable.ic_link_16),
onClick = {
navController.safeNavigate(ConversationSettingsFragmentDirections.actionConversationSettingsFragmentToShareableGroupLinkFragment(groupState.groupId.requireV2().toString()))
}
)
clickPref(
title = DSLSettingsText.from(R.string.ConversationSettingsFragment__requests_and_invites),
icon = DSLSettingsIcon.from(R.drawable.ic_update_group_add_16),
onClick = {
startActivity(ManagePendingAndRequestingMembersActivity.newIntent(requireContext(), groupState.groupId.requireV2()))
}
)
if (groupState.isSelfAdmin) {
clickPref(
title = DSLSettingsText.from(R.string.ConversationSettingsFragment__permissions),
icon = DSLSettingsIcon.from(R.drawable.ic_lock_24),
onClick = {
val action = ConversationSettingsFragmentDirections.actionConversationSettingsFragmentToPermissionsSettingsFragment(ParcelableGroupId.from(groupState.groupId))
navController.safeNavigate(action)
}
)
}
}
if (groupState.canLeave) {
dividerPref()
clickPref(
title = DSLSettingsText.from(R.string.conversation__menu_leave_group, alertTint),
icon = DSLSettingsIcon.from(leaveIcon),
onClick = {
LeaveGroupDialog.handleLeavePushGroup(requireActivity(), groupState.groupId.requirePush(), null)
}
)
}
}
if (state.canModifyBlockedState) {
state.withRecipientSettingsState {
dividerPref()
}
state.withGroupSettingsState {
if (!it.canLeave) {
dividerPref()
}
}
val isBlocked = state.recipient.isBlocked
val isGroup = state.recipient.isPushGroup
val title = when {
isBlocked && isGroup -> R.string.ConversationSettingsFragment__unblock_group
isBlocked -> R.string.ConversationSettingsFragment__unblock
isGroup -> R.string.ConversationSettingsFragment__block_group
else -> R.string.ConversationSettingsFragment__block
}
val titleTint = if (isBlocked) null else alertTint
val blockUnblockIcon = if (isBlocked) unblockIcon else blockIcon
clickPref(
title = if (titleTint != null) DSLSettingsText.from(title, titleTint) else DSLSettingsText.from(title),
icon = DSLSettingsIcon.from(blockUnblockIcon),
onClick = {
if (state.recipient.isBlocked) {
BlockUnblockDialog.showUnblockFor(requireContext(), viewLifecycleOwner.lifecycle, state.recipient) {
viewModel.unblock()
}
} else {
BlockUnblockDialog.showBlockFor(requireContext(), viewLifecycleOwner.lifecycle, state.recipient) {
viewModel.block()
}
}
}
)
}
}
}
private fun formatDisappearingMessagesLifespan(disappearingMessagesLifespan: Int): String {
return if (disappearingMessagesLifespan <= 0) {
getString(R.string.preferences_off)
} else {
ExpirationUtil.getExpirationDisplayValue(requireContext(), disappearingMessagesLifespan)
}
}
private fun handleAddToAGroup(addToAGroup: ConversationSettingsEvent.AddToAGroup) {
startActivity(AddToGroupsActivity.newIntent(requireContext(), addToAGroup.recipientId, addToAGroup.groupMembership))
}
@Suppress("DEPRECATION")
private fun handleAddMembersToGroup(addMembersToGroup: ConversationSettingsEvent.AddMembersToGroup) {
startActivityForResult(
AddMembersActivity.createIntent(
requireContext(),
addMembersToGroup.groupId,
ContactsCursorLoader.DisplayMode.FLAG_PUSH,
addMembersToGroup.selectionWarning,
addMembersToGroup.selectionLimit,
addMembersToGroup.isAnnouncementGroup,
addMembersToGroup.groupMembersWithoutSelf
),
REQUEST_CODE_ADD_MEMBERS_TO_GROUP
)
}
private fun showGroupHardLimitDialog() {
GroupLimitDialog.showHardLimitMessage(requireContext())
}
private fun showAddMembersToGroupError(showAddMembersToGroupError: ConversationSettingsEvent.ShowAddMembersToGroupError) {
Toast.makeText(requireContext(), GroupErrors.getUserDisplayMessage(showAddMembersToGroupError.failureReason), Toast.LENGTH_LONG).show()
}
private fun showGroupInvitesSentDialog(showGroupInvitesSentDialog: ConversationSettingsEvent.ShowGroupInvitesSentDialog) {
GroupInviteSentDialog.showInvitesSent(requireContext(), viewLifecycleOwner, showGroupInvitesSentDialog.invitesSentTo)
}
private fun showMembersAdded(showMembersAdded: ConversationSettingsEvent.ShowMembersAdded) {
val string = resources.getQuantityString(
R.plurals.ManageGroupActivity_added,
showMembersAdded.membersAddedCount,
showMembersAdded.membersAddedCount
)
Snackbar.make(requireView(), string, Snackbar.LENGTH_SHORT).show()
}
private class ConversationSettingsOnUserScrolledAnimationHelper(
private val toolbarAvatar: View,
private val toolbarTitle: View,
private val toolbarBackground: View
) : OnScrollAnimationHelper() {
override val duration: Long = 200L
private val actionBarSize = DimensionUnit.DP.toPixels(64f)
private val rect = Rect()
override fun getAnimationState(recyclerView: RecyclerView): AnimationState {
val layoutManager = recyclerView.layoutManager!!
val firstVisibleItemPosition = if (layoutManager is FlexboxLayoutManager) {
layoutManager.findFirstVisibleItemPosition()
} else {
(layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
}
return if (firstVisibleItemPosition == 0) {
val firstChild = requireNotNull(layoutManager.getChildAt(0))
firstChild.getLocalVisibleRect(rect)
if (rect.height() <= actionBarSize) {
AnimationState.SHOW
} else {
AnimationState.HIDE
}
} else {
AnimationState.SHOW
}
}
override fun show(duration: Long) {
toolbarAvatar
.animate()
.setDuration(duration)
.translationY(0f)
.alpha(1f)
toolbarTitle
.animate()
.setDuration(duration)
.translationY(0f)
.alpha(1f)
toolbarBackground
.animate()
.setDuration(duration)
.alpha(1f)
}
override fun hide(duration: Long) {
toolbarAvatar
.animate()
.setDuration(duration)
.translationY(ViewUtil.dpToPx(56).toFloat())
.alpha(0f)
toolbarTitle
.animate()
.setDuration(duration)
.translationY(ViewUtil.dpToPx(56).toFloat())
.alpha(0f)
toolbarBackground
.animate()
.setDuration(duration)
.alpha(0f)
}
}
interface Callback {
fun onContentWillRender()
}
}
|
gpl-3.0
|
b639c485d11df84c0e3d4b67bb26cc4c
| 39.167247 | 186 | 0.689105 | 5.340334 | false | false | false | false |
androidx/androidx
|
compose/foundation/foundation/samples/src/main/java/androidx/compose/foundation/samples/SelectableSamples.kt
|
3
|
2063
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.selection.selectable
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Sampled
@Composable
fun SelectableSample() {
val option1 = Color.Red
val option2 = Color.Blue
var selectedOption by remember { mutableStateOf(option1) }
Column {
Text("Selected: $selectedOption")
Row {
listOf(option1, option2).forEach { color ->
val selected = selectedOption == color
Box(
Modifier
.size(100.dp)
.background(color = color)
.selectable(
selected = selected,
onClick = { selectedOption = color }
)
)
}
}
}
}
|
apache-2.0
|
dd976d19633b9744e2c197926af536d2
| 33.983051 | 75 | 0.682501 | 4.710046 | false | false | false | false |
cat-in-the-dark/GamesServer
|
lib-shared/src/main/kotlin/org/catinthedark/shared/invokers/TickInvoker.kt
|
1
|
4048
|
package org.catinthedark.shared.invokers
import org.slf4j.LoggerFactory
import java.util.concurrent.locks.ReadWriteLock
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.withLock
/**
* This kind of invoker runs in a single thread but do not use some schedulers.
* Instead, it receives time ticks and handleы the timeouts, defers and so on.
* It should be used in UI systems, because this kind of systems always
* have it's own inner eventloop.
* It would be better to reuse loop instead of threading.
*
* This invoker is thread safe.
* So you can put events from any thread.
*/
class TickInvoker : DeferrableInvoker {
private val log = LoggerFactory.getLogger(this::class.java)
private var time: Long = 0L
private val queue: MutableList<Holder> = mutableListOf()
private val lock: ReadWriteLock = ReentrantReadWriteLock()
/**
* Call this method in the event loop on every loop.
* Receives [delta] in ms, for example, to calculate system time for timed events.
* This call invokes all queued funcs that must be run at this time.
*/
fun run(delta: Long) {
lock.writeLock().withLock {
time += delta
processDefer()
processPeriodic()
}
}
private fun processDefer() {
queue.filterNot {
it.isPeriodic
}.filter {
it.nextCallTime <= time
}.apply {
forEach { it.func() }
queue.removeAll(this)
}
}
private fun processPeriodic() {
queue.filter {
it.isPeriodic
}.filter {
it.nextCallTime <= time
}.forEach {
it.func()
it.next()
}
}
/**
* Puts an [func] to the queue which will be called on next [run] call.
* [invoke] will never call the event at the moment of time when it is called.
* Literally say, [invoke] is the synonym for [defer] with ZERO delay.
*/
override fun invoke(func: () -> Unit) {
lock.writeLock().withLock {
queue.add(Holder(0L, func, false))
}
}
/**
* Cancels all funcs in the [queue] and reset the [time].
*/
override fun shutdown() {
lock.writeLock().withLock {
queue.clear()
time = 0L
}
}
/**
* Puts an [func] to queue that will be called after timeout in ms.
* Event will be never called earlier then [time]+[timeout],
* but might be called later.
*
* You can cancel the event before it'll be called by invoking the callback
*/
override fun defer(func: () -> Unit, timeout: Long): () -> Unit {
lock.writeLock().withLock {
with(Holder(timeout, func, false)) {
queue.add(this)
return cancelBuilder(this)
}
}
}
/**
* Works like the [defer] method
* but [func] will be called every [timeout] in ms until it is canceled.
*
* You can cancel the [func] by invoking the returned callback.
*/
override fun periodic(func: () -> Unit, timeout: Long): () -> Unit {
lock.writeLock().withLock {
with(Holder(timeout, func, true)) {
queue.add(this)
return cancelBuilder(this)
}
}
}
private fun cancelBuilder(holder: Holder): () -> Unit {
return {
if (!queue.remove(holder)) {
log.warn("Can't cancel call $holder because it has been already invoked.")
}
}
}
private inner class Holder(val timeout: Long, val func: () -> Unit, val isPeriodic: Boolean = false) {
var nextCallTime: Long = time + timeout
private set
fun next(): Holder {
nextCallTime += timeout
return this
}
override fun toString(): String {
return "Holder(timeout=$timeout, isPeriodic=$isPeriodic, nextCallTime=$nextCallTime, currentTime=$time)"
}
}
}
|
mit
|
a1754aaed187b636913254e5848fcc5f
| 28.985185 | 116 | 0.581665 | 4.4375 | false | false | false | false |
pedroSG94/rtmp-rtsp-stream-client-java
|
rtmp/src/main/java/com/pedro/rtmp/rtmp/RtmpSender.kt
|
1
|
6198
|
/*
* Copyright (C) 2021 pedroSG94.
*
* 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.pedro.rtmp.rtmp
import android.media.MediaCodec
import android.util.Log
import com.pedro.rtmp.flv.FlvPacket
import com.pedro.rtmp.flv.FlvType
import com.pedro.rtmp.flv.audio.AacPacket
import com.pedro.rtmp.flv.audio.AudioPacketCallback
import com.pedro.rtmp.flv.video.H264Packet
import com.pedro.rtmp.flv.video.ProfileIop
import com.pedro.rtmp.flv.video.VideoPacketCallback
import com.pedro.rtmp.utils.BitrateManager
import com.pedro.rtmp.utils.ConnectCheckerRtmp
import com.pedro.rtmp.utils.socket.RtmpSocket
import java.nio.ByteBuffer
import java.util.concurrent.*
/**
* Created by pedro on 8/04/21.
*/
class RtmpSender(private val connectCheckerRtmp: ConnectCheckerRtmp,
private val commandsManager: CommandsManager) : AudioPacketCallback, VideoPacketCallback {
private var aacPacket = AacPacket(this)
private var h264Packet = H264Packet(this)
@Volatile
private var running = false
@Volatile
private var flvPacketBlockingQueue: BlockingQueue<FlvPacket> = LinkedBlockingQueue(60)
private var thread: ExecutorService? = null
private var audioFramesSent: Long = 0
private var videoFramesSent: Long = 0
var socket: RtmpSocket? = null
var droppedAudioFrames: Long = 0
private set
var droppedVideoFrames: Long = 0
private set
private val bitrateManager: BitrateManager = BitrateManager(connectCheckerRtmp)
private var isEnableLogs = true
companion object {
private const val TAG = "RtmpSender"
}
fun setVideoInfo(sps: ByteBuffer, pps: ByteBuffer, vps: ByteBuffer?) {
h264Packet.sendVideoInfo(sps, pps)
}
fun setProfileIop(profileIop: ProfileIop) {
h264Packet.profileIop = profileIop
}
fun setAudioInfo(sampleRate: Int, isStereo: Boolean) {
aacPacket.sendAudioInfo(sampleRate, isStereo)
}
fun sendVideoFrame(h264Buffer: ByteBuffer, info: MediaCodec.BufferInfo) {
if (running) h264Packet.createFlvVideoPacket(h264Buffer, info)
}
fun sendAudioFrame(aacBuffer: ByteBuffer, info: MediaCodec.BufferInfo) {
if (running) aacPacket.createFlvAudioPacket(aacBuffer, info)
}
override fun onVideoFrameCreated(flvPacket: FlvPacket) {
try {
flvPacketBlockingQueue.add(flvPacket)
} catch (e: IllegalStateException) {
Log.i(TAG, "Video frame discarded")
droppedVideoFrames++
}
}
override fun onAudioFrameCreated(flvPacket: FlvPacket) {
try {
flvPacketBlockingQueue.add(flvPacket)
} catch (e: IllegalStateException) {
Log.i(TAG, "Audio frame discarded")
droppedAudioFrames++
}
}
fun start() {
thread = Executors.newSingleThreadExecutor()
running = true
thread?.execute post@{
while (!Thread.interrupted() && running) {
try {
val flvPacket = flvPacketBlockingQueue.poll(1, TimeUnit.SECONDS)
if (flvPacket == null) {
Log.i(TAG, "Skipping iteration, frame null")
continue
}
var size = 0
if (flvPacket.type == FlvType.VIDEO) {
videoFramesSent++
socket?.let { socket ->
size = commandsManager.sendVideoPacket(flvPacket, socket)
if (isEnableLogs) {
Log.i(TAG, "wrote Video packet, size $size")
}
}
} else {
audioFramesSent++
socket?.let { socket ->
size = commandsManager.sendAudioPacket(flvPacket, socket)
if (isEnableLogs) {
Log.i(TAG, "wrote Audio packet, size $size")
}
}
}
//bytes to bits
bitrateManager.calculateBitrate(size * 8L)
} catch (e: Exception) {
//InterruptedException is only when you disconnect manually, you don't need report it.
if (e !is InterruptedException && running) {
connectCheckerRtmp.onConnectionFailedRtmp("Error send packet, " + e.message)
Log.e(TAG, "send error: ", e)
}
return@post
}
}
}
}
fun stop(clear: Boolean = true) {
running = false
thread?.shutdownNow()
try {
thread?.awaitTermination(100, TimeUnit.MILLISECONDS)
} catch (e: InterruptedException) { }
thread = null
flvPacketBlockingQueue.clear()
aacPacket.reset()
h264Packet.reset(clear)
resetSentAudioFrames()
resetSentVideoFrames()
resetDroppedAudioFrames()
resetDroppedVideoFrames()
}
fun hasCongestion(): Boolean {
val size = flvPacketBlockingQueue.size.toFloat()
val remaining = flvPacketBlockingQueue.remainingCapacity().toFloat()
val capacity = size + remaining
return size >= capacity * 0.2f //more than 20% queue used. You could have congestion
}
fun resizeCache(newSize: Int) {
if (newSize < flvPacketBlockingQueue.size - flvPacketBlockingQueue.remainingCapacity()) {
throw RuntimeException("Can't fit current cache inside new cache size")
}
val tempQueue: BlockingQueue<FlvPacket> = LinkedBlockingQueue(newSize)
flvPacketBlockingQueue.drainTo(tempQueue)
flvPacketBlockingQueue = tempQueue
}
fun getCacheSize(): Int {
return flvPacketBlockingQueue.size
}
fun getSentAudioFrames(): Long {
return audioFramesSent
}
fun getSentVideoFrames(): Long {
return videoFramesSent
}
fun resetSentAudioFrames() {
audioFramesSent = 0
}
fun resetSentVideoFrames() {
videoFramesSent = 0
}
fun resetDroppedAudioFrames() {
droppedAudioFrames = 0
}
fun resetDroppedVideoFrames() {
droppedVideoFrames = 0
}
fun setLogs(enable: Boolean) {
isEnableLogs = enable
}
}
|
apache-2.0
|
200cffb1d708a4e3d606d8ef2d30e398
| 29.092233 | 96 | 0.685544 | 4.322176 | false | false | false | false |
andstatus/andstatus
|
app/src/main/kotlin/org/andstatus/app/account/AccountSettingsFragment.kt
|
1
|
3827
|
/*
* Copyright (C) 2014 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.AccountManager
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import org.andstatus.app.ActivityRequestCode
import org.andstatus.app.R
import org.andstatus.app.account.AccountSettingsActivity.FragmentAction
import org.andstatus.app.os.NonUiThreadExecutor
import org.andstatus.app.os.UiThreadExecutor
import org.andstatus.app.util.MyLog
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
class AccountSettingsFragment : Fragment() {
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (ActivityRequestCode.fromId(requestCode)) {
ActivityRequestCode.REMOVE_ACCOUNT -> if (Activity.RESULT_OK == resultCode) {
onRemoveAccount()
}
else -> super.onActivityResult(requestCode, resultCode, data)
}
}
private fun onRemoveAccount() {
val accountSettingsActivity = activity as AccountSettingsActivity?
val state = accountSettingsActivity?.state
if (state?.builder != null && state.builder.isPersistent()) {
for (account in AccountUtils.getCurrentAccounts(accountSettingsActivity)) {
if (state.myAccount.getAccountName() == account.name) {
MyLog.i(this, "Removing account: " + account.name)
val am = AccountManager.get(activity)
CompletableFuture.supplyAsync({
try {
val result = am.removeAccount(account, activity, null, null)
.getResult(10, TimeUnit.SECONDS)
return@supplyAsync result != null && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)
} catch (e: Exception) {
MyLog.w(this, "Failed to remove account " + account.name, e)
return@supplyAsync false
}
}, NonUiThreadExecutor.INSTANCE)
.thenAcceptAsync({ ok: Boolean ->
if (ok) {
activity?.finish()
}
}, UiThreadExecutor.INSTANCE)
break
}
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.account_settings, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
val activity = activity as AccountSettingsActivity?
if (activity != null) {
activity.updateScreen()
when (FragmentAction.fromBundle(arguments)) {
FragmentAction.ON_ORIGIN_SELECTED -> activity.goToAddAccount()
else -> {
}
}
}
super.onActivityCreated(savedInstanceState)
}
}
|
apache-2.0
|
662445c853cdb4d1b1d548ae9c81f65b
| 41.054945 | 117 | 0.622942 | 5.171622 | false | false | false | false |
TCA-Team/TumCampusApp
|
app/src/main/java/de/tum/in/tumcampusapp/service/GeofencingRegistrationService.kt
|
1
|
3401
|
package de.tum.`in`.tumcampusapp.service
import android.Manifest
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import androidx.core.app.JobIntentService
import androidx.core.content.ContextCompat
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofencingClient
import com.google.android.gms.location.GeofencingRequest
import com.google.android.gms.location.LocationServices
import de.tum.`in`.tumcampusapp.utils.Const
import de.tum.`in`.tumcampusapp.utils.Const.ADD_GEOFENCE_EXTRA
import de.tum.`in`.tumcampusapp.utils.Const.GEOFENCING_SERVICE_JOB_ID
import de.tum.`in`.tumcampusapp.utils.Utils
/**
* Service that receives Geofencing requests and registers them.
*/
class GeofencingRegistrationService : JobIntentService() {
private lateinit var locationClient: GeofencingClient
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
return Service.START_STICKY
}
override fun onCreate() {
super.onCreate()
locationClient = LocationServices.getGeofencingClient(baseContext)
Utils.log("Service started")
}
@SuppressLint("MissingPermission")
override fun onHandleWork(intent: Intent) {
if (!isLocationPermissionGranted()) {
return
}
val request = intent.getParcelableExtra<GeofencingRequest>(Const.ADD_GEOFENCE_EXTRA) ?: return
val geofenceIntent = Intent(this, GeofencingUpdateReceiver::class.java)
val geofencePendingIntent = PendingIntent.getBroadcast(
this, 0, geofenceIntent, PendingIntent.FLAG_UPDATE_CURRENT)
locationClient.addGeofences(request, geofencePendingIntent)
Utils.log("Registered new Geofence")
}
private fun isLocationPermissionGranted(): Boolean {
return ContextCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
}
companion object {
@JvmStatic fun startGeofencing(context: Context, work: Intent) {
enqueueWork(context, GeofencingRegistrationService::class.java, GEOFENCING_SERVICE_JOB_ID, work)
}
/**
* Helper method for creating an intent containing a geofencing request
*/
fun buildGeofence(context: Context, id: String, latitude: Double, longitude: Double, range: Float): Intent {
val intent = Intent(context, GeofencingRegistrationService::class.java)
val geofence = Geofence.Builder()
.setRequestId(id)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(latitude, longitude, range)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build()
val geofencingRequest = GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER or GeofencingRequest.INITIAL_TRIGGER_EXIT)
.addGeofences(arrayListOf(geofence))
.build()
return intent.putExtra(ADD_GEOFENCE_EXTRA, geofencingRequest)
}
}
}
|
gpl-3.0
|
e0a9ea7304c5adab1bfa30f9ab11abf4
| 39.987952 | 121 | 0.707145 | 5.001471 | false | false | false | false |
trife/Field-Book
|
app/src/main/java/com/fieldbook/tracker/activities/DataGridActivity.kt
|
1
|
8799
|
package com.fieldbook.tracker.activities
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.*
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.Group
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.evrencoskun.tableview.TableView
import com.evrencoskun.tableview.listener.ITableViewListener
import com.fieldbook.tracker.R
import com.fieldbook.tracker.adapters.DataGridAdapter
import com.fieldbook.tracker.databinding.ActivityDataGridBinding
import com.fieldbook.tracker.utilities.Utils
import kotlinx.coroutines.*
import java.util.*
/**
* @author Chaney
*
* This activity is available as an optional toolbar action.
* Toolbar can be activated by selecting Preferences/General/Datagrid
*
* Displays a spreadsheet of plots and trait values.
* Traits are shown as static column headers, while plot ids are shown as static row headers.
*
* Users can click on cell data to navigate to that specific plot/trait in the collect activity.
* When a cell is clicked, the activity finishes and returns an intent with data e.g:
* Intent i = Intent()
* i.putExtra("result", plotId)
* i.putExtra("trait", 1) <- actually a trait index s.a 0 -> "height", 1 -> "lodging"
**/
class DataGridActivity : AppCompatActivity(), CoroutineScope by MainScope(), ITableViewListener {
/***
* Polymorphism class structure to serve different cell types to the grid.
*/
open class BlockData(open val code: String) {
override fun hashCode(): Int {
return code.hashCode()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BlockData
if (code != other.code) return false
return true
}
}
data class HeaderData(val name: String, override val code: String) : BlockData(code)
data class CellData(val value: String?, override val code: String, val color: Int = Color.GREEN, val onClick: View.OnClickListener? = null): BlockData(code)
class EmptyCell(override val code: String): BlockData(code)
//coroutine scope for launching background processes
private val scope by lazy {
CoroutineScope(Dispatchers.IO)
}
/**
* views that are initialized in oncreate
*/
private lateinit var mTableView: TableView
private lateinit var progressBar: ProgressBar
private lateinit var dataGridGroup: Group
/**
* Adapters/lists used to store grid information, also used for click events
*/
private lateinit var mAdapter: DataGridAdapter
private lateinit var mPlotIds: ArrayList<String>
private lateinit var mTraits: Array<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//this activity uses databinding to inflate the content layout
//this creates a 'binding' variable that has all the views as fields, an alternative to findViewById
val binding = DataBindingUtil.setContentView<ActivityDataGridBinding>(this, R.layout.activity_data_grid)
setSupportActionBar(binding.toolbar)
if (supportActionBar != null) {
supportActionBar?.title = null
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(true)
}
progressBar = binding.dataGridProgressBar
dataGridGroup = binding.dataGridGroup
mTableView = binding.tableView
//if something goes wrong finish the activity
try {
loadGridData()
} catch (e: Exception) {
e.printStackTrace()
setResult(RESULT_CANCELED)
finish()
}
}
//finish activity when back button is pressed
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
}
}
return super.onOptionsItemSelected(item)
}
/**
* Uses the convertDatabaseToTable query to create a spreadsheet of values.
* Columns returned are plot_id followed by all traits.
*/
private fun loadGridData() {
val ep = getSharedPreferences("Settings", MODE_PRIVATE)
val uniqueName = ep.getString("ImportUniqueName", "") ?: ""
if (uniqueName.isNotBlank()) {
//background processing
scope.launch {
//query database for visible traits
mTraits = ConfigActivity.dt.visibleTrait
//expensive database call, only asks for the unique name plot attr and all visible traits
val cursor = ConfigActivity.dt.convertDatabaseToTable(arrayOf(uniqueName), mTraits)
if (cursor.moveToFirst()) {
mPlotIds = arrayListOf()
val dataMap = arrayListOf<List<CellData>>()
do { //iterate over cursor results and populate lists of plot ids and related trait values
//unique name column is always the first column
val uniqueIndex = cursor.getColumnIndex(cursor.getColumnName(0))
if (uniqueIndex > -1) { //if it doesn't exist skip this row
val plotId = cursor.getString(uniqueIndex)
val dataList = arrayListOf<CellData>()
mPlotIds.add(plotId) //add unique name row header
mTraits.forEachIndexed { _, variable ->
val index = cursor.getColumnIndex(variable)
if (index > -1) {
val value = cursor.getString(index) ?: ""
//data list is a trait row in the data grid
dataList.add(CellData(value, plotId))
}
}
dataMap.add(dataList)
}
} while (cursor.moveToNext())
mAdapter = DataGridAdapter()
runOnUiThread {
mTableView.setHasFixedWidth(true)
mTableView.tableViewListener = this@DataGridActivity
mTableView.isShowHorizontalSeparators = false
mTableView.isShowVerticalSeparators = false
mTableView.setAdapter(mAdapter)
mAdapter.setAllItems(mTraits.map { HeaderData(it, it) },
mPlotIds.map { HeaderData(it, it) },
dataMap.toList())
}
cursor.close() //always remember to close your cursor! :)
//update the ui after background processing ends
runOnUiThread {
dataGridGroup.visibility = View.VISIBLE
progressBar.visibility = View.GONE
}
}
}
}
}
override fun onCellClicked(cellView: RecyclerView.ViewHolder, column: Int, row: Int) {
//populate plotId clicked from parameters and global store
val plotId = mPlotIds[row]
//this is the onlick handler which displays a quick message and sets the intent result / finishes
Utils.makeToast(applicationContext, plotId)
val returnIntent = Intent()
returnIntent.putExtra("result", plotId)
//the trait index is used to move collect activity to the clicked trait
returnIntent.putExtra("trait", column)
setResult(RESULT_OK, returnIntent)
finish()
}
//region unimplemented click events
override fun onCellDoubleClicked(cellView: RecyclerView.ViewHolder, column: Int, row: Int) {}
override fun onCellLongPressed(cellView: RecyclerView.ViewHolder, column: Int, row: Int) {}
override fun onColumnHeaderClicked(columnHeaderView: RecyclerView.ViewHolder, column: Int) {}
override fun onColumnHeaderDoubleClicked(
columnHeaderView: RecyclerView.ViewHolder,
column: Int
) {}
override fun onColumnHeaderLongPressed(columnHeaderView: RecyclerView.ViewHolder, column: Int) {}
override fun onRowHeaderClicked(rowHeaderView: RecyclerView.ViewHolder, row: Int) {}
override fun onRowHeaderDoubleClicked(rowHeaderView: RecyclerView.ViewHolder, row: Int) {}
override fun onRowHeaderLongPressed(rowHeaderView: RecyclerView.ViewHolder, row: Int) {}
//endregion
}
|
gpl-2.0
|
217ae8d824f66c440b877cadc13d3007
| 33.920635 | 160 | 0.626662 | 5.329497 | false | false | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepik/android/view/user_reviews/ui/adapter/decorator/UserCourseReviewItemDecoration.kt
|
2
|
2622
|
package org.stepik.android.view.user_reviews.ui.adapter.decorator
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import androidx.annotation.ColorInt
import androidx.core.view.children
import androidx.recyclerview.widget.RecyclerView
import org.stepik.android.domain.user_reviews.model.UserCourseReviewItem
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
class UserCourseReviewItemDecoration(
@ColorInt separatorColor: Int,
private val defaultSeparatorSize: SeparatorSize
) : RecyclerView.ItemDecoration() {
private val paint =
Paint().apply {
style = Paint.Style.STROKE
color = separatorColor
}
private val emptySeparatorBounds = SeparatorSize(0)
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val separatorSize = getItemSeparatorSize(view, parent).size
if (separatorSize == 0) {
outRect.setEmpty()
} else {
outRect.top += getItemSeparatorSize(view, parent).size
}
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
for (view in parent.children) {
val separatorSize = getItemSeparatorSize(view, parent)
if (separatorSize.size > 0) {
paint.strokeWidth = separatorSize.size.toFloat()
val bottom = view.bottom - separatorSize.size / 2f
c.drawLine(view.left.toFloat(), bottom, view.right.toFloat(), bottom, paint)
}
}
}
private fun getItemSeparatorSize(view: View, parent: RecyclerView): SeparatorSize {
val position = (view.layoutParams as? RecyclerView.LayoutParams)
?.viewLayoutPosition
?.takeIf { it > -1 }
?: return emptySeparatorBounds
val adapter = (parent.adapter as? DefaultDelegateAdapter<UserCourseReviewItem>)
?: return emptySeparatorBounds
val item = adapter.items.getOrNull(position)
?: return emptySeparatorBounds
val nextItem = adapter.items.getOrNull(position + 1)
?: return emptySeparatorBounds
return if (isItem(item) && isItem(nextItem)) {
defaultSeparatorSize
} else {
emptySeparatorBounds
}
}
private fun isItem(item: UserCourseReviewItem) =
item is UserCourseReviewItem.PotentialReviewItem || item is UserCourseReviewItem.ReviewedItem || item is UserCourseReviewItem.Placeholder
class SeparatorSize(val size: Int)
}
|
apache-2.0
|
f3375954b6b712d60259dee79689138f
| 35.943662 | 145 | 0.678108 | 5.061776 | false | false | false | false |
jiaminglu/kotlin-native
|
backend.native/tests/codegen/basics/spread_operator_0.kt
|
1
|
357
|
fun main(arg:Array<String>) {
val list0 = _arrayOf("K", "o", "t", "l", "i", "n")
val list1 = _arrayOf("l", "a","n", "g", "u", "a", "g", "e")
val list = foo(list0, list1)
println(list.toString())
}
fun foo(a:Array<out String>, b:Array<out String>) = listOf(*a," ", "i", "s", " ", "c", "o", "o", "l", " ", *b)
fun _arrayOf(vararg arg:String) = arg
|
apache-2.0
|
51e487c46a3c738b30c79e87dc00ff70
| 28.833333 | 110 | 0.509804 | 2.395973 | false | false | false | false |
robfletcher/orca
|
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/ResumeTaskHandler.kt
|
4
|
1828
|
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.TaskResolver
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.PAUSED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.TaskExecution
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.ResumeTask
import com.netflix.spinnaker.orca.q.RunTask
import com.netflix.spinnaker.q.Queue
import org.springframework.stereotype.Component
@Component
class ResumeTaskHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
private val taskResolver: TaskResolver
) : OrcaMessageHandler<ResumeTask> {
override val messageType = ResumeTask::class.java
override fun handle(message: ResumeTask) {
message.withStage { stage ->
stage
.tasks
.filter { it.status == PAUSED }
.forEach {
it.status = RUNNING
queue.push(RunTask(message, it.type))
}
repository.storeStage(stage)
}
}
@Suppress("UNCHECKED_CAST")
private val TaskExecution.type
get() = taskResolver.getTaskClass(implementingClass)
}
|
apache-2.0
|
d98dbcfed42a79445e27fb865ecbaa72
| 32.851852 | 77 | 0.753829 | 4.241299 | false | false | false | false |
huy-vuong/streamr
|
app/src/main/java/com/huyvuong/streamr/ui/activity/SettingsFragment.kt
|
1
|
1740
|
package com.huyvuong.streamr.ui.activity
import android.content.SharedPreferences
import android.os.Bundle
import android.support.v14.preference.SwitchPreference
import com.huyvuong.streamr.R
import com.takisoft.fix.support.v7.preference.EditTextPreference
import com.takisoft.fix.support.v7.preference.PreferenceFragmentCompat
class SettingsFragment : PreferenceFragmentCompat(),
SharedPreferences.OnSharedPreferenceChangeListener {
override fun onCreatePreferencesFix(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
val showExploreOnLaunchPreference =
preferenceManager.findPreference("pref_launch_explore") as SwitchPreference
val usernameOnLaunchPreference =
preferenceManager.findPreference("pref_launch_username") as EditTextPreference
showExploreOnLaunchPreference.setOnPreferenceChangeListener { _, showExploreOnLaunch ->
usernameOnLaunchPreference.isEnabled = !(showExploreOnLaunch as Boolean)
true
}
usernameOnLaunchPreference.isEnabled = !(showExploreOnLaunchPreference.isChecked)
usernameOnLaunchPreference.summary = usernameOnLaunchPreference.text
usernameOnLaunchPreference.setOnPreferenceChangeListener { preference, username ->
preference.summary = username as String
true
}
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
val preference = findPreference(key)
if (preference != null) {
when (preference) {
is EditTextPreference -> preference.summary = preference.text
}
}
}
}
|
gpl-3.0
|
342a3165b597cf7d0950406a1a87cc18
| 40.452381 | 95 | 0.732759 | 6.281588 | false | false | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepic/droid/core/presenters/AdaptiveRatingPresenter.kt
|
2
|
4543
|
package org.stepic.droid.core.presenters
import android.content.Context
import io.reactivex.BackpressureStrategy
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.BiFunction
import io.reactivex.rxkotlin.Singles.zip
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.subjects.PublishSubject
import org.stepic.droid.adaptive.ui.adapters.AdaptiveRatingAdapter
import org.stepic.droid.adaptive.util.RatingNamesGenerator
import org.stepic.droid.core.presenters.contracts.AdaptiveRatingView
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.CourseId
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepic.droid.preferences.SharedPreferenceHelper
import org.stepik.android.domain.rating.repository.RatingRepository
import org.stepik.android.domain.user.repository.UserRepository
import org.stepik.android.model.adaptive.RatingItem
import retrofit2.HttpException
import javax.inject.Inject
class AdaptiveRatingPresenter
@Inject
constructor(
@CourseId
private val courseId: Long,
private val ratingRepository: RatingRepository,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
@MainScheduler
private val mainScheduler: Scheduler,
private val ratingNamesGenerator: RatingNamesGenerator,
private val userRepository: UserRepository,
context: Context,
sharedPreferenceHelper: SharedPreferenceHelper
) : PresenterBase<AdaptiveRatingView>() {
companion object {
private const val ITEMS_PER_PAGE = 10
@JvmStatic
private val RATING_PERIODS = arrayOf(1, 7, 0)
}
private val adapters = RATING_PERIODS.map { AdaptiveRatingAdapter(context, sharedPreferenceHelper) }
private val compositeDisposable = CompositeDisposable()
private val retrySubject = PublishSubject.create<Int>()
private var error: Throwable? = null
private var ratingPeriod = 0
private var periodsLoaded = 0
init {
initRatingPeriods()
}
private fun initRatingPeriods() {
val left = BiFunction<Any, Any, Any> { a, _ -> a}
RATING_PERIODS.forEachIndexed { pos, period ->
compositeDisposable += resolveUsers(ratingRepository.getRating(courseId, ITEMS_PER_PAGE, period))
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.doOnError(this::onError)
.retryWhen { x -> x.zipWith(retrySubject.toFlowable(BackpressureStrategy.BUFFER), left) }
.subscribeBy(this::onError) {
adapters[pos].set(it)
periodsLoaded++
onLoadComplete()
}
}
}
private fun resolveUsers(single: Single<List<RatingItem>>): Single<List<RatingItem>> =
single.flatMap {
val userIds = it
.filter(RatingItem::isNotFake)
.map(RatingItem::user)
zip(userRepository.getUsers(userIds), Single.just(it))
}.map { (users, items) ->
items.mapIndexed { index, item ->
val user = users.find { it.id == item.user }
val name = user?.fullName ?: ratingNamesGenerator.getName(item.user)
item.copy(
rank = if (item.rank == 0) index + 1 else item.rank,
name = name
)
}
}
fun changeRatingPeriod(pos: Int) {
this.ratingPeriod = pos
view?.onRatingAdapter(adapters[pos])
}
override fun attachView(view: AdaptiveRatingView) {
super.attachView(view)
view.onRatingAdapter(adapters[ratingPeriod])
view.onLoading()
if (error != null) {
error?.let { onError(it) }
} else {
onLoadComplete()
}
}
private fun onLoadComplete() {
if (periodsLoaded == RATING_PERIODS.size) {
view?.onComplete()
}
}
private fun onError(throwable: Throwable) {
error = throwable
if (throwable is HttpException) {
view?.onRequestError()
} else {
view?.onConnectivityError()
}
}
fun retry() {
error = null
retrySubject.onNext(0)
}
fun destroy() {
compositeDisposable.dispose()
}
}
|
apache-2.0
|
d45bc9ceec1eff3e8a18a19dfa043bb5
| 31.22695 | 109 | 0.644728 | 4.874464 | false | false | false | false |
K0zka/wikistat
|
src/main/kotlin/org/dictat/wikistat/services/mongodb/MongoPageDaoImpl.kt
|
1
|
5749
|
package org.dictat.wikistat.services.mongodb
import com.mongodb.DB
import java.util.Date
import org.dictat.wikistat.model.PageActivity
import org.dictat.wikistat.services.PageDao
import org.dictat.wikistat.model.TimeFrame
import com.mongodb.BasicDBObject
import java.util.ArrayList
import com.mongodb.DBObject
import org.dictat.wikistat.utils.LazyIterable
import org.slf4j.LoggerFactory
import java.util.HashMap
import java.util.Collections
import com.mongodb.WriteConcern
import com.mongodb.MapReduceCommand
import java.io.InputStreamReader
import java.io.InputStream
import org.dictat.wikistat.utils.IterableAdapter
public class MongoPageDaoImpl (db: DB, val languages: List<String>): AbstractMongoDao(db), PageDao {
override fun findExtraordinaryActivity(lang: String, date: Date): Iterable<String> {
val mapCommand = getScriptResouce("extra_activity.map.js");
val reduceCommand = getScriptResouce("extra_activity.reduce.js");
val command = MapReduceCommand(
db.getCollection(lang)!!,
mapCommand,
reduceCommand,
null,
MapReduceCommand.OutputType.INLINE,
BasicDBObject());
return IterableAdapter(db.getCollection(lang)!!.mapReduce(command)!!.results()!!, {it.get("") as String})
}
fun getScriptResouce(resourceFile: String): String {
val f: InputStream = Thread.currentThread().getContextClassLoader()?.getResourceAsStream("org/dictat/wikistat/services/mongodb/" + resourceFile)!!;
return InputStreamReader(f).readText()
}
override fun getCollectionNames(): List<String> {
return languages
}
override fun getIndices(): List<String> {
return Collections.emptyList()
}
object constants {
val logger = LoggerFactory.getLogger(javaClass<MongoPageDaoImpl>())!!
}
override fun removePage(page: String, lang: String) {
db.getCollection(lang)!!.remove(BasicDBObject("_id", page))
}
override fun getPageNames(lang: String): LazyIterable<String> {
return Cursor(db.getCollection(lang)!!.find(BasicDBObject(), BasicDBObject("_id", 1))!!, { it.get("_id") as String })
}
override fun removePageEvents(name: String, lang: String, times: List<Pair<Date, TimeFrame>>) {
throw UnsupportedOperationException()
}
override fun getLangs(): List<String> {
return Collections.unmodifiableList(languages)
}
override fun findPages(prefix: String, lang: String, max: Int): List<String> {
val query = BasicDBObject("_id", BasicDBObject("\$regex", "^" + prefix + ".*")).append("\$where", "this.c != null");
val pages = db.getCollection(lang)!!.find(query, BasicDBObject("_id", 1))!!.sort(BasicDBObject("_id", 1))!!.limit(50);
val ret = ArrayList<String>()
for (page in pages) {
ret.add(page.get("_id") as String);
}
return ret
}
override fun getPageActivity(name: String, lang: String): List<PageActivity> {
val obj = db.getCollection(lang)!!.findOne(BasicDBObject("_id", name))
if(obj?.get("h") == null) {
return Collections.emptyList();
}
val dbActivity = obj?.get("h") as DBObject
val ret = HashMap<String, PageActivity>()
for(key in dbActivity.keySet()?.iterator()) {
val activity = PageActivity()
activity.time = DateUtil.stringToDate(key, TimeFrame.Hour)
activity.activity = dbActivity.get(key) as Int
ret.put(key, activity)
}
val r = ArrayList<PageActivity>()
ret.values().forEach { r.add(it) }
return r;
}
override fun savePageEvent(
name: String,
lang: String,
cnt: Int,
time: Date,
timeFrame: TimeFrame,
special: Boolean) {
val key = getKey(timeFrame, special)
db.getCollection(lang)!!.update(
BasicDBObject("_id", name),
BasicDBObject("\$inc", BasicDBObject(key + "." + DateUtil.dateToString(time, timeFrame), cnt)),
true,
false,
WriteConcern.JOURNALED)
}
fun getKey(timeFrame: TimeFrame, special: Boolean): String {
return timeFrame.symbol.toString() + (if(special) "s" else "");
}
override fun markChecked(page: String, lang: String) {
db.getCollection(lang)!!.update(BasicDBObject("_id", page), BasicDBObject("\$set", BasicDBObject("c", DateUtil.dateToString(Date(), TimeFrame.Hour))))
}
override fun findUnchecked(lang: String): LazyIterable<String> {
val projection = BasicDBObject("_id", 1)
val filter = BasicDBObject("\$where", "this.c == null")
return Cursor(db.getCollection(lang)!!.find(filter, projection)!!, { it.get("_id") as String })
}
override fun replaceSum(
page: String,
lang: String,
from: TimeFrame,
to: TimeFrame,
fromTime: Date,
toTime: Date,
sum: Int) {
//this is quite ineffective in mongodb, we have to send the set and the unset commands
val updateDoc =
BasicDBObject(
"\$set",
BasicDBObject(getKey(to, false) + "." + DateUtil.dateToString(fromTime, to), sum))
val key = BasicDBObject("_id", page)
val unsets = BasicDBObject()
for(i in DateUtil.datesBetween(fromTime, toTime, from)) {
unsets.append(getKey(from, false) + "." + i, 0)
}
updateDoc.append("\$unset", unsets)
db.getCollection(lang)!!.update(key, updateDoc, true, false, WriteConcern.JOURNALED)
}
}
|
apache-2.0
|
cbd34b0515a8446e66246e867e42e424
| 37.851351 | 158 | 0.623239 | 4.484399 | false | false | false | false |
apollostack/apollo-android
|
composite/samples/kotlin-sample/src/main/java/com/apollographql/apollo3/kotlinsample/data/ApolloWatcherService.kt
|
1
|
3327
|
package com.apollographql.apollo3.kotlinsample.data
import android.util.Log
import com.apollographql.apollo3.ApolloCall
import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.ApolloResponse
import com.apollographql.apollo3.exception.ApolloException
import com.apollographql.apollo3.fetcher.ApolloResponseFetchers
import com.apollographql.apollo3.kotlinsample.GithubRepositoriesQuery
import com.apollographql.apollo3.kotlinsample.GithubRepositoryCommitsQuery
import com.apollographql.apollo3.kotlinsample.GithubRepositoryDetailQuery
import com.apollographql.apollo3.kotlinsample.type.OrderDirection
import com.apollographql.apollo3.kotlinsample.type.PullRequestState
import com.apollographql.apollo3.kotlinsample.type.RepositoryOrderField
/**
* An implementation of a [GitHubDataSource] that shows how to fetch data using callbacks.
*/
class ApolloWatcherService(apolloClient: ApolloClient) : GitHubDataSource(apolloClient) {
override fun fetchRepositories() {
val repositoriesQuery = GithubRepositoriesQuery(
repositoriesCount = 50,
orderBy = RepositoryOrderField.UPDATED_AT,
orderDirection = OrderDirection.DESC
)
val callback = createCallback<GithubRepositoriesQuery.Data> {
repositoriesSubject.onNext(mapRepositoriesResponseToRepositories(it))
}
apolloClient
.query(repositoriesQuery)
.responseFetcher(ApolloResponseFetchers.CACHE_AND_NETWORK)
.watcher()
.enqueueAndWatch(callback)
}
override fun fetchRepositoryDetail(repositoryName: String) {
val repositoryDetailQuery = GithubRepositoryDetailQuery(
name = repositoryName,
pullRequestStates = listOf(PullRequestState.OPEN)
)
val callback = createCallback<GithubRepositoryDetailQuery.Data> {
repositoryDetailSubject.onNext(it)
}
apolloClient
.query(repositoryDetailQuery)
.responseFetcher(ApolloResponseFetchers.CACHE_AND_NETWORK)
.watcher()
.enqueueAndWatch(callback)
}
override fun fetchCommits(repositoryName: String) {
val commitsQuery = GithubRepositoryCommitsQuery(
name = repositoryName
)
val callback = createCallback<GithubRepositoryCommitsQuery.Data> { response ->
val headCommit = response.data?.viewer?.repository?.ref?.target as? GithubRepositoryCommitsQuery.Data.Viewer.Repository.Ref.CommitTarget
val commits = headCommit?.history?.edges?.filterNotNull().orEmpty()
commitsSubject.onNext(commits)
}
apolloClient
.query(commitsQuery)
.responseFetcher(ApolloResponseFetchers.CACHE_AND_NETWORK)
.watcher()
.enqueueAndWatch(callback)
}
private fun <T : Operation.Data> createCallback(onResponse: (response: ApolloResponse<T>) -> Unit) =
object : ApolloCall.Callback<T>() {
override fun onResponse(response: ApolloResponse<T>) = onResponse(response)
override fun onFailure(e: ApolloException) {
exceptionSubject.onNext(e)
}
override fun onStatusEvent(event: ApolloCall.StatusEvent) {
Log.d("ApolloWatcherService", "Apollo Status Event: $event")
}
}
override fun cancelFetching() {
//TODO: Determine how to cancel this when there's callbacks
}
}
|
mit
|
0cd602337ab845c057ab35155d033c04
| 35.966667 | 142 | 0.752329 | 4.856934 | false | false | false | false |
esqr/WykopMobilny
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/fragments/DataFragment.kt
|
2
|
830
|
package io.github.feelfreelinux.wykopmobilny.models.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
fun <T : Any> FragmentManager.getDataFragmentInstance(tag : String): DataFragment<T> {
var retainedFragment = findFragmentByTag(tag)
if (retainedFragment == null) {
retainedFragment = DataFragment<T>()
beginTransaction().add(retainedFragment, tag).commit()
}
return retainedFragment as DataFragment<T>
}
fun FragmentManager.removeDataFragment(fragment : Fragment) {
beginTransaction().remove(fragment).commit()
}
class DataFragment<T : Any> : Fragment() {
var data : T? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
}
}
|
mit
|
d767f13be3c2080ad6c0ed709025dfe8
| 30.961538 | 86 | 0.73253 | 4.51087 | false | false | false | false |
Maccimo/intellij-community
|
platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/impl/jps/serialization/JpsProjectSaveAfterChangesTest.kt
|
3
|
8827
|
package com.intellij.workspaceModel.ide.impl.jps.serialization
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.util.io.FileUtil
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.rules.ProjectModelRule
import com.intellij.workspaceModel.ide.JpsFileEntitySource
import com.intellij.workspaceModel.ide.JpsProjectConfigLocation
import com.intellij.workspaceModel.ide.impl.IdeVirtualFileUrlManagerImpl
import com.intellij.workspaceModel.ide.impl.JpsEntitySourceFactory
import com.intellij.workspaceModel.storage.EntityChange
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.bridgeEntities.api.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.jps.util.JpsPathUtil
import com.intellij.workspaceModel.storage.bridgeEntities.api.modifyEntity
import org.junit.Assert
import org.junit.Before
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.io.File
class JpsProjectSaveAfterChangesTest {
@Rule
@JvmField
val projectModel = ProjectModelRule(true)
private lateinit var virtualFileManager: VirtualFileUrlManager
@Before
fun setUp() {
virtualFileManager = IdeVirtualFileUrlManagerImpl()
}
@Test
fun `modify module`() {
checkSaveProjectAfterChange("common/modifyIml", "common/modifyIml") { builder, configLocation ->
val utilModule = builder.entities(ModuleEntity::class.java).first { it.name == "util" }
val sourceRoot = utilModule.sourceRoots.first()
builder.modifyEntity(sourceRoot) {
url = configLocation.baseDirectoryUrl.append("util/src2")
}
builder.modifyEntity(utilModule.customImlData!!) {
rootManagerTagCustomData = """<component>
<annotation-paths>
<root url="${configLocation.baseDirectoryUrlString}/lib/anno2" />
</annotation-paths>
<javadoc-paths>
<root url="${configLocation.baseDirectoryUrlString}/lib/javadoc2" />
</javadoc-paths>
</component>"""
}
builder.modifyEntity(utilModule) {
dependencies = dependencies.dropLast(2)
}
builder.modifyEntity(utilModule.contentRoots.first()) {
excludedPatterns = emptyList()
excludedUrls = emptyList()
}
builder.modifyEntity(sourceRoot.asJavaSourceRoot()!!) {
packagePrefix = ""
}
}
}
@Test
fun `rename module`() {
checkSaveProjectAfterChange("directoryBased/renameModule", "fileBased/renameModule") { builder, _ ->
val utilModule = builder.entities(ModuleEntity::class.java).first { it.name == "util" }
builder.modifyEntity(utilModule) {
name = "util2"
}
}
}
@Test
fun `add library and check vfu index not empty`() {
checkSaveProjectAfterChange("directoryBased/addLibrary", "fileBased/addLibrary") { builder, configLocation ->
val root = LibraryRoot(virtualFileManager.fromUrl("jar://${JpsPathUtil.urlToPath(configLocation.baseDirectoryUrlString)}/lib/junit2.jar!/"), LibraryRootTypeId.COMPILED)
val source = JpsEntitySourceFactory.createJpsEntitySourceForProjectLibrary(configLocation)
builder.addLibraryEntity("junit2", LibraryTableId.ProjectLibraryTableId, listOf(root), emptyList(), source)
builder.entities(LibraryEntity::class.java).forEach { libraryEntity ->
val virtualFileUrl = libraryEntity.roots.first().url
val entitiesByUrl = builder.getMutableVirtualFileUrlIndex().findEntitiesByUrl(virtualFileUrl)
Assert.assertTrue(entitiesByUrl.toList().isNotEmpty())
}
}
}
@Test
fun `add module`() {
checkSaveProjectAfterChange("directoryBased/addModule", "fileBased/addModule") { builder, configLocation ->
val source = JpsFileEntitySource.FileInDirectory(configLocation.baseDirectoryUrl, configLocation)
val dependencies = listOf(ModuleDependencyItem.InheritedSdkDependency, ModuleDependencyItem.ModuleSourceDependency)
val module = builder.addModuleEntity("newModule", dependencies, source)
builder.modifyEntity(module) {
type = "JAVA_MODULE"
}
val contentRootEntity = builder.addContentRootEntity(configLocation.baseDirectoryUrl.append("new"), emptyList(),
emptyList(), module)
val sourceRootEntity = builder.addSourceRootEntity(contentRootEntity, configLocation.baseDirectoryUrl.append("new"),
"java-source", source)
builder.addJavaSourceRootEntity(sourceRootEntity, false, "")
builder.addJavaModuleSettingsEntity(true, true, null, null, null, module, source)
}
}
@Test
fun `remove module`() {
checkSaveProjectAfterChange("directoryBased/removeModule", "fileBased/removeModule") { builder, _ ->
val utilModule = builder.entities(ModuleEntity::class.java).first { it.name == "util" }
//todo now we need to remove module libraries by hand, maybe we should somehow modify the model instead
val moduleLibraries = utilModule.getModuleLibraries(builder).toList()
builder.removeEntity(utilModule)
moduleLibraries.forEach {
builder.removeEntity(it)
}
}
}
@Test
fun `modify library`() {
checkSaveProjectAfterChange("directoryBased/modifyLibrary", "fileBased/modifyLibrary") { builder, configLocation ->
val junitLibrary = builder.entities(LibraryEntity::class.java).first { it.name == "junit" }
val root = LibraryRoot(virtualFileManager.fromUrl("jar://${JpsPathUtil.urlToPath(configLocation.baseDirectoryUrlString)}/lib/junit2.jar!/"),
LibraryRootTypeId.COMPILED)
builder.modifyEntity(junitLibrary) {
roots = listOf(root)
}
}
}
@Test
fun `rename library`() {
checkSaveProjectAfterChange("directoryBased/renameLibrary", "fileBased/renameLibrary") { builder, _ ->
val junitLibrary = builder.entities(LibraryEntity::class.java).first { it.name == "junit" }
builder.modifyEntity(junitLibrary) {
name = "junit2"
}
}
}
@Test
fun `remove library`() {
checkSaveProjectAfterChange("directoryBased/removeLibrary", "fileBased/removeLibrary") { builder, _ ->
val junitLibrary = builder.entities(LibraryEntity::class.java).first { it.name == "junit" }
builder.removeEntity(junitLibrary)
}
}
private fun checkSaveProjectAfterChange(directoryNameForDirectoryBased: String,
directoryNameForFileBased: String,
change: (MutableEntityStorage, JpsProjectConfigLocation) -> Unit) {
checkSaveProjectAfterChange(sampleDirBasedProjectFile, directoryNameForDirectoryBased, change)
checkSaveProjectAfterChange(sampleFileBasedProjectFile, directoryNameForFileBased, change)
}
private fun checkSaveProjectAfterChange(originalProjectFile: File, changedFilesDirectoryName: String?,
change: (MutableEntityStorage, JpsProjectConfigLocation) -> Unit) {
val projectData = copyAndLoadProject(originalProjectFile, virtualFileManager)
val builder = MutableEntityStorage.from(projectData.storage)
change(builder, projectData.configLocation)
val changesMap = builder.collectChanges(projectData.storage)
val changedSources = changesMap.values.flatMapTo(HashSet()) { changes -> changes.flatMap { change ->
when (change) {
is EntityChange.Added -> listOf(change.entity)
is EntityChange.Removed -> listOf(change.entity)
is EntityChange.Replaced -> listOf(change.oldEntity, change.newEntity)
}
}.map { it.entitySource }}
val writer = JpsFileContentWriterImpl(projectData.configLocation)
projectData.serializers.saveEntities(builder.toSnapshot(), changedSources, writer)
writer.writeFiles()
projectData.serializers.checkConsistency(projectData.configLocation, builder.toSnapshot(), virtualFileManager)
val expectedDir = FileUtil.createTempDirectory("jpsProjectTest", "expected")
FileUtil.copyDir(projectData.originalProjectDir, expectedDir)
if (changedFilesDirectoryName != null) {
val changedDir = PathManagerEx.findFileUnderCommunityHome("platform/workspaceModel/jps/tests/testData/serialization/reload/$changedFilesDirectoryName")
FileUtil.copyDir(changedDir, expectedDir)
}
expectedDir.walk().filter { it.isFile && it.readText().trim() == "<delete/>" }.forEach {
FileUtil.delete(it)
}
assertDirectoryMatches(projectData.projectDir, expectedDir,
emptySet(),
emptyList())
}
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
}
|
apache-2.0
|
8055fa45c641d6615e91e38175f4f414
| 43.585859 | 174 | 0.720403 | 5.272999 | false | true | false | false |
PolymerLabs/arcs
|
javatests/arcs/android/host/parcelables/ParcelableHandleConnectionTest.kt
|
1
|
6480
|
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.android.host.parcelables
import android.os.Parcel
import androidx.test.ext.junit.runners.AndroidJUnit4
import arcs.android.type.writeType
import arcs.core.common.ArcId
import arcs.core.data.EntityType
import arcs.core.data.FieldType.Companion.Text
import arcs.core.data.HandleMode
import arcs.core.data.Plan.Handle
import arcs.core.data.Plan.HandleConnection
import arcs.core.data.Schema
import arcs.core.data.SchemaFields
import arcs.core.data.SchemaName
import arcs.core.data.expression.asExpr
import arcs.core.storage.StorageKeyManager
import arcs.core.storage.keys.VolatileStorageKey
import com.google.common.truth.Truth.assertThat
import java.lang.IllegalArgumentException
import kotlin.test.assertFailsWith
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/** Tests for [ParcelableHandleConnection]'s classes. */
@RunWith(AndroidJUnit4::class)
class ParcelableHandleConnectionTest {
private val personSchema = Schema(
setOf(SchemaName("Person")),
SchemaFields(mapOf("name" to Text), emptyMap()),
"42"
)
private val storageKey = VolatileStorageKey(ArcId.newForTest("foo"), "bar")
private val personType = EntityType(personSchema)
@Before
fun setup() {
StorageKeyManager.GLOBAL_INSTANCE.reset(VolatileStorageKey)
}
@Test
fun handleConnection_parcelableRoundTrip_works() {
val handleConnection = HandleConnection(
Handle(storageKey, personType, emptyList()),
HandleMode.ReadWrite,
personType,
emptyList(),
true.asExpr()
)
val marshalled = with(Parcel.obtain()) {
writeTypedObject(handleConnection.toParcelable(), 0)
marshall()
}
val unmarshalled = with(Parcel.obtain()) {
unmarshall(marshalled, 0, marshalled.size)
setDataPosition(0)
readTypedObject(requireNotNull(ParcelableHandleConnection.CREATOR))
}
assertThat(unmarshalled?.describeContents()).isEqualTo(0)
assertThat(unmarshalled?.actual).isEqualTo(handleConnection)
}
@Test
fun handleConnection_parcelableRoundTrip_works_nullExpression() {
val handleConnection = HandleConnection(
Handle(storageKey, personType, emptyList()),
HandleMode.ReadWrite,
personType
)
val marshalled = with(Parcel.obtain()) {
writeTypedObject(handleConnection.toParcelable(), 0)
marshall()
}
val unmarshalled = with(Parcel.obtain()) {
unmarshall(marshalled, 0, marshalled.size)
setDataPosition(0)
readTypedObject(requireNotNull(ParcelableHandleConnection.CREATOR))
}
assertThat(unmarshalled?.actual).isEqualTo(handleConnection)
}
@Test
fun writeHandleConnectionSpec_parcelableRoundTrip_works() {
val handleConnection = HandleConnection(
Handle(storageKey, personType, emptyList()),
HandleMode.ReadWrite,
personType,
emptyList(),
true.asExpr()
)
var parcel = Parcel.obtain()
parcel.writeHandleConnectionSpec(handleConnection, 0)
parcel.setDataPosition(0)
val recovered = parcel.readHandleConnectionSpec()
assertThat(recovered).isEqualTo(handleConnection)
}
@Test
fun array_parcelableRoundTrip_works() {
val handleConnection = HandleConnection(
Handle(storageKey, personType, emptyList()),
HandleMode.ReadWrite,
personType,
emptyList(),
true.asExpr()
).toParcelable()
val arr = arrayOf(handleConnection, handleConnection)
val marshalled = with(Parcel.obtain()) {
writeTypedArray(arr, 0)
marshall()
}
val unmarshalled = with(Parcel.obtain()) {
unmarshall(marshalled, 0, marshalled.size)
setDataPosition(0)
createTypedArray(requireNotNull(ParcelableHandleConnection.CREATOR))
}
assertThat(unmarshalled?.size).isEqualTo(2)
assertThat(unmarshalled?.get(0)?.actual).isEqualTo(handleConnection.actual)
}
@Test
fun handleConnection_malformedParcelNoHandle_fails() {
val parcel = Parcel.obtain().apply {
writeInt(1) // Says value to come is non-empty.
// Invalid handle contents
writeString(null) // handle
writeType(personType, 0) // type
writeInt(0) // handleMode
writeInt(0) // annotation count
writeType(personType, 0)
writeInt(HandleMode.ReadWrite.ordinal)
writeString("") // expression
}
parcel.setDataPosition(0)
assertFailsWith<RuntimeException>("malformed handle") {
parcel.readTypedObject(requireNotNull(ParcelableHandleConnection))
}
}
@Test
fun handleConnection_malformedParcelNoType_fails() {
val handle = Handle(storageKey, personType, emptyList())
val parcel = Parcel.obtain().apply {
writeInt(1) // Says value to come is non-empty.
writeHandle(handle, 0)
writeInt(9999) // invalid handle type ordinal
writeInt(HandleMode.ReadWrite.ordinal)
writeString("") // expression
}
parcel.setDataPosition(0)
assertFailsWith<RuntimeException>("malformed type") {
parcel.readTypedObject(requireNotNull(ParcelableHandleConnection))
}
}
@Test
fun handleConnection_malformedParcelInvalidHandleMode_fails() {
val handle = Handle(storageKey, personType, emptyList())
val parcel = Parcel.obtain().apply {
writeInt(1) // Says value to come is non-empty.
writeHandle(handle, 0)
writeType(personType, 0)
writeInt(999)
writeString("") // expression
}
parcel.setDataPosition(0)
assertFailsWith<IllegalArgumentException>("invalid handle mode") {
parcel.readTypedObject(requireNotNull(ParcelableHandleConnection))
}
}
@Test
fun handleConnection_malformedParcelInvalidExpression_fails() {
val handle = Handle(storageKey, personType, emptyList())
val parcel = Parcel.obtain().apply {
writeInt(1) // Says value to come is non-empty.
writeHandle(handle, 0)
writeType(personType, 0)
writeInt(HandleMode.ReadWrite.ordinal)
writeString("not-an-expression") // expression
}
parcel.setDataPosition(0)
assertFailsWith<IllegalArgumentException>("invalid expression") {
parcel.readTypedObject(requireNotNull(ParcelableHandleConnection))
}
}
}
|
bsd-3-clause
|
e3838ce60aa65e3f005006b12549696b
| 29.7109 | 96 | 0.718519 | 4.705882 | false | true | false | false |
PolymerLabs/arcs
|
particles/Tutorial/Kotlin/Demo/src/TTTBoard.kt
|
2
|
2409
|
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.tutorials.tictactoe
import arcs.sdk.wasm.WasmHandle
class TTTBoard : AbstractTTTBoard() {
private var clicks = 0.0
init {
eventHandler("onClick") { eventData ->
handles.events.store(
TTTBoard_Events(
type = "move",
move = eventData["value"]?.toDouble() ?: -1.0,
time = clicks
)
)
clicks++
}
eventHandler("reset") {
handles.events.store(TTTBoard_Events(type = "reset", time = clicks, move = -1.0))
clicks++
}
}
override fun onHandleUpdate(handle: WasmHandle) = renderOutput()
override fun populateModel(slotName: String, model: Map<String, Any>): Map<String, Any> {
val gs = handles.gameState.fetch() ?: TTTBoard_GameState()
val boardList = gs.board.split(",")
val boardModel = mutableListOf<Map<String, String?>>()
boardList.forEachIndexed { index, cell ->
boardModel.add(mapOf("cell" to cell, "value" to index.toString()))
}
return mapOf(
"buttons" to mapOf(
"\$template" to "button",
"models" to boardModel
)
)
}
override fun getTemplate(slotName: String): String = """
<style>
.grid-container {
display: grid;
grid-template-columns: 50px 50px 50px;
grid-column-gap: 0px;
}
.valid-butt {
border: 1px outset blue;
height: 50px;
width: 50px;
cursor: pointer;
background-color: lightblue;
}
.valid-butt:hover {
background-color: blue;
color: white;
}
</style>
<div class="grid-container">{{buttons}}</div>
<template button>
<button class="valid-butt" type="button" on-click="onClick" value="{{value}}" \>
<span>{{cell}}</span>
</button>
</template>
Please hit reset to start a new game.<button on-click="reset">Reset</button>
""".trimIndent()
}
|
bsd-3-clause
|
cd2a48bf6aa8ea2c0137e8207238ea6e
| 27.678571 | 96 | 0.551681 | 4.160622 | false | false | false | false |
blindpirate/gradle
|
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/codegen/SourceFileHeader.kt
|
3
|
1925
|
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.codegen
internal
val fileHeader: String
get() = fileHeaderFor(kotlinDslPackageName)
internal
fun fileHeaderFor(packageName: String) =
"""$licenseHeader
@file:Suppress(
"unused",
"nothing_to_inline",
"useless_cast",
"unchecked_cast",
"extension_shadowed_by_member",
"redundant_projection",
"RemoveRedundantBackticks",
"ObjectPropertyName",
"deprecation"
)
@file:org.gradle.api.Generated
/* ktlint-disable */
package $packageName
"""
internal
const val kotlinDslPackageName = "org.gradle.kotlin.dsl"
internal
const val kotlinDslPackagePath = "org/gradle/kotlin/dsl"
internal
const val licenseHeader = """/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/"""
|
apache-2.0
|
f5a947b703135ea65088c535bedd45ad
| 26.112676 | 75 | 0.73039 | 4.095745 | false | false | false | false |
SnakeEys/MessagePlus
|
app/src/main/java/info/fox/messup/MainActivity.kt
|
1
|
4780
|
package info.fox.messup
import android.Manifest
import android.content.AsyncQueryHandler
import android.content.ContentResolver
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.os.Build
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.Toolbar
import info.fox.messup.activity.ConversationsFragment
import info.fox.messup.base.DrawerActivity
import info.fox.messup.domain.Conversation
class MainActivity : DrawerActivity() {
private val CODE_PERMISSION_READ_SMS = 1
private var toggle: ActionBarDrawerToggle? = null
private lateinit var mQueryHandler: AsyncQueryHandler
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val drawer = findWidget<DrawerLayout>(R.id.drawer_layout)
toggle = ActionBarDrawerToggle(this, drawer, findWidget<Toolbar>(R.id.toolbar),
R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer.addDrawerListener(toggle!!)
val nav = findWidget<NavigationView>(R.id.nav_view)
nav.setCheckedItem(R.id.nav_conversations)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val sms = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
val contacts = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
if (sms != PackageManager.PERMISSION_GRANTED || contacts != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_SMS, Manifest.permission.READ_CONTACTS), CODE_PERMISSION_READ_SMS)
} else {
start()
}
} else {
start()
}
mQueryHandler = ThreadListQueryHandler(contentResolver)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
toggle?.syncState()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, results: IntArray) {
var flag = true
results
.filter { it != PackageManager.PERMISSION_GRANTED }
.forEach { flag = false }
if (flag) {
onResumeFragments()
} else {
Snackbar.make(findWidget(R.id.fl_container), "Permission denied", Snackbar.LENGTH_LONG)
.setAction(android.R.string.ok) { }
.show()
}
}
override fun onStart() {
super.onStart()
startAsyncQuery()
}
override fun onResumeFragments() {
super.onResumeFragments()
start()
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
val nav = findWidget<NavigationView>(R.id.nav_view)
nav.setCheckedItem(R.id.nav_conversations)
}
private fun start() {
val t = supportFragmentManager.beginTransaction()
t.replace(R.id.fl_container, ConversationsFragment.newInstance(), TAG)
t.commit()
}
private fun startAsyncQuery() {
Conversation.startQueryForAll(mQueryHandler, THREAD_LIST_QUERY_TOKEN)
}
companion object {
private val THREAD_LIST_QUERY_TOKEN = 1701
private val UNREAD_THREADS_QUERY_TOKEN = 1702
val DELETE_CONVERSATION_TOKEN = 1801
val HAVE_LOCKED_MESSAGES_TOKEN = 1802
private val DELETE_OBSOLETE_THREADS_TOKEN = 1803
}
private inner class ThreadListQueryHandler(cr: ContentResolver) : Conversation.ConversationQueryHandler(cr) {
override fun onQueryComplete(token: Int, cookie: Any?, cursor: Cursor?) {
when (token) {
THREAD_LIST_QUERY_TOKEN -> {
if (cursor == null || cursor.count == 0) {
// TODO:: Display empty view.
return
}
val fragment = supportFragmentManager.findFragmentByTag(TAG)
if (fragment is ConversationsFragment) {
fragment.updateData(cursor)
}
}
UNREAD_THREADS_QUERY_TOKEN -> {}
HAVE_LOCKED_MESSAGES_TOKEN -> {}
}
}
override fun onDeleteComplete(token: Int, cookie: Any?, result: Int) {
super.onDeleteComplete(token, cookie, result)
}
}
}
|
mit
|
9019d0f7d9c0f2dde5e86a60d0ea3851
| 35.48855 | 155 | 0.644351 | 4.756219 | false | false | false | false |
75py/Aplin
|
app/src/main/java/com/nagopy/android/aplin/ui/main/MainViewModel.kt
|
1
|
5111
|
package com.nagopy.android.aplin.ui.main
import android.app.Activity
import android.app.ActivityManager
import android.app.SearchManager
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import androidx.core.app.ShareCompat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.gms.oss.licenses.OssLicensesMenuActivity
import com.nagopy.android.aplin.domain.model.PackageModel
import com.nagopy.android.aplin.domain.usecase.LoadPackagesUseCase
import com.nagopy.android.aplin.ui.prefs.UserDataStore
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import logcat.logcat
import java.net.URLEncoder
class MainViewModel(
activityManager: ActivityManager,
private val packageManager: PackageManager,
private val loadPackagesUseCase: LoadPackagesUseCase,
private val ioDispatcher: CoroutineDispatcher,
private val userDataStore: UserDataStore,
) : ViewModel() {
private val _viewModelState = MutableStateFlow(MainUiState(isLoading = false))
val viewModelState =
_viewModelState.stateIn(viewModelScope, SharingStarted.Eagerly, _viewModelState.value)
val launcherLargeIconSize = activityManager.launcherLargeIconSize
init {
updatePackages()
viewModelScope.launch(ioDispatcher) {
userDataStore.sortOrder.collect { newOrder ->
logcat { "sortOrder: $newOrder" }
_viewModelState.update {
it.copy(
isLoading = false,
packagesModel = it.packagesModel?.let { packagesModel ->
newOrder.sort(
packagesModel
)
},
sortOrder = newOrder,
)
}
}
}
}
fun updatePackages() {
if (_viewModelState.value.isLoading) {
return
}
_viewModelState.update {
it.copy(isLoading = true)
}
viewModelScope.launch(ioDispatcher) {
val result = loadPackagesUseCase.execute()
_viewModelState.update {
it.copy(
isLoading = false,
packagesModel = it.sortOrder.sort(result),
)
}
}
}
fun startDetailSettingsActivity(activity: Activity, pkg: String) {
val packageName = pkg.split(":")[0]
val intent =
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName"))
if (activity.isInMultiWindowMode) {
intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
try {
activity.startActivity(intent)
} catch (e: Exception) {
logcat { "$e" }
}
}
fun searchByWeb(activity: Activity, packageModel: PackageModel) {
val actionWebSearch = Intent(Intent.ACTION_WEB_SEARCH)
.putExtra(SearchManager.QUERY, "${packageModel.label} ${packageModel.packageName}")
if (isLaunchable(actionWebSearch)) {
activity.startActivity(actionWebSearch)
} else {
val url = "https://www.google.com/search?q=${
URLEncoder.encode(
packageModel.label,
"UTF-8"
)
}%20${packageModel.packageName}"
val actionView = Intent(Intent.ACTION_VIEW)
.setData(Uri.parse(url))
if (isLaunchable(actionView)) {
activity.startActivity(actionView)
} else {
logcat { "ActivityNotFound" }
}
}
}
private fun isLaunchable(intent: Intent): Boolean {
return intent.resolveActivity(packageManager) != null
}
fun startOssLicensesActivity(activity: Activity) {
activity.startActivity(Intent(activity, OssLicensesMenuActivity::class.java))
}
fun sharePackages(activity: Activity, packages: List<PackageModel>) {
ShareCompat.IntentBuilder(activity)
.setText(packages.joinToString(separator = LINE_SEPARATOR) { it.packageName })
.setType("text/plain")
.startChooser()
}
fun updateSearchWidgetState(newValue: SearchWidgetState) {
_viewModelState.update {
it.copy(searchWidgetState = newValue)
}
}
fun updateSearchTextState(newValue: String) {
_viewModelState.update {
it.copy(searchText = newValue)
}
}
companion object {
private val LINE_SEPARATOR: String = System.getProperty("line.separator") ?: "\n"
}
}
|
apache-2.0
|
684d7a19fd40d426a8de84ff0f679928
| 33.073333 | 99 | 0.624927 | 5.080517 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/main/java/org/wordpress/android/ui/jetpack/restore/RestoreViewModel.kt
|
1
|
24660
|
package org.wordpress.android.ui.jetpack.restore
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Parcelable
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import kotlinx.parcelize.Parcelize
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.collect
import org.json.JSONObject
import org.wordpress.android.Constants
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker
import org.wordpress.android.analytics.AnalyticsTracker.Stat.JETPACK_RESTORE_CONFIRMED
import org.wordpress.android.analytics.AnalyticsTracker.Stat.JETPACK_RESTORE_ERROR
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.ActivityLogStore.RewindRequestTypes
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.jetpack.common.JetpackListItemState
import org.wordpress.android.ui.jetpack.common.JetpackListItemState.CheckboxState
import org.wordpress.android.ui.jetpack.common.ViewType
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType.CONTENTS
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType.MEDIA_UPLOADS
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType.PLUGINS
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType.ROOTS
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType.SQLS
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType.THEMES
import org.wordpress.android.ui.jetpack.restore.RestoreErrorTypes.GenericFailure
import org.wordpress.android.ui.jetpack.restore.RestoreNavigationEvents.ShowJetpackSettings
import org.wordpress.android.ui.jetpack.restore.RestoreNavigationEvents.VisitSite
import org.wordpress.android.ui.jetpack.restore.RestoreRequestState.AwaitingCredentials
import org.wordpress.android.ui.jetpack.restore.RestoreRequestState.Complete
import org.wordpress.android.ui.jetpack.restore.RestoreRequestState.Empty
import org.wordpress.android.ui.jetpack.restore.RestoreRequestState.Failure.NetworkUnavailable
import org.wordpress.android.ui.jetpack.restore.RestoreRequestState.Failure.OtherRequestRunning
import org.wordpress.android.ui.jetpack.restore.RestoreRequestState.Failure.RemoteRequestFailure
import org.wordpress.android.ui.jetpack.restore.RestoreRequestState.Progress
import org.wordpress.android.ui.jetpack.restore.RestoreRequestState.Success
import org.wordpress.android.ui.jetpack.restore.RestoreStep.COMPLETE
import org.wordpress.android.ui.jetpack.restore.RestoreStep.DETAILS
import org.wordpress.android.ui.jetpack.restore.RestoreStep.ERROR
import org.wordpress.android.ui.jetpack.restore.RestoreStep.PROGRESS
import org.wordpress.android.ui.jetpack.restore.RestoreStep.WARNING
import org.wordpress.android.ui.jetpack.restore.RestoreUiState.ContentState.CompleteState
import org.wordpress.android.ui.jetpack.restore.RestoreUiState.ContentState.DetailsState
import org.wordpress.android.ui.jetpack.restore.RestoreUiState.ContentState.ProgressState
import org.wordpress.android.ui.jetpack.restore.RestoreUiState.ContentState.WarningState
import org.wordpress.android.ui.jetpack.restore.RestoreUiState.ErrorState
import org.wordpress.android.ui.jetpack.restore.RestoreViewModel.RestoreWizardState.RestoreCanceled
import org.wordpress.android.ui.jetpack.restore.RestoreViewModel.RestoreWizardState.RestoreCompleted
import org.wordpress.android.ui.jetpack.restore.RestoreViewModel.RestoreWizardState.RestoreInProgress
import org.wordpress.android.ui.jetpack.restore.builders.RestoreStateListItemBuilder
import org.wordpress.android.ui.jetpack.restore.usecases.GetRestoreStatusUseCase
import org.wordpress.android.ui.jetpack.restore.usecases.PostRestoreUseCase
import org.wordpress.android.ui.jetpack.usecases.GetActivityLogItemUseCase
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.ui.utils.UiString.UiStringText
import org.wordpress.android.util.text.PercentFormatter
import org.wordpress.android.util.wizard.WizardManager
import org.wordpress.android.util.wizard.WizardNavigationTarget
import org.wordpress.android.util.wizard.WizardState
import org.wordpress.android.util.wizard.WizardStep
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ScopedViewModel
import java.util.Date
import java.util.HashMap
import javax.inject.Inject
import javax.inject.Named
const val KEY_RESTORE_ACTIVITY_ID_KEY = "key_restore_activity_id_key"
const val KEY_RESTORE_CURRENT_STEP = "key_restore_current_step"
const val KEY_RESTORE_STATE = "key_restore_state"
private const val TRACKING_ERROR_CAUSE_OFFLINE = "offline"
private const val TRACKING_ERROR_CAUSE_REMOTE = "remote"
private const val TRACKING_ERROR_CAUSE_OTHER = "other"
@Parcelize
@SuppressLint("ParcelCreator")
data class RestoreState(
val rewindId: String? = null,
val optionsSelected: List<Pair<Int, Boolean>>? = null,
val restoreId: Long? = null,
val published: Date? = null,
val errorType: Int? = null,
val shouldInitProgress: Boolean = true,
val shouldInitDetails: Boolean = true
) : WizardState, Parcelable
typealias NavigationTarget = WizardNavigationTarget<RestoreStep, RestoreState>
class RestoreViewModel @Inject constructor(
private val wizardManager: WizardManager<RestoreStep>,
private val availableItemsProvider: JetpackAvailableItemsProvider,
private val getActivityLogItemUseCase: GetActivityLogItemUseCase,
private val stateListItemBuilder: RestoreStateListItemBuilder,
private val postRestoreUseCase: PostRestoreUseCase,
private val getRestoreStatusUseCase: GetRestoreStatusUseCase,
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,
private val percentFormatter: PercentFormatter
) : ScopedViewModel(mainDispatcher) {
private var isStarted = false
private lateinit var site: SiteModel
private lateinit var activityId: String
private lateinit var restoreState: RestoreState
private val progressStart = 0
private val _wizardFinishedObservable = MutableLiveData<Event<RestoreWizardState>>()
val wizardFinishedObservable: LiveData<Event<RestoreWizardState>> = _wizardFinishedObservable
private val _snackbarEvents = MediatorLiveData<Event<SnackbarMessageHolder>>()
val snackbarEvents: LiveData<Event<SnackbarMessageHolder>> = _snackbarEvents
private val _navigationEvents = MediatorLiveData<Event<RestoreNavigationEvents>>()
val navigationEvents: LiveData<Event<RestoreNavigationEvents>> = _navigationEvents
private val _uiState = MutableLiveData<RestoreUiState>()
val uiState: LiveData<RestoreUiState> = _uiState
private val wizardObserver = Observer { data: RestoreStep? ->
data?.let {
clearOldRestoreState(it)
showStep(NavigationTarget(it, restoreState))
}
}
fun start(site: SiteModel, activityId: String, savedInstanceState: Bundle?) {
if (isStarted) return
isStarted = true
this.site = site
this.activityId = activityId
wizardManager.navigatorLiveData.observeForever(wizardObserver)
if (savedInstanceState == null) {
restoreState = RestoreState()
// Show the next step only if it's a fresh activity so we can handle the navigation
wizardManager.showNextStep()
} else {
restoreState = requireNotNull(savedInstanceState.getParcelable(KEY_RESTORE_STATE))
val currentStepIndex = savedInstanceState.getInt(KEY_RESTORE_CURRENT_STEP)
wizardManager.setCurrentStepIndex(currentStepIndex)
}
}
fun onBackPressed() {
when (wizardManager.currentStep) {
DETAILS.id -> _wizardFinishedObservable.value = Event(RestoreCanceled)
WARNING.id -> _wizardFinishedObservable.value = Event(RestoreCanceled)
PROGRESS.id -> _wizardFinishedObservable.value = constructProgressEvent()
COMPLETE.id -> _wizardFinishedObservable.value = Event(RestoreCompleted)
ERROR.id -> _wizardFinishedObservable.value = Event(RestoreCanceled)
}
}
private fun constructProgressEvent() = if (restoreState.restoreId != null) {
Event(
RestoreInProgress(
restoreState.rewindId as String,
restoreState.restoreId as Long
)
)
} else {
Event(RestoreCanceled)
}
fun writeToBundle(outState: Bundle) {
outState.putInt(KEY_RESTORE_CURRENT_STEP, wizardManager.currentStep)
outState.putParcelable(KEY_RESTORE_STATE, restoreState)
}
private fun buildDetails(isAwaitingCredentials: Boolean = false) {
launch {
val availableItems = availableItemsProvider.getAvailableItems()
val activityLogModel = getActivityLogItemUseCase.get(activityId)
if (activityLogModel != null) {
if (restoreState.shouldInitDetails) {
restoreState = restoreState.copy(shouldInitDetails = false)
queryRestoreStatus(checkIfAwaitingCredentials = true)
} else {
_uiState.value = DetailsState(
activityLogModel = activityLogModel,
items = stateListItemBuilder.buildDetailsListStateItems(
availableItems = availableItems,
published = activityLogModel.published,
siteId = site.siteId,
isAwaitingCredentials = isAwaitingCredentials,
onCreateDownloadClick = this@RestoreViewModel::onRestoreSiteClick,
onCheckboxItemClicked = this@RestoreViewModel::onCheckboxItemClicked,
onEnterServerCredsIconClicked = this@RestoreViewModel::onEnterServerCredsIconClicked
),
type = StateType.DETAILS
)
}
} else {
trackError(TRACKING_ERROR_CAUSE_OTHER)
transitionToError(GenericFailure)
}
}
}
private fun buildWarning() {
_uiState.value = WarningState(
items = stateListItemBuilder.buildWarningListStateItems(
published = restoreState.published as Date,
onConfirmRestoreClick = this@RestoreViewModel::onConfirmRestoreClick,
onCancelClick = this@RestoreViewModel::onCancelClick
),
type = StateType.WARNING
)
}
private fun buildProgress() {
_uiState.value = ProgressState(
items = stateListItemBuilder.buildProgressListStateItems(
progress = progressStart,
published = restoreState.published as Date,
isIndeterminate = true
),
type = StateType.PROGRESS
)
if (restoreState.shouldInitProgress) {
restoreState = restoreState.copy(shouldInitProgress = false)
launch {
val result = postRestoreUseCase.postRestoreRequest(
restoreState.rewindId as String,
site,
buildRewindRequestTypes(restoreState.optionsSelected)
)
handleRestoreRequestResult(result)
}
} else {
queryRestoreStatus()
}
}
private fun buildComplete() {
_uiState.value = CompleteState(
items = stateListItemBuilder.buildCompleteListStateItems(
published = restoreState.published as Date,
onDoneClick = this@RestoreViewModel::onDoneClick,
onVisitSiteClick = this@RestoreViewModel::onVisitSiteClick
),
type = StateType.COMPLETE
)
}
private fun buildError(errorType: RestoreErrorTypes) {
_uiState.value = ErrorState(
items = stateListItemBuilder.buildErrorListStateErrorItems(
errorType = errorType,
onDoneClick = this@RestoreViewModel::onDoneClick
),
errorType = errorType
)
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
fun showStep(target: WizardNavigationTarget<RestoreStep, RestoreState>) {
when (target.wizardStep) {
DETAILS -> buildDetails()
WARNING -> buildWarning()
PROGRESS -> buildProgress()
COMPLETE -> buildComplete()
ERROR -> buildError(
RestoreErrorTypes.fromInt(
target.wizardState.errorType ?: GenericFailure.id
)
)
}
}
private fun transitionToError(errorType: RestoreErrorTypes) {
restoreState = restoreState.copy(errorType = errorType.id)
wizardManager.setCurrentStepIndex(RestoreStep.indexForErrorTransition())
wizardManager.showNextStep()
}
private fun getParams(): Pair<String?, List<Pair<Int, Boolean>>> {
val rewindId = (_uiState.value as? DetailsState)?.activityLogModel?.rewindID
val items = _uiState.value?.items ?: mutableListOf()
val options = buildOptionsSelected(items)
return rewindId to options
}
private fun buildOptionsSelected(items: List<JetpackListItemState>): List<Pair<Int, Boolean>> {
val checkboxes = items.filterIsInstance(CheckboxState::class.java)
return listOf(
Pair(
THEMES.id,
checkboxes.firstOrNull { it.availableItemType == THEMES }?.checked ?: true
),
Pair(
PLUGINS.id,
checkboxes.firstOrNull { it.availableItemType == PLUGINS }?.checked ?: true
),
Pair(
MEDIA_UPLOADS.id,
checkboxes.firstOrNull { it.availableItemType == MEDIA_UPLOADS }?.checked
?: true
),
Pair(
SQLS.id,
checkboxes.firstOrNull { it.availableItemType == SQLS }?.checked ?: true
),
Pair(
ROOTS.id,
checkboxes.firstOrNull { it.availableItemType == ROOTS }?.checked ?: true
),
Pair(
CONTENTS.id,
checkboxes.firstOrNull { it.availableItemType == CONTENTS }?.checked ?: true
)
)
}
private fun buildRewindRequestTypes(optionsSelected: List<Pair<Int, Boolean>>?) =
RewindRequestTypes(
themes = optionsSelected?.firstOrNull { it.first == THEMES.id }?.second ?: true,
plugins = optionsSelected?.firstOrNull { it.first == PLUGINS.id }?.second
?: true,
uploads = optionsSelected?.firstOrNull { it.first == MEDIA_UPLOADS.id }?.second
?: true,
sqls = optionsSelected?.firstOrNull { it.first == SQLS.id }?.second ?: true,
roots = optionsSelected?.firstOrNull { it.first == ROOTS.id }?.second ?: true,
contents = optionsSelected?.firstOrNull { it.first == CONTENTS.id }?.second
?: true
)
private fun handleRestoreRequestResult(result: RestoreRequestState) {
when (result) {
is NetworkUnavailable -> {
trackError(TRACKING_ERROR_CAUSE_OFFLINE)
handleRestoreRequestError(NetworkUnavailableMsg)
}
is RemoteRequestFailure -> {
trackError(TRACKING_ERROR_CAUSE_REMOTE)
handleRestoreRequestError(GenericFailureMsg)
}
is Success -> handleRestoreRequestSuccess(result)
is OtherRequestRunning -> {
trackError(TRACKING_ERROR_CAUSE_OTHER)
handleRestoreRequestError(OtherRequestRunningMsg)
}
else -> throw Throwable("Unexpected restoreRequestResult ${this.javaClass.simpleName}")
}
}
private fun handleRestoreRequestSuccess(result: Success) {
restoreState = restoreState.copy(
rewindId = result.rewindId,
restoreId = result.restoreId
)
(_uiState.value as? ProgressState)?.let {
val updatedItems = stateListItemBuilder.updateProgressActionButtonState(it, result.restoreId != null)
_uiState.postValue(it.copy(items = updatedItems))
}
queryRestoreStatus()
}
private fun handleRestoreRequestError(snackbarMessageHolder: SnackbarMessageHolder) {
_snackbarEvents.postValue((Event(snackbarMessageHolder)))
resetWizardIndex(DETAILS)
showStep(NavigationTarget(DETAILS, restoreState))
}
private fun resetWizardIndex(targetStep: WizardStep) {
val currentIndex = wizardManager.currentStep
val targetIndex = wizardManager.stepPosition(targetStep)
(currentIndex downTo targetIndex).forEach { _ ->
wizardManager.onBackPressed()
}
}
private fun extractPublishedDate(): Date {
return (_uiState.value as? DetailsState)?.activityLogModel?.published as Date
}
private fun queryRestoreStatus(checkIfAwaitingCredentials: Boolean = false) {
launch {
getRestoreStatusUseCase.getRestoreStatus(site, restoreState.restoreId, checkIfAwaitingCredentials)
.collect { state -> handleQueryStatus(state) }
}
}
private fun handleQueryStatus(restoreStatus: RestoreRequestState) {
when (restoreStatus) {
is NetworkUnavailable -> {
trackError(TRACKING_ERROR_CAUSE_OFFLINE)
transitionToError(RestoreErrorTypes.RemoteRequestFailure)
}
is RemoteRequestFailure -> {
trackError(TRACKING_ERROR_CAUSE_REMOTE)
transitionToError(RestoreErrorTypes.RemoteRequestFailure)
}
is AwaitingCredentials -> buildDetails(isAwaitingCredentials = restoreStatus.isAwaitingCredentials)
is Progress -> transitionToProgress(restoreStatus)
is Complete -> wizardManager.showNextStep()
is Empty -> transitionToError(RestoreErrorTypes.RemoteRequestFailure)
else -> Unit // Do nothing
}
}
private fun transitionToProgress(restoreStatus: Progress) {
(_uiState.value as? ProgressState)?.let { content ->
val updatedList = content.items.map { contentState ->
if (contentState.type == ViewType.PROGRESS) {
contentState as JetpackListItemState.ProgressState
contentState.copy(
progress = restoreStatus.progress ?: 0,
progressLabel = UiStringText(percentFormatter.format(restoreStatus.progress ?: 0)),
progressInfoLabel = if (restoreStatus.currentEntry != null) {
UiStringText("${restoreStatus.currentEntry}")
} else {
null
},
progressStateLabel = if (restoreStatus.message != null) {
UiStringText("${restoreStatus.message}")
} else {
null
},
isIndeterminate = (restoreStatus.progress ?: 0) <= 0
)
} else {
contentState
}
}
_uiState.postValue(content.copy(items = updatedList))
}
}
private fun clearOldRestoreState(wizardStep: RestoreStep) {
if (wizardStep == DETAILS) {
restoreState = restoreState.copy(
rewindId = null,
restoreId = null,
errorType = null,
optionsSelected = null,
published = null,
shouldInitProgress = true,
shouldInitDetails = true
)
}
}
private fun onCheckboxItemClicked(itemType: JetpackAvailableItemType) {
(_uiState.value as? DetailsState)?.let {
val updatedItems = stateListItemBuilder.updateCheckboxes(it, itemType)
_uiState.postValue(it.copy(items = updatedItems))
}
}
private fun onEnterServerCredsIconClicked() {
_navigationEvents.postValue(Event(ShowJetpackSettings("${Constants.URL_JETPACK_SETTINGS}/${site.siteId}")))
}
private fun onRestoreSiteClick() {
val (rewindId, optionsSelected) = getParams()
if (rewindId == null) {
trackError(TRACKING_ERROR_CAUSE_OTHER)
transitionToError(GenericFailure)
} else {
restoreState = restoreState.copy(
rewindId = rewindId,
optionsSelected = optionsSelected,
published = extractPublishedDate(),
shouldInitProgress = true
)
wizardManager.showNextStep()
}
}
private fun onConfirmRestoreClick() {
if (restoreState.rewindId == null) {
trackError(TRACKING_ERROR_CAUSE_OTHER)
transitionToError(GenericFailure)
} else {
trackRestoreConfirmed()
wizardManager.showNextStep()
}
}
private fun onCancelClick() {
wizardManager.onBackPressed()
showStep(NavigationTarget(DETAILS, restoreState))
}
private fun onVisitSiteClick() {
site.url?.let { _navigationEvents.postValue(Event(VisitSite(site.url))) }
}
private fun onDoneClick() {
_wizardFinishedObservable.value = Event(RestoreCanceled)
}
override fun onCleared() {
super.onCleared()
wizardManager.navigatorLiveData.removeObserver(wizardObserver)
}
private fun trackRestoreConfirmed() {
val types = buildRewindRequestTypes(restoreState.optionsSelected)
val propertiesSetup = mapOf(
"themes" to types.themes,
"plugins" to types.plugins,
"uploads" to types.uploads,
"sqls" to types.sqls,
"roots" to types.roots,
"contents" to types.contents
)
val map = mapOf("restore_types" to JSONObject(propertiesSetup))
AnalyticsTracker.track(JETPACK_RESTORE_CONFIRMED, map)
}
private fun trackError(cause: String) {
val properties: MutableMap<String, String?> = HashMap()
properties["cause"] = cause
AnalyticsTracker.track(JETPACK_RESTORE_ERROR, properties)
}
companion object {
private val NetworkUnavailableMsg = SnackbarMessageHolder(UiStringRes(R.string.error_network_connection))
private val GenericFailureMsg = SnackbarMessageHolder(UiStringRes(R.string.restore_generic_failure))
private val OtherRequestRunningMsg =
SnackbarMessageHolder(UiStringRes(R.string.restore_another_process_running))
}
@SuppressLint("ParcelCreator")
sealed class RestoreWizardState : Parcelable {
@Parcelize
object RestoreCanceled : RestoreWizardState()
@Parcelize
data class RestoreInProgress(
val rewindId: String,
val restoreId: Long
) : RestoreWizardState()
@Parcelize
object RestoreCompleted : RestoreWizardState()
}
}
|
gpl-2.0
|
ea24365894223ec87f4e0f79395035f8
| 43.836364 | 125 | 0.655961 | 5.716273 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/test/java/org/wordpress/android/ui/jetpack/scan/details/ThreatDetailsViewModelTest.kt
|
1
|
18904
|
package org.wordpress.android.ui.jetpack.scan.details
import kotlinx.coroutines.InternalCoroutinesApi
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers.anyLong
import org.mockito.Mock
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.wordpress.android.BaseUnitTest
import org.wordpress.android.Constants
import org.wordpress.android.R
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.ScanStore
import org.wordpress.android.test
import org.wordpress.android.ui.jetpack.common.JetpackListItemState
import org.wordpress.android.ui.jetpack.common.JetpackListItemState.ActionButtonState
import org.wordpress.android.ui.jetpack.common.JetpackListItemState.DescriptionState
import org.wordpress.android.ui.jetpack.scan.ScanListItemState.FootnoteState
import org.wordpress.android.ui.jetpack.scan.ThreatTestData
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsNavigationEvents.OpenThreatActionDialog
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsNavigationEvents.ShowJetpackSettings
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsNavigationEvents.ShowUpdatedFixState
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsNavigationEvents.ShowUpdatedScanStateWithMessage
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsViewModel.UiState
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsViewModel.UiState.Content
import org.wordpress.android.ui.jetpack.scan.details.usecases.GetThreatModelUseCase
import org.wordpress.android.ui.jetpack.scan.details.usecases.IgnoreThreatUseCase
import org.wordpress.android.ui.jetpack.scan.details.usecases.IgnoreThreatUseCase.IgnoreThreatState.Failure
import org.wordpress.android.ui.jetpack.scan.details.usecases.IgnoreThreatUseCase.IgnoreThreatState.Success
import org.wordpress.android.ui.jetpack.scan.usecases.FixThreatsUseCase
import org.wordpress.android.ui.jetpack.scan.usecases.FixThreatsUseCase.FixThreatsState
import org.wordpress.android.ui.mysite.SelectedSiteRepository
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.utils.HtmlMessageUtils
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.ui.utils.UiString.UiStringText
import org.wordpress.android.util.analytics.ScanTracker
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ResourceProvider
private const val ON_FIX_THREAT_BUTTON_CLICKED_PARAM_POSITION = 3
private const val ON_GET_FREE_ESTIMATE_BUTTON_CLICKED_PARAM_POSITION = 4
private const val ON_IGNORE_THREAT_BUTTON_CLICKED_PARAM_POSITION = 5
private const val ON_ENTER_SERVER_CREDS_ICON_CLICKED_PARAM_POSITION = 6
private const val TEST_SITE_NAME = "test site name"
private const val TEST_SITE_ID = 1L
private const val SERVER_CREDS_LINK = "${Constants.URL_JETPACK_SETTINGS}/$TEST_SITE_ID}"
@InternalCoroutinesApi
class ThreatDetailsViewModelTest : BaseUnitTest() {
@Mock private lateinit var site: SiteModel
@Mock private lateinit var getThreatModelUseCase: GetThreatModelUseCase
@Mock private lateinit var ignoreThreatUseCase: IgnoreThreatUseCase
@Mock private lateinit var fixThreatsUseCase: FixThreatsUseCase
@Mock private lateinit var selectedSiteRepository: SelectedSiteRepository
@Mock private lateinit var builder: ThreatDetailsListItemsBuilder
@Mock private lateinit var htmlMessageUtils: HtmlMessageUtils
@Mock private lateinit var resourceProvider: ResourceProvider
@Mock private lateinit var scanTracker: ScanTracker
@Mock private lateinit var scanStore: ScanStore
private lateinit var viewModel: ThreatDetailsViewModel
private val threatId = 1L
private val fakeUiStringText = UiStringText("")
private val fakeThreatModel = ThreatTestData.fixableThreatInCurrentStatus.copy(
baseThreatModel = ThreatTestData.fixableThreatInCurrentStatus.baseThreatModel.copy(id = threatId)
)
@Before
fun setUp() = test {
viewModel = ThreatDetailsViewModel(
getThreatModelUseCase,
ignoreThreatUseCase,
fixThreatsUseCase,
selectedSiteRepository,
scanStore,
builder,
htmlMessageUtils,
resourceProvider,
scanTracker
)
whenever(site.name).thenReturn(TEST_SITE_NAME)
whenever(selectedSiteRepository.getSelectedSite()).thenReturn(site)
whenever(htmlMessageUtils.getHtmlMessageFromStringFormatResId(any(), any())).thenReturn(mock())
whenever(getThreatModelUseCase.get(anyLong())).thenReturn(fakeThreatModel)
whenever(builder.buildThreatDetailsListItems(any(), any(), any(), any(), any(), any(), any())).thenAnswer {
createDummyThreatDetailsListItems(
it.getArgument(ON_FIX_THREAT_BUTTON_CLICKED_PARAM_POSITION),
it.getArgument(ON_IGNORE_THREAT_BUTTON_CLICKED_PARAM_POSITION),
it.getArgument(ON_ENTER_SERVER_CREDS_ICON_CLICKED_PARAM_POSITION)
)
}
whenever(builder.buildFixableThreatDescription(any())).thenAnswer {
DescriptionState(UiStringRes(R.string.threat_fix_fixable_edit))
}
whenever(scanStore.hasValidCredentials(site)).thenReturn(true)
}
@Test
fun `given threat id, when on start, then threat details are retrieved`() = test {
viewModel.start(threatId)
verify(getThreatModelUseCase).get(threatId)
}
@Test
fun `given threat id, when on start, then ui is updated with content`() = test {
val uiStates = init().uiStates
val uiState = uiStates.last()
assertThat(uiState).isInstanceOf(Content::class.java)
}
@Test
fun `when fix threat button is clicked, then open threat action dialog action is triggered for fix threat`() =
test {
val observers = init()
(observers.uiStates.last() as Content).items.filterIsInstance<ActionButtonState>()
.first().onClick.invoke()
assertThat(observers.navigation.last().peekContent()).isInstanceOf(OpenThreatActionDialog::class.java)
}
@Test
fun `when open threat action dialog is triggered for fix threat, then fix threat confirmation dialog is shown`() =
test {
val observers = init()
(observers.uiStates.last() as Content).items.filterIsInstance<ActionButtonState>()
.first().onClick.invoke()
val confirmationDialog = observers.navigation.last().peekContent() as OpenThreatActionDialog
with(confirmationDialog) {
assertThat(title).isEqualTo(UiStringRes(R.string.threat_fix))
val fixable = requireNotNull(fakeThreatModel.baseThreatModel.fixable)
assertThat(message).isEqualTo(builder.buildFixableThreatDescription(fixable).text)
assertThat(positiveButtonLabel).isEqualTo(R.string.dialog_button_ok)
assertThat(negativeButtonLabel).isEqualTo(R.string.dialog_button_cancel)
}
}
@Test
fun `when get free estimate button is clicked, then ShowGetFreeEstimate event is triggered`() = test {
whenever(builder.buildThreatDetailsListItems(any(), any(), any(), any(), any(), any(), any())).thenAnswer {
createDummyThreatDetailsListItems(
it.getArgument(ON_GET_FREE_ESTIMATE_BUTTON_CLICKED_PARAM_POSITION)
)
}
val observers = init()
(observers.uiStates.last() as Content).items.filterIsInstance<ActionButtonState>()
.first().onClick.invoke()
assertThat(observers.navigation.last().peekContent())
.isInstanceOf(ThreatDetailsNavigationEvents.ShowGetFreeEstimate::class.java)
}
@Test
fun `when enter server creds icon is clicked, then app opens site's jetpack settings external url`() = test {
whenever(builder.buildThreatDetailsListItems(any(), any(), any(), any(), any(), any(), any())).thenAnswer {
createDummyThreatDetailsListItems(
onEnterServerCredsIconClicked = it
.getArgument(ON_ENTER_SERVER_CREDS_ICON_CLICKED_PARAM_POSITION)
)
}
val observers = init()
(observers.uiStates.last() as Content)
.items
.filterIsInstance(FootnoteState::class.java)
.firstOrNull { it.text == UiStringText(SERVER_CREDS_LINK) }
?.onIconClick
?.invoke()
assertThat(observers.navigation.last().peekContent()).isEqualTo(
ShowJetpackSettings("${Constants.URL_JETPACK_SETTINGS}/${site.siteId}")
)
}
@Test
fun `given server unavailable, when fix threat action is triggered, then fix threat error msg is shown`() =
test {
whenever(fixThreatsUseCase.fixThreats(any(), any()))
.thenReturn(FixThreatsState.Failure.RemoteRequestFailure)
val observers = init()
triggerFixThreatAction(observers)
val snackBarMsg = observers.snackBarMsgs.last().peekContent()
assertThat(snackBarMsg).isEqualTo(SnackbarMessageHolder(UiStringRes(R.string.threat_fix_error_message)))
}
@Test
fun `given no network, when fix threat action is triggered, then network error msg is shown`() = test {
whenever(fixThreatsUseCase.fixThreats(any(), any())).thenReturn(FixThreatsState.Failure.NetworkUnavailable)
val observers = init()
triggerFixThreatAction(observers)
val snackBarMsg = observers.snackBarMsgs.last().peekContent()
assertThat(snackBarMsg).isEqualTo(SnackbarMessageHolder(UiStringRes(R.string.error_generic_network)))
}
@Test
fun `when ok button on fix action confirmation dialog is clicked, then action buttons are disabled`() = test {
val observers = init()
triggerFixThreatAction(observers)
val contentItems = (observers.uiStates.last() as Content).items
val ignoreThreatButton = contentItems.filterIsInstance<ActionButtonState>().first()
assertThat(ignoreThreatButton.isEnabled).isEqualTo(false)
}
@Test
fun `given failure response, when fix threat action is triggered, then action buttons are enabled`() = test {
whenever(fixThreatsUseCase.fixThreats(any(), any())).thenReturn(FixThreatsState.Failure.RemoteRequestFailure)
val observers = init()
triggerFixThreatAction(observers)
val contentItems = (observers.uiStates.last() as Content).items
val ignoreThreatButton = contentItems.filterIsInstance<ActionButtonState>().first()
assertThat(ignoreThreatButton.isEnabled).isEqualTo(true)
}
@Test
fun `given success response, when fix threat action is triggered, then update fix state action is triggered`() =
test {
whenever(fixThreatsUseCase.fixThreats(any(), any())).thenReturn(FixThreatsState.Success)
val observers = init()
triggerFixThreatAction(observers)
assertThat(observers.navigation.last().peekContent()).isEqualTo(ShowUpdatedFixState(threatId))
}
@Test
fun `when ignore threat button is clicked, then open threat action dialog action is triggered for ignore threat`() =
test {
val observers = init()
(observers.uiStates.last() as Content).items.filterIsInstance<ActionButtonState>()
.last().onClick.invoke()
assertThat(observers.navigation.last().peekContent()).isInstanceOf(OpenThreatActionDialog::class.java)
}
@Test
fun `when open threat action dialog triggered for ignore threat, then ignore threat confirmation dialog shown`() =
test {
val observers = init()
(observers.uiStates.last() as Content).items.filterIsInstance<ActionButtonState>()
.last().onClick.invoke()
val siteName = site.name ?: resourceProvider.getString(R.string.scan_this_site)
val confirmationDialog = observers.navigation.last().peekContent() as OpenThreatActionDialog
with(confirmationDialog) {
assertThat(title).isEqualTo(UiStringRes(R.string.threat_ignore))
assertThat(message).isEqualTo(
UiStringText(
htmlMessageUtils
.getHtmlMessageFromStringFormatResId(
R.string.threat_ignore_warning,
"<b>$siteName</b>"
)
)
)
assertThat(positiveButtonLabel).isEqualTo(R.string.dialog_button_ok)
assertThat(negativeButtonLabel).isEqualTo(R.string.dialog_button_cancel)
}
}
@Test
fun `given server unavailable, when ignore threat action is triggered, then ignore threat error msg is shown`() =
test {
whenever(ignoreThreatUseCase.ignoreThreat(any(), any())).thenReturn(Failure.RemoteRequestFailure)
val observers = init()
triggerIgnoreThreatAction(observers)
val snackBarMsg = observers.snackBarMsgs.last().peekContent()
assertThat(snackBarMsg)
.isEqualTo(SnackbarMessageHolder(UiStringRes(R.string.threat_ignore_error_message)))
}
@Test
fun `given no network, when ignore threat action is triggered, then network error msg is shown`() = test {
whenever(ignoreThreatUseCase.ignoreThreat(any(), any())).thenReturn(Failure.NetworkUnavailable)
val observers = init()
triggerIgnoreThreatAction(observers)
val snackBarMsg = observers.snackBarMsgs.last().peekContent()
assertThat(snackBarMsg).isEqualTo(SnackbarMessageHolder(UiStringRes(R.string.error_generic_network)))
}
@Test
fun `when ok button on ignore action confirmation dialog is clicked, then action buttons are disabled`() = test {
val observers = init()
triggerIgnoreThreatAction(observers)
val contentItems = (observers.uiStates.last() as Content).items
val ignoreThreatButton = contentItems.filterIsInstance<ActionButtonState>().first()
assertThat(ignoreThreatButton.isEnabled).isEqualTo(false)
}
@Test
fun `given failure response, when threat action fails, then action buttons are enabled`() = test {
whenever(ignoreThreatUseCase.ignoreThreat(any(), any())).thenReturn(Failure.RemoteRequestFailure)
val observers = init()
triggerIgnoreThreatAction(observers)
val contentItems = (observers.uiStates.last() as Content).items
val ignoreThreatButton = contentItems.filterIsInstance<ActionButtonState>().first()
assertThat(ignoreThreatButton.isEnabled).isEqualTo(true)
}
@Test
fun `given success response, when ignore threat action is triggered, then update scan state action is triggered`() =
test {
whenever(ignoreThreatUseCase.ignoreThreat(any(), any())).thenReturn(Success)
val observers = init()
triggerIgnoreThreatAction(observers)
assertThat(observers.navigation.last().peekContent())
.isEqualTo(ShowUpdatedScanStateWithMessage(R.string.threat_ignore_success_message))
}
private fun triggerIgnoreThreatAction(observers: Observers) {
(observers.uiStates.last() as Content).items.filterIsInstance<ActionButtonState>().last().onClick.invoke()
(observers.navigation.last().peekContent() as OpenThreatActionDialog).okButtonAction.invoke()
}
private fun triggerFixThreatAction(observers: Observers) {
(observers.uiStates.last() as Content).items.filterIsInstance<ActionButtonState>().first().onClick.invoke()
(observers.navigation.last().peekContent() as OpenThreatActionDialog).okButtonAction.invoke()
}
private fun createDummyThreatDetailsListItems(
primaryAction: (() -> Unit)? = null,
secondaryAction: (() -> Unit)? = null,
onEnterServerCredsIconClicked: (() -> Unit)? = null
): List<JetpackListItemState> {
val items = ArrayList<JetpackListItemState>()
primaryAction?.let {
items.add(
ActionButtonState(
text = fakeUiStringText,
contentDescription = fakeUiStringText,
isSecondary = false,
onClick = primaryAction
)
)
}
secondaryAction?.let {
items.add(
ActionButtonState(
text = fakeUiStringText,
contentDescription = fakeUiStringText,
isSecondary = true,
onClick = secondaryAction
)
)
}
onEnterServerCredsIconClicked?.let {
items.add(
FootnoteState(
iconResId = R.drawable.ic_plus_white_24dp,
iconColorResId = R.color.primary,
text = UiStringText(SERVER_CREDS_LINK),
onIconClick = onEnterServerCredsIconClicked
)
)
}
return items
}
private fun init(): Observers {
val uiStates = mutableListOf<UiState>()
viewModel.uiState.observeForever {
uiStates.add(it)
}
val snackbarMsgs = mutableListOf<Event<SnackbarMessageHolder>>()
viewModel.snackbarEvents.observeForever {
snackbarMsgs.add(it)
}
val navigation = mutableListOf<Event<ThreatDetailsNavigationEvents>>()
viewModel.navigationEvents.observeForever {
navigation.add(it)
}
viewModel.start(threatId)
return Observers(uiStates, snackbarMsgs, navigation)
}
private data class Observers(
val uiStates: List<UiState>,
val snackBarMsgs: List<Event<SnackbarMessageHolder>>,
val navigation: List<Event<ThreatDetailsNavigationEvents>>
)
}
|
gpl-2.0
|
61e43d103d1556d776a3f97d70ca8570
| 44.883495 | 120 | 0.665415 | 5.40887 | false | true | false | false |
RadiationX/ForPDA
|
app/src/main/java/forpdateam/ru/forpda/entity/remote/devdb/Brands.kt
|
1
|
411
|
package forpdateam.ru.forpda.entity.remote.devdb
import java.util.LinkedHashMap
/**
* Created by radiationx on 06.08.17.
*/
class Brands {
val letterMap = LinkedHashMap<String, List<Item>>()
var catId: String? = null
var catTitle: String? = null
var actual = 0
var all = 0
class Item {
var title: String? = null
var id: String? = null
var count = 0
}
}
|
gpl-3.0
|
fc3541ffaa8cd3903db057bee3865554
| 18.571429 | 55 | 0.615572 | 3.605263 | false | false | false | false |
RadiationX/ForPDA
|
app/src/main/java/forpdateam/ru/forpda/presentation/main/MainPresenter.kt
|
1
|
2561
|
package forpdateam.ru.forpda.presentation.main
import moxy.InjectViewState
import forpdateam.ru.forpda.App
import forpdateam.ru.forpda.common.mvp.BasePresenter
import forpdateam.ru.forpda.entity.common.AuthState
import forpdateam.ru.forpda.model.AuthHolder
import forpdateam.ru.forpda.model.interactors.other.MenuRepository
import forpdateam.ru.forpda.model.interactors.qms.QmsInteractor
import forpdateam.ru.forpda.model.preferences.MainPreferencesHolder
import forpdateam.ru.forpda.model.preferences.OtherPreferencesHolder
import forpdateam.ru.forpda.presentation.IErrorHandler
import forpdateam.ru.forpda.presentation.ILinkHandler
import forpdateam.ru.forpda.presentation.Screen
import forpdateam.ru.forpda.presentation.TabRouter
@InjectViewState
class MainPresenter(
private val router: TabRouter,
private val authHolder: AuthHolder,
private val linkHandler: ILinkHandler,
private val menuRepository: MenuRepository,
private val qmsInteractor: QmsInteractor,
private val otherPreferencesHolder: OtherPreferencesHolder,
private val mainPreferencesHolder: MainPreferencesHolder,
private val errorHandler: IErrorHandler
) : BasePresenter<MainView>() {
private var isRestored: Boolean = false
private var startLink: String = ""
override fun onFirstViewAttach() {
super.onFirstViewAttach()
qmsInteractor.subscribeEvents()
val firstAppStart = otherPreferencesHolder.getAppFirstStart()
if (firstAppStart) {
viewState.showFirstStartAnimation()
otherPreferencesHolder.setAppFirstStart(false)
}
val linkHandled = linkHandler.handle(startLink, router)
if (!isRestored && !linkHandled) {
val authState = authHolder.get().state
if (firstAppStart && authState == AuthState.NO_AUTH) {
router.navigateTo(Screen.Auth())
} else {
val lastMenuId = menuRepository.getLastOpened()
val screen: Screen = if (menuRepository.menuItemContains(lastMenuId)) {
menuRepository.getMenuItem(lastMenuId).screen ?: Screen.ArticleList()
} else {
Screen.ArticleList()
}
router.navigateTo(screen)
}
}
}
fun setIsRestored(restored: Boolean) {
isRestored = restored
}
fun setStartLink(link: String) {
startLink = link
}
fun openLink(url: String) {
linkHandler.handle(url, router)
}
}
|
gpl-3.0
|
9759a85e333ce3416d97b16d88e3eeaa
| 33.621622 | 89 | 0.695041 | 5.051282 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.