From 07d77458ba4d3daa46d3b3e0fdfe47312b28273a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 16:21:27 +0000 Subject: [PATCH 1/2] App: a colour dialog with colours to tap, a hue and saturation picker and a preview The colour dialog in Settings was three RGB sliders and a hex field. Neither the Android framework nor Compose Material 3 1.4.0 has a colour picker, so the dialog is the app's own and follows desktop Mudlet's QColorDialog: the sixteen ANSI colours, two greys and the setting's Mudlet colour to tap; a saturation and brightness square and a hue bar; the hex field; and the RGB sliders, folded under "Fine-tune". A preview shows the colour with the one it is seen with. TalkBack reads each colour to tap by name with its selected state, steps the square 5% at a time by custom actions, and moves the hue bar as a slider. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016ujaeFyaqXXDx8xjoThE6J --- .../ui/ColourPickerPseudoLocaleTest.kt | 156 ++++++++ .../org/mudlet/android/ui/ColourPickerTest.kt | 262 +++++++++++++ .../org/mudlet/android/ui/ScreenReaderTest.kt | 3 + .../android/ui/settings/ColourDialog.kt | 351 ++++++++++++++++++ .../android/ui/settings/ColourPicking.kt | 86 +++++ .../android/ui/settings/SettingsCatalogue.kt | 2 +- .../android/ui/settings/SettingsPageScreen.kt | 76 +--- app/src/main/res/values/strings.xml | 56 ++- .../android/ui/settings/ColourPickingTest.kt | 74 ++++ docs/architecture.md | 14 +- 10 files changed, 1006 insertions(+), 74 deletions(-) create mode 100644 app/src/androidTest/kotlin/org/mudlet/android/ui/ColourPickerPseudoLocaleTest.kt create mode 100644 app/src/androidTest/kotlin/org/mudlet/android/ui/ColourPickerTest.kt create mode 100644 app/src/main/kotlin/org/mudlet/android/ui/settings/ColourDialog.kt create mode 100644 app/src/main/kotlin/org/mudlet/android/ui/settings/ColourPicking.kt create mode 100644 app/src/test/kotlin/org/mudlet/android/ui/settings/ColourPickingTest.kt diff --git a/app/src/androidTest/kotlin/org/mudlet/android/ui/ColourPickerPseudoLocaleTest.kt b/app/src/androidTest/kotlin/org/mudlet/android/ui/ColourPickerPseudoLocaleTest.kt new file mode 100644 index 00000000..6a63bc05 --- /dev/null +++ b/app/src/androidTest/kotlin/org/mudlet/android/ui/ColourPickerPseudoLocaleTest.kt @@ -0,0 +1,156 @@ +package org.mudlet.android.ui + +import android.Manifest +import android.os.Build +import android.view.View +import androidx.annotation.StringRes +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.semantics.SemanticsNode +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.semantics.getOrNull +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assert +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.click +import androidx.compose.ui.test.hasAnyAncestor +import androidx.compose.ui.test.hasAnyDescendant +import androidx.compose.ui.test.hasClickAction +import androidx.compose.ui.test.hasContentDescription +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.isDialog +import androidx.compose.ui.test.isRoot +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onRoot +import androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.test.performSemanticsAction +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.tryPerformAccessibilityChecks +import androidx.compose.ui.text.TextLayoutResult +import androidx.test.filters.SdkSuppress +import androidx.test.rule.GrantPermissionRule +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.RuleChain +import org.junit.runner.RunWith +import org.junit.runners.Parameterized +import org.mudlet.android.R + +/** + * The colour dialog in the debug build's pseudo-locales, as PseudoLocaleTest checks the screens: no text is cut off, + * overflows its box or leaves the screen, folded or with its sliders out; and its hue bar starts at the right in a + * right-to-left layout. + */ +@RunWith(Parameterized::class) +@SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU) +class ColourPickerPseudoLocaleTest(private val locale: String) { + private val fake = FakeEngineRule() + private val compose = createAndroidComposeRule() + + @get:Rule + val rules: RuleChain = RuleChain.outerRule(MainThreadTimeout(TIMEOUT_MS)).around(fake) + .around(GrantPermissionRule.grant(Manifest.permission.POST_NOTIFICATIONS)) + .around(AppLocaleRule(locale)) + .around(compose) + + private val dialog get() = hasText(string(R.string.settings_colour_ok)) + private val hue get() = hasContentDescription(string(R.string.settings_colour_hue)) and SemanticsMatcher.keyIsDefined(SemanticsActions.SetProgress) + + @Before + fun openTheBackgroundsDialog() { + compose.enableAccessibilityChecksOfWhatShows() + val session = fake.engine.nextSession() + session.clear() + session.synced(0) + session.profiles(emptyList(), session.receive("listProfiles")) + waitFor(hasText(string(R.string.profiles_empty))) + activate(hasContentDescription(string(R.string.settings_title))) + waitFor(hasText(string(R.string.settings_new_games))) + compose.scrollSettingsHubTo(hasText(string(R.string.settings_colours))) + activate(hasText(string(R.string.settings_colours))) + // A background's preview draws the text on it + val background = hasText(string(R.string.settings_colour_background)) and hasClickAction() + waitFor(background) + compose.onNode(background).performScrollTo() + activate(background) + waitFor(dialog) + } + + @Test + fun theDialogFitsItsTextFoldedAndWithItsSliders() { + assertTextFits("the colour dialog") + val fineTune = hasText(string(R.string.settings_colour_fine_tune)) and hasClickAction() and hasAnyAncestor(isDialog()) + compose.onNode(fineTune).performScrollTo().performSemanticsAction(SemanticsActions.OnClick) + val blue = hasContentDescription(string(R.string.settings_colour_blue_amount)) and SemanticsMatcher.keyIsDefined(SemanticsActions.SetProgress) + waitFor(blue) + compose.onNode(blue).performScrollTo() + assertTextFits("the colour dialog with its red, green and blue sliders") + } + + @Test + fun theHueBarStartsWhereTheLayoutDoes() { + val rtl = compose.activity.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL + assertTrue("$locale lays out ${if (rtl) "right to left" else "left to right"}", rtl == (locale == "ar-XB")) + // A quarter of the way along from where the bar starts: a quarter of the way round, yellowish green + compose.onNode(hue).performScrollTo().performTouchInput { click(Offset(if (rtl) width * 0.75f else width * 0.25f, centerY)) } + val degrees = compose.activity.resources.getQuantityString(R.plurals.settings_colour_hue_value, 90, 90) + compose.onNode(hue).assert(SemanticsMatcher.expectValue(SemanticsProperties.StateDescription, degrees)) + } + + private fun string(@StringRes id: Int) = compose.activity.getString(id) + + private fun waitFor(matcher: SemanticsMatcher) = compose.waitUntil(WAIT_MS) { compose.onAllNodes(matcher, useUnmergedTree = true).fetchSemanticsNodes().isNotEmpty() } + + private fun activate(label: SemanticsMatcher) { + compose.onRoot().tryPerformAccessibilityChecks() + compose.onNode(label and hasClickAction()).assertIsDisplayed().performSemanticsAction(SemanticsActions.OnClick) + } + + // PseudoLocaleTest's check, copied rather than shared so the files change apart; always on the dialog's window + private fun assertTextFits(where: String) { + val rootMatcher = isRoot() and hasAnyDescendant(dialog) + compose.onNode(rootMatcher).tryPerformAccessibilityChecks() + val root = compose.onNode(rootMatcher, useUnmergedTree = true).fetchSemanticsNode() + val width = root.size.width + val problems = ArrayList() + var checked = 0 + fun visit(node: SemanticsNode) { + val text = node.config.getOrNull(SemanticsProperties.Text)?.joinToString(" ") { it.text } + ?: node.config.getOrNull(SemanticsProperties.EditableText)?.text + val layouts = ArrayList() + if (!text.isNullOrEmpty()) node.config.getOrNull(SemanticsActions.GetTextLayoutResult)?.action?.invoke(layouts) + checked += layouts.size + for (layout in layouts) { + if ((0 until layout.lineCount).any { layout.isLineEllipsized(it) }) problems += "\"$text\" is cut short" + if (layout.multiParagraph.didExceedMaxLines) problems += "\"$text\" has more lines than it may show" + if (layout.multiParagraph.height > layout.size.height + SLACK_PX) { + problems += "\"$text\" is ${layout.multiParagraph.height} px tall in its ${layout.size} box" + } + } + val bounds = node.boundsInRoot + if (layouts.isNotEmpty() && (bounds.left < -SLACK_PX || bounds.right > width + SLACK_PX)) { + problems += "\"$text\" at $bounds is outside the screen's width $width" + } + node.children.forEach(::visit) + } + visit(root) + // A window with no text laid out would pass without being checked + assertTrue("$locale, $where: no text in the window gave its layout", checked > 0) + assertTrue("$locale, $where: ${problems.joinToString("; ")}", problems.isEmpty()) + } + + companion object { + // Rounding of the bounds to pixels + private const val SLACK_PX = 1f + + // Below the per-test timeout native/tests/android_instrumented.py gives the runner, so this one reports first + private const val TIMEOUT_MS = 240_000L + private const val WAIT_MS = 10_000L + + @JvmStatic + @Parameterized.Parameters(name = "{0}") + fun locales() = listOf("en-XA", "ar-XB") + } +} diff --git a/app/src/androidTest/kotlin/org/mudlet/android/ui/ColourPickerTest.kt b/app/src/androidTest/kotlin/org/mudlet/android/ui/ColourPickerTest.kt new file mode 100644 index 00000000..20a35d50 --- /dev/null +++ b/app/src/androidTest/kotlin/org/mudlet/android/ui/ColourPickerTest.kt @@ -0,0 +1,262 @@ +package org.mudlet.android.ui + +import android.Manifest +import android.os.Build +import androidx.annotation.StringRes +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assert +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertIsNotSelected +import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.click +import androidx.compose.ui.test.hasAnyAncestor +import androidx.compose.ui.test.hasAnyDescendant +import androidx.compose.ui.test.hasClickAction +import androidx.compose.ui.test.hasContentDescription +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.isDialog +import androidx.compose.ui.test.isRoot +import androidx.compose.ui.test.isSelectable +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onRoot +import androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.test.performSemanticsAction +import androidx.compose.ui.test.performTextClearance +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.swipe +import androidx.compose.ui.test.topRight +import androidx.compose.ui.test.tryPerformAccessibilityChecks +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.rule.GrantPermissionRule +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.RuleChain +import org.junit.runner.RunWith +import org.mudlet.android.R +import org.mudlet.android.data.Settings +import kotlin.math.abs + +/** + * The dialog that changes a colour, on the Colours page for new games: colours to tap, a square and a hue bar to touch, + * the hex field, and what TalkBack reaches each by, which all pick the same colours; OK alone changes the setting. + */ +@RunWith(AndroidJUnit4::class) +class ColourPickerTest { + private val fake = FakeEngineRule() + private val compose = createAndroidComposeRule() + + @get:Rule + val rules: RuleChain = RuleChain.outerRule(MainThreadTimeout(TIMEOUT_MS)).around(fake) + .around(if (Build.VERSION.SDK_INT >= 33) GrantPermissionRule.grant(Manifest.permission.POST_NOTIFICATIONS) else RuleChain.emptyRuleChain()) + .around(compose) + + private val red = Settings.ansiColours[1] + private val redRow get() = hasText(string(R.string.settings_colour_red)) and hasClickAction() + private val inDialog = hasAnyAncestor(isDialog()) + private val hex get() = hasSetTextAction() and inDialog + private val hue get() = hasContentDescription(string(R.string.settings_colour_hue)) and SemanticsMatcher.keyIsDefined(SemanticsActions.SetProgress) + private val square get() = hasContentDescription(string(R.string.settings_colour_saturation_brightness)) and inDialog + private val fineTune get() = hasText(string(R.string.settings_colour_fine_tune)) and hasClickAction() and inDialog + private val redAmount get() = hasContentDescription(string(R.string.settings_colour_red_amount)) and SemanticsMatcher.keyIsDefined(SemanticsActions.SetProgress) + private val ok get() = hasText(string(R.string.settings_colour_ok)) and hasClickAction() + + @Before + fun openTheColoursPage() { + compose.runOnIdle { Settings.colours.forEach { it.reset() } } + compose.enableAccessibilityChecksOfWhatShows() + val session = fake.engine.nextSession() + session.clear() + session.synced(0) + session.profiles(emptyList(), session.receive("listProfiles")) + waitFor(hasText(string(R.string.profiles_empty))) + activate(hasContentDescription(string(R.string.settings_title))) + waitFor(hasText(string(R.string.settings_new_games))) + compose.scrollSettingsHubTo(hasText(string(R.string.settings_colours)) and hasClickAction()) + activate(hasText(string(R.string.settings_colours))) + waitFor(redRow) + compose.onNode(redRow).performScrollTo() + } + + @After + fun putTheColoursBack() { + InstrumentationRegistry.getInstrumentation().runOnMainSync { Settings.colours.forEach { it.reset() } } + } + + @Test + fun theColourIsMarkedAmongTheQuickPicksAndATapOnAnotherPicksIt() { + openRed() + compose.onNode(isRoot() and hasAnyDescendant(ok)).tryPerformAccessibilityChecks() + // Red's Mudlet colour is the palette's red, so that one swatch says both + val mudlets = swatch(string(R.string.settings_colour_mudlets_named, string(R.string.settings_colour_red))) + compose.onNode(mudlets).assertIsSelected() + val lightRed = swatch(string(R.string.settings_colour_light_red)) + compose.onNode(lightRed).assertIsNotSelected() + + compose.onNode(lightRed).performScrollTo().performSemanticsAction(SemanticsActions.OnClick) + compose.onNode(lightRed).assertIsSelected() + compose.onNode(mudlets).assertIsNotSelected() + compose.onNode(hex).assert(hasText("#ff0000")) + assertEquals("one colour marked", 1, compose.onAllNodes(isSelectable() and inDialog).fetchSemanticsNodes().count { it.config.getOrElse(SemanticsProperties.Selected) { false } }) + pressOk() + compose.runOnIdle { assertEquals(0xFF0000, red.value) } + compose.onNode(redRow).assert(hasText("#ff0000")) + } + + @Test + fun aMudletColourOutsideThePaletteIsOfferedFirst() { + val commandLine = hasText(string(R.string.settings_colour_command_foreground)) and hasClickAction() + compose.onNode(commandLine).performScrollTo() + activate(commandLine) + waitFor(ok) + val mudlets = swatch(string(R.string.settings_colour_mudlets)) + compose.onNode(mudlets).assertIsSelected() + val first = compose.onAllNodes(isSelectable() and inDialog).fetchSemanticsNodes().first() + assertEquals(string(R.string.settings_colour_mudlets), first.config[SemanticsProperties.ContentDescription].single()) + compose.onNode(swatch(string(R.string.settings_colour_yellow))).performScrollTo().performSemanticsAction(SemanticsActions.OnClick) + compose.onNode(mudlets).assertIsNotSelected() + compose.onNode(hex).assert(hasText("#808000")) + } + + @Test + fun theHueBarAndTheSquareChangeTheColourByTouch() { + openRed() + // Mudlet's red, #800000, half way round the hue bar: the same brightness of cyan + compose.onNode(hue).performScrollTo().performTouchInput { click(center) } + val (r, g, b) = channels(shownHex()) + assertTrue(shownHex(), r == 0 && abs(g - 0x80) <= 2 && abs(b - 0x80) <= 2) + + // Dragged from the middle of the square to its top corner at the end, the thumb follows, not the dialog's + // scrolling: full saturation and brightness + compose.onNode(square).performScrollTo().performTouchInput { swipe(center, topRight, durationMillis = 300) } + compose.onNode(square).assert(reads(string(R.string.settings_colour_saturation_brightness_value, 100, 100))) + val shown = shownHex() + val (r2, g2, b2) = channels(shown) + assertTrue(shown, r2 <= 3 && g2 >= 0xFC && b2 >= 0xFC) + pressOk() + compose.runOnIdle { assertEquals(shown, Settings.colourName(red.value)) } + } + + @Test + fun theHexFieldTakesOnlyAWholeColour_andTheOtherControlsFollowIt() { + openRed() + compose.onNode(hex).performTextClearance() + compose.onNode(hex).performTextInput("#12AB3") + compose.onNode(ok).assertIsNotEnabled() + compose.onNode(hex).performTextInput("4") + compose.onNode(ok).assertIsEnabled() + compose.onNode(hue).assert(reads(degrees(133))) + compose.onNode(square).assert(reads(string(R.string.settings_colour_saturation_brightness_value, 89, 67))) + pressOk() + compose.runOnIdle { assertEquals(0x12AB34, red.value) } + } + + @Test + fun talkBacksControlsReachTheSameColours() { + openRed() + compose.onNode(hue).performSemanticsAction(SemanticsActions.SetProgress) { it(240f) } + compose.onNode(hue).assert(reads(degrees(240))) + compose.onNode(hex).assert(hasText("#000080")) + + squareAction(R.string.settings_colour_brighter) + compose.onNode(square).assert(reads(string(R.string.settings_colour_saturation_brightness_value, 100, 55))) + compose.onNode(hex).assert(hasText("#00008c")) + squareAction(R.string.settings_colour_less_saturated) + compose.onNode(hex).assert(hasText("#07078c")) + + compose.onNode(fineTune).assert(reads(string(R.string.profile_section_collapsed))) + compose.onNode(fineTune).performScrollTo().performSemanticsAction(SemanticsActions.OnClick) + compose.onNode(fineTune).assert(reads(string(R.string.profile_section_expanded))) + compose.onNode(isRoot() and hasAnyDescendant(ok)).tryPerformAccessibilityChecks() + compose.onNode(redAmount).assert(reads("7")) + compose.onNode(redAmount).performSemanticsAction(SemanticsActions.SetProgress) { it(255f) } + compose.onNode(hex).assert(hasText("#ff078c")) + pressOk() + compose.runOnIdle { assertEquals(0xFF078C, red.value) } + } + + @Test + fun theDialogKeepsItsColourThroughARotation() { + openRed() + compose.onNode(swatch(string(R.string.settings_colour_light_green))).performScrollTo().performSemanticsAction(SemanticsActions.OnClick) + compose.onNode(fineTune).performScrollTo().performSemanticsAction(SemanticsActions.OnClick) + compose.activityRule.scenario.recreate() + // The new Activity attaches to the engine again + val again = fake.engine.nextSession() + again.profiles(emptyList(), again.receive("listProfiles")) + waitFor(ok) + compose.onNode(hex).assert(hasText("#00ff00")) + compose.onNode(redAmount).assert(reads("0")) + compose.onNode(hue).assert(reads(degrees(120))) + pressOk() + compose.runOnIdle { assertEquals(0x00FF00, red.value) } + } + + @Test + fun cancelLeavesTheColourAsItWas() { + openRed() + compose.onNode(swatch(string(R.string.settings_colour_blue))).performScrollTo().performSemanticsAction(SemanticsActions.OnClick) + compose.onNode(hue).performSemanticsAction(SemanticsActions.SetProgress) { it(60f) } + compose.onNode(hasText(string(R.string.settings_choice_cancel)) and hasClickAction()).performSemanticsAction(SemanticsActions.OnClick) + waitForNoDialog() + compose.runOnIdle { assertEquals(0x800000, red.value) } + compose.onNode(redRow).assert(hasText("#800000")) + } + + private fun openRed() { + activate(redRow) + waitFor(ok) + } + + private fun pressOk() { + compose.onNode(ok).performSemanticsAction(SemanticsActions.OnClick) + waitForNoDialog() + } + + private fun reads(state: String) = SemanticsMatcher.expectValue(SemanticsProperties.StateDescription, state) + + private fun swatch(name: String) = hasContentDescription(name) and isSelectable() and inDialog + + private fun squareAction(@StringRes label: Int) { + val action = compose.onNode(square).fetchSemanticsNode().config[SemanticsActions.CustomActions].single { it.label == string(label) } + compose.runOnIdle { action.action() } + } + + private fun shownHex() = compose.onNode(hex).fetchSemanticsNode().config[SemanticsProperties.EditableText].text + + private fun channels(hex: String): Triple { + val rgb = Settings.parseColourName(hex) ?: error("not a colour: $hex") + return Triple(rgb shr 16 and 0xFF, rgb shr 8 and 0xFF, rgb and 0xFF) + } + + private fun degrees(n: Int) = compose.activity.resources.getQuantityString(R.plurals.settings_colour_hue_value, n, n) + + private fun string(@StringRes id: Int, vararg args: Any) = compose.activity.getString(id, *args) + + private fun waitFor(matcher: SemanticsMatcher) = compose.waitUntil(WAIT_MS) { compose.onAllNodes(matcher).fetchSemanticsNodes().isNotEmpty() } + + private fun waitForNoDialog() = compose.waitUntil(WAIT_MS) { compose.onAllNodes(isDialog()).fetchSemanticsNodes().isEmpty() } + + /** What a double tap does under TalkBack: the node's accessibility click. */ + private fun activate(label: SemanticsMatcher) { + waitFor(label and hasClickAction()) + compose.onRoot().tryPerformAccessibilityChecks() + compose.onNode(label and hasClickAction()).assertIsDisplayed().performSemanticsAction(SemanticsActions.OnClick) + compose.waitForIdle() + } + + private companion object { + const val WAIT_MS = 10_000L + const val TIMEOUT_MS = 240_000L + } +} diff --git a/app/src/androidTest/kotlin/org/mudlet/android/ui/ScreenReaderTest.kt b/app/src/androidTest/kotlin/org/mudlet/android/ui/ScreenReaderTest.kt index c5780582..cd21d165 100644 --- a/app/src/androidTest/kotlin/org/mudlet/android/ui/ScreenReaderTest.kt +++ b/app/src/androidTest/kotlin/org/mudlet/android/ui/ScreenReaderTest.kt @@ -496,6 +496,8 @@ class ScreenReaderTest { activate(red) compose.onNode(isRoot() and hasAnyDescendant(hasText(string(R.string.settings_colour_ok)))).tryPerformAccessibilityChecks() + val fineTune = hasText(string(R.string.settings_colour_fine_tune)) and hasClickAction() + compose.onNode(fineTune).performScrollTo().performSemanticsAction(SemanticsActions.OnClick) val redAmount = hasContentDescription(string(R.string.settings_colour_red_amount)) and SemanticsMatcher.keyIsDefined(SemanticsActions.SetProgress) compose.onNode(redAmount).assert(SemanticsMatcher.expectValue(SemanticsProperties.StateDescription, "170")) val hex = hasSetTextAction() and hasAnyAncestor(isDialog()) @@ -513,6 +515,7 @@ class ScreenReaderTest { // A slide changes the colour; Cancel leaves the game's as it was activate(red) + compose.onNode(fineTune).performScrollTo().performSemanticsAction(SemanticsActions.OnClick) compose.onNode(redAmount).performSemanticsAction(SemanticsActions.SetProgress) { it(255f) } compose.onNode(hex).assert(hasText("#ffab34")) compose.onNode(hasText(string(R.string.settings_choice_cancel)) and hasClickAction()).performSemanticsAction(SemanticsActions.OnClick) diff --git a/app/src/main/kotlin/org/mudlet/android/ui/settings/ColourDialog.kt b/app/src/main/kotlin/org/mudlet/android/ui/settings/ColourDialog.kt new file mode 100644 index 00000000..82021548 --- /dev/null +++ b/app/src/main/kotlin/org/mudlet/android/ui/settings/ColourDialog.kt @@ -0,0 +1,351 @@ +package org.mudlet.android.ui.settings + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.listSaver +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.input.pointer.PointerInputScope +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.CustomAccessibilityAction +import androidx.compose.ui.semantics.ProgressBarRangeInfo +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.progressBarRangeInfo +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.setProgress +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import org.mudlet.android.R +import org.mudlet.android.data.Settings +import kotlin.math.roundToInt + +/** What a colour is seen with in the dialog's preview: [other], the background it is drawn on or, for a background, the text drawn on it. */ +internal class ColourPreview(val other: Int, val isBackground: Boolean) + +// Each colour's name: Mudlet's sixteen ANSI colours, then two greys between its black, grey, silver and white +private val PALETTE: Map by lazy { + val greys = listOf(0x404040 to R.string.settings_colour_dark_grey, 0xD3D3D3 to R.string.settings_colour_light_grey) + (Settings.ansiColours.map { it.mudletDefault }.zip(ANSI_COLOUR_LABELS) + greys).toMap() +} + +private val HSB_SAVER = listSaver({ listOf(it.hue, it.saturation, it.brightness) }, { Hsb(it[0], it[1], it[2]) }) + +private val HUES = (0..6).map { rgbColour(Hsb(it * 60f, 1f, 1f).toRgb()) } + +private val CHANNELS = listOf(R.string.settings_colour_red_amount to 16, R.string.settings_colour_green_amount to 8, R.string.settings_colour_blue_amount to 0) + +/** + * Colours to tap, with [mudlets] among them; a saturation and brightness square and a hue bar to pick any other by + * touch; the colour as "#rrggbb" to type; and, folded, a slider each for red, green and blue. [onPick] takes it as OK + * is pressed. [preview] shows it beside what it is seen with. + */ +@Composable +internal fun ColourDialog(title: String, initial: Int, mudlets: Int, preview: ColourPreview, onDismiss: () -> Unit, onPick: (Int) -> Unit) { + var rgb by rememberSaveable { mutableIntStateOf(initial) } + // Kept apart from rgb, which loses a grey's hue and black's saturation + var hsb by rememberSaveable(stateSaver = HSB_SAVER) { mutableStateOf(Hsb.of(initial)) } + // What is typed, kept apart from rgb while it is not yet a whole colour + var typed by rememberSaveable { mutableStateOf(Settings.colourName(initial)) } + var fineTuning by rememberSaveable { mutableStateOf(false) } + fun take(colour: Int) { + rgb = colour + hsb = Hsb.of(colour, hsb) + typed = Settings.colourName(colour) + } + fun takeHsb(colour: Hsb) { + hsb = colour + rgb = colour.toRgb() + typed = Settings.colourName(rgb) + } + AlertDialog( + onDismissRequest = onDismiss, + // OK takes only a whole colour, never the last one picked while the typed name is not one + confirmButton = { + TextButton({ onPick(rgb) }, enabled = Settings.parseColourName(typed) != null) { Text(stringResource(R.string.settings_colour_ok)) } + }, + dismissButton = { TextButton(onDismiss) { Text(stringResource(R.string.settings_choice_cancel)) } }, + title = { Text(title) }, + text = { + Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Preview(rgb, preview) + Heading(stringResource(R.string.settings_colour_quick_picks)) + QuickPicks(rgb, mudlets, ::take) + Heading(stringResource(R.string.settings_colour_custom)) + SaturationBrightness(hsb, ::takeHsb) + HueBar(hsb) { takeHsb(hsb.copy(hue = it)) } + OutlinedTextField( + typed, + { text -> + typed = text + Settings.parseColourName(text)?.let { + rgb = it + hsb = Hsb.of(it, hsb) + } + }, + Modifier.fillMaxWidth(), + label = { Text(stringResource(R.string.settings_colour_name)) }, + isError = Settings.parseColourName(typed) == null, + supportingText = { Text(stringResource(R.string.settings_colour_name_hint)) }, + singleLine = true, + keyboardOptions = KeyboardOptions(autoCorrectEnabled = false, imeAction = ImeAction.Done), + ) + FineTune(fineTuning, { fineTuning = !fineTuning }) { + CHANNELS.forEach { (name, shift) -> + val amount = (rgb shr shift) and 0xFF + val label = stringResource(name) + Text(stringResource(R.string.settings_colour_amount, label, amount), style = MaterialTheme.typography.bodyMedium) + Slider( + value = amount.toFloat(), + onValueChange = { take((rgb and (0xFF shl shift).inv()) or (it.roundToInt() shl shift)) }, + modifier = Modifier.semantics { + contentDescription = label + stateDescription = amount.toString() + }, + valueRange = 0f..255f, + ) + } + } + } + }, + ) +} + +@Composable +internal fun Swatch(rgb: Int, size: Dp = 32.dp, border: Dp = 1.dp) { + Box( + Modifier.size(size).clip(MaterialTheme.shapes.small).background(rgbColour(rgb)) + .border(border, MaterialTheme.colorScheme.outline, MaterialTheme.shapes.small), + ) +} + +// Hidden from TalkBack, which reads the colour from the hex field, and from the contrast check, as a colour that can +// barely be seen against the other is what the preview is there to show +@Composable +private fun Preview(rgb: Int, preview: ColourPreview) { + Row(Modifier.clearAndSetSemantics {}, verticalAlignment = Alignment.CenterVertically) { + Swatch(rgb, 48.dp) + val (text, background) = if (preview.isBackground) preview.other to rgb else rgb to preview.other + Text( + stringResource(R.string.settings_text_size_sample), + Modifier.padding(start = 8.dp).weight(1f).background(rgbColour(background)).padding(8.dp), + color = rgbColour(text), + fontFamily = FontFamily.Monospace, + style = MaterialTheme.typography.bodyMedium, + ) + } +} + +@Composable +private fun Heading(text: String) { + Text(text, Modifier.padding(top = 8.dp).semantics { heading() }, style = MaterialTheme.typography.titleSmall) +} + +/** A radio button for each colour, read by its name; the one that is [rgb] is marked. */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun QuickPicks(rgb: Int, mudlets: Int, onPick: (Int) -> Unit) { + FlowRow(Modifier.fillMaxWidth().selectableGroup(), horizontalArrangement = Arrangement.spacedBy(4.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + for (pick in quickPicks(PALETTE.keys.toList(), mudlets)) { + val selected = pick == rgb + val name = PALETTE[pick]?.let { stringResource(it) } + val description = when { + pick != mudlets -> name.orEmpty() + name != null -> stringResource(R.string.settings_colour_mudlets_named, name) + else -> stringResource(R.string.settings_colour_mudlets) + } + Box( + Modifier.size(48.dp).selectable(selected, role = Role.RadioButton) { onPick(pick) }.semantics { contentDescription = description }, + contentAlignment = Alignment.Center, + ) { + Swatch(pick, 40.dp, if (selected) 3.dp else 1.dp) + if (selected) Icon(painterResource(R.drawable.ic_check), contentDescription = null, tint = if (darkMarkReads(pick)) Color.Black else Color.White) + } + } + } +} + +/** + * Saturation across, brightness down, for the hue [hsb] has. TalkBack, which cannot follow a finger over a square, + * reads both values and has actions to step each. + */ +@Composable +private fun SaturationBrightness(hsb: Hsb, onChange: (Hsb) -> Unit) { + val rtl = LocalLayoutDirection.current == LayoutDirection.Rtl + val current by rememberUpdatedState(hsb) + val change by rememberUpdatedState(onChange) + val label = stringResource(R.string.settings_colour_saturation_brightness) + val state = stringResource(R.string.settings_colour_saturation_brightness_value, (hsb.saturation * 100).roundToInt(), (hsb.brightness * 100).roundToInt()) + val actions = listOf( + R.string.settings_colour_more_saturated to { h: Hsb -> h.stepSaturation(1) }, + R.string.settings_colour_less_saturated to { h: Hsb -> h.stepSaturation(-1) }, + R.string.settings_colour_brighter to { h: Hsb -> h.stepBrightness(1) }, + R.string.settings_colour_darker to { h: Hsb -> h.stepBrightness(-1) }, + ).map { (name, step) -> + CustomAccessibilityAction(stringResource(name)) { + change(step(current)) + true + } + } + val pure = rgbColour(Hsb(hsb.hue, 1f, 1f).toRgb()) + Canvas( + Modifier.fillMaxWidth().height(160.dp).clip(MaterialTheme.shapes.small) + .pointerInput(rtl) { + followTouch { at -> + change(current.copy(saturation = fraction(at.x, size.width, rtl), brightness = 1 - fraction(at.y, size.height, false))) + } + } + .semantics { + contentDescription = label + stateDescription = state + customActions = actions + }, + ) { + drawRect(Brush.horizontalGradient(if (rtl) listOf(pure, Color.White) else listOf(Color.White, pure))) + drawRect(Brush.verticalGradient(listOf(Color.Transparent, Color.Black))) + val across = if (rtl) 1 - hsb.saturation else hsb.saturation + thumb(Offset(across * size.width, (1 - hsb.brightness) * size.height)) + } +} + +/** A bar of every hue, which TalkBack reads and changes as a slider. */ +@Composable +private fun HueBar(hsb: Hsb, onHue: (Float) -> Unit) { + val rtl = LocalLayoutDirection.current == LayoutDirection.Rtl + val change by rememberUpdatedState(onHue) + val label = stringResource(R.string.settings_colour_hue) + val degrees = hsb.hue.roundToInt() + val state = pluralStringResource(R.plurals.settings_colour_hue_value, degrees, degrees) + Canvas( + Modifier.fillMaxWidth().height(48.dp) + .pointerInput(rtl) { followTouch { at -> change(fraction(at.x, size.width, rtl) * 360f) } } + .semantics { + contentDescription = label + stateDescription = state + progressBarRangeInfo = ProgressBarRangeInfo(hsb.hue, 0f..360f) + setProgress { target -> + change(target.coerceIn(0f, 360f)) + true + } + }, + ) { + val bar = 24.dp.toPx() + drawRoundRect( + Brush.horizontalGradient(if (rtl) HUES.reversed() else HUES), + Offset(0f, (size.height - bar) / 2), + Size(size.width, bar), + CornerRadius(bar / 2), + ) + val across = if (rtl) 1 - hsb.hue / 360f else hsb.hue / 360f + thumb(Offset(across * size.width, size.height / 2)) + } +} + +/** A heading that folds away [content], read by TalkBack as one heading button with its state, as the profile editor's are. */ +@Composable +private fun FineTune(open: Boolean, onToggle: () -> Unit, content: @Composable () -> Unit) { + val state = stringResource(if (open) R.string.profile_section_expanded else R.string.profile_section_collapsed) + val action = stringResource(if (open) R.string.profile_section_hide else R.string.profile_section_show) + Row( + Modifier.fillMaxWidth().heightIn(min = 48.dp) + .clickable(onClickLabel = action, role = Role.Button, onClick = onToggle) + .semantics { + heading() + stateDescription = state + } + .padding(top = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(stringResource(R.string.settings_colour_fine_tune), style = MaterialTheme.typography.titleSmall) + if (!open) { + Text(stringResource(R.string.settings_colour_fine_tune_summary), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + // A triangle, not a chevron, as it means the same either way round in a right-to-left layout + Icon(painterResource(R.drawable.ic_arrow_drop_down), contentDescription = null, Modifier.size(24.dp).rotate(if (open) 180f else 0f)) + } + if (open) content() +} + +private fun rgbColour(rgb: Int) = Color(0xFF000000 or (rgb.toLong() and 0xFFFFFF)) + +// From 0 at the start of [length] to 1 at its end, the start being the right in a right-to-left layout +private fun fraction(at: Float, length: Int, rtl: Boolean): Float { + val f = (at / length).coerceIn(0f, 1f) + return if (rtl) 1 - f else f +} + +// Takes the touch as it lands, before the dialog's scrolling can, so a drag up or down moves the thumb, not the dialog +private suspend fun PointerInputScope.followTouch(onAt: (Offset) -> Unit) = awaitEachGesture { + val down = awaitFirstDown() + down.consume() + onAt(down.position) + while (true) { + val change = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break + if (!change.pressed) break + change.consume() + onAt(change.position) + } +} + +// White on a dark ring, so it shows on every colour +private fun DrawScope.thumb(at: Offset) { + val radius = 10.dp.toPx() + drawCircle(Color.Black, radius, at, style = Stroke(4.dp.toPx())) + drawCircle(Color.White, radius, at, style = Stroke(2.dp.toPx())) +} diff --git a/app/src/main/kotlin/org/mudlet/android/ui/settings/ColourPicking.kt b/app/src/main/kotlin/org/mudlet/android/ui/settings/ColourPicking.kt new file mode 100644 index 00000000..3120b169 --- /dev/null +++ b/app/src/main/kotlin/org/mudlet/android/ui/settings/ColourPicking.kt @@ -0,0 +1,86 @@ +package org.mudlet.android.ui.settings + +import kotlin.math.abs +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.pow +import kotlin.math.roundToInt + +/** + * A colour as the colour dialog's square and hue bar pick it: [hue] in degrees from 0 to 360, [saturation] and + * [brightness] from 0 to 1. + */ +internal data class Hsb(val hue: Float, val saturation: Float, val brightness: Float) { + /** As 0xRRGGBB, each channel the nearest of 0 to 255. */ + fun toRgb(): Int { + val chroma = brightness * saturation + val sector = hue.mod(360f) / 60f + val x = chroma * (1 - abs(sector % 2 - 1)) + val (r, g, b) = when (sector.toInt()) { + 0 -> Triple(chroma, x, 0f) + 1 -> Triple(x, chroma, 0f) + 2 -> Triple(0f, chroma, x) + 3 -> Triple(0f, x, chroma) + 4 -> Triple(x, 0f, chroma) + else -> Triple(chroma, 0f, x) + } + val m = brightness - chroma + fun channel(c: Float) = ((c + m) * 255).roundToInt().coerceIn(0, 255) + return (channel(r) shl 16) or (channel(g) shl 8) or channel(b) + } + + /** [by] steps of TalkBack's actions on the square, each to the next multiple of a step. */ + fun stepSaturation(by: Int) = copy(saturation = stepped(saturation, by)) + + fun stepBrightness(by: Int) = copy(brightness = stepped(brightness, by)) + + companion object { + /** How many steps TalkBack's actions on the square take from none to full: 5% each. */ + const val STEPS = 20 + + // A value a quarter of a step or less from a multiple counts as on it, so a step never moves too little to hear + private fun stepped(fraction: Float, by: Int): Float { + val steps = fraction * STEPS + val from = if (by > 0) floor(steps + 0.25f) else ceil(steps - 0.25f) + return (from.toInt() + by).coerceIn(0, STEPS) / STEPS.toFloat() + } + + /** + * [rgb]'s. A grey has no hue, and black no saturation either, so those stay [previous]'s, and the square's and + * hue bar's thumbs stay where the player left them. + */ + fun of(rgb: Int, previous: Hsb? = null): Hsb { + val r = (rgb shr 16 and 0xFF) / 255f + val g = (rgb shr 8 and 0xFF) / 255f + val b = (rgb and 0xFF) / 255f + val max = maxOf(r, g, b) + val delta = max - minOf(r, g, b) + val hue = when { + delta == 0f -> previous?.hue ?: 0f + max == r -> 60 * ((g - b) / delta).mod(6f) + max == g -> 60 * ((b - r) / delta + 2) + else -> 60 * ((r - g) / delta + 4) + } + val saturation = if (max == 0f) previous?.saturation ?: 0f else delta / max + return Hsb(hue, saturation, max) + } + } +} + +/** The colours the dialog offers to tap: [palette], after [mudlets] where it is none of them. */ +internal fun quickPicks(palette: List, mudlets: Int): List = if (mudlets in palette) palette else listOf(mudlets) + palette + +/** Whether a mark drawn on [rgb] reads better black than white: whichever has the higher contrast, as WCAG reckons it. */ +internal fun darkMarkReads(rgb: Int): Boolean { + val luminance = luminance(rgb) + return (luminance + 0.05) / 0.05 >= 1.05 / (luminance + 0.05) +} + +// WCAG 2's relative luminance +private fun luminance(rgb: Int): Double { + fun linear(channel: Int): Double { + val c = channel / 255.0 + return if (c <= 0.04045) c / 12.92 else ((c + 0.055) / 1.055).pow(2.4) + } + return 0.2126 * linear(rgb shr 16 and 0xFF) + 0.7152 * linear(rgb shr 8 and 0xFF) + 0.0722 * linear(rgb and 0xFF) +} diff --git a/app/src/main/kotlin/org/mudlet/android/ui/settings/SettingsCatalogue.kt b/app/src/main/kotlin/org/mudlet/android/ui/settings/SettingsCatalogue.kt index 73c763d8..f010b79c 100644 --- a/app/src/main/kotlin/org/mudlet/android/ui/settings/SettingsCatalogue.kt +++ b/app/src/main/kotlin/org/mudlet/android/ui/settings/SettingsCatalogue.kt @@ -219,7 +219,7 @@ sealed class SettingEntry( const val CLEAR_MEDIA_KEY = "clearStoredMedia" // The names of the sixteen ANSI colours, in the order of [Settings.ansiColours] -private val ANSI_COLOUR_LABELS = listOf( +internal val ANSI_COLOUR_LABELS = listOf( R.string.settings_colour_black, R.string.settings_colour_red, R.string.settings_colour_green, diff --git a/app/src/main/kotlin/org/mudlet/android/ui/settings/SettingsPageScreen.kt b/app/src/main/kotlin/org/mudlet/android/ui/settings/SettingsPageScreen.kt index f7890e11..881b2037 100644 --- a/app/src/main/kotlin/org/mudlet/android/ui/settings/SettingsPageScreen.kt +++ b/app/src/main/kotlin/org/mudlet/android/ui/settings/SettingsPageScreen.kt @@ -1,7 +1,6 @@ package org.mudlet.android.ui.settings import androidx.compose.foundation.background -import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -39,7 +38,6 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState @@ -47,9 +45,7 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.onFocusChanged -import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.pluralStringResource @@ -61,7 +57,6 @@ import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.delay @@ -299,72 +294,23 @@ private fun ColourRow(entry: SettingEntry.Colour, owner: SettingsOwner) { Swatch(rgb) } if (changing) { - ColourDialog(stringResource(entry.label), rgb, onDismiss = { changing = false }) { + val (other, isBackground) = seenWith(entry.setting) + ColourDialog(stringResource(entry.label), rgb, entry.setting.mudletDefault, ColourPreview(owner.value(other), isBackground), onDismiss = { changing = false }) { changing = false owner.change(entry.setting, it) } } } -@Composable -private fun Swatch(rgb: Int, size: Dp = 32.dp) { - Box( - Modifier.size(size).clip(MaterialTheme.shapes.small).background(Color(0xFF000000 or rgb.toLong())) - .border(1.dp, MaterialTheme.colorScheme.outline, MaterialTheme.shapes.small), - ) -} - -/** A slider for each of red, green and blue, and the colour as "#rrggbb" to type, which [onPick] takes as OK is pressed. */ -@Composable -private fun ColourDialog(title: String, initial: Int, onDismiss: () -> Unit, onPick: (Int) -> Unit) { - var rgb by rememberSaveable { mutableIntStateOf(initial) } - // What is typed, kept apart from rgb while it is not yet a whole colour - var typed by rememberSaveable { mutableStateOf(Settings.colourName(initial)) } - val channels = listOf(R.string.settings_colour_red_amount to 16, R.string.settings_colour_green_amount to 8, R.string.settings_colour_blue_amount to 0) - AlertDialog( - onDismissRequest = onDismiss, - // OK takes only a whole colour, never the last one the sliders left while the typed name is not one - confirmButton = { - TextButton({ onPick(rgb) }, enabled = Settings.parseColourName(typed) != null) { Text(stringResource(R.string.settings_colour_ok)) } - }, - dismissButton = { TextButton(onDismiss) { Text(stringResource(R.string.settings_choice_cancel)) } }, - title = { Text(title) }, - text = { - Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) { - Swatch(rgb, 48.dp) - channels.forEach { (name, shift) -> - val amount = (rgb shr shift) and 0xFF - val label = stringResource(name) - Text(stringResource(R.string.settings_colour_amount, label, amount), style = MaterialTheme.typography.bodyMedium) - Slider( - value = amount.toFloat(), - onValueChange = { - rgb = (rgb and (0xFF shl shift).inv()) or (it.roundToInt() shl shift) - typed = Settings.colourName(rgb) - }, - modifier = Modifier.semantics { - contentDescription = label - stateDescription = amount.toString() - }, - valueRange = 0f..255f, - ) - } - OutlinedTextField( - typed, - { text -> - typed = text - Settings.parseColourName(text)?.let { rgb = it } - }, - Modifier.fillMaxWidth(), - label = { Text(stringResource(R.string.settings_colour_name)) }, - isError = Settings.parseColourName(typed) == null, - supportingText = { Text(stringResource(R.string.settings_colour_name_hint)) }, - singleLine = true, - keyboardOptions = KeyboardOptions(autoCorrectEnabled = false, imeAction = ImeAction.Done), - ) - } - }, - ) +/** The colour [setting]'s is seen with, and whether that is text drawn on it ([setting] being a background) or the background it is drawn on. */ +private fun seenWith(setting: Settings.ColourSetting): Pair = when (setting) { + Settings.backgroundColour -> Settings.foregroundColour to true + Settings.commandBackgroundColour -> Settings.commandForegroundColour to true + Settings.commandForegroundColour -> Settings.commandBackgroundColour to false + Settings.mapBackgroundColour -> Settings.mapLinkColour to true + Settings.playerRoomOuterColour, Settings.playerRoomInnerColour -> Settings.mapBackgroundColour to false + in Settings.mapColours -> Settings.mapBackgroundColour to false + else -> Settings.backgroundColour to false } /** A choice's label, or the choice itself for one the app has no label for, such as a name a newer Mudlet added. */ diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index a2605dc1..666f66f1 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -124,13 +124,16 @@ Secure connection (TLS) + profile), or of "Fine-tune" in the dialog that changes a colour, while what it holds shows --> Expanded - + Collapsed - + show this section - + hide this section Log in automatically @@ -615,6 +618,48 @@ Hex colour As #rrggbb, such as #ff8000 + + Quick picks + + Dark grey + + Light grey + + Mudlet\'s default + + %1$s, Mudlet\'s default + + Any colour + + Saturation and brightness + + Saturation %1$d%%, brightness %2$d%% + + More saturated + + Less saturated + + Brighter + + Darker + + Hue + + + %1$d° + %1$d° + + + Fine-tune + + Red, green and blue, each from 0 to 255 OK @@ -793,7 +838,8 @@ Smaller text Larger text - + You see a brass lantern here. Read new text aloud diff --git a/app/src/test/kotlin/org/mudlet/android/ui/settings/ColourPickingTest.kt b/app/src/test/kotlin/org/mudlet/android/ui/settings/ColourPickingTest.kt new file mode 100644 index 00000000..f0f3f0cd --- /dev/null +++ b/app/src/test/kotlin/org/mudlet/android/ui/settings/ColourPickingTest.kt @@ -0,0 +1,74 @@ +package org.mudlet.android.ui.settings + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** The colour dialog's sums: hue, saturation and brightness to and from 0xRRGGBB, and its colours to tap. */ +class ColourPickingTest { + @Test + fun theSixHuesAndTheGreysAreExact() { + val primaries = mapOf(0f to 0xFF0000, 60f to 0xFFFF00, 120f to 0x00FF00, 180f to 0x00FFFF, 240f to 0x0000FF, 300f to 0xFF00FF, 360f to 0xFF0000) + for ((hue, rgb) in primaries) assertEquals("hue $hue", hex(rgb), hex(Hsb(hue, 1f, 1f).toRgb())) + assertEquals(hex(0x000000), hex(Hsb(200f, 0.7f, 0f).toRgb())) + assertEquals(hex(0xFFFFFF), hex(Hsb(200f, 0f, 1f).toRgb())) + assertEquals("Mudlet's red", hex(0x800000), hex(Hsb(0f, 1f, 128 / 255f).toRgb())) + } + + @Test + fun everyColourComesBackFromItsHueSaturationAndBrightness() { + for (r in 0..255 step 15) { + for (g in 0..255 step 17) { + for (b in 0..255 step 5) { + val rgb = (r shl 16) or (g shl 8) or b + assertEquals(hex(rgb), hex(Hsb.of(rgb).toRgb())) + } + } + } + } + + @Test + fun aColoursHueSaturationAndBrightnessAreTheUsualOnes() { + val green = Hsb.of(0x12AB34) + assertEquals(133.3f, green.hue, 0.1f) + assertEquals(0.895f, green.saturation, 0.001f) + assertEquals(0.671f, green.brightness, 0.001f) + assertEquals(330f, Hsb.of(0xFF0080).hue, 0.5f) + } + + @Test + fun aGreyKeepsTheHueItHadAndBlackItsSaturationToo() { + val before = Hsb(200f, 0.6f, 0.8f) + assertEquals(Hsb(200f, 0f, 128 / 255f), Hsb.of(0x808080, before)) + assertEquals(Hsb(200f, 0.6f, 0f), Hsb.of(0x000000, before)) + assertEquals("with nothing before, a grey's hue is red's", Hsb(0f, 0f, 1f), Hsb.of(0xFFFFFF)) + } + + @Test + fun talkBacksStepsGoFivePercentToTheNextMultipleAndStopAtTheEnds() { + val colour = Hsb(10f, 0.53f, 128 / 255f) + assertEquals(0.55f, colour.stepSaturation(1).saturation, 0.0001f) + assertEquals(0.5f, colour.stepSaturation(-1).saturation, 0.0001f) + assertEquals(0.55f, colour.stepBrightness(1).brightness, 0.0001f) + assertEquals(0.45f, colour.stepBrightness(-1).brightness, 0.0001f) + assertEquals(1f, Hsb(10f, 0.99f, 0f).stepSaturation(1).saturation, 0f) + assertEquals(0f, Hsb(10f, 0.5f, 0.01f).stepBrightness(-1).brightness, 0f) + assertEquals("the hue stays", 10f, colour.stepBrightness(1).hue, 0f) + } + + @Test + fun mudletsColourIsOfferedFirstUnlessItIsOneOfThePalettes() { + val palette = listOf(0x000000, 0x800000, 0xFFFFFF) + assertEquals(palette, quickPicks(palette, 0x800000)) + assertEquals(listOf(0x717100) + palette, quickPicks(palette, 0x717100)) + } + + @Test + fun theSelectedMarkIsBlackOnLightColoursAndWhiteOnDarkOnes() { + for (light in listOf(0xFFFFFF, 0xFFFF00, 0x00FF00, 0x00FFFF, 0xC0C0C0, 0xD3D3D3)) assertTrue(hex(light), darkMarkReads(light)) + for (dark in listOf(0x000000, 0x800000, 0x000080, 0x0000FF, 0x404040, 0x800080)) assertFalse(hex(dark), darkMarkReads(dark)) + } + + private fun hex(rgb: Int) = "#%06x".format(rgb) +} diff --git a/docs/architecture.md b/docs/architecture.md index 667f5a66..2386bbd7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -271,8 +271,14 @@ page whose changes apply at once. `SettingsCatalogue.kt` lists every setting wit - A further game category, Colours (desktop Mudlet's Color view), holds the profile's palette, which is Mudlet's: the engine paints each run in the exact colour it resolved as it decoded the text, so a colour changed (`ColourSetting`, sent as `#rrggbb` by the keys of Mudlet's `color_table`, such as `ansiRed`) reaches text the game sends after it, and - the background reaches the console through `consoleColors`. A colour's dialog has a slider each for red, green and - blue and the colour as hex to type, and changes the game's as OK is pressed. "Reset to Mudlet's colours" sends all + the background reaches the console through `consoleColors`. A colour's dialog (`ColourDialog`) has Mudlet's + sixteen ANSI colours, two greys and the setting's own Mudlet colour to tap, a saturation and brightness square and + a hue bar (`Hsb`, in `ColourPicking.kt`), the colour as hex to type and, folded under "Fine-tune", a slider each + for red, green and blue, as desktop Mudlet's colour dialog has basic colours, a hue and saturation field and RGB. + Its preview shows the colour with the one it is seen with (text on a background, a background under text, a map + colour on the map's background), and it changes the game's as OK is pressed. TalkBack reads each colour to tap by + name, steps the square 5% at a time by actions and moves the hue bar as a slider. Neither Android nor Material 3 + for Compose has a colour picker to use instead. "Reset to Mudlet's colours" sends all twenty of Mudlet's in one request (`SettingsOwner.resetToMudlets`), as desktop Mudlet's reset button puts them back. Desktop Mudlet's input line colours are not among them, as the app's input line follows the app's theme. - A further game category, Map (desktop Mudlet's Mapper and Mapper colors tabs), holds how the engine draws the @@ -2261,7 +2267,9 @@ alias of run-lua-code, one of desktop Mudlet's default packages, which a profile - On the game's Colours page change Red to `#ff8000` by its hex field and press OK, then send `lua feedTriggers("\27[31morange\n")`: the new line is orange, and red lines from before keep their red. Change Background: the console's background follows at once. With TalkBack on, each slider reads its colour's - name and amount. "Reset to Mudlet's colours" puts Red back to `#800000`. + name and amount, each colour to tap its name, "Hue" its degrees, and the square its saturation and brightness, + with actions to change each. In the dialog, drag across the square and along the hue bar: the preview and the + hex field follow, and the dialog stays put. "Reset to Mudlet's colours" puts Red back to `#800000`. - Disconnect, then send a command: "Not sent: ..." shows over the foot of the console, above the keyboard, and TalkBack reads it without moving focus. 17. About and licences, with TalkBack on. From 9243b9feb108ed772af9d77dbf726e55a1b998b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 21:23:23 +0000 Subject: [PATCH 2/2] App: wait for the colour dialog's rows in the merged tree in its pseudo-locale test The Background row's click action is on the row, not its text, so in the unmerged tree no node has both and the wait timed out on API 33 and later. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016ujaeFyaqXXDx8xjoThE6J --- .../org/mudlet/android/ui/ColourPickerPseudoLocaleTest.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/androidTest/kotlin/org/mudlet/android/ui/ColourPickerPseudoLocaleTest.kt b/app/src/androidTest/kotlin/org/mudlet/android/ui/ColourPickerPseudoLocaleTest.kt index 6a63bc05..1df10af7 100644 --- a/app/src/androidTest/kotlin/org/mudlet/android/ui/ColourPickerPseudoLocaleTest.kt +++ b/app/src/androidTest/kotlin/org/mudlet/android/ui/ColourPickerPseudoLocaleTest.kt @@ -101,7 +101,8 @@ class ColourPickerPseudoLocaleTest(private val locale: String) { private fun string(@StringRes id: Int) = compose.activity.getString(id) - private fun waitFor(matcher: SemanticsMatcher) = compose.waitUntil(WAIT_MS) { compose.onAllNodes(matcher, useUnmergedTree = true).fetchSemanticsNodes().isNotEmpty() } + // The merged tree, where a row's click action and its text are on one node + private fun waitFor(matcher: SemanticsMatcher) = compose.waitUntil(WAIT_MS) { compose.onAllNodes(matcher).fetchSemanticsNodes().isNotEmpty() } private fun activate(label: SemanticsMatcher) { compose.onRoot().tryPerformAccessibilityChecks()