FindGettext.cmake 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file LICENSE.rst or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. FindGettext
  5. -----------
  6. Finds the GNU gettext tools and provides commands for producing multi-lingual
  7. messages:
  8. .. code-block:: cmake
  9. find_package(Gettext [<version>] [...])
  10. GNU gettext is a system for internationalization (i18n) and localization
  11. (l10n), consisting of command-line tools and a runtime library (``libintl``).
  12. This module finds the gettext tools (such as ``msgmerge`` and ``msgfmt``),
  13. while the runtime library can be found using the separate :module:`FindIntl`
  14. module, which abstracts ``libintl`` handling across various implementations.
  15. Common file types used with gettext:
  16. POT files
  17. Portable Object Template (``.pot``) files used as the source template for
  18. translations.
  19. PO files
  20. Portable Object (``.po``) files containing human-readable translations.
  21. MO files
  22. Machine Object (``.mo``) files compiled from ``.po`` files for runtime use.
  23. Result Variables
  24. ^^^^^^^^^^^^^^^^
  25. This module defines the following variables:
  26. ``Gettext_FOUND``
  27. .. versionadded:: 3.3
  28. Boolean indicating whether (the requested version of) gettext was found.
  29. ``Gettext_VERSION``
  30. .. versionadded:: 4.2
  31. The version of gettext found.
  32. Cache Variables
  33. ^^^^^^^^^^^^^^^
  34. The following cache variables may also be set:
  35. ``GETTEXT_MSGMERGE_EXECUTABLE``
  36. The full path to the ``msgmerge`` tool for merging message catalog and
  37. template.
  38. ``GETTEXT_MSGFMT_EXECUTABLE``
  39. The full path to the ``msgfmt`` tool for compiling message catalog to a binary
  40. format.
  41. Commands
  42. ^^^^^^^^
  43. This module provides the following commands to work with gettext in CMake, if
  44. gettext is found:
  45. .. command:: gettext_process_po_files
  46. Creates a build rule that processes one or more ``.po`` translation files
  47. into binary ``.mo`` files for a specified translatable language locale:
  48. .. code-block:: cmake
  49. gettext_process_po_files(
  50. <language>
  51. [ALL]
  52. [INSTALL_DESTINATION <destdir>]
  53. PO_FILES <po-files>...
  54. )
  55. This command defines a custom target that compiles the given ``<po-files>``
  56. into ``.mo`` files for the specified ``<language>``. On first invocation,
  57. it also creates a global custom target named ``pofiles``, to which all
  58. subsequent invocations contribute. This target can be used to build all
  59. translation files collectively or referenced in other CMake commands.
  60. This command should be invoked separately for each language locale to
  61. generate the appropriate ``.mo`` files per locale.
  62. The arguments are:
  63. ``<language>``
  64. The target translatable language locale of the PO files.
  65. This string is typically formatted as a locale identifier (e.g., ``de_DE``
  66. for German as used in Germany, or ``de_AT`` for German as used in Austria,
  67. etc.). The part before the underscore specifies the language, and the
  68. part after specifies the country or regional variant. In some cases, a
  69. shorter form using only the language code (e.g., ``de``) may also be used.
  70. ``ALL``
  71. This option adds the generated target to the default CMake build target so
  72. that translations are built by default.
  73. ``INSTALL_DESTINATION <destdir>``
  74. Specifies the installation directory for the generated ``.mo`` files at
  75. the install phase. If specified, files are installed to:
  76. ``<destdir>/<language>/LC_MESSAGES/*.mo``. If not specified, files are
  77. not installed.
  78. ``PO_FILES <po-files>...``
  79. A list of one or more ``.po`` translation files to be compiled into
  80. ``.mo`` files at build phase for the specified ``<language>``. Relative
  81. paths will be interpreted relative to the current source directory
  82. (:variable:`CMAKE_CURRENT_SOURCE_DIR`).
  83. .. command:: gettext_process_pot_file
  84. Creates a build rule that processes a gettext Portable Object Template
  85. (``.pot``) file and associated ``.po`` files into compiled gettext Machine
  86. Object (``.mo``) files:
  87. .. code-block:: cmake
  88. gettext_process_pot_file(
  89. <pot-file>
  90. [ALL]
  91. [INSTALL_DESTINATION <destdir>]
  92. LANGUAGES <languages>...
  93. )
  94. This command defines a custom target named ``potfiles`` that compiles the
  95. given ``<pot-file>`` and language-specific ``.po`` files into binary ``.mo``
  96. files for each specified language. The corresponding ``<language>.po``
  97. files must exist in the current binary directory
  98. (:variable:`CMAKE_CURRENT_BINARY_DIR`) before this command is invoked.
  99. The arguments are:
  100. ``<pot-file>``
  101. The path to the gettext Portable Object Template file (``.pot``) serving
  102. as the source for translations. If given as a relative path, it will be
  103. interpreted relative to the current source directory
  104. (:variable:`CMAKE_CURRENT_SOURCE_DIR`).
  105. ``ALL``
  106. Adds the generated target to the default CMake build target so that the
  107. files are built by default.
  108. ``INSTALL_DESTINATION <destdir>``
  109. Specifies the installation directory for the generated ``.mo`` files at
  110. the install phase. If specified, files are installed to:
  111. ``<destdir>/<language>/LC_MESSAGES/<pot-base-filename>.mo``. If not
  112. specified, files are not installed.
  113. ``LANGUAGES <languages>...``
  114. A list of one or more translatable language locales (e.g., ``en_US``,
  115. ``fr``, ``de_DE``, ``zh_CN``, etc.).
  116. .. command:: gettext_create_translations
  117. Creates a build rule that processes a given ``.pot`` template file and
  118. associated ``.po`` translation files into compiled Machine Object (``.mo``)
  119. files:
  120. .. code-block:: cmake
  121. gettext_create_translations(<pot-file> [ALL] <po-files>...)
  122. This command defines a custom target named ``translations`` that compiles
  123. the specified ``<pot-file>`` and ``<po-files>`` into binary ``.mo`` files.
  124. It also automatically adds an install rule for the generated ``.mo`` files,
  125. installing them into the default
  126. ``share/locale/<language>/LC_MESSAGES/<pot-base-filename>.mo`` path during
  127. the install phase.
  128. The arguments are:
  129. ``<pot-file>``
  130. The path to the gettext Portable Object Template file (``.pot``) serving
  131. as the source for translations. If given as a relative path, it will be
  132. interpreted relative to the current source directory
  133. (:variable:`CMAKE_CURRENT_SOURCE_DIR`).
  134. ``ALL``
  135. Adds the generated target to the default CMake build target so that
  136. translations are created by default during the build.
  137. ``<po-files>...``
  138. A list of one or more translation source files in ``.po`` format, whose
  139. filenames must follow the format ``<language>.po``. Relative paths will
  140. be interpreted relative to the current source directory
  141. (:variable:`CMAKE_CURRENT_SOURCE_DIR`).
  142. .. note::
  143. For better control over build and installation behavior, use
  144. :command:`gettext_process_po_files` instead.
  145. Deprecated Variables
  146. ^^^^^^^^^^^^^^^^^^^^
  147. The following variables are provided for backward compatibility:
  148. ``GETTEXT_FOUND``
  149. .. deprecated:: 4.2
  150. Use ``Gettext_FOUND``, which has the same value.
  151. Boolean indicating whether (the requested version of) gettext was found.
  152. ``GETTEXT_VERSION_STRING``
  153. .. deprecated:: 4.2
  154. Superseded by the ``Gettext_VERSION``.
  155. The version of gettext found.
  156. Examples
  157. ^^^^^^^^
  158. Examples: Finding gettext
  159. """""""""""""""""""""""""
  160. Finding the GNU gettext tools:
  161. .. code-block:: cmake
  162. find_package(Gettext)
  163. Or, finding gettext and specifying a minimum required version:
  164. .. code-block:: cmake
  165. find_package(Gettext 0.21)
  166. Or, finding gettext and making it required (if not found, processing stops
  167. with an error message):
  168. .. code-block:: cmake
  169. find_package(Gettext REQUIRED)
  170. Example: Working With gettext in CMake
  171. """"""""""""""""""""""""""""""""""""""
  172. When starting with gettext, ``.pot`` file is considered to be created manually.
  173. For example, using a ``xgettext`` tool on the provided ``main.cxx`` source
  174. code file:
  175. .. code-block:: c++
  176. :caption: ``main.cxx``
  177. :emphasize-lines: 18
  178. #include <iostream>
  179. #include <libintl.h>
  180. #include <locale.h>
  181. int main()
  182. {
  183. // Set locale from environment
  184. setlocale(LC_ALL, "");
  185. // Bind the text domain
  186. const char* dir = std::getenv("TEXTDOMAINDIR");
  187. if (!dir) {
  188. dir = "/usr/local/share/locale";
  189. }
  190. bindtextdomain("MyApp", dir);
  191. textdomain("MyApp");
  192. std::cout << gettext("Hello, World") << std::endl;
  193. return 0;
  194. }
  195. The ``xgettext`` tool extracts all strings from ``gettext()`` calls in provided
  196. source code and creates translatable strings:
  197. .. code-block:: console
  198. $ xgettext -o MyApp.pot main.cxx
  199. Translatable files can be initialized by the project manually using
  200. ``msginit`` tool:
  201. .. code-block:: console
  202. $ mkdir -p locale/de_DE
  203. $ msginit -l de_DE.UTF8 -o locale/de_DE/MyApp.po -i MyApp.pot --no-translator
  204. which creates a human-readable file that can be translated into a desired
  205. language (adjust as needed):
  206. .. code-block:: po
  207. :caption: ``locale/de_DE/MyApp.po``
  208. :emphasize-lines: 9
  209. msgid ""
  210. msgstr ""
  211. "Language: de\n"
  212. "Content-Type: text/plain; charset=UTF-8\n"
  213. "Content-Transfer-Encoding: 8bit\n"
  214. "Plural-Forms: nplurals=2; plural=(n != 1);\n"
  215. msgid "Hello, World"
  216. msgstr "Hallo, Welt"
  217. In CMake, the :command:`gettext_process_po_files` command provided by this
  218. module automatically creates the needed ``.mo`` files that application loads
  219. at runtime depending on the system environment variables such as ``LANG``.
  220. In the following example, also the :module:`GNUInstallDirs` module is used
  221. to provide the ``CMAKE_INSTALL_LOCALEDIR`` variable:
  222. .. code-block:: cmake
  223. :caption: ``CMakeLists.txt``
  224. :emphasize-lines: 9-14
  225. cmake_minimum_required(VERSION 3.24)
  226. project(GettextExample)
  227. include(GNUInstallDirs)
  228. find_package(Gettext)
  229. if(Gettext_FOUND)
  230. foreach(language IN ITEMS de_DE)
  231. gettext_process_po_files(
  232. ${language}
  233. ALL
  234. PO_FILES locale/${language}/MyApp.po
  235. INSTALL_DESTINATION ${CMAKE_INSTALL_LOCALEDIR}
  236. )
  237. endforeach()
  238. endif()
  239. add_executable(example main.cxx)
  240. # Find and link Intl library to use gettext() from libintl.h
  241. find_package(Intl)
  242. target_link_libraries(example PRIVATE Intl::Intl)
  243. install(TARGETS example)
  244. .. code-block:: console
  245. $ cmake -B build
  246. $ cmake --build build
  247. $ DESTDIR=$(pwd)/stage cmake --install build
  248. To utilize the translations, the ``de_DE`` locale needs to be enabled on the
  249. system (see ``locale -a``). And then the localized output can be run:
  250. .. code-block:: console
  251. $ LANG=de_DE.UTF-8 TEXTDOMAINDIR=./stage/usr/local/share/locale \
  252. ./stage/usr/local/bin/example
  253. Example: Processing POT File
  254. """"""""""""""""""""""""""""
  255. The :command:`gettext_process_pot_file` command processes ``.po`` translation
  256. files located in the current binary directory into ``.mo`` files:
  257. .. code-block:: cmake
  258. :caption: ``CMakeLists.txt``
  259. find_package(Gettext)
  260. if(Gettext_FOUND)
  261. set(languages de_DE fr zh_CN)
  262. foreach(language IN LISTS languages)
  263. configure_file(locale/${language}.po ${language}.po COPYONLY)
  264. endforeach()
  265. gettext_process_pot_file(
  266. MyApp.pot
  267. ALL
  268. INSTALL_DESTINATION ${CMAKE_INSTALL_LOCALEDIR}
  269. LANGUAGES ${languages}
  270. )
  271. endif()
  272. Example: Creating Translations
  273. """"""""""""""""""""""""""""""
  274. Using a simplified :command:`gettext_create_translations` command to create
  275. ``.mo`` files:
  276. .. code-block:: cmake
  277. :caption: ``CMakeLists.txt``
  278. find_package(Gettext)
  279. if(Gettext_FOUND)
  280. gettext_create_translations(
  281. MyApp.pot
  282. ALL
  283. locale/de_DE.po
  284. locale/fr.po
  285. locale/zh_CN.po
  286. )
  287. endif()
  288. See Also
  289. ^^^^^^^^
  290. * The :module:`FindIntl` module to find the Gettext runtime library (libintl).
  291. #]=======================================================================]
  292. find_program(GETTEXT_MSGMERGE_EXECUTABLE msgmerge)
  293. find_program(GETTEXT_MSGFMT_EXECUTABLE msgfmt)
  294. if(GETTEXT_MSGMERGE_EXECUTABLE)
  295. execute_process(COMMAND ${GETTEXT_MSGMERGE_EXECUTABLE} --version
  296. OUTPUT_VARIABLE gettext_version
  297. ERROR_QUIET
  298. OUTPUT_STRIP_TRAILING_WHITESPACE)
  299. get_filename_component(msgmerge_name ${GETTEXT_MSGMERGE_EXECUTABLE} NAME)
  300. get_filename_component(msgmerge_namewe ${GETTEXT_MSGMERGE_EXECUTABLE} NAME_WE)
  301. if(gettext_version MATCHES "^(${msgmerge_name}|${msgmerge_namewe}) \\([^\\)]*\\) ([0-9\\.]+[^ \n]*)")
  302. set(Gettext_VERSION "${CMAKE_MATCH_2}")
  303. set(GETTEXT_VERSION_STRING "${Gettext_VERSION}")
  304. endif()
  305. unset(gettext_version)
  306. unset(msgmerge_name)
  307. unset(msgmerge_namewe)
  308. endif()
  309. include(FindPackageHandleStandardArgs)
  310. find_package_handle_standard_args(Gettext
  311. REQUIRED_VARS GETTEXT_MSGMERGE_EXECUTABLE GETTEXT_MSGFMT_EXECUTABLE
  312. VERSION_VAR Gettext_VERSION)
  313. function(_GETTEXT_GET_UNIQUE_TARGET_NAME _name _unique_name)
  314. set(propertyName "_GETTEXT_UNIQUE_COUNTER_${_name}")
  315. get_property(currentCounter GLOBAL PROPERTY "${propertyName}")
  316. if(NOT currentCounter)
  317. set(currentCounter 1)
  318. endif()
  319. set(${_unique_name} "${_name}_${currentCounter}" PARENT_SCOPE)
  320. math(EXPR currentCounter "${currentCounter} + 1")
  321. set_property(GLOBAL PROPERTY ${propertyName} ${currentCounter})
  322. endfunction()
  323. macro(GETTEXT_CREATE_TRANSLATIONS _potFile _firstPoFileArg)
  324. # make it a real variable, so we can modify it here
  325. set(_firstPoFile "${_firstPoFileArg}")
  326. set(_gmoFiles)
  327. get_filename_component(_potName ${_potFile} NAME)
  328. string(REGEX REPLACE "^(.+)(\\.[^.]+)$" "\\1" _potBasename ${_potName})
  329. get_filename_component(_absPotFile ${_potFile} ABSOLUTE)
  330. set(_addToAll)
  331. if(${_firstPoFile} STREQUAL "ALL")
  332. set(_addToAll "ALL")
  333. set(_firstPoFile)
  334. endif()
  335. foreach(_currentPoFile ${_firstPoFile} ${ARGN})
  336. get_filename_component(_absFile ${_currentPoFile} ABSOLUTE)
  337. get_filename_component(_abs_PATH ${_absFile} PATH)
  338. get_filename_component(_lang ${_absFile} NAME_WE)
  339. set(_gmoFile ${CMAKE_CURRENT_BINARY_DIR}/${_lang}.gmo)
  340. add_custom_command(
  341. OUTPUT ${_gmoFile}
  342. COMMAND ${GETTEXT_MSGMERGE_EXECUTABLE} --quiet --update --backup=none ${_absFile} ${_absPotFile}
  343. COMMAND ${GETTEXT_MSGFMT_EXECUTABLE} -o ${_gmoFile} ${_absFile}
  344. DEPENDS ${_absPotFile} ${_absFile}
  345. )
  346. install(FILES ${_gmoFile} DESTINATION share/locale/${_lang}/LC_MESSAGES RENAME ${_potBasename}.mo)
  347. set(_gmoFiles ${_gmoFiles} ${_gmoFile})
  348. endforeach()
  349. if(NOT TARGET translations)
  350. add_custom_target(translations)
  351. endif()
  352. _GETTEXT_GET_UNIQUE_TARGET_NAME(translations uniqueTargetName)
  353. add_custom_target(${uniqueTargetName} ${_addToAll} DEPENDS ${_gmoFiles})
  354. add_dependencies(translations ${uniqueTargetName})
  355. endmacro()
  356. function(GETTEXT_PROCESS_POT_FILE _potFile)
  357. set(_gmoFiles)
  358. set(_options ALL)
  359. set(_oneValueArgs INSTALL_DESTINATION)
  360. set(_multiValueArgs LANGUAGES)
  361. cmake_parse_arguments(_parsedArguments "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
  362. get_filename_component(_potName ${_potFile} NAME)
  363. string(REGEX REPLACE "^(.+)(\\.[^.]+)$" "\\1" _potBasename ${_potName})
  364. get_filename_component(_absPotFile ${_potFile} ABSOLUTE)
  365. foreach(_lang ${_parsedArguments_LANGUAGES})
  366. set(_poFile "${CMAKE_CURRENT_BINARY_DIR}/${_lang}.po")
  367. set(_gmoFile "${CMAKE_CURRENT_BINARY_DIR}/${_lang}.gmo")
  368. add_custom_command(
  369. OUTPUT "${_poFile}"
  370. COMMAND ${GETTEXT_MSGMERGE_EXECUTABLE} --quiet --update --backup=none ${_poFile} ${_absPotFile}
  371. DEPENDS ${_absPotFile}
  372. )
  373. add_custom_command(
  374. OUTPUT "${_gmoFile}"
  375. COMMAND ${GETTEXT_MSGFMT_EXECUTABLE} -o ${_gmoFile} ${_poFile}
  376. DEPENDS ${_absPotFile} ${_poFile}
  377. )
  378. if(_parsedArguments_INSTALL_DESTINATION)
  379. install(FILES ${_gmoFile} DESTINATION ${_parsedArguments_INSTALL_DESTINATION}/${_lang}/LC_MESSAGES RENAME ${_potBasename}.mo)
  380. endif()
  381. list(APPEND _gmoFiles ${_gmoFile})
  382. endforeach()
  383. if(NOT TARGET potfiles)
  384. add_custom_target(potfiles)
  385. endif()
  386. _GETTEXT_GET_UNIQUE_TARGET_NAME( potfiles uniqueTargetName)
  387. if(_parsedArguments_ALL)
  388. add_custom_target(${uniqueTargetName} ALL DEPENDS ${_gmoFiles})
  389. else()
  390. add_custom_target(${uniqueTargetName} DEPENDS ${_gmoFiles})
  391. endif()
  392. add_dependencies(potfiles ${uniqueTargetName})
  393. endfunction()
  394. function(GETTEXT_PROCESS_PO_FILES _lang)
  395. set(_options ALL)
  396. set(_oneValueArgs INSTALL_DESTINATION)
  397. set(_multiValueArgs PO_FILES)
  398. set(_gmoFiles)
  399. cmake_parse_arguments(_parsedArguments "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
  400. foreach(_current_PO_FILE ${_parsedArguments_PO_FILES})
  401. get_filename_component(_name ${_current_PO_FILE} NAME)
  402. string(REGEX REPLACE "^(.+)(\\.[^.]+)$" "\\1" _basename ${_name})
  403. set(_gmoFile ${CMAKE_CURRENT_BINARY_DIR}/${_basename}.gmo)
  404. add_custom_command(OUTPUT ${_gmoFile}
  405. COMMAND ${GETTEXT_MSGFMT_EXECUTABLE} -o ${_gmoFile} ${_current_PO_FILE}
  406. WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
  407. DEPENDS ${_current_PO_FILE}
  408. )
  409. if(_parsedArguments_INSTALL_DESTINATION)
  410. install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${_basename}.gmo DESTINATION ${_parsedArguments_INSTALL_DESTINATION}/${_lang}/LC_MESSAGES/ RENAME ${_basename}.mo)
  411. endif()
  412. list(APPEND _gmoFiles ${_gmoFile})
  413. endforeach()
  414. if(NOT TARGET pofiles)
  415. add_custom_target(pofiles)
  416. endif()
  417. _GETTEXT_GET_UNIQUE_TARGET_NAME(pofiles uniqueTargetName)
  418. if(_parsedArguments_ALL)
  419. add_custom_target(${uniqueTargetName} ALL DEPENDS ${_gmoFiles})
  420. else()
  421. add_custom_target(${uniqueTargetName} DEPENDS ${_gmoFiles})
  422. endif()
  423. add_dependencies(pofiles ${uniqueTargetName})
  424. endfunction()