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