6ec852b703c1e4ecfc9394159a84e9c3d9ec8a49
[blender.git] / source / blender / editors / space_image / image_ops.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2002-2009, Xavier Thomas
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/space_image/image_ops.c
27  *  \ingroup spimage
28  */
29
30
31 #include <stddef.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <errno.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_math.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_utildefines.h"
41
42 #include "DNA_object_types.h"
43 #include "DNA_node_types.h"
44 #include "DNA_packedFile_types.h"
45 #include "DNA_scene_types.h"
46
47 #include "BKE_colortools.h"
48 #include "BKE_context.h"
49 #include "BKE_image.h"
50 #include "BKE_global.h"
51 #include "BKE_library.h"
52 #include "BKE_main.h"
53 #include "BKE_node.h"
54 #include "BKE_packedFile.h"
55 #include "BKE_report.h"
56 #include "BKE_screen.h"
57
58 #include "IMB_colormanagement.h"
59 #include "IMB_imbuf.h"
60 #include "IMB_imbuf_types.h"
61
62 #include "RE_pipeline.h"
63
64 #include "RNA_access.h"
65 #include "RNA_define.h"
66 #include "RNA_enum_types.h"
67
68 #include "ED_image.h"
69 #include "ED_render.h"
70 #include "ED_screen.h"
71 #include "ED_space_api.h"
72 #include "ED_uvedit.h"
73 #include "ED_util.h"
74
75 #include "UI_interface.h"
76 #include "UI_resources.h"
77 #include "UI_view2d.h"
78
79 #include "WM_api.h"
80 #include "WM_types.h"
81
82 #include "image_intern.h"
83
84 /******************** view navigation utilities *********************/
85
86 static void sima_zoom_set(SpaceImage *sima, ARegion *ar, float zoom, float location[2])
87 {
88         float oldzoom = sima->zoom;
89         int width, height;
90
91         sima->zoom = zoom;
92
93         if (sima->zoom < 0.1f || sima->zoom > 4.0f) {
94                 /* check zoom limits */
95                 ED_space_image_get_size(sima, &width, &height);
96
97                 width *= sima->zoom;
98                 height *= sima->zoom;
99
100                 if ((width < 4) && (height < 4))
101                         sima->zoom = oldzoom;
102                 else if (BLI_RCT_SIZE_X(&ar->winrct) <= sima->zoom)
103                         sima->zoom = oldzoom;
104                 else if (BLI_RCT_SIZE_Y(&ar->winrct) <= sima->zoom)
105                         sima->zoom = oldzoom;
106         }
107
108         if ((U.uiflag & USER_ZOOM_TO_MOUSEPOS) && location) {
109                 float aspx, aspy, w, h;
110
111                 ED_space_image_get_size(sima, &width, &height);
112                 ED_space_image_get_aspect(sima, &aspx, &aspy);
113
114                 w = width * aspx;
115                 h = height * aspy;
116
117                 sima->xof += ((location[0] - 0.5f) * w - sima->xof) * (sima->zoom - oldzoom) / sima->zoom;
118                 sima->yof += ((location[1] - 0.5f) * h - sima->yof) * (sima->zoom - oldzoom) / sima->zoom;
119         }
120 }
121
122 static void sima_zoom_set_factor(SpaceImage *sima, ARegion *ar, float zoomfac, float location[2])
123 {
124         sima_zoom_set(sima, ar, sima->zoom * zoomfac, location);
125 }
126
127 #if 0 // currently unused
128 static int image_poll(bContext *C)
129 {
130         return (CTX_data_edit_image(C) != NULL);
131 }
132 #endif
133
134 static int space_image_buffer_exists_poll(bContext *C)
135 {
136         SpaceImage *sima = CTX_wm_space_image(C);
137         if (sima && sima->spacetype == SPACE_IMAGE)
138                 if (ED_space_image_has_buffer(sima))
139                         return 1;
140         return 0;
141 }
142
143 static int space_image_file_exists_poll(bContext *C)
144 {
145         if (space_image_buffer_exists_poll(C)) {
146                 Main *bmain = CTX_data_main(C);
147                 SpaceImage *sima = CTX_wm_space_image(C);
148                 ImBuf *ibuf;
149                 void *lock;
150                 int ret = FALSE;
151                 char name[FILE_MAX];
152
153                 ibuf = ED_space_image_acquire_buffer(sima, &lock);
154                 if (ibuf) {
155                         BLI_strncpy(name, ibuf->name, FILE_MAX);
156                         BLI_path_abs(name, bmain->name);
157
158                         if (BLI_exists(name) == FALSE) {
159                                 CTX_wm_operator_poll_msg_set(C, "image file not found");
160                         }
161                         else if (BLI_file_is_writable(name) == FALSE) {
162                                 CTX_wm_operator_poll_msg_set(C, "image path can't be written to");
163                         }
164                         else {
165                                 ret = TRUE;
166                         }
167                 }
168                 ED_space_image_release_buffer(sima, lock);
169
170                 return ret;
171         }
172         return 0;
173 }
174
175 static int space_image_poll(bContext *C)
176 {
177         SpaceImage *sima = CTX_wm_space_image(C);
178         if (sima && sima->spacetype == SPACE_IMAGE && sima->image)
179                 return 1;
180         return 0;
181 }
182
183 int space_image_main_area_poll(bContext *C)
184 {
185         SpaceImage *sima = CTX_wm_space_image(C);
186         // XXX ARegion *ar= CTX_wm_region(C);
187
188         if (sima)
189                 return 1;  // XXX (ar && ar->type->regionid == RGN_TYPE_WINDOW);
190         
191         return 0;
192 }
193
194 /* For IMAGE_OT_curves_point_set to avoid sampling when in uv smooth mode or editmode */
195 int space_image_main_area_not_uv_brush_poll(bContext *C)
196 {
197         SpaceImage *sima = CTX_wm_space_image(C);
198         Scene *scene = CTX_data_scene(C);
199         ToolSettings *toolsettings = scene->toolsettings;
200
201         if (sima && !toolsettings->uvsculpt && !scene->obedit)
202                 return 1;
203
204         return 0;
205 }
206
207 static int image_sample_poll(bContext *C)
208 {
209         SpaceImage *sima = CTX_wm_space_image(C);
210         if (sima) {
211                 Scene *scene = CTX_data_scene(C);
212                 Object *obedit = CTX_data_edit_object(C);
213                 ToolSettings *toolsettings = scene->toolsettings;
214
215                 if (obedit) {
216                         if (ED_space_image_show_uvedit(sima, obedit) && (toolsettings->use_uv_sculpt))
217                                 return FALSE;
218                 }
219                 else if (sima->mode != SI_MODE_VIEW) {
220                         return FALSE;
221                 }
222
223                 return space_image_main_area_poll(C);
224         }
225         else {
226                 return FALSE;
227         }
228 }
229 /********************** view pan operator *********************/
230
231 typedef struct ViewPanData {
232         float x, y;
233         float xof, yof;
234         int event_type;
235 } ViewPanData;
236
237 static void image_view_pan_init(bContext *C, wmOperator *op, wmEvent *event)
238 {
239         SpaceImage *sima = CTX_wm_space_image(C);
240         ViewPanData *vpd;
241
242         op->customdata = vpd = MEM_callocN(sizeof(ViewPanData), "ImageViewPanData");
243         WM_cursor_modal(CTX_wm_window(C), BC_NSEW_SCROLLCURSOR);
244
245         vpd->x = event->x;
246         vpd->y = event->y;
247         vpd->xof = sima->xof;
248         vpd->yof = sima->yof;
249         vpd->event_type = event->type;
250
251         WM_event_add_modal_handler(C, op);
252 }
253
254 static void image_view_pan_exit(bContext *C, wmOperator *op, int cancel)
255 {
256         SpaceImage *sima = CTX_wm_space_image(C);
257         ViewPanData *vpd = op->customdata;
258
259         if (cancel) {
260                 sima->xof = vpd->xof;
261                 sima->yof = vpd->yof;
262                 ED_region_tag_redraw(CTX_wm_region(C));
263         }
264
265         WM_cursor_restore(CTX_wm_window(C));
266         MEM_freeN(op->customdata);
267 }
268
269 static int image_view_pan_exec(bContext *C, wmOperator *op)
270 {
271         SpaceImage *sima = CTX_wm_space_image(C);
272         float offset[2];
273
274         RNA_float_get_array(op->ptr, "offset", offset);
275         sima->xof += offset[0];
276         sima->yof += offset[1];
277
278         ED_region_tag_redraw(CTX_wm_region(C));
279
280         /* XXX notifier? */
281 #if 0
282         if (image_preview_active(curarea, NULL, NULL)) {
283                 /* recalculates new preview rect */
284                 scrarea_do_windraw(curarea);
285                 image_preview_event(2);
286         }
287 #endif
288         
289         return OPERATOR_FINISHED;
290 }
291
292 static int image_view_pan_invoke(bContext *C, wmOperator *op, wmEvent *event)
293 {
294         if (event->type == MOUSEPAN) {
295                 SpaceImage *sima = CTX_wm_space_image(C);
296                 float offset[2];
297                 
298                 offset[0] = (event->x - event->prevx) / sima->zoom;
299                 offset[1] = (event->y - event->prevy) / sima->zoom;
300                 RNA_float_set_array(op->ptr, "offset", offset);
301
302                 image_view_pan_exec(C, op);
303                 return OPERATOR_FINISHED;
304         }
305         else {
306                 image_view_pan_init(C, op, event);
307                 return OPERATOR_RUNNING_MODAL;
308         }
309 }
310
311 static int image_view_pan_modal(bContext *C, wmOperator *op, wmEvent *event)
312 {
313         SpaceImage *sima = CTX_wm_space_image(C);
314         ViewPanData *vpd = op->customdata;
315         float offset[2];
316
317         switch (event->type) {
318                 case MOUSEMOVE:
319                         sima->xof = vpd->xof;
320                         sima->yof = vpd->yof;
321                         offset[0] = (vpd->x - event->x) / sima->zoom;
322                         offset[1] = (vpd->y - event->y) / sima->zoom;
323                         RNA_float_set_array(op->ptr, "offset", offset);
324                         image_view_pan_exec(C, op);
325                         break;
326                 default:
327                         if (event->type == vpd->event_type && event->val == KM_RELEASE) {
328                                 image_view_pan_exit(C, op, 0);
329                                 return OPERATOR_FINISHED;
330                         }
331                         break;
332         }
333
334         return OPERATOR_RUNNING_MODAL;
335 }
336
337 static int image_view_pan_cancel(bContext *C, wmOperator *op)
338 {
339         image_view_pan_exit(C, op, 1);
340         return OPERATOR_CANCELLED;
341 }
342
343 void IMAGE_OT_view_pan(wmOperatorType *ot)
344 {
345         /* identifiers */
346         ot->name = "View Pan";
347         ot->idname = "IMAGE_OT_view_pan";
348         ot->description = "Pan the view";
349         
350         /* api callbacks */
351         ot->exec = image_view_pan_exec;
352         ot->invoke = image_view_pan_invoke;
353         ot->modal = image_view_pan_modal;
354         ot->cancel = image_view_pan_cancel;
355         ot->poll = space_image_main_area_poll;
356
357         /* flags */
358         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_POINTER;
359         
360         /* properties */
361         RNA_def_float_vector(ot->srna, "offset", 2, NULL, -FLT_MAX, FLT_MAX,
362                              "Offset", "Offset in floating point units, 1.0 is the width and height of the image", -FLT_MAX, FLT_MAX);
363 }
364
365 /********************** view zoom operator *********************/
366
367 typedef struct ViewZoomData {
368         float x, y;
369         float zoom;
370         int event_type;
371         float location[2];
372 } ViewZoomData;
373
374 static void image_view_zoom_init(bContext *C, wmOperator *op, wmEvent *event)
375 {
376         SpaceImage *sima = CTX_wm_space_image(C);
377         ARegion *ar = CTX_wm_region(C);
378         ViewZoomData *vpd;
379
380         op->customdata = vpd = MEM_callocN(sizeof(ViewZoomData), "ImageViewZoomData");
381         WM_cursor_modal(CTX_wm_window(C), BC_NSEW_SCROLLCURSOR);
382
383         vpd->x = event->x;
384         vpd->y = event->y;
385         vpd->zoom = sima->zoom;
386         vpd->event_type = event->type;
387
388         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &vpd->location[0], &vpd->location[1]);
389
390         WM_event_add_modal_handler(C, op);
391 }
392
393 static void image_view_zoom_exit(bContext *C, wmOperator *op, int cancel)
394 {
395         SpaceImage *sima = CTX_wm_space_image(C);
396         ViewZoomData *vpd = op->customdata;
397
398         if (cancel) {
399                 sima->zoom = vpd->zoom;
400                 ED_region_tag_redraw(CTX_wm_region(C));
401         }
402
403         WM_cursor_restore(CTX_wm_window(C));
404         MEM_freeN(op->customdata);
405 }
406
407 static int image_view_zoom_exec(bContext *C, wmOperator *op)
408 {
409         SpaceImage *sima = CTX_wm_space_image(C);
410         ARegion *ar = CTX_wm_region(C);
411
412         sima_zoom_set_factor(sima, ar, RNA_float_get(op->ptr, "factor"), NULL);
413
414         ED_region_tag_redraw(CTX_wm_region(C));
415
416         /* XXX notifier? */
417 #if 0
418         if (image_preview_active(curarea, NULL, NULL)) {
419                 /* recalculates new preview rect */
420                 scrarea_do_windraw(curarea);
421                 image_preview_event(2);
422         }
423 #endif
424         
425         return OPERATOR_FINISHED;
426 }
427
428 static int image_view_zoom_invoke(bContext *C, wmOperator *op, wmEvent *event)
429 {
430         if (event->type == MOUSEZOOM) {
431                 SpaceImage *sima = CTX_wm_space_image(C);
432                 ARegion *ar = CTX_wm_region(C);
433                 float factor, location[2];
434
435                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &location[0], &location[1]);
436
437                 factor = 1.0f + (event->x - event->prevx + event->y - event->prevy) / 300.0f;
438                 RNA_float_set(op->ptr, "factor", factor);
439                 sima_zoom_set(sima, ar, sima->zoom * factor, location);
440                 ED_region_tag_redraw(CTX_wm_region(C));
441                 
442                 return OPERATOR_FINISHED;
443         }
444         else {
445                 image_view_zoom_init(C, op, event);
446                 return OPERATOR_RUNNING_MODAL;
447         }
448 }
449
450 static int image_view_zoom_modal(bContext *C, wmOperator *op, wmEvent *event)
451 {
452         SpaceImage *sima = CTX_wm_space_image(C);
453         ARegion *ar = CTX_wm_region(C);
454         ViewZoomData *vpd = op->customdata;
455         float factor;
456
457         switch (event->type) {
458                 case MOUSEMOVE:
459                         factor = 1.0f + (vpd->x - event->x + vpd->y - event->y) / 300.0f;
460                         RNA_float_set(op->ptr, "factor", factor);
461                         sima_zoom_set(sima, ar, vpd->zoom * factor, vpd->location);
462                         ED_region_tag_redraw(CTX_wm_region(C));
463                         break;
464                 default:
465                         if (event->type == vpd->event_type && event->val == KM_RELEASE) {
466                                 image_view_zoom_exit(C, op, 0);
467                                 return OPERATOR_FINISHED;
468                         }
469                         break;
470         }
471
472         return OPERATOR_RUNNING_MODAL;
473 }
474
475 static int image_view_zoom_cancel(bContext *C, wmOperator *op)
476 {
477         image_view_zoom_exit(C, op, 1);
478         return OPERATOR_CANCELLED;
479 }
480
481 void IMAGE_OT_view_zoom(wmOperatorType *ot)
482 {
483         /* identifiers */
484         ot->name = "View Zoom";
485         ot->idname = "IMAGE_OT_view_zoom";
486         ot->description = "Zoom in/out the image";
487         
488         /* api callbacks */
489         ot->exec = image_view_zoom_exec;
490         ot->invoke = image_view_zoom_invoke;
491         ot->modal = image_view_zoom_modal;
492         ot->cancel = image_view_zoom_cancel;
493         ot->poll = space_image_main_area_poll;
494
495         /* flags */
496         ot->flag = OPTYPE_BLOCKING;
497         
498         /* properties */
499         RNA_def_float(ot->srna, "factor", 0.0f, 0.0f, FLT_MAX,
500                       "Factor", "Zoom factor, values higher than 1.0 zoom in, lower values zoom out", -FLT_MAX, FLT_MAX);
501 }
502
503 /********************** NDOF operator *********************/
504
505 /* Combined pan/zoom from a 3D mouse device.
506  * Z zooms, XY pans
507  * "view" (not "paper") control -- user moves the viewpoint, not the image being viewed
508  * that explains the negative signs in the code below
509  */
510
511 static int image_view_ndof_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
512 {
513         if (event->type != NDOF_MOTION)
514                 return OPERATOR_CANCELLED;
515         else {
516                 SpaceImage *sima = CTX_wm_space_image(C);
517                 ARegion *ar = CTX_wm_region(C);
518
519                 wmNDOFMotionData *ndof = (wmNDOFMotionData *) event->customdata;
520
521                 float dt = ndof->dt;
522                 /* tune these until it feels right */
523                 const float zoom_sensitivity = 0.5f; // 50% per second (I think)
524                 const float pan_sensitivity = 300.f; // screen pixels per second
525
526                 float pan_x = pan_sensitivity * dt * ndof->tvec[0] / sima->zoom;
527                 float pan_y = pan_sensitivity * dt * ndof->tvec[1] / sima->zoom;
528
529                 /* "mouse zoom" factor = 1 + (dx + dy) / 300
530                  * what about "ndof zoom" factor? should behave like this:
531                  * at rest -> factor = 1
532                  * move forward -> factor > 1
533                  * move backward -> factor < 1
534                  */
535                 float zoom_factor = 1.f + zoom_sensitivity * dt * -ndof->tvec[2];
536
537                 if (U.ndof_flag & NDOF_ZOOM_INVERT)
538                         zoom_factor = -zoom_factor;
539
540                 sima_zoom_set_factor(sima, ar, zoom_factor, NULL);
541                 sima->xof += pan_x;
542                 sima->yof += pan_y;
543
544                 ED_region_tag_redraw(ar);       
545
546                 return OPERATOR_FINISHED;
547         }
548 }
549
550 void IMAGE_OT_view_ndof(wmOperatorType *ot)
551 {
552         /* identifiers */
553         ot->name = "NDOF Pan/Zoom";
554         ot->idname = "IMAGE_OT_view_ndof";
555         ot->description = "Use a 3D mouse device to pan/zoom the view";
556         
557         /* api callbacks */
558         ot->invoke = image_view_ndof_invoke;
559 }
560
561 /********************** view all operator *********************/
562
563 /* Updates the fields of the View2D member of the SpaceImage struct.
564  * Default behavior is to reset the position of the image and set the zoom to 1
565  * If the image will not fit within the window rectangle, the zoom is adjusted */
566
567 static int image_view_all_exec(bContext *C, wmOperator *UNUSED(op))
568 {
569         SpaceImage *sima;
570         ARegion *ar;
571         float aspx, aspy, zoomx, zoomy, w, h;
572         int width, height;
573
574         /* retrieve state */
575         sima = CTX_wm_space_image(C);
576         ar = CTX_wm_region(C);
577
578         ED_space_image_get_size(sima, &width, &height);
579         ED_space_image_get_aspect(sima, &aspx, &aspy);
580
581         w = width * aspx;
582         h = height * aspy;
583         
584         /* check if the image will fit in the image with (zoom == 1) */
585         width  = BLI_RCT_SIZE_X(&ar->winrct) + 1;
586         height = BLI_RCT_SIZE_Y(&ar->winrct) + 1;
587
588         if ((w >= width || h >= height) && (width > 0 && height > 0)) {
589                 /* find the zoom value that will fit the image in the image space */
590                 zoomx = width / w;
591                 zoomy = height / h;
592                 sima_zoom_set(sima, ar, 1.0f / power_of_2(1.0f / minf(zoomx, zoomy)), NULL);
593         }
594         else
595                 sima_zoom_set(sima, ar, 1.0f, NULL);
596
597         sima->xof = sima->yof = 0.0f;
598
599         ED_region_tag_redraw(CTX_wm_region(C));
600         
601         return OPERATOR_FINISHED;
602 }
603
604 void IMAGE_OT_view_all(wmOperatorType *ot)
605 {
606         /* identifiers */
607         ot->name = "View All";
608         ot->idname = "IMAGE_OT_view_all";
609         ot->description = "View the whole picture";
610         
611         /* api callbacks */
612         ot->exec = image_view_all_exec;
613         ot->poll = space_image_main_area_poll;
614 }
615
616 /********************** view selected operator *********************/
617
618 static int image_view_selected_exec(bContext *C, wmOperator *UNUSED(op))
619 {
620         SpaceImage *sima;
621         ARegion *ar;
622         Scene *scene;
623         Object *obedit;
624         Image *ima;
625         float size, min[2], max[2], d[2], aspx, aspy;
626         int width, height;
627
628         /* retrieve state */
629         sima = CTX_wm_space_image(C);
630         ar = CTX_wm_region(C);
631         scene = CTX_data_scene(C);
632         obedit = CTX_data_edit_object(C);
633
634         ima = ED_space_image(sima);
635         ED_space_image_get_size(sima, &width, &height);
636         ED_image_get_aspect(ima, &aspx, &aspy);
637
638         width = width * aspx;
639         height = height * aspy;
640
641         /* get bounds */
642         if (!ED_uvedit_minmax(scene, ima, obedit, min, max))
643                 return OPERATOR_CANCELLED;
644
645         /* adjust offset and zoom */
646         sima->xof = (int)(((min[0] + max[0]) * 0.5f - 0.5f) * width);
647         sima->yof = (int)(((min[1] + max[1]) * 0.5f - 0.5f) * height);
648
649         d[0] = max[0] - min[0];
650         d[1] = max[1] - min[1];
651         size = 0.5f * MAX2(d[0], d[1]) * MAX2(width, height) / 256.0f;
652         
653         if (size <= 0.01f) size = 0.01f;
654         sima_zoom_set(sima, ar, 0.7f / size, NULL);
655
656         ED_region_tag_redraw(CTX_wm_region(C));
657         
658         return OPERATOR_FINISHED;
659 }
660
661 static int image_view_selected_poll(bContext *C)
662 {
663         return (space_image_main_area_poll(C) && ED_operator_uvedit(C));
664 }
665
666 void IMAGE_OT_view_selected(wmOperatorType *ot)
667 {
668         /* identifiers */
669         ot->name = "View Center";
670         ot->idname = "IMAGE_OT_view_selected";
671         ot->description = "View all selected UVs";
672         
673         /* api callbacks */
674         ot->exec = image_view_selected_exec;
675         ot->poll = image_view_selected_poll;
676 }
677
678 /********************** view zoom in/out operator *********************/
679
680 static int image_view_zoom_in_exec(bContext *C, wmOperator *op)
681 {
682         SpaceImage *sima = CTX_wm_space_image(C);
683         ARegion *ar = CTX_wm_region(C);
684         float location[2];
685
686         RNA_float_get_array(op->ptr, "location", location);
687
688         sima_zoom_set_factor(sima, ar, 1.25f, location);
689
690         ED_region_tag_redraw(CTX_wm_region(C));
691         
692         return OPERATOR_FINISHED;
693 }
694
695 static int image_view_zoom_in_invoke(bContext *C, wmOperator *op, wmEvent *event)
696 {
697         ARegion *ar = CTX_wm_region(C);
698         float location[2];
699
700         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &location[0], &location[1]);
701         RNA_float_set_array(op->ptr, "location", location);
702
703         return image_view_zoom_in_exec(C, op);
704 }
705
706 void IMAGE_OT_view_zoom_in(wmOperatorType *ot)
707 {
708         /* identifiers */
709         ot->name = "View Zoom In";
710         ot->idname = "IMAGE_OT_view_zoom_in";
711         ot->description = "Zoom in the image (centered around 2D cursor)";
712         
713         /* api callbacks */
714         ot->invoke = image_view_zoom_in_invoke;
715         ot->exec = image_view_zoom_in_exec;
716         ot->poll = space_image_main_area_poll;
717
718         /* properties */
719         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX, "Location", "Cursor location in screen coordinates", -10.0f, 10.0f);
720 }
721
722 static int image_view_zoom_out_exec(bContext *C, wmOperator *op)
723 {
724         SpaceImage *sima = CTX_wm_space_image(C);
725         ARegion *ar = CTX_wm_region(C);
726         float location[2];
727
728         RNA_float_get_array(op->ptr, "location", location);
729
730         sima_zoom_set_factor(sima, ar, 0.8f, location);
731
732         ED_region_tag_redraw(CTX_wm_region(C));
733         
734         return OPERATOR_FINISHED;
735 }
736
737 static int image_view_zoom_out_invoke(bContext *C, wmOperator *op, wmEvent *event)
738 {
739         ARegion *ar = CTX_wm_region(C);
740         float location[2];
741
742         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &location[0], &location[1]);
743         RNA_float_set_array(op->ptr, "location", location);
744
745         return image_view_zoom_out_exec(C, op);
746 }
747
748 void IMAGE_OT_view_zoom_out(wmOperatorType *ot)
749 {
750         /* identifiers */
751         ot->name = "View Zoom Out";
752         ot->idname = "IMAGE_OT_view_zoom_out";
753         ot->description = "Zoom out the image (centered around 2D cursor)";
754         
755         /* api callbacks */
756         ot->invoke = image_view_zoom_out_invoke;
757         ot->exec = image_view_zoom_out_exec;
758         ot->poll = space_image_main_area_poll;
759
760         /* properties */
761         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX, "Location", "Cursor location in screen coordinates", -10.0f, 10.0f);
762 }
763
764 /********************** view zoom ratio operator *********************/
765
766 static int image_view_zoom_ratio_exec(bContext *C, wmOperator *op)
767 {
768         SpaceImage *sima = CTX_wm_space_image(C);
769         ARegion *ar = CTX_wm_region(C);
770
771         sima_zoom_set(sima, ar, RNA_float_get(op->ptr, "ratio"), NULL);
772         
773         /* ensure pixel exact locations for draw */
774         sima->xof = (int)sima->xof;
775         sima->yof = (int)sima->yof;
776
777         /* XXX notifier? */
778 #if 0
779         if (image_preview_active(curarea, NULL, NULL)) {
780                 /* recalculates new preview rect */
781                 scrarea_do_windraw(curarea);
782                 image_preview_event(2);
783         }
784 #endif
785
786         ED_region_tag_redraw(CTX_wm_region(C));
787         
788         return OPERATOR_FINISHED;
789 }
790
791 void IMAGE_OT_view_zoom_ratio(wmOperatorType *ot)
792 {
793         /* identifiers */
794         ot->name = "View Zoom Ratio";
795         ot->idname = "IMAGE_OT_view_zoom_ratio";
796         ot->description = "Set zoom ration of the view";
797         
798         /* api callbacks */
799         ot->exec = image_view_zoom_ratio_exec;
800         ot->poll = space_image_main_area_poll;
801         
802         /* properties */
803         RNA_def_float(ot->srna, "ratio", 0.0f, 0.0f, FLT_MAX,
804                       "Ratio", "Zoom ratio, 1.0 is 1:1, higher is zoomed in, lower is zoomed out", -FLT_MAX, FLT_MAX);
805 }
806
807 /**************** load/replace/save callbacks ******************/
808 static void image_filesel(bContext *C, wmOperator *op, const char *path)
809 {
810         RNA_string_set(op->ptr, "filepath", path);
811         WM_event_add_fileselect(C, op); 
812 }
813
814 /******************** open image operator ********************/
815
816 static void image_open_init(bContext *C, wmOperator *op)
817 {
818         PropertyPointerRNA *pprop;
819
820         op->customdata = pprop = MEM_callocN(sizeof(PropertyPointerRNA), "OpenPropertyPointerRNA");
821         uiIDContextProperty(C, &pprop->ptr, &pprop->prop);
822 }
823
824 static int image_open_cancel(bContext *UNUSED(C), wmOperator *op)
825 {
826         MEM_freeN(op->customdata);
827         op->customdata = NULL;
828         return OPERATOR_CANCELLED;
829 }
830
831 static int image_open_exec(bContext *C, wmOperator *op)
832 {
833         SpaceImage *sima = CTX_wm_space_image(C); /* XXX other space types can call */
834         Scene *scene = CTX_data_scene(C);
835         Object *obedit = CTX_data_edit_object(C);
836         ImageUser *iuser = NULL;
837         PropertyPointerRNA *pprop;
838         PointerRNA idptr;
839         Image *ima = NULL;
840         char str[FILE_MAX];
841
842         RNA_string_get(op->ptr, "filepath", str);
843         /* default to frame 1 if there's no scene in context */
844
845         errno = 0;
846
847         ima = BKE_image_load_exists(str);
848
849         if (!ima) {
850                 if (op->customdata) MEM_freeN(op->customdata);
851                 BKE_reportf(op->reports, RPT_ERROR, "Can't read: \"%s\", %s", str, errno ? strerror(errno) : "Unsupported image format");
852                 return OPERATOR_CANCELLED;
853         }
854         
855         if (!op->customdata)
856                 image_open_init(C, op);
857
858         /* hook into UI */
859         pprop = op->customdata;
860
861         if (pprop->prop) {
862                 /* when creating new ID blocks, use is already 1, but RNA
863                  * pointer se also increases user, so this compensates it */
864                 ima->id.us--;
865
866                 RNA_id_pointer_create(&ima->id, &idptr);
867                 RNA_property_pointer_set(&pprop->ptr, pprop->prop, idptr);
868                 RNA_property_update(C, &pprop->ptr, pprop->prop);
869         }
870         else if (sima) {
871                 ED_space_image_set(sima, scene, obedit, ima);
872                 iuser = &sima->iuser;
873         }
874         else {
875                 Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
876                 if (tex && tex->type == TEX_IMAGE)
877                         iuser = &tex->iuser;
878                 
879         }
880         
881         /* initialize because of new image */
882         if (iuser) {
883                 iuser->sfra = 1;
884                 iuser->offset = 0;
885                 iuser->fie_ima = 2;
886         }
887
888         /* XXX unpackImage frees image buffers */
889         ED_preview_kill_jobs(C);
890         
891         BKE_image_signal(ima, iuser, IMA_SIGNAL_RELOAD);
892         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
893         
894         MEM_freeN(op->customdata);
895
896         return OPERATOR_FINISHED;
897 }
898
899 static int image_open_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
900 {
901         SpaceImage *sima = CTX_wm_space_image(C); /* XXX other space types can call */
902         char *path = U.textudir;
903         Image *ima = NULL;
904
905         if (sima) {
906                 ima = sima->image;
907         }
908
909         if (ima == NULL) {
910                 Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
911                 if (tex && tex->type == TEX_IMAGE)
912                         ima = tex->ima;
913         }
914
915         if (ima == NULL) {
916                 PointerRNA ptr;
917                 PropertyRNA *prop;
918
919                 /* hook into UI */
920                 uiIDContextProperty(C, &ptr, &prop);
921
922                 if (prop) {
923                         PointerRNA oldptr;
924                         Image *oldima;
925
926                         oldptr = RNA_property_pointer_get(&ptr, prop);
927                         oldima = (Image *)oldptr.id.data;
928                         /* unlikely to fail but better avoid strange crash */
929                         if (oldima && GS(oldima->id.name) == ID_IM) {
930                                 ima = oldima;
931                         }
932                 }
933         }
934
935         if (ima)
936                 path = ima->name;
937
938         if (RNA_struct_property_is_set(op->ptr, "filepath"))
939                 return image_open_exec(C, op);
940         
941         image_open_init(C, op);
942
943         image_filesel(C, op, path);
944
945         return OPERATOR_RUNNING_MODAL;
946 }
947
948 /* called by other space types too */
949 void IMAGE_OT_open(wmOperatorType *ot)
950 {
951         /* identifiers */
952         ot->name = "Open Image";
953         ot->description = "Open image";
954         ot->idname = "IMAGE_OT_open";
955         
956         /* api callbacks */
957         ot->exec = image_open_exec;
958         ot->invoke = image_open_invoke;
959         ot->cancel = image_open_cancel;
960
961         /* flags */
962         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
963
964         /* properties */
965         WM_operator_properties_filesel(ot, FOLDERFILE | IMAGEFILE | MOVIEFILE, FILE_SPECIAL, FILE_OPENFILE,
966                                        WM_FILESEL_FILEPATH | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY);
967 }
968
969 /******************** Match movie length operator ********************/
970 static int image_match_len_exec(bContext *C, wmOperator *UNUSED(op))
971 {
972         Scene *scene = CTX_data_scene(C);
973         Image *ima = CTX_data_pointer_get_type(C, "edit_image", &RNA_Image).data;
974         ImageUser *iuser = CTX_data_pointer_get_type(C, "edit_image_user", &RNA_ImageUser).data;
975
976         if (!ima || !iuser) {
977                 /* Try to get a Texture, or a SpaceImage from context... */
978                 SpaceImage *sima = CTX_wm_space_image(C);
979                 Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
980                 if (tex && tex->type == TEX_IMAGE) {
981                         ima = tex->ima;
982                         iuser = &tex->iuser;
983                 }
984                 else if (sima) {
985                         ima = sima->image;
986                         iuser = &sima->iuser;
987                 }
988                 
989         }
990
991         if (!ima || !iuser || !ima->anim)
992                 return OPERATOR_CANCELLED;
993
994         iuser->frames = IMB_anim_get_duration(ima->anim, IMB_TC_RECORD_RUN);
995         BKE_image_user_frame_calc(iuser, scene->r.cfra, 0);
996
997         return OPERATOR_FINISHED;
998 }
999
1000 /* called by other space types too */
1001 void IMAGE_OT_match_movie_length(wmOperatorType *ot)
1002 {
1003         /* identifiers */
1004         ot->name = "Match Movie Length";
1005         ot->description = "Set image's users length to the one of this video";
1006         ot->idname = "IMAGE_OT_match_movie_length";
1007         
1008         /* api callbacks */
1009         ot->exec = image_match_len_exec;
1010
1011         /* flags */
1012         ot->flag = OPTYPE_REGISTER /* | OPTYPE_UNDO */; /* Don't think we need undo for that. */
1013 }
1014
1015 /******************** replace image operator ********************/
1016
1017 static int image_replace_exec(bContext *C, wmOperator *op)
1018 {
1019         SpaceImage *sima = CTX_wm_space_image(C);
1020         char str[FILE_MAX];
1021
1022         if (!sima->image)
1023                 return OPERATOR_CANCELLED;
1024         
1025         RNA_string_get(op->ptr, "filepath", str);
1026
1027         /* we cant do much if the str is longer then FILE_MAX :/ */
1028         BLI_strncpy(sima->image->name, str, sizeof(sima->image->name));
1029
1030         if (BLI_testextensie_array(str, imb_ext_movie))
1031                 sima->image->source = IMA_SRC_MOVIE;
1032         else
1033                 sima->image->source = IMA_SRC_FILE;
1034
1035         /* XXX unpackImage frees image buffers */
1036         ED_preview_kill_jobs(C);
1037         
1038         BKE_image_signal(sima->image, &sima->iuser, IMA_SIGNAL_RELOAD);
1039         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
1040
1041         return OPERATOR_FINISHED;
1042 }
1043
1044 static int image_replace_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1045 {
1046         SpaceImage *sima = CTX_wm_space_image(C);
1047
1048         if (!sima->image)
1049                 return OPERATOR_CANCELLED;
1050
1051         if (RNA_struct_property_is_set(op->ptr, "filepath"))
1052                 return image_replace_exec(C, op);
1053
1054         if (!RNA_struct_property_is_set(op->ptr, "relative_path"))
1055                 RNA_boolean_set(op->ptr, "relative_path", BLI_path_is_rel(sima->image->name));
1056
1057         image_filesel(C, op, sima->image->name);
1058
1059         return OPERATOR_RUNNING_MODAL;
1060 }
1061
1062 void IMAGE_OT_replace(wmOperatorType *ot)
1063 {
1064         /* identifiers */
1065         ot->name = "Replace Image";
1066         ot->idname = "IMAGE_OT_replace";
1067         ot->description = "Replace current image by another one from disk";
1068         
1069         /* api callbacks */
1070         ot->exec = image_replace_exec;
1071         ot->invoke = image_replace_invoke;
1072         ot->poll = space_image_poll;
1073
1074         /* flags */
1075         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1076
1077         /* properties */
1078         WM_operator_properties_filesel(ot, FOLDERFILE | IMAGEFILE | MOVIEFILE, FILE_SPECIAL, FILE_OPENFILE,
1079                                        WM_FILESEL_FILEPATH | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY);
1080 }
1081
1082 /******************** save image as operator ********************/
1083
1084 typedef struct {
1085         /* matching scene->r settings */
1086         //short planes, imtype, subimtype, quality;
1087         ImageFormatData im_format;
1088         char filepath[FILE_MAX]; /* keep absolute */
1089 } SaveImageOptions;
1090
1091 static void save_image_options_defaults(SaveImageOptions *simopts)
1092 {
1093         BKE_imformat_defaults(&simopts->im_format);
1094         simopts->filepath[0] = '\0';
1095 }
1096
1097 static char imtype_best_depth(ImBuf *ibuf, const char imtype)
1098 {
1099         const char depth_ok = BKE_imtype_valid_depths(imtype);
1100
1101         if (ibuf->rect_float) {
1102                 if (depth_ok & R_IMF_CHAN_DEPTH_32) return R_IMF_CHAN_DEPTH_32;
1103                 if (depth_ok & R_IMF_CHAN_DEPTH_24) return R_IMF_CHAN_DEPTH_24;
1104                 if (depth_ok & R_IMF_CHAN_DEPTH_16) return R_IMF_CHAN_DEPTH_16;
1105                 if (depth_ok & R_IMF_CHAN_DEPTH_12) return R_IMF_CHAN_DEPTH_12;
1106                 return R_IMF_CHAN_DEPTH_8;
1107         }
1108         else {
1109                 if (depth_ok & R_IMF_CHAN_DEPTH_8) return R_IMF_CHAN_DEPTH_8;
1110                 if (depth_ok & R_IMF_CHAN_DEPTH_12) return R_IMF_CHAN_DEPTH_12;
1111                 if (depth_ok & R_IMF_CHAN_DEPTH_16) return R_IMF_CHAN_DEPTH_16;
1112                 if (depth_ok & R_IMF_CHAN_DEPTH_24) return R_IMF_CHAN_DEPTH_24;
1113                 if (depth_ok & R_IMF_CHAN_DEPTH_32) return R_IMF_CHAN_DEPTH_32;
1114                 return R_IMF_CHAN_DEPTH_8; /* fallback, should not get here */
1115         }
1116 }
1117
1118 static int save_image_options_init(SaveImageOptions *simopts, SpaceImage *sima, Scene *scene, const short guess_path)
1119 {
1120         void *lock;
1121         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
1122
1123         if (ibuf) {
1124                 Image *ima = sima->image;
1125                 short is_depth_set = FALSE;
1126
1127                 simopts->im_format.planes = ibuf->planes;
1128
1129                 if (ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE)) {
1130                         /* imtype */
1131                         simopts->im_format = scene->r.im_format;
1132                         is_depth_set = TRUE;
1133                 }
1134                 else if (ima->source == IMA_SRC_GENERATED) {
1135                         simopts->im_format.imtype = R_IMF_IMTYPE_PNG;
1136                 }
1137                 else {
1138                         simopts->im_format.imtype = BKE_ftype_to_imtype(ibuf->ftype);
1139                 }
1140                 //simopts->subimtype= scene->r.subimtype; /* XXX - this is lame, we need to make these available too! */
1141                 simopts->im_format.quality = ibuf->ftype & 0xff;
1142
1143                 BLI_strncpy(simopts->filepath, ibuf->name, sizeof(simopts->filepath));
1144
1145                 /* sanitize all settings */
1146
1147                 /* unlikely but just in case */
1148                 if (ELEM3(simopts->im_format.planes, R_IMF_PLANES_BW, R_IMF_PLANES_RGB, R_IMF_PLANES_RGBA) == 0) {
1149                         simopts->im_format.planes = R_IMF_PLANES_RGBA;
1150                 }
1151
1152                 /* depth, account for float buffer and format support */
1153                 if (is_depth_set == FALSE) {
1154                         simopts->im_format.depth = imtype_best_depth(ibuf, simopts->im_format.imtype);
1155                 }
1156
1157                 /* some formats don't use quality so fallback to scenes quality */
1158                 if (simopts->im_format.quality == 0) {
1159                         simopts->im_format.quality = scene->r.im_format.quality;
1160                 }
1161
1162                 /* check for empty path */
1163                 if (guess_path && simopts->filepath[0] == 0) {
1164                         if ((G.ima[0] == '/') && (G.ima[1] == '/') && (G.ima[2] == '\0')) {
1165                                 BLI_strncpy(simopts->filepath, "//untitled", FILE_MAX);
1166                         }
1167                         else {
1168                                 BLI_strncpy(simopts->filepath, G.ima, FILE_MAX);
1169                         }
1170                         BLI_path_abs(simopts->filepath, G.main->name);
1171                 }
1172
1173                 /* color management */
1174                 BKE_color_managed_display_settings_copy(&simopts->im_format.display_settings, &scene->display_settings);
1175                 BKE_color_managed_view_settings_copy(&simopts->im_format.view_settings, &scene->view_settings);
1176         }
1177
1178         ED_space_image_release_buffer(sima, lock);
1179
1180         return (ibuf != NULL);
1181 }
1182
1183 static void save_image_options_from_op(SaveImageOptions *simopts, wmOperator *op)
1184 {
1185         if (op->customdata) {
1186                 BKE_color_managed_view_settings_free(&simopts->im_format.view_settings);
1187
1188                 simopts->im_format = *(ImageFormatData *)op->customdata;
1189         }
1190
1191         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
1192                 RNA_string_get(op->ptr, "filepath", simopts->filepath);
1193                 BLI_path_abs(simopts->filepath, G.main->name);
1194         }
1195 }
1196
1197 static void save_image_options_to_op(SaveImageOptions *simopts, wmOperator *op)
1198 {
1199         if (op->customdata) {
1200                 BKE_color_managed_view_settings_free(&((ImageFormatData *)op->customdata)->view_settings);
1201
1202                 *(ImageFormatData *)op->customdata = simopts->im_format;
1203         }
1204
1205         RNA_string_set(op->ptr, "filepath", simopts->filepath);
1206 }
1207
1208 static ImBuf *save_image_colormanaged_imbuf_acquire(ImBuf *ibuf, SaveImageOptions *simopts, int save_as_render, void **cache_handle)
1209 {
1210         ImageFormatData *imf = &simopts->im_format;
1211         ImBuf *colormanaged_ibuf;
1212         int do_colormanagement;
1213
1214         *cache_handle = NULL;
1215         do_colormanagement = !BKE_imtype_supports_float(imf->imtype);
1216
1217         if (do_colormanagement) {
1218                 unsigned char *display_buffer;
1219
1220                 if (save_as_render)
1221                         display_buffer = IMB_display_buffer_acquire(ibuf, &imf->view_settings, &imf->display_settings, cache_handle);
1222                 else
1223                         display_buffer = IMB_display_buffer_acquire(ibuf, NULL, &imf->display_settings, cache_handle);
1224
1225                 if (*cache_handle) {
1226                         colormanaged_ibuf = IMB_allocImBuf(ibuf->x, ibuf->y, ibuf->planes, 0);
1227                         colormanaged_ibuf->rect = (unsigned int *) display_buffer;
1228                 }
1229                 else {
1230                         /* no cache handle means color management didn't run transformation
1231                          * or performed transformation to image's byte buffer which doesn't
1232                          * require allocating new image buffer
1233                          */
1234                         colormanaged_ibuf = ibuf;
1235                 }
1236         }
1237         else {
1238                 colormanaged_ibuf = ibuf;
1239         }
1240
1241         return colormanaged_ibuf;
1242 }
1243
1244 /* assumes name is FILE_MAX */
1245 /* ima->name and ibuf->name should end up the same */
1246 static void save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveImageOptions *simopts, int do_newpath)
1247 {
1248         Image *ima = ED_space_image(sima);
1249         void *lock;
1250         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
1251
1252         if (ibuf) {
1253                 void *cache_handle;
1254                 ImBuf *colormanaged_ibuf;
1255                 const char *relbase = ID_BLEND_PATH(CTX_data_main(C), &ima->id);
1256                 const short relative = (RNA_struct_find_property(op->ptr, "relative_path") && RNA_boolean_get(op->ptr, "relative_path"));
1257                 const short save_copy = (RNA_struct_find_property(op->ptr, "copy") && RNA_boolean_get(op->ptr, "copy"));
1258                 const short save_as_render = (RNA_struct_find_property(op->ptr, "save_as_render") && RNA_boolean_get(op->ptr, "save_as_render"));
1259                 short ok = FALSE;
1260
1261                 /* old global to ensure a 2nd save goes to same dir */
1262                 BLI_strncpy(G.ima, simopts->filepath, sizeof(G.ima));
1263
1264                 WM_cursor_wait(1);
1265
1266                 if (ima->type == IMA_TYPE_R_RESULT) {
1267                         /* enforce user setting for RGB or RGBA, but skip BW */
1268                         if (simopts->im_format.planes == R_IMF_PLANES_RGBA) {
1269                                 ibuf->planes = R_IMF_PLANES_RGBA;
1270                         }
1271                         else if (simopts->im_format.planes == R_IMF_PLANES_RGB) {
1272                                 ibuf->planes = R_IMF_PLANES_RGB;
1273                         }
1274                 }
1275                 else {
1276                         /* TODO, better solution, if a 24bit image is painted onto it may contain alpha */
1277                         if (ibuf->userflags & IB_BITMAPDIRTY) { /* it has been painted onto */
1278                                 /* checks each pixel, not ideal */
1279                                 ibuf->planes = BKE_imbuf_alpha_test(ibuf) ? 32 : 24;
1280                         }
1281                 }
1282
1283                 colormanaged_ibuf = save_image_colormanaged_imbuf_acquire(ibuf, simopts, save_as_render, &cache_handle);
1284
1285                 if (simopts->im_format.imtype == R_IMF_IMTYPE_MULTILAYER) {
1286                         Scene *scene = CTX_data_scene(C);
1287                         RenderResult *rr = BKE_image_acquire_renderresult(scene, ima);
1288                         if (rr) {
1289                                 RE_WriteRenderResult(op->reports, rr, simopts->filepath, simopts->im_format.quality);
1290                                 ok = TRUE;
1291                         }
1292                         else {
1293                                 BKE_report(op->reports, RPT_ERROR, "Did not write, no Multilayer Image");
1294                         }
1295                         BKE_image_release_renderresult(scene, ima);
1296                 }
1297                 else {
1298                         if (BKE_imbuf_write_as(colormanaged_ibuf, simopts->filepath, &simopts->im_format, save_copy)) {
1299                                 ok = TRUE;
1300                         }
1301                 }
1302
1303                 if (ok) {
1304                         if (!save_copy) {
1305                                 if (do_newpath) {
1306                                         BLI_strncpy(ibuf->name, simopts->filepath, sizeof(ibuf->name));
1307                                         BLI_strncpy(ima->name, simopts->filepath, sizeof(ima->name));
1308                                 }
1309
1310                                 ibuf->userflags &= ~IB_BITMAPDIRTY;
1311
1312                                 /* change type? */
1313                                 if (ima->type == IMA_TYPE_R_RESULT) {
1314                                         ima->type = IMA_TYPE_IMAGE;
1315
1316                                         /* workaround to ensure the render result buffer is no longer used
1317                                          * by this image, otherwise can crash when a new render result is
1318                                          * created. */
1319                                         if (ibuf->rect && !(ibuf->mall & IB_rect))
1320                                                 imb_freerectImBuf(ibuf);
1321                                         if (ibuf->rect_float && !(ibuf->mall & IB_rectfloat))
1322                                                 imb_freerectfloatImBuf(ibuf);
1323                                         if (ibuf->zbuf && !(ibuf->mall & IB_zbuf))
1324                                                 IMB_freezbufImBuf(ibuf);
1325                                         if (ibuf->zbuf_float && !(ibuf->mall & IB_zbuffloat))
1326                                                 IMB_freezbuffloatImBuf(ibuf);
1327                                 }
1328                                 if (ELEM(ima->source, IMA_SRC_GENERATED, IMA_SRC_VIEWER)) {
1329                                         ima->source = IMA_SRC_FILE;
1330                                         ima->type = IMA_TYPE_IMAGE;
1331                                 }
1332
1333                                 /* only image path, never ibuf */
1334                                 if (relative) {
1335                                         BLI_path_rel(ima->name, relbase); /* only after saving */
1336                                 }
1337                         }
1338                 }
1339                 else {
1340                         BKE_reportf(op->reports, RPT_ERROR, "Couldn't write image: %s", simopts->filepath);
1341                 }
1342
1343
1344                 WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
1345
1346                 WM_cursor_wait(0);
1347
1348                 if (cache_handle) {
1349                         colormanaged_ibuf->rect = NULL;
1350                         IMB_freeImBuf(colormanaged_ibuf);
1351
1352                         IMB_display_buffer_release(cache_handle);
1353                 }
1354         }
1355
1356         ED_space_image_release_buffer(sima, lock);
1357 }
1358
1359 static void image_save_as_free(wmOperator *op)
1360 {
1361         if (op->customdata) {
1362                 ImageFormatData *im_format = (ImageFormatData *)op->customdata;
1363                 BKE_color_managed_view_settings_free(&im_format->view_settings);
1364
1365                 MEM_freeN(op->customdata);
1366                 op->customdata = NULL;
1367         }
1368 }
1369
1370 static int image_save_as_exec(bContext *C, wmOperator *op)
1371 {
1372         SpaceImage *sima = CTX_wm_space_image(C);
1373         SaveImageOptions simopts;
1374
1375         save_image_options_defaults(&simopts);
1376
1377         /* just in case to initialize values,
1378          * these should be set on invoke or by the caller. */
1379         save_image_options_init(&simopts, sima, CTX_data_scene(C), 0);
1380
1381         save_image_options_from_op(&simopts, op);
1382
1383         save_image_doit(C, sima, op, &simopts, TRUE);
1384
1385         image_save_as_free(op);
1386         return OPERATOR_FINISHED;
1387 }
1388
1389
1390 static int image_save_as_check(bContext *UNUSED(C), wmOperator *op)
1391 {
1392         ImageFormatData *imf = op->customdata;
1393         return WM_operator_filesel_ensure_ext_imtype(op, imf->imtype);
1394 }
1395
1396 static int image_save_as_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1397 {
1398         SpaceImage *sima = CTX_wm_space_image(C);
1399         Image *ima = ED_space_image(sima);
1400         Scene *scene = CTX_data_scene(C);
1401         SaveImageOptions simopts;
1402
1403         if (RNA_struct_property_is_set(op->ptr, "filepath"))
1404                 return image_save_as_exec(C, op);
1405
1406         save_image_options_defaults(&simopts);
1407
1408         if (save_image_options_init(&simopts, sima, scene, TRUE) == 0)
1409                 return OPERATOR_CANCELLED;
1410         save_image_options_to_op(&simopts, op);
1411
1412         /* enable save_copy by default for render results */
1413         if (ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE) && !RNA_struct_property_is_set(op->ptr, "copy")) {
1414                 RNA_boolean_set(op->ptr, "copy", TRUE);
1415         }
1416
1417         if (ima->source == IMA_SRC_VIEWER)
1418                 RNA_boolean_set(op->ptr, "save_as_render", TRUE);
1419         else
1420                 RNA_boolean_set(op->ptr, "save_as_render", FALSE);
1421
1422         op->customdata = MEM_mallocN(sizeof(simopts.im_format), __func__);
1423         memcpy(op->customdata, &simopts.im_format, sizeof(simopts.im_format));
1424
1425         image_filesel(C, op, simopts.filepath);
1426
1427         return OPERATOR_RUNNING_MODAL;
1428 }
1429
1430 static int image_save_as_cancel(bContext *UNUSED(C), wmOperator *op)
1431 {
1432         image_save_as_free(op);
1433
1434         return OPERATOR_CANCELLED;
1435 }
1436
1437 static int image_save_as_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop)
1438 {
1439         const char *prop_id = RNA_property_identifier(prop);
1440
1441         return !(strcmp(prop_id, "filepath") == 0 ||
1442                  strcmp(prop_id, "directory") == 0 ||
1443                  strcmp(prop_id, "filename") == 0 ||
1444                  /* when saving a copy, relative path has no effect */
1445                  ((strcmp(prop_id, "relative_path") == 0) && RNA_boolean_get(ptr, "copy"))
1446                  );
1447 }
1448
1449 static void image_save_as_draw(bContext *UNUSED(C), wmOperator *op)
1450 {
1451         uiLayout *layout = op->layout;
1452         ImageFormatData *imf = op->customdata;
1453         PointerRNA ptr;
1454
1455         /* image template */
1456         RNA_pointer_create(NULL, &RNA_ImageFormatSettings, imf, &ptr);
1457         uiTemplateImageSettings(layout, &ptr, FALSE);
1458
1459         /* main draw call */
1460         RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);
1461         uiDefAutoButsRNA(layout, &ptr, image_save_as_draw_check_prop, '\0');
1462 }
1463
1464 void IMAGE_OT_save_as(wmOperatorType *ot)
1465 {
1466 //      PropertyRNA *prop;
1467
1468         /* identifiers */
1469         ot->name = "Save As Image";
1470         ot->idname = "IMAGE_OT_save_as";
1471         ot->description = "Save the image with another name and/or settings";
1472         
1473         /* api callbacks */
1474         ot->exec = image_save_as_exec;
1475         ot->check = image_save_as_check;
1476         ot->invoke = image_save_as_invoke;
1477         ot->cancel = image_save_as_cancel;
1478         ot->ui = image_save_as_draw;
1479         ot->poll = space_image_buffer_exists_poll;
1480
1481         /* flags */
1482         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1483
1484         /* properties */
1485         RNA_def_boolean(ot->srna, "save_as_render", 0, "Save As Render", "Apply render part of display transform when saving byte image");
1486         RNA_def_boolean(ot->srna, "copy", 0, "Copy", "Create a new image file without modifying the current image in blender");
1487
1488         WM_operator_properties_filesel(ot, FOLDERFILE | IMAGEFILE | MOVIEFILE, FILE_SPECIAL, FILE_SAVE,
1489                                        WM_FILESEL_FILEPATH | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY);
1490 }
1491
1492 /******************** save image operator ********************/
1493
1494 static int image_save_exec(bContext *C, wmOperator *op)
1495 {
1496         SpaceImage *sima = CTX_wm_space_image(C);
1497         Scene *scene = CTX_data_scene(C);
1498         SaveImageOptions simopts;
1499
1500         if (save_image_options_init(&simopts, sima, scene, FALSE) == 0)
1501                 return OPERATOR_CANCELLED;
1502         save_image_options_from_op(&simopts, op);
1503
1504         if (BLI_exists(simopts.filepath) && BLI_file_is_writable(simopts.filepath)) {
1505                 save_image_doit(C, sima, op, &simopts, FALSE);
1506         }
1507         else {
1508                 BKE_reportf(op->reports, RPT_ERROR, "Can not save image, path '%s' is not writable", simopts.filepath);
1509                 return OPERATOR_CANCELLED;
1510         }
1511
1512         return OPERATOR_FINISHED;
1513 }
1514
1515 void IMAGE_OT_save(wmOperatorType *ot)
1516 {
1517         /* identifiers */
1518         ot->name = "Save Image";
1519         ot->idname = "IMAGE_OT_save";
1520         ot->description = "Save the image with current name and settings";
1521         
1522         /* api callbacks */
1523         ot->exec = image_save_exec;
1524         ot->poll = space_image_file_exists_poll;
1525
1526         /* flags */
1527         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1528 }
1529
1530 /******************* save sequence operator ********************/
1531
1532 static int image_save_sequence_exec(bContext *C, wmOperator *op)
1533 {
1534         Main *bmain = CTX_data_main(C);
1535         SpaceImage *sima = CTX_wm_space_image(C);
1536         ImBuf *ibuf;
1537         int tot = 0;
1538         char di[FILE_MAX], fi[FILE_MAX];
1539         
1540         if (sima->image == NULL)
1541                 return OPERATOR_CANCELLED;
1542
1543         if (sima->image->source != IMA_SRC_SEQUENCE) {
1544                 BKE_report(op->reports, RPT_ERROR, "Can only save sequence on image sequences");
1545                 return OPERATOR_CANCELLED;
1546         }
1547
1548         if (sima->image->type == IMA_TYPE_MULTILAYER) {
1549                 BKE_report(op->reports, RPT_ERROR, "Can't save multilayer sequences");
1550                 return OPERATOR_CANCELLED;
1551         }
1552         
1553         /* get total */
1554         for (ibuf = sima->image->ibufs.first; ibuf; ibuf = ibuf->next)
1555                 if (ibuf->userflags & IB_BITMAPDIRTY)
1556                         tot++;
1557         
1558         if (tot == 0) {
1559                 BKE_report(op->reports, RPT_WARNING, "No images have been changed");
1560                 return OPERATOR_CANCELLED;
1561         }
1562
1563         /* get a filename for menu */
1564         for (ibuf = sima->image->ibufs.first; ibuf; ibuf = ibuf->next)
1565                 if (ibuf->userflags & IB_BITMAPDIRTY)
1566                         break;
1567         
1568         BLI_strncpy(di, ibuf->name, FILE_MAX);
1569         BLI_splitdirstring(di, fi);
1570         
1571         BKE_reportf(op->reports, RPT_INFO, "%d Image(s) will be saved in %s", tot, di);
1572
1573         for (ibuf = sima->image->ibufs.first; ibuf; ibuf = ibuf->next) {
1574                 if (ibuf->userflags & IB_BITMAPDIRTY) {
1575                         char name[FILE_MAX];
1576                         BLI_strncpy(name, ibuf->name, sizeof(name));
1577                         
1578                         BLI_path_abs(name, bmain->name);
1579
1580                         if (0 == IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat)) {
1581                                 BKE_reportf(op->reports, RPT_ERROR, "Could not write image %s", name);
1582                                 break;
1583                         }
1584
1585                         BKE_reportf(op->reports, RPT_INFO, "Saved: %s\n", ibuf->name);
1586                         ibuf->userflags &= ~IB_BITMAPDIRTY;
1587                 }
1588         }
1589
1590         return OPERATOR_FINISHED;
1591 }
1592
1593 void IMAGE_OT_save_sequence(wmOperatorType *ot)
1594 {
1595         /* identifiers */
1596         ot->name = "Save Sequence";
1597         ot->idname = "IMAGE_OT_save_sequence";
1598         ot->description = "Save a sequence of images";
1599         
1600         /* api callbacks */
1601         ot->exec = image_save_sequence_exec;
1602         ot->poll = space_image_buffer_exists_poll;
1603
1604         /* flags */
1605         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1606 }
1607
1608 /******************** reload image operator ********************/
1609
1610 static int image_reload_exec(bContext *C, wmOperator *UNUSED(op))
1611 {
1612         Image *ima = CTX_data_edit_image(C);
1613         SpaceImage *sima = CTX_wm_space_image(C);
1614
1615         if (!ima)
1616                 return OPERATOR_CANCELLED;
1617
1618         /* XXX unpackImage frees image buffers */
1619         ED_preview_kill_jobs(C);
1620         
1621         // XXX other users?
1622         BKE_image_signal(ima, (sima) ? &sima->iuser : NULL, IMA_SIGNAL_RELOAD);
1623
1624         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1625         
1626         return OPERATOR_FINISHED;
1627 }
1628
1629 void IMAGE_OT_reload(wmOperatorType *ot)
1630 {
1631         /* identifiers */
1632         ot->name = "Reload Image";
1633         ot->idname = "IMAGE_OT_reload";
1634         ot->description = "Reload current image from disk";
1635         
1636         /* api callbacks */
1637         ot->exec = image_reload_exec;
1638
1639         /* flags */
1640         ot->flag = OPTYPE_REGISTER; /* no undo, image buffer is not handled by undo */
1641 }
1642
1643 /********************** new image operator *********************/
1644
1645 static int image_new_exec(bContext *C, wmOperator *op)
1646 {
1647         SpaceImage *sima;
1648         Scene *scene;
1649         Object *obedit;
1650         Image *ima;
1651         PointerRNA ptr, idptr;
1652         PropertyRNA *prop;
1653         char name[MAX_ID_NAME - 2];
1654         float color[4];
1655         int width, height, floatbuf, gen_type, alpha;
1656
1657         /* retrieve state */
1658         sima = CTX_wm_space_image(C);
1659         scene = CTX_data_scene(C);
1660         obedit = CTX_data_edit_object(C);
1661
1662         RNA_string_get(op->ptr, "name", name);
1663         width = RNA_int_get(op->ptr, "width");
1664         height = RNA_int_get(op->ptr, "height");
1665         floatbuf = RNA_boolean_get(op->ptr, "float");
1666         gen_type = RNA_enum_get(op->ptr, "generated_type");
1667         RNA_float_get_array(op->ptr, "color", color);
1668         alpha = RNA_boolean_get(op->ptr, "alpha");
1669         
1670         if (!floatbuf) {
1671                 /* OCIO_TODO: perhaps we need to convert to display space, not just to sRGB */
1672                 linearrgb_to_srgb_v3_v3(color, color);
1673         }
1674
1675         if (!alpha)
1676                 color[3] = 1.0f;
1677
1678         ima = BKE_image_add_generated(width, height, name, alpha ? 32 : 24, floatbuf, gen_type, color);
1679
1680         if (!ima)
1681                 return OPERATOR_CANCELLED;
1682
1683         /* hook into UI */
1684         uiIDContextProperty(C, &ptr, &prop);
1685
1686         if (prop) {
1687                 /* when creating new ID blocks, use is already 1, but RNA
1688                  * pointer se also increases user, so this compensates it */
1689                 ima->id.us--;
1690
1691                 RNA_id_pointer_create(&ima->id, &idptr);
1692                 RNA_property_pointer_set(&ptr, prop, idptr);
1693                 RNA_property_update(C, &ptr, prop);
1694         }
1695         else if (sima)
1696                 ED_space_image_set(sima, scene, obedit, ima);
1697
1698         // XXX other users?
1699         BKE_image_signal(ima, (sima) ? &sima->iuser : NULL, IMA_SIGNAL_USER_NEW_IMAGE);
1700         
1701         return OPERATOR_FINISHED;
1702 }
1703
1704 /* XXX, Ton is not a fan of OK buttons but using this function to avoid undo/redo bug while in mesh-editmode, - campbell */
1705 static int image_new_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1706 {
1707         return WM_operator_props_dialog_popup(C, op, 300, 100);
1708
1709 }
1710
1711 void IMAGE_OT_new(wmOperatorType *ot)
1712 {
1713         PropertyRNA *prop;
1714         static float default_color[4] = {0.0f, 0.0f, 0.0f, 1.0f};
1715         
1716         /* identifiers */
1717         ot->name = "New Image";
1718         ot->description = "Create a new image";
1719         ot->idname = "IMAGE_OT_new";
1720         
1721         /* api callbacks */
1722         ot->exec = image_new_exec;
1723         ot->invoke = image_new_invoke;
1724         
1725         /* flags */
1726         ot->flag = OPTYPE_UNDO;
1727
1728         /* properties */
1729         RNA_def_string(ot->srna, "name", "untitled", MAX_ID_NAME - 2, "Name", "Image datablock name");
1730         RNA_def_int(ot->srna, "width", 1024, 1, INT_MAX, "Width", "Image width", 1, 16384);
1731         RNA_def_int(ot->srna, "height", 1024, 1, INT_MAX, "Height", "Image height", 1, 16384);
1732         prop = RNA_def_float_color(ot->srna, "color", 4, NULL, 0.0f, FLT_MAX, "Color", "Default fill color", 0.0f, 1.0f);
1733         RNA_def_property_float_array_default(prop, default_color);
1734         RNA_def_boolean(ot->srna, "alpha", 1, "Alpha", "Create an image with an alpha channel");
1735         RNA_def_enum(ot->srna, "generated_type", image_generated_type_items, IMA_GENTYPE_BLANK,
1736                      "Generated Type", "Fill the image with a grid for UV map testing");
1737         RNA_def_boolean(ot->srna, "float", 0, "32 bit Float", "Create image with 32 bit floating point bit depth");
1738 }
1739
1740 /********************* invert operators *********************/
1741
1742 static int image_invert_poll(bContext *C)
1743 {
1744         Image *ima = CTX_data_edit_image(C);
1745         ImBuf *ibuf = BKE_image_get_ibuf(ima, NULL);
1746         
1747         if (ibuf != NULL)
1748                 return 1;
1749         return 0;
1750 }
1751
1752 static int image_invert_exec(bContext *C, wmOperator *op)
1753 {
1754         Image *ima = CTX_data_edit_image(C);
1755         ImBuf *ibuf = BKE_image_get_ibuf(ima, NULL);
1756
1757         /* flags indicate if this channel should be inverted */
1758         const short r = RNA_boolean_get(op->ptr, "invert_r");
1759         const short g = RNA_boolean_get(op->ptr, "invert_g");
1760         const short b = RNA_boolean_get(op->ptr, "invert_b");
1761         const short a = RNA_boolean_get(op->ptr, "invert_a");
1762
1763         int i;
1764
1765         if (ibuf == NULL)  /* TODO: this should actually never happen, but does for render-results -> cleanup */
1766                 return OPERATOR_CANCELLED;
1767
1768         /* TODO: make this into an IMB_invert_channels(ibuf,r,g,b,a) method!? */
1769         if (ibuf->rect_float) {
1770                 
1771                 float *fp = (float *) ibuf->rect_float;
1772                 for (i = ibuf->x * ibuf->y; i > 0; i--, fp += 4) {
1773                         if (r) fp[0] = 1.0f - fp[0];
1774                         if (g) fp[1] = 1.0f - fp[1];
1775                         if (b) fp[2] = 1.0f - fp[2];
1776                         if (a) fp[3] = 1.0f - fp[3];
1777                 }
1778
1779                 if (ibuf->rect) {
1780                         IMB_rect_from_float(ibuf);
1781                 }
1782         }
1783         else if (ibuf->rect) {
1784                 
1785                 char *cp = (char *) ibuf->rect;
1786                 for (i = ibuf->x * ibuf->y; i > 0; i--, cp += 4) {
1787                         if (r) cp[0] = 255 - cp[0];
1788                         if (g) cp[1] = 255 - cp[1];
1789                         if (b) cp[2] = 255 - cp[2];
1790                         if (a) cp[3] = 255 - cp[3];
1791                 }
1792         }
1793         else {
1794                 return OPERATOR_CANCELLED;
1795         }
1796
1797         ibuf->userflags |= IB_BITMAPDIRTY;
1798         if (ibuf->mipmap[0])
1799                 ibuf->userflags |= IB_MIPMAP_INVALID;
1800
1801         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1802         return OPERATOR_FINISHED;
1803 }
1804
1805 void IMAGE_OT_invert(wmOperatorType *ot)
1806 {
1807         /* identifiers */
1808         ot->name = "Invert Channels";
1809         ot->idname = "IMAGE_OT_invert";
1810         ot->description = "Invert image's channels";
1811         
1812         /* api callbacks */
1813         ot->exec = image_invert_exec;
1814         ot->poll = image_invert_poll;
1815         
1816         /* properties */
1817         RNA_def_boolean(ot->srna, "invert_r", 0, "Red", "Invert Red Channel");
1818         RNA_def_boolean(ot->srna, "invert_g", 0, "Green", "Invert Green Channel");
1819         RNA_def_boolean(ot->srna, "invert_b", 0, "Blue", "Invert Blue Channel");
1820         RNA_def_boolean(ot->srna, "invert_a", 0, "Alpha", "Invert Alpha Channel");
1821         
1822         /* flags */
1823         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1824 }
1825
1826 /********************* pack operator *********************/
1827
1828 static int image_pack_test(bContext *C, wmOperator *op)
1829 {
1830         Image *ima = CTX_data_edit_image(C);
1831         int as_png = RNA_boolean_get(op->ptr, "as_png");
1832
1833         if (!ima)
1834                 return 0;
1835         if (!as_png && ima->packedfile)
1836                 return 0;
1837
1838         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
1839                 BKE_report(op->reports, RPT_ERROR, "Packing movies or image sequences not supported");
1840                 return 0;
1841         }
1842
1843         return 1;
1844 }
1845
1846 static int image_pack_exec(bContext *C, wmOperator *op)
1847 {
1848         struct Main *bmain = CTX_data_main(C);
1849         Image *ima = CTX_data_edit_image(C);
1850         ImBuf *ibuf = BKE_image_get_ibuf(ima, NULL);
1851         int as_png = RNA_boolean_get(op->ptr, "as_png");
1852
1853         if (!image_pack_test(C, op))
1854                 return OPERATOR_CANCELLED;
1855         
1856         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1857                 BKE_report(op->reports, RPT_ERROR, "Can't pack edited image from disk, only as internal PNG");
1858                 return OPERATOR_CANCELLED;
1859         }
1860
1861         if (as_png)
1862                 BKE_image_memorypack(ima);
1863         else
1864                 ima->packedfile = newPackedFile(op->reports, ima->name, ID_BLEND_PATH(bmain, &ima->id));
1865
1866         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1867         
1868         return OPERATOR_FINISHED;
1869 }
1870
1871 static int image_pack_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1872 {
1873         Image *ima = CTX_data_edit_image(C);
1874         ImBuf *ibuf = BKE_image_get_ibuf(ima, NULL);
1875         uiPopupMenu *pup;
1876         uiLayout *layout;
1877         int as_png = RNA_boolean_get(op->ptr, "as_png");
1878
1879         if (!image_pack_test(C, op))
1880                 return OPERATOR_CANCELLED;
1881         
1882         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1883                 pup = uiPupMenuBegin(C, "OK", ICON_QUESTION);
1884                 layout = uiPupMenuLayout(pup);
1885                 uiItemBooleanO(layout, "Can't pack edited image from disk. Pack as internal PNG?", ICON_NONE, op->idname, "as_png", 1);
1886                 uiPupMenuEnd(C, pup);
1887
1888                 return OPERATOR_CANCELLED;
1889         }
1890
1891         return image_pack_exec(C, op);
1892 }
1893
1894 void IMAGE_OT_pack(wmOperatorType *ot)
1895 {
1896         /* identifiers */
1897         ot->name = "Pack Image";
1898         ot->description = "Pack an image as embedded data into the .blend file"; 
1899         ot->idname = "IMAGE_OT_pack";
1900         
1901         /* api callbacks */
1902         ot->exec = image_pack_exec;
1903         ot->invoke = image_pack_invoke;
1904
1905         /* flags */
1906         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1907
1908         /* properties */
1909         RNA_def_boolean(ot->srna, "as_png", 0, "Pack As PNG", "Pack image as lossless PNG");
1910 }
1911
1912 /********************* unpack operator *********************/
1913
1914 static int image_unpack_exec(bContext *C, wmOperator *op)
1915 {
1916         Image *ima = CTX_data_edit_image(C);
1917         int method = RNA_enum_get(op->ptr, "method");
1918
1919         /* find the suppplied image by name */
1920         if (RNA_struct_property_is_set(op->ptr, "id")) {
1921                 char imaname[MAX_ID_NAME - 2];
1922                 RNA_string_get(op->ptr, "id", imaname);
1923                 ima = BLI_findstring(&CTX_data_main(C)->image, imaname, offsetof(ID, name) + 2);
1924                 if (!ima) ima = CTX_data_edit_image(C);
1925         }
1926         
1927         if (!ima || !ima->packedfile)
1928                 return OPERATOR_CANCELLED;
1929
1930         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
1931                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
1932                 return OPERATOR_CANCELLED;
1933         }
1934
1935         if (G.fileflags & G_AUTOPACK)
1936                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
1937         
1938         /* XXX unpackImage frees image buffers */
1939         ED_preview_kill_jobs(C);
1940         
1941         unpackImage(op->reports, ima, method);
1942         
1943         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1944
1945         return OPERATOR_FINISHED;
1946 }
1947
1948 static int image_unpack_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1949 {
1950         Image *ima = CTX_data_edit_image(C);
1951
1952         if (RNA_struct_property_is_set(op->ptr, "id"))
1953                 return image_unpack_exec(C, op);
1954                 
1955         if (!ima || !ima->packedfile)
1956                 return OPERATOR_CANCELLED;
1957
1958         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
1959                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
1960                 return OPERATOR_CANCELLED;
1961         }
1962
1963         if (G.fileflags & G_AUTOPACK)
1964                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
1965
1966         unpack_menu(C, "IMAGE_OT_unpack", ima->id.name + 2, ima->name, "textures", ima->packedfile);
1967
1968         return OPERATOR_FINISHED;
1969 }
1970
1971 void IMAGE_OT_unpack(wmOperatorType *ot)
1972 {
1973         /* identifiers */
1974         ot->name = "Unpack Image";
1975         ot->description = "Save an image packed in the .blend file to disk"; 
1976         ot->idname = "IMAGE_OT_unpack";
1977         
1978         /* api callbacks */
1979         ot->exec = image_unpack_exec;
1980         ot->invoke = image_unpack_invoke;
1981
1982         /* flags */
1983         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1984         
1985         /* properties */
1986         RNA_def_enum(ot->srna, "method", unpack_method_items, PF_USE_LOCAL, "Method", "How to unpack");
1987         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 */
1988 }
1989
1990 /******************** sample image operator ********************/
1991
1992 typedef struct ImageSampleInfo {
1993         ARegionType *art;
1994         void *draw_handle;
1995         int x, y;
1996         int channels;
1997
1998         unsigned char col[4];
1999         float colf[4];
2000         int z;
2001         float zf;
2002
2003         unsigned char *colp;
2004         float *colfp;
2005         int *zp;
2006         float *zfp;
2007
2008         int draw;
2009         int color_manage;
2010         int use_default_view;
2011 } ImageSampleInfo;
2012
2013 static void image_sample_draw(const bContext *C, ARegion *ar, void *arg_info)
2014 {
2015         ImageSampleInfo *info = arg_info;
2016         if (info->draw) {
2017                 Scene *scene = CTX_data_scene(C);
2018
2019                 ED_image_draw_info(scene, ar, info->color_manage, info->use_default_view, info->channels,
2020                                    info->x, info->y, info->colp, info->colfp, info->zp, info->zfp);
2021         }
2022 }
2023
2024 /* returns color in SRGB */
2025 /* matching ED_space_node_color_sample() */
2026 int ED_space_image_color_sample(SpaceImage *sima, ARegion *ar, int mval[2], float r_col[3])
2027 {
2028         void *lock;
2029         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2030         float fx, fy;
2031         int ret = FALSE;
2032
2033         if (ibuf == NULL) {
2034                 ED_space_image_release_buffer(sima, lock);
2035                 return FALSE;
2036         }
2037
2038         UI_view2d_region_to_view(&ar->v2d, mval[0], mval[1], &fx, &fy);
2039
2040         if (fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) {
2041                 float *fp;
2042                 unsigned char *cp;
2043                 int x = (int)(fx * ibuf->x), y = (int)(fy * ibuf->y);
2044
2045                 CLAMP(x, 0, ibuf->x - 1);
2046                 CLAMP(y, 0, ibuf->y - 1);
2047
2048                 if (ibuf->rect_float) {
2049                         fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
2050
2051                         if (ELEM(ibuf->profile, IB_PROFILE_LINEAR_RGB, IB_PROFILE_NONE)) {
2052                                 linearrgb_to_srgb_v3_v3(r_col, fp);
2053                         }
2054                         else {
2055                                 copy_v3_v3(r_col, fp);
2056                         }
2057                         ret = TRUE;
2058                 }
2059                 else if (ibuf->rect) {
2060                         cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
2061                         rgb_uchar_to_float(r_col, cp);
2062                         ret = TRUE;
2063                 }
2064         }
2065
2066         ED_space_image_release_buffer(sima, lock);
2067         return ret;
2068 }
2069
2070 static void image_sample_apply(bContext *C, wmOperator *op, wmEvent *event)
2071 {
2072         SpaceImage *sima = CTX_wm_space_image(C);
2073         ARegion *ar = CTX_wm_region(C);
2074         void *lock;
2075         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2076         ImageSampleInfo *info = op->customdata;
2077         float fx, fy;
2078         Scene *scene = CTX_data_scene(C);
2079         CurveMapping *curve_mapping = scene->view_settings.curve_mapping;
2080
2081         if (ibuf == NULL) {
2082                 ED_space_image_release_buffer(sima, lock);
2083                 info->draw = 0;
2084                 return;
2085         }
2086
2087         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &fx, &fy);
2088
2089         if (fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) {
2090                 float *fp;
2091                 unsigned char *cp;
2092                 int x = (int)(fx * ibuf->x), y = (int)(fy * ibuf->y);
2093                 Image *image = ED_space_image(sima);
2094
2095                 CLAMP(x, 0, ibuf->x - 1);
2096                 CLAMP(y, 0, ibuf->y - 1);
2097
2098                 info->x = x;
2099                 info->y = y;
2100                 info->draw = 1;
2101                 info->channels = ibuf->channels;
2102
2103                 info->colp = NULL;
2104                 info->colfp = NULL;
2105                 info->zp = NULL;
2106                 info->zfp = NULL;
2107
2108                 info->use_default_view = (image->flag & IMA_VIEW_AS_RENDER) ? FALSE : TRUE;
2109
2110                 if (ibuf->rect) {
2111                         cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
2112
2113                         info->col[0] = cp[0];
2114                         info->col[1] = cp[1];
2115                         info->col[2] = cp[2];
2116                         info->col[3] = cp[3];
2117                         info->colp = info->col;
2118
2119                         info->colf[0] = (float)cp[0] / 255.0f;
2120                         info->colf[1] = (float)cp[1] / 255.0f;
2121                         info->colf[2] = (float)cp[2] / 255.0f;
2122                         info->colf[3] = (float)cp[3] / 255.0f;
2123                         info->colfp = info->colf;
2124
2125                         info->color_manage = FALSE;
2126                 }
2127                 if (ibuf->rect_float) {
2128                         fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
2129
2130                         info->colf[0] = fp[0];
2131                         info->colf[1] = fp[1];
2132                         info->colf[2] = fp[2];
2133                         info->colf[3] = fp[3];
2134                         info->colfp = info->colf;
2135
2136                         info->color_manage = TRUE;
2137                 }
2138
2139                 if (ibuf->zbuf) {
2140                         info->z = ibuf->zbuf[y * ibuf->x + x];
2141                         info->zp = &info->z;
2142                 }
2143                 if (ibuf->zbuf_float) {
2144                         info->zf = ibuf->zbuf_float[y * ibuf->x + x];
2145                         info->zfp = &info->zf;
2146                 }
2147
2148                 if (curve_mapping && ibuf->channels == 4) {
2149                         /* we reuse this callback for set curves point operators */
2150                         if (RNA_struct_find_property(op->ptr, "point")) {
2151                                 int point = RNA_enum_get(op->ptr, "point");
2152
2153                                 if (point == 1) {
2154                                         curvemapping_set_black_white(curve_mapping, NULL, info->colfp);
2155                                 }
2156                                 else if (point == 0) {
2157                                         curvemapping_set_black_white(curve_mapping, info->colfp, NULL);
2158                                 }
2159                         }
2160                 }
2161
2162                 // XXX node curve integration ..
2163 #if 0
2164                 {
2165                         ScrArea *sa, *cur = curarea;
2166                         
2167                         node_curvemap_sample(fp);   /* sends global to node editor */
2168                         for (sa = G.curscreen->areabase.first; sa; sa = sa->next) {
2169                                 if (sa->spacetype == SPACE_NODE) {
2170                                         areawinset(sa->win);
2171                                         scrarea_do_windraw(sa);
2172                                 }
2173                         }
2174                         node_curvemap_sample(NULL);     /* clears global in node editor */
2175                         curarea = cur;
2176                 }
2177 #endif
2178         }
2179         else {
2180                 info->draw = 0;
2181         }
2182
2183         ED_space_image_release_buffer(sima, lock);
2184         ED_area_tag_redraw(CTX_wm_area(C));
2185 }
2186
2187 static void image_sample_exit(bContext *C, wmOperator *op)
2188 {
2189         ImageSampleInfo *info = op->customdata;
2190
2191         ED_region_draw_cb_exit(info->art, info->draw_handle);
2192         ED_area_tag_redraw(CTX_wm_area(C));
2193         MEM_freeN(info);
2194 }
2195
2196 static int image_sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
2197 {
2198         SpaceImage *sima = CTX_wm_space_image(C);
2199         ARegion *ar = CTX_wm_region(C);
2200         ImageSampleInfo *info;
2201
2202         if (!ED_space_image_has_buffer(sima))
2203                 return OPERATOR_CANCELLED;
2204         
2205         info = MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
2206         info->art = ar->type;
2207         info->draw_handle = ED_region_draw_cb_activate(ar->type, image_sample_draw, info, REGION_DRAW_POST_PIXEL);
2208         op->customdata = info;
2209
2210         image_sample_apply(C, op, event);
2211
2212         WM_event_add_modal_handler(C, op);
2213
2214         return OPERATOR_RUNNING_MODAL;
2215 }
2216
2217 static int image_sample_modal(bContext *C, wmOperator *op, wmEvent *event)
2218 {
2219         switch (event->type) {
2220                 case LEFTMOUSE:
2221                 case RIGHTMOUSE: // XXX hardcoded
2222                         image_sample_exit(C, op);
2223                         return OPERATOR_CANCELLED;
2224                 case MOUSEMOVE:
2225                         image_sample_apply(C, op, event);
2226                         break;
2227         }
2228
2229         return OPERATOR_RUNNING_MODAL;
2230 }
2231
2232 static int image_sample_cancel(bContext *C, wmOperator *op)
2233 {
2234         image_sample_exit(C, op);
2235         return OPERATOR_CANCELLED;
2236 }
2237
2238 void IMAGE_OT_sample(wmOperatorType *ot)
2239 {
2240         /* identifiers */
2241         ot->name = "Sample Color";
2242         ot->idname = "IMAGE_OT_sample";
2243         ot->description = "Use mouse to sample a color in current image";
2244         
2245         /* api callbacks */
2246         ot->invoke = image_sample_invoke;
2247         ot->modal = image_sample_modal;
2248         ot->cancel = image_sample_cancel;
2249         ot->poll = image_sample_poll;
2250
2251         /* flags */
2252         ot->flag = OPTYPE_BLOCKING;
2253 }
2254
2255 /******************** sample line operator ********************/
2256 static int image_sample_line_exec(bContext *C, wmOperator *op)
2257 {
2258         SpaceImage *sima = CTX_wm_space_image(C);
2259         ARegion *ar = CTX_wm_region(C);
2260         Scene *scene = CTX_data_scene(C);
2261
2262         int x_start = RNA_int_get(op->ptr, "xstart");
2263         int y_start = RNA_int_get(op->ptr, "ystart");
2264         int x_end = RNA_int_get(op->ptr, "xend");
2265         int y_end = RNA_int_get(op->ptr, "yend");
2266         
2267         void *lock;
2268         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2269         Histogram *hist = &sima->sample_line_hist;
2270         
2271         float x1f, y1f, x2f, y2f;
2272         
2273         if (ibuf == NULL) {
2274                 ED_space_image_release_buffer(sima, lock);
2275                 return OPERATOR_CANCELLED;
2276         }
2277         /* hmmmm */
2278         if (ibuf->channels < 3) {
2279                 ED_space_image_release_buffer(sima, lock);
2280                 return OPERATOR_CANCELLED;
2281         }
2282         
2283         UI_view2d_region_to_view(&ar->v2d, x_start, y_start, &x1f, &y1f);
2284         UI_view2d_region_to_view(&ar->v2d, x_end, y_end, &x2f, &y2f);
2285
2286         hist->co[0][0] = x1f;
2287         hist->co[0][1] = y1f;
2288         hist->co[1][0] = x2f;
2289         hist->co[1][1] = y2f;
2290
2291         BKE_histogram_update_sample_line(hist, ibuf, &scene->view_settings, &scene->display_settings);
2292         
2293         /* reset y zoom */
2294         hist->ymax = 1.0f;
2295
2296         ED_space_image_release_buffer(sima, lock);
2297         
2298         ED_area_tag_redraw(CTX_wm_area(C));
2299         
2300         return OPERATOR_FINISHED;
2301 }
2302
2303 static int image_sample_line_invoke(bContext *C, wmOperator *op, wmEvent *event)
2304 {
2305         SpaceImage *sima = CTX_wm_space_image(C);
2306
2307         Histogram *hist = &sima->sample_line_hist;
2308         hist->flag &= ~HISTO_FLAG_SAMPLELINE;
2309
2310         if (!ED_space_image_has_buffer(sima))
2311                 return OPERATOR_CANCELLED;
2312         
2313         return WM_gesture_straightline_invoke(C, op, event);
2314 }
2315
2316 void IMAGE_OT_sample_line(wmOperatorType *ot)
2317 {
2318         /* identifiers */
2319         ot->name = "Sample Line";
2320         ot->idname = "IMAGE_OT_sample_line";
2321         ot->description = "Sample a line and show it in Scope panels";
2322         
2323         /* api callbacks */
2324         ot->invoke = image_sample_line_invoke;
2325         ot->modal = WM_gesture_straightline_modal;
2326         ot->exec = image_sample_line_exec;
2327         ot->poll = space_image_main_area_poll;
2328         ot->cancel = WM_gesture_straightline_cancel;
2329         
2330         /* flags */
2331         ot->flag = 0; /* no undo/register since this operates on the space */
2332         
2333         WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT);
2334 }
2335
2336 /******************** set curve point operator ********************/
2337
2338 void IMAGE_OT_curves_point_set(wmOperatorType *ot)
2339 {
2340         static EnumPropertyItem point_items[] = {
2341                 {0, "BLACK_POINT", 0, "Black Point", ""},
2342                 {1, "WHITE_POINT", 0, "White Point", ""},
2343                 {0, NULL, 0, NULL, NULL}
2344         };
2345
2346         /* identifiers */
2347         ot->name = "Set Curves Point";
2348         ot->idname = "IMAGE_OT_curves_point_set";
2349         ot->description = "Set black point or white point for curves";
2350
2351         /* flags */
2352         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2353         
2354         /* api callbacks */
2355         ot->invoke = image_sample_invoke;
2356         ot->modal = image_sample_modal;
2357         ot->cancel = image_sample_cancel;
2358         ot->poll = space_image_main_area_not_uv_brush_poll;
2359
2360         /* properties */
2361         RNA_def_enum(ot->srna, "point", point_items, 0, "Point", "Set black point or white point for curves");
2362 }
2363
2364 /******************** record composite operator *********************/
2365
2366 typedef struct RecordCompositeData {
2367         wmTimer *timer;
2368         int old_cfra;
2369         int sfra, efra;
2370 } RecordCompositeData;
2371
2372 static int image_record_composite_apply(bContext *C, wmOperator *op)
2373 {
2374         SpaceImage *sima = CTX_wm_space_image(C);
2375         RecordCompositeData *rcd = op->customdata;
2376         Scene *scene = CTX_data_scene(C);
2377         ImBuf *ibuf;
2378         
2379         WM_cursor_time(CTX_wm_window(C), scene->r.cfra);
2380
2381         // XXX scene->nodetree->test_break= blender_test_break;
2382         // XXX scene->nodetree->test_break= NULL;
2383         
2384         BKE_image_all_free_anim_ibufs(scene->r.cfra);
2385         ntreeCompositTagAnimated(scene->nodetree);
2386         ntreeCompositExecTree(scene->nodetree, &scene->r, 0, scene->r.cfra != rcd->old_cfra,
2387                               &scene->view_settings, &scene->display_settings);  /* 1 is no previews */
2388
2389         ED_area_tag_redraw(CTX_wm_area(C));
2390         
2391         ibuf = BKE_image_get_ibuf(sima->image, &sima->iuser);
2392         /* save memory in flipbooks */
2393         if (ibuf)
2394                 imb_freerectfloatImBuf(ibuf);
2395         
2396         scene->r.cfra++;
2397
2398         return (scene->r.cfra <= rcd->efra);
2399 }
2400
2401 static int image_record_composite_init(bContext *C, wmOperator *op)
2402 {
2403         SpaceImage *sima = CTX_wm_space_image(C);
2404         Scene *scene = CTX_data_scene(C);
2405         RecordCompositeData *rcd;
2406
2407         if (sima->iuser.frames < 2)
2408                 return 0;
2409         if (scene->nodetree == NULL)
2410                 return 0;
2411         
2412         op->customdata = rcd = MEM_callocN(sizeof(RecordCompositeData), "ImageRecordCompositeData");
2413
2414         rcd->old_cfra = scene->r.cfra;
2415         rcd->sfra = sima->iuser.sfra;
2416         rcd->efra = sima->iuser.sfra + sima->iuser.frames - 1;
2417         scene->r.cfra = rcd->sfra;
2418
2419         return 1;
2420 }
2421
2422 static void image_record_composite_exit(bContext *C, wmOperator *op)
2423 {
2424         Scene *scene = CTX_data_scene(C);
2425         SpaceImage *sima = CTX_wm_space_image(C);
2426         RecordCompositeData *rcd = op->customdata;
2427
2428         scene->r.cfra = rcd->old_cfra;
2429
2430         WM_cursor_restore(CTX_wm_window(C));
2431
2432         if (rcd->timer)
2433                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rcd->timer);
2434
2435         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
2436
2437         // XXX play_anim(0);
2438         // XXX allqueue(REDRAWNODE, 1);
2439
2440         MEM_freeN(rcd);
2441 }
2442
2443 static int image_record_composite_exec(bContext *C, wmOperator *op)
2444 {
2445         if (!image_record_composite_init(C, op))
2446                 return OPERATOR_CANCELLED;
2447         
2448         while (image_record_composite_apply(C, op))
2449                 ;
2450         
2451         image_record_composite_exit(C, op);
2452         
2453         return OPERATOR_FINISHED;
2454 }
2455
2456 static int image_record_composite_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2457 {
2458         RecordCompositeData *rcd;
2459         
2460         if (!image_record_composite_init(C, op))
2461                 return OPERATOR_CANCELLED;
2462
2463         rcd = op->customdata;
2464         rcd->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.0f);
2465         WM_event_add_modal_handler(C, op);
2466
2467         if (!image_record_composite_apply(C, op))
2468                 return OPERATOR_FINISHED;
2469
2470         return OPERATOR_RUNNING_MODAL;
2471 }
2472
2473 static int image_record_composite_modal(bContext *C, wmOperator *op, wmEvent *event)
2474 {
2475         RecordCompositeData *rcd = op->customdata;
2476
2477         switch (event->type) {
2478                 case TIMER:
2479                         if (rcd->timer == event->customdata) {
2480                                 if (!image_record_composite_apply(C, op)) {
2481                                         image_record_composite_exit(C, op);
2482                                         return OPERATOR_FINISHED;
2483                                 }
2484                         }
2485                         break;
2486                 case ESCKEY:
2487                         image_record_composite_exit(C, op);
2488                         return OPERATOR_FINISHED;
2489         }
2490
2491         return OPERATOR_RUNNING_MODAL;
2492 }
2493
2494 static int image_record_composite_cancel(bContext *C, wmOperator *op)
2495 {
2496         image_record_composite_exit(C, op);
2497         return OPERATOR_CANCELLED;
2498 }
2499
2500 void IMAGE_OT_record_composite(wmOperatorType *ot)
2501 {
2502         /* identifiers */
2503         ot->name = "Record Composite";
2504         ot->idname = "IMAGE_OT_record_composite";
2505         
2506         /* api callbacks */
2507         ot->exec = image_record_composite_exec;
2508         ot->invoke = image_record_composite_invoke;
2509         ot->modal = image_record_composite_modal;
2510         ot->cancel = image_record_composite_cancel;
2511         ot->poll = space_image_buffer_exists_poll;
2512 }
2513
2514 /********************* cycle render slot operator *********************/
2515
2516 static int image_cycle_render_slot_poll(bContext *C)
2517 {
2518         Image *ima = CTX_data_edit_image(C);
2519
2520         return (ima && ima->type == IMA_TYPE_R_RESULT);
2521 }
2522
2523 static int image_cycle_render_slot_exec(bContext *C, wmOperator *op)
2524 {
2525         Image *ima = CTX_data_edit_image(C);
2526         int a, slot, cur = ima->render_slot;
2527         const short use_reverse = RNA_boolean_get(op->ptr, "reverse");
2528
2529         for (a = 1; a < IMA_MAX_RENDER_SLOT; a++) {
2530                 slot = (cur + (use_reverse ? -a : a)) % IMA_MAX_RENDER_SLOT;
2531                 if (slot < 0) slot += IMA_MAX_RENDER_SLOT;
2532
2533                 if (ima->renders[slot] || slot == ima->last_render_slot) {
2534                         ima->render_slot = slot;
2535                         break;
2536                 }
2537         }
2538
2539         if (a == IMA_MAX_RENDER_SLOT)
2540                 ima->render_slot = ((cur == 1) ? 0 : 1);
2541         
2542         WM_event_add_notifier(C, NC_IMAGE | ND_DRAW, NULL);
2543
2544         /* no undo push for browsing existing */
2545         if (ima->renders[ima->render_slot] || ima->render_slot == ima->last_render_slot)
2546                 return OPERATOR_CANCELLED;
2547         
2548         return OPERATOR_FINISHED;
2549 }
2550
2551 void IMAGE_OT_cycle_render_slot(wmOperatorType *ot)
2552 {
2553         /* identifiers */
2554         ot->name = "Cycle Render Slot";
2555         ot->idname = "IMAGE_OT_cycle_render_slot";
2556         ot->description = "Cycle through all non-void render slots";
2557         
2558         /* api callbacks */
2559         ot->exec = image_cycle_render_slot_exec;
2560         ot->poll = image_cycle_render_slot_poll;
2561
2562         /* flags */
2563         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2564
2565         RNA_def_boolean(ot->srna, "reverse", 0, "Cycle in Reverse", "");
2566 }