-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreading_order_gui.py
More file actions
858 lines (752 loc) · 35.9 KB
/
reading_order_gui.py
File metadata and controls
858 lines (752 loc) · 35.9 KB
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
from __future__ import annotations
import json
import os
import sys
import threading
from typing import Optional
import importlib
from pathlib import Path
from datetime import datetime
# Ensure we can always start even if the current interpreter lacks PySide6/Qt DLLs.
# If importing PySide6 fails, auto-relaunch with the known working 'web-qt' interpreter
# if present; otherwise print a helpful message and exit.
def _ensure_pyside6_or_relaunch() -> None:
try:
# Probe imports that trigger DLL loading to catch broken envs early
import PySide6 # type: ignore
from PySide6.QtCore import Qt # type: ignore
except Exception as e:
webqt = Path(r"C:\Users\becnc\.conda\envs\web-qt\python.exe")
if webqt.exists() and Path(sys.executable).resolve() != webqt.resolve():
print("PySide6 not available in current environment; relaunching with 'web-qt'...", file=sys.stderr)
os.execv(str(webqt), [str(webqt), __file__, *sys.argv[1:]])
else:
print(f"PySide6 import failed: {e}\nTip: Use 'C\\Users\\becnc\\.conda\\envs\\web-qt\\python.exe reading_order_gui.py' or switch VS Code interpreter to web-qt.", file=sys.stderr)
raise SystemExit(2)
_ensure_pyside6_or_relaunch()
from PySide6.QtCore import Qt, Signal, QObject, QTimer, QSize, QUrl
from PySide6.QtGui import QPixmap, QPainter, QColor, QFont, QKeySequence, QShortcut
from PySide6.QtWidgets import (
QApplication,
QDialog,
QFileDialog,
QHBoxLayout,
QLabel,
QLineEdit,
QListWidget,
QPushButton,
QTextEdit,
QVBoxLayout,
QWidget,
QSplitter,
)
WEBVIEW_AVAILABLE = False
WEBPAGE_AVAILABLE = False
WEBVIEW_ERROR: Optional[str] = None
WEBPAGE_ERROR: Optional[str] = None
try:
from PySide6.QtWebEngineWidgets import QWebEngineView
WEBVIEW_AVAILABLE = True
except Exception as _e:
QWebEngineView = None # type: ignore
try:
WEBVIEW_ERROR = repr(_e)
except Exception:
WEBVIEW_ERROR = str(_e)
# QWebEnginePage is optional; prefer importing from QtWebEngineCore, then fallback to Widgets
try:
from PySide6.QtWebEngineCore import QWebEnginePage # type: ignore
WEBPAGE_AVAILABLE = True
except Exception:
try:
from PySide6.QtWebEngineWidgets import QWebEnginePage # type: ignore
WEBPAGE_AVAILABLE = True
except Exception as _e2:
QWebEnginePage = None # type: ignore
try:
WEBPAGE_ERROR = repr(_e2)
except Exception:
WEBPAGE_ERROR = str(_e2)
"""
Ensure QtWebEngine starts with permissive Chromium flags to reduce SSL/TLS and network issues
that often block loads in embedded views (useful behind proxies or with self-signed certs).
Set these before any QtWebEngine import/use.
"""
# Only add flags if not already provided by the environment
try:
flags_existing = os.environ.get("QTWEBENGINE_CHROMIUM_FLAGS", "")
flags_required = [
"--ignore-certificate-errors",
"--allow-insecure-localhost",
# Helps in some corp environments; safe to include
"--disable-features=OutOfBlinkCors",
]
to_add = [f for f in flags_required if f not in flags_existing]
if to_add:
os.environ["QTWEBENGINE_CHROMIUM_FLAGS"] = (flags_existing + " " + " ".join(to_add)).strip()
except Exception:
pass
import reading_order as ro
class WorkerSignals(QObject):
finished = Signal(int)
progress = Signal(str)
result = Signal(dict)
class ScanWorker(threading.Thread):
def __init__(self, url: str, output: str, signals: WorkerSignals, headful: bool = False):
super().__init__(daemon=True)
self.url = url
self.output = output
self.signals = signals
self.headful = headful
def run(self) -> None:
try:
self.signals.progress.emit(f"Starting scan: {self.url}")
result = ro.scan_page(self.url, self.output, headful=self.headful)
self.signals.progress.emit("Scan finished")
self.signals.result.emit(result)
self.signals.finished.emit(0)
except Exception as e:
self.signals.progress.emit(f"Error during scan: {e}")
self.signals.finished.emit(1)
if WEBPAGE_AVAILABLE:
class LoggingPage(QWebEnginePage): # type: ignore[misc]
def __init__(self, parent=None, log_cb=None):
super().__init__(parent)
self._log_cb = log_cb
# Log any JS console output to the GUI log panel
def javaScriptConsoleMessage(self, level, message, line, sourceId): # type: ignore[override]
try:
if self._log_cb:
self._log_cb(f"Console[{level}]: {message} (line {line} in {sourceId})")
except Exception:
pass
# Be permissive with certificate errors to improve odds of loading
def certificateError(self, error): # type: ignore[override]
try:
if self._log_cb:
self._log_cb(f"Certificate error: {error.errorDescription() if hasattr(error,'errorDescription') else error}")
except Exception:
pass
return True
class ReadingOrderDialog(QDialog):
def __init__(self, parent: Optional[QWidget] = None):
super().__init__(parent)
self.setWindowTitle("Reading Order Scanner")
self.resize(1200, 800)
self.showMaximized()
# Controls
self.url_input = QLineEdit()
self.url_input.setPlaceholderText("https://example.com")
self.output_input = QLineEdit("reading_order_report.html")
self.output_button = QPushButton("&Browse (Alt+W)") # Alt+W
self.scan_button = QPushButton("Scan")
self.save_button = QPushButton("Save Report (Ctrl+&S)") # Ctrl+S
self.headful_checkbox = QPushButton("Headful")
self.headful_checkbox.setCheckable(True)
# Mode switch
self.mode_live = QPushButton("Live View")
self.mode_live.setCheckable(True)
self.mode_live.setChecked(WEBVIEW_AVAILABLE)
if not WEBVIEW_AVAILABLE:
self.mode_live.setToolTip("QtWebEngine not available - using screenshot fallback")
self.mode_live.setEnabled(False)
# Playback controls
self.play_button = QPushButton("&Play (Alt+P)")
self.pause_button = QPushButton("Stop (Alt+&O)") # Alt+O for stop
self.next_button = QPushButton("&Next (Alt+N)")
self.prev_button = QPushButton("Previous (Alt+&B)")
self.auto_refresh_button = QPushButton("Auto-Refresh (Alt+&A)") # Alt+A for auto-refresh
self.auto_refresh_button.setCheckable(True)
self.log = QTextEdit()
self.log.setReadOnly(True)
# Viewer area
self.viewer_container = QWidget()
self.viewer_layout = QVBoxLayout(self.viewer_container)
self.viewer_layout.setContentsMargins(0, 0, 0, 0)
self.webview = None
if WEBVIEW_AVAILABLE:
self.webview = QWebEngineView()
try:
# Attach logging page to capture JS console and relax TLS errors (if available)
if WEBPAGE_AVAILABLE:
page = LoggingPage(self.webview, log_cb=self.append_log)
self.webview.setPage(page)
except Exception:
pass
try:
# Set a modern user agent to reduce blocking by some sites
ua = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/126.0.0.0 Safari/537.36"
)
self.webview.page().profile().setHttpUserAgent(ua)
except Exception:
pass
self.viewer_layout.addWidget(self.webview)
else:
self.image_label = QLabel()
self.image_label.setAlignment(Qt.AlignCenter)
self.image_label.setMinimumHeight(480)
self.viewer_layout.addWidget(self.image_label)
self.items_list = QListWidget()
self.items_list.currentRowChanged.connect(self._on_list_selection_changed)
splitter = QSplitter(Qt.Horizontal)
splitter.addWidget(self.viewer_container)
splitter.addWidget(self.items_list)
splitter.setSizes([800, 400])
# Top controls
top_layout = QHBoxLayout()
top_layout.addWidget(QLabel("URL:"))
top_layout.addWidget(self.url_input)
top_layout.addWidget(QLabel("Output:"))
top_layout.addWidget(self.output_input)
top_layout.addWidget(self.output_button)
top_layout.addWidget(self.mode_live)
top_layout.addWidget(self.headful_checkbox)
top_layout.addWidget(self.scan_button)
top_layout.addWidget(self.save_button)
play_layout = QHBoxLayout()
play_layout.addWidget(self.prev_button)
play_layout.addWidget(self.play_button)
play_layout.addWidget(self.pause_button)
play_layout.addWidget(self.next_button)
play_layout.addWidget(self.auto_refresh_button)
play_layout.addStretch()
main = QVBoxLayout()
main.addLayout(top_layout)
main.addLayout(play_layout)
main.addWidget(splitter)
main.addWidget(QLabel("Log:"))
main.addWidget(self.log)
self.setLayout(main)
# Accessibility: keyboard shortcuts
# Browse: Alt+W, Save: Ctrl+S, Play: Alt+P, Stop: Alt+O, Next: Alt+N,
# Previous: Alt+B, Auto-refresh toggle: Alt+A, Focus list: Alt+L, Focus log: Alt+G
self._install_shortcuts()
# state
self.current_items = []
self.current_index = -1
self._scan_in_progress = False
self.play_timer = QTimer(self)
self.play_timer.setInterval(1000)
self.play_timer.timeout.connect(self.autoplay_step)
self.refresh_timer = QTimer(self)
self.refresh_timer.setInterval(10000)
self.refresh_timer.timeout.connect(self._trigger_rescan)
# wire signals
self.output_button.clicked.connect(self.choose_output)
self.scan_button.clicked.connect(self.start_scan)
self.save_button.clicked.connect(self.save_report)
if self.webview:
self.url_input.returnPressed.connect(self.start_scan) # Enter key in URL starts scan
self.play_button.clicked.connect(self.start_autoplay)
self.pause_button.clicked.connect(self.stop_autoplay)
self.next_button.clicked.connect(self.next_item)
self.prev_button.clicked.connect(self.prev_item)
self.auto_refresh_button.toggled.connect(self._toggle_auto_refresh)
# Enter in URL field should start scan
self.url_input.returnPressed.connect(self.start_scan)
# Keyboard shortcuts
self.shortcut_browse = QShortcut(QKeySequence("Alt+W"), self)
self.shortcut_browse.activated.connect(lambda: (self.choose_output(), self.append_log("Keyboard shortcut: Alt+W (Browse)")))
self.shortcut_save = QShortcut(QKeySequence("Ctrl+S"), self)
self.shortcut_save.activated.connect(lambda: (self.save_report(), self.append_log("Keyboard shortcut: Ctrl+S (Save)")))
self.shortcut_play = QShortcut(QKeySequence("Alt+P"), self)
self.shortcut_play.activated.connect(lambda: (self.start_autoplay(), self.append_log("Keyboard shortcut: Alt+P (Play)")))
self.shortcut_stop = QShortcut(QKeySequence("Alt+O"), self)
self.shortcut_stop.activated.connect(lambda: (self.stop_autoplay(), self.append_log("Keyboard shortcut: Alt+O (Stop)")))
self.shortcut_next = QShortcut(QKeySequence("Alt+N"), self)
self.shortcut_next.activated.connect(lambda: (self.next_item(), self.append_log("Keyboard shortcut: Alt+N (Next)")))
self.shortcut_prev = QShortcut(QKeySequence("Alt+B"), self)
self.shortcut_prev.activated.connect(lambda: (self.prev_item(), self.append_log("Keyboard shortcut: Alt+B (Previous)")))
self.shortcut_autorefresh = QShortcut(QKeySequence("Alt+A"), self)
self.shortcut_autorefresh.activated.connect(lambda: (self._toggle_auto_refresh_shortcut(), self.append_log("Keyboard shortcut: Alt+A (Auto-refresh)")))
self.shortcut_list = QShortcut(QKeySequence("Alt+L"), self)
self.shortcut_list.activated.connect(lambda: (self.items_list.setFocus(), self.append_log("Keyboard shortcut: Alt+L (Focus list)")))
self.shortcut_log = QShortcut(QKeySequence("Alt+G"), self)
self.shortcut_log.activated.connect(lambda: (self.log.setFocus(), self.append_log("Keyboard shortcut: Alt+G (Focus log)")))
self.worker = None
# initial live blank page
if self.mode_live.isChecked() and self.webview:
self.webview.setUrl(QUrl("about:blank"))
# Log availability to make it clear in UI
self.append_log(f"QWebEngineView available: {WEBVIEW_AVAILABLE}")
self.append_log(f"QWebEnginePage available: {WEBPAGE_AVAILABLE}")
if not WEBVIEW_AVAILABLE and WEBVIEW_ERROR:
self.append_log(f"QWebEngineView import error: {WEBVIEW_ERROR}")
self.append_log("Hint: Ensure PySide6 (pip wheels) is installed in this environment. If using conda, consider pip installing PySide6.")
if not WEBPAGE_AVAILABLE and WEBPAGE_ERROR:
self.append_log(f"QWebEnginePage import error: {WEBPAGE_ERROR}")
# Extra diagnostics so we know which interpreter and versions are in use
try:
self.append_log(f"Python: {sys.executable}")
except Exception:
pass
try:
import PySide6 # type: ignore
self.append_log(f"PySide6: {PySide6.__version__}")
except Exception:
pass
try:
spec = importlib.util.find_spec('PySide6.QtWebEngineWidgets')
self.append_log(f"QtWebEngine spec found: {bool(spec)}")
except Exception:
pass
try:
env_name = os.environ.get('CONDA_DEFAULT_ENV') or os.environ.get('VIRTUAL_ENV') or ''
if env_name:
self.append_log(f"Active env: {env_name}")
except Exception:
pass
def append_log(self, text: str) -> None:
timestamp = datetime.now().strftime('%H:%M:%S')
log_entry = f"[{timestamp}] {text}"
self.log.append(log_entry)
# Also write to log file
try:
with open('log.txt', 'a', encoding='utf-8') as f:
f.write(log_entry + '\n')
except Exception:
pass
def choose_output(self) -> None:
fname, _ = QFileDialog.getSaveFileName(self, "Select output file", os.getcwd(), "HTML files (*.html);;All files (*)")
if fname:
self.output_input.setText(fname)
def _navigate_live(self) -> None:
if not self.webview:
return
url = self.url_input.text().strip()
if url:
if not (url.startswith("http://") or url.startswith("https://")):
url = "http://" + url
self.webview.setUrl(QUrl(url))
def start_scan(self) -> None:
if self._scan_in_progress:
self.append_log("A scan is already in progress; please wait or Pause/stop.")
return
url = self.url_input.text().strip()
if not url:
self.append_log("Please enter a URL")
return
# Normalize URL if scheme is missing
if not (url.startswith("http://") or url.startswith("https://")):
url = "http://" + url
out = self.output_input.text().strip() or "reading_order_report.html"
headful = self.headful_checkbox.isChecked()
live_mode = self.mode_live.isChecked() and self.webview is not None
if live_mode and self.webview:
# Ensure the webview is visible in the viewer container (may have been replaced by screenshot)
try:
if hasattr(self, 'image_label') and self.image_label is not None:
self.viewer_layout.removeWidget(self.image_label)
self.image_label.setParent(None)
except Exception:
pass
try:
# If webview isn't already in the layout, add it
if self.webview.parent() is None:
self.viewer_layout.addWidget(self.webview)
except Exception:
pass
# UI: disable actions during live load/collection
try:
self.scan_button.setEnabled(False)
self.save_button.setEnabled(False)
except Exception:
pass
self._scan_in_progress = True
# clear previous state
self.current_items = []
self.current_index = -1
self.items_list.clear()
self.webview.setUrl(QUrl(url))
# Diagnostics and fallback
try:
self.webview.loadStarted.connect(lambda: self.append_log("Live View: load started"))
self.webview.loadProgress.connect(lambda p: self.append_log(f"Live View: load progress {p}%") if p in (0,25,50,75,100) else None)
except Exception:
pass
def on_load(ok: bool):
self.append_log(f"Live View: load finished ok={ok}")
if ok:
self._collect_items_live()
else:
# Page failed to load, trigger immediate fallback
self.append_log("Live View: page load failed, falling back to Playwright scan")
self._live_pending = False
try:
url_fallback = self.url_input.text().strip()
out_fallback = self.output_input.text().strip() or "reading_order_report.html"
headful_fallback = self.headful_checkbox.isChecked()
self._start_worker_scan(url_fallback, out_fallback, headful_fallback)
except Exception:
pass
# Don't disconnect here - let the fallback timer handle cleanup
self.webview.loadFinished.connect(on_load)
# Auto-fallback to Playwright scan if nothing arrives in 15s
self._live_pending = True
def _maybe_fallback():
if getattr(self, "_live_pending", False) and not self.current_items:
self.append_log("Live View: no items after 15s, falling back to Playwright scan")
# Clear the pending flag and run fallback scan
self._live_pending = False
self._start_worker_scan(url, out, headful)
QTimer.singleShot(15000, _maybe_fallback)
return
self._start_worker_scan(url, out, headful)
def _start_worker_scan(self, url: str, out: str, headful: bool) -> None:
signals = WorkerSignals()
signals.progress.connect(self.append_log)
signals.result.connect(self.handle_result)
signals.finished.connect(self.scan_finished)
try:
self.scan_button.setEnabled(False)
self.save_button.setEnabled(False)
except Exception:
pass
self._scan_in_progress = True
self.worker = ScanWorker(url, out, signals, headful=headful)
self.worker.start()
def _collect_items_live(self) -> None:
helper_js = r"""
(function(){
function visible(el){
const style = getComputedStyle(el);
if (style.visibility === 'hidden' || style.display === 'none') return false;
const r = el.getBoundingClientRect();
return r.width > 0 && r.height > 0;
}
function collectTabOrder(win){
const doc = win.document;
const selector = [
'a[href]','area[href]',
'input:not([disabled])','select:not([disabled])','textarea:not([disabled])',
'button:not([disabled])','iframe','audio[controls]','video[controls]',
'[contenteditable]','[tabindex]'
].join(',');
const nodes = Array.from(doc.querySelectorAll(selector)).filter(el=>{
const tiAttr = el.getAttribute('tabindex');
const ti = tiAttr !== null ? parseInt(tiAttr,10) : 0;
if (Number.isFinite(ti) && ti < 0) return false;
if (!visible(el)) return false;
return true;
});
const withPos = []; const deflt = [];
for (const el of nodes){
const tiAttr = el.getAttribute('tabindex');
const ti = tiAttr !== null ? parseInt(tiAttr,10) : 0;
if (ti > 0) withPos.push({el, ti}); else deflt.push({el, ti:0});
}
withPos.sort((a,b)=>a.ti - b.ti);
let order = withPos.concat(deflt).map(o=>o.el);
// Merge same-origin iframe contents immediately after the iframe itself
const merged = [];
for (const el of order){
merged.push(el);
try{
if (el.tagName && el.tagName.toLowerCase() === 'iframe'){
const cw = el.contentWindow;
if (cw && cw.document){
const inner = collectTabOrder(cw);
for (const ie of inner){ merged.push(ie); }
}
}
}catch(e){ /* cross-origin or access denied */ }
}
return merged;
}
window.__roBuildTabOrder = function(){
const order = collectTabOrder(window);
window.__roTabOrder = order;
const items = order.map(el=>{
const rect = el.getBoundingClientRect();
const role = el.getAttribute('role') || el.tagName.toLowerCase();
let name = el.getAttribute('aria-label') || '';
if (!name) name = (el.getAttribute('alt') || el.innerText || '').trim();
const ow = (el.ownerDocument && el.ownerDocument.defaultView) || window;
return {role, name, rect:{x: rect.left + (ow.scrollX||0), y: rect.top + (ow.scrollY||0), width: rect.width, height: rect.height}};
});
return items;
};
window.__roFocusIndex = function(i){
const els = window.__roTabOrder || [];
const el = els[i];
if (!el) return false;
try{ el.focus({preventScroll:false}); }catch(e){}
try{
const ow = (el.ownerDocument && el.ownerDocument.defaultView) || window;
el.scrollIntoView({behavior:'smooth', block:'center', inline:'nearest'});
// Determine if background is light or dark
const style = window.getComputedStyle(el);
const bgColor = style.backgroundColor;
let rgb = [255, 255, 255]; // default white
const rgbMatch = bgColor.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
if (rgbMatch) {
rgb = [parseInt(rgbMatch[1]), parseInt(rgbMatch[2]), parseInt(rgbMatch[3])];
}
// Calculate luminance: (0.299*R + 0.587*G + 0.114*B) / 255
const luminance = (0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]) / 255;
// Use dark green on light backgrounds, light blue on dark backgrounds
const outlineColor = luminance > 0.5 ? '#1B5E20' : '#64B5F6'; // dark green or light blue
const outlineStyle = `3px solid ${outlineColor}`;
const prev = (ow.document || document).querySelector('[data-ro-outline="1"]');
if (prev){ prev.removeAttribute('data-ro-outline'); prev.style.outline=''; }
el.setAttribute('data-ro-outline','1');
el.style.outline = outlineStyle;
setTimeout(()=>{ try{ el.style.outline = `3px dashed ${outlineColor}`; }catch(e){} }, 600);
}catch(e){}
return true;
};
return true;
})();
"""
def after_helpers(_ok: bool) -> None:
build_js = "window.__roBuildTabOrder && window.__roBuildTabOrder();"
if not self.webview:
return
self.webview.page().runJavaScript(build_js, handle_js_result)
def handle_js_result(result):
try:
items = result or []
self.current_items = items
self.current_index = -1
self.items_list.clear()
for i, it in enumerate(items, start=1):
self.items_list.addItem(f"{i}. [{it.get('role')}] {it.get('name')}")
self.append_log(f"Collected {len(items)} focusable items (keyboard order)")
# mark as delivered so fallback won't trigger
self._live_pending = False
# Re-enable buttons now that live collection finished
try:
self.scan_button.setEnabled(True)
self.save_button.setEnabled(True)
except Exception:
pass
self._scan_in_progress = False
# If nothing was found (likely iframe/shadow content), fallback to Playwright scan
if len(items) == 0:
try:
url = self.url_input.text().strip()
out = self.output_input.text().strip() or "reading_order_report.html"
headful = self.headful_checkbox.isChecked()
self.append_log("Live View: 0 items; running Playwright scan to populate list")
self._start_worker_scan(url, out, headful)
except Exception:
pass
else:
self.next_item()
except Exception as e:
self.append_log(f"JS result handling error: {e}")
if self.webview:
self.webview.page().runJavaScript(helper_js, after_helpers)
def handle_result(self, result: dict) -> None:
self.append_log(f"Handling scan result: {result}")
screenshot = result.get('screenshot')
json_path = result.get('json')
items = []
if json_path and os.path.exists(json_path):
try:
with open(json_path, 'r', encoding='utf-8') as jf:
data = json.load(jf)
items = data.get('dom_items', [])
self.append_log(f"Loaded {len(items)} items from JSON")
except Exception as e:
self.append_log(f"Failed to read sidecar JSON: {e}")
else:
self.append_log(f"JSON path not found: {json_path}")
if screenshot and os.path.exists(screenshot):
self.append_log(f"Displaying screenshot with {len(items)} items")
self._show_screenshot_with_items(screenshot, items)
else:
self.append_log(f"Screenshot not found: {screenshot}")
# Populate the items list even without screenshot
if items:
self.current_items = items
self.current_index = -1
self.items_list.clear()
for i, it in enumerate(items, start=1):
self.items_list.addItem(f"{i}. [{it.get('role', 'unknown')}] {it.get('name', 'unnamed')}")
self.append_log(f"Populated items list with {len(items)} items")
def _show_screenshot_with_items(self, image_path: str, items: list) -> None:
pix = QPixmap(image_path)
if pix.isNull():
self.append_log("Failed to load screenshot")
return
display = pix.scaled(QSize(900, 600), Qt.KeepAspectRatio, Qt.SmoothTransformation)
painter = QPainter(display)
painter.setRenderHint(QPainter.Antialiasing)
font = QFont('Sans', 10)
painter.setFont(font)
iw = pix.width(); ih = pix.height()
sw = display.width(); sh = display.height()
sx = sw / iw if iw else 1.0
sy = sh / ih if ih else 1.0
self.items_list.clear()
for idx, it in enumerate(items, start=1):
rect = it.get('rect', {})
x = int(rect.get('x', 0) * sx)
y = int(rect.get('y', 0) * sy)
w = int(rect.get('width', 0) * sx)
h = int(rect.get('height', 0) * sy)
painter.setBrush(QColor(0, 120, 215, 180))
painter.setPen(QColor('white'))
radius = max(12, min(28, int(min(max(8, w), max(8, h)) * 0.2)))
painter.drawEllipse(x, y, radius, radius)
painter.setPen(QColor('white'))
painter.drawText(x + 2, y + radius - 3, str(idx))
self.items_list.addItem(f"{idx}. [{it.get('role')}] {it.get('name')}")
painter.end()
if not self.webview:
self.image_label.setPixmap(display)
else:
try:
self.viewer_layout.removeWidget(self.webview)
except Exception:
pass
self.image_label = QLabel()
self.image_label.setPixmap(display)
self.viewer_layout.addWidget(self.image_label)
self.current_items = items
self.current_index = -1
def _install_shortcuts(self) -> None:
# create QShortcuts bound to the dialog (self)
QShortcut(QKeySequence("Alt+W"), self).activated.connect(self.choose_output)
QShortcut(QKeySequence("Ctrl+S"), self).activated.connect(lambda: (self.save_report(), self.append_log("Keyboard: Ctrl+S (Save)")))
QShortcut(QKeySequence("Alt+P"), self).activated.connect(lambda: (self.start_autoplay(), self.append_log("Keyboard: Alt+P (Play)")))
QShortcut(QKeySequence("Alt+O"), self).activated.connect(lambda: (self.stop_autoplay(), self.append_log("Keyboard: Alt+O (Stop)")))
QShortcut(QKeySequence("Alt+N"), self).activated.connect(lambda: (self.next_item(), self.append_log("Keyboard: Alt+N (Next)")))
QShortcut(QKeySequence("Alt+B"), self).activated.connect(lambda: (self.prev_item(), self.append_log("Keyboard: Alt+B (Previous)")))
QShortcut(QKeySequence("Alt+A"), self).activated.connect(lambda: (self.auto_refresh_button.toggle(), self.append_log("Keyboard: Alt+A (Toggle Auto-refresh)")))
QShortcut(QKeySequence("Alt+L"), self).activated.connect(lambda: (self.items_list.setFocus(), self.append_log("Keyboard: Alt+L (Focus list)")))
QShortcut(QKeySequence("Alt+G"), self).activated.connect(lambda: (self.log.setFocus(), self.append_log("Keyboard: Alt+G (Focus log)")))
def _highlight_in_live_view(self, index: int) -> None:
if not self.webview or index < 0 or index >= len(self.current_items):
return
js = f"window.__roFocusIndex && window.__roFocusIndex({index});"
self.webview.page().runJavaScript(js)
self.items_list.setCurrentRow(index)
def _highlight_in_screenshot(self, index: int) -> None:
self.items_list.setCurrentRow(index)
def _highlight_current(self) -> None:
if not self.current_items:
return
if self.webview and self.mode_live.isChecked():
self._highlight_in_live_view(self.current_index)
else:
self._highlight_in_screenshot(self.current_index)
def _flash_button(self, button: QPushButton) -> None:
"""Provide visual feedback by briefly changing button style when keyboard shortcut is used
Uses dark green on light colors and light blue on dark colors for better contrast"""
original_style = button.styleSheet()
# Determine if the current palette is light or dark by checking button palette
palette = button.palette()
text_color = palette.color(button.foregroundRole())
bg_color = palette.color(button.backgroundRole())
# Calculate luminance of background to determine if it's light or dark
# Formula: (0.299 * R + 0.587 * G + 0.114 * B) / 255
luminance = (0.299 * bg_color.red() + 0.587 * bg_color.green() + 0.114 * bg_color.blue()) / 255.0
# Use dark green on light backgrounds, light blue on dark backgrounds
if luminance > 0.5:
# Light background - use dark green
highlight_style = "QPushButton { background-color: #1B5E20; color: white; font-weight: bold; }"
else:
# Dark background - use light blue
highlight_style = "QPushButton { background-color: #64B5F6; color: black; font-weight: bold; }"
button.setStyleSheet(highlight_style)
QTimer.singleShot(200, lambda: button.setStyleSheet(original_style))
def _on_list_selection_changed(self, row: int) -> None:
if row is None or row < 0:
return
self.current_index = row
self._highlight_current()
def start_autoplay(self) -> None:
if not self.current_items:
return
self.play_timer.start()
self._flash_button(self.play_button)
def stop_autoplay(self) -> None:
self.play_timer.stop()
self._flash_button(self.pause_button)
def autoplay_step(self) -> None:
if not self.current_items:
return
self.current_index = (self.current_index + 1) % len(self.current_items)
self._highlight_current()
def next_item(self) -> None:
if not self.current_items:
return
self.current_index = (self.current_index + 1) % len(self.current_items)
self._highlight_current()
self._flash_button(self.next_button)
def prev_item(self) -> None:
if not self.current_items:
return
self.current_index = (self.current_index - 1) % len(self.current_items)
self._highlight_current()
self._flash_button(self.prev_button)
def _toggle_auto_refresh(self, checked: bool) -> None:
if checked:
self.refresh_timer.start()
else:
self.refresh_timer.stop()
def _toggle_auto_refresh_shortcut(self) -> None:
"""Toggle auto-refresh via keyboard shortcut"""
current_state = self.auto_refresh_button.isChecked()
self.auto_refresh_button.setChecked(not current_state)
self._flash_button(self.auto_refresh_button)
def _trigger_rescan(self) -> None:
self.append_log("Auto-refresh: re-scan")
self.start_scan()
def save_report(self) -> None:
# Run a background scan to generate a fresh HTML report
if self._scan_in_progress:
self.append_log("A scan is already in progress; please wait before saving.")
return
url = self.url_input.text().strip()
if not url:
self.append_log("Please enter a URL before saving the report.")
return
# Normalize URL
if not (url.startswith("http://") or url.startswith("https://")):
url = "http://" + url
out = self.output_input.text().strip() or "reading_order_report.html"
headful = self.headful_checkbox.isChecked()
signals = WorkerSignals()
signals.progress.connect(self.append_log)
signals.result.connect(lambda _res: self.append_log(f"Report saved to: {out}"))
signals.finished.connect(self.scan_finished)
self.append_log(f"Saving report: {url} -> {out}")
try:
self.scan_button.setEnabled(False)
self.save_button.setEnabled(False)
except Exception:
pass
self._scan_in_progress = True
worker = ScanWorker(url, out, signals, headful=headful)
worker.start()
def scan_finished(self, code: int) -> None:
try:
self.scan_button.setEnabled(True)
self.save_button.setEnabled(True)
except Exception:
pass
self._scan_in_progress = False
self.append_log(f"Scan finished ({code})")
def closeEvent(self, event) -> None: # type: ignore[override]
try:
self.play_timer.stop()
except Exception:
pass
try:
self.refresh_timer.stop()
except Exception:
pass
event.accept()
def main_gui(argv: list[str] | None = None) -> int:
app = QApplication(argv or sys.argv)
dlg = ReadingOrderDialog()
dlg.show()
return app.exec()
if __name__ == '__main__':
raise SystemExit(main_gui())