methods.py 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685
  1. import contextlib
  2. import glob
  3. import os
  4. import re
  5. import subprocess
  6. import sys
  7. from collections import OrderedDict
  8. from enum import Enum
  9. from io import StringIO, TextIOWrapper
  10. from pathlib import Path
  11. from typing import Generator, List, Optional, Union
  12. # Get the "Godot" folder name ahead of time
  13. base_folder_path = str(os.path.abspath(Path(__file__).parent)) + "/"
  14. base_folder_only = os.path.basename(os.path.normpath(base_folder_path))
  15. # Listing all the folders we have converted
  16. # for SCU in scu_builders.py
  17. _scu_folders = set()
  18. # Colors are disabled in non-TTY environments such as pipes. This means
  19. # that if output is redirected to a file, it won't contain color codes.
  20. # Colors are always enabled on continuous integration.
  21. _colorize = bool(sys.stdout.isatty() or os.environ.get("CI"))
  22. def set_scu_folders(scu_folders):
  23. global _scu_folders
  24. _scu_folders = scu_folders
  25. class ANSI(Enum):
  26. """
  27. Enum class for adding ansi colorcodes directly into strings.
  28. Automatically converts values to strings representing their
  29. internal value, or an empty string in a non-colorized scope.
  30. """
  31. RESET = "\x1b[0m"
  32. BOLD = "\x1b[1m"
  33. ITALIC = "\x1b[3m"
  34. UNDERLINE = "\x1b[4m"
  35. STRIKETHROUGH = "\x1b[9m"
  36. REGULAR = "\x1b[22;23;24;29m"
  37. BLACK = "\x1b[30m"
  38. RED = "\x1b[31m"
  39. GREEN = "\x1b[32m"
  40. YELLOW = "\x1b[33m"
  41. BLUE = "\x1b[34m"
  42. MAGENTA = "\x1b[35m"
  43. CYAN = "\x1b[36m"
  44. WHITE = "\x1b[37m"
  45. PURPLE = "\x1b[38;5;93m"
  46. PINK = "\x1b[38;5;206m"
  47. ORANGE = "\x1b[38;5;214m"
  48. GRAY = "\x1b[38;5;244m"
  49. def __str__(self) -> str:
  50. global _colorize
  51. return str(self.value) if _colorize else ""
  52. def print_warning(*values: object) -> None:
  53. """Prints a warning message with formatting."""
  54. print(f"{ANSI.YELLOW}{ANSI.BOLD}WARNING:{ANSI.REGULAR}", *values, ANSI.RESET, file=sys.stderr)
  55. def print_error(*values: object) -> None:
  56. """Prints an error message with formatting."""
  57. print(f"{ANSI.RED}{ANSI.BOLD}ERROR:{ANSI.REGULAR}", *values, ANSI.RESET, file=sys.stderr)
  58. def add_source_files_orig(self, sources, files, allow_gen=False):
  59. # Convert string to list of absolute paths (including expanding wildcard)
  60. if isinstance(files, (str, bytes)):
  61. # Keep SCons project-absolute path as they are (no wildcard support)
  62. if files.startswith("#"):
  63. if "*" in files:
  64. print_error("Wildcards can't be expanded in SCons project-absolute path: '{}'".format(files))
  65. return
  66. files = [files]
  67. else:
  68. # Exclude .gen.cpp files from globbing, to avoid including obsolete ones.
  69. # They should instead be added manually.
  70. skip_gen_cpp = "*" in files
  71. dir_path = self.Dir(".").abspath
  72. files = sorted(glob.glob(dir_path + "/" + files))
  73. if skip_gen_cpp and not allow_gen:
  74. files = [f for f in files if not f.endswith(".gen.cpp")]
  75. # Add each path as compiled Object following environment (self) configuration
  76. for path in files:
  77. obj = self.Object(path)
  78. if obj in sources:
  79. print_warning('Object "{}" already included in environment sources.'.format(obj))
  80. continue
  81. sources.append(obj)
  82. # The section name is used for checking
  83. # the hash table to see whether the folder
  84. # is included in the SCU build.
  85. # It will be something like "core/math".
  86. def _find_scu_section_name(subdir):
  87. section_path = os.path.abspath(subdir) + "/"
  88. folders = []
  89. folder = ""
  90. for i in range(8):
  91. folder = os.path.dirname(section_path)
  92. folder = os.path.basename(folder)
  93. if folder == base_folder_only:
  94. break
  95. folders += [folder]
  96. section_path += "../"
  97. section_path = os.path.abspath(section_path) + "/"
  98. section_name = ""
  99. for n in range(len(folders)):
  100. # section_name += folders[len(folders) - n - 1] + " "
  101. section_name += folders[len(folders) - n - 1]
  102. if n != (len(folders) - 1):
  103. section_name += "/"
  104. return section_name
  105. def add_source_files_scu(self, sources, files, allow_gen=False):
  106. if self["scu_build"] and isinstance(files, str):
  107. if "*." not in files:
  108. return False
  109. # If the files are in a subdirectory, we want to create the scu gen
  110. # files inside this subdirectory.
  111. subdir = os.path.dirname(files)
  112. if subdir != "":
  113. subdir += "/"
  114. section_name = _find_scu_section_name(subdir)
  115. # if the section name is in the hash table?
  116. # i.e. is it part of the SCU build?
  117. global _scu_folders
  118. if section_name not in (_scu_folders):
  119. return False
  120. # Add all the gen.cpp files in the SCU directory
  121. add_source_files_orig(self, sources, subdir + "scu/scu_*.gen.cpp", True)
  122. return True
  123. return False
  124. # Either builds the folder using the SCU system,
  125. # or reverts to regular build.
  126. def add_source_files(self, sources, files, allow_gen=False):
  127. if not add_source_files_scu(self, sources, files, allow_gen):
  128. # Wraps the original function when scu build is not active.
  129. add_source_files_orig(self, sources, files, allow_gen)
  130. return False
  131. return True
  132. def disable_warnings(self):
  133. # 'self' is the environment
  134. if self.msvc:
  135. # We have to remove existing warning level defines before appending /w,
  136. # otherwise we get: "warning D9025 : overriding '/W3' with '/w'"
  137. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  138. self["CFLAGS"] = [x for x in self["CFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  139. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  140. self.AppendUnique(CCFLAGS=["/w"])
  141. else:
  142. self.AppendUnique(CCFLAGS=["-w"])
  143. def force_optimization_on_debug(self):
  144. # 'self' is the environment
  145. if self["target"] == "template_release":
  146. return
  147. if self.msvc:
  148. # We have to remove existing optimization level defines before appending /O2,
  149. # otherwise we get: "warning D9025 : overriding '/0d' with '/02'"
  150. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not x.startswith("/O")]
  151. self["CFLAGS"] = [x for x in self["CFLAGS"] if not x.startswith("/O")]
  152. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not x.startswith("/O")]
  153. self.AppendUnique(CCFLAGS=["/O2"])
  154. else:
  155. self.AppendUnique(CCFLAGS=["-O3"])
  156. def add_module_version_string(self, s):
  157. self.module_version_string += "." + s
  158. def get_version_info(module_version_string="", silent=False):
  159. build_name = "custom_build"
  160. if os.getenv("BUILD_NAME") is not None:
  161. build_name = str(os.getenv("BUILD_NAME"))
  162. if not silent:
  163. print(f"Using custom build name: '{build_name}'.")
  164. import version
  165. version_info = {
  166. "short_name": str(version.short_name),
  167. "name": str(version.name),
  168. "major": int(version.major),
  169. "minor": int(version.minor),
  170. "patch": int(version.patch),
  171. "status": str(version.status),
  172. "build": str(build_name),
  173. "module_config": str(version.module_config) + module_version_string,
  174. "website": str(version.website),
  175. "docs_branch": str(version.docs),
  176. }
  177. # For dev snapshots (alpha, beta, RC, etc.) we do not commit status change to Git,
  178. # so this define provides a way to override it without having to modify the source.
  179. if os.getenv("GODOT_VERSION_STATUS") is not None:
  180. version_info["status"] = str(os.getenv("GODOT_VERSION_STATUS"))
  181. if not silent:
  182. print(f"Using version status '{version_info['status']}', overriding the original '{version.status}'.")
  183. # Parse Git hash if we're in a Git repo.
  184. githash = ""
  185. gitfolder = ".git"
  186. if os.path.isfile(".git"):
  187. with open(".git", "r", encoding="utf-8") as file:
  188. module_folder = file.readline().strip()
  189. if module_folder.startswith("gitdir: "):
  190. gitfolder = module_folder[8:]
  191. if os.path.isfile(os.path.join(gitfolder, "HEAD")):
  192. with open(os.path.join(gitfolder, "HEAD"), "r", encoding="utf8") as file:
  193. head = file.readline().strip()
  194. if head.startswith("ref: "):
  195. ref = head[5:]
  196. # If this directory is a Git worktree instead of a root clone.
  197. parts = gitfolder.split("/")
  198. if len(parts) > 2 and parts[-2] == "worktrees":
  199. gitfolder = "/".join(parts[0:-2])
  200. head = os.path.join(gitfolder, ref)
  201. packedrefs = os.path.join(gitfolder, "packed-refs")
  202. if os.path.isfile(head):
  203. with open(head, "r", encoding="utf-8") as file:
  204. githash = file.readline().strip()
  205. elif os.path.isfile(packedrefs):
  206. # Git may pack refs into a single file. This code searches .git/packed-refs file for the current ref's hash.
  207. # https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-pack-refs.html
  208. for line in open(packedrefs, "r", encoding="utf-8").read().splitlines():
  209. if line.startswith("#"):
  210. continue
  211. (line_hash, line_ref) = line.split(" ")
  212. if ref == line_ref:
  213. githash = line_hash
  214. break
  215. else:
  216. githash = head
  217. version_info["git_hash"] = githash
  218. # Fallback to 0 as a timestamp (will be treated as "unknown" in the engine).
  219. version_info["git_timestamp"] = 0
  220. # Get the UNIX timestamp of the build commit.
  221. if os.path.exists(".git"):
  222. try:
  223. version_info["git_timestamp"] = subprocess.check_output(
  224. ["git", "log", "-1", "--pretty=format:%ct", "--no-show-signature", githash]
  225. ).decode("utf-8")
  226. except (subprocess.CalledProcessError, OSError):
  227. # `git` not found in PATH.
  228. pass
  229. return version_info
  230. def parse_cg_file(fname, uniforms, sizes, conditionals):
  231. with open(fname, "r", encoding="utf-8") as fs:
  232. line = fs.readline()
  233. while line:
  234. if re.match(r"^\s*uniform", line):
  235. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  236. type = res.groups(1)
  237. name = res.groups(2)
  238. uniforms.append(name)
  239. if type.find("texobj") != -1:
  240. sizes.append(1)
  241. else:
  242. t = re.match(r"float(\d)x(\d)", type)
  243. if t:
  244. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  245. else:
  246. t = re.match(r"float(\d)", type)
  247. sizes.append(int(t.groups(1)))
  248. if line.find("[branch]") != -1:
  249. conditionals.append(name)
  250. line = fs.readline()
  251. def get_cmdline_bool(option, default):
  252. """We use `ARGUMENTS.get()` to check if options were manually overridden on the command line,
  253. and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings.
  254. """
  255. from SCons.Script import ARGUMENTS
  256. from SCons.Variables.BoolVariable import _text2bool
  257. cmdline_val = ARGUMENTS.get(option)
  258. if cmdline_val is not None:
  259. return _text2bool(cmdline_val)
  260. else:
  261. return default
  262. def detect_modules(search_path, recursive=False):
  263. """Detects and collects a list of C++ modules at specified path
  264. `search_path` - a directory path containing modules. The path may point to
  265. a single module, which may have other nested modules. A module must have
  266. "register_types.h", "SCsub", "config.py" files created to be detected.
  267. `recursive` - if `True`, then all subdirectories are searched for modules as
  268. specified by the `search_path`, otherwise collects all modules under the
  269. `search_path` directory. If the `search_path` is a module, it is collected
  270. in all cases.
  271. Returns an `OrderedDict` with module names as keys, and directory paths as
  272. values. If a path is relative, then it is a built-in module. If a path is
  273. absolute, then it is a custom module collected outside of the engine source.
  274. """
  275. modules = OrderedDict()
  276. def add_module(path):
  277. module_name = os.path.basename(path)
  278. module_path = path.replace("\\", "/") # win32
  279. modules[module_name] = module_path
  280. def is_engine(path):
  281. # Prevent recursively detecting modules in self and other
  282. # Godot sources when using `custom_modules` build option.
  283. version_path = os.path.join(path, "version.py")
  284. if os.path.exists(version_path):
  285. with open(version_path, "r", encoding="utf-8") as f:
  286. if 'short_name = "godot"' in f.read():
  287. return True
  288. return False
  289. def get_files(path):
  290. files = glob.glob(os.path.join(path, "*"))
  291. # Sort so that `register_module_types` does not change that often,
  292. # and plugins are registered in alphabetic order as well.
  293. files.sort()
  294. return files
  295. if not recursive:
  296. if is_module(search_path):
  297. add_module(search_path)
  298. for path in get_files(search_path):
  299. if is_engine(path):
  300. continue
  301. if is_module(path):
  302. add_module(path)
  303. else:
  304. to_search = [search_path]
  305. while to_search:
  306. path = to_search.pop()
  307. if is_module(path):
  308. add_module(path)
  309. for child in get_files(path):
  310. if not os.path.isdir(child):
  311. continue
  312. if is_engine(child):
  313. continue
  314. to_search.insert(0, child)
  315. return modules
  316. def is_module(path):
  317. if not os.path.isdir(path):
  318. return False
  319. must_exist = ["register_types.h", "SCsub", "config.py"]
  320. for f in must_exist:
  321. if not os.path.exists(os.path.join(path, f)):
  322. return False
  323. return True
  324. def convert_custom_modules_path(path):
  325. if not path:
  326. return path
  327. path = os.path.realpath(os.path.expanduser(os.path.expandvars(path)))
  328. err_msg = "Build option 'custom_modules' must %s"
  329. if not os.path.isdir(path):
  330. raise ValueError(err_msg % "point to an existing directory.")
  331. if path == os.path.realpath("modules"):
  332. raise ValueError(err_msg % "be a directory other than built-in `modules` directory.")
  333. return path
  334. def disable_module(self):
  335. self.disabled_modules.append(self.current_module)
  336. def module_add_dependencies(self, module, dependencies, optional=False):
  337. """
  338. Adds dependencies for a given module.
  339. Meant to be used in module `can_build` methods.
  340. """
  341. if module not in self.module_dependencies:
  342. self.module_dependencies[module] = [[], []]
  343. if optional:
  344. self.module_dependencies[module][1].extend(dependencies)
  345. else:
  346. self.module_dependencies[module][0].extend(dependencies)
  347. def module_check_dependencies(self, module):
  348. """
  349. Checks if module dependencies are enabled for a given module,
  350. and prints a warning if they aren't.
  351. Meant to be used in module `can_build` methods.
  352. Returns a boolean (True if dependencies are satisfied).
  353. """
  354. missing_deps = []
  355. required_deps = self.module_dependencies[module][0] if module in self.module_dependencies else []
  356. for dep in required_deps:
  357. opt = "module_{}_enabled".format(dep)
  358. if opt not in self or not self[opt]:
  359. missing_deps.append(dep)
  360. if missing_deps != []:
  361. print_warning(
  362. "Disabling '{}' module as the following dependencies are not satisfied: {}".format(
  363. module, ", ".join(missing_deps)
  364. )
  365. )
  366. return False
  367. else:
  368. return True
  369. def sort_module_list(env):
  370. deps = {k: v[0] + list(filter(lambda x: x in env.module_list, v[1])) for k, v in env.module_dependencies.items()}
  371. frontier = list(env.module_list.keys())
  372. explored = []
  373. while len(frontier):
  374. cur = frontier.pop()
  375. deps_list = deps[cur] if cur in deps else []
  376. if len(deps_list) and any([d not in explored for d in deps_list]):
  377. # Will explore later, after its dependencies
  378. frontier.insert(0, cur)
  379. continue
  380. explored.append(cur)
  381. for k in explored:
  382. env.module_list.move_to_end(k)
  383. def use_windows_spawn_fix(self, platform=None):
  384. if os.name != "nt":
  385. return # not needed, only for windows
  386. # On Windows, due to the limited command line length, when creating a static library
  387. # from a very high number of objects SCons will invoke "ar" once per object file;
  388. # that makes object files with same names to be overwritten so the last wins and
  389. # the library loses symbols defined by overwritten objects.
  390. # By enabling quick append instead of the default mode (replacing), libraries will
  391. # got built correctly regardless the invocation strategy.
  392. # Furthermore, since SCons will rebuild the library from scratch when an object file
  393. # changes, no multiple versions of the same object file will be present.
  394. self.Replace(ARFLAGS="q")
  395. def mySubProcess(cmdline, env):
  396. startupinfo = subprocess.STARTUPINFO()
  397. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  398. popen_args = {
  399. "stdin": subprocess.PIPE,
  400. "stdout": subprocess.PIPE,
  401. "stderr": subprocess.PIPE,
  402. "startupinfo": startupinfo,
  403. "shell": False,
  404. "env": env,
  405. }
  406. if sys.version_info >= (3, 7, 0):
  407. popen_args["text"] = True
  408. proc = subprocess.Popen(cmdline, **popen_args)
  409. _, err = proc.communicate()
  410. rv = proc.wait()
  411. if rv:
  412. print_error(err)
  413. elif len(err) > 0 and not err.isspace():
  414. print(err)
  415. return rv
  416. def mySpawn(sh, escape, cmd, args, env):
  417. newargs = " ".join(args[1:])
  418. cmdline = cmd + " " + newargs
  419. rv = 0
  420. env = {str(key): str(value) for key, value in iter(env.items())}
  421. if len(cmdline) > 32000 and cmd.endswith("ar"):
  422. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  423. for i in range(3, len(args)):
  424. rv = mySubProcess(cmdline + args[i], env)
  425. if rv:
  426. break
  427. else:
  428. rv = mySubProcess(cmdline, env)
  429. return rv
  430. self["SPAWN"] = mySpawn
  431. def no_verbose(env):
  432. colors = [ANSI.BLUE, ANSI.BOLD, ANSI.REGULAR, ANSI.RESET]
  433. # There is a space before "..." to ensure that source file names can be
  434. # Ctrl + clicked in the VS Code terminal.
  435. compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors)
  436. java_compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors)
  437. compile_shared_source_message = "{}Compiling shared {}$SOURCE{} ...{}".format(*colors)
  438. link_program_message = "{}Linking Program {}$TARGET{} ...{}".format(*colors)
  439. link_library_message = "{}Linking Static Library {}$TARGET{} ...{}".format(*colors)
  440. ranlib_library_message = "{}Ranlib Library {}$TARGET{} ...{}".format(*colors)
  441. link_shared_library_message = "{}Linking Shared Library {}$TARGET{} ...{}".format(*colors)
  442. java_library_message = "{}Creating Java Archive {}$TARGET{} ...{}".format(*colors)
  443. compiled_resource_message = "{}Creating Compiled Resource {}$TARGET{} ...{}".format(*colors)
  444. zip_archive_message = "{}Archiving {}$TARGET{} ...{}".format(*colors)
  445. generated_file_message = "{}Generating {}$TARGET{} ...{}".format(*colors)
  446. env["CXXCOMSTR"] = compile_source_message
  447. env["CCCOMSTR"] = compile_source_message
  448. env["SHCCCOMSTR"] = compile_shared_source_message
  449. env["SHCXXCOMSTR"] = compile_shared_source_message
  450. env["ARCOMSTR"] = link_library_message
  451. env["RANLIBCOMSTR"] = ranlib_library_message
  452. env["SHLINKCOMSTR"] = link_shared_library_message
  453. env["LINKCOMSTR"] = link_program_message
  454. env["JARCOMSTR"] = java_library_message
  455. env["JAVACCOMSTR"] = java_compile_source_message
  456. env["RCCOMSTR"] = compiled_resource_message
  457. env["ZIPCOMSTR"] = zip_archive_message
  458. env["GENCOMSTR"] = generated_file_message
  459. def detect_visual_c_compiler_version(tools_env):
  460. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  461. # (see the SCons documentation for more information on what it does)...
  462. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  463. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  464. # the proper vc version that will be called
  465. # There is no flag to give to visual c compilers to set the architecture, i.e. scons arch argument (x86_32, x86_64, arm64, etc.).
  466. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  467. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  468. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  469. # the following string values:
  470. # "" Compiler not detected
  471. # "amd64" Native 64 bit compiler
  472. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  473. # "x86" Native 32 bit compiler
  474. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  475. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  476. # and similar architectures/compilers
  477. # Set chosen compiler to "not detected"
  478. vc_chosen_compiler_index = -1
  479. vc_chosen_compiler_str = ""
  480. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  481. if "VCINSTALLDIR" in tools_env:
  482. # print("Checking VCINSTALLDIR")
  483. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  484. # First test if amd64 and amd64_x86 compilers are present in the path
  485. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  486. if vc_amd64_compiler_detection_index > -1:
  487. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  488. vc_chosen_compiler_str = "amd64"
  489. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  490. if vc_amd64_x86_compiler_detection_index > -1 and (
  491. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  492. ):
  493. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  494. vc_chosen_compiler_str = "amd64_x86"
  495. # Now check the 32 bit compilers
  496. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  497. if vc_x86_compiler_detection_index > -1 and (
  498. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  499. ):
  500. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  501. vc_chosen_compiler_str = "x86"
  502. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\x86_amd64;")
  503. if vc_x86_amd64_compiler_detection_index > -1 and (
  504. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  505. ):
  506. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  507. vc_chosen_compiler_str = "x86_amd64"
  508. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  509. if "VCTOOLSINSTALLDIR" in tools_env:
  510. # Newer versions have a different path available
  511. vc_amd64_compiler_detection_index = (
  512. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;")
  513. )
  514. if vc_amd64_compiler_detection_index > -1:
  515. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  516. vc_chosen_compiler_str = "amd64"
  517. vc_amd64_x86_compiler_detection_index = (
  518. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;")
  519. )
  520. if vc_amd64_x86_compiler_detection_index > -1 and (
  521. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  522. ):
  523. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  524. vc_chosen_compiler_str = "amd64_x86"
  525. vc_x86_compiler_detection_index = (
  526. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;")
  527. )
  528. if vc_x86_compiler_detection_index > -1 and (
  529. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  530. ):
  531. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  532. vc_chosen_compiler_str = "x86"
  533. vc_x86_amd64_compiler_detection_index = (
  534. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;")
  535. )
  536. if vc_x86_amd64_compiler_detection_index > -1 and (
  537. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  538. ):
  539. vc_chosen_compiler_str = "x86_amd64"
  540. return vc_chosen_compiler_str
  541. def find_visual_c_batch_file(env):
  542. # TODO: We should investigate if we can avoid relying on SCons internals here.
  543. from SCons.Tool.MSCommon.vc import find_batch_file, find_vc_pdir, get_default_version, get_host_target
  544. msvc_version = get_default_version(env)
  545. # Syntax changed in SCons 4.4.0.
  546. if env.scons_version >= (4, 4, 0):
  547. (host_platform, target_platform, _) = get_host_target(env, msvc_version)
  548. else:
  549. (host_platform, target_platform, _) = get_host_target(env)
  550. if env.scons_version < (4, 6, 0):
  551. return find_batch_file(env, msvc_version, host_platform, target_platform)[0]
  552. # SCons 4.6.0+ removed passing env, so we need to get the product_dir ourselves first,
  553. # then pass that as the last param instead of env as the first param as before.
  554. # Param names need to be explicit, as they were shuffled around in SCons 4.8.0.
  555. product_dir = find_vc_pdir(msvc_version=msvc_version, env=env)
  556. return find_batch_file(msvc_version, host_platform, target_platform, product_dir)[0]
  557. def generate_cpp_hint_file(filename):
  558. if os.path.isfile(filename):
  559. # Don't overwrite an existing hint file since the user may have customized it.
  560. pass
  561. else:
  562. try:
  563. with open(filename, "w", encoding="utf-8", newline="\n") as fd:
  564. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  565. for name in ["GDVIRTUAL", "EXBIND", "MODBIND"]:
  566. for count in range(13):
  567. for suffix in ["", "R", "C", "RC"]:
  568. fd.write(f"#define {name}{count}{suffix}(")
  569. if "R" in suffix:
  570. fd.write("m_ret, ")
  571. fd.write("m_name")
  572. for idx in range(1, count + 1):
  573. fd.write(f", type{idx}")
  574. fd.write(")\n")
  575. except OSError:
  576. print_warning("Could not write cpp.hint file.")
  577. def glob_recursive(pattern, node="."):
  578. from SCons import Node
  579. from SCons.Script import Glob
  580. results = []
  581. for f in Glob(str(node) + "/*", source=True):
  582. if type(f) is Node.FS.Dir:
  583. results += glob_recursive(pattern, f)
  584. results += Glob(str(node) + "/" + pattern, source=True)
  585. return results
  586. def add_to_vs_project(env, sources):
  587. for x in sources:
  588. fname = env.File(x).path if isinstance(x, str) else env.File(x)[0].path
  589. pieces = fname.split(".")
  590. if len(pieces) > 0:
  591. basename = pieces[0]
  592. basename = basename.replace("\\\\", "/")
  593. if os.path.isfile(basename + ".h"):
  594. env.vs_incs += [basename + ".h"]
  595. elif os.path.isfile(basename + ".hpp"):
  596. env.vs_incs += [basename + ".hpp"]
  597. if os.path.isfile(basename + ".c"):
  598. env.vs_srcs += [basename + ".c"]
  599. elif os.path.isfile(basename + ".cpp"):
  600. env.vs_srcs += [basename + ".cpp"]
  601. def precious_program(env, program, sources, **args):
  602. program = env.ProgramOriginal(program, sources, **args)
  603. env.Precious(program)
  604. return program
  605. def add_shared_library(env, name, sources, **args):
  606. library = env.SharedLibrary(name, sources, **args)
  607. env.NoCache(library)
  608. return library
  609. def add_library(env, name, sources, **args):
  610. library = env.Library(name, sources, **args)
  611. env.NoCache(library)
  612. return library
  613. def add_program(env, name, sources, **args):
  614. program = env.Program(name, sources, **args)
  615. env.NoCache(program)
  616. return program
  617. def CommandNoCache(env, target, sources, command, **args):
  618. result = env.Command(target, sources, command, **args)
  619. env.NoCache(result)
  620. return result
  621. def Run(env, function):
  622. from SCons.Script import Action
  623. return Action(function, "$GENCOMSTR")
  624. def detect_darwin_sdk_path(platform, env):
  625. sdk_name = ""
  626. if platform == "macos":
  627. sdk_name = "macosx"
  628. var_name = "MACOS_SDK_PATH"
  629. elif platform == "ios":
  630. sdk_name = "iphoneos"
  631. var_name = "IOS_SDK_PATH"
  632. elif platform == "iossimulator":
  633. sdk_name = "iphonesimulator"
  634. var_name = "IOS_SDK_PATH"
  635. else:
  636. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  637. if not env[var_name]:
  638. try:
  639. sdk_path = subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip().decode("utf-8")
  640. if sdk_path:
  641. env[var_name] = sdk_path
  642. except (subprocess.CalledProcessError, OSError):
  643. print_error("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  644. raise
  645. def is_vanilla_clang(env):
  646. if not using_clang(env):
  647. return False
  648. try:
  649. version = subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip().decode("utf-8")
  650. except (subprocess.CalledProcessError, OSError):
  651. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  652. return False
  653. return not version.startswith("Apple")
  654. def get_compiler_version(env):
  655. """
  656. Returns a dictionary with various version information:
  657. - major, minor, patch: Version following semantic versioning system
  658. - metadata1, metadata2: Extra information
  659. - date: Date of the build
  660. """
  661. ret = {
  662. "major": -1,
  663. "minor": -1,
  664. "patch": -1,
  665. "metadata1": None,
  666. "metadata2": None,
  667. "date": None,
  668. "apple_major": -1,
  669. "apple_minor": -1,
  670. "apple_patch1": -1,
  671. "apple_patch2": -1,
  672. "apple_patch3": -1,
  673. }
  674. if not env.msvc:
  675. # Not using -dumpversion as some GCC distros only return major, and
  676. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  677. try:
  678. version = (
  679. subprocess.check_output([env.subst(env["CXX"]), "--version"], shell=(os.name == "nt"))
  680. .strip()
  681. .decode("utf-8")
  682. )
  683. except (subprocess.CalledProcessError, OSError):
  684. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  685. return ret
  686. else:
  687. # TODO: Implement for MSVC
  688. return ret
  689. match = re.search(
  690. r"(?:(?<=version )|(?<=\) )|(?<=^))"
  691. r"(?P<major>\d+)"
  692. r"(?:\.(?P<minor>\d*))?"
  693. r"(?:\.(?P<patch>\d*))?"
  694. r"(?:-(?P<metadata1>[0-9a-zA-Z-]*))?"
  695. r"(?:\+(?P<metadata2>[0-9a-zA-Z-]*))?"
  696. r"(?: (?P<date>[0-9]{8}|[0-9]{6})(?![0-9a-zA-Z]))?",
  697. version,
  698. )
  699. if match is not None:
  700. for key, value in match.groupdict().items():
  701. if value is not None:
  702. ret[key] = value
  703. match_apple = re.search(
  704. r"(?:(?<=clang-)|(?<=\) )|(?<=^))"
  705. r"(?P<apple_major>\d+)"
  706. r"(?:\.(?P<apple_minor>\d*))?"
  707. r"(?:\.(?P<apple_patch1>\d*))?"
  708. r"(?:\.(?P<apple_patch2>\d*))?"
  709. r"(?:\.(?P<apple_patch3>\d*))?",
  710. version,
  711. )
  712. if match_apple is not None:
  713. for key, value in match_apple.groupdict().items():
  714. if value is not None:
  715. ret[key] = value
  716. # Transform semantic versioning to integers
  717. for key in [
  718. "major",
  719. "minor",
  720. "patch",
  721. "apple_major",
  722. "apple_minor",
  723. "apple_patch1",
  724. "apple_patch2",
  725. "apple_patch3",
  726. ]:
  727. ret[key] = int(ret[key] or -1)
  728. return ret
  729. def using_gcc(env):
  730. return "gcc" in os.path.basename(env["CC"])
  731. def using_clang(env):
  732. return "clang" in os.path.basename(env["CC"])
  733. def using_emcc(env):
  734. return "emcc" in os.path.basename(env["CC"])
  735. def show_progress(env):
  736. if env["ninja"]:
  737. # Has its own progress/tracking tool that clashes with ours
  738. return
  739. import sys
  740. from SCons.Script import AlwaysBuild, Command, Progress
  741. screen = sys.stdout
  742. # Progress reporting is not available in non-TTY environments since it
  743. # messes with the output (for example, when writing to a file)
  744. show_progress = env["progress"] and sys.stdout.isatty()
  745. node_count = 0
  746. node_count_max = 0
  747. node_count_interval = 1
  748. node_count_fname = str(env.Dir("#")) + "/.scons_node_count"
  749. import math
  750. import time
  751. class cache_progress:
  752. # The default is 1 GB cache and 12 hours half life
  753. def __init__(self, path=None, limit=1073741824, half_life=43200):
  754. self.path = path
  755. self.limit = limit
  756. self.exponent_scale = math.log(2) / half_life
  757. if env["verbose"] and path is not None:
  758. screen.write(
  759. "Current cache limit is {} (used: {})\n".format(
  760. self.convert_size(limit), self.convert_size(self.get_size(path))
  761. )
  762. )
  763. self.delete(self.file_list())
  764. def __call__(self, node, *args, **kw):
  765. nonlocal node_count, node_count_max, node_count_interval, node_count_fname, show_progress
  766. if show_progress:
  767. # Print the progress percentage
  768. node_count += node_count_interval
  769. if node_count_max > 0 and node_count <= node_count_max:
  770. screen.write("\r[%3d%%] " % (node_count * 100 / node_count_max))
  771. screen.flush()
  772. elif node_count_max > 0 and node_count > node_count_max:
  773. screen.write("\r[100%] ")
  774. screen.flush()
  775. else:
  776. screen.write("\r[Initial build] ")
  777. screen.flush()
  778. def delete(self, files):
  779. if len(files) == 0:
  780. return
  781. if env["verbose"]:
  782. # Utter something
  783. screen.write("\rPurging %d %s from cache...\n" % (len(files), len(files) > 1 and "files" or "file"))
  784. [os.remove(f) for f in files]
  785. def file_list(self):
  786. if self.path is None:
  787. # Nothing to do
  788. return []
  789. # Gather a list of (filename, (size, atime)) within the
  790. # cache directory
  791. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, "*", "*"))]
  792. if file_stat == []:
  793. # Nothing to do
  794. return []
  795. # Weight the cache files by size (assumed to be roughly
  796. # proportional to the recompilation time) times an exponential
  797. # decay since the ctime, and return a list with the entries
  798. # (filename, size, weight).
  799. current_time = time.time()
  800. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  801. # Sort by the most recently accessed files (most sensible to keep) first
  802. file_stat.sort(key=lambda x: x[2])
  803. # Search for the first entry where the storage limit is
  804. # reached
  805. sum, mark = 0, None
  806. for i, x in enumerate(file_stat):
  807. sum += x[1]
  808. if sum > self.limit:
  809. mark = i
  810. break
  811. if mark is None:
  812. return []
  813. else:
  814. return [x[0] for x in file_stat[mark:]]
  815. def convert_size(self, size_bytes):
  816. if size_bytes == 0:
  817. return "0 bytes"
  818. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  819. i = int(math.floor(math.log(size_bytes, 1024)))
  820. p = math.pow(1024, i)
  821. s = round(size_bytes / p, 2)
  822. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  823. def get_size(self, start_path="."):
  824. total_size = 0
  825. for dirpath, dirnames, filenames in os.walk(start_path):
  826. for f in filenames:
  827. fp = os.path.join(dirpath, f)
  828. total_size += os.path.getsize(fp)
  829. return total_size
  830. def progress_finish(target, source, env):
  831. nonlocal node_count, progressor
  832. try:
  833. with open(node_count_fname, "w", encoding="utf-8", newline="\n") as f:
  834. f.write("%d\n" % node_count)
  835. progressor.delete(progressor.file_list())
  836. except Exception:
  837. pass
  838. try:
  839. with open(node_count_fname, "r", encoding="utf-8") as f:
  840. node_count_max = int(f.readline())
  841. except Exception:
  842. pass
  843. cache_directory = os.environ.get("SCONS_CACHE")
  844. # Simple cache pruning, attached to SCons' progress callback. Trim the
  845. # cache directory to a size not larger than cache_limit.
  846. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  847. progressor = cache_progress(cache_directory, cache_limit)
  848. Progress(progressor, interval=node_count_interval)
  849. progress_finish_command = Command("progress_finish", [], progress_finish)
  850. AlwaysBuild(progress_finish_command)
  851. def dump(env):
  852. # Dumps latest build information for debugging purposes and external tools.
  853. from json import dump
  854. def non_serializable(obj):
  855. return "<<non-serializable: %s>>" % (type(obj).__qualname__)
  856. with open(".scons_env.json", "w", encoding="utf-8", newline="\n") as f:
  857. dump(env.Dictionary(), f, indent=4, default=non_serializable)
  858. # Custom Visual Studio project generation logic that supports any platform that has a msvs.py
  859. # script, so Visual Studio can be used to run scons for any platform, with the right defines per target.
  860. # Invoked with scons vsproj=yes
  861. #
  862. # Only platforms that opt in to vs proj generation by having a msvs.py file in the platform folder are included.
  863. # Platforms with a msvs.py file will be added to the solution, but only the current active platform+target+arch
  864. # will have a build configuration generated, because we only know what the right defines/includes/flags/etc are
  865. # on the active build target.
  866. #
  867. # Platforms that don't support an editor target will have a dummy editor target that won't do anything on build,
  868. # but will have the files and configuration for the windows editor target.
  869. #
  870. # To generate build configuration files for all platforms+targets+arch combinations, users can call
  871. # scons vsproj=yes
  872. # for each combination of platform+target+arch. This will generate the relevant vs project files but
  873. # skip the build process. This lets project files be quickly generated even if there are build errors.
  874. #
  875. # To generate AND build from the command line:
  876. # scons vsproj=yes vsproj_gen_only=no
  877. def generate_vs_project(env, original_args, project_name="godot"):
  878. # Augmented glob_recursive that also fills the dirs argument with traversed directories that have content.
  879. def glob_recursive_2(pattern, dirs, node="."):
  880. from SCons import Node
  881. from SCons.Script import Glob
  882. results = []
  883. for f in Glob(str(node) + "/*", source=True):
  884. if type(f) is Node.FS.Dir:
  885. results += glob_recursive_2(pattern, dirs, f)
  886. r = Glob(str(node) + "/" + pattern, source=True)
  887. if len(r) > 0 and str(node) not in dirs:
  888. d = ""
  889. for part in str(node).split("\\"):
  890. d += part
  891. if d not in dirs:
  892. dirs.append(d)
  893. d += "\\"
  894. results += r
  895. return results
  896. def get_bool(args, option, default):
  897. from SCons.Variables.BoolVariable import _text2bool
  898. val = args.get(option, default)
  899. if val is not None:
  900. try:
  901. return _text2bool(val)
  902. except (ValueError, AttributeError):
  903. return default
  904. else:
  905. return default
  906. def format_key_value(v):
  907. if type(v) in [tuple, list]:
  908. return v[0] if len(v) == 1 else f"{v[0]}={v[1]}"
  909. return v
  910. filtered_args = original_args.copy()
  911. # Ignore the "vsproj" option to not regenerate the VS project on every build
  912. filtered_args.pop("vsproj", None)
  913. # This flag allows users to regenerate the proj files but skip the building process.
  914. # This lets projects be regenerated even if there are build errors.
  915. filtered_args.pop("vsproj_gen_only", None)
  916. # This flag allows users to regenerate only the props file without touching the sln or vcxproj files.
  917. # This preserves any customizations users have done to the solution, while still updating the file list
  918. # and build commands.
  919. filtered_args.pop("vsproj_props_only", None)
  920. # The "progress" option is ignored as the current compilation progress indication doesn't work in VS
  921. filtered_args.pop("progress", None)
  922. # We add these three manually because they might not be explicitly passed in, and it's important to always set them.
  923. filtered_args.pop("platform", None)
  924. filtered_args.pop("target", None)
  925. filtered_args.pop("arch", None)
  926. platform = env["platform"]
  927. target = env["target"]
  928. arch = env["arch"]
  929. vs_configuration = {}
  930. common_build_prefix = []
  931. confs = []
  932. for x in sorted(glob.glob("platform/*")):
  933. # Only platforms that opt in to vs proj generation are included.
  934. if not os.path.isdir(x) or not os.path.exists(x + "/msvs.py"):
  935. continue
  936. tmppath = "./" + x
  937. sys.path.insert(0, tmppath)
  938. import msvs
  939. vs_plats = []
  940. vs_confs = []
  941. try:
  942. platform_name = x[9:]
  943. vs_plats = msvs.get_platforms()
  944. vs_confs = msvs.get_configurations()
  945. val = []
  946. for plat in vs_plats:
  947. val += [{"platform": plat[0], "architecture": plat[1]}]
  948. vsconf = {"platform": platform_name, "targets": vs_confs, "arches": val}
  949. confs += [vsconf]
  950. # Save additional information about the configuration for the actively selected platform,
  951. # so we can generate the platform-specific props file with all the build commands/defines/etc
  952. if platform == platform_name:
  953. common_build_prefix = msvs.get_build_prefix(env)
  954. vs_configuration = vsconf
  955. except Exception:
  956. pass
  957. sys.path.remove(tmppath)
  958. sys.modules.pop("msvs")
  959. headers = []
  960. headers_dirs = []
  961. for file in glob_recursive_2("*.h", headers_dirs):
  962. headers.append(str(file).replace("/", "\\"))
  963. for file in glob_recursive_2("*.hpp", headers_dirs):
  964. headers.append(str(file).replace("/", "\\"))
  965. sources = []
  966. sources_dirs = []
  967. for file in glob_recursive_2("*.cpp", sources_dirs):
  968. sources.append(str(file).replace("/", "\\"))
  969. for file in glob_recursive_2("*.c", sources_dirs):
  970. sources.append(str(file).replace("/", "\\"))
  971. others = []
  972. others_dirs = []
  973. for file in glob_recursive_2("*.natvis", others_dirs):
  974. others.append(str(file).replace("/", "\\"))
  975. for file in glob_recursive_2("*.glsl", others_dirs):
  976. others.append(str(file).replace("/", "\\"))
  977. skip_filters = False
  978. import hashlib
  979. import json
  980. md5 = hashlib.md5(
  981. json.dumps(headers + headers_dirs + sources + sources_dirs + others + others_dirs, sort_keys=True).encode(
  982. "utf-8"
  983. )
  984. ).hexdigest()
  985. if os.path.exists(f"{project_name}.vcxproj.filters"):
  986. with open(f"{project_name}.vcxproj.filters", "r", encoding="utf-8") as file:
  987. existing_filters = file.read()
  988. match = re.search(r"(?ms)^<!-- CHECKSUM$.([0-9a-f]{32})", existing_filters)
  989. if match is not None and md5 == match.group(1):
  990. skip_filters = True
  991. import uuid
  992. # Don't regenerate the filters file if nothing has changed, so we keep the existing UUIDs.
  993. if not skip_filters:
  994. print(f"Regenerating {project_name}.vcxproj.filters")
  995. with open("misc/msvs/vcxproj.filters.template", "r", encoding="utf-8") as file:
  996. filters_template = file.read()
  997. for i in range(1, 10):
  998. filters_template = filters_template.replace(f"%%UUID{i}%%", str(uuid.uuid4()))
  999. filters = ""
  1000. for d in headers_dirs:
  1001. filters += f'<Filter Include="Header Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  1002. for d in sources_dirs:
  1003. filters += f'<Filter Include="Source Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  1004. for d in others_dirs:
  1005. filters += f'<Filter Include="Other Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  1006. filters_template = filters_template.replace("%%FILTERS%%", filters)
  1007. filters = ""
  1008. for file in headers:
  1009. filters += (
  1010. f'<ClInclude Include="{file}"><Filter>Header Files\\{os.path.dirname(file)}</Filter></ClInclude>\n'
  1011. )
  1012. filters_template = filters_template.replace("%%INCLUDES%%", filters)
  1013. filters = ""
  1014. for file in sources:
  1015. filters += (
  1016. f'<ClCompile Include="{file}"><Filter>Source Files\\{os.path.dirname(file)}</Filter></ClCompile>\n'
  1017. )
  1018. filters_template = filters_template.replace("%%COMPILES%%", filters)
  1019. filters = ""
  1020. for file in others:
  1021. filters += f'<None Include="{file}"><Filter>Other Files\\{os.path.dirname(file)}</Filter></None>\n'
  1022. filters_template = filters_template.replace("%%OTHERS%%", filters)
  1023. filters_template = filters_template.replace("%%HASH%%", md5)
  1024. with open(f"{project_name}.vcxproj.filters", "w", encoding="utf-8", newline="\r\n") as f:
  1025. f.write(filters_template)
  1026. envsources = []
  1027. envsources += env.core_sources
  1028. envsources += env.drivers_sources
  1029. envsources += env.main_sources
  1030. envsources += env.modules_sources
  1031. envsources += env.scene_sources
  1032. envsources += env.servers_sources
  1033. if env.editor_build:
  1034. envsources += env.editor_sources
  1035. envsources += env.platform_sources
  1036. headers_active = []
  1037. sources_active = []
  1038. others_active = []
  1039. for x in envsources:
  1040. fname = ""
  1041. if isinstance(x, str):
  1042. fname = env.File(x).path
  1043. else:
  1044. # Some object files might get added directly as a File object and not a list.
  1045. try:
  1046. fname = env.File(x)[0].path
  1047. except Exception:
  1048. fname = x.path
  1049. pass
  1050. if fname:
  1051. fname = fname.replace("\\\\", "/")
  1052. parts = os.path.splitext(fname)
  1053. basename = parts[0]
  1054. ext = parts[1]
  1055. idx = fname.find(env["OBJSUFFIX"])
  1056. if ext in [".h", ".hpp"]:
  1057. headers_active += [fname]
  1058. elif ext in [".c", ".cpp"]:
  1059. sources_active += [fname]
  1060. elif idx > 0:
  1061. basename = fname[:idx]
  1062. if os.path.isfile(basename + ".h"):
  1063. headers_active += [basename + ".h"]
  1064. elif os.path.isfile(basename + ".hpp"):
  1065. headers_active += [basename + ".hpp"]
  1066. elif basename.endswith(".gen") and os.path.isfile(basename[:-4] + ".h"):
  1067. headers_active += [basename[:-4] + ".h"]
  1068. if os.path.isfile(basename + ".c"):
  1069. sources_active += [basename + ".c"]
  1070. elif os.path.isfile(basename + ".cpp"):
  1071. sources_active += [basename + ".cpp"]
  1072. else:
  1073. fname = os.path.relpath(os.path.abspath(fname), env.Dir("").abspath)
  1074. others_active += [fname]
  1075. all_items = []
  1076. properties = []
  1077. activeItems = []
  1078. extraItems = []
  1079. set_headers = set(headers_active)
  1080. set_sources = set(sources_active)
  1081. set_others = set(others_active)
  1082. for file in headers:
  1083. base_path = os.path.dirname(file).replace("\\", "_")
  1084. all_items.append(f'<ClInclude Include="{file}">')
  1085. all_items.append(
  1086. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1087. )
  1088. all_items.append("</ClInclude>")
  1089. if file in set_headers:
  1090. activeItems.append(file)
  1091. for file in sources:
  1092. base_path = os.path.dirname(file).replace("\\", "_")
  1093. all_items.append(f'<ClCompile Include="{file}">')
  1094. all_items.append(
  1095. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1096. )
  1097. all_items.append("</ClCompile>")
  1098. if file in set_sources:
  1099. activeItems.append(file)
  1100. for file in others:
  1101. base_path = os.path.dirname(file).replace("\\", "_")
  1102. all_items.append(f'<None Include="{file}">')
  1103. all_items.append(
  1104. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1105. )
  1106. all_items.append("</None>")
  1107. if file in set_others:
  1108. activeItems.append(file)
  1109. if vs_configuration:
  1110. vsconf = ""
  1111. for a in vs_configuration["arches"]:
  1112. if arch == a["architecture"]:
  1113. vsconf = f'{target}|{a["platform"]}'
  1114. break
  1115. condition = "'$(GodotConfiguration)|$(GodotPlatform)'=='" + vsconf + "'"
  1116. itemlist = {}
  1117. for item in activeItems:
  1118. key = os.path.dirname(item).replace("\\", "_")
  1119. if key not in itemlist:
  1120. itemlist[key] = [item]
  1121. else:
  1122. itemlist[key] += [item]
  1123. for x in itemlist.keys():
  1124. properties.append(
  1125. "<ActiveProjectItemList_%s>;%s;</ActiveProjectItemList_%s>" % (x, ";".join(itemlist[x]), x)
  1126. )
  1127. output = f'bin\\godot{env["PROGSUFFIX"]}'
  1128. with open("misc/msvs/props.template", "r", encoding="utf-8") as file:
  1129. props_template = file.read()
  1130. props_template = props_template.replace("%%VSCONF%%", vsconf)
  1131. props_template = props_template.replace("%%CONDITION%%", condition)
  1132. props_template = props_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1133. props_template = props_template.replace("%%EXTRA_ITEMS%%", "\n ".join(extraItems))
  1134. props_template = props_template.replace("%%OUTPUT%%", output)
  1135. proplist = [format_key_value(v) for v in list(env["CPPDEFINES"])]
  1136. proplist += [format_key_value(j) for j in env.get("VSHINT_DEFINES", [])]
  1137. props_template = props_template.replace("%%DEFINES%%", ";".join(proplist))
  1138. proplist = [str(j) for j in env["CPPPATH"]]
  1139. proplist += [str(j) for j in env.get("VSHINT_INCLUDES", [])]
  1140. props_template = props_template.replace("%%INCLUDES%%", ";".join(proplist))
  1141. proplist = env["CCFLAGS"]
  1142. proplist += [x for x in env["CXXFLAGS"] if not x.startswith("$")]
  1143. proplist += [str(j) for j in env.get("VSHINT_OPTIONS", [])]
  1144. props_template = props_template.replace("%%OPTIONS%%", " ".join(proplist))
  1145. # Windows allows us to have spaces in paths, so we need
  1146. # to double quote off the directory. However, the path ends
  1147. # in a backslash, so we need to remove this, lest it escape the
  1148. # last double quote off, confusing MSBuild
  1149. common_build_postfix = [
  1150. "--directory=&quot;$(ProjectDir.TrimEnd(&apos;\\&apos;))&quot;",
  1151. "progress=no",
  1152. f"platform={platform}",
  1153. f"target={target}",
  1154. f"arch={arch}",
  1155. ]
  1156. for arg, value in filtered_args.items():
  1157. common_build_postfix.append(f"{arg}={value}")
  1158. cmd_rebuild = [
  1159. "vsproj=yes",
  1160. "vsproj_props_only=yes",
  1161. "vsproj_gen_only=no",
  1162. f"vsproj_name={project_name}",
  1163. ] + common_build_postfix
  1164. cmd_clean = [
  1165. "--clean",
  1166. ] + common_build_postfix
  1167. commands = "scons"
  1168. if len(common_build_prefix) == 0:
  1169. commands = "echo Starting SCons &amp;&amp; cmd /V /C " + commands
  1170. else:
  1171. common_build_prefix[0] = "echo Starting SCons &amp;&amp; cmd /V /C " + common_build_prefix[0]
  1172. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  1173. props_template = props_template.replace("%%BUILD%%", cmd)
  1174. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + cmd_rebuild)])
  1175. props_template = props_template.replace("%%REBUILD%%", cmd)
  1176. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + cmd_clean)])
  1177. props_template = props_template.replace("%%CLEAN%%", cmd)
  1178. with open(
  1179. f"{project_name}.{platform}.{target}.{arch}.generated.props", "w", encoding="utf-8", newline="\r\n"
  1180. ) as f:
  1181. f.write(props_template)
  1182. proj_uuid = str(uuid.uuid4())
  1183. sln_uuid = str(uuid.uuid4())
  1184. if os.path.exists(f"{project_name}.sln"):
  1185. for line in open(f"{project_name}.sln", "r", encoding="utf-8").read().splitlines():
  1186. if line.startswith('Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}")'):
  1187. proj_uuid = re.search(
  1188. r"\"{(\b[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-\b[0-9a-fA-F]{12}\b)}\"$",
  1189. line,
  1190. ).group(1)
  1191. elif line.strip().startswith("SolutionGuid ="):
  1192. sln_uuid = re.search(
  1193. r"{(\b[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-\b[0-9a-fA-F]{12}\b)}", line
  1194. ).group(1)
  1195. break
  1196. configurations = []
  1197. imports = []
  1198. properties = []
  1199. section1 = []
  1200. section2 = []
  1201. for conf in confs:
  1202. godot_platform = conf["platform"]
  1203. for p in conf["arches"]:
  1204. sln_plat = p["platform"]
  1205. proj_plat = sln_plat
  1206. godot_arch = p["architecture"]
  1207. # Redirect editor configurations for non-Windows platforms to the Windows one, so the solution has all the permutations
  1208. # and VS doesn't complain about missing project configurations.
  1209. # These configurations are disabled, so they show up but won't build.
  1210. if godot_platform != "windows":
  1211. section1 += [f"editor|{sln_plat} = editor|{proj_plat}"]
  1212. section2 += [
  1213. f"{{{proj_uuid}}}.editor|{proj_plat}.ActiveCfg = editor|{proj_plat}",
  1214. ]
  1215. for t in conf["targets"]:
  1216. godot_target = t
  1217. # Windows x86 is a special little flower that requires a project platform == Win32 but a solution platform == x86.
  1218. if godot_platform == "windows" and godot_target == "editor" and godot_arch == "x86_32":
  1219. sln_plat = "x86"
  1220. configurations += [
  1221. f'<ProjectConfiguration Include="{godot_target}|{proj_plat}">',
  1222. f" <Configuration>{godot_target}</Configuration>",
  1223. f" <Platform>{proj_plat}</Platform>",
  1224. "</ProjectConfiguration>",
  1225. ]
  1226. properties += [
  1227. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='{godot_target}|{proj_plat}'\">",
  1228. f" <GodotConfiguration>{godot_target}</GodotConfiguration>",
  1229. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1230. "</PropertyGroup>",
  1231. ]
  1232. if godot_platform != "windows":
  1233. configurations += [
  1234. f'<ProjectConfiguration Include="editor|{proj_plat}">',
  1235. " <Configuration>editor</Configuration>",
  1236. f" <Platform>{proj_plat}</Platform>",
  1237. "</ProjectConfiguration>",
  1238. ]
  1239. properties += [
  1240. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='editor|{proj_plat}'\">",
  1241. " <GodotConfiguration>editor</GodotConfiguration>",
  1242. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1243. "</PropertyGroup>",
  1244. ]
  1245. p = f"{project_name}.{godot_platform}.{godot_target}.{godot_arch}.generated.props"
  1246. imports += [
  1247. f'<Import Project="$(MSBuildProjectDirectory)\\{p}" Condition="Exists(\'$(MSBuildProjectDirectory)\\{p}\')"/>'
  1248. ]
  1249. section1 += [f"{godot_target}|{sln_plat} = {godot_target}|{sln_plat}"]
  1250. section2 += [
  1251. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.ActiveCfg = {godot_target}|{proj_plat}",
  1252. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.Build.0 = {godot_target}|{proj_plat}",
  1253. ]
  1254. # Add an extra import for a local user props file at the end, so users can add more overrides.
  1255. imports += [
  1256. f'<Import Project="$(MSBuildProjectDirectory)\\{project_name}.vs.user.props" Condition="Exists(\'$(MSBuildProjectDirectory)\\{project_name}.vs.user.props\')"/>'
  1257. ]
  1258. section1 = sorted(section1)
  1259. section2 = sorted(section2)
  1260. if not get_bool(original_args, "vsproj_props_only", False):
  1261. with open("misc/msvs/vcxproj.template", "r", encoding="utf-8") as file:
  1262. proj_template = file.read()
  1263. proj_template = proj_template.replace("%%UUID%%", proj_uuid)
  1264. proj_template = proj_template.replace("%%CONFS%%", "\n ".join(configurations))
  1265. proj_template = proj_template.replace("%%IMPORTS%%", "\n ".join(imports))
  1266. proj_template = proj_template.replace("%%DEFAULT_ITEMS%%", "\n ".join(all_items))
  1267. proj_template = proj_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1268. with open(f"{project_name}.vcxproj", "w", encoding="utf-8", newline="\r\n") as f:
  1269. f.write(proj_template)
  1270. if not get_bool(original_args, "vsproj_props_only", False):
  1271. with open("misc/msvs/sln.template", "r", encoding="utf-8") as file:
  1272. sln_template = file.read()
  1273. sln_template = sln_template.replace("%%NAME%%", project_name)
  1274. sln_template = sln_template.replace("%%UUID%%", proj_uuid)
  1275. sln_template = sln_template.replace("%%SLNUUID%%", sln_uuid)
  1276. sln_template = sln_template.replace("%%SECTION1%%", "\n\t\t".join(section1))
  1277. sln_template = sln_template.replace("%%SECTION2%%", "\n\t\t".join(section2))
  1278. with open(f"{project_name}.sln", "w", encoding="utf-8", newline="\r\n") as f:
  1279. f.write(sln_template)
  1280. if get_bool(original_args, "vsproj_gen_only", True):
  1281. sys.exit()
  1282. def generate_copyright_header(filename: str) -> str:
  1283. MARGIN = 70
  1284. TEMPLATE = """\
  1285. /**************************************************************************/
  1286. /* %s*/
  1287. /**************************************************************************/
  1288. /* This file is part of: */
  1289. /* GODOT ENGINE */
  1290. /* https://godotengine.org */
  1291. /**************************************************************************/
  1292. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  1293. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  1294. /* */
  1295. /* Permission is hereby granted, free of charge, to any person obtaining */
  1296. /* a copy of this software and associated documentation files (the */
  1297. /* "Software"), to deal in the Software without restriction, including */
  1298. /* without limitation the rights to use, copy, modify, merge, publish, */
  1299. /* distribute, sublicense, and/or sell copies of the Software, and to */
  1300. /* permit persons to whom the Software is furnished to do so, subject to */
  1301. /* the following conditions: */
  1302. /* */
  1303. /* The above copyright notice and this permission notice shall be */
  1304. /* included in all copies or substantial portions of the Software. */
  1305. /* */
  1306. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  1307. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  1308. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  1309. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  1310. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  1311. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  1312. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  1313. /**************************************************************************/
  1314. """
  1315. filename = filename.split("/")[-1].ljust(MARGIN)
  1316. if len(filename) > MARGIN:
  1317. print(f'WARNING: Filename "{filename}" too large for copyright header.')
  1318. return TEMPLATE % filename
  1319. @contextlib.contextmanager
  1320. def generated_wrapper(
  1321. path, # FIXME: type with `Union[str, Node, List[Node]]` when pytest conflicts are resolved
  1322. guard: Optional[bool] = None,
  1323. prefix: str = "",
  1324. suffix: str = "",
  1325. ) -> Generator[TextIOWrapper, None, None]:
  1326. """
  1327. Wrapper class to automatically handle copyright headers and header guards
  1328. for generated scripts. Meant to be invoked via `with` statement similar to
  1329. creating a file.
  1330. - `path`: The path of the file to be created. Can be passed a raw string, an
  1331. isolated SCons target, or a full SCons target list. If a target list contains
  1332. multiple entries, produces a warning & only creates the first entry.
  1333. - `guard`: Optional bool to determine if a header guard should be added. If
  1334. unassigned, header guards are determined by the file extension.
  1335. - `prefix`: Custom prefix to prepend to a header guard. Produces a warning if
  1336. provided a value when `guard` evaluates to `False`.
  1337. - `suffix`: Custom suffix to append to a header guard. Produces a warning if
  1338. provided a value when `guard` evaluates to `False`.
  1339. """
  1340. # Handle unfiltered SCons target[s] passed as path.
  1341. if not isinstance(path, str):
  1342. if isinstance(path, list):
  1343. if len(path) > 1:
  1344. print_warning(
  1345. "Attempting to use generated wrapper with multiple targets; "
  1346. f"will only use first entry: {path[0]}"
  1347. )
  1348. path = path[0]
  1349. if not hasattr(path, "get_abspath"):
  1350. raise TypeError(f'Expected type "str", "Node" or "List[Node]"; was passed {type(path)}.')
  1351. path = path.get_abspath()
  1352. path = str(path).replace("\\", "/")
  1353. if guard is None:
  1354. guard = path.endswith((".h", ".hh", ".hpp", ".inc"))
  1355. if not guard and (prefix or suffix):
  1356. print_warning(f'Trying to assign header guard prefix/suffix while `guard` is disabled: "{path}".')
  1357. header_guard = ""
  1358. if guard:
  1359. if prefix:
  1360. prefix += "_"
  1361. if suffix:
  1362. suffix = f"_{suffix}"
  1363. split = path.split("/")[-1].split(".")
  1364. header_guard = (f"{prefix}{split[0]}{suffix}.{'.'.join(split[1:])}".upper()
  1365. .replace(".", "_").replace("-", "_").replace(" ", "_").replace("__", "_")) # fmt: skip
  1366. with open(path, "wt", encoding="utf-8", newline="\n") as file:
  1367. file.write(generate_copyright_header(path))
  1368. file.write("\n/* THIS FILE IS GENERATED. EDITS WILL BE LOST. */\n\n")
  1369. if guard:
  1370. file.write(f"#ifndef {header_guard}\n")
  1371. file.write(f"#define {header_guard}\n\n")
  1372. with StringIO(newline="\n") as str_io:
  1373. yield str_io
  1374. file.write(str_io.getvalue().strip() or "/* NO CONTENT */")
  1375. if guard:
  1376. file.write(f"\n\n#endif // {header_guard}")
  1377. file.write("\n")
  1378. def to_raw_cstring(value: Union[str, List[str]]) -> str:
  1379. MAX_LITERAL = 16 * 1024
  1380. if isinstance(value, list):
  1381. value = "\n".join(value) + "\n"
  1382. split: List[bytes] = []
  1383. offset = 0
  1384. encoded = value.encode()
  1385. while offset <= len(encoded):
  1386. segment = encoded[offset : offset + MAX_LITERAL]
  1387. offset += MAX_LITERAL
  1388. if len(segment) == MAX_LITERAL:
  1389. # Try to segment raw strings at double newlines to keep readable.
  1390. pretty_break = segment.rfind(b"\n\n")
  1391. if pretty_break != -1:
  1392. segment = segment[: pretty_break + 1]
  1393. offset -= MAX_LITERAL - pretty_break - 1
  1394. # If none found, ensure we end with valid utf8.
  1395. # https://github.com/halloleo/unicut/blob/master/truncate.py
  1396. elif segment[-1] & 0b10000000:
  1397. last_11xxxxxx_index = [i for i in range(-1, -5, -1) if segment[i] & 0b11000000 == 0b11000000][0]
  1398. last_11xxxxxx = segment[last_11xxxxxx_index]
  1399. if not last_11xxxxxx & 0b00100000:
  1400. last_char_length = 2
  1401. elif not last_11xxxxxx & 0b0010000:
  1402. last_char_length = 3
  1403. elif not last_11xxxxxx & 0b0001000:
  1404. last_char_length = 4
  1405. if last_char_length > -last_11xxxxxx_index:
  1406. segment = segment[:last_11xxxxxx_index]
  1407. offset += last_11xxxxxx_index
  1408. split += [segment]
  1409. return " ".join(f'R"<!>({x.decode()})<!>"' for x in split)