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