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