Merging from trunk up to r38119.
[blender-staging.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;
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 *UNUSED(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         
2010         ED_preview_kill_jobs(C);
2011         
2012         lastnode = ntree->nodes.last;
2013         for(node= ntree->nodes.first; node; node= node->next) {
2014                 if(node->flag & SELECT) {
2015                         newnode = nodeCopyNode(ntree, node);
2016                         
2017                         if(newnode->id) {
2018                                 /* simple id user adjustment, node internal functions dont touch this
2019                                  * but operators and readfile.c do. */
2020                                 id_us_plus(newnode->id);
2021                                 /* to ensure redraws or rerenders happen */
2022                                 ED_node_changed_update(snode->id, newnode);
2023                         }
2024                 }
2025                 
2026                 /* make sure we don't copy new nodes again! */
2027                 if (node==lastnode)
2028                         break;
2029         }
2030         
2031         /* copy links between selected nodes
2032          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
2033          */
2034         lastlink = ntree->links.last;
2035         for (link=ntree->links.first; link; link=link->next) {
2036                 /* this creates new links between copied nodes,
2037                  * as well as input links from unselected (when fromnode==NULL) !
2038                  */
2039                 if (link->tonode && (link->tonode->flag & NODE_SELECT)) {
2040                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
2041                         newlink->flag = link->flag;
2042                         newlink->tonode = link->tonode->new_node;
2043                         newlink->tosock = link->tosock->new_sock;
2044                         if (link->fromnode && (link->fromnode->flag & NODE_SELECT)) {
2045                                 newlink->fromnode = link->fromnode->new_node;
2046                                 newlink->fromsock = link->fromsock->new_sock;
2047                         }
2048                         else {
2049                                 /* input node not copied, this keeps the original input linked */
2050                                 newlink->fromnode = link->fromnode;
2051                                 newlink->fromsock = link->fromsock;
2052                         }
2053                         
2054                         BLI_addtail(&ntree->links, newlink);
2055                 }
2056                 
2057                 /* make sure we don't copy new links again! */
2058                 if (link==lastlink)
2059                         break;
2060         }
2061         
2062         /* deselect old nodes, select the copies instead */
2063         for(node= ntree->nodes.first; node; node= node->next) {
2064                 if(node->flag & SELECT) {
2065                         /* has been set during copy above */
2066                         newnode = node->new_node;
2067                         
2068                         node->flag &= ~(NODE_SELECT|NODE_ACTIVE);
2069                         newnode->flag |= NODE_SELECT;
2070                 }
2071                 
2072                 /* make sure we don't copy new nodes again! */
2073                 if (node==lastnode)
2074                         break;
2075         }
2076         
2077         ntreeSolveOrder(ntree);
2078         
2079         node_tree_verify_groups(snode->nodetree);
2080         snode_notify(C, snode);
2081         snode_dag_update(C, snode);
2082
2083         return OPERATOR_FINISHED;
2084 }
2085
2086 void NODE_OT_duplicate(wmOperatorType *ot)
2087 {
2088         /* identifiers */
2089         ot->name= "Duplicate Nodes";
2090         ot->description = "Duplicate the nodes";
2091         ot->idname= "NODE_OT_duplicate";
2092         
2093         /* api callbacks */
2094         ot->exec= node_duplicate_exec;
2095         ot->poll= ED_operator_node_active;
2096         
2097         /* flags */
2098         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2099 }
2100
2101 /* *************************** add link op ******************** */
2102
2103 static void node_remove_extra_links(SpaceNode *snode, bNodeSocket *tsock, bNodeLink *link)
2104 {
2105         bNodeLink *tlink;
2106         bNodeSocket *sock;
2107         
2108         if(tsock && nodeCountSocketLinks(snode->edittree, link->tosock) > tsock->limit) {
2109                 
2110                 for(tlink= snode->edittree->links.first; tlink; tlink= tlink->next) {
2111                         if(link!=tlink && tlink->tosock==link->tosock)
2112                                 break;
2113                 }
2114                 if(tlink) {
2115                         /* try to move the existing link to the next available socket */
2116                         if (tlink->tonode) {
2117                                 /* is there a free input socket with same type? */
2118                                 for(sock= tlink->tonode->inputs.first; sock; sock= sock->next) {
2119                                         if(sock->type==tlink->fromsock->type)
2120                                                 if(nodeCountSocketLinks(snode->edittree, sock) < sock->limit)
2121                                                         break;
2122                                 }
2123                                 if(sock) {
2124                                         tlink->tosock= sock;
2125                                         sock->flag &= ~SOCK_HIDDEN;
2126                                 }
2127                                 else {
2128                                         nodeRemLink(snode->edittree, tlink);
2129                                 }
2130                         }
2131                         else
2132                                 nodeRemLink(snode->edittree, tlink);
2133                 }
2134         }
2135 }
2136
2137 /* loop that adds a nodelink, called by function below  */
2138 /* in_out = starting socket */
2139 static int node_link_modal(bContext *C, wmOperator *op, wmEvent *event)
2140 {
2141         SpaceNode *snode= CTX_wm_space_node(C);
2142         ARegion *ar= CTX_wm_region(C);
2143         bNodeLinkDrag *nldrag= op->customdata;
2144         bNode *tnode, *node;
2145         bNodeSocket *tsock= NULL, *sock;
2146         bNodeLink *link;
2147         int in_out;
2148
2149         in_out= nldrag->in_out;
2150         node= nldrag->node;
2151         sock= nldrag->sock;
2152         link= nldrag->link;
2153         
2154         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2155                                                          &snode->mx, &snode->my);
2156
2157         switch (event->type) {
2158                 case MOUSEMOVE:
2159                         
2160                         if(in_out==SOCK_OUT) {
2161                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_IN)) {
2162                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
2163                                                 if( link->tosock!= tsock && (!tnode || (tnode!=node && link->tonode!=tnode)) ) {
2164                                                         link->tonode= tnode;
2165                                                         link->tosock= tsock;
2166                                                         if (link->prev==NULL && link->next==NULL)
2167                                                                 BLI_addtail(&snode->edittree->links, link);
2168                                                         ntreeSolveOrder(snode->edittree);       /* for interactive red line warning */
2169                                                 }
2170                                         }
2171                                 }
2172                                 else {
2173                                         BLI_remlink(&snode->edittree->links, link);
2174                                         link->prev = link->next = NULL;
2175                                         link->tonode= NULL;
2176                                         link->tosock= NULL;
2177                                 }
2178                         }
2179                         else {
2180                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_OUT)) {
2181                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
2182                                                 if(nodeCountSocketLinks(snode->edittree, tsock) < tsock->limit) {
2183                                                         if( link->fromsock!= tsock && (!tnode || (tnode!=node && link->fromnode!=tnode)) ) {
2184                                                                 link->fromnode= tnode;
2185                                                                 link->fromsock= tsock;
2186                                                                 if (link->prev==NULL && link->next==NULL)
2187                                                                         BLI_addtail(&snode->edittree->links, link);
2188                                                                 ntreeSolveOrder(snode->edittree);       /* for interactive red line warning */
2189                                                         }
2190                                                 }
2191                                         }
2192                                 }
2193                                 else {
2194                                         BLI_remlink(&snode->edittree->links, link);
2195                                         link->prev = link->next = NULL;
2196                                         link->fromnode= NULL;
2197                                         link->fromsock= NULL;
2198                                 }
2199                         }
2200                         /* hilight target sockets only */
2201                         node_socket_hilights(snode, in_out==SOCK_OUT?SOCK_IN:SOCK_OUT);
2202                         ED_region_tag_redraw(ar);
2203                         break;
2204                         
2205                 case LEFTMOUSE:
2206                 case RIGHTMOUSE:
2207                 case MIDDLEMOUSE:
2208                         if(link->tosock && link->fromsock) {
2209                                 /* send changed events for original tonode and new */
2210                                 snode_tag_changed(snode, link->tonode);
2211                                 
2212                                 /* we might need to remove a link */
2213                                 if(in_out==SOCK_OUT)
2214                                         node_remove_extra_links(snode, link->tosock, link);
2215                         }
2216                         else if (outside_group_rect(snode) && (link->tonode || link->fromnode)) {
2217                                 /* automatically add new group socket */
2218                                 if (link->tonode && link->tosock) {
2219                                         link->fromsock = nodeGroupExposeSocket(snode->edittree, link->tosock, SOCK_IN);
2220                                         link->fromnode = NULL;
2221                                         if (link->prev==NULL && link->next==NULL)
2222                                                 BLI_addtail(&snode->edittree->links, link);
2223                                 }
2224                                 else if (link->fromnode && link->fromsock) {
2225                                         link->tosock = nodeGroupExposeSocket(snode->edittree, link->fromsock, SOCK_OUT);
2226                                         link->tonode = NULL;
2227                                         if (link->prev==NULL && link->next==NULL)
2228                                                 BLI_addtail(&snode->edittree->links, link);
2229                                 }
2230                         }
2231                         else
2232                                 nodeRemLink(snode->edittree, link);
2233                         
2234                         ntreeSolveOrder(snode->edittree);
2235                         node_tree_verify_groups(snode->nodetree);
2236                         snode_notify(C, snode);
2237                         snode_dag_update(C, snode);
2238                         
2239                         BLI_remlink(&snode->linkdrag, nldrag);
2240                         MEM_freeN(nldrag);
2241                         
2242                         return OPERATOR_FINISHED;
2243         }
2244         
2245         return OPERATOR_RUNNING_MODAL;
2246 }
2247
2248 /* return 1 when socket clicked */
2249 static int node_link_init(SpaceNode *snode, bNodeLinkDrag *nldrag)
2250 {
2251         bNodeLink *link;
2252
2253         /* output indicated? */
2254         if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_OUT)) {
2255                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2256                         return SOCK_OUT;
2257                 else {
2258                         /* find if we break a link */
2259                         for(link= snode->edittree->links.first; link; link= link->next) {
2260                                 if(link->fromsock==nldrag->sock)
2261                                         break;
2262                         }
2263                         if(link) {
2264                                 nldrag->node= link->tonode;
2265                                 nldrag->sock= link->tosock;
2266                                 nodeRemLink(snode->edittree, link);
2267                                 return SOCK_IN;
2268                         }
2269                 }
2270         }
2271         /* or an input? */
2272         else if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_IN)) {
2273                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2274                         return SOCK_IN;
2275                 else {
2276                         /* find if we break a link */
2277                         for(link= snode->edittree->links.first; link; link= link->next) {
2278                                 if(link->tosock==nldrag->sock)
2279                                         break;
2280                         }
2281                         if(link) {
2282                                 /* send changed event to original tonode */
2283                                 if(link->tonode) 
2284                                         snode_tag_changed(snode, link->tonode);
2285                                 
2286                                 nldrag->node= link->fromnode;
2287                                 nldrag->sock= link->fromsock;
2288                                 nodeRemLink(snode->edittree, link);
2289                                 return SOCK_OUT;
2290                         }
2291                 }
2292         }
2293         
2294         return 0;
2295 }
2296
2297 static int node_link_invoke(bContext *C, wmOperator *op, wmEvent *event)
2298 {
2299         SpaceNode *snode= CTX_wm_space_node(C);
2300         ARegion *ar= CTX_wm_region(C);
2301         bNodeLinkDrag *nldrag= MEM_callocN(sizeof(bNodeLinkDrag), "drag link op customdata");
2302         
2303         
2304         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2305                                                          &snode->mx, &snode->my);
2306
2307         ED_preview_kill_jobs(C);
2308
2309         nldrag->in_out= node_link_init(snode, nldrag);
2310                 
2311         if(nldrag->in_out) {
2312                 op->customdata= nldrag;
2313                 
2314                 /* we make a temporal link */
2315                 if(nldrag->in_out==SOCK_OUT) {
2316                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2317                         nldrag->link->fromnode= nldrag->node;
2318                         nldrag->link->fromsock= nldrag->sock;
2319                         nldrag->link->tonode= NULL;
2320                         nldrag->link->tosock= NULL;
2321                 }
2322                 else {
2323                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2324                         nldrag->link->fromnode= NULL;
2325                         nldrag->link->fromsock= NULL;
2326                         nldrag->link->tonode= nldrag->node;
2327                         nldrag->link->tosock= nldrag->sock;
2328                 }
2329                 BLI_addtail(&snode->linkdrag, nldrag);
2330                 
2331                 /* add modal handler */
2332                 WM_event_add_modal_handler(C, op);
2333                 
2334                 return OPERATOR_RUNNING_MODAL;
2335         }
2336         else {
2337                 MEM_freeN(nldrag);
2338                 return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2339         }
2340 }
2341
2342 static int node_link_cancel(bContext *C, wmOperator *op)
2343 {
2344         SpaceNode *snode= CTX_wm_space_node(C);
2345         bNodeLinkDrag *nldrag= op->customdata;
2346
2347         nodeRemLink(snode->edittree, nldrag->link);
2348         BLI_remlink(&snode->linkdrag, nldrag);
2349         MEM_freeN(nldrag);
2350
2351         return OPERATOR_CANCELLED;
2352 }
2353
2354 void NODE_OT_link(wmOperatorType *ot)
2355 {
2356         /* identifiers */
2357         ot->name= "Link Nodes";
2358         ot->idname= "NODE_OT_link";
2359         
2360         /* api callbacks */
2361         ot->invoke= node_link_invoke;
2362         ot->modal= node_link_modal;
2363 //      ot->exec= node_link_exec;
2364         ot->poll= ED_operator_node_active;
2365         ot->cancel= node_link_cancel;
2366         
2367         /* flags */
2368         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2369 }
2370
2371 /* ********************** Make Link operator ***************** */
2372
2373 /* makes a link between selected output and input sockets */
2374 static int node_make_link_exec(bContext *C, wmOperator *op)
2375 {
2376         SpaceNode *snode= CTX_wm_space_node(C);
2377         int replace = RNA_boolean_get(op->ptr, "replace");
2378
2379         ED_preview_kill_jobs(C);
2380
2381         snode_autoconnect(snode, 1, replace);
2382
2383         node_tree_verify_groups(snode->nodetree);
2384         snode_notify(C, snode);
2385         snode_dag_update(C, snode);
2386         
2387         return OPERATOR_FINISHED;
2388 }
2389
2390 void NODE_OT_link_make(wmOperatorType *ot)
2391 {
2392         /* identifiers */
2393         ot->name= "Make Links";
2394         ot->description= "Makes a link between selected output in input sockets";
2395         ot->idname= "NODE_OT_link_make";
2396         
2397         /* callbacks */
2398         ot->exec= node_make_link_exec;
2399         ot->poll= ED_operator_node_active; // XXX we need a special poll which checks that there are selected input/output sockets
2400         
2401         /* flags */
2402         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2403         
2404         RNA_def_boolean(ot->srna, "replace", 0, "Replace", "Replace socket connections with the new links");
2405 }
2406
2407 /* ********************** Cut Link operator ***************** */
2408
2409 #define LINK_RESOL 12
2410 static int cut_links_intersect(bNodeLink *link, float mcoords[][2], int tot)
2411 {
2412         float coord_array[LINK_RESOL+1][2];
2413         int i, b;
2414         
2415         if(node_link_bezier_points(NULL, NULL, link, coord_array, LINK_RESOL)) {
2416
2417                 for(i=0; i<tot-1; i++)
2418                         for(b=0; b<LINK_RESOL; b++)
2419                                 if(isect_line_line_v2(mcoords[i], mcoords[i+1], coord_array[b], coord_array[b+1]) > 0)
2420                                         return 1;
2421         }
2422         return 0;
2423 }
2424
2425 static int cut_links_exec(bContext *C, wmOperator *op)
2426 {
2427         SpaceNode *snode= CTX_wm_space_node(C);
2428         ARegion *ar= CTX_wm_region(C);
2429         float mcoords[256][2];
2430         int i= 0;
2431         
2432         RNA_BEGIN(op->ptr, itemptr, "path") {
2433                 float loc[2];
2434                 
2435                 RNA_float_get_array(&itemptr, "loc", loc);
2436                 UI_view2d_region_to_view(&ar->v2d, (short)loc[0], (short)loc[1], 
2437                                                                  &mcoords[i][0], &mcoords[i][1]);
2438                 i++;
2439                 if(i>= 256) break;
2440         }
2441         RNA_END;
2442         
2443         if(i>1) {
2444                 bNodeLink *link, *next;
2445
2446                 ED_preview_kill_jobs(C);
2447                 
2448                 for(link= snode->edittree->links.first; link; link= next) {
2449                         next= link->next;
2450                         
2451                         if(cut_links_intersect(link, mcoords, i)) {
2452                                 snode_tag_changed(snode, link->tonode);
2453                                 nodeRemLink(snode->edittree, link);
2454                         }
2455                 }
2456                 
2457                 ntreeSolveOrder(snode->edittree);
2458                 node_tree_verify_groups(snode->nodetree);
2459                 snode_notify(C, snode);
2460                 snode_dag_update(C, snode);
2461                 
2462                 return OPERATOR_FINISHED;
2463         }
2464         
2465         return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2466 }
2467
2468 void NODE_OT_links_cut(wmOperatorType *ot)
2469 {
2470         PropertyRNA *prop;
2471         
2472         ot->name= "Cut links";
2473         ot->idname= "NODE_OT_links_cut";
2474         
2475         ot->invoke= WM_gesture_lines_invoke;
2476         ot->modal= WM_gesture_lines_modal;
2477         ot->exec= cut_links_exec;
2478         ot->cancel= WM_gesture_lines_cancel;
2479         
2480         ot->poll= ED_operator_node_active;
2481         
2482         /* flags */
2483         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2484         
2485         prop= RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2486         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2487         /* internal */
2488         RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
2489 }
2490
2491 /* ******************************** */
2492 // XXX some code needing updating to operators...
2493
2494
2495 /* goes over all scenes, reads render layers */
2496 static int node_read_renderlayers_exec(bContext *C, wmOperator *UNUSED(op))
2497 {
2498         Main *bmain= CTX_data_main(C);
2499         SpaceNode *snode= CTX_wm_space_node(C);
2500         Scene *curscene= CTX_data_scene(C), *scene;
2501         bNode *node;
2502
2503         ED_preview_kill_jobs(C);
2504
2505         /* first tag scenes unread */
2506         for(scene= bmain->scene.first; scene; scene= scene->id.next) 
2507                 scene->id.flag |= LIB_DOIT;
2508
2509         for(node= snode->edittree->nodes.first; node; node= node->next) {
2510                 if(node->type==CMP_NODE_R_LAYERS) {
2511                         ID *id= node->id;
2512                         if(id->flag & LIB_DOIT) {
2513                                 RE_ReadRenderResult(curscene, (Scene *)id);
2514                                 ntreeCompositTagRender((Scene *)id);
2515                                 id->flag &= ~LIB_DOIT;
2516                         }
2517                 }
2518         }
2519         
2520         snode_notify(C, snode);
2521         snode_dag_update(C, snode);
2522
2523         return OPERATOR_FINISHED;
2524 }
2525
2526 void NODE_OT_read_renderlayers(wmOperatorType *ot)
2527 {
2528         
2529         ot->name= "Read Render Layers";
2530         ot->idname= "NODE_OT_read_renderlayers";
2531         
2532         ot->exec= node_read_renderlayers_exec;
2533         
2534         ot->poll= composite_node_active;
2535         
2536         /* flags */
2537         ot->flag= 0;
2538 }
2539
2540 static int node_read_fullsamplelayers_exec(bContext *C, wmOperator *UNUSED(op))
2541 {
2542         Main *bmain= CTX_data_main(C);
2543         SpaceNode *snode= CTX_wm_space_node(C);
2544         Scene *curscene= CTX_data_scene(C);
2545         Render *re= RE_NewRender(curscene->id.name);
2546
2547         WM_cursor_wait(1);
2548
2549         RE_MergeFullSample(re, bmain, curscene, snode->nodetree);
2550         snode_notify(C, snode);
2551         snode_dag_update(C, snode);
2552         
2553         WM_cursor_wait(0);
2554         return OPERATOR_FINISHED;
2555 }
2556
2557
2558 void NODE_OT_read_fullsamplelayers(wmOperatorType *ot)
2559 {
2560         
2561         ot->name= "Read Full Sample Layers";
2562         ot->idname= "NODE_OT_read_fullsamplelayers";
2563         
2564         ot->exec= node_read_fullsamplelayers_exec;
2565         
2566         ot->poll= composite_node_active;
2567         
2568         /* flags */
2569         ot->flag= 0;
2570 }
2571
2572 int node_render_changed_exec(bContext *C, wmOperator *UNUSED(op))
2573 {
2574         Scene *sce= CTX_data_scene(C);
2575         bNode *node;
2576         
2577         for(node= sce->nodetree->nodes.first; node; node= node->next) {
2578                 if(node->id==(ID *)sce && node->need_exec) {
2579                         break;
2580                 }
2581         }
2582         if(node) {
2583                 SceneRenderLayer *srl= BLI_findlink(&sce->r.layers, node->custom1);
2584                 
2585                 if(srl) {
2586                         PointerRNA op_ptr;
2587                         
2588                         WM_operator_properties_create(&op_ptr, "RENDER_OT_render");
2589                         RNA_string_set(&op_ptr, "layer", srl->name);
2590                         RNA_string_set(&op_ptr, "scene", sce->id.name+2);
2591                         
2592                         /* to keep keypositions */
2593                         sce->r.scemode |= R_NO_FRAME_UPDATE;
2594                         
2595                         WM_operator_name_call(C, "RENDER_OT_render", WM_OP_INVOKE_DEFAULT, &op_ptr);
2596
2597                         WM_operator_properties_free(&op_ptr);
2598                         
2599                         return OPERATOR_FINISHED;
2600                 }
2601                    
2602         }
2603         return OPERATOR_CANCELLED;
2604 }
2605
2606 void NODE_OT_render_changed(wmOperatorType *ot)
2607 {
2608         
2609         ot->name= "Render Changed Layer";
2610         ot->idname= "NODE_OT_render_changed";
2611         
2612         ot->exec= node_render_changed_exec;
2613         
2614         ot->poll= composite_node_active;
2615         
2616         /* flags */
2617         ot->flag= 0;
2618 }
2619
2620
2621 /* ****************** Make Group operator ******************* */
2622
2623 static int node_group_make_exec(bContext *C, wmOperator *op)
2624 {
2625         SpaceNode *snode = CTX_wm_space_node(C);
2626         bNode *gnode;
2627         
2628         if(snode->edittree!=snode->nodetree) {
2629                 BKE_report(op->reports, RPT_WARNING, "Can not add a new Group in a Group");
2630                 return OPERATOR_CANCELLED;
2631         }
2632         
2633         /* for time being... is too complex to handle */
2634         if(snode->treetype==NTREE_COMPOSIT) {
2635                 for(gnode=snode->nodetree->nodes.first; gnode; gnode= gnode->next) {
2636                         if(gnode->flag & SELECT)
2637                                 if(gnode->type==CMP_NODE_R_LAYERS)
2638                                         break;
2639                 }
2640                 
2641                 if(gnode) {
2642                         BKE_report(op->reports, RPT_WARNING, "Can not add RenderLayer in a Group");
2643                         return OPERATOR_CANCELLED;
2644                 }
2645         }
2646
2647         ED_preview_kill_jobs(C);
2648         
2649         gnode= nodeMakeGroupFromSelected(snode->nodetree);
2650         if(gnode==NULL) {
2651                 BKE_report(op->reports, RPT_WARNING, "Can not make Group");
2652                 return OPERATOR_CANCELLED;
2653         }
2654         else {
2655                 nodeSetActive(snode->nodetree, gnode);
2656                 ntreeSolveOrder(snode->nodetree);
2657         }
2658         
2659         snode_notify(C, snode);
2660         snode_dag_update(C, snode);
2661         
2662         return OPERATOR_FINISHED;
2663 }
2664
2665 void NODE_OT_group_make(wmOperatorType *ot)
2666 {
2667         /* identifiers */
2668         ot->name = "Group";
2669         ot->description = "Make group from selected nodes";
2670         ot->idname = "NODE_OT_group_make";
2671         
2672         /* api callbacks */
2673         ot->exec = node_group_make_exec;
2674         ot->poll = ED_operator_node_active;
2675         
2676         /* flags */
2677         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2678 }
2679
2680 /* ****************** Hide operator *********************** */
2681
2682 static void node_flag_toggle_exec(SpaceNode *snode, int toggle_flag)
2683 {
2684         int tot_eq= 0, tot_neq= 0;
2685         bNode *node;
2686
2687         for(node= snode->edittree->nodes.first; node; node= node->next) {
2688                 if(node->flag & SELECT) {
2689
2690                         if(toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
2691                                 continue;
2692
2693                         if(node->flag & toggle_flag)
2694                                 tot_eq++;
2695                         else
2696                                 tot_neq++;
2697                 }
2698         }
2699         for(node= snode->edittree->nodes.first; node; node= node->next) {
2700                 if(node->flag & SELECT) {
2701
2702                         if(toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
2703                                 continue;
2704
2705                         if( (tot_eq && tot_neq) || tot_eq==0)
2706                                 node->flag |= toggle_flag;
2707                         else
2708                                 node->flag &= ~toggle_flag;
2709                 }
2710         }
2711 }
2712
2713 static int node_hide_exec(bContext *C, wmOperator *UNUSED(op))
2714 {
2715         SpaceNode *snode= CTX_wm_space_node(C);
2716         
2717         /* sanity checking (poll callback checks this already) */
2718         if((snode == NULL) || (snode->edittree == NULL))
2719                 return OPERATOR_CANCELLED;
2720         
2721         node_flag_toggle_exec(snode, NODE_HIDDEN);
2722         
2723         snode_notify(C, snode);
2724         
2725         return OPERATOR_FINISHED;
2726 }
2727
2728 void NODE_OT_hide_toggle(wmOperatorType *ot)
2729 {
2730         /* identifiers */
2731         ot->name= "Hide";
2732         ot->description= "Toggle hiding of selected nodes";
2733         ot->idname= "NODE_OT_hide_toggle";
2734         
2735         /* callbacks */
2736         ot->exec= node_hide_exec;
2737         ot->poll= ED_operator_node_active;
2738
2739         /* flags */
2740         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2741 }
2742
2743 static int node_preview_exec(bContext *C, wmOperator *UNUSED(op))
2744 {
2745         SpaceNode *snode= CTX_wm_space_node(C);
2746
2747         /* sanity checking (poll callback checks this already) */
2748         if((snode == NULL) || (snode->edittree == NULL))
2749                 return OPERATOR_CANCELLED;
2750
2751         ED_preview_kill_jobs(C);
2752
2753         node_flag_toggle_exec(snode, NODE_PREVIEW);
2754
2755         snode_notify(C, snode);
2756
2757         return OPERATOR_FINISHED;
2758 }
2759
2760 void NODE_OT_preview_toggle(wmOperatorType *ot)
2761 {
2762         /* identifiers */
2763         ot->name= "Toggle Node Preview";
2764         ot->description= "Toggle preview display for selected nodes";
2765         ot->idname= "NODE_OT_preview_toggle";
2766
2767         /* callbacks */
2768         ot->exec= node_preview_exec;
2769         ot->poll= ED_operator_node_active;
2770
2771         /* flags */
2772         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2773 }
2774
2775 static int node_socket_toggle_exec(bContext *C, wmOperator *UNUSED(op))
2776 {
2777         SpaceNode *snode= CTX_wm_space_node(C);
2778         bNode *node;
2779         int hidden= 0;
2780
2781         /* sanity checking (poll callback checks this already) */
2782         if((snode == NULL) || (snode->edittree == NULL))
2783                 return OPERATOR_CANCELLED;
2784
2785         ED_preview_kill_jobs(C);
2786
2787         for(node= snode->edittree->nodes.first; node; node= node->next) {
2788                 if(node->flag & SELECT) {
2789                         if(node_has_hidden_sockets(node)) {
2790                                 hidden= 1;
2791                                 break;
2792                         }
2793                 }
2794         }
2795
2796         for(node= snode->edittree->nodes.first; node; node= node->next) {
2797                 if(node->flag & SELECT) {
2798                         node_set_hidden_sockets(snode, node, !hidden);
2799                 }
2800         }
2801
2802         node_tree_verify_groups(snode->nodetree);
2803
2804         snode_notify(C, snode);
2805
2806         return OPERATOR_FINISHED;
2807 }
2808
2809 void NODE_OT_hide_socket_toggle(wmOperatorType *ot)
2810 {
2811         /* identifiers */
2812         ot->name= "Toggle Hidden Node Sockets";
2813         ot->description= "Toggle unused node socket display";
2814         ot->idname= "NODE_OT_hide_socket_toggle";
2815
2816         /* callbacks */
2817         ot->exec= node_socket_toggle_exec;
2818         ot->poll= ED_operator_node_active;
2819
2820         /* flags */
2821         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2822 }
2823
2824 /* ****************** Mute operator *********************** */
2825
2826 static int node_mute_exec(bContext *C, wmOperator *UNUSED(op))
2827 {
2828         SpaceNode *snode= CTX_wm_space_node(C);
2829         bNode *node;
2830
2831         /* no disabling inside of groups */
2832         if(node_tree_get_editgroup(snode->nodetree))
2833                 return OPERATOR_CANCELLED;
2834         
2835         ED_preview_kill_jobs(C);
2836
2837         for(node= snode->edittree->nodes.first; node; node= node->next) {
2838                 if(node->flag & SELECT) {
2839                         if(node->inputs.first && node->outputs.first) {
2840                                 node->flag ^= NODE_MUTED;
2841                                 snode_tag_changed(snode, node);
2842                         }
2843                 }
2844         }
2845         
2846         snode_notify(C, snode);
2847         snode_dag_update(C, snode);
2848         
2849         return OPERATOR_FINISHED;
2850 }
2851
2852 void NODE_OT_mute_toggle(wmOperatorType *ot)
2853 {
2854         /* identifiers */
2855         ot->name= "Toggle Node Mute";
2856         ot->description= "Toggle muting of the nodes";
2857         ot->idname= "NODE_OT_mute_toggle";
2858         
2859         /* callbacks */
2860         ot->exec= node_mute_exec;
2861         ot->poll= ED_operator_node_active;
2862         
2863         /* flags */
2864         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2865 }
2866
2867 /* ****************** Delete operator ******************* */
2868
2869 static int node_delete_exec(bContext *C, wmOperator *UNUSED(op))
2870 {
2871         SpaceNode *snode= CTX_wm_space_node(C);
2872         bNode *node, *next;
2873         
2874         ED_preview_kill_jobs(C);
2875
2876         for(node= snode->edittree->nodes.first; node; node= next) {
2877                 next= node->next;
2878                 if(node->flag & SELECT) {
2879                         /* check id user here, nodeFreeNode is called for free dbase too */
2880                         if(node->id)
2881                                 node->id->us--;
2882                         nodeFreeNode(snode->edittree, node);
2883                 }
2884         }
2885         
2886         node_tree_verify_groups(snode->nodetree);
2887
2888         snode_notify(C, snode);
2889         snode_dag_update(C, snode);
2890         
2891         return OPERATOR_FINISHED;
2892 }
2893
2894 void NODE_OT_delete(wmOperatorType *ot)
2895 {
2896         /* identifiers */
2897         ot->name= "Delete";
2898         ot->description = "Delete selected nodes";
2899         ot->idname= "NODE_OT_delete";
2900         
2901         /* api callbacks */
2902         ot->exec= node_delete_exec;
2903         ot->poll= ED_operator_node_active;
2904         
2905         /* flags */
2906         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2907 }
2908
2909 /* ****************** Show Cyclic Dependencies Operator  ******************* */
2910
2911 static int node_show_cycles_exec(bContext *C, wmOperator *UNUSED(op))
2912 {
2913         SpaceNode *snode= CTX_wm_space_node(C);
2914         
2915         /* this is just a wrapper around this call... */
2916         ntreeSolveOrder(snode->edittree);
2917         snode_notify(C, snode);
2918         
2919         return OPERATOR_FINISHED;
2920 }
2921
2922 void NODE_OT_show_cyclic_dependencies(wmOperatorType *ot)
2923 {
2924         /* identifiers */
2925         ot->name= "Show Cyclic Dependencies";
2926         ot->description= "Sort the nodes and show the cyclic dependencies between the nodes";
2927         ot->idname= "NODE_OT_show_cyclic_dependencies";
2928         
2929         /* callbacks */
2930         ot->exec= node_show_cycles_exec;
2931         ot->poll= ED_operator_node_active;
2932         
2933         /* flags */
2934         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2935 }
2936
2937 /* ****************** Add File Node Operator  ******************* */
2938
2939 static int node_add_file_exec(bContext *C, wmOperator *op)
2940 {
2941         Scene *scene= CTX_data_scene(C);
2942         SpaceNode *snode= CTX_wm_space_node(C);
2943         bNode *node;
2944         Image *ima= NULL;
2945         int ntype=0;
2946
2947         /* check input variables */
2948         if (RNA_property_is_set(op->ptr, "filepath"))
2949         {
2950                 char path[FILE_MAX];
2951                 RNA_string_get(op->ptr, "filepath", path);
2952
2953                 errno= 0;
2954
2955                 ima= BKE_add_image_file(path);
2956
2957                 if(!ima) {
2958                         BKE_reportf(op->reports, RPT_ERROR, "Can't read: \"%s\", %s.", path, errno ? strerror(errno) : "Unsupported image format");
2959                         return OPERATOR_CANCELLED;
2960                 }
2961         }
2962         else if(RNA_property_is_set(op->ptr, "name"))
2963         {
2964                 char name[32];
2965                 RNA_string_get(op->ptr, "name", name);
2966                 ima= (Image *)find_id("IM", name);
2967
2968                 if(!ima) {
2969                         BKE_reportf(op->reports, RPT_ERROR, "Image named \"%s\", not found.", name);
2970                         return OPERATOR_CANCELLED;
2971                 }
2972         }
2973         
2974         node_deselectall(snode);
2975         
2976         if (snode->nodetree->type==NTREE_COMPOSIT)
2977                 ntype = CMP_NODE_IMAGE;
2978
2979         ED_preview_kill_jobs(C);
2980         
2981         node = node_add_node(snode, scene, ntype, snode->mx, snode->my);
2982         
2983         if (!node) {
2984                 BKE_report(op->reports, RPT_WARNING, "Could not add an image node.");
2985                 return OPERATOR_CANCELLED;
2986         }
2987         
2988         node->id = (ID *)ima;
2989         
2990         snode_notify(C, snode);
2991         snode_dag_update(C, snode);
2992         
2993         return OPERATOR_FINISHED;
2994 }
2995
2996 static int node_add_file_invoke(bContext *C, wmOperator *op, wmEvent *event)
2997 {
2998         ARegion *ar= CTX_wm_region(C);
2999         SpaceNode *snode= CTX_wm_space_node(C);
3000         
3001         /* convert mouse coordinates to v2d space */
3002         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
3003                                                          &snode->mx, &snode->my);
3004         
3005         if (RNA_property_is_set(op->ptr, "filepath") || RNA_property_is_set(op->ptr, "name"))
3006                 return node_add_file_exec(C, op);
3007         else
3008                 return WM_operator_filesel(C, op, event);
3009 }
3010
3011 void NODE_OT_add_file(wmOperatorType *ot)
3012 {
3013         /* identifiers */
3014         ot->name= "Add File Node";
3015         ot->description= "Add a file node to the current node editor";
3016         ot->idname= "NODE_OT_add_file";
3017         
3018         /* callbacks */
3019         ot->exec= node_add_file_exec;
3020         ot->invoke= node_add_file_invoke;
3021         ot->poll= composite_node_active;
3022         
3023         /* flags */
3024         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3025         
3026         WM_operator_properties_filesel(ot, FOLDERFILE|IMAGEFILE, FILE_SPECIAL, FILE_OPENFILE, WM_FILESEL_FILEPATH);  //XXX TODO, relative_path
3027         RNA_def_string(ot->srna, "name", "Image", 24, "Name", "Datablock name to assign.");
3028 }
3029