colorband and image header were ignoring DPI size
[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
49 #include "BKE_colortools.h"
50 #include "BKE_context.h"
51 #include "BKE_image.h"
52 #include "BKE_global.h"
53 #include "BKE_library.h"
54 #include "BKE_main.h"
55 #include "BKE_node.h"
56 #include "BKE_packedFile.h"
57 #include "BKE_report.h"
58 #include "BKE_screen.h"
59
60 #include "IMB_imbuf.h"
61 #include "IMB_imbuf_types.h"
62
63 #include "RE_pipeline.h"
64
65 #include "RNA_access.h"
66 #include "RNA_define.h"
67 #include "RNA_enum_types.h"
68
69 #include "ED_image.h"
70 #include "ED_render.h"
71 #include "ED_screen.h"
72 #include "ED_space_api.h"
73 #include "ED_uvedit.h"
74 #include "ED_util.h"
75
76 #include "UI_interface.h"
77 #include "UI_resources.h"
78 #include "UI_view2d.h"
79
80 #include "WM_api.h"
81 #include "WM_types.h"
82
83 #include "image_intern.h"
84
85 /******************** view navigation utilities *********************/
86
87 static void sima_zoom_set(SpaceImage *sima, ARegion *ar, float zoom)
88 {
89         float oldzoom= sima->zoom;
90         int width, height;
91
92         sima->zoom= zoom;
93
94         if (sima->zoom > 0.1f && sima->zoom < 4.0f)
95                 return;
96
97         /* check zoom limits */
98         ED_space_image_size(sima, &width, &height);
99
100         width *= sima->zoom;
101         height *= sima->zoom;
102
103         if((width < 4) && (height < 4))
104                 sima->zoom= oldzoom;
105         else if((ar->winrct.xmax - ar->winrct.xmin) <= sima->zoom)
106                 sima->zoom= oldzoom;
107         else if((ar->winrct.ymax - ar->winrct.ymin) <= sima->zoom)
108                 sima->zoom= oldzoom;
109 }
110
111 static void sima_zoom_set_factor(SpaceImage *sima, ARegion *ar, float zoomfac)
112 {
113         sima_zoom_set(sima, ar, sima->zoom*zoomfac);
114 }
115
116 #if 0 // currently unused
117 static int image_poll(bContext *C)
118 {
119         return (CTX_data_edit_image(C) != NULL);
120 }
121 #endif
122
123 static int space_image_buffer_exists_poll(bContext *C)
124 {
125         SpaceImage *sima= CTX_wm_space_image(C);
126         if(sima && sima->spacetype==SPACE_IMAGE)
127                 if(ED_space_image_has_buffer(sima))
128                         return 1;
129         return 0;
130 }
131
132 static int space_image_file_exists_poll(bContext *C)
133 {
134         if(space_image_buffer_exists_poll(C)) {
135                 Main *bmain= CTX_data_main(C);
136                 SpaceImage *sima= CTX_wm_space_image(C);
137                 ImBuf *ibuf;
138                 void *lock;
139                 int poll= 0;
140                 char name[FILE_MAX];
141
142                 ibuf= ED_space_image_acquire_buffer(sima, &lock);
143                 if(ibuf) {
144                         BLI_strncpy(name, ibuf->name, FILE_MAX);
145                         BLI_path_abs(name, bmain->name);
146                         poll= (BLI_exists(name) && BLI_is_writable(name));
147                 }
148                 ED_space_image_release_buffer(sima, lock);
149
150                 return poll;
151         }
152         return 0;
153 }
154
155 static int space_image_poll(bContext *C)
156 {
157         SpaceImage *sima= CTX_wm_space_image(C);
158         if(sima && sima->spacetype==SPACE_IMAGE && sima->image)
159                 return 1;
160         return 0;
161 }
162
163 int space_image_main_area_poll(bContext *C)
164 {
165         SpaceImage *sima= CTX_wm_space_image(C);
166         // XXX ARegion *ar= CTX_wm_region(C);
167
168         if(sima)
169                 return 1; // XXX (ar && ar->type->regionid == RGN_TYPE_WINDOW);
170         
171         return 0;
172 }
173
174 /********************** view pan operator *********************/
175
176 typedef struct ViewPanData {
177         float x, y;
178         float xof, yof;
179         int event_type;
180 } ViewPanData;
181
182 static void view_pan_init(bContext *C, wmOperator *op, wmEvent *event)
183 {
184         SpaceImage *sima= CTX_wm_space_image(C);
185         ViewPanData *vpd;
186
187         op->customdata= vpd= MEM_callocN(sizeof(ViewPanData), "ImageViewPanData");
188         WM_cursor_modal(CTX_wm_window(C), BC_NSEW_SCROLLCURSOR);
189
190         vpd->x= event->x;
191         vpd->y= event->y;
192         vpd->xof= sima->xof;
193         vpd->yof= sima->yof;
194         vpd->event_type= event->type;
195
196         WM_event_add_modal_handler(C, op);
197 }
198
199 static void view_pan_exit(bContext *C, wmOperator *op, int cancel)
200 {
201         SpaceImage *sima= CTX_wm_space_image(C);
202         ViewPanData *vpd= op->customdata;
203
204         if(cancel) {
205                 sima->xof= vpd->xof;
206                 sima->yof= vpd->yof;
207                 ED_region_tag_redraw(CTX_wm_region(C));
208         }
209
210         WM_cursor_restore(CTX_wm_window(C));
211         MEM_freeN(op->customdata);
212 }
213
214 static int view_pan_exec(bContext *C, wmOperator *op)
215 {
216         SpaceImage *sima= CTX_wm_space_image(C);
217         float offset[2];
218
219         RNA_float_get_array(op->ptr, "offset", offset);
220         sima->xof += offset[0];
221         sima->yof += offset[1];
222
223         ED_region_tag_redraw(CTX_wm_region(C));
224
225         /* XXX notifier? */
226 #if 0
227         if(image_preview_active(curarea, NULL, NULL)) {
228                 /* recalculates new preview rect */
229                 scrarea_do_windraw(curarea);
230                 image_preview_event(2);
231         }
232 #endif
233         
234         return OPERATOR_FINISHED;
235 }
236
237 static int view_pan_invoke(bContext *C, wmOperator *op, wmEvent *event)
238 {
239         if (event->type == MOUSEPAN) {
240                 SpaceImage *sima= CTX_wm_space_image(C);
241                 float offset[2];
242                 
243                 offset[0]= (event->x - event->prevx)/sima->zoom;
244                 offset[1]= (event->y - event->prevy)/sima->zoom;
245                 RNA_float_set_array(op->ptr, "offset", offset);
246
247                 view_pan_exec(C, op);
248                 return OPERATOR_FINISHED;
249         }
250         else {
251                 view_pan_init(C, op, event);
252                 return OPERATOR_RUNNING_MODAL;
253         }
254 }
255
256 static int view_pan_modal(bContext *C, wmOperator *op, wmEvent *event)
257 {
258         SpaceImage *sima= CTX_wm_space_image(C);
259         ViewPanData *vpd= op->customdata;
260         float offset[2];
261
262         switch(event->type) {
263                 case MOUSEMOVE:
264                         sima->xof= vpd->xof;
265                         sima->yof= vpd->yof;
266                         offset[0]= (vpd->x - event->x)/sima->zoom;
267                         offset[1]= (vpd->y - event->y)/sima->zoom;
268                         RNA_float_set_array(op->ptr, "offset", offset);
269                         view_pan_exec(C, op);
270                         break;
271                 default:
272                         if(event->type==vpd->event_type &&  event->val==KM_RELEASE) {
273                                 view_pan_exit(C, op, 0);
274                                 return OPERATOR_FINISHED;
275                         }
276                         break;
277         }
278
279         return OPERATOR_RUNNING_MODAL;
280 }
281
282 static int view_pan_cancel(bContext *C, wmOperator *op)
283 {
284         view_pan_exit(C, op, 1);
285         return OPERATOR_CANCELLED;
286 }
287
288 void IMAGE_OT_view_pan(wmOperatorType *ot)
289 {
290         /* identifiers */
291         ot->name= "View Pan";
292         ot->idname= "IMAGE_OT_view_pan";
293         
294         /* api callbacks */
295         ot->exec= view_pan_exec;
296         ot->invoke= view_pan_invoke;
297         ot->modal= view_pan_modal;
298         ot->cancel= view_pan_cancel;
299         ot->poll= space_image_main_area_poll;
300
301         /* flags */
302         ot->flag= OPTYPE_BLOCKING;
303         
304         /* properties */
305         RNA_def_float_vector(ot->srna, "offset", 2, NULL, -FLT_MAX, FLT_MAX,
306                 "Offset", "Offset in floating point units, 1.0 is the width and height of the image.", -FLT_MAX, FLT_MAX);
307 }
308
309 /********************** view zoom operator *********************/
310
311 typedef struct ViewZoomData {
312         float x, y;
313         float zoom;
314         int event_type;
315 } ViewZoomData;
316
317 static void view_zoom_init(bContext *C, wmOperator *op, wmEvent *event)
318 {
319         SpaceImage *sima= CTX_wm_space_image(C);
320         ViewZoomData *vpd;
321
322         op->customdata= vpd= MEM_callocN(sizeof(ViewZoomData), "ImageViewZoomData");
323         WM_cursor_modal(CTX_wm_window(C), BC_NSEW_SCROLLCURSOR);
324
325         vpd->x= event->x;
326         vpd->y= event->y;
327         vpd->zoom= sima->zoom;
328         vpd->event_type= event->type;
329         
330         WM_event_add_modal_handler(C, op);
331 }
332
333 static void view_zoom_exit(bContext *C, wmOperator *op, int cancel)
334 {
335         SpaceImage *sima= CTX_wm_space_image(C);
336         ViewZoomData *vpd= op->customdata;
337
338         if(cancel) {
339                 sima->zoom= vpd->zoom;
340                 ED_region_tag_redraw(CTX_wm_region(C));
341         }
342
343         WM_cursor_restore(CTX_wm_window(C));
344         MEM_freeN(op->customdata);
345 }
346
347 static int view_zoom_exec(bContext *C, wmOperator *op)
348 {
349         SpaceImage *sima= CTX_wm_space_image(C);
350         ARegion *ar= CTX_wm_region(C);
351
352         sima_zoom_set_factor(sima, ar, RNA_float_get(op->ptr, "factor"));
353
354         ED_region_tag_redraw(CTX_wm_region(C));
355
356         /* XXX notifier? */
357 #if 0
358         if(image_preview_active(curarea, NULL, NULL)) {
359                 /* recalculates new preview rect */
360                 scrarea_do_windraw(curarea);
361                 image_preview_event(2);
362         }
363 #endif
364         
365         return OPERATOR_FINISHED;
366 }
367
368 static int view_zoom_invoke(bContext *C, wmOperator *op, wmEvent *event)
369 {
370         if (event->type == MOUSEZOOM) {
371                 SpaceImage *sima= CTX_wm_space_image(C);
372                 ARegion *ar= CTX_wm_region(C);
373                 float factor;
374                 
375                 factor= 1.0f + (event->x-event->prevx+event->y-event->prevy)/300.0f;
376                 RNA_float_set(op->ptr, "factor", factor);
377                 sima_zoom_set(sima, ar, sima->zoom*factor);
378                 ED_region_tag_redraw(CTX_wm_region(C));
379                 
380                 return OPERATOR_FINISHED;
381         }
382         else {
383                 view_zoom_init(C, op, event);
384                 return OPERATOR_RUNNING_MODAL;
385         }
386 }
387
388 static int view_zoom_modal(bContext *C, wmOperator *op, wmEvent *event)
389 {
390         SpaceImage *sima= CTX_wm_space_image(C);
391         ARegion *ar= CTX_wm_region(C);
392         ViewZoomData *vpd= op->customdata;
393         float factor;
394
395         switch(event->type) {
396                 case MOUSEMOVE:
397                         factor= 1.0f + (vpd->x-event->x+vpd->y-event->y)/300.0f;
398                         RNA_float_set(op->ptr, "factor", factor);
399                         sima_zoom_set(sima, ar, vpd->zoom*factor);
400                         ED_region_tag_redraw(CTX_wm_region(C));
401                         break;
402                 default:
403                         if(event->type==vpd->event_type && event->val==KM_RELEASE) {
404                                 view_zoom_exit(C, op, 0);
405                                 return OPERATOR_FINISHED;
406                         }
407                         break;
408         }
409
410         return OPERATOR_RUNNING_MODAL;
411 }
412
413 static int view_zoom_cancel(bContext *C, wmOperator *op)
414 {
415         view_zoom_exit(C, op, 1);
416         return OPERATOR_CANCELLED;
417 }
418
419 void IMAGE_OT_view_zoom(wmOperatorType *ot)
420 {
421         /* identifiers */
422         ot->name= "View Zoom";
423         ot->idname= "IMAGE_OT_view_zoom";
424         
425         /* api callbacks */
426         ot->exec= view_zoom_exec;
427         ot->invoke= view_zoom_invoke;
428         ot->modal= view_zoom_modal;
429         ot->cancel= view_zoom_cancel;
430         ot->poll= space_image_main_area_poll;
431
432         /* flags */
433         ot->flag= OPTYPE_BLOCKING;
434         
435         /* properties */
436         RNA_def_float(ot->srna, "factor", 0.0f, 0.0f, FLT_MAX,
437                 "Factor", "Zoom factor, values higher than 1.0 zoom in, lower values zoom out.", -FLT_MAX, FLT_MAX);
438 }
439
440 /********************** view all operator *********************/
441
442 /* Updates the fields of the View2D member of the SpaceImage struct.
443  * Default behavior is to reset the position of the image and set the zoom to 1
444  * If the image will not fit within the window rectangle, the zoom is adjusted */
445
446 static int view_all_exec(bContext *C, wmOperator *UNUSED(op))
447 {
448         SpaceImage *sima;
449         ARegion *ar;
450         float aspx, aspy, zoomx, zoomy, w, h;
451         int width, height;
452
453         /* retrieve state */
454         sima= CTX_wm_space_image(C);
455         ar= CTX_wm_region(C);
456
457         ED_space_image_size(sima, &width, &height);
458         ED_space_image_aspect(sima, &aspx, &aspy);
459
460         w= width*aspx;
461         h= height*aspy;
462         
463         /* check if the image will fit in the image with zoom==1 */
464         width = ar->winrct.xmax - ar->winrct.xmin + 1;
465         height = ar->winrct.ymax - ar->winrct.ymin + 1;
466
467         if((w >= width || h >= height) && (width > 0 && height > 0)) {
468                 /* find the zoom value that will fit the image in the image space */
469                 zoomx= width/w;
470                 zoomy= height/h;
471                 sima_zoom_set(sima, ar, 1.0f/power_of_2(1/MIN2(zoomx, zoomy)));
472         }
473         else
474                 sima_zoom_set(sima, ar, 1.0f);
475
476         sima->xof= sima->yof= 0.0f;
477
478         ED_region_tag_redraw(CTX_wm_region(C));
479         
480         return OPERATOR_FINISHED;
481 }
482
483 void IMAGE_OT_view_all(wmOperatorType *ot)
484 {
485         /* identifiers */
486         ot->name= "View All";
487         ot->idname= "IMAGE_OT_view_all";
488         
489         /* api callbacks */
490         ot->exec= view_all_exec;
491         ot->poll= space_image_main_area_poll;
492 }
493
494 /********************** view selected operator *********************/
495
496 static int view_selected_exec(bContext *C, wmOperator *UNUSED(op))
497 {
498         SpaceImage *sima;
499         ARegion *ar;
500         Scene *scene;
501         Object *obedit;
502         Image *ima;
503         float size, min[2], max[2], d[2];
504         int width, height;
505
506         /* retrieve state */
507         sima= CTX_wm_space_image(C);
508         ar= CTX_wm_region(C);
509         scene= (Scene*)CTX_data_scene(C);
510         obedit= CTX_data_edit_object(C);
511
512         ima= ED_space_image(sima);
513         ED_space_image_size(sima, &width, &height);
514
515         /* get bounds */
516         if(!ED_uvedit_minmax(scene, ima, obedit, min, max))
517                 return OPERATOR_CANCELLED;
518
519         /* adjust offset and zoom */
520         sima->xof= (int)(((min[0] + max[0])*0.5f - 0.5f)*width);
521         sima->yof= (int)(((min[1] + max[1])*0.5f - 0.5f)*height);
522
523         d[0]= max[0] - min[0];
524         d[1]= max[1] - min[1];
525         size= 0.5f*MAX2(d[0], d[1])*MAX2(width, height)/256.0f;
526         
527         if(size<=0.01f) size= 0.01f;
528         sima_zoom_set(sima, ar, 0.7f/size);
529
530         ED_region_tag_redraw(CTX_wm_region(C));
531         
532         return OPERATOR_FINISHED;
533 }
534
535 static int view_selected_poll(bContext *C)
536 {
537         return (space_image_main_area_poll(C) && ED_operator_uvedit(C));
538 }
539
540 void IMAGE_OT_view_selected(wmOperatorType *ot)
541 {
542         /* identifiers */
543         ot->name= "View Center";
544         ot->idname= "IMAGE_OT_view_selected";
545         
546         /* api callbacks */
547         ot->exec= view_selected_exec;
548         ot->poll= view_selected_poll;
549 }
550
551 /********************** view zoom in/out operator *********************/
552
553 static int view_zoom_in_exec(bContext *C, wmOperator *UNUSED(op))
554 {
555         SpaceImage *sima= CTX_wm_space_image(C);
556         ARegion *ar= CTX_wm_region(C);
557
558         sima_zoom_set_factor(sima, ar, 1.25f);
559
560         ED_region_tag_redraw(CTX_wm_region(C));
561         
562         return OPERATOR_FINISHED;
563 }
564
565 void IMAGE_OT_view_zoom_in(wmOperatorType *ot)
566 {
567         /* identifiers */
568         ot->name= "View Zoom In";
569         ot->idname= "IMAGE_OT_view_zoom_in";
570         
571         /* api callbacks */
572         ot->exec= view_zoom_in_exec;
573         ot->poll= space_image_main_area_poll;
574 }
575
576 static int view_zoom_out_exec(bContext *C, wmOperator *UNUSED(op))
577 {
578         SpaceImage *sima= CTX_wm_space_image(C);
579         ARegion *ar= CTX_wm_region(C);
580
581         sima_zoom_set_factor(sima, ar, 0.8f);
582
583         ED_region_tag_redraw(CTX_wm_region(C));
584         
585         return OPERATOR_FINISHED;
586 }
587
588 void IMAGE_OT_view_zoom_out(wmOperatorType *ot)
589 {
590         /* identifiers */
591         ot->name= "View Zoom Out";
592         ot->idname= "IMAGE_OT_view_zoom_out";
593         
594         /* api callbacks */
595         ot->exec= view_zoom_out_exec;
596         ot->poll= space_image_main_area_poll;
597 }
598
599 /********************** view zoom ratio operator *********************/
600
601 static int view_zoom_ratio_exec(bContext *C, wmOperator *op)
602 {
603         SpaceImage *sima= CTX_wm_space_image(C);
604         ARegion *ar= CTX_wm_region(C);
605
606         sima_zoom_set(sima, ar, RNA_float_get(op->ptr, "ratio"));
607         
608         /* ensure pixel exact locations for draw */
609         sima->xof= (int)sima->xof;
610         sima->yof= (int)sima->yof;
611
612         /* XXX notifier? */
613 #if 0
614         if(image_preview_active(curarea, NULL, NULL)) {
615                 /* recalculates new preview rect */
616                 scrarea_do_windraw(curarea);
617                 image_preview_event(2);
618         }
619 #endif
620
621         ED_region_tag_redraw(CTX_wm_region(C));
622         
623         return OPERATOR_FINISHED;
624 }
625
626 void IMAGE_OT_view_zoom_ratio(wmOperatorType *ot)
627 {
628         /* identifiers */
629         ot->name= "View Zoom Ratio";
630         ot->idname= "IMAGE_OT_view_zoom_ratio";
631         
632         /* api callbacks */
633         ot->exec= view_zoom_ratio_exec;
634         ot->poll= space_image_main_area_poll;
635         
636         /* properties */
637         RNA_def_float(ot->srna, "ratio", 0.0f, 0.0f, FLT_MAX,
638                 "Ratio", "Zoom ratio, 1.0 is 1:1, higher is zoomed in, lower is zoomed out.", -FLT_MAX, FLT_MAX);
639 }
640
641 /**************** load/replace/save callbacks ******************/
642
643 /* XXX make dynamic */
644 static const EnumPropertyItem image_file_type_items[] = {
645                 {R_TARGA, "TARGA", 0, "Targa", ""},
646                 {R_RAWTGA, "TARGA RAW", 0, "Targa Raw", ""},
647                 {R_PNG, "PNG", 0, "PNG", ""},
648 #ifdef WITH_DDS
649                 {R_DDS, "DDS", 0, "DirectDraw Surface", ""},
650 #endif
651                 {R_BMP, "BMP", 0, "BMP", ""},
652                 {R_JPEG90, "JPEG", 0, "Jpeg", ""},
653 #ifdef WITH_OPENJPEG
654                 {R_JP2, "JPEG_2000", 0, "Jpeg 2000", ""},
655 #endif
656                 {R_IRIS, "IRIS", 0, "Iris", ""},
657 #ifdef WITH_TIFF
658                 {R_TIFF, "TIFF", 0, "Tiff", ""},
659 #endif
660 #ifdef WITH_DDS
661                 {R_RADHDR, "RADIANCE_HDR", 0, "Radiance HDR", ""},
662 #endif
663 #ifdef WITH_CINEON
664                 {R_CINEON, "CINEON", 0, "Cineon", ""},
665                 {R_DPX, "DPX", 0, "DPX", ""},
666 #endif
667 #ifdef WITH_OPENEXR
668                 {R_OPENEXR, "OPENEXR", 0, "OpenEXR", ""},
669         /* saving sequences of multilayer won't work, they copy buffers  */
670         /*if(ima->source==IMA_SRC_SEQUENCE && ima->type==IMA_TYPE_MULTILAYER);
671         else*/
672                 {R_MULTILAYER, "MULTILAYER", 0, "MultiLayer", ""},
673 #endif  
674                 {0, NULL, 0, NULL, NULL}};
675
676 static void image_filesel(bContext *C, wmOperator *op, const char *path)
677 {
678         RNA_string_set(op->ptr, "filepath", path);
679         WM_event_add_fileselect(C, op); 
680 }
681
682 /******************** open image operator ********************/
683
684 static void open_init(bContext *C, wmOperator *op)
685 {
686         PropertyPointerRNA *pprop;
687
688         op->customdata= pprop= MEM_callocN(sizeof(PropertyPointerRNA), "OpenPropertyPointerRNA");
689         uiIDContextProperty(C, &pprop->ptr, &pprop->prop);
690 }
691
692 static int open_cancel(bContext *UNUSED(C), wmOperator *op)
693 {
694         MEM_freeN(op->customdata);
695         op->customdata= NULL;
696         return OPERATOR_CANCELLED;
697 }
698
699 static int open_exec(bContext *C, wmOperator *op)
700 {
701         SpaceImage *sima= CTX_wm_space_image(C); /* XXX other space types can call */
702         Scene *scene= CTX_data_scene(C);
703         Object *obedit= CTX_data_edit_object(C);
704         ImageUser *iuser= NULL;
705         PropertyPointerRNA *pprop;
706         PointerRNA idptr;
707         Image *ima= NULL;
708         char str[FILE_MAX];
709
710         RNA_string_get(op->ptr, "filepath", str);
711         /* default to frame 1 if there's no scene in context */
712
713         errno= 0;
714
715         ima= BKE_add_image_file(str);
716
717         if(!ima) {
718                 if(op->customdata) MEM_freeN(op->customdata);
719                 BKE_reportf(op->reports, RPT_ERROR, "Can't read: \"%s\", %s.", str, errno ? strerror(errno) : "Unsupported image format");
720                 return OPERATOR_CANCELLED;
721         }
722         
723         if(!op->customdata)
724                 open_init(C, op);
725
726         /* hook into UI */
727         pprop= op->customdata;
728
729         if(pprop->prop) {
730                 /* when creating new ID blocks, use is already 1, but RNA
731                  * pointer se also increases user, so this compensates it */
732                 ima->id.us--;
733
734                 RNA_id_pointer_create(&ima->id, &idptr);
735                 RNA_property_pointer_set(&pprop->ptr, pprop->prop, idptr);
736                 RNA_property_update(C, &pprop->ptr, pprop->prop);
737         }
738         else if(sima) {
739                 ED_space_image_set(C, sima, scene, obedit, ima);
740                 iuser= &sima->iuser;
741         }
742         else {
743                 Tex *tex= CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
744                 if(tex && tex->type==TEX_IMAGE)
745                         iuser= &tex->iuser;
746                 
747         }
748         
749         /* initialize because of new image */
750         if(iuser) {
751                 iuser->sfra= 1;
752                 iuser->offset= 0;
753                 iuser->fie_ima= 2;
754         }
755
756         /* XXX unpackImage frees image buffers */
757         ED_preview_kill_jobs(C);
758         
759         BKE_image_signal(ima, iuser, IMA_SIGNAL_RELOAD);
760         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
761         
762         MEM_freeN(op->customdata);
763
764         return OPERATOR_FINISHED;
765 }
766
767 static int open_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
768 {
769         SpaceImage *sima= CTX_wm_space_image(C); /* XXX other space types can call */
770         char *path=U.textudir;
771         Image *ima= NULL;
772
773         if(sima) {
774                 ima= sima->image;
775         }
776
777         if (ima==NULL) {
778                 Tex *tex= CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
779                 if(tex && tex->type==TEX_IMAGE)
780                         ima= tex->ima;
781         }
782
783         if(ima)
784                 path= ima->name;
785         
786
787         if(!RNA_property_is_set(op->ptr, "relative_path"))
788                 RNA_boolean_set(op->ptr, "relative_path", U.flag & USER_RELPATHS);
789
790         if(RNA_property_is_set(op->ptr, "filepath"))
791                 return open_exec(C, op);
792         
793         open_init(C, op);
794
795         image_filesel(C, op, path);
796
797         return OPERATOR_RUNNING_MODAL;
798 }
799
800 /* called by other space types too */
801 void IMAGE_OT_open(wmOperatorType *ot)
802 {
803         /* identifiers */
804         ot->name= "Open Image";
805         ot->description= "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->description= "Create a new image";
1350         ot->idname= "IMAGE_OT_new";
1351         
1352         /* api callbacks */
1353         ot->exec= image_new_exec;
1354         ot->invoke= image_new_invoke;
1355         
1356         /* flags */
1357         ot->flag= OPTYPE_UNDO;
1358
1359         /* properties */
1360         RNA_def_string(ot->srna, "name", "untitled", MAX_ID_NAME-2, "Name", "Image datablock name.");
1361         RNA_def_int(ot->srna, "width", 1024, 1, INT_MAX, "Width", "Image width.", 1, 16384);
1362         RNA_def_int(ot->srna, "height", 1024, 1, INT_MAX, "Height", "Image height.", 1, 16384);
1363         prop= RNA_def_float_color(ot->srna, "color", 4, NULL, 0.0f, FLT_MAX, "Color", "Default fill color.", 0.0f, 1.0f);
1364         RNA_def_property_float_array_default(prop, default_color);
1365         RNA_def_boolean(ot->srna, "alpha", 1, "Alpha", "Create an image with an alpha channel.");
1366         RNA_def_boolean(ot->srna, "uv_test_grid", 0, "UV Test Grid", "Fill the image with a grid for UV map testing.");
1367         RNA_def_boolean(ot->srna, "float", 0, "32 bit Float", "Create image with 32 bit floating point bit depth.");
1368 }
1369
1370 /********************* invert operators *********************/
1371
1372 static int image_invert_poll(bContext *C)
1373 {
1374         Image *ima= CTX_data_edit_image(C);
1375         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1376         
1377         if( ibuf != NULL )
1378                 return 1;
1379         return 0;
1380 }
1381
1382 static int image_invert_exec(bContext *C, wmOperator *op)
1383 {
1384         Image *ima= CTX_data_edit_image(C);
1385         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1386
1387         // flags indicate if this channel should be inverted
1388         const short r= RNA_boolean_get(op->ptr, "invert_r");
1389         const short g= RNA_boolean_get(op->ptr, "invert_g");
1390         const short b= RNA_boolean_get(op->ptr, "invert_b");
1391         const short a= RNA_boolean_get(op->ptr, "invert_a");
1392
1393         int i;
1394
1395         if( ibuf == NULL) // TODO: this should actually never happen, but does for render-results -> cleanup
1396                 return OPERATOR_CANCELLED;
1397
1398         /* TODO: make this into an IMB_invert_channels(ibuf,r,g,b,a) method!? */
1399         if (ibuf->rect_float) {
1400                 
1401                 float *fp = (float *) ibuf->rect_float;
1402                 for( i = ibuf->x * ibuf->y; i > 0; i--, fp+=4 ) {
1403                         if( r ) fp[0] = 1.0f - fp[0];
1404                         if( g ) fp[1] = 1.0f - fp[1];
1405                         if( b ) fp[2] = 1.0f - fp[2];
1406                         if( a ) fp[3] = 1.0f - fp[3];
1407                 }
1408
1409                 if(ibuf->rect) {
1410                         IMB_rect_from_float(ibuf);
1411                 }
1412         }
1413         else if(ibuf->rect) {
1414                 
1415                 char *cp = (char *) ibuf->rect;
1416                 for( i = ibuf->x * ibuf->y; i > 0; i--, cp+=4 ) {
1417                         if( r ) cp[0] = 255 - cp[0];
1418                         if( g ) cp[1] = 255 - cp[1];
1419                         if( b ) cp[2] = 255 - cp[2];
1420                         if( a ) cp[3] = 255 - cp[3];
1421                 }
1422         }
1423         else {
1424                 return OPERATOR_CANCELLED;
1425         }
1426
1427         ibuf->userflags |= IB_BITMAPDIRTY;
1428         if(ibuf->mipmap[0])
1429                 ibuf->userflags |= IB_MIPMAP_INVALID;
1430
1431         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1432         return OPERATOR_FINISHED;
1433 }
1434
1435 void IMAGE_OT_invert(wmOperatorType *ot)
1436 {
1437         /* identifiers */
1438         ot->name= "Invert Channels";
1439         ot->idname= "IMAGE_OT_invert";
1440         
1441         /* api callbacks */
1442         ot->exec= image_invert_exec;
1443         ot->poll= image_invert_poll;
1444         
1445         /* properties */
1446         RNA_def_boolean(ot->srna, "invert_r", 0, "Red", "Invert Red Channel");
1447         RNA_def_boolean(ot->srna, "invert_g", 0, "Green", "Invert Green Channel");
1448         RNA_def_boolean(ot->srna, "invert_b", 0, "Blue", "Invert Blue Channel");
1449         RNA_def_boolean(ot->srna, "invert_a", 0, "Alpha", "Invert Alpha Channel");
1450         
1451         /* flags */
1452         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1453 }
1454
1455 /********************* pack operator *********************/
1456
1457 static int pack_test(bContext *C, wmOperator *op)
1458 {
1459         Image *ima= CTX_data_edit_image(C);
1460         int as_png= RNA_boolean_get(op->ptr, "as_png");
1461
1462         if(!ima)
1463                 return 0;
1464         if(!as_png && ima->packedfile)
1465                 return 0;
1466
1467         if(ima->source==IMA_SRC_SEQUENCE || ima->source==IMA_SRC_MOVIE) {
1468                 BKE_report(op->reports, RPT_ERROR, "Packing movies or image sequences not supported.");
1469                 return 0;
1470         }
1471
1472         return 1;
1473 }
1474
1475 static int pack_exec(bContext *C, wmOperator *op)
1476 {
1477         Image *ima= CTX_data_edit_image(C);
1478         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1479         int as_png= RNA_boolean_get(op->ptr, "as_png");
1480
1481         if(!pack_test(C, op))
1482                 return OPERATOR_CANCELLED;
1483         
1484         if(!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1485                 BKE_report(op->reports, RPT_ERROR, "Can't pack edited image from disk, only as internal PNG.");
1486                 return OPERATOR_CANCELLED;
1487         }
1488
1489         if(as_png)
1490                 BKE_image_memorypack(ima);
1491         else
1492                 ima->packedfile= newPackedFile(op->reports, ima->name);
1493
1494         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1495         
1496         return OPERATOR_FINISHED;
1497 }
1498
1499 static int pack_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1500 {
1501         Image *ima= CTX_data_edit_image(C);
1502         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1503         uiPopupMenu *pup;
1504         uiLayout *layout;
1505         int as_png= RNA_boolean_get(op->ptr, "as_png");
1506
1507         if(!pack_test(C, op))
1508                 return OPERATOR_CANCELLED;
1509         
1510         if(!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1511                 pup= uiPupMenuBegin(C, "OK", ICON_QUESTION);
1512                 layout= uiPupMenuLayout(pup);
1513                 uiItemBooleanO(layout, "Can't pack edited image from disk. Pack as internal PNG?", ICON_NONE, op->idname, "as_png", 1);
1514                 uiPupMenuEnd(C, pup);
1515
1516                 return OPERATOR_CANCELLED;
1517         }
1518
1519         return pack_exec(C, op);
1520 }
1521
1522 void IMAGE_OT_pack(wmOperatorType *ot)
1523 {
1524         /* identifiers */
1525         ot->name= "Pack Image";
1526         ot->description= "Pack an image as embedded data into the .blend file"; 
1527         ot->idname= "IMAGE_OT_pack";
1528         
1529         /* api callbacks */
1530         ot->exec= pack_exec;
1531         ot->invoke= pack_invoke;
1532
1533         /* flags */
1534         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1535
1536         /* properties */
1537         RNA_def_boolean(ot->srna, "as_png", 0, "Pack As PNG", "Pack image as lossless PNG.");
1538 }
1539
1540 /********************* unpack operator *********************/
1541
1542 static int image_unpack_exec(bContext *C, wmOperator *op)
1543 {
1544         Image *ima= CTX_data_edit_image(C);
1545         int method= RNA_enum_get(op->ptr, "method");
1546
1547         /* find the suppplied image by name */
1548         if (RNA_property_is_set(op->ptr, "id")) {
1549                 char imaname[MAX_ID_NAME-2];
1550                 RNA_string_get(op->ptr, "id", imaname);
1551                 ima = BLI_findstring(&CTX_data_main(C)->image, imaname, offsetof(ID, name) + 2);
1552                 if (!ima) ima = CTX_data_edit_image(C);
1553         }
1554         
1555         if(!ima || !ima->packedfile)
1556                 return OPERATOR_CANCELLED;
1557
1558         if(ima->source==IMA_SRC_SEQUENCE || ima->source==IMA_SRC_MOVIE) {
1559                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported.");
1560                 return OPERATOR_CANCELLED;
1561         }
1562
1563         if(G.fileflags & G_AUTOPACK)
1564                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save.");
1565         
1566         /* XXX unpackImage frees image buffers */
1567         ED_preview_kill_jobs(C);
1568         
1569         unpackImage(op->reports, ima, method);
1570         
1571         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1572
1573         return OPERATOR_FINISHED;
1574 }
1575
1576 static int image_unpack_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1577 {
1578         Image *ima= CTX_data_edit_image(C);
1579
1580         if(RNA_property_is_set(op->ptr, "id"))
1581                 return image_unpack_exec(C, op);
1582                 
1583         if(!ima || !ima->packedfile)
1584                 return OPERATOR_CANCELLED;
1585
1586         if(ima->source==IMA_SRC_SEQUENCE || ima->source==IMA_SRC_MOVIE) {
1587                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported.");
1588                 return OPERATOR_CANCELLED;
1589         }
1590
1591         if(G.fileflags & G_AUTOPACK)
1592                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save.");
1593
1594         unpack_menu(C, "IMAGE_OT_unpack", ima->id.name+2, ima->name, "textures", ima->packedfile);
1595
1596         return OPERATOR_FINISHED;
1597 }
1598
1599 void IMAGE_OT_unpack(wmOperatorType *ot)
1600 {
1601         /* identifiers */
1602         ot->name= "Unpack Image";
1603         ot->description= "Save an image packed in the .blend file to disk"; 
1604         ot->idname= "IMAGE_OT_unpack";
1605         
1606         /* api callbacks */
1607         ot->exec= image_unpack_exec;
1608         ot->invoke= image_unpack_invoke;
1609
1610         /* flags */
1611         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1612         
1613         /* properties */
1614         RNA_def_enum(ot->srna, "method", unpack_method_items, PF_USE_LOCAL, "Method", "How to unpack.");
1615         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 */
1616 }
1617
1618 /******************** sample image operator ********************/
1619
1620 typedef struct ImageSampleInfo {
1621         ARegionType *art;
1622         void *draw_handle;
1623         int x, y;
1624         int channels;
1625
1626         char col[4];
1627         float colf[4];
1628         int z;
1629         float zf;
1630
1631         char *colp;
1632         float *colfp;
1633         int *zp;
1634         float *zfp;
1635
1636         int draw;
1637 } ImageSampleInfo;
1638
1639 static void sample_draw(const bContext *UNUSED(C), ARegion *ar, void *arg_info)
1640 {
1641         ImageSampleInfo *info= arg_info;
1642         if(info->draw) {
1643                 /* no color management needed for images (color_manage=0) */
1644                 draw_image_info(ar, 0, info->channels, info->x, info->y, info->colp, info->colfp, info->zp, info->zfp);
1645         }
1646 }
1647
1648 static void sample_apply(bContext *C, wmOperator *op, wmEvent *event)
1649 {
1650         SpaceImage *sima= CTX_wm_space_image(C);
1651         ARegion *ar= CTX_wm_region(C);
1652         void *lock;
1653         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
1654         ImageSampleInfo *info= op->customdata;
1655         float fx, fy;
1656         
1657         if(ibuf == NULL) {
1658                 ED_space_image_release_buffer(sima, lock);
1659                 return;
1660         }
1661
1662         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &fx, &fy);
1663
1664         if(fx>=0.0f && fy>=0.0f && fx<1.0f && fy<1.0f) {
1665                 float *fp;
1666                 char *cp;
1667                 int x= (int)(fx*ibuf->x), y= (int)(fy*ibuf->y);
1668
1669                 CLAMP(x, 0, ibuf->x-1);
1670                 CLAMP(y, 0, ibuf->y-1);
1671
1672                 info->x= x;
1673                 info->y= y;
1674                 info->draw= 1;
1675                 info->channels= ibuf->channels;
1676
1677                 info->colp= NULL;
1678                 info->colfp= NULL;
1679                 info->zp= NULL;
1680                 info->zfp= NULL;
1681                 
1682                 if(ibuf->rect) {
1683                         cp= (char *)(ibuf->rect + y*ibuf->x + x);
1684
1685                         info->col[0]= cp[0];
1686                         info->col[1]= cp[1];
1687                         info->col[2]= cp[2];
1688                         info->col[3]= cp[3];
1689                         info->colp= info->col;
1690
1691                         info->colf[0]= (float)cp[0]/255.0f;
1692                         info->colf[1]= (float)cp[1]/255.0f;
1693                         info->colf[2]= (float)cp[2]/255.0f;
1694                         info->colf[3]= (float)cp[3]/255.0f;
1695                         info->colfp= info->colf;
1696                 }
1697                 if(ibuf->rect_float) {
1698                         fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
1699
1700                         info->colf[0]= fp[0];
1701                         info->colf[1]= fp[1];
1702                         info->colf[2]= fp[2];
1703                         info->colf[3]= fp[3];
1704                         info->colfp= info->colf;
1705                 }
1706
1707                 if(ibuf->zbuf) {
1708                         info->z= ibuf->zbuf[y*ibuf->x + x];
1709                         info->zp= &info->z;
1710                 }
1711                 if(ibuf->zbuf_float) {
1712                         info->zf= ibuf->zbuf_float[y*ibuf->x + x];
1713                         info->zfp= &info->zf;
1714                 }
1715                 
1716                 if(sima->cumap && ibuf->channels==4) {
1717                         /* we reuse this callback for set curves point operators */
1718                         if(RNA_struct_find_property(op->ptr, "point")) {
1719                                 int point= RNA_enum_get(op->ptr, "point");
1720
1721                                 if(point == 1) {
1722                                         curvemapping_set_black_white(sima->cumap, NULL, info->colfp);
1723                                         if(ibuf->rect_float)
1724                                                 curvemapping_do_ibuf(sima->cumap, ibuf);
1725                                 }
1726                                 else if(point == 0) {
1727                                         curvemapping_set_black_white(sima->cumap, info->colfp, NULL);
1728                                         if(ibuf->rect_float)
1729                                                 curvemapping_do_ibuf(sima->cumap, ibuf);
1730                                 }
1731                         }
1732                 }
1733                                 
1734                 // XXX node curve integration ..
1735 #if 0
1736                 {
1737                         ScrArea *sa, *cur= curarea;
1738                         
1739                         node_curvemap_sample(fp);       /* sends global to node editor */
1740                         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
1741                                 if(sa->spacetype==SPACE_NODE) {
1742                                         areawinset(sa->win);
1743                                         scrarea_do_windraw(sa);
1744                                 }
1745                         }
1746                         node_curvemap_sample(NULL);             /* clears global in node editor */
1747                         curarea= cur;
1748                 }
1749 #endif
1750         }
1751         else
1752                 info->draw= 0;
1753
1754         ED_space_image_release_buffer(sima, lock);
1755         ED_area_tag_redraw(CTX_wm_area(C));
1756 }
1757
1758 static void sample_exit(bContext *C, wmOperator *op)
1759 {
1760         ImageSampleInfo *info= op->customdata;
1761
1762         ED_region_draw_cb_exit(info->art, info->draw_handle);
1763         ED_area_tag_redraw(CTX_wm_area(C));
1764         MEM_freeN(info);
1765 }
1766
1767 static int sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1768 {
1769         SpaceImage *sima= CTX_wm_space_image(C);
1770         ARegion *ar= CTX_wm_region(C);
1771         ImageSampleInfo *info;
1772
1773         if(!ED_space_image_has_buffer(sima))
1774                 return OPERATOR_CANCELLED;
1775         
1776         info= MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
1777         info->art= ar->type;
1778         info->draw_handle = ED_region_draw_cb_activate(ar->type, sample_draw, info, REGION_DRAW_POST_PIXEL);
1779         op->customdata= info;
1780
1781         sample_apply(C, op, event);
1782
1783         WM_event_add_modal_handler(C, op);
1784
1785         return OPERATOR_RUNNING_MODAL;
1786 }
1787
1788 static int sample_modal(bContext *C, wmOperator *op, wmEvent *event)
1789 {
1790         switch(event->type) {
1791                 case LEFTMOUSE:
1792                 case RIGHTMOUSE: // XXX hardcoded
1793                         sample_exit(C, op);
1794                         return OPERATOR_CANCELLED;
1795                 case MOUSEMOVE:
1796                         sample_apply(C, op, event);
1797                         break;
1798         }
1799
1800         return OPERATOR_RUNNING_MODAL;
1801 }
1802
1803 static int sample_cancel(bContext *C, wmOperator *op)
1804 {
1805         sample_exit(C, op);
1806         return OPERATOR_CANCELLED;
1807 }
1808
1809 void IMAGE_OT_sample(wmOperatorType *ot)
1810 {
1811         /* identifiers */
1812         ot->name= "Sample Color";
1813         ot->idname= "IMAGE_OT_sample";
1814         
1815         /* api callbacks */
1816         ot->invoke= sample_invoke;
1817         ot->modal= sample_modal;
1818         ot->cancel= sample_cancel;
1819         ot->poll= space_image_main_area_poll;
1820
1821         /* flags */
1822         ot->flag= OPTYPE_BLOCKING;
1823 }
1824
1825 /******************** sample line operator ********************/
1826 static int sample_line_exec(bContext *C, wmOperator *op)
1827 {
1828         SpaceImage *sima= CTX_wm_space_image(C);
1829         ARegion *ar= CTX_wm_region(C);
1830         Scene *scene= CTX_data_scene(C);
1831         
1832         int x_start= RNA_int_get(op->ptr, "xstart");
1833         int y_start= RNA_int_get(op->ptr, "ystart");
1834         int x_end= RNA_int_get(op->ptr, "xend");
1835         int y_end= RNA_int_get(op->ptr, "yend");
1836         
1837         void *lock;
1838         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
1839         Histogram *hist= &sima->sample_line_hist;
1840         
1841         float x1f, y1f, x2f, y2f;
1842         int x1, y1, x2, y2;
1843         int i, x, y;
1844         float *fp;
1845         float rgb[3];
1846         unsigned char *cp;
1847         
1848         if (ibuf == NULL) {
1849                 ED_space_image_release_buffer(sima, lock);
1850                 return OPERATOR_CANCELLED;
1851         }
1852         /* hmmmm */
1853         if (ibuf->channels < 3) {
1854                 ED_space_image_release_buffer(sima, lock);
1855                 return OPERATOR_CANCELLED;
1856         }
1857         
1858         UI_view2d_region_to_view(&ar->v2d, x_start, y_start, &x1f, &y1f);
1859         UI_view2d_region_to_view(&ar->v2d, x_end, y_end, &x2f, &y2f);
1860         x1= 0.5f+ x1f*ibuf->x;
1861         x2= 0.5f+ x2f*ibuf->x;
1862         y1= 0.5f+ y1f*ibuf->y;
1863         y2= 0.5f+ y2f*ibuf->y;
1864         
1865         hist->channels = 3;
1866         hist->x_resolution = 256;
1867         hist->xmax = 1.0f;
1868         hist->ymax = 1.0f;
1869         
1870         for (i=0; i<256; i++) {
1871                 x= (int)(0.5f + x1 + (float)i*(x2-x1)/255.0f);
1872                 y= (int)(0.5f + y1 + (float)i*(y2-y1)/255.0f);
1873                 
1874                 if (x<0 || y<0 || x>=ibuf->x || y>=ibuf->y) {
1875                         hist->data_luma[i] = hist->data_r[i] = hist->data_g[i]= hist->data_b[i] = 0.0f;
1876                 } else {
1877                         if (ibuf->rect_float) {
1878                                 fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
1879
1880                                 if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
1881                                         linearrgb_to_srgb_v3_v3(rgb, fp);
1882                                 else
1883                                         copy_v3_v3(rgb, fp);
1884
1885                                 hist->data_r[i] = rgb[0];
1886                                 hist->data_g[i] = rgb[1];
1887                                 hist->data_b[i] = rgb[2];
1888                                 hist->data_luma[i] = (0.299f*rgb[0] + 0.587f*rgb[1] + 0.114f*rgb[2]);
1889                         }
1890                         else if (ibuf->rect) {
1891                                 cp= (unsigned char *)(ibuf->rect + y*ibuf->x + x);
1892                                 hist->data_r[i] = (float)cp[0]/255.0f;
1893                                 hist->data_g[i] = (float)cp[1]/255.0f;
1894                                 hist->data_b[i] = (float)cp[2]/255.0f;
1895                                 hist->data_luma[i] = (0.299f*cp[0] + 0.587f*cp[1] + 0.114f*cp[2])/255;
1896                         }
1897                 }
1898         }
1899         
1900         ED_space_image_release_buffer(sima, lock);
1901         
1902         ED_area_tag_redraw(CTX_wm_area(C));
1903         
1904         return OPERATOR_FINISHED;
1905 }
1906
1907 static int sample_line_invoke(bContext *C, wmOperator *op, wmEvent *event)
1908 {
1909         SpaceImage *sima= CTX_wm_space_image(C);
1910         
1911         if(!ED_space_image_has_buffer(sima))
1912                 return OPERATOR_CANCELLED;
1913         
1914         return WM_gesture_straightline_invoke(C, op, event);
1915 }
1916
1917 void IMAGE_OT_sample_line(wmOperatorType *ot)
1918 {
1919         /* identifiers */
1920         ot->name= "Sample Line";
1921         ot->idname= "IMAGE_OT_sample_line";
1922         
1923         /* api callbacks */
1924         ot->invoke= sample_line_invoke;
1925         ot->modal= WM_gesture_straightline_modal;
1926         ot->exec= sample_line_exec;
1927         ot->poll= space_image_main_area_poll;
1928         
1929         /* flags */
1930         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1931         
1932         WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT);
1933 }
1934
1935 /******************** set curve point operator ********************/
1936
1937 void IMAGE_OT_curves_point_set(wmOperatorType *ot)
1938 {
1939         static EnumPropertyItem point_items[]= {
1940                 {0, "BLACK_POINT", 0, "Black Point", ""},
1941                 {1, "WHITE_POINT", 0, "White Point", ""},
1942                 {0, NULL, 0, NULL, NULL}};
1943
1944         /* identifiers */
1945         ot->name= "Set Curves Point";
1946         ot->idname= "IMAGE_OT_curves_point_set";
1947
1948         /* flags */
1949         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1950         
1951         /* api callbacks */
1952         ot->invoke= sample_invoke;
1953         ot->modal= sample_modal;
1954         ot->cancel= sample_cancel;
1955         ot->poll= space_image_main_area_poll;
1956
1957         /* properties */
1958         RNA_def_enum(ot->srna, "point", point_items, 0, "Point", "Set black point or white point for curves.");
1959 }
1960
1961 /******************** record composite operator *********************/
1962
1963 typedef struct RecordCompositeData {
1964         wmTimer *timer;
1965         int old_cfra;
1966         int sfra, efra;
1967 } RecordCompositeData;
1968
1969 static int record_composite_apply(bContext *C, wmOperator *op)
1970 {
1971         SpaceImage *sima= CTX_wm_space_image(C);
1972         RecordCompositeData *rcd= op->customdata;
1973         Scene *scene= CTX_data_scene(C);
1974         ImBuf *ibuf;
1975         
1976         WM_timecursor(CTX_wm_window(C), scene->r.cfra);
1977
1978         // XXX scene->nodetree->test_break= blender_test_break;
1979         // XXX scene->nodetree->test_break= NULL;
1980         
1981         BKE_image_all_free_anim_ibufs(scene->r.cfra);
1982         ntreeCompositTagAnimated(scene->nodetree);
1983         ntreeCompositExecTree(scene->nodetree, &scene->r, scene->r.cfra != rcd->old_cfra);      /* 1 is no previews */
1984
1985         ED_area_tag_redraw(CTX_wm_area(C));
1986         
1987         ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
1988         /* save memory in flipbooks */
1989         if(ibuf)
1990                 imb_freerectfloatImBuf(ibuf);
1991         
1992         scene->r.cfra++;
1993
1994         return (scene->r.cfra <= rcd->efra);
1995 }
1996
1997 static int record_composite_init(bContext *C, wmOperator *op)
1998 {
1999         SpaceImage *sima= CTX_wm_space_image(C);
2000         Scene *scene= CTX_data_scene(C);
2001         RecordCompositeData *rcd;
2002
2003         if(sima->iuser.frames < 2)
2004                 return 0;
2005         if(scene->nodetree == NULL)
2006                 return 0;
2007         
2008         op->customdata= rcd= MEM_callocN(sizeof(RecordCompositeData), "ImageRecordCompositeData");
2009
2010         rcd->old_cfra= scene->r.cfra;
2011         rcd->sfra= sima->iuser.sfra;
2012         rcd->efra= sima->iuser.sfra + sima->iuser.frames-1;
2013         scene->r.cfra= rcd->sfra;
2014
2015         return 1;
2016 }
2017
2018 static void record_composite_exit(bContext *C, wmOperator *op)
2019 {
2020         Scene *scene= CTX_data_scene(C);
2021         SpaceImage *sima= CTX_wm_space_image(C);
2022         RecordCompositeData *rcd= op->customdata;
2023
2024         scene->r.cfra= rcd->old_cfra;
2025
2026         WM_cursor_restore(CTX_wm_window(C));
2027
2028         if(rcd->timer)
2029                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rcd->timer);
2030
2031         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, sima->image);
2032
2033         // XXX play_anim(0);
2034         // XXX allqueue(REDRAWNODE, 1);
2035
2036         MEM_freeN(rcd);
2037 }
2038
2039 static int record_composite_exec(bContext *C, wmOperator *op)
2040 {
2041         if(!record_composite_init(C, op))
2042                 return OPERATOR_CANCELLED;
2043         
2044         while(record_composite_apply(C, op))
2045                 ;
2046         
2047         record_composite_exit(C, op);
2048         
2049         return OPERATOR_FINISHED;
2050 }
2051
2052 static int record_composite_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2053 {
2054         RecordCompositeData *rcd;
2055         
2056         if(!record_composite_init(C, op))
2057                 return OPERATOR_CANCELLED;
2058
2059         rcd= op->customdata;
2060         rcd->timer= WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.0f);
2061         WM_event_add_modal_handler(C, op);
2062
2063         if(!record_composite_apply(C, op))
2064                 return OPERATOR_FINISHED;
2065
2066         return OPERATOR_RUNNING_MODAL;
2067 }
2068
2069 static int record_composite_modal(bContext *C, wmOperator *op, wmEvent *event)
2070 {
2071         RecordCompositeData *rcd= op->customdata;
2072
2073         switch(event->type) {
2074                 case TIMER:
2075                         if(rcd->timer == event->customdata) {
2076                                 if(!record_composite_apply(C, op)) {
2077                                         record_composite_exit(C, op);
2078                                         return OPERATOR_FINISHED;
2079                                 }
2080                         }
2081                         break;
2082                 case ESCKEY:
2083                         record_composite_exit(C, op);
2084                         return OPERATOR_FINISHED;
2085         }
2086
2087         return OPERATOR_RUNNING_MODAL;
2088 }
2089
2090 static int record_composite_cancel(bContext *C, wmOperator *op)
2091 {
2092         record_composite_exit(C, op);
2093         return OPERATOR_CANCELLED;
2094 }
2095
2096 void IMAGE_OT_record_composite(wmOperatorType *ot)
2097 {
2098         /* identifiers */
2099         ot->name= "Record Composite";
2100         ot->idname= "IMAGE_OT_record_composite";
2101         
2102         /* api callbacks */
2103         ot->exec= record_composite_exec;
2104         ot->invoke= record_composite_invoke;
2105         ot->modal= record_composite_modal;
2106         ot->cancel= record_composite_cancel;
2107         ot->poll= space_image_buffer_exists_poll;
2108 }
2109
2110 /********************* cycle render slot operator *********************/
2111
2112 static int cycle_render_slot_poll(bContext *C)
2113 {
2114         Image *ima= CTX_data_edit_image(C);
2115
2116         return (ima && ima->type == IMA_TYPE_R_RESULT);
2117 }
2118
2119 static int cycle_render_slot_exec(bContext *C, wmOperator *op)
2120 {
2121         Image *ima= CTX_data_edit_image(C);
2122         int a, slot, cur= ima->render_slot;
2123         const short use_reverse= RNA_boolean_get(op->ptr, "reverse");
2124
2125         for(a=1; a<IMA_MAX_RENDER_SLOT; a++) {
2126                 slot= (cur + (use_reverse ? -a:a))%IMA_MAX_RENDER_SLOT;
2127                 if(slot<0) slot+=IMA_MAX_RENDER_SLOT;
2128
2129                 if(ima->renders[slot] || slot == ima->last_render_slot) {
2130                         ima->render_slot= slot;
2131                         break;
2132                 }
2133                 else if((slot - 1) == ima->last_render_slot && slot < IMA_MAX_RENDER_SLOT) {
2134                         ima->render_slot= slot;
2135                         break;
2136                 }
2137         }
2138
2139         if(a == IMA_MAX_RENDER_SLOT)
2140                 ima->render_slot= ((cur == 1)? 0: 1);
2141         
2142         WM_event_add_notifier(C, NC_IMAGE|ND_DRAW, NULL);
2143
2144         /* no undo push for browsing existing */
2145         if(ima->renders[ima->render_slot] || ima->render_slot==ima->last_render_slot)
2146                 return OPERATOR_CANCELLED;
2147         
2148         return OPERATOR_FINISHED;
2149 }
2150
2151 void IMAGE_OT_cycle_render_slot(wmOperatorType *ot)
2152 {
2153         /* identifiers */
2154         ot->name= "Cycle Render Slot";
2155         ot->idname= "IMAGE_OT_cycle_render_slot";
2156         
2157         /* api callbacks */
2158         ot->exec= cycle_render_slot_exec;
2159         ot->poll= cycle_render_slot_poll;
2160
2161         /* flags */
2162         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2163
2164         RNA_def_boolean(ot->srna, "reverse", 0, "Cycle in Reverse", "");
2165 }
2166
2167 /******************** TODO ********************/
2168
2169 /* XXX notifier? */
2170
2171 /* goes over all ImageUsers, and sets frame numbers if auto-refresh is set */
2172
2173 void ED_image_update_frame(const Main *mainp, int cfra)
2174 {
2175         wmWindowManager *wm;
2176         wmWindow *win;
2177         Tex *tex;
2178         
2179         /* texture users */
2180         for(tex= mainp->tex.first; tex; tex= tex->id.next) {
2181                 if(tex->type==TEX_IMAGE && tex->ima) {
2182                         if(ELEM(tex->ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
2183                                 if(tex->iuser.flag & IMA_ANIM_ALWAYS)
2184                                         BKE_image_user_calc_frame(&tex->iuser, cfra, 0);
2185                         }
2186                 }
2187         }
2188         
2189         /* image window, compo node users */
2190         for(wm=mainp->wm.first; wm; wm= wm->id.next) { /* only 1 wm */
2191                 for(win= wm->windows.first; win; win= win->next) {
2192                         ScrArea *sa;
2193                         for(sa= win->screen->areabase.first; sa; sa= sa->next) {
2194                                 if(sa->spacetype==SPACE_VIEW3D) {
2195                                         View3D *v3d= sa->spacedata.first;
2196                                         BGpic *bgpic;
2197                                         for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
2198                                                 if(bgpic->iuser.flag & IMA_ANIM_ALWAYS)
2199                                                         BKE_image_user_calc_frame(&bgpic->iuser, cfra, 0);
2200                                 }
2201                                 else if(sa->spacetype==SPACE_IMAGE) {
2202                                         SpaceImage *sima= sa->spacedata.first;
2203                                         if(sima->iuser.flag & IMA_ANIM_ALWAYS)
2204                                                 BKE_image_user_calc_frame(&sima->iuser, cfra, 0);
2205                                 }
2206                                 else if(sa->spacetype==SPACE_NODE) {
2207                                         SpaceNode *snode= sa->spacedata.first;
2208                                         if((snode->treetype==NTREE_COMPOSIT) && (snode->nodetree)) {
2209                                                 bNode *node;
2210                                                 for(node= snode->nodetree->nodes.first; node; node= node->next) {
2211                                                         if(node->id && node->type==CMP_NODE_IMAGE) {
2212                                                                 Image *ima= (Image *)node->id;
2213                                                                 ImageUser *iuser= node->storage;
2214                                                                 if(ELEM(ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE))
2215                                                                         if(iuser->flag & IMA_ANIM_ALWAYS)
2216                                                                                 BKE_image_user_calc_frame(iuser, cfra, 0);
2217                                                         }
2218                                                 }
2219                                         }
2220                                 }
2221                         }
2222                 }
2223         }
2224 }
2225