-
-
Notifications
You must be signed in to change notification settings - Fork 982
/
setup.py
executable file
·2207 lines (1999 loc) · 83.7 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 python
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import argparse
import glob
import json
import os
import platform
import re
import runpy
import shlex
import shutil
import struct
import subprocess
import sys
import sysconfig
import tempfile
import textwrap
import time
from contextlib import suppress
from functools import lru_cache, partial
from pathlib import Path
from typing import Callable, Dict, FrozenSet, Iterable, Iterator, List, Optional, Sequence, Set, Tuple, Union, cast
from glfw import glfw
from glfw.glfw import ISA, BinaryArch, Command, CompileKey, CompilerType
src_base = os.path.dirname(os.path.abspath(__file__))
def check_version_info() -> None:
with open(os.path.join(src_base, 'pyproject.toml')) as f:
raw = f.read()
m = re.search(r'''^requires-python\s*=\s*['"](.+?)['"]''', raw, flags=re.MULTILINE)
assert m is not None
minver = m.group(1)
match = re.match(r'(>=?)(\d+)\.(\d+)', minver)
assert match is not None
q = int(match.group(2)), int(match.group(3))
if match.group(1) == '>=':
is_ok = sys.version_info >= q
else:
is_ok = sys.version_info > q
if not is_ok:
exit(f'calibre requires Python {minver}. Current Python version: {".".join(map(str, sys.version_info[:3]))}')
check_version_info()
verbose = False
build_dir = 'build'
constants = os.path.join('kitty', 'constants.py')
with open(constants, 'rb') as f:
constants = f.read().decode('utf-8')
appname = re.search(r"^appname: str = '([^']+)'", constants, re.MULTILINE).group(1) # type: ignore
version = tuple(
map(
int,
re.search( # type: ignore
r"^version: Version = Version\((\d+), (\d+), (\d+)\)", constants, re.MULTILINE
).group(1, 2, 3)
)
)
_plat = sys.platform.lower()
is_macos = 'darwin' in _plat
is_openbsd = 'openbsd' in _plat
is_freebsd = 'freebsd' in _plat
is_netbsd = 'netbsd' in _plat
is_dragonflybsd = 'dragonfly' in _plat
is_bsd = is_freebsd or is_netbsd or is_dragonflybsd or is_openbsd
is_arm = platform.processor() == 'arm' or platform.machine() in ('arm64', 'aarch64')
Env = glfw.Env
env = Env()
PKGCONFIG = os.environ.get('PKGCONFIG_EXE', 'pkg-config')
link_targets: List[str] = []
macos_universal_arches = ('arm64', 'x86_64') if is_arm else ('x86_64', 'arm64')
def LinkKey(output: str) -> CompileKey:
return CompileKey('', output)
class CompilationDatabase:
def __init__(self, incremental: bool = False):
self.incremental = incremental
self.compile_commands: List[Command] = []
self.link_commands: List[Command] = []
self.post_link_commands: List[Command] = []
def add_command(
self,
desc: str,
cmd: List[str],
is_newer_func: Callable[[], bool],
key: Optional[CompileKey] = None,
on_success: Optional[Callable[[], None]] = None,
keyfile: Optional[str] = None,
is_post_link: bool = False,
) -> None:
def no_op() -> None:
pass
if is_post_link:
queue = self.post_link_commands
else:
queue = self.link_commands if keyfile is None else self.compile_commands
queue.append(Command(desc, cmd, is_newer_func, on_success or no_op, key, keyfile))
def build_all(self) -> None:
def sort_key(compile_cmd: Command) -> int:
if compile_cmd.keyfile:
return os.path.getsize(compile_cmd.keyfile)
return 0
items = []
for compile_cmd in self.compile_commands:
if not self.incremental or self.cmd_changed(compile_cmd) or compile_cmd.is_newer_func():
items.append(compile_cmd)
items.sort(key=sort_key, reverse=True)
parallel_run(items)
items = []
for compile_cmd in self.link_commands:
if not self.incremental or compile_cmd.is_newer_func():
items.append(compile_cmd)
parallel_run(items)
items = []
for compile_cmd in self.post_link_commands:
if not self.incremental or compile_cmd.is_newer_func():
items.append(compile_cmd)
parallel_run(items)
def cmd_changed(self, compile_cmd: Command) -> bool:
key, cmd = compile_cmd.key, compile_cmd.cmd
return bool(self.db.get(key) != cmd)
def __enter__(self) -> 'CompilationDatabase':
self.all_keys: Set[CompileKey] = set()
self.dbpath = os.path.abspath(os.path.join(build_dir, 'compile_commands.json'))
self.linkdbpath = os.path.join(os.path.dirname(self.dbpath), 'link_commands.json')
try:
with open(self.dbpath) as f:
compilation_database = json.load(f)
except FileNotFoundError:
compilation_database = []
try:
with open(self.linkdbpath) as f:
link_database = json.load(f)
except FileNotFoundError:
link_database = []
compilation_database = {
CompileKey(k['file'], k['output']): k['arguments'] for k in compilation_database
}
self.db = compilation_database
self.linkdb = {tuple(k['output']): k['arguments'] for k in link_database}
return self
def __exit__(self, *a: object) -> None:
cdb = self.db
for key in set(cdb) - self.all_keys:
del cdb[key]
compilation_database = [
{'file': c.key.src, 'arguments': c.cmd, 'directory': src_base, 'output': c.key.dest} for c in self.compile_commands if c.key is not None
]
with suppress(FileNotFoundError):
with open(self.dbpath, 'w') as f:
json.dump(compilation_database, f, indent=2, sort_keys=True)
with open(self.linkdbpath, 'w') as f:
json.dump([{'output': c.key, 'arguments': c.cmd, 'directory': src_base} for c in self.link_commands], f, indent=2, sort_keys=True)
class Options:
action: str = 'build'
debug: bool = False
verbose: int = 0
sanitize: bool = False
prefix: str = './linux-package'
dir_for_static_binaries: str = 'build/static'
skip_code_generation: bool = False
skip_building_kitten: bool = False
clean_for_cross_compile: bool = False
python_compiler_flags: str = ''
python_linker_flags: str = ''
incremental: bool = True
build_dsym: bool = False
ignore_compiler_warnings: bool = False
profile: bool = False
libdir_name: str = 'lib'
extra_logging: List[str] = []
extra_include_dirs: List[str] = []
extra_library_dirs: List[str] = []
link_time_optimization: bool = 'KITTY_NO_LTO' not in os.environ
update_check_interval: float = 24.0
shell_integration: str = 'enabled'
egl_library: Optional[str] = os.getenv('KITTY_EGL_LIBRARY')
startup_notification_library: Optional[str] = os.getenv('KITTY_STARTUP_NOTIFICATION_LIBRARY')
canberra_library: Optional[str] = os.getenv('KITTY_CANBERRA_LIBRARY')
systemd_library: Optional[str] = os.getenv('KITTY_SYSTEMD_LIBRARY')
fontconfig_library: Optional[str] = os.getenv('KITTY_FONTCONFIG_LIBRARY')
building_arch: str = ''
# Extras
compilation_database: CompilationDatabase = CompilationDatabase()
vcs_rev: str = ''
def emphasis(text: str) -> str:
if sys.stdout.isatty():
text = f'\033[32m{text}\033[39m'
return text
def error(text: str) -> str:
if sys.stdout.isatty():
text = f'\033[91m{text}\033[39m'
return text
def pkg_config(pkg: str, *args: str, extra_pc_dir: str = '', fatal: bool = True) -> List[str]:
env = os.environ.copy()
if extra_pc_dir:
pp = env.get('PKG_CONFIG_PATH', '')
if pp:
pp += os.pathsep
env['PKG_CONFIG_PATH'] = f'{pp}{extra_pc_dir}'
cmd = [PKGCONFIG, pkg] + list(args)
try:
return list(
filter(
None,
shlex.split(
subprocess.check_output(cmd, env=env, stderr=None if fatal else subprocess.DEVNULL).decode('utf-8')
)
)
)
except subprocess.CalledProcessError:
if fatal:
raise SystemExit(f'The package {error(pkg)} was not found on your system')
raise
def pkg_version(package: str) -> Tuple[int, int]:
ver = subprocess.check_output([
PKGCONFIG, package, '--modversion']).decode('utf-8').strip()
m = re.match(r'(\d+).(\d+)', ver)
if m is not None:
qmajor, qminor = map(int, m.groups())
return qmajor, qminor
return -1, -1
def libcrypto_flags() -> Tuple[List[str], List[str]]:
# Apple use their special snowflake TLS libraries and additionally
# have an ancient broken system OpenSSL, so we need to check for one
# installed by all the various macOS package managers.
extra_pc_dir = ''
try:
cflags = pkg_config('libcrypto', '--cflags-only-I', fatal=False)
except subprocess.CalledProcessError:
if is_macos:
import ssl
v = ssl.OPENSSL_VERSION_INFO
pats = f'{v[0]}.{v[1]}', f'{v[0]}'
for pat in pats:
q = f'opt/openssl@{pat}/lib/pkgconfig'
openssl_dirs = glob.glob(f'/opt/homebrew/{q}') + glob.glob(f'/usr/local/{q}')
if openssl_dirs:
break
else:
raise SystemExit(f'Failed to find OpenSSL version {v[0]}.{v[1]} on your system')
extra_pc_dir = os.pathsep.join(openssl_dirs)
cflags = pkg_config('libcrypto', '--cflags-only-I', extra_pc_dir=extra_pc_dir)
ldflags = pkg_config('libcrypto', '--libs', extra_pc_dir=extra_pc_dir)
# Workaround bug in homebrew openssl package. This bug appears in CI only
if is_macos and ldflags and 'homebrew/Cellar' in ldflags[0] and not ldflags[0].endswith('/lib'):
ldflags.insert(0, ldflags[0] + '/lib')
return cflags, ldflags
def at_least_version(package: str, major: int, minor: int = 0) -> None:
q = f'{major}.{minor}'
if subprocess.run([PKGCONFIG, package, f'--atleast-version={q}']
).returncode != 0:
qmajor = qminor = 0
try:
ver = subprocess.check_output([PKGCONFIG, package, '--modversion']
).decode('utf-8').strip()
m = re.match(r'(\d+).(\d+)', ver)
if m is not None:
qmajor, qminor = map(int, m.groups())
except Exception:
ver = 'not found'
if qmajor < major or (qmajor == major and qminor < minor):
raise SystemExit(f'{error(package)} >= {major}.{minor} is required, found version: {ver}')
def cc_version() -> Tuple[List[str], Tuple[int, int]]:
if 'CC' in os.environ:
q = os.environ['CC']
else:
if is_macos:
q = 'clang'
else:
if shutil.which('gcc'):
q = 'gcc'
elif shutil.which('clang'):
q = 'clang'
else:
q = 'cc'
cc = shlex.split(q)
raw = subprocess.check_output(cc + ['-dumpversion']).decode('utf-8')
ver_ = raw.strip().split('.')[:2]
try:
if len(ver_) == 1:
ver = int(ver_[0]), 0
else:
ver = int(ver_[0]), int(ver_[1])
except Exception:
ver = (0, 0)
return cc, ver
def get_python_include_paths() -> List[str]:
ans = []
for name in sysconfig.get_path_names():
if 'include' in name:
ans.append(name)
def gp(x: str) -> Optional[str]:
return sysconfig.get_path(x)
return sorted(frozenset(filter(None, map(gp, sorted(ans)))))
def get_python_flags(args: Options, cflags: List[str], for_main_executable: bool = False) -> List[str]:
if args.python_compiler_flags:
cflags.extend(shlex.split(args.python_compiler_flags))
else:
cflags.extend(f'-I{x}' for x in get_python_include_paths())
if args.python_linker_flags:
return shlex.split(args.python_linker_flags)
libs: List[str] = []
libs += (sysconfig.get_config_var('LIBS') or '').split()
libs += (sysconfig.get_config_var('SYSLIBS') or '').split()
fw = sysconfig.get_config_var('PYTHONFRAMEWORK')
if fw:
for var in 'data include stdlib'.split():
val = sysconfig.get_path(var)
if val and f'/{fw}.framework' in val:
fdir = val[:val.index(f'/{fw}.framework')]
if os.path.isdir(
os.path.join(fdir, f'{fw}.framework')
):
framework_dir = fdir
break
else:
raise SystemExit('Failed to find Python framework')
ldlib = sysconfig.get_config_var('LDLIBRARY')
if ldlib:
libs.append(os.path.join(framework_dir, ldlib))
else:
ldlib = sysconfig.get_config_var('LIBDIR')
if ldlib:
libs += [f'-L{ldlib}']
ldlib = sysconfig.get_config_var('VERSION')
if ldlib:
libs += [f'-lpython{ldlib}{sys.abiflags}']
lval = sysconfig.get_config_var('LINKFORSHARED') or ''
if not for_main_executable:
# Python sets the stack size on macOS which is not allowed unless
# compiling an executable https://github.com/kovidgoyal/kitty/issues/289
lval = re.sub(r'-Wl,-stack_size,\d+', '', lval)
libs += list(filter(None, lval.split()))
return libs
def get_sanitize_args(cc: List[str], ccver: Tuple[int, int]) -> List[str]:
return ['-fsanitize=address,undefined', '-fno-omit-frame-pointer']
def get_binary_arch(path: str) -> BinaryArch:
with open(path, 'rb') as f:
sig = f.read(64)
if sig.startswith(b'\x7fELF'): # ELF
bits = {1: 32, 2: 64}[sig[4]]
endian = {1: '<', 2: '>'}[sig[5]]
machine, = struct.unpack_from(endian + 'H', sig, 0x12)
isa = {i.value:i for i in ISA}.get(machine, ISA.Other)
elif sig[:4] in (b'\xcf\xfa\xed\xfe', b'\xce\xfa\xed\xfe'): # Mach-O
s, cpu_type, = struct.unpack_from('<II', sig, 0)
bits = {0xfeedface: 32, 0xfeedfacf: 64}[s]
cpu_type &= 0xff
isa = {0x7: ISA.AMD64, 0xc: ISA.ARM64}[cpu_type]
else:
raise SystemExit(f'Unknown binary format with signature: {sig[:4]!r}')
return BinaryArch(bits=bits, isa=isa)
def test_compile(
cc: List[str], *cflags: str,
src: str = '',
source_ext: str = 'c',
link_also: bool = True,
show_stderr: bool = False,
libraries: Iterable[str] = (),
ldflags: Iterable[str] = (),
get_output_arch: bool = False,
) -> Union[bool, BinaryArch]:
src = src or 'int main(void) { return 0; }'
with tempfile.TemporaryDirectory(prefix='kitty-test-compile-') as tdir:
with open(os.path.join(tdir, f'source.{source_ext}'), 'w', encoding='utf-8') as srcf:
print(src, file=srcf)
output = os.path.join(tdir, 'source.output')
ret = subprocess.Popen(
cc + ['-Werror=implicit-function-declaration'] + list(cflags) + ([] if link_also else ['-c']) +
['-o', output, srcf.name] +
[f'-l{x}' for x in libraries] + list(ldflags),
stdout=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
stderr=None if show_stderr else subprocess.DEVNULL
).wait()
if get_output_arch:
if ret != 0:
raise SystemExit(f'Failed to determine target architecture compiling test program failed with exit code: {ret}')
return get_binary_arch(output)
return ret == 0
def first_successful_compile(cc: List[str], *cflags: str, src: str = '', source_ext: str = 'c') -> str:
for x in cflags:
if test_compile(cc, *shlex.split(x), src=src, source_ext=source_ext):
return x
return ''
def set_arches(flags: List[str], *arches: str) -> None:
while True:
try:
idx = flags.index('-arch')
except ValueError:
break
del flags[idx]
del flags[idx]
for arch in arches:
flags.extend(('-arch', arch))
def init_env(
debug: bool = False,
sanitize: bool = False,
native_optimizations: bool = True,
link_time_optimization: bool = True,
profile: bool = False,
egl_library: Optional[str] = None,
startup_notification_library: Optional[str] = None,
canberra_library: Optional[str] = None,
systemd_library: Optional[str] = None,
fontconfig_library: Optional[str] = None,
extra_logging: Iterable[str] = (),
extra_include_dirs: Iterable[str] = (),
ignore_compiler_warnings: bool = False,
building_arch: str = '',
extra_library_dirs: Iterable[str] = (),
verbose: bool = True,
vcs_rev: str = '',
) -> Env:
native_optimizations = native_optimizations and not sanitize
cc, ccver = cc_version()
if verbose:
print('CC:', cc, ccver)
stack_protector = first_successful_compile(cc, '-fstack-protector-strong', '-fstack-protector')
missing_braces = ''
if ccver < (5, 2):
missing_braces = '-Wno-missing-braces'
df = '-g3'
float_conversion = ''
if ccver >= (5, 0):
df += ' -Og'
float_conversion = '-Wfloat-conversion'
fortify_source = '' if sanitize and is_macos else '-D_FORTIFY_SOURCE=2'
optimize = df if debug or sanitize else '-O3'
sanitize_args = get_sanitize_args(cc, ccver) if sanitize else []
cppflags_ = os.environ.get(
'OVERRIDE_CPPFLAGS', '-D{}DEBUG'.format('' if debug else 'N'),
)
cppflags = shlex.split(cppflags_)
for el in extra_logging:
cppflags.append('-DDEBUG_{}'.format(el.upper().replace('-', '_')))
has_copy_file_range = test_compile(cc, src='#define _GNU_SOURCE 1\n#include <unistd.h>\nint main() { copy_file_range(1, NULL, 2, NULL, 0, 0); return 0; }')
werror = '' if ignore_compiler_warnings else '-pedantic-errors -Werror'
std = '' if is_openbsd else '-std=c11'
sanitize_flag = ' '.join(sanitize_args)
env_cflags = shlex.split(os.environ.get('CFLAGS', ''))
env_cppflags = shlex.split(os.environ.get('CPPFLAGS', ''))
env_ldflags = shlex.split(os.environ.get('LDFLAGS', ''))
cflags_ = os.environ.get(
'OVERRIDE_CFLAGS', (
f'-Wextra {float_conversion} -Wno-missing-field-initializers -Wall -Wstrict-prototypes {std}'
f' {werror} {optimize} {sanitize_flag} -fwrapv {stack_protector} {missing_braces}'
f' -pipe -fvisibility=hidden -fno-plt'
)
)
cflags = shlex.split(cflags_) + shlex.split(
sysconfig.get_config_var('CCSHARED') or ''
)
ldflags_ = os.environ.get(
'OVERRIDE_LDFLAGS',
'-Wall ' + ' '.join(sanitize_args) + ('' if debug else ' -O3')
)
ldflags = shlex.split(ldflags_)
ldflags.append('-shared')
cppflags += env_cppflags
cflags += env_cflags
if fortify_source:
for x in cflags:
if '_FORTIFY_SOURCE' in x:
break
else:
cflags.append(fortify_source)
ldflags += env_ldflags
if not debug and not sanitize and not is_openbsd and link_time_optimization:
# See https://github.com/google/sanitizers/issues/647
cflags.append('-flto')
ldflags.append('-flto')
if debug:
cflags.append('-DKITTY_DEBUG_BUILD')
if profile:
cppflags.append('-DWITH_PROFILER')
cflags.append('-g3')
ldflags.append('-lprofiler')
if debug or profile:
cflags.append('-fno-omit-frame-pointer')
library_paths: Dict[str, List[str]] = {}
def add_lpath(which: str, name: str, val: Optional[str]) -> None:
if val:
if '"' in val:
raise SystemExit(f'Cannot have quotes in library paths: {val}')
library_paths.setdefault(which, []).append(f'{name}="{val}"')
add_lpath('glfw/egl_context.c', '_GLFW_EGL_LIBRARY', egl_library)
add_lpath('kitty/desktop.c', '_KITTY_STARTUP_NOTIFICATION_LIBRARY', startup_notification_library)
add_lpath('kitty/desktop.c', '_KITTY_CANBERRA_LIBRARY', canberra_library)
add_lpath('kitty/systemd.c', '_KITTY_SYSTEMD_LIBRARY', systemd_library)
add_lpath('kitty/fontconfig.c', '_KITTY_FONTCONFIG_LIBRARY', fontconfig_library)
for path in extra_include_dirs:
cflags.append(f'-I{path}')
ldpaths = []
for path in extra_library_dirs:
ldpaths.append(f'-L{path}')
if os.environ.get("DEVELOP_ROOT"):
cflags.insert(0, f'-I{os.environ["DEVELOP_ROOT"]}/include')
ldpaths.insert(0, f'-L{os.environ["DEVELOP_ROOT"]}/lib')
if building_arch:
set_arches(cflags, building_arch)
set_arches(ldflags, building_arch)
ba = test_compile(cc, *(cppflags + cflags), ldflags=ldflags, get_output_arch=True)
assert isinstance(ba, BinaryArch)
if ba.isa not in (ISA.AMD64, ISA.X86, ISA.ARM64):
cppflags.append('-DKITTY_NO_SIMD')
control_flow_protection = ''
if ba.isa == ISA.AMD64:
control_flow_protection = '-fcf-protection=full' if ccver >= (9, 0) else ''
elif ba.isa == ISA.ARM64:
# Using -mbranch-protection=standard causes crashes on Linux ARM, reported
# in https://github.com/kovidgoyal/kitty/issues/6845#issuecomment-1835886938
if is_macos:
control_flow_protection = '-mbranch-protection=standard'
if control_flow_protection:
cflags.append(control_flow_protection)
if native_optimizations and ba.isa in (ISA.AMD64, ISA.X86):
cflags.extend('-march=native -mtune=native'.split())
ans = Env(
cc, cppflags, cflags, ldflags, library_paths, binary_arch=ba, native_optimizations=native_optimizations,
ccver=ccver, ldpaths=ldpaths, vcs_rev=vcs_rev,
)
ans.has_copy_file_range = bool(has_copy_file_range)
if verbose:
print(ans.cc_version_string.strip())
print('Detected:', ans.compiler_type)
return ans
def kitty_env(args: Options) -> Env:
ans = env.copy()
cflags = ans.cflags
cflags.append('-pthread')
cppflags = ans.cppflags
# We add 4000 to the primary version because vim turns on SGR mouse mode
# automatically if this version is high enough
ans.primary_version = version[0] + 4000
ans.secondary_version = version[1]
ans.xt_version = '.'.join(map(str, version))
at_least_version('harfbuzz', 1, 5)
cflags.extend(pkg_config('libpng', '--cflags-only-I'))
cflags.extend(pkg_config('lcms2', '--cflags-only-I'))
# simde doesnt come with pkg-config files but some Linux distros add
# them and on macOS when building with homebrew it is required
with suppress(SystemExit, subprocess.CalledProcessError):
cflags.extend(pkg_config('simde', '--cflags-only-I', fatal=False))
libcrypto_cflags, libcrypto_ldflags = libcrypto_flags()
cflags.extend(libcrypto_cflags)
if is_macos:
platform_libs = [
'-framework', 'Carbon', '-framework', 'CoreText', '-framework', 'CoreGraphics',
'-framework', 'AudioToolbox',
]
test_program_src = '''#include <UserNotifications/UserNotifications.h>
int main(void) { return 0; }\n'''
user_notifications_framework = first_successful_compile(
ans.cc, '-framework UserNotifications', src=test_program_src, source_ext='m')
if user_notifications_framework:
platform_libs.extend(shlex.split(user_notifications_framework))
else:
raise SystemExit('UserNotifications framework missing')
# Apple deprecated OpenGL in Mojave (10.14) silence the endless
# warnings about it
cppflags.append('-DGL_SILENCE_DEPRECATION')
else:
cflags.extend(pkg_config('fontconfig', '--cflags-only-I'))
platform_libs = []
cflags.extend(pkg_config('harfbuzz', '--cflags-only-I'))
platform_libs.extend(pkg_config('harfbuzz', '--libs'))
pylib = get_python_flags(args, cflags)
gl_libs = ['-framework', 'OpenGL'] if is_macos else pkg_config('gl', '--libs')
libpng = pkg_config('libpng', '--libs')
lcms2 = pkg_config('lcms2', '--libs')
ans.ldpaths += pylib + platform_libs + gl_libs + libpng + lcms2 + libcrypto_ldflags
if is_macos:
ans.ldpaths.extend('-framework Cocoa'.split())
elif not is_openbsd:
ans.ldpaths += ['-lrt']
if '-ldl' not in ans.ldpaths:
ans.ldpaths.append('-ldl')
if '-lz' not in ans.ldpaths:
ans.ldpaths.append('-lz')
return ans
def define(x: str) -> str:
return f'-D{x}'
def run_tool(cmd: Union[str, List[str]], desc: Optional[str] = None) -> None:
if isinstance(cmd, str):
cmd = shlex.split(cmd[0])
if verbose:
desc = None
print(desc or ' '.join(cmd))
p = subprocess.Popen(cmd)
ret = p.wait()
if ret != 0:
if desc:
print(' '.join(cmd))
raise SystemExit(ret)
@lru_cache
def get_vcs_rev() -> str:
ans = ''
if os.path.exists('.git'):
try:
rev = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf-8')
except FileNotFoundError:
try:
with open('.git/refs/heads/master') as f:
rev = f.read()
except NotADirectoryError:
with open('.git') as f:
gitloc = f.read()
with open(os.path.join(gitloc, 'refs/heads/master')) as f:
rev = f.read()
ans = rev.strip()
return ans
@lru_cache
def base64_defines(isa: ISA) -> List[str]:
defs = {
'HAVE_AVX512': 0,
'HAVE_AVX2': 0,
'HAVE_NEON32': 0,
'HAVE_NEON64': 0,
'HAVE_SSSE3': 0,
'HAVE_SSE41': 0,
'HAVE_SSE42': 0,
'HAVE_AVX': 0,
}
if isa == ISA.ARM64:
defs['HAVE_NEON64'] = 1
elif isa == ISA.AMD64:
defs['HAVE_AVX2'] = 1
defs['HAVE_AVX'] = 1
defs['HAVE_SSE42'] = 1
defs['HAVE_SSE41'] = 1
defs['HAVE_SSE3'] = 1
elif isa == ISA.X86:
defs['HAVE_SSE42'] = 1
defs['HAVE_SSE41'] = 1
defs['HAVE_SSE3'] = 1
return [f'{k}={v}' for k, v in defs.items()]
def get_source_specific_defines(env: Env, src: str) -> Tuple[str, List[str], Optional[List[str]]]:
if src == 'kitty/vt-parser-dump.c':
return 'kitty/vt-parser.c', [], ['DUMP_COMMANDS']
if src == 'kitty/data-types.c':
if not env.vcs_rev:
env.vcs_rev = get_vcs_rev()
return src, [], [f'KITTY_VCS_REV="{env.vcs_rev}"', f'WRAPPED_KITTENS="{wrapped_kittens()}"']
if src.startswith('3rdparty/base64/'):
return src, ['3rdparty/base64',], base64_defines(env.binary_arch.isa)
if src == 'kitty/screen.c':
return src, [], [f'PRIMARY_VERSION={env.primary_version}', f'SECONDARY_VERSION={env.secondary_version}', f'XT_VERSION="{env.xt_version}"']
if src == 'kitty/fast-file-copy.c':
return src, [], (['HAS_COPY_FILE_RANGE'] if env.has_copy_file_range else None)
try:
return src, [], env.library_paths[src]
except KeyError:
return src, [], None
def get_source_specific_cflags(env: Env, src: str) -> List[str]:
ans = list(env.cflags)
# SIMD specific flags
if src in ('kitty/simd-string-128.c', 'kitty/simd-string-256.c'):
# simde recommends these are used for best performance
ans.extend(('-fopenmp-simd', '-DSIMDE_ENABLE_OPENMP'))
if env.binary_arch.isa in (ISA.AMD64, ISA.X86):
ans.append('-msse4.2' if '128' in src else '-mavx2')
if '256' in src:
# We have manual vzeroupper so prevent compiler from emitting it causing duplicates
if env.compiler_type is CompilerType.clang:
ans.append('-mllvm')
ans.append('-x86-use-vzeroupper=0')
else:
ans.append('-mno-vzeroupper')
elif src.startswith('3rdparty/base64/lib/arch/'):
if env.binary_arch.isa in (ISA.AMD64, ISA.X86):
q = src.split(os.path.sep)
if 'sse3' in q:
ans.append('-msse3')
elif 'sse41' in q:
ans.append('-msse4.1')
elif 'sse42' in q:
ans.append('-msse4.2')
elif 'avx' in q:
ans.append('-mavx')
elif 'avx2' in q:
ans.append('-mavx2')
return ans
def newer(dest: str, *sources: str) -> bool:
try:
dtime = os.path.getmtime(dest)
except OSError:
return True
for s in sources:
with suppress(FileNotFoundError):
if os.path.getmtime(s) >= dtime:
return True
return False
def dependecies_for(src: str, obj: str, all_headers: Iterable[str]) -> Iterable[str]:
dep_file = obj.rpartition('.')[0] + '.d'
try:
with open(dep_file) as f:
deps = f.read()
except FileNotFoundError:
yield src
yield from iter(all_headers)
else:
RE_INC = re.compile(
r'^(?P<target>.+?):\s+(?P<deps>.+?)$', re.MULTILINE
)
SPACE_TOK = '\x1B'
text = deps.replace('\\\n', ' ').replace('\\ ', SPACE_TOK)
for match in RE_INC.finditer(text):
files = (
f.replace(SPACE_TOK, ' ') for f in match.group('deps').split()
)
for path in files:
path = os.path.abspath(path)
if path.startswith(src_base):
yield path
def parallel_run(items: List[Command]) -> None:
try:
num_workers = max(2, os.cpu_count() or 1)
except Exception:
num_workers = 2
items = list(reversed(items))
workers: Dict[int, Tuple[Optional[Command], Optional['subprocess.Popen[bytes]']]] = {}
failed = None
num, total = 0, len(items)
def wait() -> None:
nonlocal failed
if not workers:
return
pid, s = os.wait()
compile_cmd, w = workers.pop(pid, (None, None))
if compile_cmd is None:
return
if ((s & 0xff) != 0 or ((s >> 8) & 0xff) != 0):
if failed is None:
failed = compile_cmd
elif compile_cmd.on_success is not None:
compile_cmd.on_success()
printed = False
isatty = sys.stdout.isatty()
while items and failed is None:
while len(workers) < num_workers and items:
compile_cmd = items.pop()
num += 1
if verbose:
print(' '.join(compile_cmd.cmd))
elif isatty:
print(f'\r\x1b[K[{num}/{total}] {compile_cmd.desc}', end='') # ]]
else:
print(f'[{num}/{total}] {compile_cmd.desc}', flush=True)
printed = True
w = subprocess.Popen(compile_cmd.cmd, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
workers[w.pid] = compile_cmd, w
wait()
while len(workers):
wait()
if not verbose and printed:
print(' done')
if failed:
print(failed.desc)
run_tool(list(failed.cmd))
def add_builtin_fonts(args: Options) -> None:
fonts_dir = os.path.join(src_base, 'fonts')
os.makedirs(fonts_dir, exist_ok=True)
for psname, (filename, human_name) in {
'SymbolsNFM': ('SymbolsNerdFontMono-Regular.ttf', 'Symbols NERD Font Mono')
}.items():
dest = os.path.join(fonts_dir, filename)
if os.path.exists(dest):
continue
font_file = ''
if is_macos:
for candidate in (os.path.expanduser('~/Library/Fonts'), '/Library/Fonts', '/System/Library/Fonts', '/Network/Library/Fonts'):
q = os.path.join(candidate, filename)
if os.path.exists(q):
font_file = q
break
else:
lines = subprocess.check_output([
'fc-match', '--format', '%{file}\n%{postscriptname}', f'term:postscriptname={psname}', 'file', 'postscriptname']).decode().splitlines()
if len(lines) != 2:
raise SystemExit(f'fc-match returned unexpected output: {lines}')
if lines[1] != psname:
raise SystemExit(f'The font {human_name!r} was not found on your system, please install it')
font_file = lines[0]
if not font_file:
raise SystemExit(f'The font {human_name!r} was not found on your system, please install it')
print(f'Copying {human_name!r} from {font_file}')
shutil.copy(font_file, dest)
os.chmod(dest, 0o644)
def compile_c_extension(
kenv: Env,
module: str,
compilation_database: CompilationDatabase,
sources: List[str],
headers: List[str],
desc_prefix: str = '',
build_dsym: bool = False,
) -> None:
prefix = os.path.basename(module)
objects = [
os.path.join(build_dir, f'{prefix}-{src.replace("/", "-")}.o')
for src in sources
]
for original_src, dest in zip(sources, objects):
src = original_src
cppflags = kenv.cppflags[:]
src, include_paths, defines = get_source_specific_defines(kenv, src)
if defines is not None:
cppflags.extend(map(define, defines))
cflags = get_source_specific_cflags(kenv, src)
cmd = kenv.cc + ['-MMD'] + cppflags + [f'-I{x}' for x in include_paths] + cflags
cmd += ['-c', src] + ['-o', dest]
key = CompileKey(original_src, os.path.basename(dest))
desc = f'Compiling {emphasis(desc_prefix + src)} ...'
compilation_database.add_command(desc, cmd, partial(newer, dest, *dependecies_for(src, dest, headers)), key=key, keyfile=src)
dest = os.path.join(build_dir, f'{module}.so')
real_dest = f'{module}.so'
link_targets.append(os.path.abspath(real_dest))
os.makedirs(os.path.dirname(dest), exist_ok=True)
desc = f'Linking {emphasis(desc_prefix + module)} ...'
# Old versions of clang don't like -pthread being passed to the linker
# Don't treat linker warnings as errors (linker generates spurious
# warnings on some old systems)
unsafe = {'-pthread', '-Werror', '-pedantic-errors'}
linker_cflags = list(filter(lambda x: x not in unsafe, kenv.cflags))
cmd = kenv.cc + linker_cflags + kenv.ldflags + objects + kenv.ldpaths + ['-o', dest]
def on_success() -> None:
os.rename(dest, real_dest)
compilation_database.add_command(desc, cmd, partial(newer, real_dest, *objects), on_success=on_success, key=LinkKey(f'{module}.so'))
if is_macos and build_dsym:
real_dest = os.path.abspath(real_dest)
desc = f'Linking dSYM {emphasis(desc_prefix + module)} ...'
dsym = f'{real_dest}.dSYM/Contents/Resources/DWARF/{os.path.basename(real_dest)}'
compilation_database.add_command(desc, ['dsymutil', real_dest], partial(newer, dsym, real_dest), key=LinkKey(dsym), is_post_link=True)
def find_c_files() -> Tuple[List[str], List[str]]:
ans, headers = [], []
d = 'kitty'
exclude = {
'fontconfig.c', 'freetype.c', 'desktop.c', 'freetype_render_ui_text.c'
} if is_macos else {
'core_text.m', 'cocoa_window.m', 'macos_process_info.c'
}
for x in sorted(os.listdir(d)):
ext = os.path.splitext(x)[1]
if ext in ('.c', '.m') and os.path.basename(x) not in exclude:
ans.append(os.path.join('kitty', x))
elif ext == '.h':
headers.append(os.path.join('kitty', x))
ans.append('kitty/vt-parser-dump.c')
# ringbuf
ans.append('3rdparty/ringbuf/ringbuf.c')
# base64
ans.extend(glob.glob('3rdparty/base64/lib/arch/*/codec.c'))
ans.append('3rdparty/base64/lib/tables/tables.c')
ans.append('3rdparty/base64/lib/codec_choose.c')
ans.append('3rdparty/base64/lib/lib.c')
return ans, headers
def compile_glfw(compilation_database: CompilationDatabase, build_dsym: bool = False) -> None:
modules = 'cocoa' if is_macos else 'x11 wayland'
for module in modules.split():
try:
genv = glfw.init_env(env, pkg_config, pkg_version, at_least_version, test_compile, module)
except SystemExit as err:
if module != 'wayland':
raise
print(err, file=sys.stderr)
print(error('Disabling building of wayland backend'), file=sys.stderr)
continue
sources = [os.path.join('glfw', x) for x in genv.sources]
all_headers = [os.path.join('glfw', x) for x in genv.all_headers]
if module == 'wayland':
try:
glfw.build_wayland_protocols(genv, parallel_run, emphasis, newer, 'glfw')
except SystemExit as err:
print(err, file=sys.stderr)
print(error('Disabling building of wayland backend'), file=sys.stderr)
continue
compile_c_extension(
genv, f'kitty/glfw-{module}', compilation_database,
sources, all_headers, desc_prefix=f'[{module}] ', build_dsym=build_dsym)
def kittens_env(args: Options) -> Env:
kenv = env.copy()
cflags = kenv.cflags
cflags.append('-pthread')
cflags.append('-Ikitty')
pylib = get_python_flags(args, cflags)
kenv.ldpaths += pylib
return kenv
def compile_kittens(args: Options) -> None: