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