/
server.py
1756 lines (1597 loc) · 77.9 KB
/
server.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
# coding=utf8
# This file is part of Parti.
# Copyright (C) 2011 Serviware (Arthur Huillet, <ahuillet@serviware.com>)
# Copyright (C) 2010-2012 Antoine Martin <antoine@devloop.org.uk>
# Copyright (C) 2008 Nathaniel Smith <njs@pobox.com>
# Parti is released under the terms of the GNU GPL v2, or, at your option, any
# later version. See the file COPYING for details.
# Todo:
# xsync resize stuff
# shape?
# any other interesting metadata? _NET_WM_TYPE, WM_TRANSIENT_FOR, etc.?
import gtk.gdk
gtk.gdk.threads_init()
import gobject
import cairo
import sys
import hmac
import uuid
try:
from StringIO import StringIO #@UnusedImport
except:
from io import StringIO #@UnresolvedImport @Reimport
import os
import time
import ctypes
from math import log as mathlog
def logp2(x):
return mathlog(1+max(1, x), 2)
def logp10(x):
return mathlog(9+max(1, x), 10)
from wimpiggy.wm import Wm
from wimpiggy.util import (AdHocStruct,
one_arg_signal,
gtk_main_quit_really,
gtk_main_quit_on_fatal_exceptions_enable)
from wimpiggy.lowlevel import (displayHasXComposite, #@UnresolvedImport
xtest_fake_key, #@UnresolvedImport
xtest_fake_button, #@UnresolvedImport
set_key_repeat_rate, #@UnresolvedImport
ungrab_all_keys, #@UnresolvedImport
unpress_all_keys, #@UnresolvedImport
is_override_redirect, #@UnresolvedImport
is_mapped, #@UnresolvedImport
add_event_receiver, #@UnresolvedImport
get_cursor_image, #@UnresolvedImport
get_children, #@UnresolvedImport
has_randr, get_screen_sizes, #@UnresolvedImport
set_screen_size, #@UnresolvedImport
get_screen_size, #@UnresolvedImport
init_x11_filter, #@UnresolvedImport
get_xatom #@UnresolvedImport
)
from wimpiggy.prop import prop_set
from wimpiggy.window import OverrideRedirectWindowModel, Unmanageable
from wimpiggy.keys import grok_modifier_map
from wimpiggy.error import XError, trap
from wimpiggy.log import Logger
log = Logger()
import xpra
from xpra.server_source import DamageBatchConfig, ServerSource, get_rgb_rawdata, add_list_stats
from xpra.deque import maxdeque
from xpra.protocol import Protocol, SocketConnection, dump_packet
from xpra.keys import mask_to_names, get_gtk_keymap, DEFAULT_MODIFIER_NUISANCE, ALL_X11_MODIFIERS
from xpra.xkbhelper import do_set_keymap, set_all_keycodes, set_modifiers_from_meanings, clear_modifiers, set_modifiers_from_keycodes
from xpra.xposix.xclipboard import ClipboardProtocolHelper
from xpra.xposix.xsettings import XSettingsManager
from xpra.scripts.main import ENCODINGS, DEFAULT_ENCODING
from xpra.version_util import is_compatible_with
MAX_CONCURRENT_CONNECTIONS = 20
class DesktopManager(gtk.Widget):
def __init__(self):
gtk.Widget.__init__(self)
self.set_property("can-focus", True)
self.set_flags(gtk.NO_WINDOW)
self._models = {}
## For communicating with the main WM:
def add_window(self, model, x, y, w, h):
assert self.flags() & gtk.REALIZED
s = AdHocStruct()
s.shown = False
s.geom = [x, y, w, h]
s.window = None
self._models[model] = s
model.connect("unmanaged", self._unmanaged)
model.connect("ownership-election", self._elect_me)
def new_geom(window_model, *args):
log("new_geom(%s,%s)", window_model, args)
model.connect("geometry", new_geom)
model.ownership_election()
def window_geometry(self, model):
return self._models[model].geom
def show_window(self, model):
self._models[model].shown = True
model.ownership_election()
if model.get_property("iconic"):
model.set_property("iconic", False)
def configure_window(self, model, x, y, w, h):
log("DesktopManager.configure_window(%s, %s, %s, %s, %s)", model, x, y, w, h)
if not self.visible(model):
self._models[model].shown = True
model.set_property("iconic", False)
model.ownership_election()
self._models[model].geom = [x, y, w, h]
model.maybe_recalculate_geometry_for(self)
def hide_window(self, model):
if not model.get_property("iconic"):
model.set_property("iconic", True)
self._models[model].shown = False
model.ownership_election()
def visible(self, model):
return self._models[model].shown
def raise_window(self, model):
if isinstance(model, OverrideRedirectWindowModel):
model.get_property("client-window").raise_()
else:
window = self._models[model].window
if window is not None:
window.raise_()
## For communicating with WindowModels:
def _unmanaged(self, model, wm_exiting):
del self._models[model]
def _elect_me(self, model):
if self.visible(model):
return (1, self)
else:
return (-1, self)
def take_window(self, model, window):
window.reparent(self.window, 0, 0)
self._models[model].window = window
def window_size(self, model):
w, h = self._models[model].geom[2:4]
return w, h
def window_position(self, model, w, h):
[x, y, w0, h0] = self._models[model].geom
if (w0, h0) != (w, h):
log.warn("Uh-oh, our size doesn't fit window sizing constraints: "
"%sx%s vs %sx%s", w0, h0, w, h)
return x, y
gobject.type_register(DesktopManager)
def can_run_server():
root = gtk.gdk.get_default_root_window()
if not displayHasXComposite(root):
log.error("Xpra is a compositing manager, it cannot use a display which lacks the XComposite extension!")
return False
return True
class XpraServer(gobject.GObject):
__gsignals__ = {
"wimpiggy-child-map-event": one_arg_signal,
"wimpiggy-cursor-event": one_arg_signal,
}
def __init__(self, clobber, sockets, opts):
gobject.GObject.__init__(self)
init_x11_filter()
self.init_x11_atoms()
self.start_time = time.time()
# Do this before creating the Wm object, to avoid clobbering its
# selecting SubstructureRedirect.
root = gtk.gdk.get_default_root_window()
root.set_events(root.get_events() | gtk.gdk.SUBSTRUCTURE_MASK)
root.property_change(gtk.gdk.atom_intern("XPRA_SERVER", False),
gtk.gdk.atom_intern("STRING", False),
8,
gtk.gdk.PROP_MODE_REPLACE,
xpra.__version__)
add_event_receiver(root, self)
# This must happen early, before loading in windows at least:
self._protocol = None
self._potential_protocols = []
self._server_source = None
self.default_damage_options = {}
self.supports_mmap = opts.mmap
self.encoding = opts.encoding or DEFAULT_ENCODING
assert self.encoding in ENCODINGS
self.png_window_icons = False
self.session_name = opts.session_name
try:
import glib
glib.set_application_name(self.session_name or "Xpra")
except ImportError, e:
log.warn("glib is missing, cannot set the application name, please install glib's python bindings: %s", e)
### Create the WM object
self._wm = Wm("Xpra", clobber)
self._wm.connect("new-window", self._new_window_signaled)
self._wm.connect("window-resized", self._window_resized_signaled)
self._wm.connect("bell", self._bell_signaled)
self._wm.connect("quit", lambda _: self.quit(True))
### Create our window managing data structures:
self._desktop_manager = DesktopManager()
self._wm.get_property("toplevel").add(self._desktop_manager)
self._desktop_manager.show_all()
self._window_to_id = {}
self._id_to_window = {}
# Window id 0 is reserved for "not a window"
self._max_window_id = 1
### Load in existing windows:
for window in self._wm.get_property("windows"):
self._add_new_window(window)
for window in get_children(root):
if (is_override_redirect(window) and is_mapped(window)):
self._add_new_or_window(window)
## These may get set by the client:
self.xkbmap_layout = None
self.xkbmap_variant = None
self.xkbmap_print = None
self.xkbmap_query = None
self.xkbmap_mod_meanings = {}
self.xkbmap_mod_managed = None
self.keycode_translation = {}
self.keymap_changing = False
self.keyboard = True
self.keyboard_sync = True
self.key_repeat_delay = -1
self.key_repeat_interval = -1
self.encodings = []
self.mmap = None
self.mmap_size = 0
self.reset_statistics()
self.send_notifications = False
self.last_cursor_serial = None
self.cursor_image = None
#store list of currently pressed keys
#(using a dict only so we can display their names in debug messages)
self.keys_pressed = {}
self.keys_timedout = {}
#timers for cancelling key repeat when we get jitter
self.keys_repeat_timers = {}
### Set up keymap:
self.xkbmap_initial = get_gtk_keymap()
self._keymap = gtk.gdk.keymap_get_default()
self._keymap.connect("keys-changed", self._keys_changed)
self._keys_changed()
self._keynames_for_mod = None
#clear all modifiers
self.clean_keyboard_state()
self._make_keymask_match([])
### Clipboard handling:
self.clipboard_enabled = opts.clipboard
if self.clipboard_enabled:
def send_clipboard(packet):
if self.clipboard_enabled:
self._send(packet)
else:
log("clipboard is disabled, dropping packet")
self._clipboard_helper = ClipboardProtocolHelper(send_clipboard)
else:
self._clipboard_helper = None
### Misc. state:
self._settings = {}
self._xsettings_manager = None
self._has_focus = 0
self._upgrading = False
self.password_file = opts.password_file
self.randr = opts.randr and has_randr()
if self.randr and len(get_screen_sizes())<=1:
#disable randr when we are dealing with a Xvfb
#with only one resolution available
#since we don't support adding them on the fly yet
self.randr = False
if self.randr:
display = gtk.gdk.display_get_default()
i=0
while i<display.get_n_screens():
screen = display.get_screen(i)
screen.connect("size-changed", self._screen_size_changed)
i += 1
log("randr enabled: %s", self.randr)
self.randr_notify = False
self.pulseaudio = opts.pulseaudio
try:
from xpra.dbus_notifications_forwarder import register
self.notifications_forwarder = register(self.notify_callback, self.notify_close_callback)
if self.notifications_forwarder:
log.info("using notification forwarder: %s", self.notifications_forwarder)
except Exception, e:
log.error("error loading or registering our dbus notifications forwarder: %s", e)
self.notifications_forwarder = None
### All right, we're ready to accept customers:
for sock in sockets:
self.add_listen_socket(sock)
def init_x11_atoms(self):
#some applications (like openoffice), do not work properly
#if some x11 atoms aren't defined, so we define them in advance:
for atom_name in ["_NET_WM_WINDOW_TYPE",
"_NET_WM_WINDOW_TYPE_NORMAL",
"_NET_WM_WINDOW_TYPE_DESKTOP",
"_NET_WM_WINDOW_TYPE_DOCK",
"_NET_WM_WINDOW_TYPE_TOOLBAR",
"_NET_WM_WINDOW_TYPE_MENU",
"_NET_WM_WINDOW_TYPE_UTILITY",
"_NET_WM_WINDOW_TYPE_SPLASH",
"_NET_WM_WINDOW_TYPE_DIALOG",
"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU",
"_NET_WM_WINDOW_TYPE_POPUP_MENU",
"_NET_WM_WINDOW_TYPE_TOOLTIP",
"_NET_WM_WINDOW_TYPE_NOTIFICATION",
"_NET_WM_WINDOW_TYPE_COMBO",
"_NET_WM_WINDOW_TYPE_DND",
"_NET_WM_WINDOW_TYPE_NORMAL"
]:
get_xatom(atom_name)
def reset_statistics(self):
self.client_latency = maxdeque(maxlen=100)
self.server_latency = maxdeque(maxlen=100)
self.client_load = None
def clean_keyboard_state(self):
try:
ungrab_all_keys(gtk.gdk.get_default_root_window())
except:
log.error("error ungrabbing keys", exc_info=True)
try:
unpress_all_keys(gtk.gdk.get_default_root_window())
except:
log.error("error unpressing keys", exc_info=True)
def set_keymap(self):
try:
#prevent _keys_changed() from firing:
#(using a flag instead of keymap.disconnect(handler) as this did not seem to work!)
self.keymap_changing = True
self.clean_keyboard_state()
try:
do_set_keymap(self.xkbmap_layout, self.xkbmap_variant,
self.xkbmap_print, self.xkbmap_query)
except:
log.error("error setting new keymap", exc_info=True)
try:
#first clear all existing modifiers:
self.clean_keyboard_state()
modifiers = ALL_X11_MODIFIERS.keys() #just clear all of them (set or not)
clear_modifiers(modifiers)
#now set all the keycodes:
self.clean_keyboard_state()
self.keycode_translation = {}
self._keynames_for_mod = None
if self.keyboard:
assert self.xkbmap_keycodes and len(self.xkbmap_keycodes)>0, "client failed to provide xkbmap_keycodes!"
#if the client does not provide a full keymap,
#try to preserve the initial server keycodes
#(used by non X11 clients like osx,win32 or Android)
preserve_keycodes = {}
if not self.xkbmap_print:
preserve_keycodes = self.xkbmap_initial
self.keycode_translation = set_all_keycodes(self.xkbmap_keycodes, preserve_keycodes)
#now set the new modifier mappings:
self.clean_keyboard_state()
log("going to set modifiers, xkbmap_mod_meanings=%s, len(xkbmap_keycodes)=%s", self.xkbmap_mod_meanings, len(self.xkbmap_keycodes or []))
if self.xkbmap_mod_meanings:
#Unix-like OS provides modifier meanings:
self._keynames_for_mod = set_modifiers_from_meanings(self.xkbmap_mod_meanings)
elif self.xkbmap_keycodes:
#non-Unix-like OS provides just keycodes for now:
self._keynames_for_mod = set_modifiers_from_keycodes(self.xkbmap_keycodes)
else:
log.error("missing both xkbmap_mod_meanings and xkbmap_keycodes, modifiers will probably not work as expected!")
log("keyname_for_mod=%s", self._keynames_for_mod)
except:
log.error("error setting xmodmap", exc_info=True)
finally:
# re-enable via idle_add to give all the pending
# events a chance to run first (and get ignored)
def reenable_keymap_changes(*args):
self.keymap_changing = False
self._keys_changed()
gobject.idle_add(reenable_keymap_changes)
def add_listen_socket(self, sock):
sock.listen(5)
gobject.io_add_watch(sock, gobject.IO_IN, self._new_connection, sock)
def quit(self, upgrading):
self._upgrading = upgrading
log.info("\nxpra is terminating.")
sys.stdout.flush()
gtk_main_quit_really()
def run(self):
gtk_main_quit_on_fatal_exceptions_enable()
def print_ready():
log.info("\nxpra is ready.")
sys.stdout.flush()
gobject.idle_add(print_ready)
gtk.main()
log.info("\nxpra end of gtk.main().")
return self._upgrading
def cleanup(self, *args):
if self.notifications_forwarder:
try:
self.notifications_forwarder.release()
except Exception, e:
log.error("failed to release dbus notification forwarder: %s", e)
self.disconnect("shutting down")
def _new_connection(self, listener, *args):
sock, address = listener.accept()
if len(self._potential_protocols)>=MAX_CONCURRENT_CONNECTIONS:
log.error("too many connections (%s), ignoring new one", len(self._potential_protocols))
sock.close()
return True
log.info("New connection received: %s", sock.getsockname())
protocol = Protocol(SocketConnection(sock, address), self.process_packet)
protocol.salt = None
self._potential_protocols.append(protocol)
protocol.start()
def verify_connection_accepted(protocol):
if not protocol._closed and protocol in self._potential_protocols and protocol!=self._protocol:
log.error("connection timedout: %s", protocol)
self.send_disconnect(protocol, "login timeout")
gobject.timeout_add(10*1000, verify_connection_accepted, protocol)
return True
def _keys_changed(self, *args):
if not self.keymap_changing:
self._modifier_map = grok_modifier_map(gtk.gdk.display_get_default(), self.xkbmap_mod_meanings)
def _window_resized_signaled(self, wm, window):
nw,nh = window.get_property("actual-size")
geom = self._desktop_manager.window_geometry(window)
log("XpraServer._window_resized_signaled(%s,%s) actual-size=%sx%s, current geometry=%s", wm, window, nw, nh, geom)
geom[2:4] = nw,nh
if self.server_window_resize:
self._send(["window-resized", self._window_to_id[window], nw, nh])
def _new_window_signaled(self, wm, window):
self._add_new_window(window)
def do_wimpiggy_cursor_event(self, event):
if self.last_cursor_serial==event.cursor_serial:
log("ignoring cursor event with the same serial number")
return
self.last_cursor_serial = event.cursor_serial
self.cursor_image = get_cursor_image()
if self.cursor_image:
log("do_wimpiggy_cursor_event(%s) new_cursor=%s", event, self.cursor_image[:7])
else:
log("do_wimpiggy_cursor_event(%s) failed to get cursor image", event)
self.send_cursor()
def send_cursor(self):
self._send(["cursor", self.cursor_image or ""])
def _bell_signaled(self, wm, event):
log("_bell_signaled(%s,%r)", wm, event)
if not self.send_bell:
return
wid = 0
if event.window!=gtk.gdk.get_default_root_window() and event.window_model is not None:
try:
wid = self._window_to_id[event.window_model]
except:
pass
log("_bell_signaled(%s,%r) wid=%s", wm, event, wid)
self._send(["bell", wid, event.device, event.percent, event.pitch, event.duration, event.bell_class, event.bell_id, event.bell_name or ""])
def notify_callback(self, dbus_id, nid, app_name, replaces_nid, app_icon, summary, body, expire_timeout):
log("notify_callback(%s,%s,%s,%s,%s,%s,%s,%s) send_notifications=%s", dbus_id, nid, app_name, replaces_nid, app_icon, summary, body, expire_timeout, self.send_notifications)
if self.send_notifications:
self._send(["notify_show", dbus_id, int(nid), str(app_name), int(replaces_nid), str(app_icon), str(summary), str(body), int(expire_timeout)])
def notify_close_callback(self, nid):
log("notify_close_callback(%s)", nid)
if self.send_notifications:
self._send(["notify_close", int(nid)])
def do_wimpiggy_child_map_event(self, event):
raw_window = event.window
if event.override_redirect:
self._add_new_or_window(raw_window)
def _add_new_window_common(self, window):
wid = self._max_window_id
self._max_window_id += 1
self._window_to_id[window] = wid
self._id_to_window[wid] = window
window.connect("client-contents-changed", self._contents_changed)
window.connect("unmanaged", self._lost_window)
_window_export_properties = ("title", "size-hints")
def _add_new_window(self, window):
log("Discovered new ordinary window: %s", window)
self._add_new_window_common(window)
for prop in self._window_export_properties:
window.connect("notify::%s" % prop, self._update_metadata)
(x, y, w, h, _) = window.get_property("client-window").get_geometry()
self._desktop_manager.add_window(window, x, y, w, h)
self._send_new_window_packet(window)
def _add_new_or_window(self, raw_window):
log("Discovered new override-redirect window")
try:
window = OverrideRedirectWindowModel(raw_window)
except Unmanageable:
return
self._add_new_window_common(window)
window.connect("notify::geometry", self._or_window_geometry_changed)
self._send_new_or_window_packet(window)
def _or_window_geometry_changed(self, window, pspec):
(x, y, w, h) = window.get_property("geometry")
wid = self._window_to_id[window]
self._send(["configure-override-redirect", wid, x, y, w, h])
# These are the names of WindowModel properties that, when they change,
# trigger updates in the xpra window metadata:
_all_metadata = ("title", "size-hints", "class-instance", "icon", "client-machine", "transient-for", "window-type")
# Takes the name of a WindowModel property, and returns a dictionary of
# xpra window metadata values that depend on that property:
def _make_metadata(self, window, propname):
assert propname in self._all_metadata
if propname == "title":
if window.get_property("title") is not None:
return {"title": window.get_property("title").encode("utf-8")}
else:
return {}
elif propname == "size-hints":
hints_metadata = {}
hints = window.get_property("size-hints")
if hints is not None:
for attr, metakey in [
("max_size", "maximum-size"),
("min_size", "minimum-size"),
("base_size", "base-size"),
("resize_inc", "increment"),
("min_aspect_ratio", "minimum-aspect"),
("max_aspect_ratio", "maximum-aspect"),
]:
v = getattr(hints, attr)
if v is not None:
hints_metadata[metakey] = v
return {"size-constraints": hints_metadata}
elif propname == "class-instance":
c_i = window.get_property("class-instance")
if c_i is not None:
return {"class-instance": [x.encode("utf-8") for x in c_i]}
else:
return {}
elif propname == "icon":
surf = window.get_property("icon")
if surf is not None:
w = surf.get_width()
h = surf.get_height()
log("found new window icon: %sx%s, sending as png=%s", w,h,self.png_window_icons)
if self.png_window_icons:
import Image
img = Image.frombuffer("RGBA", (w,h), surf.get_data(), "raw", "BGRA", 0, 1)
MAX_SIZE = 64
if w>MAX_SIZE or h>MAX_SIZE:
#scale icon down
if w>=h:
h = int(h*MAX_SIZE/w)
w = MAX_SIZE
else:
w = int(w*MAX_SIZE/h)
h = MAX_SIZE
log("scaling window icon down to %sx%s", w, h)
img = img.resize((w,h), Image.ANTIALIAS)
output = StringIO()
img.save(output, 'PNG')
raw_data = output.getvalue()
return {"icon": (w, h, "png", str(raw_data)) }
else:
assert surf.get_format() == cairo.FORMAT_ARGB32
assert surf.get_stride() == 4 * surf.get_width()
return {"icon": (w, h, "premult_argb32", str(surf.get_data())) }
else:
return {}
elif propname == "client-machine":
client_machine = window.get_property("client-machine")
if client_machine is not None:
return {"client-machine": client_machine.encode("utf-8")}
else:
return {}
elif propname == "transient-for":
transient_for = window.get_property("transient-for")
if transient_for:
log("found transient_for=%s, xid=%s", transient_for, transient_for.xid)
#try to find the model for this window:
for model in self._desktop_manager._models.keys():
log("testing model %s: %s", model, model.client_window.xid)
if model.client_window.xid==transient_for.xid:
wid = self._window_to_id.get(model)
log("found match, window id=%s", wid)
return {"transient-for" : wid}
return {}
return {}
elif propname == "window-type":
window_types = window.get_property("window-type")
log("window_types=%s", window_types)
wts = []
for window_type in window_types:
wts.append(str(window_type))
log("window_types=%s", wts)
return {"window-type" : wts}
raise Exception("unhandled property name: %s" % propname)
def _make_keymask_match(self, modifier_list, ignored_modifier_keycode=None, ignored_modifier_keynames=None):
"""
Given a list of modifiers that should be set, try to press the right keys
to make the server's modifier list match it.
Things to take into consideration:
* xkbmap_mod_managed is a list of modifiers which are "server-managed":
these never show up in the client's modifier list as it is not aware of them,
so we just always leave them as they are and rely on some client key event to toggle them.
ie: "num" on win32, which is toggled by the "Num_Lock" key presses.
* when called from '_handle_key', we ignore the modifier key which may be pressed
or released as it should be set by that key press event.
* when called from mouse position/click events we ignore 'xkbmap_mod_pointermissing'
which is set by the client to indicate modifiers which are missing from mouse events.
ie: on win32, "lock" is missing.
* if the modifier is a "nuisance" one ("lock", "num", "scroll") then we must
simulate a full keypress (down then up).
* some modifiers can be set by multiple keys ("shift" by both "Shift_L" and "Shift_R" for example)
so we try to find the matching modifier in the currently pressed keys (keys_pressed)
to make sure we unpress the right one.
"""
if not self.keyboard:
return
if not self._keynames_for_mod:
log("make_keymask_match: ignored as keynames_for_mod not assigned yet")
return
def get_keycodes(keyname):
keyval = gtk.gdk.keyval_from_name(keyname)
if keyval==0:
log.error("no keyval found for %s", keyname)
return []
entries = self._keymap.get_entries_for_keyval(keyval)
keycodes = []
if entries:
for _keycode,_group,_level in entries:
keycodes.append(_keycode)
return keycodes
def get_current_mask():
(_, _, current_mask) = gtk.gdk.get_default_root_window().get_pointer()
modifiers = mask_to_names(current_mask, self._modifier_map)
log("get_modifier_mask()=%s", modifiers)
return modifiers
current = set(get_current_mask())
wanted = set(modifier_list)
log("make_keymask_match(%s) current mask: %s, wanted: %s, ignoring=%s/%s, keys_pressed=%s", modifier_list, current, wanted, ignored_modifier_keycode, ignored_modifier_keynames, self.keys_pressed)
display = gtk.gdk.display_get_default()
def change_mask(modifiers, press, info):
for modifier in modifiers:
if self.xkbmap_mod_managed and modifier in self.xkbmap_mod_managed:
log("modifier is server managed: %s", modifier)
continue
keynames = self._keynames_for_mod.get(modifier)
if not keynames:
log.error("unknown modifier: %s", modifier)
continue
if ignored_modifier_keynames:
for imk in ignored_modifier_keynames:
if imk in keynames:
log("modifier %s ignored (ignored keyname=%s)", modifier, imk)
continue
keycodes = []
#log.info("keynames(%s)=%s", modifier, keynames)
for keyname in keynames:
if keyname in self.keys_pressed.values():
#found the key which was pressed to set this modifier
for keycode, name in self.keys_pressed.items():
if name==keyname:
log("found the key pressed for %s: %s", modifier, name)
keycodes.insert(0, keycode)
kcs = get_keycodes(keyname)
for kc in kcs:
if kc not in keycodes:
keycodes.append(kc)
if ignored_modifier_keycode is not None and ignored_modifier_keycode in keycodes:
log("modifier %s ignored (ignored keycode=%s)", modifier, ignored_modifier_keycode)
continue
#nuisance keys (lock, num, scroll) are toggled by a
#full key press + key release (so act accordingly in the loop below)
nuisance = modifier in DEFAULT_MODIFIER_NUISANCE
log("keynames(%s)=%s, keycodes=%s, nuisance=%s", modifier, keynames, keycodes, nuisance)
for keycode in keycodes:
if nuisance:
xtest_fake_key(display, keycode, True)
xtest_fake_key(display, keycode, False)
else:
xtest_fake_key(display, keycode, press)
new_mask = get_current_mask()
#log("make_keymask_match(%s) %s modifier %s using %s: %s", info, modifier_list, modifier, keycode, (modifier not in new_mask))
if (modifier in new_mask)==press:
break
elif not nuisance:
log("%s %s with keycode %s did not work - trying to undo it!", info, modifier, keycode)
xtest_fake_key(display, keycode, not press)
new_mask = get_current_mask()
#maybe doing the full keypress (down+up or u+down) worked:
if (modifier in new_mask)==press:
break
change_mask(current.difference(wanted), False, "remove")
change_mask(wanted.difference(current), True, "add")
def _clear_keys_pressed(self):
#make sure the timers don't fire and interfere:
if len(self.keys_repeat_timers)>0:
for timer in self.keys_repeat_timers.values():
gobject.source_remove(timer)
self.keys_repeat_timers = {}
#clear all the keys we know about:
if len(self.keys_pressed)>0:
log("clearing keys pressed: %s", self.keys_pressed)
for keycode in self.keys_pressed.keys():
xtest_fake_key(gtk.gdk.display_get_default(), keycode, False)
self.keys_pressed = {}
#this will take care of any remaining ones we are not aware of:
#(there should not be any - but we want to be certain)
unpress_all_keys(gtk.gdk.display_get_default())
def _focus(self, wid, modifiers):
log("_focus(%s,%s) has_focus=%s", wid, modifiers, self._has_focus)
if self._has_focus != wid:
def reset_focus():
self._clear_keys_pressed()
# FIXME: kind of a hack:
self._has_focus = 0
self._wm.get_property("toplevel").reset_x_focus()
if wid == 0:
return reset_focus()
window = self._id_to_window.get(wid)
if not window:
return reset_focus()
#no idea why we can't call this straight away!
#but with win32 clients, it would often fail!???
def give_focus():
window.give_client_focus()
return False
gobject.idle_add(give_focus)
if modifiers is not None:
self._make_keymask_match(modifiers, self.xkbmap_mod_pointermissing)
self._has_focus = wid
def _move_pointer(self, pos):
(x, y) = pos
display = gtk.gdk.display_get_default()
display.warp_pointer(display.get_default_screen(), x, y)
def _send(self, packet):
if self._protocol is not None:
log("Queuing packet: %s", dump_packet(packet))
self._protocol.source.queue_ordinary_packet(packet)
def _damage(self, window, x, y, width, height, options=None):
if self._protocol is not None and self._protocol.source is not None:
wid = self._window_to_id[window]
if options is None:
options = self.default_damage_options
self._protocol.source.damage(wid, window, x, y, width, height, options)
def _cancel_damage(self, wid):
if self._protocol is not None and self._protocol.source is not None:
self._protocol.source.cancel_damage(wid)
def _send_new_window_packet(self, window):
geometry = self._desktop_manager.window_geometry(window)
self._do_send_new_window_packet("new-window", window, geometry, self._all_metadata)
def _send_new_or_window_packet(self, window):
geometry = window.get_property("geometry")
properties = ["transient-for", "window-type"]
self._do_send_new_window_packet("new-override-redirect", window, geometry, properties)
(_, _, w, h) = geometry
self._damage(window, 0, 0, w, h)
def _do_send_new_window_packet(self, ptype, window, geometry, properties):
wid = self._window_to_id[window]
(x, y, w, h) = geometry
metadata = {}
for propname in properties:
metadata.update(self._make_metadata(window, propname))
self._send([ptype, wid, x, y, w, h, metadata])
def _update_metadata(self, window, pspec):
wid = self._window_to_id[window]
metadata = self._make_metadata(window, pspec.name)
self._send(["window-metadata", wid, metadata])
def _lost_window(self, window, wm_exiting):
wid = self._window_to_id[window]
self._send(["lost-window", wid])
self._cancel_damage(wid)
del self._window_to_id[window]
del self._id_to_window[wid]
if self._server_source:
self._server_source.remove_window(wid)
def _contents_changed(self, window, event):
if (isinstance(window, OverrideRedirectWindowModel)
or self._desktop_manager.visible(window)):
self._damage(window, event.x, event.y, event.width, event.height)
def _screen_size_changed(self, *args):
log("_screen_size_changed(%s)", args)
#randr has resized the screen, tell the client (if it supports it)
if not self.randr_notify:
return
def send_updated_screen_size():
max_w, max_h = self.get_max_screen_size()
root_w, root_h = gtk.gdk.get_default_root_window().get_size()
log("sending updated screen size to client: %sx%s (max %sx%s)", root_w, root_h, max_w, max_h)
self._send(["desktop_size", root_w, root_h, max_w, max_h])
gobject.idle_add(send_updated_screen_size)
def get_max_screen_size(self):
max_w, max_h = gtk.gdk.get_default_root_window().get_size()
sizes = get_screen_sizes()
if self.randr and len(sizes)>=1:
for w,h in sizes:
max_w = max(max_w, w)
max_h = max(max_h, h)
return max_w, max_h
def _get_desktop_size_capability(self, client_capabilities):
root_w, root_h = gtk.gdk.get_default_root_window().get_size()
client_size = client_capabilities.get("desktop_size")
log.info("client resolution is %s, current server resolution is %sx%s", client_size, root_w, root_h)
if not client_size:
""" client did not specify size, just return what we have """
return root_w, root_h
client_w, client_h = client_size
if not self.randr:
""" server does not support randr - return minimum of the client/server dimensions """
w = min(client_w, root_w)
h = min(client_h, root_h)
return w, h
log("client resolution is %sx%s, current server resolution is %sx%s", client_w, client_h, root_w, root_h)
return self.set_screen_size(client_w, client_h)
def set_screen_size(self, client_w, client_h):
root_w, root_h = gtk.gdk.get_default_root_window().get_size()
if client_w==root_w and client_h==root_h:
return root_w,root_h #unlikely: perfect match already!
#try to find the best screen size to resize to:
new_size = None
for w,h in get_screen_sizes():
if w<client_w or h<client_h:
continue #size is too small for client
if new_size:
ew,eh = new_size
if ew*eh<w*h:
continue #we found a better (smaller) candidate already
new_size = w,h
log("best resolution for client(%sx%s) is: %s", client_w, client_h, new_size)
if new_size:
w, h = new_size
if w==root_w and h==root_h:
log.info("best resolution for client %sx%s is unchanged: %sx%s", client_w, client_h, w, h)
else:
try:
set_screen_size(w, h)
(root_w, root_h) = get_screen_size()
if root_w!=w or root_h!=h:
log.error("odd, failed to set the new resolution, "
"tried to set it to %sx%s and ended up with %sx%s", w, h, root_w, root_h)
else:
log.info("new resolution set for client %sx%s : screen now set to %sx%s", client_w, client_h, root_w, root_h)
except Exception, e:
log.error("ouch, failed to set new resolution: %s", e, exc_info=True)
w = min(client_w, root_w)
h = min(client_h, root_h)
return w, h
def _process_desktop_size(self, proto, packet):
(width, height) = packet[1:3]
log("client requesting new size: %sx%s", width, height)
self.set_screen_size(width, height)
def _set_encoding(self, encoding, wids):
if encoding:
assert encoding in self.encodings, "encoding %s is not supported, client supplied list: %s" % (encoding, self.encodings)
if encoding not in ENCODINGS:
log.error("encoding %s is not supported by this server! " \
"Will use the first commonly supported encoding instead", encoding)
encoding = None
else:
log("encoding not specified, will use the first match")
if not encoding:
#not specified or not supported, find intersection of supported encodings:
common = [e for e in self.encodings if e in ENCODINGS]
log("encodings supported by both ends: %s", common)
if not common:
raise Exception("cannot find compatible encoding between "
"client (%s) and server (%s)" % (self.encodings, ENCODINGS))
encoding = common[0]
self.encoding = encoding
if self._server_source is not None:
self._server_source.set_new_encoding(encoding, wids)
log.info("encoding set to %s, client supports %s, server supports %s", encoding, self.encodings, ENCODINGS)
def _process_encoding(self, proto, packet):
encoding = packet[1]
if len(packet)>=3:
#client specified which windows this is for:
in_wids = packet[2]
wids = []
wid_windows = {}
for wid in in_wids:
if wid not in self._id_to_window:
continue
wids.append(wid)
wid_windows[wid] = self._id_to_window.get(wid)
else:
#apply to all windows:
wids = None
wid_windows = self._id_to_window
self._set_encoding(encoding, wids)
opts = self.default_damage_options.copy()
self.refresh_windows(opts, wid_windows)
def send_disconnect(self, proto, reason):
def force_disconnect(*args):
proto.close()
proto._add_packet_to_queue(["disconnect", reason])
gobject.timeout_add(1000, force_disconnect)
def _send_password_challenge(self, proto):
proto.salt = "%s" % uuid.uuid4()
log.info("Password required, sending challenge")
packet = ("challenge", proto.salt)
proto._add_packet_to_queue(packet)
def _verify_password(self, proto, client_hash):
salt = proto.salt
proto.salt = None
if not salt:
self.send_disconnect(proto, "illegal challenge response received - salt cleared or unset")
return
try:
passwordFile = open(self.password_file, "rU")
password = passwordFile.read()
passwordFile.close()
while password.endswith("\n") or password.endswith("\r"):
password = password[:-1]
except IOError, e:
log.error("cannot open password file %s: %s", self.password_file, e)
self.send_disconnect(proto, "invalid password file specified on server")