Blender V5.3
clipboard.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
8
9#include "DNA_space_types.h"
10
11#include "BLI_listbase.hh"
12#include "BLI_string_utf8.hh"
13
14#include "BKE_appdir.hh"
16#include "BKE_blendfile.hh"
17#include "BKE_context.hh"
18#include "BKE_global.hh"
19#include "BKE_lib_id.hh"
20#include "BKE_lib_query.hh"
21#include "BKE_library.hh"
22#include "BKE_main.hh"
23#include "BKE_main_idmap.hh"
25#include "BKE_node.hh"
26#include "BKE_node_runtime.hh"
27#include "BKE_report.hh"
28
29#include "BLO_readfile.hh"
30
31#include "BLI_path_utils.hh"
32
33#include "ED_node.hh"
34#include "ED_render.hh"
35#include "ED_screen.hh"
36
37#include "RNA_access.hh"
38#include "RNA_define.hh"
39
41
42#include "node_intern.hh"
43
45
46/* -------------------------------------------------------------------- */
49
50static void node_copybuffer_filepath_get(char filepath[FILE_MAX], size_t filepath_maxncpy)
51{
52 BLI_path_join(filepath, filepath_maxncpy, BKE_tempdir_base(), "copybuffer_nodes.blend");
53}
54
56static int node_copy_local(bNodeTree &from_tree,
57 bNodeTree &to_tree,
58 const bool allow_duplicate_names,
59 const bool do_user_count,
60 const float2 offset,
61 const bool snap_to_grid,
62 ReportList *reports)
63{
64 node_select_paired(from_tree);
65
68 const char *disabled_hint = nullptr;
69
70 for (bNode *node : get_selected_nodes(from_tree)) {
71 if (!node->typeinfo->poll_instance ||
72 node->typeinfo->poll_instance(node, &to_tree, &disabled_hint))
73 {
74 int flags = LIB_ID_COPY_DEFAULT;
75 if (!do_user_count) {
77 }
78
80 &to_tree, *node, flags, std::nullopt, std::nullopt, socket_map, allow_duplicate_names);
81 node_map.add_new(node, new_node);
82 new_node->location[0] += offset.x;
83 new_node->location[1] += offset.y;
84 if (snap_to_grid) {
85 new_node->location[0] = nearest_node_grid_coord(new_node->location[0]);
86 new_node->location[1] = nearest_node_grid_coord(new_node->location[1]);
87 }
88 }
89 else {
90 if (disabled_hint) {
91 BKE_reportf(reports,
93 "Cannot add node %s into node tree %s: %s",
94 node->name,
95 to_tree.id.name + 2,
96 disabled_hint);
97 }
98 else {
99 BKE_reportf(reports,
100 RPT_ERROR,
101 "Cannot add node %s into node tree %s",
102 node->name,
103 to_tree.id.name + 2);
104 }
105 }
106 }
107
108 if (node_map.is_empty()) {
109 return 0;
110 }
111
112 for (bNode *new_node : node_map.values()) {
113 /* Parent pointer must be redirected to new node or detached if parent is not copied. */
114 if (new_node->parent) {
115 if (node_map.contains(new_node->parent)) {
116 new_node->parent = node_map.lookup(new_node->parent);
117 }
118 else {
119 bke::node_detach_node(to_tree, *new_node);
120 }
121 }
122 }
123
124 remap_node_pairing(to_tree, node_map);
125
126 /* Copy links between selected nodes. */
127 for (bNodeLink &link : from_tree.links) {
128 BLI_assert(link.tonode);
129 BLI_assert(link.fromnode);
130 if (link.tonode->is_selected() && link.fromnode->is_selected()) {
131 if (!node_map.contains(link.tonode) || !node_map.contains(link.fromnode)) {
132 /* If copying a node fails, skip copying their links. */
133 continue;
134 };
135 bNode *from_node = node_map.lookup(link.fromnode);
136 bNode *to_node = node_map.lookup(link.tonode);
137
139 *from_node, SOCK_OUT, link.fromsock->identifier_ustr());
140 bNodeSocket *to = bke::node_find_socket(*to_node, SOCK_IN, link.tosock->identifier_ustr());
141 if (!from || !to) {
142 continue;
143 }
144
145 bNodeLink &new_link = bke::node_add_link(to_tree, *from_node, *from, *to_node, *to);
147 }
148 }
149
150 to_tree.ensure_topology_cache();
151 for (bNode *new_node : node_map.values()) {
152 /* Update multi input socket indices in case all connected nodes weren't copied. */
154 }
155
156 return node_map.size();
157}
158
160
161/* -------------------------------------------------------------------- */
164
166{
167 using namespace blender::bke::blendfile;
168
169 Main *bmain = CTX_data_main(C);
170 SpaceNode *snode = CTX_wm_space_node(C);
171 bNodeTree *node_tree = snode->edittree;
172
173 PartialWriteContext copy_buffer{*bmain};
174 bNodeTree *copy_tree = reinterpret_cast<bNodeTree *>(
175 copy_buffer.id_create(ID_NT,
176 "Copy Tree",
177 nullptr,
180
181 STRNCPY_UTF8(copy_tree->idname, node_tree->typeinfo->idname.c_str());
182 bke::node_tree_set_type(*copy_tree);
183
184 /* Copy node interface to avoid losing links to Group Input and Group Output nodes.
185 * Note: this doesn't create new interface items if they don't exist. */
186 /* #bNodeTreeInterface::copy_data() allocates runtime memory, so we need to free it to avoid
187 * memory leak. */
188 copy_tree->tree_interface.free_data();
189 copy_tree->tree_interface.copy_data(node_tree->tree_interface, LIB_ID_COPY_DEFAULT);
190
191 const int num_copied = node_copy_local(
192 *node_tree, *copy_tree, true, false, float2(0), false, op->reports);
193 if (num_copied == 0) {
194 return OPERATOR_CANCELLED;
195 }
196
197 auto add_tree_ids_dependencies_cb = [&copy_buffer,
198 copy_tree](LibraryIDLinkCallbackData *cb_data) -> int {
199 /* Embedded or null IDs usages can be ignored here. */
200 if (cb_data->cb_flag & (IDWALK_CB_EMBEDDED | IDWALK_CB_EMBEDDED_NOT_OWNING)) {
201 return IDWALK_RET_NOP;
202 }
203 ID *id_src = *cb_data->id_pointer;
204 if (!id_src) {
205 return IDWALK_RET_NOP;
206 }
207
208 ID *id_dst = nullptr;
209
210 if (id_src == &copy_tree->id) {
211 /* #copy_tree is just a container for the copied nodes, so it can be safely ignored. */
212 return IDWALK_RET_NOP;
213 }
214
215 auto partial_write_dependencies_filter_cb = [](LibraryIDLinkCallbackData *cb_deps_data,
217 ID *id_deps_src = *cb_deps_data->id_pointer;
218 const ID_Type id_type = id_deps_src->id_type();
219 if (id_type == ID_SCE) {
220 /* Note: Scenes referenced in the Render Layers node are cleared. At this stage, we
221 * don't know if the target blender instance will have a scene with identical name, so
222 * they are saved in the copy buffer as empty scenes. The pasting code deletes the
223 * extra scenes, see #node_clipboard_paste_exec(). */
225 }
226 /* All ID datablocks exposed through nodes are added here. */
228 };
229
230 id_dst = copy_buffer.id_add(
231 id_src, {PartialWriteContext::IDAddOperations::NOP}, partial_write_dependencies_filter_cb);
232
233 *cb_data->id_pointer = id_dst;
234 return IDWALK_RET_NOP;
235 };
236
238 nullptr, &copy_tree->id, add_tree_ids_dependencies_cb, nullptr, IDWALK_NOP);
239
240 char filepath[FILE_MAX];
241 node_copybuffer_filepath_get(filepath, sizeof(filepath));
242 if (!copy_buffer.write_as_copypaste_buffer(filepath, *op->reports)) {
244 BKE_report(op->reports, RPT_ERROR, "Unable to write to copy buffer on disk.");
245 return OPERATOR_CANCELLED;
246 };
247
248 BKE_reportf(op->reports, RPT_INFO, "Copied %d selected node(s)", num_copied);
249 return OPERATOR_FINISHED;
250}
251
253{
254 ot->name = "Copy to Clipboard";
255 ot->description = "Copy the selected nodes to the internal clipboard";
256 ot->idname = "NODE_OT_clipboard_copy";
257
260}
261
263
264/* -------------------------------------------------------------------- */
267
269{
270 if (scene.id.lib && scene.id.lib->runtime) {
271 return scene.id.lib->runtime->filepath_abs;
272 }
273 return "";
274}
275
277{
278 SpaceNode *snode = CTX_wm_space_node(C);
279 Main *bmain_dst = CTX_data_main(C);
280
281 char filepath[FILE_MAX];
282 node_copybuffer_filepath_get(filepath, sizeof(filepath));
283 Main *bmain_src = BKE_copybuffer_read(*bmain_dst, filepath, op->reports, FILTER_ID_NT);
284 if (!bmain_src) {
285 BKE_report(op->reports, RPT_ERROR, "No data to paste");
286 return OPERATOR_CANCELLED;
287 }
288
290
291 /* We don't want to paste scenes referenced by the Render Layers node if they don't exist in the
292 * destination bmain. */
294 for (Scene &scene : bmain_dst->scenes) {
295 /* Packed scenes are currently not needed so they are skipped.
296 * TODO: Support packed scenes. */
297 if (ID_IS_PACKED(&scene.id)) {
298 continue;
299 }
300 dst_scenes.add({scene.id.name, scene_lib_filepath(scene)});
301 }
302
303 for (Scene &scene : bmain_src->scenes.items_mutable()) {
304 if (ID_IS_PACKED(&scene.id)) {
305 continue;
306 }
307 /* All scenes that will be added through merging the two bmains are removed. */
308 if (!dst_scenes.contains({scene.id.name, scene_lib_filepath(scene)})) {
309 BKE_id_delete(bmain_src, &scene.id);
310 }
311 }
312
313 bNodeTree *from_tree = nullptr;
314 FOREACH_NODETREE_BEGIN (bmain_src, node_tree, id) {
315 if (node_tree->id.flag & ID_FLAG_CLIPBOARD_MARK) {
316 from_tree = node_tree;
317 break;
318 }
319 }
321 if (from_tree == nullptr) {
322 BKE_report(op->reports, RPT_ERROR, "No data to paste");
323 BKE_main_free(bmain_src);
324 return OPERATOR_CANCELLED;
325 }
326
327 MainMergeReport merge_reports = {};
328 /* We need to ensure that the source 'clipboard marked' main NodeTree is always merged into
329 * destination Main, even in case there would be a name collision with an existing ID (see also
330 * #158049). */
331 Set<ID *> force_merge_ids = {id_cast<ID *>(from_tree)};
332 /* Frees bmain_src. */
333 BKE_main_merge(bmain_dst, &force_merge_ids, &bmain_src, merge_reports);
334
335 bNodeTree *to_tree = snode->edittree;
336 node_deselect_all(*to_tree);
337
338 float2 offset(0);
339 PropertyRNA *offset_prop = RNA_struct_find_property(op->ptr, "offset");
340 if (RNA_property_is_set(op->ptr, offset_prop)) {
341 rctf bbox;
342 float2 center;
344 for (bNode *node : from_tree->all_nodes()) {
345 bbox.xmin = math::min(node->location[0], bbox.xmin);
346 bbox.ymin = math::min(node->location[1], bbox.ymin);
347
348 bbox.xmax = math::max(node->location[0] + node->width, bbox.xmax);
349 bbox.ymax = math::max(node->location[1] - node->height / 2, bbox.ymax);
350 }
351 center.x = BLI_rctf_cent_x(&bbox);
352 center.y = BLI_rctf_cent_y(&bbox);
353
354 float2 mouse_location;
355 RNA_property_float_get_array(op->ptr, offset_prop, mouse_location);
356 offset = mouse_location / UI_SCALE_FAC - center;
357 }
358
359 const bool snap_to_grid = CTX_data_scene(C)->toolsettings->snap_flag_node & SCE_SNAP;
360 const int num_copied = node_copy_local(
361 *from_tree, *snode->edittree, false, true, offset, snap_to_grid, op->reports);
362 if (num_copied == 0) {
363 /* Note: we don't return OPERATOR_CANCELLED here although the copy fails to avoid corrupting
364 * the undo stack after merging two bmains. */
365 };
366 BKE_id_delete(bmain_dst, &from_tree->id);
367
368 BKE_main_ensure_invariants(*bmain_dst);
369 /* Pasting nodes can create arbitrary new relations because nodes can reference IDs. */
370 DEG_relations_tag_update(bmain_dst);
371
372 return OPERATOR_FINISHED;
373}
374
376 wmOperator *op,
377 const wmEvent *event)
378{
379 const ARegion *region = CTX_wm_region(C);
380 float2 cursor;
381 ui::view2d_region_to_view(&region->v2d, event->mval[0], event->mval[1], &cursor.x, &cursor.y);
382 RNA_float_set_array(op->ptr, "offset", cursor);
383 return node_clipboard_paste_exec(C, op);
384}
385
387{
388 ot->name = "Paste from Clipboard";
389 ot->description = "Paste nodes from the internal clipboard to the active node tree";
390 ot->idname = "NODE_OT_clipboard_paste";
391
395
397
399 ot->srna,
400 "offset",
401 2,
402 nullptr,
403 -FLT_MAX,
404 FLT_MAX,
405 "Location",
406 "The 2D view location for the center of the new nodes, or unchanged if not set",
407 -FLT_MAX,
408 FLT_MAX);
411}
412
414
415} // namespace blender::ed::space_node
#define FOREACH_NODETREE_END
Definition BKE_node.hh:936
#define FOREACH_NODETREE_BEGIN(bmain, _nodetree, _id)
Definition BKE_node.hh:926
#define FILE_MAX
#define BLI_path_join(...)
#define STRNCPY_UTF8(dst, src)
external readfile function prototypes.
#define ID_IS_PACKED(_id)
Definition DNA_ID.h:703
#define FILTER_ID_NT
Definition DNA_ID.h:1215
#define UI_SCALE_FAC
#define C
Definition RandGen.cpp:29
#define BLI_assert_unreachable()
ValueIterator values() const &
Definition BLI_map.hh:884
const Value & lookup(const Key &key) const
Definition BLI_map.hh:545
void add_new(const Key &key, const Value &value)
Definition BLI_map.hh:265
int64_t size() const
Definition BLI_map.hh:976
bool is_empty() const
Definition BLI_map.hh:986
bool contains(const Key &key) const
Definition BLI_map.hh:353
bool contains(const Key &key) const
Definition BLI_set.hh:310
bool add(const Key &key)
Definition BLI_set.hh:248
const char * c_str() const
ID * id_add(const ID *id, IDAddOptions options, FunctionRef< IDAddOperations(LibraryIDLinkCallbackData *cb_data, IDAddOptions options)> dependencies_filter_cb=nullptr)
bool write_as_copypaste_buffer(const char *write_filepath, ReportList &reports)
ID * id_create(short id_type, StringRefNull id_name, Library *library, IDAddOptions options)
#define FLT_MAX
void node_tree_set_type(bNodeTree &ntree)
Definition node.cc:2748
void node_detach_node(bNodeTree &ntree, bNode &node)
Definition node.cc:4891
bNodeLink & node_add_link(bNodeTree &ntree, bNode &fromnode, bNodeSocket &fromsock, bNode &tonode, bNodeSocket &tosock)
Definition node.cc:4638
bNodeSocket * node_find_socket(bNode &node, eNodeSocketInOut in_out, UString identifier)
Definition node.cc:3036
bNode * node_copy_with_mapping(bNodeTree *dst_tree, const bNode &node_src, int flag, std::optional< StringRefNull > dst_unique_name, std::optional< int > dst_unique_identifier, Map< const bNodeSocket *, bNodeSocket * > &new_socket_map, bool allow_duplicate_names=false)
Definition node.cc:4327
void NODE_OT_clipboard_copy(wmOperatorType *ot)
Definition clipboard.cc:252
void node_select_paired(bNodeTree &node_tree)
bool node_deselect_all(bNodeTree &node_tree)
static int node_copy_local(bNodeTree &from_tree, bNodeTree &to_tree, const bool allow_duplicate_names, const bool do_user_count, const float2 offset, const bool snap_to_grid, ReportList *reports)
Definition clipboard.cc:56
void NODE_OT_clipboard_paste(wmOperatorType *ot)
Definition clipboard.cc:386
static wmOperatorStatus node_clipboard_copy_exec(bContext *C, wmOperator *op)
Definition clipboard.cc:165
static wmOperatorStatus node_clipboard_paste_exec(bContext *C, wmOperator *op)
Definition clipboard.cc:276
static void node_copybuffer_filepath_get(char filepath[FILE_MAX], size_t filepath_maxncpy)
Definition clipboard.cc:50
void remap_node_pairing(bNodeTree &dst_tree, const Map< const bNode *, bNode * > &node_map)
Definition node_edit.cc:949
VectorSet< bNode * > get_selected_nodes(bNodeTree &node_tree)
static StringRef scene_lib_filepath(const Scene &scene)
Definition clipboard.cc:268
void update_multi_input_indices_for_removed_links(bNode &node)
static wmOperatorStatus node_clipboard_paste_invoke(bContext *C, wmOperator *op, const wmEvent *event)
Definition clipboard.cc:375
float nearest_node_grid_coord(float co)
Definition node_edit.cc:516
T min(const T &a, const T &b)
T max(const T &a, const T &b)
void view2d_region_to_view(const View2D *v2d, float x, float y, float *r_view_x, float *r_view_y) ATTR_NONNULL()
Definition view2d.cc:1651
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
void RNA_float_set_array(PointerRNA *ptr, const char *name, const float *values)
bool ED_operator_node_active(bContext *C)
Main * BKE_copybuffer_read(Main &reference_bmain, const char *libname, ReportList *reports, uint64_t id_types_mask)
void RNA_property_float_get_array(PointerRNA *ptr, PropertyRNA *prop, float *values)
void BKE_id_delete(Main *bmain, void *idv, const BKEIDDeleteOptions &options={}) ATTR_NONNULL()
PropertyRNA * RNA_struct_find_property(PointerRNA *ptr, const char *identifier)
PropertyRNA * RNA_def_float_array(StructOrFunctionRNA *cont_, const char *identifier, const int len, const float *default_value, const float hardmin, const float hardmax, const char *ui_name, const char *ui_description, const float softmin, const float softmax)
bool ED_operator_node_editable(bContext *C)
@ LIB_ID_CREATE_NO_USER_REFCOUNT
@ LIB_ID_COPY_DEFAULT
void ED_preview_kill_jobs(wmWindowManager *wm, Main *bmain)
VecBase< float, 2 > float2
void BKE_report(ReportList *reports, eReportType type, const char *message)
Definition report.cc:162
wmWindowManager * CTX_wm_manager(const bContext *C)
void BKE_main_ensure_invariants(Main &bmain, std::optional< Span< ID * > > modified_ids=std::nullopt)
void BLI_rctf_init_minmax(struct rctf *rect)
Definition rct.cc:494
SpaceNode * CTX_wm_space_node(const bContext *C)
void BKE_main_merge(Main *bmain_dst, Set< ID * > *force_merge_src_ids, Main **r_bmain_src, MainMergeReport &reports)
Definition main.cc:362
const char * BKE_tempdir_base() ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL
Definition appdir.cc:1288
void BKE_main_free(Main *bmain)
Definition main.cc:202
void RNA_def_property_flag(PropertyRNA *prop, PropertyFlag flag)
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
Definition report.cc:191
Main * CTX_data_main(const bContext *C)
BLI_INLINE float BLI_rctf_cent_y(const struct rctf *rct)
Definition BLI_rect.hh:198
@ PROP_SKIP_SAVE
Definition RNA_types.hh:414
@ PROP_HIDDEN
Definition RNA_types.hh:408
void DEG_relations_tag_update(Main *bmain)
Scene * CTX_data_scene(const bContext *C)
@ ID_FLAG_CLIPBOARD_MARK
Definition DNA_ID.h:801
@ OPTYPE_REGISTER
Definition WM_types.hh:188
@ OPTYPE_UNDO
Definition WM_types.hh:190
@ IDWALK_CB_EMBEDDED_NOT_OWNING
@ IDWALK_CB_EMBEDDED
void BKE_library_foreach_ID_link(Main *bmain, ID *id, FunctionRef< LibraryIDLinkCallback > callback, void *user_data, LibraryForeachIDFlag flag)
Definition lib_query.cc:449
ARegion * CTX_wm_region(const bContext *C)
BLI_INLINE float BLI_rctf_cent_x(const struct rctf *rct)
Definition BLI_rect.hh:194
bool RNA_property_is_set(PointerRNA *ptr, PropertyRNA *prop)
char name[258]
Definition DNA_ID.h:433
struct Library * lib
Definition DNA_ID.h:421
bke::library::LibraryRuntime * runtime
Definition DNA_ID.h:591
ListBaseT< Scene > scenes
Definition BKE_main.hh:386
struct ToolSettings * toolsettings
struct bNodeTree * edittree
ListBaseT< bNodeLink > links
bke::bNodeTreeType * typeinfo
bNodeTreeInterface tree_interface
wmOperatorStatus(*) exec(bContext *C, wmOperator *op) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1125
const char * description
Definition WM_types.hh:1115
bool(*) poll(bContext *C) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1165
wmOperatorStatus(*) invoke(bContext *C, wmOperator *op, const wmEvent *event) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1141
struct ReportList * reports