setup.py 84 KB

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