-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathcamera_config_dialog.py
More file actions
2055 lines (1771 loc) · 84.1 KB
/
camera_config_dialog.py
File metadata and controls
2055 lines (1771 loc) · 84.1 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_dialog.py
from __future__ import annotations
import copy
import logging
import cv2
from PySide6.QtCore import QEvent, Qt, QThread, QTimer, Signal
from PySide6.QtGui import QFont, QImage, QKeyEvent, QPixmap, QTextCursor
from PySide6.QtWidgets import (
QCheckBox,
QComboBox,
QDialog,
QDoubleSpinBox,
QFormLayout,
QGroupBox,
QHBoxLayout,
QLabel,
QListWidget,
QListWidgetItem,
QMessageBox,
QProgressBar,
QPushButton,
QScrollArea,
QSizePolicy,
QSpinBox,
QStyle,
QTextEdit,
QVBoxLayout,
QWidget,
)
from ..cameras import CameraFactory
from ..cameras.base import CameraBackend
from ..cameras.factory import DetectedCamera
from ..config import CameraSettings, MultiCameraSettings
from .misc.drag_spinbox import ScrubSpinBox
from .misc.eliding_label import ElidingPathLabel
from .misc.layouts import _make_two_field_row
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG) # TODO @C-Achard remove for release
def _apply_detected_identity(cam: CameraSettings, detected: DetectedCamera, backend: str) -> None:
"""Persist stable identity from a detected camera into cam.properties under backend namespace."""
if not isinstance(cam.properties, dict):
cam.properties = {}
ns = cam.properties.get(backend.lower())
if not isinstance(ns, dict):
ns = {}
cam.properties[backend.lower()] = ns
# Store whatever we have (backend-specific but written generically)
if getattr(detected, "device_id", None):
ns["device_id"] = detected.device_id
if getattr(detected, "vid", None) is not None:
ns["device_vid"] = int(detected.vid)
if getattr(detected, "pid", None) is not None:
ns["device_pid"] = int(detected.pid)
if getattr(detected, "path", None):
ns["device_path"] = detected.path
# Optional: store human name for matching fallback
if getattr(detected, "label", None):
ns["device_name"] = detected.label
# Optional: store backend_hint if you expose it (e.g., CAP_DSHOW)
if getattr(detected, "backend_hint", None) is not None:
ns["backend_hint"] = int(detected.backend_hint)
# -------------------------------
# Background worker to detect cameras
# -------------------------------
class DetectCamerasWorker(QThread):
"""Background worker to detect cameras for the selected backend."""
progress = Signal(str) # human-readable text
result = Signal(list) # list[DetectedCamera]
error = Signal(str)
finished = Signal()
def __init__(self, backend: str, max_devices: int = 10, parent: QWidget | None = None):
super().__init__(parent)
self.backend = backend
self.max_devices = max_devices
def run(self):
try:
# Initial message
self.progress.emit(f"Scanning {self.backend} cameras…")
cams = CameraFactory.detect_cameras(
self.backend,
max_devices=self.max_devices,
should_cancel=self.isInterruptionRequested,
progress_cb=self.progress.emit,
)
self.result.emit(cams)
except Exception as exc:
self.error.emit(f"{type(exc).__name__}: {exc}")
finally:
self.finished.emit()
class CameraProbeWorker(QThread):
"""Request a quick device probe (open/close) without starting preview."""
progress = Signal(str)
success = Signal(object) # emits CameraSettings
error = Signal(str)
finished = Signal()
def __init__(self, cam: CameraSettings, parent: QWidget | None = None):
super().__init__(parent)
self._cam = copy.deepcopy(cam)
self._cancel = False
# Enable fast_start when supported (backend reads namespace options)
if isinstance(self._cam.properties, dict):
ns = self._cam.properties.setdefault(self._cam.backend.lower(), {})
if isinstance(ns, dict):
ns.setdefault("fast_start", True)
def request_cancel(self):
self._cancel = True
def run(self):
try:
self.progress.emit("Probing device defaults…")
if self._cancel:
return
self.success.emit(self._cam)
except Exception as exc:
self.error.emit(f"{type(exc).__name__}: {exc}")
finally:
self.finished.emit()
# -------------------------------
# Singleton camera preview loader worker
# -------------------------------
class CameraLoadWorker(QThread):
"""Open/configure a camera backend off the UI thread with progress and cancel support."""
progress = Signal(str) # Human-readable status updates
success = Signal(object) # Emits the ready backend (CameraBackend)
error = Signal(str) # Emits error message
canceled = Signal() # Emits when canceled before success
def __init__(self, cam: CameraSettings, parent: QWidget | None = None):
super().__init__(parent)
self._cam = copy.deepcopy(cam)
self._cancel = False
self._backend: CameraBackend | None = None
# Do not use fast_start here as we want to actually open the camera to probe capabilities
# If you want a quick probe without full open, use CameraProbeWorker instead which sets fast_start=True
# Ensure preview open never uses fast_start probe mode
if isinstance(self._cam.properties, dict):
ns = self._cam.properties.setdefault(self._cam.backend.lower(), {})
if isinstance(ns, dict):
ns["fast_start"] = False
def request_cancel(self):
self._cancel = True
def _check_cancel(self) -> bool:
if self._cancel:
self.progress.emit("Canceled by user.")
return True
return False
def run(self):
try:
self.progress.emit("Creating backend…")
if self._check_cancel():
self.canceled.emit()
return
LOGGER.debug("Creating camera backend for %s:%d", self._cam.backend, self._cam.index)
self.progress.emit("Opening device…")
# Open only in GUI thread to avoid simultaneous opens
self.success.emit(self._cam)
except Exception as exc:
msg = f"{type(exc).__name__}: {exc}"
try:
if self._backend:
self._backend.close()
except Exception:
pass
self.error.emit(msg)
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()
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 = None
self.dlc_camera_id: str | None = None
# Actual/working camera settings
self._multi_camera_settings = multi_camera_settings
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_backend: CameraBackend | None = None
self._preview_timer: QTimer | None = None
self._preview_active: bool = False
self._preview_starting: bool = False
# Camera detection worker
self._scan_worker: DetectCamerasWorker | None = None
# Singleton loader per dialog
self._loader: CameraLoadWorker | None = None
self._loading_active: bool = False
# UI elements for eventFilter
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()
# -------------------------------
# Config helpers
# ------------------------------
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 _merge_backend_settings_back(self, opened_settings: CameraSettings) -> None:
"""Merge identity/index changes learned during preview open back into the working settings."""
if self._current_edit_index is None:
return
row = self._current_edit_index
if row < 0 or row >= len(self._working_settings.cameras):
return
target = self._working_settings.cameras[row]
# Update index if backend rebinding occurred
try:
target.index = int(opened_settings.index)
except Exception:
pass
if isinstance(opened_settings.properties, dict):
if not isinstance(target.properties, dict):
target.properties = {}
for k, v in opened_settings.properties.items():
if isinstance(v, dict) and isinstance(target.properties.get(k), dict):
target.properties[k].update(v)
else:
target.properties[k] = v
# Update UI list item text to reflect any changes
self._update_active_list_item(row, target)
# -------------------------------
# UI setup
# -------------------------------
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 _setup_ui(self) -> None:
# Main layout for the dialog
main_layout = QVBoxLayout(self)
# Horizontal layout for left and right panels
panels_layout = QHBoxLayout()
# Left panel: Camera list and controls
left_panel = QWidget()
left_layout = QVBoxLayout(left_panel)
# Active cameras list
active_group = QGroupBox("Active Cameras")
active_layout = QVBoxLayout(active_group)
self.active_cameras_list = QListWidget()
self.active_cameras_list.setMinimumWidth(250)
active_layout.addWidget(self.active_cameras_list)
# Buttons for managing active cameras
list_buttons = QHBoxLayout()
self.remove_camera_btn = QPushButton("Remove")
self.remove_camera_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TrashIcon))
self.remove_camera_btn.setEnabled(False)
self.move_up_btn = QPushButton("↑")
self.move_up_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_ArrowUp))
self.move_up_btn.setEnabled(False)
self.move_down_btn = QPushButton("↓")
self.move_down_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_ArrowDown))
self.move_down_btn.setEnabled(False)
list_buttons.addWidget(self.remove_camera_btn)
list_buttons.addWidget(self.move_up_btn)
list_buttons.addWidget(self.move_down_btn)
active_layout.addLayout(list_buttons)
left_layout.addWidget(active_group)
# Available cameras section
available_group = QGroupBox("Available Cameras")
available_layout = QVBoxLayout(available_group)
# Backend selection
backend_layout = QHBoxLayout()
backend_layout.addWidget(QLabel("Backend:"))
self.backend_combo = QComboBox()
availability = CameraFactory.available_backends()
for backend in CameraFactory.backend_names():
label = backend
if not availability.get(backend, True):
label = f"{backend} (unavailable)"
self.backend_combo.addItem(label, backend)
if self.backend_combo.count() == 0:
raise RuntimeError("No camera backends are registered!")
# Switch to first available backend
for i in range(self.backend_combo.count()):
backend = self.backend_combo.itemData(i)
if availability.get(backend, False):
self.backend_combo.setCurrentIndex(i)
break
backend_layout.addWidget(self.backend_combo)
self.refresh_btn = QPushButton("Refresh")
self.refresh_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_BrowserReload))
backend_layout.addWidget(self.refresh_btn)
available_layout.addLayout(backend_layout)
self.available_cameras_list = QListWidget()
available_layout.addWidget(self.available_cameras_list)
# Show status overlay during scan
self._scan_overlay = QLabel(available_group)
self._scan_overlay.setVisible(False)
self._scan_overlay.setAlignment(Qt.AlignCenter)
self._scan_overlay.setWordWrap(True)
self._scan_overlay.setStyleSheet(
"background-color: rgba(0, 0, 0, 140);color: white;padding: 12px;border: 1px solid #333;font-size: 12px;"
)
self._scan_overlay.setText("Discovering cameras…")
self.available_cameras_list.installEventFilter(self)
# Indeterminate progress bar + status text for async scan
self.scan_progress = QProgressBar()
self.scan_progress.setRange(0, 0)
self.scan_progress.setVisible(False)
available_layout.addWidget(self.scan_progress)
self.scan_cancel_btn = QPushButton("Cancel Scan")
self.scan_cancel_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_BrowserStop))
self.scan_cancel_btn.setVisible(False)
self.scan_cancel_btn.clicked.connect(self._on_scan_cancel)
available_layout.addWidget(self.scan_cancel_btn)
self.add_camera_btn = QPushButton("Add Selected Camera →")
self.add_camera_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_ArrowRight))
self.add_camera_btn.setEnabled(False)
available_layout.addWidget(self.add_camera_btn)
left_layout.addWidget(available_group)
# Right panel: Camera settings editor
right_panel = QWidget()
right_layout = QVBoxLayout(right_panel)
settings_group = QGroupBox("Camera Settings")
self.settings_form = QFormLayout(settings_group)
self.settings_form.setVerticalSpacing(6)
self.settings_form.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
# --- Basic toggles/labels ---
self.cam_enabled_checkbox = QCheckBox("Enabled")
self.cam_enabled_checkbox.setChecked(True)
self.settings_form.addRow(self.cam_enabled_checkbox)
self.cam_name_label = QLabel("Camera 0")
self.cam_name_label.setStyleSheet("font-weight: bold; font-size: 14px;")
self.settings_form.addRow("Name:", self.cam_name_label)
self.cam_device_name_label = ElidingPathLabel("")
self.cam_device_name_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
self.cam_device_name_label.setWordWrap(True)
self.settings_form.addRow("Device ID:", self.cam_device_name_label)
self.cam_index_label = QLabel("0")
# self.settings_form.addRow("Index:", self.cam_index_label)
self.cam_backend_label = QLabel("opencv")
# self.settings_form.addRow("Backend:", self.cam_backend_label)
id_backend_row = _make_two_field_row(
"Index:", self.cam_index_label, "Backend:", self.cam_backend_label, key_width=120, gap=15
)
self.settings_form.addRow(id_backend_row)
# --- Detected read-only labels (do NOT change requested values) ---
self.detected_resolution_label = QLabel("—")
self.detected_resolution_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
self.detected_fps_label = QLabel("—")
self.detected_fps_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
detected_row = _make_two_field_row(
"Detected resolution:",
self.detected_resolution_label,
"Detected FPS:",
self.detected_fps_label,
key_width=120,
gap=10,
)
self.settings_form.addRow(detected_row)
# --- Requested resolution controls (Auto = 0) ---
self.cam_width = QSpinBox()
self.cam_width.setRange(0, 10000)
self.cam_width.setValue(0)
self.cam_width.setSpecialValueText("Auto")
self.cam_height = QSpinBox()
self.cam_height.setRange(0, 10000)
self.cam_height.setValue(0)
self.cam_height.setSpecialValueText("Auto")
res_row = _make_two_field_row("W", self.cam_width, "H", self.cam_height, key_width=30)
self.settings_form.addRow("Resolution:", res_row)
# --- FPS + Rotation grouped (CREATE cam_rotation ONCE) ---
self.cam_fps = QDoubleSpinBox()
self.cam_fps.setRange(0.0, 240.0)
self.cam_fps.setDecimals(2)
self.cam_fps.setSingleStep(1.0)
self.cam_fps.setValue(0.0)
self.cam_fps.setSpecialValueText("Auto")
self.cam_rotation = QComboBox()
self.cam_rotation.addItem("0°", 0)
self.cam_rotation.addItem("90°", 90)
self.cam_rotation.addItem("180°", 180)
self.cam_rotation.addItem("270°", 270)
fps_rot_row = _make_two_field_row("FPS", self.cam_fps, "Rot", self.cam_rotation, key_width=30)
self.settings_form.addRow("Capture:", fps_rot_row)
# --- Exposure + Gain grouped ---
self.cam_exposure = QSpinBox()
self.cam_exposure.setRange(0, 1000000)
self.cam_exposure.setValue(0)
self.cam_exposure.setSpecialValueText("Auto")
self.cam_exposure.setSuffix(" μs")
self.cam_gain = QDoubleSpinBox()
self.cam_gain.setRange(0.0, 100.0)
self.cam_gain.setValue(0.0)
self.cam_gain.setSpecialValueText("Auto")
self.cam_gain.setDecimals(2)
exp_gain_row = _make_two_field_row("Exp", self.cam_exposure, "Gain", self.cam_gain, key_width=30)
self.settings_form.addRow("Analog:", exp_gain_row)
# --- Crop row (keep as you already have it) ---
crop_widget = QWidget()
crop_layout = QHBoxLayout(crop_widget)
crop_layout.setContentsMargins(0, 0, 0, 0)
self.cam_crop_x0 = ScrubSpinBox()
self.cam_crop_x0.setRange(0, 7680)
self.cam_crop_x0.setPrefix("x0:")
self.cam_crop_x0.setSpecialValueText("x0:None")
crop_layout.addWidget(self.cam_crop_x0)
self.cam_crop_y0 = ScrubSpinBox()
self.cam_crop_y0.setRange(0, 4320)
self.cam_crop_y0.setPrefix("y0:")
self.cam_crop_y0.setSpecialValueText("y0:None")
crop_layout.addWidget(self.cam_crop_y0)
self.cam_crop_x1 = ScrubSpinBox()
self.cam_crop_x1.setRange(0, 7680)
self.cam_crop_x1.setPrefix("x1:")
self.cam_crop_x1.setSpecialValueText("x1:None")
crop_layout.addWidget(self.cam_crop_x1)
self.cam_crop_y1 = ScrubSpinBox()
self.cam_crop_y1.setRange(0, 4320)
self.cam_crop_y1.setPrefix("y1:")
self.cam_crop_y1.setSpecialValueText("y1:None")
crop_layout.addWidget(self.cam_crop_y1)
self.settings_form.addRow("Crop:", crop_widget)
self.apply_settings_btn = QPushButton("Apply Settings")
self.apply_settings_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_DialogApplyButton))
self.apply_settings_btn.setEnabled(False)
# self.settings_form.addRow(self.apply_settings_btn)
self.reset_settings_btn = QPushButton("Reset Settings")
self.reset_settings_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_DialogResetButton))
self.reset_settings_btn.setEnabled(False)
# self.settings_form.addRow(self.reset_settings_btn)
sttgs_buttons_row = QWidget()
sttgs_button_layout = QHBoxLayout(sttgs_buttons_row)
sttgs_button_layout.setContentsMargins(0, 0, 0, 0)
sttgs_button_layout.setSpacing(8)
sttgs_button_layout.addWidget(self.apply_settings_btn)
sttgs_button_layout.addWidget(self.reset_settings_btn)
self.settings_form.addRow(sttgs_buttons_row)
self.preview_btn = QPushButton("Start Preview")
self.preview_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
self.preview_btn.setEnabled(False)
self.settings_form.addRow(self.preview_btn)
# ----------------------------
# Preview group
# ----------------------------
self.preview_group = QGroupBox("Camera Preview")
preview_layout = QVBoxLayout(self.preview_group)
self.preview_label = QLabel("No preview")
self.preview_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.preview_label.setMinimumSize(320, 240)
self.preview_label.setMaximumSize(400, 300)
self.preview_label.setStyleSheet("background-color: #1a1a1a; color: #888;")
preview_layout.addWidget(self.preview_label)
self.preview_label.installEventFilter(self)
self.preview_status = QTextEdit()
self.preview_status.setReadOnly(True)
self.preview_status.setFixedHeight(45)
self.preview_status.setStyleSheet(
"QTextEdit { background: #141414; color: #bdbdbd; border: 1px solid #2a2a2a; }"
)
font = QFont("Consolas")
font.setPointSize(9)
self.preview_status.setFont(font)
preview_layout.addWidget(self.preview_status)
self._loading_overlay = QLabel(self.preview_group)
self._loading_overlay.setVisible(False)
self._loading_overlay.setAlignment(Qt.AlignCenter)
self._loading_overlay.setStyleSheet("background-color: rgba(0,0,0,140); color: white; border: 1px solid #333;")
self._loading_overlay.setText("Loading camera…")
self.preview_group.setVisible(False)
# ----------------------------
# Scroll area to prevent squishing
# ----------------------------
scroll = QScrollArea()
# scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
scroll.setWidgetResizable(True)
scroll.setFrameShape(QScrollArea.NoFrame)
scroll_contents = QWidget()
scroll_contents.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
self._settings_scroll = scroll
self._settings_scroll_contents = scroll_contents
scroll_contents.setMinimumWidth(scroll.viewport().width())
scroll.viewport().installEventFilter(self)
scroll_layout = QVBoxLayout(scroll_contents)
scroll_layout.setContentsMargins(0, 0, 0, 10)
scroll_layout.setSpacing(10)
# Give groups a sane size policy; scroll handles overflow
settings_group.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
self.preview_group.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
scroll_layout.addWidget(settings_group)
scroll_layout.addWidget(self.preview_group)
scroll_layout.addStretch(1)
scroll.setWidget(scroll_contents)
right_layout.addWidget(scroll)
# Dialog buttons
sttgs_button_layout = QHBoxLayout()
self.ok_btn = QPushButton("OK")
self.ok_btn.setAutoDefault(False)
self.ok_btn.setDefault(False)
self.ok_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_DialogOkButton))
self.cancel_btn = QPushButton("Cancel")
self.cancel_btn.setAutoDefault(False)
self.cancel_btn.setDefault(False)
self.cancel_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_DialogCancelButton))
sttgs_button_layout.addStretch(1)
sttgs_button_layout.addWidget(self.ok_btn)
sttgs_button_layout.addWidget(self.cancel_btn)
# Add panels to horizontal layout
panels_layout.addWidget(left_panel, stretch=1)
panels_layout.addWidget(right_panel, stretch=1)
# Add everything to main layout
main_layout.addLayout(panels_layout)
main_layout.addLayout(sttgs_button_layout)
# Pressing enter on any settings field applies settings
self.cam_fps.setKeyboardTracking(False)
fields = [
self.cam_enabled_checkbox,
self.cam_width,
self.cam_height,
self.cam_fps,
self.cam_exposure,
self.cam_gain,
self.cam_crop_x0,
self.cam_crop_y0,
self.cam_crop_x1,
self.cam_crop_y1,
]
for field in fields:
if hasattr(field, "lineEdit"):
if hasattr(field.lineEdit(), "returnPressed"):
field.lineEdit().returnPressed.connect(self._apply_camera_settings)
if hasattr(field, "installEventFilter"):
field.installEventFilter(self)
# 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() == event.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 _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())
def _camera_identity_key(self, cam: CameraSettings) -> tuple:
backend = (cam.backend or "").lower()
props = cam.properties if isinstance(cam.properties, dict) else {}
ns = props.get(backend, {}) if isinstance(props, dict) else {}
device_id = ns.get("device_id")
# Prefer stable identity if present, otherwise fallback
if device_id:
return (backend, "device_id", device_id)
return (backend, "index", int(cam.index))
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("")
# -------------------------------
# Signals / population
# -------------------------------
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))
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())
self.cam_rotation.currentIndexChanged.connect(lambda _: self.apply_settings_btn.setEnabled(True))
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)
self._refresh_available_cameras()
self._update_button_states()
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 _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 _on_backend_changed(self, _index: int) -> None:
self._refresh_available_cameras()
def _is_backend_opencv(self, backend_name: str) -> bool:
return backend_name.lower() == "opencv"
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 _refresh_available_cameras(self) -> None:
"""Refresh the list of available cameras asynchronously."""
backend = self.backend_combo.currentData()
if not backend:
backend = self.backend_combo.currentText().split()[0]
# If already scanning, ignore new requests to avoid races
if getattr(self, "_scan_worker", None) and self._scan_worker.isRunning():
self._show_scan_overlay("Already discovering cameras…")
return
# Reset list UI and show progress
self.available_cameras_list.clear()
self._detected_cameras = []
msg = f"Discovering {backend} cameras…"
self._show_scan_overlay(msg)
self.scan_progress.setRange(0, 0)
self.scan_progress.setVisible(True)
self.scan_cancel_btn.setVisible(True)
self.add_camera_btn.setEnabled(False)
self.refresh_btn.setEnabled(False)
self.backend_combo.setEnabled(False)
# Start worker
self._scan_worker = DetectCamerasWorker(backend, max_devices=10, parent=self)
self._scan_worker.progress.connect(self._on_scan_progress)
self._scan_worker.result.connect(self._on_scan_result)
self._scan_worker.error.connect(self._on_scan_error)
self._scan_worker.finished.connect(self._on_scan_finished)
self.scan_started.emit(f"Scanning {backend} cameras…")
self._scan_worker.start()
def _on_scan_progress(self, msg: str) -> None:
self._show_scan_overlay(msg or "Discovering cameras…")
def _on_scan_result(self, cams: list) -> None:
self._detected_cameras = cams or []
self.available_cameras_list.clear() # replace list contents
if not self._detected_cameras:
placeholder = QListWidgetItem("No cameras detected.")
placeholder.setFlags(Qt.ItemIsEnabled)
self.available_cameras_list.addItem(placeholder)
return
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)
def _on_scan_error(self, msg: str) -> None:
QMessageBox.warning(self, "Camera Scan", f"Failed to detect cameras:\n{msg}")
def _on_scan_finished(self) -> None:
self._hide_scan_overlay()
self.scan_progress.setVisible(False)
self._scan_worker = None
self.scan_cancel_btn.setVisible(False)
self.scan_cancel_btn.setEnabled(True)
self.refresh_btn.setEnabled(True)
self.backend_combo.setEnabled(True)
self._update_button_states()
self.scan_finished.emit()
def _on_scan_cancel(self) -> None:
"""User requested to cancel discovery."""
if self._scan_worker and self._scan_worker.isRunning():
try:
self._scan_worker.requestInterruption()
except Exception:
pass
# Keep the busy bar, update texts
self._show_scan_overlay("Canceling discovery…")
self.scan_progress.setVisible(True) # stay visible as indeterminate
self.scan_cancel_btn.setEnabled(False)
def _on_available_camera_selected(self, row: int) -> None:
self.add_camera_btn.setEnabled(row >= 0)
def _on_available_camera_double_clicked(self, item: QListWidgetItem) -> None:
self._add_selected_camera()