forked from Xpra-org/xpra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.py
executable file
·2403 lines (2208 loc) · 103 KB
/
setup.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
#!/usr/bin/env python3
# This file is part of Xpra.
# Copyright (C) 2010-2023 Antoine Martin <antoine@xpra.org>
# Copyright (C) 2008, 2009, 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.
##############################################################################
# FIXME: Cython.Distutils.build_ext leaves crud in the source directory.
import re
import sys
import glob
import shlex
import shutil
import os.path
import subprocess
from time import sleep
if sys.version_info<(3, 10):
raise RuntimeError("xpra no longer supports Python versions older than 3.10")
try:
from distutils.core import setup
from distutils.command.build import build
from distutils.command.install_data import install_data
except ImportError as e:
print(f"no distutils: {e}, trying setuptools")
from setuptools import setup
from setuptools.command.build import build
from setuptools.command.install import install as install_data
import xpra
from xpra.os_util import (
get_status_output, load_binary_file, get_distribution_version_id,
getuid,
BITS, WIN32, OSX, LINUX, POSIX, NETBSD, FREEBSD, OPENBSD,
is_Ubuntu, is_Debian, is_Fedora,
is_CentOS, is_AlmaLinux, is_RockyLinux, is_RedHat, is_openSUSE, is_OracleLinux,
)
if BITS!=64:
print(f"Warning: {BITS}-bit architecture, only 64-bits are officially supported")
for _ in range(5):
sleep(1)
print(".")
#*******************************************************************************
print(" ".join(sys.argv))
#*******************************************************************************
# build options, these may get modified further down..
#
data_files = []
modules = []
packages = [] #used by py2app
excludes = [] #only used by cx_freeze on win32
ext_modules = []
cmdclass = {}
scripts = []
description = "multi-platform screen and application forwarding system"
long_description = "Xpra is a multi platform persistent remote display server and client for " + \
"forwarding applications and desktop screens. Also known as 'screen for X11'."
url = "https://xpra.org/"
XPRA_VERSION = xpra.__version__ #@UndefinedVariable
setup_options = {
"name" : "xpra",
"version" : XPRA_VERSION,
"license" : "GPLv2+",
"author" : "Antoine Martin",
"author_email" : "antoine@xpra.org",
"url" : url,
"download_url" : "https://xpra.org/src/",
"description" : description,
"long_description" : long_description,
"data_files" : data_files,
"py_modules" : modules,
"project_urls" : {
"Documentation" : "https://github.com/Xpra-org/xpra/tree/master/docs",
"Funding" : "https://github.com/sponsors/totaam",
"Source" : "https://github.com/Xpra-org/xpra",
},
}
if "pkg-info" in sys.argv:
def write_PKG_INFO():
with open("PKG-INFO", "wb") as f:
pkg_info_values = setup_options.copy()
pkg_info_values |= {
"metadata_version" : "1.1",
"summary" : description,
"home_page" : url,
}
for k in (
"Metadata-Version", "Name", "Version", "Summary", "Home-page",
"Author", "Author-email", "License", "Download-URL", "Description"
):
v = pkg_info_values[k.lower().replace("-", "_")]
f.write(("%s: %s\n" % (k, v)).encode())
write_PKG_INFO()
sys.exit(0)
print("Xpra version %s" % XPRA_VERSION)
#*******************************************************************************
# Most of the options below can be modified on the command line
# using --with-OPTION or --without-OPTION
# only the default values are specified here:
#*******************************************************************************
try:
import cython
print(f"found Cython version {cython.__version__}")
cython_version = int(cython.__version__.split('.')[0])
if cython_version<3:
raise ValueError("Cython 3.x is now required")
except (ValueError, ImportError):
print("WARNING: unable to detect Cython version")
PKG_CONFIG = os.environ.get("PKG_CONFIG", "pkg-config")
def check_pkgconfig():
v = get_status_output([PKG_CONFIG, "--version"])
has_pkg_config = v[0]==0 and v[1]
if has_pkg_config:
print("found pkg-config version: %s" % v[1].strip("\n\r"))
else:
print("WARNING: pkg-config not found!")
check_pkgconfig()
for arg in list(sys.argv):
if arg.startswith("--pkg-config-path="):
pcp = arg[len("--pkg-config-path="):]
pcps = [pcp] + os.environ.get("PKG_CONFIG_PATH", "").split(os.path.pathsep)
os.environ["PKG_CONFIG_PATH"] = os.path.pathsep.join([x for x in pcps if x])
print("using PKG_CONFIG_PATH="+os.environ["PKG_CONFIG_PATH"])
sys.argv.remove(arg)
def no_pkgconfig(*_pkgs_options, **_ekw):
return {}
def pkg_config_ok(*args):
return get_status_output([PKG_CONFIG] + [str(x) for x in args])[0]==0
def pkg_config_version(req_version, pkgname):
r, out, _ = get_status_output([PKG_CONFIG, "--modversion", pkgname])
if r!=0 or not out:
return False
out = out.rstrip("\n\r").split(" ")[0] #ie: "0.155.2917 0a84d98" -> "0.155.2917"
#workaround for libx264 invalid version numbers:
#ie: "0.163.x" or "0.164.3094M"
while out[-1].isalpha() or out[-1]==".":
out = out[:-1]
# pylint: disable=import-outside-toplevel
try:
from packaging.version import parse
return parse(out)>=parse(req_version)
except ImportError:
from distutils.version import LooseVersion # pylint: disable=deprecated-module
return LooseVersion(out)>=LooseVersion(req_version)
DEFAULT = True
if "--minimal" in sys.argv:
sys.argv.remove("--minimal")
DEFAULT = False
skip_build = "--skip-build" in sys.argv
ARCH = get_status_output(["uname", "-m"])[1].strip("\n\r")
ARM = ARCH.startswith("arm") or ARCH.startswith("aarch")
RISCV = ARCH.startswith("riscv")
print(f"{ARCH=}")
INCLUDE_DIRS = os.environ.get("INCLUDE_DIRS", os.path.join(sys.prefix, "include")).split(os.pathsep)
if os.environ.get("INCLUDE_DIRS", None) is None and not WIN32:
# sys.prefix is where the Python interpreter is installed. This may be very different from where
# the C/C++ headers are installed. So do some guessing here:
ALWAYS_INCLUDE_DIRS = ["/usr/include", "/usr/local/include"]
for d in ALWAYS_INCLUDE_DIRS:
if os.path.isdir(d) and d not in INCLUDE_DIRS:
INCLUDE_DIRS.append(d)
print("using INCLUDE_DIRS=%s" % (INCLUDE_DIRS, ))
CPP = os.environ.get("CPP", "cpp")
CC = os.environ.get("CC", "gcc")
print(f"{CC=}")
print(f"{CPP=}")
shadow_ENABLED = DEFAULT
server_ENABLED = DEFAULT
rfb_ENABLED = DEFAULT
quic_ENABLED = DEFAULT
ssh_ENABLED = DEFAULT
http_ENABLED = DEFAULT
service_ENABLED = LINUX and server_ENABLED
sd_listen_ENABLED = POSIX and pkg_config_ok("--exists", "libsystemd")
proxy_ENABLED = DEFAULT
client_ENABLED = DEFAULT
scripts_ENABLED = not WIN32
cython_ENABLED = DEFAULT
cython_tracing_ENABLED = False
modules_ENABLED = DEFAULT
data_ENABLED = DEFAULT
def find_header_file(name, isdir=False):
matches = [v for v in
[d+name for d in INCLUDE_DIRS]
if os.path.exists(v) and os.path.isdir(v)==isdir]
if not matches:
return None
return matches[0]
def has_header_file(name, isdir=False):
return bool(find_header_file(name, isdir))
x11_ENABLED = DEFAULT and not WIN32 and not OSX
xinput_ENABLED = x11_ENABLED
uinput_ENABLED = x11_ENABLED
dbus_ENABLED = DEFAULT and x11_ENABLED and not (OSX or WIN32)
gtk_x11_ENABLED = DEFAULT and not WIN32 and not OSX
gtk3_ENABLED = DEFAULT and client_ENABLED
opengl_ENABLED = DEFAULT and client_ENABLED
pam_ENABLED = DEFAULT and (server_ENABLED or proxy_ENABLED) and POSIX and not OSX and (find_header_file("/security", isdir=True) or pkg_config_ok("--exists", "pam", "pam_misc"))
proc_use_procps = LINUX and has_header_file("/proc/procps.h")
proc_use_libproc = LINUX and has_header_file("/libproc2/pids.h")
proc_ENABLED = LINUX and (proc_use_procps or proc_use_libproc)
xdg_open_ENABLED = (LINUX or FREEBSD) and DEFAULT
netdev_ENABLED = LINUX and DEFAULT
vsock_ENABLED = LINUX and has_header_file("/linux/vm_sockets.h")
lz4_ENABLED = DEFAULT
rencodeplus_ENABLED = DEFAULT
brotli_ENABLED = DEFAULT and has_header_file("/brotli/decode.h") and has_header_file("/brotli/encode.h")
qrencode_ENABLED = DEFAULT and has_header_file("/qrencode.h")
clipboard_ENABLED = DEFAULT
Xdummy_ENABLED = None if POSIX else False #None means auto-detect
Xdummy_wrapper_ENABLED = None if POSIX else False #None means auto-detect
audio_ENABLED = DEFAULT
printing_ENABLED = DEFAULT
crypto_ENABLED = DEFAULT
mdns_ENABLED = DEFAULT
websockets_ENABLED = DEFAULT
codecs_ENABLED = DEFAULT
enc_proxy_ENABLED = DEFAULT
enc_x264_ENABLED = DEFAULT and pkg_config_version("0.155", "x264")
openh264_ENABLED = DEFAULT and pkg_config_version("2.0", "openh264")
openh264_decoder_ENABLED = openh264_ENABLED
openh264_encoder_ENABLED = openh264_ENABLED
#crashes on 32-bit windows:
pillow_ENABLED = DEFAULT
argb_ENABLED = DEFAULT
spng_decoder_ENABLED = DEFAULT and pkg_config_version("0.6", "spng")
spng_encoder_ENABLED = DEFAULT and pkg_config_version("0.7", "spng")
webp_ENABLED = DEFAULT and pkg_config_version("0.5", "libwebp")
jpeg_encoder_ENABLED = DEFAULT and pkg_config_version("1.2", "libturbojpeg")
jpeg_decoder_ENABLED = DEFAULT and pkg_config_version("1.4", "libturbojpeg")
avif_ENABLED = DEFAULT and pkg_config_version("0.9", "libavif") and not OSX
vpx_ENABLED = DEFAULT and pkg_config_version("1.7", "vpx") and BITS==64
#opencv currently broken on 32-bit windows (crashes on load):
webcam_ENABLED = DEFAULT and not OSX and not WIN32
notifications_ENABLED = DEFAULT
keyboard_ENABLED = DEFAULT
v4l2_ENABLED = DEFAULT and (not WIN32 and not OSX and not FREEBSD and not OPENBSD)
evdi_ENABLED = DEFAULT and LINUX and pkg_config_version("1.10", "evdi")
drm_ENABLED = DEFAULT and LINUX and pkg_config_version("2.4", "libdrm")
csc_cython_ENABLED = DEFAULT
nvidia_ENABLED = DEFAULT and not OSX and BITS==64
nvjpeg_encoder_ENABLED = nvidia_ENABLED and pkg_config_ok("--exists", "nvjpeg")
nvjpeg_decoder_ENABLED = nvidia_ENABLED and pkg_config_ok("--exists", "nvjpeg")
nvenc_ENABLED = nvidia_ENABLED and pkg_config_version("10", "nvenc")
nvdec_ENABLED = False
nvfbc_ENABLED = nvidia_ENABLED and not ARM and pkg_config_ok("--exists", "nvfbc")
cuda_kernels_ENABLED = nvidia_ENABLED and not OSX
cuda_rebuild_ENABLED = cuda_kernels_ENABLED and not WIN32
csc_libyuv_ENABLED = DEFAULT and pkg_config_ok("--exists", "libyuv")
gstreamer_ENABLED = DEFAULT
example_ENABLED = DEFAULT
#Cython / gcc / packaging build options:
docs_ENABLED = DEFAULT and shutil.which("pandoc")
pandoc_lua_ENABLED = DEFAULT
annotate_ENABLED = DEFAULT
warn_ENABLED = True
strict_ENABLED = False
PIC_ENABLED = not WIN32 #ming32 moans that it is always enabled already
debug_ENABLED = False
verbose_ENABLED = False
bundle_tests_ENABLED = False
tests_ENABLED = False
rebuild_ENABLED = not skip_build
#allow some of these flags to be modified on the command line:
CODEC_SWITCHES = [
"enc_x264",
"enc_proxy",
"cuda_kernels", "cuda_rebuild",
"openh264", "openh264_decoder", "openh264_encoder",
"nvidia", "nvenc", "nvdec", "nvfbc", "nvjpeg_encoder", "nvjpeg_decoder",
"vpx", "webp", "pillow",
"spng_decoder", "spng_encoder",
"jpeg_encoder", "jpeg_decoder",
"avif", "argb",
"v4l2", "evdi", "drm",
"csc_cython", "csc_libyuv", "gstreamer",
]
SWITCHES = [
"cython", "cython_tracing",
"modules", "data",
"codecs",
] + CODEC_SWITCHES + [
"brotli", "qrencode",
"vsock", "netdev", "proc", "mdns", "lz4",
"clipboard",
"scripts",
"server", "client", "dbus", "x11", "xinput", "uinput", "sd_listen",
"gtk_x11", "service",
"gtk3", "example",
"pam", "xdg_open",
"audio", "opengl", "printing", "webcam", "notifications", "keyboard",
"rebuild",
"docs", "pandoc_lua",
"annotate", "warn", "strict",
"shadow", "proxy", "rfb", "quic", "http", "ssh",
"debug", "PIC",
"Xdummy", "Xdummy_wrapper", "verbose", "tests", "bundle_tests",
]
#some switches can control multiple switches:
SWITCH_ALIAS = {
"codecs" : ["codecs"] + CODEC_SWITCHES,
"openh264" : ("openh264", "openh264_decoder", "openh264_encoder"),
"nvidia" : ("nvidia", "nvenc", "nvdec", "nvfbc", "nvjpeg_encoder", "nvjpeg_decoder", "cuda_kernels", "cuda_rebuild"),
"cython" : ("cython", "codecs",
"server", "client", "shadow",
"rencodeplus", "brotli", "qrencode", "websockets", "netdev", "vsock",
"lz4",
"gtk3", "x11", "gtk_x11",
"pam", "sd_listen", "proc",
),
}
def show_help():
setup()
print("Xpra specific build and install switches:")
for x in sorted(SWITCHES):
d = globals()[f"{x}_ENABLED"]
with_str = f" --with-{x}"
without_str = f" --without-{x}"
if d is True or d is False:
default_str = str(d)
else:
default_str = "auto-detect"
print("%s or %s (default: %s)" % (with_str.ljust(25), without_str.ljust(30), default_str))
print(" --pkg-config-path=PATH")
print(" --rpath=PATH")
HELP = "-h" in sys.argv or "--help" in sys.argv
if HELP:
show_help()
sys.exit(0)
install = None
rpath = None
ssl_cert = None
ssl_key = None
minifier = None
share_xpra = None
dummy_driver_version = None
filtered_args = []
def filter_argv():
for arg in sys.argv:
matched = False
for x in ("rpath", "ssl-cert", "ssl-key", "install", "share-xpra", "dummy-driver-version"):
varg = f"--{x}="
if arg.startswith(varg):
value = arg[len(varg):]
globals()[x.replace("-", "_")] = value
#remove these arguments from sys.argv,
#except for --install=PATH
matched = x!="install"
break
if matched:
continue
for x in SWITCHES:
with_str = f"--with-{x}"
without_str = f"--without-{x}"
var_names = list(SWITCH_ALIAS.get(x, [x]))
#recurse once, so an alias can container aliases:
for v in tuple(var_names):
var_names += list(SWITCH_ALIAS.get(v, []))
if arg.startswith(with_str+"="):
for var in var_names:
globals()[f"{var}_ENABLED"] = arg[len(with_str)+1:]
matched = True
break
if arg==with_str:
for var in var_names:
globals()[f"{var}_ENABLED"] = True
matched = True
break
if arg==without_str:
for var in var_names:
globals()[f"{var}_ENABLED"] = False
matched = True
break
if not matched:
filtered_args.append(arg)
filter_argv()
#enable any codec groups with at least one codec enabled:
#ie: enable "nvidia" if "nvenc" is enabled
for group, items in SWITCH_ALIAS.items():
if globals()[f"{group}_ENABLED"]:
#already enabled
continue
for item in items:
if globals()[f"{item}_ENABLED"]:
print(f"enabling {group!r} for {item!r}")
globals()[f"{group}_ENABLED"] = True
break
sys.argv = filtered_args
if "clean" not in sys.argv and "sdist" not in sys.argv:
def show_switch_info():
switches_info = {}
for x in SWITCHES:
switches_info[x] = globals()[f"{x}_ENABLED"]
print("build switches:")
for k in sorted(SWITCHES):
v = switches_info[k]
print("* %s : %s" % (str(k).ljust(20), {None : "Auto", True : "Y", False : "N"}.get(v, v)))
show_switch_info()
#sanity check the flags:
if clipboard_ENABLED and not server_ENABLED and not gtk3_ENABLED:
print("Warning: clipboard can only be used with the server or one of the gtk clients!")
clipboard_ENABLED = False
if x11_ENABLED and WIN32:
print("Warning: enabling x11 on MS Windows is unlikely to work!")
if gtk_x11_ENABLED and not x11_ENABLED:
print("Error: you must enable x11 to support gtk_x11!")
sys.exit(1)
if client_ENABLED and not gtk3_ENABLED:
print("Warning: client is enabled but none of the client toolkits are!?")
if DEFAULT and (not client_ENABLED and not server_ENABLED):
print("Warning: you probably want to build at least the client or server!")
if DEFAULT and not pillow_ENABLED:
print("Warning: including Python Pillow is VERY STRONGLY recommended")
if DEFAULT and (not enc_x264_ENABLED and not vpx_ENABLED):
print("Warning: no x264 and no vpx support!")
print(" you should enable at least one of these two video encodings")
if install is None and WIN32:
install = os.environ.get("MINGW_PREFIX", sys.prefix or "dist")
if share_xpra is None:
share_xpra = os.path.join("share", "xpra")
def should_rebuild(src_file, bin_file):
if not os.path.exists(bin_file):
return "no file"
if rebuild_ENABLED:
if os.path.getctime(bin_file)<os.path.getctime(src_file):
return "binary file out of date"
if os.path.getctime(bin_file)<os.path.getctime(__file__):
return "newer build file"
return None
def convert_doc(fsrc, fdst, fmt="html", force=False):
bsrc = os.path.basename(fsrc)
bdst = os.path.basename(fdst)
if not force and not should_rebuild(fsrc, fdst):
return
print(f" {bsrc:<30} -> {bdst}")
pandoc = os.environ.get("PANDOC", "pandoc")
cmd = [pandoc, "--from", "commonmark", "--to", fmt, "-o", fdst, fsrc]
if fmt=="html" and pandoc_lua_ENABLED:
cmd += ["--lua-filter", "./fs/bin/links-to-html.lua"]
r = subprocess.Popen(cmd).wait(30)
assert r==0, "'%s' returned %s" % (" ".join(cmd), r)
def convert_doc_dir(src, dst, fmt="html", force=False):
print(f"* {src:<20} -> {dst}")
if not os.path.exists(dst):
os.makedirs(dst, mode=0o755)
for x in os.listdir(src):
fsrc = os.path.join(src, x)
if os.path.isdir(fsrc):
fdst = os.path.join(dst, x)
convert_doc_dir(fsrc, fdst, fmt, force)
elif fsrc.endswith(".md"):
fdst = os.path.join(dst, x.replace("README", "index")[:-3]+"."+fmt)
convert_doc(fsrc, fdst, fmt, force)
elif fsrc.endswith(".png"):
fdst = os.path.join(dst, x)
print(f" {fsrc:<30} -> {fdst} (%s)" % oct(0o644))
os.makedirs(name=dst, mode=0o755, exist_ok=True)
data = load_binary_file(fsrc)
with open(fdst, "wb") as f:
f.write(data)
os.chmod(fdst, 0o644)
else:
print(f"ignoring {fsrc!r}")
def convert_docs(fmt="html"):
paths = [x for x in sys.argv[2:] if not x.startswith("--")]
if len(paths)==1 and os.path.isdir(paths[0]):
convert_doc_dir("docs", paths[0])
elif paths:
for x in paths:
convert_doc(x, f"build/{x}", fmt=fmt)
else:
convert_doc_dir("docs", "build/docs", fmt=fmt)
if "doc" in sys.argv:
convert_docs("html")
sys.exit(0)
if "pdf-doc" in sys.argv:
convert_docs("pdf")
sys.exit(0)
if len(sys.argv)<2:
print(f"{sys.argv[0]} arguments are missing!")
sys.exit(1)
if sys.argv[1]=="unittests":
os.execv("./tests/unittests/run", ["run"] + sys.argv[2:])
assert "unittests" not in sys.argv, sys.argv
#*******************************************************************************
# default sets:
external_includes = ["hashlib", "ctypes", "platform"]
if gtk3_ENABLED or audio_ENABLED:
external_includes += ["gi"]
external_excludes = [
#Tcl/Tk
"Tkconstants", "tkinter", "tcl",
#PIL bits that import TK:
"PIL._tkinter_finder", "_imagingtk", "PIL._imagingtk", "ImageTk", "PIL.ImageTk", "FixTk",
#formats we don't use:
"GimpGradientFile", "GimpPaletteFile", "BmpImagePlugin", "TiffImagePlugin",
#not used:
"curses", "pdb",
"tty",
"setuptools", "doctest",
"nose", "pytest", "_pytest", "pluggy", "more_itertools", "apipkg", "py", "funcsigs",
"Cython", "cython", "pyximport",
"pydoc_data",
]
if not crypto_ENABLED:
external_excludes += ["ssl", "_ssl", "uvloop"]
if not client_ENABLED:
external_excludes += ["mimetools"]
if not client_ENABLED and not server_ENABLED:
excludes += ["PIL"]
if not dbus_ENABLED:
excludes += ["dbus"]
#because of differences in how we specify packages and modules
#for distutils / py2app and cx_freeze
#use the following functions, which should get the right
#data in the global variables "packages", "modules" and "excludes"
def remove_packages(*mods):
""" ensures that the given packages are not included:
removes them from the "modules" and "packages" list and adds them to "excludes" list
"""
for m in list(modules):
for x in mods:
if m.startswith(x):
modules.remove(m)
break
for x in mods:
if x in packages:
packages.remove(x)
if x not in excludes:
excludes.append(x)
def add_packages(*pkgs):
""" adds the given packages to the packages list,
and adds all the modules found in this package (including the package itself)
"""
for x in pkgs:
if x not in packages:
packages.append(x)
add_modules(*pkgs)
def add_modules(*mods):
def add(v):
if v not in modules:
modules.append(v)
do_add_modules(add, *mods)
def do_add_modules(op, *mods):
""" adds the packages and any .py module found in the packages to the "modules" list
"""
for x in mods:
#ugly path stripping:
if x.startswith("./"):
x = x[2:]
if x.endswith(".py"):
x = x[:-3]
x = x.replace("/", ".") #.replace("\\", ".")
pathname = os.path.sep.join(x.split("."))
#is this a file module?
f = f"{pathname}.py"
if os.path.exists(f) and os.path.isfile(f):
op(x)
if os.path.exists(pathname) and os.path.isdir(pathname):
#add all file modules found in this directory
for f in os.listdir(pathname):
#make sure we only include python files,
#and ignore eclipse copies
if f.endswith(".py") and not f.startswith("Copy "):
fname = os.path.join(pathname, f)
if os.path.isfile(fname):
modname = f"{x}."+f.replace(".py", "")
op(modname)
def toggle_packages(enabled, *module_names):
if enabled:
add_packages(*module_names)
else:
remove_packages(*module_names)
def toggle_modules(enabled, *module_names):
if enabled:
def op(v):
if v not in modules:
modules.append(v)
do_add_modules(op, *module_names)
else:
remove_packages(*module_names)
#always included:
if modules_ENABLED:
add_modules("xpra", "xpra.platform", "xpra.net", "xpra.scripts.main")
#*******************************************************************************
# Utility methods for building with Cython
def add_cython_ext(*args, **kwargs):
if "--no-compile" in sys.argv and not ("build" in sys.argv and "install" in sys.argv):
return
if not cython_ENABLED:
raise ValueError(f"cannot build {args}: cython compilation is disabled")
if cython_tracing_ENABLED:
kwargs["define_macros"] = [
('CYTHON_TRACE', 1),
('CYTHON_TRACE_NOGIL', 1),
]
kwargs.setdefault("extra_compile_args", []).append("-Wno-error")
# pylint: disable=import-outside-toplevel
from Cython.Distutils import build_ext, Extension
ext_modules.append(Extension(*args, **kwargs))
cmdclass['build_ext'] = build_ext
def ace(modnames="xpra.x11.bindings.xxx", pkgconfig_names="", optimize=None, **kwargs):
src = modnames.split(",")
modname = src[0]
if not src[0].endswith(".pyx"):
src[0] = src[0].replace(".", "/")+".pyx"
if isinstance(pkgconfig_names, str):
pkgconfig_names = [x for x in pkgconfig_names.split(",") if x]
pkgc = pkgconfig(*pkgconfig_names, optimize=optimize)
for addto in ("extra_link_args", "extra_compile_args"):
value = kwargs.pop(addto, None)
if value:
if isinstance(value, str):
value = (value, )
add_to_keywords(pkgc, addto, *value)
for v in value:
if v.startswith("-Wno-error="):
#make sure to remove the corresponding switch that may enable it:
warning = v.split("-Wno-error=", 1)[1]
if remove_from_keywords(pkgc, addto, f"-W{warning}"):
print(f"removed -W{warning} for {modname}")
pkgc.update(kwargs)
CPP = kwargs.get("language", "")=="c++"
if CPP:
#default to "-std=c++11" for c++
if not any(v.startswith("-std=") for v in pkgc.get("extra_compile_args", ())):
add_to_keywords(pkgc, "extra_compile_args", "-std=c++11")
#all C++ modules trigger an address warning in the module initialization code:
if WIN32:
add_to_keywords(pkgc, "extra_compile_args", "-Wno-error=address")
if get_clang_version()>=(14, ):
add_to_keywords(pkgc, "extra_compile_args", "-Wno-error=unreachable-code-fallthrough")
add_cython_ext(modname, src, **pkgc)
def tace(toggle, *args, **kwargs):
if toggle:
ace(*args, **kwargs)
def insert_into_keywords(kw, key, *args):
values = kw.setdefault(key, [])
for arg in args:
values.insert(0, arg)
def add_to_keywords(kw, key, *args):
values = kw.setdefault(key, [])
for arg in args:
values.append(arg)
def remove_from_keywords(kw, key, value):
values = kw.get(key)
i = 0
while values and value in values:
values.remove(value)
i += 1
return i
def checkdirs(*dirs):
for d in dirs:
if not os.path.exists(d) or not os.path.isdir(d):
raise RuntimeError(f"cannot find a directory which is required for building: {d!r}")
def CC_is_clang():
if CC.find("clang")>=0:
return True
return get_clang_version()>(0, )
clang_version = None
def get_clang_version():
global clang_version
if clang_version is not None:
return clang_version
r, _, err = get_status_output([CC, "-v"])
clang_version = (0, )
if r!=0:
#not sure!
return clang_version
for line in err.splitlines():
for v_line in ("Apple clang version", "clang version"):
if line.startswith(v_line):
v_str = line[len(v_line):].strip().split(" ")[0]
tmp_version = []
for p in v_str.split("."):
try:
tmp_version.append(int(p))
except ValueError:
break
print(f"found {v_line}: %s" % ".".join(str(x) for x in tmp_version))
clang_version = tuple(tmp_version)
return clang_version
#not found!
return clang_version
_gcc_version = None
def get_gcc_version():
global _gcc_version
if _gcc_version is not None:
return _gcc_version
_gcc_version = (0, )
if CC_is_clang():
return _gcc_version
r, _, err = get_status_output([CC, "-v"])
if r==0:
V_LINE = "gcc version "
tmp_version = []
for line in err.splitlines():
if not line.startswith(V_LINE):
continue
v_str = line[len(V_LINE):].strip().split(" ")[0]
for p in v_str.split("."):
try:
tmp_version.append(int(p))
except ValueError:
break
print("found gcc version: %s" % ".".join(str(x) for x in tmp_version))
break
_gcc_version = tuple(tmp_version)
return _gcc_version
def vernum(s):
return tuple(int(v) for v in s.split("-", 1)[0].split("."))
# Tweaked from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502261
def exec_pkgconfig(*pkgs_options, **ekw):
kw = dict(ekw)
if "INCLUDE_DIRS" in os.environ:
for d in INCLUDE_DIRS:
add_to_keywords(kw, 'extra_compile_args', "-I", d)
optimize = kw.pop("optimize", None)
if optimize and not debug_ENABLED and not cython_tracing_ENABLED:
if isinstance(optimize, bool):
optimize = int(optimize)*3
add_to_keywords(kw, 'extra_compile_args', "-O%i" % optimize)
ignored_flags = kw.pop("ignored_flags", [])
ignored_tokens = kw.pop("ignored_tokens", [])
#for distros that don't patch distutils,
#we have to add the python cflags:
if not (is_Fedora() or is_Debian() or is_CentOS() or is_RedHat() or is_AlmaLinux() or is_RockyLinux() or is_OracleLinux() or is_openSUSE()):
# pylint: disable=import-outside-toplevel
import sysconfig
for cflag in shlex.split(sysconfig.get_config_var('CFLAGS') or ''):
add_to_keywords(kw, 'extra_compile_args', cflag)
def add_tokens(s, add_to="extra_link_args"):
if not s:
return
flag_map = {
'-I': 'include_dirs',
'-L': 'library_dirs',
'-l': 'libraries',
}
for token in shlex.split(s):
if token in ignored_tokens:
continue
if token[:2] in ignored_flags:
continue
if token[:2] in flag_map:
#this overrules 'add_to' - is this still needed?
if len(token)>2:
add_to_keywords(kw, flag_map[token[:2]], token[2:])
else:
print(f"Warning: invalid token {token!r}")
else:
add_to_keywords(kw, add_to, token)
def hascflag(s):
return s in kw.get("extra_compile_args", [])
def addcflags(*s):
add_to_keywords(kw, "extra_compile_args", *s)
def addldflags(*s):
add_to_keywords(kw, "extra_link_args", *s)
if pkgs_options:
for pc_arg, add_to in {
"--libs" : "extra_link_args",
"--cflags" : "extra_compile_args",
}.items():
pkg_config_cmd = ["pkg-config", pc_arg] + list(pkgs_options)
if verbose_ENABLED:
print(f"{pkg_config_cmd=}")
r, pkg_config_out, err = get_status_output(pkg_config_cmd)
if r!=0:
sys.exit("ERROR: call to '%s' failed (err=%s)" % (" ".join(pkg_config_cmd), err))
if verbose_ENABLED:
print(f"pkg-config output: {pkg_config_out}")
add_tokens(pkg_config_out, add_to)
if verbose_ENABLED:
print(f"pkg-config {kw=}")
if warn_ENABLED:
addcflags("-Wall")
addldflags("-Wall")
if strict_ENABLED:
if CC.find("clang")>=0:
#clang emits too many warnings with cython code,
#so we can't enable Werror without turning off some warnings:
#this list of flags should allow clang to build the whole source tree,
#as of Cython 0.26 + clang 4.0. Other version combinations may require
#(un)commenting other switches.
if not hascflag("-Wno-error"):
addcflags("-Werror")
addcflags(
"-Wno-deprecated-register",
"-Wno-unused-command-line-argument",
#"-Wno-unneeded-internal-declaration",
#"-Wno-unknown-attributes",
#"-Wno-unused-function",
#"-Wno-self-assign",
#"-Wno-sometimes-uninitialized",
#cython adds rpath to the compilation command??
#and the "-specs=/usr/lib/rpm/redhat/redhat-hardened-cc1" is also ignored by clang:
)
else:
if not hascflag("-Wno-error"):
addcflags("-Werror")
if NETBSD:
#see: http://trac.cython.org/ticket/395
addcflags("-fno-strict-aliasing")
elif FREEBSD:
addcflags("-Wno-error=unused-function")
remove_from_keywords(kw, 'extra_compile_args', "-fpermissive")
if PIC_ENABLED:
addcflags("-fPIC")
if debug_ENABLED:
addcflags("-g", "-ggdb")
if not WIN32:
addcflags("-fsanitize=address")
addldflags("-fsanitize=address")
if rpath and kw.get("libraries"):
insert_into_keywords(kw, "library_dirs", rpath)
insert_into_keywords(kw, "extra_link_args", f"-Wl,-rpath={rpath}")
CFLAGS = os.environ.get("CFLAGS")
LDFLAGS = os.environ.get("LDFLAGS")
#win32 remove double "-march=x86-64 -mtune=generic -O2 -pipe -O3"?
if verbose_ENABLED:
print(f"adding {CFLAGS=}")
print(f"adding {LDFLAGS=}")
add_tokens(CFLAGS, "extra_compile_args")
add_tokens(LDFLAGS, "extra_link_args")
#add_to_keywords(kw, 'include_dirs', '.')
if debug_ENABLED and WIN32 and MINGW_PREFIX:
extra_compile_args.append("-DDEBUG")
if verbose_ENABLED:
print(f"exec_pkgconfig({pkgs_options}, {ekw})={kw}")
return kw
pkgconfig = exec_pkgconfig
#*******************************************************************************
def get_base_conf_dir(install_dir, stripbuildroot=True):
#in some cases we want to strip the buildroot (to generate paths in the config file)
#but in other cases we want the buildroot path (when writing out the config files)
#and in some cases, we don't have the install_dir specified (called from detect_xorg_setup, and that's fine too)
#this is a bit hackish, but I can't think of a better way of detecting it
#(ie: "$HOME/rpmbuild/BUILDROOT/xpra-0.15.0-0.fc21.x86_64/usr")
dirs = (install_dir or sys.prefix).split(os.path.sep)
if install_dir and stripbuildroot:
pkgdir = os.environ.get("pkgdir")
if "debian" in dirs and "tmp" in dirs:
#ugly fix for stripping the debian tmp dir:
#ie: "???/tmp/???/tags/v0.15.x/src/debian/tmp/" -> ""
while "tmp" in dirs:
dirs = dirs[dirs.index("tmp")+1:]
elif "debian" in dirs:
#same for recent debian versions:
#ie: "xpra-2.0.2/debian/xpra/usr" -> "usr"
i = dirs.index("debian")
while i>=0 and len(dirs)>i+1:
if dirs[i+1] == "xpra":
dirs = dirs[i+2:]
i = dirs.index("debian")
elif "BUILDROOT" in dirs:
#strip rpm style build root:
#[$HOME, "rpmbuild", "BUILDROOT", "xpra-$VERSION"] -> []
dirs = dirs[dirs.index("BUILDROOT")+2:]
elif "pkg" in dirs:
#archlinux
#ie: "/build/xpra/pkg/xpra/etc" -> "etc"
#find the last 'pkg' from the list of directories:
i = max(loc for loc, val in enumerate(dirs) if val == "pkg")
if len(dirs)>i+1 and dirs[i+1] in ("xpra", "xpra-git"):
dirs = dirs[i+2:]
elif pkgdir and install_dir.startswith(pkgdir):
#arch build dir:
dirs = install_dir.lstrip(pkgdir).split(os.path.sep)
elif "usr" in dirs:
#ie: ["some", "path", "to", "usr"] -> ["usr"]
#assume "/usr" or "/usr/local" is the build root
while "usr" in dirs[1:]:
dirs = dirs[dirs[1:].index("usr")+1:]
elif "image" in dirs:
# Gentoo's "${PORTAGE_TMPDIR}/portage/${CATEGORY}/${PF}/image/_python2.7" -> ""
while "image" in dirs:
dirs = dirs[dirs.index("image")+2:]
#now deal with the fact that "/etc" is used for the "/usr" prefix
#but "/usr/local/etc" is used for the "/usr/local" prefix..
if dirs and dirs[-1]=="usr":
dirs = dirs[:-1]
#is this an absolute path?
if not dirs or dirs[0]=="usr" or (install_dir or sys.prefix).startswith(os.path.sep):
#ie: ["/", "usr"] or ["/", "usr", "local"]
dirs.insert(0, os.path.sep)
return dirs
def get_conf_dir(install_dir, stripbuildroot=True):
dirs = get_base_conf_dir(install_dir, stripbuildroot)
if "etc" not in dirs:
dirs.append("etc")
dirs.append("xpra")
return os.path.join(*dirs)
def detect_xorg_setup(install_dir=None):
# pylint: disable=import-outside-toplevel
from xpra.scripts import config
config.debug = config.warn
conf_dir = get_conf_dir(install_dir)
dummy = Xdummy_ENABLED
if bool(dummy_driver_version):
dummy = True
return config.detect_xvfb_command(conf_dir, None, dummy, Xdummy_wrapper_ENABLED)
def detect_xdummy_setup(install_dir=None):
# pylint: disable=import-outside-toplevel
from xpra.scripts import config
config.debug = config.warn
conf_dir = get_conf_dir(install_dir)
return config.detect_xdummy_command(conf_dir, None, Xdummy_wrapper_ENABLED)