-
-
Notifications
You must be signed in to change notification settings - Fork 228
Expand file tree
/
Copy pathsetup.py
More file actions
executable file
·3892 lines (3493 loc) · 156 KB
/
setup.py
File metadata and controls
executable file
·3892 lines (3493 loc) · 156 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
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 Antoine Martin <antoine@xpra.org>
# Copyright (C) 2008 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 struct
import subprocess
from glob import glob
from time import sleep
from collections.abc import Sequence
# required for PEP 517
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
import xpra
assert xpra
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")
try:
from setuptools import setup
from setuptools.command.build import build
from setuptools.command.install import install as install_data
except ImportError:
print("you must install setuptools to run this script")
sys.exit(1)
def check_python_version() -> None:
if sys.version_info < (3, 10):
raise RuntimeError("xpra no longer supports Python versions older than 3.10")
WIN32 = sys.platform.startswith("win")
OSX = sys.platform.startswith("darwin")
LINUX = sys.platform.startswith("linux")
NETBSD = sys.platform.startswith("netbsd")
OPENBSD = sys.platform.startswith("openbsd")
FREEBSD = sys.platform.startswith("freebsd")
POSIX = os.name == "posix"
BITS = struct.calcsize(b"P") * 8
_os_release_file_data = None
_linux_distribution = ("", "", "")
def getuid() -> int:
if POSIX:
return os.getuid()
return 0
def load_binary_file(filename) -> bytes:
if not filename or not os.path.exists(filename):
return b""
try:
with open(filename, "rb") as f:
return f.read()
except OSError:
return b""
def get_status_output(*args, **kwargs) -> "tuple[int, str, str]":
kwargs.update({
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
"universal_newlines": True,
})
try:
p = subprocess.Popen(*args, **kwargs)
except Exception:
return -1, "", ""
stdout, stderr = p.communicate()
return p.returncode, stdout, stderr
def command_string(cmd: Sequence) -> str:
return " ".join(shlex.quote(str(x)) for x in cmd)
def load_os_release_file() -> str:
global _os_release_file_data
if _os_release_file_data is None:
try:
_os_release_file_data = load_binary_file("/etc/os-release").decode() or ""
except (OSError, UnicodeDecodeError):
_os_release_file_data = ""
return _os_release_file_data
def is_distribution_variant(variant="Debian") -> bool:
if not POSIX:
return False
try:
v = load_os_release_file()
return any(line.find(variant) >= 0 for line in v.splitlines() if line.startswith("NAME="))
except Exception:
pass
try:
d = get_linux_distribution()[0]
if d == variant:
return True
if variant == "RedHat" and d.startswith(variant):
return True
except Exception:
pass
return False
def is_Debian() -> bool:
return is_distribution_variant("Debian")
def is_Ubuntu() -> bool:
return is_distribution_variant("Ubuntu")
def is_LinuxMint() -> bool:
return is_distribution_variant("Linux Mint")
def is_DEB() -> bool:
return is_Debian() or is_Ubuntu() or is_LinuxMint()
def is_RPM() -> bool:
return any(is_distribution_variant(x) for x in (
"Fedora", "RedHat", "AlmaLinux", "Rocky Linux", "CentOS", "openSUSE", "Oracle Linux",
))
def is_Arch() -> bool:
if not POSIX:
return False
try:
v = load_os_release_file()
if not v:
return False
os_release = {}
for line in v.splitlines():
if not line or "=" not in line:
continue
k, vstr = line.split("=", 1)
os_release[k] = vstr.strip().strip('"')
distro_id = os_release.get("ID", "").lower()
if distro_id in ("arch", "manjaro"):
return True
id_like = os_release.get("ID_LIKE", "").lower().split()
return any(x in id_like for x in ("arch", "archlinux"))
except Exception:
pass
return is_distribution_variant("Arch") or is_distribution_variant("Manjaro")
def get_linux_distribution() -> "tuple[str, str, str]":
global _linux_distribution
if LINUX and _linux_distribution == ("", "", ""):
r, out, _ = get_status_output(["lsb_release", "-a"])
if r == 0 and out:
d = {}
for line in out.splitlines():
parts = line.rstrip("\n\r").split(":", 1)
if len(parts) == 2:
d[parts[0].lower().replace(" ", "_")] = parts[1].strip()
_linux_distribution = (
d.get("distributor_id", "unknown"),
d.get("release", "unknown"),
d.get("codename", "unknown"),
)
else:
try:
import platform
_linux_distribution = platform.linux_distribution() # pylint: disable=deprecated-method, no-member
except Exception:
_linux_distribution = ("unknown", "unknown", "unknown")
return _linux_distribution
def is_free_threaded() -> bool:
import sysconfig
if sysconfig.get_config_var("Py_GIL_DISABLED") == 1:
return True
if hasattr(sys, "_is_gil_enabled"):
return not sys._is_gil_enabled()
return False
def warn(msg: str) -> None:
print(f"Warning: {msg}")
def error(msg: str) -> None:
print(f"Error: {msg}")
if BITS != 64:
warn(f"{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.update({
"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 not has_pkg_config:
warn("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 = os.environ.get("PKG_CONFIG_PATH", "").split(os.path.pathsep) + [pcp]
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_exists(*names: str) -> bool:
return pkg_config_ok("--exists", *names)
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]
return parse_version(out) >= parse_version(req_version)
def parse_version(version: str) -> "tuple[int, ...]":
parts = []
for vpart in re.split(r"[^0-9]+", version):
if not vpart:
continue
parts.append(int(vpart))
return tuple(parts)
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 = os.environ.get("MSYSTEM_CARCH", "") or 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 = 600
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("INCLUDE_DIRS=%s" % (INCLUDE_DIRS, ))
shadow_ENABLED = DEFAULT
server_ENABLED = DEFAULT
rfb_ENABLED = DEFAULT
quic_ENABLED = DEFAULT
ssh_ENABLED = DEFAULT
ssl_ENABLED = DEFAULT
http_ENABLED = DEFAULT
service_ENABLED = LINUX and server_ENABLED
sd_listen_ENABLED = POSIX and pkg_config_exists("libsystemd")
proxy_ENABLED = DEFAULT
client_ENABLED = DEFAULT
qt6_client_ENABLED = False
pyglet_client_ENABLED = False
tk_client_ENABLED = False
win32_client_ENABLED = DEFAULT and WIN32
scripts_ENABLED = not WIN32
cython_ENABLED = DEFAULT
cython_shared_ENABLED = True
cython_freethreading_ENABLED = is_free_threaded()
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
[os.path.join(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
wayland_client_ENABLED = not WIN32 and not OSX and pkg_config_exists("wayland-client")
wayland_server_ENABLED = not WIN32 and not OSX and pkg_config_exists("wlroots-0.19") and pkg_config_exists("wayland-server")
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
cairo_ENABLED = DEFAULT
ism_ext_ENABLED = DEFAULT and gtk3_ENABLED and data_ENABLED
opengl_ENABLED = DEFAULT and client_ENABLED
vulkan_ENABLED = False # DEFAULT and client_ENABLED and pkg_config_exists("vulkan")
has_pam_headers = has_header_file("security", isdir=True) or pkg_config_exists("pam", "pam_misc")
pam_ENABLED = DEFAULT and (server_ENABLED or proxy_ENABLED) and LINUX and has_pam_headers
peercred_ENABLED = OSX or sys.platform.lower().find("bsd") >= 0
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
mmap_ENABLED = DEFAULT
websockets_ENABLED = DEFAULT
websockets_browser_cookie_ENABLED = DEFAULT
yaml_ENABLED = DEFAULT
codecs_ENABLED = DEFAULT
encoders_ENABLED = codecs_ENABLED
decoders_ENABLED = codecs_ENABLED
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
aom_ENABLED = DEFAULT and pkg_config_version("3.0", "aom")
de265_ENABLED = DEFAULT and pkg_config_version("1.0", "libde265")
de265_decoder_ENABLED = de265_ENABLED
pillow_ENABLED = DEFAULT
pillow_encoder_ENABLED = pillow_ENABLED
pillow_decoder_ENABLED = pillow_ENABLED
dmabuf_ENABLED = DEFAULT and POSIX
argb_ENABLED = DEFAULT
argb_encoder_ENABLED = argb_ENABLED
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")
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
amf_ENABLED = pkg_config_version("1.0", "amf") or has_header_file("AMF/components/VideoEncoderVCE.h")
amf_encoder_ENABLED = amf_ENABLED
vt_ENABLED = OSX
vt_encoder_ENABLED = vt_ENABLED
mf_decoder_ENABLED = DEFAULT and WIN32
mf_encoder_ENABLED = DEFAULT and WIN32
dxgi_ENABLED = DEFAULT and WIN32
vpl_ENABLED = DEFAULT and has_header_file("vpl/mfxvideo.h")
vpl_decoder_ENABLED = vpl_ENABLED
vpl_encoder_ENABLED = vpl_ENABLED
libva_ENABLED = DEFAULT and pkg_config_version("1.18", "libva") and (
(LINUX and pkg_config_exists("libva-drm")) or
(WIN32 and pkg_config_exists("libva-win32"))
)
libva_encoder_ENABLED = libva_ENABLED
libva_decoder_ENABLED = libva_ENABLED
remote_encoder_ENABLED = DEFAULT
webcam_ENABLED = DEFAULT
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
pytorch_ENABLED = DEFAULT
nvidia_ENABLED = DEFAULT and not OSX and BITS==64 and not RISCV
nvjpeg_encoder_ENABLED = nvidia_ENABLED and pkg_config_exists("nvjpeg")
nvjpeg_decoder_ENABLED = nvidia_ENABLED and pkg_config_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_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_exists("libyuv")
gstreamer_ENABLED = DEFAULT
gstreamer_audio_ENABLED = gstreamer_ENABLED
gstreamer_video_ENABLED = gstreamer_ENABLED and not OSX
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
wireshark_ENABLED = DEFAULT and POSIX and not OSX
# allow some of these flags to be modified on the command line:
ENCODER_SWITCHES = [
"enc_x264", "openh264_encoder", "nvenc", "nvjpeg_encoder",
"vpx_encoder", "webp_encoder", "pillow_encoder",
"amf_encoder",
"mf_encoder",
"vt_encoder",
"vpl_encoder",
"libva_encoder",
"jpeg_encoder", "avif_encoder",
"argb_encoder",
"remote_encoder",
]
DECODER_SWITCHES = [
"openh264_decoder",
"nvdec", "nvjpeg_decoder",
"mf_decoder",
"vpl_decoder",
"libva_decoder",
"de265_decoder",
"vpx_decoder", "webp_decoder", "pillow_decoder",
"jpeg_decoder", "avif_decoder",
]
CODEC_SWITCHES = ENCODER_SWITCHES + DECODER_SWITCHES + [
"cuda_kernels", "cuda_rebuild",
"nvidia", "nvfbc",
"openh264",
"vpx", "webp",
"pillow",
"avif", "argb",
"de265",
"v4l2", "evdi", "drm",
"csc_cython", "csc_libyuv", "pytorch",
"gstreamer", "gstreamer_audio", "gstreamer_video",
"dmabuf",
]
# 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"),
"amf": ("amf_encoder", ),
"vt": ("vt_encoder", ),
"webp": ("webp_encoder", "webp_decoder"),
"avif": ("avif_encoder", "avif_decoder"),
"de265": ("de265_decoder", ),
"openh264": ("openh264", "openh264_decoder", "openh264_encoder"),
"vpl": ("vpl_decoder", "vpl_encoder"),
"libva": ("libva_encoder", "libva_decoder"),
"nvidia": ("nvidia", "nvenc", "nvdec", "nvfbc", "nvjpeg_encoder", "nvjpeg_decoder", "cuda_kernels"),
"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",
"peercred",
),
}
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", "cython_shared", "cython_freethreading",
"modules", "data",
"brotli", "cityhash", "qrencode",
"vsock", "netdev", "proc", "mdns", "lz4", "mmap",
"clipboard",
"scripts",
"server", "client", "dbus", "x11", "xinput", "uinput", "sd_listen",
"gtk_x11", "service",
"gtk3", "cairo", "example",
"wayland_client", "wayland_server",
"qt6_client", "pyglet_client", "tk_client", "win32_client",
"ism_ext",
"pam", "xdg_open", "peercred",
"audio", "opengl", "printing", "webcam", "notifications", "keyboard",
"rebuild",
"docs", "pandoc_lua",
"annotate", "warn", "strict", "Os",
"shadow", "proxy", "rfb", "quic", "http", "ssh", "ssl",
"debug", "PIC",
"Xdummy", "Xdummy_wrapper", "verbose", "tests", "bundle_tests",
"win32_tools", "dxgi", "websockets_browser_cookie",
"yaml",
"wireshark",
]
SWITCHES = list(sorted(set(SWITCHES)))
install = ""
rpath = ""
ssl_cert = ""
ssl_key = ""
share_xpra = os.path.join("share", "xpra")
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}"
yes_str = f"--{x}"
no_str = f"--no-{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, []))
for with_value_str in (with_str, yes_str):
if arg.startswith(with_value_str+"="):
for var in var_names:
globals()[f"{var}_ENABLED"] = arg[len(with_value_str)+1:]
matched = True
break
if arg in (with_str, yes_str):
for var in var_names:
globals()[f"{var}_ENABLED"] = True
matched = True
break
if arg in (without_str, no_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 not install and WIN32:
MINGW_PREFIX = os.environ.get("MINGW_PREFIX", "")
install = MINGW_PREFIX or sys.prefix or "dist"
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") or ""
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 du(path: str) -> int:
if os.path.isfile(path):
return os.path.getsize(path)
return sum(os.path.getsize(f) for f in glob(f"{path}/**", recursive=True) if os.path.isfile(f))
def build_package() -> int:
check_python_version()
if not LINUX:
raise RuntimeError("packaging is not implemented here yet, use platform specific scripts instead")
if not (is_RPM() or is_DEB() or is_Arch()):
distro = get_linux_distribution()
print("'package' subcommand is only supported on DEB, RPM, and Arch based distributions")
print(" detected distribution: %s" % " ".join(distro))
print(" use 'python3 ./setup.py sdist' to generate a source archive")
print(" or build packages in a DEB/RPM/Arch environment (VM, container, chroot)")
return 1
if not is_Arch():
print("* installing beta repository tools and libraries")
install_repo("-beta")
print("* installing dev-env")
from subprocess import run
cmd = install_dev_env_command()
if not cmd:
return 1
if os.geteuid() != 0 and cmd[0] in ("apt", "dnf", "pacman"):
if cmd[0] == "pacman":
print(" (pacman requires root privileges to install packages; using sudo)")
print(" (the actual package build step will run as your regular user)")
cmd.insert(0, "sudo")
if run(cmd).returncode != 0:
raise RuntimeError("failed to install dev-env using %r" % command_string(cmd))
print("* creating source archive")
cmd = ["python3", "./setup.py", "sdist", "--formats=xztar"]
if run(cmd).returncode != 0:
raise RuntimeError("failed to install create sdist source using %r" % command_string(cmd))
src_xz = f"./dist/xpra-{XPRA_VERSION}.tar.xz"
if not os.path.exists(src_xz):
raise RuntimeError(f"cannot find {src_xz!r}")
size = du(src_xz)
print(f"{src_xz}: {size}B")
if is_Arch():
if os.geteuid() == 0:
raise RuntimeError("Arch packaging must be run as a regular user (makepkg refuses to run as root)")
makepkg = shutil.which("makepkg")
if not makepkg:
raise RuntimeError("cannot find `makepkg` (install the `pacman`/`pacman-makepkg` tooling)")
arch_dir = os.path.join("build", f"archpkg-{XPRA_VERSION}")
os.makedirs(arch_dir, mode=0o755, exist_ok=True)
tar_name = f"xpra-{XPRA_VERSION}.tar.xz"
shutil.copy(src_xz, os.path.join(arch_dir, tar_name))
pkg_arch = os.uname().machine
with open(os.path.join(arch_dir, "PKGBUILD"), "w", encoding="utf-8") as f:
template_path = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
"packaging",
"arch",
"PKGBUILD.in",
)
with open(template_path, encoding="utf-8") as tf:
template = tf.read()
f.write(template.format(pkgver=XPRA_VERSION, tar_name=tar_name, pkg_arch=pkg_arch))
env = os.environ.copy()
env.setdefault("MAKEPKG_CONF", "/etc/makepkg.conf")
cmd = [makepkg, "-f", "--nosign"]
if run(cmd, cwd=arch_dir, env=env).returncode != 0:
raise RuntimeError("failed to generate Arch package using %r" % command_string(cmd))
pkgs = [x for x in os.listdir(arch_dir) if x.endswith((".pkg.tar.zst", ".pkg.tar.xz"))]
if not pkgs:
raise RuntimeError(f"cannot find generated Arch package in {arch_dir!r}")
for pkg in pkgs:
shutil.copy(os.path.join(arch_dir, pkg), "./dist/")
return 0
if is_RPM():
rpmbuild_dir = os.path.expanduser("~/rpmbuild")
if not os.path.exists(rpmbuild_dir):
os.mkdir(rpmbuild_dir)
sources_dir = os.path.join(rpmbuild_dir, "SOURCES")
if not os.path.exists(sources_dir):
os.mkdir(sources_dir)
shutil.copy(src_xz, sources_dir)
cmd = ["rpmbuild", "-ba", "./packaging/rpm/xpra.spec"]
if run(cmd).returncode != 0:
raise RuntimeError("failed to generate RPM package with %r" % command_string(cmd))
return 0
if is_DEB():
deb_src = f"../xpra-{XPRA_VERSION}.orig.tar.xz"
shutil.copy(src_xz, deb_src)
cmd = ["debuild", "-us", "-uc", "-b"]
if run(cmd).returncode != 0:
raise RuntimeError("failed to generate RPM package with %r" % command_string(cmd))
return 0
print("sorry, your distribution is not supported by this subcommand")
return 1
def get_os_release() -> "dict[str, str]":
info = {}
for line in load_os_release_file().splitlines():
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
info[key.strip()] = value.strip().strip('"')
return info
def get_rpm_distro_arch() -> "tuple[str, str, str]":
# work out the `(distro, variant, arch)` tuple used to locate
# a build manifest in `packaging/rpm/distros/*.list`,
# ie: ("centos", "stream9", "arm64") -> "centos-stream9-arm64.list"
info = get_os_release()
distro_id = info.get("ID", "").lower()
# map the os-release `ID` to the name used by the manifests:
distro = {
"centos": "centos",
"fedora": "fedora",
"almalinux": "almalinux",
"rocky": "rockylinux",
"ol": "oraclelinux",
"rhel": "almalinux", # build RHEL using the AlmaLinux manifests
}.get(distro_id, distro_id)
# major version only, ie: "9.5" -> "9":
version = info.get("VERSION_ID", "").split(".")[0]
if distro == "centos" and "stream" in info.get("NAME", "").lower():
variant = f"stream{version}"
else:
variant = version
# map the machine architecture to the manifest naming:
arch = {
"aarch64": "arm64",
}.get(os.uname().machine, os.uname().machine)
return distro, variant, arch
def find_rpm_package_list() -> str:
distro, variant, arch = get_rpm_distro_arch()
print(f"* identifying package list for distro={distro!r}, variant={variant!r}, arch={arch!r}")
distros_dir = os.path.join("packaging", "rpm", "distros")
# from the most specific manifest name to the least specific:
candidates = []
if distro and variant and arch:
candidates.append(f"{distro}-{variant}-{arch}")
if distro and variant:
candidates.append(f"{distro}-{variant}")
if distro and arch:
candidates.append(f"{distro}-{arch}")
if arch:
candidates.append(arch)
if distro:
candidates.append(distro)
candidates.append("default")
for name in candidates:
path = os.path.join(distros_dir, f"{name}.list")
if os.path.exists(path):
print(f"* using package list {path!r}")
return path
print(f" ({path!r} not found)")
tried = ", ".join(f"{name}.list" for name in candidates)
raise RuntimeError(f"no matching package list found in {distros_dir!r}, tried: {tried}")
def run_to_logfile(cmd: "list[str]", log_file: str, env: "dict[str, str]", append=False) -> bool:
from subprocess import run
with open(log_file, "ab" if append else "wb") as f:
f.write(("$ %s\n" % command_string(cmd)).encode("utf-8"))
f.flush()
return run(cmd, stdout=f, stderr=f, env=env).returncode == 0
def rpmbuild_repo_url(rpms_dir: str) -> str:
return "file://" + os.path.abspath(os.path.expanduser(rpms_dir))
def update_rpmbuild_repo(rpms_dir: str, log_file: str, env: "dict[str, str]", append=True) -> bool:
createrepo = shutil.which("createrepo") or shutil.which("createrepo_c")
if not createrepo:
raise RuntimeError("cannot find `createrepo` or `createrepo_c` for updating the local RPM repository")
os.makedirs(rpms_dir, exist_ok=True)
print(f" - updating RPM repository metadata in {rpms_dir!r}")
return run_to_logfile([createrepo, rpms_dir], log_file, env, append=append)
def show_logfile(log_file: str) -> None:
try:
with open(log_file, encoding="utf-8", errors="replace") as f:
sys.stderr.write(f.read())
except OSError:
pass
def get_rpm_macro(macro: str) -> str:
r, out, _ = get_status_output(["rpm", "--eval", macro])
return out.strip() if r == 0 else ""
def get_spec_filed_packages(spec: str, env: "dict[str, str]") -> "set[str] | None":
# the names of the (sub)packages that have a `%files` section in the
# macro-expanded spec, and which `rpmbuild` will therefore actually produce.
# a package declared with `%package` (or the main `Name:`) but *without* a
# `%files` section is never built, even though `rpmspec --rpms` still lists it.
# returns `None` if this cannot be determined (so callers do not filter):
r, out, _ = get_status_output(["rpmspec", "-q", "--srpm", "--qf", "%{name}", spec], env=env)
if r != 0:
return None
mainname = out.strip()
r, expanded, _ = get_status_output(["rpmspec", "-P", spec], env=env)
if r != 0:
return None
names = set()
for line in expanded.splitlines():
if not line.startswith("%files"):
continue
# `%files [-n NAME] [-f FILELIST] [SUFFIX]`:
# `-n NAME` gives an absolute name, a bare `SUFFIX` means `%{name}-SUFFIX`,
# and no argument at all refers to the main package (`%{name}`):
args = shlex.split(line[len("%files"):])
name: str = ""
suffix = ""
i = 0
while i < len(args):
arg = args[i]
if arg == "-n":
i += 1
name = args[i] if i < len(args) else name
elif arg == "-f":