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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
#!/usr/bin/env python3
"""STRUCTURE lane — FlorisBoard.

Owns exactly two things:
  1. The GATE: the app launches to its top-level settings surface and the
     vertical section list is present (jump_kind="none", depth=0).
  2. Tree-SHAPE deltas: an interaction changes the view tree's shape
     (node-count / surface-key delta), asserted before->after and, where it
     makes sense, reversed to prove it restores (jump_kind="transition").

SHAPE ONLY. No content-string assertions, no checked/selected state, no
named-screen reachability — those belong to other lanes. A dead pixel-perfect
shell must still FAIL, so every shape delta is tied to a real interaction
(open keyboard preview, open a dialog, navigate, scroll), never a bare
"view exists / has N children" existence check.

The Compose tree is FLAT with empty resource-ids, so everything is matched by
class + visible text/content-desc. Switches are `android.view.View`
(checkable="true"), NOT `android.widget.Switch`, and there are NO ViewGroup
nodes — the container classes here are View / ScrollView / FrameLayout.
"""
import os
import sys

os.environ.setdefault("ADB_PATH", "/opt/android/platform-tools/adb")
# DEVICE_SERIAL is supplied by the harness env; the kit already defaults it, so
# no serial literal is written here (keeps the suite portable / lint-clean).
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from android_testgen_kit import *  # noqa: F403,E402


# ── Local matchers (kit has no ampersand/startswith helper; recon.md snippet) ──
def find_node_startswith(nodes, prefix):
    """First node whose visible text starts with `prefix` (ampersand-free, so
    'Languages' matches 'Languages & Layouts' which dumps as 'Languages &')."""
    p = prefix.lower()
    for n in nodes:
        if n.get("text", "").lower().startswith(p):
            return n
    return None


SECTIONS = ["Languages", "Theme", "Keyboard", "Smartbar", "Typing",
            "Gestures", "Clipboard", "Emojis", "Addons", "Other", "About"]


def section_rows(nodes):
    """The section labels currently present in the tree (the settings list)."""
    return [s for s in SECTIONS if find_node_startswith(nodes, s)]


def home_container(nodes):
    """The top-level scroll container that hosts the settings list. Compose
    renders it as a ScrollView; there are no ViewGroup nodes in this app."""
    return find_by_class(nodes, "ScrollView")


# ── Depth-backing navigation helpers (named and_enter_* / and_reach_* so the
# depth auditor accepts any depth>=1 they produce). Each taps the section row on
# HOME and confirms the surface changed, then increments the surface counter. ──
def and_enter_section(section):
    """Navigate HOME -> a named settings sub-screen. Returns (ok, before_keys).
    Counts one surface via the kit's and_enter helper."""
    nodes = ui()
    row = find_node_startswith(nodes, section)
    if not row:
        return False, set()
    before = and_showing(nodes)
    if not tap_node(row):
        return False, before
    settle("tap")
    after = and_showing()
    if not surface_changed(before, after):
        return False, before
    and_enter(section)  # kit: increment the surface counter (backs depth>=1)
    return True, before


def and_enter_keyboard_preview():
    """Open FlorisBoard's own keyboard preview from the bottom 'Try out your
    setup' bar. The keyboard animates in as a separate IME window; two launch
    settles cover the animation. Counts one surface. Returns (ok, home_keys)."""
    nodes = ui()
    trigger = find_node_ci(nodes, "Try out your setup")
    if not trigger:
        return False, set()
    before = and_showing(nodes)
    if not tap_node(trigger):
        return False, before
    settle("launch")
    settle("launch")
    and_enter("keyboard_preview")
    return True, before


# ═══════════════════════════════════════════════════════════════════════════
# GATE — the one legitimate existence-style test (jump_kind="none", depth=0).
# ═══════════════════════════════════════════════════════════════════════════
@and_test(expects=("structure_gate_launch", "structure_gate_home_list_vlm"))
def test_gate_launch():
    """App launches to the settings launcher surface, the top-level scroll
    container is present, and it hosts the full vertical section list."""
    restart_app()
    fg = wait_for_foreground()
    nodes = ui()
    container = home_container(nodes)
    rows = section_rows(nodes)
    # A faithful launcher shows its scroll container AND (nearly) all sections;
    # a blank shell shows neither. Require the container + a clear majority.
    ok = bool(fg and container and len(rows) >= 8)
    record("structure_gate_launch", ok,
           "" if ok else f"setup_failed: foreground={fg} container={bool(container)} "
                         f"sections={len(rows)}/{len(SECTIONS)}",
           depth=0, jump_kind="none",
           expect="settings launcher foreground; ScrollView + >=8 section rows")
    vlm_assert("structure_gate_home_list",
               "Is there a vertically stacked list of at least six settings rows, "
               "each with a small icon on the left and a text label to its right, "
               "filling most of the screen?",
               RESULTS_DIR, tag="layout")


# ═══════════════════════════════════════════════════════════════════════════
# SHAPE — keyboard preview opens (tree shrinks, keyboard window appears).
# depth=0: the preview is the SAME activity (an IME window over it), so this is
# an in-place shape delta, not a surface jump.
# ═══════════════════════════════════════════════════════════════════════════
@and_test(expects=("structure_keyboard_open_shrinks",
                   "structure_keyboard_visible_vlm",
                   "structure_keyboard_grid_vlm",
                   "structure_smartbar_above_vlm"))
def test_keyboard_open_changes_shape():
    """Tapping 'Try out your setup' brings up the IME keyboard, which covers the
    lower screen: the dump loses the rows it now hides, so the visible node count
    and the count of visible section rows both DROP while the keyboard shows."""
    restart_app()
    wait_for_foreground()
    home_nodes = ui()
    home_cnt = len(home_nodes)
    home_secs = len(section_rows(home_nodes))
    trigger = find_node_ci(home_nodes, "Try out your setup")
    if not trigger:
        record("structure_keyboard_open_shrinks", False,
               "setup_failed: 'Try out your setup' bar not found",
               depth=0, jump_kind="transition",
               expect="keyboard covers lower rows; node count & visible sections drop")
    else:
        tap_node(trigger)
        settle("launch")
        settle("launch")
        kb_nodes = ui()
        kb_cnt = len(kb_nodes)
        kb_secs = len(section_rows(kb_nodes))
        shrank = kb_cnt < home_cnt and kb_secs < home_secs and keyboard_visible()
        record("structure_keyboard_open_shrinks", bool(shrank),
               "" if shrank else f"behavior_wrong: no shrink "
                                 f"(nodes {home_cnt}->{kb_cnt}, secs {home_secs}->{kb_secs}, "
                                 f"kbd_visible={keyboard_visible()})",
               depth=0, jump_kind="transition",
               expect=f"keyboard covers lower rows: nodes {home_cnt}->{kb_cnt}, "
                      f"sections {home_secs}->{kb_secs}, keyboard window visible")
    # VLM shape facts about the keyboard region (keys are canvas-drawn, so the
    # dump can't see them — this is the legitimate VLM case).
    vlm_assert("structure_keyboard_visible",
               "Is an on-screen keyboard occupying the bottom portion of the "
               "screen, below a text input field?",
               RESULTS_DIR, tag="layout", depth=0, jump_kind="transition")
    vlm_assert("structure_keyboard_grid",
               "Does the on-screen keyboard show a grid of letter keys arranged "
               "in three or more horizontal rows, each row holding roughly ten "
               "similarly-sized rectangular keys?",
               RESULTS_DIR, tag="shape", depth=0, jump_kind="transition")
    vlm_assert("structure_smartbar_above",
               "Is there a horizontal toolbar strip (with small action icons such "
               "as a settings gear and a microphone) positioned directly ABOVE the "
               "rows of keyboard keys?",
               RESULTS_DIR, tag="position", depth=0, jump_kind="transition")


# ═══════════════════════════════════════════════════════════════════════════
# SHAPE — reversibility of the keyboard preview: closing it (BACK) restores the
# fuller home tree. Same-activity, so depth=0.
# ═══════════════════════════════════════════════════════════════════════════
@and_test(expects=("structure_keyboard_close_restores",))
def test_keyboard_close_restores_shape():
    """Open the preview keyboard (shrunk tree), dismiss it, and assert the tree
    grows back: the visible section rows return to the full home count."""
    restart_app()
    wait_for_foreground()
    home_nodes = ui()
    home_secs = len(section_rows(home_nodes))
    trigger = find_node_ci(home_nodes, "Try out your setup")
    if not trigger:
        record("structure_keyboard_close_restores", False,
               "setup_failed: 'Try out your setup' bar not found",
               depth=0, jump_kind="transition",
               expect="close keyboard -> visible section rows restore to home count")
        return
    tap_node(trigger)
    settle("launch")
    settle("launch")
    open_secs = len(section_rows(ui()))
    # Dismiss the IME window without leaving the app.
    hide_keyboard()
    settle("tap")
    restored_nodes = ui()
    restored_secs = len(section_rows(restored_nodes))
    ok = open_secs < home_secs and restored_secs >= home_secs
    record("structure_keyboard_close_restores", bool(ok),
           "" if ok else f"behavior_wrong: not restored "
                         f"(home={home_secs} open={open_secs} restored={restored_secs})",
           depth=0, jump_kind="transition",
           expect=f"visible sections {home_secs}->{open_secs} (keyboard) ->"
                  f"{home_secs} (restored on close)")


# ═══════════════════════════════════════════════════════════════════════════
# SHAPE — a ListPreference dialog adds a new window layer on top of a sub-screen.
# depth=1, backed by and_enter_section("Keyboard").
# ═══════════════════════════════════════════════════════════════════════════
@and_test(expects=("structure_dialog_opens", "structure_dialog_card_vlm"))
def test_listpreference_dialog_changes_shape():
    """Inside Keyboard, tapping 'Utility key action' opens a ListPreference
    dialog. The dialog is a new layer: its option/button nodes (Cancel/OK/
    Default + radio options) appear in the tree, so the surface changes
    materially vs the plain sub-screen."""
    restart_app()
    wait_for_foreground()
    entered, _ = and_enter_section("Keyboard")  # depth -> 1
    if not entered:
        record("structure_dialog_opens", False,
               "setup_failed: could not enter the Keyboard sub-screen",
               depth=1, jump_kind="transition",
               expect="ListPreference dialog layer adds Cancel/OK/Default + options")
        vlm_assert("structure_dialog_card",
                   "Is there a rounded rectangular dialog card centered over a "
                   "dimmed background, showing a vertical list of options with "
                   "radio buttons and text buttons at the bottom?",
                   RESULTS_DIR, tag="layout")
        return
    screen_nodes = ui()
    trigger = find_node_ci(screen_nodes, "Utility key action")
    if not trigger:
        record("structure_dialog_opens", False,
               "feature_missing: 'Utility key action' ListPreference not found",
               depth=1, jump_kind="transition",
               expect="ListPreference dialog layer adds Cancel/OK/Default + options")
    else:
        before = and_showing(screen_nodes)
        tap_node(trigger)
        settle("tap")
        settle("tap")
        dlg_nodes = ui()
        after = and_showing(dlg_nodes)
        # Shape-only: the dialog layer's controls appeared (count of new keys),
        # not any specific string's content.
        added = after - before
        has_buttons = bool(find_node_ci(dlg_nodes, "Cancel")
                           and find_node_ci(dlg_nodes, "OK"))
        grew = surface_changed(before, after, min_delta=4) and has_buttons
        record("structure_dialog_opens", bool(grew),
               "" if grew else f"behavior_wrong: dialog layer did not add nodes "
                               f"(new keys={len(added)}, buttons={has_buttons})",
               depth=1, jump_kind="transition",
               expect=f"dialog layer adds Cancel/OK/Default + radio options "
                      f"(observed {len(added)} new surface keys)")
    vlm_assert("structure_dialog_card",
               "Is there a rounded rectangular dialog card, clearly narrower than "
               "the screen and centered over a dimmed background, showing a "
               "vertical list of radio-button options?",
               RESULTS_DIR, tag="shape", depth=1, jump_kind="transition")


# ═══════════════════════════════════════════════════════════════════════════
# SHAPE — dismissing the dialog (Cancel) restores the prior sub-screen shape.
# depth=1, backed by and_enter_section("Keyboard").
# ═══════════════════════════════════════════════════════════════════════════
@and_test(expects=("structure_dialog_cancel_restores",))
def test_dialog_cancel_restores_shape():
    """Open the Utility-key-action dialog, then Cancel: the dialog layer's nodes
    disappear and the tree returns to the exact sub-screen shape it had before
    (verified char-for-char on the surface key set in recon)."""
    restart_app()
    wait_for_foreground()
    entered, _ = and_enter_section("Keyboard")  # depth -> 1
    if not entered:
        record("structure_dialog_cancel_restores", False,
               "setup_failed: could not enter the Keyboard sub-screen",
               depth=1, jump_kind="transition",
               expect="Cancel removes the dialog layer; sub-screen shape restores")
        return
    screen_before = and_showing()
    trigger = find_node_ci(ui(), "Utility key action")
    if not trigger:
        record("structure_dialog_cancel_restores", False,
               "feature_missing: 'Utility key action' ListPreference not found",
               depth=1, jump_kind="transition",
               expect="Cancel removes the dialog layer; sub-screen shape restores")
        return
    tap_node(trigger)
    settle("tap")
    settle("tap")
    dlg = and_showing()
    cancel = find_node_ci(ui(), "Cancel")
    if not cancel or not tap_node(cancel):
        record("structure_dialog_cancel_restores", False,
               "setup_failed: Cancel button not tappable",
               depth=1, jump_kind="transition",
               expect="Cancel removes the dialog layer; sub-screen shape restores")
        return
    settle("tap")
    settle("tap")
    screen_after = and_showing()
    # The dialog must have been a real layer (it changed the surface), and
    # Cancel must return to the pre-dialog shape.
    was_layer = surface_changed(screen_before, dlg, min_delta=4)
    restored = not surface_changed(screen_before, screen_after, min_delta=3)
    ok = was_layer and restored
    record("structure_dialog_cancel_restores", bool(ok),
           "" if ok else f"behavior_wrong: layer={was_layer} restored={restored} "
                         f"(diff after cancel={len(screen_before ^ screen_after)})",
           depth=1, jump_kind="transition",
           expect="dialog layer added >=4 keys; Cancel restores the sub-screen "
                  "surface (symmetric-diff < 3)")


# ═══════════════════════════════════════════════════════════════════════════
# SHAPE — navigating into three different sub-screens each materially changes
# the tree shape vs home. depth=1, backed by and_enter_section(<name>).
# (SHAPE only — we assert the surface CHANGED, not that a named screen is
# reachable; reachability is navigation's lane.)
# ═══════════════════════════════════════════════════════════════════════════
def _nav_shape_case(record_name, section, min_delta=6):
    restart_app()
    wait_for_foreground()
    home = and_showing(ui())
    row = find_node_startswith(ui(), section)
    if not row:
        record(record_name, False,
               f"feature_missing: '{section}' row not present on home",
               depth=1, jump_kind="transition",
               expect=f"tree shape changes materially entering {section}")
        return
    ok_enter, _ = and_enter_section(section)  # depth -> 1
    if not ok_enter:
        record(record_name, False,
               f"behavior_wrong: surface did not change entering {section}",
               depth=1, jump_kind="transition",
               expect=f"tree shape changes materially entering {section}")
        return
    after = and_showing()
    diff = len(home ^ after)
    ok = surface_changed(home, after, min_delta=min_delta)
    record(record_name, bool(ok),
           "" if ok else f"behavior_wrong: shape barely changed "
                         f"(symmetric-diff={diff}, need >={min_delta})",
           depth=1, jump_kind="transition",
           expect=f"home->{section}: surface symmetric-diff {diff} (>= {min_delta})")


@and_test(expects=("structure_nav_keyboard_shape",))
def test_nav_keyboard_shape():
    _nav_shape_case("structure_nav_keyboard_shape", "Keyboard")


@and_test(expects=("structure_nav_typing_shape",))
def test_nav_typing_shape():
    _nav_shape_case("structure_nav_typing_shape", "Typing")


@and_test(expects=("structure_nav_about_shape",))
def test_nav_about_shape():
    _nav_shape_case("structure_nav_about_shape", "About")


# ═══════════════════════════════════════════════════════════════════════════
# SHAPE — a sub-screen that hosts switches: entering it introduces a CLASS of
# widget (checkable View nodes) that home does not have. depth=1.
# This proves a mode/screen change adds a class of widget — pure shape.
# ═══════════════════════════════════════════════════════════════════════════
@and_test(expects=("structure_switches_appear",))
def test_switch_class_appears_on_subscreen():
    """Home has no checkable (switch) nodes; the Typing screen is built from a
    stack of SwitchPreferences, so entering it adds several checkable View nodes.
    We count the CLASS of widget (shape), never its checked state."""
    restart_app()
    wait_for_foreground()
    home_switches = len(find_nodes(ui(), checkable=True))
    ok_enter, _ = and_enter_section("Typing")  # depth -> 1
    if not ok_enter:
        record("structure_switches_appear", False,
               "setup_failed: could not enter the Typing sub-screen",
               depth=1, jump_kind="transition",
               expect="checkable switch nodes go from ~0 on home to several on Typing")
        return
    sub_switches = len(find_nodes(ui(), checkable=True))
    ok = sub_switches >= home_switches + 2
    record("structure_switches_appear", bool(ok),
           "" if ok else f"behavior_wrong: switch-class count did not grow "
                         f"(home={home_switches}, Typing={sub_switches})",
           depth=1, jump_kind="transition",
           expect=f"checkable switch nodes {home_switches}(home)->{sub_switches}(Typing), "
                  f"delta >= 2")


# ═══════════════════════════════════════════════════════════════════════════
# SHAPE — scrolling a long settings screen swaps which nodes are present.
# depth=1, backed by and_enter_section("Keyboard").
# ═══════════════════════════════════════════════════════════════════════════
@and_test(expects=("structure_scroll_changes_nodes",))
def test_scroll_changes_visible_nodes():
    """The Keyboard screen is taller than the viewport, so scrolling it swaps the
    set of visible nodes (rows scroll off the top, new rows scroll in at the
    bottom) — a shape delta, asserted via the surface key set."""
    restart_app()
    wait_for_foreground()
    ok_enter, _ = and_enter_section("Keyboard")  # depth -> 1
    if not ok_enter:
        record("structure_scroll_changes_nodes", False,
               "setup_failed: could not enter the Keyboard sub-screen",
               depth=1, jump_kind="transition",
               expect="scrolling swaps the visible node set (surface changes)")
        return
    before = and_showing()
    scroll_down(0.6)
    after = and_showing()
    diff = len(before ^ after)
    ok = surface_changed(before, after, min_delta=4)
    record("structure_scroll_changes_nodes", bool(ok),
           "" if ok else f"behavior_wrong: scroll did not change the visible nodes "
                         f"(symmetric-diff={diff})",
           depth=1, jump_kind="transition",
           expect=f"scroll swaps visible rows: surface symmetric-diff {diff} (>= 4)")


TESTS = [
    test_gate_launch,
    test_keyboard_open_changes_shape,
    test_keyboard_close_restores_shape,
    test_listpreference_dialog_changes_shape,
    test_dialog_cancel_restores_shape,
    test_nav_keyboard_shape,
    test_nav_typing_shape,
    test_nav_about_shape,
    test_switch_class_appears_on_subscreen,
    test_scroll_changes_visible_nodes,
]

if __name__ == "__main__":
    run_suite(TESTS, "structure")