Blender V5.3
blender_project.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <map>
10#include <mutex>
11#include <shared_mutex>
12#include <vector>
13
15#include "BKE_global.hh"
16#include "BKE_main.hh"
17#include "BKE_path_templates.hh"
18#include "BKE_preferences.h"
19#include "BKE_recents.hh"
20
21#include "BLI_fileops.hh"
22#include "BLI_function_ref.hh"
23#include "BLI_listbase.hh"
24#include "BLI_path_utils.hh"
25#include "BLI_string.hh"
26#include "BLI_string_ref.hh"
27#include "BLI_string_utils.hh"
28
29#include "RNA_types.hh"
30
31#include "DNA_asset_types.h"
32#include "DNA_userdef_types.h"
33
34namespace blender {
35
50static std::optional<bke::BlenderProject> &get_project()
51{
52 /* Construct on First Use idiom. */
53 static std::optional<bke::BlenderProject> project;
54
55 return project;
56}
57
63static std::shared_mutex &get_project_mutex()
64{
65 /* Construct on First Use idiom. */
66 static std::shared_mutex project_mutex;
67
68 return project_mutex;
69}
70
71namespace bke {
72
74{
75 /* This variable is a hack to get around IDProperties having no value-based APIs for property
76 * creation, only pointer-based. We free this after copying its data to `this`. */
77 IDProperty *tmp_property;
78
79 /* Guard against invalid types, in case of enum casts from integers.
80 * We could instead do this as the `default` case in the switch below, but
81 * then we don't get nice compiler warnings if someone adds a type but
82 * forgets to handle it here. */
85
86 switch (type) {
88 IDPropertyTemplate prop_template{0};
89 prop_template.i = 0;
90 tmp_property = IDP_New(eIDPropertyType::IDP_INT, &prop_template, name, eIDPropertyFlag(0));
91 break;
92 }
93
95 IDPropertyTemplate prop_template{0};
96 prop_template.f = 0.0f;
97 tmp_property = IDP_New(eIDPropertyType::IDP_FLOAT, &prop_template, name, eIDPropertyFlag(0));
98 break;
99 }
100
102 tmp_property = IDP_NewString("", name, eIDPropertyFlag(0));
103 break;
104 }
105 }
106
107 IDP_ui_data_ensure(tmp_property);
108 tmp_property->ui_data->description = BLI_strdup("");
109
110 this->prop() = *tmp_property;
111
112 /* Shallow delete, so the pointers copied to `this` remain valid. */
113 MEM_delete_void(static_cast<void *>(tmp_property));
114}
115
120
122{
123 this->prop() = other.prop();
124 other.prop() = {};
125}
126
128{
129 if (this != &other) {
130 IDP_ClearProperty(this);
131 this->prop() = other.prop();
132 other.prop() = {};
133 }
134 return *this;
135}
136
138{
139 return StringRefNull(this->name);
140}
141
146
151
156
161
163{
164 return IDP_int_get(this);
165}
166
168{
169 return IDP_float_get(this);
170}
171
173{
174 IDP_AssignString(this, value.c_str());
175}
176
178{
179 IDP_int_set(this, value);
180}
181
183{
184 IDP_float_set(this, value);
185}
186
188{
189 if (this->ui_data->description == nullptr) {
190 return StringRefNull();
191 }
192 return StringRefNull(this->ui_data->description);
193}
194
196{
197 MEM_delete(this->ui_data->description);
198 this->ui_data->description = MEM_new_array<char>(description.size() + 1,
199 "ProjectVariable description");
200 description.copy_unsafe(this->ui_data->description);
201}
202
204{
205 BLI_assert(!name.is_empty());
206
207 this->name_ = name;
208
209 this->is_dirty = true;
210}
211
213{
214 BLI_assert(!root_path.is_empty());
215
216 this->root_path_ = root_path;
217
218 this->is_dirty = true;
219}
220
222{
223 this->ocio_config_path_ = ocio_config_path;
224
225 this->is_dirty = true;
226}
227
229{
230 this->splash_image_path_ = splash_image_path;
231
232 this->is_dirty = true;
233}
234
236{
237 return StringRefNull(this->name_);
238}
239
241{
242 return StringRefNull(this->root_path_);
243}
244
246{
247 return StringRefNull(this->ocio_config_path_);
248}
249
251{
252 return StringRefNull(this->splash_image_path_);
253}
254
256{
257 BLI_assert(var != nullptr);
258 if (var == nullptr) {
259 return -1;
260 }
261
262 for (int i : this->variables.index_range()) {
263 if (this->variables[i].get() == var) {
264 return i;
265 }
266 }
267
268 return -1;
269}
270
272{
273 const std::string new_name = ensure_is_valid_project_variable_name(name);
274
275 this->variables.append(std::make_unique<ProjectVariable>("", type));
276 this->rename_variable(this->variables.size() - 1, new_name); /* Also ensures name uniqueness. */
277
278 this->is_dirty = true;
279
280 return this->variables.last().get();
281}
282
284{
285 const int index = this->find_variable_index(var);
286 if (index == -1) {
287 return -1;
288 }
289
290 this->variables.remove(index);
291
292 if (this->active_variable_index > index) {
293 this->active_variable_index -= 1;
294 }
295 this->active_variable_index = std::min(this->active_variable_index,
296 int(this->variables.size() - 1));
297
298 this->is_dirty = true;
299 return index;
300}
301
302void BlenderProject::move_variable(int from_index, int to_index)
303{
304 BLI_assert(from_index < this->variables.size());
305 BLI_assert(to_index < this->variables.size());
306
307 /* No-op. */
308 if (from_index == to_index) {
309 return;
310 }
311
312 if (from_index < to_index) {
313 std::rotate(this->variables.data() + from_index,
314 this->variables.data() + from_index + 1,
315 this->variables.data() + to_index + 1);
316 }
317 else if (from_index > to_index) {
318 std::rotate(this->variables.data() + to_index,
319 this->variables.data() + from_index,
320 this->variables.data() + from_index + 1);
321 }
322
323 this->is_dirty = true;
324}
325
326void BlenderProject::rename_variable(int variable_index, StringRef name)
327{
328 BLI_assert(variable_index >= 0 && variable_index < this->variables.size());
329 if (variable_index < 0 || variable_index >= this->variables.size()) {
330 return;
331 }
332
333 const std::string new_name = ensure_is_valid_project_variable_name(name);
334
335 auto is_variable_name_used = [&](StringRef name) -> bool {
336 for (int i = 0; i < this->variables.size(); i++) {
337 if (i == variable_index) {
338 /* Skip the variable we're renaming. */
339 continue;
340 }
341
342 if (this->variables[i]->name_get() == name) {
343 return true;
344 }
345 }
346
347 return false;
348 };
349
350 this->variables[variable_index]->prop().name[0] = '\0';
351 BLI_uniquename_cb(is_variable_name_used,
352 new_name.c_str(),
353 '_',
354 this->variables[variable_index]->prop().name,
355 sizeof(IDProperty::name));
356}
357
359{
360 std::shared_lock<std::shared_mutex> lock(get_project_mutex());
361 lambda();
362}
363
365{
366 std::unique_lock<std::shared_mutex> lock(get_project_mutex());
367 lambda();
368}
369
374
376{
377 std::string new_name(name);
378
379 /* Shouldn't be empty. */
380 if (new_name.size() == 0) {
381 new_name.push_back('_');
382 }
383
384 /* Shouldn't start with a numerical digit. */
385 if (new_name[0] >= '0' && new_name[0] <= '9') {
386 new_name[0] = '_';
387 }
388
389 /* All characters should be alphanumeric or underscore.
390 *
391 * Note: this is utf8-safe because all non-ascii characters get substituted,
392 * and thus any multi-byte code points just end up as multiple underscores
393 * rather than being e.g. only partially substituted. This perhaps isn't a
394 * pleasing result in some cases, but the string always ends up being valid
395 * utf8.
396 */
397 for (int i = 0; i < new_name.size(); i++) {
398 const char c = new_name[i];
399 const bool is_valid_identifier_char = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
400 (c >= '0' && c <= '9') || c == '_';
401 if (!is_valid_identifier_char) {
402 new_name[i] = '_';
403 }
404 }
405
406 return new_name;
407}
408
409} // namespace bke
410
411std::string BKE_is_path_inside_blender_project(const char *path)
412{
413 char project_root_path[FILE_MAX];
414 if (BLI_is_file(path)) {
415 BLI_path_split_dir_part(path, project_root_path, sizeof(project_root_path));
416 }
417 else {
418 /* Note this function is used for paths that don't yet exist. We still
419 * check its parent directories then. */
420 STRNCPY(project_root_path, path);
421 }
422
423 bool found_project = false;
424 char project_root_path_test[FILE_MAX];
425
426 /* Loop as long as project_root_path has a parent dir.
427 * Stop if project_root_path contains a .blender_project folder.
428 */
429 do {
430 STRNCPY(project_root_path_test, project_root_path);
431 BLI_path_append(project_root_path_test, FILE_MAX, BLENDER_PROJECT_CONFIG_DIR);
432 found_project = BLI_is_dir(project_root_path_test);
433 } while (!found_project && BLI_path_parent_dir(project_root_path));
434
435 if (found_project) {
436 /* Ensure that we don't have a trailing slash in the path.
437 * IE, we always return "/my/folder" and not "/my/folder/".
438 */
439 BLI_path_slash_rstrip(project_root_path);
440 return project_root_path;
441 }
442 return "";
443}
444
446{
447 if (bmain == nullptr || !bmain->is_part_of_project) {
448 return nullptr;
449 }
450
451 std::optional<bke::BlenderProject> &project = get_project();
452 if (!project.has_value()) {
453 return nullptr;
454 }
455
456 return &*project;
457}
458
460{
461 if (name.is_empty() || root_path.is_empty()) {
462 return false;
463 }
464
466
468 std::optional<bke::BlenderProject> &project = get_project();
469
471
472 project->set_name(name);
473 project->set_root_path(root_path);
474 });
475
476 return true;
477}
478
479void BKE_blender_project_refresh(Main *bmain, const char *filepath)
480{
481 if (!bmain || !filepath[0]) {
482 return;
483 }
484
485 const std::string new_root_path = BKE_is_path_inside_blender_project(filepath);
486 if (new_root_path.empty()) {
487 /* The current .blend file is not located in any project, clear the active project. */
489 return;
490 }
491
493 if (project != nullptr && new_root_path == project->get_root_path()) {
494 /* Same project as before, do nothing. */
495 return;
496 }
497
499
500 /* Load the new project. */
501 BKE_blender_project_init_from_root_path(bmain, new_root_path);
502}
503
505{
507 std::optional<bke::BlenderProject> &project = get_project();
508
509 for (auto &user_library : U.asset_libraries.items_mutable()) {
510 if ((user_library.flag & ASSET_LIBRARY_PROJECT_DEFINED)) {
511 /* Usually we also poke some UI code when removing asset libraries.
512 * However this should be fine as the UI should be refreshed when
513 * we are in the process of clearing out the project data.
514 */
516 }
517 }
518
519 project = std::nullopt;
520 });
521}
522
524 const bool path_is_template,
526{
527 const std::string path_str = path;
528 const std::string path_escaped = path_is_template ? path_str :
529 BKE_path_template_escape(path_str);
530
531 /* If a path is blend file relative or not an absolute regular file path, keep it unchanged. */
532 if (BLI_path_is_rel(path_str.c_str()) || !BLI_path_is_abs_from_cwd(path_str.c_str())) {
533 return path_escaped;
534 }
535
536 /* Compare against the root in the same form as the path. */
537 const std::string root = path_is_template ? BKE_path_template_escape(project.get_root_path()) :
538 std::string(project.get_root_path());
539
540 const bool walk_up = false;
541 char path_relative[FILE_MAX];
543 path_str.c_str(), root.c_str(), walk_up, path_relative, sizeof(path_relative)))
544 {
545 return path_escaped;
546 }
547 if (path_relative[0] == '\0') {
548 return "{project_root}";
549 }
550
551 /* Forward slashes for project configuration portability. */
553 const std::string path_relative_escaped = path_is_template ?
554 std::string(path_relative) :
555 BKE_path_template_escape(path_relative);
556 return "{project_root}/" + path_relative_escaped;
557}
558
561{
562 /* Resolve path templates. */
563 char path_expanded[FILE_MAX];
564 path.copy_utf8_truncated(path_expanded);
565
568 if (!BKE_path_apply_template(path_expanded, sizeof(path_expanded), variables).is_empty()) {
569 return "";
570 }
571
572 /* Require absolute path, and no // blend file relative path. */
573 if (BLI_path_is_rel(path_expanded) || !BLI_path_is_abs_from_cwd(path_expanded)) {
574 return "";
575 }
576
577 return path_expanded;
578}
579
581{
582 const std::string project_config_dir = path + SEP_STR + BLENDER_PROJECT_CONFIG_DIR;
583
584 return BLI_is_dir(project_config_dir.c_str());
585}
586
587/* -------------------------------------------------------------------- */
592
593/* Stored as `{name = "...", path = "..."}` tables. */
594using RecentProjectsTOML = std::vector<std::map<std::string, std::string>>;
595
597{
598 Vector<RecentProject> projects;
599 for (const auto &item : recents::Section("project").get<RecentProjectsTOML>("recent")) {
600 const auto path = item.find("path");
601 if (path == item.end() || path->second.empty()) {
602 continue;
603 }
604 const auto name = item.find("name");
605 projects.append({path->second,
606 (name != item.end() && !name->second.empty()) ?
607 name->second :
608 BLI_path_basename(path->second.c_str())});
609 }
610 return projects;
611}
612
613static void recent_projects_set(const Span<RecentProject> projects)
614{
615 RecentProjectsTOML items;
616 for (const RecentProject &project : projects) {
617 items.push_back({{"name", project.name}, {"path", project.path}});
618 }
619
620 recents::Section section("project");
621 if (section.get<RecentProjectsTOML>("recent") != items) {
622 section.set("recent", items);
624 }
625}
626
628{
629 const std::optional<RecentProject> active = BKE_blender_project_read_callback(
630 bmain, [](const bke::BlenderProject *project) -> std::optional<RecentProject> {
631 if (project == nullptr) {
632 return std::nullopt;
633 }
634 char path[FILE_MAX];
635 STRNCPY(path, project->get_root_path().c_str());
636 BLI_path_normalize(path);
638 return RecentProject{path, project->get_name()};
639 });
640 if (!active) {
641 return;
642 }
643
645 projects.remove_if([&](const RecentProject &project) {
646 return BLI_path_cmp(project.path.c_str(), active->path.c_str()) == 0;
647 });
648 projects.insert(0, *active);
649
650 if (projects.size() > U.recent_files) {
651 projects.resize(U.recent_files);
652 }
653 recent_projects_set(projects);
654}
655
656void BKE_blender_project_recent_clear(const bool only_missing)
657{
659 projects.remove_if([&](const RecentProject &project) {
660 return !only_missing || !BKE_blender_project_dir_is_project(project.path);
661 });
662 recent_projects_set(projects);
663}
664
666
667} // namespace blender
#define BLENDER_PROJECT_CONFIG_DIR
#define IDP_float_get(prop)
#define IDP_int_get(prop)
#define IDP_int_set(prop, value)
#define IDP_string_get(prop)
#define IDP_float_set(prop, value)
Functions and classes for evaluating template expressions in filepaths.
File and directory operations.
#define FILE_MAX
#define BLI_path_cmp
volatile int lock
#define ELEM(...)
constexpr const char * c_str() const
constexpr StringRefNull()
int64_t size() const
int64_t remove_if(Predicate &&predicate)
void append(const T &value)
void insert(const int64_t insert_index, const T &value)
void resize(const int64_t new_size)
void set_root_path(StringRef root_path)
void rename_variable(int variable_index, StringRef name)
StringRefNull get_splash_image_path() const
void set_splash_image_path(StringRef splash_image_path)
Vector< std::unique_ptr< ProjectVariable > > variables
StringRefNull get_root_path() const
int find_variable_index(ProjectVariable *var)
StringRefNull get_ocio_config_path() const
void move_variable(int from_index, int to_index)
void set_ocio_config_path(StringRef ocio_config_path)
StringRefNull get_name() const
ProjectVariable * new_variable(StringRef name, ProjectVariableType type)
void set_name(StringRef name)
int remove_variable(ProjectVariable *var)
void string_subtype_set(ProjectVariableStringSubtype type)
ProjectVariable & operator=(const ProjectVariable &other)=delete
void description_set(StringRef description)
ProjectVariable(StringRef name, ProjectVariableType type)
StringRefNull description_get() const
void value_set(StringRefNull value)
StringRefNull value_string_get() const
ProjectVariableStringSubtype string_subtype_get() const
ProjectVariableType type_get() const
StringRefNull name_get() const
constexpr bool is_empty() const
constexpr int64_t size() const
void copy_unsafe(char *dst) const
void copy_utf8_truncated(char *dst, int64_t dst_size) const
Definition string_ref.cc:28
T get(const std::string &item_key) const
Definition recents.cc:224
void set(const std::string &item_key, const T &value)
Definition recents.cc:285
void with_blender_project_write_lock(FunctionRef< void()> lambda)
std::string ensure_is_valid_project_variable_name(StringRef name)
void with_blender_project_read_lock(FunctionRef< void()> lambda)
bool is_valid_project_variable_name(StringRef name)
BMesh Iterators.
UserDef U
Definition blender.cc:58
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
static std::shared_mutex & get_project_mutex()
char * STRNCPY(char(&dst)[N], const char *src)
std::string BKE_blender_project_path_resolve(StringRef path, const bke::BlenderProject &project)
void BLI_path_slash_forward_from_native(char *path) ATTR_NONNULL(1)
Vector< RecentProject > BKE_blender_project_recent_get()
void BKE_blender_project_recent_clear(bool only_missing)
@ ASSET_LIBRARY_PROJECT_DEFINED
bke::BlenderProject * BKE_blender_project_get(const Main *bmain)
void BKE_blender_project_refresh(Main *bmain, const char *filepath)
void BKE_preferences_asset_library_remove(struct UserDef *userdef, struct bUserAssetLibrary *library) ATTR_NONNULL()
size_t BLI_path_append(char *__restrict dst, size_t dst_maxncpy, const char *__restrict file) ATTR_NONNULL(1
auto BKE_blender_project_read_callback(const Main *bmain, Fn lambda)
IDProperty * IDP_NewString(const char *st, StringRef name, eIDPropertyFlag flags={}) ATTR_WARN_UNUSED_RESULT
Definition idprop.cc:443
void MEM_delete_void(void *vmemh)
bool BLI_path_relative_to(const char *path, const char *base_dir, bool walk_up, char *r_path_relative, size_t r_path_relative_maxncpy) ATTR_NONNULL(1
static void recent_projects_set(const Span< RecentProject > projects)
void BKE_blender_project_clear()
Vector< bke::path_templates::Error > BKE_path_apply_template(char *path, int path_maxncpy, const bke::path_templates::VariableMap &template_variables)
size_t void BLI_uniquename_cb(FunctionRef< bool(StringRefNull)> unique_check, const char *defname, char delim, char *name, size_t name_maxncpy) ATTR_NONNULL(2
void void void const char * BLI_path_basename(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
void BLI_path_slash_rstrip(char *path) ATTR_NONNULL(1)
void void BLI_path_split_dir_part(const char *filepath, char *dir, size_t dir_maxncpy) ATTR_NONNULL(1
void IDP_ClearProperty(IDProperty *prop)
Definition idprop.cc:1408
std::string BKE_path_template_escape(StringRef text)
void BKE_blender_project_recent_update(const Main *bmain)
bool BLI_path_is_abs_from_cwd(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
void IDP_AssignString(IDProperty *prop, const char *st) ATTR_NONNULL()
Definition idprop.cc:505
int BLI_path_normalize(char *path) ATTR_NONNULL(1)
void BKE_add_template_variables_for_project(bke::path_templates::VariableMap &variables, const bke::BlenderProject &project)
static std::optional< bke::BlenderProject > & get_project()
bool BLI_is_dir(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:457
std::string BKE_is_path_inside_blender_project(const char *path)
bool BKE_blender_project_init(blender::StringRef name, blender::StringRef root_path)
bool BLI_path_parent_dir(char *path) ATTR_NONNULL(1)
char * BLI_strdup(const char *str) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1) ATTR_MALLOC
bool BLI_path_is_rel(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
IDProperty * IDP_New(char type, const IDPropertyTemplate *val, StringRef name, eIDPropertyFlag flags={}) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition idprop.cc:1132
bool BKE_blender_project_dir_is_project(StringRef path)
IDPropertyUIData * IDP_ui_data_ensure(IDProperty *prop)
Definition idprop.cc:2034
bool BLI_is_file(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:469
bool BKE_blender_project_init_from_root_path(Main *bmain, std::string project_root_path)
std::string BKE_blender_project_path_make_relative(StringRef path, bool path_is_template, const bke::BlenderProject &project)
std::vector< std::map< std::string, std::string > > RecentProjectsTOML
IDPropertyUIData * ui_data
Definition DNA_ID.h:171
eIDPropertyType type
Definition DNA_ID.h:145
bool is_part_of_project
Definition BKE_main.hh:382
#define SEP_STR
Definition unit.cc:41