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