setup.py 79 KB

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