setup.py 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208
  1. #!/usr/bin/env python
  2. # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
  3. import argparse
  4. import glob
  5. import json
  6. import os
  7. import platform
  8. import re
  9. import runpy
  10. import shlex
  11. import shutil
  12. import struct
  13. import subprocess
  14. import sys
  15. import sysconfig
  16. import tempfile
  17. import textwrap
  18. import time
  19. from contextlib import suppress
  20. from functools import lru_cache, partial
  21. from pathlib import Path
  22. from typing import Callable, Dict, FrozenSet, Iterable, Iterator, List, Optional, Sequence, Set, Tuple, Union, cast
  23. from glfw import glfw
  24. from glfw.glfw import ISA, BinaryArch, Command, CompileKey, CompilerType
  25. src_base = os.path.dirname(os.path.abspath(__file__))
  26. def check_version_info() -> None:
  27. with open(os.path.join(src_base, 'pyproject.toml')) as f:
  28. raw = f.read()
  29. m = re.search(r'''^requires-python\s*=\s*['"](.+?)['"]''', raw, flags=re.MULTILINE)
  30. assert m is not None
  31. minver = m.group(1)
  32. match = re.match(r'(>=?)(\d+)\.(\d+)', minver)
  33. assert match is not None
  34. q = int(match.group(2)), int(match.group(3))
  35. if match.group(1) == '>=':
  36. is_ok = sys.version_info >= q
  37. else:
  38. is_ok = sys.version_info > q
  39. if not is_ok:
  40. exit(f'calibre requires Python {minver}. Current Python version: {".".join(map(str, sys.version_info[:3]))}')
  41. check_version_info()
  42. verbose = False
  43. build_dir = 'build'
  44. constants = os.path.join('kitty', 'constants.py')
  45. with open(constants, 'rb') as f:
  46. constants = f.read().decode('utf-8')
  47. appname = re.search(r"^appname: str = '([^']+)'", constants, re.MULTILINE).group(1) # type: ignore
  48. version = tuple(
  49. map(
  50. int,
  51. re.search( # type: ignore
  52. r"^version: Version = Version\((\d+), (\d+), (\d+)\)", constants, re.MULTILINE
  53. ).group(1, 2, 3)
  54. )
  55. )
  56. _plat = sys.platform.lower()
  57. is_macos = 'darwin' in _plat
  58. is_openbsd = 'openbsd' in _plat
  59. is_freebsd = 'freebsd' in _plat
  60. is_netbsd = 'netbsd' in _plat
  61. is_dragonflybsd = 'dragonfly' in _plat
  62. is_bsd = is_freebsd or is_netbsd or is_dragonflybsd or is_openbsd
  63. is_arm = platform.processor() == 'arm' or platform.machine() in ('arm64', 'aarch64')
  64. Env = glfw.Env
  65. env = Env()
  66. PKGCONFIG = os.environ.get('PKGCONFIG_EXE', 'pkg-config')
  67. link_targets: List[str] = []
  68. macos_universal_arches = ('arm64', 'x86_64') if is_arm else ('x86_64', 'arm64')
  69. def LinkKey(output: str) -> CompileKey:
  70. return CompileKey('', output)
  71. class CompilationDatabase:
  72. def __init__(self, incremental: bool = False):
  73. self.incremental = incremental
  74. self.compile_commands: List[Command] = []
  75. self.link_commands: List[Command] = []
  76. self.post_link_commands: List[Command] = []
  77. def add_command(
  78. self,
  79. desc: str,
  80. cmd: List[str],
  81. is_newer_func: Callable[[], bool],
  82. key: Optional[CompileKey] = None,
  83. on_success: Optional[Callable[[], None]] = None,
  84. keyfile: Optional[str] = None,
  85. is_post_link: bool = False,
  86. ) -> None:
  87. def no_op() -> None:
  88. pass
  89. if is_post_link:
  90. queue = self.post_link_commands
  91. else:
  92. queue = self.link_commands if keyfile is None else self.compile_commands
  93. queue.append(Command(desc, cmd, is_newer_func, on_success or no_op, key, keyfile))
  94. def build_all(self) -> None:
  95. def sort_key(compile_cmd: Command) -> int:
  96. if compile_cmd.keyfile:
  97. return os.path.getsize(compile_cmd.keyfile)
  98. return 0
  99. items = []
  100. for compile_cmd in self.compile_commands:
  101. if not self.incremental or self.cmd_changed(compile_cmd) or compile_cmd.is_newer_func():
  102. items.append(compile_cmd)
  103. items.sort(key=sort_key, reverse=True)
  104. parallel_run(items)
  105. items = []
  106. for compile_cmd in self.link_commands:
  107. if not self.incremental or compile_cmd.is_newer_func():
  108. items.append(compile_cmd)
  109. parallel_run(items)
  110. items = []
  111. for compile_cmd in self.post_link_commands:
  112. if not self.incremental or compile_cmd.is_newer_func():
  113. items.append(compile_cmd)
  114. parallel_run(items)
  115. def cmd_changed(self, compile_cmd: Command) -> bool:
  116. key, cmd = compile_cmd.key, compile_cmd.cmd
  117. return bool(self.db.get(key) != cmd)
  118. def __enter__(self) -> 'CompilationDatabase':
  119. self.all_keys: Set[CompileKey] = set()
  120. self.dbpath = os.path.abspath(os.path.join(build_dir, 'compile_commands.json'))
  121. self.linkdbpath = os.path.join(os.path.dirname(self.dbpath), 'link_commands.json')
  122. try:
  123. with open(self.dbpath) as f:
  124. compilation_database = json.load(f)
  125. except FileNotFoundError:
  126. compilation_database = []
  127. try:
  128. with open(self.linkdbpath) as f:
  129. link_database = json.load(f)
  130. except FileNotFoundError:
  131. link_database = []
  132. compilation_database = {
  133. CompileKey(k['file'], k['output']): k['arguments'] for k in compilation_database
  134. }
  135. self.db = compilation_database
  136. self.linkdb = {tuple(k['output']): k['arguments'] for k in link_database}
  137. return self
  138. def __exit__(self, *a: object) -> None:
  139. cdb = self.db
  140. for key in set(cdb) - self.all_keys:
  141. del cdb[key]
  142. compilation_database = [
  143. {'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
  144. ]
  145. with suppress(FileNotFoundError):
  146. with open(self.dbpath, 'w') as f:
  147. json.dump(compilation_database, f, indent=2, sort_keys=True)
  148. with open(self.linkdbpath, 'w') as f:
  149. json.dump([{'output': c.key, 'arguments': c.cmd, 'directory': src_base} for c in self.link_commands], f, indent=2, sort_keys=True)
  150. class Options:
  151. action: str = 'build'
  152. debug: bool = False
  153. verbose: int = 0
  154. sanitize: bool = False
  155. prefix: str = './linux-package'
  156. dir_for_static_binaries: str = 'build/static'
  157. skip_code_generation: bool = False
  158. skip_building_kitten: bool = False
  159. clean_for_cross_compile: bool = False
  160. python_compiler_flags: str = ''
  161. python_linker_flags: str = ''
  162. incremental: bool = True
  163. build_dsym: bool = False
  164. ignore_compiler_warnings: bool = False
  165. profile: bool = False
  166. libdir_name: str = 'lib'
  167. extra_logging: List[str] = []
  168. extra_include_dirs: List[str] = []
  169. extra_library_dirs: List[str] = []
  170. link_time_optimization: bool = 'KITTY_NO_LTO' not in os.environ
  171. update_check_interval: float = 24.0
  172. shell_integration: str = 'enabled'
  173. egl_library: Optional[str] = os.getenv('KITTY_EGL_LIBRARY')
  174. startup_notification_library: Optional[str] = os.getenv('KITTY_STARTUP_NOTIFICATION_LIBRARY')
  175. canberra_library: Optional[str] = os.getenv('KITTY_CANBERRA_LIBRARY')
  176. systemd_library: Optional[str] = os.getenv('KITTY_SYSTEMD_LIBRARY')
  177. fontconfig_library: Optional[str] = os.getenv('KITTY_FONTCONFIG_LIBRARY')
  178. building_arch: str = ''
  179. # Extras
  180. compilation_database: CompilationDatabase = CompilationDatabase()
  181. vcs_rev: str = ''
  182. def emphasis(text: str) -> str:
  183. if sys.stdout.isatty():
  184. text = f'\033[32m{text}\033[39m'
  185. return text
  186. def error(text: str) -> str:
  187. if sys.stdout.isatty():
  188. text = f'\033[91m{text}\033[39m'
  189. return text
  190. def pkg_config(pkg: str, *args: str, extra_pc_dir: str = '', fatal: bool = True) -> List[str]:
  191. env = os.environ.copy()
  192. if extra_pc_dir:
  193. pp = env.get('PKG_CONFIG_PATH', '')
  194. if pp:
  195. pp += os.pathsep
  196. env['PKG_CONFIG_PATH'] = f'{pp}{extra_pc_dir}'
  197. cmd = [PKGCONFIG, pkg] + list(args)
  198. try:
  199. return list(
  200. filter(
  201. None,
  202. shlex.split(
  203. subprocess.check_output(cmd, env=env, stderr=None if fatal else subprocess.DEVNULL).decode('utf-8')
  204. )
  205. )
  206. )
  207. except subprocess.CalledProcessError:
  208. if fatal:
  209. raise SystemExit(f'The package {error(pkg)} was not found on your system')
  210. raise
  211. def pkg_version(package: str) -> Tuple[int, int]:
  212. ver = subprocess.check_output([
  213. PKGCONFIG, package, '--modversion']).decode('utf-8').strip()
  214. m = re.match(r'(\d+).(\d+)', ver)
  215. if m is not None:
  216. qmajor, qminor = map(int, m.groups())
  217. return qmajor, qminor
  218. return -1, -1
  219. def libcrypto_flags() -> Tuple[List[str], List[str]]:
  220. # Apple use their special snowflake TLS libraries and additionally
  221. # have an ancient broken system OpenSSL, so we need to check for one
  222. # installed by all the various macOS package managers.
  223. extra_pc_dir = ''
  224. try:
  225. cflags = pkg_config('libcrypto', '--cflags-only-I', fatal=False)
  226. except subprocess.CalledProcessError:
  227. if is_macos:
  228. import ssl
  229. v = ssl.OPENSSL_VERSION_INFO
  230. pats = f'{v[0]}.{v[1]}', f'{v[0]}'
  231. for pat in pats:
  232. q = f'opt/openssl@{pat}/lib/pkgconfig'
  233. openssl_dirs = glob.glob(f'/opt/homebrew/{q}') + glob.glob(f'/usr/local/{q}')
  234. if openssl_dirs:
  235. break
  236. else:
  237. raise SystemExit(f'Failed to find OpenSSL version {v[0]}.{v[1]} on your system')
  238. extra_pc_dir = os.pathsep.join(openssl_dirs)
  239. cflags = pkg_config('libcrypto', '--cflags-only-I', extra_pc_dir=extra_pc_dir)
  240. ldflags = pkg_config('libcrypto', '--libs', extra_pc_dir=extra_pc_dir)
  241. # Workaround bug in homebrew openssl package. This bug appears in CI only
  242. if is_macos and ldflags and 'homebrew/Cellar' in ldflags[0] and not ldflags[0].endswith('/lib'):
  243. ldflags.insert(0, ldflags[0] + '/lib')
  244. return cflags, ldflags
  245. def at_least_version(package: str, major: int, minor: int = 0) -> None:
  246. q = f'{major}.{minor}'
  247. if subprocess.run([PKGCONFIG, package, f'--atleast-version={q}']
  248. ).returncode != 0:
  249. qmajor = qminor = 0
  250. try:
  251. ver = subprocess.check_output([PKGCONFIG, package, '--modversion']
  252. ).decode('utf-8').strip()
  253. m = re.match(r'(\d+).(\d+)', ver)
  254. if m is not None:
  255. qmajor, qminor = map(int, m.groups())
  256. except Exception:
  257. ver = 'not found'
  258. if qmajor < major or (qmajor == major and qminor < minor):
  259. raise SystemExit(f'{error(package)} >= {major}.{minor} is required, found version: {ver}')
  260. def cc_version() -> Tuple[List[str], Tuple[int, int]]:
  261. if 'CC' in os.environ:
  262. q = os.environ['CC']
  263. else:
  264. if is_macos:
  265. q = 'clang'
  266. else:
  267. if shutil.which('gcc'):
  268. q = 'gcc'
  269. elif shutil.which('clang'):
  270. q = 'clang'
  271. else:
  272. q = 'cc'
  273. cc = shlex.split(q)
  274. raw = subprocess.check_output(cc + ['-dumpversion']).decode('utf-8')
  275. ver_ = raw.strip().split('.')[:2]
  276. try:
  277. if len(ver_) == 1:
  278. ver = int(ver_[0]), 0
  279. else:
  280. ver = int(ver_[0]), int(ver_[1])
  281. except Exception:
  282. ver = (0, 0)
  283. return cc, ver
  284. def get_python_include_paths() -> List[str]:
  285. ans = []
  286. for name in sysconfig.get_path_names():
  287. if 'include' in name:
  288. ans.append(name)
  289. def gp(x: str) -> Optional[str]:
  290. return sysconfig.get_path(x)
  291. return sorted(frozenset(filter(None, map(gp, sorted(ans)))))
  292. def get_python_flags(args: Options, cflags: List[str], for_main_executable: bool = False) -> List[str]:
  293. if args.python_compiler_flags:
  294. cflags.extend(shlex.split(args.python_compiler_flags))
  295. else:
  296. cflags.extend(f'-I{x}' for x in get_python_include_paths())
  297. if args.python_linker_flags:
  298. return shlex.split(args.python_linker_flags)
  299. libs: List[str] = []
  300. libs += (sysconfig.get_config_var('LIBS') or '').split()
  301. libs += (sysconfig.get_config_var('SYSLIBS') or '').split()
  302. fw = sysconfig.get_config_var('PYTHONFRAMEWORK')
  303. if fw:
  304. for var in 'data include stdlib'.split():
  305. val = sysconfig.get_path(var)
  306. if val and f'/{fw}.framework' in val:
  307. fdir = val[:val.index(f'/{fw}.framework')]
  308. if os.path.isdir(
  309. os.path.join(fdir, f'{fw}.framework')
  310. ):
  311. framework_dir = fdir
  312. break
  313. else:
  314. raise SystemExit('Failed to find Python framework')
  315. ldlib = sysconfig.get_config_var('LDLIBRARY')
  316. if ldlib:
  317. libs.append(os.path.join(framework_dir, ldlib))
  318. else:
  319. ldlib = sysconfig.get_config_var('LIBDIR')
  320. if ldlib:
  321. libs += [f'-L{ldlib}']
  322. ldlib = sysconfig.get_config_var('VERSION')
  323. if ldlib:
  324. libs += [f'-lpython{ldlib}{sys.abiflags}']
  325. lval = sysconfig.get_config_var('LINKFORSHARED') or ''
  326. if not for_main_executable:
  327. # Python sets the stack size on macOS which is not allowed unless
  328. # compiling an executable https://github.com/kovidgoyal/kitty/issues/289
  329. lval = re.sub(r'-Wl,-stack_size,\d+', '', lval)
  330. libs += list(filter(None, lval.split()))
  331. return libs
  332. def get_sanitize_args(cc: List[str], ccver: Tuple[int, int]) -> List[str]:
  333. return ['-fsanitize=address,undefined', '-fno-omit-frame-pointer']
  334. def get_binary_arch(path: str) -> BinaryArch:
  335. with open(path, 'rb') as f:
  336. sig = f.read(64)
  337. if sig.startswith(b'\x7fELF'): # ELF
  338. bits = {1: 32, 2: 64}[sig[4]]
  339. endian = {1: '<', 2: '>'}[sig[5]]
  340. machine, = struct.unpack_from(endian + 'H', sig, 0x12)
  341. isa = {i.value:i for i in ISA}.get(machine, ISA.Other)
  342. elif sig[:4] in (b'\xcf\xfa\xed\xfe', b'\xce\xfa\xed\xfe'): # Mach-O
  343. s, cpu_type, = struct.unpack_from('<II', sig, 0)
  344. bits = {0xfeedface: 32, 0xfeedfacf: 64}[s]
  345. cpu_type &= 0xff
  346. isa = {0x7: ISA.AMD64, 0xc: ISA.ARM64}[cpu_type]
  347. else:
  348. raise SystemExit(f'Unknown binary format with signature: {sig[:4]!r}')
  349. return BinaryArch(bits=bits, isa=isa)
  350. def test_compile(
  351. cc: List[str], *cflags: str,
  352. src: str = '',
  353. source_ext: str = 'c',
  354. link_also: bool = True,
  355. show_stderr: bool = False,
  356. libraries: Iterable[str] = (),
  357. ldflags: Iterable[str] = (),
  358. get_output_arch: bool = False,
  359. ) -> Union[bool, BinaryArch]:
  360. src = src or 'int main(void) { return 0; }'
  361. with tempfile.TemporaryDirectory(prefix='kitty-test-compile-') as tdir:
  362. with open(os.path.join(tdir, f'source.{source_ext}'), 'w', encoding='utf-8') as srcf:
  363. print(src, file=srcf)
  364. output = os.path.join(tdir, 'source.output')
  365. ret = subprocess.Popen(
  366. cc + ['-Werror=implicit-function-declaration'] + list(cflags) + ([] if link_also else ['-c']) +
  367. ['-o', output, srcf.name] +
  368. [f'-l{x}' for x in libraries] + list(ldflags),
  369. stdout=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
  370. stderr=None if show_stderr else subprocess.DEVNULL
  371. ).wait()
  372. if get_output_arch:
  373. if ret != 0:
  374. raise SystemExit(f'Failed to determine target architecture compiling test program failed with exit code: {ret}')
  375. return get_binary_arch(output)
  376. return ret == 0
  377. def first_successful_compile(cc: List[str], *cflags: str, src: str = '', source_ext: str = 'c') -> str:
  378. for x in cflags:
  379. if test_compile(cc, *shlex.split(x), src=src, source_ext=source_ext):
  380. return x
  381. return ''
  382. def set_arches(flags: List[str], *arches: str) -> None:
  383. while True:
  384. try:
  385. idx = flags.index('-arch')
  386. except ValueError:
  387. break
  388. del flags[idx]
  389. del flags[idx]
  390. for arch in arches:
  391. flags.extend(('-arch', arch))
  392. def init_env(
  393. debug: bool = False,
  394. sanitize: bool = False,
  395. native_optimizations: bool = True,
  396. link_time_optimization: bool = True,
  397. profile: bool = False,
  398. egl_library: Optional[str] = None,
  399. startup_notification_library: Optional[str] = None,
  400. canberra_library: Optional[str] = None,
  401. systemd_library: Optional[str] = None,
  402. fontconfig_library: Optional[str] = None,
  403. extra_logging: Iterable[str] = (),
  404. extra_include_dirs: Iterable[str] = (),
  405. ignore_compiler_warnings: bool = False,
  406. building_arch: str = '',
  407. extra_library_dirs: Iterable[str] = (),
  408. verbose: bool = True,
  409. vcs_rev: str = '',
  410. ) -> Env:
  411. native_optimizations = native_optimizations and not sanitize
  412. cc, ccver = cc_version()
  413. if verbose:
  414. print('CC:', cc, ccver)
  415. stack_protector = first_successful_compile(cc, '-fstack-protector-strong', '-fstack-protector')
  416. missing_braces = ''
  417. if ccver < (5, 2):
  418. missing_braces = '-Wno-missing-braces'
  419. df = '-g3'
  420. float_conversion = ''
  421. if ccver >= (5, 0):
  422. df += ' -Og'
  423. float_conversion = '-Wfloat-conversion'
  424. fortify_source = '' if sanitize and is_macos else '-D_FORTIFY_SOURCE=2'
  425. optimize = df if debug or sanitize else '-O3'
  426. sanitize_args = get_sanitize_args(cc, ccver) if sanitize else []
  427. cppflags_ = os.environ.get(
  428. 'OVERRIDE_CPPFLAGS', '-D{}DEBUG'.format('' if debug else 'N'),
  429. )
  430. cppflags = shlex.split(cppflags_)
  431. for el in extra_logging:
  432. cppflags.append('-DDEBUG_{}'.format(el.upper().replace('-', '_')))
  433. 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; }')
  434. werror = '' if ignore_compiler_warnings else '-pedantic-errors -Werror'
  435. std = '' if is_openbsd else '-std=c11'
  436. sanitize_flag = ' '.join(sanitize_args)
  437. env_cflags = shlex.split(os.environ.get('CFLAGS', ''))
  438. env_cppflags = shlex.split(os.environ.get('CPPFLAGS', ''))
  439. env_ldflags = shlex.split(os.environ.get('LDFLAGS', ''))
  440. cflags_ = os.environ.get(
  441. 'OVERRIDE_CFLAGS', (
  442. f'-Wextra {float_conversion} -Wno-missing-field-initializers -Wall -Wstrict-prototypes {std}'
  443. f' {werror} {optimize} {sanitize_flag} -fwrapv {stack_protector} {missing_braces}'
  444. f' -pipe -fvisibility=hidden -fno-plt'
  445. )
  446. )
  447. cflags = shlex.split(cflags_) + shlex.split(
  448. sysconfig.get_config_var('CCSHARED') or ''
  449. )
  450. ldflags_ = os.environ.get(
  451. 'OVERRIDE_LDFLAGS',
  452. '-Wall ' + ' '.join(sanitize_args) + ('' if debug else ' -O3')
  453. )
  454. ldflags = shlex.split(ldflags_)
  455. ldflags.append('-shared')
  456. cppflags += env_cppflags
  457. cflags += env_cflags
  458. if fortify_source:
  459. for x in cflags:
  460. if '_FORTIFY_SOURCE' in x:
  461. break
  462. else:
  463. cflags.append(fortify_source)
  464. ldflags += env_ldflags
  465. if not debug and not sanitize and not is_openbsd and link_time_optimization:
  466. # See https://github.com/google/sanitizers/issues/647
  467. cflags.append('-flto')
  468. ldflags.append('-flto')
  469. if debug:
  470. cflags.append('-DKITTY_DEBUG_BUILD')
  471. if profile:
  472. cppflags.append('-DWITH_PROFILER')
  473. cflags.append('-g3')
  474. ldflags.append('-lprofiler')
  475. if debug or profile:
  476. cflags.append('-fno-omit-frame-pointer')
  477. library_paths: Dict[str, List[str]] = {}
  478. def add_lpath(which: str, name: str, val: Optional[str]) -> None:
  479. if val:
  480. if '"' in val:
  481. raise SystemExit(f'Cannot have quotes in library paths: {val}')
  482. library_paths.setdefault(which, []).append(f'{name}="{val}"')
  483. add_lpath('glfw/egl_context.c', '_GLFW_EGL_LIBRARY', egl_library)
  484. add_lpath('kitty/desktop.c', '_KITTY_STARTUP_NOTIFICATION_LIBRARY', startup_notification_library)
  485. add_lpath('kitty/desktop.c', '_KITTY_CANBERRA_LIBRARY', canberra_library)
  486. add_lpath('kitty/systemd.c', '_KITTY_SYSTEMD_LIBRARY', systemd_library)
  487. add_lpath('kitty/fontconfig.c', '_KITTY_FONTCONFIG_LIBRARY', fontconfig_library)
  488. for path in extra_include_dirs:
  489. cflags.append(f'-I{path}')
  490. ldpaths = []
  491. for path in extra_library_dirs:
  492. ldpaths.append(f'-L{path}')
  493. if os.environ.get("DEVELOP_ROOT"):
  494. cflags.insert(0, f'-I{os.environ["DEVELOP_ROOT"]}/include')
  495. ldpaths.insert(0, f'-L{os.environ["DEVELOP_ROOT"]}/lib')
  496. if building_arch:
  497. set_arches(cflags, building_arch)
  498. set_arches(ldflags, building_arch)
  499. ba = test_compile(cc, *(cppflags + cflags), ldflags=ldflags, get_output_arch=True)
  500. assert isinstance(ba, BinaryArch)
  501. if ba.isa not in (ISA.AMD64, ISA.X86, ISA.ARM64):
  502. cppflags.append('-DKITTY_NO_SIMD')
  503. control_flow_protection = ''
  504. if ba.isa == ISA.AMD64:
  505. control_flow_protection = '-fcf-protection=full' if ccver >= (9, 0) else ''
  506. elif ba.isa == ISA.ARM64:
  507. # Using -mbranch-protection=standard causes crashes on Linux ARM, reported
  508. # in https://github.com/kovidgoyal/kitty/issues/6845#issuecomment-1835886938
  509. if is_macos:
  510. control_flow_protection = '-mbranch-protection=standard'
  511. if control_flow_protection:
  512. cflags.append(control_flow_protection)
  513. if native_optimizations and ba.isa in (ISA.AMD64, ISA.X86):
  514. cflags.extend('-march=native -mtune=native'.split())
  515. ans = Env(
  516. cc, cppflags, cflags, ldflags, library_paths, binary_arch=ba, native_optimizations=native_optimizations,
  517. ccver=ccver, ldpaths=ldpaths, vcs_rev=vcs_rev,
  518. )
  519. ans.has_copy_file_range = bool(has_copy_file_range)
  520. if verbose:
  521. print(ans.cc_version_string.strip())
  522. print('Detected:', ans.compiler_type)
  523. return ans
  524. def kitty_env(args: Options) -> Env:
  525. ans = env.copy()
  526. cflags = ans.cflags
  527. cflags.append('-pthread')
  528. cppflags = ans.cppflags
  529. # We add 4000 to the primary version because vim turns on SGR mouse mode
  530. # automatically if this version is high enough
  531. ans.primary_version = version[0] + 4000
  532. ans.secondary_version = version[1]
  533. ans.xt_version = '.'.join(map(str, version))
  534. at_least_version('harfbuzz', 1, 5)
  535. cflags.extend(pkg_config('libpng', '--cflags-only-I'))
  536. cflags.extend(pkg_config('lcms2', '--cflags-only-I'))
  537. # simde doesnt come with pkg-config files but some Linux distros add
  538. # them and on macOS when building with homebrew it is required
  539. with suppress(SystemExit, subprocess.CalledProcessError):
  540. cflags.extend(pkg_config('simde', '--cflags-only-I', fatal=False))
  541. libcrypto_cflags, libcrypto_ldflags = libcrypto_flags()
  542. cflags.extend(libcrypto_cflags)
  543. if is_macos:
  544. platform_libs = [
  545. '-framework', 'Carbon', '-framework', 'CoreText', '-framework', 'CoreGraphics',
  546. '-framework', 'AudioToolbox',
  547. ]
  548. test_program_src = '''#include <UserNotifications/UserNotifications.h>
  549. int main(void) { return 0; }\n'''
  550. user_notifications_framework = first_successful_compile(
  551. ans.cc, '-framework UserNotifications', src=test_program_src, source_ext='m')
  552. if user_notifications_framework:
  553. platform_libs.extend(shlex.split(user_notifications_framework))
  554. else:
  555. raise SystemExit('UserNotifications framework missing')
  556. # Apple deprecated OpenGL in Mojave (10.14) silence the endless
  557. # warnings about it
  558. cppflags.append('-DGL_SILENCE_DEPRECATION')
  559. else:
  560. cflags.extend(pkg_config('fontconfig', '--cflags-only-I'))
  561. platform_libs = []
  562. cflags.extend(pkg_config('harfbuzz', '--cflags-only-I'))
  563. platform_libs.extend(pkg_config('harfbuzz', '--libs'))
  564. pylib = get_python_flags(args, cflags)
  565. gl_libs = ['-framework', 'OpenGL'] if is_macos else pkg_config('gl', '--libs')
  566. libpng = pkg_config('libpng', '--libs')
  567. lcms2 = pkg_config('lcms2', '--libs')
  568. ans.ldpaths += pylib + platform_libs + gl_libs + libpng + lcms2 + libcrypto_ldflags
  569. if is_macos:
  570. ans.ldpaths.extend('-framework Cocoa'.split())
  571. elif not is_openbsd:
  572. ans.ldpaths += ['-lrt']
  573. if '-ldl' not in ans.ldpaths:
  574. ans.ldpaths.append('-ldl')
  575. if '-lz' not in ans.ldpaths:
  576. ans.ldpaths.append('-lz')
  577. return ans
  578. def define(x: str) -> str:
  579. return f'-D{x}'
  580. def run_tool(cmd: Union[str, List[str]], desc: Optional[str] = None) -> None:
  581. if isinstance(cmd, str):
  582. cmd = shlex.split(cmd[0])
  583. if verbose:
  584. desc = None
  585. print(desc or ' '.join(cmd))
  586. p = subprocess.Popen(cmd)
  587. ret = p.wait()
  588. if ret != 0:
  589. if desc:
  590. print(' '.join(cmd))
  591. raise SystemExit(ret)
  592. @lru_cache
  593. def get_vcs_rev() -> str:
  594. ans = ''
  595. if os.path.exists('.git'):
  596. try:
  597. rev = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf-8')
  598. except FileNotFoundError:
  599. try:
  600. with open('.git/refs/heads/master') as f:
  601. rev = f.read()
  602. except NotADirectoryError:
  603. with open('.git') as f:
  604. gitloc = f.read()
  605. with open(os.path.join(gitloc, 'refs/heads/master')) as f:
  606. rev = f.read()
  607. ans = rev.strip()
  608. return ans
  609. @lru_cache
  610. def base64_defines(isa: ISA) -> List[str]:
  611. defs = {
  612. 'HAVE_AVX512': 0,
  613. 'HAVE_AVX2': 0,
  614. 'HAVE_NEON32': 0,
  615. 'HAVE_NEON64': 0,
  616. 'HAVE_SSSE3': 0,
  617. 'HAVE_SSE41': 0,
  618. 'HAVE_SSE42': 0,
  619. 'HAVE_AVX': 0,
  620. }
  621. if isa == ISA.ARM64:
  622. defs['HAVE_NEON64'] = 1
  623. elif isa == ISA.AMD64:
  624. defs['HAVE_AVX2'] = 1
  625. defs['HAVE_AVX'] = 1
  626. defs['HAVE_SSE42'] = 1
  627. defs['HAVE_SSE41'] = 1
  628. defs['HAVE_SSE3'] = 1
  629. elif isa == ISA.X86:
  630. defs['HAVE_SSE42'] = 1
  631. defs['HAVE_SSE41'] = 1
  632. defs['HAVE_SSE3'] = 1
  633. return [f'{k}={v}' for k, v in defs.items()]
  634. def get_source_specific_defines(env: Env, src: str) -> Tuple[str, List[str], Optional[List[str]]]:
  635. if src == 'kitty/vt-parser-dump.c':
  636. return 'kitty/vt-parser.c', [], ['DUMP_COMMANDS']
  637. if src == 'kitty/data-types.c':
  638. if not env.vcs_rev:
  639. env.vcs_rev = get_vcs_rev()
  640. return src, [], [f'KITTY_VCS_REV="{env.vcs_rev}"', f'WRAPPED_KITTENS="{wrapped_kittens()}"']
  641. if src.startswith('3rdparty/base64/'):
  642. return src, ['3rdparty/base64',], base64_defines(env.binary_arch.isa)
  643. if src == 'kitty/screen.c':
  644. return src, [], [f'PRIMARY_VERSION={env.primary_version}', f'SECONDARY_VERSION={env.secondary_version}', f'XT_VERSION="{env.xt_version}"']
  645. if src == 'kitty/fast-file-copy.c':
  646. return src, [], (['HAS_COPY_FILE_RANGE'] if env.has_copy_file_range else None)
  647. try:
  648. return src, [], env.library_paths[src]
  649. except KeyError:
  650. return src, [], None
  651. def get_source_specific_cflags(env: Env, src: str) -> List[str]:
  652. ans = list(env.cflags)
  653. # SIMD specific flags
  654. if src in ('kitty/simd-string-128.c', 'kitty/simd-string-256.c'):
  655. # simde recommends these are used for best performance
  656. ans.extend(('-fopenmp-simd', '-DSIMDE_ENABLE_OPENMP'))
  657. if env.binary_arch.isa in (ISA.AMD64, ISA.X86):
  658. ans.append('-msse4.2' if '128' in src else '-mavx2')
  659. if '256' in src:
  660. # We have manual vzeroupper so prevent compiler from emitting it causing duplicates
  661. if env.compiler_type is CompilerType.clang:
  662. ans.append('-mllvm')
  663. ans.append('-x86-use-vzeroupper=0')
  664. else:
  665. ans.append('-mno-vzeroupper')
  666. elif src.startswith('3rdparty/base64/lib/arch/'):
  667. if env.binary_arch.isa in (ISA.AMD64, ISA.X86):
  668. q = src.split(os.path.sep)
  669. if 'sse3' in q:
  670. ans.append('-msse3')
  671. elif 'sse41' in q:
  672. ans.append('-msse4.1')
  673. elif 'sse42' in q:
  674. ans.append('-msse4.2')
  675. elif 'avx' in q:
  676. ans.append('-mavx')
  677. elif 'avx2' in q:
  678. ans.append('-mavx2')
  679. return ans
  680. def newer(dest: str, *sources: str) -> bool:
  681. try:
  682. dtime = os.path.getmtime(dest)
  683. except OSError:
  684. return True
  685. for s in sources:
  686. with suppress(FileNotFoundError):
  687. if os.path.getmtime(s) >= dtime:
  688. return True
  689. return False
  690. def dependecies_for(src: str, obj: str, all_headers: Iterable[str]) -> Iterable[str]:
  691. dep_file = obj.rpartition('.')[0] + '.d'
  692. try:
  693. with open(dep_file) as f:
  694. deps = f.read()
  695. except FileNotFoundError:
  696. yield src
  697. yield from iter(all_headers)
  698. else:
  699. RE_INC = re.compile(
  700. r'^(?P<target>.+?):\s+(?P<deps>.+?)$', re.MULTILINE
  701. )
  702. SPACE_TOK = '\x1B'
  703. text = deps.replace('\\\n', ' ').replace('\\ ', SPACE_TOK)
  704. for match in RE_INC.finditer(text):
  705. files = (
  706. f.replace(SPACE_TOK, ' ') for f in match.group('deps').split()
  707. )
  708. for path in files:
  709. path = os.path.abspath(path)
  710. if path.startswith(src_base):
  711. yield path
  712. def parallel_run(items: List[Command]) -> None:
  713. try:
  714. num_workers = max(2, os.cpu_count() or 1)
  715. except Exception:
  716. num_workers = 2
  717. items = list(reversed(items))
  718. workers: Dict[int, Tuple[Optional[Command], Optional['subprocess.Popen[bytes]']]] = {}
  719. failed = None
  720. num, total = 0, len(items)
  721. def wait() -> None:
  722. nonlocal failed
  723. if not workers:
  724. return
  725. pid, s = os.wait()
  726. compile_cmd, w = workers.pop(pid, (None, None))
  727. if compile_cmd is None:
  728. return
  729. if ((s & 0xff) != 0 or ((s >> 8) & 0xff) != 0):
  730. if failed is None:
  731. failed = compile_cmd
  732. elif compile_cmd.on_success is not None:
  733. compile_cmd.on_success()
  734. printed = False
  735. isatty = sys.stdout.isatty()
  736. while items and failed is None:
  737. while len(workers) < num_workers and items:
  738. compile_cmd = items.pop()
  739. num += 1
  740. if verbose:
  741. print(' '.join(compile_cmd.cmd))
  742. elif isatty:
  743. print(f'\r\x1b[K[{num}/{total}] {compile_cmd.desc}', end='') # ]]
  744. else:
  745. print(f'[{num}/{total}] {compile_cmd.desc}', flush=True)
  746. printed = True
  747. w = subprocess.Popen(compile_cmd.cmd, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
  748. workers[w.pid] = compile_cmd, w
  749. wait()
  750. while len(workers):
  751. wait()
  752. if not verbose and printed:
  753. print(' done')
  754. if failed:
  755. print(failed.desc)
  756. run_tool(list(failed.cmd))
  757. def add_builtin_fonts(args: Options) -> None:
  758. fonts_dir = os.path.join(src_base, 'fonts')
  759. os.makedirs(fonts_dir, exist_ok=True)
  760. for psname, (filename, human_name) in {
  761. 'SymbolsNFM': ('SymbolsNerdFontMono-Regular.ttf', 'Symbols NERD Font Mono')
  762. }.items():
  763. dest = os.path.join(fonts_dir, filename)
  764. if os.path.exists(dest):
  765. continue
  766. font_file = ''
  767. if is_macos:
  768. for candidate in (os.path.expanduser('~/Library/Fonts'), '/Library/Fonts', '/System/Library/Fonts', '/Network/Library/Fonts'):
  769. q = os.path.join(candidate, filename)
  770. if os.path.exists(q):
  771. font_file = q
  772. break
  773. else:
  774. lines = subprocess.check_output([
  775. 'fc-match', '--format', '%{file}\n%{postscriptname}', f'term:postscriptname={psname}', 'file', 'postscriptname']).decode().splitlines()
  776. if len(lines) != 2:
  777. raise SystemExit(f'fc-match returned unexpected output: {lines}')
  778. if lines[1] != psname:
  779. raise SystemExit(f'The font {human_name!r} was not found on your system, please install it')
  780. font_file = lines[0]
  781. if not font_file:
  782. raise SystemExit(f'The font {human_name!r} was not found on your system, please install it')
  783. print(f'Copying {human_name!r} from {font_file}')
  784. shutil.copy(font_file, dest)
  785. os.chmod(dest, 0o644)
  786. def compile_c_extension(
  787. kenv: Env,
  788. module: str,
  789. compilation_database: CompilationDatabase,
  790. sources: List[str],
  791. headers: List[str],
  792. desc_prefix: str = '',
  793. build_dsym: bool = False,
  794. ) -> None:
  795. prefix = os.path.basename(module)
  796. objects = [
  797. os.path.join(build_dir, f'{prefix}-{src.replace("/", "-")}.o')
  798. for src in sources
  799. ]
  800. for original_src, dest in zip(sources, objects):
  801. src = original_src
  802. cppflags = kenv.cppflags[:]
  803. src, include_paths, defines = get_source_specific_defines(kenv, src)
  804. if defines is not None:
  805. cppflags.extend(map(define, defines))
  806. cflags = get_source_specific_cflags(kenv, src)
  807. cmd = kenv.cc + ['-MMD'] + cppflags + [f'-I{x}' for x in include_paths] + cflags
  808. cmd += ['-c', src] + ['-o', dest]
  809. key = CompileKey(original_src, os.path.basename(dest))
  810. desc = f'Compiling {emphasis(desc_prefix + src)} ...'
  811. compilation_database.add_command(desc, cmd, partial(newer, dest, *dependecies_for(src, dest, headers)), key=key, keyfile=src)
  812. dest = os.path.join(build_dir, f'{module}.so')
  813. real_dest = f'{module}.so'
  814. link_targets.append(os.path.abspath(real_dest))
  815. os.makedirs(os.path.dirname(dest), exist_ok=True)
  816. desc = f'Linking {emphasis(desc_prefix + module)} ...'
  817. # Old versions of clang don't like -pthread being passed to the linker
  818. # Don't treat linker warnings as errors (linker generates spurious
  819. # warnings on some old systems)
  820. unsafe = {'-pthread', '-Werror', '-pedantic-errors'}
  821. linker_cflags = list(filter(lambda x: x not in unsafe, kenv.cflags))
  822. cmd = kenv.cc + linker_cflags + kenv.ldflags + objects + kenv.ldpaths + ['-o', dest]
  823. def on_success() -> None:
  824. os.rename(dest, real_dest)
  825. compilation_database.add_command(desc, cmd, partial(newer, real_dest, *objects), on_success=on_success, key=LinkKey(f'{module}.so'))
  826. if is_macos and build_dsym:
  827. real_dest = os.path.abspath(real_dest)
  828. desc = f'Linking dSYM {emphasis(desc_prefix + module)} ...'
  829. dsym = f'{real_dest}.dSYM/Contents/Resources/DWARF/{os.path.basename(real_dest)}'
  830. compilation_database.add_command(desc, ['dsymutil', real_dest], partial(newer, dsym, real_dest), key=LinkKey(dsym), is_post_link=True)
  831. def find_c_files() -> Tuple[List[str], List[str]]:
  832. ans, headers = [], []
  833. d = 'kitty'
  834. exclude = {
  835. 'fontconfig.c', 'freetype.c', 'desktop.c', 'freetype_render_ui_text.c'
  836. } if is_macos else {
  837. 'core_text.m', 'cocoa_window.m', 'macos_process_info.c'
  838. }
  839. for x in sorted(os.listdir(d)):
  840. ext = os.path.splitext(x)[1]
  841. if ext in ('.c', '.m') and os.path.basename(x) not in exclude:
  842. ans.append(os.path.join('kitty', x))
  843. elif ext == '.h':
  844. headers.append(os.path.join('kitty', x))
  845. ans.append('kitty/vt-parser-dump.c')
  846. # ringbuf
  847. ans.append('3rdparty/ringbuf/ringbuf.c')
  848. # base64
  849. ans.extend(glob.glob('3rdparty/base64/lib/arch/*/codec.c'))
  850. ans.append('3rdparty/base64/lib/tables/tables.c')
  851. ans.append('3rdparty/base64/lib/codec_choose.c')
  852. ans.append('3rdparty/base64/lib/lib.c')
  853. return ans, headers
  854. def compile_glfw(compilation_database: CompilationDatabase, build_dsym: bool = False) -> None:
  855. modules = 'cocoa' if is_macos else 'x11 wayland'
  856. for module in modules.split():
  857. try:
  858. genv = glfw.init_env(env, pkg_config, pkg_version, at_least_version, test_compile, module)
  859. except SystemExit as err:
  860. if module != 'wayland':
  861. raise
  862. print(err, file=sys.stderr)
  863. print(error('Disabling building of wayland backend'), file=sys.stderr)
  864. continue
  865. sources = [os.path.join('glfw', x) for x in genv.sources]
  866. all_headers = [os.path.join('glfw', x) for x in genv.all_headers]
  867. if module == 'wayland':
  868. try:
  869. glfw.build_wayland_protocols(genv, parallel_run, emphasis, newer, 'glfw')
  870. except SystemExit as err:
  871. print(err, file=sys.stderr)
  872. print(error('Disabling building of wayland backend'), file=sys.stderr)
  873. continue
  874. compile_c_extension(
  875. genv, f'kitty/glfw-{module}', compilation_database,
  876. sources, all_headers, desc_prefix=f'[{module}] ', build_dsym=build_dsym)
  877. def kittens_env(args: Options) -> Env:
  878. kenv = env.copy()
  879. cflags = kenv.cflags
  880. cflags.append('-pthread')
  881. cflags.append('-Ikitty')
  882. pylib = get_python_flags(args, cflags)
  883. kenv.ldpaths += pylib
  884. return kenv
  885. def compile_kittens(args: Options) -> None:
  886. kenv = kittens_env(args)
  887. def list_files(q: str) -> List[str]:
  888. return sorted(glob.glob(q))
  889. def files(
  890. kitten: str,
  891. output: str,
  892. extra_headers: Sequence[str] = (),
  893. extra_sources: Sequence[str] = (),
  894. filter_sources: Optional[Callable[[str], bool]] = None,
  895. includes: Sequence[str] = (), libraries: Sequence[str] = (),
  896. ) -> Tuple[str, List[str], List[str], str, Sequence[str], Sequence[str]]:
  897. sources = list(filter(filter_sources, list(extra_sources) + list_files(os.path.join('kittens', kitten, '*.c'))))
  898. headers = list_files(os.path.join('kittens', kitten, '*.h')) + list(extra_headers)
  899. return kitten, sources, headers, f'kittens/{kitten}/{output}', includes, libraries
  900. for kitten, sources, all_headers, dest, includes, libraries in (
  901. files('transfer', 'rsync', libraries=pkg_config('libxxhash', '--libs'), includes=pkg_config('libxxhash', '--cflags-only-I')),
  902. ):
  903. final_env = kenv.copy()
  904. final_env.cflags.extend(includes)
  905. final_env.ldpaths[:0] = list(libraries)
  906. compile_c_extension(
  907. final_env, dest, args.compilation_database, sources, all_headers + ['kitty/data-types.h'], build_dsym=args.build_dsym)
  908. def init_env_from_args(args: Options, native_optimizations: bool = False) -> None:
  909. global env
  910. env = init_env(
  911. args.debug, args.sanitize, native_optimizations, args.link_time_optimization, args.profile,
  912. args.egl_library, args.startup_notification_library, args.canberra_library, args.systemd_library, args.fontconfig_library,
  913. args.extra_logging, args.extra_include_dirs, args.ignore_compiler_warnings,
  914. args.building_arch, args.extra_library_dirs, verbose=args.verbose > 0, vcs_rev=args.vcs_rev,
  915. )
  916. @lru_cache
  917. def extract_rst_targets() -> Dict[str, Dict[str, str]]:
  918. m = runpy.run_path('docs/extract-rst-targets.py')
  919. return cast(Dict[str, Dict[str, str]], m['main']())
  920. def build_ref_map(skip_generation: bool = False) -> str:
  921. dest = 'kitty/docs_ref_map_generated.h'
  922. if not skip_generation:
  923. d = extract_rst_targets()
  924. h = 'static const char docs_ref_map[] = {\n' + textwrap.fill(', '.join(map(str, bytearray(json.dumps(d, sort_keys=True).encode('utf-8'))))) + '\n};\n'
  925. q = ''
  926. with suppress(FileNotFoundError), open(dest) as f:
  927. q = f.read()
  928. if q != h:
  929. with open(dest, 'w') as f:
  930. f.write(h)
  931. return dest
  932. def build_uniforms_header(skip_generation: bool = False) -> str:
  933. dest = 'kitty/uniforms_generated.h'
  934. if skip_generation:
  935. return dest
  936. lines = ['#include "gl.h"', '']
  937. a = lines.append
  938. uniform_names: Dict[str, Tuple[str, ...]] = {}
  939. class_names = {}
  940. function_names = {}
  941. def find_uniform_names(raw: str) -> Iterator[str]:
  942. for m in re.finditer(r'^uniform\s+\S+\s+(.+?);', raw, flags=re.MULTILINE):
  943. for x in m.group(1).split(','):
  944. yield x.strip().partition('[')[0]
  945. for x in sorted(glob.glob('kitty/*.glsl')):
  946. name = os.path.basename(x).partition('.')[0]
  947. name, sep, shader_type = name.partition('_')
  948. if not sep or shader_type not in ('fragment', 'vertex'):
  949. continue
  950. class_names[name] = f'{name.capitalize()}Uniforms'
  951. function_names[name] = f'get_uniform_locations_{name}'
  952. with open(x) as f:
  953. raw = f.read()
  954. uniform_names[name] = uniform_names.setdefault(name, ()) + tuple(find_uniform_names(raw))
  955. for name in sorted(class_names):
  956. class_name, function_name, uniforms = class_names[name], function_names[name], uniform_names[name]
  957. a(f'typedef struct {class_name} ''{')
  958. for n in uniforms:
  959. a(f' GLint {n};')
  960. a('}'f' {class_name};')
  961. a('')
  962. a(f'static inline void\n{function_name}(int program, {class_name} *ans) ''{')
  963. for n in uniforms:
  964. a(f' ans->{n} = get_uniform_location(program, "{n}");')
  965. a('}')
  966. a('')
  967. src = '\n'.join(lines)
  968. try:
  969. with open(dest) as f:
  970. current = f.read()
  971. except FileNotFoundError:
  972. current = ''
  973. if src != current:
  974. with open(dest, 'w') as f:
  975. f.write(src)
  976. return dest
  977. @lru_cache
  978. def wrapped_kittens() -> str:
  979. with open('shell-integration/ssh/kitty') as f:
  980. for line in f:
  981. if line.startswith(' wrapped_kittens="'):
  982. val = line.strip().partition('"')[2][:-1]
  983. return ' '.join(sorted(filter(None, val.split())))
  984. raise Exception('Failed to read wrapped kittens from kitty wrapper script')
  985. def build(args: Options, native_optimizations: bool = True, call_init: bool = True) -> None:
  986. if call_init:
  987. init_env_from_args(args, native_optimizations)
  988. sources, headers = find_c_files()
  989. headers.append(build_ref_map(args.skip_code_generation))
  990. headers.append(build_uniforms_header(args.skip_code_generation))
  991. compile_c_extension(
  992. kitty_env(args), 'kitty/fast_data_types', args.compilation_database, sources, headers,
  993. build_dsym=args.build_dsym,
  994. )
  995. compile_glfw(args.compilation_database, args.build_dsym)
  996. compile_kittens(args)
  997. add_builtin_fonts(args)
  998. def safe_makedirs(path: str) -> None:
  999. os.makedirs(path, exist_ok=True)
  1000. def update_go_generated_files(args: Options, kitty_exe: str) -> None:
  1001. if args.skip_code_generation:
  1002. print('Skipping generation of Go files due to command line option', flush=True)
  1003. return
  1004. # update all the various auto-generated go files, if needed
  1005. if args.verbose:
  1006. print('Updating Go generated files...', flush=True)
  1007. env = os.environ.copy()
  1008. env['ASAN_OPTIONS'] = 'detect_leaks=0'
  1009. cp = subprocess.run([kitty_exe, '+launch', os.path.join(src_base, 'gen/go_code.py')], stdout=subprocess.DEVNULL, env=env)
  1010. if cp.returncode != 0:
  1011. if os.environ.get('CI') == 'true' and cp.returncode < 0 and shutil.which('coredumpctl'):
  1012. subprocess.run(['sh', '-c', 'echo bt | coredumpctl debug'])
  1013. raise SystemExit(f'Generating go code failed with exit code: {cp.returncode}')
  1014. def parse_go_version(x: str) -> Tuple[int, int, int]:
  1015. def safe_int(x: str) -> int:
  1016. with suppress(ValueError):
  1017. return int(x)
  1018. return int(re.split(r'[-a-zA-Z]', x)[0])
  1019. ans = list(map(safe_int, x.split('.')))
  1020. while len(ans) < 3:
  1021. ans.append(0)
  1022. return ans[0], ans[1], ans[2]
  1023. def build_static_kittens(
  1024. args: Options, launcher_dir: str, destination_dir: str = '', for_freeze: bool = False,
  1025. for_platform: Optional[Tuple[str, str]] = None
  1026. ) -> str:
  1027. sys.stdout.flush()
  1028. sys.stderr.flush()
  1029. go = shutil.which('go')
  1030. if not go:
  1031. raise SystemExit('The go tool was not found on this system. Install Go')
  1032. required_go_version = subprocess.check_output([go] + 'list -f {{.GoVersion}} -m'.split(), env=dict(os.environ, GO111MODULE="on")).decode().strip()
  1033. current_go_version = subprocess.check_output([go, 'version']).decode().strip().split()[2][2:]
  1034. if parse_go_version(required_go_version) > parse_go_version(current_go_version):
  1035. raise SystemExit(f'The version of go on this system ({current_go_version}) is too old. go >= {required_go_version} is needed')
  1036. if not for_platform:
  1037. update_go_generated_files(args, os.path.join(launcher_dir, appname))
  1038. if args.skip_building_kitten:
  1039. print('Skipping building of the kitten binary because of a command line option. Build is incomplete', file=sys.stderr)
  1040. return ''
  1041. cmd = [go, 'build', '-v']
  1042. vcs_rev = args.vcs_rev or get_vcs_rev()
  1043. ld_flags: List[str] = []
  1044. binary_data_flags = [f"-X kitty.VCSRevision={vcs_rev}"]
  1045. if for_freeze:
  1046. binary_data_flags.append("-X kitty.IsFrozenBuild=true")
  1047. if for_platform:
  1048. binary_data_flags.append("-X kitty.IsStandaloneBuild=true")
  1049. if not args.debug:
  1050. ld_flags.append('-s')
  1051. ld_flags.append('-w')
  1052. cmd += ['-ldflags', ' '.join(binary_data_flags + ld_flags)]
  1053. dest = os.path.join(destination_dir or launcher_dir, 'kitten')
  1054. if for_platform:
  1055. dest += f'-{for_platform[0]}-{for_platform[1]}'
  1056. src = os.path.abspath('tools/cmd')
  1057. def run_one(dest: str) -> None:
  1058. c = cmd + ['-o', dest, src]
  1059. if args.verbose:
  1060. print(shlex.join(c))
  1061. e = os.environ.copy()
  1062. # https://github.com/kovidgoyal/kitty/issues/6051#issuecomment-1441369828
  1063. e.pop('PWD', None)
  1064. if for_platform:
  1065. e['CGO_ENABLED'] = '0'
  1066. e['GOOS'] = for_platform[0]
  1067. e['GOARCH'] = for_platform[1]
  1068. elif args.building_arch:
  1069. e['GOARCH'] = {'x86_64': 'amd64', 'arm64': 'arm64'}[args.building_arch]
  1070. cp = subprocess.run(c, env=e)
  1071. if cp.returncode != 0:
  1072. raise SystemExit(cp.returncode)
  1073. if is_macos and for_freeze and not for_platform:
  1074. adests = []
  1075. for arch in macos_universal_arches:
  1076. args.building_arch = arch
  1077. adest = dest + '-' + arch
  1078. adests.append(adest)
  1079. run_one(adest)
  1080. lipo({dest: adests})
  1081. else:
  1082. run_one(dest)
  1083. return dest
  1084. def build_static_binaries(args: Options, launcher_dir: str) -> None:
  1085. arches = 'amd64', 'arm64'
  1086. for os_, arches_ in {
  1087. 'darwin': arches, 'linux': arches + ('arm', '386'), 'freebsd': arches, 'netbsd': arches, 'openbsd': arches,
  1088. 'dragonfly': ('amd64',),
  1089. }.items():
  1090. for arch in arches_:
  1091. print('Cross compiling static kitten for:', os_, arch)
  1092. build_static_kittens(args, launcher_dir, args.dir_for_static_binaries, for_platform=(os_, arch))
  1093. @lru_cache(2)
  1094. def kitty_cli_boolean_options() -> Tuple[str, ...]:
  1095. with open(os.path.join(src_base, 'kitty/cli.py')) as f:
  1096. raw = f.read()
  1097. m = re.search(r"^\s*OPTIONS = '''(.+?)'''", raw, flags=re.MULTILINE | re.DOTALL)
  1098. assert m is not None
  1099. ans: List[str] = []
  1100. in_option: List[str] = []
  1101. prev_line_was_blank = False
  1102. for line in m.group(1).splitlines():
  1103. if in_option:
  1104. is_blank = not line.strip()
  1105. if is_blank:
  1106. if prev_line_was_blank:
  1107. in_option = []
  1108. prev_line_was_blank = is_blank
  1109. if line.startswith('type=bool-'):
  1110. ans.extend(x.lstrip('-') for x in in_option)
  1111. else:
  1112. if line.startswith('-'):
  1113. in_option = line.strip().split()
  1114. return tuple(ans)
  1115. def build_launcher(args: Options, launcher_dir: str = '.', bundle_type: str = 'source') -> None:
  1116. werror = '' if args.ignore_compiler_warnings else '-pedantic-errors -Werror'
  1117. cflags = f'-Wall {werror} -fpie'.split()
  1118. cppflags = [define(f'WRAPPED_KITTENS=" {wrapped_kittens()} "')]
  1119. libs: List[str] = []
  1120. ldflags = shlex.split(os.environ.get('LDFLAGS', ''))
  1121. if args.profile or args.sanitize:
  1122. cflags.append('-g3')
  1123. if args.sanitize:
  1124. sanitize_args = get_sanitize_args(env.cc, env.ccver)
  1125. cflags.extend(sanitize_args)
  1126. ldflags.extend(sanitize_args)
  1127. libs += ['-lasan'] if not is_macos and env.compiler_type is not CompilerType.clang else []
  1128. if args.profile:
  1129. libs.append('-lprofiler')
  1130. else:
  1131. cflags.append('-g3' if args.debug else '-O3')
  1132. if bundle_type.endswith('-freeze'):
  1133. cppflags.append('-DFOR_BUNDLE')
  1134. cppflags.append(f'-DPYVER="{sysconfig.get_python_version()}"')
  1135. cppflags.append(f'-DKITTY_LIB_DIR_NAME="{args.libdir_name}"')
  1136. elif bundle_type == 'source':
  1137. cppflags.append('-DFROM_SOURCE')
  1138. elif bundle_type == 'develop':
  1139. cppflags.append('-DFROM_SOURCE')
  1140. ph = os.path.relpath(os.environ["DEVELOP_ROOT"], '.')
  1141. cppflags.append(f'-DSET_PYTHON_HOME="{ph}"')
  1142. if not is_macos:
  1143. ldflags += ['-Wl,--disable-new-dtags', f'-Wl,-rpath,$ORIGIN/../../{ph}/lib']
  1144. if bundle_type.startswith('macos-'):
  1145. klp = '../Resources/kitty'
  1146. elif bundle_type.startswith('linux-'):
  1147. klp = '../{}/kitty'.format(args.libdir_name.strip('/'))
  1148. elif bundle_type == 'source':
  1149. klp = os.path.relpath('.', launcher_dir)
  1150. elif bundle_type == 'develop':
  1151. # make the kitty executable relocatable
  1152. klp = src_base
  1153. else:
  1154. raise SystemExit(f'Unknown bundle type: {bundle_type}')
  1155. cppflags.append(f'-DKITTY_LIB_PATH="{klp}"')
  1156. pylib = get_python_flags(args, cflags, for_main_executable=True)
  1157. cppflags += shlex.split(os.environ.get('CPPFLAGS', ''))
  1158. cflags += shlex.split(os.environ.get('CFLAGS', ''))
  1159. for path in args.extra_include_dirs:
  1160. cflags.append(f'-I{path}')
  1161. if args.building_arch:
  1162. set_arches(cflags, args.building_arch)
  1163. set_arches(ldflags, args.building_arch)
  1164. if bundle_type == 'linux-freeze':
  1165. # --disable-new-dtags prevents -rpath from generating RUNPATH instead of
  1166. # RPATH entries in the launcher. The ld dynamic linker does not search
  1167. # RUNPATH locations for transitive dependencies, unlike RPATH.
  1168. ldflags += ['-Wl,--disable-new-dtags', '-Wl,-rpath,$ORIGIN/../lib']
  1169. os.makedirs(launcher_dir, exist_ok=True)
  1170. os.makedirs(build_dir, exist_ok=True)
  1171. objects = []
  1172. cppflags.append('-DKITTY_CLI_BOOL_OPTIONS=" ' + ' '.join(kitty_cli_boolean_options()) + ' "')
  1173. cppflags.append('-DKITTY_VERSION="' + '.'.join(map(str, version)) + '"')
  1174. for src in ('kitty/launcher/main.c', 'kitty/launcher/single-instance.c'):
  1175. obj = os.path.join(build_dir, src.replace('/', '-').replace('.c', '.o'))
  1176. objects.append(obj)
  1177. cmd = env.cc + cppflags + cflags + ['-c', src, '-o', obj]
  1178. key = CompileKey(src, os.path.basename(obj))
  1179. args.compilation_database.add_command(f'Compiling {emphasis(src)} ...', cmd, partial(newer, obj, src), key=key, keyfile=src)
  1180. dest = os.path.join(launcher_dir, 'kitty')
  1181. link_targets.append(os.path.abspath(dest))
  1182. desc = f'Linking {emphasis("launcher")} ...'
  1183. cmd = env.cc + ldflags + objects + libs + pylib + ['-o', dest]
  1184. args.compilation_database.add_command(desc, cmd, partial(newer, dest, *objects), key=LinkKey('kitty'))
  1185. if args.build_dsym and is_macos:
  1186. desc = f'Linking dSYM {emphasis("launcher")} ...'
  1187. dsym = f'{dest}.dSYM/Contents/Resources/DWARF/{os.path.basename(dest)}'
  1188. args.compilation_database.add_command(desc, ['dsymutil', dest], partial(newer, dsym, dest), key=LinkKey(dsym), is_post_link=True)
  1189. args.compilation_database.build_all()
  1190. # Packaging {{{
  1191. def copy_man_pages(ddir: str) -> None:
  1192. mandir = os.path.join(ddir, 'share', 'man')
  1193. safe_makedirs(mandir)
  1194. man_levels = '15'
  1195. with suppress(FileNotFoundError):
  1196. for x in man_levels:
  1197. shutil.rmtree(os.path.join(mandir, f'man{x}'))
  1198. src = 'docs/_build/man'
  1199. if not os.path.exists(src):
  1200. raise SystemExit('''\
  1201. The kitty man pages are missing. If you are building from git then run:
  1202. make && make docs
  1203. (needs the sphinx documentation system to be installed)
  1204. ''')
  1205. for x in man_levels:
  1206. os.makedirs(os.path.join(mandir, f'man{x}'))
  1207. for y in glob.glob(os.path.join(src, f'*.{x}')):
  1208. shutil.copy2(y, os.path.join(mandir, f'man{x}'))
  1209. def copy_html_docs(ddir: str) -> None:
  1210. htmldir = os.path.join(ddir, 'share', 'doc', appname, 'html')
  1211. safe_makedirs(os.path.dirname(htmldir))
  1212. with suppress(FileNotFoundError):
  1213. shutil.rmtree(htmldir)
  1214. src = 'docs/_build/html'
  1215. if not os.path.exists(src):
  1216. raise SystemExit('''\
  1217. The kitty html docs are missing. If you are building from git then run:
  1218. make && make docs
  1219. (needs the sphinx documentation system to be installed)
  1220. ''')
  1221. shutil.copytree(src, htmldir)
  1222. def compile_python(base_path: str) -> None:
  1223. import compileall
  1224. import py_compile
  1225. for root, dirs, files in os.walk(base_path):
  1226. for f in files:
  1227. if f.rpartition('.')[-1] in ('pyc', 'pyo'):
  1228. os.remove(os.path.join(root, f))
  1229. exclude = re.compile('.*/shell-integration/ssh/bootstrap.py')
  1230. compileall.compile_dir(
  1231. base_path, rx=exclude, force=True, optimize=(0, 1, 2), quiet=1, workers=0, # type: ignore
  1232. invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH, ddir='')
  1233. def create_linux_bundle_gunk(ddir: str, args: Options) -> None:
  1234. libdir_name = args.libdir_name
  1235. base = Path(ddir)
  1236. in_src_launcher = base / (f'{libdir_name}/kitty/kitty/launcher/kitty')
  1237. launcher = base / 'bin/kitty'
  1238. skip_docs = False
  1239. if not os.path.exists('docs/_build/html'):
  1240. kitten_exe = os.path.join(os.path.dirname(str(launcher)), 'kitten')
  1241. if os.path.exists(kitten_exe):
  1242. os.environ['KITTEN_EXE_FOR_DOCS'] = kitten_exe
  1243. make = 'gmake' if is_freebsd else 'make'
  1244. run_tool([make, 'docs'])
  1245. else:
  1246. if args.skip_building_kitten:
  1247. skip_docs = True
  1248. print('WARNING: You have chosen to skip building kitten.'
  1249. ' This means docs could not be generated and will not be included in the linux package.'
  1250. ' You should build kitten and then re-run this build.', file=sys.stderr)
  1251. else:
  1252. raise SystemExit(f'kitten binary not found at: {kitten_exe}')
  1253. if not skip_docs:
  1254. copy_man_pages(ddir)
  1255. copy_html_docs(ddir)
  1256. for (icdir, ext) in {'256x256': 'png', 'scalable': 'svg'}.items():
  1257. icdir = os.path.join(ddir, 'share', 'icons', 'hicolor', icdir, 'apps')
  1258. safe_makedirs(icdir)
  1259. shutil.copy2(f'logo/kitty.{ext}', icdir)
  1260. deskdir = os.path.join(ddir, 'share', 'applications')
  1261. safe_makedirs(deskdir)
  1262. with open(os.path.join(deskdir, 'kitty.desktop'), 'w') as f:
  1263. f.write(
  1264. '''\
  1265. [Desktop Entry]
  1266. Version=1.0
  1267. Type=Application
  1268. Name=kitty
  1269. GenericName=Terminal emulator
  1270. Comment=Fast, feature-rich, GPU based terminal
  1271. TryExec=kitty
  1272. StartupNotify=true
  1273. Exec=kitty
  1274. Icon=kitty
  1275. Categories=System;TerminalEmulator;
  1276. ''')
  1277. with open(os.path.join(deskdir, 'kitty-open.desktop'), 'w') as f:
  1278. f.write(
  1279. '''\
  1280. [Desktop Entry]
  1281. Version=1.0
  1282. Type=Application
  1283. Name=kitty URL Launcher
  1284. GenericName=Terminal emulator
  1285. Comment=Open URLs with kitty
  1286. StartupNotify=true
  1287. TryExec=kitty
  1288. Exec=kitty +open %U
  1289. Icon=kitty
  1290. Categories=System;TerminalEmulator;
  1291. NoDisplay=true
  1292. MimeType=image/*;application/x-sh;application/x-shellscript;inode/directory;text/*;x-scheme-handler/kitty;x-scheme-handler/ssh;
  1293. ''')
  1294. if os.path.exists(in_src_launcher):
  1295. os.remove(in_src_launcher)
  1296. os.makedirs(os.path.dirname(in_src_launcher), exist_ok=True)
  1297. os.symlink(os.path.relpath(launcher, os.path.dirname(in_src_launcher)), in_src_launcher)
  1298. def macos_info_plist() -> bytes:
  1299. import plistlib
  1300. VERSION = '.'.join(map(str, version))
  1301. def access(what: str, verb: str = 'would like to access') -> str:
  1302. return f'A program running inside kitty {verb} {what}'
  1303. docs = [
  1304. {
  1305. 'CFBundleTypeName': 'Terminal scripts',
  1306. 'CFBundleTypeExtensions': ['command', 'sh', 'zsh', 'bash', 'fish', 'tool'],
  1307. 'CFBundleTypeIconFile': f'{appname}.icns',
  1308. 'CFBundleTypeRole': 'Editor',
  1309. },
  1310. {
  1311. 'CFBundleTypeName': 'Folders',
  1312. 'LSItemContentTypes': ['public.directory'],
  1313. 'CFBundleTypeRole': 'Editor',
  1314. 'LSHandlerRank': 'Alternate',
  1315. },
  1316. {
  1317. 'LSItemContentTypes': ['public.unix-executable'],
  1318. 'CFBundleTypeRole': 'Shell',
  1319. },
  1320. {
  1321. 'CFBundleTypeName': 'Text files',
  1322. 'LSItemContentTypes': ['public.text'],
  1323. 'CFBundleTypeRole': 'Editor',
  1324. 'LSHandlerRank': 'Alternate',
  1325. },
  1326. {
  1327. 'CFBundleTypeName': 'Image files',
  1328. 'LSItemContentTypes': ['public.image'],
  1329. 'CFBundleTypeRole': 'Viewer',
  1330. 'LSHandlerRank': 'Alternate',
  1331. },
  1332. # Allows dragging arbitrary files to kitty Dock icon, and list kitty in the Open With context menu.
  1333. {
  1334. 'CFBundleTypeName': 'All files',
  1335. 'LSItemContentTypes': ['public.archive', 'public.content', 'public.data'],
  1336. 'CFBundleTypeRole': 'Editor',
  1337. 'LSHandlerRank': 'Alternate',
  1338. },
  1339. ]
  1340. url_schemes = [
  1341. {
  1342. 'CFBundleURLName': 'File URL',
  1343. 'CFBundleURLSchemes': ['file'],
  1344. },
  1345. {
  1346. 'CFBundleURLName': 'FTP URL',
  1347. 'CFBundleURLSchemes': ['ftp', 'ftps'],
  1348. },
  1349. {
  1350. 'CFBundleURLName': 'Gemini URL',
  1351. 'CFBundleURLSchemes': ['gemini'],
  1352. },
  1353. {
  1354. 'CFBundleURLName': 'Git URL',
  1355. 'CFBundleURLSchemes': ['git'],
  1356. },
  1357. {
  1358. 'CFBundleURLName': 'Gopher URL',
  1359. 'CFBundleURLSchemes': ['gopher'],
  1360. },
  1361. {
  1362. 'CFBundleURLName': 'HTTP URL',
  1363. 'CFBundleURLSchemes': ['http', 'https'],
  1364. },
  1365. {
  1366. 'CFBundleURLName': 'IRC URL',
  1367. 'CFBundleURLSchemes': ['irc', 'irc6', 'ircs'],
  1368. },
  1369. {
  1370. 'CFBundleURLName': 'kitty URL',
  1371. 'CFBundleURLSchemes': ['kitty'],
  1372. 'LSHandlerRank': 'Owner',
  1373. 'LSIsAppleDefaultForScheme': True,
  1374. },
  1375. {
  1376. 'CFBundleURLName': 'Mail Address URL',
  1377. 'CFBundleURLSchemes': ['mailto'],
  1378. },
  1379. {
  1380. 'CFBundleURLName': 'News URL',
  1381. 'CFBundleURLSchemes': ['news', 'nntp'],
  1382. },
  1383. {
  1384. 'CFBundleURLName': 'SSH and SFTP URL',
  1385. 'CFBundleURLSchemes': ['ssh', 'sftp'],
  1386. },
  1387. {
  1388. 'CFBundleURLName': 'Telnet URL',
  1389. 'CFBundleURLSchemes': ['telnet'],
  1390. },
  1391. ]
  1392. services = [
  1393. {
  1394. 'NSMenuItem': {'default': f'New {appname} Tab Here'},
  1395. 'NSMessage': 'openTab',
  1396. 'NSRequiredContext': {'NSTextContent': 'FilePath'},
  1397. 'NSSendTypes': ['NSFilenamesPboardType', 'public.plain-text'],
  1398. },
  1399. {
  1400. 'NSMenuItem': {'default': f'New {appname} Window Here'},
  1401. 'NSMessage': 'openOSWindow',
  1402. 'NSRequiredContext': {'NSTextContent': 'FilePath'},
  1403. 'NSSendTypes': ['NSFilenamesPboardType', 'public.plain-text'],
  1404. },
  1405. {
  1406. 'NSMenuItem': {'default': f'Open with {appname}'},
  1407. 'NSMessage': 'openFileURLs',
  1408. 'NSRequiredContext': {'NSTextContent': 'FilePath'},
  1409. 'NSSendTypes': ['NSFilenamesPboardType', 'public.plain-text'],
  1410. },
  1411. ]
  1412. pl = dict(
  1413. # Naming
  1414. CFBundleName=appname,
  1415. CFBundleDisplayName=appname,
  1416. # Identification
  1417. CFBundleIdentifier=f'net.kovidgoyal.{appname}',
  1418. # Bundle Version Info
  1419. CFBundleVersion=VERSION,
  1420. CFBundleShortVersionString=VERSION,
  1421. CFBundleInfoDictionaryVersion='6.0',
  1422. NSHumanReadableCopyright=time.strftime('Copyright %Y, Kovid Goyal'),
  1423. CFBundleGetInfoString='kitty - The fast, feature-rich, GPU based terminal emulator. https://sw.kovidgoyal.net/kitty/',
  1424. # Operating System Version
  1425. LSMinimumSystemVersion='11.0.0',
  1426. # Categorization
  1427. CFBundlePackageType='APPL',
  1428. CFBundleSignature='????',
  1429. LSApplicationCategoryType='public.app-category.utilities',
  1430. # App Execution
  1431. CFBundleExecutable=appname,
  1432. LSEnvironment={'KITTY_LAUNCHED_BY_LAUNCH_SERVICES': '1'},
  1433. LSRequiresNativeExecution=True,
  1434. NSSupportsSuddenTermination=False,
  1435. # Localization
  1436. # see https://github.com/kovidgoyal/kitty/issues/1233
  1437. CFBundleDevelopmentRegion='English',
  1438. CFBundleAllowMixedLocalizations=True,
  1439. TICapsLockLanguageSwitchCapable=True,
  1440. # User Interface and Graphics
  1441. CFBundleIconFile=f'{appname}.icns',
  1442. NSHighResolutionCapable=True,
  1443. NSSupportsAutomaticGraphicsSwitching=True,
  1444. # Needed for dark mode in Mojave when linking against older SDKs
  1445. NSRequiresAquaSystemAppearance='NO',
  1446. # Document and URL Types
  1447. CFBundleDocumentTypes=docs,
  1448. CFBundleURLTypes=url_schemes,
  1449. # Services
  1450. NSServices=services,
  1451. # Calendar and Reminders
  1452. NSCalendarsUsageDescription=access('your calendar data.'),
  1453. NSRemindersUsageDescription=access('your reminders.'),
  1454. # Camera and Microphone
  1455. NSCameraUsageDescription=access('the camera.'),
  1456. NSMicrophoneUsageDescription=access('the microphone.'),
  1457. # Contacts
  1458. NSContactsUsageDescription=access('your contacts.'),
  1459. # Location
  1460. NSLocationUsageDescription=access('your location information.'),
  1461. NSLocationTemporaryUsageDescriptionDictionary=access('your location temporarily.'),
  1462. # Motion
  1463. NSMotionUsageDescription=access('motion data.'),
  1464. # Networking
  1465. NSLocalNetworkUsageDescription=access('local network.'),
  1466. # Photos
  1467. NSPhotoLibraryUsageDescription=access('your photo library.'),
  1468. # Scripting
  1469. NSAppleScriptEnabled=False,
  1470. # Security
  1471. NSAppleEventsUsageDescription=access('AppleScript.'),
  1472. NSSystemAdministrationUsageDescription=access('elevated privileges.', 'requires'),
  1473. NSBluetoothAlwaysUsageDescription=access('Bluetooth.'),
  1474. # Speech
  1475. NSSpeechRecognitionUsageDescription=access('speech recognition.'),
  1476. )
  1477. return plistlib.dumps(pl)
  1478. def create_macos_app_icon(where: str = 'Resources') -> None:
  1479. iconset_dir = os.path.abspath(os.path.join('logo', f'{appname}.iconset'))
  1480. icns_dir = os.path.join(where, f'{appname}.icns')
  1481. try:
  1482. subprocess.check_call([
  1483. 'iconutil', '-c', 'icns', iconset_dir, '-o', icns_dir
  1484. ])
  1485. except FileNotFoundError:
  1486. print(f'{error("iconutil not found")}, using png2icns (without retina support) to convert the logo', file=sys.stderr)
  1487. subprocess.check_call([
  1488. 'png2icns', icns_dir
  1489. ] + [os.path.join(iconset_dir, logo) for logo in [
  1490. # png2icns does not support retina icons, so only pass the non-retina icons
  1491. 'icon_16x16.png',
  1492. 'icon_32x32.png',
  1493. 'icon_128x128.png',
  1494. 'icon_256x256.png',
  1495. 'icon_512x512.png',
  1496. ]])
  1497. def create_minimal_macos_bundle(args: Options, launcher_dir: str, relocate: bool = False) -> None:
  1498. kapp = os.path.join(launcher_dir, 'kitty.app')
  1499. if os.path.exists(kapp):
  1500. shutil.rmtree(kapp)
  1501. bin_dir = os.path.join(kapp, 'Contents/MacOS')
  1502. resources_dir = os.path.join(kapp, 'Contents/Resources')
  1503. os.makedirs(resources_dir)
  1504. os.makedirs(bin_dir)
  1505. with open(os.path.join(kapp, 'Contents/Info.plist'), 'wb') as f:
  1506. f.write(macos_info_plist())
  1507. if relocate:
  1508. shutil.copy2(os.path.join(launcher_dir, "kitty"), bin_dir)
  1509. shutil.copy2(os.path.join(launcher_dir, "kitten"), bin_dir)
  1510. else:
  1511. build_launcher(args, bin_dir)
  1512. build_static_kittens(args, launcher_dir=bin_dir)
  1513. kitty_exe = os.path.join(launcher_dir, appname)
  1514. with suppress(FileNotFoundError):
  1515. os.remove(kitty_exe)
  1516. os.symlink(os.path.join(os.path.relpath(bin_dir, launcher_dir), appname), kitty_exe)
  1517. create_macos_app_icon(resources_dir)
  1518. def create_macos_bundle_gunk(dest: str, for_freeze: bool, args: Options) -> str:
  1519. ddir = Path(dest)
  1520. os.mkdir(ddir / 'Contents')
  1521. with open(ddir / 'Contents/Info.plist', 'wb') as fp:
  1522. fp.write(macos_info_plist())
  1523. copy_man_pages(str(ddir))
  1524. copy_html_docs(str(ddir))
  1525. os.rename(ddir / 'share', ddir / 'Contents/Resources')
  1526. os.rename(ddir / 'bin', ddir / 'Contents/MacOS')
  1527. os.rename(ddir / 'lib', ddir / 'Contents/Frameworks')
  1528. os.rename(ddir / 'Contents/Frameworks/kitty', ddir / 'Contents/Resources/kitty')
  1529. kitty_exe = ddir / 'Contents/MacOS/kitty'
  1530. in_src_launcher = ddir / 'Contents/Resources/kitty/kitty/launcher/kitty'
  1531. if os.path.exists(in_src_launcher):
  1532. os.remove(in_src_launcher)
  1533. os.makedirs(os.path.dirname(in_src_launcher), exist_ok=True)
  1534. os.symlink(os.path.relpath(kitty_exe, os.path.dirname(in_src_launcher)), in_src_launcher)
  1535. create_macos_app_icon(os.path.join(ddir, 'Contents', 'Resources'))
  1536. if not for_freeze:
  1537. kitten_exe = build_static_kittens(args, launcher_dir=os.path.dirname(kitty_exe))
  1538. if not kitten_exe:
  1539. raise SystemExit('kitten not built cannot create macOS bundle')
  1540. os.symlink(os.path.relpath(kitten_exe, os.path.dirname(in_src_launcher)),
  1541. os.path.join(os.path.dirname(in_src_launcher), os.path.basename(kitten_exe)))
  1542. return str(kitty_exe)
  1543. def package(args: Options, bundle_type: str, do_build_all: bool = True) -> None:
  1544. ddir = args.prefix
  1545. for_freeze = bundle_type.endswith('-freeze')
  1546. if bundle_type == 'linux-freeze':
  1547. args.libdir_name = 'lib'
  1548. libdir = os.path.join(ddir, args.libdir_name.strip('/'), 'kitty')
  1549. if os.path.exists(libdir):
  1550. shutil.rmtree(libdir)
  1551. launcher_dir = os.path.join(ddir, 'bin')
  1552. safe_makedirs(launcher_dir)
  1553. if for_freeze: # freeze launcher is built separately
  1554. if do_build_all:
  1555. args.compilation_database.build_all()
  1556. else:
  1557. build_launcher(args, launcher_dir, bundle_type)
  1558. os.makedirs(os.path.join(libdir, 'logo'))
  1559. build_terminfo = runpy.run_path('build-terminfo', run_name='import_build')
  1560. for x in (libdir, os.path.join(ddir, 'share')):
  1561. odir = os.path.join(x, 'terminfo')
  1562. safe_makedirs(odir)
  1563. build_terminfo['compile_terminfo'](odir)
  1564. shutil.copy2('terminfo/kitty.terminfo', os.path.join(libdir, 'terminfo'))
  1565. shutil.copy2('terminfo/kitty.termcap', os.path.join(libdir, 'terminfo'))
  1566. shutil.copy2('__main__.py', libdir)
  1567. shutil.copy2('logo/kitty-128.png', os.path.join(libdir, 'logo'))
  1568. shutil.copy2('logo/kitty.png', os.path.join(libdir, 'logo'))
  1569. shutil.copy2('logo/beam-cursor.png', os.path.join(libdir, 'logo'))
  1570. shutil.copy2('logo/beam-cursor@2x.png', os.path.join(libdir, 'logo'))
  1571. shutil.copytree('shell-integration', os.path.join(libdir, 'shell-integration'), dirs_exist_ok=True)
  1572. shutil.copytree('fonts', os.path.join(libdir, 'fonts'), dirs_exist_ok=True)
  1573. allowed_extensions = frozenset('py glsl so'.split())
  1574. def src_ignore(parent: str, entries: Iterable[str]) -> List[str]:
  1575. return [
  1576. x for x in entries
  1577. if '.' in x and x.rpartition('.')[2] not in
  1578. allowed_extensions
  1579. ]
  1580. shutil.copytree('kitty', os.path.join(libdir, 'kitty'), ignore=src_ignore)
  1581. shutil.copytree('kittens', os.path.join(libdir, 'kittens'), ignore=src_ignore)
  1582. if for_freeze:
  1583. shutil.copytree('kitty_tests', os.path.join(libdir, 'kitty_tests'))
  1584. def repl(name: str, raw: str, defval: Union[str, float, FrozenSet[str]], val: Union[str, float, FrozenSet[str]]) -> str:
  1585. if defval == val:
  1586. return raw
  1587. tname = type(defval).__name__
  1588. if tname == 'frozenset':
  1589. tname = 'typing.FrozenSet[str]'
  1590. prefix = f'{name}: {tname} ='
  1591. nraw = raw.replace(f'{prefix} {defval!r}', f'{prefix} {val!r}', 1)
  1592. if nraw == raw:
  1593. raise SystemExit(f'Failed to change the value of {name}')
  1594. return nraw
  1595. with open(os.path.join(libdir, 'kitty/options/types.py'), 'r+', encoding='utf-8') as f:
  1596. oraw = raw = f.read()
  1597. raw = repl('update_check_interval', raw, Options.update_check_interval, args.update_check_interval)
  1598. raw = repl('shell_integration', raw, frozenset(Options.shell_integration.split()), frozenset(args.shell_integration.split()))
  1599. if raw != oraw:
  1600. f.seek(0), f.truncate(), f.write(raw)
  1601. compile_python(libdir)
  1602. def should_be_executable(path: str) -> bool:
  1603. if path.endswith('.so'):
  1604. return True
  1605. q = path.split(os.sep)[-2:]
  1606. if len(q) == 2 and q[0] == 'ssh' and q[1] in ('kitty', 'kitten'):
  1607. return True
  1608. return False
  1609. for root, dirs, files in os.walk(libdir):
  1610. for f_ in files:
  1611. path = os.path.join(root, f_)
  1612. os.chmod(path, 0o755 if should_be_executable(path) else 0o644)
  1613. if not for_freeze and not bundle_type.startswith('macos-'):
  1614. build_static_kittens(args, launcher_dir=launcher_dir)
  1615. if not is_macos:
  1616. create_linux_bundle_gunk(ddir, args)
  1617. if bundle_type.startswith('macos-'):
  1618. create_macos_bundle_gunk(ddir, for_freeze, args)
  1619. # }}}
  1620. def clean_launcher_dir(launcher_dir: str) -> None:
  1621. for x in glob.glob(os.path.join(launcher_dir, 'kitt*')):
  1622. if os.path.isdir(x):
  1623. shutil.rmtree(x)
  1624. else:
  1625. os.remove(x)
  1626. def clean(for_cross_compile: bool = False) -> None:
  1627. def safe_remove(*entries: str) -> None:
  1628. for x in entries:
  1629. if os.path.exists(x):
  1630. if os.path.isdir(x):
  1631. shutil.rmtree(x)
  1632. else:
  1633. os.unlink(x)
  1634. safe_remove(
  1635. 'build', 'compile_commands.json', 'link_commands.json',
  1636. 'linux-package', 'kitty.app', 'asan-launcher',
  1637. 'kitty-profile') # no fonts as that is not generated by build
  1638. if not for_cross_compile:
  1639. safe_remove('docs/generated')
  1640. clean_launcher_dir('kitty/launcher')
  1641. def excluded(root: str, d: str) -> bool:
  1642. q = os.path.relpath(os.path.join(root, d), src_base).replace(os.sep, '/')
  1643. return q in ('.git', 'bypy/b', 'dependencies')
  1644. def is_generated(f: str) -> bool:
  1645. e = f.endswith
  1646. return (
  1647. e('_generated.h') or e('_generated.go') or e('_generated.bin') or
  1648. e('_generated.s') or e('_generated_test.s') or e('_generated_test.go')
  1649. )
  1650. for root, dirs, files in os.walk(src_base, topdown=True):
  1651. dirs[:] = [d for d in dirs if not excluded(root, d)]
  1652. remove_dirs = {d for d in dirs if d == '__pycache__' or d.endswith('.dSYM')}
  1653. for d in remove_dirs:
  1654. shutil.rmtree(os.path.join(root, d))
  1655. dirs.remove(d)
  1656. for f in files:
  1657. ext = f.rpartition('.')[-1]
  1658. if ext in ('so', 'dylib', 'pyc', 'pyo') or (not for_cross_compile and is_generated(f)):
  1659. os.unlink(os.path.join(root, f))
  1660. for x in glob.glob('glfw/wayland-*-protocol.[ch]'):
  1661. os.unlink(x)
  1662. for x in glob.glob('kittens/*'):
  1663. if os.path.isdir(x) and not os.path.exists(os.path.join(x, '__init__.py')):
  1664. shutil.rmtree(x)
  1665. subprocess.check_call(['go', 'clean', '-cache', '-testcache', '-modcache', '-fuzzcache'])
  1666. def option_parser() -> argparse.ArgumentParser: # {{{
  1667. p = argparse.ArgumentParser()
  1668. p.add_argument(
  1669. 'action',
  1670. nargs='?',
  1671. default=Options.action,
  1672. choices=('build',
  1673. 'test',
  1674. 'develop',
  1675. 'linux-package',
  1676. 'kitty.app',
  1677. 'linux-freeze',
  1678. 'macos-freeze',
  1679. 'build-launcher',
  1680. 'build-frozen-launcher',
  1681. 'build-frozen-tools',
  1682. 'clean',
  1683. 'export-ci-bundles',
  1684. 'build-dep',
  1685. 'build-static-binaries',
  1686. ),
  1687. help='Action to perform (default is build)'
  1688. )
  1689. p.add_argument(
  1690. '--debug',
  1691. default=Options.debug,
  1692. action='store_true',
  1693. help='Build extension modules with debugging symbols'
  1694. )
  1695. p.add_argument(
  1696. '-v', '--verbose',
  1697. default=Options.verbose,
  1698. action='count',
  1699. help='Be verbose'
  1700. )
  1701. p.add_argument(
  1702. '--sanitize',
  1703. default=Options.sanitize,
  1704. action='store_true',
  1705. help='Turn on sanitization to detect memory access errors and undefined behavior. This is a big performance hit.'
  1706. )
  1707. p.add_argument(
  1708. '--prefix',
  1709. default=Options.prefix,
  1710. help='Where to create the linux package'
  1711. )
  1712. p.add_argument(
  1713. '--dir-for-static-binaries',
  1714. default=Options.dir_for_static_binaries,
  1715. help='Where to create the static kitten binary'
  1716. )
  1717. p.add_argument(
  1718. '--skip-code-generation',
  1719. default=Options.skip_code_generation,
  1720. action='store_true',
  1721. help='Do not create the *_generated.* source files. This is useful if they'
  1722. ' have already been generated by a previous build, for example during a two-stage cross compilation.'
  1723. )
  1724. p.add_argument(
  1725. '--skip-building-kitten',
  1726. default=Options.skip_building_kitten,
  1727. action='store_true',
  1728. help='Do not build the kitten binary. Useful if you want to build it separately.'
  1729. )
  1730. p.add_argument(
  1731. '--clean-for-cross-compile',
  1732. default=Options.clean_for_cross_compile,
  1733. action='store_true',
  1734. help='Do not clean generated Go source files. Useful for cross-compilation.'
  1735. )
  1736. p.add_argument(
  1737. '--python-compiler-flags', default=Options.python_compiler_flags,
  1738. help='Compiler flags for compiling against Python. Typically include directives. If not set'
  1739. ' the Python used to run setup.py is queried for these.'
  1740. )
  1741. p.add_argument(
  1742. '--python-linker-flags', default=Options.python_linker_flags,
  1743. help='Linker flags for linking against Python. Typically dynamic library names and search paths directives. If not set'
  1744. ' the Python used to run setup.py is queried for these.'
  1745. )
  1746. p.add_argument(
  1747. '--full',
  1748. dest='incremental',
  1749. default=Options.incremental,
  1750. action='store_false',
  1751. help='Do a full build, even for unchanged files'
  1752. )
  1753. p.add_argument(
  1754. '--profile',
  1755. default=Options.profile,
  1756. action='store_true',
  1757. help='Use the -pg compile flag to add profiling information'
  1758. )
  1759. p.add_argument(
  1760. '--libdir-name',
  1761. default=Options.libdir_name,
  1762. help='The name of the directory inside --prefix in which to store compiled files. Defaults to "lib"'
  1763. )
  1764. p.add_argument(
  1765. '--vcs-rev', default='',
  1766. help='The VCS revision to embed in the binary. The default is to read it from the .git directory when present.'
  1767. )
  1768. p.add_argument(
  1769. '--extra-logging',
  1770. action='append',
  1771. default=Options.extra_logging,
  1772. choices=('event-loop',),
  1773. help='Turn on extra logging for debugging in this build. Can be specified multiple times, to turn'
  1774. ' on different types of logging.'
  1775. )
  1776. p.add_argument(
  1777. '--extra-include-dirs', '-I',
  1778. action='append',
  1779. default=Options.extra_include_dirs,
  1780. help='Extra include directories to use while compiling'
  1781. )
  1782. p.add_argument(
  1783. '--extra-library-dirs', '-L',
  1784. action='append',
  1785. default=Options.extra_library_dirs,
  1786. help='Extra library directories to use while linking'
  1787. )
  1788. p.add_argument(
  1789. '--update-check-interval',
  1790. type=float,
  1791. default=Options.update_check_interval,
  1792. help='When building a package, the default value for the update_check_interval setting will'
  1793. ' be set to this number. Use zero to disable update checking.'
  1794. )
  1795. p.add_argument(
  1796. '--shell-integration',
  1797. type=str,
  1798. default=Options.shell_integration,
  1799. help='When building a package, the default value for the shell_integration setting will'
  1800. ' be set to this. Use "enabled no-rc" if you intend to install the shell integration scripts system wide.'
  1801. )
  1802. p.add_argument(
  1803. '--egl-library',
  1804. type=str,
  1805. default=Options.egl_library,
  1806. help='The filename argument passed to dlopen for libEGL.'
  1807. ' This can be used to change the name of the loaded library or specify an absolute path.'
  1808. )
  1809. p.add_argument(
  1810. '--startup-notification-library',
  1811. type=str,
  1812. default=Options.startup_notification_library,
  1813. help='The filename argument passed to dlopen for libstartup-notification-1.'
  1814. ' This can be used to change the name of the loaded library or specify an absolute path.'
  1815. )
  1816. p.add_argument(
  1817. '--canberra-library',
  1818. type=str,
  1819. default=Options.canberra_library,
  1820. help='The filename argument passed to dlopen for libcanberra.'
  1821. ' This can be used to change the name of the loaded library or specify an absolute path.'
  1822. )
  1823. p.add_argument(
  1824. '--systemd-library',
  1825. type=str,
  1826. default=Options.systemd_library,
  1827. help='The filename argument passed to dlopen for libsystemd.'
  1828. ' This can be used to change the name of the loaded library or specify an absolute path.'
  1829. )
  1830. p.add_argument(
  1831. '--fontconfig-library',
  1832. type=str,
  1833. default=Options.fontconfig_library,
  1834. help='The filename argument passed to dlopen for libfontconfig.'
  1835. ' This can be used to change the name of the loaded library or specify an absolute path.'
  1836. )
  1837. p.add_argument(
  1838. '--disable-link-time-optimization',
  1839. dest='link_time_optimization',
  1840. default=Options.link_time_optimization,
  1841. action='store_false',
  1842. help='Turn off Link Time Optimization (LTO).'
  1843. )
  1844. p.add_argument(
  1845. '--ignore-compiler-warnings',
  1846. default=Options.ignore_compiler_warnings, action='store_true',
  1847. help='Ignore any warnings from the compiler while building'
  1848. )
  1849. p.add_argument(
  1850. '--build-dSYM', dest='build_dsym',
  1851. default=Options.build_dsym, action='store_true',
  1852. help='Build the dSYM bundle on macOS, ignored on other platforms'
  1853. )
  1854. return p
  1855. # }}}
  1856. def build_dep() -> None:
  1857. class Options:
  1858. platform: str = 'all'
  1859. deps: List[str] = []
  1860. p = argparse.ArgumentParser(prog=f'{sys.argv[0]} build-dep', description='Build dependencies for the kitty binary packages')
  1861. p.add_argument(
  1862. '--platform',
  1863. default=Options.platform,
  1864. choices='all macos linux linux-arm64 linux-64'.split(),
  1865. help='Platforms to build the dep for'
  1866. )
  1867. p.add_argument(
  1868. 'deps',
  1869. nargs='*',
  1870. default=Options.deps,
  1871. help='Names of the dependencies, if none provided, build all'
  1872. )
  1873. args = p.parse_args(sys.argv[2:], namespace=Options())
  1874. linux_platforms = [
  1875. ['linux', '--arch=64'],
  1876. ['linux', '--arch=arm64'],
  1877. ]
  1878. if args.platform == 'all':
  1879. platforms = linux_platforms + [['macos']]
  1880. elif args.platform == 'linux':
  1881. platforms = linux_platforms
  1882. elif args.platform == 'macos':
  1883. platforms = [['macos']]
  1884. elif '-' in args.platform:
  1885. parts = args.platform.split('-')
  1886. platforms = [[parts[0], f'--arch={parts[1]}']]
  1887. else:
  1888. raise SystemExit(f'Unknown platform: {args.platform}')
  1889. base = [sys.executable, '../bypy']
  1890. for pf in platforms:
  1891. cmd = base + pf + ['dependencies'] + args.deps
  1892. run_tool(cmd)
  1893. def lipo(target_map: Dict[str, List[str]]) -> None:
  1894. print(f'Using lipo to generate {len(target_map)} universal binaries...')
  1895. for dest, inputs in target_map.items():
  1896. cmd = ['lipo', '-create', '-output', dest] + inputs
  1897. subprocess.check_call(cmd)
  1898. for x in inputs:
  1899. os.remove(x)
  1900. def macos_freeze(args: Options, launcher_dir: str, only_frozen_launcher: bool = False) -> None:
  1901. global build_dir
  1902. # Need to build a universal binary in two stages
  1903. orig_build_dir = build_dir
  1904. link_target_map: Dict[str, List[str]] = {}
  1905. bundle_type = 'macos-freeze'
  1906. for arch in macos_universal_arches:
  1907. args.building_arch = arch
  1908. build_dir = os.path.join(orig_build_dir, arch)
  1909. os.makedirs(build_dir, exist_ok=True)
  1910. print('Building for arch:', arch, 'in', build_dir)
  1911. if arch is not macos_universal_arches[0]:
  1912. args.skip_code_generation = True # cant run kitty as its not a native arch
  1913. link_targets.clear()
  1914. with CompilationDatabase() as cdb:
  1915. args.compilation_database = cdb
  1916. init_env_from_args(args, native_optimizations=False)
  1917. if only_frozen_launcher:
  1918. build_launcher(args, launcher_dir=launcher_dir, bundle_type=bundle_type)
  1919. else:
  1920. build_launcher(args, launcher_dir=launcher_dir)
  1921. build(args, native_optimizations=False, call_init=False)
  1922. cdb.build_all()
  1923. for x in link_targets:
  1924. arch_specific = x + '-' + arch
  1925. link_target_map.setdefault(x, []).append(arch_specific)
  1926. os.rename(x, arch_specific)
  1927. build_dir = orig_build_dir
  1928. lipo(link_target_map)
  1929. if not only_frozen_launcher:
  1930. package(args, bundle_type=bundle_type, do_build_all=False)
  1931. def do_build(args: Options) -> None:
  1932. launcher_dir = 'kitty/launcher'
  1933. if args.action == 'test':
  1934. texe = os.path.abspath(os.path.join(launcher_dir, 'kitty'))
  1935. os.execl(texe, texe, '+launch', 'test.py')
  1936. if args.action == 'clean':
  1937. clean(for_cross_compile=args.clean_for_cross_compile)
  1938. return
  1939. if args.action == 'macos-freeze':
  1940. return macos_freeze(args, launcher_dir)
  1941. if args.action == 'build-frozen-launcher' and is_macos:
  1942. launcher_dir=os.path.join(args.prefix, 'bin')
  1943. return macos_freeze(args, launcher_dir, only_frozen_launcher=True)
  1944. with CompilationDatabase(args.incremental) as cdb:
  1945. args.compilation_database = cdb
  1946. if args.action == 'build':
  1947. build(args)
  1948. if is_macos:
  1949. create_minimal_macos_bundle(args, launcher_dir)
  1950. else:
  1951. build_launcher(args, launcher_dir=launcher_dir)
  1952. build_static_kittens(args, launcher_dir=launcher_dir)
  1953. elif args.action == 'develop':
  1954. build(args)
  1955. build_launcher(args, launcher_dir=launcher_dir, bundle_type='develop')
  1956. build_static_kittens(args, launcher_dir=launcher_dir)
  1957. if is_macos:
  1958. create_minimal_macos_bundle(args, launcher_dir, relocate=True)
  1959. elif args.action == 'build-launcher':
  1960. init_env_from_args(args, False)
  1961. build_launcher(args, launcher_dir=launcher_dir)
  1962. build_static_kittens(args, launcher_dir=launcher_dir)
  1963. elif args.action == 'build-frozen-launcher':
  1964. init_env_from_args(args, False)
  1965. bundle_type = ('macos' if is_macos else 'linux') + '-freeze'
  1966. build_launcher(args, launcher_dir=os.path.join(args.prefix, 'bin'), bundle_type=bundle_type)
  1967. elif args.action == 'build-frozen-tools':
  1968. build_static_kittens(args, launcher_dir=args.prefix, for_freeze=True)
  1969. elif args.action == 'linux-package':
  1970. build(args, native_optimizations=False)
  1971. package(args, bundle_type='linux-package')
  1972. elif args.action == 'linux-freeze':
  1973. build(args, native_optimizations=False)
  1974. package(args, bundle_type='linux-freeze')
  1975. elif args.action == 'kitty.app':
  1976. args.prefix = 'kitty.app'
  1977. if os.path.exists(args.prefix):
  1978. shutil.rmtree(args.prefix)
  1979. build(args)
  1980. package(args, bundle_type='macos-package')
  1981. print('kitty.app successfully built!')
  1982. elif args.action == 'export-ci-bundles':
  1983. cmd = [sys.executable, '../bypy', 'export', 'download.calibre-ebook.com:/srv/download/ci/kitty']
  1984. subprocess.check_call(cmd + ['linux'])
  1985. subprocess.check_call(cmd + ['macos'])
  1986. elif args.action == 'build-static-binaries':
  1987. build_static_binaries(args, launcher_dir)
  1988. def main() -> None:
  1989. global verbose, build_dir
  1990. if len(sys.argv) > 1 and sys.argv[1] == 'build-dep':
  1991. return build_dep()
  1992. args = option_parser().parse_args(namespace=Options())
  1993. verbose = args.verbose > 0
  1994. args.prefix = os.path.abspath(args.prefix)
  1995. os.chdir(src_base)
  1996. os.makedirs(build_dir, exist_ok=True)
  1997. do_build(args)
  1998. if __name__ == '__main__':
  1999. main()