-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvnc_widget.py
More file actions
670 lines (576 loc) · 25.3 KB
/
Copy pathvnc_widget.py
File metadata and controls
670 lines (576 loc) · 25.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
"""
vnc_widget.py - Viewer VNC integrato (GTK3)
Strategia con fallback automatico:
1. gtk-vnc (gir1.2-gtk-vnc-2.0) — widget nativo, zero processi esterni
2. Gtk.Socket + vncviewer — embedding X11 del client VNC installato
3. Messaggio di errore con istruzioni
Dipendenze per metodo 1 (raccomandato):
sudo apt install gir1.2-gtk-vnc-2.0
Dipendenze per metodo 2 (fallback):
uno qualsiasi tra: vncviewer, xtightvncviewer, tigervnc-viewer, xvnc4viewer
"""
import os
import shutil
import subprocess
from pcm_logging import get_logger as _get_log
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GLib
from translations import t
# Prova a caricare gtk-vnc
_GTKV_OK = False
try:
gi.require_version("GtkVnc", "2.0")
from gi.repository import GtkVnc
_GTKV_OK = True
except Exception:
_get_log(__name__).debug("GtkVnc non disponibile")
def _find_vnc_client() -> str | None:
for c in ["vncviewer", "xtightvncviewer", "xvnc4viewer",
"tigervncviewer", "xtigervncviewer", "krdc", "remmina"]:
if shutil.which(c):
return c
return None
# Keysyms X11 per send_keys
_KEY_CTRL = 0xffe3
_KEY_ALT = 0xffe9
_KEY_DEL = 0xffff
_KEY_F1 = 0xffbe
_KEY_ESC = 0xff1b
_KEY_SUPER = 0xffeb
# ---------------------------------------------------------------------------
# Metodo 1: gtk-vnc nativo
# ---------------------------------------------------------------------------
class _VncGtkVnc(Gtk.Box):
def __init__(self, host, port, password, color_depth=0, quality=2,
on_save_password=None, on_vnc_ready=None):
super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=0)
self._host = host
self._port = str(port)
self._password = password
self._on_save_password = on_save_password
self._on_vnc_ready = on_vnc_ready
self._closed = False
self._scaling = True
self._pointer_local = True
self._keyboard_grab = False
self._read_only = False
# 0=32bpp, 1=16bpp, 2=8bpp | 0=best, 1=good, 2=fast
try:
self._color_depth = int(color_depth) if color_depth is not None else 0
except (ValueError, TypeError):
self._color_depth = 0
try:
self._quality = int(quality) if quality is not None else 2
except (ValueError, TypeError):
self._quality = 2
self._build()
# ------------------------------------------------------------------
# UI
# ------------------------------------------------------------------
def _build(self):
# ── Barra superiore: stato + toolbar ─────────────────────────
topbar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
topbar.get_style_context().add_class("vnc-topbar")
# Label stato (sx)
self._lbl = Gtk.Label(label=f"VNC — {self._host}:{self._port} connessione…")
self._lbl.set_xalign(0.0)
self._lbl.set_hexpand(True)
self._lbl.set_margin_start(8)
topbar.pack_start(self._lbl, True, True, 0)
# Toolbar pulsanti (dx)
tb = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=2)
tb.set_margin_start(4)
tb.set_margin_end(4)
tb.set_margin_top(2)
tb.set_margin_bottom(2)
# Adatta schermo (scaling)
self._btn_scale = Gtk.ToggleButton()
self._btn_scale.set_relief(Gtk.ReliefStyle.NONE)
self._btn_scale.set_tooltip_text(t("vnc.tt_fit_screen"))
self._btn_scale.add(Gtk.Image.new_from_icon_name(
"zoom-fit-best-symbolic", Gtk.IconSize.SMALL_TOOLBAR))
self._btn_scale.set_active(self._scaling)
self._btn_scale.connect("toggled", self._on_scale_toggled)
tb.pack_start(self._btn_scale, False, False, 0)
# Puntatore locale/remoto
self._btn_ptr = Gtk.ToggleButton()
self._btn_ptr.set_relief(Gtk.ReliefStyle.NONE)
self._btn_ptr.set_tooltip_text(t("vnc.tt_pointer"))
self._btn_ptr.add(Gtk.Image.new_from_icon_name(
"input-mouse-symbolic", Gtk.IconSize.SMALL_TOOLBAR))
self._btn_ptr.set_active(self._pointer_local)
self._btn_ptr.connect("toggled", self._on_pointer_toggled)
tb.pack_start(self._btn_ptr, False, False, 0)
# Grab tastiera
self._btn_kb = Gtk.ToggleButton()
self._btn_kb.set_relief(Gtk.ReliefStyle.NONE)
self._btn_kb.set_tooltip_text(t("vnc.tt_keyboard"))
self._btn_kb.add(Gtk.Image.new_from_icon_name(
"input-keyboard-symbolic", Gtk.IconSize.SMALL_TOOLBAR))
self._btn_kb.set_active(self._keyboard_grab)
self._btn_kb.connect("toggled", self._on_keyboard_toggled)
tb.pack_start(self._btn_kb, False, False, 0)
# Sola lettura
self._btn_ro = Gtk.ToggleButton()
self._btn_ro.set_relief(Gtk.ReliefStyle.NONE)
self._btn_ro.set_tooltip_text(t("vnc.tt_readonly"))
self._btn_ro.add(Gtk.Image.new_from_icon_name(
"changes-prevent-symbolic", Gtk.IconSize.SMALL_TOOLBAR))
self._btn_ro.set_active(self._read_only)
self._btn_ro.connect("toggled", self._on_readonly_toggled)
tb.pack_start(self._btn_ro, False, False, 0)
tb.pack_start(Gtk.Separator(orientation=Gtk.Orientation.VERTICAL), False, False, 4)
# Ctrl+Alt+Del
btn_cad = Gtk.Button()
btn_cad.set_relief(Gtk.ReliefStyle.NONE)
btn_cad.set_tooltip_text(t("vnc.tt_cad"))
btn_cad.add(Gtk.Image.new_from_icon_name(
"system-restart-symbolic", Gtk.IconSize.SMALL_TOOLBAR))
btn_cad.connect("clicked", lambda b: self._send_ctrl_alt_del())
tb.pack_start(btn_cad, False, False, 0)
# Ctrl+Alt+F1..F7 (cambio VT)
btn_vt = Gtk.MenuButton()
btn_vt.set_relief(Gtk.ReliefStyle.NONE)
btn_vt.set_tooltip_text(t("vnc.tt_vt"))
btn_vt.add(Gtk.Image.new_from_icon_name(
"computer-symbolic", Gtk.IconSize.SMALL_TOOLBAR))
btn_vt.set_popup(self._build_vt_menu())
tb.pack_start(btn_vt, False, False, 0)
# Screenshot
btn_ss = Gtk.Button()
btn_ss.set_relief(Gtk.ReliefStyle.NONE)
btn_ss.set_tooltip_text(t("vnc.tt_screenshot"))
btn_ss.add(Gtk.Image.new_from_icon_name(
"camera-photo-symbolic", Gtk.IconSize.SMALL_TOOLBAR))
btn_ss.connect("clicked", lambda b: self._screenshot())
tb.pack_start(btn_ss, False, False, 0)
tb.pack_start(Gtk.Separator(orientation=Gtk.Orientation.VERTICAL), False, False, 4)
# Riconnetti
btn_r = Gtk.Button()
btn_r.set_relief(Gtk.ReliefStyle.NONE)
btn_r.set_tooltip_text(t("vnc.tt_reconnect"))
btn_r.add(Gtk.Image.new_from_icon_name(
"view-refresh-symbolic", Gtk.IconSize.SMALL_TOOLBAR))
btn_r.connect("clicked", lambda b: self._riconnetti())
tb.pack_start(btn_r, False, False, 0)
topbar.pack_start(tb, False, False, 0)
self.pack_start(topbar, False, False, 0)
self.pack_start(
Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL),
False, False, 0)
# ── Display VNC ───────────────────────────────────────────────
self._display = GtkVnc.Display()
self._display.set_hexpand(True)
self._display.set_vexpand(True)
self._display.set_scaling(self._scaling)
self._display.set_allow_resize(True)
self._display.set_keep_aspect_ratio(True)
self._display.set_pointer_local(self._pointer_local)
self._display.set_keyboard_grab(self._keyboard_grab)
self._display.set_read_only(self._read_only)
# Imposta depth/quality sul display appena creato, prima di open_host().
# Su Windows VNC (TightVNC, RealVNC, UltraVNC) è necessario farlo
# prima della connessione per evitare lo schermo nero.
self._applica_depth_quality()
self._display.connect("vnc-connected", self._on_connected)
self._display.connect("vnc-initialized", self._on_initialized)
self._display.connect("vnc-disconnected", self._on_disconnected)
self._display.connect("vnc-error", self._on_error)
self._display.connect("vnc-auth-credential", self._on_auth)
self._display.connect("vnc-auth-failure", self._on_auth_failure)
self.pack_start(self._display, True, True, 0)
# Connetti solo dopo che il widget è realizzato
self._display.connect("realize", lambda w: self._connetti())
def _applica_depth_quality(self):
"""Imposta color depth e qualità compressione sul display GtkVnc."""
depth_map = {
0: GtkVnc.DisplayDepthColor.FULL, # 32bpp
1: GtkVnc.DisplayDepthColor.MEDIUM, # 16bpp
2: GtkVnc.DisplayDepthColor.LOW, # 8bpp
}
depth_enum = depth_map.get(self._color_depth, GtkVnc.DisplayDepthColor.FULL)
try:
self._display.set_depth(depth_enum)
except Exception:
_get_log(__name__).debug("eccezione benigna soppressa", exc_info=True)
try:
self._display.set_lossy_encoding(self._quality == 2)
except Exception:
_get_log(__name__).debug("eccezione benigna soppressa", exc_info=True)
def _build_vt_menu(self) -> Gtk.Menu:
menu = Gtk.Menu()
for n in range(1, 8):
key = _KEY_F1 + n - 1
mi = Gtk.MenuItem(label=f"Ctrl+Alt+F{n} (VT{n})")
mi.connect("activate", lambda _, k=key: self._send_keys([_KEY_CTRL, _KEY_ALT, k]))
menu.append(mi)
menu.show_all()
return menu
# ------------------------------------------------------------------
# Connessione
# ------------------------------------------------------------------
def _connetti(self):
try:
# open_host() è il metodo corretto per connessioni TCP con GtkVnc.
# open_fd() con socket Python causa problemi di negoziazione del
# protocollo perché GtkVnc non controlla il fd direttamente.
self._display.open_host(self._host, str(self._port))
except Exception as e:
self._lbl.set_text(f"VNC — errore connessione: {e}")
def _riconnetti(self):
if not self._closed:
try:
self._display.close()
except Exception:
_get_log(__name__).debug("eccezione benigna soppressa", exc_info=True)
self._lbl.set_text(f"VNC — {self._host}:{self._port} riconnessione…")
GLib.timeout_add(800, lambda: self._connetti() or False)
# ------------------------------------------------------------------
# Segnali GtkVnc
# ------------------------------------------------------------------
def _on_connected(self, d):
self._lbl.set_text(f"VNC — {self._host}:{self._port} autenticazione…")
def _on_initialized(self, d):
nome = ""
try:
nome = self._display.get_name() or ""
except Exception:
_get_log(__name__).debug("eccezione benigna soppressa", exc_info=True)
self._lbl.set_text(
f"VNC — {self._host}:{self._port}"
+ (f" [{nome}]" if nome else "")
)
if self._on_vnc_ready:
self._on_vnc_ready()
def _on_disconnected(self, d):
if not self._closed:
self._lbl.set_text(f"VNC — {self._host}:{self._port} disconnesso")
def _on_error(self, d, msg):
self._lbl.set_text(f"VNC errore: {msg}")
def _on_auth_failure(self, d, msg):
self._lbl.set_text(f"VNC — autenticazione fallita: {msg}")
def _on_auth(self, display, credlist):
cred = GtkVnc.DisplayCredential
needs_password = False
needs_username = False
for i in range(credlist.n_values):
v = credlist.get_nth(i)
if v == cred.PASSWORD:
needs_password = True
elif v == cred.USERNAME:
needs_username = True
if needs_password:
pwd = self._password
if not pwd:
pwd = self._chiedi_password(display)
if pwd is not None:
display.set_credential(cred.PASSWORD, pwd)
if needs_username:
display.set_credential(cred.USERNAME, "")
def _chiedi_password(self, display) -> str | None:
"""Dialog modale che chiede la password VNC con opzione di salvataggio."""
toplevel = self.get_toplevel()
dlg = Gtk.Dialog(
title=t("vnc.password_dialog"),
transient_for=toplevel if isinstance(toplevel, Gtk.Window) else None,
modal=True,
)
dlg.set_default_size(360, -1)
dlg.add_button(t("vnc.btn_cancel"), Gtk.ResponseType.CANCEL)
dlg.add_button(t("vnc.btn_connect"), Gtk.ResponseType.OK)
dlg.set_default_response(Gtk.ResponseType.OK)
box = dlg.get_content_area()
box.set_spacing(8)
box.set_margin_start(16)
box.set_margin_end(16)
box.set_margin_top(12)
box.set_margin_bottom(8)
lbl = Gtk.Label(label=f"Password per {self._host}:{self._port}")
lbl.set_xalign(0.0)
box.pack_start(lbl, False, False, 0)
entry = Gtk.Entry()
entry.set_visibility(False)
entry.set_activates_default(True)
box.pack_start(entry, False, False, 0)
chk = Gtk.CheckButton(label=t("vnc.save_password"))
box.pack_start(chk, False, False, 0)
box.show_all()
risposta = dlg.run()
pwd = entry.get_text()
salva = chk.get_active()
dlg.destroy()
if risposta != Gtk.ResponseType.OK or not pwd:
return None
self._password = pwd
if salva and self._on_save_password:
try:
self._on_save_password(pwd)
except Exception:
_get_log(__name__).debug("eccezione benigna soppressa", exc_info=True)
return pwd
# ------------------------------------------------------------------
# Azioni toolbar
# ------------------------------------------------------------------
def _on_scale_toggled(self, btn):
self._scaling = btn.get_active()
try:
self._display.set_scaling(self._scaling)
self._display.set_keep_aspect_ratio(self._scaling)
except Exception:
_get_log(__name__).debug("eccezione benigna soppressa", exc_info=True)
def _on_pointer_toggled(self, btn):
self._pointer_local = btn.get_active()
try:
self._display.set_pointer_local(self._pointer_local)
except Exception:
_get_log(__name__).debug("eccezione benigna soppressa", exc_info=True)
def _on_keyboard_toggled(self, btn):
self._keyboard_grab = btn.get_active()
try:
self._display.set_keyboard_grab(self._keyboard_grab)
except Exception:
_get_log(__name__).debug("eccezione benigna soppressa", exc_info=True)
def _on_readonly_toggled(self, btn):
self._read_only = btn.get_active()
try:
self._display.set_read_only(self._read_only)
except Exception:
_get_log(__name__).debug("eccezione benigna soppressa", exc_info=True)
def _send_keys(self, keysyms: list):
try:
self._display.send_keys(keysyms)
except Exception:
_get_log(__name__).debug("eccezione benigna soppressa", exc_info=True)
def _send_ctrl_alt_del(self):
self._send_keys([_KEY_CTRL, _KEY_ALT, _KEY_DEL])
def _screenshot(self):
try:
pixbuf = self._display.get_pixbuf()
if pixbuf is None:
return
import time
from gi.repository import GdkPixbuf
ts = time.strftime("%Y%m%d_%H%M%S")
path = os.path.expanduser(f"~/vnc_screenshot_{self._host}_{ts}.png")
pixbuf.savev(path, "png", [], [])
# Notifica utente
dlg = Gtk.MessageDialog(
transient_for=self.get_toplevel(),
modal=False,
message_type=Gtk.MessageType.INFO,
buttons=Gtk.ButtonsType.CLOSE,
text=t("vnc.screenshot_saved").format(path=path)
)
dlg.connect("response", lambda d, r: d.destroy())
dlg.show()
except Exception as e:
self._lbl.set_text(t("vnc.screenshot_err").format(e=e))
# ------------------------------------------------------------------
# Chiusura
# ------------------------------------------------------------------
def chiudi_processo(self):
if self._closed:
return
self._closed = True
try:
self._display.close()
except Exception:
_get_log(__name__).debug("eccezione benigna soppressa", exc_info=True)
# ---------------------------------------------------------------------------
# Metodo 2: Gtk.Socket + vncviewer esterno (XEmbed)
# ---------------------------------------------------------------------------
class _VncSocket(Gtk.Box):
_EMBED = {
"vncviewer": ("--EmbedIn={}", None),
"xtigervncviewer": ("--EmbedIn={}", None),
"xtightvncviewer": ("-Parent {}", "-passwd {}"),
"xvnc4viewer": ("-Parent {}", "-passwd {}"),
}
def __init__(self, host, port, password, on_vnc_ready=None):
super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=0)
self._host = host
self._port = str(port)
self._password = password
self._on_vnc_ready = on_vnc_ready
self._client = _find_vnc_client()
self._proc = None
self._closed = False
self._passwd_files = []
self._build()
def _build(self):
bar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
bar.set_margin_start(8); bar.set_margin_end(8)
bar.set_margin_top(4); bar.set_margin_bottom(4)
self._lbl = Gtk.Label(label=f"VNC → {self._host}:{self._port} avvio…")
self._lbl.set_xalign(0.0); self._lbl.set_hexpand(True)
bar.pack_start(self._lbl, True, True, 0)
btn_r = Gtk.Button()
btn_r.set_relief(Gtk.ReliefStyle.NONE)
btn_r.set_tooltip_text(t("vnc.tt_reconnect"))
btn_r.add(Gtk.Image.new_from_icon_name(
"view-refresh-symbolic", Gtk.IconSize.SMALL_TOOLBAR))
btn_r.connect("clicked", lambda b: self._avvia_client())
bar.pack_start(btn_r, False, False, 0)
self.pack_start(bar, False, False, 0)
self.pack_start(
Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL),
False, False, 0)
self._socket = Gtk.Socket()
self._socket.set_hexpand(True)
self._socket.set_vexpand(True)
self._socket.connect("plug-added", self._on_plug_added)
self._socket.connect("plug-removed", self._on_plug_removed)
self.pack_start(self._socket, True, True, 0)
self._socket.connect("realize", lambda w: GLib.idle_add(self._avvia_client))
def _avvia_client(self):
if self._closed:
return False
if not self._client:
self._errore(
t("vnc.no_client") +
t("vnc.install_hint") +
" " + t("vnc.install_gtklib")
)
return False
if self._proc and self._proc.poll() is None:
self._proc.terminate()
self._proc = None
xid = self._socket.get_id()
if not xid:
return False
embed_fmt, passwd_fmt = self._EMBED.get(self._client, ("--EmbedIn={}", None))
cmd = [self._client]
if self._password:
if passwd_fmt:
pf = self._write_passwd_file(self._password)
if pf:
self._passwd_files.append(pf)
cmd.append(passwd_fmt.format(pf))
elif self._client in ("vncviewer", "xtigervncviewer"):
pf = self._write_passwd_file(self._password)
if pf:
self._passwd_files.append(pf)
cmd += ["--PasswordFile", pf]
cmd.append(embed_fmt.format(xid))
cmd.append(f"{self._host}:{self._port}")
try:
self._proc = subprocess.Popen(
cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self._lbl.set_text(
f"VNC → {self._host}:{self._port} ({self._client})")
GLib.timeout_add(3000, self._check_proc)
except Exception as e:
self._errore(f"Errore avvio {self._client}:\n{e}")
return False
def _check_proc(self):
if self._closed or self._proc is None:
return False
if self._proc.poll() is not None:
if not self._closed:
self._lbl.set_text(
f"VNC → {self._host}:{self._port} disconnesso")
return False
return True
@staticmethod
def _write_passwd_file(password):
"""Il formato richiesto da -passwd/--PasswordFile è quello binario
offuscato prodotto da vncpasswd(1) (DES con chiave fissa), non un
semplice XOR byte a byte come faceva questa funzione in precedenza:
quel file non veniva mai accettato dal client, che quindi ignorava
la password salvata e chiedeva sempre l'immissione manuale.
Se vncpasswd non è disponibile si rinuncia al file (return None):
il client chiederà la password a schermo, invece di riceverne uno
comunque non valido."""
from session_command import _vnc_obfuscate_password
enc = _vnc_obfuscate_password(password)
if enc is None:
return None
try:
import tempfile
fd, path = tempfile.mkstemp(prefix="pcm_vnc_", suffix=".passwd")
with os.fdopen(fd, 'wb') as f:
f.write(enc)
return path
except Exception:
return None
def _on_plug_added(self, s):
self._lbl.set_text(f"VNC → {self._host}:{self._port}")
if self._on_vnc_ready:
self._on_vnc_ready()
def _on_plug_removed(self, s):
if not self._closed:
self._lbl.set_text(
f"VNC → {self._host}:{self._port} disconnesso")
return True
def _errore(self, msg):
lbl = Gtk.Label(label=msg)
lbl.set_line_wrap(True); lbl.set_xalign(0.0)
lbl.set_valign(Gtk.Align.CENTER); lbl.set_vexpand(True)
lbl.set_margin_start(12)
self.pack_start(lbl, True, True, 0)
self.show_all()
def chiudi_processo(self):
if self._closed:
return
self._closed = True
if self._proc and self._proc.poll() is None:
try:
self._proc.terminate()
try:
self._proc.wait(timeout=2)
except subprocess.TimeoutExpired:
self._proc.kill()
except Exception:
_get_log(__name__).debug("eccezione benigna soppressa", exc_info=True)
for pf in self._passwd_files:
if os.path.exists(pf):
try:
os.unlink(pf)
except Exception:
_get_log(__name__).debug("eccezione benigna soppressa", exc_info=True)
self._passwd_files.clear()
# ---------------------------------------------------------------------------
# Metodo 3: nessun driver disponibile
# ---------------------------------------------------------------------------
class _VncNoDriver(Gtk.Box):
def __init__(self, host, port, **_):
super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=12)
self.set_valign(Gtk.Align.CENTER)
self.set_halign(Gtk.Align.CENTER)
self.set_margin_start(24); self.set_margin_end(24)
lbl = Gtk.Label()
lbl.set_markup(
t("vnc.embedded_unavail") +
t("vnc.install_pkgs") +
t("vnc.pkg_recommended") +
t("vnc.pkg_alternative")
)
lbl.set_line_wrap(True); lbl.set_xalign(0.0)
self.pack_start(lbl, False, False, 0)
def chiudi_processo(self):
pass
# ---------------------------------------------------------------------------
# Factory pubblica
# ---------------------------------------------------------------------------
def VncWebWidget(host: str, port: str = "5900", password: str = "",
color_depth: int = 0, quality: int = 2,
on_save_password=None, on_vnc_ready=None):
"""
Restituisce il miglior widget VNC disponibile:
1. gtk-vnc nativo (gir1.2-gtk-vnc-2.0) — toolbar completa
2. Gtk.Socket + client vncviewer — embedding XEmbed
3. Widget con istruzioni di installazione
color_depth: 0=32bpp, 1=16bpp, 2=8bpp
quality: 0=best, 1=good, 2=fast
on_vnc_ready: callable() invocato sul main thread quando VNC è connesso
"""
if _GTKV_OK:
return _VncGtkVnc(host=host, port=port, password=password,
color_depth=color_depth, quality=quality,
on_save_password=on_save_password,
on_vnc_ready=on_vnc_ready)
if _find_vnc_client():
return _VncSocket(host=host, port=port, password=password,
on_vnc_ready=on_vnc_ready)
return _VncNoDriver(host=host, port=port)