File size: 23,696 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
"""logbert_ui — vetted UIA primitives for the Logbert test suite.

Every function here was validated against the running reference build during recon.
Import it from a test module::

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

WHY THIS MODULE EXISTS (pitfalls it solves — do not re-invent these):

1. ``rb_uia.find_first(app, ...)`` ALWAYS returns ``None``.  The ``app`` fixture
   yields a pywinauto ``UIAWrapper``, which has no ``child_window()``.  Use
   ``L.one()`` / ``L.alld()`` (they go through ``.descendants()``) instead.
2. Logbert's modal dialogs (New Logger, Options, About, Edit Filter, message
   boxes, and even the native "Open" file dialog) are NOT desktop top-level
   windows — they appear as ``control_type="Window"`` DESCENDANTS of the main
   window.  Use ``L.dialog(app, "New Logger")``.
3. Menu dropdown items are only present in the tree while the dropdown is open,
   and the tree lists each item twice.  Use ``L.open_menu`` + ``L.pick_menu``.
4. Toolbar toggle buttons expose NO TogglePattern.  Read CHECKED with
   ``L.is_checked(button)`` (LegacyIAccessible STATE_SYSTEM_CHECKED bit).
5. The app opens on a Welcome page with no log data.  Call
   ``L.rb_enter_document(app, rb)`` first to reach the core working state.
"""
from __future__ import annotations

import ctypes
import os
import time

# ── fixtures ─────────────────────────────────────────────────────────────────

DEFAULT_LOG = "sample_log4net.log"
MIXED_LOG = "sample_log4net_mixed.log"


def fixtures_dir() -> str:
    """FIXTURES_DIR when the eval harness sets it, else ``fixtures/`` next to the
    results dir (warm ``run_live.ps1`` runs).

    Always returned as a NATIVE path: the Windows file chooser silently refuses a
    path typed with forward slashes, so `/` separators must be normalised away.
    """
    fd = os.environ.get("FIXTURES_DIR", "")
    if fd and os.path.isdir(fd):
        return os.path.normpath(fd)
    rd = os.environ.get("RB_RESULTS_DIR") or os.environ.get("RESULTS_DIR") or "."
    cand = os.path.join(os.path.dirname(os.path.abspath(rd)), "fixtures")
    if os.path.isdir(cand):
        return os.path.normpath(cand)
    return os.path.normpath(os.path.join(os.path.abspath(rd), "fixtures"))


def fixture(name: str = DEFAULT_LOG) -> str:
    return os.path.normpath(os.path.join(fixtures_dir(), name))


# ── locators (never use rb_uia.find_first — see module docstring) ────────────

def alld(root, ct: str | None = None, title: str | None = None, **kw) -> list:
    """All descendants of ``root`` matching control_type / visible title."""
    root = _healed(root)
    if root is None:
        return []
    crit = {}
    if ct:
        crit["control_type"] = ct
    if title:
        crit["title"] = title
    crit.update(kw)
    try:
        return root.descendants(**crit) if crit else root.descendants()
    except Exception:
        return []


def one(root, ct: str | None = None, title: str | None = None, **kw):
    r = alld(root, ct, title, **kw)
    return r[0] if r else None


def named(root, ct: str, name: str):
    """First descendant of ``ct`` whose visible name is EXACTLY ``name``."""
    for e in alld(root, ct):
        try:
            if (e.window_text() or "") == name:
                return e
        except Exception:
            continue
    return None


def btn(root, name: str):
    """Button (incl. toolbar button) by exact visible name."""
    return named(root, "Button", name)


def tab(root, name: str):
    return named(root, "TabItem", name)


def pane(root, name: str):
    return named(root, "Pane", name)


def pane_names(root) -> set:
    out = set()
    for p in alld(root, "Pane"):
        try:
            t = p.window_text() or ""
        except Exception:
            continue
        if t:
            out.add(t)
    return out


def button_names(root) -> set:
    out = set()
    for b in alld(root, "Button"):
        try:
            t = b.window_text() or ""
        except Exception:
            continue
        if t:
            out.add(t)
    return out


def wait_until(fn, timeout: float = 10.0, interval: float = 0.25):
    """Poll ``fn`` until it returns something truthy; return last value."""
    deadline = time.time() + timeout
    val = None
    while time.time() < deadline:
        try:
            val = fn()
            if val:
                return val
        except Exception:
            pass
        time.sleep(interval)
    return val


# ── stray-window defence ─────────────────────────────────────────────────────
#
# Once a log file lands in Logbert's MRU, the Welcome page renders it as a link.
# A pointer resting over that link makes Logbert pop a ToolTip, which on Windows
# is a *top-level window owned by the same process* and carries the file path as
# its title.  The harness picks "the first titled window of this PID", so it can
# latch onto the ToolTip instead of the main window — after which every locator
# comes back empty and the whole module fails.  Two defences:
#   park_cursor()  — keep the pointer off the app so the ToolTip never appears
#   main_window()  — if we were handed a childless stray, swap in the real window

def park_cursor() -> None:
    """Move the physical pointer to the right edge of the screen, away from the app."""
    try:
        u = ctypes.windll.user32
        w = u.GetSystemMetrics(0)
        h = u.GetSystemMetrics(1)
        u.SetCursorPos(max(0, int(w) - 3), max(0, int(h) // 2))
    except Exception:
        pass


def main_window(root):
    """The app's real main window — repairs a childless stray (ToolTip) root."""
    if root is None:
        return None
    try:
        if len(root.children()) > 0:
            return root
    except Exception:
        pass
    try:
        from pywinauto import Desktop
        pid = root.process_id()
        for w in Desktop(backend="uia").windows():
            try:
                if w.process_id() != pid:
                    continue
                if (w.window_text() or "") and len(w.children()) > 0:
                    return w
            except Exception:
                continue
    except Exception:
        pass
    return root


def _healed(root):
    """Cheap guard used by every locator: only pays for a repair when the root is
    a childless top-level Window (never true of a real dialog or pane)."""
    if root is None:
        return None
    try:
        if root.element_info.control_type != "Window":
            return root
        if len(root.children()) > 0:
            return root
    except Exception:
        return root
    return main_window(root)


# ── dialogs (descendants, NOT desktop windows) ───────────────────────────────

def dialog(app, title: str, timeout: float = 10.0):
    """Wait for and return the modal dialog whose title is exactly ``title``."""
    return wait_until(lambda: named(app, "Window", title), timeout=timeout)


def dialog_titles(app) -> list:
    out = []
    for w in alld(app, "Window"):
        try:
            t = w.window_text() or ""
        except Exception:
            continue
        if t:
            out.append(t)
    return out


def close_dialog(app, title: str | None = None) -> None:
    """Dismiss a dialog non-destructively: Cancel button if present, else Escape.

    NEVER commits changes (no OK) — Logbert persists Options to user settings and
    a committed change would leak into later tests.
    """
    dlg = named(app, "Window", title) if title else None
    target = dlg if dlg is not None else app
    b = btn(target, "Cancel") or btn(target, "Close")
    if b is not None and (b.window_text() or "") == "Cancel":
        try:
            b.click_input()
            time.sleep(0.4)
            return
        except Exception:
            pass
    press("{ESC}")
    time.sleep(0.4)


# ── keyboard / mouse ─────────────────────────────────────────────────────────

def press(keys: str) -> None:
    from pywinauto.keyboard import send_keys
    send_keys(keys)


def type_text(text: str) -> None:
    from pywinauto.keyboard import send_keys
    send_keys(text, with_spaces=True)


def click_at(x: int, y: int) -> None:
    import pywinauto.mouse as mouse
    mouse.click(coords=(int(x), int(y)))


# ── menus ────────────────────────────────────────────────────────────────────

def open_menu(app, top: str) -> bool:
    """Click a top-level menu ("File" / "Edit" / "Extras" / "Help")."""
    m = named(app, "MenuItem", top)
    if m is None:
        return False
    m.click_input()
    time.sleep(0.5)
    return True


def pick_menu(app, prefix: str) -> bool:
    """Click the open dropdown item whose visible text starts with ``prefix``."""
    for mi in alld(app, "MenuItem"):
        try:
            if (mi.window_text() or "").startswith(prefix):
                mi.click_input()
                time.sleep(0.7)
                return True
        except Exception:
            continue
    return False


def menu_item_names(app) -> set:
    out = set()
    for mi in alld(app, "MenuItem"):
        try:
            t = mi.window_text() or ""
        except Exception:
            continue
        if t:
            out.add(t)
    return out


def use_menu(app, top: str, prefix: str) -> bool:
    """open_menu + pick_menu in one call."""
    return open_menu(app, top) and pick_menu(app, prefix)


# ── reaching the core working state ──────────────────────────────────────────

def select_tab(root, name: str, pause: float = 0.4) -> bool:
    """Click a TabItem by its visible name."""
    t = tab(root, name)
    if t is None:
        return False
    try:
        t.click_input()
        time.sleep(pause)
        return True
    except Exception:
        return False


def normalize_document(app) -> None:
    """Put a freshly opened document into its canonical layout.

    Logbert PERSISTS the docking layout per receiver, so whichever document tab and
    bottom-dock tab a previous run left active come back on the next launch — and a
    panel that is not the active one contributes nothing to the UIA tree. Without
    this, a run in which some earlier test selected `Filter` would leave every later
    test unable to read the Message Details fields.
    """
    select_tab(app, "Messages")
    select_tab(app, "Message Details")
    try:
        if pane(app, "Logger Tree") is None:
            b = btn(app, "Logger Tree")
            if b is not None:
                b.click_input()
                time.sleep(0.5)
    except Exception:
        pass


def rb_enter_document(app, rb=None, log_name: str = DEFAULT_LOG,
                      receiver: str = "Log4Net File Receiver"):
    """Welcome page -> File > New Logger... -> pick receiver -> set file -> OK.

    A REAL surface crossing (Welcome -> log document), so it bumps ``rb`` by one
    when a tracker is passed.  Leaves the app showing a loaded log document in its
    canonical layout: 6 messages (one per level) for DEFAULT_LOG, 10 for MIXED_LOG.
    """
    park_cursor()
    use_menu(app, "File", "New Logger")
    dlg = dialog(app, "New Logger", 12)
    if dlg is None:
        raise AssertionError("New Logger dialog did not open")
    item = named(dlg, "ListItem", receiver)
    if item is None:
        raise AssertionError("receiver not in list: %s" % receiver)
    item.click_input()
    time.sleep(0.6)
    ed = named(dlg, "Edit", "File to observe:")
    if ed is None:
        raise AssertionError("'File to observe:' edit not found")
    ed.set_edit_text(fixture(log_name))
    time.sleep(0.3)
    ok = btn(dlg, "OK")
    if ok is None:
        raise AssertionError("OK button not found in New Logger dialog")
    ok.click_input()
    if wait_until(lambda: len(column_values(app, "Number")) > 0, timeout=15) is None:
        raise AssertionError("log document did not load any messages")
    time.sleep(0.5)
    normalize_document(app)
    park_cursor()
    if rb is not None:
        rb.enter("document")
    return app


# ── status bar ───────────────────────────────────────────────────────────────

def status_texts(app) -> list:
    out = []
    for t in alld(app, "Text"):
        try:
            s = t.window_text() or ""
        except Exception:
            continue
        if s.startswith("Status:") or "Messages (" in s:
            out.append(s)
    return out


def message_count_text(app) -> str:
    """e.g. '6 Messages (all displayed)' or '6 Messages (2 displayed)'."""
    for s in status_texts(app):
        if "Messages (" in s:
            return s
    return ""


def run_state_text(app) -> str:
    """'Status: Running' or 'Status: Stopped'."""
    for s in status_texts(app):
        if s.startswith("Status:"):
            return s
    return ""


# ── message grid ─────────────────────────────────────────────────────────────

_GRID_COLS = ("Number", "Level", "Timestamp", "Logger", "Thread", "Message")


def _cell_edits(root):
    """Grid cells are Edits named '<Column> Row <n>, <sort state>.'."""
    out = []
    for e in alld(root, "Edit"):
        try:
            n = e.window_text() or ""
        except Exception:
            continue
        if " Row " in n and n.split(" Row ")[0].strip() in _GRID_COLS:
            out.append((n, e))
    return out


def _messages_root(app):
    """Scope grid reads to the Messages pane so the Bookmarks / Statistic grids
    can never bleed in."""
    return pane(app, "Messages") or app


def grid_rows(app) -> list:
    """Visible message rows as a list of dicts keyed by column name."""
    rows: dict[int, dict] = {}
    for n, e in _cell_edits(_messages_root(app)):
        col = n.split(" Row ")[0].strip()
        try:
            idx = int(n.split(" Row ")[1].split(",")[0].strip())
        except Exception:
            continue
        try:
            rows.setdefault(idx, {})[col] = e.get_value()
        except Exception:
            rows.setdefault(idx, {})[col] = None
    return [rows[k] for k in sorted(rows)]


def column_values(app, col: str) -> list:
    return [r.get(col) for r in grid_rows(app) if col in r]


def row_count(app) -> int:
    return len(column_values(app, "Number"))


def cell(app, row: int, col: str):
    for n, e in _cell_edits(_messages_root(app)):
        if n.startswith("%s Row %d," % (col, row)):
            return e
    return None


# ── message details pane ─────────────────────────────────────────────────────

_DETAIL_FIELDS = ("Logger", "Level", "Date and Time", "Thread", "Message",
                  "Location", "Properties")


def details_fields(app) -> dict:
    """Message Details pane field values (the selected message).

    Self-activating: the bottom dock shares one slot between Message Details /
    Bookmarks / Filter / Statistic and the active one is persisted, so bring the
    Message Details tab forward if some other panel currently owns the slot.
    """
    root = pane(app, "Message Details")
    if root is None:
        select_tab(app, "Message Details")
        root = pane(app, "Message Details")
    if root is None:
        root = app
    out = {}
    for e in alld(root, "Edit"):
        try:
            n = e.window_text() or ""
        except Exception:
            continue
        if n in _DETAIL_FIELDS and n not in out:
            try:
                out[n] = e.get_value()
            except Exception:
                out[n] = None
    return out


# ── other panes ──────────────────────────────────────────────────────────────

def bookmark_rows(app) -> list:
    """Rows of the Bookmarks pane grid: [{'Number': .., 'Message': ..}, ...].
    Self-activating (the bottom dock shares one slot — see details_fields)."""
    root = pane(app, "Bookmarks")
    if root is None:
        select_tab(app, "Bookmarks")
        root = pane(app, "Bookmarks")
    if root is None:
        return []
    rows: dict[int, dict] = {}
    for n, e in _cell_edits(root):
        col = n.split(" Row ")[0].strip()
        try:
            idx = int(n.split(" Row ")[1].split(",")[0].strip())
        except Exception:
            continue
        try:
            rows.setdefault(idx, {})[col] = e.get_value()
        except Exception:
            rows.setdefault(idx, {})[col] = None
    return [rows[k] for k in sorted(rows)]


def statistic_labels(app) -> list:
    """Percentage labels of the Statistic pie chart, e.g. ['20%','50%','30%'].
    Self-activating (the bottom dock shares one slot — see details_fields)."""
    if pane(app, "Statistic") is None:
        select_tab(app, "Statistic", pause=0.8)
    out = []
    for e in alld(app, "Edit"):
        try:
            if (e.window_text() or "").startswith("Data Point Label"):
                out.append(e.get_value())
        except Exception:
            continue
    return out


def logger_tree_items(app) -> list:
    out = []
    for t in alld(app, "TreeItem"):
        try:
            out.append(t.window_text() or "")
        except Exception:
            continue
    return out


def logger_node(app, name: str):
    return named(app, "TreeItem", name)


# ── script (Lua) tab ─────────────────────────────────────────────────────────

def script_output(app) -> str:
    """Value of the Lua output box at the bottom of the Script tab."""
    sp = pane(app, "Script")
    if sp is None:
        return ""
    for e in alld(sp, "Edit"):
        try:
            if not (e.window_text() or ""):
                return e.get_value() or ""
        except Exception:
            continue
    return ""


def put_script(app, code: str) -> bool:
    """Replace the Scintilla editor content with ``code``.

    Uses the clipboard: Scintilla auto-closes brackets, so typing Lua source
    character-by-character corrupts it.  The Script tab must already be open.
    """
    sp = pane(app, "Script")
    if sp is None:
        return False
    r = sp.rectangle()
    click_at(r.left + min(240, (r.right - r.left) // 3), r.top + 120)
    time.sleep(0.4)
    set_clipboard(code)
    press("^a")
    time.sleep(0.2)
    press("^v")
    time.sleep(0.6)
    return True


# ── checked state (toolbar buttons expose no TogglePattern) ──────────────────

_STATE_CHECKED = 0x10


def is_checked(el):
    """CHECKED for toolbar toggle buttons via LegacyIAccessible state bit.
    Returns True/False, or None when the element exposes no state at all."""
    if el is None:
        return None
    try:
        return bool(int(el.legacy_properties().get("State", 0)) & _STATE_CHECKED)
    except Exception:
        pass
    try:
        return el.get_toggle_state() == 1
    except Exception:
        return None


def toggle_state(el):
    """CHECKED for real CheckBox controls (TogglePattern): True/False/None."""
    if el is None:
        return None
    try:
        return el.get_toggle_state() == 1
    except Exception:
        return is_checked(el)


def checkbox(root, name_startswith: str):
    for c in alld(root, "CheckBox"):
        try:
            if (c.window_text() or "").startswith(name_startswith):
                return c
        except Exception:
            continue
    return None


def focused_name(app=None) -> str:
    """Name of the element that currently owns keyboard focus ('' if unknown)."""
    try:
        from pywinauto.uia_defines import IUIA
        el = IUIA().iuia.GetFocusedElement()
        if el is None:
            return ""
        return el.CurrentName or ""
    except Exception:
        return ""


def has_focus(el) -> bool:
    try:
        return bool(el.has_keyboard_focus())
    except Exception:
        return False


# ── clipboard ────────────────────────────────────────────────────────────────

_CF_UNICODETEXT = 13


def set_clipboard(text: str) -> bool:
    try:
        u = ctypes.windll.user32
        k = ctypes.windll.kernel32
        k.GlobalAlloc.restype = ctypes.c_void_p
        k.GlobalLock.restype = ctypes.c_void_p
        k.GlobalLock.argtypes = [ctypes.c_void_p]
        k.GlobalUnlock.argtypes = [ctypes.c_void_p]
        u.SetClipboardData.argtypes = [ctypes.c_uint, ctypes.c_void_p]
        if not u.OpenClipboard(None):
            return False
        try:
            u.EmptyClipboard()
            data = text.encode("utf-16-le") + b"\x00\x00"
            h = k.GlobalAlloc(0x2042, len(data))
            p = k.GlobalLock(h)
            ctypes.memmove(p, data, len(data))
            k.GlobalUnlock(h)
            u.SetClipboardData(_CF_UNICODETEXT, h)
        finally:
            u.CloseClipboard()
        return True
    except Exception:
        return False


def get_clipboard() -> str:
    try:
        u = ctypes.windll.user32
        k = ctypes.windll.kernel32
        k.GlobalLock.restype = ctypes.c_void_p
        k.GlobalLock.argtypes = [ctypes.c_void_p]
        k.GlobalUnlock.argtypes = [ctypes.c_void_p]
        u.GetClipboardData.restype = ctypes.c_void_p
        if not u.OpenClipboard(None):
            return ""
        try:
            h = u.GetClipboardData(_CF_UNICODETEXT)
            if not h:
                return ""
            p = k.GlobalLock(h)
            s = ctypes.wstring_at(p)
            k.GlobalUnlock(h)
            return s
        finally:
            u.CloseClipboard()
    except Exception:
        return ""


# ── geometry (style / layout assertions) ─────────────────────────────────────

def rect(el):
    """(left, top, right, bottom) or None."""
    try:
        r = el.rectangle()
        return (r.left, r.top, r.right, r.bottom)
    except Exception:
        return None


def size(el):
    r = rect(el)
    return None if r is None else (r[2] - r[0], r[3] - r[1])


def center(el):
    r = rect(el)
    return None if r is None else ((r[0] + r[2]) // 2, (r[1] + r[3]) // 2)


def is_right_of(a, b) -> bool:
    ra, rb = rect(a), rect(b)
    return bool(ra and rb and ra[0] >= rb[2] - 2)


def is_below(a, b) -> bool:
    ra, rb = rect(a), rect(b)
    return bool(ra and rb and ra[1] >= rb[3] - 2)


def in_row(elements, tol: int = 6) -> bool:
    """True when all elements share a horizontal band (toolbar-style row)."""
    tops = [rect(e)[1] for e in elements if rect(e)]
    return bool(tops) and (max(tops) - min(tops)) <= tol