TIFFGenerator.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2023, Lucas Chollet <lucas.chollet@serenityos.org>
  3. #
  4. # SPDX-License-Identifier: BSD-2-Clause
  5. import argparse
  6. import re
  7. from enum import Enum
  8. from collections import namedtuple
  9. from pathlib import Path
  10. from typing import Any, List, Type
  11. class EnumWithExportName(Enum):
  12. @classmethod
  13. def export_name(cls) -> str:
  14. return cls.__name__
  15. class TIFFType(EnumWithExportName):
  16. @classmethod
  17. def export_name(cls) -> str:
  18. return "Type"
  19. def __new__(cls, *args):
  20. obj = object.__new__(cls)
  21. obj._value_ = args[0]
  22. obj.size = args[1]
  23. return obj
  24. # First value is the underlying u16, second one is the size in bytes
  25. Byte = 1, 1
  26. ASCII = 2, 1
  27. UnsignedShort = 3, 2
  28. UnsignedLong = 4, 4
  29. UnsignedRational = 5, 8
  30. Undefined = 7, 1
  31. SignedLong = 9, 4
  32. SignedRational = 10, 8
  33. Float = 11, 4
  34. Double = 12, 8
  35. IFD = 13, 4
  36. UTF8 = 129, 1
  37. class Predictor(EnumWithExportName):
  38. NoPrediction = 1
  39. HorizontalDifferencing = 2
  40. class Compression(EnumWithExportName):
  41. NoCompression = 1
  42. CCITTRLE = 2
  43. Group3Fax = 3
  44. Group4Fax = 4
  45. LZW = 5
  46. OldJPEG = 6
  47. JPEG = 7
  48. AdobeDeflate = 8
  49. PackBits = 32773
  50. PixarDeflate = 32946 # This is the old (and deprecated) code for AdobeDeflate
  51. class PhotometricInterpretation(EnumWithExportName):
  52. WhiteIsZero = 0
  53. BlackIsZero = 1
  54. RGB = 2
  55. RGBPalette = 3
  56. TransparencyMask = 4
  57. CMYK = 5
  58. YCbCr = 6
  59. CIELab = 8
  60. class FillOrder(EnumWithExportName):
  61. LeftToRight = 1
  62. RightToLeft = 2
  63. class Orientation(EnumWithExportName):
  64. Default = 1
  65. FlipHorizontally = 2
  66. Rotate180 = 3
  67. FlipVertically = 4
  68. Rotate90ClockwiseThenFlipHorizontally = 5
  69. Rotate90Clockwise = 6
  70. FlipHorizontallyThenRotate90Clockwise = 7
  71. Rotate90CounterClockwise = 8
  72. class PlanarConfiguration(EnumWithExportName):
  73. Chunky = 1
  74. Planar = 2
  75. class ResolutionUnit(EnumWithExportName):
  76. NoAbsolute = 1
  77. Inch = 2
  78. Centimeter = 3
  79. class SampleFormat(EnumWithExportName):
  80. Unsigned = 1
  81. Signed = 2
  82. Float = 3
  83. Undefined = 4
  84. class ExtraSample(EnumWithExportName):
  85. Unspecified = 0
  86. AssociatedAlpha = 1
  87. UnassociatedAlpha = 2
  88. tag_fields = ['id', 'types', 'counts', 'default', 'name', 'associated_enum', 'is_required']
  89. Tag = namedtuple(
  90. 'Tag',
  91. field_names=tag_fields,
  92. defaults=(None,) * len(tag_fields)
  93. )
  94. # FIXME: Some tag have only a few allowed values, we should ensure that
  95. known_tags: List[Tag] = [
  96. Tag('256', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [1], None, "ImageWidth", is_required=True),
  97. Tag('257', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [1], None, "ImageLength", is_required=True),
  98. Tag('258', [TIFFType.UnsignedShort], [], None, "BitsPerSample", is_required=True),
  99. Tag('259', [TIFFType.UnsignedShort], [1], None, "Compression", Compression, is_required=True),
  100. Tag('262', [TIFFType.UnsignedShort], [1], None, "PhotometricInterpretation",
  101. PhotometricInterpretation, is_required=True),
  102. Tag('266', [TIFFType.UnsignedShort], [1], FillOrder.LeftToRight, "FillOrder", FillOrder),
  103. Tag('271', [TIFFType.ASCII], [], None, "Make"),
  104. Tag('272', [TIFFType.ASCII], [], None, "Model"),
  105. Tag('273', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [], None, "StripOffsets", is_required=False),
  106. Tag('274', [TIFFType.UnsignedShort], [1], Orientation.Default, "Orientation", Orientation),
  107. Tag('277', [TIFFType.UnsignedShort], [1], None, "SamplesPerPixel", is_required=True),
  108. Tag('278', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [1], None, "RowsPerStrip", is_required=False),
  109. Tag('279', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [], None, "StripByteCounts", is_required=False),
  110. Tag('282', [TIFFType.UnsignedRational], [1], None, "XResolution"),
  111. Tag('283', [TIFFType.UnsignedRational], [1], None, "YResolution"),
  112. Tag('284', [TIFFType.UnsignedShort], [1], PlanarConfiguration.Chunky, "PlanarConfiguration", PlanarConfiguration),
  113. Tag('285', [TIFFType.ASCII], [], None, "PageName"),
  114. Tag('292', [TIFFType.UnsignedLong], [1], 0, "T4Options"),
  115. Tag('296', [TIFFType.UnsignedShort], [1], ResolutionUnit.Inch, "ResolutionUnit", ResolutionUnit),
  116. Tag('305', [TIFFType.ASCII], [], None, "Software"),
  117. Tag('306', [TIFFType.ASCII], [20], None, "DateTime"),
  118. Tag('315', [TIFFType.ASCII], [], None, "Artist"),
  119. Tag('317', [TIFFType.UnsignedShort], [1], Predictor.NoPrediction, "Predictor", Predictor),
  120. Tag('320', [TIFFType.UnsignedShort], [], None, "ColorMap"),
  121. Tag('322', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [1], None, "TileWidth"),
  122. Tag('323', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [1], None, "TileLength"),
  123. Tag('324', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [], None, "TileOffsets"),
  124. Tag('325', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [], None, "TileByteCounts"),
  125. Tag('338', [TIFFType.UnsignedShort], [], None, "ExtraSamples", ExtraSample),
  126. Tag('339', [TIFFType.UnsignedShort], [], SampleFormat.Unsigned, "SampleFormat", SampleFormat),
  127. Tag('34665', [TIFFType.UnsignedLong, TIFFType.IFD], [1], None, "ExifIFD"),
  128. Tag('34675', [TIFFType.Undefined], [], None, "ICCProfile"),
  129. ]
  130. HANDLE_TAG_SIGNATURE_TEMPLATE = ("ErrorOr<void> {namespace}handle_tag(Function<ErrorOr<void>(u32)>&& subifd_handler, "
  131. "ExifMetadata& metadata, u16 tag, {namespace}Type type, u32 count, "
  132. "Vector<{namespace}Value>&& value)")
  133. HANDLE_TAG_SIGNATURE = HANDLE_TAG_SIGNATURE_TEMPLATE.format(namespace="")
  134. HANDLE_TAG_SIGNATURE_TIFF_NAMESPACE = HANDLE_TAG_SIGNATURE_TEMPLATE.format(namespace="TIFF::")
  135. ENSURE_BASELINE_TAG_PRESENCE = "ErrorOr<void> ensure_baseline_tags_are_present(ExifMetadata const& metadata)"
  136. TIFF_TYPE_FROM_U16 = "ErrorOr<Type> tiff_type_from_u16(u16 type)"
  137. SIZE_OF_TIFF_TYPE = "u8 size_of_type(Type type)"
  138. LICENSE = R"""/*
  139. * Copyright (c) 2023, Lucas Chollet <lucas.chollet@serenityos.org>
  140. *
  141. * SPDX-License-Identifier: BSD-2-Clause
  142. */"""
  143. def export_enum_to_cpp(e: Type[EnumWithExportName]) -> str:
  144. output = f'enum class {e.export_name()} {{\n'
  145. for entry in e:
  146. output += f' {entry.name} = {entry.value},\n'
  147. output += "};\n"
  148. return output
  149. def export_enum_to_string_converter(enums: List[Type[EnumWithExportName]]) -> str:
  150. stringifier_internals = []
  151. for e in enums:
  152. single_stringifier = fR""" if constexpr (IsSame<E, {e.export_name()}>) {{
  153. switch (value) {{
  154. default:
  155. return "Invalid value for {e.export_name()}"sv;"""
  156. for entry in e:
  157. single_stringifier += fR"""
  158. case {e.export_name()}::{entry.name}:
  159. return "{entry.name}"sv;"""
  160. single_stringifier += R"""
  161. }
  162. }"""
  163. stringifier_internals.append(single_stringifier)
  164. stringifier_internals_str = '\n'.join(stringifier_internals)
  165. out = fR"""template<Enum E>
  166. StringView name_for_enum_tag_value(E value) {{
  167. {stringifier_internals_str}
  168. VERIFY_NOT_REACHED();
  169. }}"""
  170. return out
  171. def export_tag_related_enums(tags: List[Tag]) -> str:
  172. exported_enums = []
  173. for tag in tags:
  174. if tag.associated_enum:
  175. exported_enums.append(export_enum_to_cpp(tag.associated_enum))
  176. return '\n'.join(exported_enums)
  177. def promote_type(t: TIFFType) -> TIFFType:
  178. if t == TIFFType.UnsignedShort:
  179. return TIFFType.UnsignedLong
  180. if t == TIFFType.Float:
  181. return TIFFType.Double
  182. return t
  183. def tiff_type_to_cpp(t: TIFFType, with_promotion: bool = True) -> str:
  184. # To simplify the code generator and the ExifMetadata class API, all u16 are promoted to u32
  185. # Note that the Value<> type doesn't include u16 for this reason
  186. if with_promotion:
  187. t = promote_type(t)
  188. if t in [TIFFType.ASCII, TIFFType.UTF8]:
  189. return 'String'
  190. if t == TIFFType.Undefined:
  191. return 'ByteBuffer'
  192. if t == TIFFType.UnsignedShort:
  193. return 'u16'
  194. if t == TIFFType.UnsignedLong or t == TIFFType.IFD:
  195. return 'u32'
  196. if t == TIFFType.UnsignedRational:
  197. return 'TIFF::Rational<u32>'
  198. if t == TIFFType.Float:
  199. return 'float'
  200. if t == TIFFType.Double:
  201. return 'double'
  202. raise RuntimeError(f'Type "{t}" not recognized, please update tiff_type_to_read_only_cpp()')
  203. def is_container(t: TIFFType) -> bool:
  204. """
  205. Some TIFF types are defined on the unit scale but are intended to be used within a collection.
  206. An example of that are ASCII strings defined as N * byte. Let's intercept that and generate
  207. a nice API instead of Vector<u8>.
  208. """
  209. return t in [TIFFType.ASCII, TIFFType.Byte, TIFFType.Undefined, TIFFType.UTF8]
  210. def export_promoter() -> str:
  211. output = R"""template<typename T>
  212. struct TypePromoter {
  213. using Type = T;
  214. };
  215. """
  216. specialization_template = R"""template<>
  217. struct TypePromoter<{}> {{
  218. using Type = {};
  219. }};
  220. """
  221. for t in TIFFType:
  222. if promote_type(t) != t:
  223. output += specialization_template.format(tiff_type_to_cpp(t, with_promotion=False), tiff_type_to_cpp(t))
  224. return output
  225. def retrieve_biggest_type(types: List[TIFFType]) -> TIFFType:
  226. return TIFFType(max([t.value for t in types]))
  227. def pascal_case_to_snake_case(name: str) -> str:
  228. name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
  229. return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower()
  230. def default_value_to_cpp(value: Any) -> str:
  231. if isinstance(value, EnumWithExportName):
  232. return f'TIFF::{value.export_name()}::{value.name}'
  233. return str(value)
  234. def generate_getter(tag: Tag) -> str:
  235. biggest_type = retrieve_biggest_type(tag.types)
  236. variant_inner_type = tiff_type_to_cpp(biggest_type)
  237. extracted_value_template = f"(*possible_value)[{{}}].get<{variant_inner_type}>()"
  238. tag_final_type = variant_inner_type
  239. if tag.associated_enum:
  240. tag_final_type = f"TIFF::{tag.associated_enum.__name__}"
  241. extracted_value_template = f"static_cast<{tag_final_type}>({extracted_value_template})"
  242. single_count = len(tag.counts) == 1 and tag.counts[0] == 1 or is_container(biggest_type)
  243. if single_count:
  244. return_type = tag_final_type
  245. if is_container(biggest_type):
  246. return_type += ' const&'
  247. unpacked_if_needed = f"return {extracted_value_template.format(0)};"
  248. else:
  249. if len(tag.counts) == 1:
  250. container_type = f'Array<{tag_final_type}, {tag.counts[0]}>'
  251. container_initialization = f'{container_type} tmp{{}};'
  252. else:
  253. container_type = f'Vector<{tag_final_type}>'
  254. container_initialization = fR"""{container_type} tmp{{}};
  255. auto maybe_failure = tmp.try_resize(possible_value->size());
  256. if (maybe_failure.is_error())
  257. return OptionalNone {{}};
  258. """
  259. return_type = container_type
  260. unpacked_if_needed = fR"""
  261. {container_initialization}
  262. for (u32 i = 0; i < possible_value->size(); ++i)
  263. tmp[i] = {extracted_value_template.format('i')};
  264. return tmp;"""
  265. signature = fR" Optional<{return_type}> {pascal_case_to_snake_case(tag.name)}() const"
  266. if tag.default is not None and single_count:
  267. return_if_empty = f'{default_value_to_cpp(tag.default)}'
  268. else:
  269. return_if_empty = 'OptionalNone {}'
  270. body = fR"""
  271. {{
  272. auto const& possible_value = m_data.get("{tag.name}"sv);
  273. if (!possible_value.has_value())
  274. return {return_if_empty};
  275. {unpacked_if_needed}
  276. }}
  277. """
  278. return signature + body
  279. def generate_metadata_class(tags: List[Tag]) -> str:
  280. getters = '\n'.join([generate_getter(tag) for tag in tags])
  281. output = fR"""class ExifMetadata : public Metadata {{
  282. public:
  283. virtual ~ExifMetadata() = default;
  284. {getters}
  285. private:
  286. friend {HANDLE_TAG_SIGNATURE_TIFF_NAMESPACE};
  287. virtual void fill_main_tags() const override {{
  288. if (model().has_value())
  289. m_main_tags.set("Model"sv, model().value());
  290. if (make().has_value())
  291. m_main_tags.set("Manufacturer"sv, make().value());
  292. if (software().has_value())
  293. m_main_tags.set("Software"sv, software().value());
  294. if (date_time().has_value())
  295. m_main_tags.set("Creation Time"sv, date_time().value());
  296. if (artist().has_value())
  297. m_main_tags.set("Author"sv, artist().value());
  298. }}
  299. void add_entry(StringView key, Vector<TIFF::Value>&& value) {{
  300. m_data.set(key, move(value));
  301. }}
  302. HashMap<StringView, Vector<TIFF::Value>> m_data;
  303. }};
  304. """
  305. return output
  306. def generate_metadata_file(tags: List[Tag]) -> str:
  307. output = fR"""{LICENSE}
  308. #pragma once
  309. #include <AK/HashMap.h>
  310. #include <AK/Variant.h>
  311. #include <AK/Vector.h>
  312. #include <LibGfx/Size.h>
  313. #include <LibGfx/ImageFormats/ImageDecoder.h>
  314. namespace Gfx {{
  315. class ExifMetadata;
  316. namespace TIFF {{
  317. {export_enum_to_cpp(TIFFType)}
  318. template<OneOf<u32, i32> x32>
  319. struct Rational {{
  320. using Type = x32;
  321. x32 numerator;
  322. x32 denominator;
  323. double as_double() const {{
  324. return static_cast<double>(numerator) / denominator;
  325. }}
  326. }};
  327. {export_promoter()}
  328. // Note that u16 is not include on purpose
  329. using Value = Variant<ByteBuffer, String, u32, Rational<u32>, i32, Rational<i32>, double>;
  330. {export_tag_related_enums(known_tags)}
  331. {export_enum_to_string_converter([tag.associated_enum for tag in known_tags if tag.associated_enum] + [TIFFType])}
  332. {HANDLE_TAG_SIGNATURE};
  333. {ENSURE_BASELINE_TAG_PRESENCE};
  334. {TIFF_TYPE_FROM_U16};
  335. {SIZE_OF_TIFF_TYPE};
  336. }}
  337. {generate_metadata_class(tags)}
  338. }}
  339. template<typename T>
  340. struct AK::Formatter<Gfx::TIFF::Rational<T>> : Formatter<FormatString> {{
  341. ErrorOr<void> format(FormatBuilder& builder, Gfx::TIFF::Rational<T> value)
  342. {{
  343. return Formatter<FormatString>::format(builder, "{{}} ({{}}/{{}})"sv,
  344. value.as_double(), value.numerator, value.denominator);
  345. }}
  346. }};
  347. template<>
  348. struct AK::Formatter<Gfx::TIFF::Value> : Formatter<FormatString> {{
  349. ErrorOr<void> format(FormatBuilder& builder, Gfx::TIFF::Value const& value)
  350. {{
  351. String content;
  352. value.visit(
  353. [&](ByteBuffer const& buffer) {{
  354. content = MUST(String::formatted("Buffer of size: {{}}"sv, buffer.size()));
  355. }},
  356. [&](auto const& other) {{
  357. content = MUST(String::formatted("{{}}", other));
  358. }}
  359. );
  360. return Formatter<FormatString>::format(builder, "{{}}"sv, content);
  361. }}
  362. }};
  363. """
  364. return output
  365. def generate_tag_handler(tag: Tag) -> str:
  366. not_in_type_list = f"({' && '.join([f'type != Type::{t.name}' for t in tag.types])})"
  367. not_in_count_list = ''
  368. if len(tag.counts) != 0:
  369. not_in_count_list = f"|| ({' && '.join([f'count != {c}' for c in tag.counts])})"
  370. pre_condition = fR"""if ({not_in_type_list}
  371. {not_in_count_list})
  372. return Error::from_string_literal("TIFFImageDecoderPlugin: Tag {tag.name} invalid");"""
  373. check_value = ''
  374. if tag.associated_enum is not None:
  375. not_in_value_list = f"({' && '.join([f'v != {v.value}' for v in tag.associated_enum])})"
  376. check_value = fR"""
  377. for (u32 i = 0; i < value.size(); ++i) {{
  378. TRY(value[i].visit(
  379. []({tiff_type_to_cpp(tag.types[0])} const& v) -> ErrorOr<void> {{
  380. if ({not_in_value_list})
  381. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid value for tag {tag.name}");
  382. return {{}};
  383. }},
  384. [&](auto const&) -> ErrorOr<void> {{
  385. VERIFY_NOT_REACHED();
  386. }})
  387. );
  388. }}
  389. """
  390. handle_subifd = ''
  391. if TIFFType.IFD in tag.types:
  392. if tag.counts != [1]:
  393. raise RuntimeError("Accessing `value[0]` in the C++ code might fail!")
  394. handle_subifd = f'TRY(subifd_handler(value[0].get<{tiff_type_to_cpp(TIFFType.IFD)}>()));'
  395. output = fR""" case {tag.id}:
  396. // {tag.name}
  397. dbgln_if(TIFF_DEBUG, "{tag.name}({{}}): {{}}", name_for_enum_tag_value(type), format_tiff_value(tag, value));
  398. {pre_condition}
  399. {check_value}
  400. {handle_subifd}
  401. metadata.add_entry("{tag.name}"sv, move(value));
  402. break;
  403. """
  404. return output
  405. def generate_tag_handler_file(tags: List[Tag]) -> str:
  406. formatter_for_tag_with_enum = '\n'.join([fR""" case {tag.id}:
  407. return MUST(String::from_utf8(
  408. name_for_enum_tag_value(static_cast<{tag.associated_enum.export_name()}>(v.get<u32>()))));"""
  409. for tag in tags if tag.associated_enum])
  410. ensure_tags_are_present = '\n'.join([fR""" if (!metadata.{pascal_case_to_snake_case(tag.name)}().has_value())
  411. return Error::from_string_literal("Unable to decode image, missing required tag {tag.name}.");
  412. """ for tag in filter(lambda tag: tag.is_required, known_tags)])
  413. tiff_type_from_u16_cases = '\n'.join([fR""" case to_underlying(Type::{t.name}):
  414. return Type::{t.name};""" for t in TIFFType])
  415. size_of_tiff_type_cases = '\n'.join([fR""" case Type::{t.name}:
  416. return {t.size};""" for t in TIFFType])
  417. output = fR"""{LICENSE}
  418. #include <AK/Debug.h>
  419. #include <AK/String.h>
  420. #include <LibGfx/ImageFormats/TIFFMetadata.h>
  421. namespace Gfx::TIFF {{
  422. static String value_formatter(u32 tag_id, Value const& v) {{
  423. switch (tag_id) {{
  424. {formatter_for_tag_with_enum}
  425. default:
  426. return MUST(String::formatted("{{}}", v));
  427. }}
  428. }}
  429. [[maybe_unused]] static String format_tiff_value(u32 tag_id, Vector<Value> const& values) {{
  430. if (values.size() == 1)
  431. return MUST(String::formatted("{{}}", value_formatter(tag_id, values[0])));
  432. StringBuilder builder;
  433. builder.append('[');
  434. for (u32 i = 0; i < values.size(); ++i) {{
  435. builder.appendff("{{}}", value_formatter(tag_id, values[i]));
  436. if (i != values.size() - 1)
  437. builder.append(", "sv);
  438. }}
  439. builder.append(']');
  440. return MUST(builder.to_string());
  441. }}
  442. {ENSURE_BASELINE_TAG_PRESENCE}
  443. {{
  444. {ensure_tags_are_present}
  445. return {{}};
  446. }}
  447. {TIFF_TYPE_FROM_U16}
  448. {{
  449. switch (type) {{
  450. {tiff_type_from_u16_cases}
  451. default:
  452. return Error::from_string_literal("TIFFImageDecoderPlugin: Unknown type");
  453. }}
  454. }}
  455. {SIZE_OF_TIFF_TYPE}
  456. {{
  457. switch (type) {{
  458. {size_of_tiff_type_cases}
  459. default:
  460. VERIFY_NOT_REACHED();
  461. }}
  462. }}
  463. {HANDLE_TAG_SIGNATURE}
  464. {{
  465. switch (tag) {{
  466. """
  467. output += '\n'.join([generate_tag_handler(t) for t in tags])
  468. output += R"""
  469. default:
  470. dbgln_if(TIFF_DEBUG, "UnknownTag({}, {}): {}",
  471. tag, name_for_enum_tag_value(type), format_tiff_value(tag, value));
  472. }
  473. return {};
  474. }
  475. }
  476. """
  477. return output
  478. def update_file(target: Path, new_content: str):
  479. should_update = True
  480. if target.exists():
  481. with target.open('r') as file:
  482. content = file.read()
  483. if content == new_content:
  484. should_update = False
  485. if should_update:
  486. with target.open('w') as file:
  487. file.write(new_content)
  488. def main():
  489. parser = argparse.ArgumentParser()
  490. parser.add_argument('-o', '--output')
  491. args = parser.parse_args()
  492. output_path = Path(args.output)
  493. update_file(output_path / 'TIFFMetadata.h', generate_metadata_file(known_tags))
  494. update_file(output_path / 'TIFFTagHandler.cpp', generate_tag_handler_file(known_tags))
  495. if __name__ == '__main__':
  496. main()