setup.py 84 KB

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