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