Blender V5.3
bpy_library_write.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 <Python.h>
13#include <cstddef>
14
15#include "BLI_path_utils.hh"
16#include "BLI_string.hh"
17
18#include "BKE_blendfile.hh"
19#include "BKE_global.hh"
20#include "BKE_layer.hh"
21#include "BKE_lib_id.hh"
22#include "BKE_main.hh"
24#include "BKE_report.hh"
25
26#include "BLO_writefile.hh"
27
28#include "RNA_types.hh"
29
30#include "bpy_capi_utils.hh"
31#include "bpy_library.hh" /* Declaration for #BPY_library_load_method_def */
32#include "bpy_rna.hh"
33
35#include "../generic/python_compat.hh" /* IWYU pragma: keep. */
36
37namespace blender {
38
39using namespace blender::bke::blendfile;
40
42 /* Wrap. */
43 bpy_lib_write_doc,
44 ".. method:: write(filepath, datablocks, *, "
45 "path_remap='NONE', fake_user=False, compress=False)\n"
46 "\n"
47 " Write data-blocks into a blend file.\n"
48 "\n"
49 " .. note::\n"
50 "\n"
51 " Indirectly referenced data-blocks will be expanded and written too.\n"
52 "\n"
53 " :param filepath: The path to write the blend-file.\n"
54 " :type filepath: str | bytes\n"
55 " :param datablocks: set of data-blocks.\n"
56 " :type datablocks: set[:class:`bpy.types.ID`]\n"
57 " :param path_remap: Optionally remap paths when writing the file:\n"
58 "\n"
59 " - ``NONE`` No path manipulation (default).\n"
60 " - ``RELATIVE`` Remap paths that are already relative to the new location.\n"
61 " - ``RELATIVE_ALL`` Remap all paths to be relative to the new location.\n"
62 " - ``ABSOLUTE`` Make all paths absolute on writing.\n"
63 "\n"
64 " :type path_remap: str\n"
65 " :param fake_user: When True, data-blocks will be written with fake-user flag enabled.\n"
66 " :type fake_user: bool\n"
67 " :param compress: When True, write a compressed blend file.\n"
68 " :type compress: bool\n");
69static PyObject *bpy_lib_write(BPy_PropertyRNA *self, PyObject *args, PyObject *kw)
70{
71 /* args */
72 PyC_UnicodeAsBytesAndSize_Data filepath_data = {nullptr};
73 char filepath_abs[FILE_MAX];
74 PyObject *datablocks = nullptr;
75
76 const PyC_StringEnumItems path_remap_items[] = {
79 {BLO_WRITE_PATH_REMAP_RELATIVE_ALL, "RELATIVE_ALL"},
81 {0, nullptr},
82 };
83 PyC_StringEnum path_remap = {path_remap_items, BLO_WRITE_PATH_REMAP_NONE};
84
85 bool use_fake_user = false, use_compress = false;
86
87 static const char *_keywords[] = {
88 "filepath",
89 "datablocks",
90 "path_remap",
91 "fake_user",
92 "compress",
93 nullptr,
94 };
95 static _PyArg_Parser _parser = {
96 "O&" /* `filepath` */
97 "O!" /* `datablocks` */
98 "|$" /* Optional, keyword only arguments. */
99 "O&" /* `path_remap` */
100 "O&" /* `fake_user` */
101 "O&" /* `compress` */
102 ":write",
103 _keywords,
104 nullptr,
105 };
106 if (!_PyArg_ParseTupleAndKeywordsFast(args,
107 kw,
108 &_parser,
110 &filepath_data,
111 &PySet_Type,
112 &datablocks,
114 &path_remap,
116 &use_fake_user,
118 &use_compress))
119 {
120 return nullptr;
121 }
122
123 Main *bmain_src = static_cast<Main *>(self->ptr->data); /* Typically #G_MAIN */
124
125 /* Ensure invariants before writing, or writing process may fail. See e.g. #165588. */
127 BKE_main_ensure_invariants(*bmain_src);
128
129 int write_flags = 0;
130
131 if (use_compress) {
132 write_flags |= G_FILE_COMPRESS;
133 }
134
135 STRNCPY(filepath_abs, filepath_data.value);
136 Py_XDECREF(filepath_data.value_coerce);
137
138 const bool was_relative = BLI_path_abs(filepath_abs, BKE_main_blendfile_path_from_global());
139 if (!was_relative) {
140 /* If this was a blendfile-relative path, it's been made absolute now. However, BLI_path_abs()
141 * doesn't turn normal relative paths into absolute ones, so that still has to happen. */
142 BLI_path_abs_from_cwd(filepath_abs, sizeof(filepath_abs));
143 }
144
145 PartialWriteContext partial_write_ctx{*bmain_src};
146 const PartialWriteContext::IDAddOptions add_options{
150
151 if (PySet_GET_SIZE(datablocks) > 0) {
152 PyObject *it = PyObject_GetIter(datablocks);
153 PyObject *key;
154 while ((key = PyIter_Next(it))) {
155 /* Borrow from the set. */
156 Py_DECREF(key);
157 ID *id;
158 if (!pyrna_id_FromPyObject(key, &id)) {
159 PyErr_Format(PyExc_TypeError, "Expected an ID type, not %.200s", Py_TYPE(key)->tp_name);
160 break;
161 }
162 partial_write_ctx.id_add(id, add_options, nullptr);
163 }
164 Py_DECREF(it);
165 if (key) {
166 return nullptr;
167 }
168 }
169
170 BLI_assert(partial_write_ctx.is_valid());
171
172 /* write blend */
173 ReportList reports;
174
176 bool success = partial_write_ctx.write(
177 filepath_abs, write_flags, path_remap.value_found, reports);
178
179 PyObject *py_return_value;
180 if (success) {
182 py_return_value = Py_None;
183 Py_INCREF(py_return_value);
184 }
185 else {
186 if (BPy_reports_to_error(&reports, PyExc_IOError, false) == 0) {
187 PyErr_SetString(PyExc_IOError, "Unknown error writing library data");
188 }
189 py_return_value = nullptr;
190 }
191
192 BKE_reports_free(&reports);
193
194 return py_return_value;
195}
196
197#ifdef __GNUC__
198# ifdef __clang__
199# pragma clang diagnostic push
200# pragma clang diagnostic ignored "-Wcast-function-type"
201# else
202# pragma GCC diagnostic push
203# pragma GCC diagnostic ignored "-Wcast-function-type"
204# endif
205#endif
206
208 "write",
209 reinterpret_cast<PyCFunction>(bpy_lib_write),
210 METH_VARARGS | METH_KEYWORDS,
211 bpy_lib_write_doc,
212};
213
214#ifdef __GNUC__
215# ifdef __clang__
216# pragma clang diagnostic pop
217# else
218# pragma GCC diagnostic pop
219# endif
220#endif
221
222} // namespace blender
#define RPT_ERROR_ALL
Definition BKE_report.hh:53
#define FILE_MAX
external writefile.cc function prototypes.
ID * id_add(const ID *id, IDAddOptions options, FunctionRef< IDAddOperations(LibraryIDLinkCallbackData *cb_data, IDAddOptions options)> dependencies_filter_cb=nullptr)
bool write(const char *write_filepath, int write_flags, int remap_mode, ReportList &reports)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
char * STRNCPY(char(&dst)[N], const char *src)
int PyC_ParseBool(PyObject *o, void *p)
bool BLI_path_abs(char path[FILE_MAX], const char *basepath) ATTR_NONNULL(1
void BKE_reports_free(ReportList *reports)
Definition report.cc:106
PyMethodDef BPY_library_write_method_def
void BKE_reports_init(ReportList *reports, int flag)
Definition report.cc:91
PyDoc_STRVAR(bpy_bm_new_doc, ".. function:: new(*, use_operators=True)\n" "\n" " :param use_operators: Support calling operators in :mod:`bmesh.ops` (uses some " "extra memory per vert/edge/face).\n" " :type use_operators: bool\n" " :return: Return a new, empty BMesh.\n" " :rtype: :class:`bmesh.types.BMesh`\n")
const char * BKE_main_blendfile_path_from_global()
Definition main.cc:1063
@ G_FILE_COMPRESS
@ BLO_WRITE_PATH_REMAP_RELATIVE_ALL
@ BLO_WRITE_PATH_REMAP_RELATIVE
@ BLO_WRITE_PATH_REMAP_NONE
@ BLO_WRITE_PATH_REMAP_ABSOLUTE
void BKE_main_ensure_invariants(Main &bmain, std::optional< Span< ID * > > modified_ids=std::nullopt)
bool BKE_main_view_layers_synced_ensure(const Main *bmain)
bool pyrna_id_FromPyObject(PyObject *obj, ID **id)
Definition bpy_rna.cc:8988
bool BLI_path_abs_from_cwd(char *path, size_t path_maxncpy) ATTR_NONNULL(1)
int PyC_ParseUnicodeAsBytesAndSize(PyObject *o, void *p)
void BKE_reports_print(ReportList *reports, eReportType level)
Definition report.cc:367
static PyObject * bpy_lib_write(BPy_PropertyRNA *self, PyObject *args, PyObject *kw)
short BPy_reports_to_error(ReportList *reports, PyObject *exception, const bool clear)
int PyC_ParseStringEnum(PyObject *o, void *p)
@ RPT_PRINT_HANDLED_BY_OWNER
Definition BKE_report.hh:62
header-only compatibility defines.
PyObject_HEAD std::optional< PointerRNA > ptr
Definition bpy_rna.hh:153