Blender V5.3
path_templates.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2025 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <fmt/format.h>
10
11#include "BLT_translation.hh"
12
13#include "BLI_math_base.hh"
14#include "BLI_path_utils.hh"
15#include "BLI_span.hh"
16
18#include "BKE_context.hh"
19#include "BKE_idprop.hh"
20#include "BKE_library.hh"
21#include "BKE_main.hh"
22#include "BKE_path_templates.hh"
23#include "BKE_scene.hh"
24
25#include "RNA_access.hh"
26#include "RNA_prototypes.hh"
27
28#include "DNA_ID_enums.h"
29#include "DNA_node_types.h"
30
31namespace blender {
32
33namespace bke::path_templates {
34
36{
37 if (this->strings_.contains(name)) {
38 return true;
39 }
40 if (this->filepaths_.contains(name)) {
41 return true;
42 }
43 if (this->integers_.contains(name)) {
44 return true;
45 }
46 if (this->floats_.contains(name)) {
47 return true;
48 }
49 return false;
50}
51
53{
54 if (this->strings_.remove(name)) {
55 return true;
56 }
57 if (this->filepaths_.remove(name)) {
58 return true;
59 }
60 if (this->integers_.remove(name)) {
61 return true;
62 }
63 if (this->floats_.remove(name)) {
64 return true;
65 }
66 return false;
67}
68
70{
71 if (this->contains(name)) {
72 return false;
73 }
74 this->strings_.add_new(name, value);
75 return true;
76}
77
79{
80 if (this->contains(name)) {
81 return false;
82 }
83 this->filepaths_.add_new(name, value);
84 return true;
85}
86
88{
89 if (this->contains(name)) {
90 return false;
91 }
92 this->integers_.add_new(name, value);
93 return true;
94}
95
96bool VariableMap::add_float(StringRef name, const double value)
97{
98 if (this->contains(name)) {
99 return false;
100 }
101 this->floats_.add_new(name, value);
102 return true;
103}
104
105std::optional<StringRefNull> VariableMap::get_string(StringRef name) const
106{
107 const std::string *value = this->strings_.lookup_ptr(name);
108 if (value == nullptr) {
109 return std::nullopt;
110 }
111 return StringRefNull(*value);
112}
113
114std::optional<StringRefNull> VariableMap::get_filepath(StringRef name) const
115{
116 const std::string *value = this->filepaths_.lookup_ptr(name);
117 if (value == nullptr) {
118 return std::nullopt;
119 }
120 return StringRefNull(*value);
121}
122
123std::optional<int64_t> VariableMap::get_integer(StringRef name) const
124{
125 const int64_t *value = this->integers_.lookup_ptr(name);
126 if (value == nullptr) {
127 return std::nullopt;
128 }
129 return *value;
130}
131
132std::optional<double> VariableMap::get_float(StringRef name) const
133{
134 const double *value = this->floats_.lookup_ptr(name);
135 if (value == nullptr) {
136 return std::nullopt;
137 }
138 return *value;
139}
140
142 StringRefNull full_path,
143 StringRef fallback)
144{
145 const char *file_name = BLI_path_basename(full_path.c_str());
146 const char *file_name_end = BLI_path_extension_or_end(file_name);
147
148 if (file_name[0] == '\0') {
149 /* If there is no file name, default to the fallback. */
150 return this->add_filepath(var_name, fallback);
151 }
152 if (file_name_end == file_name) {
153 /* When the filename has no extension, but starts with a period. */
154 return this->add_filepath(var_name, StringRef(file_name));
155 }
156 /* Normal case. */
157 return this->add_filepath(var_name, StringRef(file_name, file_name_end));
158}
159
161 StringRefNull full_path,
162 StringRef fallback)
163{
164 /* Empty path. */
165 if (full_path.is_empty()) {
166 return this->add_filepath(var_name, fallback);
167 }
168
169 /* No filename at the end. */
170 if (BLI_path_basename(full_path.c_str()) == full_path.end()) {
171 return this->add_filepath(var_name, full_path);
172 }
173
174 Vector<char> dir_path(full_path.size() + 1);
175 full_path.copy_unsafe(dir_path.data());
176
177 const bool success = BLI_path_parent_dir(dir_path.data());
178
179 if (!success || dir_path[0] == '\0') {
180 /* If no path before the filename, default to the fallback. */
181 return this->add_filepath(var_name, fallback);
182 }
183
184 return this->add_filepath(var_name, dir_path.data());
185}
186
187bool operator==(const Error &left, const Error &right)
188{
189 return left.type == right.type && left.byte_range == right.byte_range;
190}
191
192} // namespace bke::path_templates
193
194using namespace bke::path_templates;
195
196std::optional<VariableMap> BKE_build_template_variables_for_prop(const bContext *C,
197 PointerRNA *ptr,
198 PropertyRNA *prop)
199{
200 /*
201 * This function should be maintained such that it always produces variables
202 * consistent with the variables produced elsewhere in the code base for the
203 * same property. For example, render paths are processed in the rendering
204 * code and the variables for that purpose are built there; this function
205 * should produce variables consistent with that for the same render path
206 * properties here.
207 *
208 * This function is organized into two sections: a `switch` giving each
209 * purpose its "general" and "purpose-specific" variables, and one for
210 * "type-specific" variables. (See the top-level documentation in
211 * BKE_path_templates.hh for details on what that means).
212 *
213 * To add support for additional variables here:
214 *
215 * - For "general" variables, simply add them to
216 * #BKE_add_template_variables_general(). Nothing else special needs to be
217 * done.
218 * - For "purpose-specific" variables, add them to the appropriate
219 * purpose-specific function (e.g.
220 * #BKE_add_template_variables_for_render_path()). If no function exists
221 * for your purpose yet, add a new enum item to #PropertyPathTemplateType
222 * and a corresponding new function, add your variable to the new function,
223 * and then call it from the `switch` on #RNA_property_path_template_type()
224 * below.
225 * - For "type-specific" variables, add them to the appropriate type-specific
226 * function (e.g. #BKE_add_template_variables_for_node()). If no function
227 * exists for that type yet, create a new function for it, add the variable
228 * there, and then call it from the bottom section of this function, with an
229 * appropriate guard on the struct type.
230 */
231
232 /* No property passed, or it doesn't support path templates. */
233 if (ptr == nullptr || prop == nullptr ||
235 {
236 return std::nullopt;
237 }
238
239 VariableMap variables;
240 const Main *bmain = CTX_data_main(C);
241
242 /* General and purpose-specific variables. */
243 switch (RNA_property_path_template_type(prop)) {
244 case PROP_VARIABLES_NONE: {
247 });
248 break;
249 }
250
251 /* Scene render output path, the compositor's File Output node's paths, etc. */
255 });
256
257 const Scene *scene;
258 if (GS(ptr->owner_id->name) == ID_SCE) {
259 scene = reinterpret_cast<const Scene *>(ptr->owner_id);
260 }
261 else {
262 scene = CTX_data_scene(C);
263 }
264
266 break;
267 }
268
269 /* Project settings. */
272 if (project) {
274 }
275 });
276 break;
277 }
278 }
279
280 /* Type-specific variables. */
281
282 /* Nodes. */
283 if (std::optional<AncestorPointerRNA> node_rna_ptr = RNA_struct_search_closest_ancestor_by_type(
284 ptr, RNA_Node))
285 {
286 const bNode *bnode = reinterpret_cast<const bNode *>(node_rna_ptr->data);
287 BKE_add_template_variables_for_node(variables, *bnode);
288 }
289
290 return variables;
291}
292
295{
296 variables.add_string("project_name", project.get_name());
297
298 variables.add_filepath("project_root", project.get_root_path());
299
300 for (const std::unique_ptr<bke::ProjectVariable> &var : project.variables) {
301 switch (var->type_get()) {
303 if (var->string_subtype_get() == bke::ProjectVariableStringSubtype::FILEPATH) {
304 variables.add_filepath(var->name_get(), var->value_string_get());
305 }
306 else {
307 variables.add_string(var->name_get(), var->value_string_get());
308 }
309 break;
310 }
311
313 variables.add_integer(var->name_get(), var->value_int_get());
314 break;
315
317 variables.add_float(var->name_get(), var->value_float_get());
318 break;
319 }
320 }
321}
322
324 const ID *path_owner_id,
326{
327 /* Project variables. */
328 if (project) {
330 }
331
332 /* Global blend filepath (a.k.a. path to the blend file that's currently
333 * open). */
334 {
335 const char *g_blend_file_path = BKE_main_blendfile_path_from_global();
336
337 variables.add_filename_only("blend_name", g_blend_file_path, StringRef(DATA_("Unsaved")));
338
339 /* Note: fallback to `./` for unsaved files, which if used at the start of a
340 * path is equivalent to the current working directory. This is consistent
341 * with how `//` works. */
342 variables.add_path_up_to_file("blend_dir", g_blend_file_path, StringRef("./"));
343 }
344
345 /* Library blend filepath (a.k.a. path to the blend file that actually owns the ID). */
346 if (path_owner_id) {
347 const char *lib_blend_file_path = ID_BLEND_PATH_FROM_GLOBAL(path_owner_id);
348 variables.add_filename_only(
349 "blend_name_lib", lib_blend_file_path, StringRef(DATA_("Unsaved")));
350
351 /* Note: fallback to `./` for unsaved files, which if used at the start of a
352 * path is equivalent to the current working directory. This is consistent
353 * with how `//` works. */
354 variables.add_path_up_to_file("blend_dir_lib", lib_blend_file_path, StringRef("./"));
355 }
356}
357
359{
360 /* Resolution variables. */
361 int res_x, res_y;
362 BKE_render_resolution(&scene.r, false, &res_x, &res_y);
363 variables.add_integer("resolution_x", res_x);
364 variables.add_integer("resolution_y", res_y);
365
366 /* FPS variable.
367 *
368 * FPS eval code copied from #BKE_cachefile_filepath_get().
369 *
370 * TODO: should probably use one function for this everywhere to ensure that
371 * fps is computed consistently, but at the time of writing no such function
372 * seems to exist. Every place in the code base just has its own bespoke
373 * code, using different precision, etc. */
374 const double fps = double(scene.r.frs_sec) / double(scene.r.frs_sec_base);
375 variables.add_float("fps", fps);
376
377 /* Scene name variable. */
378 variables.add_string("scene_name", scene.id.name + 2);
379
380 /* Camera name variable. */
381 if (scene.camera) {
382 variables.add_string("camera_name", scene.camera->id.name + 2);
383 }
384}
385
387 const bNode &owning_node)
388{
389 variables.add_string("node_name", owning_node.name);
390}
391
392/* -------------------------------------------------------------------- */
393
394/* Set to FILE_MAX to ensure that it can handle all path variables. */
395#define FORMAT_BUFFER_SIZE FILE_MAX
396
397namespace {
398
399enum class FormatSpecifierType {
400 /* No format specifier given. Use default formatting. */
401 NONE = 0,
402
403 /* The format specifier was a string of just "#" characters. E.g. "####". */
404 INTEGER,
405
406 /* The format specifier was a string of "#" characters with a single ".". E.g.
407 * "###.##". */
408 FLOAT,
409
410 /* The format specifier was invalid due to incorrect syntax. */
411 SYNTAX_ERROR,
412};
413
418struct FormatSpecifier {
419 FormatSpecifierType type = FormatSpecifierType::NONE;
420
421 /* For INTEGER and FLOAT formatting types, the number of digits indicated on
422 * either side of the decimal point. */
423 std::optional<uint8_t> integer_digit_count;
424 std::optional<uint8_t> fractional_digit_count;
425};
426
427enum class TokenType {
428 /* Either "{variable_name}" or "{variable_name:format_spec}". */
429 VARIABLE_EXPRESSION,
430
431 /* "{{", which is an escaped "{". */
432 LEFT_CURLY_BRACE,
433
434 /* "}}", which is an escaped "}". */
435 RIGHT_CURLY_BRACE,
436
437 /* Encountered a syntax error while trying to parse a variable expression. */
438 VARIABLE_SYNTAX_ERROR,
439
440 /* Encountered an unescaped curly brace in an invalid position. */
441 UNESCAPED_CURLY_BRACE_ERROR,
442};
443
447struct Token {
448 TokenType type = TokenType::VARIABLE_EXPRESSION;
449
450 /* Byte index range (exclusive on the right) of the token or syntax error in
451 * the path string. */
452 IndexRange byte_range;
453
454 /* Reference to the variable name as written in the template string. Note
455 * that this points into the template string, and does not own the value.
456 *
457 * Only relevant when `type == VARIABLE_EXPRESSION`. */
458 StringRef variable_name;
459
460 /* Indicates how the variable's value should be formatted into a string. This
461 * is derived from the format specification (e.g. the "###" in "{blah:###}").
462 *
463 * Only relevant when `type == VARIABLE_EXPRESSION`. */
464 FormatSpecifier format;
465};
466
467} // namespace
468
477static int format_int_to_string(const FormatSpecifier &format,
478 const int64_t integer_value,
479 char r_output_string[FORMAT_BUFFER_SIZE])
480{
481 BLI_assert(format.type != FormatSpecifierType::SYNTAX_ERROR);
482
483 r_output_string[0] = '\0';
484 int output_length = 0;
485
486 switch (format.type) {
487 case FormatSpecifierType::NONE: {
488 output_length =
489 fmt::format_to_n(r_output_string, FORMAT_BUFFER_SIZE - 1, "{}", integer_value).size;
490 r_output_string[output_length] = '\0';
491 break;
492 }
493
494 case FormatSpecifierType::INTEGER: {
495 BLI_assert(format.integer_digit_count.has_value());
496 BLI_assert(*format.integer_digit_count > 0);
497 output_length = fmt::format_to_n(r_output_string,
499 "{:0{}}",
500 integer_value,
501 *format.integer_digit_count)
502 .size;
503 r_output_string[output_length] = '\0';
504 break;
505 }
506
507 case FormatSpecifierType::FLOAT: {
508 /* Formatting an integer as a float: we do *not* defer to the float
509 * formatter for this because we could lose precision with very large
510 * numbers. Instead we simply print the integer, and then append ".000..."
511 * to it. */
512 BLI_assert(format.fractional_digit_count.has_value());
513 BLI_assert(*format.fractional_digit_count > 0);
514
515 if (format.integer_digit_count.has_value()) {
516 BLI_assert(*format.integer_digit_count > 0);
517 output_length = fmt::format_to_n(r_output_string,
519 "{:0{}}",
520 integer_value,
521 *format.integer_digit_count)
522 .size;
523 }
524 else {
525 output_length =
526 fmt::format_to_n(r_output_string, FORMAT_BUFFER_SIZE - 1, "{}", integer_value).size;
527 }
528
529 r_output_string[output_length] = '.';
530 output_length++;
531
532 for (int i = 0; i < *format.fractional_digit_count && i < (FORMAT_BUFFER_SIZE - 1); i++) {
533 r_output_string[output_length] = '0';
534 output_length++;
535 }
536
537 r_output_string[output_length] = '\0';
538
539 break;
540 }
541
542 case FormatSpecifierType::SYNTAX_ERROR: {
544 false,
545 "Format specifiers with invalid syntax should have been rejected before getting here.");
546 break;
547 }
548 }
549
550 return output_length;
551}
552
561static int format_float_to_string(const FormatSpecifier &format,
562 const double float_value,
563 char r_output_string[FORMAT_BUFFER_SIZE])
564{
565 BLI_assert(format.type != FormatSpecifierType::SYNTAX_ERROR);
566
567 r_output_string[0] = '\0';
568 int output_length = 0;
569
570 switch (format.type) {
571 case FormatSpecifierType::NONE: {
572 /* When no format specification is given, we attempt to replicate Python's
573 * behavior in the same situation. The only major thing we can't replicate
574 * via `libfmt` is that in Python whole numbers are printed with a trailing
575 * ".0". So we handle that bit manually. */
576 output_length =
577 fmt::format_to_n(r_output_string, FORMAT_BUFFER_SIZE - 1, "{}", float_value).size;
578 r_output_string[output_length] = '\0';
579
580 /* If the string consists only of digits and a possible negative sign, then
581 * we append a ".0" to match Python. */
582 if (StringRef(r_output_string).find_first_not_of("-0123456789") == std::string::npos) {
583 r_output_string[output_length] = '.';
584 r_output_string[output_length + 1] = '0';
585 r_output_string[output_length + 2] = '\0';
586 output_length += 2;
587 }
588 break;
589 }
590
591 case FormatSpecifierType::INTEGER: {
592 /* Defer to the integer formatter with a rounded value. */
593 return format_int_to_string(format, std::round(float_value), r_output_string);
594 }
595
596 case FormatSpecifierType::FLOAT: {
597 BLI_assert(format.fractional_digit_count.has_value());
598 BLI_assert(*format.fractional_digit_count > 0);
599
600 if (format.integer_digit_count.has_value()) {
601 /* Both integer and fractional component lengths are specified. */
602 BLI_assert(*format.integer_digit_count > 0);
603 output_length = fmt::format_to_n(r_output_string,
605 "{:0{}.{}f}",
606 float_value,
607 *format.integer_digit_count +
608 *format.fractional_digit_count + 1,
609 *format.fractional_digit_count)
610 .size;
611 r_output_string[output_length] = '\0';
612 }
613 else {
614 /* Only fractional component length is specified. */
615 output_length = fmt::format_to_n(r_output_string,
617 "{:.{}f}",
618 float_value,
619 *format.fractional_digit_count)
620 .size;
621 r_output_string[output_length] = '\0';
622 }
623
624 break;
625 }
626
627 case FormatSpecifierType::SYNTAX_ERROR: {
629 false,
630 "Format specifiers with invalid syntax should have been rejected before getting here.");
631 break;
632 }
633 }
634
635 return output_length;
636}
637
645static FormatSpecifier parse_format_specifier(StringRef format_specifier)
646{
647 FormatSpecifier format = {};
648
649 /* A ":" was used, but no format specifier was given, which is invalid. */
650 if (format_specifier.is_empty()) {
651 format.type = FormatSpecifierType::SYNTAX_ERROR;
652 return format;
653 }
654
655 /* If it's all digit specifiers, then format as an integer. */
656 if (format_specifier.find_first_not_of("#") == std::string::npos) {
657 format.integer_digit_count = format_specifier.size();
658
659 format.type = FormatSpecifierType::INTEGER;
660 return format;
661 }
662
663 /* If it's digit specifiers and a dot, format as a float. */
664 const int64_t dot_index = format_specifier.find_first_of('.');
665 const int64_t dot_index_last = format_specifier.find_last_of('.');
666 const bool found_dot = dot_index != std::string::npos;
667 const bool only_one_dot = dot_index == dot_index_last;
668 if (format_specifier.find_first_not_of(".#") == std::string::npos && found_dot && only_one_dot) {
669 StringRef left = format_specifier.substr(0, dot_index);
670 StringRef right = format_specifier.substr(dot_index + 1);
671
672 /* We currently require that the fractional digits are specified, so bail if
673 * they aren't. */
674 if (right.is_empty()) {
675 format.type = FormatSpecifierType::SYNTAX_ERROR;
676 return format;
677 }
678
679 if (!left.is_empty()) {
680 format.integer_digit_count = left.size();
681 }
682
683 format.fractional_digit_count = right.size();
684
685 format.type = FormatSpecifierType::FLOAT;
686 return format;
687 }
688
689 format.type = FormatSpecifierType::SYNTAX_ERROR;
690 return format;
691}
692
703static std::optional<Token> next_token(StringRef path, const int from_char)
704{
705 Token token;
706
707 /* We use the magic number -1 here to indicate that a component hasn't been
708 * found yet. When a component is found, the respective token here is set
709 * to the byte offset it was found at. */
710 int start = -1; /* "{" */
711 int format_specifier_split = -1; /* ":" */
712 int end = -1; /* "}" */
713
714 for (int byte_index = from_char; byte_index < path.size(); byte_index++) {
715 /* Check for escaped "{". */
716 if (start == -1 && (byte_index + 1) < path.size() && path[byte_index] == '{' &&
717 path[byte_index + 1] == '{')
718 {
719 Token token;
720 token.type = TokenType::LEFT_CURLY_BRACE;
721 token.byte_range = IndexRange::from_begin_end(byte_index, byte_index + 2);
722 return token;
723 }
724
725 /* Check for escaped "}".
726 *
727 * Note that we only do this check when not already inside a variable
728 * expression, since it could be a valid closing "}" followed by additional
729 * escaped closing braces. */
730 if (start == -1 && (byte_index + 1) < path.size() && path[byte_index] == '}' &&
731 path[byte_index + 1] == '}')
732 {
733 token.type = TokenType::RIGHT_CURLY_BRACE;
734 token.byte_range = IndexRange::from_begin_end(byte_index, byte_index + 2);
735 return token;
736 }
737
738 /* Check for unescaped "}", which outside of a variable expression is
739 * illegal. */
740 if (start == -1 && path[byte_index] == '}') {
741 token.type = TokenType::UNESCAPED_CURLY_BRACE_ERROR;
742 token.byte_range = IndexRange::from_begin_end(byte_index, byte_index + 1);
743 return token;
744 }
745
746 /* Check if we've found a starting "{". */
747 if (path[byte_index] == '{') {
748 if (start != -1) {
749 /* Already inside a variable expression. */
750 token.type = TokenType::VARIABLE_SYNTAX_ERROR;
751 token.byte_range = IndexRange::from_begin_end(start, byte_index);
752 return token;
753 }
754 start = byte_index;
755 format_specifier_split = -1;
756 continue;
757 }
758
759 /* If we haven't found a start, we shouldn't try to parse the other bits
760 * yet. */
761 if (start == -1) {
762 continue;
763 }
764
765 /* Check if we've found a format splitter. */
766 if (path[byte_index] == ':') {
767 if (format_specifier_split == -1) {
768 /* Only set if it's the first ":" we've encountered in the variable
769 * expression. Subsequent ones will be handled in the format specifier
770 * parsing. */
771 format_specifier_split = byte_index;
772 }
773 continue;
774 }
775
776 /* Check if we've found the closing "}". */
777 if (path[byte_index] == '}') {
778 end = byte_index + 1; /* Exclusive end. */
779 break;
780 }
781 }
782
783 /* No variable expression found. */
784 if (start == -1) {
785 return std::nullopt;
786 }
787
788 /* Unclosed variable expression. Syntax error. */
789 if (end == -1) {
790 token.type = TokenType::VARIABLE_SYNTAX_ERROR;
791 token.byte_range = IndexRange::from_begin_end(start, path.size());
792 return token;
793 }
794
795 /* Parse the variable expression we found. */
796 token.byte_range = IndexRange::from_begin_end(start, end);
797 if (format_specifier_split == -1) {
798 /* No format specifier. */
799 token.variable_name = path.substr(start + 1, (end - 1) - (start + 1));
800 }
801 else {
802 /* Found format specifier. */
803 token.variable_name = path.substr(start + 1, format_specifier_split - (start + 1));
804 token.format = parse_format_specifier(
805 path.substr(format_specifier_split + 1, (end - 1) - (format_specifier_split + 1)));
806 if (token.format.type == FormatSpecifierType::SYNTAX_ERROR) {
807 token.type = TokenType::VARIABLE_SYNTAX_ERROR;
808 return token;
809 }
810 }
811
812 return token;
813}
814
815namespace bke::path_templates {
816
817std::optional<ExpressionInfo> next_template_variable_expression(StringRef text,
818 size_t starting_offset)
819{
820 while (const std::optional<Token> token = next_token(text, starting_offset)) {
821 switch (token->type) {
822 case TokenType::LEFT_CURLY_BRACE:
823 case TokenType::RIGHT_CURLY_BRACE: {
824 starting_offset = token->byte_range.one_after_last();
825 continue;
826 }
827
828 case TokenType::VARIABLE_EXPRESSION: {
829 ExpressionInfo info;
830 info.byte_range = token->byte_range;
831 info.variable_name = token->variable_name;
832 return info;
833 }
834
835 case TokenType::VARIABLE_SYNTAX_ERROR:
836 case TokenType::UNESCAPED_CURLY_BRACE_ERROR: {
837 return std::nullopt;
838 }
839 }
840 }
841
842 return std::nullopt;
843}
844
845} // namespace bke::path_templates
846
847/* Parse the given template and return the list of tokens found, in the same
848 * order as they appear in the template. */
850{
851 Vector<Token> tokens;
852
853 for (int bytes_read = 0; bytes_read < path.size();) {
854 const std::optional<Token> token = next_token(path, bytes_read);
855
856 if (!token.has_value()) {
857 break;
858 }
859
860 bytes_read = token->byte_range.one_after_last();
861 tokens.append(*token);
862 }
863
864 return tokens;
865}
866
867/* Convert a token to its corresponding syntax error. If the token doesn't have
868 * an error, returns nullopt. */
869static std::optional<Error> token_to_syntax_error(const Token &token)
870{
871 switch (token.type) {
872 case TokenType::VARIABLE_SYNTAX_ERROR: {
873 if (token.format.type == FormatSpecifierType::SYNTAX_ERROR) {
874 return {{ErrorType::FORMAT_SPECIFIER, token.byte_range}};
875 }
876 return {{ErrorType::VARIABLE_SYNTAX, token.byte_range}};
877 }
878
879 case TokenType::UNESCAPED_CURLY_BRACE_ERROR: {
880 return {{ErrorType::UNESCAPED_CURLY_BRACE, token.byte_range}};
881 }
882
883 /* Non-errors. */
884 case TokenType::VARIABLE_EXPRESSION:
885 case TokenType::LEFT_CURLY_BRACE:
886 case TokenType::RIGHT_CURLY_BRACE:
887 return std::nullopt;
888 }
889
890 BLI_assert_msg(false, "Unhandled token type.");
891 return std::nullopt;
892}
893
895{
896 return path.find_first_of("{}") != std::string_view::npos;
897}
898
899std::string BKE_path_template_escape(const StringRef text)
900{
901 std::string escaped;
902 escaped.reserve(text.size());
903
904 for (const char c : text) {
905 escaped.push_back(c);
906 if (c == '{' || c == '}') {
907 escaped.push_back(c);
908 }
909 }
910
911 return escaped;
912}
913
930static Vector<Error> eval_template(std::string *r_out_path,
931 StringRef in_path,
932 const VariableMap &template_variables)
933{
934 if (r_out_path) {
935 /* Just in case. */
936 r_out_path->clear();
937 }
938
939 const Vector<Token> tokens = parse_template(in_path);
940
941 if (tokens.is_empty()) {
942 /* No tokens found, so the output is the same as the input. */
943 if (r_out_path) {
944 r_out_path->append(in_path);
945 }
946 return {};
947 }
948
949 /* Accumulates errors as we process the tokens. */
950 Vector<Error> errors;
951
952 /* Byte index of our position in the input path, to track where we are while
953 * copying things over. */
954 int in_head = 0;
955
956 for (const Token &token : tokens) {
957 /* Syntax errors. */
958 if (std::optional<Error> error = token_to_syntax_error(token)) {
959 errors.append(*error);
960 continue;
961 }
962
963 char replacement_string[FORMAT_BUFFER_SIZE];
964
965 switch (token.type) {
966 /* Syntax errors should have been handled above. */
967 case TokenType::VARIABLE_SYNTAX_ERROR:
968 case TokenType::UNESCAPED_CURLY_BRACE_ERROR: {
969 BLI_assert_msg(false, "Unhandled syntax error.");
970 continue;
971 }
972
973 /* Curly brace escapes. */
974 case TokenType::LEFT_CURLY_BRACE: {
975 ARRAY_SET_ITEMS(replacement_string, '{', '\0');
976 break;
977 }
978 case TokenType::RIGHT_CURLY_BRACE: {
979 ARRAY_SET_ITEMS(replacement_string, '}', '\0');
980 break;
981 }
982
983 /* Expand variable expression into the variable's value. */
984 case TokenType::VARIABLE_EXPRESSION: {
985 if (std::optional<StringRefNull> string_value = template_variables.get_string(
986 token.variable_name))
987 {
988 if (token.format.type != FormatSpecifierType::NONE) {
989 /* String variables don't take format specifiers: error. */
990 errors.append({ErrorType::FORMAT_SPECIFIER, token.byte_range});
991 continue;
992 }
993 STRNCPY(replacement_string, string_value->c_str());
994 BLI_path_make_safe_filename(replacement_string);
995 break;
996 }
997
998 if (std::optional<StringRefNull> path_value = template_variables.get_filepath(
999 token.variable_name))
1000 {
1001 if (token.format.type != FormatSpecifierType::NONE) {
1002 /* Path variables don't take format specifiers: error. */
1003 errors.append({ErrorType::FORMAT_SPECIFIER, token.byte_range});
1004 continue;
1005 }
1006 STRNCPY(replacement_string, path_value->c_str());
1007 break;
1008 }
1009
1010 if (std::optional<int64_t> integer_value = template_variables.get_integer(
1011 token.variable_name))
1012 {
1013 /* Integer variable found. */
1014 format_int_to_string(token.format, *integer_value, replacement_string);
1015 break;
1016 }
1017
1018 if (std::optional<double> float_value = template_variables.get_float(token.variable_name))
1019 {
1020 /* Float variable found. */
1021 format_float_to_string(token.format, *float_value, replacement_string);
1022 break;
1023 }
1024
1025 /* No matching variable found: error. */
1026 errors.append({ErrorType::UNKNOWN_VARIABLE, token.byte_range});
1027 continue;
1028 }
1029 }
1030
1031 if (r_out_path) {
1032 /* Copy over any non-token text that precedes the token. */
1033 r_out_path->append(in_path.substr(in_head, token.byte_range.start() - in_head));
1034
1035 /* Copy over the token replacement text. */
1036 r_out_path->append(StringRef(replacement_string));
1037 }
1038 in_head = token.byte_range.one_after_last();
1039 }
1040
1041 /* Copy any remaining non-token text after the last token. */
1042 if (r_out_path) {
1043 r_out_path->append(in_path.substr(in_head));
1044 }
1045
1046 return errors;
1047}
1048
1050 StringRef path, const bke::path_templates::VariableMap &template_variables)
1051{
1052 return eval_template(nullptr, path, template_variables);
1053}
1054
1056 int path_maxncpy,
1057 const VariableMap &template_variables)
1058{
1059 BLI_assert(path != nullptr);
1060
1061 std::string evaluated_path;
1062 const Vector<Error> errors = eval_template(&evaluated_path, path, template_variables);
1063
1064 if (errors.is_empty()) {
1065 /* No errors, so copy the modified path back to the original. */
1066 BLI_strncpy(path, evaluated_path.c_str(), path_maxncpy);
1067 }
1068 return errors;
1069}
1070
1072 int path_maxncpy,
1073 const VariableMap &template_variables)
1074{
1075 BLI_assert(path != nullptr);
1076 BLI_assert(*path != nullptr);
1077
1078 std::string evaluated_path;
1079 const Vector<Error> errors = eval_template(&evaluated_path, *path, template_variables);
1080
1081 if (!errors.is_empty()) {
1082 return errors;
1083 }
1084
1085 const int buffer_size = math::min(int(evaluated_path.size()) + 1, path_maxncpy);
1086 char *buffer = MEM_new_array_uninitialized<char>(buffer_size, __func__);
1087 BLI_strncpy(buffer, evaluated_path.c_str(), buffer_size);
1088
1089 MEM_delete(*path);
1090 *path = buffer;
1091
1092 return {};
1093}
1094
1096{
1097 StringRef subpath = path.substr(error.byte_range.start(), error.byte_range.size());
1098
1099 switch (error.type) {
1100 case ErrorType::UNESCAPED_CURLY_BRACE: {
1101 return std::string("Unescaped curly brace '") + subpath + "'.";
1102 }
1103
1104 case ErrorType::VARIABLE_SYNTAX: {
1105 return std::string("Invalid or incomplete template expression '") + subpath + "'.";
1106 }
1107
1108 case ErrorType::FORMAT_SPECIFIER: {
1109 return std::string("Invalid format specifier in template expression '") + subpath + "'.";
1110 }
1111
1112 case ErrorType::UNKNOWN_VARIABLE: {
1113 return std::string("Unknown variable referenced in template expression '") + subpath + "'.";
1114 }
1115 }
1116
1117 BLI_assert_msg(false, "Unhandled error type.");
1118 return "Unknown error.";
1119}
1120
1122 const eReportType report_type,
1123 StringRef path,
1124 Span<Error> errors)
1125{
1126 BLI_assert(!errors.is_empty());
1127
1128 std::string error_message = "Parse errors in path '" + path + "':";
1129 for (const Error &error : errors) {
1130 error_message += "\n- " + BKE_path_template_error_to_string(error, path);
1131 }
1132
1133 BKE_report(reports, report_type, error_message.c_str());
1134}
1135
1136std::optional<std::string> BKE_path_template_format_float(const StringRef format_specifier,
1137 const double value)
1138{
1139 const FormatSpecifier format = parse_format_specifier(format_specifier);
1140 if (format.type == FormatSpecifierType::SYNTAX_ERROR) {
1141 return std::nullopt;
1142 }
1143 char buffer[FORMAT_BUFFER_SIZE];
1144 format_float_to_string(format, value, buffer);
1145 return buffer;
1146}
1147
1148std::optional<std::string> BKE_path_template_format_int(const StringRef format_specifier,
1149 const int64_t value)
1150{
1151 const FormatSpecifier format = parse_format_specifier(format_specifier);
1152 if (format.type == FormatSpecifierType::SYNTAX_ERROR) {
1153 return std::nullopt;
1154 }
1155 char buffer[FORMAT_BUFFER_SIZE];
1156 format_int_to_string(format, value, buffer);
1157 return buffer;
1158}
1159
1160} // namespace blender
Functions and classes for evaluating template expressions in filepaths.
#define DATA_(msgid)
#define ID_BLEND_PATH_FROM_GLOBAL(_id)
Definition DNA_ID.h:691
Enumerations for DNA_ID.h.
#define C
Definition RandGen.cpp:29
#define ARRAY_SET_ITEMS(...)
#define BLI_assert_msg(a, msg)
@ NONE
constexpr int64_t size() const
static constexpr IndexRange from_begin_end(const int64_t begin, const int64_t end)
constexpr int64_t start() const
constexpr bool is_empty() const
Definition BLI_span.hh:264
constexpr const char * c_str() const
constexpr StringRefNull()
constexpr StringRef()
void append(const T &value)
bool is_empty() const
std::optional< int64_t > get_integer(StringRef name) const
bool add_filename_only(StringRef var_name, StringRefNull full_path, StringRef fallback)
bool add_float(StringRef name, double value)
bool add_path_up_to_file(StringRef var_name, StringRefNull full_path, StringRef fallback)
std::optional< double > get_float(StringRef name) const
std::optional< StringRefNull > get_filepath(StringRef name) const
std::optional< StringRefNull > get_string(StringRef name) const
bool add_integer(StringRef name, int64_t value)
bool add_string(StringRef name, StringRef value)
bool add_filepath(StringRef name, StringRef value)
constexpr int64_t find_first_of(StringRef chars, int64_t pos=0) const
constexpr const char * end() const
constexpr bool is_empty() const
constexpr int64_t size() const
constexpr int64_t find_first_not_of(StringRef chars, int64_t pos=0) const
void copy_unsafe(char *dst) const
constexpr StringRef substr(int64_t start, int64_t size) const
constexpr int64_t find_last_of(StringRef chars, int64_t pos=INT64_MAX) const
nullptr FLOAT
std::optional< ExpressionInfo > next_template_variable_expression(StringRef text, size_t starting_offset)
bool operator==(const Error &left, const Error &right)
T min(const T &a, const T &b)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
const char * BLI_path_extension_or_end(const char *filepath) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL
__int64 int64_t
Definition BKE_text.h:90
char * STRNCPY(char(&dst)[N], const char *src)
static int format_int_to_string(const FormatSpecifier &format, const int64_t integer_value, char r_output_string[FORMAT_BUFFER_SIZE])
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
void BKE_add_template_variables_general(bke::path_templates::VariableMap &variables, const ID *path_owner_id, const bke::BlenderProject *project)
bool BKE_path_contains_template_syntax(StringRef path)
Vector< bke::path_templates::Error > BKE_path_apply_template_alloc(char **path, int path_maxncpy, const bke::path_templates::VariableMap &template_variables)
std::optional< AncestorPointerRNA > RNA_struct_search_closest_ancestor_by_type(const PointerRNA *ptr, const StructRNA *srna)
void BKE_report_path_template_errors(ReportList *reports, eReportType report_type, StringRef path, Span< bke::path_templates::Error > errors)
static FormatSpecifier parse_format_specifier(StringRef format_specifier)
const char * BKE_main_blendfile_path_from_global()
Definition main.cc:1063
static std::optional< Token > next_token(StringRef path, const int from_char)
auto BKE_blender_project_read_callback(const Main *bmain, Fn lambda)
static Vector< Token > parse_template(StringRef path)
@ PROP_VARIABLES_NONE
Definition RNA_types.hh:567
@ PROP_VARIABLES_PROJECT
Definition RNA_types.hh:577
@ PROP_VARIABLES_RENDER_OUTPUT
Definition RNA_types.hh:572
void BKE_render_resolution(const RenderData *r, const bool use_crop, int *r_width, int *r_height)
Definition scene.cc:3168
std::string BKE_path_template_error_to_string(const bke::path_templates::Error &error, StringRef path)
void BKE_add_template_variables_for_render_path(bke::path_templates::VariableMap &variables, const Scene &scene)
void BKE_add_template_variables_for_node(bke::path_templates::VariableMap &variables, const bNode &owning_node)
Vector< bke::path_templates::Error > BKE_path_apply_template(char *path, int path_maxncpy, const bke::path_templates::VariableMap &template_variables)
void void void const char * BLI_path_basename(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
static int format_float_to_string(const FormatSpecifier &format, const double float_value, char r_output_string[FORMAT_BUFFER_SIZE])
char * BLI_strncpy(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
static std::optional< Error > token_to_syntax_error(const Token &token)
PropertyPathTemplateType RNA_property_path_template_type(PropertyRNA *prop)
std::string BKE_path_template_escape(StringRef text)
void BKE_report(ReportList *reports, eReportType type, const char *message)
Definition report.cc:162
std::optional< bke::path_templates::VariableMap > BKE_build_template_variables_for_prop(const bContext *C, PointerRNA *ptr, PropertyRNA *prop)
int RNA_property_flag(PropertyRNA *prop)
void BKE_add_template_variables_for_project(bke::path_templates::VariableMap &variables, const bke::BlenderProject &project)
bool BLI_path_parent_dir(char *path) ATTR_NONNULL(1)
static Vector< Error > eval_template(std::string *r_out_path, StringRef in_path, const VariableMap &template_variables)
Main * CTX_data_main(const bContext *C)
Vector< bke::path_templates::Error > BKE_path_validate_template(StringRef path, const bke::path_templates::VariableMap &template_variables)
ID_Type GS(const char *name)
Definition DNA_ID.h:410
@ PROP_PATH_SUPPORTS_TEMPLATES
Definition RNA_types.hh:540
std::optional< std::string > BKE_path_template_format_float(StringRef format_specifier, double value)
Scene * CTX_data_scene(const bContext *C)
bool BLI_path_make_safe_filename(char *filename) ATTR_NONNULL(1)
std::optional< std::string > BKE_path_template_format_int(StringRef format_specifier, int64_t value)
TokenType
Definition types.hh:41
#define FORMAT_BUFFER_SIZE
char name[258]
Definition DNA_ID.h:433
struct Object * camera
struct RenderData r