diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/candidate/CandidateTypes.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/candidate/CandidateTypes.kt index 78b610cac..643f50f84 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/candidate/CandidateTypes.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/candidate/CandidateTypes.kt @@ -6,3 +6,6 @@ const val QWERTY_GLIDE_CANDIDATE_TYPE: Byte = 45 const val CANDIDATE_TYPE_USER_TEMPLATE: Byte = 46 const val CANDIDATE_TYPE_TIME: Byte = 47 const val CANDIDATE_TYPE_ERA: Byte = 48 +const val CANDIDATE_TYPE_CALCULATION: Byte = 49 +const val CANDIDATE_TYPE_UNIT_CONVERSION: Byte = 50 +const val CANDIDATE_TYPE_UTILITY_LITERAL: Byte = 51 diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/CalculationParser.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/CalculationParser.kt new file mode 100644 index 000000000..d146da3ee --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/CalculationParser.kt @@ -0,0 +1,443 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +import java.math.BigDecimal +import java.math.MathContext +import java.math.RoundingMode +import kotlin.math.abs + +sealed interface CalculationExpression { + data class NumberLiteral(val value: BigDecimal) : CalculationExpression + data class Constant(val name: String) : CalculationExpression + data class Unary(val operator: UnaryOperator, val operand: CalculationExpression) : CalculationExpression + data class Binary( + val left: CalculationExpression, + val operator: BinaryOperator, + val right: CalculationExpression, + ) : CalculationExpression + data class Percentage(val operand: CalculationExpression) : CalculationExpression + data class Factorial(val operand: CalculationExpression) : CalculationExpression + data class Function(val name: String, val arguments: List) : CalculationExpression +} + +enum class UnaryOperator { PLUS, MINUS } +enum class BinaryOperator { ADD, SUBTRACT, MULTIPLY, DIVIDE, POWER, MOD } + +class CalculationParser( + private val maxTokens: Int = 128, + private val maxParenthesisDepth: Int = 32, +) { + private val mathContext = MathContext(34, RoundingMode.HALF_EVEN) + + fun parse(expression: String): CalculationExpression? { + val tokens = Lexer(expression, maxTokens).tokenize() ?: return null + return Parser(tokens, maxParenthesisDepth).parse() + } + + fun evaluate( + expression: CalculationExpression, + angleMode: AngleMode = AngleMode.DEGREES, + ): BigDecimal? = try { + Evaluator(angleMode, mathContext).evaluate(expression)?.takeIf(::isWithinResultLimits) + } catch (_: ArithmeticException) { + null + } catch (_: IllegalArgumentException) { + null + } + + fun calculate( + expression: String, + angleMode: AngleMode = AngleMode.DEGREES, + ): BigDecimal? = parse(expression)?.let { evaluate(it, angleMode) } + + private fun isWithinResultLimits(value: BigDecimal): Boolean { + val decimalExponent = value.precision().toLong() - value.scale().toLong() + return abs(decimalExponent) <= MAX_DECIMAL_EXPONENT + } + + private enum class TokenType { + NUMBER, IDENTIFIER, PLUS, MINUS, STAR, SLASH, CARET, PERCENT, BANG, + LEFT_PAREN, RIGHT_PAREN, COMMA, END, + } + + private data class Token(val type: TokenType, val text: String = "") + + private class Lexer( + private val source: String, + private val maxTokens: Int, + ) { + private var index = 0 + private val tokens = mutableListOf() + + fun tokenize(): List? { + while (index < source.length) { + val char = source[index] + when { + char.isWhitespace() -> index++ + char.isDigit() || (char == '.' && source.getOrNull(index + 1)?.isDigit() == true) -> { + val number = readNumber() ?: return null + tokens += Token(TokenType.NUMBER, number) + } + char.isLetter() || char == 'π' -> tokens += Token( + TokenType.IDENTIFIER, + readIdentifier().lowercase(), + ) + else -> { + val type = when (char) { + '+' -> TokenType.PLUS + '-' -> TokenType.MINUS + '*' -> TokenType.STAR + '/' -> TokenType.SLASH + '^' -> TokenType.CARET + '%' -> TokenType.PERCENT + '!' -> TokenType.BANG + '(' -> TokenType.LEFT_PAREN + ')' -> TokenType.RIGHT_PAREN + ',' -> TokenType.COMMA + else -> return null + } + tokens += Token(type, char.toString()) + index++ + } + } + if (tokens.size > maxTokens) return null + } + tokens += Token(TokenType.END) + return tokens + } + + private fun readNumber(): String? { + val start = index + var digitCount = 0 + var integerDigits = 0 + while (source.getOrNull(index)?.isDigit() == true) { + index++ + digitCount++ + integerDigits++ + } + + if (integerDigits > 0) { + var consumedGrouping = false + while (source.getOrNull(index) == ',') { + val groupStart = index + 1 + var groupLength = 0 + while (source.getOrNull(groupStart + groupLength)?.isDigit() == true) groupLength++ + val validFirstGroup = consumedGrouping || integerDigits in 1..3 + if (groupLength != 3 || !validFirstGroup) break + consumedGrouping = true + index += 4 + digitCount += 3 + } + } + + if (source.getOrNull(index) == '.') { + index++ + while (source.getOrNull(index)?.isDigit() == true) { + index++ + digitCount++ + } + } + if (digitCount == 0 || digitCount > MAX_LITERAL_DIGITS) return null + + val exponentStart = index + if (source.getOrNull(index) == 'e' || source.getOrNull(index) == 'E') { + var probe = index + 1 + if (source.getOrNull(probe) == '+' || source.getOrNull(probe) == '-') probe++ + val exponentDigitsStart = probe + while (source.getOrNull(probe)?.isDigit() == true) probe++ + if (probe > exponentDigitsStart) { + if (probe - exponentDigitsStart > 6) return null + index = probe + } else { + index = exponentStart + } + } + return source.substring(start, index).replace(",", "") + } + + private fun readIdentifier(): String { + val start = index + while (source.getOrNull(index)?.let { it.isLetter() || it == 'π' } == true) index++ + return source.substring(start, index) + } + } + + private class Parser( + private val tokens: List, + private val maxDepth: Int, + ) { + private var index = 0 + private var depth = 0 + + fun parse(): CalculationExpression? { + val result = parseAddition() ?: return null + return result.takeIf { peek().type == TokenType.END } + } + + private fun parseAddition(): CalculationExpression? { + var left = parseMultiplication() ?: return null + while (true) { + val operator = when (peek().type) { + TokenType.PLUS -> BinaryOperator.ADD + TokenType.MINUS -> BinaryOperator.SUBTRACT + else -> return left + } + advance() + val right = parseMultiplication() ?: return null + left = CalculationExpression.Binary(left, operator, right) + } + } + + private fun parseMultiplication(): CalculationExpression? { + var left = parseUnary() ?: return null + while (true) { + val explicit = when { + match(TokenType.STAR) -> BinaryOperator.MULTIPLY + match(TokenType.SLASH) -> BinaryOperator.DIVIDE + peek().type == TokenType.IDENTIFIER && peek().text == "mod" -> { + advance() + BinaryOperator.MOD + } + else -> null + } + if (explicit != null) { + val right = parseUnary() ?: return null + left = CalculationExpression.Binary(left, explicit, right) + continue + } + if (peek().type == TokenType.LEFT_PAREN || peek().type == TokenType.IDENTIFIER) { + val right = parseUnary() ?: return null + left = CalculationExpression.Binary(left, BinaryOperator.MULTIPLY, right) + continue + } + return left + } + } + + private fun parseUnary(): CalculationExpression? = when { + match(TokenType.PLUS) -> parseUnary()?.let { + CalculationExpression.Unary(UnaryOperator.PLUS, it) + } + match(TokenType.MINUS) -> parseUnary()?.let { + CalculationExpression.Unary(UnaryOperator.MINUS, it) + } + else -> parsePower() + } + + private fun parsePower(): CalculationExpression? { + val left = parsePostfix() ?: return null + if (!match(TokenType.CARET)) return left + val right = parseUnary() ?: return null + return CalculationExpression.Binary(left, BinaryOperator.POWER, right) + } + + private fun parsePostfix(): CalculationExpression? { + var value = parsePrimary() ?: return null + while (true) { + value = when { + match(TokenType.PERCENT) -> CalculationExpression.Percentage(value) + match(TokenType.BANG) -> CalculationExpression.Factorial(value) + else -> return value + } + } + } + + private fun parsePrimary(): CalculationExpression? { + if (match(TokenType.NUMBER)) { + return previous().text.toBigDecimalOrNull()?.let(CalculationExpression::NumberLiteral) + } + if (match(TokenType.IDENTIFIER)) { + val name = previous().text + if (!match(TokenType.LEFT_PAREN)) { + return if (name == "pi" || name == "π" || name == "e") { + CalculationExpression.Constant(name) + } else { + null + } + } + if (++depth > maxDepth) return null + val arguments = mutableListOf() + if (!match(TokenType.RIGHT_PAREN)) { + do { + arguments += parseAddition() ?: return null + } while (match(TokenType.COMMA)) + if (!match(TokenType.RIGHT_PAREN)) return null + } + depth-- + return CalculationExpression.Function(name, arguments) + } + if (match(TokenType.LEFT_PAREN)) { + if (++depth > maxDepth) return null + val value = parseAddition() ?: return null + if (!match(TokenType.RIGHT_PAREN)) return null + depth-- + return value + } + return null + } + + private fun peek(): Token = tokens[index] + private fun previous(): Token = tokens[index - 1] + private fun advance(): Token = tokens[index++] + private fun match(type: TokenType): Boolean { + if (peek().type != type) return false + advance() + return true + } + } + + private class Evaluator( + private val angleMode: AngleMode, + private val context: MathContext, + ) { + fun evaluate(expression: CalculationExpression): BigDecimal? = when (expression) { + is CalculationExpression.NumberLiteral -> expression.value + is CalculationExpression.Constant -> when (expression.name) { + "pi", "π" -> BigDecimal(StrictMath.PI, context) + "e" -> BigDecimal(StrictMath.E, context) + else -> null + } + is CalculationExpression.Unary -> evaluate(expression.operand)?.let { + if (expression.operator == UnaryOperator.MINUS) it.negate(context) else it + } + is CalculationExpression.Percentage -> evaluate(expression.operand) + ?.divide(ONE_HUNDRED, context) + is CalculationExpression.Factorial -> evaluate(expression.operand)?.let(::factorial) + is CalculationExpression.Binary -> evaluateBinary(expression) + is CalculationExpression.Function -> evaluateFunction(expression) + } + + private fun evaluateBinary(expression: CalculationExpression.Binary): BigDecimal? { + val left = evaluate(expression.left) ?: return null + if ( + (expression.operator == BinaryOperator.ADD || expression.operator == BinaryOperator.SUBTRACT) && + expression.right is CalculationExpression.Percentage + ) { + val percent = evaluate(expression.right.operand)?.divide(ONE_HUNDRED, context) + ?: return null + val delta = left.multiply(percent, context) + return if (expression.operator == BinaryOperator.ADD) { + left.add(delta, context) + } else { + left.subtract(delta, context) + } + } + val right = evaluate(expression.right) ?: return null + return when (expression.operator) { + BinaryOperator.ADD -> left.add(right, context) + BinaryOperator.SUBTRACT -> left.subtract(right, context) + BinaryOperator.MULTIPLY -> left.multiply(right, context) + BinaryOperator.DIVIDE -> if (right.signum() == 0) null else left.divide(right, context) + BinaryOperator.MOD -> if (right.signum() == 0) null else left.remainder(right, context) + BinaryOperator.POWER -> power(left, right) + } + } + + private fun power(base: BigDecimal, exponent: BigDecimal): BigDecimal? { + val stripped = exponent.stripTrailingZeros() + if (stripped.scale() <= 0) { + val integer = stripped.toBigIntegerExact() + if (integer.bitLength() > 31) return null + val power = integer.toInt() + if (abs(power.toLong()) > MAX_INTEGER_POWER) return null + if (power >= 0) return base.pow(power, context) + if (base.signum() == 0) return null + return BigDecimal.ONE.divide(base.pow(-power, context), context) + } + if (base.signum() < 0) return null + return finiteDecimal(StrictMath.pow(base.toDouble(), exponent.toDouble())) + } + + private fun factorial(value: BigDecimal): BigDecimal? { + val integer = try { + value.toBigIntegerExact() + } catch (_: ArithmeticException) { + return null + } + if (integer.signum() < 0 || integer.bitLength() > 31) return null + val count = integer.toInt() + if (count > MAX_FACTORIAL) return null + var result = BigDecimal.ONE + for (factor in 2..count) result = result.multiply(BigDecimal.valueOf(factor.toLong())) + return result + } + + private fun evaluateFunction(function: CalculationExpression.Function): BigDecimal? { + val args = function.arguments.map { evaluate(it) ?: return null } + fun unary(block: (Double) -> Double): BigDecimal? = + args.singleOrNull()?.toDouble()?.let(block)?.let(::finiteDecimal) + fun positiveUnary(block: (Double) -> Double): BigDecimal? { + val value = args.singleOrNull() ?: return null + if (value.signum() <= 0) return null + return finiteDecimal(block(value.toDouble())) + } + return when (function.name) { + "sqrt" -> { + val value = args.singleOrNull() ?: return null + if (value.signum() < 0) null else finiteDecimal(StrictMath.sqrt(value.toDouble())) + } + "cbrt" -> unary(StrictMath::cbrt) + "abs" -> args.singleOrNull()?.abs(context) + "sin" -> unary { StrictMath.sin(toRadians(it)) } + "cos" -> unary { StrictMath.cos(toRadians(it)) } + "tan" -> unary { StrictMath.tan(toRadians(it)) } + "asin" -> unary { fromRadians(StrictMath.asin(it)) } + "acos" -> unary { fromRadians(StrictMath.acos(it)) } + "atan" -> unary { fromRadians(StrictMath.atan(it)) } + "sinh" -> unary(StrictMath::sinh) + "cosh" -> unary(StrictMath::cosh) + "tanh" -> unary(StrictMath::tanh) + "asinh" -> unary { StrictMath.log(it + StrictMath.sqrt(it * it + 1.0)) } + "acosh" -> { + val value = args.singleOrNull()?.toDouble() ?: return null + if (value < 1.0) null else finiteDecimal( + StrictMath.log(value + StrictMath.sqrt(value * value - 1.0)) + ) + } + "atanh" -> { + val value = args.singleOrNull()?.toDouble() ?: return null + if (abs(value) >= 1.0) null else finiteDecimal( + 0.5 * StrictMath.log((1.0 + value) / (1.0 - value)) + ) + } + "log" -> when (args.size) { + 1 -> positiveUnary(StrictMath::log10) + 2 -> { + val value = args[0].toDouble() + val base = args[1].toDouble() + if (value <= 0.0 || base <= 0.0 || base == 1.0) null + else finiteDecimal(StrictMath.log(value) / StrictMath.log(base)) + } + else -> null + } + "ln" -> positiveUnary(StrictMath::log) + "exp" -> unary(StrictMath::exp) + "min" -> args.takeIf { it.isNotEmpty() }?.minOrNull() + "max" -> args.takeIf { it.isNotEmpty() }?.maxOrNull() + "floor" -> args.singleOrNull()?.setScale(0, RoundingMode.FLOOR) + "ceil" -> args.singleOrNull()?.setScale(0, RoundingMode.CEILING) + "round" -> args.singleOrNull()?.setScale(0, RoundingMode.HALF_UP) + "factorial", "fact" -> args.singleOrNull()?.let(::factorial) + else -> null + } + } + + private fun toRadians(value: Double): Double = if (angleMode == AngleMode.DEGREES) { + StrictMath.toRadians(value) + } else value + + private fun fromRadians(value: Double): Double = if (angleMode == AngleMode.DEGREES) { + StrictMath.toDegrees(value) + } else value + + private fun finiteDecimal(value: Double): BigDecimal? = + value.takeIf(Double::isFinite)?.let(BigDecimal::valueOf) + } + + private companion object { + const val MAX_LITERAL_DIGITS = 64 + const val MAX_DECIMAL_EXPONENT = 100_000L + const val MAX_INTEGER_POWER = 1_000L + const val MAX_FACTORIAL = 1_000 + val ONE_HUNDRED = BigDecimal("100") + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/ResultFormatter.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/ResultFormatter.kt new file mode 100644 index 000000000..31182d580 --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/ResultFormatter.kt @@ -0,0 +1,42 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +import java.math.BigDecimal +import java.math.MathContext +import java.math.RoundingMode + +object ResultFormatter { + private const val AUTO_DIGITS = 15 + private const val SCIENTIFIC_UPPER_EXPONENT = 12 + private const val SCIENTIFIC_LOWER_EXPONENT = -7 + + @Suppress("DEPRECATION") + fun format(value: BigDecimal, precision: Precision): String { + if (value.signum() == 0) return "0" + val rounded = when (precision) { + Precision.Auto -> { + if (value.precision() > AUTO_DIGITS) { + value.round(MathContext(AUTO_DIGITS, RoundingMode.HALF_UP)) + } else { + value + } + } + Precision.Integer -> value.setScale(0, RoundingMode.HALF_UP) + is Precision.DecimalPlaces -> value.setScale( + precision.places, + RoundingMode.HALF_UP, + ) + is Precision.SignificantDigits -> value.round( + MathContext(precision.digits, RoundingMode.HALF_UP) + ) + }.stripTrailingZeros() + if (rounded.signum() == 0) return "0" + + val exponent = rounded.precision() - rounded.scale() - 1 + return if (exponent >= SCIENTIFIC_UPPER_EXPONENT || exponent <= SCIENTIFIC_LOWER_EXPONENT) { + val mantissa = rounded.movePointLeft(exponent).stripTrailingZeros().toPlainString() + "$mantissa" + "e" + exponent + } else { + rounded.toPlainString() + } + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitExpressionParser.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitExpressionParser.kt new file mode 100644 index 000000000..275aa7c70 --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitExpressionParser.kt @@ -0,0 +1,169 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +import java.math.BigDecimal +import java.math.MathContext +import java.math.RoundingMode + +data class ParsedUnitExpression( + val category: UnitCategory, + val baseValue: BigDecimal, + val terms: List, + val canonicalSourceText: String, + val prefersCanonicalSource: Boolean, +) + +data class ParsedUnitTerm( + val value: BigDecimal, + val unit: UnitDefinition, +) + +class UnitExpressionParser( + private val registry: UnitRegistry = UnitRegistry.Default, + private val maxTerms: Int = 128, +) { + private val context = MathContext(50, RoundingMode.HALF_EVEN) + + fun parse( + expression: String, + profile: RegionalUnitProfile = RegionalUnitProfile.JAPAN, + ): ParsedUnitExpression? { + val rewritten = rewriteJapaneseTemperature(expression.trim()) + val source = rewritten.text + if (source.isEmpty()) return null + var offset = 0 + var category: UnitCategory? = null + var baseValue = BigDecimal.ZERO + val terms = mutableListOf() + val canonicalSource = StringBuilder(source.length) + var prefersCanonicalSource = rewritten.wasRewritten + + while (true) { + offset = skipSpaces(source, offset) + if (offset >= source.length) break + var sign = 1 + var operator = "" + when (source[offset]) { + '+' -> { + if (terms.isNotEmpty()) operator = "+" + offset++ + offset = skipSpaces(source, offset) + } + '-' -> { + sign = -1 + operator = "-" + offset++ + offset = skipSpaces(source, offset) + } + } + + val numberStart = offset + val number = readNumber(source, offset) ?: return null + offset = number.end + offset = skipSpaces(source, offset) + val match = registry.matchAt(source, offset, category, profile) ?: return null + offset += match.length + + val unit = match.definition + if (category == null) category = unit.category + if (unit.category != category) return null + val signedValue = if (sign < 0) number.value.negate() else number.value + terms += ParsedUnitTerm(signedValue, unit) + canonicalSource.append(operator) + canonicalSource.append(source, numberStart, number.end) + canonicalSource.append(unit.symbol) + prefersCanonicalSource = prefersCanonicalSource || match.isWordAlias + if (terms.size > maxTerms) return null + + if (category == UnitCategory.TEMPERATURE && terms.size > 1) return null + baseValue = if (category == UnitCategory.TEMPERATURE) { + unit.toBase(signedValue, context) + } else { + baseValue.add(unit.toBase(signedValue, context), context) + } + + offset = skipSpaces(source, offset) + if (offset >= source.length) break + val next = source[offset] + if (next != '+' && next != '-' && !next.isDigit() && next != '.') return null + } + + return ParsedUnitExpression( + category = category ?: return null, + baseValue = baseValue, + terms = terms, + canonicalSourceText = canonicalSource.toString(), + prefersCanonicalSource = prefersCanonicalSource, + ) + } + + private data class NumberRead(val value: BigDecimal, val end: Int) + + private fun readNumber(source: String, start: Int): NumberRead? { + var offset = start + var digits = 0 + var integerDigits = 0 + while (source.getOrNull(offset)?.isDigit() == true) { + offset++ + digits++ + integerDigits++ + } + if (integerDigits > 0) { + var consumedGrouping = false + while (source.getOrNull(offset) == ',') { + val groupStart = offset + 1 + var groupLength = 0 + while (source.getOrNull(groupStart + groupLength)?.isDigit() == true) groupLength++ + if (groupLength != 3 || (!consumedGrouping && integerDigits !in 1..3)) break + consumedGrouping = true + offset += 4 + digits += 3 + } + } + if (source.getOrNull(offset) == '.') { + offset++ + while (source.getOrNull(offset)?.isDigit() == true) { + offset++ + digits++ + } + } + if (digits == 0 || digits > MAX_LITERAL_DIGITS) return null + val exponentStart = offset + if (source.getOrNull(offset) == 'e' || source.getOrNull(offset) == 'E') { + var probe = offset + 1 + if (source.getOrNull(probe) == '+' || source.getOrNull(probe) == '-') probe++ + val exponentDigits = probe + while (source.getOrNull(probe)?.isDigit() == true) probe++ + if (probe > exponentDigits) { + if (probe - exponentDigits > 6) return null + offset = probe + } else { + offset = exponentStart + } + } + val value = source.substring(start, offset).replace(",", "").toBigDecimalOrNull() + ?: return null + return NumberRead(value, offset) + } + + private data class RewrittenSource(val text: String, val wasRewritten: Boolean) + + private fun rewriteJapaneseTemperature(source: String): RewrittenSource { + val match = JAPANESE_TEMPERATURE.matchEntire(source) + ?: return RewrittenSource(source, false) + val unit = if (match.groupValues[1] == "華氏") "°F" else "°C" + return RewrittenSource(match.groupValues[2] + unit, true) + } + + private fun skipSpaces(source: String, start: Int): Int { + var offset = start + while (source.getOrNull(offset)?.isWhitespace() == true) offset++ + return offset + } + + private companion object { + const val MAX_LITERAL_DIGITS = 64 + val JAPANESE_TEMPERATURE = Regex( + "^(華氏|摂氏)\\s*([+-]?(?:\\d+(?:,\\d{3})*|\\d*\\.\\d+)(?:[eE][+-]?\\d+)?)\\s*度?$" + ) + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitRegistry.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitRegistry.kt new file mode 100644 index 000000000..a8350be0f --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitRegistry.kt @@ -0,0 +1,299 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +import java.math.BigDecimal +import java.math.MathContext +import java.math.RoundingMode + +data class UnitDefinition( + val id: UnitId, + val category: UnitCategory, + val symbol: String, + val factorToBase: BigDecimal, + val offsetToBase: BigDecimal = BigDecimal.ZERO, + val exactAliases: Set = emptySet(), + val wordAliases: Set = emptySet(), +) { + fun toBase(value: BigDecimal, context: MathContext): BigDecimal = + value.multiply(factorToBase, context).add(offsetToBase, context) + + fun fromBase(value: BigDecimal, context: MathContext): BigDecimal = + value.subtract(offsetToBase, context).divide(factorToBase, context) +} + +class UnitRegistry private constructor( + definitions: List, +) { + private data class AliasEntry( + val alias: String, + val ignoreCase: Boolean, + val isWordAlias: Boolean, + val definition: UnitDefinition, + ) + + data class Match( + val definition: UnitDefinition, + val length: Int, + val isWordAlias: Boolean, + ) + + private val byId = definitions.associateBy(UnitDefinition::id) + private val aliasEntries = definitions.flatMap { definition -> + val exact = (definition.exactAliases + definition.symbol).map { + AliasEntry(it, false, false, definition) + } + val folded = definition.wordAliases.map { AliasEntry(it, true, true, definition) } + exact + folded + }.distinctBy { Triple(it.alias, it.ignoreCase, it.definition.id) } + .sortedByDescending { it.alias.length } + + val units: List = definitions.toList() + + fun findById(id: UnitId): UnitDefinition? = byId[id] + + fun findExact( + text: String, + expectedCategory: UnitCategory? = null, + profile: RegionalUnitProfile = RegionalUnitProfile.JAPAN, + ): UnitDefinition? { + val matches = matchCandidates(text, 0) + .filter { it.length == text.length } + .map(Match::definition) + .filter { expectedCategory == null || it.category == expectedCategory } + return resolveAmbiguity(matches, profile, expectedCategory) + } + + fun matchAt( + text: String, + offset: Int, + expectedCategory: UnitCategory? = null, + profile: RegionalUnitProfile = RegionalUnitProfile.JAPAN, + ): Match? { + val candidates = matchCandidates(text, offset) + val categoryMatches = if (expectedCategory == null) { + candidates + } else { + candidates.filter { it.definition.category == expectedCategory } + } + val longest = categoryMatches.maxOfOrNull(Match::length) ?: return null + val definitions = categoryMatches.filter { it.length == longest }.map(Match::definition) + val definition = resolveAmbiguity(definitions, profile, expectedCategory) ?: return null + val selectedMatch = categoryMatches + .asSequence() + .filter { it.length == longest && it.definition.id == definition.id } + .minByOrNull { if (it.isWordAlias) 1 else 0 } + ?: return null + return Match(definition, longest, selectedMatch.isWordAlias) + } + + private fun matchCandidates(text: String, offset: Int): List = aliasEntries.mapNotNull { entry -> + if (offset + entry.alias.length > text.length) return@mapNotNull null + val characterAfterAlias = text.getOrNull(offset + entry.alias.length) + if (entry.alias.lastOrNull()?.isDigit() == true && characterAfterAlias?.isLetter() == true) { + return@mapNotNull null + } + if (text.regionMatches(offset, entry.alias, 0, entry.alias.length, entry.ignoreCase)) { + Match(entry.definition, entry.alias.length, entry.isWordAlias) + } else { + null + } + } + + private fun resolveAmbiguity( + definitions: List, + profile: RegionalUnitProfile, + expectedCategory: UnitCategory?, + ): UnitDefinition? { + val distinct = definitions.distinctBy(UnitDefinition::id) + if (distinct.isEmpty()) return null + if (distinct.size == 1) return distinct.single() + + fun find(suffix: String) = distinct.firstOrNull { it.id.value.endsWith(suffix) } + if (expectedCategory == UnitCategory.TIME) find(".min")?.let { return it } + when (distinct.first().category) { + UnitCategory.VOLUME -> when (profile) { + RegionalUnitProfile.JAPAN -> find("_jp") ?: find("_us") + RegionalUnitProfile.UNITED_STATES -> find("_us") + RegionalUnitProfile.UNITED_KINGDOM -> find("_uk") + }?.let { return it } + UnitCategory.MASS -> when (profile) { + RegionalUnitProfile.JAPAN -> find("mass.t") + RegionalUnitProfile.UNITED_STATES -> find("short_ton") + RegionalUnitProfile.UNITED_KINGDOM -> find("long_ton") + }?.let { return it } + UnitCategory.POWER -> when (profile) { + RegionalUnitProfile.JAPAN -> find(".ps") + RegionalUnitProfile.UNITED_STATES, + RegionalUnitProfile.UNITED_KINGDOM -> find(".hp") + }?.let { return it } + else -> Unit + } + return distinct.firstOrNull() + } + + companion object { + val Default: UnitRegistry by lazy { UnitRegistry(createDefinitions()) } + + private val registryContext = MathContext(50, RoundingMode.HALF_EVEN) + + private fun decimal(value: String) = BigDecimal(value) + private fun rational(numerator: String, denominator: String) = + decimal(numerator).divide(decimal(denominator), registryContext) + + private fun unit( + id: String, + category: UnitCategory, + symbol: String, + factor: String, + vararg aliases: String, + words: Set = emptySet(), + offset: BigDecimal = BigDecimal.ZERO, + ) = UnitDefinition( + id = UnitId(id), + category = category, + symbol = symbol, + factorToBase = decimal(factor), + offsetToBase = offset, + exactAliases = aliases.toSet(), + wordAliases = words, + ) + + private fun createDefinitions(): List = buildList { + // Length (base: metre) + add(unit("length.nm", UnitCategory.LENGTH, "nm", "1e-9", words = setOf("nanometer", "nanometers", "nanometre", "nanometres", "ナノメートル"))) + add(unit("length.um", UnitCategory.LENGTH, "µm", "1e-6", "um", "μm", words = setOf("micrometer", "micrometers", "micrometre", "micrometres", "マイクロメートル"))) + add(unit("length.mm", UnitCategory.LENGTH, "mm", "1e-3", words = setOf("millimeter", "millimeters", "millimetre", "millimetres", "ミリメートル"))) + add(unit("length.cm", UnitCategory.LENGTH, "cm", "1e-2", words = setOf("centimeter", "centimeters", "centimetre", "centimetres", "センチ", "センチメートル"))) + add(unit("length.m", UnitCategory.LENGTH, "m", "1", words = setOf("meter", "meters", "metre", "metres", "メートル"))) + add(unit("length.km", UnitCategory.LENGTH, "km", "1e3", words = setOf("kilometer", "kilometers", "kilometre", "kilometres", "キロ", "キロメートル"))) + add(unit("length.angstrom", UnitCategory.LENGTH, "Å", "1e-10", "Å", words = setOf("angstrom", "angstroms", "オングストローム"))) + add(unit("length.in", UnitCategory.LENGTH, "in", "0.0254", "\"", "″", words = setOf("inch", "inches", "インチ"))) + add(unit("length.ft", UnitCategory.LENGTH, "ft", "0.3048", "'", "′", words = setOf("foot", "feet", "フィート"))) + add(unit("length.yd", UnitCategory.LENGTH, "yd", "0.9144", words = setOf("yard", "yards", "ヤード"))) + add(unit("length.mi", UnitCategory.LENGTH, "mi", "1609.344", words = setOf("mile", "miles", "マイル"))) + add(unit("length.nmi", UnitCategory.LENGTH, "nmi", "1852", words = setOf("nautical mile", "nautical miles", "海里"))) + add(unit("length.shaku", UnitCategory.LENGTH, "尺", rational("10", "33").toPlainString(), words = setOf("しゃく"))) + add(unit("length.sun", UnitCategory.LENGTH, "寸", rational("1", "33").toPlainString(), words = setOf("すん"))) + add(unit("length.kujirajaku", UnitCategory.LENGTH, "鯨尺", rational("25", "66").toPlainString())) + add(unit("length.kujirasun", UnitCategory.LENGTH, "鯨寸", rational("5", "132").toPlainString())) + + // Area (base: square metre) + add(unit("area.mm2", UnitCategory.AREA, "mm²", "1e-6", "mm2", "mm^2", words = setOf("square millimeter", "square millimeters", "平方ミリメートル"))) + add(unit("area.cm2", UnitCategory.AREA, "cm²", "1e-4", "cm2", "cm^2", words = setOf("square centimeter", "square centimeters", "平方センチメートル"))) + add(unit("area.m2", UnitCategory.AREA, "m²", "1", "m2", "m^2", words = setOf("square meter", "square meters", "square metre", "square metres", "平方メートル"))) + add(unit("area.km2", UnitCategory.AREA, "km²", "1e6", "km2", "km^2", words = setOf("square kilometer", "square kilometers", "平方キロメートル"))) + add(unit("area.in2", UnitCategory.AREA, "in²", "0.00064516", "in2", "in^2", words = setOf("square inch", "square inches"))) + add(unit("area.ft2", UnitCategory.AREA, "ft²", "0.09290304", "ft2", "ft^2", words = setOf("square foot", "square feet"))) + add(unit("area.yd2", UnitCategory.AREA, "yd²", "0.83612736", "yd2", "yd^2", words = setOf("square yard", "square yards"))) + add(unit("area.a", UnitCategory.AREA, "a", "100", words = setOf("are", "ares", "アール"))) + add(unit("area.ha", UnitCategory.AREA, "ha", "10000", words = setOf("hectare", "hectares", "ヘクタール"))) + add(unit("area.acre", UnitCategory.AREA, "acre", "4046.8564224", words = setOf("acres", "エーカー"))) + add(unit("area.tsubo", UnitCategory.AREA, "坪", rational("400", "121").toPlainString(), words = setOf("つぼ"))) + + // Volume (base: litre) + add(unit("volume.ul", UnitCategory.VOLUME, "µL", "1e-6", "uL", "μL", words = setOf("microliter", "microliters", "microlitre", "microlitres", "マイクロリットル"))) + add(unit("volume.ml", UnitCategory.VOLUME, "mL", "1e-3", words = setOf("milliliter", "milliliters", "millilitre", "millilitres", "ミリリットル"))) + add(unit("volume.l", UnitCategory.VOLUME, "L", "1", "l", words = setOf("liter", "liters", "litre", "litres", "リットル"))) + add(unit("volume.cm3", UnitCategory.VOLUME, "cm³", "1e-3", "cm3", "cm^3", "cc", words = setOf("cubic centimeter", "cubic centimeters", "立方センチメートル"))) + add(unit("volume.m3", UnitCategory.VOLUME, "m³", "1000", "m3", "m^3", words = setOf("cubic meter", "cubic meters", "cubic metre", "cubic metres", "立方メートル"))) + add(unit("volume.in3", UnitCategory.VOLUME, "in³", "0.016387064", "in3", "in^3", words = setOf("cubic inch", "cubic inches"))) + add(unit("volume.ft3", UnitCategory.VOLUME, "ft³", "28.316846592", "ft3", "ft^3", words = setOf("cubic foot", "cubic feet"))) + add(unit("volume.tsp_jp", UnitCategory.VOLUME, "tspJP", "0.005", "tspJP", words = setOf("tsp", "teaspoon", "teaspoons", "小さじ"))) + add(unit("volume.tsp_us", UnitCategory.VOLUME, "tspUS", "0.00492892159375", "tspUS", words = setOf("tsp", "teaspoon", "teaspoons"))) + add(unit("volume.tsp_uk", UnitCategory.VOLUME, "tspUK", "0.005919388020833333333333333333333333", "tspUK", words = setOf("tsp", "teaspoon", "teaspoons"))) + add(unit("volume.tbsp_jp", UnitCategory.VOLUME, "tbspJP", "0.015", "tbspJP", words = setOf("tbsp", "tablespoon", "tablespoons", "大さじ"))) + add(unit("volume.tbsp_us", UnitCategory.VOLUME, "tbspUS", "0.01478676478125", "tbspUS", words = setOf("tbsp", "tablespoon", "tablespoons"))) + add(unit("volume.tbsp_uk", UnitCategory.VOLUME, "tbspUK", "0.0177581640625", "tbspUK", words = setOf("tbsp", "tablespoon", "tablespoons"))) + add(unit("volume.cup_jp", UnitCategory.VOLUME, "cupJP", "0.2", "cupJP", words = setOf("cup", "cups", "カップ"))) + add(unit("volume.cup_us", UnitCategory.VOLUME, "cupUS", "0.2365882365", "cupUS", words = setOf("cup", "cups"))) + add(unit("volume.cup_uk", UnitCategory.VOLUME, "cupUK", "0.284130625", "cupUK", words = setOf("cup", "cups"))) + add(unit("volume.floz_us", UnitCategory.VOLUME, "flOzUS", "0.0295735295625", "fl oz US", "flOzUS", words = setOf("fl oz", "fluid ounce", "fluid ounces"))) + add(unit("volume.floz_uk", UnitCategory.VOLUME, "flOzUK", "0.0284130625", "fl oz UK", "flOzUK", words = setOf("fl oz", "fluid ounce", "fluid ounces"))) + add(unit("volume.pt_us", UnitCategory.VOLUME, "ptUS", "0.473176473", "ptUS", words = setOf("pt", "pint", "pints"))) + add(unit("volume.pt_uk", UnitCategory.VOLUME, "ptUK", "0.56826125", "ptUK", words = setOf("pt", "pint", "pints"))) + add(unit("volume.qt_us", UnitCategory.VOLUME, "qtUS", "0.946352946", "qtUS", words = setOf("qt", "quart", "quarts"))) + add(unit("volume.qt_uk", UnitCategory.VOLUME, "qtUK", "1.1365225", "qtUK", words = setOf("qt", "quart", "quarts"))) + add(unit("volume.gal_us", UnitCategory.VOLUME, "galUS", "3.785411784", "galUS", words = setOf("gal", "gallon", "gallons"))) + add(unit("volume.gal_uk", UnitCategory.VOLUME, "galUK", "4.54609", "galUK", words = setOf("gal", "gallon", "gallons"))) + add(unit("volume.go", UnitCategory.VOLUME, "合", "0.18039")) + add(unit("volume.sho", UnitCategory.VOLUME, "升", "1.8039")) + + // Mass (base: kilogram) + add(unit("mass.mg", UnitCategory.MASS, "mg", "1e-6", words = setOf("milligram", "milligrams", "ミリグラム"))) + add(unit("mass.g", UnitCategory.MASS, "g", "1e-3", words = setOf("gram", "grams", "グラム"))) + add(unit("mass.kg", UnitCategory.MASS, "kg", "1", words = setOf("kilogram", "kilograms", "キログラム", "キロ"))) + add(unit("mass.t", UnitCategory.MASS, "t", "1000", words = setOf("ton", "tons", "tonne", "tonnes", "metric ton", "metric tons", "トン"))) + add(unit("mass.oz", UnitCategory.MASS, "oz", "0.028349523125", words = setOf("ounce", "ounces", "オンス"))) + add(unit("mass.lb", UnitCategory.MASS, "lb", "0.45359237", "lbs", words = setOf("pound", "pounds", "ポンド"))) + add(unit("mass.stone", UnitCategory.MASS, "stone", "6.35029318", "st", words = setOf("stones", "ストーン"))) + add(unit("mass.short_ton", UnitCategory.MASS, "shortTon", "907.18474", "short ton", words = setOf("ton", "tons", "short ton", "short tons", "米トン"))) + add(unit("mass.long_ton", UnitCategory.MASS, "longTon", "1016.0469088", "long ton", words = setOf("ton", "tons", "long ton", "long tons", "英トン"))) + add(unit("mass.momme", UnitCategory.MASS, "匁", "0.00375", words = setOf("もんめ"))) + add(unit("mass.kan", UnitCategory.MASS, "貫", "3.75", words = setOf("かん"))) + + // Temperature (base: kelvin) + add(unit("temperature.c", UnitCategory.TEMPERATURE, "°C", "1", "℃", "C", "c", words = setOf("celsius", "degree celsius", "degrees celsius", "摂氏", "摂氏度"), offset = decimal("273.15"))) + add(unit("temperature.f", UnitCategory.TEMPERATURE, "°F", rational("5", "9").toPlainString(), "℉", "F", "f", words = setOf("fahrenheit", "degree fahrenheit", "degrees fahrenheit", "華氏", "華氏度"), offset = rational("45967", "180"))) + add(unit("temperature.k", UnitCategory.TEMPERATURE, "K", "1", words = setOf("kelvin", "kelvins", "ケルビン"))) + + // Speed (base: metre per second) + add(unit("speed.ms", UnitCategory.SPEED, "m/s", "1", words = setOf("meter per second", "meters per second", "metre per second", "秒速"))) + add(unit("speed.kmh", UnitCategory.SPEED, "km/h", rational("5", "18").toPlainString(), "kph", words = setOf("kilometer per hour", "kilometers per hour", "時速"))) + add(unit("speed.fts", UnitCategory.SPEED, "ft/s", "0.3048", "fps", words = setOf("foot per second", "feet per second"))) + add(unit("speed.mph", UnitCategory.SPEED, "mph", "0.44704", words = setOf("mile per hour", "miles per hour"))) + add(unit("speed.kn", UnitCategory.SPEED, "kn", rational("463", "900").toPlainString(), "kt", "kts", words = setOf("knot", "knots", "ノット"))) + + // Pressure (base: pascal) + add(unit("pressure.pa", UnitCategory.PRESSURE, "Pa", "1", words = setOf("pascal", "pascals", "パスカル"))) + add(unit("pressure.hpa", UnitCategory.PRESSURE, "hPa", "100", words = setOf("hectopascal", "hectopascals", "ヘクトパスカル"))) + add(unit("pressure.kpa", UnitCategory.PRESSURE, "kPa", "1000", words = setOf("kilopascal", "kilopascals", "キロパスカル"))) + add(unit("pressure.mpa", UnitCategory.PRESSURE, "MPa", "1e6", words = setOf("megapascal", "megapascals", "メガパスカル"))) + add(unit("pressure.bar", UnitCategory.PRESSURE, "bar", "100000", words = setOf("bars", "バール"))) + add(unit("pressure.atm", UnitCategory.PRESSURE, "atm", "101325", words = setOf("atmosphere", "atmospheres", "気圧"))) + add(unit("pressure.psi", UnitCategory.PRESSURE, "psi", "6894.757293168", words = setOf("pound per square inch", "pounds per square inch"))) + add(unit("pressure.mmhg", UnitCategory.PRESSURE, "mmHg", "133.322387415", words = setOf("millimeter of mercury", "millimeters of mercury"))) + add(unit("pressure.torr", UnitCategory.PRESSURE, "Torr", rational("101325", "760").toPlainString(), "torr")) + add(unit("pressure.inhg", UnitCategory.PRESSURE, "inHg", "3386.389", words = setOf("inch of mercury", "inches of mercury"))) + + // Energy (base: joule) + add(unit("energy.j", UnitCategory.ENERGY, "J", "1", words = setOf("joule", "joules", "ジュール"))) + add(unit("energy.kj", UnitCategory.ENERGY, "kJ", "1000", words = setOf("kilojoule", "kilojoules", "キロジュール"))) + add(unit("energy.mj", UnitCategory.ENERGY, "MJ", "1e6", words = setOf("megajoule", "megajoules", "メガジュール"))) + add(unit("energy.wh", UnitCategory.ENERGY, "Wh", "3600", words = setOf("watt hour", "watt hours", "ワット時"))) + add(unit("energy.kwh", UnitCategory.ENERGY, "kWh", "3600000", words = setOf("kilowatt hour", "kilowatt hours", "キロワット時"))) + add(unit("energy.cal", UnitCategory.ENERGY, "cal", "4.184", words = setOf("calorie", "calories", "カロリー"))) + add(unit("energy.kcal", UnitCategory.ENERGY, "kcal", "4184", words = setOf("kilocalorie", "kilocalories", "キロカロリー"))) + add(unit("energy.btu", UnitCategory.ENERGY, "BTU", "1055.05585262", "Btu", words = setOf("british thermal unit", "british thermal units"))) + add(unit("energy.ev", UnitCategory.ENERGY, "eV", "1.602176634e-19", words = setOf("electronvolt", "electronvolts", "電子ボルト"))) + + // Power (base: watt) + add(unit("power.mw", UnitCategory.POWER, "mW", "0.001", words = setOf("milliwatt", "milliwatts", "ミリワット"))) + add(unit("power.w", UnitCategory.POWER, "W", "1", words = setOf("watt", "watts", "ワット"))) + add(unit("power.kw", UnitCategory.POWER, "kW", "1000", words = setOf("kilowatt", "kilowatts", "キロワット"))) + add(unit("power.mw_large", UnitCategory.POWER, "MW", "1e6", words = setOf("megawatt", "megawatts", "メガワット"))) + add(unit("power.hp", UnitCategory.POWER, "hp", "745.69987158227022", words = setOf("horsepower", "mechanical horsepower", "馬力"))) + add(unit("power.ps", UnitCategory.POWER, "PS", "735.49875", words = setOf("metric horsepower", "pferdestarke", "仏馬力", "馬力"))) + + // Time (base: second) + add(unit("time.ms", UnitCategory.TIME, "ms", "0.001", words = setOf("millisecond", "milliseconds", "ミリ秒"))) + add(unit("time.s", UnitCategory.TIME, "s", "1", words = setOf("sec", "second", "seconds", "秒"))) + add(unit("time.min", UnitCategory.TIME, "min", "60", "m", words = setOf("minute", "minutes", "分"))) + add(unit("time.h", UnitCategory.TIME, "h", "3600", "hr", words = setOf("hour", "hours", "時間"))) + add(unit("time.day", UnitCategory.TIME, "day", "86400", "d", words = setOf("days", "日"))) + add(unit("time.week", UnitCategory.TIME, "week", "604800", "wk", words = setOf("weeks", "週間", "週"))) + + // Data (base: byte; SI and IEC case is significant) + add(unit("data.bit", UnitCategory.DATA, "bit", "0.125", words = setOf("bits", "ビット"))) + add(unit("data.b", UnitCategory.DATA, "B", "1", words = setOf("byte", "bytes", "バイト"))) + add(unit("data.kb", UnitCategory.DATA, "kB", "1000", words = setOf("kilobyte", "kilobytes", "キロバイト"))) + add(unit("data.mb", UnitCategory.DATA, "MB", "1000000", words = setOf("megabyte", "megabytes", "メガバイト"))) + add(unit("data.gb", UnitCategory.DATA, "GB", "1000000000", words = setOf("gigabyte", "gigabytes", "ギガバイト"))) + add(unit("data.tb", UnitCategory.DATA, "TB", "1000000000000", words = setOf("terabyte", "terabytes", "テラバイト"))) + add(unit("data.pb", UnitCategory.DATA, "PB", "1000000000000000", words = setOf("petabyte", "petabytes", "ペタバイト"))) + add(unit("data.kib", UnitCategory.DATA, "KiB", "1024", words = setOf("kibibyte", "kibibytes"))) + add(unit("data.mib", UnitCategory.DATA, "MiB", "1048576", words = setOf("mebibyte", "mebibytes"))) + add(unit("data.gib", UnitCategory.DATA, "GiB", "1073741824", words = setOf("gibibyte", "gibibytes"))) + add(unit("data.tib", UnitCategory.DATA, "TiB", "1099511627776", words = setOf("tebibyte", "tebibytes"))) + add(unit("data.pib", UnitCategory.DATA, "PiB", "1125899906842624", words = setOf("pebibyte", "pebibytes"))) + } + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitTargetSettingsJsonCodec.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitTargetSettingsJsonCodec.kt new file mode 100644 index 000000000..5b5ff8dc7 --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitTargetSettingsJsonCodec.kt @@ -0,0 +1,287 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +/** Versioned, dependency-free codec for the small unit-target preference document. */ +class UnitTargetSettingsJsonCodec( + private val registry: UnitRegistry = UnitRegistry.Default, +) { + @Suppress("DEPRECATION") + fun encode(settings: Map>): String = buildString { + append("{\"version\":") + append(CURRENT_VERSION) + append(",\"categories\":{") + UnitCategory.entries.forEachIndexed { categoryIndex, category -> + if (categoryIndex > 0) append(',') + appendJsonString(category.storageId) + append(":[") + settings[category].orEmpty().forEachIndexed { targetIndex, setting -> + if (targetIndex > 0) append(',') + append("{\"unitId\":") + appendJsonString(setting.unitId.value) + append(",\"precision\":") + appendJsonString( + when (val precision = setting.precision) { + Precision.Auto -> "auto" + Precision.Integer -> "${DECIMAL_PREFIX}0" + is Precision.DecimalPlaces -> "$DECIMAL_PREFIX${precision.places}" + is Precision.SignificantDigits -> precision.digits.toString() + } + ) + append('}') + } + append(']') + } + append("}}") + } + + fun decodeOrDefault( + json: String?, + defaults: Map> = + UtilityCandidateConfig.defaultUnitTargets(), + ): Map> { + if (json.isNullOrBlank() || json.length > MAX_JSON_LENGTH) return immutableCopy(defaults) + return try { + val root = JsonParser(json).parse() as? JsonValue.ObjectValue + ?: return immutableCopy(defaults) + val version = (root.values["version"] as? JsonValue.NumberValue) + ?.text?.toIntOrNull() + if (version != CURRENT_VERSION) return immutableCopy(defaults) + val categories = root.values["categories"] as? JsonValue.ObjectValue + ?: return immutableCopy(defaults) + UnitCategory.entries.associateWith { category -> + val storedValue = categories.values[category.storageId] + ?: return@associateWith defaults[category].orEmpty().toList() + val stored = storedValue as? JsonValue.ArrayValue + ?: throw InvalidJsonException() + stored.values.asSequence().mapNotNull { value -> + val target = value as? JsonValue.ObjectValue ?: return@mapNotNull null + val idText = (target.values["unitId"] as? JsonValue.StringValue)?.text + ?: return@mapNotNull null + val precisionText = when (val precision = target.values["precision"]) { + is JsonValue.StringValue -> precision.text + is JsonValue.NumberValue -> precision.text + else -> return@mapNotNull null + } + val id = runCatching { UnitId(idText) }.getOrNull() + ?: return@mapNotNull null + val definition = registry.findById(id) ?: return@mapNotNull null + if (definition.category != category) return@mapNotNull null + val precision = when (precisionText) { + "auto" -> Precision.Auto + "integer" -> Precision.DecimalPlaces(0) + else -> { + if (precisionText.startsWith(DECIMAL_PREFIX)) { + val places = precisionText.removePrefix(DECIMAL_PREFIX) + .toIntOrNull() + ?.takeIf { + it in Precision.MIN_DECIMAL_PLACES.. + Precision.MAX_DECIMAL_PLACES + } + ?: return@mapNotNull null + Precision.DecimalPlaces(places) + } else { + val digits = precisionText.toIntOrNull() + ?.takeIf { it in Precision.MIN_DIGITS..Precision.MAX_DIGITS } + ?: return@mapNotNull null + Precision.SignificantDigits(digits) + } + } + } + UnitTargetSetting(id, precision) + }.distinctBy(UnitTargetSetting::unitId) + .take(UtilityCandidateConfig.MAX_TARGETS_PER_CATEGORY) + .toList() + } + } catch (_: RuntimeException) { + immutableCopy(defaults) + } + } + + private fun StringBuilder.appendJsonString(value: String) { + append('"') + value.forEach { char -> + when (char) { + '"' -> append("\\\"") + '\\' -> append("\\\\") + '\b' -> append("\\b") + '\u000c' -> append("\\f") + '\n' -> append("\\n") + '\r' -> append("\\r") + '\t' -> append("\\t") + else -> if (char < ' ') { + append("\\u") + append(char.code.toString(16).padStart(4, '0')) + } else append(char) + } + } + append('"') + } + + private fun immutableCopy(settings: Map>) = + UnitCategory.entries.associateWith { settings[it].orEmpty().toList() } + + private val UnitCategory.storageId: String get() = name.lowercase() + + private sealed interface JsonValue { + data class ObjectValue(val values: Map) : JsonValue + data class ArrayValue(val values: List) : JsonValue + data class StringValue(val text: String) : JsonValue + data class NumberValue(val text: String) : JsonValue + data class BooleanValue(val value: Boolean) : JsonValue + data object NullValue : JsonValue + } + + private class InvalidJsonException : RuntimeException() + + private class JsonParser(private val source: String) { + private var offset = 0 + private var depth = 0 + + fun parse(): JsonValue { + val value = parseValue() + skipWhitespace() + if (offset != source.length) throw InvalidJsonException() + return value + } + + private fun parseValue(): JsonValue { + skipWhitespace() + return when (source.getOrNull(offset)) { + '{' -> parseObject() + '[' -> parseArray() + '"' -> JsonValue.StringValue(parseString()) + 't' -> parseLiteral("true", JsonValue.BooleanValue(true)) + 'f' -> parseLiteral("false", JsonValue.BooleanValue(false)) + 'n' -> parseLiteral("null", JsonValue.NullValue) + '-', in '0'..'9' -> JsonValue.NumberValue(parseNumber()) + else -> throw InvalidJsonException() + } + } + + private fun parseObject(): JsonValue.ObjectValue = withDepth { + expect('{') + skipWhitespace() + val values = linkedMapOf() + if (takeIf('}')) return@withDepth JsonValue.ObjectValue(values) + while (true) { + skipWhitespace() + if (source.getOrNull(offset) != '"') throw InvalidJsonException() + val key = parseString() + skipWhitespace() + expect(':') + values[key] = parseValue() + skipWhitespace() + if (takeIf('}')) break + expect(',') + } + JsonValue.ObjectValue(values) + } + + private fun parseArray(): JsonValue.ArrayValue = withDepth { + expect('[') + skipWhitespace() + val values = mutableListOf() + if (takeIf(']')) return@withDepth JsonValue.ArrayValue(values) + while (true) { + values += parseValue() + skipWhitespace() + if (takeIf(']')) break + expect(',') + } + JsonValue.ArrayValue(values) + } + + private fun parseString(): String { + expect('"') + return buildString { + while (true) { + val char = source.getOrNull(offset++) ?: throw InvalidJsonException() + when (char) { + '"' -> return@buildString + '\\' -> { + when (val escaped = source.getOrNull(offset++) ?: throw InvalidJsonException()) { + '"', '\\', '/' -> append(escaped) + 'b' -> append('\b') + 'f' -> append('\u000c') + 'n' -> append('\n') + 'r' -> append('\r') + 't' -> append('\t') + 'u' -> { + val end = offset + 4 + if (end > source.length) throw InvalidJsonException() + append(source.substring(offset, end).toIntOrNull(16)?.toChar() + ?: throw InvalidJsonException()) + offset = end + } + else -> throw InvalidJsonException() + } + } + else -> { + if (char < ' ') throw InvalidJsonException() + append(char) + } + } + } + } + } + + private fun parseNumber(): String { + val start = offset + if (source.getOrNull(offset) == '-') offset++ + if (source.getOrNull(offset) == '0') { + offset++ + } else { + if (source.getOrNull(offset)?.isDigit() != true) throw InvalidJsonException() + while (source.getOrNull(offset)?.isDigit() == true) offset++ + } + if (source.getOrNull(offset) == '.') { + offset++ + if (source.getOrNull(offset)?.isDigit() != true) throw InvalidJsonException() + while (source.getOrNull(offset)?.isDigit() == true) offset++ + } + if (source.getOrNull(offset) == 'e' || source.getOrNull(offset) == 'E') { + offset++ + if (source.getOrNull(offset) == '+' || source.getOrNull(offset) == '-') offset++ + if (source.getOrNull(offset)?.isDigit() != true) throw InvalidJsonException() + while (source.getOrNull(offset)?.isDigit() == true) offset++ + } + return source.substring(start, offset) + } + + private fun withDepth(block: () -> T): T { + if (++depth > MAX_JSON_DEPTH) throw InvalidJsonException() + return try { + block() + } finally { + depth-- + } + } + + private fun parseLiteral(text: String, value: T): T { + if (!source.startsWith(text, offset)) throw InvalidJsonException() + offset += text.length + return value + } + + private fun skipWhitespace() { + while (source.getOrNull(offset)?.isWhitespace() == true) offset++ + } + + private fun expect(char: Char) { + if (source.getOrNull(offset) != char) throw InvalidJsonException() + offset++ + } + + private fun takeIf(char: Char): Boolean { + if (source.getOrNull(offset) != char) return false + offset++ + return true + } + } + + companion object { + const val CURRENT_VERSION = 1 + private const val MAX_JSON_LENGTH = 32_768 + private const val MAX_JSON_DEPTH = 16 + private const val DECIMAL_PREFIX = "decimal:" + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateComposer.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateComposer.kt new file mode 100644 index 000000000..649c055d3 --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateComposer.kt @@ -0,0 +1,77 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_CALCULATION +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_UNIT_CONVERSION +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_UTILITY_LITERAL +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.Candidate + +object UtilityCandidateComposer { + fun compose( + input: String, + existingCandidates: List, + result: UtilityCandidateResult, + ): List { + if (!result.hasCandidates) return existingCandidates + val utilityCandidates = result.candidates.map { candidate -> + Candidate( + string = candidate.text, + type = when (candidate.kind) { + UtilityCandidateKind.CALCULATION -> CANDIDATE_TYPE_CALCULATION + UtilityCandidateKind.UNIT_CONVERSION -> CANDIDATE_TYPE_UNIT_CONVERSION + UtilityCandidateKind.LITERAL -> CANDIDATE_TYPE_UTILITY_LITERAL + }, + length = input.length.coerceAtMost(UByte.MAX_VALUE.toInt()).toUByte(), + score = 0, + yomi = input, + ) + } + val ordered = when (result.trigger) { + UtilityTrigger.EXPLICIT_CALCULATION, + UtilityTrigger.EXPLICIT_UNIT_CONVERSION -> utilityCandidates + existingCandidates + + UtilityTrigger.AUTOMATIC_UNIT_CONVERSION -> { + val inputLiteral = existingCandidates.firstOrNull { it.string == input } + ?: utilityLiteral(input, input) + val preferredSource = result.preferredSourceText + ?.takeIf { it.isNotBlank() && it != input } + ?.let { text -> + existingCandidates.firstOrNull { it.string == text } + ?: utilityLiteral(text, input) + } + if (preferredSource == null) { + listOf(inputLiteral) + utilityCandidates + + existingCandidates.filterNot { it === inputLiteral } + } else { + listOf(preferredSource) + utilityCandidates + inputLiteral + + existingCandidates.filterNot { + it === preferredSource || it === inputLiteral + } + } + } + + UtilityTrigger.NONE -> existingCandidates + } + return ordered.distinctBy(Candidate::string) + } + + private fun utilityLiteral(text: String, input: String) = Candidate( + string = text, + type = CANDIDATE_TYPE_UTILITY_LITERAL, + length = input.length.coerceAtMost(UByte.MAX_VALUE.toInt()).toUByte(), + score = 0, + yomi = input, + ) + + fun isUtilityCandidate(candidate: Candidate?): Boolean = when (candidate?.type) { + CANDIDATE_TYPE_CALCULATION, + CANDIDATE_TYPE_UNIT_CONVERSION, + CANDIDATE_TYPE_UTILITY_LITERAL -> true + else -> false + } + + fun isResultCandidate(candidate: Candidate?): Boolean = when (candidate?.type) { + CANDIDATE_TYPE_CALCULATION, + CANDIDATE_TYPE_UNIT_CONVERSION -> true + else -> false + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateProvider.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateProvider.kt new file mode 100644 index 000000000..ec55f0c8d --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateProvider.kt @@ -0,0 +1,172 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +import java.math.MathContext +import java.math.RoundingMode + +class UtilityCandidateProvider( + private val calculationParser: CalculationParser = CalculationParser(), + private val unitRegistry: UnitRegistry = UnitRegistry.Default, + private val unitExpressionParser: UnitExpressionParser = UnitExpressionParser(unitRegistry), +) { + private val conversionContext = MathContext(50, RoundingMode.HALF_EVEN) + + fun provide( + input: String, + config: UtilityCandidateConfig = UtilityCandidateConfig(), + ): UtilityCandidateResult { + if (!isWithinInputLimits(input)) return UtilityCandidateResult.Empty + val normalized = UtilityInputNormalizer.normalize(input) + if (normalized.isBlank()) return UtilityCandidateResult.Empty + + val calculation = calculationTrigger(normalized) + if (calculation != null) { + if (!config.calculationEnabled) return UtilityCandidateResult.Empty + return provideCalculation(calculation, config) + } + if (containsBoundaryEquals(normalized)) return UtilityCandidateResult.Empty + if (!config.unitConversionEnabled) return UtilityCandidateResult.Empty + return provideUnitConversion(normalized, config) + } + + private data class CalculationTrigger(val expression: String, val prefix: Boolean) + + private fun calculationTrigger(input: String): CalculationTrigger? { + val trimmed = input.trim() + if (trimmed.isEmpty()) return null + val prefix = trimmed.first() == '=' + val suffix = trimmed.last() == '=' + if (prefix == suffix) return null + val expression = if (prefix) trimmed.drop(1).trim() else trimmed.dropLast(1).trim() + if (expression.isEmpty() || '=' in expression) return null + return CalculationTrigger(expression, prefix) + } + + private fun containsBoundaryEquals(input: String): Boolean { + val trimmed = input.trim() + return trimmed.startsWith('=') || trimmed.endsWith('=') || '=' in trimmed + } + + private fun provideCalculation( + trigger: CalculationTrigger, + config: UtilityCandidateConfig, + ): UtilityCandidateResult { + val value = calculationParser.calculate(trigger.expression, config.angleMode) + ?: return UtilityCandidateResult.Empty + val result = ResultFormatter.format(value, config.calculationPrecision) + val candidates = buildList { + add(UtilityCandidate(result, UtilityCandidateKind.CALCULATION)) + if (config.includeExpressionCandidate) { + val displayExpression = trigger.expression + .replace("*", "×") + .replace("/", "÷") + val expressionCandidate = if (trigger.prefix) { + "$result=$displayExpression" + } else { + "$displayExpression=$result" + } + if (expressionCandidate != result) { + add(UtilityCandidate(expressionCandidate, UtilityCandidateKind.CALCULATION)) + } + } + } + return UtilityCandidateResult(candidates, UtilityTrigger.EXPLICIT_CALCULATION) + } + + private fun provideUnitConversion( + normalizedInput: String, + config: UtilityCandidateConfig, + ): UtilityCandidateResult { + val split = splitExplicitConversion(normalizedInput) + if (split != null) { + val parsed = unitExpressionParser.parse(split.source, config.regionalUnitProfile) + ?: return UtilityCandidateResult.Empty + val target = unitRegistry.findExact( + split.target, + parsed.category, + config.regionalUnitProfile, + ) ?: return UtilityCandidateResult.Empty + val precision = config.unitTargets[parsed.category] + ?.firstOrNull { it.unitId == target.id } + ?.precision + ?: Precision.Auto + val text = formatConversion(parsed, target, precision) ?: return UtilityCandidateResult.Empty + return UtilityCandidateResult( + listOf(UtilityCandidate(text, UtilityCandidateKind.UNIT_CONVERSION)), + UtilityTrigger.EXPLICIT_UNIT_CONVERSION, + ) + } + if (hasExplicitConversionSyntax(normalizedInput)) return UtilityCandidateResult.Empty + + val parsed = unitExpressionParser.parse(normalizedInput.trim(), config.regionalUnitProfile) + ?: return UtilityCandidateResult.Empty + val targets = config.unitTargets[parsed.category].orEmpty().take( + UtilityCandidateConfig.MAX_TARGETS_PER_CATEGORY + ) + if (targets.isEmpty()) return UtilityCandidateResult.Empty + val onlySourceId = parsed.terms.singleOrNull()?.unit?.id + val candidates = targets.mapNotNull { setting -> + val target = unitRegistry.findById(setting.unitId) ?: return@mapNotNull null + if (target.category != parsed.category || target.id == onlySourceId) return@mapNotNull null + formatConversion(parsed, target, setting.precision)?.let { + UtilityCandidate(it, UtilityCandidateKind.UNIT_CONVERSION) + } + }.distinctBy(UtilityCandidate::text) + return if (candidates.isEmpty()) { + UtilityCandidateResult.Empty + } else { + UtilityCandidateResult( + candidates = candidates, + trigger = UtilityTrigger.AUTOMATIC_UNIT_CONVERSION, + preferredSourceText = parsed.canonicalSourceText.takeIf { + parsed.prefersCanonicalSource && it != normalizedInput.trim() + }, + ) + } + } + + private data class ExplicitConversion(val source: String, val target: String) + + private fun splitExplicitConversion(input: String): ExplicitConversion? { + val trimmed = input.trim() + if (trimmed.count { it == '>' } == 1) { + val position = trimmed.indexOf('>') + val source = trimmed.substring(0, position).trim() + val target = trimmed.substring(position + 1).trim() + return if (source.isNotEmpty() && target.isNotEmpty()) { + ExplicitConversion(source, target) + } else null + } + val matches = TO_SEPARATOR.findAll(trimmed).toList() + if (matches.size != 1) return null + val match = matches.single() + val source = trimmed.substring(0, match.range.first).trim() + val target = trimmed.substring(match.range.last + 1).trim() + return if (source.isNotEmpty() && target.isNotEmpty()) { + ExplicitConversion(source, target) + } else null + } + + private fun hasExplicitConversionSyntax(input: String): Boolean = + '>' in input || TO_SEPARATOR.containsMatchIn(input) + + private fun formatConversion( + parsed: ParsedUnitExpression, + target: UnitDefinition, + precision: Precision, + ): String? = try { + val converted = target.fromBase(parsed.baseValue, conversionContext) + ResultFormatter.format(converted, precision) + target.symbol + } catch (_: ArithmeticException) { + null + } + + private fun isWithinInputLimits(input: String): Boolean = + input.length <= MAX_UTF16_LENGTH && + input.codePointCount(0, input.length) <= MAX_CODE_POINTS + + private companion object { + const val MAX_UTF16_LENGTH = 255 + const val MAX_CODE_POINTS = 200 + val TO_SEPARATOR = Regex("\\s+to\\s+", RegexOption.IGNORE_CASE) + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityInputNormalizer.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityInputNormalizer.kt new file mode 100644 index 000000000..1686fcac9 --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityInputNormalizer.kt @@ -0,0 +1,26 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +import java.text.Normalizer + +object UtilityInputNormalizer { + fun normalize(input: String): String { + val normalized = Normalizer.normalize(input, Normalizer.Form.NFKC) + return buildString(normalized.length) { + normalized.forEach { char -> + append( + when (char) { + '\u00a0', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', + '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200a', + '\u202f', '\u205f', '\u3000' -> ' ' + '×' -> '*' + '÷' -> '/' + '−', '–', '—' -> '-' + '→', '⇒' -> '>' + 'μ' -> 'µ' + else -> char + } + ) + } + } + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityModels.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityModels.kt new file mode 100644 index 000000000..a1303eb6b --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityModels.kt @@ -0,0 +1,121 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +@JvmInline +value class UnitId(val value: String) { + init { + require(value.matches(Regex("[a-z0-9._-]+"))) { "UnitId must be stable ASCII" } + } + + override fun toString(): String = value +} + +enum class AngleMode { DEGREES, RADIANS } + +enum class RegionalUnitProfile { JAPAN, UNITED_STATES, UNITED_KINGDOM } + +enum class UnitCategory { + LENGTH, + AREA, + VOLUME, + MASS, + TEMPERATURE, + SPEED, + PRESSURE, + ENERGY, + POWER, + TIME, + DATA, +} + +sealed class Precision { + data object Auto : Precision() + + @Deprecated("Use DecimalPlaces(0)") + data object Integer : Precision() + + data class DecimalPlaces(val places: Int) : Precision() { + init { + require(places in MIN_DECIMAL_PLACES..MAX_DECIMAL_PLACES) + } + } + + data class SignificantDigits(val digits: Int) : Precision() { + init { + require(digits in MIN_DIGITS..MAX_DIGITS) + } + } + + companion object { + const val MIN_DIGITS = 1 + const val MAX_DIGITS = 15 + const val MIN_DECIMAL_PLACES = 0 + const val MAX_DECIMAL_PLACES = 15 + } +} + +data class UnitTargetSetting( + val unitId: UnitId, + val precision: Precision = Precision.Auto, +) + +data class UtilityCandidateConfig( + val calculationEnabled: Boolean = true, + val unitConversionEnabled: Boolean = true, + val includeExpressionCandidate: Boolean = true, + val angleMode: AngleMode = AngleMode.DEGREES, + val calculationPrecision: Precision = Precision.Auto, + val regionalUnitProfile: RegionalUnitProfile = RegionalUnitProfile.JAPAN, + val unitTargets: Map> = defaultUnitTargets(), +) { + init { + require(unitTargets.values.all { it.size <= MAX_TARGETS_PER_CATEGORY }) + } + + companion object { + const val MAX_TARGETS_PER_CATEGORY = 8 + + fun defaultUnitTargets(): Map> = mapOf( + UnitCategory.LENGTH to targets("length.m" to 6, "length.cm" to 6, "length.ft" to 5, "length.in" to 5), + UnitCategory.AREA to targets("area.m2" to 6, "area.km2" to 6, "area.ft2" to 5, "area.tsubo" to 5), + UnitCategory.VOLUME to targets("volume.ml" to 6, "volume.l" to 6, "volume.m3" to 6, "volume.cup_jp" to 5), + UnitCategory.MASS to targets("mass.g" to 6, "mass.kg" to 6, "mass.lb" to 3, "mass.oz" to 4), + UnitCategory.TEMPERATURE to targets("temperature.c" to 6, "temperature.f" to 6, "temperature.k" to 6), + UnitCategory.SPEED to targets("speed.kmh" to 6, "speed.ms" to 6, "speed.mph" to 5, "speed.kn" to 5), + UnitCategory.PRESSURE to targets("pressure.kpa" to 6, "pressure.bar" to 6, "pressure.psi" to 5, "pressure.atm" to 6), + UnitCategory.ENERGY to targets("energy.j" to 6, "energy.kj" to 6, "energy.kwh" to 6, "energy.kcal" to 5), + UnitCategory.POWER to targets("power.w" to 6, "power.kw" to 6, "power.hp" to 5, "power.ps" to 5), + UnitCategory.TIME to targets("time.s" to 6, "time.min" to 6, "time.h" to 6, "time.day" to 6), + UnitCategory.DATA to targets("data.b" to 6, "data.kb" to 6, "data.mb" to 6, "data.gb" to 6), + ) + + private fun targets(vararg values: Pair) = values.map { (id, digits) -> + UnitTargetSetting(UnitId(id), Precision.SignificantDigits(digits)) + } + } +} + +enum class UtilityTrigger { + NONE, + EXPLICIT_CALCULATION, + EXPLICIT_UNIT_CONVERSION, + AUTOMATIC_UNIT_CONVERSION, +} + +enum class UtilityCandidateKind { CALCULATION, UNIT_CONVERSION, LITERAL } + +data class UtilityCandidate( + val text: String, + val kind: UtilityCandidateKind, +) + +data class UtilityCandidateResult( + val candidates: List = emptyList(), + val trigger: UtilityTrigger = UtilityTrigger.NONE, + val preferredSourceText: String? = null, +) { + val hasCandidates: Boolean get() = candidates.isNotEmpty() + + companion object { + val Empty = UtilityCandidateResult() + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt index 03a890eb4..f05e75cb2 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/IMEService.kt @@ -180,8 +180,11 @@ import com.kazumaproject.markdownhelperkeyboard.clipboard_history.database.Clipb import com.kazumaproject.markdownhelperkeyboard.clipboard_history.database.ItemType import com.kazumaproject.markdownhelperkeyboard.converter.candidate.BunsetsuCandidateResult import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_ERA +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_CALCULATION import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_LEARNED_DICTIONARY import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_TIME +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_UNIT_CONVERSION +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_UTILITY_LITERAL import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_USER_DICTIONARY import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_USER_TEMPLATE import com.kazumaproject.markdownhelperkeyboard.converter.candidate.Candidate @@ -201,6 +204,10 @@ import com.kazumaproject.markdownhelperkeyboard.converter.session.ConversionBack import com.kazumaproject.markdownhelperkeyboard.converter.session.KanaKanjiConversionSession import com.kazumaproject.markdownhelperkeyboard.converter.session.KanaKanjiQueryRequest import com.kazumaproject.markdownhelperkeyboard.converter.session.KanaKanjiQueryResult +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UtilityCandidateComposer +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UtilityCandidateConfig +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UtilityCandidateProvider +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UtilityTrigger import com.kazumaproject.markdownhelperkeyboard.custom_keyboard.data.CustomKeyboardLayout import com.kazumaproject.markdownhelperkeyboard.databinding.FloatingKeyboardLayoutBinding import com.kazumaproject.markdownhelperkeyboard.databinding.MainLayoutBinding @@ -823,7 +830,14 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, AppPreference.KEY_SOUND_KEY, AppPreference.KEY_SOUND_VOLUME_PERCENT_KEY, AppPreference.FLICK_TFBI_POPUP_PRESENTATION_KEY, - AppPreference.FLICK_TFBI_FLICK_START_POSITION_KEY + AppPreference.FLICK_TFBI_FLICK_START_POSITION_KEY, + AppPreference.UTILITY_CALCULATION_ENABLED_KEY, + AppPreference.UTILITY_UNIT_CONVERSION_ENABLED_KEY, + AppPreference.UTILITY_EXPRESSION_CANDIDATE_ENABLED_KEY, + AppPreference.UTILITY_ANGLE_MODE_KEY, + AppPreference.UTILITY_CALCULATION_PRECISION_KEY, + AppPreference.UTILITY_REGIONAL_PROFILE_KEY, + AppPreference.UTILITY_UNIT_TARGETS_JSON_KEY, ) private val runtimeInputPreferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> @@ -1727,6 +1741,8 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, private var candidateViewHeight: String? = "2" private var candidateTabVisibility: Boolean? = false private var conversionBackend: ConversionBackend = ConversionBackend.LEGACY + private val utilityCandidateProvider = UtilityCandidateProvider() + private var utilityCandidateConfig: UtilityCandidateConfig = UtilityCandidateConfig() private var predictionConfig: PredictionConfig = PredictionConfig() @Volatile private var kanaKanjiConversionSession: KanaKanjiConversionSession? = null @@ -2560,6 +2576,8 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, private fun syncRuntimeInputPreferences() { assertMainThread("syncRuntimeInputPreferences") + utilityCandidateConfig = appPreference.utility_candidate_config + val sensitivity = (appPreference.flick_sensitivity_preference ?: 100).coerceIn(1, 200) val thresholdShape = FlickThresholdShape.fromPreferenceValue( appPreference.flick_threshold_shape_preference @@ -2647,6 +2665,7 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, keyboardOrder = preferences.keyboardOrder candidateTabOrder = preferences.candidateTabOrder conversionBackend = preferences.conversionBackend + utilityCandidateConfig = preferences.utilityCandidateConfig predictionConfig = preferences.predictionConfig mozcUTPersonName = preferences.mozcUTPersonName mozcUTPlaces = preferences.mozcUTPlaces @@ -15944,15 +15963,19 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, zenzLiveLocalCandidatesSnapshot = localCandidates zenzLiveSnapshotDisplayInput = insertString } - val displayedCandidates = buildDisplayedCandidatesWithZenzSlot( + val displayedCandidatesWithZenz = buildDisplayedCandidatesWithZenzSlot( localCandidates = localCandidates, input = insertString, zenzSlotState = _zenzLiveSlotState.value ) + val displayedCandidates = composeUtilityCandidates( + input = insertString, + candidates = displayedCandidatesWithZenz, + ) if (physicalKeyboardEnable.replayCache.isNotEmpty() && physicalKeyboardEnable.replayCache.first()) { if (!suppressSuggestions) { updateFloatingCandidatesOnMain( - candidates = localCandidates.map { + candidates = displayedCandidates.map { CandidateItem( word = it.string, length = it.length ) @@ -15965,7 +15988,7 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, updateSuggestionAdaptersOnMain( candidates = displayedCandidates, insertString = insertString, - fullCandidates = localCandidates, + fullCandidates = composeUtilityCandidates(insertString, localCandidates), token = token, ) } @@ -15977,6 +16000,50 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } } + private fun composeUtilityCandidates( + input: String, + candidates: List, + ): List = UtilityCandidateComposer.compose( + input = input, + existingCandidates = candidates, + result = utilityCandidateProvider.provide(input, utilityCandidateConfig), + ) + + private fun candidateForAutomaticApplication( + input: String, + candidate: Candidate?, + ): Candidate? { + val utilityResult = utilityCandidateProvider.provide(input, utilityCandidateConfig) + return if (utilityResult.hasCandidates) null else candidate + } + + private fun commitExplicitUtilityCandidateOnEnter( + suggestions: List, + input: String, + ): Boolean { + val utilityResult = utilityCandidateProvider.provide(input, utilityCandidateConfig) + if ( + utilityResult.trigger != UtilityTrigger.EXPLICIT_CALCULATION && + utilityResult.trigger != UtilityTrigger.EXPLICIT_UNIT_CONVERSION + ) return false + val resultText = utilityResult.candidates.firstOrNull()?.text ?: return false + // Keep the parameter as a consistency guard for the normal candidate path. Hardware + // candidate rows do not retain candidate type metadata, so the provider remains the + // source of truth there. + if (suggestions.isEmpty() && inputString.value != input) return false + commitUtilityCandidate(resultText) + clearSuggestionStateAfterCommit() + resetFlagsEnterKey() + return true + } + + private fun commitUtilityCandidate(text: String) { + conversionLearningSession.cancel() + _inputString.update { "" } + stringInTail.set("") + commitText(text, 1) + } + private fun shouldApplyCandidateResult( requestInput: String, token: CandidateRequestToken? = null, @@ -21729,6 +21796,15 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, return } when (candidate.type.toInt()) { + CANDIDATE_TYPE_CALCULATION.toInt(), + CANDIDATE_TYPE_UNIT_CONVERSION.toInt() -> { + commitUtilityCandidate(candidate.string) + } + + CANDIDATE_TYPE_UTILITY_LITERAL.toInt() -> { + commitUtilityCandidate(candidate.string) + } + 15 -> { val readingCorrection = candidate.string.correctReading() commitAndClearInput(readingCorrection.first) @@ -22616,7 +22692,10 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, if (!shouldApplyCandidateResult(insertString, token)) return if (!applyFirstSuggestionOnMainIfCurrent( insertString = insertString, - candidate = displayedCandidates.firstOrNull(), + candidate = candidateForAutomaticApplication( + insertString, + displayedCandidates.firstOrNull(), + ), ) ) return } @@ -22633,7 +22712,10 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } if (!applyFirstSuggestionOnMainIfCurrent( insertString = insertString, - candidate = displayedCandidates.firstOrNull() + candidate = candidateForAutomaticApplication( + insertString, + displayedCandidates.firstOrNull(), + ) ) ) { return @@ -22644,7 +22726,10 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } if (!applyFirstSuggestionOnMainIfCurrent( insertString = insertString, - candidate = displayedCandidates.firstOrNull() + candidate = composeUtilityCandidates( + insertString, + displayedCandidates, + ).firstOrNull() ) ) { return @@ -22706,7 +22791,10 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, if (!shouldApplyCandidateResult(insertString, token)) return if (!applyFirstSuggestionOnMainIfCurrent( insertString = insertString, - candidate = displayedCandidates.firstOrNull(), + candidate = candidateForAutomaticApplication( + insertString, + displayedCandidates.firstOrNull(), + ), ) ) return } @@ -22723,7 +22811,10 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } if (!applyFirstSuggestionOnMainIfCurrent( insertString = insertString, - candidate = displayedCandidates.firstOrNull() + candidate = candidateForAutomaticApplication( + insertString, + displayedCandidates.firstOrNull(), + ) ) ) { return @@ -22734,7 +22825,10 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } if (!applyFirstSuggestionOnMainIfCurrent( insertString = insertString, - candidate = displayedCandidates.firstOrNull() + candidate = composeUtilityCandidates( + insertString, + displayedCandidates, + ).firstOrNull() ) ) { return @@ -22768,13 +22862,14 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } else { candidates } + val displayedCandidates = composeUtilityCandidates(insertString, filtered) if (!shouldApplyCandidateResult(insertString, token)) { return } if (physicalKeyboardEnable.replayCache.isNotEmpty() && physicalKeyboardEnable.replayCache.first()) { if (!suppressSuggestions) { updateFloatingCandidatesOnMain( - candidates = filtered.map { + candidates = displayedCandidates.map { CandidateItem( word = it.string, length = it.length ) @@ -22785,7 +22880,7 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } else { if (!suppressSuggestions) { updateSuggestionAdaptersOnMain( - candidates = filtered, + candidates = displayedCandidates, insertString = insertString, token = token, ) @@ -22799,7 +22894,10 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } if (!applyFirstSuggestionOnMainIfCurrent( insertString = insertString, - candidate = filtered.firstOrNull() + candidate = candidateForAutomaticApplication( + insertString, + filtered.firstOrNull(), + ) ) ) { return @@ -22810,7 +22908,7 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } if (!applyFirstSuggestionOnMainIfCurrent( insertString = insertString, - candidate = filtered.firstOrNull() + candidate = displayedCandidates.firstOrNull() ) ) { return @@ -22843,13 +22941,14 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } else { candidates } + val displayedCandidates = composeUtilityCandidates(insertString, filtered) if (!shouldApplyCandidateResult(insertString, token)) { return } if (physicalKeyboardEnable.replayCache.isNotEmpty() && physicalKeyboardEnable.replayCache.first()) { if (!suppressSuggestions) { updateFloatingCandidatesOnMain( - candidates = filtered.map { + candidates = displayedCandidates.map { CandidateItem( word = it.string, length = it.length ) @@ -22860,7 +22959,7 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } else { if (!suppressSuggestions) { updateSuggestionAdaptersOnMain( - candidates = filtered, + candidates = displayedCandidates, insertString = insertString, token = token, ) @@ -22874,7 +22973,10 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, } if (!applyFirstSuggestionOnMainIfCurrent( insertString = insertString, - candidate = filtered.firstOrNull() + candidate = candidateForAutomaticApplication( + insertString, + filtered.firstOrNull(), + ) ) ) { return @@ -24161,6 +24263,7 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, suggestions: List, mainView: MainLayoutBinding, insertString: String ) { if (dispatchDirectEnterIfNeeded()) return + if (commitExplicitUtilityCandidateOnEnter(suggestions, insertString)) return if (commitBunsetsuConversionSession()) { return } @@ -24209,6 +24312,7 @@ class IMEService : InputMethodService(), LifecycleOwner, InputConnection, insertString: String ) { if (dispatchDirectEnterIfNeeded()) return + if (commitExplicitUtilityCandidateOnEnter(suggestions, insertString)) return if (commitBunsetsuConversionSession()) { return } diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/ImePreferencesSnapshot.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/ImePreferencesSnapshot.kt index 0749c5e51..48798cf10 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/ImePreferencesSnapshot.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/ImePreferencesSnapshot.kt @@ -9,6 +9,7 @@ import com.kazumaproject.markdownhelperkeyboard.dictionary_override.DictionarySo import com.kazumaproject.markdownhelperkeyboard.converter.session.ConversionBackend import com.kazumaproject.markdownhelperkeyboard.converter.engine.PredictionAggressiveness import com.kazumaproject.markdownhelperkeyboard.converter.engine.PredictionConfig +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UtilityCandidateConfig import com.kazumaproject.markdownhelperkeyboard.setting_activity.AppPreference import com.kazumaproject.markdownhelperkeyboard.variant.AppVariantConfig @@ -246,6 +247,7 @@ data class ImePreferencesSnapshot( val enableTypoCorrectionJapaneseFlickKeyboardPreference: Boolean, val enableTypoCorrectionQwertyEnglishKeyboardPreference: Boolean, val enableGemmaTranslationPreference: Boolean, + val utilityCandidateConfig: UtilityCandidateConfig, ) { companion object { fun from( @@ -691,7 +693,8 @@ data class ImePreferencesSnapshot( enableTypoCorrectionQwertyEnglishKeyboardPreference = appPreference.enable_typo_correction_qwerty_english_keyboard_preference, enableGemmaTranslationPreference = - AppVariantConfig.hasGemma && appPreference.enable_gemma_translation_preference + AppVariantConfig.hasGemma && appPreference.enable_gemma_translation_preference, + utilityCandidateConfig = appPreference.utility_candidate_config, ) } } diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/adapters/SuggestionAdapter.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/adapters/SuggestionAdapter.kt index 2e8909519..cb9080839 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/adapters/SuggestionAdapter.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/ime_service/adapters/SuggestionAdapter.kt @@ -30,8 +30,10 @@ import com.kazumaproject.core.domain.extensions.setDrawableSolidColor import com.kazumaproject.core.domain.state.TenKeyQWERTYMode import com.kazumaproject.markdownhelperkeyboard.R import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_ERA +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_CALCULATION import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_LEARNED_DICTIONARY import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_TIME +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_UNIT_CONVERSION import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_USER_DICTIONARY import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_USER_TEMPLATE import com.kazumaproject.markdownhelperkeyboard.converter.candidate.Candidate @@ -1607,6 +1609,10 @@ class SuggestionAdapter internal constructor( (30).toByte() -> "[全]" CANDIDATE_TYPE_TIME -> "" CANDIDATE_TYPE_ERA -> "" + CANDIDATE_TYPE_CALCULATION -> + holder.itemView.context.getString(R.string.candidate_badge_calculation) + CANDIDATE_TYPE_UNIT_CONVERSION -> + holder.itemView.context.getString(R.string.candidate_badge_unit_conversion) CANDIDATE_TYPE_USER_TEMPLATE -> if (showDictionaryCandidateLabels) "[定型]" else "" /** 半角 **/ diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/AppPreference.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/AppPreference.kt index ad0447e68..a884f6b6c 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/AppPreference.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/AppPreference.kt @@ -16,6 +16,11 @@ import com.kazumaproject.custom_keyboard.data.KeyboardInputMode import com.kazumaproject.custom_keyboard.data.buildEvenCircularRanges import com.kazumaproject.domain.EmojiSkinToneSupport import com.kazumaproject.markdownhelperkeyboard.converter.engine.PredictionConfig +import com.kazumaproject.markdownhelperkeyboard.converter.utility.AngleMode +import com.kazumaproject.markdownhelperkeyboard.converter.utility.Precision +import com.kazumaproject.markdownhelperkeyboard.converter.utility.RegionalUnitProfile +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UnitTargetSettingsJsonCodec +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UtilityCandidateConfig import com.kazumaproject.markdownhelperkeyboard.ime_service.image_effect.CinematicWaveSettings import com.kazumaproject.markdownhelperkeyboard.ime_service.image_effect.KeyboardTouchEffectQuality import com.kazumaproject.markdownhelperkeyboard.ime_service.image_effect.KeyboardTouchEffectType @@ -39,6 +44,15 @@ internal object CustomThemeColorPreferenceKeys { object AppPreference { + const val UTILITY_CALCULATION_ENABLED_KEY = "utility_calculation_enabled" + const val UTILITY_UNIT_CONVERSION_ENABLED_KEY = "utility_unit_conversion_enabled" + const val UTILITY_EXPRESSION_CANDIDATE_ENABLED_KEY = "utility_expression_candidate_enabled" + const val UTILITY_ANGLE_MODE_KEY = "utility_angle_mode" + const val UTILITY_CALCULATION_PRECISION_KEY = "utility_calculation_precision" + const val UTILITY_REGIONAL_PROFILE_KEY = "utility_regional_profile" + const val UTILITY_UNIT_TARGETS_JSON_KEY = "utility_unit_targets_json" + private const val UTILITY_DECIMAL_PRECISION_PREFIX = "decimal:" + const val DEFAULT_CUSTOM_THEME_CANDIDATE_ITEM_BG_COLOR = 0x00000000 const val DEFAULT_CUSTOM_THEME_CANDIDATE_ITEM_PRESSED_BG_COLOR = 0xFFF0F0F3.toInt() const val SHORTCUT_TOOLBAR_HEIGHT_DEFAULT_DP = 36 @@ -93,6 +107,7 @@ object AppPreference { private lateinit var preferences: SharedPreferences private val gson = Gson() + private val unitTargetSettingsCodec = UnitTargetSettingsJsonCodec() private const val LEGACY_SYMBOL_EMOJI_CANDIDATE_ENABLE_KEY = "symbol_emoji_candidate_enable_preference" private val circularSlotActionEditableSlots = setOf( @@ -1703,6 +1718,115 @@ object AppPreference { it.putBoolean(INCREMENTAL_CONVERSION_SESSION_PREFERENCE.first, value) } + var utility_candidate_config: UtilityCandidateConfig + get() { + val calculationPrecision = preferences.getString( + UTILITY_CALCULATION_PRECISION_KEY, + "auto", + ).toUtilityPrecision() + return UtilityCandidateConfig( + calculationEnabled = preferences.getBoolean( + UTILITY_CALCULATION_ENABLED_KEY, + true, + ), + unitConversionEnabled = preferences.getBoolean( + UTILITY_UNIT_CONVERSION_ENABLED_KEY, + true, + ), + includeExpressionCandidate = preferences.getBoolean( + UTILITY_EXPRESSION_CANDIDATE_ENABLED_KEY, + true, + ), + angleMode = preferences.getString(UTILITY_ANGLE_MODE_KEY, "degrees") + .toAngleMode(), + calculationPrecision = calculationPrecision, + regionalUnitProfile = preferences.getString( + UTILITY_REGIONAL_PROFILE_KEY, + "japan", + ).toRegionalUnitProfile(), + unitTargets = unitTargetSettingsCodec.decodeOrDefault( + preferences.getString(UTILITY_UNIT_TARGETS_JSON_KEY, null), + ), + ) + } + set(value) = preferences.edit { editor -> + editor.putBoolean(UTILITY_CALCULATION_ENABLED_KEY, value.calculationEnabled) + editor.putBoolean(UTILITY_UNIT_CONVERSION_ENABLED_KEY, value.unitConversionEnabled) + editor.putBoolean( + UTILITY_EXPRESSION_CANDIDATE_ENABLED_KEY, + value.includeExpressionCandidate, + ) + editor.putString( + UTILITY_ANGLE_MODE_KEY, + if (value.angleMode == AngleMode.DEGREES) "degrees" else "radians", + ) + editor.putString( + UTILITY_CALCULATION_PRECISION_KEY, + value.calculationPrecision.toPreferenceValue(), + ) + editor.putString( + UTILITY_REGIONAL_PROFILE_KEY, + when (value.regionalUnitProfile) { + RegionalUnitProfile.JAPAN -> "japan" + RegionalUnitProfile.UNITED_STATES -> "united_states" + RegionalUnitProfile.UNITED_KINGDOM -> "united_kingdom" + }, + ) + editor.putString( + UTILITY_UNIT_TARGETS_JSON_KEY, + unitTargetSettingsCodec.encode(value.unitTargets), + ) + } + + fun resetUtilityCandidateConfig() { + preferences.edit { editor -> + editor.remove(UTILITY_CALCULATION_ENABLED_KEY) + editor.remove(UTILITY_UNIT_CONVERSION_ENABLED_KEY) + editor.remove(UTILITY_EXPRESSION_CANDIDATE_ENABLED_KEY) + editor.remove(UTILITY_ANGLE_MODE_KEY) + editor.remove(UTILITY_CALCULATION_PRECISION_KEY) + editor.remove(UTILITY_REGIONAL_PROFILE_KEY) + editor.remove(UTILITY_UNIT_TARGETS_JSON_KEY) + } + } + + private fun String?.toAngleMode(): AngleMode = when (this) { + "radians" -> AngleMode.RADIANS + else -> AngleMode.DEGREES + } + + private fun String?.toRegionalUnitProfile(): RegionalUnitProfile = when (this) { + "united_states" -> RegionalUnitProfile.UNITED_STATES + "united_kingdom" -> RegionalUnitProfile.UNITED_KINGDOM + else -> RegionalUnitProfile.JAPAN + } + + private fun String?.toUtilityPrecision(): Precision = when (this) { + "auto", null -> Precision.Auto + "integer" -> Precision.DecimalPlaces(0) + else -> if (startsWith(UTILITY_DECIMAL_PRECISION_PREFIX)) { + removePrefix(UTILITY_DECIMAL_PRECISION_PREFIX).toIntOrNull() + ?.takeIf { + it in Precision.MIN_DECIMAL_PLACES..Precision.MAX_DECIMAL_PLACES + } + ?.let(Precision::DecimalPlaces) + ?: Precision.Auto + } else { + toIntOrNull() + ?.takeIf { it in Precision.MIN_DIGITS..Precision.MAX_DIGITS } + ?.let(Precision::SignificantDigits) + ?: Precision.Auto + } + } + + @Suppress("DEPRECATION") + private fun Precision.toPreferenceValue(): String = when (this) { + Precision.Auto -> "auto" + Precision.Integer -> "${UTILITY_DECIMAL_PRECISION_PREFIX}0" + is Precision.DecimalPlaces -> "$UTILITY_DECIMAL_PRECISION_PREFIX$places" + is Precision.SignificantDigits -> digits.toString() + } + var japanese_prediction_enable_preference: Boolean get() = preferences.getBoolean( JAPANESE_PREDICTION_ENABLE_PREFERENCE.first, diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/candidate_view_height_setting/SuggestionAdapter2.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/candidate_view_height_setting/SuggestionAdapter2.kt index 419a05008..e704ac931 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/candidate_view_height_setting/SuggestionAdapter2.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/candidate_view_height_setting/SuggestionAdapter2.kt @@ -30,8 +30,10 @@ import com.kazumaproject.core.domain.extensions.setDrawableSolidColor import com.kazumaproject.core.domain.state.TenKeyQWERTYMode import com.kazumaproject.markdownhelperkeyboard.R import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_ERA +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_CALCULATION import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_LEARNED_DICTIONARY import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_TIME +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_UNIT_CONVERSION import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_USER_DICTIONARY import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_USER_TEMPLATE import com.kazumaproject.markdownhelperkeyboard.converter.candidate.Candidate @@ -1012,6 +1014,10 @@ class SuggestionAdapter2 : RecyclerView.Adapter() { (30).toByte() -> "[全]" CANDIDATE_TYPE_TIME -> "" CANDIDATE_TYPE_ERA -> "" + CANDIDATE_TYPE_CALCULATION -> + holder.itemView.context.getString(R.string.candidate_badge_calculation) + CANDIDATE_TYPE_UNIT_CONVERSION -> + holder.itemView.context.getString(R.string.candidate_badge_unit_conversion) CANDIDATE_TYPE_USER_TEMPLATE -> if (showDictionaryCandidateLabels) "定型" else "" (31).toByte() -> "[半]" diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/CommonPreferenceFragment.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/CommonPreferenceFragment.kt index 69145aab5..69925504c 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/CommonPreferenceFragment.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/CommonPreferenceFragment.kt @@ -986,6 +986,7 @@ open class CommonPreferenceFragment : PreferenceFragmentCompat() { "setting_route_input_method" to R.id.inputMethodPreferenceFragment, "setting_route_candidate_conversion" to R.id.candidateConversionPreferenceFragment, "setting_route_conversion_engine" to R.id.conversionEnginePreferenceFragment, + "setting_route_utility_candidates" to R.id.utilityCandidatePreferenceFragment, "setting_route_dictionary" to R.id.dictionaryPreferenceFragment, "setting_route_ai_conversion" to R.id.aiConversionPreferenceFragment, "setting_route_clipboard_shortcut" to R.id.clipboardShortcutPreferenceFragment, diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/PrecisionSelectionDialog.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/PrecisionSelectionDialog.kt new file mode 100644 index 000000000..b75dc1cd8 --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/PrecisionSelectionDialog.kt @@ -0,0 +1,182 @@ +package com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting + +import android.content.Context +import android.view.LayoutInflater +import android.widget.NumberPicker +import android.widget.RadioGroup +import android.widget.TextView +import androidx.appcompat.app.AlertDialog +import com.kazumaproject.markdownhelperkeyboard.R +import com.kazumaproject.markdownhelperkeyboard.converter.utility.Precision + +internal enum class PrecisionSelectionMode { + AUTO, + DECIMAL_PLACES, + SIGNIFICANT_DIGITS, +} + +@Suppress("DEPRECATION") +internal class PrecisionSelectionState(current: Precision) { + var mode: PrecisionSelectionMode = when (current) { + Precision.Auto -> PrecisionSelectionMode.AUTO + Precision.Integer -> PrecisionSelectionMode.DECIMAL_PLACES + is Precision.DecimalPlaces -> PrecisionSelectionMode.DECIMAL_PLACES + is Precision.SignificantDigits -> PrecisionSelectionMode.SIGNIFICANT_DIGITS + } + private set + + var decimalPlaces: Int = when (current) { + Precision.Integer -> 0 + is Precision.DecimalPlaces -> current.places + else -> DEFAULT_DECIMAL_PLACES + } + private set + + var significantDigits: Int = when (current) { + is Precision.SignificantDigits -> current.digits + else -> DEFAULT_SIGNIFICANT_DIGITS + } + private set + + val minimumDigits: Int + get() = when (mode) { + PrecisionSelectionMode.AUTO, + PrecisionSelectionMode.DECIMAL_PLACES -> Precision.MIN_DECIMAL_PLACES + PrecisionSelectionMode.SIGNIFICANT_DIGITS -> Precision.MIN_DIGITS + } + + val maximumDigits: Int + get() = when (mode) { + PrecisionSelectionMode.AUTO, + PrecisionSelectionMode.DECIMAL_PLACES -> Precision.MAX_DECIMAL_PLACES + PrecisionSelectionMode.SIGNIFICANT_DIGITS -> Precision.MAX_DIGITS + } + + val selectedDigits: Int + get() = when (mode) { + PrecisionSelectionMode.AUTO, + PrecisionSelectionMode.DECIMAL_PLACES -> decimalPlaces + PrecisionSelectionMode.SIGNIFICANT_DIGITS -> significantDigits + } + + fun selectMode(value: PrecisionSelectionMode) { + mode = value + } + + fun updateDigits(value: Int) { + when (mode) { + PrecisionSelectionMode.AUTO -> Unit + PrecisionSelectionMode.DECIMAL_PLACES -> { + decimalPlaces = value.coerceIn( + Precision.MIN_DECIMAL_PLACES, + Precision.MAX_DECIMAL_PLACES, + ) + } + PrecisionSelectionMode.SIGNIFICANT_DIGITS -> { + significantDigits = value.coerceIn( + Precision.MIN_DIGITS, + Precision.MAX_DIGITS, + ) + } + } + } + + fun toPrecision(): Precision = when (mode) { + PrecisionSelectionMode.AUTO -> Precision.Auto + PrecisionSelectionMode.DECIMAL_PLACES -> Precision.DecimalPlaces(decimalPlaces) + PrecisionSelectionMode.SIGNIFICANT_DIGITS -> Precision.SignificantDigits(significantDigits) + } + + companion object { + const val DEFAULT_DECIMAL_PLACES = 2 + const val DEFAULT_SIGNIFICANT_DIGITS = 6 + } +} + +internal object PrecisionSelectionDialog { + fun create( + context: Context, + current: Precision, + onSelected: (Precision) -> Unit, + ): AlertDialog { + val content = LayoutInflater.from(context).inflate( + R.layout.dialog_utility_precision, + null, + false, + ) + val modeGroup = content.findViewById(R.id.utility_precision_mode_group) + val digitLabel = content.findViewById(R.id.utility_precision_digit_label) + val digitPicker = content.findViewById(R.id.utility_precision_digit_picker) + val state = PrecisionSelectionState(current) + + fun renderMode() { + digitPicker.setOnValueChangedListener(null) + digitPicker.minValue = state.minimumDigits + digitPicker.maxValue = state.maximumDigits + digitPicker.value = state.selectedDigits + val digitsEnabled = state.mode != PrecisionSelectionMode.AUTO + digitPicker.isEnabled = digitsEnabled + digitLabel.isEnabled = digitsEnabled + digitLabel.text = when (state.mode) { + PrecisionSelectionMode.AUTO -> context.getString(R.string.utility_precision_digit_count) + PrecisionSelectionMode.DECIMAL_PLACES -> context.getString( + R.string.utility_precision_mode_decimal_places, + ) + PrecisionSelectionMode.SIGNIFICANT_DIGITS -> context.getString( + R.string.utility_precision_mode_significant_digits, + ) + } + digitPicker.setOnValueChangedListener { _, _, newValue -> + state.updateDigits(newValue) + } + } + + val checkedId = when (state.mode) { + PrecisionSelectionMode.AUTO -> R.id.utility_precision_mode_auto + PrecisionSelectionMode.DECIMAL_PLACES -> R.id.utility_precision_mode_decimal_places + PrecisionSelectionMode.SIGNIFICANT_DIGITS -> + R.id.utility_precision_mode_significant_digits + } + modeGroup.check(checkedId) + renderMode() + modeGroup.setOnCheckedChangeListener { _, id -> + val mode = when (id) { + R.id.utility_precision_mode_decimal_places -> + PrecisionSelectionMode.DECIMAL_PLACES + R.id.utility_precision_mode_significant_digits -> + PrecisionSelectionMode.SIGNIFICANT_DIGITS + else -> PrecisionSelectionMode.AUTO + } + state.selectMode(mode) + renderMode() + } + + return AlertDialog.Builder(context) + .setTitle(R.string.utility_precision_dialog_title) + .setView(content) + .setNegativeButton(android.R.string.cancel, null) + .setPositiveButton(android.R.string.ok) { _, _ -> + onSelected(state.toPrecision()) + } + .create() + } +} + +@Suppress("DEPRECATION") +internal fun Context.utilityPrecisionLabel(precision: Precision): String = when (precision) { + Precision.Auto -> getString(R.string.utility_precision_auto) + Precision.Integer -> getString( + R.string.utility_precision_decimal_places, + 0, + ) + is Precision.DecimalPlaces -> if (precision.places == 1) { + getString(R.string.utility_precision_decimal_place) + } else { + getString(R.string.utility_precision_decimal_places, precision.places) + } + is Precision.SignificantDigits -> if (precision.digits == 1) { + getString(R.string.utility_precision_significant_digit) + } else { + getString(R.string.utility_precision_digits, precision.digits) + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingDestination.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingDestination.kt index d45b5855d..d362d1f5f 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingDestination.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingDestination.kt @@ -731,6 +731,7 @@ object SettingDestinations { "setting_route_input_method" -> R.id.inputMethodPreferenceFragment "setting_route_candidate_conversion" -> R.id.candidateConversionPreferenceFragment "setting_route_conversion_engine" -> R.id.conversionEnginePreferenceFragment + "setting_route_utility_candidates" -> R.id.utilityCandidatePreferenceFragment "setting_route_dictionary" -> R.id.dictionaryPreferenceFragment "setting_route_ai_conversion" -> R.id.aiConversionPreferenceFragment "setting_route_clipboard_shortcut" -> R.id.clipboardShortcutPreferenceFragment diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingSearchIndex.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingSearchIndex.kt index c3b8f1104..ef8681fc2 100644 --- a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingSearchIndex.kt +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/SettingSearchIndex.kt @@ -60,6 +60,7 @@ object SettingSearchIndex { R.id.inputMethodPreferenceFragment, R.id.candidateConversionPreferenceFragment, R.id.conversionEnginePreferenceFragment, + R.id.utilityCandidatePreferenceFragment, R.id.aiConversionPreferenceFragment, R.id.operationFeedbackPreferenceFragment, R.id.clipboardShortcutPreferenceFragment, @@ -284,6 +285,7 @@ object SettingSearchIndex { add(PreferenceXmlSource(R.xml.pref_input_method, R.id.inputMethodPreferenceFragment, SettingCategory.INPUT_METHOD)) add(PreferenceXmlSource(R.xml.pref_candidate_conversion, R.id.candidateConversionPreferenceFragment, SettingCategory.CANDIDATE_CONVERSION)) add(PreferenceXmlSource(R.xml.pref_conversion_engine, R.id.conversionEnginePreferenceFragment, SettingCategory.CONVERSION_ENGINE)) + add(PreferenceXmlSource(R.xml.pref_utility_candidate, R.id.utilityCandidatePreferenceFragment, SettingCategory.CONVERSION_ENGINE)) add(PreferenceXmlSource(R.xml.pref_dictionary, R.id.dictionaryPreferenceFragment, SettingCategory.DICTIONARY)) add(PreferenceXmlSource(R.xml.pref_ai_conversion, R.id.aiConversionPreferenceFragment, SettingCategory.AI_CONVERSION)) if (AppVariantConfig.hasZenz) { diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/UnitTargetSettingsFragment.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/UnitTargetSettingsFragment.kt new file mode 100644 index 000000000..74036b55e --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/UnitTargetSettingsFragment.kt @@ -0,0 +1,215 @@ +package com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting + +import android.os.Bundle +import android.view.Gravity +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Button +import android.widget.LinearLayout +import android.widget.TextView +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.Fragment +import androidx.recyclerview.widget.ItemTouchHelper +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import com.kazumaproject.markdownhelperkeyboard.R +import com.kazumaproject.markdownhelperkeyboard.converter.utility.Precision +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UnitCategory +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UnitRegistry +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UnitTargetSetting +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UtilityCandidateConfig +import com.kazumaproject.markdownhelperkeyboard.setting_activity.AppPreference +import dagger.hilt.android.AndroidEntryPoint +import java.util.Collections + +@AndroidEntryPoint +class UnitTargetSettingsFragment : Fragment() { + private val registry = UnitRegistry.Default + private lateinit var category: UnitCategory + private lateinit var adapter: TargetAdapter + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + category = arguments?.getString(ARG_CATEGORY)?.let { + runCatching { UnitCategory.valueOf(it) }.getOrNull() + } ?: UnitCategory.LENGTH + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle?, + ): View { + val context = requireContext() + val root = LinearLayout(context).apply { + orientation = LinearLayout.VERTICAL + setPadding(16.dp, 12.dp, 16.dp, 12.dp) + } + root.addView(TextView(context).apply { + text = getString(R.string.utility_drag_hint) + setPadding(8.dp, 4.dp, 8.dp, 12.dp) + }) + val recyclerView = RecyclerView(context).apply { + layoutManager = LinearLayoutManager(context) + layoutParams = LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + 0, + 1f, + ) + } + adapter = TargetAdapter( + items = AppPreference.utility_candidate_config.unitTargets[category] + .orEmpty().toMutableList(), + onPrecision = ::showPrecisionDialog, + onRemove = { position -> + adapter.remove(position) + saveTargets() + }, + ) + recyclerView.adapter = adapter + ItemTouchHelper(object : ItemTouchHelper.SimpleCallback( + ItemTouchHelper.UP or ItemTouchHelper.DOWN, + 0, + ) { + override fun onMove( + recyclerView: RecyclerView, + viewHolder: RecyclerView.ViewHolder, + target: RecyclerView.ViewHolder, + ): Boolean { + adapter.move(viewHolder.bindingAdapterPosition, target.bindingAdapterPosition) + saveTargets() + return true + } + + override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) = Unit + }).attachToRecyclerView(recyclerView) + root.addView(recyclerView) + root.addView(Button(context).apply { + text = getString(R.string.utility_add_target) + setOnClickListener { showAddDialog() } + }) + return root + } + + private fun showAddDialog() { + if (adapter.items.size >= UtilityCandidateConfig.MAX_TARGETS_PER_CATEGORY) { + Toast.makeText( + requireContext(), + getString( + R.string.utility_target_limit, + UtilityCandidateConfig.MAX_TARGETS_PER_CATEGORY, + ), + Toast.LENGTH_SHORT, + ).show() + return + } + val selectedIds = adapter.items.mapTo(mutableSetOf()) { it.unitId } + val available = registry.units.filter { it.category == category && it.id !in selectedIds } + .sortedBy { it.symbol } + if (available.isEmpty()) { + Toast.makeText(requireContext(), R.string.utility_no_more_targets, Toast.LENGTH_SHORT).show() + return + } + AlertDialog.Builder(requireContext()) + .setTitle(R.string.utility_add_target) + .setItems(available.map { it.symbol }.toTypedArray()) { _, index -> + adapter.add(UnitTargetSetting(available[index].id, Precision.Auto)) + saveTargets() + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } + + private fun showPrecisionDialog(position: Int) { + val current = adapter.items.getOrNull(position) ?: return + PrecisionSelectionDialog.create( + context = requireContext(), + current = current.precision, + ) { precision -> + adapter.updatePrecision(position, precision) + saveTargets() + }.show() + } + + private fun saveTargets() { + val current = AppPreference.utility_candidate_config + AppPreference.utility_candidate_config = current.copy( + unitTargets = current.unitTargets + (category to adapter.items.toList()), + ) + } + + private inner class TargetAdapter( + val items: MutableList, + private val onPrecision: (Int) -> Unit, + private val onRemove: (Int) -> Unit, + ) : RecyclerView.Adapter() { + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TargetViewHolder { + val row = LinearLayout(parent.context).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + setPadding(8.dp, 6.dp, 8.dp, 6.dp) + } + val symbol = TextView(parent.context).apply { + textSize = 18f + layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f) + } + val precision = Button(parent.context) + val remove = Button(parent.context).apply { + text = "×" + contentDescription = getString(R.string.utility_remove_target) + } + row.addView(symbol) + row.addView(precision) + row.addView(remove) + return TargetViewHolder(row, symbol, precision, remove) + } + + override fun getItemCount(): Int = items.size + + override fun onBindViewHolder(holder: TargetViewHolder, position: Int) { + val item = items[position] + holder.symbol.text = registry.findById(item.unitId)?.symbol ?: item.unitId.value + holder.precision.text = requireContext().utilityPrecisionLabel(item.precision) + holder.precision.setOnClickListener { onPrecision(holder.bindingAdapterPosition) } + holder.remove.setOnClickListener { onRemove(holder.bindingAdapterPosition) } + } + + fun add(item: UnitTargetSetting) { + items += item + notifyItemInserted(items.lastIndex) + } + + fun remove(position: Int) { + if (position !in items.indices) return + items.removeAt(position) + notifyItemRemoved(position) + } + + fun move(from: Int, to: Int) { + if (from !in items.indices || to !in items.indices || from == to) return + Collections.swap(items, from, to) + notifyItemMoved(from, to) + } + + fun updatePrecision(position: Int, precision: Precision) { + if (position !in items.indices) return + items[position] = items[position].copy(precision = precision) + notifyItemChanged(position) + } + } + + private class TargetViewHolder( + itemView: View, + val symbol: TextView, + val precision: Button, + val remove: Button, + ) : RecyclerView.ViewHolder(itemView) + + private val Int.dp: Int get() = (this * resources.displayMetrics.density).toInt() + + companion object { + const val ARG_CATEGORY = "category" + } +} diff --git a/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/UtilityCandidatePreferenceFragment.kt b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/UtilityCandidatePreferenceFragment.kt new file mode 100644 index 000000000..931a7aad7 --- /dev/null +++ b/app/src/main/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/UtilityCandidatePreferenceFragment.kt @@ -0,0 +1,97 @@ +package com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting + +import android.os.Bundle +import androidx.appcompat.app.AlertDialog +import androidx.navigation.fragment.findNavController +import androidx.preference.Preference +import com.kazumaproject.markdownhelperkeyboard.R +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UnitCategory +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UnitRegistry +import com.kazumaproject.markdownhelperkeyboard.setting_activity.AppPreference +import dagger.hilt.android.AndroidEntryPoint + +@AndroidEntryPoint +class UtilityCandidatePreferenceFragment : CommonPreferenceFragment() { + override val preferencesXmlRes: Int = R.xml.pref_utility_candidate + + override fun onCommonPreferencesCreated() { + findPreference(CALCULATION_PRECISION_KEY)?.setOnPreferenceClickListener { + val current = AppPreference.utility_candidate_config + PrecisionSelectionDialog.create( + context = requireContext(), + current = current.calculationPrecision, + ) { precision -> + AppPreference.utility_candidate_config = current.copy( + calculationPrecision = precision, + ) + updateSummaries() + }.show() + true + } + targetPreferenceKeys.forEach { (key, category) -> + findPreference(key)?.setOnPreferenceClickListener { + findNavController().navigate( + R.id.unitTargetSettingsFragment, + Bundle().apply { putString(UnitTargetSettingsFragment.ARG_CATEGORY, category.name) }, + ) + true + } + } + findPreference("utility_reset_all")?.setOnPreferenceClickListener { + AlertDialog.Builder(requireContext()) + .setTitle(R.string.utility_reset_confirm_title) + .setMessage(R.string.utility_reset_confirm_message) + .setNegativeButton(android.R.string.cancel, null) + .setPositiveButton(android.R.string.ok) { _, _ -> + AppPreference.resetUtilityCandidateConfig() + preferenceScreen.removeAll() + setPreferencesFromResource(preferencesXmlRes, null) + onCommonPreferencesCreated() + } + .show() + true + } + updateSummaries() + } + + override fun onResume() { + super.onResume() + updateSummaries() + } + + private fun updateSummaries() { + val config = AppPreference.utility_candidate_config + findPreference(CALCULATION_PRECISION_KEY)?.summary = + requireContext().utilityPrecisionLabel(config.calculationPrecision) + targetPreferenceKeys.forEach { (key, category) -> + val settings = config.unitTargets[category].orEmpty() + findPreference(key)?.summary = if (settings.isEmpty()) { + getString(R.string.utility_targets_disabled) + } else { + settings.mapNotNull { setting -> + UnitRegistry.Default.findById(setting.unitId)?.let { unit -> + val precision = requireContext().utilityPrecisionLabel(setting.precision) + "${unit.symbol} ($precision)" + } + }.joinToString() + } + } + } + + private companion object { + const val CALCULATION_PRECISION_KEY = "utility_calculation_precision" + val targetPreferenceKeys = mapOf( + "utility_targets_length" to UnitCategory.LENGTH, + "utility_targets_area" to UnitCategory.AREA, + "utility_targets_volume" to UnitCategory.VOLUME, + "utility_targets_mass" to UnitCategory.MASS, + "utility_targets_temperature" to UnitCategory.TEMPERATURE, + "utility_targets_speed" to UnitCategory.SPEED, + "utility_targets_pressure" to UnitCategory.PRESSURE, + "utility_targets_energy" to UnitCategory.ENERGY, + "utility_targets_power" to UnitCategory.POWER, + "utility_targets_time" to UnitCategory.TIME, + "utility_targets_data" to UnitCategory.DATA, + ) + } +} diff --git a/app/src/main/res/layout/dialog_utility_precision.xml b/app/src/main/res/layout/dialog_utility_precision.xml new file mode 100644 index 000000000..48e10de5e --- /dev/null +++ b/app/src/main/res/layout/dialog_utility_precision.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/navigation/mobile_navigation.xml b/app/src/main/res/navigation/mobile_navigation.xml index a04d33fa1..14c265734 100644 --- a/app/src/main/res/navigation/mobile_navigation.xml +++ b/app/src/main/res/navigation/mobile_navigation.xml @@ -153,6 +153,16 @@ android:name="com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting.ConversionEnginePreferenceFragment" android:label="@string/conversion_engine_category_title" /> + + + + + [計算] + [換算] + 計算・単位換算候補 + 計算結果と単位換算候補を設定します + 計算 + 計算候補を表示 + 式付き候補も表示 + 角度単位 + 計算精度 + 単位換算 + 単位換算候補を表示 + 地域プロファイル + 度数法 + ラジアン + 日本 + 米国 + 英国 + 自動 + 表示精度 + 小数点以下 + 有効数字 + 桁数 + 小数点以下 1 桁 + 小数点以下 %1$d 桁 + 有効数字 1 桁 + 有効数字 %1$d 桁 + 自動候補は無効 + すべての設定をリセット + 計算・単位換算候補を既定値へ戻します + ユーティリティ候補設定をリセットしますか? + 計算・単位換算候補のすべての設定を既定値へ戻します。 + 変換先を追加 + 変換先 + 削除 + 変換先は%1$d件まで選択できます。 + 追加できる変換先はありません。 + 行をドラッグして並べ替え、精度をタップして変更できます。 + 長さ + 面積 + 体積 + 質量 + 温度 + 速度 + 圧力 + エネルギー + 仕事率 + 時間 + データ 濁点 / 清音 半濁点 / 清音 半角スペース diff --git a/app/src/main/res/values/arrays.xml b/app/src/main/res/values/arrays.xml index 1f688d490..284f3b1e5 100644 --- a/app/src/main/res/values/arrays.xml +++ b/app/src/main/res/values/arrays.xml @@ -1,5 +1,23 @@ + + @string/utility_angle_degrees + @string/utility_angle_radians + + + degrees + radians + + + @string/utility_region_japan + @string/utility_region_us + @string/utility_region_uk + + + japan + united_states + united_kingdom + @string/delete_long_press_conversion_behavior_deferred @string/delete_long_press_conversion_behavior_continuous diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 814fdaa95..5dd2c5d84 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,5 +1,53 @@ + [Calc] + [Convert] + Calculations and unit conversions + Configure calculator and conversion candidates + Calculator + Show calculation candidates + Also show result with expression + Angle unit + Calculation precision + Unit conversions + Show unit conversion candidates + Regional units + Degrees + Radians + Japan + United States + United Kingdom + Automatic + Display precision + Decimal places + Significant digits + Digits + 1 decimal place + %1$d decimal places + 1 significant digit + %1$d significant digits + Automatic candidates off + Reset all settings + Restore calculator and unit conversion defaults + Reset utility candidate settings? + All calculator and unit conversion settings will be restored to their defaults. + Add conversion target + Conversion targets + Remove + You can select up to %1$d targets. + All available targets are already selected. + Drag rows to reorder them. Tap precision to change it. + Length + Area + Volume + Mass + Temperature + Speed + Pressure + Energy + Power + Time + Data Dakuten / Clear Handakuten / Clear Half-width space diff --git a/app/src/main/res/xml/pref_conversion_engine.xml b/app/src/main/res/xml/pref_conversion_engine.xml index c0e9a4f03..445e5d49d 100644 --- a/app/src/main/res/xml/pref_conversion_engine.xml +++ b/app/src/main/res/xml/pref_conversion_engine.xml @@ -152,6 +152,12 @@ android:title="@string/emoticon_candidate_enable_title" app:iconSpaceReserved="false" /> + + diff --git a/app/src/main/res/xml/pref_utility_candidate.xml b/app/src/main/res/xml/pref_utility_candidate.xml new file mode 100644 index 000000000..20fc7a310 --- /dev/null +++ b/app/src/main/res/xml/pref_utility_candidate.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/ResultFormatterTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/ResultFormatterTest.kt new file mode 100644 index 000000000..12edc72b1 --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/ResultFormatterTest.kt @@ -0,0 +1,47 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +import org.junit.Assert.assertEquals +import org.junit.Test +import java.math.BigDecimal + +class ResultFormatterTest { + @Test + fun automaticPrecisionKeepsFiniteDecimalsAndUsesScientificNotationAtExtremes() { + assertEquals("1412.5", ResultFormatter.format(BigDecimal("1412.5000"), Precision.Auto)) + assertEquals("1.23456789012346", ResultFormatter.format(BigDecimal("1.2345678901234567"), Precision.Auto)) + assertEquals("1.23e12", ResultFormatter.format(BigDecimal("1230000000000"), Precision.Auto)) + assertEquals("1.23e-7", ResultFormatter.format(BigDecimal("0.000000123"), Precision.Auto)) + } + + @Test + fun manualPrecisionUsesHalfUpAndStripsZerosAndNegativeZero() { + assertEquals("1000", ResultFormatter.format(BigDecimal("1234.5"), Precision.SignificantDigits(1))) + assertEquals("1200", ResultFormatter.format(BigDecimal("1234.5"), Precision.SignificantDigits(2))) + assertEquals("0.01", ResultFormatter.format(BigDecimal("0.01234"), Precision.SignificantDigits(1))) + assertEquals("0.012", ResultFormatter.format(BigDecimal("0.01234"), Precision.SignificantDigits(2))) + assertEquals("1.24", ResultFormatter.format(BigDecimal("1.235"), Precision.SignificantDigits(3))) + assertEquals("12", ResultFormatter.format(BigDecimal("12.000"), Precision.SignificantDigits(6))) + assertEquals("0", ResultFormatter.format(BigDecimal("-0.000"), Precision.SignificantDigits(3))) + } + + @Suppress("DEPRECATION") + @Test + fun decimalPlacesUseHalfUpStripZerosAndNeverReturnNegativeZero() { + assertEquals("1234.57", ResultFormatter.format(BigDecimal("1234.567"), Precision.DecimalPlaces(2))) + assertEquals("1.5", ResultFormatter.format(BigDecimal("1.500"), Precision.DecimalPlaces(2))) + assertEquals("2", ResultFormatter.format(BigDecimal("1.5"), Precision.DecimalPlaces(0))) + assertEquals("-2", ResultFormatter.format(BigDecimal("-1.5"), Precision.DecimalPlaces(0))) + assertEquals("0", ResultFormatter.format(BigDecimal("0.49"), Precision.DecimalPlaces(0))) + assertEquals("0", ResultFormatter.format(BigDecimal("-0.49"), Precision.DecimalPlaces(0))) + assertEquals("0", ResultFormatter.format(BigDecimal("-0.000"), Precision.DecimalPlaces(2))) + assertEquals("2", ResultFormatter.format(BigDecimal("1.5"), Precision.Integer)) + } + + @Test + fun decimalPlacesKeepScientificNotationForExtremeValues() { + assertEquals( + "1.234567890123e12", + ResultFormatter.format(BigDecimal("1234567890123.4"), Precision.DecimalPlaces(0)), + ) + } +} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitRegistryTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitRegistryTest.kt new file mode 100644 index 000000000..b62898318 --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitRegistryTest.kt @@ -0,0 +1,37 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.math.BigDecimal +import java.math.MathContext + +class UnitRegistryTest { + @Test + fun everyRegisteredUnitRoundTripsThroughItsBaseUnit() { + val context = MathContext(40) + val input = BigDecimal("12.345") + UnitRegistry.Default.units.forEach { unit -> + val roundTrip = unit.fromBase(unit.toBase(input, context), context) + assertTrue(unit.id.value, roundTrip.subtract(input).abs() < BigDecimal("1e-30")) + } + } + + @Test + fun registryIdsAreUniqueAndStable() { + val units = UnitRegistry.Default.units + assertEquals(units.size, units.map { it.id }.distinct().size) + assertTrue(units.all { it.id.value.matches(Regex("[a-z0-9._-]+")) }) + assertTrue(UnitCategory.entries.all { category -> units.any { it.category == category } }) + } + + @Test + fun everyCanonicalSymbolCanBeParsed() { + val parser = UnitExpressionParser() + UnitRegistry.Default.units.forEach { unit -> + val normalized = UtilityInputNormalizer.normalize("1${unit.symbol}") + val parsed = parser.parse(normalized) + assertEquals(unit.id.value, unit.category, parsed?.category) + } + } +} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitTargetSettingsJsonCodecTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitTargetSettingsJsonCodecTest.kt new file mode 100644 index 000000000..b29d8fe37 --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UnitTargetSettingsJsonCodecTest.kt @@ -0,0 +1,108 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class UnitTargetSettingsJsonCodecTest { + private val codec = UnitTargetSettingsJsonCodec() + + @Test + fun defaultsAndRoundTripPreserveExplicitEmptyCategories() { + assertEquals(UtilityCandidateConfig.defaultUnitTargets(), codec.decodeOrDefault(null)) + val settings = UtilityCandidateConfig.defaultUnitTargets() + + (UnitCategory.LENGTH to emptyList()) + assertEquals(settings, codec.decodeOrDefault(codec.encode(settings))) + } + + @Test + fun decimalPrecisionRoundTripsWithoutChangingTheDocumentVersion() { + val settings = UtilityCandidateConfig.defaultUnitTargets() + + ( + UnitCategory.LENGTH to listOf( + UnitTargetSetting(UnitId("length.m"), Precision.DecimalPlaces(2)), + ) + ) + + val encoded = codec.encode(settings) + + assertTrue(encoded.contains("\"version\":1")) + assertTrue(encoded.contains("\"precision\":\"decimal:2\"")) + assertEquals(settings, codec.decodeOrDefault(encoded)) + } + + @Test + fun legacyIntegerAndNumericPrecisionsRemainReadable() { + val decoded = codec.decodeOrDefault( + """{"version":1,"categories":{"length":[ + {"unitId":"length.m","precision":"integer"}, + {"unitId":"length.cm","precision":"1"}, + {"unitId":"length.ft","precision":"2"} + ]}}""".trimIndent(), + ).getValue(UnitCategory.LENGTH) + + assertEquals(Precision.DecimalPlaces(0), decoded[0].precision) + assertEquals(Precision.SignificantDigits(1), decoded[1].precision) + assertEquals(Precision.SignificantDigits(2), decoded[2].precision) + } + + @Test + fun invalidDecimalPrecisionIsDiscarded() { + val decoded = codec.decodeOrDefault( + """{"version":1,"categories":{"length":[ + {"unitId":"length.m","precision":"decimal:-1"}, + {"unitId":"length.cm","precision":"decimal:16"}, + {"unitId":"length.ft","precision":"decimal:2"} + ]}}""".trimIndent(), + ).getValue(UnitCategory.LENGTH) + + assertEquals(listOf("length.ft"), decoded.map { it.unitId.value }) + assertEquals(Precision.DecimalPlaces(2), decoded.single().precision) + } + + @Test + fun corruptDocumentFallsBackToDefaults() { + assertEquals(UtilityCandidateConfig.defaultUnitTargets(), codec.decodeOrDefault("{")) + assertEquals( + UtilityCandidateConfig.defaultUnitTargets(), + codec.decodeOrDefault("""{"version":999,"categories":{}}"""), + ) + } + + @Test + fun invalidDuplicateWrongCategoryAndExcessTargetsAreRepaired() { + val json = """ + {"version":1,"categories":{"length":[ + {"unitId":"length.m","precision":"6"}, + {"unitId":"length.m","precision":"5"}, + {"unitId":"mass.kg","precision":"6"}, + {"unitId":"unknown.id","precision":"auto"}, + {"unitId":"length.cm","precision":"0"}, + {"unitId":"length.ft","precision":"5"}, + {"unitId":"length.in","precision":"5"}, + {"unitId":"length.km","precision":"5"}, + {"unitId":"length.mi","precision":"5"}, + {"unitId":"length.yd","precision":"5"}, + {"unitId":"length.nmi","precision":"5"}, + {"unitId":"length.mm","precision":"5"}, + {"unitId":"length.nm","precision":"5"}, + {"unitId":"length.um","precision":"5"} + ]}} + """.trimIndent() + val decoded = codec.decodeOrDefault(json) + assertEquals( + listOf( + "length.m", + "length.ft", + "length.in", + "length.km", + "length.mi", + "length.yd", + "length.nmi", + "length.mm", + ), + decoded.getValue(UnitCategory.LENGTH).map { it.unitId.value }, + ) + assertTrue(decoded.getValue(UnitCategory.AREA).isNotEmpty()) + } +} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateComposerTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateComposerTest.kt new file mode 100644 index 000000000..b27afcba8 --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateComposerTest.kt @@ -0,0 +1,108 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_CALCULATION +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_UNIT_CONVERSION +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_UTILITY_LITERAL +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.Candidate +import org.junit.Assert.assertEquals +import org.junit.Test + +class UtilityCandidateComposerTest { + @Test + fun explicitResultsLeadAndDuplicateStringsAreRemoved() { + val existing = listOf(candidate("3"), candidate("三")) + val result = UtilityCandidateResult( + candidates = listOf(UtilityCandidate("3", UtilityCandidateKind.CALCULATION)), + trigger = UtilityTrigger.EXPLICIT_CALCULATION, + ) + val composed = UtilityCandidateComposer.compose("1+2=", existing, result) + assertEquals(listOf("3", "三"), composed.map { it.string }) + assertEquals(CANDIDATE_TYPE_CALCULATION, composed.first().type) + } + + @Test + fun automaticConversionKeepsLiteralFirstAndConversionsImmediatelyAfterIt() { + val result = UtilityCandidateResult( + candidates = listOf(UtilityCandidate("1m", UtilityCandidateKind.UNIT_CONVERSION)), + trigger = UtilityTrigger.AUTOMATIC_UNIT_CONVERSION, + ) + val composed = UtilityCandidateComposer.compose("100cm", listOf(candidate("百")), result) + assertEquals(listOf("100cm", "1m", "百"), composed.map { it.string }) + assertEquals(CANDIDATE_TYPE_UTILITY_LITERAL, composed[0].type) + assertEquals(CANDIDATE_TYPE_UNIT_CONVERSION, composed[1].type) + } + + @Test + fun existingLiteralIsReusedWithoutUtilityMarker() { + val literal = candidate("100cm", type = 3) + val result = UtilityCandidateResult( + candidates = listOf(UtilityCandidate("1m", UtilityCandidateKind.UNIT_CONVERSION)), + trigger = UtilityTrigger.AUTOMATIC_UNIT_CONVERSION, + ) + val composed = UtilityCandidateComposer.compose("100cm", listOf(candidate("百"), literal), result) + assertEquals(3, composed.first().type.toInt()) + assertEquals(1, composed.count { it.string == "100cm" }) + } + + @Test + fun canonicalSourceFromUnitReadingLeadsAutomaticConversions() { + val canonical = candidate("10尺", type = 3) + val input = candidate("10しゃく", type = 4) + val result = UtilityCandidateResult( + candidates = listOf(UtilityCandidate("3.0303m", UtilityCandidateKind.UNIT_CONVERSION)), + trigger = UtilityTrigger.AUTOMATIC_UNIT_CONVERSION, + preferredSourceText = "10尺", + ) + + val composed = UtilityCandidateComposer.compose( + input = "10しゃく", + existingCandidates = listOf(input, candidate("十尺"), canonical), + result = result, + ) + + assertEquals(listOf("10尺", "3.0303m", "10しゃく", "十尺"), composed.map { it.string }) + assertEquals(3, composed.first().type.toInt()) + assertEquals(CANDIDATE_TYPE_UNIT_CONVERSION, composed[1].type) + } + + @Test + fun canonicalSourceIsSynthesizedWhenDictionaryDoesNotProvideIt() { + val result = UtilityCandidateResult( + candidates = listOf(UtilityCandidate("33.0579m²", UtilityCandidateKind.UNIT_CONVERSION)), + trigger = UtilityTrigger.AUTOMATIC_UNIT_CONVERSION, + preferredSourceText = "10坪", + ) + + val composed = UtilityCandidateComposer.compose("10つぼ", emptyList(), result) + + assertEquals(listOf("10坪", "33.0579m²", "10つぼ"), composed.map { it.string }) + assertEquals(CANDIDATE_TYPE_UTILITY_LITERAL, composed.first().type) + } + + @Test + fun parsedJapaneseUnitReadingsProduceCanonicalFirstCandidates() { + val provider = UtilityCandidateProvider() + + val shaku = UtilityCandidateComposer.compose( + input = "10 しゃく", + existingCandidates = listOf(candidate("10尺"), candidate("10 しゃく")), + result = provider.provide("10 しゃく"), + ) + val tsubo = UtilityCandidateComposer.compose( + input = "10 つぼ", + existingCandidates = listOf(candidate("10 つぼ")), + result = provider.provide("10 つぼ"), + ) + + assertEquals("10尺", shaku.first().string) + assertEquals("10坪", tsubo.first().string) + assertEquals(CANDIDATE_TYPE_UTILITY_LITERAL, tsubo.first().type) + } + + private fun candidate(text: String, type: Byte = 1) = Candidate( + string = text, + type = type, + length = text.length.toUByte(), + score = 0, + ) +} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateConfigTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateConfigTest.kt new file mode 100644 index 000000000..7bf7d9a21 --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateConfigTest.kt @@ -0,0 +1,59 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +class UtilityCandidateConfigTest { + @Test + fun significantDigitsAcceptOneThroughFifteen() { + assertEquals(1, Precision.SignificantDigits(1).digits) + assertEquals(2, Precision.SignificantDigits(2).digits) + assertEquals(15, Precision.SignificantDigits(15).digits) + assertThrows(IllegalArgumentException::class.java) { + Precision.SignificantDigits(0) + } + assertThrows(IllegalArgumentException::class.java) { + Precision.SignificantDigits(16) + } + } + + @Test + fun decimalPlacesAcceptZeroThroughFifteen() { + assertEquals(0, Precision.DecimalPlaces(0).places) + assertEquals(15, Precision.DecimalPlaces(15).places) + assertThrows(IllegalArgumentException::class.java) { + Precision.DecimalPlaces(-1) + } + assertThrows(IllegalArgumentException::class.java) { + Precision.DecimalPlaces(16) + } + } + + @Test + fun defaultsStayAtFourTargetsWhileLimitIsEight() { + assertEquals(8, UtilityCandidateConfig.MAX_TARGETS_PER_CATEGORY) + assertTrue(UtilityCandidateConfig.defaultUnitTargets().values.all { it.size <= 4 }) + } + + @Test + fun acceptsEightTargetsAndRejectsNine() { + val targets = UnitRegistry.Default.units + .filter { it.category == UnitCategory.LENGTH } + .take(9) + .map { UnitTargetSetting(it.id) } + val defaults = UtilityCandidateConfig.defaultUnitTargets() + + val config = UtilityCandidateConfig( + unitTargets = defaults + (UnitCategory.LENGTH to targets.take(8)), + ) + assertEquals(8, config.unitTargets.getValue(UnitCategory.LENGTH).size) + + assertThrows(IllegalArgumentException::class.java) { + UtilityCandidateConfig( + unitTargets = defaults + (UnitCategory.LENGTH to targets), + ) + } + } +} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateProviderTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateProviderTest.kt new file mode 100644 index 000000000..82e681ec0 --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/converter/utility/UtilityCandidateProviderTest.kt @@ -0,0 +1,239 @@ +package com.kazumaproject.markdownhelperkeyboard.converter.utility + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import kotlin.random.Random + +class UtilityCandidateProviderTest { + private val provider = UtilityCandidateProvider() + + @Test + fun acceptanceExamplesAreAvailableWithDefaultSettings() { + assertEquals("1412.5", texts("1250*1.13=").first()) + assertEquals("10.4394m", texts("411in").first()) + assertEquals("0°C", texts("32f").first()) + assertTrue(texts("5ft3in").toString(), "160.02cm" in texts("5ft3in")) + assertTrue("7.72lb" in texts("3.5kg")) + } + + @Test + fun calculationRequiresExactlyOneBoundaryEquals() { + assertFalse(provider.provide("1+2").hasCandidates) + assertFalse(provider.provide("=1+2=").hasCandidates) + assertFalse(provider.provide("1=2").hasCandidates) + assertFalse(provider.provide("1+=").hasCandidates) + assertEquals(UtilityTrigger.EXPLICIT_CALCULATION, provider.provide("=1+2").trigger) + assertEquals(listOf("3", "3=1+2"), texts("=1+2")) + } + + @Test + fun precedencePowerUnaryImplicitMultiplicationAndScientificNotation() { + assertEquals("14", texts("2+3*4=").first()) + assertEquals("512", texts("2^3^2=").first()) + assertEquals("-4", texts("-2^2=").first()) + assertEquals("0.25", texts("2^-2=").first()) + assertEquals("14", texts("2(3+4)=").first()) + assertEquals("2000", texts("2e3=").first()) + } + + @Test + fun calculatorPercentAndModAreSupported() { + assertEquals("110", texts("100+10%=").first()) + assertEquals("90", texts("100-10%=").first()) + assertEquals("10", texts("100*10%=").first()) + assertEquals("1000", texts("100/10%=").first()) + assertEquals("1", texts("10 mod 3=").first()) + } + + @Test + fun functionsAndAngleModesAreSupported() { + assertEquals("3", texts("sqrt(9)=").first()) + assertEquals("120", texts("5!=").first()) + assertEquals("1", texts("sin(90)=").first()) + val radians = UtilityCandidateConfig(angleMode = AngleMode.RADIANS) + assertEquals("1", provider.provide("sin(pi/2)=", radians).candidates.first().text) + assertEquals("90", texts("asin(1)=").first()) + } + + @Test + fun decimalPlacesApplyToCalculationExpressionAndUnitCandidates() { + val calculationConfig = UtilityCandidateConfig( + calculationPrecision = Precision.DecimalPlaces(2), + ) + assertEquals( + listOf("0.33", "1÷3=0.33"), + provider.provide("1/3=", calculationConfig).candidates.map { it.text }, + ) + + val unitConfig = UtilityCandidateConfig( + unitTargets = UtilityCandidateConfig.defaultUnitTargets() + + ( + UnitCategory.LENGTH to listOf( + UnitTargetSetting(UnitId("length.cm"), Precision.DecimalPlaces(2)), + ) + ), + ) + assertEquals( + listOf("2.54cm"), + provider.provide("1in", unitConfig).candidates.map { it.text }, + ) + } + + @Test + fun oneAndTwoSignificantDigitsApplyToCandidates() { + assertEquals( + "1000", + provider.provide( + "1234.5=", + UtilityCandidateConfig(calculationPrecision = Precision.SignificantDigits(1)), + ).candidates.first().text, + ) + assertEquals( + "1200", + provider.provide( + "1234.5=", + UtilityCandidateConfig(calculationPrecision = Precision.SignificantDigits(2)), + ).candidates.first().text, + ) + } + + @Test + fun fullWidthInputAndGroupingAreNormalized() { + assertEquals("7", texts("123÷3+2×2-38=").first()) + assertEquals("1234.5", texts("1,200+34.5=").first()) + } + + @Test + fun invalidAndOversizedCalculationInputsReturnNoCandidate() { + listOf("1/0=", "sqrt(-1)=", "log(0)=", "(-1)^0.5=").forEach { + assertFalse(it, provider.provide(it).hasCandidates) + } + assertFalse(provider.provide("1".repeat(65) + "=").hasCandidates) + assertFalse(provider.provide("(".repeat(33) + "1" + ")".repeat(33) + "=").hasCandidates) + assertFalse(provider.provide("1".repeat(256)).hasCandidates) + } + + @Test + fun explicitAndAutomaticConversionTriggersAreDistinct() { + assertEquals(UtilityTrigger.AUTOMATIC_UNIT_CONVERSION, provider.provide("411in").trigger) + assertEquals(UtilityTrigger.EXPLICIT_UNIT_CONVERSION, provider.provide("411in>m").trigger) + assertEquals(listOf("10.4394m"), texts("411in → m")) + assertEquals(listOf("10.4394m"), texts("411in to m")) + assertFalse(provider.provide("411in tom").hasCandidates) + } + + @Test + fun wordAliasesExposeCanonicalSourceWithoutChangingSymbolInputOrdering() { + assertEquals("10尺", provider.provide("10 しゃく").preferredSourceText) + assertEquals("10坪", provider.provide("10つぼ").preferredSourceText) + assertEquals("5ft3in", provider.provide("5 feet 3 inches").preferredSourceText) + assertEquals("1h30min", provider.provide("1 時間 30 分").preferredSourceText) + assertEquals("32°F", provider.provide("華氏32度").preferredSourceText) + + assertEquals(null, provider.provide("10尺").preferredSourceText) + assertEquals(null, provider.provide("411in").preferredSourceText) + assertEquals(null, provider.provide("32f").preferredSourceText) + } + + @Test + fun compoundUnitsAndSameDimensionAdditionAreSupported() { + assertTrue("160.02cm" in texts("5'3\"")) + assertTrue("5400s" in texts("1h30min")) + assertTrue("5400s" in texts("1h30m")) + assertEquals(listOf("1.0668m"), texts("3ft+6in>m")) + assertFalse(provider.provide("100km/2h").hasCandidates) + assertFalse(provider.provide("2m*3m").hasCandidates) + assertFalse(provider.provide("1m+2s").hasCandidates) + } + + @Test + fun temperatureAliasesAndAffineRestrictionsWork() { + assertEquals("0°C", texts("32°F").first()) + assertEquals("0°C", texts("華氏32度").first()) + assertEquals("68°F", texts("摂氏20度").first { it.endsWith("°F") }) + assertFalse(provider.provide("20°C+10°C").hasCandidates) + } + + @Test + fun areaVolumeDataAndRegionalAliasesWork() { + assertEquals(texts("1m2>ft2"), texts("1m^2>ft²")) + assertEquals("1000mL", texts("1L>mL").single()) + assertEquals("1024B", texts("1KiB>B").single()) + assertEquals("1000B", texts("1kB>B").single()) + + val japan = UtilityCandidateConfig(regionalUnitProfile = RegionalUnitProfile.JAPAN) + val us = UtilityCandidateConfig(regionalUnitProfile = RegionalUnitProfile.UNITED_STATES) + val uk = UtilityCandidateConfig(regionalUnitProfile = RegionalUnitProfile.UNITED_KINGDOM) + assertEquals("200mL", provider.provide("1cup>mL", japan).candidates.single().text) + assertEquals("236.588mL", provider.provide("1cup>mL", us).candidates.single().text) + assertEquals("284.131mL", provider.provide("1cup>mL", uk).candidates.single().text) + assertEquals("3785.41mL", provider.provide("1galUS>mL", uk).candidates.single().text) + } + + @Test + fun categoryCanDisableAutomaticTargetsWithoutDisablingExplicitConversion() { + val config = UtilityCandidateConfig( + unitTargets = UtilityCandidateConfig.defaultUnitTargets() + + (UnitCategory.LENGTH to emptyList()) + ) + assertFalse(provider.provide("411in", config).hasCandidates) + assertEquals("10.4394m", provider.provide("411in>m", config).candidates.single().text) + } + + @Test + fun automaticConversionReturnsEightDistinctTargetsInConfiguredOrder() { + val targetIds = listOf( + "length.m", + "length.cm", + "length.ft", + "length.in", + "length.km", + "length.mi", + "length.yd", + "length.nmi", + ) + val config = UtilityCandidateConfig( + unitTargets = UtilityCandidateConfig.defaultUnitTargets() + + (UnitCategory.LENGTH to targetIds.map { UnitTargetSetting(UnitId(it)) }) + ) + + val candidates = provider.provide("1寸", config).candidates.map { it.text } + + assertEquals(8, candidates.size) + assertEquals(candidates.size, candidates.distinct().size) + val expectedSymbols = listOf("m", "cm", "ft", "in", "km", "mi", "yd", "nmi") + candidates.zip(expectedSymbols).forEach { (candidate, symbol) -> + assertTrue("$candidate should end with $symbol", candidate.endsWith(symbol)) + } + } + + @Test + fun fixedSeedRandomInputsNeverEscapeAsExceptions() { + val random = Random(0x51C0DE) + val alphabet = "0123456789+-*/^%=().,abcdefghijklmnopqrstuvwxyzπ°尺寸華氏摂氏→ " + repeat(2_000) { + val input = buildString { + repeat(random.nextInt(0, 256)) { append(alphabet.random(random)) } + } + provider.provide(input) + } + } + + @Test + fun maximumAcceptedInputStaysWithinOneFrameOnAverage() { + val input = " ".repeat(198) + "1m" + repeat(50) { provider.provide(input) } + + val iterations = 500 + val startedAt = System.nanoTime() + repeat(iterations) { + assertTrue(provider.provide(input).hasCandidates) + } + val averageMillis = (System.nanoTime() - startedAt) / iterations / 1_000_000.0 + assertTrue("average=${averageMillis}ms", averageMillis < 1_000.0 / 60.0) + } + + private fun texts(input: String): List = provider.provide(input).candidates.map { it.text } +} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/ime_service/adapters/SuggestionAdapterUserTemplateTypeTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/ime_service/adapters/SuggestionAdapterUserTemplateTypeTest.kt index f76b436cd..aca950329 100644 --- a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/ime_service/adapters/SuggestionAdapterUserTemplateTypeTest.kt +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/ime_service/adapters/SuggestionAdapterUserTemplateTypeTest.kt @@ -5,8 +5,10 @@ import android.os.Looper import android.widget.FrameLayout import androidx.test.core.app.ApplicationProvider import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_ERA +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_CALCULATION import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_LEARNED_DICTIONARY import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_TIME +import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_UNIT_CONVERSION import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_USER_DICTIONARY import com.kazumaproject.markdownhelperkeyboard.converter.candidate.CANDIDATE_TYPE_USER_TEMPLATE import com.kazumaproject.markdownhelperkeyboard.converter.candidate.Candidate @@ -159,6 +161,23 @@ class SuggestionAdapterUserTemplateTypeTest { adapter.release() } + @Test + fun utilityCandidatesShowCalculationAndConversionBadges() { + val adapter = SuggestionAdapter() + adapter.suggestions = listOf( + candidate("3", CANDIDATE_TYPE_CALCULATION), + candidate("1m", CANDIDATE_TYPE_UNIT_CONVERSION), + ) + awaitItemCount(adapter, 2) + val holder = createHolder(adapter) + + adapter.onBindViewHolder(holder, 0) + assertEquals("[Calc]", holder.typeText.text.toString()) + adapter.onBindViewHolder(holder, 1) + assertEquals("[Convert]", holder.typeText.text.toString()) + adapter.release() + } + private fun dictionaryCandidates(): List = listOf( candidate("学習候補", CANDIDATE_TYPE_LEARNED_DICTIONARY), candidate("ユーザー候補", CANDIDATE_TYPE_USER_DICTIONARY), diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/PrecisionSelectionDialogTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/PrecisionSelectionDialogTest.kt new file mode 100644 index 000000000..38241dc0c --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/PrecisionSelectionDialogTest.kt @@ -0,0 +1,105 @@ +package com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting + +import android.content.Context +import android.content.DialogInterface +import android.os.Looper +import android.view.ContextThemeWrapper +import android.widget.NumberPicker +import android.widget.RadioGroup +import androidx.test.core.app.ApplicationProvider +import com.kazumaproject.markdownhelperkeyboard.R +import com.kazumaproject.markdownhelperkeyboard.converter.utility.Precision +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class PrecisionSelectionDialogTest { + @Test + fun stateKeepsIndependentDefaultsAndSelectionsForBothManualModes() { + val state = PrecisionSelectionState(Precision.Auto) + assertEquals(PrecisionSelectionMode.AUTO, state.mode) + assertEquals(2, state.decimalPlaces) + assertEquals(6, state.significantDigits) + + state.selectMode(PrecisionSelectionMode.DECIMAL_PLACES) + state.updateDigits(4) + state.selectMode(PrecisionSelectionMode.SIGNIFICANT_DIGITS) + state.updateDigits(8) + state.selectMode(PrecisionSelectionMode.DECIMAL_PLACES) + + assertEquals(4, state.selectedDigits) + assertEquals(Precision.DecimalPlaces(4), state.toPrecision()) + state.selectMode(PrecisionSelectionMode.SIGNIFICANT_DIGITS) + assertEquals(8, state.selectedDigits) + assertEquals(Precision.SignificantDigits(8), state.toPrecision()) + } + + @Suppress("DEPRECATION") + @Test + fun stateMapsLegacyIntegerAndEnforcesModeRanges() { + val legacy = PrecisionSelectionState(Precision.Integer) + assertEquals(PrecisionSelectionMode.DECIMAL_PLACES, legacy.mode) + assertEquals(0, legacy.selectedDigits) + assertEquals(Precision.DecimalPlaces(0), legacy.toPrecision()) + + legacy.updateDigits(99) + assertEquals(15, legacy.selectedDigits) + legacy.selectMode(PrecisionSelectionMode.SIGNIFICANT_DIGITS) + legacy.updateDigits(0) + assertEquals(1, legacy.selectedDigits) + } + + @Test + fun dialogSwitchesModesRetainsDigitsAndAppliesOnlyWithOk() { + val selected = mutableListOf() + val dialog = PrecisionSelectionDialog.create( + context = themedContext(), + current = Precision.Auto, + onSelected = selected::add, + ) + dialog.show() + val modeGroup = dialog.findViewById(R.id.utility_precision_mode_group)!! + val picker = dialog.findViewById(R.id.utility_precision_digit_picker)!! + + assertFalse(picker.isEnabled) + modeGroup.check(R.id.utility_precision_mode_decimal_places) + assertTrue(picker.isEnabled) + assertEquals(0, picker.minValue) + assertEquals(15, picker.maxValue) + assertEquals(2, picker.value) + + modeGroup.check(R.id.utility_precision_mode_significant_digits) + assertEquals(1, picker.minValue) + assertEquals(6, picker.value) + modeGroup.check(R.id.utility_precision_mode_decimal_places) + assertEquals(2, picker.value) + + dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(listOf(Precision.DecimalPlaces(2)), selected) + + val cancelled = PrecisionSelectionDialog.create( + context = themedContext(), + current = Precision.Auto, + onSelected = selected::add, + ) + cancelled.show() + cancelled.findViewById(R.id.utility_precision_mode_group)!! + .check(R.id.utility_precision_mode_significant_digits) + cancelled.getButton(DialogInterface.BUTTON_NEGATIVE).performClick() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(listOf(Precision.DecimalPlaces(2)), selected) + } + + private fun themedContext(): Context = ContextThemeWrapper( + ApplicationProvider.getApplicationContext(), + R.style.Theme_MarkdownKeyboard, + ) +} diff --git a/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/UtilityCandidatePreferenceTest.kt b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/UtilityCandidatePreferenceTest.kt new file mode 100644 index 000000000..081ee0a17 --- /dev/null +++ b/app/src/test/java/com/kazumaproject/markdownhelperkeyboard/setting_activity/ui/setting/UtilityCandidatePreferenceTest.kt @@ -0,0 +1,283 @@ +package com.kazumaproject.markdownhelperkeyboard.setting_activity.ui.setting + +import android.content.Context +import android.content.res.Configuration +import androidx.preference.PreferenceManager +import androidx.test.core.app.ApplicationProvider +import com.kazumaproject.markdownhelperkeyboard.R +import com.kazumaproject.markdownhelperkeyboard.converter.utility.AngleMode +import com.kazumaproject.markdownhelperkeyboard.converter.utility.Precision +import com.kazumaproject.markdownhelperkeyboard.converter.utility.RegionalUnitProfile +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UnitCategory +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UnitId +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UnitTargetSetting +import com.kazumaproject.markdownhelperkeyboard.converter.utility.UtilityCandidateConfig +import com.kazumaproject.markdownhelperkeyboard.ime_service.ImePreferencesSnapshot +import com.kazumaproject.markdownhelperkeyboard.setting_activity.AppPreference +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.xmlpull.v1.XmlPullParser +import java.util.Locale + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class UtilityCandidatePreferenceTest { + private lateinit var context: Context + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + PreferenceManager.getDefaultSharedPreferences(context).edit().clear().commit() + AppPreference.init(context) + } + + @Test + fun defaultsAreEnabledForExistingUsersAndIncludedInImeSnapshot() { + val config = ImePreferencesSnapshot.from(AppPreference).utilityCandidateConfig + + assertTrue(config.calculationEnabled) + assertTrue(config.unitConversionEnabled) + assertTrue(config.includeExpressionCandidate) + assertEquals(AngleMode.DEGREES, config.angleMode) + assertEquals(Precision.Auto, config.calculationPrecision) + assertEquals(RegionalUnitProfile.JAPAN, config.regionalUnitProfile) + assertTrue(config.unitTargets.values.all { it.size <= 4 }) + assertEquals(8, UtilityCandidateConfig.MAX_TARGETS_PER_CATEGORY) + assertEquals( + "You can select up to 8 targets.", + context.getString( + R.string.utility_target_limit, + UtilityCandidateConfig.MAX_TARGETS_PER_CATEGORY, + ), + ) + } + + @Test + fun persistedConfigIsReadIntoImeSnapshot() { + val updated = AppPreference.utility_candidate_config.copy( + calculationEnabled = false, + includeExpressionCandidate = false, + angleMode = AngleMode.RADIANS, + calculationPrecision = Precision.SignificantDigits(9), + regionalUnitProfile = RegionalUnitProfile.UNITED_KINGDOM, + ) + AppPreference.utility_candidate_config = updated + + assertEquals(updated, ImePreferencesSnapshot.from(AppPreference).utilityCandidateConfig) + } + + @Test + fun decimalPrecisionPersistsForCalculationAndUnitTargets() { + val defaults = AppPreference.utility_candidate_config + val updated = defaults.copy( + calculationPrecision = Precision.DecimalPlaces(2), + unitTargets = defaults.unitTargets + + ( + UnitCategory.LENGTH to + listOf( + UnitTargetSetting( + UnitId("length.m"), + Precision.DecimalPlaces(2), + ), + ) + ), + ) + + AppPreference.utility_candidate_config = updated + + assertEquals(updated, ImePreferencesSnapshot.from(AppPreference).utilityCandidateConfig) + val preferences = PreferenceManager.getDefaultSharedPreferences(context) + assertEquals( + "decimal:2", + preferences.getString(AppPreference.UTILITY_CALCULATION_PRECISION_KEY, null), + ) + assertTrue( + preferences.getString(AppPreference.UTILITY_UNIT_TARGETS_JSON_KEY, null) + ?.contains("\"precision\":\"decimal:2\"") == true, + ) + } + + @Test + fun legacyIntegerPreferenceMigratesToDecimalPlacesZero() { + val preferences = PreferenceManager.getDefaultSharedPreferences(context) + preferences.edit() + .putString(AppPreference.UTILITY_CALCULATION_PRECISION_KEY, "integer") + .putString( + AppPreference.UTILITY_UNIT_TARGETS_JSON_KEY, + """{"version":1,"categories":{"length":[ + {"unitId":"length.m","precision":"integer"} + ]}}""".trimIndent(), + ) + .commit() + + val config = ImePreferencesSnapshot.from(AppPreference).utilityCandidateConfig + assertEquals(Precision.DecimalPlaces(0), config.calculationPrecision) + assertEquals( + Precision.DecimalPlaces(0), + config.unitTargets.getValue(UnitCategory.LENGTH).single().precision, + ) + } + + @Test + fun invalidDecimalCalculationPreferenceFallsBackToAutomatic() { + PreferenceManager.getDefaultSharedPreferences(context).edit() + .putString(AppPreference.UTILITY_CALCULATION_PRECISION_KEY, "decimal:16") + .commit() + + assertEquals( + Precision.Auto, + ImePreferencesSnapshot.from(AppPreference).utilityCandidateConfig.calculationPrecision, + ) + } + + @Test + fun precisionLabelsAreLocalized() { + val english = localizedContext(Locale.ENGLISH) + val japanese = localizedContext(Locale.JAPANESE) + + assertEquals("Automatic", english.utilityPrecisionLabel(Precision.Auto)) + assertEquals("0 decimal places", english.utilityPrecisionLabel(Precision.DecimalPlaces(0))) + assertEquals("1 decimal place", english.utilityPrecisionLabel(Precision.DecimalPlaces(1))) + assertEquals("2 decimal places", english.utilityPrecisionLabel(Precision.DecimalPlaces(2))) + assertEquals("1 significant digit", english.utilityPrecisionLabel(Precision.SignificantDigits(1))) + assertEquals("2 significant digits", english.utilityPrecisionLabel(Precision.SignificantDigits(2))) + assertEquals("自動", japanese.utilityPrecisionLabel(Precision.Auto)) + assertEquals("小数点以下 0 桁", japanese.utilityPrecisionLabel(Precision.DecimalPlaces(0))) + assertEquals("小数点以下 2 桁", japanese.utilityPrecisionLabel(Precision.DecimalPlaces(2))) + assertEquals("有効数字 1 桁", japanese.utilityPrecisionLabel(Precision.SignificantDigits(1))) + assertEquals("有効数字 2 桁", japanese.utilityPrecisionLabel(Precision.SignificantDigits(2))) + } + + @Test + fun screenInflatesAndSearchTargetsItsHighlightableDestination() { + val screen = PreferenceManager(context).inflateFromResource( + context, + R.xml.pref_utility_candidate, + null, + ) + assertTrue(screen.findPreference(CALCULATION_KEY) != null) + assertTrue(screen.findPreference(PRECISION_KEY) != null) + TARGET_KEYS.forEach { key -> + assertTrue(key, screen.findPreference(key) != null) + } + + val result = SettingSearchIndex.searchable(context, SettingSearchScope.NEW_HOME) + .first { it.key == CALCULATION_KEY } + assertEquals(SettingCategory.CONVERSION_ENGINE, result.category) + assertEquals( + R.id.utilityCandidatePreferenceFragment, + SettingDestinations.destinationId(result.destination), + ) + assertEquals( + CALCULATION_KEY, + SettingDestinations.highlightPreferenceKey(result.destination), + ) + + val precisionResult = SettingSearchIndex.searchable(context, SettingSearchScope.NEW_HOME) + .first { it.key == PRECISION_KEY } + assertTrue(precisionResult.destination is SettingDestinationType.NavDestination) + assertEquals( + R.id.utilityCandidatePreferenceFragment, + SettingDestinations.destinationId(precisionResult.destination), + ) + assertEquals( + PRECISION_KEY, + SettingDestinations.highlightPreferenceKey(precisionResult.destination), + ) + } + + @Test + fun bothSettingsExperiencesExposeTheSharedConversionEngineRoute() { + val newRoute = SettingSearchIndex.searchable(context, SettingSearchScope.NEW_HOME) + .first { it.key == ROUTE_KEY } + val legacyTab = SettingTabRegistry.createTabs() + .first { it.key == SettingTabRegistry.TAB_CONVERSION_ENGINE } + + assertEquals( + R.id.utilityCandidatePreferenceFragment, + SettingDestinations.destinationId(newRoute.destination), + ) + assertEquals(R.xml.pref_conversion_engine, legacyTab.xmlRes) + assertTrue(conversionEngineXmlContainsRoute()) + assertTrue(routeIsInPredictionSourceCategory()) + } + + private fun conversionEngineXmlContainsRoute(): Boolean { + val parser = context.resources.getXml(R.xml.pref_conversion_engine) + val androidNamespace = "http://schemas.android.com/apk/res/android" + return parser.use { + while (parser.eventType != XmlPullParser.END_DOCUMENT) { + if ( + parser.eventType == XmlPullParser.START_TAG && + parser.getAttributeValue(androidNamespace, "key") == ROUTE_KEY + ) return@use true + parser.next() + } + false + } + } + + private fun routeIsInPredictionSourceCategory(): Boolean { + val parser = context.resources.getXml(R.xml.pref_conversion_engine) + val androidNamespace = "http://schemas.android.com/apk/res/android" + var currentCategoryTitle: String? = null + return parser.use { + while (parser.eventType != XmlPullParser.END_DOCUMENT) { + when (parser.eventType) { + XmlPullParser.START_TAG -> when (parser.name) { + "PreferenceCategory" -> { + val titleRes = parser.getAttributeResourceValue( + androidNamespace, + "title", + 0, + ) + currentCategoryTitle = titleRes.takeIf { it != 0 }?.let(context::getString) + } + "Preference" -> if ( + parser.getAttributeValue(androidNamespace, "key") == ROUTE_KEY + ) { + return@use currentCategoryTitle == + context.getString(R.string.prediction_source_category_title) + } + } + XmlPullParser.END_TAG -> if (parser.name == "PreferenceCategory") { + currentCategoryTitle = null + } + } + parser.next() + } + false + } + } + + private fun localizedContext(locale: Locale): Context { + val configuration = Configuration(context.resources.configuration).apply { + setLocale(locale) + } + return context.createConfigurationContext(configuration) + } + + private companion object { + const val CALCULATION_KEY = "utility_calculation_enabled" + const val PRECISION_KEY = "utility_calculation_precision" + const val ROUTE_KEY = "setting_route_utility_candidates" + val TARGET_KEYS = listOf( + "utility_targets_length", + "utility_targets_area", + "utility_targets_volume", + "utility_targets_mass", + "utility_targets_temperature", + "utility_targets_speed", + "utility_targets_pressure", + "utility_targets_energy", + "utility_targets_power", + "utility_targets_time", + "utility_targets_data", + ) + } +}