summaryrefslogtreecommitdiff
path: root/ui/windows/channels_window.py
blob: cc83b3bccd6a53862519f5c242d768e2f960cc60 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
"""
ui/windows/channels_window.py

CHANNELS window — toolbar section 3.

Layout (QSplitter, horizontal):
  Physical Channels  — per-channel filter pipeline; add/remove channels,
                       configure filters (moving average, low-pass, etc.),
                       math ops (derivative, integral), calibrate.
  Virtual Channels   — create derived channels (RMS, power, difference,
                       sum, Python expression/script, etc.)

Classes:
  ChannelsWindow        — top-level floating window
  PipelineTab           — splitter content (physical + virtual sections)
  ChannelPipelineBlock  — collapsible filter+math stack for one physical channel
  ChannelPickerDialog   — checkbox dialog for selecting channels to add
  ChannelBlock          — editor for one virtual/derived channel
  FilterRow             — single filter stage row inside a pipeline block
  SignalsListTab        — unused; kept for profile-load compatibility
"""

from __future__ import annotations
import re
from typing import List, Optional, Set, Tuple

from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
    QScrollArea, QFrame, QComboBox, QLineEdit,
    QDoubleSpinBox, QSpinBox, QCheckBox, QTextEdit, QGroupBox,
    QToolButton, QSplitter, QDialog, QDialogButtonBox,
)
from PyQt6.QtCore import Qt, pyqtSignal
from PyQt6.QtGui import QCloseEvent, QFont, QFontMetrics

from devices.device_registry import DeviceRegistry
from core.signal_processor import (
    SignalProcessor, ChannelPipeline, Channel,
    FilterBase, FILTER_CLASSES,
)
from ui.windows.plot_window import _DragHandle, _DragReorderContainer

_DERIVED_COLORS = [
    "#f72585","#7209b7","#4361ee","#4cc9f0",
    "#f77f00","#d62828","#588157","#e9c46a",
]

_FILTER_KEYS = [k for k in FILTER_CLASSES if k not in ("derivative", "integral", "scale_offset")]
_MATH_KEYS   = ["derivative", "integral"]


def _channel_display_name(registry: DeviceRegistry,
                          processor: Optional[SignalProcessor],
                          dev_id: str, ch_id: str) -> str:
    """Return human display name for a source; falls back to ch_id."""
    if dev_id == "derived" and processor:
        for dc in processor.get_derived():
            if dc.channel_id == ch_id:
                return dc.name
    else:
        for dev in registry.all_instances():
            if dev.info.device_id == dev_id:
                for ch in dev.info.signals:
                    if ch.signal_id == ch_id:
                        return ch.name if ch.name else ch_id
    return ch_id


def _channel_combo(registry: DeviceRegistry,
                   processor: Optional[SignalProcessor] = None,
                   include_derived: bool = False,
                   show_unit: bool = False) -> QComboBox:
    cb = QComboBox(); cb.setObjectName("channelPickerCb")
    for dev in registry.all_instances():
        for ch in dev.info.signals:
            if not ch.enabled:
                continue
            label = f"Signal: {ch.name}  ({dev.info.device_id}/{ch.signal_id})"
            if show_unit and ch.unit:
                label += f"  [{ch.unit}]"
            cb.addItem(label, userData=(dev.info.device_id, ch.signal_id))
    if include_derived and processor:
        for dc in processor.get_derived():
            label = f"Channel: {dc.channel_id}  ({dc.name})"
            if show_unit and dc.unit:
                label += f"  [{dc.unit}]"
            cb.addItem(label, userData=("derived", dc.channel_id))
    return cb


# ══════════════════════════════════════════════════════════════════════════════
#  Channel Picker Dialog
# ══════════════════════════════════════════════════════════════════════════════

class ChannelPickerDialog(QDialog):
    def __init__(self, registry: DeviceRegistry,
                 already_shown: Set[Tuple[str, str]], parent=None):
        super().__init__(parent)
        self.setWindowTitle("Add Channels")
        self.setMinimumWidth(380)
        self.resize(420, 320)
        self._checks: List[Tuple[QCheckBox, str, str]] = []

        lay = QVBoxLayout(self)

        scroll = QScrollArea(); scroll.setWidgetResizable(True)
        scroll.setObjectName("deviceScroll")
        cont = QWidget()
        cl = QVBoxLayout(cont); cl.setContentsMargins(8, 8, 8, 8); cl.setSpacing(4)

        any_available = False
        for dev in registry.all_instances():
            for ch in dev.info.signals:
                if not ch.enabled:
                    continue
                if (dev.info.device_id, ch.signal_id) in already_shown:
                    continue
                any_available = True
                label = f"{ch.name}  ({dev.info.device_id}/{ch.signal_id})"
                if ch.unit:
                    label += f"  [{ch.unit}]"
                chk = QCheckBox(label)
                self._checks.append((chk, dev.info.device_id, ch.signal_id))
                cl.addWidget(chk)

        if not any_available:
            cl.addWidget(QLabel("No additional signals available."))

        cl.addStretch()
        scroll.setWidget(cont)
        lay.addWidget(scroll, 1)

        btns = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
        )
        btns.accepted.connect(self.accept)
        btns.rejected.connect(self.reject)
        lay.addWidget(btns)

    def selected(self) -> List[Tuple[str, str]]:
        return [(d, c) for chk, d, c in self._checks if chk.isChecked()]


# ══════════════════════════════════════════════════════════════════════════════
#  Filter row
# ══════════════════════════════════════════════════════════════════════════════

_PARAM_SPECS = {
    "moving_average": [("window", "int",   10,   1,  5000)],
    "median":         [("window", "int",    5,   1,   500)],
    "low_pass":       [("alpha",  "float", 0.1, 0.001, 1.0)],
    "high_pass":      [("alpha",  "float", 0.9, 0.001, 1.0)],
    "scale_offset":   [("scale",  "float", 1.0, -1e6, 1e6),
                       ("offset", "float", 0.0, -1e9, 1e9)],
    "derivative":     [],
    "integral":       [],
}

class FilterRow(QFrame):
    removed = pyqtSignal(object)
    changed = pyqtSignal()

    def __init__(self, filt: FilterBase):
        super().__init__()
        self.filt = filt
        self.setObjectName("traceRow")
        self._build()

    def _build(self):
        lay = QHBoxLayout(self); lay.setContentsMargins(6, 4, 6, 4); lay.setSpacing(8)

        lbl = QLabel(self.filt.name.replace("_", " ").title())
        lbl.setObjectName("traceSource"); lbl.setMinimumWidth(120)
        lay.addWidget(lbl)

        for pname, ptype, default, lo, hi in _PARAM_SPECS.get(self.filt.name, []):
            pl = QLabel(f"{pname}:"); pl.setObjectName("pwmLabel")
            lay.addWidget(pl)
            if ptype == "int":
                w = QSpinBox(); w.setRange(int(lo), int(hi))
                w.setValue(int(self.filt.params.get(pname, default)))
                w.setFixedWidth(70); w.setObjectName("traceWidthSpin")
                w.valueChanged.connect(lambda v, p=pname: self._upd(p, v))
            else:
                w = QDoubleSpinBox(); w.setRange(lo, hi); w.setDecimals(4)
                w.setValue(float(self.filt.params.get(pname, default)))
                w.setFixedWidth(88); w.setObjectName("traceWidthSpin")
                w.valueChanged.connect(lambda v, p=pname: self._upd(p, v))
            lay.addWidget(w)

        lay.addStretch()
        rm = QToolButton(); rm.setText("✕"); rm.setObjectName("traceRemoveBtn")
        rm.setFixedSize(22, 22); rm.clicked.connect(lambda: self.removed.emit(self))
        lay.addWidget(rm)

    def _upd(self, name, value):
        self.filt.params[name] = value
        cls = FILTER_CLASSES.get(self.filt.name)
        if cls:
            nf = cls(**self.filt.params); self.filt.__dict__.update(nf.__dict__)
        self.changed.emit()


# monkey-patch QLabel.also for inline objectName
from PyQt6.QtWidgets import QLabel as _QLabel
def _also(self, fn): fn(self); return self
_QLabel.also = _also


# ══════════════════════════════════════════════════════════════════════════════
#  Channel Pipeline Block — collapsible filter+math stack for one channel
# ══════════════════════════════════════════════════════════════════════════════

class ChannelPipelineBlock(QFrame):
    changed = pyqtSignal()
    removed = pyqtSignal(object)

    def __init__(self, dev_id: str, ch_id: str, ch_name: str, unit: str,
                 processor: SignalProcessor, show_calibration: bool = True,
                 show_header: bool = True):
        super().__init__()
        self.dev_id    = dev_id
        self.ch_id     = ch_id
        self.processor = processor
        self._filter_rows: List[FilterRow] = []
        self._cal_rows:    List[FilterRow] = []
        self._cur_pipeline: Optional[ChannelPipeline] = None
        self._expanded = False
        self._show_calibration = show_calibration
        self._show_header      = show_header
        self.setObjectName("plotBlock")
        self._build(ch_name, unit)
        self._load()

    def _build(self, ch_name: str, unit: str):
        self._ch_name = ch_name
        self._unit = unit
        outer = QVBoxLayout(self); outer.setContentsMargins(0, 0, 0, 0); outer.setSpacing(0)

        # Header (omitted when embedded in another block, e.g. ChannelBlock's
        # Filters section — the parent already provides a header/toggle)
        if self._show_header:
            hdr = QWidget(); hdr.setObjectName("plotBlockHeader"); hdr.setFixedHeight(32)
            hl  = QHBoxLayout(hdr); hl.setContentsMargins(8, 0, 6, 0)
            title = f"{ch_name}  ({self.dev_id}/{self.ch_id})"
            if unit:
                title += f"  [{unit}]"
            self._title_lbl = QLabel(title); self._title_lbl.setObjectName("traceSource")
            hl.addWidget(self._title_lbl, 1)

            rm_btn = QToolButton(); rm_btn.setText("✕")
            rm_btn.setObjectName("traceRemoveBtn"); rm_btn.setFixedSize(22, 22)
            rm_btn.clicked.connect(lambda: self.removed.emit(self))
            hl.addWidget(rm_btn)

            self._toggle_btn = QToolButton(); self._toggle_btn.setText("▶")
            self._toggle_btn.setObjectName("traceRemoveBtn"); self._toggle_btn.setFixedSize(22, 22)
            self._toggle_btn.clicked.connect(self._toggle)
            hl.addWidget(self._toggle_btn)
            outer.addWidget(hdr)
            hdr.mousePressEvent = lambda e: self._toggle()

        # Body
        self._body = QWidget(); self._body.setObjectName("plotBlockSettings")
        bl = QVBoxLayout(self._body)
        bl.setContentsMargins(10, 8, 10, 10); bl.setSpacing(6)

        # ── Filters section ───────────────────────────────────────────────────
        filt_lbl = QLabel("Filters"); filt_lbl.setObjectName("pwmLabel")
        bl.addWidget(filt_lbl)

        self._filter_area = QWidget()
        self._filter_lay  = QVBoxLayout(self._filter_area)
        self._filter_lay.setContentsMargins(0, 0, 0, 0); self._filter_lay.setSpacing(3)
        bl.addWidget(self._filter_area)

        filt_add_bar = QHBoxLayout()
        self._filt_cb = QComboBox(); self._filt_cb.setObjectName("channelPickerCb")
        self._filt_cb.addItems([k.replace("_", " ").title() for k in _FILTER_KEYS])
        filt_add_bar.addWidget(self._filt_cb, 1)
        filt_add_btn = QPushButton("+ Add Filter"); filt_add_btn.setObjectName("addTraceBtn")
        filt_add_btn.clicked.connect(self._add_filter)
        filt_add_bar.addWidget(filt_add_btn)
        bl.addLayout(filt_add_bar)

        div = QFrame(); div.setFrameShape(QFrame.Shape.HLine)
        div.setObjectName("devWindowDivider")
        bl.addWidget(div)

        # ── Calibration section — hidden when embedded (calibration is now
        #    configured as a Channel "Scale/Offset" Operation instead), but the
        #    widgets still exist so a legacy scale_offset filter already saved
        #    on this pipeline (from an older profile) is preserved by _push()
        #    rather than silently dropped the next time a filter is edited.
        self._cal_area = QWidget()
        self._cal_lay  = QVBoxLayout(self._cal_area)
        self._cal_lay.setContentsMargins(0, 0, 0, 0); self._cal_lay.setSpacing(3)
        if self._show_calibration:
            cal_lbl = QLabel("Calibration"); cal_lbl.setObjectName("pwmLabel")
            bl.addWidget(cal_lbl)
            bl.addWidget(self._cal_area)

            cal_add_bar = QHBoxLayout()
            cal_add_btn = QPushButton("+ Add Calibration"); cal_add_btn.setObjectName("addTraceBtn")
            cal_add_btn.clicked.connect(self._add_calibrate)
            cal_add_bar.addWidget(cal_add_btn)
            cal_add_bar.addStretch()
            bl.addLayout(cal_add_bar)

        ap_row = QHBoxLayout(); ap_row.addStretch()
        ap_btn = QPushButton("✓  Apply"); ap_btn.setObjectName("applyButton")
        ap_btn.clicked.connect(self._push)
        ap_row.addWidget(ap_btn)
        bl.addLayout(ap_row)

        outer.addWidget(self._body)
        self._body.setVisible(self._show_header is False)
        self._expanded = not self._show_header

    def _refresh_title(self):
        if not self._show_header:
            return
        title = f"{self._ch_name}  ({self.dev_id}/{self.ch_id})"
        if self._unit:
            title += f"  [{self._unit}]"
        self._title_lbl.setText(title)

    def update_name(self, ch_name: str):
        self._ch_name = ch_name
        self._refresh_title()

    def update_unit(self, unit: str):
        self._unit = unit
        self._refresh_title()

    def _toggle(self):
        self._expanded = not self._expanded
        self._body.setVisible(self._expanded)
        self._toggle_btn.setText("▼" if self._expanded else "▶")

    def _load(self):
        pipeline = self.processor.get_pipeline(self.dev_id, self.ch_id)
        if pipeline is None:
            pipeline = ChannelPipeline(device_id=self.dev_id, channel_id=self.ch_id)
            self.processor.set_pipeline(pipeline)
        self._cur_pipeline = pipeline
        pipeline.enabled = True
        for f in pipeline.filters:
            if f.name == "scale_offset":
                self._add_cal_row(f)
            elif f.name not in _MATH_KEYS:
                self._add_filter_row(f)

    def _add_calibrate(self):
        filt = FILTER_CLASSES["scale_offset"]()
        self._add_cal_row(filt)
        self._push()
        if not self._expanded:
            self._toggle()

    def _add_filter(self):
        key  = _FILTER_KEYS[self._filt_cb.currentIndex()]
        filt = FILTER_CLASSES[key]()
        self._add_filter_row(filt)
        self._push()

    def _add_filter_row(self, filt: FilterBase):
        row = FilterRow(filt)
        row.removed.connect(self._remove_row)
        row.changed.connect(self._push)
        self._filter_rows.append(row)
        self._filter_lay.addWidget(row)

    def _add_cal_row(self, filt: FilterBase):
        row = FilterRow(filt)
        row.removed.connect(self._remove_row)
        row.changed.connect(self._push)
        self._cal_rows.append(row)
        self._cal_lay.addWidget(row)

    def _remove_row(self, row: FilterRow):
        if row in self._filter_rows:
            self._filter_rows.remove(row)
            self._filter_lay.removeWidget(row)
        elif row in self._cal_rows:
            self._cal_rows.remove(row)
            self._cal_lay.removeWidget(row)
        row.deleteLater()
        self._push()

    def _push(self):
        if self._cur_pipeline:
            self._cur_pipeline.filters = (
                [r.filt for r in self._filter_rows] +
                [r.filt for r in self._cal_rows]
            )
            self.processor.set_pipeline(self._cur_pipeline)
        self.changed.emit()


# ══════════════════════════════════════════════════════════════════════════════
#  Pipeline Tab — filter pipelines per channel + virtual channel creation
# ══════════════════════════════════════════════════════════════════════════════

class PipelineTab(QWidget):
    changed         = pyqtSignal()
    derived_changed = pyqtSignal()
    channel_renamed = pyqtSignal(str, str, str, str)  # old_dev, old_id, new_dev, new_id

    def __init__(self, registry: DeviceRegistry, processor: SignalProcessor):
        super().__init__()
        self.registry        = registry
        self.processor       = processor
        self._shown:  Set[Tuple[str, str]]                       = set()
        self._blocks: dict[Tuple[str, str], ChannelPipelineBlock] = {}
        self._derived_blocks: List[ChannelBlock] = []
        self._color_idx = 0
        self._build()

    def _build(self):
        root = QVBoxLayout(self); root.setContentsMargins(0, 0, 0, 0); root.setSpacing(0)

        splitter = QSplitter(Qt.Orientation.Horizontal)
        splitter.setObjectName("channelSplitter")
        root.addWidget(splitter)

        # ── Physical Channels pane ─────────────────────────────────────────────
        phys_w = QWidget()
        phys_l = QVBoxLayout(phys_w); phys_l.setContentsMargins(0, 0, 0, 0); phys_l.setSpacing(0)

        phys_bar = QWidget(); phys_bar.setObjectName("cfgGlobalBar")
        pb_lay = QHBoxLayout(phys_bar); pb_lay.setContentsMargins(10, 7, 10, 7); pb_lay.setSpacing(6)
        pb_lbl = QLabel("Signals"); pb_lbl.setObjectName("devWindowTitle")
        pb_lay.addWidget(pb_lbl)
        self._src_cb = _channel_combo(self.registry, self.processor, include_derived=True)
        self._src_cb.setObjectName("channelPickerCb")
        self._src_cb.insertItem(0, "Signal: none (empty channel)", userData=None)
        self._src_cb.setCurrentIndex(0)
        pb_lay.addWidget(self._src_cb, 1)
        add_virt = QPushButton("+ New Channel"); add_virt.setObjectName("addTraceBtn")
        add_virt.setToolTip("Create a Channel from the selected Signal")
        add_virt.clicked.connect(self._add_virtual)
        pb_lay.addWidget(add_virt)
        add_btn = QPushButton("+ Add"); add_btn.setObjectName("addTraceBtn")
        add_btn.setToolTip("Add an existing Signal to this list")
        add_btn.clicked.connect(self._on_add_channel)
        pb_lay.addWidget(add_btn)
        phys_l.addWidget(phys_bar)

        div1 = QFrame(); div1.setFrameShape(QFrame.Shape.HLine)
        div1.setObjectName("devWindowDivider"); phys_l.addWidget(div1)

        phys_scroll = QScrollArea(); phys_scroll.setWidgetResizable(True)
        phys_scroll.setObjectName("deviceScroll")
        phys_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self._phys_cont = QWidget()
        self._phys_inner = QVBoxLayout(self._phys_cont)
        self._phys_inner.setContentsMargins(10, 10, 10, 10); self._phys_inner.setSpacing(6)
        self._phys_inner.addStretch()
        phys_scroll.setWidget(self._phys_cont)
        phys_l.addWidget(phys_scroll, 1)
        splitter.addWidget(phys_w)

        # ── Virtual Channels pane ──────────────────────────────────────────────
        virt_w = QWidget()
        virt_l = QVBoxLayout(virt_w); virt_l.setContentsMargins(0, 0, 0, 0); virt_l.setSpacing(0)

        virt_bar = QWidget(); virt_bar.setObjectName("cfgGlobalBar")
        vb_lay = QHBoxLayout(virt_bar); vb_lay.setContentsMargins(10, 7, 10, 7); vb_lay.setSpacing(6)
        vb_lbl = QLabel("Channels"); vb_lbl.setObjectName("devWindowTitle")
        vb_lay.addWidget(vb_lbl, 1)
        virt_l.addWidget(virt_bar)

        div2 = QFrame(); div2.setFrameShape(QFrame.Shape.HLine)
        div2.setObjectName("devWindowDivider"); virt_l.addWidget(div2)

        virt_scroll = QScrollArea(); virt_scroll.setWidgetResizable(True)
        virt_scroll.setObjectName("deviceScroll")
        virt_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self._virt_cont = _DragReorderContainer(self)
        self._virt_inner = QVBoxLayout(self._virt_cont)
        self._virt_inner.setContentsMargins(10, 10, 10, 10); self._virt_inner.setSpacing(6)
        self._virt_inner.addStretch()
        virt_scroll.setWidget(self._virt_cont)
        virt_l.addWidget(virt_scroll, 1)
        splitter.addWidget(virt_w)

        splitter.setStretchFactor(0, 0)
        splitter.setStretchFactor(1, 1)

        def _init_split():
            min_w = splitter.widget(0).minimumSizeHint().width()
            w = max(min_w, 280)
            splitter.setSizes([w, max(1, splitter.width() - w)])

        from PyQt6.QtCore import QTimer
        QTimer.singleShot(0, _init_split)

        for dev in self.registry.all_instances():
            for ch in dev.info.signals:
                if ch.enabled:
                    self._add_block(dev.info.device_id, ch.signal_id, ch.name, ch.unit)

    # ── Physical channel block management ──────────────────────────────────────

    def _add_block(self, dev_id: str, ch_id: str, ch_name: str, unit: str):
        if (dev_id, ch_id) in self._shown:
            return
        self._shown.add((dev_id, ch_id))
        block = ChannelPipelineBlock(dev_id, ch_id, ch_name, unit, self.processor)
        block.changed.connect(self.changed)
        block.removed.connect(self._on_remove_block)
        self._blocks[(dev_id, ch_id)] = block
        self._phys_inner.insertWidget(self._phys_inner.count() - 1, block)

    def on_channel_enabled_changed(self, dev_id: str, ch_id: str, enabled: bool):
        key = (dev_id, ch_id)
        if enabled:
            if key not in self._shown:
                dev = self.registry.get_instance(dev_id)
                if dev:
                    ch = dev.get_signal(ch_id)
                    if ch:
                        self._add_block(dev_id, ch_id, ch.name, ch.unit)
            else:
                block = self._blocks.get(key)
                if block:
                    block.setVisible(True)
        else:
            block = self._blocks.get(key)
            if block:
                block.setVisible(False)

    def on_device_removed(self, dev_id: str):
        keys = [(d, c) for (d, c) in list(self._shown) if d == dev_id]
        for key in keys:
            block = self._blocks.get(key)
            if block:
                self._on_remove_block(block)
        self._refresh_src_cb()
        for blk in self._derived_blocks:
            blk.refresh_missing_sources()

    def on_device_reconfigured(self, dev_id: str):
        dev = self.registry.get_instance(dev_id)
        if dev is None:
            self.on_device_removed(dev_id)
            return
        valid = {ch.signal_id for ch in dev.info.signals}
        keys = [(d, c) for (d, c) in list(self._shown)
                if d == dev_id and c not in valid]
        for key in keys:
            block = self._blocks.get(key)
            if block:
                self._on_remove_block(block)
        self._refresh_src_cb()
        for blk in self._derived_blocks:
            blk.refresh_missing_sources()

    def on_device_added(self):
        self._refresh_src_cb()

    def on_channel_name_changed(self, dev_id: str, ch_id: str, ch_name: str):
        key = (dev_id, ch_id)
        if key in self._blocks:
            self._blocks[key].update_name(ch_name)
        else:
            dev = self.registry.get_instance(dev_id)
            if dev:
                ch = dev.get_signal(ch_id)
                if ch and ch.enabled:
                    self._add_block(dev_id, ch_id, ch_name, ch.unit)
        self._refresh_src_cb()

    def on_channel_unit_changed(self, dev_id: str, ch_id: str, unit: str):
        key = (dev_id, ch_id)
        if key in self._blocks:
            self._blocks[key].update_unit(unit)

    def _refresh_src_cb(self):
        """Rebuild the 'Source: …' picker at the top of the Channels pane —
        it's a persistent combo (not a dialog), so it must be kept in sync
        whenever devices/channels are added, removed, or renamed, not just
        built once at construction time."""
        current = self._src_cb.currentData()
        self._src_cb.blockSignals(True)
        self._src_cb.clear()
        self._src_cb.insertItem(0, "Signal: none (empty channel)", userData=None)
        for dev in self.registry.all_instances():
            for ch in dev.info.signals:
                if not ch.enabled:
                    continue
                label = f"Signal: {ch.name}  ({dev.info.device_id}/{ch.signal_id})"
                self._src_cb.addItem(label, userData=(dev.info.device_id, ch.signal_id))
        for dc in self.processor.get_derived():
            label = f"Channel: {dc.channel_id}  ({dc.name})"
            self._src_cb.addItem(label, userData=("derived", dc.channel_id))
        if current:
            for i in range(self._src_cb.count()):
                if self._src_cb.itemData(i) == current:
                    self._src_cb.setCurrentIndex(i)
                    break
            else:
                self._src_cb.setCurrentIndex(0)
        else:
            self._src_cb.setCurrentIndex(0)
        self._src_cb.blockSignals(False)

    def _on_add_channel(self):
        dlg = ChannelPickerDialog(self.registry, self._shown, self)
        if dlg.exec() != QDialog.DialogCode.Accepted:
            return
        for dev_id, ch_id in dlg.selected():
            dev = self.registry.get_instance(dev_id)
            if not dev:
                continue
            ch = dev.get_signal(ch_id)
            if not ch:
                continue
            self._add_block(dev_id, ch_id, ch.name, ch.unit)

    def _on_remove_block(self, block: ChannelPipelineBlock):
        key = (block.dev_id, block.ch_id)
        self._shown.discard(key)
        self._blocks.pop(key, None)
        self._phys_inner.removeWidget(block)
        block.deleteLater()

    # ── Virtual channel management ─────────────────────────────────────────────

    def _add_virtual(self):
        color = _DERIVED_COLORS[self._color_idx % len(_DERIVED_COLORS)]
        self._color_idx += 1
        existing_names = {d.name for d in self.processor.get_derived()}
        existing_ids   = {d.channel_id for d in self.processor.get_derived()}
        # Pre-seed the source picked in the bar above, if any — otherwise the
        # channel is created empty and signals can be added manually.
        src = self._src_cb.currentData()
        if src:
            src_name = _channel_display_name(self.registry, self.processor, src[0], src[1])
        else:
            src_name = f"Channel {len(self._derived_blocks) + 1}"
        name = _dedupe_name(src_name, existing_names)
        channel_id = _slug_id(name, existing_ids)
        dc = Channel(channel_id=channel_id, name=name,
                            kind="expression", color=color)
        blk = self._make_derived_block(dc)
        self._virt_inner.insertWidget(self._virt_inner.count() - 1, blk)
        if src:
            blk._add_src(src)

    def _make_derived_block(self, dc: Channel) -> ChannelBlock:
        blk = ChannelBlock(dc, self.registry, self.processor)
        blk.removed.connect(self._rm_virtual)
        blk.applied.connect(lambda _: self.derived_changed.emit())
        blk.id_renamed.connect(self._on_block_id_renamed)
        blk._drag_handle.set_drag_source(self, blk)
        self._derived_blocks.append(blk)
        return blk

    def _on_block_id_renamed(self, old_id: str, new_id: str):
        self.refresh_derived()
        self.channel_renamed.emit("derived", old_id, "derived", new_id)

    def _rm_virtual(self, blk: ChannelBlock):
        self.processor.remove_derived(blk.dc.channel_id)
        self._derived_blocks.remove(blk)
        self._virt_inner.removeWidget(blk); blk.deleteLater()
        self.derived_changed.emit()

    # ── Drag-to-reorder — see _DragReorderContainer in ui/windows/plot_window.py

    def _index_of(self, block: ChannelBlock) -> int:
        return self._derived_blocks.index(block)

    def _drop_index(self, y: float) -> int:
        """Insertion index for a drop at container-relative y."""
        n = self._virt_inner.count() - 1   # exclude trailing stretch
        for i in range(n):
            w = self._virt_inner.itemAt(i).widget()
            if y < w.y() + w.height() / 2:
                return i
        return n

    def _indicator_y_for(self, idx: int) -> int:
        """Container-relative y for the drop-line at insertion index idx."""
        n = self._virt_inner.count() - 1   # exclude trailing stretch
        spacing = self._virt_inner.spacing()
        if n == 0:
            return self._virt_inner.contentsMargins().top()
        if idx <= 0:
            w = self._virt_inner.itemAt(0).widget()
            return w.y() - spacing // 2
        if idx >= n:
            w = self._virt_inner.itemAt(n - 1).widget()
            return w.y() + w.height() + spacing // 2
        prev = self._virt_inner.itemAt(idx - 1).widget()
        nxt  = self._virt_inner.itemAt(idx).widget()
        return (prev.y() + prev.height() + nxt.y()) // 2

    def _reorder(self, src_idx: int, dst_idx: int):
        """Move the Channel at src_idx to dst_idx (drop-target index,
        pre-removal) — same semantics as ControlPanel._reorder(). Also
        reorders processor._derived so evaluation order stays matched to
        the visual order: a Channel sourced from another Channel needs that
        source evaluated first in the same pass (SignalProcessor.
        _evaluate_derived), or it lags by one sample."""
        if dst_idx > src_idx:
            dst_idx -= 1
        if dst_idx == src_idx:
            return

        blk = self._derived_blocks.pop(src_idx)
        self._derived_blocks.insert(dst_idx, blk)
        self._virt_inner.removeWidget(blk)
        self._virt_inner.insertWidget(dst_idx, blk)

        self.processor.reorder_derived(src_idx, dst_idx)
        self.derived_changed.emit()

    def refresh_derived(self):
        """Rebuild ChannelBlock widgets from processor state (called after profile load)."""
        for blk in self._derived_blocks:
            self._virt_inner.removeWidget(blk); blk.deleteLater()
        self._derived_blocks.clear()
        self._color_idx = 0

        for dc in self.processor.get_derived():
            blk = self._make_derived_block(dc)
            self._virt_inner.insertWidget(self._virt_inner.count() - 1, blk)

        self._color_idx = len(self._derived_blocks)
        self._refresh_src_cb()


# ══════════════════════════════════════════════════════════════════════════════
#  Derived editor for one Channel
# ══════════════════════════════════════════════════════════════════════════════

_BUILTIN   = ["none", "scale_offset", "derivative", "second_derivative", "power", "rms", "difference", "sum"]
_SCRIPT    = ["expression", "function", "custom_script"]
_ALL_KINDS = _BUILTIN + _SCRIPT

_KIND_DISPLAY = {k: k.replace("_", " ").title() for k in _ALL_KINDS}
_KIND_DISPLAY["none"] = "None"
_KIND_DISPLAY["scale_offset"] = "Scale/Offset (Calibration)"

_KIND_HELP = {
    "none":              "Pass signal through unchanged",
    "scale_offset":      "Linear calibration from 1 signal: result = value × scale + offset",
    "derivative":        "Backward difference dy/dt from 1 signal",
    "second_derivative": "Second derivative d²y/dt² from 1 signal",
    "power":        "V × I  from 2 signals (voltage, current)",
    "rms":          "Rolling RMS from 1 signal  (set window below)",
    "difference":   "signal[0] − signal[1]  from 2 signals",
    "sum":          "Σ all signal values",
    "expression":   (
        "Single-line Python expression.\n"
        "Available: x[0]…  or use signal names directly (e.g. A0, encoder_0)\n"
        "          t = elapsed time (s),  math,  vars,  state\n"
        "Example:  A0 * 3.14159 / 180\n"
        "Tip: vars is shared with Control Panel 'On Action Script' — a button\n"
        "     can set vars['specimen_length'] = value; read it here as\n"
        "     vars.get('specimen_length', 1.0)."
    ),
    "function":     (
        "Multi-line function body — auto-wrapped as def compute(x, t):\n"
        "Available globals: x, signal names, t, math, vars, state\n"
        "Example:\n    offset = vars.get('zero', 0)\n    return x[0] - offset\n"
        "Tip: vars is shared with Control Panel 'On Action Script' — a 'Zero'\n"
        "     button can set vars['zero'] = value while this reads it back."
    ),
    "custom_script": (
        "Multi-line Python block.  Assign computed value to result.\n"
        "Available: x, signal names, t, math, vars, state\n"
        "Tip: vars is shared with Control Panel 'On Action Script' — a button\n"
        "     can set vars['key'] = value; read it here as vars.get('key', default)."
    ),
}


def _slug_id(name: str, existing: Set[str]) -> str:
    """Short-hand channel_id derived from a display name, deduplicated against
    existing derived channel IDs so a new Channel never silently overwrites
    (goes stale on top of) an existing one."""
    words = re.findall(r"[A-Za-z0-9]+", name)
    if not words:
        base = "CH"
    elif len(words) == 1:
        base = words[0][:4].upper()
    else:
        base = "".join(w[0] for w in words[:4]).upper()
    slug = base
    i = 2
    while slug in existing:
        slug = f"{base}_{i}"
        i += 1
    return slug


def _dedupe_name(name: str, existing: Set[str]) -> str:
    """Two channels must never share a display name — append ' (2)', ' (3)'...
    until unique."""
    if name not in existing:
        return name
    i = 2
    while f"{name} ({i})" in existing:
        i += 1
    return f"{name} ({i})"


def _sub_xrefs(code: str, names: list) -> str:
    """Replace x[0], x[1], ... with named source vars where index is in range."""
    def repl(m):
        i = int(m.group(1))
        return names[i] if i < len(names) else m.group(0)
    return re.sub(r'\bx\[(\d+)\]', repl, code)


class ChannelBlock(QFrame):
    removed     = pyqtSignal(object)
    applied     = pyqtSignal(object)  # Channel
    id_renamed  = pyqtSignal(str, str)  # old_id, new_id — this Channel's ID
                                         # changed; other blocks' source
                                         # pickers, and everything outside
                                         # this processor referencing it
                                         # (plot traces, controls), may now
                                         # be stale — see propagate_rename()

    def __init__(self, dc: Channel, registry: DeviceRegistry,
                 processor: SignalProcessor):
        super().__init__()
        self.dc = dc; self.registry = registry; self.processor = processor
        self.setObjectName("plotBlock")
        self._src_combos: List[QComboBox] = []
        self._expanded = False
        self._orig_id = dc.channel_id
        self._build()

    def _build(self):
        outer = QVBoxLayout(self); outer.setContentsMargins(0, 0, 0, 0); outer.setSpacing(0)

        # Header
        hdr = QWidget(); hdr.setObjectName("plotBlockHeader"); hdr.setFixedHeight(32)
        hl  = QHBoxLayout(hdr); hl.setContentsMargins(8, 0, 6, 0)
        self._drag_handle = _DragHandle()
        hl.addWidget(self._drag_handle)
        self._name = QLineEdit(self.dc.name); self._name.setObjectName("plotBlockTitle")
        self._name.textChanged.connect(lambda t: setattr(self.dc, "name", t))
        hl.addWidget(self._name, 1)
        rm = QToolButton(); rm.setText("✕"); rm.setObjectName("plotRemoveBtn")
        rm.setFixedSize(22, 22); rm.clicked.connect(lambda: self.removed.emit(self))
        hl.addWidget(rm)
        self._missing_lbl = QLabel("⚠")
        self._missing_lbl.setObjectName("controlWidgetStale")
        self._missing_lbl.setToolTip("A source signal is missing — reconfigured or removed")
        self._missing_lbl.setVisible(False)
        hl.addWidget(self._missing_lbl)
        self._toggle_btn = QToolButton(); self._toggle_btn.setText("▶")
        self._toggle_btn.setObjectName("traceRemoveBtn"); self._toggle_btn.setFixedSize(22, 22)
        self._toggle_btn.clicked.connect(self._toggle)
        hl.addWidget(self._toggle_btn)
        outer.addWidget(hdr)
        hdr.mousePressEvent = lambda e: self._toggle()

        # Subtitle — always visible (collapsed or expanded): what this
        # Channel is currently wired to, plus a one-click rebind for the
        # common single-source case. Lets a rewire be fixed (or a channel
        # proactively repointed at a different Signal) without expanding
        # the block or hunting for the per-source combo in the editor body.
        sub = QWidget(); sub.setObjectName("plotBlockSubtitle")
        sub_lay = QHBoxLayout(sub)
        sub_lay.setContentsMargins(30, 0, 6, 4); sub_lay.setSpacing(6)
        self._src_lbl = QLabel(""); self._src_lbl.setObjectName("traceSource")
        sub_lay.addWidget(self._src_lbl, 1)
        self._reconnect_cb = _channel_combo(self.registry, include_derived=False)
        self._reconnect_cb.setFixedWidth(220)
        sub_lay.addWidget(self._reconnect_cb)
        self._reconnect_btn = QPushButton("↺ Reconnect")
        self._reconnect_btn.setObjectName("addTraceBtn")
        self._reconnect_btn.setToolTip("Point this channel at a different physical Signal")
        self._reconnect_btn.clicked.connect(self._do_reconnect)
        sub_lay.addWidget(self._reconnect_btn)
        outer.addWidget(sub)

        # Body
        body = QWidget(); body.setObjectName("plotBlockSettings")
        bl = QVBoxLayout(body); bl.setContentsMargins(10, 8, 10, 10); bl.setSpacing(6)

        # ID / unit row — the id is auto-derived from the name at creation
        # (_slug_id()) and normally never needs to be seen, let alone typed;
        # tucked behind a toggle so Name is the only identity field most
        # users ever interact with.
        meta = QHBoxLayout()
        self._id_toggle = QToolButton(); self._id_toggle.setText("ID ▸")
        self._id_toggle.setObjectName("traceRemoveBtn"); self._id_toggle.setCheckable(True)
        self._id_toggle.setToolTip(f"Technical id: {self.dc.channel_id} — only needed to "
                                    f"reference this channel from an expression/script by id, "
                                    f"or to rename it. Click to edit.")
        self._id_toggle.toggled.connect(self._toggle_id_box)
        meta.addWidget(self._id_toggle)
        self._id = QLineEdit(self.dc.channel_id)
        self._id.setObjectName("traceLabel"); self._id.setFixedWidth(100)
        self._id.setVisible(False)
        self._id.textChanged.connect(lambda t: setattr(self.dc, "channel_id", t))
        meta.addWidget(self._id)
        meta.addWidget(QLabel("Unit:"))
        self._unit = QLineEdit(self.dc.unit)
        self._unit.setObjectName("traceLabel"); self._unit.setFixedWidth(60)
        self._unit.textChanged.connect(lambda t: setattr(self.dc, "unit", t))
        meta.addWidget(self._unit); meta.addStretch()
        bl.addLayout(meta)

        # Sources — include derived channels as valid sources
        src_grp = QGroupBox("Signals"); src_grp.setObjectName("cfgGlobalBar")
        src_lay = QVBoxLayout(src_grp); src_lay.setContentsMargins(6, 4, 6, 4); src_lay.setSpacing(3)
        self._src_cont = QWidget(); self._src_vlay = QVBoxLayout(self._src_cont)
        self._src_vlay.setContentsMargins(0, 0, 0, 0); self._src_vlay.setSpacing(3)
        _is_deriv = self.dc.kind in ("derivative", "second_derivative")
        if _is_deriv:
            self._add_src(self.dc.sources[0] if self.dc.sources else None)
        else:
            for _s in self.dc.sources:
                self._add_src(_s)
        self._add_src_btn = QPushButton("+ Add Signal"); self._add_src_btn.setObjectName("addTraceBtn")
        self._add_src_btn.clicked.connect(lambda: self._add_src())
        src_lay.addWidget(self._src_cont); src_lay.addWidget(self._add_src_btn)
        bl.addWidget(src_grp)

        # Kind combo + help
        k_row = QHBoxLayout(); k_row.addWidget(QLabel("Operation:"))
        self._kind_cb = QComboBox(); self._kind_cb.setObjectName("channelPickerCb")
        self._kind_cb.addItems([_KIND_DISPLAY[k] for k in _ALL_KINDS])
        cur_idx = _ALL_KINDS.index(self.dc.kind) if self.dc.kind in _ALL_KINDS else 0
        self._kind_cb.setCurrentIndex(cur_idx)
        self._kind_cb.currentIndexChanged.connect(self._on_kind)
        k_row.addWidget(self._kind_cb); k_row.addStretch()
        bl.addLayout(k_row)
        self._help = QLabel(_KIND_HELP.get(self.dc.kind, ""))
        self._help.setObjectName("traceSource"); self._help.setWordWrap(True)
        bl.addWidget(self._help)

        # RMS window
        self._win_row = QHBoxLayout()
        self._win_row.addWidget(QLabel("Window samples:"))
        self._win_sp = QSpinBox(); self._win_sp.setRange(2, 10000)
        self._win_sp.setValue(self.dc.params.get("window", 20))
        self._win_sp.setObjectName("traceWidthSpin"); self._win_sp.setFixedWidth(80)
        self._win_sp.valueChanged.connect(lambda v: self.dc.params.update({"window": v}))
        self._win_row.addWidget(self._win_sp); self._win_row.addStretch()
        self._win_widget = QWidget(); self._win_widget.setLayout(self._win_row)
        bl.addWidget(self._win_widget)

        # Scale/Offset params
        self._so_row = QHBoxLayout()
        self._so_row.addWidget(QLabel("Scale:"))
        self._scale_sp = QDoubleSpinBox(); self._scale_sp.setRange(-1e6, 1e6); self._scale_sp.setDecimals(6)
        self._scale_sp.setValue(self.dc.params.get("scale", 1.0))
        self._scale_sp.setObjectName("traceWidthSpin"); self._scale_sp.setFixedWidth(90)
        self._scale_sp.valueChanged.connect(lambda v: self.dc.params.update({"scale": v}))
        self._so_row.addWidget(self._scale_sp)
        self._so_row.addWidget(QLabel("Offset:"))
        self._offset_sp = QDoubleSpinBox(); self._offset_sp.setRange(-1e9, 1e9); self._offset_sp.setDecimals(6)
        self._offset_sp.setValue(self.dc.params.get("offset", 0.0))
        self._offset_sp.setObjectName("traceWidthSpin"); self._offset_sp.setFixedWidth(90)
        self._offset_sp.valueChanged.connect(lambda v: self.dc.params.update({"offset": v}))
        self._so_row.addWidget(self._offset_sp); self._so_row.addStretch()
        self._so_widget = QWidget(); self._so_widget.setLayout(self._so_row)
        bl.addWidget(self._so_widget)

        # Filters — only for a single-physical-source passthrough channel
        # (kind="none"); the embedded block is (re)built by _refresh_filters()
        self._filters_grp = QGroupBox("Filters"); self._filters_grp.setObjectName("cfgGlobalBar")
        self._filters_lay = QVBoxLayout(self._filters_grp)
        self._filters_lay.setContentsMargins(6, 4, 6, 4)
        self._filters_block: Optional[ChannelPipelineBlock] = None
        bl.addWidget(self._filters_grp)

        # W.r.t. — only for derivative/second_derivative
        self._wrt_grp = QGroupBox("With Respect To"); self._wrt_grp.setObjectName("cfgGlobalBar")
        wrt_lay = QVBoxLayout(self._wrt_grp); wrt_lay.setContentsMargins(6, 6, 6, 6); wrt_lay.setSpacing(4)
        wrt_top = QHBoxLayout(); wrt_top.addWidget(QLabel("Variable:"))
        self._wrt_cb = QComboBox(); self._wrt_cb.setObjectName("channelPickerCb")
        self._wrt_cb.addItems(["Time", "Channel"])
        _cur_wrt = self.dc.params.get("deriv_wrt", "time")
        self._wrt_cb.setCurrentIndex(1 if _cur_wrt == "channel" else 0)
        self._wrt_cb.currentIndexChanged.connect(self._on_wrt_changed)
        self._wrt_cb.currentIndexChanged.connect(lambda _: self._update_vars_hint())
        wrt_top.addWidget(self._wrt_cb); wrt_top.addStretch()
        wrt_lay.addLayout(wrt_top)
        self._wrt_x_row = QWidget()
        wx_lay = QHBoxLayout(self._wrt_x_row); wx_lay.setContentsMargins(0, 0, 0, 0); wx_lay.setSpacing(6)
        wx_lay.addWidget(QLabel("Channel (x):"))
        self._wrt_x_cb = _channel_combo(self.registry, self.processor,
                                         include_derived=True, show_unit=True)
        self._wrt_x_cb.setObjectName("channelPickerCb")
        if _cur_wrt == "channel" and len(self.dc.sources) > 1:
            x_src = self.dc.sources[1]
            for i in range(self._wrt_x_cb.count()):
                if self._wrt_x_cb.itemData(i) == x_src:
                    self._wrt_x_cb.setCurrentIndex(i); break
        self._wrt_x_cb.currentIndexChanged.connect(lambda _: self._update_vars_hint())
        wx_lay.addWidget(self._wrt_x_cb, 1)
        wrt_lay.addWidget(self._wrt_x_row)
        bl.addWidget(self._wrt_grp)

        # Code editor (shown for all kinds — read-only for built-ins)
        self._code_grp = QGroupBox("Code")
        code_lay = QVBoxLayout(self._code_grp); code_lay.setContentsMargins(6, 4, 6, 4)
        # Live variable-name hint — updated whenever sources change
        self._vars_lbl = QLabel("")
        self._vars_lbl.setObjectName("traceSource"); self._vars_lbl.setWordWrap(True)
        code_lay.addWidget(self._vars_lbl)
        _mono = QFont("IBM Plex Mono, Consolas, Monospace"); _mono.setStyleHint(QFont.StyleHint.Monospace)
        self._code = QTextEdit(); self._code.setObjectName("codeEditor")
        self._code.setMinimumHeight(90); self._code.setMaximumHeight(180)
        self._code.setFont(_mono)
        self._code.setTabStopDistance(QFontMetrics(_mono).horizontalAdvance(" ") * 4)
        from ui.code_templates import BUILTIN_TEMPLATES, SCRIPT_TEMPLATES
        if self.dc.kind in _BUILTIN:
            txt = BUILTIN_TEMPLATES.get(self.dc.kind, "")
            self._template_base = txt
            self._last_auto_code = txt
        elif self.dc.kind == "expression":
            existing = self.dc.expression
            txt = existing or SCRIPT_TEMPLATES.get("expression", "")
            self._template_base = SCRIPT_TEMPLATES.get("expression", "")
            self._last_auto_code = txt if not existing else None
        else:
            existing = self.dc.script
            txt = existing or SCRIPT_TEMPLATES.get(self.dc.kind, "")
            self._template_base = SCRIPT_TEMPLATES.get(self.dc.kind, "")
            self._last_auto_code = txt if not existing else None
        self._code.setPlainText(txt)
        code_lay.addWidget(self._code)
        # "Edit as Custom Script" button — only visible for built-in kinds
        self._edit_as_script_btn = QPushButton("✎  Edit as Custom Script")
        self._edit_as_script_btn.setObjectName("addTraceBtn")
        self._edit_as_script_btn.clicked.connect(self._convert_to_custom_script)
        code_lay.addWidget(self._edit_as_script_btn)
        bl.addWidget(self._code_grp)

        # Status + apply
        ap_row = QHBoxLayout()
        self._st = QLabel(""); self._st.setObjectName("traceSource")
        ap_row.addWidget(self._st, 1)
        ap = QPushButton("✓  Apply"); ap.setObjectName("applyButton")
        ap.clicked.connect(self._apply)
        ap_row.addWidget(ap)
        bl.addLayout(ap_row)

        body.setVisible(False)
        outer.addWidget(body)
        self._body = body
        self._update_vars_hint()
        self._update_visibility()
        self.refresh_missing_sources()
        self._refresh_source_subtitle()

    def _refresh_source_subtitle(self):
        """Update the always-visible '← wired-to' line and show/hide the
        inline quick-reconnect control — only offered for the unambiguous
        single-source case; multi-source channels use the per-source combos
        in the expanded editor instead."""
        names = [f"{_channel_display_name(self.registry, self.processor, d, c)}  ({d}/{c})"
                 for d, c in self.dc.sources]
        self._src_lbl.setText("← " + ", ".join(names) if names else "no source")
        single = len(self.dc.sources) == 1
        self._reconnect_cb.setVisible(single)
        self._reconnect_btn.setVisible(single)
        # Pre-select the actual current source — otherwise the combo always
        # shows whatever landed first in registry iteration order, which
        # looks like that's what's connected even when it isn't.
        if single:
            cur = self.dc.sources[0]
            self._reconnect_cb.blockSignals(True)
            for i in range(self._reconnect_cb.count()):
                if self._reconnect_cb.itemData(i) == cur:
                    self._reconnect_cb.setCurrentIndex(i)
                    break
            else:
                self._reconnect_cb.setCurrentIndex(-1)
            self._reconnect_cb.blockSignals(False)

    def _do_reconnect(self):
        """Inline one-click rebind: point this channel's sole source at
        whatever Signal is currently selected in the quick-reconnect combo —
        no need to expand the block or use the per-source editor combos."""
        new_src = self._reconnect_cb.currentData()
        if not new_src or len(self.dc.sources) != 1:
            return
        self.dc.sources = [new_src]
        self.dc.source_names = [_channel_display_name(self.registry, self.processor, *new_src)]
        if self._src_combos:
            cb = self._src_combos[0]
            for i in range(cb.count()):
                if cb.itemData(i) == new_src:
                    cb.setCurrentIndex(i)
                    break
        err = self.processor.add_derived(self.dc)
        self._refresh_source_subtitle()
        self.refresh_missing_sources()
        if err:
            self._st.setText(f"⚠ {err[:100]}")
            self._st.setStyleSheet("color:#ef4444;")
        else:
            self._st.setText("✓ Reconnected")
            self._st.setStyleSheet("color:#22c55e;")
            self.applied.emit(self.dc)

    def refresh_missing_sources(self):
        """Update the header warning icon for a source signal that no longer
        resolves (device removed, or Apply & Reconnect dropped that pin).
        Called after any device add/remove/reconfigure — see PipelineTab."""
        missing = False
        for dev_id, ch_id in self.dc.sources:
            if dev_id == "derived":
                if ch_id not in self.processor.all_virtual_channel_ids():
                    missing = True
                    break
            else:
                dev = self.registry.get_instance(dev_id)
                if dev is None or dev.get_signal(ch_id) is None:
                    missing = True
                    break
        self._missing_lbl.setVisible(missing)

    def _toggle(self):
        self._expanded = not self._expanded
        self._body.setVisible(self._expanded)
        self._toggle_btn.setText("▼" if self._expanded else "▶")

    def _toggle_id_box(self, checked: bool):
        self._id.setVisible(checked)
        self._id_toggle.setText("ID ▾" if checked else "ID ▸")

    def _add_src(self, src=None):
        row = QHBoxLayout()
        cb = _channel_combo(self.registry, self.processor,
                            include_derived=True, show_unit=True)
        cb.setObjectName("channelPickerCb")
        if src:
            for i in range(cb.count()):
                if cb.itemData(i) == src:
                    cb.setCurrentIndex(i); break
        cb.currentIndexChanged.connect(lambda _: self._update_vars_hint())
        rm = QToolButton(); rm.setText("✕"); rm.setObjectName("traceRemoveBtn")
        rm.setFixedSize(22, 22); rm.clicked.connect(lambda: self._rm_src(row, cb))
        row.addWidget(cb, 1); row.addWidget(rm)
        self._src_vlay.addLayout(row)
        self._src_combos.append(cb)
        self._update_vars_hint()

    def _rm_src(self, row, cb):
        if cb in self._src_combos:
            self._src_combos.remove(cb)
        while row.count():
            it = row.takeAt(0)
            if it.widget(): it.widget().deleteLater()
        self._update_vars_hint()

    def _update_vars_hint(self):
        """Refresh the variable-name hint label whenever sources change."""
        if not hasattr(self, "_vars_lbl"):
            return
        from core.signal_processor import _make_src_names

        sources = [cb.currentData() for cb in self._src_combos if cb.currentData()]
        is_deriv = self.dc.kind in ("derivative", "second_derivative")
        if (is_deriv and hasattr(self, "_wrt_cb")
                and self._wrt_cb.currentIndex() == 1
                and hasattr(self, "_wrt_x_cb")):
            wrt_src = self._wrt_x_cb.currentData()
            if wrt_src and wrt_src not in sources:
                sources.append(wrt_src)

        self._refresh_filters()

        if not sources:
            self._vars_lbl.setText("No signals — add signals above to use named variables")
            return

        display_names = [_channel_display_name(self.registry, self.processor, d, c)
                         for d, c in sources]
        names = _make_src_names(sources, display_names)
        parts = [f"{name}  (x[{i}])" for i, name in enumerate(names)]
        self._vars_lbl.setText("Variables:  " + "   ·   ".join(parts))

        # Update code editor if it still matches the last auto-generated text
        if (getattr(self, "_last_auto_code", None) is not None
                and hasattr(self, "_code")
                and getattr(self, "_template_base", "")):
            current = self._code.toPlainText()
            if current == self._last_auto_code:
                new_code = _sub_xrefs(self._template_base, names)
                self._last_auto_code = new_code
                if current != new_code:
                    self._code.blockSignals(True)
                    cursor_pos = self._code.textCursor().position()
                    self._code.setPlainText(new_code)
                    c = self._code.textCursor()
                    c.setPosition(min(cursor_pos, len(new_code)))
                    self._code.setTextCursor(c)
                    self._code.blockSignals(False)

    def _refresh_filters(self):
        """(Re)build the embedded single-source Filters block when eligible:
        kind is a plain passthrough ("none") with exactly one physical source."""
        if not hasattr(self, "_filters_grp"):
            return  # called during initial Sources construction, too early
        sources = [cb.currentData() for cb in self._src_combos if cb.currentData()]
        eligible = (self.dc.kind == "none" and len(sources) == 1
                    and sources[0][0] != "derived")
        if not eligible:
            self._filters_grp.setVisible(False)
            if self._filters_block is not None:
                self._filters_lay.removeWidget(self._filters_block)
                self._filters_block.deleteLater()
                self._filters_block = None
            return
        dev_id, ch_id = sources[0]
        if (self._filters_block is not None
                and (self._filters_block.dev_id, self._filters_block.ch_id) != (dev_id, ch_id)):
            self._filters_lay.removeWidget(self._filters_block)
            self._filters_block.deleteLater()
            self._filters_block = None
        if self._filters_block is None:
            ch_name = _channel_display_name(self.registry, self.processor, dev_id, ch_id)
            self._filters_block = ChannelPipelineBlock(
                dev_id, ch_id, ch_name, "", self.processor,
                show_calibration=False, show_header=False,
            )
            self._filters_lay.addWidget(self._filters_block)
        self._filters_grp.setVisible(True)

    def _on_kind(self, idx: int):
        from ui.code_templates import BUILTIN_TEMPLATES, SCRIPT_TEMPLATES
        k = _ALL_KINDS[idx]
        self.dc.kind = k
        self._help.setText(_KIND_HELP.get(k, ""))
        if k in ("derivative", "second_derivative") and not self._src_combos:
            self._add_src()
        if k in ("derivative", "second_derivative"):
            wrt_ch = (hasattr(self, "_wrt_cb") and self._wrt_cb.currentIndex() == 1)
            key = f"{k}_channel" if wrt_ch else k
            base = BUILTIN_TEMPLATES.get(key, BUILTIN_TEMPLATES.get(k, ""))
        elif k in _BUILTIN:
            base = BUILTIN_TEMPLATES.get(k, "")
        else:
            base = SCRIPT_TEMPLATES.get(k, "")
        self._template_base = base
        self._last_auto_code = base
        self._code.setPlainText(base)
        self._update_vars_hint()
        self._update_visibility()

    def _on_wrt_changed(self, idx: int):
        self._wrt_x_row.setVisible(idx == 1)
        if self.dc.kind in ("derivative", "second_derivative"):
            from ui.code_templates import BUILTIN_TEMPLATES
            key = f"{self.dc.kind}_channel" if idx == 1 else self.dc.kind
            self._template_base = BUILTIN_TEMPLATES.get(key, BUILTIN_TEMPLATES.get(self.dc.kind, ""))

    def _convert_to_custom_script(self):
        """Switch kind to custom_script, pre-fill with built-in template, make editable."""
        from ui.code_templates import BUILTIN_TEMPLATES
        template = BUILTIN_TEMPLATES.get(self.dc.kind, "")
        # Switch kind combo to custom_script
        idx = _ALL_KINDS.index("custom_script")
        self._kind_cb.blockSignals(True)
        self._kind_cb.setCurrentIndex(idx)
        self._kind_cb.blockSignals(False)
        self.dc.kind = "custom_script"
        self._help.setText(_KIND_HELP.get("custom_script", ""))
        self._template_base = template
        self._last_auto_code = template
        self._code.setPlainText(template)
        self.dc.script = template
        self._update_vars_hint()
        self._update_visibility()

    def _update_visibility(self):
        is_deriv   = self.dc.kind in ("derivative", "second_derivative")
        is_builtin = self.dc.kind in _BUILTIN
        is_script  = self.dc.kind in _SCRIPT
        # Code group shown for all kinds; read-only for built-ins
        self._code_grp.setVisible(True)
        self._code.setReadOnly(is_builtin)
        self._edit_as_script_btn.setVisible(is_builtin)
        self._win_widget.setVisible(self.dc.kind == "rms")
        self._so_widget.setVisible(self.dc.kind == "scale_offset")
        self._refresh_filters()
        self._wrt_grp.setVisible(is_deriv)
        self._add_src_btn.setVisible(not is_deriv)
        if is_deriv:
            self._wrt_x_row.setVisible(self._wrt_cb.currentIndex() == 1)

    def _apply(self):
        name = self.dc.name.strip()
        channel_id = self.dc.channel_id.strip()
        if not name:
            self._st.setText("⚠ Name cannot be empty")
            self._st.setStyleSheet("color:#ef4444;")
            return
        if not channel_id:
            self._st.setText("⚠ ID cannot be empty")
            self._st.setStyleSheet("color:#ef4444;")
            return
        others = [d for d in self.processor.get_derived() if d is not self.dc]
        if any(d.name == name for d in others):
            self._st.setText(f"⚠ Name '{name}' is already used by another channel")
            self._st.setStyleSheet("color:#ef4444;")
            return
        if any(d.channel_id == channel_id for d in others):
            self._st.setText(f"⚠ ID '{channel_id}' is already used by another channel")
            self._st.setStyleSheet("color:#ef4444;")
            return
        renamed = channel_id != self._orig_id
        old_id  = self._orig_id
        if renamed:
            self._orig_id = channel_id
        sources = [cb.currentData() for cb in self._src_combos if cb.currentData()]
        if self.dc.kind in ("derivative", "second_derivative"):
            wrt = "channel" if self._wrt_cb.currentIndex() == 1 else "time"
            self.dc.params["deriv_wrt"] = wrt
            if wrt == "channel":
                x_src = self._wrt_x_cb.currentData()
                if x_src:
                    sources.append(x_src)
        self.dc.sources = sources
        self.dc.source_names = [_channel_display_name(self.registry, self.processor, d, c)
                                 for d, c in sources]
        if self.dc.kind == "expression":
            self.dc.expression = self._code.toPlainText().strip()
        elif self.dc.kind in ("function", "custom_script"):
            self.dc.script = self._code.toPlainText()
        err = self.processor.add_derived(self.dc)
        self._refresh_source_subtitle()
        self.refresh_missing_sources()
        # Emitted regardless of whether this channel's own expression/script
        # compiles — propagate_rename() (via id_renamed) still needs to run
        # so other channels' sources / plot traces / controls don't dangle.
        if renamed:
            self.id_renamed.emit(old_id, channel_id)
        if err:
            self._st.setText(f"⚠ {err[:100]}")
            self._st.setStyleSheet("color:#ef4444;")
        else:
            self._st.setText("✓ Applied")
            self._st.setStyleSheet("color:#22c55e;")
            self.applied.emit(self.dc)


# ══════════════════════════════════════════════════════════════════════════════
#  Signals List Tab — flat list of all signals with enable/disable
# ══════════════════════════════════════════════════════════════════════════════

class SignalsListTab(QWidget):
    visibility_changed = pyqtSignal()
    channel_toggled    = pyqtSignal(str, str, bool)  # dev_id, ch_id, enabled

    def __init__(self, registry: DeviceRegistry, processor: SignalProcessor):
        super().__init__()
        self.registry  = registry
        self.processor = processor
        self._build()

    def _build(self):
        scroll = QScrollArea(); scroll.setWidgetResizable(True)
        scroll.setObjectName("deviceScroll")
        scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self._cont = QWidget()
        self._lay  = QVBoxLayout(self._cont)
        self._lay.setContentsMargins(8, 8, 8, 8); self._lay.setSpacing(2)
        scroll.setWidget(self._cont)
        root = QVBoxLayout(self); root.setContentsMargins(0, 0, 0, 0)
        root.addWidget(scroll)
        self.refresh()

    def refresh(self):
        while self._lay.count():
            it = self._lay.takeAt(0)
            if it.widget(): it.widget().deleteLater()

        for dev in self.registry.all_instances():
            for ch in dev.info.signals:
                dev_id_cap = dev.info.device_id
                ch_id_cap  = ch.signal_id
                self._lay.addWidget(self._make_row(
                    color     = ch.color,
                    name      = f"{ch.signal_id}  —  {ch.name}",
                    unit      = ch.unit,
                    source    = dev_id_cap,
                    enabled   = ch.enabled,
                    on_toggle = lambda v, c=ch, d=dev_id_cap, ci=ch_id_cap: (
                        setattr(c, "enabled", v),
                        self.visibility_changed.emit(),
                        self.channel_toggled.emit(d, ci, v),
                    ),
                ))

        derived = self.processor.get_derived()
        if self.registry.all_instances() and derived:
            div = QFrame(); div.setFrameShape(QFrame.Shape.HLine)
            div.setObjectName("devWindowDivider")
            self._lay.addWidget(div)

        for dc in derived:
            self._lay.addWidget(self._make_row(
                color     = dc.color,
                name      = f"{dc.channel_id}  —  {dc.name}",
                unit      = dc.unit,
                source    = "virtual",
                enabled   = dc.enabled,
                on_toggle = lambda v, d=dc: (setattr(d, "enabled", v), self.visibility_changed.emit()),
            ))

        self._lay.addStretch()

    def _make_row(self, color: str, name: str, unit: str, source: str,
                  enabled: bool, on_toggle) -> QFrame:
        row = QFrame(); row.setObjectName("traceRow")
        lay = QHBoxLayout(row); lay.setContentsMargins(8, 4, 8, 4); lay.setSpacing(8)

        dot = QLabel("●"); dot.setStyleSheet(f"color:{color};"); dot.setFixedWidth(14)
        lay.addWidget(dot)

        chk = QCheckBox(name); chk.setChecked(enabled)
        chk.toggled.connect(on_toggle)
        lay.addWidget(chk, 1)

        if unit:
            ul = QLabel(unit); ul.setObjectName("traceSource")
            ul.setFixedWidth(52)
            ul.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
            lay.addWidget(ul)

        sl = QLabel(source); sl.setObjectName("traceSource")
        sl.setFixedWidth(72)
        sl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
        lay.addWidget(sl)

        return row


# ══════════════════════════════════════════════════════════════════════════════
#  ChannelsWindow — main
# ══════════════════════════════════════════════════════════════════════════════

class ChannelsWindow(QWidget):
    pipeline_changed = pyqtSignal()
    derived_changed  = pyqtSignal()
    closed           = pyqtSignal()

    def __init__(self, registry: DeviceRegistry,
                 processor: SignalProcessor, parent=None):
        super().__init__(parent, Qt.WindowType.Window)
        self.registry  = registry
        self.processor = processor

        self.setWindowTitle("Channels")
        self.setMinimumSize(800, 520)
        self.resize(1400, 820)
        self._build()

    def _build(self):
        root = QVBoxLayout(self); root.setContentsMargins(0, 0, 0, 0); root.setSpacing(0)

        hdr = QWidget(); hdr.setObjectName("devWindowTitleBar"); hdr.setFixedHeight(44)
        hl  = QHBoxLayout(hdr); hl.setContentsMargins(14, 0, 14, 0)
        hl.addWidget(QLabel("CHANNELS").also(lambda w: w.setObjectName("devWindowTitle")), 1)
        root.addWidget(hdr)
        div = QFrame(); div.setFrameShape(QFrame.Shape.HLine)
        div.setObjectName("devWindowDivider"); root.addWidget(div)

        self._pip_tab = PipelineTab(self.registry, self.processor)
        self._pip_tab.changed.connect(self.pipeline_changed)
        self._pip_tab.derived_changed.connect(self.derived_changed)
        root.addWidget(self._pip_tab, 1)

        self.refresh_derived()

    def refresh_derived(self):
        self._pip_tab.refresh_derived()

    def on_channel_enabled_changed(self, dev_id: str, ch_id: str, enabled: bool):
        self._pip_tab.on_channel_enabled_changed(dev_id, ch_id, enabled)

    def on_device_removed(self, dev_id: str):
        self._pip_tab.on_device_removed(dev_id)

    def on_device_reconfigured(self, dev_id: str):
        self._pip_tab.on_device_reconfigured(dev_id)

    def on_device_added(self):
        self._pip_tab.on_device_added()

    def on_channel_name_changed(self, dev_id: str, ch_id: str, ch_name: str):
        self._pip_tab.on_channel_name_changed(dev_id, ch_id, ch_name)

    def on_channel_unit_changed(self, dev_id: str, ch_id: str, unit: str):
        self._pip_tab.on_channel_unit_changed(dev_id, ch_id, unit)

    def closeEvent(self, e: QCloseEvent):
        self.closed.emit(); e.accept()