Blender V5.3
bpy_app_translations.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
12
13#include <Python.h>
14
15/* XXX Why bloody hell isn't that included in Python.h???? */
16#include <structmember.h>
17
18#include "../generic/python_compat.hh" /* IWYU pragma: keep. */
19
20#include "BLI_utildefines.hh"
21
22#include "BPY_extern.hh"
24
25#include "MEM_guardedalloc.h"
26
27#include "BLT_lang.hh"
28#include "BLT_translation.hh"
29
30#include "RNA_types.hh"
31
32#ifdef WITH_INTERNATIONAL
33# include "BLI_map.hh"
34# include "BLI_string_ref.hh"
35# include "BLI_string_utf8.hh"
36#endif
37
38namespace blender {
39
40/* ------------------------------------------------------------------- */
43
45 PyObject_HEAD
47 const char *context_separator;
49 PyObject *contexts;
56 PyObject *py_messages;
57};
58
59/* Our singleton instance pointer */
61
63
64/* ------------------------------------------------------------------- */
67
68#ifdef WITH_INTERNATIONAL
69
70struct MessageKeyRef {
71 StringRef context;
73
74 uint64_t hash() const
75 {
77 !BLT_is_default_context(this->context));
78 return get_default_hash(this->context, this->str);
79 }
80};
81
82struct MessageKey {
83 std::string context;
84 std::string str;
85
86 uint64_t hash() const
87 {
88 return get_default_hash(this->context, this->str);
89 }
90
91 static uint64_t hash_as(const MessageKeyRef &key)
92 {
93 return key.hash();
94 }
95};
96
97inline bool operator==(const MessageKey &a, const MessageKey &b)
98{
99 return a.context == b.context && a.str == b.str;
100}
101
102inline bool operator==(const MessageKeyRef &a, const MessageKey &b)
103{
104 return a.context == b.context && a.str == b.str;
105}
106
108
109/* ------------------------------------------------------------------- */
112
120static std::unique_ptr<Map<MessageKey, std::string>> &get_translations_cache()
121{
122 static std::unique_ptr<Map<MessageKey, std::string>> translations;
123 return translations;
124}
125
126static void _clear_translations_cache()
127{
128 get_translations_cache().reset();
129}
130
131static void _build_translations_cache(PyObject *py_messages, const char *locale)
132{
133 PyObject *uuid, *uuid_dict;
134 Py_ssize_t pos = 0;
135 char *language = nullptr, *language_country = nullptr, *language_variant = nullptr;
136
137 /* For each py dict, we'll search for full locale, then language+country, then language+variant,
138 * then only language keys... */
140 locale, &language, nullptr, nullptr, &language_country, &language_variant);
141
142 /* Clear the cached #Map if needed, and create a new one. */
143 _clear_translations_cache();
144 get_translations_cache() = std::make_unique<Map<MessageKey, std::string>>();
145
146 /* Iterate over all Python dictionaries. */
147 while (PyDict_Next(py_messages, &pos, &uuid, &uuid_dict)) {
148 PyObject *lang_dict;
149
150# if 0
151 PyObject_Print(uuid_dict, stdout, 0);
152 printf("\n");
153# endif
154
155 /* Try to get first complete locale, then language+country,
156 * then language+variant, then only language. */
157 lang_dict = PyDict_GetItemString(uuid_dict, locale);
158 if (!lang_dict && language_country) {
159 lang_dict = PyDict_GetItemString(uuid_dict, language_country);
160 locale = language_country;
161 }
162 if (!lang_dict && language_variant) {
163 lang_dict = PyDict_GetItemString(uuid_dict, language_variant);
164 locale = language_variant;
165 }
166 if (!lang_dict && language) {
167 lang_dict = PyDict_GetItemString(uuid_dict, language);
168 locale = language;
169 }
170
171 if (lang_dict) {
172 PyObject *pykey, *trans;
173 Py_ssize_t ppos = 0;
174
175 if (!PyDict_Check(lang_dict)) {
176 printf("WARNING! In translations' dict of \"");
177 PyObject_Print(uuid, stdout, Py_PRINT_RAW);
178 printf("\":\n");
179 printf(
180 " Each language key must have a dictionary as value, \"%s\" is not valid, "
181 "skipping: ",
182 locale);
183 PyObject_Print(lang_dict, stdout, Py_PRINT_RAW);
184 printf("\n");
185 continue;
186 }
187
188 /* Iterate over all translations of the found language dict and populate our cache. */
189 while (PyDict_Next(lang_dict, &ppos, &pykey, &trans)) {
190 const char *msgctxt = nullptr, *msgid = nullptr;
191 bool invalid_key = false;
192
193 if ((PyTuple_CheckExact(pykey) == false) || (PyTuple_GET_SIZE(pykey) != 2)) {
194 invalid_key = true;
195 }
196 else {
197 PyObject *tmp = PyTuple_GET_ITEM(pykey, 0);
198 if (tmp == Py_None) {
200 }
201 else if (PyUnicode_Check(tmp)) {
202 msgctxt = PyUnicode_AsUTF8(tmp);
203 }
204 else {
205 invalid_key = true;
206 }
207
208 tmp = PyTuple_GET_ITEM(pykey, 1);
209 if (PyUnicode_Check(tmp)) {
210 msgid = PyUnicode_AsUTF8(tmp);
211 }
212 else {
213 invalid_key = true;
214 }
215 }
216
217 if (invalid_key) {
218 printf("WARNING! In translations' dict of \"");
219 PyObject_Print(uuid, stdout, Py_PRINT_RAW);
220 printf("\", %s language:\n", locale);
221 printf(
222 " Keys must be tuples of (msgctxt [string or None], msgid [string]), "
223 "this one is not valid, skipping: ");
224 PyObject_Print(pykey, stdout, Py_PRINT_RAW);
225 printf("\n");
226 continue;
227 }
228 if (PyUnicode_Check(trans) == false) {
229 printf("WARNING! In translations' dict of \"");
230 PyObject_Print(uuid, stdout, Py_PRINT_RAW);
231 printf("\":\n");
232 printf(" Values must be strings, this one is not valid, skipping: ");
233 PyObject_Print(trans, stdout, Py_PRINT_RAW);
234 printf("\n");
235 continue;
236 }
237
238 /* Do not overwrite existing keys! */
239 if (!BPY_app_translations_py_pgettext(msgctxt, msgid).has_value()) {
240 MessageKey key;
241 key.context = BLT_is_default_context(msgctxt) ? BLT_I18NCONTEXT_DEFAULT_BPYRNA : msgctxt;
242 key.str = msgid;
243 Py_ssize_t trans_str_len;
244 const char *trans_str = PyUnicode_AsUTF8AndSize(trans, &trans_str_len);
245 get_translations_cache()->add(key, std::string(trans_str, trans_str_len));
246 }
247 }
248 }
249 }
250
251 /* Clean up! */
252 MEM_SAFE_DELETE(language);
253 MEM_SAFE_DELETE(language_country);
254 MEM_SAFE_DELETE(language_variant);
255}
256
257std::optional<StringRefNull> BPY_app_translations_py_pgettext(const StringRef msgctxt,
258 const StringRef msgid)
259{
260# define STATIC_LOCALE_SIZE 32 /* Should be more than enough! */
261
262 static char locale[STATIC_LOCALE_SIZE] = "";
263 const char *tmp;
264
265 /* Just in case, should never happen! */
266 if (!_translations) {
267 return std::nullopt;
268 }
269
270 tmp = BLT_lang_get();
271 if (!STREQ(tmp, locale) || !get_translations_cache()) {
272 /* This function may be called from C (i.e. outside of python interpreter 'context'). */
273 PyGILState_STATE _py_state = PyGILState_Ensure();
274
275 STRNCPY_UTF8(locale, tmp);
276
277 /* Locale changed or cache does not exist, refresh the whole cache! */
278 _build_translations_cache(_translations->py_messages, locale);
279
280 PyGILState_Release(_py_state);
281 }
282
283 /* And now, simply create the key (context, messageid) and find it in the cached dict! */
284 MessageKeyRef key;
285 key.context = BLT_is_default_context(msgctxt) ? BLT_I18NCONTEXT_DEFAULT_BPYRNA : msgctxt;
286 key.str = msgid;
287
288 const std::string *result = get_translations_cache()->lookup_ptr_as(key);
289 if (!result) {
290 return std::nullopt;
291 }
292 return *result;
293
294# undef STATIC_LOCALE_SIZE
295}
296
297#endif /* WITH_INTERNATIONAL */
298
300 /* Wrap. */
301 app_translations_py_messages_register_doc,
302 ".. function:: register(module_name, translations_dict)\n"
303 "\n"
304 " Registers an addon's UI translations.\n"
305 "\n"
306 " .. note::\n"
307 " Does nothing when Blender is built without internationalization support.\n"
308 "\n"
309 " :param module_name: The name identifying the addon.\n"
310 " :type module_name: str\n"
311 " :param translations_dict: A dictionary built like that:\n"
312 " ``{locale: {msg_key: msg_translation, ...}, ...}``\n"
313 " :type translations_dict: dict[str, dict[tuple[str, str], str]]\n"
314 "\n");
316 PyObject *args,
317 PyObject *kw)
318{
319#ifdef WITH_INTERNATIONAL
320 static const char *kwlist[] = {"module_name", "translations_dict", nullptr};
321 PyObject *module_name, *uuid_dict;
322
323 if (!PyArg_ParseTupleAndKeywords(args,
324 kw,
325 "O!" /* `module_name` */
326 "O!" /* `translations_dict` */
327 ":bpy.app.translations.register",
328 (char **)kwlist,
329 &PyUnicode_Type,
330 &module_name,
331 &PyDict_Type,
332 &uuid_dict))
333 {
334 return nullptr;
335 }
336
337 if (PyDict_Contains(self->py_messages, module_name)) {
338 PyErr_Format(
339 PyExc_ValueError,
340 "bpy.app.translations.register: translations message cache already contains some data for "
341 "addon '%s'",
342 PyUnicode_AsUTF8(module_name));
343 return nullptr;
344 }
345
346 PyDict_SetItem(self->py_messages, module_name, uuid_dict);
347
348 /* Clear cached messages dict! */
349 _clear_translations_cache();
350#else
351 (void)self;
352 (void)args;
353 (void)kw;
354#endif
355
356 /* And we are done! */
357 Py_RETURN_NONE;
358}
359
361 /* Wrap. */
362 app_translations_py_messages_unregister_doc,
363 ".. function:: unregister(module_name)\n"
364 "\n"
365 " Unregisters an addon's UI translations.\n"
366 "\n"
367 " .. note::\n"
368 " Does nothing when Blender is built without internationalization support.\n"
369 "\n"
370 " :param module_name: The name identifying the addon.\n"
371 " :type module_name: str\n"
372 "\n");
374 PyObject *args,
375 PyObject *kw)
376{
377#ifdef WITH_INTERNATIONAL
378 static const char *kwlist[] = {"module_name", nullptr};
379 PyObject *module_name;
380
381 if (!PyArg_ParseTupleAndKeywords(args,
382 kw,
383 "O!" /* `module_name` */
384 ":bpy.app.translations.unregister",
385 (char **)kwlist,
386 &PyUnicode_Type,
387 &module_name))
388 {
389 return nullptr;
390 }
391
392 if (PyDict_Contains(self->py_messages, module_name)) {
393 PyDict_DelItem(self->py_messages, module_name);
394 /* Clear cached messages map. */
395 _clear_translations_cache();
396 }
397#else
398 (void)self;
399 (void)args;
400 (void)kw;
401#endif
402
403 /* And we are done! */
404 Py_RETURN_NONE;
405}
406
408
409/* ------------------------------------------------------------------- */
412
413/* This is always available (even when WITH_INTERNATIONAL is not defined). */
414
416
418
419/* These fields are just empty placeholders, actual values get set in app_translations_struct().
420 * This allows us to avoid many handwriting, and above all,
421 * to keep all context definition stuff in BLT_translation.hh! */
422static PyStructSequence_Field app_translations_contexts_fields[ARRAY_SIZE(_contexts)] = {
423 {nullptr}};
424
425static PyStructSequence_Desc app_translations_contexts_desc = {
426 /*name*/ "bpy.app.translations.contexts",
427 /*doc*/ "This named tuple contains all predefined translation contexts",
429 /*n_in_sequence*/ ARRAY_SIZE(app_translations_contexts_fields) - 1,
430};
431
433{
434 PyObject *translations_contexts;
436 int pos = 0;
437
438 translations_contexts = PyStructSequence_New(&BlenderAppTranslationsContextsType);
439 if (translations_contexts == nullptr) {
440 return nullptr;
441 }
442
443#define SetObjString(item) \
444 PyStructSequence_SET_ITEM(translations_contexts, pos++, PyUnicode_FromString(item))
445#define SetObjNone() PyStructSequence_SET_ITEM(translations_contexts, pos++, Py_NewRef(Py_None))
446
447 for (ctxt = _contexts; ctxt->c_id; ctxt++) {
448 if (ctxt->value) {
449 SetObjString(ctxt->value);
450 }
451 else {
452 SetObjNone();
453 }
454 }
455
456#undef SetObjString
457#undef SetObjNone
458
459 return translations_contexts;
460}
461
463
464/* ------------------------------------------------------------------- */
467
469 /* Wrap. */
470 app_translations_contexts_doc,
471 "A named tuple containing all predefined translation contexts.\n"
472 "\n"
473 ".. warning::\n"
474 " Never use a (new) context starting with \"" BLT_I18NCONTEXT_DEFAULT_BPYRNA
475 "\", it would be internally\n"
476 " assimilated as the default one!\n");
478 /* Wrap. */
479 app_translations_contexts_C_to_py_doc,
480 "A readonly dict mapping contexts' C-identifiers to their py-identifiers.\n");
481
482static PyMemberDef app_translations_members[] = {
483 {"contexts",
484 T_OBJECT_EX,
486 READONLY,
487 app_translations_contexts_doc},
488 {"contexts_C_to_py",
489 T_OBJECT_EX,
490 offsetof(BlenderAppTranslations, contexts_C_to_py),
491 READONLY,
492 app_translations_contexts_C_to_py_doc},
493 {nullptr},
494};
495
497 /* Wrap. */
498 app_translations_locale_doc,
499 "The actual locale currently in use (will always return an empty string when Blender "
500 "is built without "
501 "internationalization support).\n"
502 "\n"
503 ":type: str\n");
504static PyObject *app_translations_locale_get(PyObject * /*self*/, void * /*userdata*/)
505{
506 return PyUnicode_FromString(BLT_lang_get());
507}
508
509/* NOTE: defining as getter, as (even if quite unlikely), this *may* change during runtime... */
511 /* Wrap. */
512 app_translations_locales_doc,
513 "All locales currently known by Blender (i.e. available as translations).\n"
514 "\n"
515 ":type: list[str]\n");
516static PyObject *app_translations_locales_get(PyObject * /*self*/, void * /*userdata*/)
517{
518 PyObject *ret;
520 int num_locales = 0, pos = 0;
521
522 if (items) {
523 /* This is not elegant, but simple! */
524 for (it = items; it->identifier; it++) {
525 if (it->value) {
526 num_locales++;
527 }
528 }
529 }
530
531 ret = PyTuple_New(num_locales);
532
533 if (items) {
534 for (it = items; it->identifier; it++) {
535 if (it->value) {
536 PyTuple_SET_ITEM(ret, pos++, PyUnicode_FromString(it->identifier));
537 }
538 }
539 }
540
541 return ret;
542}
543
544static PyGetSetDef app_translations_getseters[] = {
545 /* {name, getter, setter, doc, userdata} */
546 {"locale",
547 static_cast<getter>(app_translations_locale_get),
548 nullptr,
549 app_translations_locale_doc,
550 nullptr},
551 {"locales",
552 static_cast<getter>(app_translations_locales_get),
553 nullptr,
554 app_translations_locales_doc,
555 nullptr},
556 {nullptr},
557};
558
559/* Argument format for #_py_pgettext. */
560#ifdef WITH_INTERNATIONAL
561# define PY_PGETTEXT_FORMAT \
562 "s" /* `msgid` */ \
563 "|" /* Optional arguments. */ \
564 "z" /* `msgctxt` */
565#else
566# define PY_PGETTEXT_FORMAT \
567 "O" /* `msgid` */ \
568 "|" /* Optional arguments. */ \
569 "O" /* `msgctxt` */
570#endif
571
572/* pgettext helper. */
573static PyObject *_py_pgettext(PyObject *args,
574 PyObject *kw,
575 const char *format,
576 const char *(*_pgettext)(const char *, const char *))
577{
578 static const char *kwlist[] = {"msgid", "msgctxt", nullptr};
579
580#ifdef WITH_INTERNATIONAL
581 char *msgid, *msgctxt = nullptr;
582
583 if (!PyArg_ParseTupleAndKeywords(args, kw, format, (char **)kwlist, &msgid, &msgctxt)) {
584 return nullptr;
585 }
586
587 return PyUnicode_FromString((*_pgettext)(msgctxt ? msgctxt : BLT_I18NCONTEXT_DEFAULT, msgid));
588#else
589 PyObject *msgid, *msgctxt;
590 (void)_pgettext;
591
592 if (!PyArg_ParseTupleAndKeywords(
593 args, kw, format, const_cast<char **>(kwlist), &msgid, &msgctxt))
594 {
595 return nullptr;
596 }
597
598 return Py_NewRef(msgid);
599#endif
600}
601
603 /* Wrap. */
604 app_translations_pgettext_doc,
605 ".. function:: pgettext(msgid, msgctxt=None)\n"
606 "\n"
607 " Try to translate the given msgid (with optional msgctxt).\n"
608 "\n"
609 " .. note::\n"
610 " The ``(msgid, msgctxt)`` parameters order has been switched compared to gettext "
611 "function, to allow\n"
612 " single-parameter calls (context then defaults to BLT_I18NCONTEXT_DEFAULT).\n"
613 "\n"
614 " .. note::\n"
615 " You should really rarely need to use this function in regular addon code, as all "
616 "translation should be\n"
617 " handled by Blender internal code. "
618 "The only exceptions are strings containing formatting "
619 "(like \"File: %r\"),\n"
620 " but you should rather use :func:`pgettext_iface`/:func:`pgettext_tip` in those cases!\n"
621 "\n"
622 " .. note::\n"
623 " Does nothing when Blender is built without internationalization support (hence always "
624 "returns ``msgid``).\n"
625 "\n"
626 " :param msgid: The string to translate.\n"
627 " :type msgid: str\n"
628 " :param msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
629 " :type msgctxt: str | None\n"
630 " :return: The translated string (or msgid if no translation was found).\n"
631 " :rtype: str\n"
632 "\n");
634 PyObject *args,
635 PyObject *kw)
636{
637 return _py_pgettext(args, kw, PY_PGETTEXT_FORMAT ":bpy.app.translations.pgettext", BLT_pgettext);
638}
639
641 /* Wrap. */
642 app_translations_pgettext_n_doc,
643 ".. function:: pgettext_n(msgid, msgctxt=None)\n"
644 "\n"
645 " Extract the given msgid to translation files. This is a no-op function that will "
646 "only mark the string to extract, but not perform the actual translation.\n"
647 "\n"
648 " .. note::\n"
649 " See :func:`pgettext` notes.\n"
650 "\n"
651 " :param msgid: The string to extract.\n"
652 " :type msgid: str\n"
653 " :param msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
654 " :type msgctxt: str | None\n"
655 " :return: The original string.\n"
656 " :rtype: str\n"
657 "\n");
659 PyObject *args,
660 PyObject *kw)
661{
662 static const char *kwlist[] = {"msgid", "msgctxt", nullptr};
663 PyObject *msgid, *msgctxt;
664 // (void)_pgettext;
665
666 if (!PyArg_ParseTupleAndKeywords(args,
667 kw,
668 "O" /* `msgid` */
669 "|" /* Optional arguments. */
670 "O" /* `msgctxt` */
671 ":bpy.app.translations.pgettext_n",
672 const_cast<char **>(kwlist),
673 &msgid,
674 &msgctxt))
675 {
676 return nullptr;
677 }
678
679 return Py_NewRef(msgid);
680}
681
683 /* Wrap. */
684 app_translations_pgettext_iface_doc,
685 ".. function:: pgettext_iface(msgid, msgctxt=None)\n"
686 "\n"
687 " Try to translate the given msgid (with optional msgctxt), if labels' translation "
688 "is enabled.\n"
689 "\n"
690 " .. note::\n"
691 " See :func:`pgettext` notes.\n"
692 "\n"
693 " :param msgid: The string to translate.\n"
694 " :type msgid: str\n"
695 " :param msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
696 " :type msgctxt: str | None\n"
697 " :return: The translated string (or msgid if no translation was found).\n"
698 " :rtype: str\n"
699 "\n");
701 PyObject *args,
702 PyObject *kw)
703{
704 return _py_pgettext(
705 args, kw, PY_PGETTEXT_FORMAT ":bpy.app.translations.pgettext_iface", BLT_translate_do_iface);
706}
707
709 /* Wrap. */
710 app_translations_pgettext_tip_doc,
711 ".. function:: pgettext_tip(msgid, msgctxt=None)\n"
712 "\n"
713 " Try to translate the given msgid (with optional msgctxt), if tooltips' "
714 "translation is enabled.\n"
715 "\n"
716 " .. note::\n"
717 " See :func:`pgettext` notes.\n"
718 "\n"
719 " :param msgid: The string to translate.\n"
720 " :type msgid: str\n"
721 " :param msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
722 " :type msgctxt: str | None\n"
723 " :return: The translated string (or msgid if no translation was found).\n"
724 " :rtype: str\n"
725 "\n");
727 PyObject *args,
728 PyObject *kw)
729{
730 return _py_pgettext(
731 args, kw, PY_PGETTEXT_FORMAT ":bpy.app.translations.pgettext_tip", BLT_translate_do_tooltip);
732}
733
735 /* Wrap. */
736 app_translations_pgettext_rpt_doc,
737 ".. function:: pgettext_rpt(msgid, msgctxt=None)\n"
738 "\n"
739 " Try to translate the given msgid (with optional msgctxt), if reports' translation "
740 "is enabled.\n"
741 "\n"
742 " .. note::\n"
743 " See :func:`pgettext` notes.\n"
744 "\n"
745 " :param msgid: The string to translate.\n"
746 " :type msgid: str\n"
747 " :param msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
748 " :type msgctxt: str | None\n"
749 " :return: The translated string (or msgid if no translation was found).\n"
750 " :rtype: str\n"
751 "\n");
753 PyObject *args,
754 PyObject *kw)
755{
756 return _py_pgettext(
757 args, kw, PY_PGETTEXT_FORMAT ":bpy.app.translations.pgettext_rpt", BLT_translate_do_report);
758}
759
761 /* Wrap. */
762 app_translations_pgettext_data_doc,
763 ".. function:: pgettext_data(msgid, msgctxt=None)\n"
764 "\n"
765 " Try to translate the given msgid (with optional msgctxt), if new data name's "
766 "translation is enabled.\n"
767 "\n"
768 " .. note::\n"
769 " See :func:`pgettext` notes.\n"
770 "\n"
771 " :param msgid: The string to translate.\n"
772 " :type msgid: str\n"
773 " :param msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
774 " :type msgctxt: str | None\n"
775 " :return: The translated string (or ``msgid`` if no translation was found).\n"
776 " :rtype: str\n"
777 "\n");
779 PyObject *args,
780 PyObject *kw)
781{
782 return _py_pgettext(args,
783 kw,
784 PY_PGETTEXT_FORMAT ":bpy.app.translations.pgettext_data",
786}
787
789 /* Wrap. */
790 app_translations_locale_explode_doc,
791 ".. function:: locale_explode(locale)\n"
792 "\n"
793 " Return all components and their combinations of the given ISO locale string.\n"
794 "\n"
795 " >>> bpy.app.translations.locale_explode(\"sr_RS@latin\")\n"
796 " (\"sr\", \"RS\", \"latin\", \"sr_RS\", \"sr@latin\")\n"
797 "\n"
798 " For non-complete locales, missing elements will be None.\n"
799 "\n"
800 " :param locale: The ISO locale string to explode.\n"
801 " :type locale: str\n"
802 " :return: A tuple ``(language, country, variant, language_country, language@variant)``.\n"
803 " :rtype: tuple[str | None, str | None, str | None, str | None, str | None]\n"
804 "\n");
806 PyObject *args,
807 PyObject *kw)
808{
809 PyObject *ret_tuple;
810 static const char *kwlist[] = {"locale", nullptr};
811 const char *locale;
812 char *language, *country, *variant, *language_country, *language_variant;
813
814 if (!PyArg_ParseTupleAndKeywords(args,
815 kw,
816 "s" /* `locale` */
817 ":bpy.app.translations.locale_explode",
818 const_cast<char **>(kwlist),
819 &locale))
820 {
821 return nullptr;
822 }
823
825 locale, &language, &country, &variant, &language_country, &language_variant);
826
827 ret_tuple = Py_BuildValue(
828 "sssss", language, country, variant, language_country, language_variant);
829
830 MEM_SAFE_DELETE(language);
831 MEM_SAFE_DELETE(country);
832 MEM_SAFE_DELETE(variant);
833 MEM_SAFE_DELETE(language_country);
834 MEM_SAFE_DELETE(language_variant);
835
836 return ret_tuple;
837}
838
839#ifdef __GNUC__
840# ifdef __clang__
841# pragma clang diagnostic push
842# pragma clang diagnostic ignored "-Wcast-function-type"
843# else
844# pragma GCC diagnostic push
845# pragma GCC diagnostic ignored "-Wcast-function-type"
846# endif
847#endif
848
849static PyMethodDef app_translations_methods[] = {
850 /* Can't use METH_KEYWORDS alone, see http://bugs.python.org/issue11587 */
851 {"register",
852 reinterpret_cast<PyCFunction>(app_translations_py_messages_register),
853 METH_VARARGS | METH_KEYWORDS,
854 app_translations_py_messages_register_doc},
855 {"unregister",
856 reinterpret_cast<PyCFunction>(app_translations_py_messages_unregister),
857 METH_VARARGS | METH_KEYWORDS,
858 app_translations_py_messages_unregister_doc},
859 {"pgettext",
860 reinterpret_cast<PyCFunction>(app_translations_pgettext),
861 METH_VARARGS | METH_KEYWORDS | METH_STATIC,
862 app_translations_pgettext_doc},
863 {"pgettext_n",
864 reinterpret_cast<PyCFunction>(app_translations_pgettext_n),
865 METH_VARARGS | METH_KEYWORDS | METH_STATIC,
866 app_translations_pgettext_n_doc},
867 {"pgettext_iface",
868 reinterpret_cast<PyCFunction>(app_translations_pgettext_iface),
869 METH_VARARGS | METH_KEYWORDS | METH_STATIC,
870 app_translations_pgettext_iface_doc},
871 {"pgettext_tip",
872 reinterpret_cast<PyCFunction>(app_translations_pgettext_tip),
873 METH_VARARGS | METH_KEYWORDS | METH_STATIC,
874 app_translations_pgettext_tip_doc},
875 {"pgettext_rpt",
876 reinterpret_cast<PyCFunction>(app_translations_pgettext_rpt),
877 METH_VARARGS | METH_KEYWORDS | METH_STATIC,
878 app_translations_pgettext_rpt_doc},
879 {"pgettext_data",
880 reinterpret_cast<PyCFunction>(app_translations_pgettext_data),
881 METH_VARARGS | METH_KEYWORDS | METH_STATIC,
882 app_translations_pgettext_data_doc},
883 {"locale_explode",
884 reinterpret_cast<PyCFunction>(app_translations_locale_explode),
885 METH_VARARGS | METH_KEYWORDS | METH_STATIC,
886 app_translations_locale_explode_doc},
887 {nullptr},
888};
889
890#ifdef __GNUC__
891# ifdef __clang__
892# pragma clang diagnostic pop
893# else
894# pragma GCC diagnostic pop
895# endif
896#endif
897
898static PyObject *app_translations_new(PyTypeObject *type, PyObject *args, PyObject *kw)
899{
900 // printf("%s (%p)\n", __func__, _translations);
901
902 /* Only called internally on startup, no need for exceptions. */
903 BLI_assert(PyTuple_GET_SIZE(args) == 0 && kw == nullptr);
904 UNUSED_VARS_NDEBUG(args, kw);
905
906 if (!_translations) {
907 _translations = reinterpret_cast<BlenderAppTranslations *>(type->tp_alloc(type, 0));
908 if (_translations) {
909 PyObject *py_ctxts;
911
913
914 py_ctxts = _PyDict_NewPresized(ARRAY_SIZE(_contexts));
915 for (ctxt = _contexts; ctxt->c_id; ctxt++) {
916 PyObject *val = PyUnicode_FromString(ctxt->py_id);
917 PyDict_SetItemString(py_ctxts, ctxt->c_id, val);
918 Py_DECREF(val);
919 }
920 _translations->contexts_C_to_py = PyDictProxy_New(py_ctxts);
921 Py_DECREF(py_ctxts); /* The actual dict is only owned by its proxy */
922
923 _translations->py_messages = PyDict_New();
924 }
925 }
926
927 return reinterpret_cast<PyObject *>(_translations);
928}
929
930static void app_translations_free(void *self_v)
931{
932 BlenderAppTranslations *self = static_cast<BlenderAppTranslations *>(self_v);
933
934 Py_DECREF(self->contexts);
935 Py_DECREF(self->contexts_C_to_py);
936 Py_DECREF(self->py_messages);
937
938 PyObject_Del(self);
939#ifdef WITH_INTERNATIONAL
940 _clear_translations_cache();
941#endif
942}
943
945 /* Wrap. */
946 app_translations_doc,
947 "This object contains some data/methods regarding internationalization in Blender, "
948 "and allows every py script\n"
949 "to feature translations for its own UI messages.\n"
950 "\n");
951static PyTypeObject BlenderAppTranslationsType = {
952 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
953 /*tp_name*/ "bpy_app_translations",
954 /*tp_basicsize*/ sizeof(BlenderAppTranslations),
955 /*tp_itemsize*/ 0,
956 /*tp_dealloc*/ nullptr,
957 /*tp_vectorcall_offset*/ 0,
958 /*tp_getattr*/ nullptr,
959 /*tp_setattr*/ nullptr,
960 /*tp_as_async*/ nullptr,
961 /*tp_repr*/ nullptr,
962 /*tp_as_number*/ nullptr,
963 /*tp_as_sequence*/ nullptr,
964 /*tp_as_mapping*/ nullptr,
965 /*tp_hash*/ nullptr,
966 /*tp_call*/ nullptr,
967 /*tp_str*/ nullptr,
968 /*tp_getattro*/ nullptr,
969 /*tp_setattro*/ nullptr,
970 /*tp_as_buffer*/ nullptr,
971 /*tp_flags*/ Py_TPFLAGS_DEFAULT,
972 /*tp_doc*/ app_translations_doc,
973 /*tp_traverse*/ nullptr,
974 /*tp_clear*/ nullptr,
975 /*tp_richcompare*/ nullptr,
976 /*tp_weaklistoffset*/ 0,
977 /*tp_iter*/ nullptr,
978 /*tp_iternext*/ nullptr,
979 /*tp_methods*/ app_translations_methods,
980 /*tp_members*/ app_translations_members,
981 /*tp_getset*/ app_translations_getseters,
982 /*tp_base*/ nullptr,
983 /*tp_dict*/ nullptr,
984 /*tp_descr_get*/ nullptr,
985 /*tp_descr_set*/ nullptr,
986 /*tp_dictoffset*/ 0,
987 /*tp_init*/ nullptr,
988 /*tp_alloc*/ nullptr,
989 /*tp_new*/ app_translations_new,
990 /*tp_free*/ app_translations_free,
991 /*tp_is_gc*/ nullptr,
992 /*tp_bases*/ nullptr,
993 /*tp_mro*/ nullptr,
994 /*tp_cache*/ nullptr,
995 /*tp_subclasses*/ nullptr,
996 /*tp_weaklist*/ nullptr,
997 /*tp_del*/ nullptr,
998 /*tp_version_tag*/ 0,
999 /*tp_finalize*/ nullptr,
1000 /*tp_vectorcall*/ nullptr,
1001};
1002
1004{
1005 PyObject *ret;
1006
1007 /* Let's finalize our contexts `PyStructSequence` definition! */
1008 {
1010 PyStructSequence_Field *desc;
1011
1012 /* We really populate the contexts' fields here! */
1013 for (ctxt = _contexts, desc = app_translations_contexts_desc.fields; ctxt->c_id;
1014 ctxt++, desc++)
1015 {
1016 desc->name = ctxt->py_id;
1017 desc->doc = nullptr;
1018 }
1019 desc->name = desc->doc = nullptr; /* End sentinel! */
1020
1021 PyStructSequence_InitType(&BlenderAppTranslationsContextsType,
1023 }
1024
1025 if (PyType_Ready(&BlenderAppTranslationsType) < 0) {
1026 return nullptr;
1027 }
1028
1029 ret = PyObject_CallObject(reinterpret_cast<PyObject *>(&BlenderAppTranslationsType), nullptr);
1030
1031 /* prevent user from creating new instances */
1032 BlenderAppTranslationsType.tp_new = nullptr;
1033 /* Without this we can't do `set(sys.modules)` #29635. */
1034 BlenderAppTranslationsType.tp_hash = reinterpret_cast<hashfunc>(Py_HashPointer);
1035
1036 return ret;
1037}
1038
1040{
1041/* In case the object remains in a module's name-space, see #44127. */
1042#ifdef WITH_INTERNATIONAL
1043 _clear_translations_cache();
1044#endif
1045}
1046
1048
1049} // namespace blender
#define STRNCPY_UTF8(dst, src)
#define BLT_I18NCONTEXTS_DESC
#define BLT_I18NCONTEXT_DEFAULT
#define BLT_I18NCONTEXT_DEFAULT_BPYRNA
Read Blender memory allocation and freeing.
#define UNUSED_VARS_NDEBUG(...)
#define STREQ(a, b)
#define SetObjString(item)
#define SetObjNone()
#define PY_PGETTEXT_FORMAT
unsigned long long int uint64_t
#define offsetof(t, d)
#define str(s)
bool operator==(const Error &left, const Error &right)
BMesh Iterators.
static PyTypeObject BlenderAppTranslationsType
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
unsigned __int64 uint64_t
Definition BKE_text.h:91
static BLT_i18n_contexts_descriptor _contexts[]
static PyObject * app_translations_pgettext_rpt(BlenderAppTranslations *, PyObject *args, PyObject *kw)
static PyObject * app_translations_locales_get(PyObject *, void *)
static PyObject * app_translations_pgettext_n(BlenderAppTranslations *, PyObject *args, PyObject *kw)
PyDoc_STRVAR(bpy_bm_new_doc, ".. function:: new(*, use_operators=True)\n" "\n" " :param use_operators: Support calling operators in :mod:`bmesh.ops` (uses some " "extra memory per vert/edge/face).\n" " :type use_operators: bool\n" " :return: Return a new, empty BMesh.\n" " :rtype: :class:`bmesh.types.BMesh`\n")
static PyStructSequence_Field app_translations_contexts_fields[ARRAY_SIZE(_contexts)]
static PyObject * _py_pgettext(PyObject *args, PyObject *kw, const char *format, const char *(*_pgettext)(const char *, const char *))
static BlenderAppTranslations * _translations
bool BLT_is_default_context(StringRef msgctxt)
static PyObject * app_translations_pgettext_data(BlenderAppTranslations *, PyObject *args, PyObject *kw)
static void app_translations_free(void *self_v)
static PyObject * app_translations_new(PyTypeObject *type, PyObject *args, PyObject *kw)
const char * BLT_pgettext(const char *msgctxt, const char *msgid)
const char * BLT_translate_do_report(const char *msgctxt, const char *msgid)
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
static PyObject * app_translations_pgettext_tip(BlenderAppTranslations *, PyObject *args, PyObject *kw)
static PyObject * app_translations_pgettext(BlenderAppTranslations *, PyObject *args, PyObject *kw)
void BPY_app_translations_end()
static PyMemberDef app_translations_members[]
static PyObject * app_translations_py_messages_register(BlenderAppTranslations *self, PyObject *args, PyObject *kw)
static PyTypeObject BlenderAppTranslationsContextsType
const char * BLT_translate_do_iface(const char *msgctxt, const char *msgid)
static PyObject * app_translations_py_messages_unregister(BlenderAppTranslations *self, PyObject *args, PyObject *kw)
static PyMethodDef app_translations_methods[]
static PyObject * app_translations_pgettext_iface(BlenderAppTranslations *, PyObject *args, PyObject *kw)
PyObject * BPY_app_translations_struct()
void BLT_lang_locale_explode(const char *locale, char **language, char **country, char **variant, char **language_country, char **language_variant)
Definition blt_lang.cc:288
static PyObject * app_translations_locale_get(PyObject *, void *)
static PyObject * app_translations_locale_explode(BlenderAppTranslations *, PyObject *args, PyObject *kw)
static PyStructSequence_Desc app_translations_contexts_desc
const char * BLT_lang_get()
Definition blt_lang.cc:268
static PyGetSetDef app_translations_getseters[]
const char * BLT_translate_do_new_dataname(const char *msgctxt, const char *msgid)
const EnumPropertyItem * BLT_lang_RNA_enum_properties()
Definition blt_lang.cc:186
const char * BLT_translate_do_tooltip(const char *msgctxt, const char *msgid)
constexpr uint64_t get_default_hash(const T &v, const Args &...args)
Definition BLI_hash.hh:252
static PyObject * app_translations_contexts_make()
#define hash
Definition noise_c.cc:156
header-only compatibility defines.
#define Py_HashPointer
PyObject_HEAD const char * context_separator