Blender V5.3
blendfile.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
11
12#include <cstdlib>
13#include <cstring>
14#include <optional>
15
16#include "CLG_log.h"
17
18#include "MEM_guardedalloc.h"
19
20#include "DNA_brush_types.h"
21#include "DNA_scene_types.h"
22#include "DNA_screen_types.h"
23#include "DNA_space_types.h"
25
26#include "BLI_fileops.hh"
27#include "BLI_function_ref.hh"
28#include "BLI_listbase.hh"
29#include "BLI_path_utils.hh"
30#include "BLI_string.hh"
31#include "BLI_string_utf8.hh"
32#include "BLI_system.hh"
33#include "BLI_time.hh"
34#include "BLI_utildefines.hh"
35#include "BLI_vector.hh"
36#include "BLI_vector_set.hh"
37
38#include "BLT_translation.hh"
39
41
42#include "BKE_addon.h"
43#include "BKE_appdir.hh"
44#include "BKE_blender.hh"
45#include "BKE_blender_version.h"
46#include "BKE_blendfile.hh"
47#include "BKE_bpath.hh"
48#include "BKE_colorband.hh"
49#include "BKE_context.hh"
50#include "BKE_global.hh"
51#include "BKE_idtype.hh"
52#include "BKE_layer.hh"
53#include "BKE_lib_id.hh"
54#include "BKE_lib_override.hh"
55#include "BKE_lib_query.hh"
56#include "BKE_lib_remap.hh"
57#include "BKE_library.hh"
58#include "BKE_main.hh"
59#include "BKE_main_idmap.hh"
60#include "BKE_main_namemap.hh"
61#include "BKE_preferences.h"
62#include "BKE_report.hh"
63#include "BKE_scene.hh"
64#include "BKE_screen.hh"
65#include "BKE_studiolight.h"
66#include "BKE_undo_system.hh"
67#include "BKE_workspace.hh"
68
69#include "BLO_read_write.hh"
70#include "BLO_readfile.hh"
71#include "BLO_userdef_default.h"
72#include "BLO_writefile.hh"
73
74#include "RE_pipeline.h"
75
76#ifdef WITH_PYTHON
77# include "BPY_extern.hh"
78#endif
79
80namespace blender {
81
82using namespace bke;
83
84/* -------------------------------------------------------------------- */
87
89{
90 const char *ext_test[4] = {".blend", ".ble", ".blend.gz", nullptr};
91 return BLI_path_extension_check_array(str, ext_test);
92}
93
95 char *r_dir,
96 char **r_group,
97 char **r_name)
98{
99 /* We might get some data names with slashes,
100 * so we have to go up in path until we find blend file itself,
101 * then we know next path item is group, and everything else is data name. */
102 char *slash = nullptr, *prev_slash = nullptr, c = '\0';
103
104 r_dir[0] = '\0';
105 if (r_group) {
106 *r_group = nullptr;
107 }
108 if (r_name) {
109 *r_name = nullptr;
110 }
111
112 /* if path leads to an existing directory, we can be sure we're not (in) a library */
113 if (BLI_is_dir(path)) {
114 return false;
115 }
116
117 BLI_strncpy(r_dir, path, FILE_MAX_LIBEXTRA);
118
119 while ((slash = const_cast<char *>(BLI_path_slash_rfind(r_dir)))) {
120 char tc = *slash;
121 *slash = '\0';
122 if (BKE_blendfile_extension_check(r_dir) && BLI_is_file(r_dir)) {
123 break;
124 }
125 if (STREQ(r_dir, BLO_EMBEDDED_STARTUP_BLEND)) {
126 break;
127 }
128
129 if (prev_slash) {
130 *prev_slash = c;
131 }
132 prev_slash = slash;
133 c = tc;
134 }
135
136 if (!slash) {
137 return false;
138 }
139
140 if (slash[1] != '\0') {
141 BLI_assert(strlen(slash + 1) < BLO_GROUP_MAX);
142 if (r_group) {
143 *r_group = slash + 1;
144 }
145 }
146
147 if (prev_slash && (prev_slash[1] != '\0')) {
148 BLI_assert(strlen(prev_slash + 1) < MAX_ID_NAME - 2);
149 if (r_name) {
150 *r_name = prev_slash + 1;
151 }
152 }
153
154 return true;
155}
156
157bool BKE_blendfile_is_readable(const char *path, ReportList *reports)
158{
159 BlendFileReadReport readfile_reports;
160 readfile_reports.reports = reports;
161 BlendHandle *bh = BLO_blendhandle_from_file(path, &readfile_reports);
162 if (bh != nullptr) {
164 return true;
165 }
166 return false;
167}
168
170
171/* -------------------------------------------------------------------- */
174
175static bool foreach_path_clean_cb(BPathForeachPathData * /*bpath_data*/,
176 char *path_dst,
177 size_t path_dst_maxncpy,
178 const char *path_src)
179{
180 BLI_strncpy(path_dst, path_src, path_dst_maxncpy);
181 BLI_path_slash_native(path_dst);
182 return !STREQ(path_dst, path_src);
183}
184
185/* make sure path names are correct for OS */
186static void clean_paths(Main *bmain)
187{
188 BPathForeachPathData foreach_path_data{};
189 foreach_path_data.bmain = bmain;
190 foreach_path_data.callback_function = foreach_path_clean_cb;
192 foreach_path_data.user_data = nullptr;
193
194 BKE_bpath_foreach_path_main(&foreach_path_data);
195
196 for (Scene &scene : bmain->scenes) {
198 }
199}
200
202{
203 for (wmWindow &win : wm->windows) {
204 if (win.scene == scene) {
205 return true;
206 }
207 }
208 return false;
209}
210
212{
213 if (bfd->user) {
214 /* only here free userdef themes... */
216 bfd->user = nullptr;
217
218 /* Security issue: any blend file could include a #BLO_CODE_USER block.
219 *
220 * Preferences are loaded from #BLENDER_STARTUP_FILE and later on load #BLENDER_USERPREF_FILE,
221 * to load the preferences defined in the users home directory.
222 *
223 * This means we will never accidentally (or maliciously)
224 * enable scripts auto-execution by loading a `.blend` file. */
226 }
227}
228
261
273{
274 if (reuse_data->is_libraries_remapped) {
275 return *reuse_data->remapper;
276 }
277
278 if (reuse_data->remapper == nullptr) {
279 reuse_data->remapper = MEM_new<id::IDRemapper>(__func__);
280 }
281
282 Main *new_bmain = reuse_data->new_bmain;
283 Main *old_bmain = reuse_data->old_bmain;
284 id::IDRemapper &remapper = *reuse_data->remapper;
285
286 for (Library &old_lib_iter : old_bmain->libraries) {
287 /* In case newly opened `new_bmain` is a library of the `old_bmain`, remap it to null, since a
288 * file should never ever have linked data from itself. */
289 if (STREQ(old_lib_iter.runtime->filepath_abs, new_bmain->filepath)) {
290 remapper.add(&old_lib_iter.id, nullptr);
291 continue;
292 }
293
294 /* NOTE: Although this is quadratic complexity, it is not expected to be an issue in practice:
295 * - Files using more than a few tens of libraries are extremely rare.
296 * - This code is only executed once for every file reading (not on undos).
297 */
298 for (Library &new_lib_iter : new_bmain->libraries) {
299 if (!STREQ(old_lib_iter.runtime->filepath_abs, new_lib_iter.runtime->filepath_abs)) {
300 continue;
301 }
302
303 remapper.add(&old_lib_iter.id, &new_lib_iter.id);
304 break;
305 }
306 }
307
308 reuse_data->is_libraries_remapped = true;
309 return *reuse_data->remapper;
310}
311
313{
316 /* ID is already remapped to its matching ID in the new main, or explicitly remapped to null,
317 * nothing else to do here. */
318 return true;
319 }
321 "There should never be a non-mappable (i.e. null) input here.");
323 return false;
324}
325
327 ID *id,
328 Library *lib,
329 const bool reuse_existing)
330{
331 id::IDRemapper &remapper = reuse_bmain_data_remapper_ensure(reuse_data);
332 /* Nothing to move for embedded ID. */
333 if (id->flag & ID_FLAG_EMBEDDED_DATA) {
334 remapper.add(id, id);
335 return true;
336 }
337
338 Main *new_bmain = reuse_data->new_bmain;
339 Main *old_bmain = reuse_data->old_bmain;
340 ListBaseT<ID> *new_lb = which_libbase(new_bmain, id->id_type());
341 ListBaseT<ID> *old_lb = which_libbase(old_bmain, id->id_type());
342
343 if (reuse_existing) {
344 /* A 'new' version of the same data may already exist in new_bmain, in the rare case
345 * that the same asset blend file was linked explicitly into the blend file we are loading.
346 * Don't move the old linked ID, but remap its usages to the new one instead. */
347 for (ID &id_iter : new_lb->items_reversed()) {
348 if (!ELEM(id_iter.lib, id->lib, lib)) {
349 continue;
350 }
351 if (!STREQ(id_iter.name + 2, id->name + 2)) {
352 continue;
353 }
354
355 remapper.add(id, &id_iter);
356 return false;
357 }
358 }
359
360 /* If ID is already in the new_bmain, this should not have been called. */
361 BLI_assert(BLI_findindex(new_lb, id) < 0);
362 BLI_assert(BLI_findindex(old_lb, id) >= 0);
363
364 /* Move from one list to another, and ensure name is valid. */
365 BLI_remlink_safe(old_lb, id);
366
367 /* In case the ID is linked and its library ID is re-used from the old Main, it is not possible
368 * to handle name_map (and ensure name uniqueness).
369 * This is because IDs are moved one by one from old Main's lists to new ones, while the re-used
370 * library's name_map would be built only from IDs in the new list, leading to incomplete/invalid
371 * states.
372 * Currently, such name uniqueness checks should not be needed, as no new name would be expected
373 * in the re-used library. Should this prove to be wrong at some point, the name check will have
374 * to happen at the end of #reuse_editable_asset_bmain_data_for_blendfile, in a separate loop
375 * over Main IDs.
376 */
377 const bool handle_name_map_updates = !ID_IS_LINKED(id) || id->lib != lib;
378 if (handle_name_map_updates) {
379 BKE_main_namemap_remove_id(*old_bmain, *id);
380 }
381
382 id->lib = lib;
383 BLI_addtail(new_lb, id);
384 if (handle_name_map_updates) {
386 *new_bmain, *new_lb, *id, nullptr, IDNewNameMode::RenameExistingNever, true);
387 }
388 else {
389 id_sort_by_name(new_lb, id, nullptr);
390 }
392
393 /* Remap to itself, to avoid re-processing this ID again. */
394 remapper.add(id, id);
395 return true;
396}
397
399 Library *old_lib)
400{
401 const id::IDRemapper &remapper = reuse_bmain_data_remapper_ensure(reuse_data);
402 Library *new_lib = old_lib;
403 IDRemapperApplyResult result = remapper.apply(reinterpret_cast<ID **>(&new_lib),
405
406 switch (result) {
408 /* Move library to new bmain.
409 * There should be no filepath conflicts, as #reuse_bmain_data_remapper_ensure has
410 * already remapped existing libraries with matching filepath. */
411 reuse_bmain_move_id(reuse_data, &old_lib->id, nullptr, false);
412 /* Clear the name_map of the library, as not all of its IDs are guaranteed reused. The name
413 * map cannot be used/kept in valid state while some IDs are moved from old to new main. See
414 * also #reuse_bmain_move_id code. */
416 return old_lib;
417 }
420 return nullptr;
421 }
423 /* Already in new bmain, only transfer flags. */
424 new_lib->runtime->tag |= old_lib->runtime->tag &
426 return new_lib;
427 }
429 /* Happens when the library is the newly opened blend file. */
430 return nullptr;
431 }
432 }
433
435 return nullptr;
436}
437
440{
441 ID *id = *cb_data->id_pointer;
442
443 if (id == nullptr) {
444 return IDWALK_RET_NOP;
445 }
446
447 if (id->id_type() == ID_LI) {
448 /* Libraries are handled separately. */
450 }
451
452 ReuseOldBMainData *reuse_data = static_cast<ReuseOldBMainData *>(cb_data->user_data);
453
454 /* First check if it has already been remapped. */
455 id::IDRemapper &remapper = reuse_bmain_data_remapper_ensure(reuse_data);
458 }
459
460 if (id->lib == nullptr) {
461 /* There should be no links to local datablocks from linked editable data. */
462 remapper.add(id, nullptr);
465 }
466
467 /* Only preserve specific datablock types. */
468 if (!ID_TYPE_SUPPORTS_ASSET_EDITABLE(id->id_type())) {
469 remapper.add(id, nullptr);
471 }
472
473 /* There may be a new library pointer in new_bmain, matching a library in old_bmain, even
474 * though pointer values are not the same. So we need to check new linked IDs in new_bmain
475 * against both potential library pointers. */
476 Library *old_id_new_lib = reuse_bmain_data_dependencies_new_library_get(reuse_data, id->lib);
477
478 /* Happens when the library is the newly opened blend file. */
479 if (old_id_new_lib == nullptr) {
480 remapper.add(id, nullptr);
482 }
483
484 /* Move to new main database. */
485 return reuse_bmain_move_id(reuse_data, id, old_id_new_lib, true) ? IDWALK_RET_STOP_RECURSION :
487}
488
490{
491 Main *old_bmain = reuse_data->old_bmain;
492 for (Library &lib : old_bmain->libraries) {
494 return true;
495 }
496 }
497 return false;
498}
499
514 const short idcode)
515{
516 Main *new_bmain = reuse_data->new_bmain;
517 Main *old_bmain = reuse_data->old_bmain;
518
519 id::IDRemapper &remapper = reuse_bmain_data_remapper_ensure(reuse_data);
520
521 ListBaseT<ID> *old_lb = which_libbase(old_bmain, idcode);
522 ID *old_id_iter;
523
524 FOREACH_MAIN_LISTBASE_ID_BEGIN (old_lb, old_id_iter) {
525 /* Keep any datablocks from libraries marked as LIBRARY_ASSET_EDITABLE. */
526 if (!(ID_IS_LINKED(old_id_iter) && old_id_iter->lib->runtime->tag & LIBRARY_ASSET_EDITABLE)) {
527 continue;
528 }
529
530 Library *old_id_new_lib = reuse_bmain_data_dependencies_new_library_get(reuse_data,
531 old_id_iter->lib);
532
533 /* Happens when the library is the newly opened blend file. */
534 if (old_id_new_lib == nullptr) {
535 remapper.add(old_id_iter, nullptr);
536 continue;
537 }
538
539 if (reuse_bmain_move_id(reuse_data, old_id_iter, old_id_new_lib, true)) {
540 /* Port over dependencies of re-used ID, unless matching already existing ones in
541 * new_bmain can be found.
542 *
543 * NOTE : No pointers are remapped here, this code only moves dependencies from old_bmain
544 * to new_bmain if needed, and add necessary remapping rules to the reuse_data.remapper. */
546 old_id_iter,
548 reuse_data,
550 }
551 }
553}
554
560{
561 ID *old_id_iter;
562 FOREACH_MAIN_LISTBASE_ID_BEGIN (&reuse_data->old_bmain->brushes, old_id_iter) {
563 const Brush *brush = reinterpret_cast<Brush *>(old_id_iter);
564 if (brush->gpencil_settings && brush->gpencil_settings->material &&
565 /* Don't unpin if this material is linked, then it can be preserved for the new file. */
566 !ID_IS_LINKED(brush->gpencil_settings->material))
567 {
568 /* Unpin material and clear pointer. */
569 brush->gpencil_settings->flag &= ~GP_BRUSH_MATERIAL_PINNED;
570 brush->gpencil_settings->material = nullptr;
571 }
572 }
574}
575
587static void swap_old_bmain_data_for_blendfile(ReuseOldBMainData *reuse_data, const short id_code)
588{
589 Main *new_bmain = reuse_data->new_bmain;
590 Main *old_bmain = reuse_data->old_bmain;
591
592 ListBaseT<ID> *new_lb = which_libbase(new_bmain, id_code);
593 ListBaseT<ID> *old_lb = which_libbase(old_bmain, id_code);
594
595 id::IDRemapper &remapper = reuse_bmain_data_remapper_ensure(reuse_data);
596
597 /* NOTE: Full swapping is only supported for ID types that are assumed to be only local
598 * data-blocks (like UI-like ones). Otherwise, the swapping could fail in many funny ways. */
599 BLI_assert(old_lb->is_empty() || !ID_IS_LINKED(old_lb->last()));
600 BLI_assert(new_lb->is_empty() || !ID_IS_LINKED(new_lb->last()));
601
602 std::swap(*new_lb, *old_lb);
603
604 /* TODO: Could add per-IDType control over name-maps clearing, if this becomes a performances
605 * concern. */
606 BKE_main_namemap_clear(*old_bmain);
607 BKE_main_namemap_clear(*new_bmain);
608
609 /* Original 'new' IDs have been moved into the old listbase and will be discarded (deleted).
610 * Original 'old' IDs have been moved into the new listbase and are being reused (kept).
611 * The discarded ones need to be remapped to a matching reused one, based on their names, if
612 * possible.
613 *
614 * Since both lists are ordered, and they are all local, we can do a smart parallel processing of
615 * both lists here instead of doing complete full list searches. */
616 ID *discarded_id_iter = old_lb->first();
617 ID *reused_id_iter = new_lb->first();
618 while (!ELEM(nullptr, discarded_id_iter, reused_id_iter)) {
619 const int strcmp_result = strcmp(discarded_id_iter->name + 2, reused_id_iter->name + 2);
620 if (strcmp_result == 0) {
621 /* Matching IDs, we can remap the discarded 'new' one to the re-used 'old' one. */
622 remapper.add(discarded_id_iter, reused_id_iter);
623
624 discarded_id_iter = static_cast<ID *>(discarded_id_iter->next);
625 reused_id_iter = static_cast<ID *>(reused_id_iter->next);
626 }
627 else if (strcmp_result < 0) {
628 /* No matching reused 'old' ID for this discarded 'new' one. */
629 remapper.add(discarded_id_iter, nullptr);
630
631 discarded_id_iter = static_cast<ID *>(discarded_id_iter->next);
632 }
633 else {
634 reused_id_iter = static_cast<ID *>(reused_id_iter->next);
635 }
636 }
637 /* Also remap all remaining non-compared discarded 'new' IDs to null. */
638 for (; discarded_id_iter != nullptr;
639 discarded_id_iter = static_cast<ID *>(discarded_id_iter->next))
640 {
641 remapper.add(discarded_id_iter, nullptr);
642 }
643
644 FOREACH_MAIN_LISTBASE_ID_BEGIN (new_lb, reused_id_iter) {
645 /* Necessary as all `session_uid` are renewed on blendfile loading. */
647
648 /* Ensure that the reused ID is remapped to itself, since it is known to be in the `new_bmain`.
649 */
650 remapper.add_overwrite(reused_id_iter, reused_id_iter);
651 }
653}
654
660static void swap_wm_data_for_blendfile(ReuseOldBMainData *reuse_data, const bool load_ui)
661{
662 Main *old_bmain = reuse_data->old_bmain;
663 Main *new_bmain = reuse_data->new_bmain;
664 ListBaseT<wmWindowManager> *old_wm_list = &old_bmain->wm;
665 ListBaseT<wmWindowManager> *new_wm_list = &new_bmain->wm;
666
667 /* Currently there should never be more than one WM in a main. */
668 BLI_assert(BLI_listbase_count_at_most(new_wm_list, 2) <= 1);
669 BLI_assert(BLI_listbase_count_at_most(old_wm_list, 2) <= 1);
670
671 wmWindowManager *old_wm = old_wm_list->first();
672 wmWindowManager *new_wm = new_wm_list->first();
673
674 if (old_wm == nullptr) {
675 /* No current (old) WM. Either (new) WM from file is used, or if none, WM code is responsible
676 * to add a new default WM. Nothing to do here. */
677 return;
678 }
679
680 /* Current (old) WM, and (new) WM in file, and loading UI: use WM from file, keep old WM around
681 * for further processing in WM code. */
682 if (load_ui && new_wm != nullptr) {
683 /* Support window-manager ID references being held between file load operations by keeping
684 * #Main.wm.first memory address in-place, while swapping all of its contents.
685 *
686 * This is needed so items such as key-maps can be held by an add-on,
687 * without it pointing to invalid memory, see: #86431. */
688 BLI_remlink(old_wm_list, old_wm);
689 BLI_remlink(new_wm_list, new_wm);
690 BKE_lib_id_swap_full(nullptr,
691 &old_wm->id,
692 &new_wm->id,
693 true,
696 /* Not strictly necessary, but helps for readability. */
697 std::swap<wmWindowManager *>(old_wm, new_wm);
698 BLI_addhead(new_wm_list, new_wm);
699 /* Do not add old WM back to `old_bmain`, so that it does not get freed when `old_bmain` is
700 * freed. Calling WM code will need this old WM to restore some windows etc. data into the
701 * new WM, and is responsible to free it properly. */
702 reuse_data->wm_setup_data->old_wm = old_wm;
703
704 id::IDRemapper &remapper = reuse_bmain_data_remapper_ensure(reuse_data);
705 remapper.add(&old_wm->id, &new_wm->id);
706 }
707 /* Current (old) WM, but no (new) one in file (should only happen when reading pre 2.5 files, no
708 * WM back then), or not loading UI: Keep current WM. */
709 else {
712 reuse_data->wm_setup_data->old_wm = old_wm;
713 }
714}
715
718{
719 ID *id = *cb_data->id_pointer;
720
721 if (id == nullptr) {
722 return IDWALK_RET_NOP;
723 }
724
725 ReuseOldBMainData *reuse_data = static_cast<ReuseOldBMainData *>(cb_data->user_data);
726
727 /* First check if it has already been remapped. */
728 id::IDRemapper &remapper = reuse_bmain_data_remapper_ensure(reuse_data);
730 return IDWALK_RET_NOP;
731 }
732
733 IDNameLib_Map *id_map = reuse_data->id_map;
734 BLI_assert(id_map != nullptr);
735
736 ID *id_new = BKE_main_idmap_lookup_id(id_map, id);
737 remapper.add(id, id_new);
738
739 return IDWALK_RET_NOP;
740}
741
743 const short id_code)
744{
745 Main *new_bmain = reuse_data->new_bmain;
746 ListBaseT<ID> *new_lb = which_libbase(new_bmain, id_code);
747
748 BLI_assert(reuse_data->id_map != nullptr);
749
750 ID *new_id_iter;
751 FOREACH_MAIN_LISTBASE_ID_BEGIN (new_lb, new_id_iter) {
752 /* Check all ID usages and find a matching new ID to remap them to in `new_bmain` if possible
753 * (matching by names and libraries).
754 *
755 * Note that this call does not do any effective remapping, it only adds required remapping
756 * operations to the remapper. */
758 new_id_iter,
760 reuse_data,
762 }
764}
765
767{
768 ID *id = *cb_data->id_pointer;
769
770 if (id == nullptr) {
771 return IDWALK_RET_NOP;
772 }
773
774 /* Embedded data cannot (yet) be fully trusted to have the same lib pointer as their owner ID, so
775 * for now ignore them. This code should never have anything to fix for them anyway, otherwise
776 * there is something extremely wrong going on. */
777 if ((cb_data->cb_flag & (IDWALK_CB_EMBEDDED | IDWALK_CB_EMBEDDED_NOT_OWNING)) != 0) {
778 return IDWALK_RET_NOP;
779 }
780
781 if (!ID_IS_LINKED(id)) {
782 ID *owner_id = cb_data->owner_id;
783
784 /* Do not allow linked data to use local data. */
785 if (ID_IS_LINKED(owner_id)) {
786 if (cb_data->cb_flag & IDWALK_CB_USER) {
787 id_us_min(id);
788 }
789 *cb_data->id_pointer = nullptr;
790 }
791 /* Do not allow local liboverride data to use local data as reference. */
792 else if (ID_IS_OVERRIDE_LIBRARY_REAL(owner_id) &&
793 &owner_id->override_library->reference == cb_data->id_pointer)
794 {
795 if (cb_data->cb_flag & IDWALK_CB_USER) {
796 id_us_min(id);
797 }
798 *cb_data->id_pointer = nullptr;
799 }
800 }
801
802 return IDWALK_RET_NOP;
803}
804
809{
810 Main *new_bmain = reuse_data->new_bmain;
811 ID *id_iter;
812 FOREACH_MAIN_ID_BEGIN (new_bmain, id_iter) {
813 if (!ID_IS_LINKED(id_iter) && !ID_IS_OVERRIDE_LIBRARY_REAL(id_iter)) {
814 continue;
815 }
816
817 ID *liboverride_reference = ID_IS_OVERRIDE_LIBRARY_REAL(id_iter) ?
818 id_iter->override_library->reference :
819 nullptr;
820
822 new_bmain, id_iter, reuse_bmain_data_invalid_local_usages_fix_cb, reuse_data, IDWALK_NOP);
823
824 /* Liboverrides who lost their reference should not be liboverrides anymore, but regular IDs.
825 */
826 if (ID_IS_OVERRIDE_LIBRARY_REAL(id_iter) &&
827 id_iter->override_library->reference != liboverride_reference)
828 {
830 }
831 }
833}
834
835/* Post-remapping helpers to ensure validity of the UI data. */
836
837static void view3d_data_consistency_ensure(wmWindow *win, Scene *scene, ViewLayer *view_layer)
838{
840
841 for (ScrArea &area : screen->areabase) {
842 for (SpaceLink &sl : area.spacedata) {
843 if (sl.spacetype != SPACE_VIEW3D) {
844 continue;
845 }
846
847 View3D *v3d = reinterpret_cast<View3D *>(&sl);
848 if (v3d->camera == nullptr || v3d->scenelock) {
849 v3d->camera = scene->camera;
850 }
851 if (v3d->localvd == nullptr) {
852 continue;
853 }
854
855 if (v3d->localvd->camera == nullptr || v3d->scenelock) {
856 v3d->localvd->camera = v3d->camera;
857 }
858 /* Local-view can become invalid during undo/redo steps, exit it when no valid object could
859 * be found. */
860 Base *base;
861 for (base = view_layer->object_bases.first(); base; base = base->next) {
862 if (base->local_view_bits & v3d->local_view_uid) {
863 break;
864 }
865 }
866 if (base != nullptr) {
867 /* The local view3D still has a valid object, nothing else to do. */
868 continue;
869 }
870
871 /* No valid object found for the local view3D, it has to be cleared off. */
872 MEM_delete(v3d->localvd);
873 v3d->localvd = nullptr;
874 v3d->local_view_uid = 0;
875
876 /* Region-base storage is different depending on whether the space is active or not. */
877 ListBaseT<ARegion> *regionbase = (&sl == area.spacedata.first()) ? &area.regionbase :
878 &sl.regionbase;
879 for (ARegion &region : *regionbase) {
880 if (region.regiontype != RGN_TYPE_WINDOW) {
881 continue;
882 }
883
884 RegionView3D *rv3d = static_cast<RegionView3D *>(region.regiondata);
885 MEM_SAFE_DELETE(rv3d->localvd);
886 }
887 }
888 }
889}
890
892 Scene *cur_scene,
893 ViewLayer *cur_view_layer)
894{
895 /* There may not be any available WM (e.g. when reading `userpref.blend`). */
896 if (curwm == nullptr) {
897 return;
898 }
899
900 for (wmWindow &win : curwm->windows) {
901 if (win.scene == nullptr) {
902 win.scene = cur_scene;
903 }
904 if (BKE_view_layer_find(win.scene, win.view_layer_name) == nullptr) {
905 STRNCPY_UTF8(win.view_layer_name, cur_view_layer->name);
906 }
907
908 view3d_data_consistency_ensure(&win, win.scene, cur_view_layer);
909 }
910}
911
925 BlendFileData *bfd,
926 const BlendFileReadParams *params,
927 BlendFileReadWMSetupData *wm_setup_data,
928 BlendFileReadReport *reports)
929{
930 Main *bmain = G_MAIN;
931 const bool recover = (G.fileflags & G_FILE_RECOVER_READ) != 0;
932 enum {
933 LOAD_UI = 1,
934 LOAD_UI_OFF,
935 LOAD_UNDO,
936 } mode;
937
938 if (params->undo_direction != STEP_INVALID) {
939 BLI_assert(bfd->curscene != nullptr);
940 mode = LOAD_UNDO;
941 }
942 else if (bfd->fileflags & G_FILE_ASSET_EDIT_FILE) {
943 BKE_report(reports->reports,
945 "This file is managed by the asset system, you cannot overwrite it (using \"Save "
946 "As\" is possible)");
947 /* From now on the file in memory is a normal file, further saving it will contain a
948 * window-manager, scene, ... and potentially user created data. Use #Main.is_asset_edit_file
949 * to detect if saving this file needs extra protections. */
952 mode = LOAD_UI_OFF;
953 }
954 /* May happen with library files, loading undo-data should never have a null `curscene`
955 * (but may have a null `curscreen`). */
956 else if (ELEM(nullptr, bfd->curscreen, bfd->curscene)) {
957 BKE_report(reports->reports, RPT_WARNING, "Library file, loading empty scene");
958 mode = LOAD_UI_OFF;
959 }
960 else if (G.fileflags & G_FILE_NO_UI) {
961 mode = LOAD_UI_OFF;
962 }
963 else {
964 mode = LOAD_UI;
965 }
966
967 /* Free all render results and interactive compositor renders, without this stale data gets
968 * displayed after loading files */
969 if (mode != LOAD_UNDO) {
972 }
973
974 /* Only make file-paths compatible when loading for real (not undo). */
975 if (mode != LOAD_UNDO) {
976 clean_paths(bfd->main);
977 }
978
980
981 /* Temporary data to handle swapping around IDs between old and new mains,
982 * and accumulate the required remapping accordingly. */
983 ReuseOldBMainData reuse_data = {nullptr};
984 reuse_data.new_bmain = bfd->main;
985 reuse_data.old_bmain = bmain;
986 reuse_data.wm_setup_data = wm_setup_data;
987
988 const bool reuse_editable_assets = mode != LOAD_UNDO && !params->is_factory_settings &&
989 reuse_editable_asset_needed(&reuse_data);
990
991 if (mode != LOAD_UNDO) {
992 /* Convert editable assets to the new file working space. */
994 bfd->main, bmain, params->is_startup, reuse_editable_assets);
995
996 const short ui_id_codes[]{ID_WS, ID_SCR};
997
998 /* WM needs special complex handling, regardless of whether UI is kept or loaded from file. */
999 swap_wm_data_for_blendfile(&reuse_data, mode == LOAD_UI);
1000 if (mode != LOAD_UI) {
1001 /* Re-use UI data from `old_bmain` if keeping existing UI. */
1002 for (auto id_code : ui_id_codes) {
1003 swap_old_bmain_data_for_blendfile(&reuse_data, id_code);
1004 }
1005 }
1006
1007 /* Needs to happen after all data from `old_bmain` has been moved into new one. */
1008 BLI_assert(reuse_data.id_map == nullptr);
1009 reuse_data.id_map = BKE_main_idmap_create(
1010 reuse_data.new_bmain, true, reuse_data.old_bmain, MAIN_IDMAP_TYPE_NAME);
1011
1013 if (mode != LOAD_UI) {
1014 for (auto id_code : ui_id_codes) {
1015 swap_old_bmain_data_dependencies_process(&reuse_data, id_code);
1016 }
1017 }
1018
1019 BKE_main_idmap_destroy(reuse_data.id_map);
1020
1021 if (reuse_editable_assets) {
1023 /* Keep linked brush asset data, similar to UI data. Only does a known
1024 * subset know. Could do everything, but that risks dragging along more
1025 * scene data than we want. */
1026 for (short idtype_index = 0; idtype_index < INDEX_ID_MAX; idtype_index++) {
1027 const IDTypeInfo *idtype_info = BKE_idtype_get_info_from_idtype_index(idtype_index);
1028 if (ID_TYPE_SUPPORTS_ASSET_EDITABLE(idtype_info->id_code)) {
1029 reuse_editable_asset_bmain_data_for_blendfile(&reuse_data, idtype_info->id_code);
1030 }
1031 }
1032 }
1033
1034 if (mode != LOAD_UI) {
1035 for (bScreen &screen : bfd->main->screens) {
1037 }
1038 }
1039 }
1040
1041 /* Logic for 'track_undo_scene' is to keep using the scene which the active screen has, as long
1042 * as the scene associated with the undo operation is visible in one of the open windows.
1043 *
1044 * - 'curscreen->scene': Scene the user is currently looking at.
1045 * - 'bfd->curscene': Scene undo-step was created in.
1046 *
1047 * This means that users can have 2 or more windows open and undo in both without screens
1048 * switching. But if they close one of the screens, undo will ensure that the scene being
1049 * operated on will be activated (otherwise we'd be undoing on an off-screen scene which isn't
1050 * acceptable). See: #43424. */
1051 bool track_undo_scene = false;
1052
1053 /* Always use the Scene and ViewLayer pointers from new file, if possible. */
1054 ViewLayer *cur_view_layer = bfd->cur_view_layer;
1055 Scene *curscene = bfd->curscene;
1056
1057 wmWindow *win = nullptr;
1058 bScreen *curscreen = nullptr;
1059
1060 /* Ensure that there is a valid scene and view-layer. */
1061 if (curscene == nullptr) {
1062 curscene = bfd->main->scenes.first();
1063 }
1064 /* Empty file, add a scene to make Blender work. */
1065 if (curscene == nullptr) {
1066 curscene = BKE_scene_add(bfd->main, "Empty");
1067 }
1068 if (cur_view_layer == nullptr) {
1069 /* Fallback to the active scene view layer. */
1070 cur_view_layer = BKE_view_layer_default_view(curscene);
1071 }
1072
1073 /* If UI is not loaded when opening actual `.blend` file,
1074 * and always in case of undo MEMFILE reading. */
1075 if (mode != LOAD_UI) {
1076 /* Re-use current window and screen. */
1077 win = CTX_wm_window(C);
1078 curscreen = CTX_wm_screen(C);
1079
1080 track_undo_scene = (mode == LOAD_UNDO && curscreen && curscene && bfd->main->wm.first());
1081
1082 if (track_undo_scene) {
1083 /* Keep the old (to-be-freed) scene, remapping below will ensure it's remapped to the
1084 * matching new scene if available, or null otherwise, in which case
1085 * #wm_data_consistency_ensure will define `curscene` as the active one. */
1086 }
1087 /* Enforce `curscene` to be in current screen. */
1088 else if (win) { /* The window may be null in background-mode. */
1089 win->scene = curscene;
1090 }
1091 }
1092
1094
1095 /* Apply remapping of ID pointers caused by re-using part of the data from the 'old' main into
1096 * the new one. */
1097 if (reuse_data.remapper != nullptr) {
1098 /* In undo case all "keeping old data" and remapping logic is now handled
1099 * in file reading code itself, so there should never be any remapping to do here. */
1100 BLI_assert(mode != LOAD_UNDO);
1101
1102 /* Handle all pending remapping from swapping old and new IDs around. */
1104 *reuse_data.remapper,
1107
1108 /* Fix potential invalid usages of now-locale-data created by remapping above. Should never
1109 * be needed in undo case, this is to address cases like:
1110 * "opening a blend-file that was a library of the previous opened blend-file". */
1112
1113 MEM_delete(reuse_data.remapper);
1114 reuse_data.remapper = nullptr;
1115
1116 wm_data_consistency_ensure(CTX_wm_manager(C), curscene, cur_view_layer);
1117 }
1118
1119 if (mode == LOAD_UNDO) {
1120 /* It's possible to undo into a time before the scene existed, in this case the window's scene
1121 * will be null. Since it doesn't make sense to remove the window, set it to the current scene.
1122 *
1123 * NOTE: Redo will restore the active scene to the window so a reasonably consistent state
1124 * is maintained. We could do better by keeping a window/scene map for each undo step.
1125 *
1126 * Another source of potential inconsistency is undoing into a step where the active camera
1127 * object does not exist (see e.g. #125636).
1128 */
1129 wm_data_consistency_ensure(CTX_wm_manager(C), curscene, cur_view_layer);
1130 }
1131
1133
1134 if (mode != LOAD_UI) {
1135 if (win) {
1136 curscene = win->scene;
1137 }
1138
1139 if (track_undo_scene) {
1140 wmWindowManager *wm = bfd->main->wm.first();
1141 if (!wm_scene_is_visible(wm, bfd->curscene)) {
1142 curscene = bfd->curscene;
1143 if (win) {
1144 win->scene = curscene;
1145 }
1146 BKE_screen_view3d_scene_sync(curscreen, curscene);
1147 }
1148 }
1149
1150 /* We need to tag this here because events may be handled immediately after.
1151 * only the current screen is important because we won't have to handle
1152 * events from multiple screens at once. */
1153 if (curscreen) {
1155 }
1156 }
1157 CTX_data_scene_set(C, curscene);
1158
1160
1161 /* For undo to preserve some runtime state. */
1162 const MainColorspace old_colorspace = bmain->colorspace;
1163
1164 /* This frees the `old_bmain`. */
1166 bmain = G_MAIN;
1167 bfd->main = nullptr;
1168 CTX_data_main_set(C, bmain);
1169
1171
1172 /* These context data should remain valid if old UI is being re-used. */
1173 if (mode == LOAD_UI) {
1174 /* Setting a window-manger clears all other windowing members (window, screen, area, etc).
1175 * So only do it when effectively loading a new #wmWindowManager
1176 * otherwise just assert that the WM from context is still the same as in `new_bmain`. */
1177 CTX_wm_manager_set(C, bmain->wm.first());
1179 CTX_wm_area_set(C, nullptr);
1180 CTX_wm_region_set(C, nullptr);
1181 CTX_wm_region_popup_set(C, nullptr);
1182 }
1183 BLI_assert(CTX_wm_manager(C) == bmain->wm.first());
1184
1185 /* Keep state from preferences. */
1186 const int fileflags_keep = G_FILE_FLAG_ALL_RUNTIME;
1187 G.fileflags = (G.fileflags & fileflags_keep) | (bfd->fileflags & ~fileflags_keep);
1188
1189 /* Special cases, override any #G_FLAG_ALL_READFILE flags from the blend-file. */
1190 if (G.f != bfd->globalf) {
1191 const int flags_keep = G_FLAG_ALL_RUNTIME;
1193 bfd->globalf = (bfd->globalf & ~flags_keep) | (G.f & flags_keep);
1194 }
1195
1196 G.f = bfd->globalf;
1197
1198#ifdef WITH_PYTHON
1199 /* let python know about new main */
1200 if (CTX_py_init_get(C)) {
1202 }
1203#endif
1204
1205 if (mode != LOAD_UNDO) {
1206 /* Perform complex versioning that involves adding or removing IDs,
1207 * and/or needs to operate over the whole Main data-base
1208 * (versioning done in file reading code only operates on a per-library basis). */
1209 BLO_read_do_version_after_setup(bmain, nullptr, reports);
1210 }
1211
1212 /* Always clear readfile runtime data, keeping this beyond the readfile scope can have unexpected
1213 * side-effects, especially on next readfile call when considering IDs from the old Main
1214 * data-base, see e.g. #157387. */
1216
1217 bmain->recovered = false;
1218
1219 /* `startup.blend` or recovered startup. */
1220 if (params->is_startup) {
1221 bmain->filepath[0] = '\0';
1222 }
1223 else if (recover) {
1224 /* In case of auto-save or `quit.blend`, use original file-path instead
1225 * (see also #read_global in `readfile.cc`). */
1226 bmain->recovered = true;
1227 STRNCPY(bmain->filepath, bfd->filepath);
1228 }
1229
1230 /* Set the loaded .blend file path for crash recovery. */
1231 STRNCPY(G.filepath_last_blend, bmain->filepath);
1232
1233 /* Base-flags, groups, make depsgraph, etc. */
1234 /* first handle case if other windows have different scenes visible. */
1235 if (mode == LOAD_UI) {
1236 wmWindowManager *wm = bmain->wm.first();
1237 if (wm) {
1238 for (wmWindow &win : wm->windows) {
1239 if (win.scene && win.scene != curscene) {
1240 BKE_scene_set_background(bmain, win.scene);
1241 }
1242 }
1243 }
1244 }
1245
1246 /* Setting scene might require having a dependency graph, with copy-on-eval
1247 * we need to make sure we ensure scene has correct color management before
1248 * constructing dependency graph. */
1249 if (mode == LOAD_UNDO) {
1250 IMB_colormanagement_undo_read_post(bmain, old_colorspace);
1251 }
1253
1254 BKE_scene_set_background(bmain, curscene);
1255
1256 if (mode != LOAD_UNDO) {
1257 /* TODO(@sergey): Can this be also move above? */
1259 }
1260
1261 /* Both undo and regular file loading can perform some fairly complex ID manipulation, simpler
1262 * and safer to fully redo reference-counting. This is a relatively cheap process anyway. */
1263 BKE_main_id_refcount_recompute(bmain, false);
1264
1266
1267 if (mode != LOAD_UNDO && liboverride::is_auto_resync_enabled()) {
1268 reports->duration.lib_overrides_resync = BLI_time_now_seconds();
1269
1270 /* Null hierarchy roots are never expected here for regular liboverrides. Attempt to fix them
1271 * so that resync can perform as best as possible, and report them as errors. */
1274
1276 bmain,
1277 nullptr,
1278 curscene,
1280 reports);
1281
1282 reports->duration.lib_overrides_resync = BLI_time_now_seconds() -
1283 reports->duration.lib_overrides_resync;
1284
1285 /* We need to rebuild some of the deleted override rules (for UI feedback purpose). */
1287 }
1288
1289 /* Now that liboverrides have been resynced and 'irrelevant' missing linked IDs has been removed,
1290 * report actual missing linked data. */
1291 if (mode != LOAD_UNDO) {
1292 ID *id_iter;
1293 int missing_linked_ids_num = 0;
1294 FOREACH_MAIN_ID_BEGIN (bmain, id_iter) {
1295 if (ID_IS_LINKED(id_iter) && (id_iter->tag & ID_TAG_MISSING)) {
1296 missing_linked_ids_num++;
1297 BLO_reportf_wrap(reports,
1298 RPT_INFO,
1299 RPT_("LIB: %s: '%s' missing from '%s', parent '%s'"),
1300 BKE_idtype_idcode_to_name(id_iter->id_type()),
1301 id_iter->name + 2,
1302 id_iter->lib->runtime->filepath_abs,
1303 id_iter->lib->runtime->parent ?
1304 id_iter->lib->runtime->parent->runtime->filepath_abs :
1305 "<direct>");
1306 }
1307 }
1309 reports->count.missing_linked_id = missing_linked_ids_num;
1310 }
1311}
1312
1314 BlendFileData *bfd,
1315 const BlendFileReadParams *params,
1316 BlendFileReadWMSetupData *wm_setup_data,
1317 BlendFileReadReport *reports)
1318{
1319 if ((params->skip_flags & BLO_READ_SKIP_USERDEF) == 0) {
1320 setup_app_userdef(bfd);
1321 }
1322 if ((params->skip_flags & BLO_READ_SKIP_DATA) == 0) {
1323 setup_app_data(C, bfd, params, wm_setup_data, reports);
1324 }
1325}
1326
1328{
1329 if (main->versionfile > BLENDER_FILE_VERSION || (main->versionfile == BLENDER_FILE_VERSION &&
1330 main->subversionfile > BLENDER_FILE_SUBVERSION))
1331 {
1332 BKE_reportf(reports->reports,
1334 "File written by newer Blender binary (%d.%d), expect loss of data!",
1335 main->versionfile,
1336 main->subversionfile);
1337 }
1338}
1339
1341 BlendFileData *bfd,
1342 const BlendFileReadParams *params,
1343 BlendFileReadWMSetupData *wm_setup_data,
1344 BlendFileReadReport *reports,
1345 /* Extra args. */
1346 const bool startup_update_defaults,
1347 const char *startup_app_template)
1348{
1349 if (bfd->main->is_read_invalid) {
1351 "File could not be read, critical data corruption detected");
1353 return;
1354 }
1355
1356 if (startup_update_defaults) {
1357 if ((params->skip_flags & BLO_READ_SKIP_DATA) == 0) {
1358 BLO_update_defaults_startup_blend(bfd->main, startup_app_template);
1359 }
1360 }
1361 setup_app_blend_file_data(C, bfd, params, wm_setup_data, reports);
1363}
1364
1366 BlendFileData *bfd,
1367 const BlendFileReadParams *params,
1368 BlendFileReadReport *reports)
1369{
1370 BKE_blendfile_read_setup_readfile(C, bfd, params, nullptr, reports, false, nullptr);
1371}
1372
1373static CLG_LogRef LOG_BLEND = {"blend"};
1374
1375BlendFileData *BKE_blendfile_read(const char *filepath,
1376 const BlendFileReadParams *params,
1377 BlendFileReadReport *reports)
1378{
1379 /* Don't print startup file loading. */
1380 if (params->is_startup == false) {
1381 CLOG_INFO_NOCHECK(&LOG_BLEND, "Read blend: \"%s\"", filepath);
1382 }
1383
1384 BlendFileData *bfd = BLO_read_from_file(filepath, eBLOReadSkip(params->skip_flags), reports);
1385 if (bfd && bfd->main->is_read_invalid) {
1387 bfd = nullptr;
1388 }
1389 if (bfd) {
1390 handle_subversion_warning(bfd->main, reports);
1391 }
1392 else {
1393 BKE_reports_prependf(reports->reports, "Loading \"%s\" failed: ", filepath);
1394 }
1395 return bfd;
1396}
1397
1399 int file_buf_size,
1400 const BlendFileReadParams *params,
1401 ReportList *reports)
1402{
1404 file_buf, file_buf_size, eBLOReadSkip(params->skip_flags), reports);
1405 if (bfd && bfd->main->is_read_invalid) {
1407 bfd = nullptr;
1408 }
1409 if (bfd) {
1410 /* Pass. */
1411 }
1412 else {
1413 BKE_reports_prepend(reports, "Loading failed: ");
1414 }
1415 return bfd;
1416}
1417
1419 MemFile *memfile,
1420 const BlendFileReadParams *params,
1421 ReportList *reports)
1422{
1424 bmain, BKE_main_blendfile_path(bmain), memfile, params, reports);
1425 if (bfd && bfd->main->is_read_invalid) {
1427 bfd = nullptr;
1428 }
1429 if (bfd == nullptr) {
1430 BKE_reports_prepend(reports, "Loading failed: ");
1431 }
1432 return bfd;
1433}
1434
1436{
1437 Main *bmain = CTX_data_main(C);
1438 ListBaseT<ID> *lb;
1439 ID *id;
1440
1441 FOREACH_MAIN_LISTBASE_BEGIN (bmain, lb) {
1443 if (ELEM(id->id_type(), ID_SCE, ID_SCR, ID_WM, ID_WS)) {
1444 break;
1445 }
1446 BKE_id_delete(bmain, id);
1447 }
1449 }
1451}
1452
1454
1455/* -------------------------------------------------------------------- */
1480
1481UserDef *BKE_blendfile_userdef_read(const char *filepath, ReportList *reports)
1482{
1483 BlendFileData *bfd;
1484 UserDef *userdef = nullptr;
1485
1486 BlendFileReadReport blend_file_read_reports{};
1487 blend_file_read_reports.reports = reports;
1488
1489 bfd = BLO_read_from_file(
1490 filepath, BLO_READ_SKIP_ALL & ~BLO_READ_SKIP_USERDEF, &blend_file_read_reports);
1491 if (bfd) {
1492 if (bfd->user) {
1493 userdef = bfd->user;
1494 }
1495 BKE_main_free(bfd->main);
1496 MEM_delete(bfd);
1497 }
1498
1499 /*
1500 * Enable translation by default. ALT Linux specific patch.
1501 * See ALT#31561
1502 */
1503
1504 userdef->language = ULANGUAGE_AUTO;
1505 userdef->transopts |= USER_TR_IFACE;
1506 userdef->transopts |= USER_TR_TOOLTIPS;
1507 userdef->transopts |= USER_TR_NEWDATANAME;
1508
1509 return userdef;
1510}
1511
1513 int file_buf_size,
1514 ReportList *reports)
1515{
1516 BlendFileData *bfd;
1517 UserDef *userdef = nullptr;
1518
1520 file_buf, file_buf_size, BLO_READ_SKIP_ALL & ~BLO_READ_SKIP_USERDEF, reports);
1521 if (bfd) {
1522 if (bfd->user) {
1523 userdef = bfd->user;
1524 }
1525 BKE_main_free(bfd->main);
1526 MEM_delete(bfd);
1527 }
1528 else {
1529 BKE_reports_prepend(reports, "Loading failed: ");
1530 }
1531
1532 return userdef;
1533}
1534
1536{
1537 UserDef *userdef = MEM_new<UserDef>(__func__);
1538
1541
1542 /* Add-ons. */
1543 {
1544 const char *addons[] = {
1545 "io_anim_bvh",
1546 "io_curve_svg",
1547 "io_mesh_uv_layout",
1548 "io_scene_fbx",
1549 "io_scene_gltf2",
1550 "cycles",
1551 "pose_library",
1552 "bl_pkg",
1553 };
1554 for (int i = 0; i < ARRAY_SIZE(addons); i++) {
1555 bAddon *addon = BKE_addon_new();
1556 STRNCPY_UTF8(addon->module, addons[i]);
1557 BLI_addtail(&userdef->addons, addon);
1558 }
1559 }
1560
1561 /* Theme. */
1562 {
1563 bTheme *btheme = MEM_new_uninitialized<bTheme>(__func__);
1564 memcpy(btheme, &U_theme_default, sizeof(*btheme));
1565
1566 BLI_addtail(&userdef->themes, btheme);
1567 }
1568
1569#ifdef WITH_PYTHON_SECURITY
1570 /* use alternative setting for security nuts
1571 * otherwise we'd need to patch the binary blob - startup.blend.c */
1573#else
1575#endif
1576
1577 /* System-specific fonts directory.
1578 * NOTE: when not found, leaves as-is (`//` for the blend-file directory). */
1579 if (BKE_appdir_font_folder_default(userdef->fontdir, sizeof(userdef->fontdir))) {
1580 /* Not actually needed, just a convention that directory selection
1581 * adds a trailing slash. */
1582 BLI_path_slash_ensure(userdef->fontdir, sizeof(userdef->fontdir));
1583 }
1584
1586 userdef->memcachelimit);
1587
1588 /* Init weight paint range. */
1589 BKE_colorband_init(&userdef->coba_weight, true);
1590
1591 /* Default studio light. */
1593
1595
1597
1598 {
1600 userdef, "VIEW3D_AST_brush_sculpt", "Brushes/Mesh Sculpt/General");
1602 userdef, "VIEW3D_AST_brush_sculpt", "Brushes/Mesh Sculpt/Paint");
1604 userdef, "VIEW3D_AST_brush_sculpt", "Brushes/Mesh Sculpt/Simulation");
1605
1607 userdef, "IMAGE_AST_brush_paint", "Brushes/Mesh Texture Paint/Basic");
1609 userdef, "IMAGE_AST_brush_paint", "Brushes/Mesh Texture Paint/Erase");
1611 userdef, "IMAGE_AST_brush_paint", "Brushes/Mesh Texture Paint/Pixel Art");
1613 userdef, "IMAGE_AST_brush_paint", "Brushes/Mesh Texture Paint/Utilities");
1614
1616 userdef, "VIEW3D_AST_brush_texture_paint", "Brushes/Mesh Texture Paint/Basic");
1618 userdef, "VIEW3D_AST_brush_texture_paint", "Brushes/Mesh Texture Paint/Erase");
1620 userdef, "VIEW3D_AST_brush_texture_paint", "Brushes/Mesh Texture Paint/Pixel Art");
1622 userdef, "VIEW3D_AST_brush_texture_paint", "Brushes/Mesh Texture Paint/Utilities");
1623
1625 userdef, "VIEW3D_AST_brush_gpencil_paint", "Brushes/Grease Pencil Draw/Draw");
1627 userdef, "VIEW3D_AST_brush_gpencil_paint", "Brushes/Grease Pencil Draw/Erase");
1629 userdef, "VIEW3D_AST_brush_gpencil_paint", "Brushes/Grease Pencil Draw/Utilities");
1630
1632 userdef, "VIEW3D_AST_brush_gpencil_sculpt", "Brushes/Grease Pencil Sculpt/Contrast");
1634 userdef, "VIEW3D_AST_brush_gpencil_sculpt", "Brushes/Grease Pencil Sculpt/Transform");
1636 userdef, "VIEW3D_AST_brush_gpencil_sculpt", "Brushes/Grease Pencil Sculpt/Utilities");
1637
1639 userdef, "NODE_AST_compositor", "Camera & Lens Effects");
1641 userdef, "NODE_AST_compositor", "Creative");
1643 userdef, "NODE_AST_compositor", "Utilities");
1644
1646 userdef, "NODE_AST_compositor", "Compositing/Camera & Lens Effects");
1648 userdef, "NODE_AST_compositor", "Compositing/Creative");
1650 userdef, "NODE_AST_compositor", "Compositing/Utilities");
1651 /* Note: "Compositing/Mask" is not enabled by default because it only contains online assets,
1652 * which are not available because online access is disabled by default.*/
1653 }
1654
1655 return userdef;
1656}
1657
1658bool BKE_blendfile_userdef_write(const char *filepath, ReportList *reports)
1659{
1660 Main *mainb = MEM_new<Main>(__func__);
1661 bool ok = false;
1662
1663 BlendFileWriteParams params{};
1664 params.use_userdef = true;
1665
1666 if (BLO_write_file(mainb, filepath, 0, &params, reports)) {
1667 ok = true;
1668 }
1669
1670 MEM_delete(mainb);
1671
1672 return ok;
1673}
1674
1675bool BKE_blendfile_userdef_write_app_template(const char *filepath, ReportList *reports)
1676{
1677 /* Checking that `filepath` exists is not essential, it just avoids printing a warning that
1678 * the file can't be found. In this case it's not an error - as the file is used if it exists,
1679 * falling back to the defaults.
1680 * If the preferences exists but file reading fails - the file can be assumed corrupt
1681 * so overwriting the file is OK. */
1682 UserDef *userdef_default = BLI_exists(filepath) ? BKE_blendfile_userdef_read(filepath, nullptr) :
1683 nullptr;
1684 if (userdef_default == nullptr) {
1685 userdef_default = BKE_blendfile_userdef_from_defaults();
1686 }
1687
1689 bool ok = BKE_blendfile_userdef_write(filepath, reports);
1691 BKE_blender_userdef_data_free(userdef_default, false);
1692 MEM_delete(userdef_default);
1693 return ok;
1694}
1695
1697{
1698 char filepath[FILE_MAX];
1699 bool ok = true;
1700 const bool use_template_userpref = BKE_appdir_app_template_has_userpref(U.app_template);
1701 std::optional<std::string> cfgdir = BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, nullptr);
1702
1703 if (cfgdir) {
1704 bool ok_write;
1705 BLI_path_join(filepath, sizeof(filepath), cfgdir->c_str(), BLENDER_USERPREF_FILE);
1706 CLOG_INFO_NOCHECK(&LOG_BLEND, "Writing user preferences: \"%s\" ", filepath);
1707 if (use_template_userpref) {
1708 ok_write = BKE_blendfile_userdef_write_app_template(filepath, reports);
1709 }
1710 else {
1711 ok_write = BKE_blendfile_userdef_write(filepath, reports);
1712 }
1713
1714 if (ok_write) {
1715 BKE_report(reports, RPT_INFO, "Preferences saved");
1716 }
1717 else {
1718 CLOG_WARN(&LOG_BLEND, "Failed to write user preferences");
1719 ok = false;
1720 BKE_report(reports, RPT_ERROR, "Saving preferences failed");
1721 }
1722 }
1723 else {
1724 BKE_report(reports, RPT_ERROR, "Unable to create userpref path");
1725 }
1726
1727 if (use_template_userpref) {
1728 cfgdir = BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, U.app_template);
1729 if (cfgdir) {
1730 /* Also save app-template preferences. */
1731 BLI_path_join(filepath, sizeof(filepath), cfgdir->c_str(), BLENDER_USERPREF_FILE);
1732
1733 CLOG_INFO_NOCHECK(&LOG_BLEND, "Writing user preferences app-template: \"%s\" ", filepath);
1734 if (BKE_blendfile_userdef_write(filepath, reports) != 0) {
1735 }
1736 else {
1737 CLOG_WARN(&LOG_BLEND, "Failed to write user preferences");
1738 ok = false;
1739 }
1740 }
1741 else {
1742 BKE_report(reports, RPT_ERROR, "Unable to create app-template userpref path");
1743 ok = false;
1744 }
1745 }
1746
1747 if (ok) {
1748 U.runtime.is_dirty = false;
1749 }
1750 return ok;
1751}
1752
1754
1755/* -------------------------------------------------------------------- */
1758
1760 const void *file_buf,
1761 int file_buf_size,
1762 ReportList *reports)
1763{
1764 BlendFileData *bfd;
1765 WorkspaceConfigFileData *workspace_config = nullptr;
1766
1767 if (filepath) {
1768 BlendFileReadReport blend_file_read_reports{};
1769 blend_file_read_reports.reports = reports;
1770 bfd = BLO_read_from_file(filepath, BLO_READ_SKIP_USERDEF, &blend_file_read_reports);
1771 }
1772 else {
1773 bfd = BLO_read_from_memory(file_buf, file_buf_size, BLO_READ_SKIP_USERDEF, reports);
1774 }
1775
1776 if (bfd) {
1777 workspace_config = MEM_new_zeroed<WorkspaceConfigFileData>(__func__);
1778 workspace_config->main = bfd->main;
1779
1780 /* Only 2.80+ files have actual workspaces, don't try to use screens
1781 * from older versions. */
1782 if (bfd->main->versionfile >= 280) {
1783 workspace_config->workspaces = bfd->main->workspaces;
1784 }
1785
1786 MEM_delete(bfd);
1787 }
1788
1789 return workspace_config;
1790}
1791
1793{
1794 BKE_main_free(workspace_config->main);
1795 MEM_delete(workspace_config);
1796}
1797
1799
1800/* -------------------------------------------------------------------- */
1803
1804static CLG_LogRef LOG_PARTIALWRITE = {"blend.partial_write"};
1805
1806namespace bke::blendfile {
1807
1809 : reference_root_filepath_(BKE_main_blendfile_path(&reference_main))
1810{
1811 BKE_main_init_from_reference(this->bmain, reference_main);
1812 /* Only for IDs matching existing data in current G_MAIN. */
1813 matching_uid_map_ = BKE_main_idmap_create(&this->bmain, false, nullptr, MAIN_IDMAP_TYPE_UID);
1814 /* For all IDs existing in the context. */
1816 &this->bmain, false, nullptr, MAIN_IDMAP_TYPE_UID | MAIN_IDMAP_TYPE_NAME);
1817};
1818
1823
1824void PartialWriteContext::preempt_session_uid(ID *ctx_id, uint session_uid)
1825{
1826 /* If there is already an existing ID in the 'matching' set with that UID, it should be the same
1827 * as the given ctx_id. */
1828 ID *matching_ctx_id = BKE_main_idmap_lookup_uid(matching_uid_map_, session_uid);
1829 if (matching_ctx_id == ctx_id) {
1830 /* That ID has already been added to the context, nothing to do. */
1831 BLI_assert(matching_ctx_id->session_uid == session_uid);
1832 return;
1833 }
1834 if (matching_ctx_id != nullptr) {
1835 /* Another ID in the context, who has a matching ID in current G_MAIN, is sharing the same
1836 * session UID. This marks a critical corruption somewhere! */
1837 CLOG_FATAL(
1839 "Different matching IDs sharing the same session UID in the partial write context.");
1840 return;
1841 }
1842 /* No ID with this session UID in the context, who's matching a current ID in G_MAIN. Check if a
1843 * non-matching context ID is already using that UID, if yes, regenerate a new one for it, such
1844 * that given `ctx_id` can use the desired UID. */
1845 /* NOTE: In theory, there should never be any session uid collision currently, since these are
1846 * generated session-wide, regardless of the type/source of the IDs. */
1847 matching_ctx_id = BKE_main_idmap_lookup_uid(this->bmain.id_map, session_uid);
1848 BLI_assert(matching_ctx_id != ctx_id);
1849 if (matching_ctx_id) {
1851 "Non-matching IDs sharing the same session UID in the partial write context.");
1852 BKE_main_idmap_remove_id(this->bmain.id_map, matching_ctx_id);
1853 /* FIXME: Allow #BKE_lib_libblock_session_uid_renew to work with temp IDs? */
1854 matching_ctx_id->tag &= ~ID_TAG_TEMP_MAIN;
1855 BKE_lib_libblock_session_uid_renew(matching_ctx_id);
1856 matching_ctx_id->tag |= ID_TAG_TEMP_MAIN;
1857 BKE_main_idmap_insert_id(this->bmain.id_map, matching_ctx_id);
1858 BLI_assert(BKE_main_idmap_lookup_uid(this->bmain.id_map, session_uid) == nullptr);
1859 }
1860 ctx_id->session_uid = session_uid;
1861}
1862
1863void PartialWriteContext::process_added_id(ID *ctx_id,
1864 const PartialWriteContext::IDAddOperations operations)
1865{
1866 const bool set_fake_user = (operations & SET_FAKE_USER) != 0;
1867 const bool set_clipboard_mark = (operations & SET_CLIPBOARD_MARK) != 0;
1868
1869 if (set_fake_user) {
1870 id_fake_user_set(ctx_id);
1871 }
1872 else {
1873 /* NOTE: Using this tag will ensure that this ID is written on disk in current state (current
1874 * context session). However, reloading the blendfile will clear this tag. */
1875 id_us_ensure_real(ctx_id);
1876 }
1877
1878 if (set_clipboard_mark) {
1879 ctx_id->flag |= ID_FLAG_CLIPBOARD_MARK;
1880 }
1881}
1882
1883ID *PartialWriteContext::id_add_copy(const ID *id, const bool regenerate_session_uid)
1884{
1885 ID *ctx_root_id = nullptr;
1886 BLI_assert(BKE_main_idmap_lookup_uid(matching_uid_map_, id->session_uid) == nullptr);
1887 const int copy_flags = (LIB_ID_CREATE_LOCALIZE |
1888 /* NOTE: Could make this an option if needed in the future */
1890 ctx_root_id = BKE_id_copy_in_lib(nullptr, id->lib, id, std::nullopt, nullptr, copy_flags);
1891 if (!ctx_root_id) {
1892 return ctx_root_id;
1893 }
1894 ctx_root_id->tag |= ID_TAG_TEMP_MAIN;
1895 /* It is critical to preserve the deep hash here, as the copy put in the partial write context is
1896 * expected to be a perfect duplicate of the packed ID (including all of its dependencies). This
1897 * will also be used on paste for deduplication. */
1898 ctx_root_id->deep_hash = id->deep_hash;
1899 /* Ensure that the newly copied ID has a library in temp local bmain if it was linked.
1900 * While this could be optimized out in case the ID is made local in the context, this adds
1901 * complexity as default ID management code like 'make local' code will create invalid bmain
1902 * namemap data. */
1903 this->ensure_library(ctx_root_id);
1904 if (regenerate_session_uid) {
1905 /* Calling #BKE_lib_libblock_session_uid_renew is not needed here, copying already generated a
1906 * new one. */
1907 BLI_assert(BKE_main_idmap_lookup_uid(matching_uid_map_, id->session_uid) == nullptr);
1908 }
1909 else {
1910 this->preempt_session_uid(ctx_root_id, id->session_uid);
1911 BKE_main_idmap_insert_id(matching_uid_map_, ctx_root_id);
1912 }
1913 BKE_main_idmap_insert_id(this->bmain.id_map, ctx_root_id);
1914 BKE_libblock_management_main_add(&this->bmain, ctx_root_id);
1915 /* Note: remapping of external file relative paths is done as part of the 'write' process. */
1916 return ctx_root_id;
1917}
1918
1919void PartialWriteContext::make_local(ID *ctx_id, const int make_local_flags)
1920{
1921 /* Making an ID local typically resets its session UID, here we want to keep the same value. */
1922 const uint ctx_id_session_uid = ctx_id->session_uid;
1923 BKE_main_idmap_remove_id(this->bmain.id_map, ctx_id);
1924 BKE_main_idmap_remove_id(matching_uid_map_, ctx_id);
1925
1926 if (ID_IS_LINKED(ctx_id)) {
1927 BKE_lib_id_make_local(&this->bmain, ctx_id, make_local_flags);
1928 }
1929 /* NOTE: Cannot rely only on `ID_IS_OVERRIDE_LIBRARY` here, as the reference pointer to the
1930 * linked data may have already been cleared out by dependency management in code above that
1931 * call. */
1932 else if ((ctx_id->override_library || ID_IS_OVERRIDE_LIBRARY(ctx_id)) &&
1933 (make_local_flags & LIB_ID_MAKELOCAL_LIBOVERRIDE_CLEAR) != 0)
1934
1935 {
1937 }
1938
1939 this->preempt_session_uid(ctx_id, ctx_id_session_uid);
1940 BKE_main_idmap_insert_id(this->bmain.id_map, ctx_id);
1941 BKE_main_idmap_insert_id(matching_uid_map_, ctx_id);
1942}
1943
1944Library *PartialWriteContext::ensure_library(ID *ctx_id)
1945{
1946 if (!ID_IS_LINKED(ctx_id)) {
1947 return nullptr;
1948 }
1949
1950 Library *src_lib = ctx_id->lib;
1951 const bool is_archive_lib = (src_lib->flag & LIBRARY_FLAG_IS_ARCHIVE) != 0;
1952 Library *src_base_lib = is_archive_lib ? src_lib->archive_parent_library : src_lib;
1953 BLI_assert(src_base_lib);
1954 BLI_assert((is_archive_lib && src_lib != src_base_lib && !ctx_id->deep_hash.is_null()) ||
1955 (!is_archive_lib && src_lib == src_base_lib && ctx_id->deep_hash.is_null()));
1956
1957 StringRefNull lib_path = src_base_lib->runtime->filepath_abs;
1958 Library *ctx_base_lib = this->libraries_map_.lookup_default(lib_path, nullptr);
1959 if (!ctx_base_lib) {
1960 ctx_base_lib = reinterpret_cast<Library *>(id_add_copy(&src_base_lib->id, true));
1961 BLI_assert(ctx_base_lib);
1962 this->libraries_map_.add(lib_path, ctx_base_lib);
1963 }
1964 /* The mapping should only contain real libraries, never packed ones. */
1965 BLI_assert(!ctx_base_lib || (ctx_base_lib->flag & LIBRARY_FLAG_IS_ARCHIVE) == 0);
1966
1967 /* There is a valid context base library, now find or create a valid archived library if needed.
1968 */
1969 Library *ctx_lib = ctx_base_lib;
1970 if (is_archive_lib) {
1971 /* Leave the creation of a new archive library to the Library code, when needed, instead of
1972 * using the write context's own `id_add_copy` util. Both are doing different and complex
1973 * things, but for archive libraries the Library code should be mostly usable 'as-is'. */
1974 bool is_new = false;
1976 this->bmain, *ctx_id, *ctx_lib, ctx_id->deep_hash, is_new);
1977 if (is_new) {
1978 ctx_lib->id.tag |= ID_TAG_TEMP_MAIN;
1979 BKE_main_idmap_insert_id(this->bmain.id_map, &ctx_lib->id);
1980 }
1981 }
1982
1983 ctx_id->lib = ctx_lib;
1984 return ctx_lib;
1985}
1986Library *PartialWriteContext::ensure_library(StringRefNull library_absolute_path)
1987{
1988 Library *ctx_lib = this->libraries_map_.lookup_default(library_absolute_path, nullptr);
1989 if (!ctx_lib) {
1990 const char *library_name = BLI_path_basename(library_absolute_path.c_str());
1991 ctx_lib = BKE_id_new_in_lib<Library>(&this->bmain, nullptr, library_name);
1992 ctx_lib->id.tag |= ID_TAG_TEMP_MAIN;
1993 id_us_min(&ctx_lib->id);
1994 this->libraries_map_.add(library_absolute_path, ctx_lib);
1995 }
1996 return ctx_lib;
1997}
1998
2000 const ID *id,
2004 dependencies_filter_cb)
2005{
2006 constexpr int make_local_flags = (LIB_ID_MAKELOCAL_INDIRECT | LIB_ID_MAKELOCAL_FORCE_LOCAL |
2008
2009 const bool add_dependencies = (options.operations & ADD_DEPENDENCIES) != 0;
2010 const bool clear_dependencies = (options.operations & CLEAR_DEPENDENCIES) != 0;
2011 const bool duplicate_dependencies = (options.operations & DUPLICATE_DEPENDENCIES) != 0;
2012 BLI_assert(clear_dependencies || add_dependencies || dependencies_filter_cb);
2013 BLI_assert(!clear_dependencies || !(add_dependencies || duplicate_dependencies));
2014 UNUSED_VARS_NDEBUG(add_dependencies, clear_dependencies, duplicate_dependencies);
2015
2016 /* Do not directly add an embedded ID. Add its owner instead. */
2017 if (id->flag & ID_FLAG_EMBEDDED_DATA) {
2018 id = BKE_id_owner_get(const_cast<ID *>(id), true);
2019 }
2020
2021 /* The given ID may have already been added (either explicitly or as a dependency) before. */
2022 /* NOTE: This should not be needed currently (as this is only used as temporary partial copy of
2023 * the current main data-base, so ID's runtime `session_uid` should be enough), but in the
2024 * future it might also be good to lookup by ID deep hash for packed data? */
2025 ID *ctx_root_id = BKE_main_idmap_lookup_uid(matching_uid_map_, id->session_uid);
2026 if (ctx_root_id) {
2027 /* If the root orig ID is already in the context, assume all of its dependencies are as well.
2028 */
2029 BLI_assert(ctx_root_id->session_uid == id->session_uid);
2030 this->process_added_id(ctx_root_id, options.operations);
2031 return ctx_root_id;
2032 }
2033
2034 /* Local mapping, such that even in case dependencies are duplicated for this specific added ID,
2035 * once a dependency has been duplicated, it can be re-used for other ID usages within the
2036 * dependencies of the added ID. */
2037 Map<const ID *, ID *> local_ctx_id_map;
2038 /* A list of IDs to post-process. Only contains IDs that were actually added to the context (not
2039 * the ones that were already there and were re-used). The #IDAddOperations item of the pair
2040 * stores the returned value from the given #dependencies_filter_cb (or given global #options
2041 * parameter otherwise). */
2043
2044 ctx_root_id = id_add_copy(id, false);
2045 if (!ctx_root_id) {
2047 "Failed to copy ID '%s', could not add it to the partial write context",
2048 id->name);
2049 return ctx_root_id;
2050 }
2051
2052 BLI_assert(ctx_root_id->session_uid == id->session_uid);
2053 local_ctx_id_map.add(id, ctx_root_id);
2054 post_process_ids_todo.append({ctx_root_id, options.operations});
2055 this->process_added_id(ctx_root_id, options.operations);
2056
2057 VectorSet<ID *> ids_to_process{ctx_root_id};
2058 auto dependencies_cb = [this,
2059 options,
2060 &local_ctx_id_map,
2061 &ids_to_process,
2062 &post_process_ids_todo,
2063 dependencies_filter_cb](LibraryIDLinkCallbackData *cb_data) -> int {
2064 ID **id_ptr = cb_data->id_pointer;
2065 const ID *orig_deps_id = *id_ptr;
2066
2068 return IDWALK_RET_NOP;
2069 }
2070 if (!orig_deps_id) {
2071 return IDWALK_RET_NOP;
2072 }
2073
2074 if (cb_data->cb_flag & IDWALK_CB_INTERNAL) {
2075 /* Cleanup internal ID pointers. */
2076 *id_ptr = nullptr;
2077 return IDWALK_RET_NOP;
2078 }
2079
2080 PartialWriteContext::IDAddOperations operations_final = (options.operations & MASK_INHERITED);
2081 if (dependencies_filter_cb) {
2082 const PartialWriteContext::IDAddOperations operations_per_id = dependencies_filter_cb(
2083 cb_data, options);
2084 operations_final = ((operations_per_id & MASK_PER_ID_USAGE) |
2085 (operations_final & ~MASK_PER_ID_USAGE));
2086 if (ID_IS_PACKED(orig_deps_id) && (operations_final & MAKE_LOCAL) == 0) {
2087 /* To ensure that their deep hash still matches with their 'context' copy, packed IDs that
2088 * are not made local (i.e. 'unpacked'):
2089 * - Must also include all of their dependencies.
2090 * - Should never duplicate or clear their dependencies. */
2091 operations_final |= ADD_DEPENDENCIES;
2092 operations_final &= ~(DUPLICATE_DEPENDENCIES | CLEAR_DEPENDENCIES);
2093 }
2094 }
2095
2096 const bool add_dependencies = (operations_final & ADD_DEPENDENCIES) != 0;
2097 const bool clear_dependencies = (operations_final & CLEAR_DEPENDENCIES) != 0;
2098 const bool duplicate_dependencies = (operations_final & DUPLICATE_DEPENDENCIES) != 0;
2099 BLI_assert(clear_dependencies || add_dependencies);
2100 BLI_assert(!clear_dependencies || !(add_dependencies || duplicate_dependencies));
2101 UNUSED_VARS_NDEBUG(add_dependencies);
2102
2103 if (clear_dependencies) {
2104 if (cb_data->cb_flag & IDWALK_CB_NEVER_NULL) {
2106 "Clearing a 'never null' ID usage of '%s' by '%s', this is likely not a "
2107 "desired action",
2108 (*id_ptr)->name,
2109 cb_data->owner_id->name);
2110 }
2111 /* Owner ID should be a 'context-main' duplicate of a real Main ID, as such there should be
2112 * no need to decrease ID usages refcount here. */
2113 *id_ptr = nullptr;
2114 return IDWALK_RET_NOP;
2115 }
2116 /* else if (add_dependencies) */
2117 /* The given ID may have already been added (either explicitly or as a dependency) before. */
2118 ID *ctx_deps_id = nullptr;
2119 if (duplicate_dependencies) {
2120 ctx_deps_id = local_ctx_id_map.lookup(orig_deps_id);
2121 }
2122 else {
2123 ctx_deps_id = BKE_main_idmap_lookup_uid(matching_uid_map_, orig_deps_id->session_uid);
2124 }
2125 if (!ctx_deps_id) {
2126 if (cb_data->cb_flag & IDWALK_CB_LOOPBACK) {
2127 /* Do not follow 'loop back' pointers. */
2128 /* NOTE: Not sure whether this should be considered an error or not. Typically hitting such
2129 * a case is bad practice. On the other hand, some of these pointers are present in
2130 * 'normal' IDs, like e.g. the parent collections ones. This implies that currently, all
2131 * attempt to adding a collection to a partial write context should make usage of a custom
2132 * `dependencies_filter_cb` function to explicitly clear these pointers. */
2134 "First dependency to ID '%s' found through a 'loopback' usage from ID '%s', "
2135 "this should never happen",
2136 (*id_ptr)->name,
2137 cb_data->owner_id->name);
2138 *id_ptr = nullptr;
2139 return IDWALK_RET_NOP;
2140 }
2141 ctx_deps_id = this->id_add_copy(orig_deps_id, duplicate_dependencies);
2142 local_ctx_id_map.add(orig_deps_id, ctx_deps_id);
2143 if (!ctx_deps_id) {
2145 "Failed to copy ID '%s' (used by ID '%s'), could not add it to the partial "
2146 "write context",
2147 (*id_ptr)->name,
2148 cb_data->owner_id->name);
2149 *id_ptr = nullptr;
2150 return IDWALK_RET_NOP;
2151 }
2152 ids_to_process.add(ctx_deps_id);
2153 post_process_ids_todo.append({ctx_deps_id, operations_final});
2154 }
2155 if (duplicate_dependencies) {
2156 BLI_assert(ctx_deps_id->session_uid != orig_deps_id->session_uid);
2157 }
2158 else {
2159 BLI_assert(ctx_deps_id->session_uid == orig_deps_id->session_uid);
2160 }
2161 this->process_added_id(ctx_deps_id, operations_final);
2162 /* In-place remapping. */
2163 *id_ptr = ctx_deps_id;
2164 return IDWALK_RET_NOP;
2165 };
2166 while (!ids_to_process.is_empty()) {
2167 ID *ctx_id = ids_to_process.pop();
2169 &this->bmain, ctx_id, dependencies_cb, &options, IDWALK_DO_INTERNAL_RUNTIME_POINTERS);
2170 }
2171
2172 /* Post process all newly added IDs in the context:
2173 * - Make them local or ensure that their library reference is also in the context.
2174 */
2175 for (auto [ctx_id, options_final] : post_process_ids_todo) {
2176 const bool do_make_local = (options_final & MAKE_LOCAL) != 0;
2177 if (do_make_local) {
2178 this->make_local(ctx_id, make_local_flags);
2179 }
2180 }
2181
2182 return ctx_root_id;
2183}
2184
2186 const StringRefNull id_name,
2189{
2190 Library *ctx_library = nullptr;
2191 if (library) {
2192 ctx_library = this->ensure_library(library->runtime->filepath_abs);
2193 }
2194 ID *ctx_id = static_cast<ID *>(
2195 BKE_id_new_in_lib(&this->bmain, ctx_library, id_type, id_name.c_str()));
2196 ctx_id->tag |= ID_TAG_TEMP_MAIN;
2197 id_us_min(ctx_id);
2198 this->process_added_id(ctx_id, options.operations);
2199 /* See function doc about why handling of #matching_uid_map_ can be skipped here. */
2200 BKE_main_idmap_insert_id(this->bmain.id_map, ctx_id);
2201 return ctx_id;
2202}
2203
2205{
2206 if (ID *ctx_id = BKE_main_idmap_lookup_uid(matching_uid_map_, id->session_uid)) {
2207 BKE_main_idmap_remove_id(matching_uid_map_, ctx_id);
2208 BKE_id_delete(&this->bmain, ctx_id);
2209 }
2210}
2211
2212void PartialWriteContext::remove_unused(const bool clear_extra_user)
2213{
2214 LibQueryUnusedIDsData parameters;
2215 parameters.do_local_ids = true;
2216 parameters.do_linked_ids = true;
2217 parameters.do_recursive = true;
2218
2219 if (clear_extra_user) {
2220 ID *id_iter;
2221 FOREACH_MAIN_ID_BEGIN (&this->bmain, id_iter) {
2222 id_us_clear_real(id_iter);
2223 }
2225 }
2226 BKE_lib_query_unused_ids_tag(&this->bmain, ID_TAG_DOIT, parameters);
2227
2229 "Removing %d unused IDs from current partial write context",
2230 parameters.num_total[INDEX_ID_NULL]);
2231 ID *id_iter;
2232 FOREACH_MAIN_ID_BEGIN (&this->bmain, id_iter) {
2233 if ((id_iter->tag & ID_TAG_DOIT) != 0) {
2234 BKE_main_idmap_remove_id(matching_uid_map_, id_iter);
2235 }
2236 }
2239}
2240
2242{
2243 BKE_main_idmap_clear(*matching_uid_map_);
2244 BKE_main_clear(this->bmain);
2245}
2246
2248{
2249 Set<ID *> ids_in_context;
2250 Set<uint> session_uids_in_context;
2251 bool is_valid = true;
2252
2253 ID *id_iter;
2254
2255 /* Fill `ids_in_context`, check uniqueness of session_uid's. */
2256 FOREACH_MAIN_ID_BEGIN (&this->bmain, id_iter) {
2257 ids_in_context.add(id_iter);
2258 if (session_uids_in_context.contains(id_iter->session_uid)) {
2259 CLOG_ERROR(&LOG_PARTIALWRITE, "ID %s does not have a unique session_uid", id_iter->name);
2260 is_valid = false;
2261 }
2262 else {
2263 session_uids_in_context.add(id_iter->session_uid);
2264 }
2265 }
2267
2268 /* Check that no ID uses IDs from outside this context. */
2269 auto id_validate_dependencies_cb = [&ids_in_context,
2270 &is_valid](LibraryIDLinkCallbackData *cb_data) -> int {
2271 ID **id_p = cb_data->id_pointer;
2272 ID *owner_id = cb_data->owner_id;
2273 ID *self_id = cb_data->self_id;
2274
2275 /* By definition, embedded IDs are not in Main, so they are not listed in this context either.
2276 */
2277 if (cb_data->cb_flag & (IDWALK_CB_EMBEDDED | IDWALK_CB_EMBEDDED_NOT_OWNING)) {
2278 return IDWALK_RET_NOP;
2279 }
2280 /* 'Runtime' ID usages ignored by read/write file code can also be ignored here. Covers e.g.
2281 * the 'parent' runtime pointer of Library. */
2282 if (cb_data->cb_flag & (IDWALK_CB_READFILE_IGNORE | IDWALK_CB_WRITEFILE_IGNORE)) {
2283 return IDWALK_RET_NOP;
2284 }
2285
2286 if (*id_p && !ids_in_context.contains(*id_p)) {
2287 if (owner_id != self_id) {
2288 CLOG_ERROR(
2290 "ID %s (used by ID '%s', embedded ID '%s') is not in current partial write context",
2291 (*id_p)->name,
2292 owner_id->name,
2293 self_id->name);
2294 }
2295 else {
2297 "ID %s (used by ID '%s') is not in current partial write context",
2298 (*id_p)->name,
2299 owner_id->name);
2300 }
2301 is_valid = false;
2302 }
2303 return IDWALK_RET_NOP;
2304 };
2305 FOREACH_MAIN_ID_BEGIN (&this->bmain, id_iter) {
2307 &this->bmain, id_iter, id_validate_dependencies_cb, nullptr, IDWALK_READONLY);
2308 }
2310
2311 return is_valid;
2312}
2313
2314bool PartialWriteContext::write_impl(const char *write_filepath,
2315 const int write_flags,
2316 const BlendFileWriteParams &blend_file_write_params,
2317 ReportList &reports)
2318{
2319 BLI_assert_msg(write_filepath != reference_root_filepath_,
2320 "A library blendfile should not overwrite currently edited blendfile");
2321
2322 /* In case the write path is the same as one of the libraries used by this context, make this
2323 * library local, and delete it (and all of its potentially remaining linked data). */
2324 Vector<Library *> make_local_libs;
2325 for (Library &library : this->bmain.libraries) {
2326 if (STREQ(write_filepath, library.runtime->filepath_abs)) {
2327 make_local_libs.append(&library);
2328 }
2329 }
2330 /* Will likely change in the near future (embedded linked IDs, virtual libraries...), but
2331 * currently this should never happen. */
2332 if (make_local_libs.size() > 1) {
2334 "%d libraries found using the same filepath as destination one ('%s'), should "
2335 "never happen.",
2336 int32_t(make_local_libs.size()),
2337 write_filepath);
2338 }
2339 for (Library *lib : make_local_libs) {
2340 BKE_library_make_local(&this->bmain, lib, nullptr, false, false, false);
2341 BKE_id_delete(&this->bmain, lib);
2342 }
2343 make_local_libs.clear();
2344
2345 BLI_assert(this->is_valid());
2346
2347 return BLO_write_file(
2348 &this->bmain, write_filepath, write_flags, &blend_file_write_params, &reports);
2349}
2350
2351bool PartialWriteContext::write(const char *write_filepath,
2352 const int write_flags,
2353 const int remap_mode,
2354 ReportList &reports)
2355{
2356 BlendFileWriteParams blend_file_write_params{};
2357 blend_file_write_params.remap_mode = eBLO_WritePathRemap(remap_mode);
2358 return this->write_impl(write_filepath, write_flags, blend_file_write_params, reports);
2359}
2360
2361bool PartialWriteContext::write(const char *write_filepath, ReportList &reports)
2362{
2363 return this->write(write_filepath, 0, BLO_WRITE_PATH_REMAP_RELATIVE, reports);
2364}
2365
2367 ReportList &reports)
2368{
2369 BlendFileWriteParams blend_file_write_params{};
2370 blend_file_write_params.remap_mode = BLO_WRITE_PATH_REMAP_RELATIVE;
2371 blend_file_write_params.is_copypaste_buffer = true;
2372 return this->write_impl(write_filepath, 0, blend_file_write_params, reports);
2373}
2374
2375} // namespace bke::blendfile
2376
2378
2379} // namespace blender
#define BLENDER_USERPREF_FILE
Blender util stuff.
#define BLENDER_FILE_SUBVERSION
#define BLENDER_FILE_VERSION
#define G_FLAG_ALL_READFILE
#define G_MAIN
#define G_FILE_FLAG_ALL_RUNTIME
#define G_FLAG_ALL_RUNTIME
#define FOREACH_MAIN_ID_END
Definition BKE_main.hh:735
#define FOREACH_MAIN_LISTBASE_ID_END
Definition BKE_main.hh:703
#define FOREACH_MAIN_LISTBASE_ID_BEGIN(_lb, _id)
Definition BKE_main.hh:697
#define FOREACH_MAIN_LISTBASE_END
Definition BKE_main.hh:715
#define FOREACH_MAIN_LISTBASE_BEGIN(_bmain, _lb)
Definition BKE_main.hh:708
#define FOREACH_MAIN_ID_BEGIN(_bmain, _id)
Definition BKE_main.hh:729
File and directory operations.
#define FILE_MAX
#define BLI_path_join(...)
#define STRNCPY_UTF8(dst, src)
Platform independent time functions.
external readfile function prototypes.
#define BLO_GROUP_MAX
#define BLO_EMBEDDED_STARTUP_BLEND
#define BLO_READ_SKIP_ALL
external writefile.cc function prototypes.
#define RPT_(msgid)
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define CLOG_DEBUG(clg_ref,...)
Definition CLG_log.h:191
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
#define CLOG_INFO_NOCHECK(clg_ref, format,...)
Definition CLG_log.h:204
#define CLOG_FATAL(clg_ref,...)
Definition CLG_log.h:187
#define ID_IS_PACKED(_id)
Definition DNA_ID.h:703
#define ID_TYPE_SUPPORTS_ASSET_EDITABLE(id_type)
Definition DNA_ID.h:705
#define ID_IS_OVERRIDE_LIBRARY_REAL(_id)
Definition DNA_ID.h:729
#define ID_IS_LINKED(_id)
Definition DNA_ID.h:697
#define MAX_ID_NAME
Definition DNA_ID.h:367
#define INDEX_ID_MAX
Definition DNA_ID.h:1362
#define ID_IS_OVERRIDE_LIBRARY(_id)
Definition DNA_ID.h:736
#define FILE_MAX_LIBEXTRA
Read Blender memory allocation and freeing.
#define C
Definition RandGen.cpp:29
#define BLI_assert_unreachable()
#define UNUSED_VARS_NDEBUG(...)
#define BLI_assert(a)
#define ELEM(...)
#define BLI_assert_msg(a, msg)
#define STREQ(a, b)
bool add(const Key &key, const Value &value)
Definition BLI_map.hh:295
const Value & lookup(const Key &key) const
Definition BLI_map.hh:545
bool contains(const Key &key) const
Definition BLI_set.hh:310
bool add(const Key &key)
Definition BLI_set.hh:248
constexpr const char * c_str() const
bool add(const Key &key)
int64_t size() const
void append(const T &value)
ID * id_add(const ID *id, IDAddOptions options, FunctionRef< IDAddOperations(LibraryIDLinkCallbackData *cb_data, IDAddOptions options)> dependencies_filter_cb=nullptr)
void remove_unused(bool clear_extra_user=false)
bool write_as_copypaste_buffer(const char *write_filepath, ReportList &reports)
bool write(const char *write_filepath, int write_flags, int remap_mode, ReportList &reports)
ID * id_create(short id_type, StringRefNull id_name, Library *library, IDAddOptions options)
IDRemapperApplyResult get_mapping_result(ID *id, IDRemapperApplyOptions options, const ID *id_self) const
IDRemapperApplyResult apply(ID **r_id_ptr, IDRemapperApplyOptions options, ID *id_self=nullptr) const
void add(ID *old_id, ID *new_id)
void add_overwrite(ID *old_id, ID *new_id)
CCL_NAMESPACE_BEGIN struct Options options
static DynamicLibrary lib
#define str(s)
#define main()
Library * ensure_archive_library(Main &bmain, ID &id, Library &reference_library, const IDHash &id_deep_hash, bool &is_new)
Definition library.cc:542
BMesh Iterators.
static bool reuse_editable_asset_needed(ReuseOldBMainData *reuse_data)
Definition blendfile.cc:489
const char * BKE_idtype_idcode_to_name(short idcode)
Definition idtype.cc:261
void * MEM_new_uninitialized(size_t len, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2)
@ ID_REMAP_RESULT_SOURCE_UNASSIGNED
@ ID_REMAP_RESULT_SOURCE_UNAVAILABLE
@ ID_REMAP_RESULT_SOURCE_REMAPPED
@ ID_REMAP_RESULT_SOURCE_NOT_MAPPABLE
static void reuse_bmain_data_invalid_local_usages_fix(ReuseOldBMainData *reuse_data)
Definition blendfile.cc:808
UserDef U
Definition blender.cc:58
static void view3d_data_consistency_ensure(wmWindow *win, Scene *scene, ViewLayer *view_layer)
Definition blendfile.cc:837
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
BlendHandle * BLO_blendhandle_from_file(const char *filepath, BlendFileReadReport *reports)
void BKE_blender_userdef_data_set_and_free(UserDef *userdef)
Definition blender.cc:286
char * STRNCPY(char(&dst)[N], const char *src)
void BKE_preferences_asset_library_default_add(struct UserDef *userdef) ATTR_NONNULL()
void BKE_colorband_init(ColorBand *coba, bool rangetype)
Definition colorband.cc:25
@ LIBRARY_ASSET_EDITABLE
@ LIBRARY_ASSET_FILE_WRITABLE
@ RPT_WARNING
Definition BKE_report.hh:40
void BKE_id_delete(Main *bmain, void *idv, const BKEIDDeleteOptions &options={}) ATTR_NONNULL()
bool CTX_py_init_get(const bContext *C)
void BKE_lib_query_unused_ids_tag(Main *bmain, int tag, LibQueryUnusedIDsData &parameters)
void BKE_blendfile_workspace_config_data_free(WorkspaceConfigFileData *workspace_config)
bool BKE_blendfile_userdef_write_app_template(const char *filepath, ReportList *reports)
unsigned int uint
Definition BKE_text.h:55
void BLI_addhead(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:98
void BKE_libblock_remap_multiple_raw(Main *bmain, bke::id::IDRemapper &mappings, const int remap_flags)
Definition lib_remap.cc:678
bool BLO_write_file(Main *mainvar, const char *filepath, int write_flags, const BlendFileWriteParams *params, ReportList *reports)
std::optional< std::string > BKE_appdir_folder_id_create(int folder_id, const char *subfolder) ATTR_WARN_UNUSED_RESULT
Definition appdir.cc:822
void void BKE_reports_prepend(ReportList *reports, const char *prepend)
Definition report.cc:244
void BKE_blendfile_read_make_empty(bContext *C)
bool BKE_blendfile_library_path_explode(const char *path, char *r_dir, char **r_group, char **r_name)
Definition blendfile.cc:94
void BLO_blendhandle_close(BlendHandle *bh) ATTR_NONNULL(1)
UserDef * BKE_blendfile_userdef_read(const char *filepath, ReportList *reports)
void BKE_blender_userdef_data_free(UserDef *userdef, bool clear_fonts)
Definition blender.cc:349
void BLO_blendfiledata_free(BlendFileData *bfd)
@ IDWALK_DO_INTERNAL_RUNTIME_POINTERS
@ IDWALK_DO_LIBRARY_POINTER
bool BLI_exists(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:404
void BKE_bpath_foreach_path_main(BPathForeachPathData *bpath_data)
Definition bpath.cc:121
void BKE_main_init_from_reference(Main &bmain, const Main &reference)
Definition main.cc:100
void BKE_main_namemap_destroy(UniqueName_Map **r_name_map) ATTR_NONNULL()
static void swap_old_bmain_data_dependencies_process(ReuseOldBMainData *reuse_data, const short id_code)
Definition blendfile.cc:742
ID ID * BKE_main_idmap_lookup_id(IDNameLib_Map *id_map, const ID *id) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1
wmWindow * CTX_wm_window(const bContext *C)
@ ID_REMAP_SKIP_NEVER_NULL_USAGE
@ ID_REMAP_SKIP_USER_REFCOUNT
@ ID_REMAP_SKIP_USER_CLEAR
@ ID_REMAP_SKIP_UPDATE_TAGGING
@ ID_REMAP_FORCE_UI_POINTERS
WorkspaceConfigFileData * BKE_blendfile_workspace_config_read(const char *filepath, const void *file_buf, int file_buf_size, ReportList *reports)
static void wm_data_consistency_ensure(wmWindowManager *curwm, Scene *cur_scene, ViewLayer *cur_view_layer)
Definition blendfile.cc:891
bScreen * BKE_workspace_active_screen_get(const WorkSpaceInstanceHook *hook) GETTER_ATTRS
Definition workspace.cc:684
bool BKE_preferences_asset_shelf_settings_ensure_catalog_path_enabled(UserDef *userdef, const char *shelf_idname, const char *catalog_path)
void BLO_read_do_version_after_setup(Main *new_bmain, BlendfileLinkAppendContext *lapp_context, BlendFileReadReport *reports)
static bool reuse_bmain_data_remapper_is_id_remapped(id::IDRemapper &remapper, ID *id)
Definition blendfile.cc:312
bool BKE_blendfile_userdef_write(const char *filepath, ReportList *reports)
void id_fake_user_set(ID *id)
Definition lib_id.cc:471
static CLG_LogRef LOG_PARTIALWRITE
void BLI_path_slash_native(char *path) ATTR_NONNULL(1)
void id_us_clear_real(ID *id)
Definition lib_id.cc:406
void BKE_studiolight_default(SolidLight lights[4], float light_ambient[3])
@ LIB_ID_CREATE_LOCALIZE
@ LIB_ID_COPY_ASSET_METADATA
ViewLayer * BKE_view_layer_default_view(const Scene *scene)
@ ONLY_PROCESS_NULL_ROOT_POINTERS
@ REPORT_NULL_ROOT_POINTERS
void BKE_main_namemap_remove_id(Main &bmain, ID &id)
void BKE_main_id_refcount_recompute(Main *bmain, bool do_linked_only)
Definition lib_id.cc:2131
Global G
Definition blender.cc:57
const char * BKE_main_blendfile_path(const Main *bmain) ATTR_NONNULL()
Definition main.cc:1058
void id_sort_by_name(ListBaseT< ID > *lb, ID *id, ID *id_sorting_hint)
Definition lib_id.cc:1888
BlendFileData * BLO_read_from_file(const char *filepath, eBLOReadSkip skip_flags, BlendFileReadReport *reports)
void void void const char * BLI_path_basename(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
void BKE_blendfile_read_setup_readfile(bContext *C, BlendFileData *bfd, const BlendFileReadParams *params, BlendFileReadWMSetupData *wm_setup_data, BlendFileReadReport *reports, bool startup_update_defaults, const char *startup_app_template)
int BLI_findindex(const ListBase *listbase, const void *vlink) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:593
@ G_FILE_RECOVER_READ
@ G_FILE_ASSET_EDIT_FILE
char * BLI_strncpy(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
bool BKE_blendfile_is_readable(const char *path, ReportList *reports)
Definition blendfile.cc:157
UserDef * BKE_blendfile_userdef_read_from_memory(const void *file_buf, int file_buf_size, ReportList *reports)
void * MEM_new_zeroed(size_t len, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2)
void CTX_wm_screen_set(bContext *C, bScreen *screen)
@ BLO_WRITE_PATH_REMAP_RELATIVE
static int reuse_editable_asset_bmain_data_dependencies_process_cb(LibraryIDLinkCallbackData *cb_data)
Definition blendfile.cc:438
void BLI_remlink(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:138
void BKE_lib_override_library_main_hierarchy_root_ensure(Main *bmain, LibOverride_HierarchyRoot_ValidateOptions options={}, ReportList *reports=nullptr)
void BKE_report(ReportList *reports, eReportType type, const char *message)
Definition report.cc:162
wmWindowManager * CTX_wm_manager(const bContext *C)
static void setup_app_blend_file_data(bContext *C, BlendFileData *bfd, const BlendFileReadParams *params, BlendFileReadWMSetupData *wm_setup_data, BlendFileReadReport *reports)
BlendFileData * BKE_blendfile_read_from_memfile(Main *bmain, MemFile *memfile, const BlendFileReadParams *params, ReportList *reports)
void BKE_screen_runtime_refresh_for_blendfile(bScreen *screen)
Definition screen.cc:638
const IDTypeInfo * BKE_idtype_get_info_from_idtype_index(const int idtype_index)
Definition idtype.cc:213
static int swap_old_bmain_data_for_blendfile_dependencies_process_cb(LibraryIDLinkCallbackData *cb_data)
Definition blendfile.cc:716
struct bAddon * BKE_addon_new()
Definition addon.cc:36
bool BKE_appdir_app_template_has_userpref(const char *app_template) ATTR_NONNULL(1)
Definition appdir.cc:1141
void BKE_lib_override_library_make_local(Main *bmain, ID *id)
size_t BKE_id_multi_tagged_delete(Main *bmain, const BKEIDDeleteOptions &options={}) ATTR_NONNULL()
Scene * BKE_scene_add(Main *bmain, const char *name)
Definition scene.cc:2200
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
void BKE_blender_userdef_app_template_data_swap(UserDef *userdef_a, UserDef *userdef_b)
Definition blender.cc:400
BlendFileData * BKE_blendfile_read_from_memory(const void *file_buf, int file_buf_size, const BlendFileReadParams *params, ReportList *reports)
static void setup_app_data(bContext *C, BlendFileData *bfd, const BlendFileReadParams *params, BlendFileReadWMSetupData *wm_setup_data, BlendFileReadReport *reports)
Definition blendfile.cc:924
void BKE_main_namemap_clear(Main &bmain)
@ LIBRARY_FLAG_IS_ARCHIVE
void BLO_reportf_wrap(BlendFileReadReport *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
Definition readfile.cc:237
static void swap_wm_data_for_blendfile(ReuseOldBMainData *reuse_data, const bool load_ui)
Definition blendfile.cc:660
static void clean_paths(Main *bmain)
Definition blendfile.cc:186
void CTX_wm_region_popup_set(bContext *C, ARegion *region_popup)
static Library * reuse_bmain_data_dependencies_new_library_get(ReuseOldBMainData *reuse_data, Library *old_lib)
Definition blendfile.cc:398
int BLI_path_slash_ensure(char *path, size_t path_maxncpy) ATTR_NONNULL(1)
bool BKE_main_namemap_validate(Main &bmain)
ScrArea ScrArea void BKE_screen_gizmo_tag_refresh(bScreen *screen)
Definition screen.cc:623
int BLI_listbase_count_at_most(const ListBase *listbase, int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:518
void BKE_blendfile_read_setup_undo(bContext *C, BlendFileData *bfd, const BlendFileReadParams *params, BlendFileReadReport *reports)
void BKE_lib_override_library_main_operations_create(Main *bmain, bool force_auto, int *r_report_flags)
void BKE_lib_override_library_main_resync(Main *bmain, const Map< Library *, Library * > *new_to_old_libraries_map, Scene *scene, ViewLayer *view_layer, BlendFileReadReport *reports)
@ BLO_READ_SKIP_USERDEF
@ BLO_READ_SKIP_DATA
int BLI_system_memory_max_in_megabytes_int()
Definition system.cc:218
bool BLI_is_dir(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:457
void BKE_main_free(Main *bmain)
Definition main.cc:202
void BKE_preferences_extension_repo_add_defaults_all(UserDef *userdef)
ViewLayer * BKE_view_layer_find(const Scene *scene, const char *layer_name)
void id_us_ensure_real(ID *id)
Definition lib_id.cc:388
@ BKE_BPATH_FOREACH_PATH_SKIP_MULTIFILE
Definition BKE_bpath.hh:76
void BKE_scene_set_background(Main *bmain, Scene *sce)
Definition scene.cc:2233
static bool reuse_bmain_move_id(ReuseOldBMainData *reuse_data, ID *id, Library *lib, const bool reuse_existing)
Definition blendfile.cc:326
void BKE_main_idmap_clear(IDNameLib_Map &id_map)
void IMB_colormanagement_undo_read_post(Main *bmain, const MainColorspace &old_colorspace)
static void unpin_file_local_grease_pencil_brush_materials(const ReuseOldBMainData *reuse_data)
Definition blendfile.cc:559
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
Definition report.cc:191
void BKE_screen_view3d_scene_sync(bScreen *screen, Scene *scene)
Definition screen.cc:1249
void BLI_addtail(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:118
Main * CTX_data_main(const bContext *C)
void BKE_lib_override_library_free(IDOverrideLibrary **liboverride, bool do_id_user)
@ IDWALK_RET_STOP_RECURSION
void IMB_colormanagement_file_read_post(Main *bmain, Main *old_bmain, bool is_startup, bool have_editable_assets)
@ INDEX_ID_NULL
Definition DNA_ID.h:1359
void BKE_lib_id_swap_full(Main *bmain, ID *id_a, ID *id_b, const bool do_self_remap, const int self_remap_flags)
Definition lib_id.cc:1136
bool BLI_path_extension_check_array(const char *path, const char **ext_array) ATTR_NONNULL(1
BlendFileData * BKE_blendfile_read(const char *filepath, const BlendFileReadParams *params, BlendFileReadReport *reports)
@ USER_SCRIPT_AUTOEXEC_DISABLE
bool BKE_blendfile_userdef_write_all(ReportList *reports)
void BKE_lib_libblock_session_uid_renew(ID *id)
Definition lib_id.cc:1588
void BKE_main_idmap_insert_id(IDNameLib_Map *id_map, ID *id) ATTR_NONNULL()
IDNameLib_Map * BKE_main_idmap_create(Main *bmain, bool create_valid_ids_set, Main *old_bmain, int idmap_types) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition main_idmap.cc:80
@ ID_TAG_MISSING
Definition DNA_ID.h:870
@ ID_TAG_TEMP_MAIN
Definition DNA_ID.h:974
@ ID_TAG_DOIT
Definition DNA_ID.h:1029
bool BKE_appdir_font_folder_default(char *dir, size_t dir_maxncpy)
Definition appdir.cc:234
signed int int32_t
Definition BKE_text.h:78
void CTX_wm_manager_set(bContext *C, wmWindowManager *wm)
bool BKE_blendfile_extension_check(const char *str)
Definition blendfile.cc:88
void BKE_libblock_management_main_add(Main *bmain, void *idv)
Definition lib_id.cc:1201
double BLI_time_now_seconds()
Definition time.cc:30
@ MAIN_IDMAP_TYPE_UID
@ MAIN_IDMAP_TYPE_NAME
ID * BKE_id_owner_get(ID *id, const bool debug_relationship_assert=true)
Definition lib_id.cc:2770
void * BKE_id_new_in_lib(Main *bmain, std::optional< Library * > owner_library, short type, const char *name)
Definition lib_id.cc:1594
bool BLI_remlink_safe(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:161
BlendFileData * BLO_read_from_memory(const void *mem, int memsize, eBLOReadSkip skip_flags, ReportList *reports)
void BKE_reports_prependf(ReportList *reports, const char *prepend_format,...) ATTR_PRINTF_FORMAT(2
Definition report.cc:252
static void setup_app_userdef(BlendFileData *bfd)
Definition blendfile.cc:211
@ ID_FLAG_EMBEDDED_DATA
Definition DNA_ID.h:775
@ ID_FLAG_CLIPBOARD_MARK
Definition DNA_ID.h:801
bScreen * CTX_wm_screen(const bContext *C)
void CTX_wm_region_set(bContext *C, ARegion *region)
void CTX_data_main_set(bContext *C, Main *bmain)
@ LIB_ID_MAKELOCAL_LIBOVERRIDE_CLEAR
@ LIB_ID_MAKELOCAL_FORCE_LOCAL
@ LIB_ID_MAKELOCAL_INDIRECT
static void handle_subversion_warning(Main *main, BlendFileReadReport *reports)
void BKE_main_clear(Main &bmain)
Definition main.cc:106
@ ID_REMAP_APPLY_DEFAULT
@ IDWALK_CB_LOOPBACK
@ IDWALK_CB_WRITEFILE_IGNORE
@ IDWALK_CB_EMBEDDED_NOT_OWNING
@ IDWALK_CB_NEVER_NULL
@ IDWALK_CB_INTERNAL
@ IDWALK_CB_READFILE_IGNORE
@ IDWALK_CB_EMBEDDED
void BPY_context_update(bContext *C)
BlendFileData * BLO_read_from_memfile(Main *oldmain, const char *filepath, MemFile *memfile, const BlendFileReadParams *params, ReportList *reports)
bool BKE_lib_id_make_local(Main *bmain, ID *id, int flags)
Definition lib_id.cc:672
@ BLENDER_USER_CONFIG
void BKE_main_idmap_remove_id(IDNameLib_Map *id_map, const ID *id) ATTR_NONNULL()
static CLG_LogRef LOG_BLEND
@ GP_BRUSH_MATERIAL_PINNED
void BLO_update_defaults_startup_blend(Main *bmain, const char *app_template)
void BLO_readfile_id_runtime_data_free_all(Main &bmain)
Definition readfile.cc:2318
ID ID ID * BKE_main_idmap_lookup_uid(IDNameLib_Map *id_map, uint session_uid) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
static void reuse_editable_asset_bmain_data_for_blendfile(ReuseOldBMainData *reuse_data, const short idcode)
Definition blendfile.cc:513
MINLINE int min_ii(int a, int b)
bool BLI_is_file(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:469
const bTheme U_theme_default
void id_us_min(ID *id)
Definition lib_id.cc:441
static bool wm_scene_is_visible(wmWindowManager *wm, Scene *scene)
Definition blendfile.cc:201
void BKE_library_foreach_ID_link(Main *bmain, ID *id, FunctionRef< LibraryIDLinkCallback > callback, void *user_data, LibraryForeachIDFlag flag)
Definition lib_query.cc:449
void IMB_colormanagement_check_file_config(Main *bmain)
struct ID * BKE_id_copy_in_lib(Main *bmain, std::optional< Library * > owner_library, const ID *id, std::optional< const ID * > new_owner_id, ID **new_id_p, int flag)
Definition lib_id.cc:749
const char * BLI_path_slash_rfind(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
void CTX_data_scene_set(bContext *C, Scene *scene)
void BKE_library_make_local(Main *bmain, const Library *lib, GHash *old_to_new_ids, bool untagged_only, bool set_fake, bool clear_asset_data)
Definition lib_id.cc:2395
void BKE_blender_globals_main_replace(Main *bmain)
Definition blender.cc:226
IDNewNameResult BKE_id_new_name_validate(Main &bmain, ListBaseT< ID > &lb, ID &id, const char *newname, IDNewNameMode mode, bool do_linked_data)
Definition lib_id.cc:1999
static bool foreach_path_clean_cb(BPathForeachPathData *, char *path_dst, size_t path_dst_maxncpy, const char *path_src)
Definition blendfile.cc:175
static void swap_old_bmain_data_for_blendfile(ReuseOldBMainData *reuse_data, const short id_code)
Definition blendfile.cc:587
static id::IDRemapper & reuse_bmain_data_remapper_ensure(ReuseOldBMainData *reuse_data)
Definition blendfile.cc:272
ListBaseT< ID > * which_libbase(Main *bmain, short type)
Definition main.cc:1073
static int reuse_bmain_data_invalid_local_usages_fix_cb(LibraryIDLinkCallbackData *cb_data)
Definition blendfile.cc:766
void CTX_wm_area_set(bContext *C, ScrArea *area)
void BKE_main_idmap_destroy(IDNameLib_Map *id_map) ATTR_NONNULL()
UserDef * BKE_blendfile_userdef_from_defaults()
BPathForeachPathFunctionCallback callback_function
Definition BKE_bpath.hh:124
struct Base * next
unsigned short local_view_bits
struct blender::BlendFileReadReport::@140003175311343306107257242277261221002217304000 count
struct blender::BlendFileReadReport::@070156237370130334241363347365056360307125257043 duration
eBLO_WritePathRemap remap_mode
char name[258]
Definition DNA_ID.h:433
unsigned int session_uid
Definition DNA_ID.h:463
struct Library * lib
Definition DNA_ID.h:421
void * next
Definition DNA_ID.h:418
IDOverrideLibrary * override_library
Definition DNA_ID.h:495
std::array< int, INDEX_ID_MAX > num_total
LibraryForeachIDCallbackFlag cb_flag
bke::library::LibraryRuntime * runtime
Definition DNA_ID.h:591
ListBaseT< wmWindowManager > wm
Definition BKE_main.hh:415
char filepath[1024]
Definition BKE_main.hh:267
IDNameLib_Map * id_map
Definition BKE_main.hh:440
MainColorspace colorspace
Definition BKE_main.hh:371
ListBaseT< Library > libraries
Definition BKE_main.hh:387
short versionfile
Definition BKE_main.hh:269
ListBaseT< Brush > brushes
Definition BKE_main.hh:410
bool is_read_invalid
Definition BKE_main.hh:320
bool is_asset_edit_file
Definition BKE_main.hh:288
ListBaseT< WorkSpace > workspaces
Definition BKE_main.hh:423
ListBaseT< Scene > scenes
Definition BKE_main.hh:386
ListBaseT< bScreen > screens
Definition BKE_main.hh:400
struct RegionView3D * localvd
id::IDRemapper * remapper
Definition blendfile.cc:252
BlendFileReadWMSetupData * wm_setup_data
Definition blendfile.cc:246
struct Object * camera
struct RenderData r
ListBaseT< ARegion > regionbase
ListBaseT< SpaceLink > spacedata
ListBaseT< bTheme > themes
eUserpref_Translation_Flags transopts
struct ColorBand coba_weight
ListBaseT< bAddon > addons
eUserPref_Flag flag
eUserpref_Language language
struct SolidLight light_param[4]
struct Object * camera
struct View3D * localvd
unsigned short local_view_uid
ListBaseT< Base > object_bases
ListBaseT< WorkSpace > workspaces
ListBaseT< struct ScrArea > areabase
struct WorkSpaceInstanceHook * workspace_hook