-
-
Notifications
You must be signed in to change notification settings - Fork 169
/
setup.py
executable file
·2829 lines (2536 loc) · 114 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 shlex
import shutil
import os.path
import subprocess
from glob import glob
from time import sleep
from collections.abc import Sequence
if sys.version_info < (3, 10):
raise RuntimeError("xpra no longer supports Python versions older than 3.10")
# required for PEP 517
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
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 BITS, WIN32, OSX, LINUX, POSIX, NETBSD, FREEBSD, OPENBSD, getuid
from xpra.util.system import is_distribution_variant, get_linux_distribution, is_DEB, is_RPM
from xpra.util.io import load_binary_file, get_status_output
if BITS != 64:
print(f"Warning: {BITS}-bit architecture, only 64-bits are officially supported")
for _ in range(5):
sleep(1)
print(".")
def is_Fedora() -> bool:
return is_distribution_variant("Fedora")
def is_openSUSE() -> bool:
return is_distribution_variant("openSUSE")
#*******************************************************************************
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 = "".join(
"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__
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() -> None:
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)
print("Python version %s" % (".".join(str(v) for v in sys.version_info[:3])))
#*******************************************************************************
# 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:
#*******************************************************************************
PKG_CONFIG = os.environ.get("PKG_CONFIG", "pkg-config")
def check_pkgconfig() -> None:
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) -> dict:
return {}
def pkg_config_ok(*args) -> bool:
return get_status_output([PKG_CONFIG] + [str(x) for x in args])[0] == 0
def pkg_config_version(req_version: str, pkgname: str) -> bool:
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)
argv = sys.argv + list(filter(len, os.environ.get("XPRA_EXTRA_BUILD_ARGS", "").split(" ")))
DEFAULT = True
if "--minimal" in argv:
argv.remove("--minimal")
DEFAULT = False
skip_build = "--skip-build" in 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={ARCH}")
TIMEOUT = 60
if ARM or RISCV:
# arm64 and riscv builds run on emulated CPU, very slowly
TIMEOUT = 300
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={CC}")
print(f"CPP={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
qt6_client_ENABLED = False
scripts_ENABLED = not WIN32
cython_ENABLED = DEFAULT
cythonize_more_ENABLED = False
cython_tracing_ENABLED = False
modules_ENABLED = DEFAULT
data_ENABLED = DEFAULT
def find_header_file(name: str, isdir=False) -> str:
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 ""
return matches[0]
def has_header_file(name, isdir=False) -> bool:
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 or WIN32) and not OSX
gtk_x11_ENABLED = DEFAULT and not WIN32 and not OSX
gtk3_ENABLED = DEFAULT and client_ENABLED
ism_ext_ENABLED = DEFAULT and gtk3_ENABLED and data_ENABLED
opengl_ENABLED = DEFAULT and client_ENABLED
has_pam_headers = has_header_file("/security", isdir=True) or pkg_config_ok("--exists", "pam", "pam_misc")
pam_ENABLED = DEFAULT and (server_ENABLED or proxy_ENABLED) and LINUX and has_pam_headers
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")
cityhash_ENABLED = False # has_header_file("/city.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
websockets_browser_cookie_ENABLED = DEFAULT
codecs_ENABLED = DEFAULT
encoders_ENABLED = codecs_ENABLED
decoders_ENABLED = codecs_ENABLED
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
pillow_encoder_ENABLED = pillow_ENABLED
pillow_decoder_ENABLED = pillow_ENABLED
argb_ENABLED = DEFAULT
argb_encoder_ENABLED = argb_ENABLED
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")
webp_encoder_ENABLED = webp_ENABLED
webp_decoder_ENABLED = webp_ENABLED
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
avif_encoder_ENABLED = avif_ENABLED
avif_decoder_ENABLED = avif_ENABLED
vpx_ENABLED = DEFAULT and pkg_config_version("1.7", "vpx") and BITS==64
vpx_encoder_ENABLED = vpx_ENABLED
vpx_decoder_ENABLED = vpx_ENABLED
# 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 or FREEBSD) 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 (nvenc_ENABLED or nvjpeg_encoder_ENABLED)
cuda_rebuild_ENABLED = None if (nvidia_ENABLED and not WIN32) else False
csc_libyuv_ENABLED = DEFAULT and pkg_config_ok("--exists", "libyuv")
gstreamer_ENABLED = DEFAULT
gstreamer_audio_ENABLED = gstreamer_ENABLED
gstreamer_video_ENABLED = gstreamer_ENABLED
example_ENABLED = DEFAULT
win32_tools_ENABLED = WIN32 and DEFAULT
# Cython / gcc / packaging build options:
docs_ENABLED = DEFAULT and shutil.which("pandoc")
pandoc_lua_ENABLED = DEFAULT
annotate_ENABLED = False
warn_ENABLED = True
strict_ENABLED = False
Os_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:
ENCODER_SWITCHES = [
"enc_proxy",
"enc_x264", "openh264_encoder", "nvenc", "nvjpeg_encoder",
"vpx_encoder", "webp_encoder", "pillow_encoder",
"spng_encoder", "jpeg_encoder", "avif_encoder",
"argb_encoder",
]
DECODER_SWITCHES = [
"openh264_decoder",
"nvdec", "nvjpeg_decoder",
"vpx_decoder", "webp_decoder", "pillow_decoder",
"spng_decoder", "jpeg_decoder", "avif_decoder",
]
CODEC_SWITCHES = ENCODER_SWITCHES + DECODER_SWITCHES + [
"cuda_kernels", "cuda_rebuild",
"nvidia", "nvfbc",
"openh264",
"vpx", "webp",
"pillow",
"avif", "argb",
"v4l2", "evdi", "drm",
"csc_cython", "csc_libyuv",
"gstreamer", "gstreamer_audio", "gstreamer_video",
]
# some switches can control multiple switches:
SWITCH_ALIAS = {
"codecs": ["codecs"] + CODEC_SWITCHES,
"encoders": ENCODER_SWITCHES,
"decoders": DECODER_SWITCHES,
"argb" : ("argb_encoder", ),
"pillow": ("pillow_encoder", "pillow_decoder"),
"vpx" : ("vpx_encoder", "vpx_decoder"),
"webp" : ("webp_encoder", "webp_decoder"),
"avif": ("avif_encoder", "avif_decoder"),
"openh264": ("openh264", "openh264_decoder", "openh264_encoder"),
"nvidia": ("nvidia", "nvenc", "nvdec", "nvfbc", "nvjpeg_encoder", "nvjpeg_decoder", "cuda_kernels", "cuda_rebuild"),
"gstreamer": ("gstreamer_audio", "gstreamer_video"),
"cython": (
"cython", "codecs",
"server", "client", "shadow",
"rencodeplus", "brotli", "cityhash", "qrencode", "websockets", "netdev", "vsock",
"lz4",
"x11", "gtk_x11",
"pam", "sd_listen", "proc",
),
}
SWITCHES = []
# add the ones we have aliases for:
for sw, deps in SWITCH_ALIAS.items():
SWITCHES += [sw] + list(deps)
for sw in CODEC_SWITCHES:
if sw not in SWITCHES:
SWITCHES.append(sw)
SWITCHES += [
"cython_tracing", "cythonize_more",
"modules", "data",
"brotli", "cityhash", "qrencode",
"vsock", "netdev", "proc", "mdns", "lz4",
"clipboard",
"scripts",
"server", "client", "dbus", "x11", "xinput", "uinput", "sd_listen",
"gtk_x11", "service",
"gtk3", "example", "qt6_client",
"ism_ext",
"pam", "xdg_open",
"audio", "opengl", "printing", "webcam", "notifications", "keyboard",
"rebuild",
"docs", "pandoc_lua",
"annotate", "warn", "strict", "Os",
"shadow", "proxy", "rfb", "quic", "http", "ssh",
"debug", "PIC",
"Xdummy", "Xdummy_wrapper", "verbose", "tests", "bundle_tests",
"win32_tools", "websockets_browser_cookie",
]
SWITCHES = list(sorted(set(SWITCHES)))
install = None
rpath = None
ssl_cert = None
ssl_key = None
minifier = None
share_xpra = None
dummy_driver_version = None
filtered_args = []
def filter_argv() -> None:
for arg in 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 install is None and WIN32:
MINGW_PREFIX = os.environ.get("MINGW_PREFIX", "")
install = MINGW_PREFIX or sys.prefix or "dist"
if share_xpra is None:
share_xpra = os.path.join("share", "xpra")
def should_rebuild(src_file: str, bin_file: str) -> str:
if not os.path.exists(bin_file):
return "no file"
if rebuild_ENABLED and os.path.getctime(bin_file) < os.path.getctime(src_file):
return "binary file is out of date"
return ""
def convert_doc(fsrc: str, fdst: str, fmt="html", force=False) -> None:
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", "") or shutil.which("pandoc")
if WIN32 and not pandoc:
pandoc = "/c/Program Files/Pandoc/pandoc.exe"
if not os.path.exists(pandoc):
raise RuntimeError("`pandoc` was not found!")
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(TIMEOUT)
assert r==0, "'%s' returned %s" % (" ".join(cmd), r)
def convert_doc_dir(src, dst, fmt="html", force=False) -> None:
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:<50} -> {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") -> None:
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)
def install_dev_env() -> None:
if not LINUX:
print(f"'dev-env' subcommand is not supported on {sys.platform!r}")
sys.exit(1)
elif is_RPM() and not is_openSUSE():
py3 = os.environ.get("PYTHON3", "")
if not py3:
py3 = "python3"
# is this default python?
exit_code, out, _ = get_status_output(["python3", "--version"])
if exit_code == 0:
# ie: out = "Python 3.12.4"
try:
default_python_version = tuple(int(nstr) for nstr in out.split(" ", 1)[-1].split(".", 2))
except ValueError:
pass
else:
if len(default_python_version) >= 2 and sys.version_info[:2] != default_python_version[:2]:
# this is not the default python interpreter!
py3 = "python%i.%i" % sys.version_info[:2]
flag_to_pkgs = {
"modules": (
# generic build requirements:
"tar", "grep", "gawk", "gcc", "gcc-c++", "pkgconfig",
"which", "coreutils",
f"{py3}-cryptography", ),
"cython": (f"{py3}-devel", f"{py3}-cython", f"{py3}-setuptools", "xxhash-devel", ),
"lz4": ("pkgconfig(liblz4)", ),
"brotli": ("pkgconfig(libbrotlidec)", "pkgconfig(libbrotlienc)", ),
"qrencode": ("pkgconfig(libqrencode)", ),
"gtk3": (
f"{py3}-gobject", "pkgconfig(pygobject-3.0)", "pkgconfig(py3cairo)", "pkgconfig(gtk+-3.0)",
"pkgconfig(gobject-introspection-1.0)",
),
"nvidia|tests": (f"{py3}-numpy", ),
"drm": ("pkgconfig(libdrm)", ),
"vpx": ("pkgconfig(vpx)", ),
"webp": ("pkgconfig(libwebp)", ),
"jpeg_decoder|jpeg_encoder": ("pkgconfig(libturbojpeg)", ),
"csc_libyuv": ("pkgconfig(libyuv)", ),
"openh264": ("pkgconfig(openh264)", ),
"spng_decoder|spng_encoder": ("pkgconfig(spng)", ),
"evdi": ("libevdi-devel", ),
"enc_x264": ("pkgconfig(x264)", ),
"avif": ("pkgconfig(libavif)", ),
"nvidia": ("cuda", ),
"docs": ("pandoc", ),
"tests": ("gstreamer1", "gstreamer1-plugins-good", "pulseaudio", "pulseaudio-utils", "desktop-file-utils", "xclip", ),
"x11": ("pkgconfig(xkbfile)", "pkgconfig(xtst)", "pkgconfig(xcomposite)",
"pkgconfig(xdamage)", "pkgconfig(xres)", "pkgconfig(xfixes)", "pkgconfig(xrandr)",
"xorg-x11-drv-dummy",
),
"Xdummy": ("xorg-x11-drv-dummy", ),
"proc": ("procps-ng-devel" if is_Fedora() else "pkgconfig(libprocps)", ),
"sd_listen": ("pkgconfig(libsystemd)", ),
"pam": ("pam-devel", ),
}
if py3 == "python3":
# we don't have a spec file for this one, can only install the default python3 package:
flag_to_pkgs["printing"] = (f"{py3}-cups", )
cmd = ["dnf", "install"]
elif is_DEB():
flag_to_pkgs = {
"modules": (
"python3-dev",
"pkgconf", "xz-utils", "lsb-release",
),
"cython": ("gcc", "cython3", "libxxhash-dev", ),
"x11": ("libx11-dev", "libxcomposite-dev", "libxdamage-dev",
"libxtst-dev", "libxkbfile-dev", "libxres-dev",
"xvfb",
),
"drm": ("libdrm-dev", ),
"evdi": ("libevdi0-dev", ),
"avif": ("libavif-dev", ),
"csc_libyuv": ("libyuv-dev", ),
"vpx": ("libvpx-dev", ),
"enc_x264": ("libx264-dev", ),
"openh264": ("libopenh264-dev", ),
"webp": ("libwebp-dev", ),
"jpeg_decoder|jpeg_encoder": ("libturbojpeg-dev", ),
"spng_decoder|spng_encoder": ("libspng-dev", ),
"gtk3": ("libgtk-3-dev", "python3-cairo-dev", "python-gi-dev"),
"sd_listen": ("python-gi-dev", ),
"pam": ("libpam0g-dev", ),
"proc": ("libproc2-dev | libprocps-dev", ),
"lz4": ("liblz4-dev", ),
"brotli": ("libbrotli-dev", ),
"qrencode": ("libqrencode-dev", ),
"docs": ("pandoc", ),
}
cmd = ["apt", "install"]
else:
distro = get_linux_distribution()
print("'dev-env' subcommand is not supported on your distribution")
print(" %s" % " ".join(distro))
print(" please submit a patch")
sys.exit(1)
if os.geteuid() != 0:
cmd.insert(0, "sudo")
for flag_str, pkg_names in flag_to_pkgs.items():
flags = flag_str.split("|")
if any(globals()[f"{flag}_ENABLED"] for flag in flags):
cmd += list(set(pkg_names))
from shutil import which
exe = which(cmd[0])
os.execv(exe, cmd)
def install_repo(repo_variant="") -> None:
if not LINUX:
print(f"'install{repo_variant}-repo' subcommand is not supported on {sys.platform!r}")
sys.exit(1)
distro = get_linux_distribution()
setup_cmds: list[list[str]] = []
DEB_VARIANTS = (
"focal", "jammy", "noble", "oracular",
"bullseye", "bookworm", "trixie", "sid",
)
variant = distro[2] # ie: "noble"
if distro[0] in ("Debian", "Ubuntu") or variant in DEB_VARIANTS:
if variant not in DEB_VARIANTS:
raise ValueError(f"Debian / Ubuntu variant {variant} is not supported by this subcommand")
to = "/etc/apt/sources.list.d/"
setup_cmds.append(["wget", "-O", "/usr/share/keyrings/xpra.asc", "https://xpra.org/xpra.asc"])
setup_cmds.append(["chmod", "644", "/usr/share/keyrings/xpra.asc"])
setup_cmds.append(["cp", f"packaging/repos/{variant}/xpra.sources", to])
if repo_variant == "-beta":
setup_cmds.append(["cp", f"packaging/repos/{variant}/xpra-beta.sources", to])
else:
# assume RPM
def add_epel() -> None:
setup_cmds.append(["dnf-3", "config-manager", "--set-enabled", "crb"])
setup_cmds.append(["dnf-3", "install", "epel-release"])
if is_Fedora():
variant = "Fedora"
release = get_status_output(["rpm", "-E", "%fedora"])
assert release[0] == 0, "failed to run `rpm -E %fedora`"
release_name = release[1].strip("\n\r")
setup_cmds.append(["dnf-3", "install", f"https://mirrors.rpmfusion.org/free/fedora/rpmfusion-free-release-{release_name}.noarch.rpm"])
# setup_cmds.append(["dnf", "install", f"https://mirrors.rpmfusion.org/free/fedora/rpmfusion-nonfree-release-{release_name}.noarch.rpm"])
setup_cmds.append(["dnf-3", "config-manager", "--set-enabled", "fedora-cisco-openh264"])
elif is_distribution_variant("RedHat") or is_distribution_variant("AlmaLinux"):
variant = "almalinux"
add_epel()
elif is_distribution_variant("Rocky Linux"):
variant = "rockylinux"
add_epel()
elif is_distribution_variant("Oracle Linux"):
variant = "oraclelinux"
add_epel()
elif is_distribution_variant("CentOS"):
variant = "CentOS-Stream"
add_epel()
else:
raise ValueError(f"unsupported distribution {distro}")
to = "/etc/yum.repos.d/"
setup_cmds.append(["cp", f"packaging/repos/{variant}/xpra.repo", to])
if repo_variant == "-beta":
setup_cmds.append(["cp", f"packaging/repos/{variant}/xpra-beta.repo", to])
for cmd in setup_cmds:
if os.geteuid() != 0:
cmd.insert(0, "sudo")
subprocess.run(cmd)
def show_help() -> None:
setup()
print("Xpra specific build and install switches:")
for x in 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)
if "doc" in sys.argv:
convert_docs("html")
sys.exit(0)
if "pdf-doc" in sys.argv:
convert_docs("pdf")
sys.exit(0)
if "dev-env" in sys.argv:
install_dev_env()
sys.exit(0)
if "install-repo" in sys.argv:
install_repo()
sys.exit(0)
if "install-beta-repo" in sys.argv:
install_repo("-beta")
sys.exit(0)
if len(sys.argv) < 2:
print(f"{sys.argv[0]} arguments are missing!")
print("usage:")
for subcommand in (
"--help",
"clean",
"sdist",
"pkg-info",
"build",
"install",
"doc",
"pdf-doc",
"dev-env",
"install-repo",
"install-beta-repo",
"unittests",
):
print(f"{sys.argv[0]} {subcommand}")
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
if "clean" not in sys.argv and "sdist" not in sys.argv:
def show_switch_info() -> None:
switches_info = {}
for x in SWITCHES:
switches_info[x] = globals()[f"{x}_ENABLED"]
print("build switches:")
for k in SWITCHES:
v = switches_info[k]
print("* %s : %s" % (str(k).ljust(20), {None : "Auto", True : "Yes", False : "No"}.get(v, v)))
show_switch_info()
def check_sane_defaults() -> None:
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")
check_sane_defaults()
def check_cython3() -> None:
try:
import cython
print(f"found Cython version {cython.__version__}")
version = int(cython.__version__.split('.')[0])
except (ValueError, ImportError):
print("WARNING: unable to detect Cython version")
else:
if version < 3:
print("*******************************************")
print("please switch to Cython 3.x")
print(f" version {version} is not supported")
print("*******************************************")
sys.exit(1)
check_cython3()
#*******************************************************************************
# 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:
"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"]
if not qt6_client_ENABLED:
excludes += ["PyQt6"]
# 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: str) -> None:
""" 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: str) -> None:
""" 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: str) -> None:
def add(v):
if v not in modules:
modules.append(v)
do_add_modules(add, *mods)
def do_add_modules(op, *mods: str) -> None:
""" 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: bool, *module_names: str) -> None:
if enabled:
add_packages(*module_names)
else:
remove_packages(*module_names)
def toggle_modules(enabled: bool, *module_names: str) -> None:
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", "xpra.util")
#*******************************************************************************
# Utility methods for building with Cython
def do_add_cython_ext(*args, **kwargs) -> None:
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
add_cython_ext = do_add_cython_ext
def ace(modnames="xpra.x11.bindings.xxx", pkgconfig_names="", optimize=None, **kwargs) -> None:
src = modnames.split(",")
modname = src[0]
if not src[0].endswith(".pyx"):
for ext in ("pyx", "py"):
filename = src[0].replace(".", "/")+"."+ext
if os.path.exists(filename):
src[0] = filename
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, )