-
-
Notifications
You must be signed in to change notification settings - Fork 142
/
gtk_client_base.py
1458 lines (1340 loc) · 63.4 KB
/
gtk_client_base.py
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
# This file is part of Xpra.
# Copyright (C) 2011 Serviware (Arthur Huillet, <ahuillet@serviware.com>)
# Copyright (C) 2010-2020 Antoine Martin <antoine@xpra.org>
# Copyright (C) 2008, 2010 Nathaniel Smith <njs@pobox.com>
# Xpra is released under the terms of the GNU GPL v2, or, at your option, any
# later version. See the file COPYING for details.
import os
import weakref
from subprocess import Popen, PIPE
from gi.repository import Gtk, Gdk, GdkPixbuf
from xpra.client.gtk_base.gtk_client_window_base import HAS_X11_BINDINGS, XSHAPE
from xpra.util import (
updict, pver, iround, flatten_dict, noerr,
envbool, envint, repr_ellipsized, csv, first_time, typedict,
DEFAULT_METADATA_SUPPORTED, XPRA_OPENGL_NOTIFICATION_ID,
)
from xpra.os_util import (
bytestostr, strtobytes, hexstr, monotonic_time, load_binary_file,
WIN32, OSX, POSIX, is_Wayland,
)
from xpra.simple_stats import std_unit
from xpra.exit_codes import EXIT_PASSWORD_REQUIRED
from xpra.scripts.config import TRUE_OPTIONS, FALSE_OPTIONS
from xpra.make_thread import start_thread
from xpra.gtk_common.cursor_names import cursor_types
from xpra.gtk_common.gtk_util import (
get_gtk_version_info, scaled_image, get_default_cursor, color_parse,
get_pixbuf_from_data,
get_default_root_window, get_root_size,
get_screen_sizes, GDKWindow,
GRAB_STATUS_STRING,
)
from xpra.gtk_common.gobject_util import no_arg_signal
from xpra.client.ui_client_base import UIXpraClient
from xpra.client.gobject_client_base import GObjectXpraClient
from xpra.client.gtk_base.gtk_keyboard_helper import GTKKeyboardHelper
from xpra.client.gtk_base.css_overrides import inject_css_overrides
from xpra.client.mixins.window_manager import WindowClient
from xpra.platform.paths import get_icon_filename
from xpra.platform.gui import force_focus
from xpra.platform.gui import (
get_window_frame_sizes, get_window_frame_size,
system_bell, get_wm_name, get_fixed_cursor_size,
)
from xpra.log import Logger
log = Logger("gtk", "client")
opengllog = Logger("gtk", "opengl")
cursorlog = Logger("gtk", "client", "cursor")
framelog = Logger("gtk", "client", "frame")
screenlog = Logger("gtk", "client", "screen")
filelog = Logger("gtk", "client", "file")
clipboardlog = Logger("gtk", "client", "clipboard")
notifylog = Logger("gtk", "notify")
grablog = Logger("client", "grab")
focuslog = Logger("client", "focus")
missing_cursor_names = set()
METADATA_SUPPORTED = os.environ.get("XPRA_METADATA_SUPPORTED")
#on win32, the named cursors work, but they are hard to see
#when using the Adwaita theme
USE_LOCAL_CURSORS = envbool("XPRA_USE_LOCAL_CURSORS", not WIN32 and not is_Wayland())
EXPORT_ICON_DATA = envbool("XPRA_EXPORT_ICON_DATA", True)
SAVE_CURSORS = envbool("XPRA_SAVE_CURSORS", False)
CLIPBOARD_NOTIFY = envbool("XPRA_CLIPBOARD_NOTIFY", True)
OPENGL_MIN_SIZE = envint("XPRA_OPENGL_MIN_SIZE", 32)
NO_OPENGL_WINDOW_TYPES = os.environ.get("XPRA_NO_OPENGL_WINDOW_TYPES",
"DOCK,TOOLBAR,MENU,UTILITY,SPLASH,DROPDOWN_MENU,POPUP_MENU,TOOLTIP,NOTIFICATION,COMBO,DND").split(",")
inject_css_overrides()
class GTKXpraClient(GObjectXpraClient, UIXpraClient):
__gsignals__ = {}
#add signals from super classes (all no-arg signals)
for signal_name in UIXpraClient.__signals__:
__gsignals__[signal_name] = no_arg_signal
ClientWindowClass = None
GLClientWindowClass = None
def __init__(self):
GObjectXpraClient.__init__(self)
UIXpraClient.__init__(self)
self.pinentry_proc = None
self.shortcuts_info = None
self.session_info = None
self.bug_report = None
self.file_size_dialog = None
self.file_ask_dialog = None
self.file_dialog = None
self.start_new_command = None
self.server_commands = None
self.keyboard_helper_class = GTKKeyboardHelper
self.border = None
self.data_send_requests = {}
#clipboard bits:
self.clipboard_notification_timer = None
self.last_clipboard_notification = 0
#opengl bits:
self.client_supports_opengl = False
self.opengl_force = False
self.opengl_enabled = False
self.opengl_props = {}
self.gl_max_viewport_dims = 0, 0
self.gl_texture_size_limit = 0
self._cursors = weakref.WeakKeyDictionary()
#frame request hidden window:
self.frame_request_window = None
#group leader bits:
self._ref_to_group_leader = {}
self._group_leader_wids = {}
try:
self.connect("scaling-changed", self.reset_windows_cursors)
except TypeError:
log("no 'scaling-changed' signal")
#detect when the UI thread isn't responding:
self.UI_watcher = None
self.connect("first-ui-received", self.start_UI_watcher)
def init(self, opts):
GObjectXpraClient.init(self, opts)
UIXpraClient.init(self, opts)
def setup_frame_request_windows(self):
#query the window manager to get the frame size:
from xpra.gtk_common.error import xsync
from xpra.x11.gtk_x11.send_wm import send_wm_request_frame_extents
self.frame_request_window = Gtk.Window(type=Gtk.WindowType.TOPLEVEL)
self.frame_request_window.set_title("Xpra-FRAME_EXTENTS")
root = self.get_root_window()
self.frame_request_window.realize()
with xsync:
win = self.frame_request_window.get_window()
framelog("setup_frame_request_windows() window=%#x", win.get_xid())
send_wm_request_frame_extents(root, win)
def run(self):
log("run() HAS_X11_BINDINGS=%s", HAS_X11_BINDINGS)
if HAS_X11_BINDINGS:
self.setup_frame_request_windows()
UIXpraClient.run(self)
self.gtk_main()
log("GTKXpraClient.run_main_loop() main loop ended, returning exit_code=%s", self.exit_code)
return self.exit_code
def gtk_main(self):
log("GTKXpraClient.gtk_main() calling %s", Gtk.main)
Gtk.main()
log("GTKXpraClient.gtk_main() ended")
def quit(self, exit_code=0):
log("GTKXpraClient.quit(%s) current exit_code=%s", exit_code, self.exit_code)
if self.exit_code is None:
self.exit_code = exit_code
if Gtk.main_level()>0:
#if for some reason cleanup() hangs, maybe this will fire...
self.timeout_add(4*1000, self.exit)
#try harder!:
self.timeout_add(5*1000, self.force_quit)
self.cleanup()
log("GTKXpraClient.quit(%s) cleanup done, main_level=%s",
exit_code, Gtk.main_level())
if Gtk.main_level()>0:
log("GTKXpraClient.quit(%s) main loop at level %s, calling gtk quit via timeout",
exit_code, Gtk.main_level())
self.timeout_add(500, self.exit)
def force_quit(self):
from xpra.os_util import force_quit
log("GTKXpraClient.force_quit() calling %s", force_quit)
force_quit()
def exit(self):
self.show_progress(100, "terminating")
log("GTKXpraClient.exit() calling %s", Gtk.main_quit)
Gtk.main_quit()
def cleanup(self):
log("GTKXpraClient.cleanup()")
self.stop_pinentry()
if self.shortcuts_info:
self.shortcuts_info.destroy()
self.shortcuts_info = None
if self.session_info:
self.session_info.destroy()
self.session_info = None
if self.bug_report:
self.bug_report.destroy()
self.bug_report = None
self.close_file_size_warning()
self.close_file_upload_dialog()
self.close_ask_data_dialog()
self.cancel_clipboard_notification_timer()
if self.start_new_command:
self.start_new_command.destroy()
self.start_new_command = None
if self.server_commands:
self.server_commands.destroy()
self.server_commands = None
uw = self.UI_watcher
if uw:
self.UI_watcher = None
uw.stop()
UIXpraClient.cleanup(self)
def start_UI_watcher(self, _client):
from xpra.platform.ui_thread_watcher import get_UI_watcher
self.UI_watcher = get_UI_watcher(self.timeout_add, self.source_remove)
self.UI_watcher.start()
#if server supports it, enable UI thread monitoring workaround when needed:
def UI_resumed():
self.send("resume", True, tuple(self._id_to_window.keys()))
#maybe the system was suspended?
#so we may want to call WindowClient.resume()
resume = getattr(self, "resume", None)
if resume:
resume()
def UI_failed():
self.send("suspend", True, tuple(self._id_to_window.keys()))
self.UI_watcher.add_resume_callback(UI_resumed)
self.UI_watcher.add_fail_callback(UI_failed)
def get_vrefresh(self):
#try via GTK:
rates = {}
display = Gdk.Display.get_default()
for m in range(display.get_n_monitors()):
monitor = display.get_monitor(m)
log("monitor %i (%s) refresh-rate=%i", m, monitor.get_model(), monitor.get_refresh_rate())
rates[m] = monitor.get_refresh_rate()
rate = -1
if rates:
rate = iround(min(rates.values())/1000)
if rate<30 or rate>250:
rate = super().get_vrefresh()
return rate
def get_notifier_classes(self):
#subclasses may add their toolkit specific variants
#by overriding this method
#use the native ones first:
from xpra.client import mixin_features
assert mixin_features.notifications
from xpra.client.mixins.notifications import NotificationClient
assert isinstance(self, NotificationClient)
ncs = NotificationClient.get_notifier_classes(self)
try:
from xpra.gtk_common.gtk_notifier import GTK_Notifier
ncs.append(GTK_Notifier)
except Exception as e:
notifylog("get_notifier_classes()", exc_info=True)
notifylog.warn("Warning: cannot load GTK notifier:")
notifylog.warn(" %s", e)
return ncs
def _process_startup_complete(self, packet):
UIXpraClient._process_startup_complete(self, packet)
Gdk.notify_startup_complete()
def do_process_challenge_prompt(self, packet, prompt="password"):
authlog = Logger("auth")
self.show_progress(100, "authentication")
PINENTRY = os.environ.get("XPRA_PINENTRY", "")
from xpra.scripts.main import get_pinentry_command
pinentry_cmd = get_pinentry_command(PINENTRY)
authlog("do_process_challenge_prompt%s get_pinentry_command(%s)=%s",
(packet, prompt), PINENTRY, pinentry_cmd)
if pinentry_cmd:
start_thread(self.handle_challenge_with_pinentry,
"pinentry", True, (packet, prompt, pinentry_cmd))
return True
return self.do_process_challenge_prompt_dialog(packet, prompt)
def stop_pinentry(self):
pp = self.pinentry_proc
if pp:
self.pinentry_proc = None
noerr(pp.terminate)
def handle_challenge_with_pinentry(self, packet, prompt="password", cmd="pinentry"):
authlog = Logger("auth")
authlog("handle_challenge_with_pinentry%s", (packet, prompt, cmd))
try:
proc = Popen([cmd], stdin=PIPE, stdout=PIPE, stderr=PIPE)
except OSError:
authlog("pinentry failed", exc_info=True)
else:
self.pinentry_proc = proc
q = "Enter %s" % prompt
p = self._protocol
if p:
conn = getattr(p, "_conn", None)
if conn:
from xpra.net.bytestreams import pretty_socket
cinfo = conn.get_info()
endpoint = pretty_socket(cinfo.get("endpoint", conn.target)).split("?")[0]
q += " for %s" % endpoint
def got_pin(value):
self.idle_add(self.send_challenge_reply, packet, value)
def no_pin():
self.idle_add(self.quit, EXIT_PASSWORD_REQUIRED)
from xpra.scripts.main import pinentry_getpin
pinentry_getpin(proc, "Xpra Server Authentication:", q, got_pin, no_pin)
return True
return self.do_process_challenge_prompt_dialog(packet, prompt)
def do_process_challenge_prompt_dialog(self, packet, prompt="password"):
dialog = Gtk.Dialog("Server Authentication",
None,
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT)
dialog.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT)
dialog.add_button(Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT)
def add(widget, padding=0):
a = Gtk.Alignment()
a.set(0.5, 0.5, 1, 1)
a.add(widget)
a.set_padding(padding, padding, padding, padding)
dialog.vbox.pack_start(a)
import gi
gi.require_version("Pango", "1.0")
from gi.repository import Pango
title = Gtk.Label("Server Authentication")
title.modify_font(Pango.FontDescription("sans 14"))
add(title, 16)
add(Gtk.Label(self.get_challenge_prompt(prompt)), 10)
password_input = Gtk.Entry()
password_input.set_max_length(255)
password_input.set_width_chars(32)
password_input.set_visibility(False)
add(password_input, 10)
dialog.vbox.show_all()
dialog.password_input = password_input
def handle_response(dialog, response):
if OSX:
from xpra.platform.darwin.gui import disable_focus_workaround
disable_focus_workaround()
password = dialog.password_input.get_text()
dialog.hide()
dialog.destroy()
if response!=Gtk.ResponseType.ACCEPT or not password:
self.quit(EXIT_PASSWORD_REQUIRED)
return
self.send_challenge_reply(packet, password)
def password_activate(*_args):
handle_response(dialog, Gtk.ResponseType.ACCEPT)
password_input.connect("activate", password_activate)
dialog.connect("response", handle_response)
if OSX:
from xpra.platform.darwin.gui import enable_focus_workaround
enable_focus_workaround()
dialog.show()
return True
def setup_connection(self, conn):
conn = super().setup_connection(conn)
#now that we have display_desc, parse the border again:
self.parse_border(False)
return conn
def show_border_help(self):
if not first_time("border-help"):
return
log.info(" border format: color[,size][:off]")
log.info(" eg: red,10")
log.info(" eg: ,5")
log.info(" eg: auto,5")
log.info(" eg: blue")
def parse_border(self, warn=True):
enabled = not self.border_str.endswith(":off")
parts = [x.strip() for x in self.border_str.replace(":off", "").split(",")]
color_str = parts[0]
if color_str.lower() in ("none", "no", "off", "0"):
return
if color_str.lower()=="help":
self.show_border_help()
return
color_str = color_str.replace(":off", "")
if color_str in ("auto", ""):
from hashlib import md5, sha1
try:
if envbool("XPRA_NOMD5", False):
raise ValueError("md5 explicitly disabled")
m = md5()
except ValueError:
m = sha1()
endpoint = self.display_desc.get("display_name")
if endpoint:
m.update(strtobytes(endpoint))
color_str = "#%s" % m.hexdigest()[:6]
log("border color derived from %s: %s", endpoint, color_str)
try:
color = color_parse(color_str)
assert color is not None
except Exception as e:
if warn:
log.warn("Warning: invalid border color specified '%s'", color_str)
if str(e):
log.warn(" %s", e)
self.show_border_help()
color = color_parse("red")
alpha = 0.6
size = 4
if len(parts)==2:
size_str = parts[1]
try:
size = int(size_str)
except Exception as e:
if warn:
log.warn("Warning: invalid border size specified '%s'", size_str)
log.warn(" %s", e)
self.show_border_help()
if size<=0:
log("border size is %s, disabling it", size)
return
if size>=45:
log.warn("Warning: border size is too large: %s, clipping it", size)
size = 45
from xpra.client.window_border import WindowBorder
self.border = WindowBorder(enabled, color.red/65536.0, color.green/65536.0, color.blue/65536.0, alpha, size)
log("parse_border(%s)=%s", self.border_str, self.border)
def show_server_commands(self, *_args):
if not self.server_commands_info:
log.warn("Warning: cannot show server commands")
log.warn(" the feature is not available on the server")
return
if self.server_commands is None:
from xpra.client.gtk_base.server_commands import getServerCommandsWindow
self.server_commands = getServerCommandsWindow(self)
self.server_commands.show()
def show_start_new_command(self, *args):
if not self.server_start_new_commands:
log.warn("Warning: cannot start new commands")
log.warn(" the feature is currently disabled on the server")
return
log("show_start_new_command%s current start_new_command=%s, flag=%s",
args, self.start_new_command, self.server_start_new_commands)
if self.start_new_command is None:
from xpra.client.gtk_base.start_new_command import getStartNewCommand
def run_command_cb(command, sharing=True):
self.send_start_command(command, command, False, sharing)
self.start_new_command = getStartNewCommand(run_command_cb,
self.server_sharing,
self.server_xdg_menu)
self.start_new_command.show()
################################
# file handling
def ask_data_request(self, cb_answer, send_id, dtype, url, filesize, printit, openit):
self.idle_add(self.do_ask_data_request, cb_answer, send_id, dtype, url, filesize, printit, openit)
def do_ask_data_request(self, cb_answer, send_id, dtype, url, filesize, printit, openit):
from xpra.client.gtk_base.open_requests import getOpenRequestsWindow
timeout = self.remote_file_ask_timeout
def rec_answer(accept, newopenit=openit):
from xpra.net.file_transfer import ACCEPT
if int(accept)==ACCEPT:
#record our response, so we will actually accept the file when the packets arrive:
self.data_send_requests[send_id] = (dtype, url, printit, newopenit)
cb_answer(accept)
self.file_ask_dialog = getOpenRequestsWindow(self.show_file_upload, self.cancel_download)
self.file_ask_dialog.add_request(rec_answer, send_id, dtype, url, filesize, printit, openit, timeout)
self.file_ask_dialog.show()
def close_ask_data_dialog(self):
fad = self.file_ask_dialog
if fad:
self.file_ask_dialog = None
fad.destroy()
def show_ask_data_dialog(self, *_args):
from xpra.client.gtk_base.open_requests import getOpenRequestsWindow
self.file_ask_dialog = getOpenRequestsWindow(self.show_file_upload, self.cancel_download)
self.file_ask_dialog.show()
def transfer_progress_update(self, send=True, transfer_id=0, elapsed=0, position=0, total=0, error=None):
fad = self.file_ask_dialog
if fad:
self.idle_add(fad.transfer_progress_update, send, transfer_id, elapsed, position, total, error)
def accept_data(self, send_id, dtype, url, printit, openit):
#check if we have accepted this file via the GUI:
r = self.data_send_requests.pop(send_id, None)
if not r:
filelog("accept_data: data send request %s not found", send_id)
from xpra.net.file_transfer import FileTransferHandler
return FileTransferHandler.accept_data(self, send_id, dtype, url, printit, openit)
edtype = r[0]
eurl = r[1]
if edtype!=dtype or eurl!=url:
filelog.warn("Warning: the file attributes are different")
filelog.warn(" from the ones that were used to accept the transfer")
s = bytestostr
if edtype!=dtype:
filelog.warn(" expected data type '%s' but got '%s'", s(edtype), s(dtype))
if eurl!=url:
filelog.warn(" expected url '%s',", s(eurl))
filelog.warn(" but got url '%s'", s(url))
return None
#return the printit and openit flag we got from the UI:
return (r[2], r[3])
def file_size_warning(self, action, location, basefilename, filesize, limit):
if self.file_size_dialog:
#close previous warning
self.file_size_dialog.destroy()
self.file_size_dialog = None
parent = None
msgs = (
"Warning: cannot %s the file '%s'" % (action, basefilename),
"this file is too large: %sB" % std_unit(filesize),
"the %s file size limit is %iB" % (location, std_unit(limit)),
)
self.file_size_dialog = Gtk.MessageDialog(parent, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.INFO,
Gtk.ButtonsType.CLOSE, "\n".join(msgs))
try:
image = Gtk.Image.new_from_stock(Gtk.STOCK_DIALOG_WARNING, Gtk.IconSize.BUTTON)
self.file_size_dialog.set_image(image)
except Exception as e:
log.warn("Warning: failed to set dialog image: %s", e)
self.file_size_dialog.connect("response", self.close_file_size_warning)
self.file_size_dialog.show()
def close_file_size_warning(self, *_args):
fsd = self.file_size_dialog
if fsd:
self.file_size_dialog = None
fsd.destroy()
def download_server_log(self, callback=None):
filename = "${XPRA_SERVER_LOG}"
if callback:
self.file_request_callback[filename] = callback
self.send_request_file(filename, self.open_files)
def send_download_request(self, *_args):
command = ["xpra", "send-file"]
self.send_start_command("Client-Download-File", command, True)
def show_file_upload(self, *args):
if self.file_dialog:
self.file_dialog.present()
return
filelog("show_file_upload%s can open=%s", args, self.remote_open_files)
buttons = [Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL]
if self.remote_open_files:
buttons += [Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT]
buttons += [Gtk.STOCK_OK, Gtk.ResponseType.OK]
self.file_dialog = Gtk.FileChooserDialog(
"File to upload",
parent=None,
action=Gtk.FileChooserAction.OPEN,
buttons=tuple(buttons))
self.file_dialog.set_default_response(Gtk.ResponseType.OK)
self.file_dialog.connect("response", self.file_upload_dialog_response)
self.file_dialog.show()
def close_file_upload_dialog(self):
fd = self.file_dialog
if fd:
fd.destroy()
self.file_dialog = None
def file_upload_dialog_response(self, dialog, v):
if v not in (Gtk.ResponseType.OK, Gtk.ResponseType.ACCEPT):
filelog("dialog response code %s", v)
self.close_file_upload_dialog()
return
filename = dialog.get_filename()
filelog("file_upload_dialog_response: filename=%s", filename)
try:
filesize = os.stat(filename).st_size
except OSError:
pass
else:
if not self.check_file_size("upload", filename, filesize):
self.close_file_upload_dialog()
return
gfile = dialog.get_file()
self.close_file_upload_dialog()
filelog("load_contents: filename=%s, response=%s", filename, v)
cancellable = None
user_data = (filename, v==Gtk.ResponseType.ACCEPT)
gfile.load_contents_async(cancellable, self.file_upload_ready, user_data)
def file_upload_ready(self, gfile, result, user_data):
filelog("file_upload_ready%s", (gfile, result, user_data))
filename, openit = user_data
_, data, entity = gfile.load_contents_finish(result)
filesize = len(data)
filelog("load_contents_finish(%s)=%s", result, (type(data), filesize, entity))
if not data:
log.warn("Warning: failed to load file '%s'", filename)
return
filelog("load_contents: filename=%s, %i bytes, entity=%s, openit=%s",
filename, filesize, entity, openit)
self.send_file(filename, "", data, filesize=filesize, openit=openit)
def show_about(self, *_args):
from xpra.gtk_common.about import about
force_focus()
about()
def show_shortcuts(self, *_args):
if self.shortcuts_info and not self.shortcuts_info.is_closed:
force_focus()
self.shortcuts_info.present()
return
from xpra.client.gtk3.show_shortcuts import ShortcutInfo
kh = self.keyboard_helper
assert kh, "no keyboard helper"
self.shortcuts_info = ShortcutInfo(kh.shortcut_modifiers, kh.key_shortcuts)
self.shortcuts_info.show_all()
def show_session_info(self, *args):
if self.session_info and not self.session_info.is_closed:
#exists already: just raise its window:
self.session_info.set_args(*args)
force_focus()
self.session_info.present()
return
pixbuf = self.get_pixbuf("statistics.png")
if not pixbuf:
pixbuf = self.get_pixbuf("xpra.png")
p = self._protocol
conn = p._conn if p else None
from xpra.client.gtk_base.session_info import SessionInfo
self.session_info = SessionInfo(self, self.session_name, pixbuf, conn, self.get_pixbuf)
self.session_info.set_args(*args)
force_focus()
self.session_info.show_all()
def show_bug_report(self, *_args):
self.send_info_request()
if self.bug_report:
force_focus()
self.bug_report.show()
return
from xpra.client.gtk_base.bug_report import BugReport
self.bug_report = BugReport()
def init_bug_report():
#skip things we aren't using:
includes ={
"keyboard" : bool(self.keyboard_helper),
"opengl" : self.opengl_enabled,
}
def get_server_info():
return self.server_last_info
self.bug_report.init(show_about=False,
get_server_info=get_server_info,
opengl_info=self.opengl_props,
includes=includes)
self.bug_report.show()
#gives the server time to send an info response..
#(by the time the user clicks on copy, it should have arrived, we hope!)
def got_server_log(filename, filesize):
log("got_server_log(%s, %s)", filename, filesize)
filedata = load_binary_file(filename)
self.bug_report.set_server_log_data(filedata)
self.download_server_log(got_server_log)
self.timeout_add(200, init_bug_report)
def get_pixbuf(self, icon_name):
try:
if not icon_name:
log("get_pixbuf(%s)=None", icon_name)
return None
icon_filename = get_icon_filename(icon_name)
log("get_pixbuf(%s) icon_filename=%s", icon_name, icon_filename)
if icon_filename:
return GdkPixbuf.Pixbuf.new_from_file(icon_filename)
except Exception:
log.error("get_pixbuf(%s)", icon_name, exc_info=True)
return None
def get_image(self, icon_name, size=None):
try:
pixbuf = self.get_pixbuf(icon_name)
log("get_image(%s, %s) pixbuf=%s", icon_name, size, pixbuf)
if not pixbuf:
return None
return scaled_image(pixbuf, size)
except Exception:
log.error("get_image(%s, %s)", icon_name, size, exc_info=True)
return None
def request_frame_extents(self, window):
from xpra.x11.gtk_x11.send_wm import send_wm_request_frame_extents
from xpra.gtk_common.error import xsync
root = self.get_root_window()
with xsync:
win = window.get_window()
framelog("request_frame_extents(%s) xid=%#x", window, win.get_xid())
send_wm_request_frame_extents(root, win)
def get_frame_extents(self, window):
#try native platform code first:
x, y = window.get_position()
w, h = window.get_size()
v = get_window_frame_size(x, y, w, h) #pylint: disable=assignment-from-none
framelog("get_window_frame_size%s=%s", (x, y, w, h), v)
if v:
#(OSX does give us these values via Quartz API)
return v
if not HAS_X11_BINDINGS:
#nothing more we can do!
return None
from xpra.x11.gtk_x11.prop import prop_get
gdkwin = window.get_window()
assert gdkwin
v = prop_get(gdkwin, "_NET_FRAME_EXTENTS", ["u32"], ignore_errors=False)
framelog("get_frame_extents(%s)=%s", window.get_title(), v)
return v
def get_window_frame_sizes(self):
wfs = get_window_frame_sizes()
if self.frame_request_window:
v = self.get_frame_extents(self.frame_request_window)
if v:
try:
wm_name = get_wm_name() #pylint: disable=assignment-from-none
except Exception:
wm_name = None
try:
if len(v)==8:
if first_time("invalid-frame-extents"):
framelog.warn("Warning: invalid frame extents value '%s'", v)
if wm_name:
framelog.warn(" this is probably a bug in '%s'", wm_name)
framelog.warn(" using '%s' instead", v[4:])
v = v[4:]
l, r, t, b = v
wfs["frame"] = (l, r, t, b)
wfs["offset"] = (l, t)
except Exception as e:
framelog.warn("Warning: invalid frame extents value '%s'", v)
framelog.warn(" %s", e)
framelog.warn(" this is probably a bug in '%s'", wm_name)
framelog("get_window_frame_sizes()=%s", wfs)
return wfs
def _add_statusicon_tray(self, tray_list):
#add Gtk.StatusIcon tray:
try:
from xpra.client.gtk_base.statusicon_tray import GTKStatusIconTray
tray_list.append(GTKStatusIconTray)
except Exception as e:
log.warn("failed to load StatusIcon tray: %s" % e)
return tray_list
def get_tray_classes(self):
from xpra.client.mixins.tray import TrayClient
return self._add_statusicon_tray(TrayClient.get_tray_classes(self))
def get_system_tray_classes(self):
return self._add_statusicon_tray(WindowClient.get_system_tray_classes(self))
def supports_system_tray(self) -> bool:
#always True: we can always use Gtk.StatusIcon as fallback
return True
def get_root_window(self):
return get_default_root_window()
def get_root_size(self):
return get_root_size()
def get_mouse_position(self):
p = self.get_root_window().get_pointer()[-3:-1]
return self.cp(p[0], p[1])
def get_current_modifiers(self):
root = self.get_root_window()
if root is None:
return ()
modifiers_mask = root.get_pointer()[-1]
return self.mask_to_names(modifiers_mask)
def make_hello(self) -> dict:
capabilities = UIXpraClient.make_hello(self)
capabilities["named_cursors"] = len(cursor_types)>0
capabilities["encoding.transparency"] = self.has_transparency()
capabilities.update(flatten_dict(get_gtk_version_info()))
if EXPORT_ICON_DATA:
#tell the server which icons GTK can use
#so it knows when it should supply one as fallback
it = Gtk.IconTheme.get_default()
if it:
#this would add our bundled icon directory
#to the search path, but I don't think we have
#any extra icons that matter in there:
#from xpra.platform.paths import get_icon_dir
#d = get_icon_dir()
#if d not in it.get_search_path():
# it.append_search_path(d)
# it.rescan_if_needed()
log("default icon theme: %s", it)
log("icon search path: %s", it.get_search_path())
log("contexts: %s", it.list_contexts())
icons = []
for context in it.list_contexts():
icons += it.list_icons(context)
log("icons: %s", icons)
capabilities["theme.default.icons"] = tuple(set(icons))
if METADATA_SUPPORTED:
ms = [x.strip() for x in METADATA_SUPPORTED.split(",")]
else:
#this is currently unused, and slightly redundant because of metadata.supported below:
capabilities["window.states"] = [
"fullscreen", "maximized",
"sticky", "above", "below",
"shaded", "iconified",
"skip-taskbar", "skip-pager",
]
ms = list(DEFAULT_METADATA_SUPPORTED)
#added in 0.15:
ms += ["command", "workspace", "above", "below", "sticky",
"set-initial-position", #0.17
"content-type",
]
if POSIX:
#this is only really supported on X11, but posix is easier to check for..
#"strut" and maybe even "fullscreen-monitors" could also be supported on other platforms I guess
ms += ["shaded", "bypass-compositor", "strut", "fullscreen-monitors"]
if HAS_X11_BINDINGS:
ms += ["x11-property"]
if XSHAPE:
ms += ["shape"]
log("metadata.supported: %s", ms)
capabilities["metadata.supported"] = ms
updict(capabilities, "pointer", {
"grabs" : True,
"relative" : True,
})
updict(capabilities, "window", {
"initiate-moveresize" : True, #v4 servers assume this is available
"frame_sizes" : self.get_window_frame_sizes()
})
updict(capabilities, "encoding", {
"icons.greedy" : True, #we don't set a default window icon any more
"icons.size" : (64, 64), #size we want
"icons.max_size" : (128, 128), #limit
})
capabilities["opengl"] = self.opengl_props
return capabilities
def has_transparency(self) -> bool:
screen = Gdk.Screen.get_default()
if screen is None:
return is_Wayland()
return screen.get_rgba_visual() is not None
def get_screen_sizes(self, xscale=1, yscale=1):
return get_screen_sizes(xscale, yscale)
def reset_windows_cursors(self, *_args):
cursorlog("reset_windows_cursors() resetting cursors for: %s", tuple(self._cursors.keys()))
for w,cursor_data in tuple(self._cursors.items()):
self.set_windows_cursor([w], cursor_data)
def set_windows_cursor(self, windows, cursor_data):
cursorlog("set_windows_cursor(%s, args[%i])", windows, len(cursor_data))
cursor = None
if cursor_data:
try:
cursor = self.make_cursor(cursor_data)
cursorlog("make_cursor(..)=%s", cursor)
except Exception as e:
log.warn("error creating cursor: %s (using default)", e, exc_info=True)
if cursor is None:
#use default:
cursor = get_default_cursor()
for w in windows:
w.set_cursor_data(cursor_data)
gdkwin = w.get_window()
#trays don't have a gdk window
if gdkwin:
self._cursors[w] = cursor_data
gdkwin.set_cursor(cursor)
def make_cursor(self, cursor_data):
#if present, try cursor ny name:
display = Gdk.Display.get_default()
cursorlog("make_cursor: has-name=%s, has-cursor-types=%s, xscale=%s, yscale=%s, USE_LOCAL_CURSORS=%s",
len(cursor_data)>=10, bool(cursor_types), self.xscale, self.yscale, USE_LOCAL_CURSORS)
pixbuf = None
if len(cursor_data)>=10 and cursor_types:
cursor_name = bytestostr(cursor_data[9])
if cursor_name and USE_LOCAL_CURSORS:
try:
cursor = Gdk.Cursor.new_from_name(display, cursor_name)
except TypeError:
cursorlog("Gdk.Cursor.new_from_name%s", (display, cursor_name), exc_info=True)
cursor = None
if cursor:
cursorlog("Gdk.Cursor.new_from_name(%s, %s)=%s", display, cursor_name, cursor)
else:
gdk_cursor = cursor_types.get(cursor_name.upper())
cursorlog("gdk_cursor(%s)=%s", cursor_name, gdk_cursor)
if gdk_cursor:
try:
cursor = Gdk.Cursor.new_for_display(display, gdk_cursor)
cursorlog("Cursor.new_for_display(%s, %s)=%s", display, gdk_cursor, cursor)
except TypeError as e:
log("new_Cursor_for_display(%s, %s)", display, gdk_cursor, exc_info=True)
if first_time("cursor:%s" % cursor_name.upper()):
log.error("Error creating cursor %s: %s", cursor_name.upper(), e)
global missing_cursor_names
if cursor:
pixbuf = cursor.get_image()
cursorlog("image=%s", pixbuf)
elif cursor_name not in missing_cursor_names:
cursorlog("cursor name '%s' not found", cursor_name)
missing_cursor_names.add(cursor_name)
#create cursor from the pixel data:
encoding, _, _, w, h, xhot, yhot, serial, pixels = cursor_data[0:9]
encoding = bytestostr(encoding)
if encoding!="raw":
cursorlog.warn("Warning: invalid cursor encoding: %s", encoding)
return None
if not pixbuf:
if len(pixels)<w*h*4:
cursorlog.warn("Warning: not enough pixels provided in cursor data")
cursorlog.warn(" %s needed and only %s bytes found:", w*h*4, len(pixels))
cursorlog.warn(" '%s')", repr_ellipsized(hexstr(pixels)))
return None
pixbuf = get_pixbuf_from_data(pixels, True, w, h, w*4)
else:
w = pixbuf.get_width()
h = pixbuf.get_height()
pixels = pixbuf.get_pixels()
x = max(0, min(xhot, w-1))
y = max(0, min(yhot, h-1))
csize = display.get_default_cursor_size()
cmaxw, cmaxh = display.get_maximal_cursor_size()
if len(cursor_data)>=12:
ssize = cursor_data[10]
smax = cursor_data[11]
cursorlog("server cursor sizes: default=%s, max=%s", ssize, smax)
cursorlog("new %s cursor at %s,%s with serial=%#x, dimensions: %sx%s, len(pixels)=%s",
encoding, xhot, yhot, serial, w, h, len(pixels))
cursorlog("default cursor size is %s, maximum=%s", csize, (cmaxw, cmaxh))
fw, fh = get_fixed_cursor_size()
if fw>0 and fh>0 and (w!=fw or h!=fh):
#OS wants a fixed cursor size! (win32 does, and GTK doesn't do this for us)
if w<=fw and h<=fh:
cursorlog("pasting %ix%i cursor to fixed OS size %ix%i", w, h, fw, fh)
from PIL import Image
img = Image.frombytes("RGBA", (w, h), pixels, "raw", "BGRA", w*4, 1)
target = Image.new("RGBA", (fw, fh))
target.paste(img, (0, 0, w, h))
pixels = img.tobytes("raw", "BGRA")
cursor_pixbuf = get_pixbuf_from_data(pixels, True, w, h, w*4)
else:
cursorlog("scaling cursor from %ix%i to fixed OS size %ix%i", w, h, fw, fh)
cursor_pixbuf = pixbuf.scale_simple(fw, fh, GdkPixbuf.InterpType.BILINEAR)
xratio, yratio = w/fw, h/fh
x, y = iround(x/xratio), iround(y/yratio)
else:
sx, sy, sw, sh = x, y, w, h
#scale the cursors:
if self.xscale!=1 or self.yscale!=1:
sx, sy, sw, sh = self.srect(x, y, w, h)
sw = max(1, sw)
sh = max(1, sh)
#ensure we honour the max size if there is one:
if 0<cmaxw<sw or 0<cmaxh<sh:
ratio = 1.0