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