small edits to text editor from writing a python editor extension.
[blender.git] / source / blender / editors / space_image / image_ops.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributor(s): Blender Foundation, 2002-2009, Xavier Thomas
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include <stddef.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <errno.h>
32
33 #include "MEM_guardedalloc.h"
34
35 #include "DNA_object_types.h"
36 #include "DNA_node_types.h"
37 #include "DNA_packedFile_types.h"
38 #include "DNA_scene_types.h"
39
40 #include "BKE_colortools.h"
41 #include "BKE_context.h"
42 #include "BKE_image.h"
43 #include "BKE_global.h"
44 #include "BKE_library.h"
45 #include "BKE_main.h"
46 #include "BKE_node.h"
47 #include "BKE_packedFile.h"
48 #include "BKE_report.h"
49 #include "BKE_screen.h"
50
51 #include "BLI_math.h"
52 #include "BLI_blenlib.h"
53
54 #include "IMB_imbuf.h"
55 #include "IMB_imbuf_types.h"
56
57 #include "RE_pipeline.h"
58
59 #include "RNA_access.h"
60 #include "RNA_define.h"
61 #include "RNA_enum_types.h"
62
63 #include "ED_image.h"
64 #include "ED_screen.h"
65 #include "ED_space_api.h"
66 #include "ED_uvedit.h"
67
68 #include "UI_interface.h"
69 #include "UI_resources.h"
70 #include "UI_view2d.h"
71
72 #include "WM_api.h"
73 #include "WM_types.h"
74
75 #include "image_intern.h"
76
77 /******************** view navigation utilities *********************/
78
79 static void sima_zoom_set(SpaceImage *sima, ARegion *ar, float zoom)
80 {
81         float oldzoom= sima->zoom;
82         int width, height;
83
84         sima->zoom= zoom;
85
86         if (sima->zoom > 0.1f && sima->zoom < 4.0f)
87                 return;
88
89         /* check zoom limits */
90         ED_space_image_size(sima, &width, &height);
91
92         width *= sima->zoom;
93         height *= sima->zoom;
94
95         if((width < 4) && (height < 4))
96                 sima->zoom= oldzoom;
97         else if((ar->winrct.xmax - ar->winrct.xmin) <= sima->zoom)
98                 sima->zoom= oldzoom;
99         else if((ar->winrct.ymax - ar->winrct.ymin) <= sima->zoom)
100                 sima->zoom= oldzoom;
101 }
102
103 static void sima_zoom_set_factor(SpaceImage *sima, ARegion *ar, float zoomfac)
104 {
105         sima_zoom_set(sima, ar, sima->zoom*zoomfac);
106 }
107
108 #if 0 // currently unused
109 static int image_poll(bContext *C)
110 {
111         return (CTX_data_edit_image(C) != NULL);
112 }
113 #endif
114
115 static int space_image_buffer_exists_poll(bContext *C)
116 {
117         SpaceImage *sima= CTX_wm_space_image(C);
118         if(sima && sima->spacetype==SPACE_IMAGE)
119                 if(ED_space_image_has_buffer(sima))
120                         return 1;
121         return 0;
122 }
123
124 static int space_image_file_exists_poll(bContext *C)
125 {
126         if(space_image_buffer_exists_poll(C)) {
127                 SpaceImage *sima= CTX_wm_space_image(C);
128                 ImBuf *ibuf;
129                 void *lock;
130                 int poll= 0;
131                 char name[FILE_MAX];
132
133                 ibuf= ED_space_image_acquire_buffer(sima, &lock);
134                 if(ibuf) {
135                         BLI_strncpy(name, ibuf->name, FILE_MAX);
136                         BLI_path_abs(name, G.sce);
137                         poll= (BLI_exists(name) && BLI_is_writable(name));
138                 }
139                 ED_space_image_release_buffer(sima, lock);
140
141                 return poll;
142         }
143         return 0;
144 }
145
146 static int space_image_poll(bContext *C)
147 {
148         SpaceImage *sima= CTX_wm_space_image(C);
149         if(sima && sima->spacetype==SPACE_IMAGE && sima->image)
150                 return 1;
151         return 0;
152 }
153
154 int space_image_main_area_poll(bContext *C)
155 {
156         SpaceImage *sima= CTX_wm_space_image(C);
157         // XXX ARegion *ar= CTX_wm_region(C);
158
159         if(sima)
160                 return 1; // XXX (ar && ar->type->regionid == RGN_TYPE_WINDOW);
161         
162         return 0;
163 }
164
165 /********************** view pan operator *********************/
166
167 typedef struct ViewPanData {
168         float x, y;
169         float xof, yof;
170 } ViewPanData;
171
172 static void view_pan_init(bContext *C, wmOperator *op, wmEvent *event)
173 {
174         SpaceImage *sima= CTX_wm_space_image(C);
175         ViewPanData *vpd;
176
177         op->customdata= vpd= MEM_callocN(sizeof(ViewPanData), "ImageViewPanData");
178         WM_cursor_modal(CTX_wm_window(C), BC_NSEW_SCROLLCURSOR);
179
180         vpd->x= event->x;
181         vpd->y= event->y;
182         vpd->xof= sima->xof;
183         vpd->yof= sima->yof;
184
185         WM_event_add_modal_handler(C, op);
186 }
187
188 static void view_pan_exit(bContext *C, wmOperator *op, int cancel)
189 {
190         SpaceImage *sima= CTX_wm_space_image(C);
191         ViewPanData *vpd= op->customdata;
192
193         if(cancel) {
194                 sima->xof= vpd->xof;
195                 sima->yof= vpd->yof;
196                 ED_region_tag_redraw(CTX_wm_region(C));
197         }
198
199         WM_cursor_restore(CTX_wm_window(C));
200         MEM_freeN(op->customdata);
201 }
202
203 static int view_pan_exec(bContext *C, wmOperator *op)
204 {
205         SpaceImage *sima= CTX_wm_space_image(C);
206         float offset[2];
207
208         RNA_float_get_array(op->ptr, "offset", offset);
209         sima->xof += offset[0];
210         sima->yof += offset[1];
211
212         ED_region_tag_redraw(CTX_wm_region(C));
213
214         /* XXX notifier? */
215 #if 0
216         if(image_preview_active(curarea, NULL, NULL)) {
217                 /* recalculates new preview rect */
218                 scrarea_do_windraw(curarea);
219                 image_preview_event(2);
220         }
221 #endif
222         
223         return OPERATOR_FINISHED;
224 }
225
226 static int view_pan_invoke(bContext *C, wmOperator *op, wmEvent *event)
227 {
228         if (event->type == MOUSEPAN) {
229                 SpaceImage *sima= CTX_wm_space_image(C);
230                 float offset[2];
231                 
232                 offset[0]= (event->x - event->prevx)/sima->zoom;
233                 offset[1]= (event->y - event->prevy)/sima->zoom;
234                 RNA_float_set_array(op->ptr, "offset", offset);
235
236                 view_pan_exec(C, op);
237                 return OPERATOR_FINISHED;
238         }
239         else {
240                 view_pan_init(C, op, event);
241                 return OPERATOR_RUNNING_MODAL;
242         }
243 }
244
245 static int view_pan_modal(bContext *C, wmOperator *op, wmEvent *event)
246 {
247         SpaceImage *sima= CTX_wm_space_image(C);
248         ViewPanData *vpd= op->customdata;
249         float offset[2];
250
251         switch(event->type) {
252                 case MOUSEMOVE:
253                         sima->xof= vpd->xof;
254                         sima->yof= vpd->yof;
255                         offset[0]= (vpd->x - event->x)/sima->zoom;
256                         offset[1]= (vpd->y - event->y)/sima->zoom;
257                         RNA_float_set_array(op->ptr, "offset", offset);
258                         view_pan_exec(C, op);
259                         break;
260                 case MIDDLEMOUSE:
261                 case LEFTMOUSE:
262                         if(event->val==KM_RELEASE) {
263                                 view_pan_exit(C, op, 0);
264                                 return OPERATOR_FINISHED;
265                         }
266                         break;
267         }
268
269         return OPERATOR_RUNNING_MODAL;
270 }
271
272 static int view_pan_cancel(bContext *C, wmOperator *op)
273 {
274         view_pan_exit(C, op, 1);
275         return OPERATOR_CANCELLED;
276 }
277
278 void IMAGE_OT_view_pan(wmOperatorType *ot)
279 {
280         /* identifiers */
281         ot->name= "View Pan";
282         ot->idname= "IMAGE_OT_view_pan";
283         
284         /* api callbacks */
285         ot->exec= view_pan_exec;
286         ot->invoke= view_pan_invoke;
287         ot->modal= view_pan_modal;
288         ot->cancel= view_pan_cancel;
289         ot->poll= space_image_main_area_poll;
290
291         /* flags */
292         ot->flag= OPTYPE_BLOCKING;
293         
294         /* properties */
295         RNA_def_float_vector(ot->srna, "offset", 2, NULL, -FLT_MAX, FLT_MAX,
296                 "Offset", "Offset in floating point units, 1.0 is the width and height of the image.", -FLT_MAX, FLT_MAX);
297 }
298
299 /********************** view zoom operator *********************/
300
301 typedef struct ViewZoomData {
302         float x, y;
303         float zoom;
304 } ViewZoomData;
305
306 static void view_zoom_init(bContext *C, wmOperator *op, wmEvent *event)
307 {
308         SpaceImage *sima= CTX_wm_space_image(C);
309         ViewZoomData *vpd;
310
311         op->customdata= vpd= MEM_callocN(sizeof(ViewZoomData), "ImageViewZoomData");
312         WM_cursor_modal(CTX_wm_window(C), BC_NSEW_SCROLLCURSOR);
313
314         vpd->x= event->x;
315         vpd->y= event->y;
316         vpd->zoom= sima->zoom;
317
318         WM_event_add_modal_handler(C, op);
319 }
320
321 static void view_zoom_exit(bContext *C, wmOperator *op, int cancel)
322 {
323         SpaceImage *sima= CTX_wm_space_image(C);
324         ViewZoomData *vpd= op->customdata;
325
326         if(cancel) {
327                 sima->zoom= vpd->zoom;
328                 ED_region_tag_redraw(CTX_wm_region(C));
329         }
330
331         WM_cursor_restore(CTX_wm_window(C));
332         MEM_freeN(op->customdata);
333 }
334
335 static int view_zoom_exec(bContext *C, wmOperator *op)
336 {
337         SpaceImage *sima= CTX_wm_space_image(C);
338         ARegion *ar= CTX_wm_region(C);
339
340         sima_zoom_set_factor(sima, ar, RNA_float_get(op->ptr, "factor"));
341
342         ED_region_tag_redraw(CTX_wm_region(C));
343
344         /* XXX notifier? */
345 #if 0
346         if(image_preview_active(curarea, NULL, NULL)) {
347                 /* recalculates new preview rect */
348                 scrarea_do_windraw(curarea);
349                 image_preview_event(2);
350         }
351 #endif
352         
353         return OPERATOR_FINISHED;
354 }
355
356 static int view_zoom_invoke(bContext *C, wmOperator *op, wmEvent *event)
357 {
358         if (event->type == MOUSEZOOM) {
359                 SpaceImage *sima= CTX_wm_space_image(C);
360                 ARegion *ar= CTX_wm_region(C);
361                 float factor;
362                 
363                 factor= 1.0 + (event->x-event->prevx+event->y-event->prevy)/300.0f;
364                 RNA_float_set(op->ptr, "factor", factor);
365                 sima_zoom_set(sima, ar, sima->zoom*factor);
366                 ED_region_tag_redraw(CTX_wm_region(C));
367                 
368                 return OPERATOR_FINISHED;
369         }
370         else {
371                 view_zoom_init(C, op, event);
372                 return OPERATOR_RUNNING_MODAL;
373         }
374 }
375
376 static int view_zoom_modal(bContext *C, wmOperator *op, wmEvent *event)
377 {
378         SpaceImage *sima= CTX_wm_space_image(C);
379         ARegion *ar= CTX_wm_region(C);
380         ViewZoomData *vpd= op->customdata;
381         float factor;
382
383         switch(event->type) {
384                 case MOUSEMOVE:
385                         factor= 1.0 + (vpd->x-event->x+vpd->y-event->y)/300.0f;
386                         RNA_float_set(op->ptr, "factor", factor);
387                         sima_zoom_set(sima, ar, vpd->zoom*factor);
388                         ED_region_tag_redraw(CTX_wm_region(C));
389                         break;
390                 case MIDDLEMOUSE:
391                 case LEFTMOUSE:
392                         if(event->val==KM_RELEASE) {
393                                 view_zoom_exit(C, op, 0);
394                                 return OPERATOR_FINISHED;
395                         }
396                         break;
397         }
398
399         return OPERATOR_RUNNING_MODAL;
400 }
401
402 static int view_zoom_cancel(bContext *C, wmOperator *op)
403 {
404         view_zoom_exit(C, op, 1);
405         return OPERATOR_CANCELLED;
406 }
407
408 void IMAGE_OT_view_zoom(wmOperatorType *ot)
409 {
410         /* identifiers */
411         ot->name= "View Zoom";
412         ot->idname= "IMAGE_OT_view_zoom";
413         
414         /* api callbacks */
415         ot->exec= view_zoom_exec;
416         ot->invoke= view_zoom_invoke;
417         ot->modal= view_zoom_modal;
418         ot->cancel= view_zoom_cancel;
419         ot->poll= space_image_main_area_poll;
420
421         /* flags */
422         ot->flag= OPTYPE_BLOCKING;
423         
424         /* properties */
425         RNA_def_float(ot->srna, "factor", 0.0f, 0.0f, FLT_MAX,
426                 "Factor", "Zoom factor, values higher than 1.0 zoom in, lower values zoom out.", -FLT_MAX, FLT_MAX);
427 }
428
429 /********************** view all operator *********************/
430
431 /* Updates the fields of the View2D member of the SpaceImage struct.
432  * Default behavior is to reset the position of the image and set the zoom to 1
433  * If the image will not fit within the window rectangle, the zoom is adjusted */
434
435 static int view_all_exec(bContext *C, wmOperator *op)
436 {
437         SpaceImage *sima;
438         ARegion *ar;
439         Scene *scene;
440         Object *obedit;
441         float aspx, aspy, zoomx, zoomy, w, h;
442         int width, height;
443
444         /* retrieve state */
445         sima= CTX_wm_space_image(C);
446         ar= CTX_wm_region(C);
447         scene= (Scene*)CTX_data_scene(C);
448         obedit= CTX_data_edit_object(C);
449
450         ED_space_image_size(sima, &width, &height);
451         ED_space_image_aspect(sima, &aspx, &aspy);
452
453         w= width*aspx;
454         h= height*aspy;
455         
456         /* check if the image will fit in the image with zoom==1 */
457         width = ar->winrct.xmax - ar->winrct.xmin + 1;
458         height = ar->winrct.ymax - ar->winrct.ymin + 1;
459
460         if((w >= width || h >= height) && (width > 0 && height > 0)) {
461                 /* find the zoom value that will fit the image in the image space */
462                 zoomx= width/w;
463                 zoomy= height/h;
464                 sima_zoom_set(sima, ar, 1.0f/power_of_2(1/MIN2(zoomx, zoomy)));
465         }
466         else
467                 sima_zoom_set(sima, ar, 1.0f);
468
469         sima->xof= sima->yof= 0.0f;
470
471         ED_region_tag_redraw(CTX_wm_region(C));
472         
473         return OPERATOR_FINISHED;
474 }
475
476 void IMAGE_OT_view_all(wmOperatorType *ot)
477 {
478         /* identifiers */
479         ot->name= "View All";
480         ot->idname= "IMAGE_OT_view_all";
481         
482         /* api callbacks */
483         ot->exec= view_all_exec;
484         ot->poll= space_image_main_area_poll;
485 }
486
487 /********************** view selected operator *********************/
488
489 static int view_selected_exec(bContext *C, wmOperator *op)
490 {
491         SpaceImage *sima;
492         ARegion *ar;
493         Scene *scene;
494         Object *obedit;
495         Image *ima;
496         float size, min[2], max[2], d[2];
497         int width, height;
498
499         /* retrieve state */
500         sima= CTX_wm_space_image(C);
501         ar= CTX_wm_region(C);
502         scene= (Scene*)CTX_data_scene(C);
503         obedit= CTX_data_edit_object(C);
504
505         ima= ED_space_image(sima);
506         ED_space_image_size(sima, &width, &height);
507
508         /* get bounds */
509         if(!ED_uvedit_minmax(scene, ima, obedit, min, max))
510                 return OPERATOR_CANCELLED;
511
512         /* adjust offset and zoom */
513         sima->xof= (int)(((min[0] + max[0])*0.5f - 0.5f)*width);
514         sima->yof= (int)(((min[1] + max[1])*0.5f - 0.5f)*height);
515
516         d[0]= max[0] - min[0];
517         d[1]= max[1] - min[1];
518         size= 0.5*MAX2(d[0], d[1])*MAX2(width, height)/256.0f;
519         
520         if(size<=0.01) size= 0.01;
521         sima_zoom_set(sima, ar, 0.7/size);
522
523         ED_region_tag_redraw(CTX_wm_region(C));
524         
525         return OPERATOR_FINISHED;
526 }
527
528 static int view_selected_poll(bContext *C)
529 {
530         return (space_image_main_area_poll(C) && ED_operator_uvedit(C));
531 }
532
533 void IMAGE_OT_view_selected(wmOperatorType *ot)
534 {
535         /* identifiers */
536         ot->name= "View Center";
537         ot->idname= "IMAGE_OT_view_selected";
538         
539         /* api callbacks */
540         ot->exec= view_selected_exec;
541         ot->poll= view_selected_poll;
542 }
543
544 /********************** view zoom in/out operator *********************/
545
546 static int view_zoom_in_exec(bContext *C, wmOperator *op)
547 {
548         SpaceImage *sima= CTX_wm_space_image(C);
549         ARegion *ar= CTX_wm_region(C);
550
551         sima_zoom_set_factor(sima, ar, 1.25f);
552
553         ED_region_tag_redraw(CTX_wm_region(C));
554         
555         return OPERATOR_FINISHED;
556 }
557
558 void IMAGE_OT_view_zoom_in(wmOperatorType *ot)
559 {
560         /* identifiers */
561         ot->name= "View Zoom In";
562         ot->idname= "IMAGE_OT_view_zoom_in";
563         
564         /* api callbacks */
565         ot->exec= view_zoom_in_exec;
566         ot->poll= space_image_main_area_poll;
567 }
568
569 static int view_zoom_out_exec(bContext *C, wmOperator *op)
570 {
571         SpaceImage *sima= CTX_wm_space_image(C);
572         ARegion *ar= CTX_wm_region(C);
573
574         sima_zoom_set_factor(sima, ar, 0.8f);
575
576         ED_region_tag_redraw(CTX_wm_region(C));
577         
578         return OPERATOR_FINISHED;
579 }
580
581 void IMAGE_OT_view_zoom_out(wmOperatorType *ot)
582 {
583         /* identifiers */
584         ot->name= "View Zoom Out";
585         ot->idname= "IMAGE_OT_view_zoom_out";
586         
587         /* api callbacks */
588         ot->exec= view_zoom_out_exec;
589         ot->poll= space_image_main_area_poll;
590 }
591
592 /********************** view zoom ratio operator *********************/
593
594 static int view_zoom_ratio_exec(bContext *C, wmOperator *op)
595 {
596         SpaceImage *sima= CTX_wm_space_image(C);
597         ARegion *ar= CTX_wm_region(C);
598
599         sima_zoom_set(sima, ar, RNA_float_get(op->ptr, "ratio"));
600         
601         /* ensure pixel exact locations for draw */
602         sima->xof= (int)sima->xof;
603         sima->yof= (int)sima->yof;
604
605         /* XXX notifier? */
606 #if 0
607         if(image_preview_active(curarea, NULL, NULL)) {
608                 /* recalculates new preview rect */
609                 scrarea_do_windraw(curarea);
610                 image_preview_event(2);
611         }
612 #endif
613
614         ED_region_tag_redraw(CTX_wm_region(C));
615         
616         return OPERATOR_FINISHED;
617 }
618
619 void IMAGE_OT_view_zoom_ratio(wmOperatorType *ot)
620 {
621         /* identifiers */
622         ot->name= "View Zoom Ratio";
623         ot->idname= "IMAGE_OT_view_zoom_ratio";
624         
625         /* api callbacks */
626         ot->exec= view_zoom_ratio_exec;
627         ot->poll= space_image_main_area_poll;
628         
629         /* properties */
630         RNA_def_float(ot->srna, "ratio", 0.0f, 0.0f, FLT_MAX,
631                 "Ratio", "Zoom ratio, 1.0 is 1:1, higher is zoomed in, lower is zoomed out.", -FLT_MAX, FLT_MAX);
632 }
633
634 /**************** load/replace/save callbacks ******************/
635
636 /* XXX make dynamic */
637 static const EnumPropertyItem image_file_type_items[] = {
638                 {R_TARGA, "TARGA", 0, "Targa", ""},
639                 {R_RAWTGA, "TARGA RAW", 0, "Targa Raw", ""},
640                 {R_PNG, "PNG", 0, "PNG", ""},
641                 {R_BMP, "BMP", 0, "BMP", ""},
642                 {R_JPEG90, "JPEG", 0, "Jpeg", ""},
643 #ifdef WITH_OPENJPEG
644                 {R_JP2, "JPEG_2000", 0, "Jpeg 2000", ""},
645 #endif
646                 {R_IRIS, "IRIS", 0, "Iris", ""},
647 #ifdef WITH_TIFF
648                 {R_TIFF, "TIFF", 0, "Tiff", ""},
649 #endif
650 #ifdef WITH_DDS
651                 {R_RADHDR, "RADIANCE_HDR", 0, "Radiance HDR", ""},
652 #endif
653 #ifdef WITH_CINEON
654                 {R_CINEON, "CINEON", 0, "Cineon", ""},
655                 {R_DPX, "DPX", 0, "DPX", ""},
656 #endif
657 #ifdef WITH_OPENEXR
658                 {R_OPENEXR, "OPENEXR", 0, "OpenEXR", ""},
659         /* saving sequences of multilayer won't work, they copy buffers  */
660         /*if(ima->source==IMA_SRC_SEQUENCE && ima->type==IMA_TYPE_MULTILAYER);
661         else*/
662                 {R_MULTILAYER, "MULTILAYER", 0, "MultiLayer", ""},
663 #endif  
664                 {0, NULL, 0, NULL, NULL}};
665
666 static void image_filesel(bContext *C, wmOperator *op, const char *path)
667 {
668         RNA_string_set(op->ptr, "filepath", path);
669         WM_event_add_fileselect(C, op); 
670 }
671
672 /******************** open image operator ********************/
673
674 static void open_init(bContext *C, wmOperator *op)
675 {
676         PropertyPointerRNA *pprop;
677
678         op->customdata= pprop= MEM_callocN(sizeof(PropertyPointerRNA), "OpenPropertyPointerRNA");
679         uiIDContextProperty(C, &pprop->ptr, &pprop->prop);
680 }
681
682 static int open_cancel(bContext *C, wmOperator *op)
683 {
684         MEM_freeN(op->customdata);
685         op->customdata= NULL;
686         return OPERATOR_CANCELLED;
687 }
688
689 static int open_exec(bContext *C, wmOperator *op)
690 {
691         SpaceImage *sima= CTX_wm_space_image(C);
692         Scene *scene= CTX_data_scene(C);
693         Object *obedit= CTX_data_edit_object(C);
694         PropertyPointerRNA *pprop;
695         PointerRNA idptr;
696         Image *ima= NULL;
697         char str[FILE_MAX];
698
699         RNA_string_get(op->ptr, "filepath", str);
700         /* default to frame 1 if there's no scene in context */
701
702         errno= 0;
703
704         ima= BKE_add_image_file(str, scene ? scene->r.cfra : 1);
705
706         if(!ima) {
707                 if(op->customdata) MEM_freeN(op->customdata);
708                 BKE_reportf(op->reports, RPT_ERROR, "Can't read: \"%s\", %s.", str, errno ? strerror(errno) : "Unsupported image format");
709                 return OPERATOR_CANCELLED;
710         }
711         
712         if(!op->customdata)
713                 open_init(C, op);
714
715         /* hook into UI */
716         pprop= op->customdata;
717
718         if(pprop->prop) {
719                 /* when creating new ID blocks, use is already 1, but RNA
720                  * pointer se also increases user, so this compensates it */
721                 ima->id.us--;
722
723                 RNA_id_pointer_create(&ima->id, &idptr);
724                 RNA_property_pointer_set(&pprop->ptr, pprop->prop, idptr);
725                 RNA_property_update(C, &pprop->ptr, pprop->prop);
726         }
727         else if(sima)
728                 ED_space_image_set(C, sima, scene, obedit, ima);
729
730         // XXX other users?
731         BKE_image_signal(ima, (sima)? &sima->iuser: NULL, IMA_SIGNAL_RELOAD);
732         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
733         
734         MEM_freeN(op->customdata);
735
736         return OPERATOR_FINISHED;
737 }
738
739 static int open_invoke(bContext *C, wmOperator *op, wmEvent *event)
740 {
741         SpaceImage *sima= CTX_wm_space_image(C);
742         char *path=U.textudir;
743         Image *ima= NULL;
744
745         if(sima) {
746                  ima= sima->image;
747         }
748
749         if (ima==NULL) {
750                  Tex *tex= CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
751                  if(tex && tex->type==TEX_IMAGE)
752                          ima= tex->ima;
753         }
754
755         if(ima)
756                 path= ima->name;
757         
758
759         if(!RNA_property_is_set(op->ptr, "relative_path"))
760                 RNA_boolean_set(op->ptr, "relative_path", U.flag & USER_RELPATHS);
761
762         if(RNA_property_is_set(op->ptr, "filepath"))
763                 return open_exec(C, op);
764         
765         open_init(C, op);
766
767         image_filesel(C, op, path);
768
769         return OPERATOR_RUNNING_MODAL;
770 }
771
772 void IMAGE_OT_open(wmOperatorType *ot)
773 {
774         /* identifiers */
775         ot->name= "Open";
776         ot->idname= "IMAGE_OT_open";
777         
778         /* api callbacks */
779         ot->exec= open_exec;
780         ot->invoke= open_invoke;
781         ot->cancel= open_cancel;
782
783         /* flags */
784         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
785
786         /* properties */
787         WM_operator_properties_filesel(ot, FOLDERFILE|IMAGEFILE|MOVIEFILE, FILE_SPECIAL, FILE_OPENFILE, WM_FILESEL_FILEPATH|WM_FILESEL_RELPATH);
788 }
789
790 /******************** replace image operator ********************/
791
792 static int replace_exec(bContext *C, wmOperator *op)
793 {
794         SpaceImage *sima= CTX_wm_space_image(C);
795         char str[FILE_MAX];
796
797         if(!sima->image)
798                 return OPERATOR_CANCELLED;
799         
800         RNA_string_get(op->ptr, "filepath", str);
801         BLI_strncpy(sima->image->name, str, sizeof(sima->image->name)-1); /* we cant do much if the str is longer then 240 :/ */
802
803         BKE_image_signal(sima->image, &sima->iuser, IMA_SIGNAL_RELOAD);
804         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, sima->image);
805
806         return OPERATOR_FINISHED;
807 }
808
809 static int replace_invoke(bContext *C, wmOperator *op, wmEvent *event)
810 {
811         SpaceImage *sima= CTX_wm_space_image(C);
812
813         if(!sima->image)
814                 return OPERATOR_CANCELLED;
815
816         if(RNA_property_is_set(op->ptr, "filepath"))
817                 return replace_exec(C, op);
818
819         if(!RNA_property_is_set(op->ptr, "relative_path"))
820                 RNA_boolean_set(op->ptr, "relative_path", (strncmp(sima->image->name, "//", 2))==0);
821
822         image_filesel(C, op, sima->image->name);
823
824         return OPERATOR_RUNNING_MODAL;
825 }
826
827 void IMAGE_OT_replace(wmOperatorType *ot)
828 {
829         /* identifiers */
830         ot->name= "Replace";
831         ot->idname= "IMAGE_OT_replace";
832         
833         /* api callbacks */
834         ot->exec= replace_exec;
835         ot->invoke= replace_invoke;
836         ot->poll= space_image_poll;
837
838         /* flags */
839         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
840
841         /* properties */
842         WM_operator_properties_filesel(ot, FOLDERFILE|IMAGEFILE|MOVIEFILE, FILE_SPECIAL, FILE_OPENFILE, WM_FILESEL_FILEPATH|WM_FILESEL_RELPATH);
843 }
844
845 /******************** save image as operator ********************/
846
847 /* assumes name is FILE_MAX */
848 /* ima->name and ibuf->name should end up the same */
849 static void save_image_doit(bContext *C, SpaceImage *sima, Scene *scene, wmOperator *op, char *path)
850 {
851         Image *ima= ED_space_image(sima);
852         void *lock;
853         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
854
855         if (ibuf) {
856                 int relative= RNA_boolean_get(op->ptr, "relative_path");
857                 int save_copy= (RNA_struct_find_property(op->ptr, "copy") && RNA_boolean_get(op->ptr, "copy"));
858
859                 BLI_path_abs(path, G.sce);
860                 
861                 if(scene->r.scemode & R_EXTENSION)  {
862                         BKE_add_image_extension(path, sima->imtypenr);
863                 }
864                 
865                 /* enforce user setting for RGB or RGBA, but skip BW */
866                 if(scene->r.planes==32)
867                         ibuf->depth= 32;
868                 else if(scene->r.planes==24)
869                         ibuf->depth= 24;
870                 
871                 WM_cursor_wait(1);
872
873                 if(sima->imtypenr==R_MULTILAYER) {
874                         RenderResult *rr= BKE_image_acquire_renderresult(scene, ima);
875                         if(rr) {
876                                 RE_WriteRenderResult(rr, path, scene->r.quality);
877
878                                 if(relative)
879                                         BLI_path_rel(path, G.sce); /* only after saving */
880
881                                 if(!save_copy) {
882                                         BLI_strncpy(ima->name, path, sizeof(ima->name));
883                                         BLI_strncpy(ibuf->name, path, sizeof(ibuf->name));
884
885                                         /* should be function? nevertheless, saving only happens here */
886                                         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next)
887                                                 ibuf->userflags &= ~IB_BITMAPDIRTY;
888                                 }
889                         }
890                         else
891                                 BKE_report(op->reports, RPT_ERROR, "Did not write, no Multilayer Image");
892                         BKE_image_release_renderresult(scene, ima);
893                 }
894                 else if (BKE_write_ibuf(scene, ibuf, path, sima->imtypenr, scene->r.subimtype, scene->r.quality)) {
895
896                         if(relative)
897                                 BLI_path_rel(path, G.sce); /* only after saving */
898
899                         if(!save_copy) {
900
901                                 BLI_strncpy(ima->name, path, sizeof(ima->name));
902                                 BLI_strncpy(ibuf->name, path, sizeof(ibuf->name));
903
904                                 ibuf->userflags &= ~IB_BITMAPDIRTY;
905
906                                 /* change type? */
907                                 if(ima->type==IMA_TYPE_R_RESULT) {
908                                         ima->type= IMA_TYPE_IMAGE;
909
910                                         /* workaround to ensure the render result buffer is no longer used
911                                          * by this image, otherwise can crash when a new render result is
912                                          * created. */
913                                         if(ibuf->rect && !(ibuf->mall & IB_rect))
914                                                 imb_freerectImBuf(ibuf);
915                                         if(ibuf->rect_float && !(ibuf->mall & IB_rectfloat))
916                                                 imb_freerectfloatImBuf(ibuf);
917                                         if(ibuf->zbuf && !(ibuf->mall & IB_zbuf))
918                                                 IMB_freezbufImBuf(ibuf);
919                                         if(ibuf->zbuf_float && !(ibuf->mall & IB_zbuffloat))
920                                                 IMB_freezbuffloatImBuf(ibuf);
921                                 }
922                                 if( ELEM(ima->source, IMA_SRC_GENERATED, IMA_SRC_VIEWER)) {
923                                         ima->source= IMA_SRC_FILE;
924                                         ima->type= IMA_TYPE_IMAGE;
925                                 }
926
927                                 /* name image as how we saved it */
928                                 rename_id(&ima->id, BLI_path_basename(path));
929                         }
930                 } 
931                 else
932                         BKE_reportf(op->reports, RPT_ERROR, "Couldn't write image: %s", path);
933
934                 WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, sima->image);
935
936                 WM_cursor_wait(0);
937         }
938
939         ED_space_image_release_buffer(sima, lock);
940 }
941
942 static int save_as_exec(bContext *C, wmOperator *op)
943 {
944         SpaceImage *sima= CTX_wm_space_image(C);
945         Scene *scene= CTX_data_scene(C);
946         Image *ima = ED_space_image(sima);
947         char str[FILE_MAX];
948
949         if(!ima)
950                 return OPERATOR_CANCELLED;
951
952         sima->imtypenr= RNA_enum_get(op->ptr, "file_type");
953         RNA_string_get(op->ptr, "filepath", str);
954
955         save_image_doit(C, sima, scene, op, str);
956
957         return OPERATOR_FINISHED;
958 }
959
960 static int save_as_invoke(bContext *C, wmOperator *op, wmEvent *event)
961 {
962         SpaceImage *sima= CTX_wm_space_image(C);
963         Image *ima = ED_space_image(sima);
964         Scene *scene= CTX_data_scene(C);
965         ImBuf *ibuf;
966         void *lock;
967
968         if(!RNA_property_is_set(op->ptr, "relative_path"))
969                 RNA_boolean_set(op->ptr, "relative_path", U.flag & USER_RELPATHS);
970
971         if(RNA_property_is_set(op->ptr, "filepath"))
972                 return save_as_exec(C, op);
973         
974         if(!ima)
975                 return OPERATOR_CANCELLED;
976
977         /* always opens fileselect */
978         ibuf= ED_space_image_acquire_buffer(sima, &lock);
979
980         if(ibuf) {
981                 /* cant save multilayer sequence, ima->rr isn't valid for a specific frame */
982                 if(ima->rr && !(ima->source==IMA_SRC_SEQUENCE && ima->type==IMA_TYPE_MULTILAYER))
983                         sima->imtypenr= R_MULTILAYER;
984                 else if(ima->type==IMA_TYPE_R_RESULT)
985                         sima->imtypenr= scene->r.imtype;
986                 else if (ima->source == IMA_SRC_GENERATED)
987                         sima->imtypenr= R_PNG;
988                 else
989                         sima->imtypenr= BKE_ftype_to_imtype(ibuf->ftype);
990
991                 RNA_enum_set(op->ptr, "file_type", sima->imtypenr);
992                 
993                 if(ibuf->name[0]==0)
994                         BLI_strncpy(ibuf->name, G.ima, FILE_MAX);
995
996                 /* enable save_copy by default for render results */
997                 if(ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE) && !RNA_property_is_set(op->ptr, "copy")) {
998                         RNA_boolean_set(op->ptr, "copy", TRUE);
999                 }
1000
1001                 // XXX note: we can give default menu enums to operator for this 
1002                 image_filesel(C, op, ibuf->name);
1003
1004                 ED_space_image_release_buffer(sima, lock);
1005                 
1006                 return OPERATOR_RUNNING_MODAL;
1007         }
1008
1009         ED_space_image_release_buffer(sima, lock);
1010
1011         return OPERATOR_CANCELLED;
1012 }
1013
1014 void IMAGE_OT_save_as(wmOperatorType *ot)
1015 {
1016         /* identifiers */
1017         ot->name= "Save As";
1018         ot->idname= "IMAGE_OT_save_as";
1019         
1020         /* api callbacks */
1021         ot->exec= save_as_exec;
1022         ot->invoke= save_as_invoke;
1023         ot->poll= space_image_buffer_exists_poll;
1024
1025         /* flags */
1026         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1027
1028         /* properties */
1029         RNA_def_enum(ot->srna, "file_type", image_file_type_items, R_PNG, "File Type", "File type to save image as.");
1030         WM_operator_properties_filesel(ot, FOLDERFILE|IMAGEFILE|MOVIEFILE, FILE_SPECIAL, FILE_SAVE, WM_FILESEL_FILEPATH|WM_FILESEL_RELPATH);
1031
1032         RNA_def_boolean(ot->srna, "copy", 0, "Copy", "Create a new image file without modifying the current image in blender");
1033 }
1034
1035 /******************** save image operator ********************/
1036
1037 static int save_exec(bContext *C, wmOperator *op)
1038 {
1039         SpaceImage *sima= CTX_wm_space_image(C);
1040         Image *ima = ED_space_image(sima);
1041         void *lock;
1042         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
1043         Scene *scene= CTX_data_scene(C);
1044         RenderResult *rr;
1045         char name[FILE_MAX];
1046
1047         if(!ima || !ibuf) {
1048                 ED_space_image_release_buffer(sima, lock);
1049                 return OPERATOR_CANCELLED;
1050         }
1051
1052         /* if exists, saves over without fileselect */
1053         
1054         BLI_strncpy(name, ibuf->name, FILE_MAX);
1055         if(name[0]==0)
1056                 BLI_strncpy(name, G.ima, FILE_MAX);
1057         else
1058                 BLI_path_abs(name, G.sce);
1059         
1060         if(BLI_exists(name) && BLI_is_writable(name)) {
1061                 rr= BKE_image_acquire_renderresult(scene, ima);
1062
1063                 if(rr)
1064                         sima->imtypenr= R_MULTILAYER;
1065                 else 
1066                         sima->imtypenr= BKE_ftype_to_imtype(ibuf->ftype);
1067
1068                 BKE_image_release_renderresult(scene, ima);
1069                 ED_space_image_release_buffer(sima, lock);
1070                 
1071                 save_image_doit(C, sima, scene, op, name);
1072         }
1073         else {
1074                 ED_space_image_release_buffer(sima, lock);
1075
1076                 BKE_report(op->reports, RPT_ERROR, "Can not save image.");
1077                 return OPERATOR_CANCELLED;
1078         }
1079
1080         return OPERATOR_FINISHED;
1081 }
1082
1083 void IMAGE_OT_save(wmOperatorType *ot)
1084 {
1085         /* identifiers */
1086         ot->name= "Save";
1087         ot->idname= "IMAGE_OT_save";
1088         
1089         /* api callbacks */
1090         ot->exec= save_exec;
1091         ot->poll= space_image_file_exists_poll;
1092
1093         /* flags */
1094         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1095 }
1096
1097 /******************* save sequence operator ********************/
1098
1099 static int save_sequence_exec(bContext *C, wmOperator *op)
1100 {
1101         SpaceImage *sima= CTX_wm_space_image(C);
1102         ImBuf *ibuf;
1103         int tot= 0;
1104         char di[FILE_MAX], fi[FILE_MAX];
1105         
1106         if(sima->image==NULL)
1107                 return OPERATOR_CANCELLED;
1108
1109         if(sima->image->source!=IMA_SRC_SEQUENCE) {
1110                 BKE_report(op->reports, RPT_ERROR, "Can only save sequence on image sequences.");
1111                 return OPERATOR_CANCELLED;
1112         }
1113
1114         if(sima->image->type==IMA_TYPE_MULTILAYER) {
1115                 BKE_report(op->reports, RPT_ERROR, "Can't save multilayer sequences.");
1116                 return OPERATOR_CANCELLED;
1117         }
1118         
1119         /* get total */
1120         for(ibuf= sima->image->ibufs.first; ibuf; ibuf= ibuf->next) 
1121                 if(ibuf->userflags & IB_BITMAPDIRTY)
1122                         tot++;
1123         
1124         if(tot==0) {
1125                 BKE_report(op->reports, RPT_WARNING, "No images have been changed.");
1126                 return OPERATOR_CANCELLED;
1127         }
1128
1129         /* get a filename for menu */
1130         for(ibuf= sima->image->ibufs.first; ibuf; ibuf= ibuf->next) 
1131                 if(ibuf->userflags & IB_BITMAPDIRTY)
1132                         break;
1133         
1134         BLI_strncpy(di, ibuf->name, FILE_MAX);
1135         BLI_splitdirstring(di, fi);
1136         
1137         BKE_reportf(op->reports, RPT_INFO, "%d Image(s) will be saved in %s", tot, di);
1138
1139         for(ibuf= sima->image->ibufs.first; ibuf; ibuf= ibuf->next) {
1140                 if(ibuf->userflags & IB_BITMAPDIRTY) {
1141                         char name[FILE_MAX];
1142                         BLI_strncpy(name, ibuf->name, sizeof(name));
1143                         
1144                         BLI_path_abs(name, G.sce);
1145
1146                         if(0 == IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat)) {
1147                                 BKE_reportf(op->reports, RPT_ERROR, "Could not write image %s.", name);
1148                                 break;
1149                         }
1150
1151                         BKE_reportf(op->reports, RPT_INFO, "Saved: %s\n", ibuf->name);
1152                         ibuf->userflags &= ~IB_BITMAPDIRTY;
1153                 }
1154         }
1155
1156         return OPERATOR_FINISHED;
1157 }
1158
1159 void IMAGE_OT_save_sequence(wmOperatorType *ot)
1160 {
1161         /* identifiers */
1162         ot->name= "Save Sequence";
1163         ot->idname= "IMAGE_OT_save_sequence";
1164         
1165         /* api callbacks */
1166         ot->exec= save_sequence_exec;
1167         ot->poll= space_image_buffer_exists_poll;
1168
1169         /* flags */
1170         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1171 }
1172
1173 /******************** reload image operator ********************/
1174
1175 static int reload_exec(bContext *C, wmOperator *op)
1176 {
1177         Image *ima= CTX_data_edit_image(C);
1178         SpaceImage *sima= CTX_wm_space_image(C);
1179
1180         if(!ima)
1181                 return OPERATOR_CANCELLED;
1182
1183         // XXX other users?
1184         BKE_image_signal(ima, (sima)? &sima->iuser: NULL, IMA_SIGNAL_RELOAD);
1185
1186         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1187         
1188         return OPERATOR_FINISHED;
1189 }
1190
1191 void IMAGE_OT_reload(wmOperatorType *ot)
1192 {
1193         /* identifiers */
1194         ot->name= "Reload";
1195         ot->idname= "IMAGE_OT_reload";
1196         
1197         /* api callbacks */
1198         ot->exec= reload_exec;
1199
1200         /* flags */
1201         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1202 }
1203
1204 /********************** new image operator *********************/
1205
1206 static int new_exec(bContext *C, wmOperator *op)
1207 {
1208         SpaceImage *sima;
1209         Scene *scene;
1210         Object *obedit;
1211         Image *ima;
1212         PointerRNA ptr, idptr;
1213         PropertyRNA *prop;
1214         char name[22];
1215         float color[4];
1216         int width, height, floatbuf, uvtestgrid, alpha;
1217
1218         /* retrieve state */
1219         sima= CTX_wm_space_image(C);
1220         scene= (Scene*)CTX_data_scene(C);
1221         obedit= CTX_data_edit_object(C);
1222
1223         RNA_string_get(op->ptr, "name", name);
1224         width= RNA_int_get(op->ptr, "width");
1225         height= RNA_int_get(op->ptr, "height");
1226         floatbuf= RNA_boolean_get(op->ptr, "float");
1227         uvtestgrid= RNA_boolean_get(op->ptr, "uv_test_grid");
1228         RNA_float_get_array(op->ptr, "color", color);
1229         alpha= RNA_boolean_get(op->ptr, "alpha");
1230         
1231         if (!floatbuf && scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
1232                 linearrgb_to_srgb_v3_v3(color, color);
1233
1234         if(!alpha)
1235                 color[3]= 1.0f;
1236
1237         ima = BKE_add_image_size(width, height, name, alpha ? 32 : 24, floatbuf, uvtestgrid, color);
1238
1239         if(!ima)
1240                 return OPERATOR_CANCELLED;
1241
1242         /* hook into UI */
1243         uiIDContextProperty(C, &ptr, &prop);
1244
1245         if(prop) {
1246                 /* when creating new ID blocks, use is already 1, but RNA
1247                  * pointer se also increases user, so this compensates it */
1248                 ima->id.us--;
1249
1250                 RNA_id_pointer_create(&ima->id, &idptr);
1251                 RNA_property_pointer_set(&ptr, prop, idptr);
1252                 RNA_property_update(C, &ptr, prop);
1253         }
1254         else if(sima)
1255                 ED_space_image_set(C, sima, scene, obedit, ima);
1256
1257         // XXX other users?
1258         BKE_image_signal(ima, (sima)? &sima->iuser: NULL, IMA_SIGNAL_USER_NEW_IMAGE);
1259         
1260         return OPERATOR_FINISHED;
1261 }
1262
1263 void IMAGE_OT_new(wmOperatorType *ot)
1264 {
1265         PropertyRNA *prop;
1266         static float default_color[4]= {0.0f, 0.0f, 0.0f, 1.0f};
1267         
1268         /* identifiers */
1269         ot->name= "New";
1270         ot->idname= "IMAGE_OT_new";
1271         
1272         /* api callbacks */
1273         ot->exec= new_exec;
1274         ot->invoke= WM_operator_props_popup;
1275
1276         /* flags */
1277         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1278
1279         /* properties */
1280         RNA_def_string(ot->srna, "name", "Untitled", 21, "Name", "Image datablock name.");
1281         RNA_def_int(ot->srna, "width", 1024, 1, INT_MAX, "Width", "Image width.", 1, 16384);
1282         RNA_def_int(ot->srna, "height", 1024, 1, INT_MAX, "Height", "Image height.", 1, 16384);
1283         prop= RNA_def_float_color(ot->srna, "color", 4, NULL, 0.0f, FLT_MAX, "Color", "Default fill color.", 0.0f, 1.0f);
1284         RNA_def_property_float_array_default(prop, default_color);
1285         RNA_def_boolean(ot->srna, "alpha", 1, "Alpha", "Create an image with an alpha channel.");
1286         RNA_def_boolean(ot->srna, "uv_test_grid", 0, "UV Test Grid", "Fill the image with a grid for UV map testing.");
1287         RNA_def_boolean(ot->srna, "float", 0, "32 bit Float", "Create image with 32 bit floating point bit depth.");
1288 }
1289
1290 /********************* pack operator *********************/
1291
1292 static int pack_test(bContext *C, wmOperator *op)
1293 {
1294         Image *ima= CTX_data_edit_image(C);
1295         int as_png= RNA_boolean_get(op->ptr, "as_png");
1296
1297         if(!ima)
1298                 return 0;
1299         if(!as_png && ima->packedfile)
1300                 return 0;
1301
1302         if(ima->source==IMA_SRC_SEQUENCE || ima->source==IMA_SRC_MOVIE) {
1303                 BKE_report(op->reports, RPT_ERROR, "Can't pack movie or image sequence.");
1304                 return 0;
1305         }
1306
1307         return 1;
1308 }
1309
1310 static int pack_exec(bContext *C, wmOperator *op)
1311 {
1312         Image *ima= CTX_data_edit_image(C);
1313         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1314         int as_png= RNA_boolean_get(op->ptr, "as_png");
1315
1316         if(!pack_test(C, op))
1317                 return OPERATOR_CANCELLED;
1318         
1319         if(!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1320                 BKE_report(op->reports, RPT_ERROR, "Can't pack edited image from disk, only as internal PNG.");
1321                 return OPERATOR_CANCELLED;
1322         }
1323
1324         if(as_png)
1325                 BKE_image_memorypack(ima);
1326         else
1327                 ima->packedfile= newPackedFile(op->reports, ima->name);
1328
1329         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1330         
1331         return OPERATOR_FINISHED;
1332 }
1333
1334 static int pack_invoke(bContext *C, wmOperator *op, wmEvent *event)
1335 {
1336         Image *ima= CTX_data_edit_image(C);
1337         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1338         uiPopupMenu *pup;
1339         uiLayout *layout;
1340         int as_png= RNA_boolean_get(op->ptr, "as_png");
1341
1342         if(!pack_test(C, op))
1343                 return OPERATOR_CANCELLED;
1344         
1345         if(!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1346                 pup= uiPupMenuBegin(C, "OK", ICON_QUESTION);
1347                 layout= uiPupMenuLayout(pup);
1348                 uiItemBooleanO(layout, "Can't pack edited image from disk. Pack as internal PNG?", 0, op->idname, "as_png", 1);
1349                 uiPupMenuEnd(C, pup);
1350
1351                 return OPERATOR_CANCELLED;
1352         }
1353
1354         return pack_exec(C, op);
1355 }
1356
1357 void IMAGE_OT_pack(wmOperatorType *ot)
1358 {
1359         /* identifiers */
1360         ot->name= "Pack";
1361         ot->description= "Pack an image as embedded data into the .blend file"; 
1362         ot->idname= "IMAGE_OT_pack";
1363         
1364         /* api callbacks */
1365         ot->exec= pack_exec;
1366         ot->invoke= pack_invoke;
1367
1368         /* flags */
1369         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1370
1371         /* properties */
1372         RNA_def_boolean(ot->srna, "as_png", 0, "Pack As PNG", "Pack image as lossless PNG.");
1373 }
1374
1375 /********************* unpack operator *********************/
1376
1377 void unpack_menu(bContext *C, char *opname, Image *ima, char *folder, PackedFile *pf)
1378 {
1379         PointerRNA props_ptr;
1380         uiPopupMenu *pup;
1381         uiLayout *layout;
1382         char line[FILE_MAXDIR + FILE_MAXFILE + 100];
1383         char local_name[FILE_MAXDIR + FILE_MAX], fi[FILE_MAX];
1384         char *abs_name = ima->name;
1385         
1386         strcpy(local_name, abs_name);
1387         BLI_splitdirstring(local_name, fi);
1388         sprintf(local_name, "//%s/%s", folder, fi);
1389
1390         pup= uiPupMenuBegin(C, "Unpack file", 0);
1391         layout= uiPupMenuLayout(pup);
1392
1393         uiItemEnumO(layout, opname, "Remove Pack", 0, "method", PF_REMOVE);
1394
1395         if(strcmp(abs_name, local_name)) {
1396                 switch(checkPackedFile(local_name, pf)) {
1397                         case PF_NOFILE:
1398                                 sprintf(line, "Create %s", local_name);
1399                                 props_ptr= uiItemFullO(layout, opname, line, 0, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
1400                                 RNA_enum_set(&props_ptr, "method", PF_WRITE_LOCAL);
1401                                 RNA_string_set(&props_ptr, "image", ima->id.name+2);
1402         
1403                                 break;
1404                         case PF_EQUAL:
1405                                 sprintf(line, "Use %s (identical)", local_name);
1406                                 //uiItemEnumO(layout, opname, line, 0, "method", PF_USE_LOCAL);
1407                                 props_ptr= uiItemFullO(layout, opname, line, 0, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
1408                                 RNA_enum_set(&props_ptr, "method", PF_USE_LOCAL);
1409                                 RNA_string_set(&props_ptr, "image", ima->id.name+2);
1410                                 
1411                                 break;
1412                         case PF_DIFFERS:
1413                                 sprintf(line, "Use %s (differs)", local_name);
1414                                 //uiItemEnumO(layout, opname, line, 0, "method", PF_USE_LOCAL);
1415                                 props_ptr= uiItemFullO(layout, opname, line, 0, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
1416                                 RNA_enum_set(&props_ptr, "method", PF_USE_LOCAL);
1417                                 RNA_string_set(&props_ptr, "image", ima->id.name);
1418                                 
1419                                 sprintf(line, "Overwrite %s", local_name);
1420                                 //uiItemEnumO(layout, opname, line, 0, "method", PF_WRITE_LOCAL);
1421                                 props_ptr= uiItemFullO(layout, opname, line, 0, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
1422                                 RNA_enum_set(&props_ptr, "method", PF_WRITE_LOCAL);
1423                                 RNA_string_set(&props_ptr, "image", ima->id.name+2);
1424                                 
1425                                 
1426                                 break;
1427                 }
1428         }
1429         
1430         switch(checkPackedFile(abs_name, pf)) {
1431                 case PF_NOFILE:
1432                         sprintf(line, "Create %s", abs_name);
1433                         //uiItemEnumO(layout, opname, line, 0, "method", PF_WRITE_ORIGINAL);
1434                         props_ptr= uiItemFullO(layout, opname, line, 0, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
1435                         RNA_enum_set(&props_ptr, "method", PF_WRITE_ORIGINAL);
1436                         RNA_string_set(&props_ptr, "image", ima->id.name+2);
1437                         break;
1438                 case PF_EQUAL:
1439                         sprintf(line, "Use %s (identical)", abs_name);
1440                         //uiItemEnumO(layout, opname, line, 0, "method", PF_USE_ORIGINAL);
1441                         props_ptr= uiItemFullO(layout, opname, line, 0, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
1442                         RNA_enum_set(&props_ptr, "method", PF_USE_ORIGINAL);
1443                         RNA_string_set(&props_ptr, "image", ima->id.name+2);
1444                         break;
1445                 case PF_DIFFERS:
1446                         sprintf(line, "Use %s (differs)", local_name);
1447                         //uiItemEnumO(layout, opname, line, 0, "method", PF_USE_ORIGINAL);
1448                         props_ptr= uiItemFullO(layout, opname, line, 0, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
1449                         RNA_enum_set(&props_ptr, "method", PF_USE_ORIGINAL);
1450                         RNA_string_set(&props_ptr, "image", ima->id.name+2);
1451                         
1452                         sprintf(line, "Overwrite %s", local_name);
1453                         //uiItemEnumO(layout, opname, line, 0, "method", PF_WRITE_ORIGINAL);
1454                         props_ptr= uiItemFullO(layout, opname, line, 0, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
1455                         RNA_enum_set(&props_ptr, "method", PF_WRITE_ORIGINAL);
1456                         RNA_string_set(&props_ptr, "image", ima->id.name+2);
1457                         break;
1458         }
1459
1460         uiPupMenuEnd(C, pup);
1461 }
1462
1463 static int unpack_exec(bContext *C, wmOperator *op)
1464 {
1465         Image *ima= CTX_data_edit_image(C);
1466         int method= RNA_enum_get(op->ptr, "method");
1467
1468         /* find the suppplied image by name */
1469         if (RNA_property_is_set(op->ptr, "image")) {
1470                 char imaname[22];
1471                 RNA_string_get(op->ptr, "image", imaname);
1472                 ima = BLI_findstring(&CTX_data_main(C)->image, imaname, offsetof(ID, name) + 2);
1473                 if (!ima) ima = CTX_data_edit_image(C);
1474         }
1475         
1476         if(!ima || !ima->packedfile)
1477                 return OPERATOR_CANCELLED;
1478
1479         if(ima->source==IMA_SRC_SEQUENCE || ima->source==IMA_SRC_MOVIE) {
1480                 BKE_report(op->reports, RPT_ERROR, "Can't unpack movie or image sequence.");
1481                 return OPERATOR_CANCELLED;
1482         }
1483
1484         if(G.fileflags & G_AUTOPACK)
1485                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save.");
1486                 
1487         unpackImage(op->reports, ima, method);
1488         
1489         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1490
1491         return OPERATOR_FINISHED;
1492 }
1493
1494 static int unpack_invoke(bContext *C, wmOperator *op, wmEvent *event)
1495 {
1496         Image *ima= CTX_data_edit_image(C);
1497
1498         if(RNA_property_is_set(op->ptr, "image"))
1499                 return unpack_exec(C, op);
1500                 
1501         if(!ima || !ima->packedfile)
1502                 return OPERATOR_CANCELLED;
1503
1504         if(ima->source==IMA_SRC_SEQUENCE || ima->source==IMA_SRC_MOVIE) {
1505                 BKE_report(op->reports, RPT_ERROR, "Can't unpack movie or image sequence.");
1506                 return OPERATOR_CANCELLED;
1507         }
1508
1509         if(G.fileflags & G_AUTOPACK)
1510                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save.");
1511         
1512         unpack_menu(C, "IMAGE_OT_unpack", ima, "textures", ima->packedfile);
1513
1514         return OPERATOR_FINISHED;
1515 }
1516
1517 void IMAGE_OT_unpack(wmOperatorType *ot)
1518 {
1519         /* identifiers */
1520         ot->name= "Unpack";
1521         ot->description= "Save an image packed in the .blend file to disk"; 
1522         ot->idname= "IMAGE_OT_unpack";
1523         
1524         /* api callbacks */
1525         ot->exec= unpack_exec;
1526         ot->invoke= unpack_invoke;
1527
1528         /* flags */
1529         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1530
1531         /* properties */
1532         RNA_def_enum(ot->srna, "method", unpack_method_items, PF_USE_LOCAL, "Method", "How to unpack.");
1533         RNA_def_string(ot->srna, "image", "", 21, "Image Name", "Image datablock name to unpack.");
1534 }
1535
1536 /******************** sample image operator ********************/
1537
1538 typedef struct ImageSampleInfo {
1539         ARegionType *art;
1540         void *draw_handle;
1541         int x, y;
1542         int channels;
1543
1544         char col[4];
1545         float colf[4];
1546         int z;
1547         float zf;
1548
1549         char *colp;
1550         float *colfp;
1551         int *zp;
1552         float *zfp;
1553
1554         int draw;
1555 } ImageSampleInfo;
1556
1557 static void sample_draw(const bContext *C, ARegion *ar, void *arg_info)
1558 {
1559         ImageSampleInfo *info= arg_info;
1560
1561         draw_image_info(ar, info->channels, info->x, info->y, info->colp,
1562                 info->colfp, info->zp, info->zfp);
1563 }
1564
1565 static void sample_apply(bContext *C, wmOperator *op, wmEvent *event)
1566 {
1567         SpaceImage *sima= CTX_wm_space_image(C);
1568         ARegion *ar= CTX_wm_region(C);
1569         void *lock;
1570         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
1571         ImageSampleInfo *info= op->customdata;
1572         float fx, fy;
1573         int x, y;
1574         
1575         if(ibuf == NULL) {
1576                 ED_space_image_release_buffer(sima, lock);
1577                 return;
1578         }
1579
1580         x= event->x - ar->winrct.xmin;
1581         y= event->y - ar->winrct.ymin;
1582         UI_view2d_region_to_view(&ar->v2d, x, y, &fx, &fy);
1583
1584         if(fx>=0.0 && fy>=0.0 && fx<1.0 && fy<1.0) {
1585                 float *fp;
1586                 char *cp;
1587                 int x= (int)(fx*ibuf->x), y= (int)(fy*ibuf->y);
1588
1589                 CLAMP(x, 0, ibuf->x-1);
1590                 CLAMP(y, 0, ibuf->y-1);
1591
1592                 info->x= x;
1593                 info->y= y;
1594                 info->draw= 1;
1595                 info->channels= ibuf->channels;
1596
1597                 info->colp= NULL;
1598                 info->colfp= NULL;
1599                 info->zp= NULL;
1600                 info->zfp= NULL;
1601                 
1602                 if(ibuf->rect) {
1603                         cp= (char *)(ibuf->rect + y*ibuf->x + x);
1604
1605                         info->col[0]= cp[0];
1606                         info->col[1]= cp[1];
1607                         info->col[2]= cp[2];
1608                         info->col[3]= cp[3];
1609                         info->colp= info->col;
1610
1611                         info->colf[0]= (float)cp[0]/255.0f;
1612                         info->colf[1]= (float)cp[1]/255.0f;
1613                         info->colf[2]= (float)cp[2]/255.0f;
1614                         info->colf[3]= (float)cp[3]/255.0f;
1615                         info->colfp= info->colf;
1616                 }
1617                 if(ibuf->rect_float) {
1618                         fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
1619
1620                         info->colf[0]= fp[0];
1621                         info->colf[1]= fp[1];
1622                         info->colf[2]= fp[2];
1623                         info->colf[3]= fp[3];
1624                         info->colfp= info->colf;
1625                 }
1626
1627                 if(ibuf->zbuf) {
1628                         info->z= ibuf->zbuf[y*ibuf->x + x];
1629                         info->zp= &info->z;
1630                 }
1631                 if(ibuf->zbuf_float) {
1632                         info->zf= ibuf->zbuf_float[y*ibuf->x + x];
1633                         info->zfp= &info->zf;
1634                 }
1635                 
1636                 if(sima->cumap && ibuf->channels==4) {
1637                         /* we reuse this callback for set curves point operators */
1638                         if(RNA_struct_find_property(op->ptr, "point")) {
1639                                 int point= RNA_enum_get(op->ptr, "point");
1640
1641                                 if(point == 1) {
1642                                         curvemapping_set_black_white(sima->cumap, NULL, info->colfp);
1643                                         curvemapping_do_ibuf(sima->cumap, ibuf);
1644                                 }
1645                                 else if(point == 0) {
1646                                         curvemapping_set_black_white(sima->cumap, info->colfp, NULL);
1647                                         curvemapping_do_ibuf(sima->cumap, ibuf);
1648                                 }
1649                         }
1650                 }
1651                                 
1652                 // XXX node curve integration ..
1653 #if 0
1654                 {
1655                         ScrArea *sa, *cur= curarea;
1656                         
1657                         node_curvemap_sample(fp);       /* sends global to node editor */
1658                         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
1659                                 if(sa->spacetype==SPACE_NODE) {
1660                                         areawinset(sa->win);
1661                                         scrarea_do_windraw(sa);
1662                                 }
1663                         }
1664                         node_curvemap_sample(NULL);             /* clears global in node editor */
1665                         curarea= cur;
1666                 }
1667 #endif
1668         }
1669         else
1670                 info->draw= 0;
1671
1672         ED_space_image_release_buffer(sima, lock);
1673         ED_area_tag_redraw(CTX_wm_area(C));
1674 }
1675
1676 static void sample_exit(bContext *C, wmOperator *op)
1677 {
1678         ImageSampleInfo *info= op->customdata;
1679
1680         ED_region_draw_cb_exit(info->art, info->draw_handle);
1681         ED_area_tag_redraw(CTX_wm_area(C));
1682         MEM_freeN(info);
1683 }
1684
1685 static int sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1686 {
1687         SpaceImage *sima= CTX_wm_space_image(C);
1688         ARegion *ar= CTX_wm_region(C);
1689         ImageSampleInfo *info;
1690
1691         if(!ED_space_image_has_buffer(sima))
1692                 return OPERATOR_CANCELLED;
1693         
1694         info= MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
1695         info->art= ar->type;
1696         info->draw_handle = ED_region_draw_cb_activate(ar->type, sample_draw, info, REGION_DRAW_POST_PIXEL);
1697         op->customdata= info;
1698
1699         sample_apply(C, op, event);
1700
1701         WM_event_add_modal_handler(C, op);
1702
1703         return OPERATOR_RUNNING_MODAL;
1704 }
1705
1706 static int sample_modal(bContext *C, wmOperator *op, wmEvent *event)
1707 {
1708         switch(event->type) {
1709                 case LEFTMOUSE:
1710                 case RIGHTMOUSE: // XXX hardcoded
1711                         sample_exit(C, op);
1712                         return OPERATOR_CANCELLED;
1713                 case MOUSEMOVE:
1714                         sample_apply(C, op, event);
1715                         break;
1716         }
1717
1718         return OPERATOR_RUNNING_MODAL;
1719 }
1720
1721 static int sample_cancel(bContext *C, wmOperator *op)
1722 {
1723         sample_exit(C, op);
1724         return OPERATOR_CANCELLED;
1725 }
1726
1727 void IMAGE_OT_sample(wmOperatorType *ot)
1728 {
1729         /* identifiers */
1730         ot->name= "Sample";
1731         ot->idname= "IMAGE_OT_sample";
1732         
1733         /* api callbacks */
1734         ot->invoke= sample_invoke;
1735         ot->modal= sample_modal;
1736         ot->cancel= sample_cancel;
1737         ot->poll= space_image_main_area_poll;
1738
1739         /* flags */
1740         ot->flag= OPTYPE_BLOCKING;
1741 }
1742
1743 /******************** sample line operator ********************/
1744 static int sample_line_exec(bContext *C, wmOperator *op)
1745 {
1746         SpaceImage *sima= CTX_wm_space_image(C);
1747         ARegion *ar= CTX_wm_region(C);
1748         Scene *scene= CTX_data_scene(C);
1749         
1750         int x_start= RNA_int_get(op->ptr, "xstart");
1751         int y_start= RNA_int_get(op->ptr, "ystart");
1752         int x_end= RNA_int_get(op->ptr, "xend");
1753         int y_end= RNA_int_get(op->ptr, "yend");
1754         
1755         void *lock;
1756         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
1757         Histogram *hist= &sima->sample_line_hist;
1758         
1759         float x1f, y1f, x2f, y2f;
1760         int x1, y1, x2, y2;
1761         int i, x, y;
1762         float *fp;
1763         float rgb[3];
1764         unsigned char *cp;
1765         
1766         if (ibuf == NULL) {
1767                 ED_space_image_release_buffer(sima, lock);
1768                 return OPERATOR_CANCELLED;
1769         }
1770         /* hmmmm */
1771         if (ibuf->channels < 3) {
1772                 ED_space_image_release_buffer(sima, lock);
1773                 return OPERATOR_CANCELLED;
1774         }
1775         
1776         UI_view2d_region_to_view(&ar->v2d, x_start, y_start, &x1f, &y1f);
1777         UI_view2d_region_to_view(&ar->v2d, x_end, y_end, &x2f, &y2f);
1778         x1= 0.5f+ x1f*ibuf->x;
1779         x2= 0.5f+ x2f*ibuf->x;
1780         y1= 0.5f+ y1f*ibuf->y;
1781         y2= 0.5f+ y2f*ibuf->y;
1782         
1783         hist->channels = 3;
1784         hist->x_resolution = 256;
1785         hist->xmax = 1.0f;
1786         hist->ymax = 1.0f;
1787         
1788         for (i=0; i<256; i++) {
1789                 x= (int)(0.5f + x1 + (float)i*(x2-x1)/255.0f);
1790                 y= (int)(0.5f + y1 + (float)i*(y2-y1)/255.0f);
1791                 
1792                 if (x<0 || y<0 || x>=ibuf->x || y>=ibuf->y) {
1793                         hist->data_luma[i] = hist->data_r[i] = hist->data_g[i]= hist->data_b[i] = 0.0f;
1794                 } else {
1795                         if (ibuf->rect_float) {
1796                                 fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
1797
1798                                 if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
1799                                         linearrgb_to_srgb_v3_v3(rgb, fp);
1800                                 else
1801                                         copy_v3_v3(rgb, fp);
1802
1803                                 hist->data_r[i] = rgb[0];
1804                                 hist->data_g[i] = rgb[1];
1805                                 hist->data_b[i] = rgb[2];
1806                                 hist->data_luma[i] = (0.299f*rgb[0] + 0.587f*rgb[1] + 0.114f*rgb[2]);
1807                         }
1808                         else if (ibuf->rect) {
1809                                 cp= (unsigned char *)(ibuf->rect + y*ibuf->x + x);
1810                                 hist->data_r[i] = (float)cp[0]/255.0f;
1811                                 hist->data_g[i] = (float)cp[1]/255.0f;
1812                                 hist->data_b[i] = (float)cp[2]/255.0f;
1813                                 hist->data_luma[i] = (0.299f*cp[0] + 0.587f*cp[1] + 0.114f*cp[2])/255;
1814                         }
1815                 }
1816         }
1817         
1818         ED_space_image_release_buffer(sima, lock);
1819         
1820         ED_area_tag_redraw(CTX_wm_area(C));
1821         
1822         return OPERATOR_FINISHED;
1823 }
1824
1825 static int sample_line_invoke(bContext *C, wmOperator *op, wmEvent *event)
1826 {
1827         SpaceImage *sima= CTX_wm_space_image(C);
1828         
1829         if(!ED_space_image_has_buffer(sima))
1830                 return OPERATOR_CANCELLED;
1831         
1832         return WM_gesture_straightline_invoke(C, op, event);
1833 }
1834
1835 void IMAGE_OT_sample_line(wmOperatorType *ot)
1836 {
1837         /* identifiers */
1838         ot->name= "Sample Line";
1839         ot->idname= "IMAGE_OT_sample_line";
1840         
1841         /* api callbacks */
1842         ot->invoke= sample_line_invoke;
1843         ot->modal= WM_gesture_straightline_modal;
1844         ot->exec= sample_line_exec;
1845         ot->poll= space_image_main_area_poll;
1846         
1847         /* flags */
1848         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1849         
1850         WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT);
1851 }
1852
1853 /******************** set curve point operator ********************/
1854
1855 void IMAGE_OT_curves_point_set(wmOperatorType *ot)
1856 {
1857         static EnumPropertyItem point_items[]= {
1858                 {0, "BLACK_POINT", 0, "Black Point", ""},
1859                 {1, "WHITE_POINT", 0, "White Point", ""},
1860                 {0, NULL, 0, NULL, NULL}};
1861
1862         /* identifiers */
1863         ot->name= "Set Curves Point";
1864         ot->idname= "IMAGE_OT_curves_point_set";
1865
1866         /* flags */
1867         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1868         
1869         /* api callbacks */
1870         ot->invoke= sample_invoke;
1871         ot->modal= sample_modal;
1872         ot->cancel= sample_cancel;
1873         ot->poll= space_image_main_area_poll;
1874
1875         /* properties */
1876         RNA_def_enum(ot->srna, "point", point_items, 0, "Point", "Set black point or white point for curves.");
1877 }
1878
1879 /******************** record composite operator *********************/
1880
1881 typedef struct RecordCompositeData {
1882         wmTimer *timer;
1883         int old_cfra;
1884         int sfra, efra;
1885 } RecordCompositeData;
1886
1887 int record_composite_apply(bContext *C, wmOperator *op)
1888 {
1889         SpaceImage *sima= CTX_wm_space_image(C);
1890         RecordCompositeData *rcd= op->customdata;
1891         Scene *scene= CTX_data_scene(C);
1892         ImBuf *ibuf;
1893         
1894         WM_timecursor(CTX_wm_window(C), scene->r.cfra);
1895
1896         // XXX scene->nodetree->test_break= blender_test_break;
1897         // XXX scene->nodetree->test_break= NULL;
1898         
1899         BKE_image_all_free_anim_ibufs(scene->r.cfra);
1900         ntreeCompositTagAnimated(scene->nodetree);
1901         ntreeCompositExecTree(scene->nodetree, &scene->r, scene->r.cfra != rcd->old_cfra);      /* 1 is no previews */
1902
1903         ED_area_tag_redraw(CTX_wm_area(C));
1904         
1905         ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
1906         /* save memory in flipbooks */
1907         if(ibuf)
1908                 imb_freerectfloatImBuf(ibuf);
1909         
1910         scene->r.cfra++;
1911
1912         return (scene->r.cfra <= rcd->efra);
1913 }
1914
1915 static int record_composite_init(bContext *C, wmOperator *op)
1916 {
1917         SpaceImage *sima= CTX_wm_space_image(C);
1918         Scene *scene= CTX_data_scene(C);
1919         RecordCompositeData *rcd;
1920
1921         if(sima->iuser.frames < 2)
1922                 return 0;
1923         if(scene->nodetree == NULL)
1924                 return 0;
1925         
1926         op->customdata= rcd= MEM_callocN(sizeof(RecordCompositeData), "ImageRecordCompositeData");
1927
1928         rcd->old_cfra= scene->r.cfra;
1929         rcd->sfra= sima->iuser.sfra;
1930         rcd->efra= sima->iuser.sfra + sima->iuser.frames-1;
1931         scene->r.cfra= rcd->sfra;
1932
1933         return 1;
1934 }
1935
1936 static void record_composite_exit(bContext *C, wmOperator *op)
1937 {
1938         Scene *scene= CTX_data_scene(C);
1939         SpaceImage *sima= CTX_wm_space_image(C);
1940         RecordCompositeData *rcd= op->customdata;
1941
1942         scene->r.cfra= rcd->old_cfra;
1943
1944         WM_cursor_restore(CTX_wm_window(C));
1945
1946         if(rcd->timer)
1947                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rcd->timer);
1948
1949         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, sima->image);
1950
1951         // XXX play_anim(0);
1952         // XXX allqueue(REDRAWNODE, 1);
1953
1954         MEM_freeN(rcd);
1955 }
1956
1957 static int record_composite_exec(bContext *C, wmOperator *op)
1958 {
1959         if(!record_composite_init(C, op))
1960                 return OPERATOR_CANCELLED;
1961         
1962         while(record_composite_apply(C, op))
1963                 ;
1964         
1965         record_composite_exit(C, op);
1966         
1967         return OPERATOR_FINISHED;
1968 }
1969
1970 static int record_composite_invoke(bContext *C, wmOperator *op, wmEvent *event)
1971 {
1972         RecordCompositeData *rcd= op->customdata;
1973         
1974         if(!record_composite_init(C, op))
1975                 return OPERATOR_CANCELLED;
1976
1977         rcd= op->customdata;
1978         rcd->timer= WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.0f);
1979         WM_event_add_modal_handler(C, op);
1980
1981         if(!record_composite_apply(C, op))
1982                 return OPERATOR_FINISHED;
1983
1984         return OPERATOR_RUNNING_MODAL;
1985 }
1986
1987 static int record_composite_modal(bContext *C, wmOperator *op, wmEvent *event)
1988 {
1989         RecordCompositeData *rcd= op->customdata;
1990
1991         switch(event->type) {
1992                 case TIMER:
1993                         if(rcd->timer == event->customdata) {
1994                                 if(!record_composite_apply(C, op)) {
1995                                         record_composite_exit(C, op);
1996                                         return OPERATOR_FINISHED;
1997                                 }
1998                         }
1999                         break;
2000                 case ESCKEY:
2001                         record_composite_exit(C, op);
2002                         return OPERATOR_FINISHED;
2003         }
2004
2005         return OPERATOR_RUNNING_MODAL;
2006 }
2007
2008 static int record_composite_cancel(bContext *C, wmOperator *op)
2009 {
2010         record_composite_exit(C, op);
2011         return OPERATOR_CANCELLED;
2012 }
2013
2014 void IMAGE_OT_record_composite(wmOperatorType *ot)
2015 {
2016         /* identifiers */
2017         ot->name= "Record Composite";
2018         ot->idname= "IMAGE_OT_record_composite";
2019         
2020         /* api callbacks */
2021         ot->exec= record_composite_exec;
2022         ot->invoke= record_composite_invoke;
2023         ot->modal= record_composite_modal;
2024         ot->cancel= record_composite_cancel;
2025         ot->poll= space_image_buffer_exists_poll;
2026 }
2027
2028 /********************* cycle render slot operator *********************/
2029
2030 static int cycle_render_slot_poll(bContext *C)
2031 {
2032         Image *ima= CTX_data_edit_image(C);
2033
2034         return (ima && ima->type == IMA_TYPE_R_RESULT);
2035 }
2036
2037 static int cycle_render_slot_exec(bContext *C, wmOperator *op)
2038 {
2039         Image *ima= CTX_data_edit_image(C);
2040         int a, slot, cur= ima->render_slot;
2041
2042         for(a=1; a<IMA_MAX_RENDER_SLOT; a++) {
2043                 slot= (cur+a)%IMA_MAX_RENDER_SLOT;
2044
2045                 if(ima->renders[slot] || slot == ima->last_render_slot) {
2046                         ima->render_slot= slot;
2047                         break;
2048                 }
2049         }
2050
2051         if(a == IMA_MAX_RENDER_SLOT)
2052                 ima->render_slot= ((cur == 1)? 0: 1);
2053         
2054         WM_event_add_notifier(C, NC_IMAGE|ND_DRAW, NULL);
2055
2056         return OPERATOR_FINISHED;
2057 }
2058
2059 void IMAGE_OT_cycle_render_slot(wmOperatorType *ot)
2060 {
2061         /* identifiers */
2062         ot->name= "Cycle Render Slot";
2063         ot->idname= "IMAGE_OT_cycle_render_slot";
2064         
2065         /* api callbacks */
2066         ot->exec= cycle_render_slot_exec;
2067         ot->poll= cycle_render_slot_poll;
2068
2069         /* flags */
2070         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2071 }
2072
2073 /******************** TODO ********************/
2074
2075 /* XXX notifier? */
2076
2077 /* goes over all ImageUsers, and sets frame numbers if auto-refresh is set */
2078
2079 void ED_image_update_frame(const bContext *C)
2080 {
2081         Main *mainp= CTX_data_main(C);
2082         Scene *scene= CTX_data_scene(C);
2083         wmWindowManager *wm= CTX_wm_manager(C);
2084         wmWindow *win;
2085         Tex *tex;
2086         
2087         /* texture users */
2088         for(tex= mainp->tex.first; tex; tex= tex->id.next) {
2089                 if(tex->type==TEX_IMAGE && tex->ima) {
2090                         if(ELEM(tex->ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
2091                                 if(tex->iuser.flag & IMA_ANIM_ALWAYS)
2092                                         BKE_image_user_calc_frame(&tex->iuser, scene->r.cfra, 0);
2093                         }
2094                 }
2095         }
2096         
2097         /* image window, compo node users */
2098         if(wm) {
2099                 for(win= wm->windows.first; win; win= win->next) {
2100                         ScrArea *sa;
2101                         for(sa= win->screen->areabase.first; sa; sa= sa->next) {
2102                                 if(sa->spacetype==SPACE_VIEW3D) {
2103                                         View3D *v3d= sa->spacedata.first;
2104                                         BGpic *bgpic;
2105                                         for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
2106                                                 if(bgpic->iuser.flag & IMA_ANIM_ALWAYS)
2107                                                         BKE_image_user_calc_frame(&bgpic->iuser, scene->r.cfra, 0);
2108                                 }
2109                                 else if(sa->spacetype==SPACE_IMAGE) {
2110                                         SpaceImage *sima= sa->spacedata.first;
2111                                         if(sima->iuser.flag & IMA_ANIM_ALWAYS)
2112                                                 BKE_image_user_calc_frame(&sima->iuser, scene->r.cfra, 0);
2113                                 }
2114                                 else if(sa->spacetype==SPACE_NODE) {
2115                                         SpaceNode *snode= sa->spacedata.first;
2116                                         if((snode->treetype==NTREE_COMPOSIT) && (snode->nodetree)) {
2117                                                 bNode *node;
2118                                                 for(node= snode->nodetree->nodes.first; node; node= node->next) {
2119                                                         if(node->id && node->type==CMP_NODE_IMAGE) {
2120                                                                 Image *ima= (Image *)node->id;
2121                                                                 ImageUser *iuser= node->storage;
2122                                                                 if(ELEM(ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE))
2123                                                                         if(iuser->flag & IMA_ANIM_ALWAYS)
2124                                                                                 BKE_image_user_calc_frame(iuser, scene->r.cfra, 0);
2125                                                         }
2126                                                 }
2127                                         }
2128                                 }
2129                         }
2130                 }
2131         }
2132 }
2133