-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreading_order_gui_fixed.py
More file actions
507 lines (433 loc) · 20.4 KB
/
reading_order_gui_fixed.py
File metadata and controls
507 lines (433 loc) · 20.4 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
from __future__ import annotations
import json
import os
import sys
import threading
from typing import Optional
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,
)
try:
from PySide6.QtWebEngineWidgets import QWebEngineView
WEBENGINE_AVAILABLE = True
except Exception:
QWebEngineView = None # type: ignore
WEBENGINE_AVAILABLE = False
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):
# Daemon thread ensures the app can close cleanly even if a scan is running
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)
class ReadingOrderDialog(QDialog):
def __init__(self, parent: Optional[QWidget] = None):
super().__init__(parent)
self.setWindowTitle("Reading Order Scanner")
self.resize(1200, 800)
# 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")
self.scan_button = QPushButton("Scan")
self.save_button = QPushButton("Save Report")
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(WEBENGINE_AVAILABLE)
if not WEBENGINE_AVAILABLE:
self.mode_live.setToolTip("QtWebEngine not available — will use screenshot fallback")
# Playback controls
self.play_button = QPushButton("&Play (Alt+P)") # Alt+P
self.pause_button = QPushButton("Stop (Alt+&A)") # Alt+A
self.next_button = QPushButton("&Next (Alt+N)") # Alt+N
self.prev_button = QPushButton("Previous (Alt+&B)") # Alt+B
self.auto_refresh_button = QPushButton("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: Optional[QWebEngineView] = None
if WEBENGINE_AVAILABLE:
self.webview = QWebEngineView()
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.setToolTip("List of focusable elements (Alt+L to focus)")
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)
# state
self.current_items: list = []
self.current_index: int = -1
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._navigate_live)
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)
# Keyboard shortcuts
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+A"), self)
self.shortcut_stop.activated.connect(lambda: (self.stop_autoplay(), self.append_log("Keyboard shortcut: Alt+A (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_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.worker: Optional[ScanWorker] = None
# initial live blank page
if self.mode_live.isChecked() and self.webview:
self.webview.setUrl(QUrl("about:blank"))
def append_log(self, text: str) -> None:
self.log.append(text)
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:
url = self.url_input.text().strip()
if not url:
self.append_log("Please enter a URL")
return
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:
if not (url.startswith("http://") or url.startswith("https://")):
url = "http://" + url
self.webview.setUrl(QUrl(url))
def on_load(_ok: bool):
self.append_log("Page loaded in live view; collecting items via JS (keyboard order)")
# Install helper functions and build keyboard (tab) order
self._collect_items_live()
try:
self.webview.loadFinished.disconnect(on_load)
except Exception:
pass
self.webview.loadFinished.connect(on_load)
return
# Configure worker signals and start background scan
signals = WorkerSignals()
signals.progress.connect(self.append_log)
signals.result.connect(self.handle_result)
signals.finished.connect(self.scan_finished)
# Disable the scan button while a scan is running
self.scan_button.setEnabled(False)
self.worker = ScanWorker(url, out, signals, headful=headful)
self.worker.start()
def _collect_items_live(self) -> None:
# Inject helpers that compute keyboard (Tab) order and provide a focus-by-index function
helper_js = r"""
(function(){
window.__roBuildTabOrder = function(){
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(',');
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;
}
const nodes = Array.from(document.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; // skip negative tabindex
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);
const order = withPos.concat(deflt).map(o=>o.el);
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();
return {role, name, rect:{x: rect.left + window.scrollX, y: rect.top + window.scrollY, 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{ el.scrollIntoView({behavior:'smooth', block:'center', inline:'nearest'}); }catch(e){}
try{
const prev = 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 = '3px solid orange';
setTimeout(()=>{ try{ el.style.outline = '3px dashed orange'; }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)")
self.next_item()
except Exception as e:
self.append_log(f"JS result handling error: {e}")
if self.webview:
# Inject helpers, then build the tab order and populate list
self.webview.page().runJavaScript(helper_js, after_helpers)
def handle_result(self, result: dict) -> None:
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', [])
except Exception as e:
self.append_log(f"Failed to read sidecar JSON: {e}")
if screenshot and os.path.exists(screenshot):
self._show_screenshot_with_items(screenshot, items)
else:
self.append_log("No screenshot to display")
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 _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 save_report(self) -> None:
# Trigger a background Playwright scan to generate the HTML report
url = self.url_input.text().strip()
if not url:
self.append_log("Please enter a URL before saving the report.")
return
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(lambda code: self.append_log(f"Save finished ({code})"))
self.append_log(f"Saving report: {url} -> {out}")
worker = ScanWorker(url, out, signals, headful=headful)
worker.start()
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 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()
# Provide visual feedback for keyboard navigation
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()
# Provide visual feedback for keyboard navigation
self._flash_button(self.prev_button)
def _flash_button(self, button: QPushButton) -> None:
"""Provide visual feedback by briefly changing button style"""
original_style = button.styleSheet()
button.setStyleSheet("QPushButton { background-color: #4CAF50; color: white; }")
# Reset style after a short delay
QTimer.singleShot(200, lambda: button.setStyleSheet(original_style))
def _toggle_auto_refresh(self, checked: bool) -> None:
if checked:
self.refresh_timer.start()
else:
self.refresh_timer.stop()
def _trigger_rescan(self) -> None:
self.append_log("Auto-refresh: re-scan")
self.start_scan()
def scan_finished(self, code: int) -> None:
# Re-enable the scan button and log the result
self.scan_button.setEnabled(True)
self.append_log(f"Scan finished ({code})")
def closeEvent(self, event) -> None: # type: ignore[override]
# Stop timers and let daemon worker threads exit on their own
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())