File size: 37,054 Bytes
598838a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
"""Structure lane — top-level surface gate + widget-tree SHAPE deltas for Logbert.



Owns: (a) the startup gate (main window + menu bar + Welcome surface), kept small;

(b) tree-SHAPE deltas — an interaction that adds/removes nodes (document load adds a

document tab + docked panes, a menu dropdown adds/removes MenuItems, a dialog adds a

Window node, the Logger Tree toggle removes a Pane, the Messages<->Script mode switch

swaps the button set, the Statistic tab materialises a Pane); (c) layout geometry.



Deliberately NOT asserted here (other lanes own them): status-bar strings, computed

message counts, CHECKED state, dialog identity from a menu, push-button consequences.

"""
import time

import pytest

import rb_uia
import logbert_ui as L
from rb_uia import rb_showing, rb_reach, rb_flip, rb_value


@pytest.fixture(autouse=True)
def _rb_park_cursor():
    """Keep the physical pointer off the app window for the whole test.



    Once a log file is in Logbert's MRU the Welcome page renders it as a link; a

    pointer resting on that link pops a ToolTip, which is a top-level window owned

    by the same process. The harness picks "the first titled window of this PID",

    so it can latch onto the ToolTip instead of the main window and every locator

    then returns empty. Runs before the ``app`` fixture launches the app.

    """
    L.park_cursor()
    yield
    L.park_cursor()


GRID_COLUMNS = ["Number", "Level", "Timestamp", "Logger", "Thread", "Message"]
LEVEL_BUTTONS = ["Trace", "Debug", "Info", "Warning", "Error", "Fatal"]
CORE_PANES = {"Messages", "Logger Tree", "Message Details"}


def _header_positions(app):
    """{column name -> left x} for the Messages grid column headers.



    Tolerant on purpose: a grid may surface its column headers as ``Header`` or as

    ``HeaderItem``, so both are collected and only the six known column names are

    kept — chrome from other grids or panes can never bleed in.

    """
    root = L.pane(app, "Messages") or app
    wanted = set(GRID_COLUMNS)
    found = {}
    for h in L.alld(root, "Header") + L.alld(root, "HeaderItem"):
        try:
            name = (h.window_text() or "").strip()
        except Exception:
            continue
        if name not in wanted:
            continue
        r = L.rect(h)
        if r is None:
            continue
        if name not in found or r[0] < found[name]:
            found[name] = r[0]
    return found


def _header_order(app):
    """Column header names ordered left -> right by their x position."""
    pos = _header_positions(app)
    return [n for n, _x in sorted(pos.items(), key=lambda kv: kv[1])]


def _texts(elements):
    out = []
    for e in elements:
        try:
            t = e.window_text() or ""
        except Exception:
            continue
        if t:
            out.append(t)
    return out


# ── GATE (jump_kind="none") ──────────────────────────────────────────────────

@pytest.mark.rb(

    jump_kind="none",

    expect="main window titled Logbert carrying a File/Edit/Extras/Help menu bar and a Welcome tab",

    depth=0,

)
def test_gate_main_window_and_menu_bar(app, rb, results_dir):
    notes = []
    title = ""
    try:
        title = app.window_text() or ""
    except Exception as e:
        notes.append(f"[read window title] {type(e).__name__}: {e}")

    menus = set()
    try:
        menus = L.menu_item_names(app)
    except Exception as e:
        notes.append(f"[read menu bar] {type(e).__name__}: {e}")

    tabs = set()
    try:
        tabs = set(_texts(L.alld(app, "TabItem")))
    except Exception as e:
        notes.append(f"[read tab strip] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "structure_gate_startup",
            "Logbert just after launch: a light-grey WinForms window whose title bar "
            "reads 'Logbert' with a small 3-D box icon at its left and minimise / "
            "maximise / close buttons at its right. Directly under the title bar is a "
            "menu bar with four items reading 'File  Edit  Extras  Help'. Below that a "
            "document tab strip holds a single tab labelled 'Welcome', and the client "
            "area shows the welcome page: a 'New Logger' column listing log receiver "
            "entries (Log4Net UDP / File / Dir Receiver, NLog receivers, Syslog "
            "receivers, ...), a 'Recent Files' section and an 'Online Recources' "
            "section of blue hyperlinks. There is no message grid and no 'Log Level:' "
            "toolbar of coloured round buttons yet.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    assert title.strip() != "" and "logbert" in title.lower(), (
        f"main window title observed={title!r}, expected a non-empty title naming "
        f"Logbert; steps={notes}")
    assert {"File", "Edit", "Extras", "Help"} <= menus, (
        f"menu bar observed={sorted(menus)}, expected to contain File/Edit/Extras/Help; "
        f"steps={notes}")
    assert "Welcome" in tabs, (
        f"tab strip observed={sorted(tabs)}, expected a 'Welcome' tab at startup; "
        f"steps={notes}")


@pytest.mark.rb(

    jump_kind="none",

    expect="Welcome startup surface carries a List of log-receiver ListItems",

    depth=0,

)
def test_gate_welcome_receiver_list_surface(app, rb):
    notes = []
    lst = None
    try:
        lst = L.named(app, "List", "New Logger") or L.one(app, "List")
    except Exception as e:
        notes.append(f"[locate welcome list] {type(e).__name__}: {e}")

    items = []
    try:
        items = _texts(L.alld(lst, "ListItem"))
    except Exception as e:
        notes.append(f"[read list items] {type(e).__name__}: {e}")

    receivers = sorted({i for i in items if i.endswith("Receiver")})

    assert len(items) >= 8, (
        f"welcome list item count observed={len(items)}, expected >= 8 entries; "
        f"items={items[:12]}; steps={notes}")
    assert len(receivers) >= 5, (
        f"distinct '... Receiver' entries observed={receivers}, expected at least 5 "
        f"selectable receiver types on the welcome surface; steps={notes}")


# ── SHAPE DELTAS ─────────────────────────────────────────────────────────────

@pytest.mark.rb(

    jump_kind="reach",

    expect="loading a log document adds a 'Log4Net File Receiver (...)' TabItem plus the "

           "Messages / Logger Tree / Message Details panes",

    depth=1,

)
def test_document_load_adds_surfaces(app, rb, results_dir):
    notes = []
    before = set()
    panes_before = set()
    try:
        before = rb_showing(app)
    except Exception as e:
        notes.append(f"[snapshot before] {type(e).__name__}: {e}")
    try:
        panes_before = L.pane_names(app)
    except Exception as e:
        notes.append(f"[panes before] {type(e).__name__}: {e}")

    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    after = set()
    panes_after = set()
    try:
        after = rb_showing(app)
    except Exception as e:
        notes.append(f"[snapshot after] {type(e).__name__}: {e}")
    try:
        panes_after = L.pane_names(app)
    except Exception as e:
        notes.append(f"[panes after] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "structure_document_load",
            "Logbert after a log file has been opened: the tab strip now holds TWO "
            "document tabs — 'Welcome' and an active tab reading 'Log4Net File Receiver "
            "(sampl...' with a small blue close cross — and the client area has been "
            "rebuilt. A toolbar starting with the label 'Log Level:' runs across the "
            "top, the centre holds a six-column message grid whose headers read Number, "
            "Level, Timestamp, Logger, Thread, Message with six data rows, a 'Logger "
            "Tree' panel is docked at the right showing 'Logger Root' -> 'Root' -> "
            "'Alpha' / 'Beta' / 'Gamma', and a 'Message Details' panel is docked along "
            "the bottom above a blue status bar. None of these existed on the welcome "
            "page captured at startup.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    ok = rb_reach(before, after, target="TabItem|Log4Net File Receiver", source=None)
    assert ok, (
        f"no log-document tab appeared; newly visible keys="
        f"{sorted(after - before)[:15]}; steps={notes}")
    assert len(panes_after) > len(panes_before), (
        f"pane count observed {len(panes_before)} -> {len(panes_after)}, expected the "
        f"tree to gain docked panes; before={sorted(panes_before)}; "
        f"after={sorted(panes_after)}; steps={notes}")
    assert CORE_PANES <= panes_after, (
        f"panes observed={sorted(panes_after)}, expected to contain {sorted(CORE_PANES)} "
        f"after the document loaded; steps={notes}")


@pytest.mark.rb(

    jump_kind="transition",

    expect="message grid row count 0 -> 6 when the log document loads",

    depth=1,

)
def test_document_load_changes_row_count(app, rb):
    notes = []
    before = None
    try:
        before = L.row_count(app)
    except Exception as e:
        notes.append(f"[row count before] {type(e).__name__}: {e}")

    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    after = None
    try:
        after = L.row_count(app)
    except Exception as e:
        notes.append(f"[row count after] {type(e).__name__}: {e}")

    ok = rb_flip(before, after)
    assert ok, (
        f"grid row count did not change: observed {before} -> {after}, expected 0 -> 6 "
        f"rows materialising in the message grid; steps={notes}")
    assert before == 0 and (after or 0) > 0, (
        f"row shape observed {before} -> {after}, expected an empty grid before the "
        f"load and populated rows after it; steps={notes}")


@pytest.mark.rb(

    jump_kind="transition",

    expect="File dropdown adds New Logger.../Open Log File.../Recent Files/Close All/Exit "

           "MenuItems; ESC removes them again",

    depth=0,

)
def test_file_menu_open_close_changes_item_set(app, rb, results_dir):
    notes = []
    before = set()
    try:
        before = L.menu_item_names(app)
    except Exception as e:
        notes.append(f"[menu items before] {type(e).__name__}: {e}")

    try:
        L.open_menu(app, "File")
    except Exception as e:
        notes.append(f"[open File menu] {type(e).__name__}: {e}")

    opened = set()
    try:
        opened = L.menu_item_names(app)
    except Exception as e:
        notes.append(f"[menu items while open] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "structure_menu_file_open",
            "Full-screen desktop capture with the Logbert window in the upper-left "
            "corner and its File menu dropped open. A dropdown panel hangs from the "
            "'File' entry of the menu bar and lists, top to bottom, 'New Logger...', "
            "'Open Log File...', 'Recent Files' (with a submenu arrow at its right), "
            "then 'Close All' and 'Exit'. The dropdown overlays the left column of the "
            "welcome page, whose list of receiver links (Log4Net / NLog / Syslog / "
            "Eventlog / Windows Debug / Custom receivers) continues below it, while the "
            "'Recent Files' and 'Online Recources' headings stay visible on the right. "
            "The Windows desktop wallpaper and taskbar fill the rest of the frame.",
            results_dir)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    try:
        L.press("{ESC}")
        time.sleep(0.4)
        L.press("{ESC}")
        time.sleep(0.4)
    except Exception as e:
        notes.append(f"[close dropdown] {type(e).__name__}: {e}")

    closed = set()
    try:
        closed = L.menu_item_names(app)
    except Exception as e:
        notes.append(f"[menu items after close] {type(e).__name__}: {e}")

    added = opened - before

    ok = rb_flip(len(before), len(opened))
    assert ok, (
        f"opening the File dropdown changed no MenuItem: observed {len(before)} -> "
        f"{len(opened)} items; before={sorted(before)}; while open={sorted(opened)}; "
        f"steps={notes}")
    for prefix in ("New Logger", "Open Log File", "Exit"):
        assert any(a.startswith(prefix) for a in added), (
            f"dropdown items observed={sorted(added)}, expected one starting with "
            f"{prefix!r}; steps={notes}")
    assert not (added & closed), (
        f"dropdown items survived the dismiss: still present={sorted(added & closed)}, "
        f"expected the dropdown nodes to leave the tree on ESC; steps={notes}")


@pytest.mark.rb(

    jump_kind="reach",

    expect="opening New Logger from a loaded document adds a 'New Logger' Window node; "

           "dismissing it removes the node again",

    depth=2,

)
def test_dialog_adds_window_node(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    titles_before = []
    try:
        titles_before = L.dialog_titles(app)
    except Exception as e:
        notes.append(f"[window nodes before] {type(e).__name__}: {e}")

    menu_open = set()
    try:
        L.open_menu(app, "File")
        menu_open = rb_showing(app)
    except Exception as e:
        notes.append(f"[open File menu] {type(e).__name__}: {e}")

    dlg = None
    try:
        L.pick_menu(app, "New Logger")
        rb.enter("new logger dialog")
        dlg = L.dialog(app, "New Logger", 10)
    except Exception as e:
        notes.append(f"[open New Logger] {type(e).__name__}: {e}")

    after = set()
    titles_open = []
    try:
        after = rb_showing(app)
    except Exception as e:
        notes.append(f"[snapshot with dialog] {type(e).__name__}: {e}")
    try:
        titles_open = L.dialog_titles(app)
    except Exception as e:
        notes.append(f"[window nodes with dialog] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "structure_new_logger_dialog",
            "The 'New Logger' dialog, a separate framed window centred over the Logbert "
            "main window. Its left half is a tall list of receiver types (Log4Net UDP / "
            "File / Dir Receiver, NLog TCP / UDP / File / Dir Receiver, Syslog UDP / "
            "File Receiver, Eventlog Receiver, Windows Debug Receiver, Custom UDP / TCP "
            "/ HTTP / File / Dir Receiver); its right half is a group box whose caption "
            "names the highlighted receiver and which holds that receiver's settings "
            "controls (network interface / port / multicast for the UDP default). Two "
            "buttons, OK and Cancel, sit at the bottom-right corner of the dialog.",
            results_dir, window=(dlg if dlg is not None else app))
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    try:
        L.close_dialog(app, "New Logger")
        L.wait_until(lambda: L.named(app, "Window", "New Logger") is None, timeout=6)
    except Exception as e:
        notes.append(f"[dismiss dialog] {type(e).__name__}: {e}")

    titles_closed = []
    try:
        titles_closed = L.dialog_titles(app)
    except Exception as e:
        notes.append(f"[window nodes after close] {type(e).__name__}: {e}")

    ok = rb_reach(menu_open, after, target="Window|New Logger",
                  source="MenuItem|Open Log File")
    assert ok, (
        f"no new Window node appeared for the dialog; newly visible keys="
        f"{sorted(after - menu_open)[:15]}; steps={notes}")
    assert len(titles_open) > len(titles_before), (
        f"Window-node count observed {len(titles_before)} -> {len(titles_open)}, "
        f"expected the tree to gain a window; before={titles_before}; "
        f"open={titles_open}; steps={notes}")
    assert len(titles_closed) == len(titles_before), (
        f"Window-node count after dismissing observed={len(titles_closed)} "
        f"({titles_closed}), expected it back at {len(titles_before)} "
        f"({titles_before}); steps={notes}")


@pytest.mark.rb(

    jump_kind="transition",

    expect="Logger Tree toolbar toggle removes the 'Logger Tree' pane and its 5 tree "

           "nodes from the tree, clicking again restores the pane",

    depth=1,

)
def test_logger_tree_toggle_removes_pane(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    panes_before = set()
    items_before = []
    try:
        panes_before = L.pane_names(app)
        items_before = L.logger_tree_items(app)
    except Exception as e:
        notes.append(f"[shape before] {type(e).__name__}: {e}")

    try:
        b = L.btn(app, "Logger Tree")
        b.click_input()
        time.sleep(0.6)
    except Exception as e:
        notes.append(f"[click Logger Tree toggle] {type(e).__name__}: {e}")

    panes_after = set()
    items_after = []
    try:
        panes_after = L.pane_names(app)
        items_after = L.logger_tree_items(app)
    except Exception as e:
        notes.append(f"[shape after] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "structure_logger_tree_hidden",
            "The Logbert main window with the Logger Tree panel switched off: the "
            "right-hand 'Logger Tree' panel that showed 'Logger Root' -> 'Root' -> "
            "'Alpha' / 'Beta' / 'Gamma' with its own zoom and filter buttons is gone, "
            "and the six-column message grid (Number, Level, Timestamp, Logger, Thread, "
            "Message) now stretches across the full width of the document area. The "
            "'Log Level:' toolbar at the top, the 'Message Details' panel docked along "
            "the bottom and the blue status bar are unchanged.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    panes_restored = set()
    try:
        b2 = L.btn(app, "Logger Tree")
        b2.click_input()
        time.sleep(0.6)
        panes_restored = L.pane_names(app)
    except Exception as e:
        notes.append(f"[restore Logger Tree] {type(e).__name__}: {e}")

    ok = rb_flip(("Logger Tree" in panes_before, len(items_before)),
                 ("Logger Tree" in panes_after, len(items_after)))
    assert ok, (
        f"tree shape unchanged by the Logger Tree toggle: pane present "
        f"{'Logger Tree' in panes_before} -> {'Logger Tree' in panes_after}, tree nodes "
        f"{len(items_before)} -> {len(items_after)}; steps={notes}")
    assert "Logger Tree" in panes_before and "Logger Tree" not in panes_after, (
        f"panes observed before={sorted(panes_before)} after={sorted(panes_after)}, "
        f"expected the 'Logger Tree' pane to leave the tree; steps={notes}")
    assert len(items_before) > 0 and len(items_after) == 0, (
        f"logger tree nodes observed {items_before} -> {items_after}, expected the "
        f"nodes to disappear with the pane; steps={notes}")
    assert "Logger Tree" in panes_restored, (
        f"panes after toggling back observed={sorted(panes_restored)}, expected the "
        f"'Logger Tree' pane to return; steps={notes}")


@pytest.mark.rb(

    jump_kind="reach",

    expect="switching the document from Messages to Script swaps the widget set: grid "

           "headers vanish and Start/Stop/Load script buttons appear",

    depth=1,

)
def test_script_mode_swaps_widget_set(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    before = set()
    buttons_before = set()
    try:
        before = rb_showing(app)
        buttons_before = L.button_names(app)
    except Exception as e:
        notes.append(f"[snapshot messages mode] {type(e).__name__}: {e}")

    try:
        L.tab(app, "Script").click_input()
        time.sleep(0.7)
    except Exception as e:
        notes.append(f"[switch to Script] {type(e).__name__}: {e}")

    after = set()
    buttons_after = set()
    try:
        after = rb_showing(app)
        buttons_after = L.button_names(app)
    except Exception as e:
        notes.append(f"[snapshot script mode] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "structure_script_mode",
            "The open log document switched to its 'Script' tab: the six-column message "
            "grid has been replaced by a Lua code editor that fills the document area — "
            "a grey line-number gutter numbered 1, 2, 3, ... down its left edge and "
            "green comment text starting 'Logbert Lua script interface' followed by "
            "lines about callback functions. Above the editor sits its own small "
            "toolbar (open / save, copy / cut / paste, undo / redo, a green right-"
            "pointing triangle to start the script and a grey square to stop it, zoom "
            "in / zoom out), and below it an empty white output box with scrollbars. "
            "The 'Log Level:' toolbar, the 'Logger Tree' panel at the right, the "
            "'Message Details' panel at the bottom and the blue status bar are "
            "unchanged.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    headers_back = []
    try:
        L.tab(app, "Messages").click_input()
        time.sleep(0.7)
        headers_back = _header_order(app)
    except Exception as e:
        notes.append(f"[switch back to Messages] {type(e).__name__}: {e}")

    ok = rb_reach(before, after, target="Button|Start script", source="Timestamp")
    assert ok, (
        f"the mode switch did not reshape the tree; appeared="
        f"{sorted(after - before)[:15]}; disappeared={sorted(before - after)[:15]}; "
        f"steps={notes}")
    new_buttons = buttons_after - buttons_before
    assert {"Start script", "Stop script", "Load script"} <= buttons_after, (
        f"button set in Script mode observed={sorted(buttons_after)}, expected it to "
        f"contain Start script / Stop script / Load script; new={sorted(new_buttons)}; "
        f"steps={notes}")
    assert not ({"Start script", "Stop script", "Load script"} & buttons_before), (
        f"script buttons were already present in Messages mode: "
        f"{sorted(buttons_before)}; steps={notes}")
    assert len(headers_back) >= len(GRID_COLUMNS), (
        f"grid headers after switching back observed={headers_back}, expected the six "
        f"message columns to be restored; steps={notes}")


@pytest.mark.rb(

    jump_kind="transition",

    expect="selecting the bottom-dock 'Statistic' tab adds a 'Statistic' Pane to the "

           "tree; switching back to Message Details reshapes it again",

    depth=1,

)
def test_statistic_tab_adds_pane(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    panes_before = set()
    try:
        panes_before = L.pane_names(app)
    except Exception as e:
        notes.append(f"[panes before] {type(e).__name__}: {e}")

    try:
        L.tab(app, "Statistic").click_input()
        time.sleep(0.7)
    except Exception as e:
        notes.append(f"[select Statistic tab] {type(e).__name__}: {e}")

    panes_after = set()
    visible_stat = set()
    try:
        panes_after = L.pane_names(app)
    except Exception as e:
        notes.append(f"[panes after] {type(e).__name__}: {e}")
    try:
        visible_stat = rb_showing(app)
    except Exception as e:
        notes.append(f"[snapshot statistic] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "structure_statistic_pane",
            "The bottom dock of the open log document switched to its 'Statistic' tab: "
            "the panel caption that read 'Message Details' now reads 'Statistic', the "
            "'Copy Details' toolbar and the Logger / Level / ... detail fields are gone, "
            "and in their place the panel shows a legend of small coloured swatches "
            "naming the log levels with their message counts next to a small pie chart "
            "whose slices carry percentage callout labels on thin leader lines (six "
            "equal slices, each labelled 17%, for this six-message log). The tab row "
            "along the bottom of the panel still reads 'Message Details | Bookmarks | "
            "Filter | Statistic' with 'Statistic' now selected; the message grid, the "
            "'Logger Tree' panel at the right and the blue status bar are unchanged.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    visible_back = set()
    try:
        L.tab(app, "Message Details").click_input()
        time.sleep(0.7)
        visible_back = rb_showing(app)
    except Exception as e:
        notes.append(f"[switch back to Message Details] {type(e).__name__}: {e}")

    ok = rb_flip(panes_before, panes_after)
    assert ok, (
        f"pane set unchanged by selecting the Statistic tab: observed "
        f"{sorted(panes_before)} -> {sorted(panes_after)}; steps={notes}")
    assert "Statistic" in (panes_after - panes_before), (
        f"new panes observed={sorted(panes_after - panes_before)}, expected a "
        f"'Statistic' pane to materialise; steps={notes}")
    assert rb_flip(visible_stat, visible_back), (
        f"switching back to Message Details changed nothing visible: "
        f"{len(visible_stat)} vs {len(visible_back)} visible nodes; "
        f"gone={sorted(visible_stat - visible_back)[:10]}; steps={notes}")


@pytest.mark.rb(

    jump_kind="value",

    expect="Window-node count delta while a dialog is open then dismissed == [1, 0]",

    depth=2,

)
def test_dialog_window_node_count_cycle(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    n_before = None
    try:
        n_before = len(L.dialog_titles(app))
    except Exception as e:
        notes.append(f"[window nodes before] {type(e).__name__}: {e}")

    dlg = None
    n_open = None
    try:
        L.use_menu(app, "Extras", "Options")
        rb.enter("options dialog")
        dlg = L.dialog(app, "Options", 10)
    except Exception as e:
        notes.append(f"[open Options] {type(e).__name__}: {e}")
    try:
        n_open = len(L.dialog_titles(app))
    except Exception as e:
        notes.append(f"[window nodes with dialog] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "structure_options_dialog",
            "The 'Options' dialog open on top of the Logbert main window: a narrow "
            "icon list occupies the left edge with three entries, and the rest of the "
            "dialog is filled by a group box captioned 'General Settings' holding "
            "stacked checkboxes ('Show welcome page on startup.', 'Check for a new "
            "version of Logbert on startup.', 'Allow only one instance of the "
            "application.') and labelled text fields ('Timestamp Format:' showing "
            "HH:mm:ss.fff, 'Update Rate in Milliseconds:' showing 250, 'Maximum log "
            "messages for each receiver:' showing 1000000). The dialog's action buttons "
            "sit along its bottom edge.",
            results_dir, window=(dlg if dlg is not None else app))
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    n_closed = None
    try:
        L.close_dialog(app, "Options")
        L.wait_until(lambda: L.named(app, "Window", "Options") is None, timeout=6)
        n_closed = len(L.dialog_titles(app))
    except Exception as e:
        notes.append(f"[dismiss Options] {type(e).__name__}: {e}")

    observed = None
    if n_before is not None and n_open is not None and n_closed is not None:
        observed = [n_open - n_before, n_closed - n_before]

    ok = rb_value(observed, [1, 0])
    assert ok, (
        f"Window-node count delta observed={observed} (raw counts before={n_before}, "
        f"open={n_open}, closed={n_closed}), expected [1, 0] — exactly one window node "
        f"added while the dialog is up and none left behind after it is dismissed; "
        f"steps={notes}")


# ── STYLE / LAYOUT ───────────────────────────────────────────────────────────

@pytest.mark.rb(

    jump_kind="none",

    expect="Logger Tree docked right of Messages, Message Details docked below it, menu "

           "bar above the tab strip",

    depth=1,

)
def test_layout_docking_geometry(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    messages = tree = details = None
    try:
        messages = L.pane(app, "Messages")
        tree = L.pane(app, "Logger Tree")
        details = L.pane(app, "Message Details")
    except Exception as e:
        notes.append(f"[locate panes] {type(e).__name__}: {e}")

    right_of = below = None
    try:
        right_of = L.is_right_of(tree, messages)
    except Exception as e:
        notes.append(f"[compare tree/messages] {type(e).__name__}: {e}")
    try:
        below = L.is_below(details, messages)
    except Exception as e:
        notes.append(f"[compare details/messages] {type(e).__name__}: {e}")

    menu_top = tab_top = None
    try:
        menu_top = L.rect(L.named(app, "MenuItem", "File"))[1]
        tab_top = L.rect(L.tab(app, "Welcome"))[1]
    except Exception as e:
        notes.append(f"[compare menu bar/tab strip] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "structure_core_layout",
            "The full Logbert working layout: a light-grey WinForms window titled "
            "'Logbert'; a menu bar reading 'File  Edit  Extras  Help'; a document tab "
            "strip with 'Welcome' and the active tab 'Log4Net File Receiver (sampl...' "
            "carrying a blue close cross; below it a toolbar that begins with the text "
            "label 'Log Level:' followed by six small round buttons coloured, left to "
            "right, white, green, blue, yellow, orange and red, then a run button, "
            "navigation, bookmark, zoom, refresh, delete, save, layout and filter icons "
            "and, at the right end, a numeric spinner showing 0 next to a greyed "
            "'Millisecond' drop-down. The centre is a white six-column message grid with "
            "pale blue-grey column headers Number / Level / Timestamp / Logger / Thread "
            "/ Message; a 'Logger Tree' panel is docked along the right edge showing "
            "'Logger Root' (highlighted blue) -> 'Root' -> 'Alpha', 'Beta', 'Gamma'; a "
            "'Message Details' panel is docked along the bottom with a 'Copy Details' "
            "toolbar and a tab row reading 'Message Details | Bookmarks | Filter | "
            "Statistic'; and a solid blue status bar spans the very bottom of the "
            "window.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    assert right_of is True, (
        f"'Logger Tree' pane rect={L.rect(tree)} vs 'Messages' pane rect="
        f"{L.rect(messages)}, expected the logger tree docked to the RIGHT of the "
        f"message grid; steps={notes}")
    assert below is True, (
        f"'Message Details' pane rect={L.rect(details)} vs 'Messages' pane rect="
        f"{L.rect(messages)}, expected the details panel docked BELOW the message grid; "
        f"steps={notes}")
    assert menu_top is not None and tab_top is not None and menu_top < tab_top, (
        f"menu bar top={menu_top} vs tab strip top={tab_top}, expected the menu bar row "
        f"above the document tab strip; steps={notes}")


@pytest.mark.rb(

    jump_kind="value",

    expect="the six level buttons share one toolbar row in the order "

           "Trace, Debug, Info, Warning, Error, Fatal left to right",

    depth=1,

)
def test_level_buttons_share_row_in_order(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    found = {}
    for name in LEVEL_BUTTONS:
        try:
            b = L.btn(app, name)
            if b is not None:
                found[name] = b
        except Exception as e:
            notes.append(f"[locate level button {name}] {type(e).__name__}: {e}")

    same_row = None
    try:
        same_row = L.in_row(list(found.values()))
    except Exception as e:
        notes.append(f"[row check] {type(e).__name__}: {e}")

    observed = []
    lefts = {}
    try:
        for name, b in found.items():
            r = L.rect(b)
            if r is not None:
                lefts[name] = r[0]
        observed = [n for n, _x in sorted(lefts.items(), key=lambda kv: kv[1])]
    except Exception as e:
        notes.append(f"[read button geometry] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "structure_level_button_row",
            "The 'Log Level:' toolbar row of the open log document: the text label "
            "'Log Level:' at the far left, immediately followed by six small round "
            "level buttons packed side by side in a single horizontal row and coloured, "
            "left to right, white, green, blue, yellow, orange and red. The remaining "
            "toolbar icons (a dark run/stop circle, up/down navigation arrows, a "
            "bookmark flag, magnifier zoom-in / zoom-out, a circular refresh arrow, a "
            "red delete cross, a blue save-with-drop-down icon, layout and filter "
            "icons, a clock) continue to the right on the very same row, ending with a "
            "numeric spinner and a 'Millisecond' drop-down.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    ok = rb_value(observed, LEVEL_BUTTONS)
    assert ok, (
        f"level buttons ordered by left edge observed={observed}, expected "
        f"{LEVEL_BUTTONS}; measured lefts={lefts}; steps={notes}")
    assert same_row is True, (
        f"level buttons share-a-row check observed={same_row}, expected all six on one "
        f"toolbar row; tops={[L.rect(b)[1] for b in found.values() if L.rect(b)]}; "
        f"steps={notes}")


@pytest.mark.rb(

    jump_kind="value",

    expect="message grid column headers run left to right as "

           "Number, Level, Timestamp, Logger, Thread, Message",

    depth=1,

)
def test_grid_header_order(app, rb):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    positions = {}
    observed = []
    try:
        positions = _header_positions(app)
        observed = _header_order(app)
    except Exception as e:
        notes.append(f"[read grid headers] {type(e).__name__}: {e}")

    ok = rb_value(observed, GRID_COLUMNS)
    assert ok, (
        f"grid header order observed={observed}, expected {GRID_COLUMNS}; measured "
        f"left edges={positions}; steps={notes}")