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