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