-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession_dialog.py
More file actions
1438 lines (1274 loc) · 63.3 KB
/
Copy pathsession_dialog.py
File metadata and controls
1438 lines (1274 loc) · 63.3 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
"""
session_dialog.py - Dialog di creazione/modifica sessioni PCM
Supporta tutti i protocolli con tab specifici per le impostazioni avanzate.
"""
import os
import shutil
from session_command import installed_tools as _installed_tools
import subprocess
from PyQt6.QtWidgets import (
QDialog, QVBoxLayout, QHBoxLayout, QFormLayout, QTabWidget,
QWidget, QLabel, QLineEdit, QComboBox, QCheckBox, QPushButton,
QDialogButtonBox, QFileDialog, QSpinBox, QGroupBox, QGridLayout,
QTextEdit, QSizePolicy, QFrame, QToolButton,
QMessageBox, QListWidget, QListWidgetItem, QInputDialog, QApplication
)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QIcon, QColor, QPalette
from PyQt6.QtWidgets import QScrollArea
from themes import TERMINAL_THEMES
from translations import t
# ---------------------------------------------------------------------------
# Percorso assoluto cartella icons (risolve il problema CWD)
# ---------------------------------------------------------------------------
_HERE = os.path.dirname(os.path.abspath(__file__))
_ICONS_DIR = os.path.join(_HERE, "icons")
_ICON_CACHE: dict = {}
def _icon(filename: str) -> QIcon:
"""Carica SVG/PNG con percorso assoluto; restituisce QIcon vuota se mancante."""
if filename in _ICON_CACHE:
return _ICON_CACHE[filename]
path = os.path.join(_ICONS_DIR, filename)
ico = QIcon(path) if os.path.isfile(path) else QIcon()
_ICON_CACHE[filename] = ico
return ico
PROTOCOLLI = ["ssh", "telnet", "sftp", "ftp", "rdp", "vnc", "mosh", "serial"]
PROTO_LABEL = {
"ssh": "SSH",
"telnet": "Telnet",
"sftp": "SFTP",
"ftp": "FTP / FTPS",
"rdp": "RDP",
"vnc": "VNC",
"mosh": "Mosh",
"serial": "Seriale",
}
PROTO_ICON = {
"ssh": "ssh.png",
"telnet": "network.png",
"sftp": "folder.png",
"ftp": "folder.png",
"rdp": "monitor.png",
"vnc": "vnc.png",
"mosh": "flash.png",
"serial": "cable.png",
}
def _available_tools(candidates: list[str], always_include: list[str] | None = None) -> list[str]:
"""
Restituisce i tool della lista che sono presenti nel PATH.
I tool in always_include vengono sempre inclusi (es. "Terminale Interno").
Se nessun candidato e' trovato, restituisce il primo della lista come fallback.
"""
found = [t for t in candidates if shutil.which(t)]
if always_include:
result = list(always_include) + [t for t in found if t not in always_include]
else:
result = found
# Fallback: almeno un elemento
if not result:
result = [candidates[0]]
return result
class SessionDialog(QDialog):
"""
Dialog per creare o modificare una sessione.
Adatta i campi visibili al protocollo selezionato.
"""
def __init__(self, parent=None, nome="", dati=None):
super().__init__(parent)
self._nome_originale = nome
self._dati_originali = dati or {}
self.setWindowTitle(t("sd.new_title") if not nome else t("sd.edit_title", name=nome))
self.setMinimumSize(720, 600)
self.resize(800, 700)
self.setModal(True)
# ── Palette chiara (sovrascrive tema dark globale) ──────────────
p = QPalette()
p.setColor(QPalette.ColorRole.Window, QColor("#f5f5f5"))
p.setColor(QPalette.ColorRole.WindowText, QColor("#111111"))
p.setColor(QPalette.ColorRole.Base, QColor("#ffffff"))
p.setColor(QPalette.ColorRole.AlternateBase, QColor("#ececec"))
p.setColor(QPalette.ColorRole.Text, QColor("#111111"))
p.setColor(QPalette.ColorRole.Button, QColor("#e0e0e0"))
p.setColor(QPalette.ColorRole.ButtonText, QColor("#111111"))
p.setColor(QPalette.ColorRole.Highlight, QColor("#0078d4"))
p.setColor(QPalette.ColorRole.HighlightedText, QColor("#ffffff"))
self.setPalette(p)
self.setStyleSheet(
"QDialog, QWidget { background:#f5f5f5; color:#111111; }"
"QLineEdit, QComboBox, QSpinBox, QTextEdit, QPlainTextEdit {"
" background:#ffffff; color:#111111; border:1px solid #aaaaaa;"
" border-radius:3px; padding:2px 4px; }"
"QComboBox QAbstractItemView {"
" background:#ffffff; color:#111111; min-width:200px; }"
"QLabel { color:#111111; }"
"QCheckBox { color:#111111; spacing:6px; }"
"QCheckBox::indicator { width:15px; height:15px;"
" border:2px solid #aaaaaa; border-radius:3px; background:#ffffff; }"
"QCheckBox::indicator:hover { border-color:#0078d4; background:#e8f0fe; }"
"QCheckBox::indicator:checked { background:#0078d4; border-color:#0057a8; }"
"QCheckBox::indicator:checked:hover { background:#006cbf; }"
"QGroupBox { color:#333333; border:1px solid #cccccc; border-radius:4px;"
" margin-top:6px; padding-top:8px; }"
"QGroupBox::title { subcontrol-origin:margin; left:8px; color:#333333; }"
"QTabWidget::pane { border:1px solid #cccccc; }"
"QTabBar::tab { background:#e0e0e0; color:#333333; padding:5px 12px;"
" border:1px solid #cccccc; border-bottom:none;"
" border-radius:3px 3px 0 0; }"
"QTabBar::tab:selected { background:#ffffff; color:#111111; font-weight:bold; }"
"QTabBar::tab:hover { background:#d0d0d0; }"
"QPushButton { background:#e0e0e0; color:#111111; border:1px solid #aaaaaa;"
" border-radius:3px; padding:4px 12px; }"
"QPushButton:hover { background:#c8c8c8; }"
"QPushButton:pressed { background:#b0b0b0; }"
"QScrollArea { border:none; background:#f5f5f5; }"
)
# ────────────────────────────────────────────────────────────────
self._init_ui()
if nome and dati:
self._popola(nome, dati)
# ------------------------------------------------------------------
# UI principale
# ------------------------------------------------------------------
def _init_ui(self):
root = QVBoxLayout(self)
root.setSpacing(8)
# --- Nome sessione + protocollo ---
top = QFormLayout()
top.setLabelAlignment(Qt.AlignmentFlag.AlignRight)
top.setSpacing(8)
self.edit_nome = QLineEdit()
self.edit_nome.setPlaceholderText(t("sd.session_name_ph"))
lbl_nome = QLabel(t("sd.session_name"))
lbl_nome.setMinimumWidth(115)
top.addRow(lbl_nome, self.edit_nome)
self.combo_gruppo = QComboBox()
self.combo_gruppo.setEditable(True)
self.combo_gruppo.setPlaceholderText(t("sd.group_ph"))
self._carica_gruppi_esistenti()
lbl_gruppo = QLabel(t("sd.group"))
lbl_gruppo.setMinimumWidth(115)
top.addRow(lbl_gruppo, self.combo_gruppo)
self.combo_proto = QComboBox()
self.combo_proto.setMinimumWidth(200)
for k, v in PROTO_LABEL.items():
self.combo_proto.addItem(_icon(PROTO_ICON.get(k, "terminal.png")), v, k)
self.combo_proto.currentIndexChanged.connect(self._aggiorna_tab)
lbl_proto = QLabel(t("sd.protocol"))
lbl_proto.setMinimumWidth(115)
top.addRow(lbl_proto, self.combo_proto)
root.addLayout(top)
sep = QFrame()
sep.setFrameShape(QFrame.Shape.HLine)
sep.setStyleSheet("color:#555;")
root.addWidget(sep)
# --- Tab avanzate ---
self.tabs = QTabWidget()
root.addWidget(self.tabs, 1)
# Tab Connessione: avvolto in QScrollArea per evitare troncature
# quando i GroupBox specifici per protocollo sono grandi
self._scroll_conn = QScrollArea()
self._scroll_conn.setWidgetResizable(True)
self._scroll_conn.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.tab_conn = QWidget()
self._scroll_conn.setWidget(self.tab_conn)
self.tabs.addTab(self._scroll_conn, _icon("connection.png"), t("sd.tab.connection"))
self._build_tab_connessione()
self.tab_auth = QWidget()
self.tabs.addTab(self.tab_auth, _icon("key.png"), t("sd.tab.auth"))
self._build_tab_autenticazione()
self.tab_term = QWidget()
self.tabs.addTab(self.tab_term, _icon("terminal.png"), t("sd.tab.terminal"))
self._build_tab_terminale()
self.tab_adv = QWidget()
self.tabs.addTab(self.tab_adv, _icon("settings.png"), t("sd.tab.advanced"))
self._build_tab_avanzate()
self.tab_note = QWidget()
self.tabs.addTab(self.tab_note, _icon("notes.png"), t("sd.tab.notes"))
self._build_tab_note()
self.tab_macro = QWidget()
self.tabs.addTab(self.tab_macro, _icon("flash.png"), t("sd.tab.macros"))
self._build_tab_macro()
# --- Pulsanti OK / Annulla ---
bbox = QDialogButtonBox(
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
)
bbox.accepted.connect(self._valida_e_accetta)
bbox.rejected.connect(self.reject)
root.addWidget(bbox)
self._aggiorna_tab()
# ------------------------------------------------------------------
# Tab Connessione
# ------------------------------------------------------------------
def _carica_gruppi_esistenti(self):
"""Legge i profili salvati e popola la tendina con i gruppi esistenti."""
import config_manager
profili = config_manager.load_profiles()
gruppi = set()
for dati in profili.values():
g = dati.get("group", "").strip()
if g:
gruppi.add(g)
self.combo_gruppo.addItems(sorted(list(gruppi)))
self.combo_gruppo.setCurrentText("")
# ------------------------------------------------------------------
# Tab Connessione
# ------------------------------------------------------------------
def _build_tab_connessione(self):
layout = QFormLayout(self.tab_conn)
layout.setSpacing(10)
layout.setContentsMargins(12, 15, 12, 10)
layout.setLabelAlignment(Qt.AlignmentFlag.AlignRight)
self.edit_host = QLineEdit()
self.edit_host.setPlaceholderText(t("sd.host_ph"))
lbl_host = QLabel(t("sd.host"))
lbl_host.setMinimumWidth(115)
layout.addRow(lbl_host, self.edit_host)
self.edit_port = QLineEdit()
self.edit_port.setMaximumWidth(80)
lbl_port = QLabel(t("sd.port"))
lbl_port.setMinimumWidth(115)
layout.addRow(lbl_port, self.edit_port)
self.edit_user = QLineEdit()
self.edit_user.setPlaceholderText(t("sd.user_ph"))
lbl_user = QLabel(t("sd.user"))
lbl_user.setMinimumWidth(115)
layout.addRow(lbl_user, self.edit_user)
self.grp_rdp = QGroupBox(t("sd.grp.rdp") if not t("sd.grp.rdp").startswith("sd.") else "Opzioni RDP")
rdp_layout = QFormLayout(self.grp_rdp)
# 1. Client RDP (creato per primo — serve a _aggiorna_rdp_open)
self.combo_rdp_client = QComboBox()
_rdp_tools = _installed_tools("rdp") or ["xfreerdp"]
self.combo_rdp_client.addItems(_rdp_tools)
rdp_layout.addRow(t("sd.rdp.client") if not t("sd.rdp.client").startswith("sd.") else "Client RDP:", self.combo_rdp_client)
self.edit_rdp_domain = QLineEdit()
self.edit_rdp_domain.setPlaceholderText(t("sd.rdp.domain_ph") if not t("sd.rdp.domain_ph").startswith("sd.") else "es. MAGGIOLI")
rdp_layout.addRow(t("sd.rdp.domain") if not t("sd.rdp.domain").startswith("sd.") else "Dominio:", self.edit_rdp_domain)
# Separatore visivo
from PyQt6.QtWidgets import QFrame as _QFrame
_sep = _QFrame(); _sep.setFrameShape(_QFrame.Shape.HLine)
_sep.setStyleSheet("color:#ccc;")
rdp_layout.addRow(_sep)
# 2. Modalita apertura (dopo il client, cosi il connect funziona)
self.combo_rdp_open = QComboBox()
self.combo_rdp_open.setMinimumWidth(260)
self.combo_rdp_open.setSizePolicy(
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
# Fallback hardcoded per compatibilita con translations.py non aggiornato
_lbl_ext = t("sd.rdp.open_ext") if not t("sd.rdp.open_ext").startswith("sd.") else "Finestra esterna"
_lbl_int = t("sd.rdp.open_int") if not t("sd.rdp.open_int").startswith("sd.") else "Pannello interno"
self.combo_rdp_open.addItem(_lbl_ext, "external")
self.combo_rdp_open.addItem(_lbl_int, "internal")
_lbl_mode = t("sd.rdp.open_mode") if not t("sd.rdp.open_mode").startswith("sd.") else "Modalita:"
rdp_layout.addRow(_lbl_mode, self.combo_rdp_open)
self.lbl_rdp_embed_warn = QLabel(t("sd.rdp.embed_v2_warn") if not t("sd.rdp.embed_v2_warn").startswith("sd.") else "Pannello interno richiede xfreerdp3")
self.lbl_rdp_embed_warn.setStyleSheet("color:#c09020; font-size:10px;")
self.lbl_rdp_embed_warn.setWordWrap(True)
self.lbl_rdp_embed_warn.setVisible(False)
rdp_layout.addRow("", self.lbl_rdp_embed_warn)
# Connect ora che entrambi i widget esistono
self.combo_rdp_client.currentTextChanged.connect(self._aggiorna_rdp_open)
self.chk_rdp_fs = QCheckBox(t("sd.rdp.fullscreen") if not t("sd.rdp.fullscreen").startswith("sd.") else "Schermo intero")
self.chk_rdp_fs.setChecked(True)
rdp_layout.addRow("", self.chk_rdp_fs)
self.chk_rdp_clip = QCheckBox(t("sd.rdp.clipboard") if not t("sd.rdp.clipboard").startswith("sd.") else "Condividi clipboard")
self.chk_rdp_clip.setChecked(True)
rdp_layout.addRow("", self.chk_rdp_clip)
self.chk_rdp_drives = QCheckBox(t("sd.rdp.drives") if not t("sd.rdp.drives").startswith("sd.") else "Condividi cartelle locali")
rdp_layout.addRow("", self.chk_rdp_drives)
# Autenticazione NLA: NTLM (veloce) o Kerberos+NTLM (standard AD)
self.combo_rdp_auth = QComboBox()
self.combo_rdp_auth.setMinimumWidth(260)
self.combo_rdp_auth.setSizePolicy(
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
_lbl_ntlm = t("sd.rdp.auth_ntlm") if not t("sd.rdp.auth_ntlm").startswith("sd.") else "NTLM (veloce, senza Kerberos)"
_lbl_kerb = t("sd.rdp.auth_kerberos") if not t("sd.rdp.auth_kerberos").startswith("sd.") else "Kerberos + NTLM (standard AD)"
_tip_auth = t("sd.rdp.auth_tooltip") if not t("sd.rdp.auth_tooltip").startswith("sd.") else "NTLM: connessione rapida. Kerberos: standard AD, puo impiegare 60s+"
self.combo_rdp_auth.addItem(_lbl_ntlm, "ntlm")
self.combo_rdp_auth.addItem(_lbl_kerb, "kerberos")
self.combo_rdp_auth.setToolTip(_tip_auth)
_lbl_auth = t("sd.rdp.auth") if not t("sd.rdp.auth").startswith("sd.") else "Autenticazione:"
rdp_layout.addRow(_lbl_auth, self.combo_rdp_auth)
layout.addRow(self.grp_rdp)
self.grp_vnc = QGroupBox(t("sd.grp.vnc"))
vnc_layout = QFormLayout(self.grp_vnc)
self.chk_vnc_internal = QCheckBox(t("sd.vnc.integrated"))
self.chk_vnc_internal.setChecked(True)
vnc_layout.addRow("", self.chk_vnc_internal)
self.combo_vnc_client = QComboBox()
_vnc_tools = _installed_tools("vnc") or ["vncviewer"]
self.combo_vnc_client.addItems(_vnc_tools)
vnc_layout.addRow(t("sd.vnc.client"), self.combo_vnc_client)
self.combo_vnc_color = QComboBox()
self.combo_vnc_color.addItems([t("sd.vnc.color_32"), t("sd.vnc.color_16"), t("sd.vnc.color_8")])
vnc_layout.addRow(t("sd.vnc.color"), self.combo_vnc_color)
self.combo_vnc_quality = QComboBox()
self.combo_vnc_quality.addItems([t("sd.vnc.q_best"), t("sd.vnc.q_good"), t("sd.vnc.q_fast")])
self.combo_vnc_quality.setCurrentIndex(2)
vnc_layout.addRow(t("sd.vnc.quality"), self.combo_vnc_quality)
layout.addRow(self.grp_vnc)
self.grp_ftp = QGroupBox(t("sd.grp.ftp"))
ftp_layout = QFormLayout(self.grp_ftp)
self.chk_ftp_tls = QCheckBox(t("sd.ftp.tls"))
self.chk_ftp_tls.toggled.connect(self._aggiorna_porta_ftp)
ftp_layout.addRow("", self.chk_ftp_tls)
self.chk_ftp_passive = QCheckBox(t("sd.ftp.passive"))
self.chk_ftp_passive.setChecked(True)
ftp_layout.addRow("", self.chk_ftp_passive)
lbl_ftp_note = QLabel(t("sd.ftp.note"))
lbl_ftp_note.setWordWrap(True)
lbl_ftp_note.setStyleSheet(
"background:#fef9e7; border:1px solid #f0c050; border-radius:4px; "
"padding:6px; font-size:11px; color:#555; margin-top:4px;"
)
ftp_layout.addRow(lbl_ftp_note)
layout.addRow(self.grp_ftp)
self.grp_tunnel = QGroupBox(t("sd.grp.tunnel"))
t_layout = QFormLayout(self.grp_tunnel)
self.combo_tunnel_type = QComboBox()
self.combo_tunnel_type.addItems(["Proxy SOCKS (-D)", "Locale (-L)", "Remoto (-R)"])
self.combo_tunnel_type.currentTextChanged.connect(self._aggiorna_tunnel_fields)
t_layout.addRow(t("sd.tunnel.type"), self.combo_tunnel_type)
self.edit_tunnel_lport = QLineEdit("1080")
self.edit_tunnel_lport.setMaximumWidth(80)
t_layout.addRow(t("sd.tunnel.lport"), self.edit_tunnel_lport)
self.edit_tunnel_rhost = QLineEdit()
self.edit_tunnel_rhost.setPlaceholderText(t("sd.tunnel.rhost_ph"))
t_layout.addRow(t("sd.tunnel.rhost"), self.edit_tunnel_rhost)
self.edit_tunnel_rport = QLineEdit()
self.edit_tunnel_rport.setMaximumWidth(80)
self.edit_tunnel_rport.setPlaceholderText(t("sd.tunnel.rport_ph"))
t_layout.addRow(t("sd.tunnel.rport"), self.edit_tunnel_rport)
layout.addRow(self.grp_tunnel)
self.grp_serial = QGroupBox(t("sd.grp.serial"))
ser_layout = QFormLayout(self.grp_serial)
self.edit_serial_dev = QLineEdit("/dev/ttyUSB0")
ser_layout.addRow(t("sd.serial.device"), self.edit_serial_dev)
self.combo_baud = QComboBox()
self.combo_baud.addItems(["9600","19200","38400","57600","115200","230400","460800","921600"])
self.combo_baud.setCurrentText("115200")
ser_layout.addRow(t("sd.serial.baud"), self.combo_baud)
self.combo_data_bits = QComboBox()
self.combo_data_bits.addItems(["5","6","7","8"])
self.combo_data_bits.setCurrentText("8")
ser_layout.addRow(t("sd.serial.databits"), self.combo_data_bits)
self.combo_parity = QComboBox()
self.combo_parity.addItems(["None","Even","Odd","Mark","Space"])
ser_layout.addRow(t("sd.serial.parity"), self.combo_parity)
self.combo_stop_bits = QComboBox()
self.combo_stop_bits.addItems(["1","1.5","2"])
ser_layout.addRow(t("sd.serial.stopbits"), self.combo_stop_bits)
layout.addRow(self.grp_serial)
self.grp_wol = QGroupBox(t("sd.grp.wol"))
wol_layout = QFormLayout(self.grp_wol)
self.chk_wol = QCheckBox(t("sd.wol.enable"))
self.chk_wol.setToolTip(t("sd.wol.enable_tip"))
wol_layout.addRow("", self.chk_wol)
self.edit_wol_mac = QLineEdit()
self.edit_wol_mac.setPlaceholderText("es. AA:BB:CC:DD:EE:FF")
self.edit_wol_mac.setMaximumWidth(180)
wol_layout.addRow(t("sd.wol.mac"), self.edit_wol_mac)
self.spin_wol_wait = QSpinBox()
self.spin_wol_wait.setRange(1, 120)
self.spin_wol_wait.setValue(20)
self.spin_wol_wait.setSuffix(" s")
self.spin_wol_wait.setMaximumWidth(80)
self.spin_wol_wait.setToolTip(t("sd.wol.wait_tip"))
wol_layout.addRow(t("sd.wol.wait"), self.spin_wol_wait)
layout.addRow(self.grp_wol)
# ------------------------------------------------------------------
# Tab Autenticazione
# ------------------------------------------------------------------
def _build_tab_autenticazione(self):
layout = QFormLayout(self.tab_auth)
layout.setSpacing(10)
layout.setLabelAlignment(Qt.AlignmentFlag.AlignRight)
self.edit_password = QLineEdit()
self.edit_password.setEchoMode(QLineEdit.EchoMode.Password)
self.edit_password.setPlaceholderText(t("sd.pwd_ph"))
self.btn_mostra_pwd = QToolButton()
self.btn_mostra_pwd.setText("👁")
self.btn_mostra_pwd.setCheckable(True)
self.btn_mostra_pwd.setToolTip(t("sd.pwd_show_tip"))
self.btn_mostra_pwd.toggled.connect(
lambda checked: self.edit_password.setEchoMode(
QLineEdit.EchoMode.Normal if checked else QLineEdit.EchoMode.Password
)
)
pwd_row = QHBoxLayout()
pwd_row.setContentsMargins(0, 0, 0, 0)
pwd_row.addWidget(self.edit_password)
pwd_row.addWidget(self.btn_mostra_pwd)
layout.addRow(t("sd.pwd"), pwd_row)
pkey_row = QHBoxLayout()
self.edit_pkey = QLineEdit()
self.edit_pkey.setPlaceholderText(t("sd.pkey_ph"))
self.btn_pkey_browse = QPushButton("...")
self.btn_pkey_browse.setMaximumWidth(30)
self.btn_pkey_browse.clicked.connect(self._sfoglia_chiave)
pkey_row.addWidget(self.edit_pkey)
pkey_row.addWidget(self.btn_pkey_browse)
layout.addRow(t("sd.pkey"), pkey_row)
self.grp_chiavi = QGroupBox(t("sd.grp.keys"))
chiavi_layout = QVBoxLayout(self.grp_chiavi)
chiavi_layout.setSpacing(6)
riga_esistenti = QHBoxLayout()
lbl_chiavi = QLabel(t("sd.keys.existing"))
lbl_chiavi.setMinimumWidth(110)
self.combo_chiavi = QComboBox()
self.combo_chiavi.setToolTip(t("sd.keys.existing"))
self.combo_chiavi.currentTextChanged.connect(self._chiave_selezionata)
btn_ricarica = QPushButton("↺")
btn_ricarica.setMaximumWidth(28)
btn_ricarica.setToolTip(t("sd.keys.reload_tip"))
btn_ricarica.clicked.connect(self._carica_chiavi_esistenti)
riga_esistenti.addWidget(lbl_chiavi)
riga_esistenti.addWidget(self.combo_chiavi, 1)
riga_esistenti.addWidget(btn_ricarica)
chiavi_layout.addLayout(riga_esistenti)
riga_genera = QHBoxLayout()
lbl_tipo = QLabel(t("sd.keys.generate"))
lbl_tipo.setMinimumWidth(110)
self.combo_key_type = QComboBox()
self.combo_key_type.addItems([t("sd.keys.type_ed25519"), t("sd.keys.type_rsa"), t("sd.keys.type_ecdsa")])
self.edit_key_comment = QLineEdit()
self.edit_key_comment.setPlaceholderText(t("sd.keys.comment_ph"))
self.edit_key_comment.setText(f"{os.environ.get('USER', 'user')}@{__import__('socket').gethostname()}")
btn_genera = QPushButton(t("sd.keys.gen_btn"))
btn_genera.setToolTip(t("sd.keys.gen_tip"))
btn_genera.clicked.connect(self._genera_chiave)
riga_genera.addWidget(lbl_tipo)
riga_genera.addWidget(self.combo_key_type, 1)
riga_genera.addWidget(self.edit_key_comment)
riga_genera.addWidget(btn_genera)
chiavi_layout.addLayout(riga_genera)
riga_copia = QHBoxLayout()
self.btn_copia_server = QPushButton(t("sd.keys.copy_server"))
self.btn_copia_server.setToolTip(t("sd.keys.copy_tip"))
self.btn_copia_server.clicked.connect(self._copia_chiave_server)
self.btn_copia_server.setStyleSheet(
"QPushButton { background:#2d5a8e; color:#fff; border-radius:3px; padding:4px 12px; }"
"QPushButton:hover { background:#4e7abc; }"
)
riga_copia.addWidget(self.btn_copia_server)
self.btn_mostra_pub = QPushButton(t("sd.keys.show_pub"))
self.btn_mostra_pub.setToolTip(t("sd.keys.show_pub_tip"))
self.btn_mostra_pub.clicked.connect(self._mostra_chiave_pubblica)
riga_copia.addWidget(self.btn_mostra_pub)
chiavi_layout.addLayout(riga_copia)
layout.addRow(self.grp_chiavi)
self._carica_chiavi_esistenti()
self.grp_jump = QGroupBox(t("sd.grp.jump"))
jlayout = QFormLayout(self.grp_jump)
lbl_jump_info = QLabel(t("sd.jump.info"))
lbl_jump_info.setWordWrap(True)
lbl_jump_info.setStyleSheet(
"background:#eef3fa; border:1px solid #b8cfe8; border-radius:4px; "
"padding:8px; font-size:11px; color:#333; margin-bottom:4px;"
)
jlayout.addRow(lbl_jump_info)
self.edit_jump_host = QLineEdit()
self.edit_jump_host.setPlaceholderText(t("sd.jump.host_ph"))
jlayout.addRow(t("sd.jump.host"), self.edit_jump_host)
self.edit_jump_user = QLineEdit()
self.edit_jump_user.setPlaceholderText(t("sd.jump.user_ph"))
jlayout.addRow(t("sd.jump.user"), self.edit_jump_user)
self.edit_jump_port = QLineEdit("22")
self.edit_jump_port.setMaximumWidth(80)
jlayout.addRow(t("sd.jump.port"), self.edit_jump_port)
layout.addRow(self.grp_jump)
def _carica_chiavi_esistenti(self):
self.combo_chiavi.clear()
self.combo_chiavi.addItem(t("sd.keys.none"))
ssh_dir = os.path.expanduser("~/.ssh")
if not os.path.isdir(ssh_dir):
return
# Cerca file di chiave privata (non .pub, non known_hosts, non config)
esclusi = {".pub", "known_hosts", "authorized_keys", "config"}
try:
for f in sorted(os.listdir(ssh_dir)):
path = os.path.join(ssh_dir, f)
if os.path.isfile(path) and not any(f.endswith(e) or f == e for e in esclusi):
# Verifica che sia una chiave privata leggendo la prima riga
try:
with open(path, "r", errors="ignore") as fh:
prima = fh.readline().strip()
if "PRIVATE KEY" in prima or prima.startswith("-----BEGIN"):
self.combo_chiavi.addItem(f"~/.ssh/{f}", path)
except Exception:
pass
except Exception:
pass
def _chiave_selezionata(self, testo: str):
path = self.combo_chiavi.currentData()
if path:
self.edit_pkey.setText(path)
elif testo == t("sd.keys.none"):
self.edit_pkey.clear()
def _genera_chiave(self):
"""Genera una nuova coppia di chiavi SSH con ssh-keygen."""
import shutil, subprocess
from PyQt6.QtWidgets import QInputDialog
if not shutil.which("ssh-keygen"):
QMessageBox.critical(self, t("error.title"), t("sd.keygen.missing"))
return
tipo_raw = self.combo_key_type.currentText()
if "ed25519" in tipo_raw:
tipo, bits = "ed25519", None
elif "rsa" in tipo_raw:
tipo, bits = "rsa", "4096"
else:
tipo, bits = "ecdsa", "521"
commento = self.edit_key_comment.text().strip() or "pcm-key"
ssh_dir = os.path.expanduser("~/.ssh")
os.makedirs(ssh_dir, mode=0o700, exist_ok=True)
nome_default = f"id_{tipo}_pcm"
nome, ok = QInputDialog.getText(
self, t("sd.keygen.title"), t("sd.keygen.label"), text=nome_default
)
if not ok or not nome.strip():
return
nome = nome.strip()
percorso = os.path.join(ssh_dir, nome)
if os.path.exists(percorso):
risposta = QMessageBox.question(
self, t("sd.keygen.title"),
t("sd.keygen.overwrite", path=percorso),
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
)
if risposta != QMessageBox.StandardButton.Yes:
return
passphrase, ok2 = QInputDialog.getText(
self, t("sd.keygen.passphrase_title"),
t("sd.keygen.passphrase_label"),
QLineEdit.EchoMode.Password
)
if not ok2:
return
cmd = ["ssh-keygen", "-t", tipo, "-f", percorso, "-C", commento, "-N", passphrase or ""]
if bits:
cmd += ["-b", bits]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
if result.returncode == 0:
self.edit_pkey.setText(percorso)
self._carica_chiavi_esistenti()
for i in range(self.combo_chiavi.count()):
if self.combo_chiavi.itemData(i) == percorso:
self.combo_chiavi.setCurrentIndex(i)
break
QMessageBox.information(
self, t("sd.keygen.done"),
t("sd.keygen.done_msg", priv=percorso, pub=percorso+".pub")
)
else:
QMessageBox.critical(self, t("error.title"), result.stderr)
except subprocess.TimeoutExpired:
QMessageBox.critical(self, t("error.title"), t("sd.keygen.timeout"))
except Exception as e:
QMessageBox.critical(self, t("error.title"), str(e))
def _copia_chiave_server(self):
"""Guida l'utente a copiare la chiave pubblica sul server con ssh-copy-id."""
import shutil, subprocess
from PyQt6.QtWidgets import QDialog, QVBoxLayout, QTextEdit, QPushButton, QDialogButtonBox
pkey = self.edit_pkey.text().strip()
host = self.edit_host.text().strip()
user = self.edit_user.text().strip()
port = self.edit_port.text().strip() or "22"
if not shutil.which("ssh-copy-id"):
QMessageBox.critical(self, t("error.title"), t("sd.copykey.missing_sshcopyid"))
return
if not pkey:
QMessageBox.warning(self, t("sd.grp.keys").strip(), t("sd.copykey.no_key"))
return
pub_path = pkey + ".pub"
if not os.path.exists(pub_path):
QMessageBox.warning(self, t("sd.grp.keys").strip(),
t("sd.copykey.no_pub", path=pub_path))
return
if not host:
QMessageBox.warning(self, t("sd.grp.keys").strip(), t("sd.copykey.no_host"))
return
target = f"{user}@{host}" if user else host
cmd = f"ssh-copy-id -i '{pub_path}' -p {port} {target}"
dlg = QDialog(self)
dlg.setWindowTitle(t("sd.copykey.title"))
dlg.setMinimumWidth(560)
lay = QVBoxLayout(dlg)
from PyQt6.QtWidgets import QLabel as _QLabel
info = _QLabel(t("sd.copykey.info", target=target, port=port, pub=pub_path, cmd=cmd))
info.setWordWrap(True)
info.setStyleSheet("padding:8px;")
lay.addWidget(info)
try:
with open(pub_path) as f:
pub_content = f.read().strip()
except Exception:
pub_content = "(impossibile leggere il file)"
txt_pub = QTextEdit()
txt_pub.setReadOnly(True)
txt_pub.setPlainText(pub_content)
txt_pub.setFixedHeight(60)
txt_pub.setStyleSheet("font-family:monospace; font-size:10px; background:#f8f8f8;")
lay.addWidget(_QLabel(t("sd.copykey.content_lbl")))
lay.addWidget(txt_pub)
bbox = QDialogButtonBox()
btn_esegui = bbox.addButton(t("sd.copykey.run"), QDialogButtonBox.ButtonRole.AcceptRole)
btn_manuale = bbox.addButton(t("sd.copykey.manual"), QDialogButtonBox.ButtonRole.ActionRole)
btn_annulla = bbox.addButton(t("close.cancel"), QDialogButtonBox.ButtonRole.RejectRole)
lay.addWidget(bbox)
def esegui():
dlg.accept()
import shutil as _sh
xterm = _sh.which("xterm") or "xterm"
cmd_xterm = (
f"{xterm} -title 'PCM — ssh-copy-id' "
f"-e bash -c '{cmd}; echo; echo \"Premi Invio per chiudere...\"; read'"
)
subprocess.Popen(cmd_xterm, shell=True)
def copia_testo():
from PyQt6.QtWidgets import QApplication
QApplication.clipboard().setText(pub_content)
QMessageBox.information(dlg, t("btn.copied").strip("✅ ").strip("!"),
t("sd.copykey.copied"))
btn_esegui.clicked.connect(esegui)
btn_manuale.clicked.connect(copia_testo)
btn_annulla.clicked.connect(dlg.reject)
dlg.exec()
def _mostra_chiave_pubblica(self):
"""Mostra il contenuto della chiave pubblica selezionata."""
from PyQt6.QtWidgets import QDialog, QVBoxLayout, QTextEdit, QPushButton, QLabel as _QLabel
pkey = self.edit_pkey.text().strip()
if not pkey:
QMessageBox.warning(self, t("sd.grp.keys").strip(), t("sd.showpub.no_key"))
return
pub_path = pkey + ".pub"
if not os.path.exists(pub_path):
QMessageBox.warning(self, t("sd.grp.keys").strip(),
t("sd.showpub.no_file", path=pub_path))
return
try:
with open(pub_path) as f:
contenuto = f.read().strip()
except Exception as e:
QMessageBox.critical(self, t("sd.showpub.read_err"), str(e))
return
dlg = QDialog(self)
dlg.setWindowTitle(t("sd.showpub.title", name=os.path.basename(pub_path)))
dlg.setMinimumWidth(600)
lay = QVBoxLayout(dlg)
lay.addWidget(_QLabel(f"<b>{pub_path}</b>"))
txt = QTextEdit()
txt.setReadOnly(True)
txt.setPlainText(contenuto)
txt.setStyleSheet("font-family:monospace; font-size:11px;")
lay.addWidget(txt)
btn_row = QHBoxLayout()
btn_copia = QPushButton(t("sd.copykey.manual"))
btn_ok = QPushButton(t("close.dialog"))
btn_copia.clicked.connect(lambda: (
__import__('PyQt6.QtWidgets', fromlist=['QApplication']).QApplication.clipboard().setText(contenuto),
btn_copia.setText("✅ " + t("btn.copied").strip("✅ ").strip("!"))
))
btn_ok.clicked.connect(dlg.accept)
btn_row.addWidget(btn_copia)
btn_row.addStretch()
btn_row.addWidget(btn_ok)
lay.addLayout(btn_row)
dlg.exec()
def _sfoglia_chiave(self):
path, _ = QFileDialog.getOpenFileName(
self, t("sd.browse_key"),
os.path.expanduser("~/.ssh"), "Tutti i file (*)"
)
if path:
self.edit_pkey.setText(path)
# ------------------------------------------------------------------
# Tab Terminale
# ------------------------------------------------------------------
def _build_tab_terminale(self):
layout = QFormLayout(self.tab_term)
layout.setSpacing(10)
layout.setLabelAlignment(Qt.AlignmentFlag.AlignRight)
# Leggi default dalle impostazioni globali
import config_manager as _cm
_ts = _cm.load_settings().get('terminal', {})
_def_tema = _ts.get('default_theme', 'Scuro (Default)')
_def_font = _ts.get('default_font', 'Monospace')
_def_size = _ts.get('default_font_size', 11)
self.combo_tema = QComboBox()
for tm in TERMINAL_THEMES.keys():
self.combo_tema.addItem(tm)
idx_def = self.combo_tema.findText(_def_tema)
if idx_def >= 0: self.combo_tema.setCurrentIndex(idx_def)
layout.addRow(t("sd.term.theme"), self.combo_tema)
self.combo_font = QComboBox()
self.combo_font.addItems([
"Monospace", "DejaVu Sans Mono", "Hack", "JetBrains Mono",
"Fira Code", "Source Code Pro", "Inconsolata", "Terminus",
"Noto Mono", "Roboto Mono"
])
idx_def_f = self.combo_font.findText(_def_font)
if idx_def_f >= 0: self.combo_font.setCurrentIndex(idx_def_f)
layout.addRow(t("sd.term.font"), self.combo_font)
self.spin_font_size = QSpinBox()
self.spin_font_size.setRange(6, 32)
self.spin_font_size.setValue(_def_size)
self.spin_font_size.setMaximumWidth(60)
layout.addRow(t("sd.term.font_size"), self.spin_font_size)
self.edit_startup_cmd = QLineEdit()
self.edit_startup_cmd.setPlaceholderText(t("sd.term.startup_ph"))
layout.addRow(t("sd.term.startup_cmd"), self.edit_startup_cmd)
self.edit_pre_cmd = QLineEdit()
self.edit_pre_cmd.setPlaceholderText(t("sd.term.pre_cmd_ph"))
lbl_pre = QLabel(t("sd.term.pre_cmd"))
lbl_pre.setToolTip(t("sd.term.pre_cmd_tip"))
layout.addRow(lbl_pre, self.edit_pre_cmd)
self.spin_pre_cmd_timeout = QSpinBox()
self.spin_pre_cmd_timeout.setRange(0, 120)
self.spin_pre_cmd_timeout.setValue(15)
self.spin_pre_cmd_timeout.setSuffix(t("sd.term.timeout_sfx"))
self.spin_pre_cmd_timeout.setMaximumWidth(170)
self.spin_pre_cmd_timeout.setToolTip(t("sd.term.timeout_tip"))
layout.addRow(t("sd.term.timeout"), self.spin_pre_cmd_timeout)
self.chk_sftp_browser = QCheckBox(t("sd.term.sftp_auto"))
self.chk_sftp_browser.setChecked(True)
layout.addRow("", self.chk_sftp_browser)
self.chk_log = QCheckBox(t("sd.term.log"))
layout.addRow("", self.chk_log)
self.chk_paste_right = QCheckBox(t("sd.term.paste_right"))
layout.addRow("", self.chk_paste_right)
log_row = QHBoxLayout()
self.edit_log_dir = QLineEdit("/tmp/pcm_logs")
self.btn_log_browse = QPushButton("...")
self.btn_log_browse.setMaximumWidth(30)
self.btn_log_browse.clicked.connect(self._sfoglia_log_dir)
log_row.addWidget(self.edit_log_dir)
log_row.addWidget(self.btn_log_browse)
layout.addRow(t("sd.term.log_dir"), log_row)
def _sfoglia_log_dir(self):
d = QFileDialog.getExistingDirectory(self, t("sd.browse_log"))
if d:
self.edit_log_dir.setText(d)
# ------------------------------------------------------------------
# Tab Avanzate
# ------------------------------------------------------------------
def _build_tab_avanzate(self):
layout = QFormLayout(self.tab_adv)
layout.setSpacing(10)
layout.setLabelAlignment(Qt.AlignmentFlag.AlignRight)
self.grp_ssh_adv = QGroupBox(t("sd.grp.ssh_adv"))
ssh_layout = QFormLayout(self.grp_ssh_adv)
self.chk_x11 = QCheckBox(t("sd.ssh.x11"))
ssh_layout.addRow("", self.chk_x11)
self.chk_compression = QCheckBox(t("sd.ssh.compression"))
ssh_layout.addRow("", self.chk_compression)
self.chk_keepalive = QCheckBox(t("sd.ssh.keepalive"))
ssh_layout.addRow("", self.chk_keepalive)
self.chk_strict_host = QCheckBox(t("sd.ssh.strict"))
ssh_layout.addRow("", self.chk_strict_host)
layout.addRow(self.grp_ssh_adv)
self.grp_ssh_open = QGroupBox(t("sd.grp.ssh_open"))
ssh_open_layout = QFormLayout(self.grp_ssh_open)
self.combo_ssh_open = QComboBox()
self.combo_ssh_open.addItems([
"Terminale interno",
"Terminale esterno",
])
ssh_open_layout.addRow(t("sd.open_with"), self.combo_ssh_open)
layout.addRow(self.grp_ssh_open)
self.grp_sftp_open = QGroupBox(t("sd.grp.sftp_open"))
sftp_open_layout = QFormLayout(self.grp_sftp_open)
self.combo_sftp_open = QComboBox()
self.combo_sftp_open.addItems([
t("sd.open_int"),
t("sd.open_browser_ext"),
t("sd.sftp.open_term_int"),
t("sd.sftp.open_term_ext"),
])
sftp_open_layout.addRow(t("sd.open_with"), self.combo_sftp_open)
layout.addRow(self.grp_sftp_open)
self.grp_ftp_open = QGroupBox(t("sd.grp.ftp_open"))
ftp_open_layout = QFormLayout(self.grp_ftp_open)
self.combo_ftp_open = QComboBox()
self.combo_ftp_open.addItems([
t("sd.open_int"),
t("sd.open_browser_ext"),
t("sd.ftp.open_term_int"),
t("sd.ftp.open_term_ext"),
])
ftp_open_layout.addRow(t("sd.open_with"), self.combo_ftp_open)
layout.addRow(self.grp_ftp_open)
self.grp_term_ext = QGroupBox(t("sd.grp.terminal"))
te_layout = QFormLayout(self.grp_term_ext)
self.combo_term_ext = QComboBox()
self.combo_term_ext.setEditable(True)
self.combo_term_ext.setInsertPolicy(QComboBox.InsertPolicy.NoInsert)
_term_tools = _installed_tools("terminal")
self.combo_term_ext.addItems(["Terminale Interno"] + _term_tools)
te_layout.addRow(t("sd.terminal_lbl"), self.combo_term_ext)
layout.addRow(self.grp_term_ext)
# ------------------------------------------------------------------
# Tab Note
# ------------------------------------------------------------------
def _build_tab_note(self):
layout = QVBoxLayout(self.tab_note)
self.edit_notes = QTextEdit()
self.edit_notes.setPlaceholderText(t("sd.notes_ph"))
layout.addWidget(self.edit_notes)
def _build_tab_macro(self):
layout = QVBoxLayout(self.tab_macro)
layout.setContentsMargins(10, 10, 10, 10)
layout.setSpacing(6)
lbl_info = QLabel(t("sd.macro.info"))
lbl_info.setWordWrap(True)
lbl_info.setStyleSheet(
"background:#f0f6ff; border:1px solid #b0c8e8; border-radius:4px; "
"padding:6px; font-size:11px; color:#335;"
)
layout.addWidget(lbl_info)
self._lista_macro = QListWidget()
self._lista_macro.setAlternatingRowColors(True)
self._lista_macro.setStyleSheet(
"QListWidget { background:#ffffff; color:#111111; border:1px solid #ccc; }"
"QListWidget::item:selected { background:#4e7abc; color:#ffffff; }"
"QListWidget::item:alternate { background:#f7f7f7; }"
)
layout.addWidget(self._lista_macro, 1)
form = QWidget()
fl = QFormLayout(form)
fl.setSpacing(6)
fl.setLabelAlignment(Qt.AlignmentFlag.AlignRight)
self._edit_macro_nome = QLineEdit()
self._edit_macro_nome.setPlaceholderText(t("sd.macro.name_ph"))
fl.addRow(t("sd.macro.name"), self._edit_macro_nome)
self._edit_macro_cmd = QLineEdit()
self._edit_macro_cmd.setPlaceholderText(t("sd.macro.cmd_ph"))
fl.addRow(t("sd.macro.cmd"), self._edit_macro_cmd)
layout.addWidget(form)
btn_row = QHBoxLayout()
btn_add = QPushButton(t("sd.macro.add"))
btn_add.clicked.connect(self._macro_aggiungi)
btn_mod = QPushButton(t("sd.macro.update"))
btn_mod.clicked.connect(self._macro_aggiorna)
btn_del = QPushButton(t("sd.macro.delete"))
btn_del.clicked.connect(self._macro_elimina)
btn_up = QPushButton("▲")
btn_up.setMaximumWidth(32)
btn_up.clicked.connect(self._macro_su)
btn_dn = QPushButton("▼")
btn_dn.setMaximumWidth(32)
btn_dn.clicked.connect(self._macro_giu)
for b in (btn_add, btn_mod, btn_del, btn_up, btn_dn):
btn_row.addWidget(b)
btn_row.addStretch()
layout.addLayout(btn_row)
self._lista_macro.currentItemChanged.connect(self._macro_selezionata)
def _macro_selezionata(self, item):
if item is None:
return
dati = item.data(Qt.ItemDataRole.UserRole)
if dati:
self._edit_macro_nome.setText(dati.get("nome", ""))
self._edit_macro_cmd.setText(dati.get("cmd", ""))
def _macro_aggiungi(self):
nome = self._edit_macro_nome.text().strip()
cmd = self._edit_macro_cmd.text().strip()
if not nome or not cmd:
QMessageBox.warning(self, t("sd.tab.macros").strip(), t("sd.macro.warn"))
return
item = QListWidgetItem(f"[{nome}] → {cmd}")