forked from kovidgoyal/kitty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.py
executable file
·1439 lines (1278 loc) · 52 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
# vim:fileencoding=utf-8
# 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 subprocess
import sys
import sysconfig
import tempfile
import time
from contextlib import suppress
from functools import lru_cache, partial
from pathlib import Path
from typing import (
Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Tuple,
Union
)
from glfw import glfw
from glfw.glfw import Command, CompileKey
if sys.version_info[:2] < (3, 6):
raise SystemExit('kitty requires python >= 3.6')
base = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, base)
del sys.path[0]
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() == 'arm64'
Env = glfw.Env
env = Env()
PKGCONFIG = os.environ.get('PKGCONFIG_EXE', 'pkg-config')
class Options(argparse.Namespace):
action: str = 'build'
debug: bool = False
verbose: int = 0
sanitize: bool = False
prefix: str = './linux-package'
incremental: bool = True
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')
def emphasis(text: str) -> str:
if sys.stdout.isatty():
text = '\033[32m' + text + '\033[39m'
return text
def error(text: str) -> str:
if sys.stdout.isatty():
text = '\033[91m' + text + '\033[39m'
return text
def pkg_config(pkg: str, *args: str) -> List[str]:
try:
return list(
filter(
None,
shlex.split(
subprocess.check_output([PKGCONFIG, pkg] + list(args))
.decode('utf-8')
)
)
)
except subprocess.CalledProcessError:
raise SystemExit('The package {} was not found on your system'.format(error(pkg)))
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 at_least_version(package: str, major: int, minor: int = 0) -> None:
q = '{}.{}'.format(major, minor)
if subprocess.run([PKGCONFIG, package, '--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(
'{} >= {}.{} is required, found version: {}'.format(
error(package), major, minor, 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(cflags: List[str]) -> List[str]:
cflags.extend('-I' + x for x in get_python_include_paths())
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 '/{}.framework'.format(fw) in val:
fdir = val[:val.index('/{}.framework'.format(fw))]
if os.path.isdir(
os.path.join(fdir, '{}.framework'.format(fw))
):
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 += ['-L' + ldlib]
ldlib = sysconfig.get_config_var('VERSION')
if ldlib:
libs += ['-lpython' + ldlib + sys.abiflags]
libs += (sysconfig.get_config_var('LINKFORSHARED') or '').split()
return libs
def get_sanitize_args(cc: List[str], ccver: Tuple[int, int]) -> List[str]:
sanitize_args = ['-fsanitize=address']
if ccver >= (5, 0):
sanitize_args.append('-fsanitize=undefined')
# if cc == 'gcc' or (cc == 'clang' and ccver >= (4, 2)):
# sanitize_args.append('-fno-sanitize-recover=all')
sanitize_args.append('-fno-omit-frame-pointer')
return sanitize_args
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] = (),
) -> bool:
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)
return subprocess.Popen(
cc + list(cflags) + ([] if link_also else ['-c']) +
['-o', os.path.join(tdir, 'source.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() == 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: Iterable[str] = ('x86_64', 'arm64')) -> 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 detect_librsync(cc: List[str], cflags: List[str], ldflags: List[str]) -> str:
if not test_compile(
cc, *cflags, libraries=('rsync',), ldflags=ldflags, show_stderr=True,
src='#include <librsync.h>\nint main(void) { rs_strerror(0); return 0; }'):
raise SystemExit('The librsync library is required')
# check for rs_sig_args() which was added to librsync in Apr 2020 version 2.3.0
if test_compile(cc, *cflags, libraries=('rsync',), ldflags=ldflags, src='''
#include <librsync.h>
int main(void) {
rs_magic_number magic_number = 0;
size_t block_len = 0, strong_len = 0;
rs_sig_args(1024, &magic_number, &block_len, &strong_len);
return 0;
}'''):
return '-DKITTY_HAS_RS_SIG_ARGS'
return ''
def is_gcc(cc: Iterable[str]) -> bool:
@lru_cache()
def f(cc: Tuple[str]) -> bool:
raw = subprocess.check_output(cc + ('--version',)).decode('utf-8').splitlines()[0]
return '(GCC)' in raw.split()
return f(tuple(cc))
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,
extra_logging: Iterable[str] = (),
extra_include_dirs: Iterable[str] = (),
ignore_compiler_warnings: bool = False,
build_universal_binary: bool = False,
extra_library_dirs: Iterable[str] = ()
) -> Env:
native_optimizations = native_optimizations and not sanitize and not debug
if native_optimizations and is_macos and is_arm:
# see https://github.com/kovidgoyal/kitty/issues/3126
# -march=native is not supported when targeting Apple Silicon
native_optimizations = False
cc, ccver = cc_version()
print('CC:', cc, ccver)
stack_protector = first_successful_compile(cc, '-fstack-protector-strong', '-fstack-protector')
missing_braces = ''
if ccver < (5, 2) and is_gcc(cc):
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 set()
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('-', '_')))
werror = '' if ignore_compiler_warnings else '-pedantic-errors -Werror'
std = '' if is_openbsd else '-std=c11'
sanitize_flag = ' '.join(sanitize_args)
march = '-march=native' if native_optimizations else ''
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 {march} -fvisibility=hidden {fortify_source}'
)
)
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 += shlex.split(os.environ.get('CPPFLAGS', ''))
cflags += shlex.split(os.environ.get('CFLAGS', ''))
ldflags += shlex.split(os.environ.get('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')
library_paths = {}
if egl_library is not None:
assert('"' not in egl_library)
library_paths['glfw/egl_context.c'] = ['_GLFW_EGL_LIBRARY="' + egl_library + '"']
desktop_libs = []
if startup_notification_library is not None:
assert('"' not in startup_notification_library)
desktop_libs = ['_KITTY_STARTUP_NOTIFICATION_LIBRARY="' + startup_notification_library + '"']
if canberra_library is not None:
assert('"' not in canberra_library)
desktop_libs += ['_KITTY_CANBERRA_LIBRARY="' + canberra_library + '"']
if desktop_libs != []:
library_paths['kitty/desktop.c'] = desktop_libs
for path in extra_include_dirs:
cflags.append(f'-I{path}')
ldpaths = []
for path in extra_library_dirs:
ldpaths.append(f'-L{path}')
rs_cflag = detect_librsync(cc, cflags, ldflags + ldpaths)
if rs_cflag:
cflags.append(rs_cflag)
if build_universal_binary:
set_arches(cflags)
set_arches(ldflags)
return Env(cc, cppflags, cflags, ldflags, library_paths, ccver=ccver, ldpaths=ldpaths)
def kitty_env() -> Env:
ans = env.copy()
cflags = ans.cflags
cflags.append('-pthread')
# We add 4000 to the primary version because vim turns on SGR mouse mode
# automatically if this version is high enough
cppflags = ans.cppflags
cppflags.append('-DPRIMARY_VERSION={}'.format(version[0] + 4000))
cppflags.append('-DSECONDARY_VERSION={}'.format(version[1]))
cppflags.append('-DXT_VERSION="{}"'.format('.'.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'))
if is_macos:
platform_libs = [
'-framework', 'CoreText', '-framework', 'CoreGraphics',
]
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:
cppflags.append('-DKITTY_USE_DEPRECATED_MACOS_NOTIFICATION_API')
# 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 = pkg_config('fontconfig', '--libs')
cflags.extend(pkg_config('harfbuzz', '--cflags-only-I'))
platform_libs.extend(pkg_config('harfbuzz', '--libs'))
pylib = get_python_flags(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
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')
with suppress(FileExistsError):
os.mkdir(build_dir)
return ans
def define(x: str) -> str:
return '-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)
def get_vcs_rev_defines(env: Env, src: str) -> List[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.append('KITTY_VCS_REV="{}"'.format(rev.strip()))
return ans
def get_library_defines(env: Env, src: str) -> Optional[List[str]]:
try:
return env.library_paths[src]
except KeyError:
return None
SPECIAL_SOURCES: Dict[str, Tuple[str, Union[List[str], Callable[[Env, str], Union[Optional[List[str]], Iterator[str]]]]]] = {
'glfw/egl_context.c': ('glfw/egl_context.c', get_library_defines),
'kitty/desktop.c': ('kitty/desktop.c', get_library_defines),
'kitty/parser_dump.c': ('kitty/parser.c', ['DUMP_COMMANDS']),
'kitty/data-types.c': ('kitty/data-types.c', get_vcs_rev_defines),
}
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(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('\r\x1b[K[{}/{}] {}'.format(num, total, compile_cmd.desc), end='')
else:
print('[{}/{}] {}'.format(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))
class CompilationDatabase:
def __init__(self, incremental: bool):
self.incremental = incremental
self.compile_commands: List[Command] = []
self.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
) -> None:
def no_op() -> None:
pass
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)
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('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': base, 'output': c.key.dest} for c in self.compile_commands if c.key is not None
]
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': base} for c in self.link_commands], f, indent=2, sort_keys=True)
def compile_c_extension(
kenv: Env,
module: str,
compilation_database: CompilationDatabase,
sources: List[str],
headers: List[str],
desc_prefix: str = ''
) -> None:
prefix = os.path.basename(module)
objects = [
os.path.join(build_dir, prefix + '-' + os.path.basename(src) + '.o')
for src in sources
]
for original_src, dest in zip(sources, objects):
src = original_src
cppflags = kenv.cppflags[:]
is_special = src in SPECIAL_SOURCES
if is_special:
src, defines_ = SPECIAL_SOURCES[src]
defines = defines_(kenv, src) if callable(defines_) else defines_
if defines is not None:
cppflags.extend(map(define, defines))
cmd = kenv.cc + ['-MMD'] + cppflags + kenv.cflags
cmd += ['-c', src] + ['-o', dest]
key = CompileKey(original_src, os.path.basename(dest))
desc = 'Compiling {} ...'.format(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, module + '.so')
real_dest = module + '.so'
os.makedirs(os.path.dirname(dest), exist_ok=True)
desc = 'Linking {} ...'.format(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=CompileKey('', module + '.so'))
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/parser_dump.c')
return ans, headers
def compile_glfw(compilation_database: CompilationDatabase) -> 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, 'kitty/glfw-' + module, compilation_database,
sources, all_headers, desc_prefix='[{}] '.format(module))
def kittens_env() -> Env:
kenv = env.copy()
cflags = kenv.cflags
cflags.append('-pthread')
cflags.append('-Ikitty')
pylib = get_python_flags(cflags)
kenv.ldpaths += pylib
return kenv
def compile_kittens(compilation_database: CompilationDatabase) -> None:
kenv = kittens_env()
def list_files(q: str) -> List[str]:
return sorted(glob.glob(q))
def files(
kitten: str,
output: str,
extra_headers: Sequence[str] = (),
extra_sources: Sequence[str] = (),
filter_sources: Optional[Callable[[str], bool]] = None,
includes: Sequence[str] = (), libraries: Sequence[str] = (),
) -> Tuple[str, List[str], List[str], str, Sequence[str], Sequence[str]]:
sources = list(filter(filter_sources, list(extra_sources) + list_files(os.path.join('kittens', kitten, '*.c'))))
headers = list_files(os.path.join('kittens', kitten, '*.h')) + list(extra_headers)
return kitten, sources, headers, 'kittens/{}/{}'.format(kitten, output), includes, libraries
for kitten, sources, all_headers, dest, includes, libraries in (
files('unicode_input', 'unicode_names'),
files('diff', 'diff_speedup'),
files('transfer', 'rsync', libraries=('rsync',)),
files(
'choose', 'subseq_matcher',
extra_headers=('kitty/charsets.h',),
extra_sources=('kitty/charsets.c',),
filter_sources=lambda x: 'windows_compat.c' not in x),
):
final_env = kenv.copy()
final_env.cflags.extend(f'-I{x}' for x in includes)
final_env.ldpaths[:0] = list(f'-l{x}' for x in libraries)
compile_c_extension(
final_env, dest, compilation_database, sources, all_headers + ['kitty/data-types.h'])
def init_env_from_args(args: Options, native_optimizations: bool = False) -> None:
global env
env = init_env(
args.debug, args.sanitize, native_optimizations, args.link_time_optimization, args.profile,
args.egl_library, args.startup_notification_library, args.canberra_library,
args.extra_logging, args.extra_include_dirs, args.ignore_compiler_warnings,
args.build_universal_binary, args.extra_library_dirs
)
def build(args: Options, native_optimizations: bool = True, call_init: bool = True) -> None:
if call_init:
init_env_from_args(args, native_optimizations)
sources, headers = find_c_files()
compile_c_extension(
kitty_env(), 'kitty/fast_data_types', args.compilation_database, sources, headers
)
compile_glfw(args.compilation_database)
compile_kittens(args.compilation_database)
def safe_makedirs(path: str) -> None:
os.makedirs(path, exist_ok=True)
def build_launcher(args: Options, launcher_dir: str = '.', bundle_type: str = 'source') -> None:
werror = '' if args.ignore_compiler_warnings else '-pedantic-errors -Werror'
cflags = f'-Wall {werror} -fpie'.split()
if args.build_universal_binary:
cflags += '-arch x86_64 -arch arm64'.split()
cppflags = []
libs: List[str] = []
if args.profile or args.sanitize:
if args.sanitize:
cflags.append('-g3')
cflags.extend(get_sanitize_args(env.cc, env.ccver))
libs += ['-lasan'] if is_gcc(env.cc) and not is_macos else []
else:
cflags.append('-g')
if args.profile:
libs.append('-lprofiler')
else:
cflags.append('-O3')
if bundle_type.endswith('-freeze'):
cppflags.append('-DFOR_BUNDLE')
cppflags.append('-DPYVER="{}"'.format(sysconfig.get_python_version()))
cppflags.append('-DKITTY_LIB_DIR_NAME="{}"'.format(args.libdir_name))
elif bundle_type == 'source':
cppflags.append('-DFROM_SOURCE')
if bundle_type.startswith('macos-'):
klp = '../Resources/kitty'
elif bundle_type.startswith('linux-'):
klp = '../{}/kitty'.format(args.libdir_name.strip('/'))
elif bundle_type == 'source':
klp = os.path.relpath('.', launcher_dir)
else:
raise SystemExit('Unknown bundle type: {}'.format(bundle_type))
cppflags.append('-DKITTY_LIB_PATH="{}"'.format(klp))
pylib = get_python_flags(cflags)
cppflags += shlex.split(os.environ.get('CPPFLAGS', ''))
cflags += shlex.split(os.environ.get('CFLAGS', ''))
ldflags = shlex.split(os.environ.get('LDFLAGS', ''))
for path in args.extra_include_dirs:
cflags.append(f'-I{path}')
if bundle_type == 'linux-freeze':
ldflags += ['-Wl,-rpath,$ORIGIN/../lib']
os.makedirs(launcher_dir, exist_ok=True)
dest = os.path.join(launcher_dir, 'kitty')
src = 'launcher.c'
cmd = env.cc + cppflags + cflags + [
src, '-o', dest] + ldflags + libs + pylib
key = CompileKey('launcher.c', 'kitty')
desc = 'Building {}...'.format(emphasis('launcher'))
args.compilation_database.add_command(desc, cmd, partial(newer, dest, src), key=key, keyfile=src)
args.compilation_database.build_all()
# Packaging {{{
def copy_man_pages(ddir: str) -> None:
mandir = os.path.join(ddir, 'share', 'man')
safe_makedirs(mandir)
man_levels = '15'
with suppress(FileNotFoundError):
for x in man_levels:
shutil.rmtree(os.path.join(mandir, f'man{x}'))
src = 'docs/_build/man'
if not os.path.exists(src):
raise SystemExit('''\
The kitty man pages are missing. If you are building from git then run:
make && make docs
(needs the sphinx documentation system to be installed)
''')
for x in man_levels:
os.makedirs(os.path.join(mandir, f'man{x}'))
for y in glob.glob(os.path.join(src, f'*.{x}')):
shutil.copy2(y, os.path.join(mandir, f'man{x}'))
def copy_html_docs(ddir: str) -> None:
htmldir = os.path.join(ddir, 'share', 'doc', appname, 'html')
safe_makedirs(os.path.dirname(htmldir))
with suppress(FileNotFoundError):
shutil.rmtree(htmldir)
src = 'docs/_build/html'
if not os.path.exists(src):
raise SystemExit('''\
The kitty html docs are missing. If you are building from git then run:
make && make docs
(needs the sphinx documentation system to be installed)
''')
shutil.copytree(src, htmldir)
def compile_python(base_path: str) -> None:
import compileall
import py_compile
try:
num_workers = max(1, os.cpu_count() or 1)
except Exception:
num_workers = 1
for root, dirs, files in os.walk(base_path):
for f in files:
if f.rpartition('.')[-1] in ('pyc', 'pyo'):
os.remove(os.path.join(root, f))
def c(base_path: str, **kw: object) -> None:
try:
kw['invalidation_mode'] = py_compile.PycInvalidationMode.UNCHECKED_HASH
except AttributeError:
pass
compileall.compile_dir(base_path, **kw) # type: ignore
for optimize in (0, 1, 2):
c(base_path, ddir='', force=True, optimize=optimize, quiet=1, workers=num_workers)
def create_linux_bundle_gunk(ddir: str, libdir_name: str) -> None:
if not os.path.exists('docs/_build/html'):
make = "gmake" if is_freebsd else "make"
run_tool([make, 'docs'])
copy_man_pages(ddir)
copy_html_docs(ddir)
for (icdir, ext) in {'256x256': 'png', 'scalable': 'svg'}.items():
icdir = os.path.join(ddir, 'share', 'icons', 'hicolor', icdir, 'apps')
safe_makedirs(icdir)
shutil.copy2(f'logo/kitty.{ext}', icdir)
deskdir = os.path.join(ddir, 'share', 'applications')
safe_makedirs(deskdir)
with open(os.path.join(deskdir, 'kitty.desktop'), 'w') as f:
f.write(
'''\
[Desktop Entry]
Version=1.0
Type=Application
Name=kitty
GenericName=Terminal emulator
Comment=Fast, feature-rich, GPU based terminal
TryExec=kitty
Exec=kitty
Icon=kitty
Categories=System;TerminalEmulator;
'''
)
base = Path(ddir)
in_src_launcher = base / (libdir_name + '/kitty/kitty/launcher/kitty')
launcher = base / 'bin/kitty'
if os.path.exists(in_src_launcher):
os.remove(in_src_launcher)
os.makedirs(os.path.dirname(in_src_launcher), exist_ok=True)
os.symlink(os.path.relpath(launcher, os.path.dirname(in_src_launcher)), in_src_launcher)
def macos_info_plist() -> bytes:
import plistlib
VERSION = '.'.join(map(str, version))
def access(what: str, verb: str = 'would like to access') -> str:
return f'A program running inside kitty {verb} {what}'
docs = [
{
'CFBundleTypeName': 'Terminal scripts',
'CFBundleTypeExtensions': ['command', 'sh', 'zsh', 'bash', 'fish', 'tool'],
'CFBundleTypeIconFile': appname + '.icns',
'CFBundleTypeRole': 'Editor',
},
{
'CFBundleTypeName': 'Folders',
'CFBundleTypeOSTypes': ['fold'],
'CFBundleTypeRole': 'Editor',
},
{