-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathcamera_config_dialog.py
More file actions
1589 lines (1347 loc) · 64.7 KB
/
camera_config_dialog.py
File metadata and controls
1589 lines (1347 loc) · 64.7 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
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Camera configuration dialog for multi-camera setup (with async preview loading)."""
# dlclivegui/gui/camera_config/camera_config_dialog.py
from __future__ import annotations
import copy
import logging
from PySide6.QtCore import QEvent, Qt, QTimer, Signal
from PySide6.QtGui import QKeyEvent, QTextCursor
from PySide6.QtWidgets import (
QDialog,
QListWidgetItem,
QMessageBox,
QScrollArea,
QStyle,
QWidget,
)
from ...cameras.factory import CameraFactory, DetectedCamera, apply_detected_identity, camera_identity_key
from ...config import CameraSettings, MultiCameraSettings
from .loaders import CameraLoadWorker, CameraProbeWorker, CameraScanState, DetectCamerasWorker
from .preview import PreviewSession, PreviewState, apply_crop, apply_rotation, resize_to_fit, to_display_pixmap
from .ui_blocks import setup_camera_config_dialog_ui
LOGGER = logging.getLogger(__name__)
class CameraConfigDialog(QDialog):
"""Dialog for configuring multiple cameras with async preview loading."""
MAX_CAMERAS = 4
settings_changed = Signal(object) # MultiCameraSettingsModel
# Camera discovery signals
scan_started = Signal(str)
scan_finished = Signal()
# -------------------------------
# Constructor, properties, Qt lifecycle
# -------------------------------
def __init__(
self,
parent: QWidget | None = None,
multi_camera_settings: MultiCameraSettings | None = None,
):
super().__init__(parent)
self.setWindowTitle("Configure Cameras")
self.setMinimumSize(960, 720)
self._dlc_camera_id: str | None = None
# self.dlc_camera_id: str | None = None
# Actual/working camera settings
self._multi_camera_settings = multi_camera_settings or MultiCameraSettings(cameras=[])
self._working_settings = self._multi_camera_settings.model_copy(deep=True)
self._detected_cameras: list[DetectedCamera] = []
self._probe_apply_to_requested: bool = False
self._probe_target_row: int | None = None
self._current_edit_index: int | None = None
self._suppress_selection_actions: bool = False
# Preview state
self._preview: PreviewSession = PreviewSession()
# Camera detection worker
self._scan_worker: DetectCamerasWorker | None = None
self._scan_state: CameraScanState = CameraScanState.IDLE
# UI elements for eventFilter (assigned in _setup_ui)
self._settings_scroll: QScrollArea | None = None
self._settings_scroll_contents: QWidget | None = None
self._setup_ui()
self._populate_from_settings()
self._connect_signals()
@property
def dlc_camera_id(self) -> str | None:
"""Get the currently selected DLC camera ID."""
return self._dlc_camera_id
@dlc_camera_id.setter
def dlc_camera_id(self, value: str | None) -> None:
"""Set the currently selected DLC camera ID."""
self._dlc_camera_id = value
self._refresh_camera_labels()
# Maintain overlay geometry when resizing
def resizeEvent(self, event):
super().resizeEvent(event)
if hasattr(self, "_loading_overlay") and self._loading_overlay.isVisible():
self._position_loading_overlay()
def eventFilter(self, obj, event):
# --- Keep scroll contents locked to viewport width (prevents horizontal scrolling/clipping) ---
if (
hasattr(self, "_settings_scroll")
and self._settings_scroll is not None
and obj is self._settings_scroll.viewport()
and event.type() == QEvent.Type.Resize
):
try:
if self._settings_scroll_contents is not None:
vw = self._settings_scroll.viewport().width()
# Set minimum width to viewport width to force wrapping/reflow instead of horizontal overflow
self._settings_scroll_contents.setMinimumWidth(vw)
except Exception:
pass
return False # allow normal processing
# Keep your existing overlay resize handling
if obj is self.available_cameras_list and event.type() == QEvent.Type.Resize:
if self._scan_overlay and self._scan_overlay.isVisible():
self._position_scan_overlay()
return super().eventFilter(obj, event)
# Intercept Enter in FPS and crop spinboxes
if event.type() == QEvent.KeyPress and isinstance(event, QKeyEvent):
if event.key() in (Qt.Key_Return, Qt.Key_Enter):
if obj in (
self.cam_fps,
self.cam_width,
self.cam_height,
self.cam_exposure,
self.cam_gain,
self.cam_crop_x0,
self.cam_crop_y0,
self.cam_crop_x1,
self.cam_crop_y1,
):
# Commit any pending text → value
try:
obj.interpretText()
except Exception:
pass
# Apply settings to persist crop/FPS to CameraSettings
self._apply_camera_settings()
# Consume so OK isn't triggered
return True
return super().eventFilter(obj, event)
def closeEvent(self, event):
"""Handle dialog close event to ensure cleanup."""
self._on_close_cleanup()
super().closeEvent(event)
def reject(self) -> None:
"""Handle dialog rejection (Cancel or close)."""
self._on_close_cleanup()
super().reject()
def _on_close_cleanup(self) -> None:
"""Stop preview, cancel workers, and reset scan UI. Safe to call multiple times."""
# Guard to avoid running twice if closeEvent + reject/accept both run
if getattr(self, "_cleanup_done", False):
return
self._cleanup_done = True
# Stop preview (loader + backend + timer)
try:
self._stop_preview()
except Exception:
LOGGER.exception("Cleanup: failed stopping preview")
# Cancel scan worker
sw = getattr(self, "_scan_worker", None)
if sw and sw.isRunning():
try:
sw.requestInterruption()
except Exception:
pass
# Keep this short to reduce UI freeze
sw.wait(300)
self._set_scan_state(CameraScanState.IDLE)
self._cleanup_scan_worker()
# Cancel probe worker
pw = getattr(self, "_probe_worker", None)
if pw and pw.isRunning():
try:
pw.request_cancel()
except Exception:
pass
pw.wait(300)
self._probe_worker = None
# Hide overlays / reset UI bits
try:
self._hide_scan_overlay()
except Exception:
pass
# Defensive: some widgets may not exist depending on UI setup timing
for w, visible, enabled in (
("scan_progress", False, None),
("scan_cancel_btn", False, True),
("refresh_btn", None, True),
("backend_combo", None, True),
):
widget = getattr(self, w, None)
if widget is None:
continue
if visible is not None:
widget.setVisible(visible)
if enabled is not None:
widget.setEnabled(enabled)
try:
self._sync_scan_ui()
except Exception:
pass
# -------------------------------
# UI setup
# -------------------------------
def _setup_ui(self) -> None:
setup_camera_config_dialog_ui(self)
def _position_scan_overlay(self) -> None:
"""Position scan overlay to cover the available_cameras_list area."""
if not self._scan_overlay or not self.available_cameras_list:
return
parent = self._scan_overlay.parent() # available_group
top_left = self.available_cameras_list.mapTo(parent, self.available_cameras_list.rect().topLeft())
rect = self.available_cameras_list.rect()
self._scan_overlay.setGeometry(top_left.x(), top_left.y(), rect.width(), rect.height())
def _show_scan_overlay(self, message: str = "Discovering cameras…") -> None:
self._scan_overlay.setText(message)
self._scan_overlay.setVisible(True)
self._position_scan_overlay()
def _hide_scan_overlay(self) -> None:
self._scan_overlay.setVisible(False)
def _position_loading_overlay(self):
# Cover just the preview image area (label), not the whole group
if not self.preview_label:
return
gp = self.preview_label.mapTo(self.preview_group, self.preview_label.rect().topLeft())
rect = self.preview_label.rect()
self._loading_overlay.setGeometry(gp.x(), gp.y(), rect.width(), rect.height())
# -------------------------------
# Signal setup
# -------------------------------
def _connect_signals(self) -> None:
self.backend_combo.currentIndexChanged.connect(self._on_backend_changed)
self.refresh_btn.clicked.connect(self._refresh_available_cameras)
self.add_camera_btn.clicked.connect(self._add_selected_camera)
self.remove_camera_btn.clicked.connect(self._remove_selected_camera)
self.move_up_btn.clicked.connect(self._move_camera_up)
self.move_down_btn.clicked.connect(self._move_camera_down)
self.active_cameras_list.currentRowChanged.connect(self._on_active_camera_selected)
self.available_cameras_list.currentRowChanged.connect(self._on_available_camera_selected)
self.available_cameras_list.itemDoubleClicked.connect(self._on_available_camera_double_clicked)
self.apply_settings_btn.clicked.connect(self._apply_camera_settings)
self.reset_settings_btn.clicked.connect(self._reset_selected_camera)
self.preview_btn.clicked.connect(self._toggle_preview)
self.ok_btn.clicked.connect(self._on_ok_clicked)
self.cancel_btn.clicked.connect(self.reject)
self.scan_started.connect(lambda _: setattr(self, "_dialog_active", True))
self.scan_finished.connect(lambda: setattr(self, "_dialog_active", False))
self.scan_cancel_btn.clicked.connect(self.request_scan_cancel)
def _mark_dirty(*_args):
self.apply_settings_btn.setEnabled(True)
self._set_apply_dirty(True)
for sb in (
self.cam_fps,
self.cam_crop_x0,
self.cam_crop_y0,
self.cam_crop_x1,
self.cam_crop_y1,
self.cam_exposure,
self.cam_gain,
self.cam_width,
self.cam_height,
):
if hasattr(sb, "valueChanged"):
sb.valueChanged.connect(_mark_dirty)
self.cam_rotation.currentIndexChanged.connect(lambda *_: _mark_dirty())
self.cam_enabled_checkbox.stateChanged.connect(lambda *_: _mark_dirty())
# -------------------------------
# UI state updates
# -------------------------------
def _set_apply_dirty(self, dirty: bool) -> None:
"""Visually mark Apply Settings button as 'dirty' (pending edits)."""
if dirty:
self.apply_settings_btn.setText("Apply Settings *")
self.apply_settings_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MessageBoxWarning))
self.apply_settings_btn.setToolTip("You have unapplied changes. Click to apply them.")
else:
self.apply_settings_btn.setText("Apply Settings")
self.apply_settings_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_DialogApplyButton))
self.apply_settings_btn.setToolTip("")
def _update_button_states(self) -> None:
scan_running = self._is_scan_running()
active_row = self.active_cameras_list.currentRow()
has_active_selection = active_row >= 0
allow_structure_edits = has_active_selection and not scan_running
self.remove_camera_btn.setEnabled(allow_structure_edits)
self.move_up_btn.setEnabled(allow_structure_edits and active_row > 0)
self.move_down_btn.setEnabled(allow_structure_edits and active_row < self.active_cameras_list.count() - 1)
# During loading, preview button becomes "Cancel Loading"
self.preview_btn.setEnabled(has_active_selection or self._preview.state == PreviewState.LOADING)
available_row = self.available_cameras_list.currentRow()
self.add_camera_btn.setEnabled(available_row >= 0 and not scan_running)
def _sync_preview_ui(self) -> None:
"""Update buttons/overlays based on preview state only."""
st = self._preview.state
if st == PreviewState.LOADING:
self._set_preview_button_loading(True)
self.preview_btn.setEnabled(True)
self.preview_group.setVisible(True)
elif st == PreviewState.ACTIVE:
self._set_preview_button_loading(False)
self.preview_btn.setText("Stop Preview")
self.preview_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaStop))
self.preview_btn.setEnabled(True)
self.preview_group.setVisible(True)
else: # IDLE / STOPPING / ERROR
self._set_preview_button_loading(False)
self.preview_btn.setText("Start Preview")
self.preview_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
self.preview_btn.setEnabled(self.active_cameras_list.currentRow() >= 0)
self.preview_group.setVisible(False)
self._update_button_states()
def _set_detected_labels(self, cam: CameraSettings) -> None:
"""Update the read-only detected labels based on cam.properties[backend]."""
backend = (cam.backend or "").lower()
props = cam.properties if isinstance(cam.properties, dict) else {}
ns = props.get(backend, {}) if isinstance(props.get(backend, None), dict) else {}
det_res = ns.get("detected_resolution")
det_fps = ns.get("detected_fps")
if isinstance(det_res, (list, tuple)) and len(det_res) == 2:
try:
w, h = int(det_res[0]), int(det_res[1])
self.detected_resolution_label.setText(f"{w}×{h}")
except Exception:
self.detected_resolution_label.setText("—")
else:
self.detected_resolution_label.setText("—")
if isinstance(det_fps, (int, float)) and float(det_fps) > 0:
self.detected_fps_label.setText(f"{float(det_fps):.2f}")
else:
self.detected_fps_label.setText("—")
def _refresh_camera_labels(self) -> None:
cam_list = getattr(self, "active_cameras_list", None)
if not cam_list:
return
cam_list.blockSignals(True) # prevent unwanted selection change events during update
try:
for i in range(cam_list.count()):
item = cam_list.item(i)
cam = item.data(Qt.ItemDataRole.UserRole)
if cam:
item.setText(self._format_camera_label(cam, i))
finally:
cam_list.blockSignals(False)
def _format_camera_label(self, cam: CameraSettings, index: int = -1) -> str:
status = "✓" if cam.enabled else "○"
this_id = f"{cam.backend}:{cam.index}"
dlc_indicator = " [DLC]" if this_id == self._dlc_camera_id and cam.enabled else ""
return f"{status} {cam.name} [{cam.backend}:{cam.index}]{dlc_indicator}"
def _update_active_list_item(self, row: int, cam: CameraSettings) -> None:
"""Refresh the active camera list row text and color."""
item = self.active_cameras_list.item(row)
if not item:
return
self._suppress_selection_actions = True # prevent unwanted selection change events during update
try:
item.setText(self._format_camera_label(cam, row))
item.setData(Qt.ItemDataRole.UserRole, cam)
item.setForeground(Qt.GlobalColor.gray if not cam.enabled else Qt.GlobalColor.black)
self._refresh_camera_labels()
self._update_button_states()
finally:
self._suppress_selection_actions = False
def _update_controls_for_backend(self, backend_name: str) -> None:
backend_key = (backend_name or "opencv").lower()
caps = CameraFactory.backend_capabilities(backend_key)
def apply(widget, feature: str, label: str, *, allow_best_effort: bool = True):
level = caps.get(feature, None)
if level is None:
widget.setEnabled(False)
widget.setToolTip(f"{label} is not supported by this backend.")
return
if level.value == "unsupported":
widget.setEnabled(False)
widget.setToolTip(f"{label} is not supported by the {backend_key} backend.")
elif level.value == "best_effort":
widget.setEnabled(bool(allow_best_effort))
widget.setToolTip(f"{label} is best-effort in {backend_key}. Some cameras/drivers may ignore it.")
else: # supported
widget.setEnabled(True)
widget.setToolTip("")
# Resolution controls
apply(self.cam_width, "set_resolution", "Resolution")
apply(self.cam_height, "set_resolution", "Resolution")
# FPS
apply(self.cam_fps, "set_fps", "Frame rate")
# Exposure / Gain
apply(self.cam_exposure, "set_exposure", "Exposure")
apply(self.cam_gain, "set_gain", "Gain")
def _set_preview_button_loading(self, loading: bool) -> None:
if loading:
self.preview_btn.setText("Cancel Loading")
self.preview_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_BrowserStop))
else:
self.preview_btn.setText("Start Preview")
self.preview_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
def _show_loading_overlay(self, message: str) -> None:
self._loading_overlay.setText(message)
self._loading_overlay.setVisible(True)
self._position_loading_overlay()
def _hide_loading_overlay(self) -> None:
self._loading_overlay.setVisible(False)
def _append_status(self, text: str) -> None:
LOGGER.debug(f"Preview status: {text}")
self.preview_status.append(text)
self.preview_status.moveCursor(QTextCursor.End)
self.preview_status.ensureCursorVisible()
# -------------------------------
# Camera discovery and probing
# -------------------------------
def _on_backend_changed(self, _index: int) -> None:
self._refresh_available_cameras()
def _is_scan_running(self) -> bool:
return self._scan_state in (CameraScanState.RUNNING, CameraScanState.CANCELING)
def _set_scan_state(self, state: CameraScanState, message: str | None = None) -> None:
"""Single source of truth for scan-related UI controls."""
self._scan_state = state
scanning = state in (CameraScanState.RUNNING, CameraScanState.CANCELING)
# Overlay message
if scanning:
self._show_scan_overlay(
message or ("Canceling discovery…" if state == CameraScanState.CANCELING else "Discovering cameras…")
)
else:
self._hide_scan_overlay()
# Progress + cancel controls
self.scan_progress.setVisible(scanning)
if scanning:
self.scan_progress.setRange(0, 0) # indeterminate
self.scan_cancel_btn.setVisible(scanning)
self.scan_cancel_btn.setEnabled(state == CameraScanState.RUNNING) # disabled while canceling
# Disable discovery inputs while scanning
self.backend_combo.setEnabled(not scanning)
self.refresh_btn.setEnabled(not scanning)
# Available list + add flow blocked while scanning (structure edits disallowed)
self.available_cameras_list.setEnabled(not scanning)
self.add_camera_btn.setEnabled(False if scanning else (self.available_cameras_list.currentRow() >= 0))
self._update_button_states()
def _cleanup_scan_worker(self) -> None:
# worker is truly finished now
w = self._scan_worker
self._scan_worker = None
if w is not None:
w.deleteLater()
def _finish_scan(self, reason: str) -> None:
"""Mark scan UX complete (idempotent) and emit scan_finished queued."""
if self._scan_state in (CameraScanState.DONE, CameraScanState.IDLE):
return
# Transition scan UX to DONE (UI controls restored)
self._set_scan_state(CameraScanState.DONE)
QTimer.singleShot(0, self.scan_finished.emit)
LOGGER.debug("[Scan] finished reason=%s", reason)
def _refresh_available_cameras(self) -> None:
"""Refresh the list of available cameras asynchronously."""
backend = self.backend_combo.currentData() or self.backend_combo.currentText().split()[0]
if self._is_scan_running():
self._show_scan_overlay("Already discovering cameras…")
return
# Reset UI/list
self.available_cameras_list.clear()
self._detected_cameras = []
self._set_scan_state(CameraScanState.RUNNING, message=f"Discovering {backend} cameras…")
# Start worker
w = DetectCamerasWorker(backend, max_devices=10, parent=self)
self._scan_worker = w
w.progress.connect(self._on_scan_progress)
w.result.connect(self._on_scan_result)
w.error.connect(self._on_scan_error)
w.canceled.connect(self._on_scan_canceled)
# Cleanup only
w.finished.connect(self._cleanup_scan_worker)
self.scan_started.emit(f"Scanning {backend} cameras…")
w.start()
def _on_scan_progress(self, msg: str) -> None:
if self._scan_state not in (CameraScanState.RUNNING, CameraScanState.CANCELING):
return
self._show_scan_overlay(msg or "Discovering cameras…")
def _on_scan_result(self, cams: list) -> None:
if self._scan_state not in (CameraScanState.RUNNING, CameraScanState.CANCELING):
return
# Apply results to UI first (stability guarantee)
self._detected_cameras = cams or []
self.available_cameras_list.clear()
if not self._detected_cameras:
placeholder = QListWidgetItem("No cameras detected.")
placeholder.setFlags(Qt.ItemIsEnabled)
self.available_cameras_list.addItem(placeholder)
else:
for cam in self._detected_cameras:
item = QListWidgetItem(f"{cam.label} (index {cam.index})")
item.setData(Qt.ItemDataRole.UserRole, cam)
self.available_cameras_list.addItem(item)
self.available_cameras_list.setCurrentRow(0)
# Now UI is stable: finish scan UX and emit scan_finished queued
self._finish_scan("result")
def _on_scan_error(self, msg: str) -> None:
if self._scan_state not in (CameraScanState.RUNNING, CameraScanState.CANCELING):
return
QMessageBox.warning(self, "Camera Scan", f"Failed to detect cameras:\n{msg}")
# Ensure UI is stable (list is stable even if empty) before finishing
if self.available_cameras_list.count() == 0:
placeholder = QListWidgetItem("Scan failed.")
placeholder.setFlags(Qt.ItemIsEnabled)
self.available_cameras_list.addItem(placeholder)
self._finish_scan("error")
def request_scan_cancel(self) -> None:
if not self._is_scan_running():
return
self._set_scan_state(CameraScanState.CANCELING, message="Canceling discovery…")
w = self._scan_worker
if w is not None:
try:
w.requestInterruption()
except Exception:
pass
# Guarantee UI stability before scan_finished:
if self.available_cameras_list.count() == 0:
placeholder = QListWidgetItem("Scan canceled.")
placeholder.setFlags(Qt.ItemIsEnabled)
self.available_cameras_list.addItem(placeholder)
self._finish_scan("cancel")
def _on_scan_canceled(self) -> None:
self._set_scan_state(CameraScanState.CANCELING, message="Finalizing cancellation…")
# If cancel is requested without clicking cancel (e.g., dialog closing), ensure UI finishes
if self._scan_state in (CameraScanState.RUNNING, CameraScanState.CANCELING):
if self.available_cameras_list.count() == 0:
placeholder = QListWidgetItem("Scan canceled.")
placeholder.setFlags(Qt.ItemIsEnabled)
self.available_cameras_list.addItem(placeholder)
self._finish_scan("canceled")
def _on_available_camera_selected(self, row: int) -> None:
if self._scan_worker and self._scan_worker.isRunning():
self.add_camera_btn.setEnabled(False)
return
self.add_camera_btn.setEnabled(row >= 0 and not self._is_scan_running())
def _on_available_camera_double_clicked(self, item: QListWidgetItem) -> None:
if self._is_scan_running():
return
self._add_selected_camera()
# -------------------------------
# Active camera selection and list
# -------------------------------
def _on_active_camera_selected(self, row: int) -> None:
if getattr(self, "_suppress_selection_actions", False):
LOGGER.debug("[Selection] Suppressed currentRowChanged event at index %d.", row)
return
prev_row = self._current_edit_index
LOGGER.debug(
"[Select] row=%s prev=%s preview_state=%s",
row,
prev_row,
self._preview.state,
)
if row is None or row < 0:
LOGGER.debug(
"[Selection] row<0 (selection cleared) ignored to avoid"
" stopping preview/loading when clicking away. row=%s",
row,
)
return
# If row is the same, ignore
if prev_row is not None and prev_row == row:
LOGGER.debug("[Selection] Redundant currentRowChanged to same index %d; ignoring.", row)
return
# If switching away from a previous camera, commit pending edits first
if prev_row is not None and prev_row != row:
if not self._commit_pending_edits(reason="before switching camera selection"):
# Revert selection back to previous row so the user stays on the invalid camera
try:
self.active_cameras_list.blockSignals(True)
self.active_cameras_list.setCurrentRow(prev_row)
finally:
self.active_cameras_list.blockSignals(False)
return
# Stop any running preview when selection changes
if self._preview.state in (PreviewState.ACTIVE, PreviewState.LOADING):
self._stop_preview()
self._current_edit_index = row
self._update_button_states()
if row < 0 or row >= self.active_cameras_list.count():
self._clear_settings_form()
return
item = self.active_cameras_list.item(row)
cam = item.data(Qt.ItemDataRole.UserRole)
if cam:
self.apply_settings_btn.setEnabled(True)
self.reset_settings_btn.setEnabled(True)
self._load_camera_to_form(cam)
self._start_probe_for_camera(cam, apply_to_requested=False)
def _add_selected_camera(self) -> None:
if not self._commit_pending_edits(reason="before adding a new camera"):
return
row = self.available_cameras_list.currentRow()
if row < 0:
return
# limit check
active_count = len(
[
i
for i in range(self.active_cameras_list.count())
if self.active_cameras_list.item(i).data(Qt.ItemDataRole.UserRole).enabled
]
)
if active_count >= self.MAX_CAMERAS:
QMessageBox.warning(self, "Maximum Cameras", f"Maximum of {self.MAX_CAMERAS} active cameras allowed.")
return
item = self.available_cameras_list.item(row)
detected = item.data(Qt.ItemDataRole.UserRole)
# make sure this is to lower for comparison against camera_identity_key
backend = (self.backend_combo.currentData() or "opencv").lower()
det_key = None
if getattr(detected, "device_id", None):
det_key = (backend, "device_id", detected.device_id)
else:
det_key = (backend, "index", int(detected.index))
for i in range(self.active_cameras_list.count()):
existing_cam = self.active_cameras_list.item(i).data(Qt.ItemDataRole.UserRole)
if camera_identity_key(existing_cam) == det_key:
QMessageBox.warning(self, "Duplicate Camera", "This camera is already in the active list.")
return
new_cam = CameraSettings(
name=detected.label,
index=detected.index,
width=0,
height=0,
fps=0.0,
backend=backend,
exposure=0,
gain=0.0,
enabled=True,
properties={},
)
apply_detected_identity(new_cam, detected, backend)
self._working_settings.cameras.append(new_cam)
new_index = len(self._working_settings.cameras) - 1
new_item = QListWidgetItem(self._format_camera_label(new_cam, new_index))
new_item.setData(Qt.ItemDataRole.UserRole, new_cam)
self.active_cameras_list.addItem(new_item)
self.active_cameras_list.setCurrentItem(new_item)
self._refresh_camera_labels()
self._update_button_states()
self._start_probe_for_camera(new_cam)
def _remove_selected_camera(self) -> None:
if not self._commit_pending_edits(reason="before removing a camera"):
return
row = self.active_cameras_list.currentRow()
if row < 0:
return
self.active_cameras_list.takeItem(row)
if row < len(self._working_settings.cameras):
del self._working_settings.cameras[row]
self._current_edit_index = None
self._clear_settings_form()
self._refresh_camera_labels()
self._update_button_states()
def _move_camera_up(self) -> None:
if not self._commit_pending_edits(reason="before reordering cameras"):
return
row = self.active_cameras_list.currentRow()
if row <= 0:
return
item = self.active_cameras_list.takeItem(row)
self.active_cameras_list.insertItem(row - 1, item)
self.active_cameras_list.setCurrentRow(row - 1)
cams = self._working_settings.cameras
cams[row], cams[row - 1] = cams[row - 1], cams[row]
self._refresh_camera_labels()
def _move_camera_down(self) -> None:
if not self._commit_pending_edits(reason="before reordering cameras"):
return
row = self.active_cameras_list.currentRow()
if row < 0 or row >= self.active_cameras_list.count() - 1:
return
item = self.active_cameras_list.takeItem(row)
self.active_cameras_list.insertItem(row + 1, item)
self.active_cameras_list.setCurrentRow(row + 1)
cams = self._working_settings.cameras
cams[row], cams[row + 1] = cams[row + 1], cams[row]
self._refresh_camera_labels()
# -------------------------------
# Form/model mapping & settings application
# -------------------------------
def _build_model_from_form(self, base: CameraSettings) -> CameraSettings:
# construct a dict from form widgets; Pydantic will coerce/validate
payload = base.model_dump()
payload.update(
{
"enabled": bool(self.cam_enabled_checkbox.isChecked()),
"width": int(self.cam_width.value()),
"height": int(self.cam_height.value()),
"fps": float(self.cam_fps.value()),
"exposure": int(self.cam_exposure.value()) if self.cam_exposure.isEnabled() else 0,
"gain": float(self.cam_gain.value()) if self.cam_gain.isEnabled() else 0.0,
"rotation": int(self.cam_rotation.currentData() or 0),
"crop_x0": int(self.cam_crop_x0.value()),
"crop_y0": int(self.cam_crop_y0.value()),
"crop_x1": int(self.cam_crop_x1.value()),
"crop_y1": int(self.cam_crop_y1.value()),
}
)
# Validate and coerce; if invalid, Pydantic will raise
return CameraSettings.model_validate(payload)
def _load_camera_to_form(self, cam: CameraSettings) -> None:
block = [
self.cam_enabled_checkbox,
self.cam_width,
self.cam_height,
self.cam_fps,
self.cam_exposure,
self.cam_gain,
self.cam_rotation,
self.cam_crop_x0,
self.cam_crop_y0,
self.cam_crop_x1,
self.cam_crop_y1,
]
for widget in block:
if hasattr(widget, "blockSignals"):
widget.blockSignals(True)
try:
backend = (cam.backend or "").lower()
props = cam.properties if isinstance(cam.properties, dict) else {}
ns = props.get(backend, {}) if isinstance(props, dict) else {}
self.cam_enabled_checkbox.setChecked(cam.enabled)
self.cam_name_label.setText(cam.name)
self.cam_device_name_label.setText(str(ns.get("device_id", "")))
self.cam_index_label.setText(str(cam.index))
self.cam_backend_label.setText(cam.backend)
self._update_controls_for_backend(cam.backend)
self.cam_width.setValue(cam.width)
self.cam_height.setValue(cam.height)
self.cam_fps.setValue(cam.fps)
self.cam_exposure.setValue(cam.exposure)
self.cam_gain.setValue(cam.gain)
rot_index = self.cam_rotation.findData(cam.rotation)
if rot_index >= 0:
self.cam_rotation.setCurrentIndex(rot_index)
self.cam_crop_x0.setValue(cam.crop_x0)
self.cam_crop_y0.setValue(cam.crop_y0)
self.cam_crop_x1.setValue(cam.crop_x1)
self.cam_crop_y1.setValue(cam.crop_y1)
self.apply_settings_btn.setEnabled(True)
self._set_detected_labels(cam)
finally:
for widget in block:
if hasattr(widget, "blockSignals"):
widget.blockSignals(False)
self.apply_settings_btn.setEnabled(False)
self._set_apply_dirty(False)
def _write_form_to_cam(self, cam: CameraSettings) -> None:
cam.enabled = bool(self.cam_enabled_checkbox.isChecked())
cam.width = int(self.cam_width.value())
cam.height = int(self.cam_height.value())
cam.fps = float(self.cam_fps.value())
cam.exposure = int(self.cam_exposure.value() if self.cam_exposure.isEnabled() else 0)
cam.gain = float(self.cam_gain.value() if self.cam_gain.isEnabled() else 0.0)
cam.rotation = int(self.cam_rotation.currentData() or 0)
cam.crop_x0 = int(self.cam_crop_x0.value())
cam.crop_y0 = int(self.cam_crop_y0.value())
cam.crop_x1 = int(self.cam_crop_x1.value())
cam.crop_y1 = int(self.cam_crop_y1.value())
def _commit_pending_edits(self, *, reason: str = "") -> bool:
"""
Auto-apply pending edits (if any) before context-changing actions.
Returns True if it's safe to proceed, False if validation failed.
"""
# No selection → nothing to commit
if self._current_edit_index is None or self._current_edit_index < 0:
return True
# If Apply button isn't enabled, assume no pending edits
if not self.apply_settings_btn.isEnabled():
return True
try:
self._append_status(f"[Auto-Apply] Committing pending edits ({reason})…")
ok = self._apply_camera_settings()
return bool(ok)
except Exception as exc:
# _apply_camera_settings already shows a QMessageBox in many cases,
# but we add a clear guardrail here in case it doesn't.
QMessageBox.warning(
self,
"Unsaved / Invalid Settings",
"Your current camera settings are not valid and cannot be applied yet.\n\n"
"Please fix the highlighted fields (e.g. crop rectangle) or press Reset.\n\n"
f"Details: {exc}",
)
return False
def _apply_camera_settings(self) -> bool:
try:
for sb in (
self.cam_fps,
self.cam_crop_x0,
self.cam_width,
self.cam_height,
self.cam_exposure,
self.cam_gain,
self.cam_crop_y0,
self.cam_crop_x1,
self.cam_crop_y1,
):
try:
if hasattr(sb, "interpretText"):
sb.interpretText()
except Exception:
pass
if self._current_edit_index is None:
return True
row = self._current_edit_index
if row < 0 or row >= len(self._working_settings.cameras):
return True
current_model = self._working_settings.cameras[row]
new_model = self._build_model_from_form(current_model)
diff = CameraSettings.check_diff(current_model, new_model)
self._working_settings.cameras[row] = new_model
self._update_active_list_item(row, new_model)
LOGGER.debug(
"[Apply] backend=%s idx=%s changes=%s",
getattr(new_model, "backend", None),
getattr(new_model, "index", None),
diff,
)
# --- Persist validated model back BEFORE touching preview ---
self._working_settings.cameras[row] = new_model
self._update_active_list_item(row, new_model)
# Decide whether we need to restart preview (fast UX)
old_settings = None
if self._preview.backend and isinstance(getattr(self._preview.backend, "settings", None), CameraSettings):
old_settings = self._preview.backend.settings
else:
old_settings = current_model
restart = False
should_consider_restart = self._preview.state == PreviewState.ACTIVE and isinstance(
old_settings, CameraSettings
)
if should_consider_restart:
restart = self._should_restart_preview(old_settings, new_model)
LOGGER.debug(
"[Apply] preview_state=%s restart=%s backend=%s idx=%s",
self._preview.state,
restart,
new_model.backend,
new_model.index,
)
if self._preview.state == PreviewState.ACTIVE and restart:
self._append_status("[Apply] Restarting preview to apply camera settings changes.")
self._request_preview_restart(new_model, reason="apply-settings")
self.apply_settings_btn.setEnabled(False)
self._set_apply_dirty(False)
return True
except Exception as exc:
LOGGER.exception("Apply camera settings failed")
QMessageBox.warning(self, "Apply Settings Error", str(exc))
return False
def _clear_settings_form(self) -> None:
self.cam_enabled_checkbox.setChecked(True)
self.cam_name_label.setText("")
self.cam_device_name_label.setText("")
self.cam_index_label.setText("")
self.cam_backend_label.setText("")
self.detected_resolution_label.setText("—")
self.detected_fps_label.setText("—")
self.cam_width.setValue(0)
self.cam_height.setValue(0)
self.cam_fps.setValue(0.0)
self.cam_exposure.setValue(0)
self.cam_gain.setValue(0.0)
self.cam_rotation.setCurrentIndex(0)
self.cam_crop_x0.setValue(0)
self.cam_crop_y0.setValue(0)
self.cam_crop_x1.setValue(0)
self.cam_crop_y1.setValue(0)
self.apply_settings_btn.setEnabled(False)
self.reset_settings_btn.setEnabled(False)
def _populate_from_settings(self) -> None:
"""Populate the dialog from existing settings."""
self.active_cameras_list.clear()
for i, cam in enumerate(self._working_settings.cameras):
item = QListWidgetItem(self._format_camera_label(cam, i))
item.setData(Qt.ItemDataRole.UserRole, cam)
if not cam.enabled:
item.setForeground(Qt.GlobalColor.gray)
self.active_cameras_list.addItem(item)