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