setup.py 84 KB

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