f1662bc254dcfb33c27f3409aca3f6f309ed374b
[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->x - event->prevx) / sima->zoom;
303                 offset[1] = (event->y - event->prevy) / 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->x - event->prevx + event->y - event->prevy;
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 (BLI_testextensie_array(str, imb_ext_movie))
1113                 sima->image->source = IMA_SRC_MOVIE;
1114         else
1115                 sima->image->source = IMA_SRC_FILE;
1116
1117         /* XXX unpackImage frees image buffers */
1118         ED_preview_kill_jobs(C);
1119         
1120         BKE_image_signal(sima->image, &sima->iuser, IMA_SIGNAL_RELOAD);
1121         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
1122
1123         return OPERATOR_FINISHED;
1124 }
1125
1126 static int image_replace_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1127 {
1128         SpaceImage *sima = CTX_wm_space_image(C);
1129
1130         if (!sima->image)
1131                 return OPERATOR_CANCELLED;
1132
1133         if (RNA_struct_property_is_set(op->ptr, "filepath"))
1134                 return image_replace_exec(C, op);
1135
1136         if (!RNA_struct_property_is_set(op->ptr, "relative_path"))
1137                 RNA_boolean_set(op->ptr, "relative_path", BLI_path_is_rel(sima->image->name));
1138
1139         image_filesel(C, op, sima->image->name);
1140
1141         return OPERATOR_RUNNING_MODAL;
1142 }
1143
1144 void IMAGE_OT_replace(wmOperatorType *ot)
1145 {
1146         /* identifiers */
1147         ot->name = "Replace Image";
1148         ot->idname = "IMAGE_OT_replace";
1149         ot->description = "Replace current image by another one from disk";
1150         
1151         /* api callbacks */
1152         ot->exec = image_replace_exec;
1153         ot->invoke = image_replace_invoke;
1154         ot->poll = space_image_poll;
1155
1156         /* flags */
1157         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1158
1159         /* properties */
1160         WM_operator_properties_filesel(ot, FOLDERFILE | IMAGEFILE | MOVIEFILE, FILE_SPECIAL, FILE_OPENFILE,
1161                                        WM_FILESEL_FILEPATH | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY);
1162 }
1163
1164 /******************** save image as operator ********************/
1165
1166 typedef struct {
1167         /* matching scene->r settings */
1168         //short planes, imtype, subimtype, quality;
1169         ImageFormatData im_format;
1170         char filepath[FILE_MAX]; /* keep absolute */
1171 } SaveImageOptions;
1172
1173 static void save_image_options_defaults(SaveImageOptions *simopts)
1174 {
1175         BKE_imformat_defaults(&simopts->im_format);
1176         simopts->filepath[0] = '\0';
1177 }
1178
1179 static char imtype_best_depth(ImBuf *ibuf, const char imtype)
1180 {
1181         const char depth_ok = BKE_imtype_valid_depths(imtype);
1182
1183         if (ibuf->rect_float) {
1184                 if (depth_ok & R_IMF_CHAN_DEPTH_32) return R_IMF_CHAN_DEPTH_32;
1185                 if (depth_ok & R_IMF_CHAN_DEPTH_24) return R_IMF_CHAN_DEPTH_24;
1186                 if (depth_ok & R_IMF_CHAN_DEPTH_16) return R_IMF_CHAN_DEPTH_16;
1187                 if (depth_ok & R_IMF_CHAN_DEPTH_12) return R_IMF_CHAN_DEPTH_12;
1188                 return R_IMF_CHAN_DEPTH_8;
1189         }
1190         else {
1191                 if (depth_ok & R_IMF_CHAN_DEPTH_8) return R_IMF_CHAN_DEPTH_8;
1192                 if (depth_ok & R_IMF_CHAN_DEPTH_12) return R_IMF_CHAN_DEPTH_12;
1193                 if (depth_ok & R_IMF_CHAN_DEPTH_16) return R_IMF_CHAN_DEPTH_16;
1194                 if (depth_ok & R_IMF_CHAN_DEPTH_24) return R_IMF_CHAN_DEPTH_24;
1195                 if (depth_ok & R_IMF_CHAN_DEPTH_32) return R_IMF_CHAN_DEPTH_32;
1196                 return R_IMF_CHAN_DEPTH_8; /* fallback, should not get here */
1197         }
1198 }
1199
1200 static int save_image_options_init(SaveImageOptions *simopts, SpaceImage *sima, Scene *scene, const short guess_path)
1201 {
1202         void *lock;
1203         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
1204
1205         if (ibuf) {
1206                 Image *ima = sima->image;
1207                 short is_depth_set = FALSE;
1208
1209                 simopts->im_format.planes = ibuf->planes;
1210
1211                 if (ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE)) {
1212                         /* imtype */
1213                         simopts->im_format = scene->r.im_format;
1214                         is_depth_set = TRUE;
1215                 }
1216                 else if (ima->source == IMA_SRC_GENERATED) {
1217                         simopts->im_format.imtype = R_IMF_IMTYPE_PNG;
1218                 }
1219                 else {
1220                         BKE_imbuf_to_image_format(&simopts->im_format, ibuf);
1221                 }
1222                 //simopts->subimtype = scene->r.subimtype; /* XXX - this is lame, we need to make these available too! */
1223                 simopts->im_format.quality = ibuf->ftype & 0xff;
1224
1225                 BLI_strncpy(simopts->filepath, ibuf->name, sizeof(simopts->filepath));
1226
1227                 /* sanitize all settings */
1228
1229                 /* unlikely but just in case */
1230                 if (ELEM3(simopts->im_format.planes, R_IMF_PLANES_BW, R_IMF_PLANES_RGB, R_IMF_PLANES_RGBA) == 0) {
1231                         simopts->im_format.planes = R_IMF_PLANES_RGBA;
1232                 }
1233
1234                 /* depth, account for float buffer and format support */
1235                 if (is_depth_set == FALSE) {
1236                         simopts->im_format.depth = imtype_best_depth(ibuf, simopts->im_format.imtype);
1237                 }
1238
1239                 /* some formats don't use quality so fallback to scenes quality */
1240                 if (simopts->im_format.quality == 0) {
1241                         simopts->im_format.quality = scene->r.im_format.quality;
1242                 }
1243
1244                 /* check for empty path */
1245                 if (guess_path && simopts->filepath[0] == 0) {
1246                         if ((G.ima[0] == '/') && (G.ima[1] == '/') && (G.ima[2] == '\0')) {
1247                                 BLI_strncpy(simopts->filepath, "//untitled", FILE_MAX);
1248                         }
1249                         else {
1250                                 BLI_strncpy(simopts->filepath, G.ima, FILE_MAX);
1251                         }
1252                         BLI_path_abs(simopts->filepath, G.main->name);
1253                 }
1254
1255                 /* color management */
1256                 BKE_color_managed_display_settings_copy(&simopts->im_format.display_settings, &scene->display_settings);
1257                 BKE_color_managed_view_settings_copy(&simopts->im_format.view_settings, &scene->view_settings);
1258         }
1259
1260         ED_space_image_release_buffer(sima, ibuf, lock);
1261
1262         return (ibuf != NULL);
1263 }
1264
1265 static void save_image_options_from_op(SaveImageOptions *simopts, wmOperator *op)
1266 {
1267         if (op->customdata) {
1268                 BKE_color_managed_view_settings_free(&simopts->im_format.view_settings);
1269
1270                 simopts->im_format = *(ImageFormatData *)op->customdata;
1271         }
1272
1273         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
1274                 RNA_string_get(op->ptr, "filepath", simopts->filepath);
1275                 BLI_path_abs(simopts->filepath, G.main->name);
1276         }
1277 }
1278
1279 static void save_image_options_to_op(SaveImageOptions *simopts, wmOperator *op)
1280 {
1281         if (op->customdata) {
1282                 BKE_color_managed_view_settings_free(&((ImageFormatData *)op->customdata)->view_settings);
1283
1284                 *(ImageFormatData *)op->customdata = simopts->im_format;
1285         }
1286
1287         RNA_string_set(op->ptr, "filepath", simopts->filepath);
1288 }
1289
1290 /* assumes name is FILE_MAX */
1291 /* ima->name and ibuf->name should end up the same */
1292 static void save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveImageOptions *simopts, int do_newpath)
1293 {
1294         Image *ima = ED_space_image(sima);
1295         void *lock;
1296         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
1297
1298         if (ibuf) {
1299                 ImBuf *colormanaged_ibuf;
1300                 const char *relbase = ID_BLEND_PATH(CTX_data_main(C), &ima->id);
1301                 const short relative = (RNA_struct_find_property(op->ptr, "relative_path") && RNA_boolean_get(op->ptr, "relative_path"));
1302                 const short save_copy = (RNA_struct_find_property(op->ptr, "copy") && RNA_boolean_get(op->ptr, "copy"));
1303                 const short save_as_render = (RNA_struct_find_property(op->ptr, "save_as_render") && RNA_boolean_get(op->ptr, "save_as_render"));
1304                 ImageFormatData *imf = &simopts->im_format;
1305                 short ok = FALSE;
1306
1307                 /* old global to ensure a 2nd save goes to same dir */
1308                 BLI_strncpy(G.ima, simopts->filepath, sizeof(G.ima));
1309
1310                 WM_cursor_wait(1);
1311
1312                 if (ima->type == IMA_TYPE_R_RESULT) {
1313                         /* enforce user setting for RGB or RGBA, but skip BW */
1314                         if (simopts->im_format.planes == R_IMF_PLANES_RGBA) {
1315                                 ibuf->planes = R_IMF_PLANES_RGBA;
1316                         }
1317                         else if (simopts->im_format.planes == R_IMF_PLANES_RGB) {
1318                                 ibuf->planes = R_IMF_PLANES_RGB;
1319                         }
1320                 }
1321                 else {
1322                         /* TODO, better solution, if a 24bit image is painted onto it may contain alpha */
1323                         if (ibuf->userflags & IB_BITMAPDIRTY) { /* it has been painted onto */
1324                                 /* checks each pixel, not ideal */
1325                                 ibuf->planes = BKE_imbuf_alpha_test(ibuf) ? 32 : 24;
1326                         }
1327                 }
1328
1329                 colormanaged_ibuf = IMB_colormanagement_imbuf_for_write(ibuf, save_as_render, TRUE, &imf->view_settings, &imf->display_settings, imf);
1330
1331                 if (simopts->im_format.imtype == R_IMF_IMTYPE_MULTILAYER) {
1332                         Scene *scene = CTX_data_scene(C);
1333                         RenderResult *rr = BKE_image_acquire_renderresult(scene, ima);
1334                         if (rr) {
1335                                 RE_WriteRenderResult(op->reports, rr, simopts->filepath, simopts->im_format.quality);
1336                                 ok = TRUE;
1337                         }
1338                         else {
1339                                 BKE_report(op->reports, RPT_ERROR, "Did not write, no Multilayer Image");
1340                         }
1341                         BKE_image_release_renderresult(scene, ima);
1342                 }
1343                 else {
1344                         if (BKE_imbuf_write_as(colormanaged_ibuf, simopts->filepath, &simopts->im_format, save_copy)) {
1345                                 ok = TRUE;
1346                         }
1347                 }
1348
1349                 if (ok) {
1350                         if (!save_copy) {
1351                                 if (do_newpath) {
1352                                         BLI_strncpy(ibuf->name, simopts->filepath, sizeof(ibuf->name));
1353                                         BLI_strncpy(ima->name, simopts->filepath, sizeof(ima->name));
1354                                 }
1355
1356                                 ibuf->userflags &= ~IB_BITMAPDIRTY;
1357
1358                                 /* change type? */
1359                                 if (ima->type == IMA_TYPE_R_RESULT) {
1360                                         ima->type = IMA_TYPE_IMAGE;
1361
1362                                         /* workaround to ensure the render result buffer is no longer used
1363                                          * by this image, otherwise can crash when a new render result is
1364                                          * created. */
1365                                         if (ibuf->rect && !(ibuf->mall & IB_rect))
1366                                                 imb_freerectImBuf(ibuf);
1367                                         if (ibuf->rect_float && !(ibuf->mall & IB_rectfloat))
1368                                                 imb_freerectfloatImBuf(ibuf);
1369                                         if (ibuf->zbuf && !(ibuf->mall & IB_zbuf))
1370                                                 IMB_freezbufImBuf(ibuf);
1371                                         if (ibuf->zbuf_float && !(ibuf->mall & IB_zbuffloat))
1372                                                 IMB_freezbuffloatImBuf(ibuf);
1373                                 }
1374                                 if (ELEM(ima->source, IMA_SRC_GENERATED, IMA_SRC_VIEWER)) {
1375                                         ima->source = IMA_SRC_FILE;
1376                                         ima->type = IMA_TYPE_IMAGE;
1377                                 }
1378
1379                                 /* only image path, never ibuf */
1380                                 if (relative) {
1381                                         BLI_path_rel(ima->name, relbase); /* only after saving */
1382                                 }
1383
1384                                 IMB_colormanagment_colorspace_from_ibuf_ftype(&ima->colorspace_settings, ibuf);
1385                         }
1386                 }
1387                 else {
1388                         BKE_reportf(op->reports, RPT_ERROR, "Could not write image %s", simopts->filepath);
1389                 }
1390
1391
1392                 WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
1393
1394                 WM_cursor_wait(0);
1395
1396                 if (colormanaged_ibuf != ibuf)
1397                         IMB_freeImBuf(colormanaged_ibuf);
1398         }
1399
1400         ED_space_image_release_buffer(sima, ibuf, lock);
1401 }
1402
1403 static void image_save_as_free(wmOperator *op)
1404 {
1405         if (op->customdata) {
1406                 ImageFormatData *im_format = (ImageFormatData *)op->customdata;
1407                 BKE_color_managed_view_settings_free(&im_format->view_settings);
1408
1409                 MEM_freeN(op->customdata);
1410                 op->customdata = NULL;
1411         }
1412 }
1413
1414 static int image_save_as_exec(bContext *C, wmOperator *op)
1415 {
1416         SpaceImage *sima = CTX_wm_space_image(C);
1417         SaveImageOptions simopts;
1418
1419         save_image_options_defaults(&simopts);
1420
1421         /* just in case to initialize values,
1422          * these should be set on invoke or by the caller. */
1423         save_image_options_init(&simopts, sima, CTX_data_scene(C), 0);
1424
1425         save_image_options_from_op(&simopts, op);
1426
1427         save_image_doit(C, sima, op, &simopts, TRUE);
1428
1429         image_save_as_free(op);
1430         return OPERATOR_FINISHED;
1431 }
1432
1433
1434 static int image_save_as_check(bContext *UNUSED(C), wmOperator *op)
1435 {
1436         ImageFormatData *imf = op->customdata;
1437         return WM_operator_filesel_ensure_ext_imtype(op, imf);
1438 }
1439
1440 static int image_save_as_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1441 {
1442         SpaceImage *sima = CTX_wm_space_image(C);
1443         Image *ima = ED_space_image(sima);
1444         Scene *scene = CTX_data_scene(C);
1445         SaveImageOptions simopts;
1446
1447         if (RNA_struct_property_is_set(op->ptr, "filepath"))
1448                 return image_save_as_exec(C, op);
1449
1450         save_image_options_defaults(&simopts);
1451
1452         if (save_image_options_init(&simopts, sima, scene, TRUE) == 0)
1453                 return OPERATOR_CANCELLED;
1454         save_image_options_to_op(&simopts, op);
1455
1456         /* enable save_copy by default for render results */
1457         if (ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE) && !RNA_struct_property_is_set(op->ptr, "copy")) {
1458                 RNA_boolean_set(op->ptr, "copy", TRUE);
1459         }
1460
1461         if (ima->source == IMA_SRC_VIEWER || (ima->flag & IMA_VIEW_AS_RENDER))
1462                 RNA_boolean_set(op->ptr, "save_as_render", TRUE);
1463         else
1464                 RNA_boolean_set(op->ptr, "save_as_render", FALSE);
1465
1466         op->customdata = MEM_mallocN(sizeof(simopts.im_format), __func__);
1467         memcpy(op->customdata, &simopts.im_format, sizeof(simopts.im_format));
1468
1469         image_filesel(C, op, simopts.filepath);
1470
1471         return OPERATOR_RUNNING_MODAL;
1472 }
1473
1474 static int image_save_as_cancel(bContext *UNUSED(C), wmOperator *op)
1475 {
1476         image_save_as_free(op);
1477
1478         return OPERATOR_CANCELLED;
1479 }
1480
1481 static int image_save_as_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop)
1482 {
1483         const char *prop_id = RNA_property_identifier(prop);
1484
1485         return !(strcmp(prop_id, "filepath") == 0 ||
1486                  strcmp(prop_id, "directory") == 0 ||
1487                  strcmp(prop_id, "filename") == 0 ||
1488                  /* when saving a copy, relative path has no effect */
1489                  ((strcmp(prop_id, "relative_path") == 0) && RNA_boolean_get(ptr, "copy"))
1490                  );
1491 }
1492
1493 static void image_save_as_draw(bContext *UNUSED(C), wmOperator *op)
1494 {
1495         uiLayout *layout = op->layout;
1496         ImageFormatData *imf = op->customdata;
1497         PointerRNA ptr;
1498
1499         /* image template */
1500         RNA_pointer_create(NULL, &RNA_ImageFormatSettings, imf, &ptr);
1501         uiTemplateImageSettings(layout, &ptr, FALSE);
1502
1503         /* main draw call */
1504         RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);
1505         uiDefAutoButsRNA(layout, &ptr, image_save_as_draw_check_prop, '\0');
1506 }
1507
1508 static int image_save_as_poll(bContext *C)
1509 {
1510         if (space_image_buffer_exists_poll(C)) {
1511                 if (G.is_rendering) {
1512                         /* no need to NULL check here */
1513                         SpaceImage *sima = CTX_wm_space_image(C);
1514                         Image *ima = ED_space_image(sima);
1515
1516                         if (ima->source == IMA_SRC_VIEWER) {
1517                                 CTX_wm_operator_poll_msg_set(C, "can't save image while rendering");
1518                                 return FALSE;
1519                         }
1520                 }
1521                 return TRUE;
1522         }
1523         return FALSE;
1524 }
1525
1526 void IMAGE_OT_save_as(wmOperatorType *ot)
1527 {
1528 //      PropertyRNA *prop;
1529
1530         /* identifiers */
1531         ot->name = "Save As Image";
1532         ot->idname = "IMAGE_OT_save_as";
1533         ot->description = "Save the image with another name and/or settings";
1534         
1535         /* api callbacks */
1536         ot->exec = image_save_as_exec;
1537         ot->check = image_save_as_check;
1538         ot->invoke = image_save_as_invoke;
1539         ot->cancel = image_save_as_cancel;
1540         ot->ui = image_save_as_draw;
1541         ot->poll = image_save_as_poll;
1542
1543         /* flags */
1544         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1545
1546         /* properties */
1547         RNA_def_boolean(ot->srna, "save_as_render", 0, "Save As Render", "Apply render part of display transform when saving byte image");
1548         RNA_def_boolean(ot->srna, "copy", 0, "Copy", "Create a new image file without modifying the current image in blender");
1549
1550         WM_operator_properties_filesel(ot, FOLDERFILE | IMAGEFILE | MOVIEFILE, FILE_SPECIAL, FILE_SAVE,
1551                                        WM_FILESEL_FILEPATH | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY);
1552 }
1553
1554 /******************** save image operator ********************/
1555
1556 static int image_save_exec(bContext *C, wmOperator *op)
1557 {
1558         SpaceImage *sima = CTX_wm_space_image(C);
1559         Scene *scene = CTX_data_scene(C);
1560         SaveImageOptions simopts;
1561
1562         save_image_options_defaults(&simopts);
1563         if (save_image_options_init(&simopts, sima, scene, FALSE) == 0)
1564                 return OPERATOR_CANCELLED;
1565         save_image_options_from_op(&simopts, op);
1566
1567         if (BLI_exists(simopts.filepath) && BLI_file_is_writable(simopts.filepath)) {
1568                 save_image_doit(C, sima, op, &simopts, FALSE);
1569         }
1570         else {
1571                 BKE_reportf(op->reports, RPT_ERROR, "Cannot save image, path '%s' is not writable", simopts.filepath);
1572                 return OPERATOR_CANCELLED;
1573         }
1574
1575         return OPERATOR_FINISHED;
1576 }
1577
1578 void IMAGE_OT_save(wmOperatorType *ot)
1579 {
1580         /* identifiers */
1581         ot->name = "Save Image";
1582         ot->idname = "IMAGE_OT_save";
1583         ot->description = "Save the image with current name and settings";
1584         
1585         /* api callbacks */
1586         ot->exec = image_save_exec;
1587         ot->poll = space_image_file_exists_poll;
1588
1589         /* flags */
1590         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1591 }
1592
1593 /******************* save sequence operator ********************/
1594
1595 static int image_save_sequence_exec(bContext *C, wmOperator *op)
1596 {
1597         Main *bmain = CTX_data_main(C);
1598         SpaceImage *sima = CTX_wm_space_image(C);
1599         ImBuf *ibuf;
1600         int tot = 0;
1601         char di[FILE_MAX], fi[FILE_MAX];
1602         
1603         if (sima->image == NULL)
1604                 return OPERATOR_CANCELLED;
1605
1606         if (sima->image->source != IMA_SRC_SEQUENCE) {
1607                 BKE_report(op->reports, RPT_ERROR, "Can only save sequence on image sequences");
1608                 return OPERATOR_CANCELLED;
1609         }
1610
1611         if (sima->image->type == IMA_TYPE_MULTILAYER) {
1612                 BKE_report(op->reports, RPT_ERROR, "Cannot save multilayer sequences");
1613                 return OPERATOR_CANCELLED;
1614         }
1615         
1616         /* get total */
1617         for (ibuf = sima->image->ibufs.first; ibuf; ibuf = ibuf->next)
1618                 if (ibuf->userflags & IB_BITMAPDIRTY)
1619                         tot++;
1620         
1621         if (tot == 0) {
1622                 BKE_report(op->reports, RPT_WARNING, "No images have been changed");
1623                 return OPERATOR_CANCELLED;
1624         }
1625
1626         /* get a filename for menu */
1627         for (ibuf = sima->image->ibufs.first; ibuf; ibuf = ibuf->next)
1628                 if (ibuf->userflags & IB_BITMAPDIRTY)
1629                         break;
1630         
1631         BLI_strncpy(di, ibuf->name, FILE_MAX);
1632         BLI_splitdirstring(di, fi);
1633         
1634         BKE_reportf(op->reports, RPT_INFO, "%d image(s) will be saved in %s", tot, di);
1635
1636         for (ibuf = sima->image->ibufs.first; ibuf; ibuf = ibuf->next) {
1637                 if (ibuf->userflags & IB_BITMAPDIRTY) {
1638                         char name[FILE_MAX];
1639                         BLI_strncpy(name, ibuf->name, sizeof(name));
1640                         
1641                         BLI_path_abs(name, bmain->name);
1642
1643                         if (0 == IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat)) {
1644                                 BKE_reportf(op->reports, RPT_ERROR, "Could not write image %s", name);
1645                                 break;
1646                         }
1647
1648                         BKE_reportf(op->reports, RPT_INFO, "Saved %s", ibuf->name);
1649                         ibuf->userflags &= ~IB_BITMAPDIRTY;
1650                 }
1651         }
1652
1653         return OPERATOR_FINISHED;
1654 }
1655
1656 void IMAGE_OT_save_sequence(wmOperatorType *ot)
1657 {
1658         /* identifiers */
1659         ot->name = "Save Sequence";
1660         ot->idname = "IMAGE_OT_save_sequence";
1661         ot->description = "Save a sequence of images";
1662         
1663         /* api callbacks */
1664         ot->exec = image_save_sequence_exec;
1665         ot->poll = space_image_buffer_exists_poll;
1666
1667         /* flags */
1668         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1669 }
1670
1671 /******************** reload image operator ********************/
1672
1673 static int image_reload_exec(bContext *C, wmOperator *UNUSED(op))
1674 {
1675         Image *ima = CTX_data_edit_image(C);
1676         SpaceImage *sima = CTX_wm_space_image(C);
1677
1678         if (!ima)
1679                 return OPERATOR_CANCELLED;
1680
1681         /* XXX unpackImage frees image buffers */
1682         ED_preview_kill_jobs(C);
1683         
1684         // XXX other users?
1685         BKE_image_signal(ima, (sima) ? &sima->iuser : NULL, IMA_SIGNAL_RELOAD);
1686
1687         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1688         
1689         return OPERATOR_FINISHED;
1690 }
1691
1692 void IMAGE_OT_reload(wmOperatorType *ot)
1693 {
1694         /* identifiers */
1695         ot->name = "Reload Image";
1696         ot->idname = "IMAGE_OT_reload";
1697         ot->description = "Reload current image from disk";
1698         
1699         /* api callbacks */
1700         ot->exec = image_reload_exec;
1701
1702         /* flags */
1703         ot->flag = OPTYPE_REGISTER; /* no undo, image buffer is not handled by undo */
1704 }
1705
1706 /********************** new image operator *********************/
1707
1708 static int image_new_exec(bContext *C, wmOperator *op)
1709 {
1710         SpaceImage *sima;
1711         Scene *scene;
1712         Object *obedit;
1713         Image *ima;
1714         PointerRNA ptr, idptr;
1715         PropertyRNA *prop;
1716         char name[MAX_ID_NAME - 2];
1717         float color[4];
1718         int width, height, floatbuf, gen_type, alpha;
1719
1720         /* retrieve state */
1721         sima = CTX_wm_space_image(C);
1722         scene = CTX_data_scene(C);
1723         obedit = CTX_data_edit_object(C);
1724
1725         RNA_string_get(op->ptr, "name", name);
1726         width = RNA_int_get(op->ptr, "width");
1727         height = RNA_int_get(op->ptr, "height");
1728         floatbuf = RNA_boolean_get(op->ptr, "float");
1729         gen_type = RNA_enum_get(op->ptr, "generated_type");
1730         RNA_float_get_array(op->ptr, "color", color);
1731         alpha = RNA_boolean_get(op->ptr, "alpha");
1732         
1733         if (!floatbuf) {
1734                 /* OCIO_TODO: perhaps we need to convert to display space, not just to sRGB */
1735                 linearrgb_to_srgb_v3_v3(color, color);
1736         }
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_float_array_default(prop, default_color);
1805         RNA_def_boolean(ot->srna, "alpha", 1, "Alpha", "Create an image with an alpha channel");
1806         RNA_def_enum(ot->srna, "generated_type", image_generated_type_items, IMA_GENTYPE_BLANK,
1807                      "Generated Type", "Fill the image with a grid for UV map testing");
1808         RNA_def_boolean(ot->srna, "float", 0, "32 bit Float", "Create image with 32 bit floating point bit depth");
1809 }
1810
1811 /********************* invert operators *********************/
1812
1813 static int image_invert_poll(bContext *C)
1814 {
1815         Image *ima = CTX_data_edit_image(C);
1816
1817         return BKE_image_has_ibuf(ima, NULL);
1818 }
1819
1820 static int image_invert_exec(bContext *C, wmOperator *op)
1821 {
1822         Image *ima = CTX_data_edit_image(C);
1823         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
1824
1825         /* flags indicate if this channel should be inverted */
1826         const short r = RNA_boolean_get(op->ptr, "invert_r");
1827         const short g = RNA_boolean_get(op->ptr, "invert_g");
1828         const short b = RNA_boolean_get(op->ptr, "invert_b");
1829         const short a = RNA_boolean_get(op->ptr, "invert_a");
1830
1831         int i;
1832
1833         if (ibuf == NULL)  /* TODO: this should actually never happen, but does for render-results -> cleanup */
1834                 return OPERATOR_CANCELLED;
1835
1836         /* TODO: make this into an IMB_invert_channels(ibuf,r,g,b,a) method!? */
1837         if (ibuf->rect_float) {
1838                 
1839                 float *fp = (float *) ibuf->rect_float;
1840                 for (i = ibuf->x * ibuf->y; i > 0; i--, fp += 4) {
1841                         if (r) fp[0] = 1.0f - fp[0];
1842                         if (g) fp[1] = 1.0f - fp[1];
1843                         if (b) fp[2] = 1.0f - fp[2];
1844                         if (a) fp[3] = 1.0f - fp[3];
1845                 }
1846
1847                 if (ibuf->rect) {
1848                         IMB_rect_from_float(ibuf);
1849                 }
1850         }
1851         else if (ibuf->rect) {
1852                 
1853                 char *cp = (char *) ibuf->rect;
1854                 for (i = ibuf->x * ibuf->y; i > 0; i--, cp += 4) {
1855                         if (r) cp[0] = 255 - cp[0];
1856                         if (g) cp[1] = 255 - cp[1];
1857                         if (b) cp[2] = 255 - cp[2];
1858                         if (a) cp[3] = 255 - cp[3];
1859                 }
1860         }
1861         else {
1862                 BKE_image_release_ibuf(ima, ibuf, NULL);
1863                 return OPERATOR_CANCELLED;
1864         }
1865
1866         ibuf->userflags |= IB_BITMAPDIRTY;
1867         if (ibuf->mipmap[0])
1868                 ibuf->userflags |= IB_MIPMAP_INVALID;
1869
1870         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1871
1872         BKE_image_release_ibuf(ima, ibuf, NULL);
1873
1874         return OPERATOR_FINISHED;
1875 }
1876
1877 void IMAGE_OT_invert(wmOperatorType *ot)
1878 {
1879         /* identifiers */
1880         ot->name = "Invert Channels";
1881         ot->idname = "IMAGE_OT_invert";
1882         ot->description = "Invert image's channels";
1883         
1884         /* api callbacks */
1885         ot->exec = image_invert_exec;
1886         ot->poll = image_invert_poll;
1887         
1888         /* properties */
1889         RNA_def_boolean(ot->srna, "invert_r", 0, "Red", "Invert Red Channel");
1890         RNA_def_boolean(ot->srna, "invert_g", 0, "Green", "Invert Green Channel");
1891         RNA_def_boolean(ot->srna, "invert_b", 0, "Blue", "Invert Blue Channel");
1892         RNA_def_boolean(ot->srna, "invert_a", 0, "Alpha", "Invert Alpha Channel");
1893         
1894         /* flags */
1895         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1896 }
1897
1898 /********************* pack operator *********************/
1899
1900 static int image_pack_test(bContext *C, wmOperator *op)
1901 {
1902         Image *ima = CTX_data_edit_image(C);
1903         int as_png = RNA_boolean_get(op->ptr, "as_png");
1904
1905         if (!ima)
1906                 return 0;
1907         if (!as_png && ima->packedfile)
1908                 return 0;
1909
1910         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
1911                 BKE_report(op->reports, RPT_ERROR, "Packing movies or image sequences not supported");
1912                 return 0;
1913         }
1914
1915         return 1;
1916 }
1917
1918 static int image_pack_exec(bContext *C, wmOperator *op)
1919 {
1920         struct Main *bmain = CTX_data_main(C);
1921         Image *ima = CTX_data_edit_image(C);
1922         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
1923         int as_png = RNA_boolean_get(op->ptr, "as_png");
1924
1925         if (!image_pack_test(C, op))
1926                 return OPERATOR_CANCELLED;
1927         
1928         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1929                 BKE_report(op->reports, RPT_ERROR, "Cannot pack edited image from disk, only as internal PNG");
1930                 return OPERATOR_CANCELLED;
1931         }
1932
1933         if (as_png)
1934                 BKE_image_memorypack(ima);
1935         else
1936                 ima->packedfile = newPackedFile(op->reports, ima->name, ID_BLEND_PATH(bmain, &ima->id));
1937
1938         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1939
1940         BKE_image_release_ibuf(ima, ibuf, NULL);
1941
1942         return OPERATOR_FINISHED;
1943 }
1944
1945 static int image_pack_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1946 {
1947         Image *ima = CTX_data_edit_image(C);
1948         ImBuf *ibuf;
1949         uiPopupMenu *pup;
1950         uiLayout *layout;
1951         int as_png = RNA_boolean_get(op->ptr, "as_png");
1952
1953         if (!image_pack_test(C, op))
1954                 return OPERATOR_CANCELLED;
1955
1956         ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
1957
1958         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1959                 pup = uiPupMenuBegin(C, "OK", ICON_QUESTION);
1960                 layout = uiPupMenuLayout(pup);
1961                 uiItemBooleanO(layout, "Can't pack edited image from disk. Pack as internal PNG?", ICON_NONE, op->idname, "as_png", 1);
1962                 uiPupMenuEnd(C, pup);
1963
1964                 BKE_image_release_ibuf(ima, ibuf, NULL);
1965
1966                 return OPERATOR_CANCELLED;
1967         }
1968
1969         BKE_image_release_ibuf(ima, ibuf, NULL);
1970
1971         return image_pack_exec(C, op);
1972 }
1973
1974 void IMAGE_OT_pack(wmOperatorType *ot)
1975 {
1976         /* identifiers */
1977         ot->name = "Pack Image";
1978         ot->description = "Pack an image as embedded data into the .blend file"; 
1979         ot->idname = "IMAGE_OT_pack";
1980         
1981         /* api callbacks */
1982         ot->exec = image_pack_exec;
1983         ot->invoke = image_pack_invoke;
1984
1985         /* flags */
1986         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1987
1988         /* properties */
1989         RNA_def_boolean(ot->srna, "as_png", 0, "Pack As PNG", "Pack image as lossless PNG");
1990 }
1991
1992 /********************* unpack operator *********************/
1993
1994 static int image_unpack_exec(bContext *C, wmOperator *op)
1995 {
1996         Image *ima = CTX_data_edit_image(C);
1997         int method = RNA_enum_get(op->ptr, "method");
1998
1999         /* find the suppplied image by name */
2000         if (RNA_struct_property_is_set(op->ptr, "id")) {
2001                 char imaname[MAX_ID_NAME - 2];
2002                 RNA_string_get(op->ptr, "id", imaname);
2003                 ima = BLI_findstring(&CTX_data_main(C)->image, imaname, offsetof(ID, name) + 2);
2004                 if (!ima) ima = CTX_data_edit_image(C);
2005         }
2006         
2007         if (!ima || !ima->packedfile)
2008                 return OPERATOR_CANCELLED;
2009
2010         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
2011                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
2012                 return OPERATOR_CANCELLED;
2013         }
2014
2015         if (G.fileflags & G_AUTOPACK)
2016                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
2017         
2018         /* XXX unpackImage frees image buffers */
2019         ED_preview_kill_jobs(C);
2020         
2021         unpackImage(op->reports, ima, method);
2022         
2023         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
2024
2025         return OPERATOR_FINISHED;
2026 }
2027
2028 static int image_unpack_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2029 {
2030         Image *ima = CTX_data_edit_image(C);
2031
2032         if (RNA_struct_property_is_set(op->ptr, "id"))
2033                 return image_unpack_exec(C, op);
2034                 
2035         if (!ima || !ima->packedfile)
2036                 return OPERATOR_CANCELLED;
2037
2038         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
2039                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
2040                 return OPERATOR_CANCELLED;
2041         }
2042
2043         if (G.fileflags & G_AUTOPACK)
2044                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
2045
2046         unpack_menu(C, "IMAGE_OT_unpack", ima->id.name + 2, ima->name, "textures", ima->packedfile);
2047
2048         return OPERATOR_FINISHED;
2049 }
2050
2051 void IMAGE_OT_unpack(wmOperatorType *ot)
2052 {
2053         /* identifiers */
2054         ot->name = "Unpack Image";
2055         ot->description = "Save an image packed in the .blend file to disk"; 
2056         ot->idname = "IMAGE_OT_unpack";
2057         
2058         /* api callbacks */
2059         ot->exec = image_unpack_exec;
2060         ot->invoke = image_unpack_invoke;
2061
2062         /* flags */
2063         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2064         
2065         /* properties */
2066         RNA_def_enum(ot->srna, "method", unpack_method_items, PF_USE_LOCAL, "Method", "How to unpack");
2067         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 */
2068 }
2069
2070 /******************** sample image operator ********************/
2071
2072 typedef struct ImageSampleInfo {
2073         ARegionType *art;
2074         void *draw_handle;
2075         int x, y;
2076         int channels;
2077
2078         unsigned char col[4];
2079         float colf[4];
2080         int z;
2081         float zf;
2082
2083         unsigned char *colp;
2084         float *colfp;
2085         int *zp;
2086         float *zfp;
2087
2088         int draw;
2089         int color_manage;
2090         int use_default_view;
2091 } ImageSampleInfo;
2092
2093 static void image_sample_draw(const bContext *C, ARegion *ar, void *arg_info)
2094 {
2095         ImageSampleInfo *info = arg_info;
2096         if (info->draw) {
2097                 Scene *scene = CTX_data_scene(C);
2098
2099                 ED_image_draw_info(scene, ar, info->color_manage, info->use_default_view, info->channels,
2100                                    info->x, info->y, info->colp, info->colfp, info->zp, info->zfp);
2101         }
2102 }
2103
2104 /* returns color in SRGB */
2105 /* matching ED_space_node_color_sample() */
2106 int ED_space_image_color_sample(SpaceImage *sima, ARegion *ar, int mval[2], float r_col[3])
2107 {
2108         void *lock;
2109         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2110         float fx, fy;
2111         int ret = FALSE;
2112
2113         if (ibuf == NULL) {
2114                 ED_space_image_release_buffer(sima, ibuf, lock);
2115                 return FALSE;
2116         }
2117
2118         UI_view2d_region_to_view(&ar->v2d, mval[0], mval[1], &fx, &fy);
2119
2120         if (fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) {
2121                 float *fp;
2122                 unsigned char *cp;
2123                 int x = (int)(fx * ibuf->x), y = (int)(fy * ibuf->y);
2124
2125                 CLAMP(x, 0, ibuf->x - 1);
2126                 CLAMP(y, 0, ibuf->y - 1);
2127
2128                 if (ibuf->rect_float) {
2129                         fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
2130                         linearrgb_to_srgb_v3_v3(r_col, fp);
2131                         ret = TRUE;
2132                 }
2133                 else if (ibuf->rect) {
2134                         cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
2135                         rgb_uchar_to_float(r_col, cp);
2136                         ret = TRUE;
2137                 }
2138         }
2139
2140         ED_space_image_release_buffer(sima, ibuf, lock);
2141         return ret;
2142 }
2143
2144 static void image_sample_apply(bContext *C, wmOperator *op, wmEvent *event)
2145 {
2146         SpaceImage *sima = CTX_wm_space_image(C);
2147         ARegion *ar = CTX_wm_region(C);
2148         void *lock;
2149         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2150         ImageSampleInfo *info = op->customdata;
2151         float fx, fy;
2152         Scene *scene = CTX_data_scene(C);
2153         CurveMapping *curve_mapping = scene->view_settings.curve_mapping;
2154
2155         if (ibuf == NULL) {
2156                 ED_space_image_release_buffer(sima, ibuf, lock);
2157                 info->draw = 0;
2158                 return;
2159         }
2160
2161         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &fx, &fy);
2162
2163         if (fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) {
2164                 float *fp;
2165                 unsigned char *cp;
2166                 int x = (int)(fx * ibuf->x), y = (int)(fy * ibuf->y);
2167                 Image *image = ED_space_image(sima);
2168
2169                 CLAMP(x, 0, ibuf->x - 1);
2170                 CLAMP(y, 0, ibuf->y - 1);
2171
2172                 info->x = x;
2173                 info->y = y;
2174                 info->draw = 1;
2175                 info->channels = ibuf->channels;
2176
2177                 info->colp = NULL;
2178                 info->colfp = NULL;
2179                 info->zp = NULL;
2180                 info->zfp = NULL;
2181
2182                 info->use_default_view = (image->flag & IMA_VIEW_AS_RENDER) ? FALSE : TRUE;
2183
2184                 if (ibuf->rect) {
2185                         cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
2186
2187                         info->col[0] = cp[0];
2188                         info->col[1] = cp[1];
2189                         info->col[2] = cp[2];
2190                         info->col[3] = cp[3];
2191                         info->colp = info->col;
2192
2193                         info->colf[0] = (float)cp[0] / 255.0f;
2194                         info->colf[1] = (float)cp[1] / 255.0f;
2195                         info->colf[2] = (float)cp[2] / 255.0f;
2196                         info->colf[3] = (float)cp[3] / 255.0f;
2197                         info->colfp = info->colf;
2198
2199                         info->color_manage = FALSE;
2200                 }
2201                 if (ibuf->rect_float) {
2202                         fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
2203
2204                         info->colf[0] = fp[0];
2205                         info->colf[1] = fp[1];
2206                         info->colf[2] = fp[2];
2207                         info->colf[3] = fp[3];
2208                         info->colfp = info->colf;
2209
2210                         info->color_manage = TRUE;
2211                 }
2212
2213                 if (ibuf->zbuf) {
2214                         info->z = ibuf->zbuf[y * ibuf->x + x];
2215                         info->zp = &info->z;
2216                 }
2217                 if (ibuf->zbuf_float) {
2218                         info->zf = ibuf->zbuf_float[y * ibuf->x + x];
2219                         info->zfp = &info->zf;
2220                 }
2221
2222                 if (curve_mapping && ibuf->channels == 4) {
2223                         /* we reuse this callback for set curves point operators */
2224                         if (RNA_struct_find_property(op->ptr, "point")) {
2225                                 int point = RNA_enum_get(op->ptr, "point");
2226
2227                                 if (point == 1) {
2228                                         curvemapping_set_black_white(curve_mapping, NULL, info->colfp);
2229                                 }
2230                                 else if (point == 0) {
2231                                         curvemapping_set_black_white(curve_mapping, info->colfp, NULL);
2232                                 }
2233                         }
2234                 }
2235
2236                 // XXX node curve integration ..
2237 #if 0
2238                 {
2239                         ScrArea *sa, *cur = curarea;
2240                         
2241                         node_curvemap_sample(fp);   /* sends global to node editor */
2242                         for (sa = G.curscreen->areabase.first; sa; sa = sa->next) {
2243                                 if (sa->spacetype == SPACE_NODE) {
2244                                         areawinset(sa->win);
2245                                         scrarea_do_windraw(sa);
2246                                 }
2247                         }
2248                         node_curvemap_sample(NULL);     /* clears global in node editor */
2249                         curarea = cur;
2250                 }
2251 #endif
2252         }
2253         else {
2254                 info->draw = 0;
2255         }
2256
2257         ED_space_image_release_buffer(sima, ibuf, lock);
2258         ED_area_tag_redraw(CTX_wm_area(C));
2259 }
2260
2261 static void image_sample_exit(bContext *C, wmOperator *op)
2262 {
2263         ImageSampleInfo *info = op->customdata;
2264
2265         ED_region_draw_cb_exit(info->art, info->draw_handle);
2266         ED_area_tag_redraw(CTX_wm_area(C));
2267         MEM_freeN(info);
2268 }
2269
2270 static int image_sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
2271 {
2272         SpaceImage *sima = CTX_wm_space_image(C);
2273         ARegion *ar = CTX_wm_region(C);
2274         ImageSampleInfo *info;
2275
2276         if (!ED_space_image_has_buffer(sima))
2277                 return OPERATOR_CANCELLED;
2278         
2279         info = MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
2280         info->art = ar->type;
2281         info->draw_handle = ED_region_draw_cb_activate(ar->type, image_sample_draw, info, REGION_DRAW_POST_PIXEL);
2282         op->customdata = info;
2283
2284         image_sample_apply(C, op, event);
2285
2286         WM_event_add_modal_handler(C, op);
2287
2288         return OPERATOR_RUNNING_MODAL;
2289 }
2290
2291 static int image_sample_modal(bContext *C, wmOperator *op, wmEvent *event)
2292 {
2293         switch (event->type) {
2294                 case LEFTMOUSE:
2295                 case RIGHTMOUSE: // XXX hardcoded
2296                         image_sample_exit(C, op);
2297                         return OPERATOR_CANCELLED;
2298                 case MOUSEMOVE:
2299                         image_sample_apply(C, op, event);
2300                         break;
2301         }
2302
2303         return OPERATOR_RUNNING_MODAL;
2304 }
2305
2306 static int image_sample_cancel(bContext *C, wmOperator *op)
2307 {
2308         image_sample_exit(C, op);
2309         return OPERATOR_CANCELLED;
2310 }
2311
2312 void IMAGE_OT_sample(wmOperatorType *ot)
2313 {
2314         /* identifiers */
2315         ot->name = "Sample Color";
2316         ot->idname = "IMAGE_OT_sample";
2317         ot->description = "Use mouse to sample a color in current image";
2318         
2319         /* api callbacks */
2320         ot->invoke = image_sample_invoke;
2321         ot->modal = image_sample_modal;
2322         ot->cancel = image_sample_cancel;
2323         ot->poll = image_sample_poll;
2324
2325         /* flags */
2326         ot->flag = OPTYPE_BLOCKING;
2327 }
2328
2329 /******************** sample line operator ********************/
2330 static int image_sample_line_exec(bContext *C, wmOperator *op)
2331 {
2332         SpaceImage *sima = CTX_wm_space_image(C);
2333         ARegion *ar = CTX_wm_region(C);
2334         Scene *scene = CTX_data_scene(C);
2335
2336         int x_start = RNA_int_get(op->ptr, "xstart");
2337         int y_start = RNA_int_get(op->ptr, "ystart");
2338         int x_end = RNA_int_get(op->ptr, "xend");
2339         int y_end = RNA_int_get(op->ptr, "yend");
2340         
2341         void *lock;
2342         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2343         Histogram *hist = &sima->sample_line_hist;
2344         
2345         float x1f, y1f, x2f, y2f;
2346         
2347         if (ibuf == NULL) {
2348                 ED_space_image_release_buffer(sima, ibuf, lock);
2349                 return OPERATOR_CANCELLED;
2350         }
2351         /* hmmmm */
2352         if (ibuf->channels < 3) {
2353                 ED_space_image_release_buffer(sima, ibuf, lock);
2354                 return OPERATOR_CANCELLED;
2355         }
2356         
2357         UI_view2d_region_to_view(&ar->v2d, x_start, y_start, &x1f, &y1f);
2358         UI_view2d_region_to_view(&ar->v2d, x_end, y_end, &x2f, &y2f);
2359
2360         hist->co[0][0] = x1f;
2361         hist->co[0][1] = y1f;
2362         hist->co[1][0] = x2f;
2363         hist->co[1][1] = y2f;
2364
2365         BKE_histogram_update_sample_line(hist, ibuf, &scene->view_settings, &scene->display_settings);
2366         
2367         /* reset y zoom */
2368         hist->ymax = 1.0f;
2369
2370         ED_space_image_release_buffer(sima, ibuf, lock);
2371         
2372         ED_area_tag_redraw(CTX_wm_area(C));
2373         
2374         return OPERATOR_FINISHED;
2375 }
2376
2377 static int image_sample_line_invoke(bContext *C, wmOperator *op, wmEvent *event)
2378 {
2379         SpaceImage *sima = CTX_wm_space_image(C);
2380
2381         Histogram *hist = &sima->sample_line_hist;
2382         hist->flag &= ~HISTO_FLAG_SAMPLELINE;
2383
2384         if (!ED_space_image_has_buffer(sima))
2385                 return OPERATOR_CANCELLED;
2386         
2387         return WM_gesture_straightline_invoke(C, op, event);
2388 }
2389
2390 void IMAGE_OT_sample_line(wmOperatorType *ot)
2391 {
2392         /* identifiers */
2393         ot->name = "Sample Line";
2394         ot->idname = "IMAGE_OT_sample_line";
2395         ot->description = "Sample a line and show it in Scope panels";
2396         
2397         /* api callbacks */
2398         ot->invoke = image_sample_line_invoke;
2399         ot->modal = WM_gesture_straightline_modal;
2400         ot->exec = image_sample_line_exec;
2401         ot->poll = space_image_main_area_poll;
2402         ot->cancel = WM_gesture_straightline_cancel;
2403         
2404         /* flags */
2405         ot->flag = 0; /* no undo/register since this operates on the space */
2406         
2407         WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT);
2408 }
2409
2410 /******************** set curve point operator ********************/
2411
2412 void IMAGE_OT_curves_point_set(wmOperatorType *ot)
2413 {
2414         static EnumPropertyItem point_items[] = {
2415                 {0, "BLACK_POINT", 0, "Black Point", ""},
2416                 {1, "WHITE_POINT", 0, "White Point", ""},
2417                 {0, NULL, 0, NULL, NULL}
2418         };
2419
2420         /* identifiers */
2421         ot->name = "Set Curves Point";
2422         ot->idname = "IMAGE_OT_curves_point_set";
2423         ot->description = "Set black point or white point for curves";
2424
2425         /* flags */
2426         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2427         
2428         /* api callbacks */
2429         ot->invoke = image_sample_invoke;
2430         ot->modal = image_sample_modal;
2431         ot->cancel = image_sample_cancel;
2432         ot->poll = space_image_main_area_not_uv_brush_poll;
2433
2434         /* properties */
2435         RNA_def_enum(ot->srna, "point", point_items, 0, "Point", "Set black point or white point for curves");
2436 }
2437
2438 /******************** record composite operator *********************/
2439
2440 typedef struct RecordCompositeData {
2441         wmTimer *timer;
2442         int old_cfra;
2443         int sfra, efra;
2444 } RecordCompositeData;
2445
2446 static int image_record_composite_apply(bContext *C, wmOperator *op)
2447 {
2448         SpaceImage *sima = CTX_wm_space_image(C);
2449         RecordCompositeData *rcd = op->customdata;
2450         Scene *scene = CTX_data_scene(C);
2451         ImBuf *ibuf;
2452         
2453         WM_cursor_time(CTX_wm_window(C), scene->r.cfra);
2454
2455         // XXX scene->nodetree->test_break = blender_test_break;
2456         // XXX scene->nodetree->test_break = NULL;
2457         
2458         BKE_image_all_free_anim_ibufs(scene->r.cfra);
2459         ntreeCompositTagAnimated(scene->nodetree);
2460         ntreeCompositExecTree(scene->nodetree, &scene->r, 0, scene->r.cfra != rcd->old_cfra,
2461                               &scene->view_settings, &scene->display_settings);  /* 1 is no previews */
2462
2463         ED_area_tag_redraw(CTX_wm_area(C));
2464         
2465         ibuf = BKE_image_acquire_ibuf(sima->image, &sima->iuser, NULL);
2466         /* save memory in flipbooks */
2467         if (ibuf)
2468                 imb_freerectfloatImBuf(ibuf);
2469
2470         BKE_image_release_ibuf(sima->image, ibuf, NULL);
2471
2472         scene->r.cfra++;
2473
2474         return (scene->r.cfra <= rcd->efra);
2475 }
2476
2477 static int image_record_composite_init(bContext *C, wmOperator *op)
2478 {
2479         SpaceImage *sima = CTX_wm_space_image(C);
2480         Scene *scene = CTX_data_scene(C);
2481         RecordCompositeData *rcd;
2482
2483         if (sima->iuser.frames < 2)
2484                 return 0;
2485         if (scene->nodetree == NULL)
2486                 return 0;
2487         
2488         op->customdata = rcd = MEM_callocN(sizeof(RecordCompositeData), "ImageRecordCompositeData");
2489
2490         rcd->old_cfra = scene->r.cfra;
2491         rcd->sfra = sima->iuser.sfra;
2492         rcd->efra = sima->iuser.sfra + sima->iuser.frames - 1;
2493         scene->r.cfra = rcd->sfra;
2494
2495         return 1;
2496 }
2497
2498 static void image_record_composite_exit(bContext *C, wmOperator *op)
2499 {
2500         Scene *scene = CTX_data_scene(C);
2501         SpaceImage *sima = CTX_wm_space_image(C);
2502         RecordCompositeData *rcd = op->customdata;
2503
2504         scene->r.cfra = rcd->old_cfra;
2505
2506         WM_cursor_restore(CTX_wm_window(C));
2507
2508         if (rcd->timer)
2509                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rcd->timer);
2510
2511         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
2512
2513         // XXX play_anim(0);
2514         // XXX allqueue(REDRAWNODE, 1);
2515
2516         MEM_freeN(rcd);
2517 }
2518
2519 static int image_record_composite_exec(bContext *C, wmOperator *op)
2520 {
2521         if (!image_record_composite_init(C, op))
2522                 return OPERATOR_CANCELLED;
2523         
2524         while (image_record_composite_apply(C, op)) {}
2525         
2526         image_record_composite_exit(C, op);
2527         
2528         return OPERATOR_FINISHED;
2529 }
2530
2531 static int image_record_composite_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2532 {
2533         RecordCompositeData *rcd;
2534         
2535         if (!image_record_composite_init(C, op))
2536                 return OPERATOR_CANCELLED;
2537
2538         rcd = op->customdata;
2539         rcd->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.0f);
2540         WM_event_add_modal_handler(C, op);
2541
2542         if (!image_record_composite_apply(C, op))
2543                 return OPERATOR_FINISHED;
2544
2545         return OPERATOR_RUNNING_MODAL;
2546 }
2547
2548 static int image_record_composite_modal(bContext *C, wmOperator *op, wmEvent *event)
2549 {
2550         RecordCompositeData *rcd = op->customdata;
2551
2552         switch (event->type) {
2553                 case TIMER:
2554                         if (rcd->timer == event->customdata) {
2555                                 if (!image_record_composite_apply(C, op)) {
2556                                         image_record_composite_exit(C, op);
2557                                         return OPERATOR_FINISHED;
2558                                 }
2559                         }
2560                         break;
2561                 case ESCKEY:
2562                         image_record_composite_exit(C, op);
2563                         return OPERATOR_FINISHED;
2564         }
2565
2566         return OPERATOR_RUNNING_MODAL;
2567 }
2568
2569 static int image_record_composite_cancel(bContext *C, wmOperator *op)
2570 {
2571         image_record_composite_exit(C, op);
2572         return OPERATOR_CANCELLED;
2573 }
2574
2575 void IMAGE_OT_record_composite(wmOperatorType *ot)
2576 {
2577         /* identifiers */
2578         ot->name = "Record Composite";
2579         ot->idname = "IMAGE_OT_record_composite";
2580         
2581         /* api callbacks */
2582         ot->exec = image_record_composite_exec;
2583         ot->invoke = image_record_composite_invoke;
2584         ot->modal = image_record_composite_modal;
2585         ot->cancel = image_record_composite_cancel;
2586         ot->poll = space_image_buffer_exists_poll;
2587 }
2588
2589 /********************* cycle render slot operator *********************/
2590
2591 static int image_cycle_render_slot_poll(bContext *C)
2592 {
2593         Image *ima = CTX_data_edit_image(C);
2594
2595         return (ima && ima->type == IMA_TYPE_R_RESULT);
2596 }
2597
2598 static int image_cycle_render_slot_exec(bContext *C, wmOperator *op)
2599 {
2600         Image *ima = CTX_data_edit_image(C);
2601         int a, slot, cur = ima->render_slot;
2602         const short use_reverse = RNA_boolean_get(op->ptr, "reverse");
2603
2604         for (a = 1; a < IMA_MAX_RENDER_SLOT; a++) {
2605                 slot = (cur + (use_reverse ? -a : a)) % IMA_MAX_RENDER_SLOT;
2606                 if (slot < 0) slot += IMA_MAX_RENDER_SLOT;
2607
2608                 if (ima->renders[slot] || slot == ima->last_render_slot) {
2609                         ima->render_slot = slot;
2610                         break;
2611                 }
2612         }
2613
2614         if (a == IMA_MAX_RENDER_SLOT)
2615                 ima->render_slot = ((cur == 1) ? 0 : 1);
2616         
2617         WM_event_add_notifier(C, NC_IMAGE | ND_DRAW, NULL);
2618
2619         /* no undo push for browsing existing */
2620         if (ima->renders[ima->render_slot] || ima->render_slot == ima->last_render_slot)
2621                 return OPERATOR_CANCELLED;
2622         
2623         return OPERATOR_FINISHED;
2624 }
2625
2626 void IMAGE_OT_cycle_render_slot(wmOperatorType *ot)
2627 {
2628         /* identifiers */
2629         ot->name = "Cycle Render Slot";
2630         ot->idname = "IMAGE_OT_cycle_render_slot";
2631         ot->description = "Cycle through all non-void render slots";
2632         
2633         /* api callbacks */
2634         ot->exec = image_cycle_render_slot_exec;
2635         ot->poll = image_cycle_render_slot_poll;
2636
2637         /* flags */
2638         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2639
2640         RNA_def_boolean(ot->srna, "reverse", 0, "Cycle in Reverse", "");
2641 }