When relinking node group outputs from sockets of different type, automatically chang...
[blender.git] / source / blender / editors / space_node / node_edit.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2005 Blender Foundation.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): David Millan Escriva, Juho Vepsäläinen, Nathan Letwory
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /** \file blender/editors/space_node/node_edit.c
31  *  \ingroup spnode
32  */
33
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <math.h>
38 #include <string.h>
39 #include <errno.h>
40
41 #include "MEM_guardedalloc.h"
42
43 #include "DNA_object_types.h"
44 #include "DNA_material_types.h"
45 #include "DNA_node_types.h"
46 #include "DNA_scene_types.h"
47
48 #include "BLI_math.h"
49 #include "BLI_blenlib.h"
50 #include "BLI_storage_types.h"
51 #include "BLI_utildefines.h"
52
53 #include "BKE_context.h"
54 #include "BKE_depsgraph.h"
55 #include "BKE_global.h"
56 #include "BKE_image.h"
57 #include "BKE_library.h"
58 #include "BKE_main.h"
59 #include "BKE_node.h"
60 #include "BKE_material.h"
61 #include "BKE_paint.h"
62 #include "BKE_screen.h"
63 #include "BKE_texture.h"
64 #include "BKE_report.h"
65
66 #include "RE_pipeline.h"
67
68 #include "IMB_imbuf_types.h"
69
70 #include "ED_node.h"
71 #include "ED_screen.h"
72 #include "ED_space_api.h"
73 #include "ED_render.h"
74
75 #include "RNA_access.h"
76 #include "RNA_define.h"
77
78 #include "WM_api.h"
79 #include "WM_types.h"
80
81 #include "UI_interface.h"
82 #include "UI_view2d.h"
83
84 #include "IMB_imbuf.h"
85
86 #include "RNA_enum_types.h"
87
88 #include "node_intern.h"
89
90 static EnumPropertyItem socket_in_out_items[] = {
91         { SOCK_IN, "IN", 0, "In", "" },
92         { SOCK_OUT, "OUT", 0, "Out", "" },
93         { 0, NULL, 0, NULL, NULL}
94 };
95
96 /* ***************** composite job manager ********************** */
97
98 typedef struct CompoJob {
99         Scene *scene;
100         bNodeTree *ntree;
101         bNodeTree *localtree;
102         short *stop;
103         short *do_update;
104         float *progress;
105 } CompoJob;
106
107 /* called by compo, only to check job 'stop' value */
108 static int compo_breakjob(void *cjv)
109 {
110         CompoJob *cj= cjv;
111         
112         return *(cj->stop);
113 }
114
115 /* called by compo, wmJob sends notifier */
116 static void compo_redrawjob(void *cjv, char *UNUSED(str))
117 {
118         CompoJob *cj= cjv;
119         
120         *(cj->do_update)= 1;
121 }
122
123 static void compo_freejob(void *cjv)
124 {
125         CompoJob *cj= cjv;
126
127         if(cj->localtree) {
128                 ntreeLocalMerge(cj->localtree, cj->ntree);
129         }
130         MEM_freeN(cj);
131 }
132
133 /* only now we copy the nodetree, so adding many jobs while
134    sliding buttons doesn't frustrate */
135 static void compo_initjob(void *cjv)
136 {
137         CompoJob *cj= cjv;
138
139         cj->localtree= ntreeLocalize(cj->ntree);
140 }
141
142 /* called before redraw notifiers, it moves finished previews over */
143 static void compo_updatejob(void *cjv)
144 {
145         CompoJob *cj= cjv;
146         
147         ntreeLocalSync(cj->localtree, cj->ntree);
148 }
149
150 static void compo_progressjob(void *cjv, float progress)
151 {
152         CompoJob *cj= cjv;
153         
154         *(cj->progress) = progress;
155 }
156
157
158 /* only this runs inside thread */
159 static void compo_startjob(void *cjv, short *stop, short *do_update, float *progress)
160 {
161         CompoJob *cj= cjv;
162         bNodeTree *ntree= cj->localtree;
163
164         if(cj->scene->use_nodes==0)
165                 return;
166         
167         cj->stop= stop;
168         cj->do_update= do_update;
169         cj->progress= progress;
170         
171         ntree->test_break= compo_breakjob;
172         ntree->tbh= cj;
173         ntree->stats_draw= compo_redrawjob;
174         ntree->sdh= cj;
175         ntree->progress= compo_progressjob;
176         ntree->prh= cj;
177         
178         // XXX BIF_store_spare();
179         
180         ntreeCompositExecTree(ntree, &cj->scene->r, 1); /* 1 is do_previews */
181         
182         ntree->test_break= NULL;
183         ntree->stats_draw= NULL;
184         ntree->progress= NULL;
185
186 }
187
188 void snode_composite_job(const bContext *C, ScrArea *sa)
189 {
190         SpaceNode *snode= sa->spacedata.first;
191         wmJob *steve;
192         CompoJob *cj;
193
194         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), sa, "Compositing", WM_JOB_EXCL_RENDER|WM_JOB_PROGRESS);
195         cj= MEM_callocN(sizeof(CompoJob), "compo job");
196         
197         /* customdata for preview thread */
198         cj->scene= CTX_data_scene(C);
199         cj->ntree= snode->nodetree;
200         
201         /* setup job */
202         WM_jobs_customdata(steve, cj, compo_freejob);
203         WM_jobs_timer(steve, 0.1, NC_SCENE, NC_SCENE|ND_COMPO_RESULT);
204         WM_jobs_callbacks(steve, compo_startjob, compo_initjob, compo_updatejob, NULL);
205         
206         WM_jobs_start(CTX_wm_manager(C), steve);
207         
208 }
209
210 /* ***************************************** */
211
212 /* operator poll callback */
213 static int composite_node_active(bContext *C)
214 {
215         if( ED_operator_node_active(C)) {
216                 SpaceNode *snode= CTX_wm_space_node(C);
217                 if(snode->treetype==NTREE_COMPOSIT)
218                         return 1;
219         }
220         return 0;
221 }
222
223 /* also checks for edited groups */
224 static bNode *editnode_get_active(bNodeTree *ntree)
225 {
226         bNode *node;
227         
228         /* check for edited group */
229         for(node= ntree->nodes.first; node; node= node->next)
230                 if(node->flag & NODE_GROUP_EDIT)
231                         break;
232         if(node)
233                 return nodeGetActive((bNodeTree *)node->id);
234         else
235                 return nodeGetActive(ntree);
236 }
237
238 void snode_dag_update(bContext *UNUSED(C), SpaceNode *snode)
239 {
240         DAG_id_tag_update(snode->id, 0);
241 }
242
243 void snode_notify(bContext *C, SpaceNode *snode)
244 {
245         WM_event_add_notifier(C, NC_NODE|NA_EDITED, NULL);
246
247         if(snode->treetype==NTREE_SHADER)
248                 WM_event_add_notifier(C, NC_MATERIAL|ND_NODES, snode->id);
249         else if(snode->treetype==NTREE_COMPOSIT)
250                 WM_event_add_notifier(C, NC_SCENE|ND_NODES, snode->id);
251         else if(snode->treetype==NTREE_TEXTURE)
252                 WM_event_add_notifier(C, NC_TEXTURE|ND_NODES, snode->id);
253 }
254
255 bNode *node_tree_get_editgroup(bNodeTree *nodetree)
256 {
257         bNode *gnode;
258         
259         /* get the groupnode */
260         for(gnode= nodetree->nodes.first; gnode; gnode= gnode->next)
261                 if(gnode->flag & NODE_GROUP_EDIT)
262                         break;
263         return gnode;
264 }
265
266 /* assumes nothing being done in ntree yet, sets the default in/out node */
267 /* called from shading buttons or header */
268 void ED_node_shader_default(Material *ma)
269 {
270         bNode *in, *out;
271         bNodeSocket *fromsock, *tosock;
272         
273         /* but lets check it anyway */
274         if(ma->nodetree) {
275                 if (G.f & G_DEBUG)
276                         printf("error in shader initialize\n");
277                 return;
278         }
279         
280         ma->nodetree= ntreeAddTree("Shader Nodetree", NTREE_SHADER, FALSE);
281         
282         out= nodeAddNodeType(ma->nodetree, SH_NODE_OUTPUT, NULL, NULL);
283         out->locx= 300.0f; out->locy= 300.0f;
284         
285         in= nodeAddNodeType(ma->nodetree, SH_NODE_MATERIAL, NULL, NULL);
286         in->locx= 10.0f; in->locy= 300.0f;
287         nodeSetActive(ma->nodetree, in);
288         
289         /* only a link from color to color */
290         fromsock= in->outputs.first;
291         tosock= out->inputs.first;
292         nodeAddLink(ma->nodetree, in, fromsock, out, tosock);
293         
294         ntreeSolveOrder(ma->nodetree);  /* needed for pointers */
295 }
296
297 /* assumes nothing being done in ntree yet, sets the default in/out node */
298 /* called from shading buttons or header */
299 void ED_node_composit_default(Scene *sce)
300 {
301         bNode *in, *out;
302         bNodeSocket *fromsock, *tosock;
303         
304         /* but lets check it anyway */
305         if(sce->nodetree) {
306                 if (G.f & G_DEBUG)
307                         printf("error in composite initialize\n");
308                 return;
309         }
310         
311         sce->nodetree= ntreeAddTree("Compositing Nodetree", NTREE_COMPOSIT, FALSE);
312         
313         out= nodeAddNodeType(sce->nodetree, CMP_NODE_COMPOSITE, NULL, NULL);
314         out->locx= 300.0f; out->locy= 400.0f;
315         out->id= &sce->id;
316         id_us_plus(out->id);
317         
318         in= nodeAddNodeType(sce->nodetree, CMP_NODE_R_LAYERS, NULL, NULL);
319         in->locx= 10.0f; in->locy= 400.0f;
320         in->id= &sce->id;
321         id_us_plus(in->id);
322         nodeSetActive(sce->nodetree, in);
323         
324         /* links from color to color */
325         fromsock= in->outputs.first;
326         tosock= out->inputs.first;
327         nodeAddLink(sce->nodetree, in, fromsock, out, tosock);
328         
329         ntreeSolveOrder(sce->nodetree); /* needed for pointers */
330         
331         // XXX ntreeCompositForceHidden(sce->nodetree);
332 }
333
334 /* assumes nothing being done in ntree yet, sets the default in/out node */
335 /* called from shading buttons or header */
336 void ED_node_texture_default(Tex *tx)
337 {
338         bNode *in, *out;
339         bNodeSocket *fromsock, *tosock;
340         
341         /* but lets check it anyway */
342         if(tx->nodetree) {
343                 if (G.f & G_DEBUG)
344                         printf("error in texture initialize\n");
345                 return;
346         }
347         
348         tx->nodetree= ntreeAddTree("Texture Nodetree", NTREE_TEXTURE, FALSE);
349         
350         out= nodeAddNodeType(tx->nodetree, TEX_NODE_OUTPUT, NULL, NULL);
351         out->locx= 300.0f; out->locy= 300.0f;
352         
353         in= nodeAddNodeType(tx->nodetree, TEX_NODE_CHECKER, NULL, NULL);
354         in->locx= 10.0f; in->locy= 300.0f;
355         nodeSetActive(tx->nodetree, in);
356         
357         fromsock= in->outputs.first;
358         tosock= out->inputs.first;
359         nodeAddLink(tx->nodetree, in, fromsock, out, tosock);
360         
361         ntreeSolveOrder(tx->nodetree);  /* needed for pointers */
362 }
363
364 /* id is supposed to contain a node tree */
365 void node_tree_from_ID(ID *id, bNodeTree **ntree, bNodeTree **edittree, int *treetype)
366 {
367         bNode *node= NULL;
368         short idtype= GS(id->name);
369
370         if(idtype == ID_MA) {
371                 *ntree= ((Material*)id)->nodetree;
372                 if(treetype) *treetype= NTREE_SHADER;
373         }
374         else if(idtype == ID_SCE) {
375                 *ntree= ((Scene*)id)->nodetree;
376                 if(treetype) *treetype= NTREE_COMPOSIT;
377         }
378         else if(idtype == ID_TE) {
379                 *ntree= ((Tex*)id)->nodetree;
380                 if(treetype) *treetype= NTREE_TEXTURE;
381         }
382         else {
383                 if(treetype) *treetype= 0;
384                 return;
385         }
386
387         /* find editable group */
388         if(edittree) {
389                 if(*ntree)
390                         for(node= (*ntree)->nodes.first; node; node= node->next)
391                                 if(node->flag & NODE_GROUP_EDIT)
392                                         break;
393                 
394                 if(node && node->id)
395                         *edittree= (bNodeTree *)node->id;
396                 else
397                         *edittree= *ntree;
398         }
399 }
400
401 /* Here we set the active tree(s), even called for each redraw now, so keep it fast :) */
402 void snode_set_context(SpaceNode *snode, Scene *scene)
403 {
404         Object *ob= OBACT;
405         
406         snode->nodetree= NULL;
407         snode->edittree= NULL;
408         snode->id= snode->from= NULL;
409         
410         if(snode->treetype==NTREE_SHADER) {
411                 /* need active object, or we allow pinning... */
412                 if(ob) {
413                         Material *ma= give_current_material(ob, ob->actcol);
414                         if(ma) {
415                                 snode->from= &ob->id;
416                                 snode->id= &ma->id;
417                         }
418                 }
419         }
420         else if(snode->treetype==NTREE_COMPOSIT) {
421                 snode->from= NULL;
422                 snode->id= &scene->id;
423                 
424                 /* bit clumsy but reliable way to see if we draw first time */
425                 if(snode->nodetree==NULL)
426                         ntreeCompositForceHidden(scene->nodetree, scene);
427         }
428         else if(snode->treetype==NTREE_TEXTURE) {
429                 Tex *tx= NULL;
430
431                 if(snode->texfrom==SNODE_TEX_OBJECT) {
432                         if(ob) {
433                                 tx= give_current_object_texture(ob);
434
435                                 if(ob->type == OB_LAMP)
436                                         snode->from= (ID*)ob->data;
437                                 else
438                                         snode->from= (ID*)give_current_material(ob, ob->actcol);
439
440                                 /* from is not set fully for material nodes, should be ID + Node then */
441                                 snode->id= &tx->id;
442                         }
443                 }
444                 else if(snode->texfrom==SNODE_TEX_WORLD) {
445                         tx= give_current_world_texture(scene->world);
446                         snode->from= (ID *)scene->world;
447                         snode->id= &tx->id;
448                 }
449                 else {
450                         struct Brush *brush= NULL;
451                         
452                         if(ob && (ob->mode & OB_MODE_SCULPT))
453                                 brush= paint_brush(&scene->toolsettings->sculpt->paint);
454                         else
455                                 brush= paint_brush(&scene->toolsettings->imapaint.paint);
456
457                         if (brush) {
458                                 snode->from= (ID *)brush;
459                                 tx= give_current_brush_texture(brush);
460                                 snode->id= &tx->id;
461                         }
462                 }
463         }
464
465         if(snode->id)
466                 node_tree_from_ID(snode->id, &snode->nodetree, &snode->edittree, NULL);
467 }
468
469 static void snode_tag_changed(SpaceNode *snode, bNode *node)
470 {
471         bNode *gnode;
472         
473         if (node)
474                 NodeTagChanged(snode->edittree, node);
475         
476         /* if inside group, tag entire group */
477         gnode= node_tree_get_editgroup(snode->nodetree);
478         if(gnode)
479                 NodeTagIDChanged(snode->nodetree, gnode->id);
480 }
481
482 void node_set_active(SpaceNode *snode, bNode *node)
483 {
484         nodeSetActive(snode->edittree, node);
485         
486         if(node->type!=NODE_GROUP) {
487                 int was_output= (node->flag & NODE_DO_OUTPUT);
488                 
489                 /* tree specific activate calls */
490                 if(snode->treetype==NTREE_SHADER) {
491                         /* when we select a material, active texture is cleared, for buttons */
492                         if(node->id && GS(node->id->name)==ID_MA)
493                                 nodeClearActiveID(snode->edittree, ID_TE);
494                         
495                         if(node->type==SH_NODE_OUTPUT) {
496                                 bNode *tnode;
497                                 
498                                 for(tnode= snode->edittree->nodes.first; tnode; tnode= tnode->next)
499                                         if( tnode->type==SH_NODE_OUTPUT)
500                                                 tnode->flag &= ~NODE_DO_OUTPUT;
501                                 
502                                 node->flag |= NODE_DO_OUTPUT;
503                                 if(was_output==0)
504                                         ED_node_changed_update(snode->id, node);
505                         }
506
507                         WM_main_add_notifier(NC_MATERIAL|ND_NODES, node->id);
508                 }
509                 else if(snode->treetype==NTREE_COMPOSIT) {
510                         Scene *scene= (Scene*)snode->id;
511
512                         /* make active viewer, currently only 1 supported... */
513                         if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
514                                 bNode *tnode;
515                                 
516
517                                 for(tnode= snode->edittree->nodes.first; tnode; tnode= tnode->next)
518                                         if( ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
519                                                 tnode->flag &= ~NODE_DO_OUTPUT;
520                                 
521                                 node->flag |= NODE_DO_OUTPUT;
522                                 if(was_output==0) {
523                                         snode_tag_changed(snode, node);
524                                         
525                                         ED_node_changed_update(snode->id, node);
526                                 }
527                                 
528                                 /* addnode() doesnt link this yet... */
529                                 node->id= (ID *)BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
530                         }
531                         else if(node->type==CMP_NODE_R_LAYERS) {
532                                 if(node->id==NULL || node->id==(ID *)scene) {
533                                         scene->r.actlay= node->custom1;
534                                 }
535                         }
536                         else if(node->type==CMP_NODE_COMPOSITE) {
537                                 bNode *tnode;
538                                 
539                                 for(tnode= snode->edittree->nodes.first; tnode; tnode= tnode->next)
540                                         if( tnode->type==CMP_NODE_COMPOSITE)
541                                                 tnode->flag &= ~NODE_DO_OUTPUT;
542                                 
543                                 node->flag |= NODE_DO_OUTPUT;
544                                 ED_node_changed_update(snode->id, node);
545                         }
546                 }
547                 else if(snode->treetype==NTREE_TEXTURE) {
548                         // XXX
549 #if 0
550                         if(node->id)
551                                 ; // XXX BIF_preview_changed(-1);
552                         // allqueue(REDRAWBUTSSHADING, 1);
553                         // allqueue(REDRAWIPO, 0);
554 #endif
555                 }
556         }
557 }
558
559 /* when links in groups change, inputs/outputs change, nodes added/deleted... */
560 void node_tree_verify_groups(bNodeTree *nodetree)
561 {
562         bNode *gnode;
563         
564         gnode= node_tree_get_editgroup(nodetree);
565         
566         /* does all materials */
567         if(gnode)
568                 nodeGroupVerify((bNodeTree *)gnode->id);
569         
570 }
571
572 /* ***************** Edit Group operator ************* */
573
574 void snode_make_group_editable(SpaceNode *snode, bNode *gnode)
575 {
576         bNode *node;
577         
578         /* make sure nothing has group editing on */
579         for(node= snode->nodetree->nodes.first; node; node= node->next)
580                 node->flag &= ~NODE_GROUP_EDIT;
581         
582         if(gnode==NULL) {
583                 /* with NULL argument we do a toggle */
584                 if(snode->edittree==snode->nodetree)
585                         gnode= nodeGetActive(snode->nodetree);
586         }
587         
588         if(gnode && gnode->type==NODE_GROUP && gnode->id) {
589                 if(gnode->id->lib)
590                         ntreeMakeLocal((bNodeTree *)gnode->id);
591
592                 gnode->flag |= NODE_GROUP_EDIT;
593                 snode->edittree= (bNodeTree *)gnode->id;
594                 
595                 /* deselect all other nodes, so we can also do grabbing of entire subtree */
596                 for(node= snode->nodetree->nodes.first; node; node= node->next)
597                         node->flag &= ~SELECT;
598                 gnode->flag |= SELECT;
599                 
600         }
601         else 
602                 snode->edittree= snode->nodetree;
603         
604         ntreeSolveOrder(snode->nodetree);
605 }
606
607 static int node_group_edit_exec(bContext *C, wmOperator *UNUSED(op))
608 {
609         SpaceNode *snode = CTX_wm_space_node(C);
610         bNode *gnode;
611
612         ED_preview_kill_jobs(C);
613
614         gnode= nodeGetActive(snode->edittree);
615         snode_make_group_editable(snode, gnode);
616
617         WM_event_add_notifier(C, NC_SCENE|ND_NODES, NULL);
618
619         return OPERATOR_FINISHED;
620 }
621
622 static int node_group_edit_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
623 {
624         SpaceNode *snode = CTX_wm_space_node(C);
625         bNode *gnode;
626
627         gnode= nodeGetActive(snode->edittree);
628         if(gnode && gnode->type==NODE_GROUP && gnode->id && gnode->id->lib) {
629                 uiPupMenuOkee(C, op->type->idname, "Make group local?");
630                 return OPERATOR_CANCELLED;
631         }
632
633         return node_group_edit_exec(C, op);
634 }
635
636 void NODE_OT_group_edit(wmOperatorType *ot)
637 {
638         /* identifiers */
639         ot->name = "Edit Group";
640         ot->description = "Edit node group";
641         ot->idname = "NODE_OT_group_edit";
642         
643         /* api callbacks */
644         ot->invoke = node_group_edit_invoke;
645         ot->exec = node_group_edit_exec;
646         ot->poll = ED_operator_node_active;
647         
648         /* flags */
649         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
650 }
651
652 /* ***************** Add Group Socket operator ************* */
653
654 static int node_group_socket_add_exec(bContext *C, wmOperator *op)
655 {
656         SpaceNode *snode = CTX_wm_space_node(C);
657         int in_out= -1;
658         char name[32]= "";
659         int type= SOCK_VALUE;
660         bNodeTree *ngroup= snode->edittree;
661         bNodeSocket *sock;
662         
663         ED_preview_kill_jobs(C);
664         
665         if (RNA_property_is_set(op->ptr, "name"))
666                 RNA_string_get(op->ptr, "name", name);
667         
668         if (RNA_property_is_set(op->ptr, "type"))
669                 type = RNA_enum_get(op->ptr, "type");
670         
671         if (RNA_property_is_set(op->ptr, "in_out"))
672                 in_out = RNA_enum_get(op->ptr, "in_out");
673         else
674                 return OPERATOR_CANCELLED;
675         
676         sock = nodeGroupAddSocket(ngroup, name, type, in_out);
677         
678         node_tree_verify_groups(snode->nodetree);
679         
680         snode_notify(C, snode);
681         
682         return OPERATOR_FINISHED;
683 }
684
685 void NODE_OT_group_socket_add(wmOperatorType *ot)
686 {
687         /* identifiers */
688         ot->name = "Add Group Socket";
689         ot->description = "Add node group socket";
690         ot->idname = "NODE_OT_group_socket_add";
691         
692         /* api callbacks */
693         ot->exec = node_group_socket_add_exec;
694         ot->poll = ED_operator_node_active;
695         
696         /* flags */
697         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
698         
699         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
700         RNA_def_string(ot->srna, "name", "", 32, "Name", "Group socket name");
701         RNA_def_enum(ot->srna, "type", node_socket_type_items, SOCK_VALUE, "Type", "Type of the group socket");
702 }
703
704 /* ***************** Remove Group Socket operator ************* */
705
706 static int node_group_socket_remove_exec(bContext *C, wmOperator *op)
707 {
708         SpaceNode *snode = CTX_wm_space_node(C);
709         int index= -1;
710         int in_out= -1;
711         bNodeTree *ngroup= snode->edittree;
712         bNodeSocket *sock;
713         
714         ED_preview_kill_jobs(C);
715         
716         if (RNA_property_is_set(op->ptr, "index"))
717                 index = RNA_int_get(op->ptr, "index");
718         else
719                 return OPERATOR_CANCELLED;
720         
721         if (RNA_property_is_set(op->ptr, "in_out"))
722                 in_out = RNA_enum_get(op->ptr, "in_out");
723         else
724                 return OPERATOR_CANCELLED;
725         
726         sock = (bNodeSocket*)BLI_findlink(in_out==SOCK_IN ? &ngroup->inputs : &ngroup->outputs, index);
727         if (sock) {
728                 nodeGroupRemoveSocket(ngroup, sock, in_out);
729                 node_tree_verify_groups(snode->nodetree);
730                 
731                 snode_notify(C, snode);
732         }
733         
734         return OPERATOR_FINISHED;
735 }
736
737 void NODE_OT_group_socket_remove(wmOperatorType *ot)
738 {
739         /* identifiers */
740         ot->name = "Remove Group Socket";
741         ot->description = "Removed node group socket";
742         ot->idname = "NODE_OT_group_socket_remove";
743         
744         /* api callbacks */
745         ot->exec = node_group_socket_remove_exec;
746         ot->poll = ED_operator_node_active;
747         
748         /* flags */
749         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
750         
751         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
752         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
753 }
754
755 /* ***************** Move Group Socket Up operator ************* */
756
757 static int node_group_socket_move_up_exec(bContext *C, wmOperator *op)
758 {
759         SpaceNode *snode = CTX_wm_space_node(C);
760         int index= -1;
761         int in_out= -1;
762         bNodeTree *ngroup= snode->edittree;
763         bNodeSocket *sock, *prev;
764         
765         ED_preview_kill_jobs(C);
766         
767         if (RNA_property_is_set(op->ptr, "index"))
768                 index = RNA_int_get(op->ptr, "index");
769         else
770                 return OPERATOR_CANCELLED;
771         
772         if (RNA_property_is_set(op->ptr, "in_out"))
773                 in_out = RNA_enum_get(op->ptr, "in_out");
774         else
775                 return OPERATOR_CANCELLED;
776         
777         /* swap */
778         if (in_out==SOCK_IN) {
779                 sock = (bNodeSocket*)BLI_findlink(&ngroup->inputs, index);
780                 prev = sock->prev;
781                 /* can't move up the first socket */
782                 if (!prev)
783                         return OPERATOR_CANCELLED;
784                 BLI_remlink(&ngroup->inputs, sock);
785                 BLI_insertlinkbefore(&ngroup->inputs, prev, sock);
786         }
787         else if (in_out==SOCK_OUT) {
788                 sock = (bNodeSocket*)BLI_findlink(&ngroup->outputs, index);
789                 prev = sock->prev;
790                 /* can't move up the first socket */
791                 if (!prev)
792                         return OPERATOR_CANCELLED;
793                 BLI_remlink(&ngroup->outputs, sock);
794                 BLI_insertlinkbefore(&ngroup->outputs, prev, sock);
795         }
796         node_tree_verify_groups(snode->nodetree);
797         
798         snode_notify(C, snode);
799         
800         return OPERATOR_FINISHED;
801 }
802
803 void NODE_OT_group_socket_move_up(wmOperatorType *ot)
804 {
805         /* identifiers */
806         ot->name = "Move Group Socket Up";
807         ot->description = "Move up node group socket";
808         ot->idname = "NODE_OT_group_socket_move_up";
809         
810         /* api callbacks */
811         ot->exec = node_group_socket_move_up_exec;
812         ot->poll = ED_operator_node_active;
813         
814         /* flags */
815         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
816         
817         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
818         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
819 }
820
821 /* ***************** Move Group Socket Up operator ************* */
822
823 static int node_group_socket_move_down_exec(bContext *C, wmOperator *op)
824 {
825         SpaceNode *snode = CTX_wm_space_node(C);
826         int index= -1;
827         int in_out= -1;
828         bNodeTree *ngroup= snode->edittree;
829         bNodeSocket *sock, *next;
830         
831         ED_preview_kill_jobs(C);
832         
833         if (RNA_property_is_set(op->ptr, "index"))
834                 index = RNA_int_get(op->ptr, "index");
835         else
836                 return OPERATOR_CANCELLED;
837         
838         if (RNA_property_is_set(op->ptr, "in_out"))
839                 in_out = RNA_enum_get(op->ptr, "in_out");
840         else
841                 return OPERATOR_CANCELLED;
842         
843         /* swap */
844         if (in_out==SOCK_IN) {
845                 sock = (bNodeSocket*)BLI_findlink(&ngroup->inputs, index);
846                 next = sock->next;
847                 /* can't move down the last socket */
848                 if (!next)
849                         return OPERATOR_CANCELLED;
850                 BLI_remlink(&ngroup->inputs, sock);
851                 BLI_insertlinkafter(&ngroup->inputs, next, sock);
852         }
853         else if (in_out==SOCK_OUT) {
854                 sock = (bNodeSocket*)BLI_findlink(&ngroup->outputs, index);
855                 next = sock->next;
856                 /* can't move down the last socket */
857                 if (!next)
858                         return OPERATOR_CANCELLED;
859                 BLI_remlink(&ngroup->outputs, sock);
860                 BLI_insertlinkafter(&ngroup->outputs, next, sock);
861         }
862         node_tree_verify_groups(snode->nodetree);
863         
864         snode_notify(C, snode);
865         
866         return OPERATOR_FINISHED;
867 }
868
869 void NODE_OT_group_socket_move_down(wmOperatorType *ot)
870 {
871         /* identifiers */
872         ot->name = "Move Group Socket Down";
873         ot->description = "Move down node group socket";
874         ot->idname = "NODE_OT_group_socket_move_down";
875         
876         /* api callbacks */
877         ot->exec = node_group_socket_move_down_exec;
878         ot->poll = ED_operator_node_active;
879         
880         /* flags */
881         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
882         
883         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
884         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
885 }
886
887 /* ******************** Ungroup operator ********************** */
888
889 static int node_group_ungroup_exec(bContext *C, wmOperator *op)
890 {
891         SpaceNode *snode = CTX_wm_space_node(C);
892         bNode *gnode;
893
894         ED_preview_kill_jobs(C);
895
896         /* are we inside of a group? */
897         gnode= node_tree_get_editgroup(snode->nodetree);
898         if(gnode)
899                 snode_make_group_editable(snode, NULL);
900         
901         gnode= nodeGetActive(snode->edittree);
902         if(gnode==NULL)
903                 return OPERATOR_CANCELLED;
904         
905         if(gnode->type!=NODE_GROUP) {
906                 BKE_report(op->reports, RPT_WARNING, "Not a group");
907                 return OPERATOR_CANCELLED;
908         }
909         else if(!nodeGroupUnGroup(snode->edittree, gnode)) {
910                 BKE_report(op->reports, RPT_WARNING, "Can't ungroup");
911                 return OPERATOR_CANCELLED;
912         }
913
914         snode_notify(C, snode);
915         snode_dag_update(C, snode);
916
917         return OPERATOR_FINISHED;
918 }
919
920 void NODE_OT_group_ungroup(wmOperatorType *ot)
921 {
922         /* identifiers */
923         ot->name = "Ungroup";
924         ot->description = "Ungroup selected nodes";
925         ot->idname = "NODE_OT_group_ungroup";
926         
927         /* api callbacks */
928         ot->exec = node_group_ungroup_exec;
929         ot->poll = ED_operator_node_active;
930         
931         /* flags */
932         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
933 }
934
935 /* ************************** Node generic ************** */
936
937 /* allows to walk the list in order of visibility */
938 bNode *next_node(bNodeTree *ntree)
939 {
940         static bNode *current=NULL, *last= NULL;
941         
942         if(ntree) {
943                 /* set current to the first selected node */
944                 for(current= ntree->nodes.last; current; current= current->prev)
945                         if(current->flag & NODE_SELECT)
946                                 break;
947                 
948                 /* set last to the first unselected node */
949                 for(last= ntree->nodes.last; last; last= last->prev)
950                         if((last->flag & NODE_SELECT)==0)
951                                 break;
952                 
953                 if(current==NULL)
954                         current= last;
955                 
956                 return NULL;
957         }
958         /* no nodes, or we are ready */
959         if(current==NULL)
960                 return NULL;
961         
962         /* now we walk the list backwards, but we always return current */
963         if(current->flag & NODE_SELECT) {
964                 bNode *node= current;
965                 
966                 /* find previous selected */
967                 current= current->prev;
968                 while(current && (current->flag & NODE_SELECT)==0)
969                         current= current->prev;
970                 
971                 /* find first unselected */
972                 if(current==NULL)
973                         current= last;
974                 
975                 return node;
976         }
977         else {
978                 bNode *node= current;
979                 
980                 /* find previous unselected */
981                 current= current->prev;
982                 while(current && (current->flag & NODE_SELECT))
983                         current= current->prev;
984                 
985                 return node;
986         }
987         
988         return NULL;
989 }
990
991 /* is rct in visible part of node? */
992 static bNode *visible_node(SpaceNode *snode, rctf *rct)
993 {
994         bNode *tnode;
995         
996         for(next_node(snode->edittree); (tnode=next_node(NULL));) {
997                 if(BLI_isect_rctf(&tnode->totr, rct, NULL))
998                         break;
999         }
1000         return tnode;
1001 }
1002
1003 /* **************************** */
1004
1005 typedef struct NodeViewMove {
1006         int mvalo[2];
1007         int xmin, ymin, xmax, ymax;
1008 } NodeViewMove;
1009
1010 static int snode_bg_viewmove_modal(bContext *C, wmOperator *op, wmEvent *event)
1011 {
1012         SpaceNode *snode= CTX_wm_space_node(C);
1013         ARegion *ar= CTX_wm_region(C);
1014         NodeViewMove *nvm= op->customdata;
1015
1016         switch (event->type) {
1017                 case MOUSEMOVE:
1018                         
1019                         snode->xof -= (nvm->mvalo[0]-event->mval[0]);
1020                         snode->yof -= (nvm->mvalo[1]-event->mval[1]);
1021                         nvm->mvalo[0]= event->mval[0];
1022                         nvm->mvalo[1]= event->mval[1];
1023                         
1024                         /* prevent dragging image outside of the window and losing it! */
1025                         CLAMP(snode->xof, nvm->xmin, nvm->xmax);
1026                         CLAMP(snode->yof, nvm->ymin, nvm->ymax);
1027                         
1028                         ED_region_tag_redraw(ar);
1029                         
1030                         break;
1031                         
1032                 case LEFTMOUSE:
1033                 case MIDDLEMOUSE:
1034                 case RIGHTMOUSE:
1035                         
1036                         MEM_freeN(nvm);
1037                         op->customdata= NULL;
1038
1039                         WM_event_add_notifier(C, NC_SPACE|ND_SPACE_NODE, NULL);
1040                         
1041                         return OPERATOR_FINISHED;
1042         }
1043         
1044         return OPERATOR_RUNNING_MODAL;
1045 }
1046
1047 static int snode_bg_viewmove_invoke(bContext *C, wmOperator *op, wmEvent *event)
1048 {
1049         ARegion *ar= CTX_wm_region(C);
1050         NodeViewMove *nvm;
1051         Image *ima;
1052         ImBuf *ibuf;
1053         int pad= 10;
1054         void *lock;
1055         
1056         ima= BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
1057         ibuf= BKE_image_acquire_ibuf(ima, NULL, &lock);
1058         
1059         if(ibuf == NULL) {
1060                 BKE_image_release_ibuf(ima, lock);
1061                 return OPERATOR_CANCELLED;
1062         }
1063
1064         nvm= MEM_callocN(sizeof(NodeViewMove), "NodeViewMove struct");
1065         op->customdata= nvm;
1066         nvm->mvalo[0]= event->mval[0];
1067         nvm->mvalo[1]= event->mval[1];
1068
1069         nvm->xmin = -(ar->winx/2) - ibuf->x/2 + pad;
1070         nvm->xmax = ar->winx/2 + ibuf->x/2 - pad;
1071         nvm->ymin = -(ar->winy/2) - ibuf->y/2 + pad;
1072         nvm->ymax = ar->winy/2 + ibuf->y/2 - pad;
1073
1074         BKE_image_release_ibuf(ima, lock);
1075         
1076         /* add modal handler */
1077         WM_event_add_modal_handler(C, op);
1078         
1079         return OPERATOR_RUNNING_MODAL;
1080 }
1081
1082 static int snode_bg_viewmove_cancel(bContext *UNUSED(C), wmOperator *op)
1083 {
1084         MEM_freeN(op->customdata);
1085         op->customdata= NULL;
1086
1087         return OPERATOR_CANCELLED;
1088 }
1089
1090 void NODE_OT_backimage_move(wmOperatorType *ot)
1091 {
1092         /* identifiers */
1093         ot->name= "Background Image Move";
1094         ot->description = "Move Node backdrop";
1095         ot->idname= "NODE_OT_backimage_move";
1096         
1097         /* api callbacks */
1098         ot->invoke= snode_bg_viewmove_invoke;
1099         ot->modal= snode_bg_viewmove_modal;
1100         ot->poll= composite_node_active;
1101         ot->cancel= snode_bg_viewmove_cancel;
1102         
1103         /* flags */
1104         ot->flag= OPTYPE_BLOCKING|OPTYPE_GRAB_POINTER;
1105 }
1106
1107 static int backimage_zoom(bContext *C, wmOperator *op)
1108 {
1109         SpaceNode *snode= CTX_wm_space_node(C);
1110         ARegion *ar= CTX_wm_region(C);
1111         float fac= RNA_float_get(op->ptr, "factor");
1112
1113         snode->zoom *= fac;
1114         ED_region_tag_redraw(ar);
1115
1116         return OPERATOR_FINISHED;
1117 }
1118
1119
1120 void NODE_OT_backimage_zoom(wmOperatorType *ot)
1121 {
1122         
1123         /* identifiers */
1124         ot->name= "Background Image Zoom";
1125         ot->idname= "NODE_OT_backimage_zoom";
1126         
1127         /* api callbacks */
1128         ot->exec= backimage_zoom;
1129         ot->poll= composite_node_active;
1130         
1131         /* flags */
1132         ot->flag= OPTYPE_BLOCKING;
1133
1134         /* internal */
1135         RNA_def_float(ot->srna, "factor", 1.2f, 0.0f, 10.0f, "Factor", "", 0.0f, 10.0f);
1136 }
1137
1138 /******************** sample backdrop operator ********************/
1139
1140 typedef struct ImageSampleInfo {
1141         ARegionType *art;
1142         void *draw_handle;
1143         int x, y;
1144         int channels;
1145         int color_manage;
1146
1147         char col[4];
1148         float colf[4];
1149
1150         int draw;
1151 } ImageSampleInfo;
1152
1153 static void sample_draw(const bContext *C, ARegion *ar, void *arg_info)
1154 {
1155         ImageSampleInfo *info= arg_info;
1156
1157         draw_nodespace_color_info(ar, (CTX_data_scene(C)->r.color_mgt_flag & R_COLOR_MANAGEMENT), info->channels,
1158                                                           info->x, info->y, info->col, info->colf);
1159 }
1160
1161 static void sample_apply(bContext *C, wmOperator *op, wmEvent *event)
1162 {
1163         SpaceNode *snode= CTX_wm_space_node(C);
1164         ARegion *ar= CTX_wm_region(C);
1165         ImageSampleInfo *info= op->customdata;
1166         void *lock;
1167         Image *ima;
1168         ImBuf *ibuf;
1169         float fx, fy, bufx, bufy;
1170         
1171         ima= BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
1172         ibuf= BKE_image_acquire_ibuf(ima, NULL, &lock);
1173         if(!ibuf)
1174                 return;
1175         
1176         if(!ibuf->rect) {
1177                 if(info->color_manage)
1178                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1179                 else
1180                         ibuf->profile = IB_PROFILE_NONE;
1181                 IMB_rect_from_float(ibuf);
1182         }
1183
1184         /* map the mouse coords to the backdrop image space */
1185         bufx = ibuf->x * snode->zoom;
1186         bufy = ibuf->y * snode->zoom;
1187         fx = (bufx > 0.0f ? ((float)event->mval[0] - 0.5f*ar->winx - snode->xof) / bufx + 0.5f : 0.0f);
1188         fy = (bufy > 0.0f ? ((float)event->mval[1] - 0.5f*ar->winy - snode->yof) / bufy + 0.5f : 0.0f);
1189
1190         if(fx>=0.0f && fy>=0.0f && fx<1.0f && fy<1.0f) {
1191                 float *fp;
1192                 char *cp;
1193                 int x= (int)(fx*ibuf->x), y= (int)(fy*ibuf->y);
1194
1195                 CLAMP(x, 0, ibuf->x-1);
1196                 CLAMP(y, 0, ibuf->y-1);
1197
1198                 info->x= x;
1199                 info->y= y;
1200                 info->draw= 1;
1201                 info->channels= ibuf->channels;
1202
1203                 if(ibuf->rect) {
1204                         cp= (char *)(ibuf->rect + y*ibuf->x + x);
1205
1206                         info->col[0]= cp[0];
1207                         info->col[1]= cp[1];
1208                         info->col[2]= cp[2];
1209                         info->col[3]= cp[3];
1210
1211                         info->colf[0]= (float)cp[0]/255.0f;
1212                         info->colf[1]= (float)cp[1]/255.0f;
1213                         info->colf[2]= (float)cp[2]/255.0f;
1214                         info->colf[3]= (float)cp[3]/255.0f;
1215                 }
1216                 if(ibuf->rect_float) {
1217                         fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
1218
1219                         info->colf[0]= fp[0];
1220                         info->colf[1]= fp[1];
1221                         info->colf[2]= fp[2];
1222                         info->colf[3]= fp[3];
1223                 }
1224         }
1225         else
1226                 info->draw= 0;
1227
1228         BKE_image_release_ibuf(ima, lock);
1229         
1230         ED_area_tag_redraw(CTX_wm_area(C));
1231 }
1232
1233 static void sample_exit(bContext *C, wmOperator *op)
1234 {
1235         ImageSampleInfo *info= op->customdata;
1236
1237         ED_region_draw_cb_exit(info->art, info->draw_handle);
1238         ED_area_tag_redraw(CTX_wm_area(C));
1239         MEM_freeN(info);
1240 }
1241
1242 static int sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1243 {
1244         SpaceNode *snode= CTX_wm_space_node(C);
1245         ARegion *ar= CTX_wm_region(C);
1246         ImageSampleInfo *info;
1247
1248         if(snode->treetype!=NTREE_COMPOSIT || !(snode->flag & SNODE_BACKDRAW))
1249                 return OPERATOR_CANCELLED;
1250         
1251         info= MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
1252         info->art= ar->type;
1253         info->draw_handle = ED_region_draw_cb_activate(ar->type, sample_draw, info, REGION_DRAW_POST_PIXEL);
1254         op->customdata= info;
1255
1256         sample_apply(C, op, event);
1257
1258         WM_event_add_modal_handler(C, op);
1259
1260         return OPERATOR_RUNNING_MODAL;
1261 }
1262
1263 static int sample_modal(bContext *C, wmOperator *op, wmEvent *event)
1264 {
1265         switch(event->type) {
1266                 case LEFTMOUSE:
1267                 case RIGHTMOUSE: // XXX hardcoded
1268                         sample_exit(C, op);
1269                         return OPERATOR_CANCELLED;
1270                 case MOUSEMOVE:
1271                         sample_apply(C, op, event);
1272                         break;
1273         }
1274
1275         return OPERATOR_RUNNING_MODAL;
1276 }
1277
1278 static int sample_cancel(bContext *C, wmOperator *op)
1279 {
1280         sample_exit(C, op);
1281         return OPERATOR_CANCELLED;
1282 }
1283
1284 void NODE_OT_backimage_sample(wmOperatorType *ot)
1285 {
1286         /* identifiers */
1287         ot->name= "Backimage Sample";
1288         ot->idname= "NODE_OT_backimage_sample";
1289         
1290         /* api callbacks */
1291         ot->invoke= sample_invoke;
1292         ot->modal= sample_modal;
1293         ot->cancel= sample_cancel;
1294         ot->poll= ED_operator_node_active;
1295
1296         /* flags */
1297         ot->flag= OPTYPE_BLOCKING;
1298 }
1299
1300 /* ********************** size widget operator ******************** */
1301
1302 typedef struct NodeSizeWidget {
1303         float mxstart;
1304         float oldwidth;
1305 } NodeSizeWidget;
1306
1307 static int node_resize_modal(bContext *C, wmOperator *op, wmEvent *event)
1308 {
1309         SpaceNode *snode= CTX_wm_space_node(C);
1310         ARegion *ar= CTX_wm_region(C);
1311         bNode *node= editnode_get_active(snode->edittree);
1312         NodeSizeWidget *nsw= op->customdata;
1313         float mx, my;
1314         
1315         switch (event->type) {
1316                 case MOUSEMOVE:
1317                         
1318                         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
1319                                                                          &mx, &my);
1320                         
1321                         if (node) {
1322                                 if(node->flag & NODE_HIDDEN) {
1323                                         node->miniwidth= nsw->oldwidth + mx - nsw->mxstart;
1324                                         CLAMP(node->miniwidth, 0.0f, 100.0f);
1325                                 }
1326                                 else {
1327                                         node->width= nsw->oldwidth + mx - nsw->mxstart;
1328                                         CLAMP(node->width, UI_DPI_FAC*node->typeinfo->minwidth, UI_DPI_FAC*node->typeinfo->maxwidth);
1329                                 }
1330                         }
1331                                 
1332                         ED_region_tag_redraw(ar);
1333
1334                         break;
1335                         
1336                 case LEFTMOUSE:
1337                 case MIDDLEMOUSE:
1338                 case RIGHTMOUSE:
1339                         
1340                         MEM_freeN(nsw);
1341                         op->customdata= NULL;
1342                         
1343                         return OPERATOR_FINISHED;
1344         }
1345         
1346         return OPERATOR_RUNNING_MODAL;
1347 }
1348
1349 static int node_resize_invoke(bContext *C, wmOperator *op, wmEvent *event)
1350 {
1351         SpaceNode *snode= CTX_wm_space_node(C);
1352         ARegion *ar= CTX_wm_region(C);
1353         bNode *node= editnode_get_active(snode->edittree);
1354         
1355         if(node) {
1356                 rctf totr;
1357                 
1358                 /* convert mouse coordinates to v2d space */
1359                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
1360                                                                  &snode->mx, &snode->my);
1361                 
1362                 totr= node->totr;
1363                 
1364                 if(node->flag & NODE_HIDDEN) {
1365                         /* right part of node */
1366                         totr.xmin= node->totr.xmax-20.0f;
1367                 }
1368                 else {
1369                         /* bottom right corner */
1370                         totr.xmin= totr.xmax-10.0f;
1371                         totr.ymax= totr.ymin+10.0f;
1372                 }
1373                 
1374                 if(BLI_in_rctf(&totr, snode->mx, snode->my)) {
1375                         NodeSizeWidget *nsw= MEM_callocN(sizeof(NodeSizeWidget), "size widget op data");
1376                         
1377                         op->customdata= nsw;
1378                         nsw->mxstart= snode->mx;
1379                         
1380                         /* store old */
1381                         if(node->flag & NODE_HIDDEN)
1382                                 nsw->oldwidth= node->miniwidth;
1383                         else
1384                                 nsw->oldwidth= node->width;
1385                         
1386                         /* add modal handler */
1387                         WM_event_add_modal_handler(C, op);
1388
1389                         return OPERATOR_RUNNING_MODAL;
1390                 }
1391         }
1392         return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
1393 }
1394
1395 static int node_resize_cancel(bContext *UNUSED(C), wmOperator *op)
1396 {
1397         MEM_freeN(op->customdata);
1398         op->customdata= NULL;
1399
1400         return OPERATOR_CANCELLED;
1401 }
1402
1403 void NODE_OT_resize(wmOperatorType *ot)
1404 {
1405         /* identifiers */
1406         ot->name= "Resize Node";
1407         ot->idname= "NODE_OT_resize";
1408         
1409         /* api callbacks */
1410         ot->invoke= node_resize_invoke;
1411         ot->modal= node_resize_modal;
1412         ot->poll= ED_operator_node_active;
1413         ot->cancel= node_resize_cancel;
1414         
1415         /* flags */
1416         ot->flag= OPTYPE_BLOCKING;
1417 }
1418
1419 /* ********************** select ******************** */
1420
1421
1422 /* no undo here! */
1423 void node_deselectall(SpaceNode *snode)
1424 {
1425         bNode *node;
1426         
1427         for(node= snode->edittree->nodes.first; node; node= node->next)
1428                 node->flag &= ~SELECT;
1429 }
1430
1431 /* return 1 if we need redraw otherwise zero. */
1432 int node_select_same_type(SpaceNode *snode)
1433 {
1434         bNode *nac, *p;
1435         int redraw;
1436
1437         /* search for the active node. */
1438         for (nac= snode->edittree->nodes.first; nac; nac= nac->next) {
1439                 if (nac->flag & SELECT)
1440                         break;
1441         }
1442
1443         /* no active node, return. */
1444         if (!nac)
1445                 return(0);
1446
1447         redraw= 0;
1448         for (p= snode->edittree->nodes.first; p; p= p->next) {
1449                 if (p->type != nac->type && p->flag & SELECT) {
1450                         /* if it's selected but different type, unselect */
1451                         redraw= 1;
1452                         p->flag &= ~SELECT;
1453                 }
1454                 else if (p->type == nac->type && (!(p->flag & SELECT))) {
1455                         /* if it's the same type and is not selected, select! */
1456                         redraw= 1;
1457                         p->flag |= SELECT;
1458                 }
1459         }
1460         return(redraw);
1461 }
1462
1463 /* return 1 if we need redraw, otherwise zero.
1464  * dir can be 0 == next or 0 != prev.
1465  */
1466 int node_select_same_type_np(SpaceNode *snode, int dir)
1467 {
1468         bNode *nac, *p;
1469
1470         /* search the active one. */
1471         for (nac= snode->edittree->nodes.first; nac; nac= nac->next) {
1472                 if (nac->flag & SELECT)
1473                         break;
1474         }
1475
1476         /* no active node, return. */
1477         if (!nac)
1478                 return(0);
1479
1480         if (dir == 0)
1481                 p= nac->next;
1482         else
1483                 p= nac->prev;
1484
1485         while (p) {
1486                 /* Now search the next with the same type. */
1487                 if (p->type == nac->type)
1488                         break;
1489
1490                 if (dir == 0)
1491                         p= p->next;
1492                 else
1493                         p= p->prev;
1494         }
1495
1496         if (p) {
1497                 node_deselectall(snode);
1498                 p->flag |= SELECT;
1499                 return(1);
1500         }
1501         return(0);
1502 }
1503
1504 int node_has_hidden_sockets(bNode *node)
1505 {
1506         bNodeSocket *sock;
1507         
1508         for(sock= node->inputs.first; sock; sock= sock->next)
1509                 if(sock->flag & SOCK_HIDDEN)
1510                         return 1;
1511         for(sock= node->outputs.first; sock; sock= sock->next)
1512                 if(sock->flag & SOCK_HIDDEN)
1513                         return 1;
1514         return 0;
1515 }
1516
1517 static void node_link_viewer(SpaceNode *snode, bNode *tonode)
1518 {
1519         bNode *node;
1520
1521         /* context check */
1522         if(tonode==NULL || tonode->outputs.first==NULL)
1523                 return;
1524         if( ELEM(tonode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1525                 return;
1526         
1527         /* get viewer */
1528         for(node= snode->edittree->nodes.first; node; node= node->next)
1529                 if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1530                         if(node->flag & NODE_DO_OUTPUT)
1531                                 break;
1532         /* no viewer, we make one active */
1533         if(node==NULL) {
1534                 for(node= snode->edittree->nodes.first; node; node= node->next) {
1535                         if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
1536                                 node->flag |= NODE_DO_OUTPUT;
1537                                 break;
1538                         }
1539                 }
1540         }
1541                 
1542         if(node) {
1543                 bNodeLink *link;
1544                 bNodeSocket *sock= NULL;
1545
1546                 /* try to find an already connected socket to cycle to the next */
1547                 for(link= snode->edittree->links.first; link; link= link->next)
1548                         if(link->tonode==node && link->fromnode==tonode)
1549                                 if(link->tosock==node->inputs.first)
1550                                         break;
1551
1552                 if(link) {
1553                         /* unlink existing connection */
1554                         sock= link->fromsock;
1555                         nodeRemLink(snode->edittree, link);
1556
1557                         /* find a socket after the previously connected socket */
1558                         for(sock=sock->next; sock; sock= sock->next)
1559                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL)))
1560                                         break;
1561                 }
1562
1563                 /* find a socket starting from the first socket */
1564                 if(!sock) {
1565                         for(sock= tonode->outputs.first; sock; sock= sock->next)
1566                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL)))
1567                                         break;
1568                 }
1569                 
1570                 if(sock) {
1571                         /* get link to viewer */
1572                         for(link= snode->edittree->links.first; link; link= link->next)
1573                                 if(link->tonode==node && link->tosock==node->inputs.first)
1574                                         break;
1575                         
1576                         if(link==NULL) {
1577                                 nodeAddLink(snode->edittree, tonode, sock, node, node->inputs.first);
1578                         }
1579                         else {
1580                                 link->fromnode= tonode;
1581                                 link->fromsock= sock;
1582                         }
1583                         ntreeSolveOrder(snode->edittree);
1584                         snode_tag_changed(snode, node);
1585                 }
1586         }
1587 }
1588
1589
1590 static int node_active_link_viewer(bContext *C, wmOperator *UNUSED(op))
1591 {
1592         SpaceNode *snode= CTX_wm_space_node(C);
1593         bNode *node;
1594         
1595         node= editnode_get_active(snode->edittree);
1596         
1597         if(!node)
1598                 return OPERATOR_CANCELLED;
1599
1600         ED_preview_kill_jobs(C);
1601
1602         node_link_viewer(snode, node);
1603         snode_notify(C, snode);
1604
1605         return OPERATOR_FINISHED;
1606 }
1607
1608
1609
1610 void NODE_OT_link_viewer(wmOperatorType *ot)
1611 {
1612         /* identifiers */
1613         ot->name= "Link to Viewer Node";
1614         ot->description = "Link to Viewer Node";
1615         ot->idname= "NODE_OT_link_viewer";
1616         
1617         /* api callbacks */
1618         ot->exec= node_active_link_viewer;
1619         ot->poll= ED_operator_node_active;
1620         
1621         /* flags */
1622         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1623 }
1624
1625
1626
1627 /* return 0, nothing done */
1628 static int node_mouse_groupheader(SpaceNode *snode)
1629 {
1630         bNode *gnode;
1631         float mx=0, my=0;
1632 // XXX  int mval[2];
1633         
1634         gnode= node_tree_get_editgroup(snode->nodetree);
1635         if(gnode==NULL) return 0;
1636         
1637 // XXX  getmouseco_areawin(mval);
1638 // XXX  areamouseco_to_ipoco(G.v2d, mval, &mx, &my);
1639         
1640         /* click in header or outside? */
1641         if(BLI_in_rctf(&gnode->totr, mx, my)==0) {
1642                 rctf rect= gnode->totr;
1643                 
1644                 rect.ymax += NODE_DY;
1645                 if(BLI_in_rctf(&rect, mx, my)==0)
1646                         snode_make_group_editable(snode, NULL); /* toggles, so exits editmode */
1647 //              else
1648 // XXX                  transform_nodes(snode->nodetree, 'g', "Move group");
1649                 
1650                 return 1;
1651         }
1652         return 0;
1653 }
1654
1655 /* checks snode->mouse position, and returns found node/socket */
1656 /* type is SOCK_IN and/or SOCK_OUT */
1657 static int find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **sockp, int in_out)
1658 {
1659         bNode *node;
1660         bNodeSocket *sock;
1661         rctf rect;
1662         
1663         /* check if we click in a socket */
1664         for(node= snode->edittree->nodes.first; node; node= node->next) {
1665                 
1666                 rect.xmin = snode->mx - (NODE_SOCKSIZE+4);
1667                 rect.ymin = snode->my - (NODE_SOCKSIZE+4);
1668                 rect.xmax = snode->mx + (NODE_SOCKSIZE+4);
1669                 rect.ymax = snode->my + (NODE_SOCKSIZE+4);
1670                 
1671                 if (!(node->flag & NODE_HIDDEN)) {
1672                         /* extra padding inside and out - allow dragging on the text areas too */
1673                         if (in_out == SOCK_IN) {
1674                                 rect.xmax += NODE_SOCKSIZE;
1675                                 rect.xmin -= NODE_SOCKSIZE*4;
1676                         } else if (in_out == SOCK_OUT) {
1677                                 rect.xmax += NODE_SOCKSIZE*4;
1678                                 rect.xmin -= NODE_SOCKSIZE;
1679                         }
1680                 }
1681                 
1682                 if(in_out & SOCK_IN) {
1683                         for(sock= node->inputs.first; sock; sock= sock->next) {
1684                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1685                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1686                                                 if(node == visible_node(snode, &rect)) {
1687                                                         *nodep= node;
1688                                                         *sockp= sock;
1689                                                         return 1;
1690                                                 }
1691                                         }
1692                                 }
1693                         }
1694                 }
1695                 if(in_out & SOCK_OUT) {
1696                         for(sock= node->outputs.first; sock; sock= sock->next) {
1697                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1698                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1699                                                 if(node == visible_node(snode, &rect)) {
1700                                                         *nodep= node;
1701                                                         *sockp= sock;
1702                                                         return 1;
1703                                                 }
1704                                         }
1705                                 }
1706                         }
1707                 }
1708         }
1709         
1710         /* check group sockets
1711          * NB: using ngroup->outputs as input sockets and vice versa here!
1712          */
1713         if(in_out & SOCK_IN) {
1714                 for(sock= snode->edittree->outputs.first; sock; sock= sock->next) {
1715                         if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1716                                 if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1717                                         *nodep= NULL;   /* NULL node pointer indicates group socket */
1718                                         *sockp= sock;
1719                                         return 1;
1720                                 }
1721                         }
1722                 }
1723         }
1724         if(in_out & SOCK_OUT) {
1725                 for(sock= snode->edittree->inputs.first; sock; sock= sock->next) {
1726                         if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1727                                 if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1728                                         *nodep= NULL;   /* NULL node pointer indicates group socket */
1729                                         *sockp= sock;
1730                                         return 1;
1731                                 }
1732                         }
1733                 }
1734         }
1735         
1736         return 0;
1737 }
1738
1739 static int node_socket_hilights(SpaceNode *snode, int in_out)
1740 {
1741         bNode *node;
1742         bNodeSocket *sock, *tsock, *socksel= NULL;
1743         short redraw= 0;
1744         
1745         if(snode->edittree==NULL) return 0;
1746         
1747         /* deselect sockets */
1748         for(node= snode->edittree->nodes.first; node; node= node->next) {
1749                 for(sock= node->inputs.first; sock; sock= sock->next) {
1750                         if(sock->flag & SELECT) {
1751                                 sock->flag &= ~SELECT;
1752                                 redraw++;
1753                                 socksel= sock;
1754                         }
1755                 }
1756                 for(sock= node->outputs.first; sock; sock= sock->next) {
1757                         if(sock->flag & SELECT) {
1758                                 sock->flag &= ~SELECT;
1759                                 redraw++;
1760                                 socksel= sock;
1761                         }
1762                 }
1763         }
1764         
1765         // XXX mousepos should be set here!
1766         
1767         if(find_indicated_socket(snode, &node, &tsock, in_out)) {
1768                 tsock->flag |= SELECT;
1769                 if(redraw==1 && tsock==socksel) redraw= 0;
1770                 else redraw= 1;
1771         }
1772         
1773         return redraw;
1774 }
1775
1776 static int outside_group_rect(SpaceNode *snode)
1777 {
1778         bNode *gnode= node_tree_get_editgroup(snode->nodetree);
1779         if (gnode) {
1780                 return (snode->mx < gnode->totr.xmin || snode->mx >= gnode->totr.xmax
1781                                 || snode->my < gnode->totr.ymin || snode->my >= gnode->totr.ymax);
1782         }
1783         return 0;
1784 }
1785
1786 /* ****************** Add *********************** */
1787
1788
1789 typedef struct bNodeListItem {
1790         struct bNodeListItem *next, *prev;
1791         struct bNode *node;     
1792 } bNodeListItem;
1793
1794 static int sort_nodes_locx(void *a, void *b)
1795 {
1796         bNodeListItem *nli1 = (bNodeListItem *)a;
1797         bNodeListItem *nli2 = (bNodeListItem *)b;
1798         bNode *node1 = nli1->node;
1799         bNode *node2 = nli2->node;
1800         
1801         if (node1->locx > node2->locx)
1802                 return 1;
1803         else 
1804                 return 0;
1805 }
1806
1807 static int socket_is_available(bNodeTree *ntree, bNodeSocket *sock, int allow_used)
1808 {
1809         if (sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))
1810                 return 0;
1811         
1812         if (!allow_used) {
1813                 if (nodeCountSocketLinks(ntree, sock) > 0)
1814                         return 0;
1815         }
1816         return 1;
1817 }
1818
1819 static bNodeSocket *best_socket_output(bNodeTree *ntree, bNode *node, bNodeSocket *sock_target, int allow_multiple)
1820 {
1821         bNodeSocket *sock;
1822         
1823         /* first try to find a socket with a matching name */
1824         for (sock=node->outputs.first; sock; sock=sock->next) {
1825
1826                 if (!socket_is_available(ntree, sock, allow_multiple))
1827                         continue;
1828
1829                 /* check for same types */
1830                 if (sock->type == sock_target->type) {
1831                         if (strcmp(sock->name, sock_target->name)==0)
1832                                 return sock;
1833                 }
1834         }
1835         
1836         /* otherwise settle for the first available socket of the right type */
1837         for (sock=node->outputs.first; sock; sock=sock->next) {
1838
1839                 if (!socket_is_available(ntree, sock, allow_multiple))
1840                         continue;
1841                 
1842                 /* check for same types */
1843                 if (sock->type == sock_target->type) {
1844                         return sock;
1845                 }
1846         }
1847         
1848         return NULL;
1849 }
1850
1851 /* this is a bit complicated, but designed to prioritise finding 
1852  * sockets of higher types, such as image, first */
1853 static bNodeSocket *best_socket_input(bNodeTree *ntree, bNode *node, int num, int replace)
1854 {
1855         bNodeSocket *sock;
1856         int socktype, maxtype=0;
1857         int a = 0;
1858         
1859         for (sock=node->inputs.first; sock; sock=sock->next) {
1860                 maxtype = MAX2(sock->type, maxtype);
1861         }
1862         
1863         /* find sockets of higher 'types' first (i.e. image) */
1864         for (socktype=maxtype; socktype >= 0; socktype--) {
1865                 for (sock=node->inputs.first; sock; sock=sock->next) {
1866                         
1867                         if (!socket_is_available(ntree, sock, replace)) {
1868                                 a++;
1869                                 continue;
1870                         }
1871                                 
1872                         if (sock->type == socktype) {
1873                                 /* increment to make sure we don't keep finding 
1874                                  * the same socket on every attempt running this function */
1875                                 a++;
1876                                 if (a > num)
1877                                         return sock;
1878                         }
1879                 }
1880         }
1881         
1882         return NULL;
1883 }
1884
1885 void snode_autoconnect(SpaceNode *snode, int allow_multiple, int replace)
1886 {
1887         ListBase *nodelist = MEM_callocN(sizeof(ListBase), "items_list");
1888         bNodeListItem *nli;
1889         bNode *node;
1890         int i, numlinks=0;
1891         
1892         for(node= snode->edittree->nodes.first; node; node= node->next) {
1893                 if(node->flag & NODE_SELECT) {
1894                         nli = MEM_mallocN(sizeof(bNodeListItem), "temporary node list item");
1895                         nli->node = node;
1896                         BLI_addtail(nodelist, nli);
1897                 }
1898         }
1899         
1900         /* sort nodes left to right */
1901         BLI_sortlist(nodelist, sort_nodes_locx);
1902         
1903         for (nli=nodelist->first; nli; nli=nli->next) {
1904                 bNode *node_fr, *node_to;
1905                 bNodeSocket *sock_fr, *sock_to;
1906                 
1907                 if (nli->next == NULL) break;
1908                 
1909                 node_fr = nli->node;
1910                 node_to = nli->next->node;
1911                 
1912                 /* check over input sockets first */
1913                 for (i=0; i<BLI_countlist(&node_to->inputs); i++) {
1914                         
1915                         /* find the best guess input socket */
1916                         sock_to = best_socket_input(snode->edittree, node_to, i, replace);
1917                         if (!sock_to) continue;
1918                         
1919                         /* check for an appropriate output socket to connect from */
1920                         sock_fr = best_socket_output(snode->edittree, node_fr, sock_to, allow_multiple);
1921                         if (!sock_fr) continue;
1922                         
1923                         /* then we can connect */
1924                         if (replace)
1925                                 nodeRemSocketLinks(snode->edittree, sock_to);
1926                         nodeAddLink(snode->edittree, node_fr, sock_fr, node_to, sock_to);
1927                         snode_tag_changed(snode, node_to);
1928                         ++numlinks;
1929                         break;
1930                 }
1931         }
1932         
1933         if (numlinks > 0) {
1934                 node_tree_verify_groups(snode->nodetree);
1935                 ntreeSolveOrder(snode->edittree);
1936         }
1937         
1938         BLI_freelistN(nodelist);
1939         MEM_freeN(nodelist);
1940 }
1941
1942 /* can be called from menus too, but they should do own undopush and redraws */
1943 bNode *node_add_node(SpaceNode *snode, Scene *scene, int type, float locx, float locy)
1944 {
1945         bNode *node= NULL, *gnode;
1946         
1947         node_deselectall(snode);
1948         
1949         if(type>=NODE_DYNAMIC_MENU) {
1950                 node= nodeAddNodeType(snode->edittree, type, NULL, NULL);
1951         }
1952         else if(type>=NODE_GROUP_MENU) {
1953                 if(snode->edittree!=snode->nodetree) {
1954                         // XXX error("Can not add a Group in a Group");
1955                         return NULL;
1956                 }
1957                 else {
1958                         bNodeTree *ngroup= BLI_findlink(&G.main->nodetree, type-NODE_GROUP_MENU);
1959                         if(ngroup)
1960                                 node= nodeAddNodeType(snode->edittree, NODE_GROUP, ngroup, NULL);
1961                 }
1962         }
1963         else
1964                 node= nodeAddNodeType(snode->edittree, type, NULL, NULL);
1965         
1966         /* generics */
1967         if(node) {
1968                 node->locx= locx;
1969                 node->locy= locy + 60.0f;               // arbitrary.. so its visible, (0,0) is top of node
1970                 node->flag |= SELECT;
1971                 
1972                 gnode= node_tree_get_editgroup(snode->nodetree);
1973                 if(gnode) {
1974                         node->locx -= gnode->locx;
1975                         node->locy -= gnode->locy;
1976                 }
1977
1978                 node_tree_verify_groups(snode->nodetree);
1979                 node_set_active(snode, node);
1980                 
1981                 if(snode->nodetree->type==NTREE_COMPOSIT) {
1982                         if(ELEM4(node->type, CMP_NODE_R_LAYERS, CMP_NODE_COMPOSITE, CMP_NODE_DEFOCUS, CMP_NODE_OUTPUT_FILE))
1983                                 node->id = &scene->id;
1984                         
1985                         ntreeCompositForceHidden(snode->edittree, scene);
1986                 }
1987                         
1988                 if(node->id)
1989                         id_us_plus(node->id);
1990                         
1991                 snode_tag_changed(snode, node);
1992         }
1993         
1994         if(snode->nodetree->type==NTREE_TEXTURE) {
1995                 ntreeTexCheckCyclics(snode->edittree);
1996         }
1997         
1998         return node;
1999 }
2000
2001 /* ****************** Duplicate *********************** */
2002
2003 static int node_duplicate_exec(bContext *C, wmOperator *op)
2004 {
2005         SpaceNode *snode= CTX_wm_space_node(C);
2006         bNodeTree *ntree= snode->edittree;
2007         bNode *node, *newnode, *lastnode;
2008         bNodeLink *link, *newlink, *lastlink;
2009         int keep_inputs = RNA_boolean_get(op->ptr, "keep_inputs");
2010         
2011         ED_preview_kill_jobs(C);
2012         
2013         lastnode = ntree->nodes.last;
2014         for(node= ntree->nodes.first; node; node= node->next) {
2015                 if(node->flag & SELECT) {
2016                         newnode = nodeCopyNode(ntree, node);
2017                         
2018                         if(newnode->id) {
2019                                 /* simple id user adjustment, node internal functions dont touch this
2020                                  * but operators and readfile.c do. */
2021                                 id_us_plus(newnode->id);
2022                                 /* to ensure redraws or rerenders happen */
2023                                 ED_node_changed_update(snode->id, newnode);
2024                         }
2025                 }
2026                 
2027                 /* make sure we don't copy new nodes again! */
2028                 if (node==lastnode)
2029                         break;
2030         }
2031         
2032         /* copy links between selected nodes
2033          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
2034          */
2035         lastlink = ntree->links.last;
2036         for (link=ntree->links.first; link; link=link->next) {
2037                 /* This creates new links between copied nodes.
2038                  * If keep_inputs is set, also copies input links from unselected (when fromnode==NULL)!
2039                  */
2040                 if (link->tonode && (link->tonode->flag & NODE_SELECT)
2041                         && (keep_inputs || (link->fromnode && (link->fromnode->flag & NODE_SELECT)))) {
2042                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
2043                         newlink->flag = link->flag;
2044                         newlink->tonode = link->tonode->new_node;
2045                         newlink->tosock = link->tosock->new_sock;
2046                         if (link->fromnode && (link->fromnode->flag & NODE_SELECT)) {
2047                                 newlink->fromnode = link->fromnode->new_node;
2048                                 newlink->fromsock = link->fromsock->new_sock;
2049                         }
2050                         else {
2051                                 /* input node not copied, this keeps the original input linked */
2052                                 newlink->fromnode = link->fromnode;
2053                                 newlink->fromsock = link->fromsock;
2054                         }
2055                         
2056                         BLI_addtail(&ntree->links, newlink);
2057                 }
2058                 
2059                 /* make sure we don't copy new links again! */
2060                 if (link==lastlink)
2061                         break;
2062         }
2063         
2064         /* deselect old nodes, select the copies instead */
2065         for(node= ntree->nodes.first; node; node= node->next) {
2066                 if(node->flag & SELECT) {
2067                         /* has been set during copy above */
2068                         newnode = node->new_node;
2069                         
2070                         node->flag &= ~(NODE_SELECT|NODE_ACTIVE);
2071                         newnode->flag |= NODE_SELECT;
2072                 }
2073                 
2074                 /* make sure we don't copy new nodes again! */
2075                 if (node==lastnode)
2076                         break;
2077         }
2078         
2079         ntreeSolveOrder(ntree);
2080         
2081         node_tree_verify_groups(snode->nodetree);
2082         snode_notify(C, snode);
2083         snode_dag_update(C, snode);
2084
2085         return OPERATOR_FINISHED;
2086 }
2087
2088 void NODE_OT_duplicate(wmOperatorType *ot)
2089 {
2090         /* identifiers */
2091         ot->name= "Duplicate Nodes";
2092         ot->description = "Duplicate the nodes";
2093         ot->idname= "NODE_OT_duplicate";
2094         
2095         /* api callbacks */
2096         ot->exec= node_duplicate_exec;
2097         ot->poll= ED_operator_node_active;
2098         
2099         /* flags */
2100         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2101         
2102         RNA_def_boolean(ot->srna, "keep_inputs", 0, "Keep Inputs", "Keep the input links to duplicated nodes");
2103 }
2104
2105 /* *************************** add link op ******************** */
2106
2107 static void node_remove_extra_links(SpaceNode *snode, bNodeSocket *tsock, bNodeLink *link)
2108 {
2109         bNodeLink *tlink;
2110         bNodeSocket *sock;
2111         
2112         if(tsock && nodeCountSocketLinks(snode->edittree, link->tosock) > tsock->limit) {
2113                 
2114                 for(tlink= snode->edittree->links.first; tlink; tlink= tlink->next) {
2115                         if(link!=tlink && tlink->tosock==link->tosock)
2116                                 break;
2117                 }
2118                 if(tlink) {
2119                         /* try to move the existing link to the next available socket */
2120                         if (tlink->tonode) {
2121                                 /* is there a free input socket with the target type? */
2122                                 for(sock= tlink->tonode->inputs.first; sock; sock= sock->next) {
2123                                         if(sock->type==tlink->tosock->type)
2124                                                 if(nodeCountSocketLinks(snode->edittree, sock) < sock->limit)
2125                                                         break;
2126                                 }
2127                                 if(sock) {
2128                                         tlink->tosock= sock;
2129                                         sock->flag &= ~SOCK_HIDDEN;
2130                                 }
2131                                 else {
2132                                         nodeRemLink(snode->edittree, tlink);
2133                                 }
2134                         }
2135                         else
2136                                 nodeRemLink(snode->edittree, tlink);
2137                 }
2138         }
2139 }
2140
2141 /* loop that adds a nodelink, called by function below  */
2142 /* in_out = starting socket */
2143 static int node_link_modal(bContext *C, wmOperator *op, wmEvent *event)
2144 {
2145         SpaceNode *snode= CTX_wm_space_node(C);
2146         ARegion *ar= CTX_wm_region(C);
2147         bNodeLinkDrag *nldrag= op->customdata;
2148         bNode *tnode, *node;
2149         bNodeSocket *tsock= NULL, *sock;
2150         bNodeLink *link;
2151         int in_out;
2152
2153         in_out= nldrag->in_out;
2154         node= nldrag->node;
2155         sock= nldrag->sock;
2156         link= nldrag->link;
2157         
2158         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2159                                                          &snode->mx, &snode->my);
2160
2161         switch (event->type) {
2162                 case MOUSEMOVE:
2163                         
2164                         if(in_out==SOCK_OUT) {
2165                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_IN)) {
2166                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
2167                                                 if( link->tosock!= tsock && (!tnode || (tnode!=node && link->tonode!=tnode)) ) {
2168                                                         link->tonode= tnode;
2169                                                         link->tosock= tsock;
2170                                                         if (link->prev==NULL && link->next==NULL)
2171                                                                 BLI_addtail(&snode->edittree->links, link);
2172                                                         ntreeSolveOrder(snode->edittree);       /* for interactive red line warning */
2173                                                 }
2174                                         }
2175                                 }
2176                                 else {
2177                                         BLI_remlink(&snode->edittree->links, link);
2178                                         link->prev = link->next = NULL;
2179                                         link->tonode= NULL;
2180                                         link->tosock= NULL;
2181                                 }
2182                         }
2183                         else {
2184                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_OUT)) {
2185                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
2186                                                 if(nodeCountSocketLinks(snode->edittree, tsock) < tsock->limit) {
2187                                                         if( link->fromsock!= tsock && (!tnode || (tnode!=node && link->fromnode!=tnode)) ) {
2188                                                                 link->fromnode= tnode;
2189                                                                 link->fromsock= tsock;
2190                                                                 if (link->prev==NULL && link->next==NULL)
2191                                                                         BLI_addtail(&snode->edittree->links, link);
2192                                                                 ntreeSolveOrder(snode->edittree);       /* for interactive red line warning */
2193                                                         }
2194                                                 }
2195                                         }
2196                                 }
2197                                 else {
2198                                         BLI_remlink(&snode->edittree->links, link);
2199                                         link->prev = link->next = NULL;
2200                                         link->fromnode= NULL;
2201                                         link->fromsock= NULL;
2202                                 }
2203                         }
2204                         /* hilight target sockets only */
2205                         node_socket_hilights(snode, in_out==SOCK_OUT?SOCK_IN:SOCK_OUT);
2206                         ED_region_tag_redraw(ar);
2207                         break;
2208                         
2209                 case LEFTMOUSE:
2210                 case RIGHTMOUSE:
2211                 case MIDDLEMOUSE:
2212                         if(link->tosock && link->fromsock) {
2213                                 /* send changed events for original tonode and new */
2214                                 snode_tag_changed(snode, link->tonode);
2215                                 
2216                                 /* we might need to remove a link */
2217                                 if(in_out==SOCK_OUT)
2218                                         node_remove_extra_links(snode, link->tosock, link);
2219                                 
2220                                 /* when linking to group outputs, update the socket type */
2221                                 /* XXX this should all be part of a generic update system */
2222                                 if (!link->tonode) {
2223                                         link->tosock->type = link->fromsock->type;
2224                                 }
2225                         }
2226                         else if (outside_group_rect(snode) && (link->tonode || link->fromnode)) {
2227                                 /* automatically add new group socket */
2228                                 if (link->tonode && link->tosock) {
2229                                         link->fromsock = nodeGroupExposeSocket(snode->edittree, link->tosock, SOCK_IN);
2230                                         link->fromnode = NULL;
2231                                         if (link->prev==NULL && link->next==NULL)
2232                                                 BLI_addtail(&snode->edittree->links, link);
2233                                 }
2234                                 else if (link->fromnode && link->fromsock) {
2235                                         link->tosock = nodeGroupExposeSocket(snode->edittree, link->fromsock, SOCK_OUT);
2236                                         link->tonode = NULL;
2237                                         if (link->prev==NULL && link->next==NULL)
2238                                                 BLI_addtail(&snode->edittree->links, link);
2239                                 }
2240                         }
2241                         else
2242                                 nodeRemLink(snode->edittree, link);
2243                         
2244                         ntreeSolveOrder(snode->edittree);
2245                         node_tree_verify_groups(snode->nodetree);
2246                         snode_notify(C, snode);
2247                         snode_dag_update(C, snode);
2248                         
2249                         BLI_remlink(&snode->linkdrag, nldrag);
2250                         MEM_freeN(nldrag);
2251                         
2252                         return OPERATOR_FINISHED;
2253         }
2254         
2255         return OPERATOR_RUNNING_MODAL;
2256 }
2257
2258 /* return 1 when socket clicked */
2259 static int node_link_init(SpaceNode *snode, bNodeLinkDrag *nldrag)
2260 {
2261         bNodeLink *link;
2262
2263         /* output indicated? */
2264         if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_OUT)) {
2265                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2266                         return SOCK_OUT;
2267                 else {
2268                         /* find if we break a link */
2269                         for(link= snode->edittree->links.first; link; link= link->next) {
2270                                 if(link->fromsock==nldrag->sock)
2271                                         break;
2272                         }
2273                         if(link) {
2274                                 nldrag->node= link->tonode;
2275                                 nldrag->sock= link->tosock;
2276                                 nodeRemLink(snode->edittree, link);
2277                                 return SOCK_IN;
2278                         }
2279                 }
2280         }
2281         /* or an input? */
2282         else if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_IN)) {
2283                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2284                         return SOCK_IN;
2285                 else {
2286                         /* find if we break a link */
2287                         for(link= snode->edittree->links.first; link; link= link->next) {
2288                                 if(link->tosock==nldrag->sock)
2289                                         break;
2290                         }
2291                         if(link) {
2292                                 /* send changed event to original tonode */
2293                                 if(link->tonode) 
2294                                         snode_tag_changed(snode, link->tonode);
2295                                 
2296                                 nldrag->node= link->fromnode;
2297                                 nldrag->sock= link->fromsock;
2298                                 nodeRemLink(snode->edittree, link);
2299                                 return SOCK_OUT;
2300                         }
2301                 }
2302         }
2303         
2304         return 0;
2305 }
2306
2307 static int node_link_invoke(bContext *C, wmOperator *op, wmEvent *event)
2308 {
2309         SpaceNode *snode= CTX_wm_space_node(C);
2310         ARegion *ar= CTX_wm_region(C);
2311         bNodeLinkDrag *nldrag= MEM_callocN(sizeof(bNodeLinkDrag), "drag link op customdata");
2312         
2313         
2314         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2315                                                          &snode->mx, &snode->my);
2316
2317         ED_preview_kill_jobs(C);
2318
2319         nldrag->in_out= node_link_init(snode, nldrag);
2320                 
2321         if(nldrag->in_out) {
2322                 op->customdata= nldrag;
2323                 
2324                 /* we make a temporal link */
2325                 if(nldrag->in_out==SOCK_OUT) {
2326                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2327                         nldrag->link->fromnode= nldrag->node;
2328                         nldrag->link->fromsock= nldrag->sock;
2329                         nldrag->link->tonode= NULL;
2330                         nldrag->link->tosock= NULL;
2331                 }
2332                 else {
2333                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2334                         nldrag->link->fromnode= NULL;
2335                         nldrag->link->fromsock= NULL;
2336                         nldrag->link->tonode= nldrag->node;
2337                         nldrag->link->tosock= nldrag->sock;
2338                 }
2339                 BLI_addtail(&snode->linkdrag, nldrag);
2340                 
2341                 /* add modal handler */
2342                 WM_event_add_modal_handler(C, op);
2343                 
2344                 return OPERATOR_RUNNING_MODAL;
2345         }
2346         else {
2347                 MEM_freeN(nldrag);
2348                 return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2349         }
2350 }
2351
2352 static int node_link_cancel(bContext *C, wmOperator *op)
2353 {
2354         SpaceNode *snode= CTX_wm_space_node(C);
2355         bNodeLinkDrag *nldrag= op->customdata;
2356
2357         nodeRemLink(snode->edittree, nldrag->link);
2358         BLI_remlink(&snode->linkdrag, nldrag);
2359         MEM_freeN(nldrag);
2360
2361         return OPERATOR_CANCELLED;
2362 }
2363
2364 void NODE_OT_link(wmOperatorType *ot)
2365 {
2366         /* identifiers */
2367         ot->name= "Link Nodes";
2368         ot->idname= "NODE_OT_link";
2369         
2370         /* api callbacks */
2371         ot->invoke= node_link_invoke;
2372         ot->modal= node_link_modal;
2373 //      ot->exec= node_link_exec;
2374         ot->poll= ED_operator_node_active;
2375         ot->cancel= node_link_cancel;
2376         
2377         /* flags */
2378         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2379 }
2380
2381 /* ********************** Make Link operator ***************** */
2382
2383 /* makes a link between selected output and input sockets */
2384 static int node_make_link_exec(bContext *C, wmOperator *op)
2385 {
2386         SpaceNode *snode= CTX_wm_space_node(C);
2387         int replace = RNA_boolean_get(op->ptr, "replace");
2388
2389         ED_preview_kill_jobs(C);
2390
2391         snode_autoconnect(snode, 1, replace);
2392
2393         node_tree_verify_groups(snode->nodetree);
2394         snode_notify(C, snode);
2395         snode_dag_update(C, snode);
2396         
2397         return OPERATOR_FINISHED;
2398 }
2399
2400 void NODE_OT_link_make(wmOperatorType *ot)
2401 {
2402         /* identifiers */
2403         ot->name= "Make Links";
2404         ot->description= "Makes a link between selected output in input sockets";
2405         ot->idname= "NODE_OT_link_make";
2406         
2407         /* callbacks */
2408         ot->exec= node_make_link_exec;
2409         ot->poll= ED_operator_node_active; // XXX we need a special poll which checks that there are selected input/output sockets
2410         
2411         /* flags */
2412         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2413         
2414         RNA_def_boolean(ot->srna, "replace", 0, "Replace", "Replace socket connections with the new links");
2415 }
2416
2417 /* ********************** Cut Link operator ***************** */
2418
2419 #define LINK_RESOL 12
2420 static int cut_links_intersect(bNodeLink *link, float mcoords[][2], int tot)
2421 {
2422         float coord_array[LINK_RESOL+1][2];
2423         int i, b;
2424         
2425         if(node_link_bezier_points(NULL, NULL, link, coord_array, LINK_RESOL)) {
2426
2427                 for(i=0; i<tot-1; i++)
2428                         for(b=0; b<LINK_RESOL; b++)
2429                                 if(isect_line_line_v2(mcoords[i], mcoords[i+1], coord_array[b], coord_array[b+1]) > 0)
2430                                         return 1;
2431         }
2432         return 0;
2433 }
2434
2435 static int cut_links_exec(bContext *C, wmOperator *op)
2436 {
2437         SpaceNode *snode= CTX_wm_space_node(C);
2438         ARegion *ar= CTX_wm_region(C);
2439         float mcoords[256][2];
2440         int i= 0;
2441         
2442         RNA_BEGIN(op->ptr, itemptr, "path") {
2443                 float loc[2];
2444                 
2445                 RNA_float_get_array(&itemptr, "loc", loc);
2446                 UI_view2d_region_to_view(&ar->v2d, (short)loc[0], (short)loc[1], 
2447                                                                  &mcoords[i][0], &mcoords[i][1]);
2448                 i++;
2449                 if(i>= 256) break;
2450         }
2451         RNA_END;
2452         
2453         if(i>1) {
2454                 bNodeLink *link, *next;
2455
2456                 ED_preview_kill_jobs(C);
2457                 
2458                 for(link= snode->edittree->links.first; link; link= next) {
2459                         next= link->next;
2460                         
2461                         if(cut_links_intersect(link, mcoords, i)) {
2462                                 snode_tag_changed(snode, link->tonode);
2463                                 nodeRemLink(snode->edittree, link);
2464                         }
2465                 }
2466                 
2467                 ntreeSolveOrder(snode->edittree);
2468                 node_tree_verify_groups(snode->nodetree);
2469                 snode_notify(C, snode);
2470                 snode_dag_update(C, snode);
2471                 
2472                 return OPERATOR_FINISHED;
2473         }
2474         
2475         return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2476 }
2477
2478 void NODE_OT_links_cut(wmOperatorType *ot)
2479 {
2480         PropertyRNA *prop;
2481         
2482         ot->name= "Cut links";
2483         ot->idname= "NODE_OT_links_cut";
2484         
2485         ot->invoke= WM_gesture_lines_invoke;
2486         ot->modal= WM_gesture_lines_modal;
2487         ot->exec= cut_links_exec;
2488         ot->cancel= WM_gesture_lines_cancel;
2489         
2490         ot->poll= ED_operator_node_active;
2491         
2492         /* flags */
2493         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2494         
2495         prop= RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2496         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2497         /* internal */
2498         RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
2499 }
2500
2501 /* *********************  automatic node insert on dragging ******************* */
2502
2503 /* assumes sockets in list */
2504 static bNodeSocket *socket_best_match(ListBase *sockets, int type)
2505 {
2506         bNodeSocket *sock;
2507         
2508         /* first, match type */
2509         for(sock= sockets->first; sock; sock= sock->next)
2510                 if(!(sock->flag & SOCK_HIDDEN))
2511                         if(type == sock->type)
2512                                 return sock;
2513         
2514         /* then just use first unhidden socket */
2515         for(sock= sockets->first; sock; sock= sock->next)
2516                 if(!(sock->flag & SOCK_HIDDEN))
2517                         return sock;
2518
2519         /* OK, let's unhide proper one */
2520         for(sock= sockets->first; sock; sock= sock->next) {
2521                 if(type == sock->type) {
2522                         sock->flag &= ~SOCK_HIDDEN;
2523                         return sock;
2524                 }
2525         }
2526         
2527         /* just the first */
2528         sock= sockets->first;
2529         sock->flag &= ~SOCK_HIDDEN;
2530         
2531         return sockets->first;
2532 }
2533
2534 /* prevent duplicate testing code below */
2535 static SpaceNode *ed_node_link_conditions(ScrArea *sa, bNode **select)
2536 {
2537         SpaceNode *snode= sa?sa->spacedata.first:NULL;
2538         bNode *node;
2539         bNodeLink *link;
2540         
2541         /* no unlucky accidents */
2542         if(sa==NULL || sa->spacetype!=SPACE_NODE) return NULL;
2543         
2544         *select= NULL;
2545         
2546         for(node= snode->edittree->nodes.first; node; node= node->next) {
2547                 if(node->flag & SELECT) {
2548                         if(*select)
2549                                 break;
2550                         else
2551                                 *select= node;
2552                 }
2553         }
2554         /* only one selected */
2555         if(node || *select==NULL) return NULL;
2556         
2557         /* correct node */
2558         if((*select)->inputs.first==NULL || (*select)->outputs.first==NULL) return NULL;
2559         
2560         /* test node for links */
2561         for(link= snode->edittree->links.first; link; link=link->next) {
2562                 if(link->tonode == *select || link->fromnode == *select)
2563                         return NULL;
2564         }
2565         
2566         return snode;
2567 }
2568
2569 /* assumes link with NODE_LINKFLAG_HILITE set */
2570 void ED_node_link_insert(ScrArea *sa)
2571 {
2572         bNode *node, *select;
2573         SpaceNode *snode= ed_node_link_conditions(sa, &select);
2574         bNodeLink *link;
2575         bNodeSocket *sockto;
2576         
2577         if(snode==NULL) return;
2578         
2579         /* get the link */
2580         for(link= snode->edittree->links.first; link; link=link->next)
2581                 if(link->flag & NODE_LINKFLAG_HILITE)
2582                         break;
2583         
2584         if(link) {
2585                 node= link->tonode;
2586                 sockto= link->tosock;
2587                 
2588                 link->tonode= select;
2589                 link->tosock= socket_best_match(&select->inputs, link->fromsock->type);
2590                 link->flag &= ~NODE_LINKFLAG_HILITE;
2591                 
2592                 nodeAddLink(snode->edittree, select, socket_best_match(&select->outputs, sockto->type), node, sockto);
2593                 ntreeSolveOrder(snode->edittree);       /* needed for pointers */
2594                 snode_tag_changed(snode, select);
2595                 ED_node_changed_update(snode->id, select);
2596         }
2597 }
2598
2599
2600 /* test == 0, clear all intersect flags */
2601 void ED_node_link_intersect_test(ScrArea *sa, int test)
2602 {
2603         bNode *select;
2604         SpaceNode *snode= ed_node_link_conditions(sa, &select);
2605         bNodeLink *link, *selink=NULL;
2606         float mcoords[6][2];
2607         
2608         if(snode==NULL) return;
2609         
2610         /* clear flags */
2611         for(link= snode->edittree->links.first; link; link=link->next)
2612                 link->flag &= ~NODE_LINKFLAG_HILITE;
2613         
2614         if(test==0) return;
2615         
2616         /* okay, there's 1 node, without links, now intersect */
2617         mcoords[0][0]= select->totr.xmin;
2618         mcoords[0][1]= select->totr.ymin;
2619         mcoords[1][0]= select->totr.xmax;
2620         mcoords[1][1]= select->totr.ymin;
2621         mcoords[2][0]= select->totr.xmax;
2622         mcoords[2][1]= select->totr.ymax;
2623         mcoords[3][0]= select->totr.xmin;
2624         mcoords[3][1]= select->totr.ymax;
2625         mcoords[4][0]= select->totr.xmin;
2626         mcoords[4][1]= select->totr.ymin;
2627         mcoords[5][0]= select->totr.xmax;
2628         mcoords[5][1]= select->totr.ymax;
2629         
2630         /* we only tag a single link for intersect now */
2631         /* idea; use header dist when more? */
2632         for(link= snode->edittree->links.first; link; link=link->next) {
2633                 
2634                 if(cut_links_intersect(link, mcoords, 5)) { /* intersect code wants edges */
2635                         if(selink) 
2636                                 break;
2637                         selink= link;
2638                 }
2639         }
2640                 
2641         if(link==NULL && selink)
2642                 selink->flag |= NODE_LINKFLAG_HILITE;
2643 }
2644
2645
2646 /* ******************************** */
2647 // XXX some code needing updating to operators...
2648
2649
2650 /* goes over all scenes, reads render layers */
2651 static int node_read_renderlayers_exec(bContext *C, wmOperator *UNUSED(op))
2652 {
2653         Main *bmain= CTX_data_main(C);
2654         SpaceNode *snode= CTX_wm_space_node(C);
2655         Scene *curscene= CTX_data_scene(C), *scene;
2656         bNode *node;
2657
2658         ED_preview_kill_jobs(C);
2659
2660         /* first tag scenes unread */
2661         for(scene= bmain->scene.first; scene; scene= scene->id.next) 
2662                 scene->id.flag |= LIB_DOIT;
2663
2664         for(node= snode->edittree->nodes.first; node; node= node->next) {
2665                 if(node->type==CMP_NODE_R_LAYERS) {
2666                         ID *id= node->id;
2667                         if(id->flag & LIB_DOIT) {
2668                                 RE_ReadRenderResult(curscene, (Scene *)id);
2669                                 ntreeCompositTagRender((Scene *)id);
2670                                 id->flag &= ~LIB_DOIT;
2671                         }
2672                 }
2673         }
2674         
2675         snode_notify(C, snode);
2676         snode_dag_update(C, snode);
2677
2678         return OPERATOR_FINISHED;
2679 }
2680
2681 void NODE_OT_read_renderlayers(wmOperatorType *ot)
2682 {
2683         
2684         ot->name= "Read Render Layers";
2685         ot->idname= "NODE_OT_read_renderlayers";
2686         
2687         ot->exec= node_read_renderlayers_exec;
2688         
2689         ot->poll= composite_node_active;
2690         
2691         /* flags */
2692         ot->flag= 0;
2693 }
2694
2695 static int node_read_fullsamplelayers_exec(bContext *C, wmOperator *UNUSED(op))
2696 {
2697         Main *bmain= CTX_data_main(C);
2698         SpaceNode *snode= CTX_wm_space_node(C);
2699         Scene *curscene= CTX_data_scene(C);
2700         Render *re= RE_NewRender(curscene->id.name);
2701
2702         WM_cursor_wait(1);
2703
2704         RE_MergeFullSample(re, bmain, curscene, snode->nodetree);
2705         snode_notify(C, snode);
2706         snode_dag_update(C, snode);
2707         
2708         WM_cursor_wait(0);
2709         return OPERATOR_FINISHED;
2710 }
2711
2712
2713 void NODE_OT_read_fullsamplelayers(wmOperatorType *ot)
2714 {
2715         
2716         ot->name= "Read Full Sample Layers";
2717         ot->idname= "NODE_OT_read_fullsamplelayers";
2718         
2719         ot->exec= node_read_fullsamplelayers_exec;
2720         
2721         ot->poll= composite_node_active;
2722         
2723         /* flags */
2724         ot->flag= 0;
2725 }
2726
2727 int node_render_changed_exec(bContext *C, wmOperator *UNUSED(op))
2728 {
2729         Scene *sce= CTX_data_scene(C);
2730         bNode *node;
2731         
2732         for(node= sce->nodetree->nodes.first; node; node= node->next) {
2733                 if(node->id==(ID *)sce && node->need_exec) {
2734                         break;
2735                 }
2736         }
2737         if(node) {
2738                 SceneRenderLayer *srl= BLI_findlink(&sce->r.layers, node->custom1);
2739                 
2740                 if(srl) {
2741                         PointerRNA op_ptr;
2742                         
2743                         WM_operator_properties_create(&op_ptr, "RENDER_OT_render");
2744                         RNA_string_set(&op_ptr, "layer", srl->name);
2745                         RNA_string_set(&op_ptr, "scene", sce->id.name+2);
2746                         
2747                         /* to keep keypositions */
2748                         sce->r.scemode |= R_NO_FRAME_UPDATE;
2749                         
2750                         WM_operator_name_call(C, "RENDER_OT_render", WM_OP_INVOKE_DEFAULT, &op_ptr);
2751
2752                         WM_operator_properties_free(&op_ptr);
2753                         
2754                         return OPERATOR_FINISHED;
2755                 }
2756                    
2757         }
2758         return OPERATOR_CANCELLED;
2759 }
2760
2761 void NODE_OT_render_changed(wmOperatorType *ot)
2762 {
2763         
2764         ot->name= "Render Changed Layer";
2765         ot->idname= "NODE_OT_render_changed";
2766         
2767         ot->exec= node_render_changed_exec;
2768         
2769         ot->poll= composite_node_active;
2770         
2771         /* flags */
2772         ot->flag= 0;
2773 }
2774
2775
2776 /* ****************** Make Group operator ******************* */
2777
2778 static int node_group_make_exec(bContext *C, wmOperator *op)
2779 {
2780         SpaceNode *snode = CTX_wm_space_node(C);
2781         bNode *gnode;
2782         
2783         if(snode->edittree!=snode->nodetree) {
2784                 BKE_report(op->reports, RPT_WARNING, "Can not add a new Group in a Group");
2785                 return OPERATOR_CANCELLED;
2786         }
2787         
2788         /* for time being... is too complex to handle */
2789         if(snode->treetype==NTREE_COMPOSIT) {
2790                 for(gnode=snode->nodetree->nodes.first; gnode; gnode= gnode->next) {
2791                         if(gnode->flag & SELECT)
2792                                 if(gnode->type==CMP_NODE_R_LAYERS)
2793                                         break;
2794                 }
2795                 
2796                 if(gnode) {
2797                         BKE_report(op->reports, RPT_WARNING, "Can not add RenderLayer in a Group");
2798                         return OPERATOR_CANCELLED;
2799                 }
2800         }
2801
2802         ED_preview_kill_jobs(C);
2803         
2804         gnode= nodeMakeGroupFromSelected(snode->nodetree);
2805         if(gnode==NULL) {
2806                 BKE_report(op->reports, RPT_WARNING, "Can not make Group");
2807                 return OPERATOR_CANCELLED;
2808         }
2809         else {
2810                 nodeSetActive(snode->nodetree, gnode);
2811                 ntreeSolveOrder(snode->nodetree);
2812         }
2813         
2814         snode_notify(C, snode);
2815         snode_dag_update(C, snode);
2816         
2817         return OPERATOR_FINISHED;
2818 }
2819
2820 void NODE_OT_group_make(wmOperatorType *ot)
2821 {
2822         /* identifiers */
2823         ot->name = "Group";
2824         ot->description = "Make group from selected nodes";
2825         ot->idname = "NODE_OT_group_make";
2826         
2827         /* api callbacks */
2828         ot->exec = node_group_make_exec;
2829         ot->poll = ED_operator_node_active;
2830         
2831         /* flags */
2832         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2833 }
2834
2835 /* ****************** Hide operator *********************** */
2836
2837 static void node_flag_toggle_exec(SpaceNode *snode, int toggle_flag)
2838 {
2839         int tot_eq= 0, tot_neq= 0;
2840         bNode *node;
2841
2842         for(node= snode->edittree->nodes.first; node; node= node->next) {
2843                 if(node->flag & SELECT) {
2844
2845                         if(toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
2846                                 continue;
2847
2848                         if(node->flag & toggle_flag)
2849                                 tot_eq++;
2850                         else
2851                                 tot_neq++;
2852                 }
2853         }
2854         for(node= snode->edittree->nodes.first; node; node= node->next) {
2855                 if(node->flag & SELECT) {
2856
2857                         if(toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
2858                                 continue;
2859
2860                         if( (tot_eq && tot_neq) || tot_eq==0)
2861                                 node->flag |= toggle_flag;
2862                         else
2863                                 node->flag &= ~toggle_flag;
2864                 }
2865         }
2866 }
2867
2868 static int node_hide_exec(bContext *C, wmOperator *UNUSED(op))
2869 {
2870         SpaceNode *snode= CTX_wm_space_node(C);
2871         
2872         /* sanity checking (poll callback checks this already) */
2873         if((snode == NULL) || (snode->edittree == NULL))
2874                 return OPERATOR_CANCELLED;
2875         
2876         node_flag_toggle_exec(snode, NODE_HIDDEN);
2877         
2878         snode_notify(C, snode);
2879         
2880         return OPERATOR_FINISHED;
2881 }
2882
2883 void NODE_OT_hide_toggle(wmOperatorType *ot)
2884 {
2885         /* identifiers */
2886         ot->name= "Hide";
2887         ot->description= "Toggle hiding of selected nodes";
2888         ot->idname= "NODE_OT_hide_toggle";
2889         
2890         /* callbacks */
2891         ot->exec= node_hide_exec;
2892         ot->poll= ED_operator_node_active;
2893
2894         /* flags */
2895         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2896 }
2897
2898 static int node_preview_exec(bContext *C, wmOperator *UNUSED(op))
2899 {
2900         SpaceNode *snode= CTX_wm_space_node(C);
2901
2902         /* sanity checking (poll callback checks this already) */
2903         if((snode == NULL) || (snode->edittree == NULL))
2904                 return OPERATOR_CANCELLED;
2905
2906         ED_preview_kill_jobs(C);
2907
2908         node_flag_toggle_exec(snode, NODE_PREVIEW);
2909
2910         snode_notify(C, snode);
2911
2912         return OPERATOR_FINISHED;
2913 }
2914
2915 void NODE_OT_preview_toggle(wmOperatorType *ot)
2916 {
2917         /* identifiers */
2918         ot->name= "Toggle Node Preview";
2919         ot->description= "Toggle preview display for selected nodes";
2920         ot->idname= "NODE_OT_preview_toggle";
2921
2922         /* callbacks */
2923         ot->exec= node_preview_exec;
2924         ot->poll= ED_operator_node_active;
2925
2926         /* flags */
2927         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2928 }
2929
2930 static int node_socket_toggle_exec(bContext *C, wmOperator *UNUSED(op))
2931 {
2932         SpaceNode *snode= CTX_wm_space_node(C);
2933         bNode *node;
2934         int hidden= 0;
2935
2936         /* sanity checking (poll callback checks this already) */
2937         if((snode == NULL) || (snode->edittree == NULL))
2938                 return OPERATOR_CANCELLED;
2939
2940         ED_preview_kill_jobs(C);
2941
2942         for(node= snode->edittree->nodes.first; node; node= node->next) {
2943                 if(node->flag & SELECT) {
2944                         if(node_has_hidden_sockets(node)) {
2945                                 hidden= 1;
2946                                 break;
2947                         }
2948                 }
2949         }
2950
2951         for(node= snode->edittree->nodes.first; node; node= node->next) {
2952                 if(node->flag & SELECT) {
2953                         node_set_hidden_sockets(snode, node, !hidden);
2954                 }
2955         }
2956
2957         node_tree_verify_groups(snode->nodetree);
2958
2959         snode_notify(C, snode);
2960
2961         return OPERATOR_FINISHED;
2962 }
2963
2964 void NODE_OT_hide_socket_toggle(wmOperatorType *ot)
2965 {
2966         /* identifiers */
2967         ot->name= "Toggle Hidden Node Sockets";
2968         ot->description= "Toggle unused node socket display";
2969         ot->idname= "NODE_OT_hide_socket_toggle";
2970
2971         /* callbacks */
2972         ot->exec= node_socket_toggle_exec;
2973         ot->poll= ED_operator_node_active;
2974
2975         /* flags */
2976         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2977 }
2978
2979 /* ****************** Mute operator *********************** */
2980
2981 static int node_mute_exec(bContext *C, wmOperator *UNUSED(op))
2982 {
2983         SpaceNode *snode= CTX_wm_space_node(C);
2984         bNode *node;
2985
2986         /* no disabling inside of groups */
2987         if(node_tree_get_editgroup(snode->nodetree))
2988                 return OPERATOR_CANCELLED;
2989         
2990         ED_preview_kill_jobs(C);
2991
2992         for(node= snode->edittree->nodes.first; node; node= node->next) {
2993                 if(node->flag & SELECT) {
2994                         if(node->inputs.first && node->outputs.first) {
2995                                 node->flag ^= NODE_MUTED;
2996                                 snode_tag_changed(snode, node);
2997                         }
2998                 }
2999         }
3000         
3001         snode_notify(C, snode);
3002         snode_dag_update(C, snode);
3003         
3004         return OPERATOR_FINISHED;
3005 }
3006
3007 void NODE_OT_mute_toggle(wmOperatorType *ot)
3008 {
3009         /* identifiers */
3010         ot->name= "Toggle Node Mute";
3011         ot->description= "Toggle muting of the nodes";
3012         ot->idname= "NODE_OT_mute_toggle";
3013         
3014         /* callbacks */
3015         ot->exec= node_mute_exec;
3016         ot->poll= ED_operator_node_active;
3017         
3018         /* flags */
3019         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3020 }
3021
3022 /* ****************** Delete operator ******************* */
3023
3024 static int node_delete_exec(bContext *C, wmOperator *UNUSED(op))
3025 {
3026         SpaceNode *snode= CTX_wm_space_node(C);
3027         bNode *node, *next;
3028         
3029         ED_preview_kill_jobs(C);
3030
3031         for(node= snode->edittree->nodes.first; node; node= next) {
3032                 next= node->next;
3033                 if(node->flag & SELECT) {
3034                         /* check id user here, nodeFreeNode is called for free dbase too */
3035                         if(node->id)
3036                                 node->id->us--;
3037                         nodeFreeNode(snode->edittree, node);
3038                 }
3039         }
3040         
3041         node_tree_verify_groups(snode->nodetree);
3042
3043         snode_notify(C, snode);
3044         snode_dag_update(C, snode);
3045         
3046         return OPERATOR_FINISHED;
3047 }
3048
3049 void NODE_OT_delete(wmOperatorType *ot)
3050 {
3051         /* identifiers */
3052         ot->name= "Delete";
3053         ot->description = "Delete selected nodes";
3054         ot->idname= "NODE_OT_delete";
3055         
3056         /* api callbacks */
3057         ot->exec= node_delete_exec;
3058         ot->poll= ED_operator_node_active;
3059         
3060         /* flags */
3061         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3062 }
3063
3064 /* ****************** Delete with reconnect ******************* */
3065
3066 /* note: in cmp_util.c is similar code, for node_compo_pass_on() */
3067 /* used for disabling node  (similar code in node_draw.c for disable line) */
3068 static void node_delete_reconnect(bNodeTree* tree, bNode* node) 
3069 {
3070         bNodeLink *link, *next;
3071         bNodeSocket *valsocket= NULL, *colsocket= NULL, *vecsocket= NULL;
3072         bNodeSocket *deliveringvalsocket= NULL, *deliveringcolsocket= NULL, *deliveringvecsocket= NULL;
3073         bNode *deliveringvalnode= NULL, *deliveringcolnode= NULL, *deliveringvecnode= NULL;
3074         bNodeSocket *sock;
3075
3076         /* test the inputs */
3077         for(sock= node->inputs.first; sock; sock= sock->next) {
3078                 int type = sock->type;
3079                 if(type==SOCK_VALUE && valsocket==NULL) valsocket = sock;
3080                 if(type==SOCK_VECTOR && vecsocket==NULL) vecsocket = sock;
3081                 if(type==SOCK_RGBA && colsocket==NULL) colsocket = sock;
3082         }
3083         // we now have the input sockets for the 'data types'
3084         // now find the output sockets (and nodes) in the tree that delivers data to these input sockets
3085         for(link= tree->links.first; link; link=link->next) {
3086                 if (valsocket != NULL) {
3087                         if (link->tosock == valsocket) {
3088                                 deliveringvalnode = link->fromnode;
3089                                 deliveringvalsocket = link->fromsock;
3090                         }
3091                 }
3092                 if (vecsocket != NULL) {
3093                         if (link->tosock == vecsocket) {
3094                                 deliveringvecnode = link->fromnode;
3095                                 deliveringvecsocket = link->fromsock;
3096                         }
3097                 }
3098                 if (colsocket != NULL) {
3099                         if (link->tosock == colsocket) {
3100                                 deliveringcolnode = link->fromnode;
3101                                 deliveringcolsocket = link->fromsock;
3102                         }
3103                 }
3104         }
3105         // we now have the sockets+nodes that fill the inputsockets be aware for group nodes these can be NULL
3106         // now make the links for all outputlinks of the node to be reconnected
3107         for(link= tree->links.first; link; link=next) {
3108                 next= link->next;
3109                 if (link->fromnode == node) {
3110                         sock = link->fromsock;
3111                         switch(sock->type) {
3112                         case SOCK_VALUE:
3113                                 if (deliveringvalsocket) {
3114                                         link->fromnode = deliveringvalnode;
3115                                         link->fromsock = deliveringvalsocket;
3116                                 }
3117                                 break;
3118                         case SOCK_VECTOR:
3119                                 if (deliveringvecsocket) {
3120                                         link->fromnode = deliveringvecnode;
3121                                         link->fromsock = deliveringvecsocket;
3122                                 }
3123                                 break;
3124                         case SOCK_RGBA:
3125                                 if (deliveringcolsocket) {
3126                                         link->fromnode = deliveringcolnode;
3127                                         link->fromsock = deliveringcolsocket;
3128                                 }
3129                                 break;
3130                         }
3131                 }
3132         }
3133         if(node->id)
3134                 node->id->us--;
3135         nodeFreeNode(tree, node);
3136
3137 }
3138
3139 static int node_delete_reconnect_exec(bContext *C, wmOperator *UNUSED(op))
3140 {
3141         SpaceNode *snode= CTX_wm_space_node(C);
3142         bNode *node, *next;
3143
3144         ED_preview_kill_jobs(C);
3145
3146         for(node= snode->edittree->nodes.first; node; node= next) {
3147                 next= node->next;
3148                 if(node->flag & SELECT) {
3149                         node_delete_reconnect(snode->edittree, node);
3150                 }
3151         }
3152
3153         node_tree_verify_groups(snode->nodetree);
3154
3155         snode_notify(C, snode);
3156         snode_dag_update(C, snode);
3157
3158         return OPERATOR_FINISHED;
3159 }
3160
3161 void NODE_OT_delete_reconnect(wmOperatorType *ot)
3162 {
3163         /* identifiers */
3164         ot->name= "Delete with reconnect";
3165         ot->description = "Delete nodes; will reconnect nodes as if deletion was muted";
3166         ot->idname= "NODE_OT_delete_reconnect";
3167
3168         /* api callbacks */
3169         ot->exec= node_delete_reconnect_exec;
3170         ot->poll= ED_operator_node_active;
3171
3172         /* flags */
3173         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3174 }
3175
3176 /* ****************** Show Cyclic Dependencies Operator  ******************* */
3177
3178 static int node_show_cycles_exec(bContext *C, wmOperator *UNUSED(op))
3179 {
3180         SpaceNode *snode= CTX_wm_space_node(C);
3181         
3182         /* this is just a wrapper around this call... */
3183         ntreeSolveOrder(snode->edittree);
3184         snode_notify(C, snode);
3185         
3186         return OPERATOR_FINISHED;
3187 }
3188
3189 void NODE_OT_show_cyclic_dependencies(wmOperatorType *ot)
3190 {
3191         /* identifiers */
3192         ot->name= "Show Cyclic Dependencies";
3193         ot->description= "Sort the nodes and show the cyclic dependencies between the nodes";
3194         ot->idname= "NODE_OT_show_cyclic_dependencies";
3195         
3196         /* callbacks */
3197         ot->exec= node_show_cycles_exec;
3198         ot->poll= ED_operator_node_active;
3199         
3200         /* flags */
3201         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3202 }
3203
3204 /* ****************** Add File Node Operator  ******************* */
3205
3206 static int node_add_file_exec(bContext *C, wmOperator *op)
3207 {
3208         Scene *scene= CTX_data_scene(C);
3209         SpaceNode *snode= CTX_wm_space_node(C);
3210         bNode *node;
3211         Image *ima= NULL;
3212         int ntype=0;
3213
3214         /* check input variables */
3215         if (RNA_property_is_set(op->ptr, "filepath"))
3216         {
3217                 char path[FILE_MAX];
3218                 RNA_string_get(op->ptr, "filepath", path);
3219
3220                 errno= 0;
3221
3222                 ima= BKE_add_image_file(path);
3223
3224                 if(!ima) {
3225                         BKE_reportf(op->reports, RPT_ERROR, "Can't read: \"%s\", %s.", path, errno ? strerror(errno) : "Unsupported image format");
3226                         return OPERATOR_CANCELLED;
3227                 }