Cleanup: use `rna_enum_` prefix for RNA enums
[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 <fcntl.h>
34 #include <stdlib.h>
35 #include <errno.h>
36 #ifndef WIN32
37 #  include <unistd.h>
38 #else
39 #  include <io.h>
40 #endif
41
42 #include "MEM_guardedalloc.h"
43
44 #include "BLI_math.h"
45 #include "BLI_blenlib.h"
46 #include "BLI_utildefines.h"
47 #include "BLI_string_utf8.h"
48
49 #include "BLT_translation.h"
50
51 #include "DNA_object_types.h"
52 #include "DNA_node_types.h"
53 #include "DNA_packedFile_types.h"
54 #include "DNA_scene_types.h"
55
56 #include "BKE_colortools.h"
57 #include "BKE_context.h"
58 #include "BKE_depsgraph.h"
59 #include "BKE_DerivedMesh.h"
60 #include "BKE_icons.h"
61 #include "BKE_image.h"
62 #include "BKE_global.h"
63 #include "BKE_library.h"
64 #include "BKE_main.h"
65 #include "BKE_packedFile.h"
66 #include "BKE_paint.h"
67 #include "BKE_report.h"
68 #include "BKE_screen.h"
69 #include "BKE_sound.h"
70 #include "BKE_scene.h"
71
72 #include "GPU_draw.h"
73 #include "GPU_buffers.h"
74
75 #include "IMB_colormanagement.h"
76 #include "IMB_imbuf.h"
77 #include "IMB_imbuf_types.h"
78 #include "IMB_moviecache.h"
79 #include "intern/openexr/openexr_multi.h"
80
81 #include "RE_pipeline.h"
82
83 #include "RNA_access.h"
84 #include "RNA_define.h"
85 #include "RNA_enum_types.h"
86
87 #include "ED_image.h"
88 #include "ED_mask.h"
89 #include "ED_paint.h"
90 #include "ED_render.h"
91 #include "ED_screen.h"
92 #include "ED_space_api.h"
93 #include "ED_uvedit.h"
94 #include "ED_util.h"
95
96 #include "UI_interface.h"
97 #include "UI_resources.h"
98 #include "UI_view2d.h"
99
100 #include "WM_api.h"
101 #include "WM_types.h"
102
103 #include "PIL_time.h"
104
105 #include "RE_engine.h"
106
107 #include "image_intern.h"
108
109 /******************** view navigation utilities *********************/
110
111 static void sima_zoom_set(SpaceImage *sima, ARegion *ar, float zoom, const float location[2])
112 {
113         float oldzoom = sima->zoom;
114         int width, height;
115
116         sima->zoom = zoom;
117
118         if (sima->zoom < 0.1f || sima->zoom > 4.0f) {
119                 /* check zoom limits */
120                 ED_space_image_get_size(sima, &width, &height);
121
122                 width *= sima->zoom;
123                 height *= sima->zoom;
124
125                 if ((width < 4) && (height < 4))
126                         sima->zoom = oldzoom;
127                 else if (BLI_rcti_size_x(&ar->winrct) <= sima->zoom)
128                         sima->zoom = oldzoom;
129                 else if (BLI_rcti_size_y(&ar->winrct) <= sima->zoom)
130                         sima->zoom = oldzoom;
131         }
132
133         if ((U.uiflag & USER_ZOOM_TO_MOUSEPOS) && location) {
134                 float aspx, aspy, w, h;
135
136                 ED_space_image_get_size(sima, &width, &height);
137                 ED_space_image_get_aspect(sima, &aspx, &aspy);
138
139                 w = width * aspx;
140                 h = height * aspy;
141
142                 sima->xof += ((location[0] - 0.5f) * w - sima->xof) * (sima->zoom - oldzoom) / sima->zoom;
143                 sima->yof += ((location[1] - 0.5f) * h - sima->yof) * (sima->zoom - oldzoom) / sima->zoom;
144         }
145 }
146
147 static void sima_zoom_set_factor(SpaceImage *sima, ARegion *ar, float zoomfac, const float location[2])
148 {
149         sima_zoom_set(sima, ar, sima->zoom * zoomfac, location);
150 }
151
152 #if 0 // currently unused
153 static int image_poll(bContext *C)
154 {
155         return (CTX_data_edit_image(C) != NULL);
156 }
157 #endif
158
159 static int space_image_buffer_exists_poll(bContext *C)
160 {
161         SpaceImage *sima = CTX_wm_space_image(C);
162         if (sima && ED_space_image_has_buffer(sima)) {
163                 return true;
164         }
165         return false;
166 }
167
168 static int image_not_packed_poll(bContext *C)
169 {
170         SpaceImage *sima = CTX_wm_space_image(C);
171
172         /* Do not run 'replace' on packed images, it does not give user expected results at all. */
173         if (sima && sima->image && BLI_listbase_is_empty(&sima->image->packedfiles)) {
174                 return true;
175         }
176         return false;
177 }
178
179 static bool imbuf_format_writeable(const ImBuf *ibuf)
180 {
181         ImageFormatData im_format;
182         ImbFormatOptions options_dummy;
183         BKE_imbuf_to_image_format(&im_format, ibuf);
184         return (BKE_image_imtype_to_ftype(im_format.imtype, &options_dummy) == ibuf->ftype);
185 }
186
187 static int space_image_file_exists_poll(bContext *C)
188 {
189         if (space_image_buffer_exists_poll(C)) {
190                 Main *bmain = CTX_data_main(C);
191                 SpaceImage *sima = CTX_wm_space_image(C);
192                 ImBuf *ibuf;
193                 void *lock;
194                 bool ret = false;
195                 char name[FILE_MAX];
196
197                 ibuf = ED_space_image_acquire_buffer(sima, &lock);
198                 if (ibuf) {
199                         BLI_strncpy(name, ibuf->name, FILE_MAX);
200                         BLI_path_abs(name, bmain->name);
201
202                         if (BLI_exists(name) == false) {
203                                 CTX_wm_operator_poll_msg_set(C, "image file not found");
204                         }
205                         else if (!BLI_file_is_writable(name)) {
206                                 CTX_wm_operator_poll_msg_set(C, "image path can't be written to");
207                         }
208                         else if (!imbuf_format_writeable(ibuf)) {
209                                 CTX_wm_operator_poll_msg_set(C, "image format is read-only");
210                         }
211                         else {
212                                 ret = true;
213                         }
214                 }
215                 ED_space_image_release_buffer(sima, ibuf, lock);
216
217                 return ret;
218         }
219         return false;
220 }
221
222 #if 0  /* UNUSED */
223 static int space_image_poll(bContext *C)
224 {
225         SpaceImage *sima = CTX_wm_space_image(C);
226         if (sima && sima->image) {
227                 return true;
228         }
229         return false;
230 }
231 #endif
232
233 int space_image_main_area_poll(bContext *C)
234 {
235         SpaceImage *sima = CTX_wm_space_image(C);
236         /* XXX ARegion *ar = CTX_wm_region(C); */
237
238         if (sima) {
239                 return true;  /* XXX (ar && ar->type->regionid == RGN_TYPE_WINDOW); */
240         }
241         return false;
242 }
243
244 /* For IMAGE_OT_curves_point_set to avoid sampling when in uv smooth mode or editmode */
245 static int space_image_main_area_not_uv_brush_poll(bContext *C)
246 {
247         SpaceImage *sima = CTX_wm_space_image(C);
248         Scene *scene = CTX_data_scene(C);
249         ToolSettings *toolsettings = scene->toolsettings;
250
251         if (sima && !toolsettings->uvsculpt && !scene->obedit)
252                 return 1;
253
254         return 0;
255 }
256
257 static int image_sample_poll(bContext *C)
258 {
259         SpaceImage *sima = CTX_wm_space_image(C);
260         if (sima) {
261                 Scene *scene = CTX_data_scene(C);
262                 Object *obedit = CTX_data_edit_object(C);
263                 ToolSettings *toolsettings = scene->toolsettings;
264
265                 if (obedit) {
266                         if (ED_space_image_show_uvedit(sima, obedit) && (toolsettings->use_uv_sculpt))
267                                 return false;
268                 }
269                 else if (sima->mode != SI_MODE_VIEW) {
270                         return false;
271                 }
272
273                 return space_image_main_area_poll(C);
274         }
275         else {
276                 return false;
277         }
278 }
279 /********************** view pan operator *********************/
280
281 typedef struct ViewPanData {
282         float x, y;
283         float xof, yof;
284         int event_type;
285 } ViewPanData;
286
287 static void image_view_pan_init(bContext *C, wmOperator *op, const wmEvent *event)
288 {
289         SpaceImage *sima = CTX_wm_space_image(C);
290         ViewPanData *vpd;
291
292         op->customdata = vpd = MEM_callocN(sizeof(ViewPanData), "ImageViewPanData");
293         WM_cursor_modal_set(CTX_wm_window(C), BC_NSEW_SCROLLCURSOR);
294
295         vpd->x = event->x;
296         vpd->y = event->y;
297         vpd->xof = sima->xof;
298         vpd->yof = sima->yof;
299         vpd->event_type = event->type;
300
301         WM_event_add_modal_handler(C, op);
302 }
303
304 static void image_view_pan_exit(bContext *C, wmOperator *op, bool cancel)
305 {
306         SpaceImage *sima = CTX_wm_space_image(C);
307         ViewPanData *vpd = op->customdata;
308
309         if (cancel) {
310                 sima->xof = vpd->xof;
311                 sima->yof = vpd->yof;
312                 ED_region_tag_redraw(CTX_wm_region(C));
313         }
314
315         WM_cursor_modal_restore(CTX_wm_window(C));
316         MEM_freeN(op->customdata);
317 }
318
319 static int image_view_pan_exec(bContext *C, wmOperator *op)
320 {
321         SpaceImage *sima = CTX_wm_space_image(C);
322         float offset[2];
323
324         RNA_float_get_array(op->ptr, "offset", offset);
325         sima->xof += offset[0];
326         sima->yof += offset[1];
327
328         ED_region_tag_redraw(CTX_wm_region(C));
329
330         /* XXX notifier? */
331 #if 0
332         if (image_preview_active(curarea, NULL, NULL)) {
333                 /* recalculates new preview rect */
334                 scrarea_do_windraw(curarea);
335                 image_preview_event(2);
336         }
337 #endif
338         
339         return OPERATOR_FINISHED;
340 }
341
342 static int image_view_pan_invoke(bContext *C, wmOperator *op, const wmEvent *event)
343 {
344         if (event->type == MOUSEPAN) {
345                 SpaceImage *sima = CTX_wm_space_image(C);
346                 float offset[2];
347                 
348                 offset[0] = (event->prevx - event->x) / sima->zoom;
349                 offset[1] = (event->prevy - event->y) / sima->zoom;
350                 RNA_float_set_array(op->ptr, "offset", offset);
351
352                 image_view_pan_exec(C, op);
353                 return OPERATOR_FINISHED;
354         }
355         else {
356                 image_view_pan_init(C, op, event);
357                 return OPERATOR_RUNNING_MODAL;
358         }
359 }
360
361 static int image_view_pan_modal(bContext *C, wmOperator *op, const wmEvent *event)
362 {
363         SpaceImage *sima = CTX_wm_space_image(C);
364         ViewPanData *vpd = op->customdata;
365         float offset[2];
366
367         switch (event->type) {
368                 case MOUSEMOVE:
369                         sima->xof = vpd->xof;
370                         sima->yof = vpd->yof;
371                         offset[0] = (vpd->x - event->x) / sima->zoom;
372                         offset[1] = (vpd->y - event->y) / sima->zoom;
373                         RNA_float_set_array(op->ptr, "offset", offset);
374                         image_view_pan_exec(C, op);
375                         break;
376                 default:
377                         if (event->type == vpd->event_type && event->val == KM_RELEASE) {
378                                 image_view_pan_exit(C, op, false);
379                                 return OPERATOR_FINISHED;
380                         }
381                         break;
382         }
383
384         return OPERATOR_RUNNING_MODAL;
385 }
386
387 static void image_view_pan_cancel(bContext *C, wmOperator *op)
388 {
389         image_view_pan_exit(C, op, true);
390 }
391
392 void IMAGE_OT_view_pan(wmOperatorType *ot)
393 {
394         /* identifiers */
395         ot->name = "View Pan";
396         ot->idname = "IMAGE_OT_view_pan";
397         ot->description = "Pan the view";
398         
399         /* api callbacks */
400         ot->exec = image_view_pan_exec;
401         ot->invoke = image_view_pan_invoke;
402         ot->modal = image_view_pan_modal;
403         ot->cancel = image_view_pan_cancel;
404         ot->poll = space_image_main_area_poll;
405
406         /* flags */
407         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR | OPTYPE_LOCK_BYPASS;
408         
409         /* properties */
410         RNA_def_float_vector(ot->srna, "offset", 2, NULL, -FLT_MAX, FLT_MAX,
411                              "Offset", "Offset in floating point units, 1.0 is the width and height of the image", -FLT_MAX, FLT_MAX);
412 }
413
414 /********************** view zoom operator *********************/
415
416 typedef struct ViewZoomData {
417         float origx, origy;
418         float zoom;
419         int event_type;
420         float location[2];
421
422         /* needed for continuous zoom */
423         wmTimer *timer;
424         double timer_lastdraw;
425
426         /* */
427         SpaceImage *sima;
428         ARegion *ar;
429 } ViewZoomData;
430
431 static void image_view_zoom_init(bContext *C, wmOperator *op, const wmEvent *event)
432 {
433         SpaceImage *sima = CTX_wm_space_image(C);
434         ARegion *ar = CTX_wm_region(C);
435         ViewZoomData *vpd;
436
437         op->customdata = vpd = MEM_callocN(sizeof(ViewZoomData), "ImageViewZoomData");
438         WM_cursor_modal_set(CTX_wm_window(C), BC_NSEW_SCROLLCURSOR);
439
440         vpd->origx = event->x;
441         vpd->origy = event->y;
442         vpd->zoom = sima->zoom;
443         vpd->event_type = event->type;
444
445         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &vpd->location[0], &vpd->location[1]);
446
447         if (U.viewzoom == USER_ZOOM_CONT) {
448                 /* needs a timer to continue redrawing */
449                 vpd->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.01f);
450                 vpd->timer_lastdraw = PIL_check_seconds_timer();
451         }
452
453         vpd->sima = sima;
454         vpd->ar = ar;
455
456         WM_event_add_modal_handler(C, op);
457 }
458
459 static void image_view_zoom_exit(bContext *C, wmOperator *op, bool cancel)
460 {
461         SpaceImage *sima = CTX_wm_space_image(C);
462         ViewZoomData *vpd = op->customdata;
463
464         if (cancel) {
465                 sima->zoom = vpd->zoom;
466                 ED_region_tag_redraw(CTX_wm_region(C));
467         }
468
469         if (vpd->timer)
470                 WM_event_remove_timer(CTX_wm_manager(C), vpd->timer->win, vpd->timer);
471
472         WM_cursor_modal_restore(CTX_wm_window(C));
473         MEM_freeN(op->customdata);
474 }
475
476 static int image_view_zoom_exec(bContext *C, wmOperator *op)
477 {
478         SpaceImage *sima = CTX_wm_space_image(C);
479         ARegion *ar = CTX_wm_region(C);
480
481         sima_zoom_set_factor(sima, ar, RNA_float_get(op->ptr, "factor"), NULL);
482
483         ED_region_tag_redraw(ar);
484
485         /* XXX notifier? */
486 #if 0
487         if (image_preview_active(curarea, NULL, NULL)) {
488                 /* recalculates new preview rect */
489                 scrarea_do_windraw(curarea);
490                 image_preview_event(2);
491         }
492 #endif
493         
494         return OPERATOR_FINISHED;
495 }
496
497 enum {
498         VIEW_PASS = 0,
499         VIEW_APPLY,
500         VIEW_CONFIRM
501 };
502
503 static int image_view_zoom_invoke(bContext *C, wmOperator *op, const wmEvent *event)
504 {
505         if (event->type == MOUSEZOOM || event->type == MOUSEPAN) {
506                 SpaceImage *sima = CTX_wm_space_image(C);
507                 ARegion *ar = CTX_wm_region(C);
508                 float delta, factor, location[2];
509
510                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &location[0], &location[1]);
511
512                 delta = event->prevx - event->x + event->prevy - event->y;
513
514                 if (U.uiflag & USER_ZOOM_INVERT)
515                         delta *= -1;
516
517                 factor = 1.0f + delta / 300.0f;
518                 RNA_float_set(op->ptr, "factor", factor);
519                 sima_zoom_set(sima, ar, sima->zoom * factor, location);
520                 ED_region_tag_redraw(ar);
521                 
522                 return OPERATOR_FINISHED;
523         }
524         else {
525                 image_view_zoom_init(C, op, event);
526                 return OPERATOR_RUNNING_MODAL;
527         }
528 }
529
530 static void image_zoom_apply(ViewZoomData *vpd, wmOperator *op, const int x, const int y, const short viewzoom, const short zoom_invert)
531 {
532         float factor;
533
534         if (viewzoom == USER_ZOOM_CONT) {
535                 double time = PIL_check_seconds_timer();
536                 float time_step = (float)(time - vpd->timer_lastdraw);
537                 float fac;
538                 float zfac;
539
540                 if (U.uiflag & USER_ZOOM_HORIZ) {
541                         fac = (float)(x - vpd->origx);
542                 }
543                 else {
544                         fac = (float)(y - vpd->origy);
545                 }
546
547                 if (zoom_invert) {
548                         fac = -fac;
549                 }
550
551                 /* oldstyle zoom */
552                 zfac = 1.0f + ((fac / 20.0f) * time_step);
553                 vpd->timer_lastdraw = time;
554                 /* this is the final zoom, but instead make it into a factor */
555                 //zoom = vpd->sima->zoom * zfac;
556                 factor = (vpd->sima->zoom * zfac) / vpd->zoom;
557         }
558         else {
559                 /* for now do the same things for scale and dolly */
560                 float delta = x - vpd->origx + y - vpd->origy;
561
562                 if (zoom_invert)
563                         delta *= -1.0f;
564
565                 factor = 1.0f + delta / 300.0f;
566         }
567
568         RNA_float_set(op->ptr, "factor", factor);
569         sima_zoom_set(vpd->sima, vpd->ar, vpd->zoom * factor, vpd->location);
570         ED_region_tag_redraw(vpd->ar);
571 }
572
573 static int image_view_zoom_modal(bContext *C, wmOperator *op, const wmEvent *event)
574 {
575         ViewZoomData *vpd = op->customdata;
576         short event_code = VIEW_PASS;
577
578         /* execute the events */
579         if (event->type == TIMER && event->customdata == vpd->timer) {
580                 /* continuous zoom */
581                 event_code = VIEW_APPLY;
582         }
583         else if (event->type == MOUSEMOVE) {
584                 event_code = VIEW_APPLY;
585         }
586         else if (event->type == vpd->event_type && event->val == KM_RELEASE) {
587                 event_code = VIEW_CONFIRM;
588         }
589
590         if (event_code == VIEW_APPLY) {
591                 image_zoom_apply(vpd, op, event->x, event->y, U.viewzoom, (U.uiflag & USER_ZOOM_INVERT) != 0);
592         }
593         else if (event_code == VIEW_CONFIRM) {
594                 image_view_zoom_exit(C, op, false);
595                 return OPERATOR_FINISHED;
596         }
597
598         return OPERATOR_RUNNING_MODAL;
599 }
600
601 static void image_view_zoom_cancel(bContext *C, wmOperator *op)
602 {
603         image_view_zoom_exit(C, op, true);
604 }
605
606 void IMAGE_OT_view_zoom(wmOperatorType *ot)
607 {
608         PropertyRNA *prop;
609
610         /* identifiers */
611         ot->name = "View Zoom";
612         ot->idname = "IMAGE_OT_view_zoom";
613         ot->description = "Zoom in/out the image";
614         
615         /* api callbacks */
616         ot->exec = image_view_zoom_exec;
617         ot->invoke = image_view_zoom_invoke;
618         ot->modal = image_view_zoom_modal;
619         ot->cancel = image_view_zoom_cancel;
620         ot->poll = space_image_main_area_poll;
621
622         /* flags */
623         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR | OPTYPE_LOCK_BYPASS;
624         
625         /* properties */
626         prop = RNA_def_float(ot->srna, "factor", 0.0f, -FLT_MAX, FLT_MAX, "Factor",
627                              "Zoom factor, values higher than 1.0 zoom in, lower values zoom out", -FLT_MAX, FLT_MAX);
628         RNA_def_property_flag(prop, PROP_HIDDEN);
629 }
630
631 /********************** NDOF operator *********************/
632
633 /* Combined pan/zoom from a 3D mouse device.
634  * Z zooms, XY pans
635  * "view" (not "paper") control -- user moves the viewpoint, not the image being viewed
636  * that explains the negative signs in the code below
637  */
638
639 static int image_view_ndof_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
640 {
641         if (event->type != NDOF_MOTION)
642                 return OPERATOR_CANCELLED;
643         else {
644                 SpaceImage *sima = CTX_wm_space_image(C);
645                 ARegion *ar = CTX_wm_region(C);
646                 float pan_vec[3];
647
648                 const wmNDOFMotionData *ndof = event->customdata;
649                 const float speed = NDOF_PIXELS_PER_SECOND;
650
651                 WM_event_ndof_pan_get(ndof, pan_vec, true);
652
653                 mul_v2_fl(pan_vec, (speed * ndof->dt) / sima->zoom);
654                 pan_vec[2] *= -ndof->dt;
655
656                 sima_zoom_set_factor(sima, ar, 1.0f + pan_vec[2], NULL);
657                 sima->xof += pan_vec[0];
658                 sima->yof += pan_vec[1];
659
660                 ED_region_tag_redraw(ar);
661
662                 return OPERATOR_FINISHED;
663         }
664 }
665
666 void IMAGE_OT_view_ndof(wmOperatorType *ot)
667 {
668         /* identifiers */
669         ot->name = "NDOF Pan/Zoom";
670         ot->idname = "IMAGE_OT_view_ndof";
671         ot->description = "Use a 3D mouse device to pan/zoom the view";
672         
673         /* api callbacks */
674         ot->invoke = image_view_ndof_invoke;
675         ot->poll = space_image_main_area_poll;
676
677         /* flags */
678         ot->flag = OPTYPE_LOCK_BYPASS;
679 }
680
681 /********************** view all operator *********************/
682
683 /* Updates the fields of the View2D member of the SpaceImage struct.
684  * Default behavior is to reset the position of the image and set the zoom to 1
685  * If the image will not fit within the window rectangle, the zoom is adjusted */
686
687 static int image_view_all_exec(bContext *C, wmOperator *op)
688 {
689         SpaceImage *sima;
690         ARegion *ar;
691         float aspx, aspy, zoomx, zoomy, w, h;
692         int width, height;
693         const bool fit_view = RNA_boolean_get(op->ptr, "fit_view");
694
695         /* retrieve state */
696         sima = CTX_wm_space_image(C);
697         ar = CTX_wm_region(C);
698
699         ED_space_image_get_size(sima, &width, &height);
700         ED_space_image_get_aspect(sima, &aspx, &aspy);
701
702         w = width * aspx;
703         h = height * aspy;
704         
705         /* check if the image will fit in the image with (zoom == 1) */
706         width  = BLI_rcti_size_x(&ar->winrct) + 1;
707         height = BLI_rcti_size_y(&ar->winrct) + 1;
708
709         if (fit_view) {
710                 const int margin = 5; /* margin from border */
711
712                 zoomx = (float) width / (w + 2 * margin);
713                 zoomy = (float) height / (h + 2 * margin);
714
715                 sima_zoom_set(sima, ar, min_ff(zoomx, zoomy), NULL);
716         }
717         else {
718                 if ((w >= width || h >= height) && (width > 0 && height > 0)) {
719                         zoomx = (float) width / w;
720                         zoomy = (float) height / h;
721
722                         /* find the zoom value that will fit the image in the image space */
723                         sima_zoom_set(sima, ar, 1.0f / power_of_2(1.0f / min_ff(zoomx, zoomy)), NULL);
724                 }
725                 else
726                         sima_zoom_set(sima, ar, 1.0f, NULL);
727         }
728
729         sima->xof = sima->yof = 0.0f;
730
731         ED_region_tag_redraw(ar);
732         
733         return OPERATOR_FINISHED;
734 }
735
736 void IMAGE_OT_view_all(wmOperatorType *ot)
737 {
738         PropertyRNA *prop;
739
740         /* identifiers */
741         ot->name = "View All";
742         ot->idname = "IMAGE_OT_view_all";
743         ot->description = "View the entire image";
744         
745         /* api callbacks */
746         ot->exec = image_view_all_exec;
747         ot->poll = space_image_main_area_poll;
748
749         /* flags */
750         ot->flag = OPTYPE_LOCK_BYPASS;
751
752         /* properties */
753         prop = RNA_def_boolean(ot->srna, "fit_view", 0, "Fit View", "Fit frame to the viewport");
754         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
755 }
756
757 /********************** view selected operator *********************/
758
759 static int image_view_selected_exec(bContext *C, wmOperator *UNUSED(op))
760 {
761         SpaceImage *sima;
762         ARegion *ar;
763         Scene *scene;
764         Object *obedit;
765         Image *ima;
766         float size, min[2], max[2], d[2], aspx, aspy;
767         int width, height;
768
769         /* retrieve state */
770         sima = CTX_wm_space_image(C);
771         ar = CTX_wm_region(C);
772         scene = CTX_data_scene(C);
773         obedit = CTX_data_edit_object(C);
774
775         ima = ED_space_image(sima);
776         ED_space_image_get_size(sima, &width, &height);
777         ED_space_image_get_aspect(sima, &aspx, &aspy);
778
779         width = width * aspx;
780         height = height * aspy;
781
782         /* get bounds */
783         if (ED_space_image_show_uvedit(sima, obedit)) {
784                 if (!ED_uvedit_minmax(scene, ima, obedit, min, max))
785                         return OPERATOR_CANCELLED;
786         }
787         else if (ED_space_image_check_show_maskedit(scene, sima)) {
788                 if (!ED_mask_selected_minmax(C, min, max)) {
789                         return OPERATOR_CANCELLED;
790                 }
791         }
792
793         /* adjust offset and zoom */
794         sima->xof = (int)(((min[0] + max[0]) * 0.5f - 0.5f) * width);
795         sima->yof = (int)(((min[1] + max[1]) * 0.5f - 0.5f) * height);
796
797         d[0] = max[0] - min[0];
798         d[1] = max[1] - min[1];
799         size = 0.5f * MAX2(d[0], d[1]) * MAX2(width, height) / 256.0f;
800         
801         if (size <= 0.01f) size = 0.01f;
802         sima_zoom_set(sima, ar, 0.7f / size, NULL);
803
804         ED_region_tag_redraw(ar);
805         
806         return OPERATOR_FINISHED;
807 }
808
809 static int image_view_selected_poll(bContext *C)
810 {
811         return (space_image_main_area_poll(C) && (ED_operator_uvedit(C) || ED_operator_mask(C)));
812 }
813
814 void IMAGE_OT_view_selected(wmOperatorType *ot)
815 {
816         /* identifiers */
817         ot->name = "View Center";
818         ot->idname = "IMAGE_OT_view_selected";
819         ot->description = "View all selected UVs";
820         
821         /* api callbacks */
822         ot->exec = image_view_selected_exec;
823         ot->poll = image_view_selected_poll;
824 }
825
826 /********************** view zoom in/out operator *********************/
827
828 static int image_view_zoom_in_exec(bContext *C, wmOperator *op)
829 {
830         SpaceImage *sima = CTX_wm_space_image(C);
831         ARegion *ar = CTX_wm_region(C);
832         float location[2];
833         
834         RNA_float_get_array(op->ptr, "location", location);
835
836         sima_zoom_set_factor(sima, ar, powf(2.0f, 1.0f / 3.0f), location);
837
838         ED_region_tag_redraw(ar);
839         
840         return OPERATOR_FINISHED;
841 }
842
843 static int image_view_zoom_in_invoke(bContext *C, wmOperator *op, const wmEvent *event)
844 {
845         ARegion *ar = CTX_wm_region(C);
846         float location[2];
847
848         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &location[0], &location[1]);
849         RNA_float_set_array(op->ptr, "location", location);
850
851         return image_view_zoom_in_exec(C, op);
852 }
853
854 void IMAGE_OT_view_zoom_in(wmOperatorType *ot)
855 {
856         PropertyRNA *prop;
857
858         /* identifiers */
859         ot->name = "View Zoom In";
860         ot->idname = "IMAGE_OT_view_zoom_in";
861         ot->description = "Zoom in the image (centered around 2D cursor)";
862         
863         /* api callbacks */
864         ot->invoke = image_view_zoom_in_invoke;
865         ot->exec = image_view_zoom_in_exec;
866         ot->poll = space_image_main_area_poll;
867
868         /* flags */
869         ot->flag = OPTYPE_LOCK_BYPASS;
870
871         /* properties */
872         prop = RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX,
873                                     "Location", "Cursor location in screen coordinates", -10.0f, 10.0f);
874         RNA_def_property_flag(prop, PROP_HIDDEN);
875 }
876
877 static int image_view_zoom_out_exec(bContext *C, wmOperator *op)
878 {
879         SpaceImage *sima = CTX_wm_space_image(C);
880         ARegion *ar = CTX_wm_region(C);
881         float location[2];
882         
883         RNA_float_get_array(op->ptr, "location", location);
884
885         sima_zoom_set_factor(sima, ar, powf(0.5f, 1.0f / 3.0f), location);
886         
887         ED_region_tag_redraw(ar);
888         
889         return OPERATOR_FINISHED;
890 }
891
892 static int image_view_zoom_out_invoke(bContext *C, wmOperator *op, const wmEvent *event)
893 {
894         ARegion *ar = CTX_wm_region(C);
895         float location[2];
896
897         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &location[0], &location[1]);
898         RNA_float_set_array(op->ptr, "location", location);
899
900         return image_view_zoom_out_exec(C, op);
901 }
902
903 void IMAGE_OT_view_zoom_out(wmOperatorType *ot)
904 {
905         PropertyRNA *prop;
906
907         /* identifiers */
908         ot->name = "View Zoom Out";
909         ot->idname = "IMAGE_OT_view_zoom_out";
910         ot->description = "Zoom out the image (centered around 2D cursor)";
911         
912         /* api callbacks */
913         ot->invoke = image_view_zoom_out_invoke;
914         ot->exec = image_view_zoom_out_exec;
915         ot->poll = space_image_main_area_poll;
916
917         /* flags */
918         ot->flag = OPTYPE_LOCK_BYPASS;
919
920         /* properties */
921         prop = RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX,
922                                     "Location", "Cursor location in screen coordinates", -10.0f, 10.0f);
923         RNA_def_property_flag(prop, PROP_HIDDEN);
924 }
925
926 /********************** view zoom ratio operator *********************/
927
928 static int image_view_zoom_ratio_exec(bContext *C, wmOperator *op)
929 {
930         SpaceImage *sima = CTX_wm_space_image(C);
931         ARegion *ar = CTX_wm_region(C);
932
933         sima_zoom_set(sima, ar, RNA_float_get(op->ptr, "ratio"), NULL);
934         
935         /* ensure pixel exact locations for draw */
936         sima->xof = (int)sima->xof;
937         sima->yof = (int)sima->yof;
938
939         /* XXX notifier? */
940 #if 0
941         if (image_preview_active(curarea, NULL, NULL)) {
942                 /* recalculates new preview rect */
943                 scrarea_do_windraw(curarea);
944                 image_preview_event(2);
945         }
946 #endif
947
948         ED_region_tag_redraw(ar);
949         
950         return OPERATOR_FINISHED;
951 }
952
953 void IMAGE_OT_view_zoom_ratio(wmOperatorType *ot)
954 {
955         /* identifiers */
956         ot->name = "View Zoom Ratio";
957         ot->idname = "IMAGE_OT_view_zoom_ratio";
958         ot->description = "Set zoom ratio of the view";
959         
960         /* api callbacks */
961         ot->exec = image_view_zoom_ratio_exec;
962         ot->poll = space_image_main_area_poll;
963
964         /* flags */
965         ot->flag = OPTYPE_LOCK_BYPASS;
966
967         /* properties */
968         RNA_def_float(ot->srna, "ratio", 0.0f, -FLT_MAX, FLT_MAX,
969                       "Ratio", "Zoom ratio, 1.0 is 1:1, higher is zoomed in, lower is zoomed out", -FLT_MAX, FLT_MAX);
970 }
971
972 /**************** load/replace/save callbacks ******************/
973 static void image_filesel(bContext *C, wmOperator *op, const char *path)
974 {
975         RNA_string_set(op->ptr, "filepath", path);
976         WM_event_add_fileselect(C, op); 
977 }
978
979 /******************** open image operator ********************/
980
981 typedef struct ImageOpenData {
982         PropertyPointerRNA pprop;
983         ImageUser *iuser;
984         ImageFormatData im_format;
985 } ImageOpenData;
986
987 typedef struct ImageFrame {
988         struct ImageFrame *next, *prev;
989         int framenr;
990 } ImageFrame;
991
992 static void image_open_init(bContext *C, wmOperator *op)
993 {
994         ImageOpenData *iod;
995         op->customdata = iod = MEM_callocN(sizeof(ImageOpenData), __func__);
996         iod->iuser = CTX_data_pointer_get_type(C, "image_user", &RNA_ImageUser).data;
997         UI_context_active_but_prop_get_templateID(C, &iod->pprop.ptr, &iod->pprop.prop);
998 }
999
1000 static void image_open_cancel(bContext *UNUSED(C), wmOperator *op)
1001 {
1002         MEM_freeN(op->customdata);
1003         op->customdata = NULL;
1004 }
1005
1006 /**
1007  * \brief Get a list of frames from the list of image files matching the first file name sequence pattern
1008  * \param ptr [in] the RNA pointer containing the "directory" entry and "files" collection
1009  * \param frames [out] the list of frame numbers found in the files matching the first one by name
1010  * \param path [out] the full path of the first file in the list of image files
1011  */
1012 static void image_sequence_get_frames(PointerRNA *ptr, ListBase *frames, char *path, const size_t maxlen)
1013 {
1014         char dir[FILE_MAXDIR];
1015         bool is_first_entry = true;
1016
1017         RNA_string_get(ptr, "directory", dir);
1018         RNA_BEGIN (ptr, itemptr, "files")
1019         {
1020                 char base_head[FILE_MAX], base_tail[FILE_MAX];
1021                 char head[FILE_MAX], tail[FILE_MAX];
1022                 unsigned short digits;
1023                 char *filename = RNA_string_get_alloc(&itemptr, "name", NULL, 0);
1024                 ImageFrame *frame = MEM_callocN(sizeof(ImageFrame), "image_frame");
1025
1026                 /* use the first file in the list as base filename */
1027                 if (is_first_entry) {
1028                         BLI_join_dirfile(path, maxlen, dir, filename);
1029                         frame->framenr = BLI_stringdec(filename, base_head, base_tail, &digits);
1030                         BLI_addtail(frames, frame);
1031                         is_first_entry = false;
1032                 }
1033                 else {
1034                         frame->framenr = BLI_stringdec(filename, head, tail, &digits);
1035
1036                         /* still in the same sequence */
1037                         if ((STREQLEN(base_head, head, FILE_MAX)) &&
1038                             (STREQLEN(base_tail, tail, FILE_MAX)))
1039                         {
1040                                 BLI_addtail(frames, frame);
1041                         }
1042                         else {
1043                                 /* different file base name found, is ignored */
1044                                 MEM_freeN(filename);
1045                                 MEM_freeN(frame);
1046                                 break;
1047                         }
1048                 }
1049
1050                 MEM_freeN(filename);
1051         }
1052         RNA_END
1053 }
1054
1055 static int image_cmp_frame(const void *a, const void *b)
1056 {
1057         const ImageFrame *frame_a = a;
1058         const ImageFrame *frame_b = b;
1059
1060         if (frame_a->framenr < frame_b->framenr) return -1;
1061         if (frame_a->framenr > frame_b->framenr) return 1;
1062         return 0;
1063 }
1064
1065 /**
1066  * \brief Return the start (offset) and the length of the sequence of continuous frames in the list of frames
1067  * \param frames [in] the list of frame numbers, as a side-effect the list is sorted
1068  * \param ofs [out] offest, the first frame number in the sequence
1069  * \return the number of contiguous frames in the sequence
1070  */
1071 static int image_sequence_get_len(ListBase *frames, int *ofs)
1072 {
1073         ImageFrame *frame;
1074
1075         BLI_listbase_sort(frames, image_cmp_frame);
1076
1077         frame = frames->first;
1078         if (frame) {
1079                 int frame_curr = frame->framenr;
1080                 (*ofs) = frame_curr;
1081                 while (frame && (frame->framenr == frame_curr)) {
1082                         frame_curr++;
1083                         frame = frame->next;
1084                 }
1085                 return frame_curr - (*ofs);
1086         }
1087         return 0;
1088 }
1089
1090 static int image_open_exec(bContext *C, wmOperator *op)
1091 {
1092         Main *bmain = CTX_data_main(C);
1093         SpaceImage *sima = CTX_wm_space_image(C); /* XXX other space types can call */
1094         Scene *scene = CTX_data_scene(C);
1095         Object *obedit = CTX_data_edit_object(C);
1096         ImageUser *iuser = NULL;
1097         ImageOpenData *iod = op->customdata;
1098         PointerRNA idptr;
1099         Image *ima = NULL;
1100         char path[FILE_MAX];
1101         int frame_seq_len = 0;
1102         int frame_ofs = 1;
1103         bool exists = false;
1104
1105         const bool is_relative_path = RNA_boolean_get(op->ptr, "relative_path");
1106
1107         RNA_string_get(op->ptr, "filepath", path);
1108
1109         if (RNA_struct_property_is_set(op->ptr, "directory") &&
1110             RNA_struct_property_is_set(op->ptr, "files"))
1111         {
1112                 /* only to pass to imbuf */
1113                 char path_full[FILE_MAX];
1114                 BLI_strncpy(path_full, path, sizeof(path_full));
1115                 BLI_path_abs(path_full, G.main->name);
1116
1117                 if (!IMB_isanim(path_full)) {
1118                         bool was_relative = BLI_path_is_rel(path);
1119                         ListBase frames;
1120
1121                         BLI_listbase_clear(&frames);
1122                         image_sequence_get_frames(op->ptr, &frames, path, sizeof(path));
1123                         frame_seq_len = image_sequence_get_len(&frames, &frame_ofs);
1124                         BLI_freelistN(&frames);
1125
1126                         if (was_relative) {
1127                                 BLI_path_rel(path, G.main->name);
1128                         }
1129                 }
1130         }
1131
1132         errno = 0;
1133
1134         ima = BKE_image_load_exists_ex(path, &exists);
1135
1136         if (!ima) {
1137                 if (op->customdata) MEM_freeN(op->customdata);
1138                 BKE_reportf(op->reports, RPT_ERROR, "Cannot read '%s': %s",
1139                             path, errno ? strerror(errno) : TIP_("unsupported image format"));
1140                 return OPERATOR_CANCELLED;
1141         }
1142
1143         if (!op->customdata)
1144                 image_open_init(C, op);
1145
1146         /* handle multiview images */
1147         if (RNA_boolean_get(op->ptr, "use_multiview")) {
1148                 ImageFormatData *imf = &iod->im_format;
1149
1150                 ima->flag |= IMA_USE_VIEWS;
1151                 ima->views_format = imf->views_format;
1152                 *ima->stereo3d_format = imf->stereo3d_format;
1153         }
1154         else {
1155                 ima->flag &= ~IMA_USE_VIEWS;
1156                 BKE_image_free_views(ima);
1157         }
1158
1159         /* only image path after save, never ibuf */
1160         if (is_relative_path) {
1161                 if (!exists) {
1162                         BLI_path_rel(ima->name, bmain->name);
1163                 }
1164         }
1165
1166         /* hook into UI */
1167         iod = op->customdata;
1168
1169         if (iod->pprop.prop) {
1170                 /* when creating new ID blocks, use is already 1, but RNA
1171                  * pointer se also increases user, so this compensates it */
1172                 id_us_min(&ima->id);
1173                 if ((frame_seq_len > 1) && ima->source == IMA_SRC_FILE) {
1174                         ima->source = IMA_SRC_SEQUENCE;
1175                 }
1176                 RNA_id_pointer_create(&ima->id, &idptr);
1177                 RNA_property_pointer_set(&iod->pprop.ptr, iod->pprop.prop, idptr);
1178                 RNA_property_update(C, &iod->pprop.ptr, iod->pprop.prop);
1179         }
1180
1181         if (iod->iuser) {
1182                 iuser = iod->iuser;
1183         }
1184         else if (sima) {
1185                 ED_space_image_set(sima, scene, obedit, ima);
1186                 iuser = &sima->iuser;
1187         }
1188         else {
1189                 Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
1190                 if (tex && tex->type == TEX_IMAGE) {
1191                         iuser = &tex->iuser;
1192                 }
1193         }
1194
1195         /* initialize because of new image */
1196         if (iuser) {
1197                 iuser->frames = frame_seq_len;
1198                 iuser->sfra = 1;
1199                 iuser->framenr = 1;
1200                 iuser->offset = frame_ofs - 1;
1201                 iuser->fie_ima = 2;
1202                 iuser->scene = scene;
1203                 BKE_image_init_imageuser(ima, iuser);
1204         }
1205
1206         /* XXX unpackImage frees image buffers */
1207         ED_preview_kill_jobs(CTX_wm_manager(C), bmain);
1208         
1209         BKE_image_signal(ima, iuser, IMA_SIGNAL_RELOAD);
1210         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1211         
1212         MEM_freeN(op->customdata);
1213
1214         return OPERATOR_FINISHED;
1215 }
1216
1217 static int image_open_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1218 {
1219         SpaceImage *sima = CTX_wm_space_image(C); /* XXX other space types can call */
1220         const char *path = U.textudir;
1221         Image *ima = NULL;
1222         Scene *scene = CTX_data_scene(C);
1223         PropertyRNA *prop;
1224         if (sima) {
1225                 ima = sima->image;
1226         }
1227
1228         if (ima == NULL) {
1229                 Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
1230                 if (tex && tex->type == TEX_IMAGE)
1231                         ima = tex->ima;
1232         }
1233
1234         if (ima == NULL) {
1235                 PointerRNA ptr;
1236                 PropertyRNA *prop;
1237
1238                 /* hook into UI */
1239                 UI_context_active_but_prop_get_templateID(C, &ptr, &prop);
1240
1241                 if (prop) {
1242                         PointerRNA oldptr;
1243                         Image *oldima;
1244
1245                         oldptr = RNA_property_pointer_get(&ptr, prop);
1246                         oldima = (Image *)oldptr.id.data;
1247                         /* unlikely to fail but better avoid strange crash */
1248                         if (oldima && GS(oldima->id.name) == ID_IM) {
1249                                 ima = oldima;
1250                         }
1251                 }
1252         }
1253
1254         if (ima)
1255                 path = ima->name;
1256
1257         if (RNA_struct_property_is_set(op->ptr, "filepath"))
1258                 return image_open_exec(C, op);
1259         
1260         image_open_init(C, op);
1261
1262         /* show multiview save options only if scene has multiviews */
1263         prop = RNA_struct_find_property(op->ptr, "show_multiview");
1264         RNA_property_boolean_set(op->ptr, prop, (scene->r.scemode & R_MULTIVIEW) != 0);
1265
1266         image_filesel(C, op, path);
1267
1268         return OPERATOR_RUNNING_MODAL;
1269 }
1270
1271 static bool image_open_draw_check_prop(PointerRNA *UNUSED(ptr), PropertyRNA *prop)
1272 {
1273         const char *prop_id = RNA_property_identifier(prop);
1274
1275         return !(STREQ(prop_id, "filepath") ||
1276                  STREQ(prop_id, "directory") ||
1277                  STREQ(prop_id, "filename")
1278                  );
1279 }
1280
1281 static void image_open_draw(bContext *UNUSED(C), wmOperator *op)
1282 {
1283         uiLayout *layout = op->layout;
1284         ImageOpenData *iod = op->customdata;
1285         ImageFormatData *imf = &iod->im_format;
1286         PointerRNA imf_ptr, ptr;
1287
1288         /* main draw call */
1289         RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);
1290         uiDefAutoButsRNA(layout, &ptr, image_open_draw_check_prop, '\0');
1291
1292         /* image template */
1293         RNA_pointer_create(NULL, &RNA_ImageFormatSettings, imf, &imf_ptr);
1294
1295         /* multiview template */
1296         if (RNA_boolean_get(op->ptr, "show_multiview"))
1297                 uiTemplateImageFormatViews(layout, &imf_ptr, op->ptr);
1298 }
1299
1300 /* called by other space types too */
1301 void IMAGE_OT_open(wmOperatorType *ot)
1302 {
1303         /* identifiers */
1304         ot->name = "Open Image";
1305         ot->description = "Open image";
1306         ot->idname = "IMAGE_OT_open";
1307         
1308         /* api callbacks */
1309         ot->exec = image_open_exec;
1310         ot->invoke = image_open_invoke;
1311         ot->cancel = image_open_cancel;
1312         ot->ui = image_open_draw;
1313
1314         /* flags */
1315         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1316
1317         /* properties */
1318         WM_operator_properties_filesel(ot, FILE_TYPE_FOLDER | FILE_TYPE_IMAGE | FILE_TYPE_MOVIE, FILE_SPECIAL, FILE_OPENFILE,
1319                                        WM_FILESEL_FILEPATH | WM_FILESEL_DIRECTORY | WM_FILESEL_FILES | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
1320 }
1321
1322 /******************** Match movie length operator ********************/
1323 static int image_match_len_exec(bContext *C, wmOperator *UNUSED(op))
1324 {
1325         Scene *scene = CTX_data_scene(C);
1326         Image *ima = CTX_data_pointer_get_type(C, "edit_image", &RNA_Image).data;
1327         ImageUser *iuser = CTX_data_pointer_get_type(C, "edit_image_user", &RNA_ImageUser).data;
1328
1329         if (!ima || !iuser) {
1330                 /* Try to get a Texture, or a SpaceImage from context... */
1331                 SpaceImage *sima = CTX_wm_space_image(C);
1332                 Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
1333                 if (tex && tex->type == TEX_IMAGE) {
1334                         ima = tex->ima;
1335                         iuser = &tex->iuser;
1336                 }
1337                 else if (sima) {
1338                         ima = sima->image;
1339                         iuser = &sima->iuser;
1340                 }
1341                 
1342         }
1343
1344         if (!ima || !iuser || !BKE_image_has_anim(ima))
1345                 return OPERATOR_CANCELLED;
1346
1347         iuser->frames = IMB_anim_get_duration(((ImageAnim *) ima->anims.first)->anim, IMB_TC_RECORD_RUN);
1348         BKE_image_user_frame_calc(iuser, scene->r.cfra, 0);
1349
1350         return OPERATOR_FINISHED;
1351 }
1352
1353 /* called by other space types too */
1354 void IMAGE_OT_match_movie_length(wmOperatorType *ot)
1355 {
1356         /* identifiers */
1357         ot->name = "Match Movie Length";
1358         ot->description = "Set image's user's length to the one of this video";
1359         ot->idname = "IMAGE_OT_match_movie_length";
1360         
1361         /* api callbacks */
1362         ot->exec = image_match_len_exec;
1363
1364         /* flags */
1365         ot->flag = OPTYPE_REGISTER | OPTYPE_INTERNAL/* | OPTYPE_UNDO */; /* Don't think we need undo for that. */
1366 }
1367
1368 /******************** replace image operator ********************/
1369
1370 static int image_replace_exec(bContext *C, wmOperator *op)
1371 {
1372         SpaceImage *sima = CTX_wm_space_image(C);
1373         char str[FILE_MAX];
1374
1375         if (!sima->image)
1376                 return OPERATOR_CANCELLED;
1377         
1378         RNA_string_get(op->ptr, "filepath", str);
1379
1380         /* we cant do much if the str is longer then FILE_MAX :/ */
1381         BLI_strncpy(sima->image->name, str, sizeof(sima->image->name));
1382
1383         if (sima->image->source == IMA_SRC_GENERATED) {
1384                 sima->image->source = IMA_SRC_FILE;
1385                 BKE_image_signal(sima->image, &sima->iuser, IMA_SIGNAL_SRC_CHANGE);
1386         }
1387         
1388         if (BLI_testextensie_array(str, imb_ext_movie))
1389                 sima->image->source = IMA_SRC_MOVIE;
1390         else
1391                 sima->image->source = IMA_SRC_FILE;
1392
1393         /* XXX unpackImage frees image buffers */
1394         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
1395         
1396         BKE_icon_changed(BKE_icon_id_ensure(&sima->image->id));
1397         BKE_image_signal(sima->image, &sima->iuser, IMA_SIGNAL_RELOAD);
1398         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
1399
1400         return OPERATOR_FINISHED;
1401 }
1402
1403 static int image_replace_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1404 {
1405         SpaceImage *sima = CTX_wm_space_image(C);
1406
1407         if (!sima->image)
1408                 return OPERATOR_CANCELLED;
1409
1410         if (RNA_struct_property_is_set(op->ptr, "filepath"))
1411                 return image_replace_exec(C, op);
1412
1413         if (!RNA_struct_property_is_set(op->ptr, "relative_path"))
1414                 RNA_boolean_set(op->ptr, "relative_path", BLI_path_is_rel(sima->image->name));
1415
1416         image_filesel(C, op, sima->image->name);
1417
1418         return OPERATOR_RUNNING_MODAL;
1419 }
1420
1421 void IMAGE_OT_replace(wmOperatorType *ot)
1422 {
1423         /* identifiers */
1424         ot->name = "Replace Image";
1425         ot->idname = "IMAGE_OT_replace";
1426         ot->description = "Replace current image by another one from disk";
1427         
1428         /* api callbacks */
1429         ot->exec = image_replace_exec;
1430         ot->invoke = image_replace_invoke;
1431         ot->poll = image_not_packed_poll;
1432
1433         /* flags */
1434         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1435
1436         /* properties */
1437         WM_operator_properties_filesel(ot, FILE_TYPE_FOLDER | FILE_TYPE_IMAGE | FILE_TYPE_MOVIE, FILE_SPECIAL, FILE_OPENFILE,
1438                                        WM_FILESEL_FILEPATH | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
1439 }
1440
1441 /******************** save image as operator ********************/
1442
1443 typedef struct {
1444         /* matching scene->r settings */
1445         //short planes, imtype, subimtype, quality;
1446         ImageFormatData im_format;
1447         char filepath[FILE_MAX]; /* keep absolute */
1448 } SaveImageOptions;
1449
1450 static void save_image_options_defaults(SaveImageOptions *simopts)
1451 {
1452         BKE_imformat_defaults(&simopts->im_format);
1453         simopts->filepath[0] = '\0';
1454 }
1455
1456 static char imtype_best_depth(ImBuf *ibuf, const char imtype)
1457 {
1458         const char depth_ok = BKE_imtype_valid_depths(imtype);
1459
1460         if (ibuf->rect_float) {
1461                 if (depth_ok & R_IMF_CHAN_DEPTH_32) return R_IMF_CHAN_DEPTH_32;
1462                 if (depth_ok & R_IMF_CHAN_DEPTH_24) return R_IMF_CHAN_DEPTH_24;
1463                 if (depth_ok & R_IMF_CHAN_DEPTH_16) return R_IMF_CHAN_DEPTH_16;
1464                 if (depth_ok & R_IMF_CHAN_DEPTH_12) return R_IMF_CHAN_DEPTH_12;
1465                 return R_IMF_CHAN_DEPTH_8;
1466         }
1467         else {
1468                 if (depth_ok & R_IMF_CHAN_DEPTH_8) return R_IMF_CHAN_DEPTH_8;
1469                 if (depth_ok & R_IMF_CHAN_DEPTH_12) return R_IMF_CHAN_DEPTH_12;
1470                 if (depth_ok & R_IMF_CHAN_DEPTH_16) return R_IMF_CHAN_DEPTH_16;
1471                 if (depth_ok & R_IMF_CHAN_DEPTH_24) return R_IMF_CHAN_DEPTH_24;
1472                 if (depth_ok & R_IMF_CHAN_DEPTH_32) return R_IMF_CHAN_DEPTH_32;
1473                 return R_IMF_CHAN_DEPTH_8; /* fallback, should not get here */
1474         }
1475 }
1476
1477 static int save_image_options_init(SaveImageOptions *simopts, SpaceImage *sima, Scene *scene,
1478                                    const bool guess_path, const bool save_as_render)
1479 {
1480         void *lock;
1481         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
1482
1483         if (ibuf) {
1484                 Image *ima = sima->image;
1485                 bool is_depth_set = false;
1486
1487                 if (ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE)) {
1488                         /* imtype */
1489                         simopts->im_format = scene->r.im_format;
1490                         is_depth_set = true;
1491                 }
1492                 else {
1493                         if (ima->source == IMA_SRC_GENERATED) {
1494                                 simopts->im_format.imtype = R_IMF_IMTYPE_PNG;
1495                                 simopts->im_format.compress = ibuf->foptions.quality;
1496                         }
1497                         else {
1498                                 BKE_imbuf_to_image_format(&simopts->im_format, ibuf);
1499                         }
1500                 }
1501
1502                 simopts->im_format.planes = ibuf->planes;
1503
1504                 //simopts->subimtype = scene->r.subimtype; /* XXX - this is lame, we need to make these available too! */
1505
1506                 BLI_strncpy(simopts->filepath, ibuf->name, sizeof(simopts->filepath));
1507
1508                 /* sanitize all settings */
1509
1510                 /* unlikely but just in case */
1511                 if (ELEM(simopts->im_format.planes, R_IMF_PLANES_BW, R_IMF_PLANES_RGB, R_IMF_PLANES_RGBA) == 0) {
1512                         simopts->im_format.planes = R_IMF_PLANES_RGBA;
1513                 }
1514
1515                 /* depth, account for float buffer and format support */
1516                 if (is_depth_set == false) {
1517                         simopts->im_format.depth = imtype_best_depth(ibuf, simopts->im_format.imtype);
1518                 }
1519
1520                 /* some formats don't use quality so fallback to scenes quality */
1521                 if (simopts->im_format.quality == 0) {
1522                         simopts->im_format.quality = scene->r.im_format.quality;
1523                 }
1524
1525                 /* check for empty path */
1526                 if (guess_path && simopts->filepath[0] == 0) {
1527                         const bool is_prev_save = !STREQ(G.ima, "//");
1528                         if (save_as_render) {
1529                                 if (is_prev_save) {
1530                                         BLI_strncpy(simopts->filepath, G.ima, sizeof(simopts->filepath));
1531                                 }
1532                                 else {
1533                                         BLI_strncpy(simopts->filepath, "//untitled", sizeof(simopts->filepath));
1534                                         BLI_path_abs(simopts->filepath, G.main->name);
1535                                 }
1536                         }
1537                         else {
1538                                 BLI_snprintf(simopts->filepath, sizeof(simopts->filepath), "//%s", ima->id.name + 2);
1539                                 BLI_path_abs(simopts->filepath, is_prev_save ? G.ima : G.main->name);
1540                         }
1541                 }
1542
1543                 /* use the multiview image settings as the default */
1544                 simopts->im_format.stereo3d_format = *ima->stereo3d_format;
1545                 simopts->im_format.views_format = ima->views_format;
1546
1547                 /* color management */
1548                 BKE_color_managed_display_settings_copy(&simopts->im_format.display_settings, &scene->display_settings);
1549                 BKE_color_managed_view_settings_copy(&simopts->im_format.view_settings, &scene->view_settings);
1550         }
1551
1552         ED_space_image_release_buffer(sima, ibuf, lock);
1553
1554         return (ibuf != NULL);
1555 }
1556
1557 static void save_image_options_from_op(SaveImageOptions *simopts, wmOperator *op)
1558 {
1559         if (op->customdata) {
1560                 BKE_color_managed_view_settings_free(&simopts->im_format.view_settings);
1561
1562                 simopts->im_format = *(ImageFormatData *)op->customdata;
1563         }
1564
1565         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
1566                 RNA_string_get(op->ptr, "filepath", simopts->filepath);
1567                 BLI_path_abs(simopts->filepath, G.main->name);
1568         }
1569 }
1570
1571 static void save_image_options_to_op(SaveImageOptions *simopts, wmOperator *op)
1572 {
1573         if (op->customdata) {
1574                 BKE_color_managed_view_settings_free(&((ImageFormatData *)op->customdata)->view_settings);
1575
1576                 *(ImageFormatData *)op->customdata = simopts->im_format;
1577         }
1578
1579         RNA_string_set(op->ptr, "filepath", simopts->filepath);
1580 }
1581
1582 static void save_image_post(wmOperator *op, ImBuf *ibuf, Image *ima, int ok, int save_copy, const char *relbase, int relative, int do_newpath, const char *filepath)
1583 {
1584         if (ok) {
1585                 if (!save_copy) {
1586                         ColorManagedColorspaceSettings old_colorspace_settings;
1587
1588                         if (do_newpath) {
1589                                 BLI_strncpy(ibuf->name, filepath, sizeof(ibuf->name));
1590                                 BLI_strncpy(ima->name, filepath, sizeof(ima->name));
1591                         }
1592
1593                         ibuf->userflags &= ~IB_BITMAPDIRTY;
1594
1595                         /* change type? */
1596                         if (ima->type == IMA_TYPE_R_RESULT) {
1597                                 ima->type = IMA_TYPE_IMAGE;
1598
1599                                 /* workaround to ensure the render result buffer is no longer used
1600                                  * by this image, otherwise can crash when a new render result is
1601                                  * created. */
1602                                 if (ibuf->rect && !(ibuf->mall & IB_rect))
1603                                         imb_freerectImBuf(ibuf);
1604                                 if (ibuf->rect_float && !(ibuf->mall & IB_rectfloat))
1605                                         imb_freerectfloatImBuf(ibuf);
1606                                 if (ibuf->zbuf && !(ibuf->mall & IB_zbuf))
1607                                         IMB_freezbufImBuf(ibuf);
1608                                 if (ibuf->zbuf_float && !(ibuf->mall & IB_zbuffloat))
1609                                         IMB_freezbuffloatImBuf(ibuf);
1610                         }
1611                         if (ELEM(ima->source, IMA_SRC_GENERATED, IMA_SRC_VIEWER)) {
1612                                 ima->source = IMA_SRC_FILE;
1613                                 ima->type = IMA_TYPE_IMAGE;
1614                         }
1615
1616                         /* only image path, never ibuf */
1617                         if (relative) {
1618                                 BLI_path_rel(ima->name, relbase); /* only after saving */
1619                         }
1620
1621                         BKE_color_managed_colorspace_settings_copy(&old_colorspace_settings,
1622                                                                    &ima->colorspace_settings);
1623                         IMB_colormanagment_colorspace_from_ibuf_ftype(&ima->colorspace_settings, ibuf);
1624                         if (!BKE_color_managed_colorspace_settings_equals(&old_colorspace_settings,
1625                                                                           &ima->colorspace_settings))
1626                         {
1627                                 BKE_image_signal(ima, NULL, IMA_SIGNAL_COLORMANAGE);
1628                         }
1629                 }
1630         }
1631         else {
1632                 BKE_reportf(op->reports, RPT_ERROR, "Could not write image %s", filepath);
1633         }
1634 }
1635
1636 static void save_imbuf_post(ImBuf *ibuf, ImBuf *colormanaged_ibuf)
1637 {
1638         if (colormanaged_ibuf != ibuf) {
1639                 /* This guys might be modified by image buffer write functions,
1640                  * need to copy them back from color managed image buffer to an
1641                  * original one, so file type of image is being properly updated.
1642                  */
1643                 ibuf->ftype = colormanaged_ibuf->ftype;
1644                 ibuf->foptions = colormanaged_ibuf->foptions;
1645                 ibuf->planes = colormanaged_ibuf->planes;
1646
1647                 IMB_freeImBuf(colormanaged_ibuf);
1648         }
1649 }
1650
1651 /**
1652  * \return success.
1653  * \note ``ima->name`` and ``ibuf->name`` should end up the same.
1654  * \note for multiview the first ``ibuf`` is important to get the settings.
1655  */
1656 static bool save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveImageOptions *simopts, bool do_newpath)
1657 {
1658         Image *ima = ED_space_image(sima);
1659         void *lock;
1660         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
1661         Scene *scene;
1662         RenderResult *rr = NULL;
1663         bool ok = false;
1664
1665         WM_cursor_wait(1);
1666
1667         if (ibuf) {
1668                 ImBuf *colormanaged_ibuf = NULL;
1669                 const char *relbase = ID_BLEND_PATH(CTX_data_main(C), &ima->id);
1670                 const bool relative = (RNA_struct_find_property(op->ptr, "relative_path") && RNA_boolean_get(op->ptr, "relative_path"));
1671                 const bool save_copy = (RNA_struct_find_property(op->ptr, "copy") && RNA_boolean_get(op->ptr, "copy"));
1672                 const bool save_as_render = (RNA_struct_find_property(op->ptr, "save_as_render") && RNA_boolean_get(op->ptr, "save_as_render"));
1673                 ImageFormatData *imf = &simopts->im_format;
1674
1675                 const bool is_multilayer = imf->imtype == R_IMF_IMTYPE_MULTILAYER;
1676                 bool is_mono;
1677
1678                 /* old global to ensure a 2nd save goes to same dir */
1679                 BLI_strncpy(G.ima, simopts->filepath, sizeof(G.ima));
1680
1681                 if (ima->type == IMA_TYPE_R_RESULT) {
1682                         /* enforce user setting for RGB or RGBA, but skip BW */
1683                         if (simopts->im_format.planes == R_IMF_PLANES_RGBA) {
1684                                 ibuf->planes = R_IMF_PLANES_RGBA;
1685                         }
1686                         else if (simopts->im_format.planes == R_IMF_PLANES_RGB) {
1687                                 ibuf->planes = R_IMF_PLANES_RGB;
1688                         }
1689                 }
1690                 else {
1691                         /* TODO, better solution, if a 24bit image is painted onto it may contain alpha */
1692                         if ((simopts->im_format.planes == R_IMF_PLANES_RGBA) &&
1693                             /* it has been painted onto */
1694                             (ibuf->userflags & IB_BITMAPDIRTY))
1695                         {
1696                                 /* checks each pixel, not ideal */
1697                                 ibuf->planes = BKE_imbuf_alpha_test(ibuf) ? R_IMF_PLANES_RGBA : R_IMF_PLANES_RGB;
1698                         }
1699                 }
1700
1701                 /* we need renderresult for exr and rendered multiview */
1702                 scene = CTX_data_scene(C);
1703                 rr = BKE_image_acquire_renderresult(scene, ima);
1704                 is_mono = rr ? BLI_listbase_count_ex(&rr->views, 2) < 2 : BLI_listbase_count_ex(&ima->views, 2) < 2;
1705
1706                 /* error handling */
1707                 if (!rr) {
1708                         if (imf->imtype == R_IMF_IMTYPE_MULTILAYER) {
1709                                 BKE_report(op->reports, RPT_ERROR, "Did not write, no Multilayer Image");
1710                                 goto cleanup;
1711                         }
1712                 }
1713                 else {
1714                         if (imf->views_format == R_IMF_VIEWS_STEREO_3D) {
1715                                 if (!BKE_image_is_stereo(ima)) {
1716                                         BKE_reportf(op->reports, RPT_ERROR, "Did not write, the image doesn't have a \"%s\" and \"%s\" views",
1717                                                    STEREO_LEFT_NAME, STEREO_RIGHT_NAME);
1718                                         goto cleanup;
1719                                 }
1720
1721                                 /* it shouldn't ever happen*/
1722                                 if ((BLI_findstring(&rr->views, STEREO_LEFT_NAME, offsetof(RenderView, name)) == NULL) ||
1723                                     (BLI_findstring(&rr->views, STEREO_RIGHT_NAME, offsetof(RenderView, name)) == NULL))
1724                                 {
1725                                         BKE_reportf(op->reports, RPT_ERROR, "Did not write, the image doesn't have a \"%s\" and \"%s\" views",
1726                                                    STEREO_LEFT_NAME, STEREO_RIGHT_NAME);
1727                                         goto cleanup;
1728                                 }
1729                         }
1730                         BKE_imbuf_stamp_info(rr, ibuf);
1731                 }
1732
1733                 /* fancy multiview OpenEXR */
1734                 if ((imf->imtype == R_IMF_IMTYPE_MULTILAYER) && (imf->views_format == R_IMF_VIEWS_MULTIVIEW)) {
1735                         ok = RE_WriteRenderResult(op->reports, rr, simopts->filepath, imf, true, NULL);
1736                         save_image_post(op, ibuf, ima, ok, true, relbase, relative, do_newpath, simopts->filepath);
1737                         ED_space_image_release_buffer(sima, ibuf, lock);
1738                 }
1739                 else if ((imf->imtype == R_IMF_IMTYPE_OPENEXR) && (imf->views_format == R_IMF_VIEWS_MULTIVIEW)) {
1740                         /* treat special Openexr case separetely (this is the singlelayer multiview OpenEXR */
1741                         BKE_imbuf_write_prepare(ibuf, imf);
1742                         ok = BKE_image_save_openexr_multiview(ima, ibuf, simopts->filepath, (IB_rect | IB_zbuf | IB_zbuffloat | IB_multiview));
1743                         ED_space_image_release_buffer(sima, ibuf, lock);
1744                 }
1745                 /* regular mono pipeline */
1746                 else if (is_mono) {
1747                         if (is_multilayer) {
1748                                 ok = RE_WriteRenderResult(op->reports, rr, simopts->filepath, imf, false, NULL);
1749                         }
1750                         else {
1751                                 colormanaged_ibuf = IMB_colormanagement_imbuf_for_write(ibuf, save_as_render, true, &imf->view_settings, &imf->display_settings, imf);
1752                                 IMB_metadata_copy(colormanaged_ibuf, ibuf);
1753                                 ok = BKE_imbuf_write_as(colormanaged_ibuf, simopts->filepath, imf, save_copy);
1754                                 save_imbuf_post(ibuf, colormanaged_ibuf);
1755                         }
1756                         save_image_post(op, ibuf, ima, ok, (is_multilayer ? true : save_copy), relbase, relative, do_newpath, simopts->filepath);
1757                         ED_space_image_release_buffer(sima, ibuf, lock);
1758                 }
1759                 /* individual multiview images */
1760                 else if (imf->views_format == R_IMF_VIEWS_INDIVIDUAL) {
1761                         int i;
1762                         unsigned char planes = ibuf->planes;
1763                         const int totviews = (rr ? BLI_listbase_count(&rr->views) : BLI_listbase_count(&ima->views));
1764
1765                         if (!is_multilayer) {
1766                                 ED_space_image_release_buffer(sima, ibuf, lock);
1767                         }
1768
1769                         for (i = 0; i < totviews; i++) {
1770                                 char filepath[FILE_MAX];
1771                                 bool ok_view = false;
1772                                 const char *view = rr ? ((RenderView *) BLI_findlink(&rr->views, i))->name :
1773                                                         ((ImageView *) BLI_findlink(&ima->views, i))->name;
1774
1775                                 if (is_multilayer) {
1776                                         BKE_scene_multiview_view_filepath_get(&scene->r, simopts->filepath, view, filepath);
1777                                         ok_view = RE_WriteRenderResult(op->reports, rr, filepath, imf, false, view);
1778                                         save_image_post(op, ibuf, ima, ok_view, true, relbase, relative, do_newpath, filepath);
1779                                 }
1780                                 else {
1781                                         /* copy iuser to get the correct ibuf for this view */
1782                                         ImageUser iuser = sima->iuser;
1783                                         iuser.view = i;
1784                                         iuser.flag &= ~IMA_SHOW_STEREO;
1785
1786                                         if (rr)
1787                                                 BKE_image_multilayer_index(rr, &iuser);
1788                                         else
1789                                                 BKE_image_multiview_index(ima, &iuser);
1790
1791                                         ibuf = BKE_image_acquire_ibuf(sima->image, &iuser, &lock);
1792                                         ibuf->planes = planes;
1793
1794                                         BKE_scene_multiview_view_filepath_get(&scene->r, simopts->filepath, view, filepath);
1795
1796                                         colormanaged_ibuf = IMB_colormanagement_imbuf_for_write(ibuf, save_as_render, true, &imf->view_settings, &imf->display_settings, imf);
1797                                         ok_view = BKE_imbuf_write_as(colormanaged_ibuf, filepath, &simopts->im_format, save_copy);
1798                                         save_imbuf_post(ibuf, colormanaged_ibuf);
1799                                         save_image_post(op, ibuf, ima, ok_view, true, relbase, relative, do_newpath, filepath);
1800                                         BKE_image_release_ibuf(sima->image, ibuf, lock);
1801                                 }
1802                                 ok &= ok_view;
1803                         }
1804
1805                         if (is_multilayer) {
1806                                 ED_space_image_release_buffer(sima, ibuf, lock);
1807                         }
1808                 }
1809                 /* stereo (multiview) images */
1810                 else if (simopts->im_format.views_format == R_IMF_VIEWS_STEREO_3D) {
1811                         if (imf->imtype == R_IMF_IMTYPE_MULTILAYER) {
1812                                 ok = RE_WriteRenderResult(op->reports, rr, simopts->filepath, imf, false, NULL);
1813                                 save_image_post(op, ibuf, ima, ok, true, relbase, relative, do_newpath, simopts->filepath);
1814                                 ED_space_image_release_buffer(sima, ibuf, lock);
1815                         }
1816                         else {
1817                                 ImBuf *ibuf_stereo[2] = {NULL};
1818
1819                                 unsigned char planes = ibuf->planes;
1820                                 const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};
1821                                 int i;
1822
1823                                 /* we need to get the specific per-view buffers */
1824                                 ED_space_image_release_buffer(sima, ibuf, lock);
1825
1826                                 for (i = 0; i < 2; i ++) {
1827                                         ImageUser iuser = sima->iuser;
1828                                         iuser.flag &= ~IMA_SHOW_STEREO;
1829
1830                                         if (rr) {
1831                                                 int id = BLI_findstringindex(&rr->views, names[i], offsetof(RenderView, name));
1832                                                 iuser.view = id;
1833                                                 BKE_image_multilayer_index(rr, &iuser);
1834                                         }
1835                                         else {
1836                                                 iuser.view = i;
1837                                                 BKE_image_multiview_index(ima, &iuser);
1838                                         }
1839
1840                                         ibuf = BKE_image_acquire_ibuf(sima->image, &iuser, &lock);
1841
1842                                         if (ibuf == NULL) {
1843                                                 BKE_report(op->reports, RPT_ERROR, "Did not write, unexpected error when saving stereo image");
1844                                                 goto cleanup;
1845                                         }
1846
1847                                         ibuf->planes = planes;
1848
1849                                         /* color manage the ImBuf leaving it ready for saving */
1850                                         colormanaged_ibuf = IMB_colormanagement_imbuf_for_write(ibuf, save_as_render, true,
1851                                                                                                 &imf->view_settings, &imf->display_settings, imf);
1852
1853                                         BKE_imbuf_write_prepare(colormanaged_ibuf, imf);
1854                                         IMB_prepare_write_ImBuf(IMB_isfloat(colormanaged_ibuf), colormanaged_ibuf);
1855
1856                                         /* duplicate buffer to prevent locker issue when using render result */
1857                                         ibuf_stereo[i] = IMB_dupImBuf(colormanaged_ibuf);
1858
1859                                         save_imbuf_post(ibuf, colormanaged_ibuf);
1860                                         BKE_image_release_ibuf(sima->image, ibuf, lock);
1861                                 }
1862
1863                                 ibuf = IMB_stereo3d_ImBuf(imf, ibuf_stereo[0], ibuf_stereo[1]);
1864
1865                                 /* save via traditional path */
1866                                 ok = BKE_imbuf_write_as(ibuf, simopts->filepath, imf, save_copy);
1867
1868                                 IMB_freeImBuf(ibuf);
1869
1870                                 for (i = 0; i < 2; i ++) {
1871                                         IMB_freeImBuf(ibuf_stereo[i]);
1872                                 }
1873                         }
1874                 }
1875
1876                 WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
1877
1878         }
1879         else {
1880 cleanup:
1881                 ED_space_image_release_buffer(sima, ibuf, lock);
1882         }
1883
1884         if (rr) {
1885                 BKE_image_release_renderresult(scene, ima);
1886         }
1887
1888         WM_cursor_wait(0);
1889
1890         return ok;
1891 }
1892
1893 static void image_save_as_free(wmOperator *op)
1894 {
1895         if (op->customdata) {
1896                 ImageFormatData *im_format = (ImageFormatData *)op->customdata;
1897                 BKE_color_managed_view_settings_free(&im_format->view_settings);
1898
1899                 MEM_freeN(op->customdata);
1900                 op->customdata = NULL;
1901         }
1902 }
1903
1904 static int image_save_as_exec(bContext *C, wmOperator *op)
1905 {
1906         SpaceImage *sima = CTX_wm_space_image(C);
1907         SaveImageOptions simopts;
1908
1909         save_image_options_defaults(&simopts);
1910
1911         /* just in case to initialize values,
1912          * these should be set on invoke or by the caller. */
1913         save_image_options_init(&simopts, sima, CTX_data_scene(C), false, false);
1914
1915         save_image_options_from_op(&simopts, op);
1916
1917         save_image_doit(C, sima, op, &simopts, true);
1918
1919         image_save_as_free(op);
1920         return OPERATOR_FINISHED;
1921 }
1922
1923
1924 static bool image_save_as_check(bContext *UNUSED(C), wmOperator *op)
1925 {
1926         ImageFormatData *imf = op->customdata;
1927         return WM_operator_filesel_ensure_ext_imtype(op, imf);
1928 }
1929
1930 static int image_save_as_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1931 {
1932         SpaceImage *sima = CTX_wm_space_image(C);
1933         Image *ima = ED_space_image(sima);
1934         Scene *scene = CTX_data_scene(C);
1935         SaveImageOptions simopts;
1936         PropertyRNA *prop;
1937         const bool save_as_render = ((ima->source == IMA_SRC_VIEWER) || (ima->flag & IMA_VIEW_AS_RENDER));
1938
1939         if (RNA_struct_property_is_set(op->ptr, "filepath"))
1940                 return image_save_as_exec(C, op);
1941
1942         save_image_options_defaults(&simopts);
1943
1944         if (save_image_options_init(&simopts, sima, scene, true, save_as_render) == 0)
1945                 return OPERATOR_CANCELLED;
1946         save_image_options_to_op(&simopts, op);
1947
1948         /* enable save_copy by default for render results */
1949         if (ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE) && !RNA_struct_property_is_set(op->ptr, "copy")) {
1950                 RNA_boolean_set(op->ptr, "copy", true);
1951         }
1952
1953         RNA_boolean_set(op->ptr, "save_as_render", save_as_render);
1954
1955         op->customdata = MEM_mallocN(sizeof(simopts.im_format), __func__);
1956         memcpy(op->customdata, &simopts.im_format, sizeof(simopts.im_format));
1957
1958         /* show multiview save options only if image has multiviews */
1959         prop = RNA_struct_find_property(op->ptr, "show_multiview");
1960         RNA_property_boolean_set(op->ptr, prop, BKE_image_is_multiview(ima));
1961         prop = RNA_struct_find_property(op->ptr, "use_multiview");
1962         RNA_property_boolean_set(op->ptr, prop, BKE_image_is_multiview(ima));
1963
1964         image_filesel(C, op, simopts.filepath);
1965
1966         return OPERATOR_RUNNING_MODAL;
1967 }
1968
1969 static void image_save_as_cancel(bContext *UNUSED(C), wmOperator *op)
1970 {
1971         image_save_as_free(op);
1972 }
1973
1974 static bool image_save_as_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop)
1975 {
1976         const char *prop_id = RNA_property_identifier(prop);
1977
1978         return !(STREQ(prop_id, "filepath") ||
1979                  STREQ(prop_id, "directory") ||
1980                  STREQ(prop_id, "filename") ||
1981                  /* when saving a copy, relative path has no effect */
1982                  ((STREQ(prop_id, "relative_path")) && RNA_boolean_get(ptr, "copy"))
1983                  );
1984 }
1985
1986 static void image_save_as_draw(bContext *UNUSED(C), wmOperator *op)
1987 {
1988         uiLayout *layout = op->layout;
1989         ImageFormatData *imf = op->customdata;
1990         PointerRNA imf_ptr, ptr;
1991         const bool is_multiview = RNA_boolean_get(op->ptr, "show_multiview");
1992
1993         /* image template */
1994         RNA_pointer_create(NULL, &RNA_ImageFormatSettings, imf, &imf_ptr);
1995         uiTemplateImageSettings(layout, &imf_ptr, false);
1996
1997         /* main draw call */
1998         RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);
1999         uiDefAutoButsRNA(layout, &ptr, image_save_as_draw_check_prop, '\0');
2000
2001         /* multiview template */
2002         if (is_multiview)
2003                 uiTemplateImageFormatViews(layout, &imf_ptr, op->ptr);
2004 }
2005
2006 static int image_save_as_poll(bContext *C)
2007 {
2008         if (space_image_buffer_exists_poll(C)) {
2009                 if (G.is_rendering) {
2010                         /* no need to NULL check here */
2011                         SpaceImage *sima = CTX_wm_space_image(C);
2012                         Image *ima = ED_space_image(sima);
2013
2014                         if (ima->source == IMA_SRC_VIEWER) {
2015                                 CTX_wm_operator_poll_msg_set(C, "can't save image while rendering");
2016                                 return false;
2017                         }
2018                 }
2019                 return true;
2020         }
2021         return false;
2022 }
2023
2024 void IMAGE_OT_save_as(wmOperatorType *ot)
2025 {
2026         /* identifiers */
2027         ot->name = "Save As Image";
2028         ot->idname = "IMAGE_OT_save_as";
2029         ot->description = "Save the image with another name and/or settings";
2030         
2031         /* api callbacks */
2032         ot->exec = image_save_as_exec;
2033         ot->check = image_save_as_check;
2034         ot->invoke = image_save_as_invoke;
2035         ot->cancel = image_save_as_cancel;
2036         ot->ui = image_save_as_draw;
2037         ot->poll = image_save_as_poll;
2038
2039         /* flags */
2040         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2041
2042         /* properties */
2043         RNA_def_boolean(ot->srna, "save_as_render", 0, "Save As Render", "Apply render part of display transform when saving byte image");
2044         RNA_def_boolean(ot->srna, "copy", 0, "Copy", "Create a new image file without modifying the current image in blender");
2045
2046         WM_operator_properties_filesel(ot, FILE_TYPE_FOLDER | FILE_TYPE_IMAGE | FILE_TYPE_MOVIE, FILE_SPECIAL, FILE_SAVE,
2047                                        WM_FILESEL_FILEPATH | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
2048 }
2049
2050 /******************** save image operator ********************/
2051
2052 static int image_save_exec(bContext *C, wmOperator *op)
2053 {
2054         SpaceImage *sima = CTX_wm_space_image(C);
2055         Scene *scene = CTX_data_scene(C);
2056         SaveImageOptions simopts;
2057
2058         save_image_options_defaults(&simopts);
2059         if (save_image_options_init(&simopts, sima, scene, false, false) == 0)
2060                 return OPERATOR_CANCELLED;
2061         save_image_options_from_op(&simopts, op);
2062
2063         if (BLI_exists(simopts.filepath) && BLI_file_is_writable(simopts.filepath)) {
2064                 if (save_image_doit(C, sima, op, &simopts, false)) {
2065                         /* report since this can be called from key-shortcuts */
2066                         BKE_reportf(op->reports, RPT_INFO, "Saved Image '%s'", simopts.filepath);
2067                 }
2068         }
2069         else {
2070                 BKE_reportf(op->reports, RPT_ERROR, "Cannot save image, path '%s' is not writable", simopts.filepath);
2071                 return OPERATOR_CANCELLED;
2072         }
2073
2074         return OPERATOR_FINISHED;
2075 }
2076
2077 void IMAGE_OT_save(wmOperatorType *ot)
2078 {
2079         /* identifiers */
2080         ot->name = "Save Image";
2081         ot->idname = "IMAGE_OT_save";
2082         ot->description = "Save the image with current name and settings";
2083         
2084         /* api callbacks */
2085         ot->exec = image_save_exec;
2086         ot->poll = space_image_file_exists_poll;
2087
2088         /* flags */
2089         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2090 }
2091
2092 /******************* save sequence operator ********************/
2093
2094 static int image_save_sequence_exec(bContext *C, wmOperator *op)
2095 {
2096         Main *bmain = CTX_data_main(C);
2097         SpaceImage *sima = CTX_wm_space_image(C);
2098         ImBuf *ibuf, *first_ibuf = NULL;
2099         int tot = 0;
2100         char di[FILE_MAX];
2101         struct MovieCacheIter *iter;
2102         
2103         if (sima->image == NULL)
2104                 return OPERATOR_CANCELLED;
2105
2106         if (sima->image->source != IMA_SRC_SEQUENCE) {
2107                 BKE_report(op->reports, RPT_ERROR, "Can only save sequence on image sequences");
2108                 return OPERATOR_CANCELLED;
2109         }
2110
2111         if (sima->image->type == IMA_TYPE_MULTILAYER) {
2112                 BKE_report(op->reports, RPT_ERROR, "Cannot save multilayer sequences");
2113                 return OPERATOR_CANCELLED;
2114         }
2115         
2116         /* get total dirty buffers and first dirty buffer which is used for menu */
2117         ibuf = NULL;
2118         if (sima->image->cache != NULL) {
2119                 iter = IMB_moviecacheIter_new(sima->image->cache);
2120                 while (!IMB_moviecacheIter_done(iter)) {
2121                         ibuf = IMB_moviecacheIter_getImBuf(iter);
2122                         if (ibuf->userflags & IB_BITMAPDIRTY) {
2123                                 if (first_ibuf == NULL) {
2124                                         first_ibuf = ibuf;
2125                                 }
2126                                 tot++;
2127                         }
2128                         IMB_moviecacheIter_step(iter);
2129                 }
2130                 IMB_moviecacheIter_free(iter);
2131         }
2132         
2133         if (tot == 0) {
2134                 BKE_report(op->reports, RPT_WARNING, "No images have been changed");
2135                 return OPERATOR_CANCELLED;
2136         }
2137
2138         /* get a filename for menu */
2139         BLI_split_dir_part(first_ibuf->name, di, sizeof(di));
2140         BKE_reportf(op->reports, RPT_INFO, "%d image(s) will be saved in %s", tot, di);
2141
2142         iter = IMB_moviecacheIter_new(sima->image->cache);
2143         while (!IMB_moviecacheIter_done(iter)) {
2144                 ibuf = IMB_moviecacheIter_getImBuf(iter);
2145
2146                 if (ibuf->userflags & IB_BITMAPDIRTY) {
2147                         char name[FILE_MAX];
2148                         BLI_strncpy(name, ibuf->name, sizeof(name));
2149
2150                         BLI_path_abs(name, bmain->name);
2151
2152                         if (0 == IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat)) {
2153                                 BKE_reportf(op->reports, RPT_ERROR, "Could not write image %s", name);
2154                                 break;
2155                         }
2156
2157                         BKE_reportf(op->reports, RPT_INFO, "Saved %s", ibuf->name);
2158                         ibuf->userflags &= ~IB_BITMAPDIRTY;
2159                 }
2160
2161                 IMB_moviecacheIter_step(iter);
2162         }
2163         IMB_moviecacheIter_free(iter);
2164
2165         return OPERATOR_FINISHED;
2166 }
2167
2168 void IMAGE_OT_save_sequence(wmOperatorType *ot)
2169 {
2170         /* identifiers */
2171         ot->name = "Save Sequence";
2172         ot->idname = "IMAGE_OT_save_sequence";
2173         ot->description = "Save a sequence of images";
2174         
2175         /* api callbacks */
2176         ot->exec = image_save_sequence_exec;
2177         ot->poll = space_image_buffer_exists_poll;
2178
2179         /* flags */
2180         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2181 }
2182
2183 /******************** reload image operator ********************/
2184
2185 static int image_reload_exec(bContext *C, wmOperator *UNUSED(op))
2186 {
2187         Image *ima = CTX_data_edit_image(C);
2188         SpaceImage *sima = CTX_wm_space_image(C);
2189
2190         if (!ima)
2191                 return OPERATOR_CANCELLED;
2192
2193         /* XXX unpackImage frees image buffers */
2194         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
2195         
2196         // XXX other users?
2197         BKE_image_signal(ima, (sima) ? &sima->iuser : NULL, IMA_SIGNAL_RELOAD);
2198         DAG_id_tag_update(&ima->id, 0);
2199
2200         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
2201         
2202         return OPERATOR_FINISHED;
2203 }
2204
2205 void IMAGE_OT_reload(wmOperatorType *ot)
2206 {
2207         /* identifiers */
2208         ot->name = "Reload Image";
2209         ot->idname = "IMAGE_OT_reload";
2210         ot->description = "Reload current image from disk";
2211         
2212         /* api callbacks */
2213         ot->exec = image_reload_exec;
2214
2215         /* flags */
2216         ot->flag = OPTYPE_REGISTER; /* no undo, image buffer is not handled by undo */
2217 }
2218
2219 /********************** new image operator *********************/
2220 #define IMA_DEF_NAME N_("Untitled")
2221
2222 enum {
2223         GEN_CONTEXT_NONE = 0,
2224         GEN_CONTEXT_PAINT_CANVAS = 1,
2225         GEN_CONTEXT_PAINT_STENCIL = 2
2226 };
2227
2228 static int image_new_exec(bContext *C, wmOperator *op)
2229 {
2230         SpaceImage *sima;
2231         Scene *scene;
2232         Object *obedit;
2233         Image *ima;
2234         Main *bmain;
2235         PointerRNA ptr, idptr;
2236         PropertyRNA *prop;
2237         char _name[MAX_ID_NAME - 2];
2238         char *name = _name;
2239         float color[4];
2240         int width, height, floatbuf, gen_type, alpha;
2241         int gen_context;
2242         int stereo3d;
2243
2244         /* retrieve state */
2245         sima = CTX_wm_space_image(C);
2246         scene = CTX_data_scene(C);
2247         obedit = CTX_data_edit_object(C);
2248         bmain = CTX_data_main(C);
2249
2250         prop = RNA_struct_find_property(op->ptr, "name");
2251         RNA_property_string_get(op->ptr, prop, name);
2252         if (!RNA_property_is_set(op->ptr, prop)) {
2253                 /* Default value, we can translate! */
2254                 name = (char *)DATA_(name);
2255         }
2256         width = RNA_int_get(op->ptr, "width");
2257         height = RNA_int_get(op->ptr, "height");
2258         floatbuf = RNA_boolean_get(op->ptr, "float");
2259         gen_type = RNA_enum_get(op->ptr, "generated_type");
2260         RNA_float_get_array(op->ptr, "color", color);
2261         alpha = RNA_boolean_get(op->ptr, "alpha");
2262         gen_context = RNA_enum_get(op->ptr, "gen_context");
2263         stereo3d = RNA_boolean_get(op->ptr, "use_stereo_3d");
2264
2265         if (!alpha)
2266                 color[3] = 1.0f;
2267
2268         ima = BKE_image_add_generated(bmain, width, height, name, alpha ? 32 : 24, floatbuf, gen_type, color, stereo3d);
2269
2270         if (!ima)
2271                 return OPERATOR_CANCELLED;
2272
2273         /* hook into UI */
2274         UI_context_active_but_prop_get_templateID(C, &ptr, &prop);
2275
2276         if (prop) {
2277                 /* when creating new ID blocks, use is already 1, but RNA
2278                  * pointer se also increases user, so this compensates it */
2279                 id_us_min(&ima->id);
2280
2281                 RNA_id_pointer_create(&ima->id, &idptr);
2282                 RNA_property_pointer_set(&ptr, prop, idptr);
2283                 RNA_property_update(C, &ptr, prop);
2284         }
2285         else if (sima) {
2286                 ED_space_image_set(sima, scene, obedit, ima);
2287         }
2288         else if (gen_context == GEN_CONTEXT_PAINT_CANVAS) {
2289                 bScreen *sc;
2290                 Object *ob = CTX_data_active_object(C);
2291                 
2292                 GPU_drawobject_free(ob->derivedFinal);  
2293                 if (scene->toolsettings->imapaint.canvas)
2294                         id_us_min(&scene->toolsettings->imapaint.canvas->id);
2295                 scene->toolsettings->imapaint.canvas = ima;
2296                 
2297                 for (sc = bmain->screen.first; sc; sc = sc->id.next) {
2298                         ScrArea *sa;
2299                         for (sa = sc->areabase.first; sa; sa = sa->next) {
2300                                 SpaceLink *sl;
2301                                 for (sl = sa->spacedata.first; sl; sl = sl->next) {
2302                                         if (sl->spacetype == SPACE_IMAGE) {
2303                                                 SpaceImage *sima = (SpaceImage *)sl;
2304                                                 
2305                                                 if (!sima->pin)
2306                                                         ED_space_image_set(sima, scene, scene->obedit, ima);
2307                                         }
2308                                 }
2309                         }
2310                 }
2311                 BKE_paint_proj_mesh_data_check(scene, ob, NULL, NULL, NULL, NULL);
2312                 WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, NULL);
2313         }
2314         else if (gen_context == GEN_CONTEXT_PAINT_STENCIL) {
2315                 Object *ob = CTX_data_active_object(C);
2316                 if (scene->toolsettings->imapaint.stencil)
2317                         id_us_min(&scene->toolsettings->imapaint.stencil->id);
2318                 scene->toolsettings->imapaint.stencil = ima;
2319                 BKE_paint_proj_mesh_data_check(scene, ob, NULL, NULL, NULL, NULL);      
2320                 WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, NULL);             
2321         }
2322         else {
2323                 Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
2324                 if (tex && tex->type == TEX_IMAGE) {
2325                         if (tex->ima)
2326                                 id_us_min(&tex->ima->id);
2327                         tex->ima = ima;
2328                         ED_area_tag_redraw(CTX_wm_area(C));
2329                 }
2330         }
2331
2332         BKE_image_signal(ima, (sima) ? &sima->iuser : NULL, IMA_SIGNAL_USER_NEW_IMAGE);
2333         
2334         WM_event_add_notifier(C, NC_IMAGE | NA_ADDED, ima);
2335         
2336         return OPERATOR_FINISHED;
2337 }
2338
2339 /* XXX, Ton is not a fan of OK buttons but using this function to avoid undo/redo bug while in mesh-editmode, - campbell */
2340 /* XXX Note: the WM_operator_props_dialog_popup() doesn't work for UI_context_active_but_prop_get_templateID(), image is not being that way */
2341 static int image_new_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2342 {
2343         /* Better for user feedback. */
2344         RNA_string_set(op->ptr, "name", DATA_(IMA_DEF_NAME));
2345         return WM_operator_props_dialog_popup(C, op, 15 * UI_UNIT_X, 5 * UI_UNIT_Y);
2346 }
2347
2348 static void image_new_draw(bContext *UNUSED(C), wmOperator *op)
2349 {
2350         uiLayout *split, *col[2];
2351         uiLayout *layout = op->layout;
2352         PointerRNA ptr;
2353 #if 0
2354         Scene *scene = CTX_data_scene(C);
2355         const bool is_multiview = (scene->r.scemode & R_MULTIVIEW) != 0;
2356 #endif
2357
2358         RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);
2359
2360         /* copy of WM_operator_props_dialog_popup() layout */
2361
2362         split = uiLayoutSplit(layout, 0.5f, false);
2363         col[0] = uiLayoutColumn(split, false);
2364         col[1] = uiLayoutColumn(split, false);
2365
2366         uiItemL(col[0], IFACE_("Name"), ICON_NONE);
2367         uiItemR(col[1], &ptr, "name", 0, "", ICON_NONE);
2368
2369         uiItemL(col[0], IFACE_("Width"), ICON_NONE);
2370         uiItemR(col[1], &ptr, "width", 0, "", ICON_NONE);
2371
2372         uiItemL(col[0], IFACE_("Height"), ICON_NONE);
2373         uiItemR(col[1], &ptr, "height", 0, "", ICON_NONE);
2374
2375         uiItemL(col[0], IFACE_("Color"), ICON_NONE);
2376         uiItemR(col[1], &ptr, "color", 0, "", ICON_NONE);
2377
2378         uiItemL(col[0], "", ICON_NONE);
2379         uiItemR(col[1], &ptr, "alpha", 0, NULL, ICON_NONE);
2380
2381         uiItemL(col[0], IFACE_("Generated Type"), ICON_NONE);
2382         uiItemR(col[1], &ptr, "generated_type", 0, "", ICON_NONE);
2383
2384         uiItemL(col[0], "", ICON_NONE);
2385         uiItemR(col[1], &ptr, "float", 0, NULL, ICON_NONE);
2386
2387 #if 0
2388         if (is_multiview) {
2389                 uiItemL(col[0], "", ICON_NONE);
2390                 uiItemR(col[1], &ptr, "use_stereo_3d", 0, NULL, ICON_NONE);
2391         }
2392 #endif
2393 }
2394
2395 void IMAGE_OT_new(wmOperatorType *ot)
2396 {
2397         PropertyRNA *prop;
2398         static float default_color[4] = {0.0f, 0.0f, 0.0f, 1.0f};
2399
2400         static EnumPropertyItem gen_context_items[] = {
2401                 {GEN_CONTEXT_NONE, "NONE", 0, "None", ""},
2402                 {GEN_CONTEXT_PAINT_CANVAS, "PAINT_CANVAS", 0, "Paint Canvas", ""},
2403             {GEN_CONTEXT_PAINT_STENCIL, "PAINT_STENCIL", 0, "Paint Stencil", ""},
2404                 {0, NULL, 0, NULL, NULL}
2405         };
2406         
2407         /* identifiers */
2408         ot->name = "New Image";
2409         ot->description = "Create a new image";
2410         ot->idname = "IMAGE_OT_new";
2411         
2412         /* api callbacks */
2413         ot->exec = image_new_exec;
2414         ot->invoke = image_new_invoke;
2415         ot->ui = image_new_draw;
2416         
2417         /* flags */
2418         ot->flag = OPTYPE_UNDO;
2419
2420         /* properties */
2421         RNA_def_string(ot->srna, "name", IMA_DEF_NAME, MAX_ID_NAME - 2, "Name", "Image datablock name");
2422         prop = RNA_def_int(ot->srna, "width", 1024, 1, INT_MAX, "Width", "Image width", 1, 16384);
2423         RNA_def_property_subtype(prop, PROP_PIXEL);
2424         prop = RNA_def_int(ot->srna, "height", 1024, 1, INT_MAX, "Height", "Image height", 1, 16384);
2425         RNA_def_property_subtype(prop, PROP_PIXEL);
2426         prop = RNA_def_float_color(ot->srna, "color", 4, NULL, 0.0f, FLT_MAX, "Color", "Default fill color", 0.0f, 1.0f);
2427         RNA_def_property_subtype(prop, PROP_COLOR_GAMMA);
2428         RNA_def_property_float_array_default(prop, default_color);
2429         RNA_def_boolean(ot->srna, "alpha", 1, "Alpha", "Create an image with an alpha channel");
2430         RNA_def_enum(ot->srna, "generated_type", rna_enum_image_generated_type_items, IMA_GENTYPE_BLANK,
2431                      "Generated Type", "Fill the image with a grid for UV map testing");
2432         RNA_def_boolean(ot->srna, "float", 0, "32 bit Float", "Create image with 32 bit floating point bit depth");
2433         prop = RNA_def_enum(ot->srna, "gen_context", gen_context_items, 0, "Gen Context", "Generation context");
2434         RNA_def_property_flag(prop, PROP_HIDDEN);
2435         prop = RNA_def_boolean(ot->srna, "use_stereo_3d", 0, "Stereo 3D", "Create an image with left and right views");
2436         RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
2437 }
2438
2439 #undef IMA_DEF_NAME
2440
2441 /********************* invert operators *********************/
2442
2443 static int image_invert_poll(bContext *C)
2444 {
2445         Image *ima = CTX_data_edit_image(C);
2446
2447         return BKE_image_has_ibuf(ima, NULL);
2448 }
2449
2450 static int image_invert_exec(bContext *C, wmOperator *op)
2451 {
2452         Image *ima = CTX_data_edit_image(C);
2453         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
2454         SpaceImage *sima = CTX_wm_space_image(C);
2455         /* undo is supported only on image paint mode currently */
2456         bool support_undo = ((sima != NULL) && (sima->mode == SI_MODE_PAINT));
2457
2458         /* flags indicate if this channel should be inverted */
2459         const bool r = RNA_boolean_get(op->ptr, "invert_r");
2460         const bool g = RNA_boolean_get(op->ptr, "invert_g");
2461         const bool b = RNA_boolean_get(op->ptr, "invert_b");
2462         const bool a = RNA_boolean_get(op->ptr, "invert_a");
2463
2464         size_t i;
2465
2466         if (ibuf == NULL)  /* TODO: this should actually never happen, but does for render-results -> cleanup */
2467                 return OPERATOR_CANCELLED;
2468
2469         if (support_undo) {
2470                 ED_undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
2471                                          ED_image_undo_restore, ED_image_undo_free, NULL);
2472                 /* not strictly needed, because we only imapaint_dirty_region to invalidate all tiles
2473                  * but better do this right in case someone copies this for a tool that uses partial redraw better */
2474                 ED_imapaint_clear_partial_redraw();
2475                 ED_imapaint_dirty_region(ima, ibuf, 0, 0, ibuf->x, ibuf->y, false);
2476         }
2477         /* TODO: make this into an IMB_invert_channels(ibuf,r,g,b,a) method!? */
2478         if (ibuf->rect_float) {
2479                 
2480                 float *fp = (float *) ibuf->rect_float;
2481                 for (i = ((size_t)ibuf->x) * ibuf->y; i > 0; i--, fp += 4) {
2482                         if (r) fp[0] = 1.0f - fp[0];
2483                         if (g) fp[1] = 1.0f - fp[1];
2484                         if (b) fp[2] = 1.0f - fp[2];
2485                         if (a) fp[3] = 1.0f - fp[3];
2486                 }
2487
2488                 if (ibuf->rect) {
2489                         IMB_rect_from_float(ibuf);
2490                 }
2491         }
2492         else if (ibuf->rect) {
2493                 
2494                 char *cp = (char *) ibuf->rect;
2495                 for (i = ((size_t)ibuf->x) * ibuf->y; i > 0; i--, cp += 4) {
2496                         if (r) cp[0] = 255 - cp[0];
2497                         if (g) cp[1] = 255 - cp[1];
2498                         if (b) cp[2] = 255 - cp[2];
2499                         if (a) cp[3] = 255 - cp[3];
2500                 }
2501         }
2502         else {
2503                 BKE_image_release_ibuf(ima, ibuf, NULL);
2504                 return OPERATOR_CANCELLED;
2505         }
2506
2507         ibuf->userflags |= IB_BITMAPDIRTY | IB_DISPLAY_BUFFER_INVALID;
2508
2509         if (ibuf->mipmap[0])
2510                 ibuf->userflags |= IB_MIPMAP_INVALID;
2511
2512         if (support_undo)
2513                 ED_undo_paint_push_end(UNDO_PAINT_IMAGE);
2514
2515         /* force GPU reupload, all image is invalid */
2516         GPU_free_image(ima);
2517
2518         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
2519
2520         BKE_image_release_ibuf(ima, ibuf, NULL);
2521
2522         return OPERATOR_FINISHED;
2523 }
2524
2525 void IMAGE_OT_invert(wmOperatorType *ot)
2526 {
2527         PropertyRNA *prop;
2528
2529         /* identifiers */
2530         ot->name = "Invert Channels";
2531         ot->idname = "IMAGE_OT_invert";
2532         ot->description = "Invert image's channels";
2533         
2534         /* api callbacks */
2535         ot->exec = image_invert_exec;
2536         ot->poll = image_invert_poll;
2537         
2538         /* properties */
2539         prop = RNA_def_boolean(ot->srna, "invert_r", 0, "Red", "Invert Red Channel");
2540         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2541         prop = RNA_def_boolean(ot->srna, "invert_g", 0, "Green", "Invert Green Channel");
2542         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2543         prop = RNA_def_boolean(ot->srna, "invert_b", 0, "Blue", "Invert Blue Channel");
2544         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2545         prop = RNA_def_boolean(ot->srna, "invert_a", 0, "Alpha", "Invert Alpha Channel");
2546         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2547         
2548         /* flags */
2549         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2550 }
2551
2552 /********************* pack operator *********************/
2553
2554 static bool image_pack_test(bContext *C, wmOperator *op)
2555 {
2556         Image *ima = CTX_data_edit_image(C);
2557         const bool as_png = RNA_boolean_get(op->ptr, "as_png");
2558
2559         if (!ima)
2560                 return 0;
2561         if (!as_png && BKE_image_has_packedfile(ima))
2562                 return 0;
2563
2564         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
2565                 BKE_report(op->reports, RPT_ERROR, "Packing movies or image sequences not supported");
2566                 return 0;
2567         }
2568
2569         return 1;
2570 }
2571
2572 static int image_pack_exec(bContext *C, wmOperator *op)
2573 {
2574         struct Main *bmain = CTX_data_main(C);
2575         Image *ima = CTX_data_edit_image(C);
2576         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
2577         const bool as_png = RNA_boolean_get(op->ptr, "as_png");
2578
2579         if (!image_pack_test(C, op))
2580                 return OPERATOR_CANCELLED;
2581         
2582         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
2583                 BKE_report(op->reports, RPT_ERROR, "Cannot pack edited image from disk, only as internal PNG");
2584                 return OPERATOR_CANCELLED;
2585         }
2586
2587         if (as_png)
2588                 BKE_image_memorypack(ima);
2589         else
2590                 BKE_image_packfiles(op->reports, ima, ID_BLEND_PATH(bmain, &ima->id));
2591
2592         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
2593
2594         BKE_image_release_ibuf(ima, ibuf, NULL);
2595
2596         return OPERATOR_FINISHED;
2597 }
2598
2599 static int image_pack_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2600 {
2601         Image *ima = CTX_data_edit_image(C);
2602         ImBuf *ibuf;
2603         uiPopupMenu *pup;
2604         uiLayout *layout;
2605         const bool as_png = RNA_boolean_get(op->ptr, "as_png");
2606
2607         if (!image_pack_test(C, op))
2608                 return OPERATOR_CANCELLED;
2609
2610         ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
2611
2612         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
2613                 pup = UI_popup_menu_begin(C, IFACE_("OK"), ICON_QUESTION);
2614                 layout = UI_popup_menu_layout(pup);
2615                 uiItemBooleanO(layout, IFACE_("Can't pack edited image from disk, pack as internal PNG?"), ICON_NONE,
2616                                op->idname, "as_png", 1);
2617                 UI_popup_menu_end(C, pup);
2618
2619                 BKE_image_release_ibuf(ima, ibuf, NULL);
2620
2621                 return OPERATOR_INTERFACE;
2622         }
2623
2624         BKE_image_release_ibuf(ima, ibuf, NULL);
2625
2626         return image_pack_exec(C, op);
2627 }
2628
2629 void IMAGE_OT_pack(wmOperatorType *ot)
2630 {
2631         /* identifiers */
2632         ot->name = "Pack Image";
2633         ot->description = "Pack an image as embedded data into the .blend file"; 
2634         ot->idname = "IMAGE_OT_pack";
2635         
2636         /* api callbacks */
2637         ot->exec = image_pack_exec;
2638         ot->invoke = image_pack_invoke;
2639
2640         /* flags */
2641         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2642
2643         /* properties */
2644         RNA_def_boolean(ot->srna, "as_png", 0, "Pack As PNG", "Pack image as lossless PNG");
2645 }
2646
2647 /********************* unpack operator *********************/
2648
2649 static int image_unpack_exec(bContext *C, wmOperator *op)
2650 {
2651         Image *ima = CTX_data_edit_image(C);
2652         int method = RNA_enum_get(op->ptr, "method");
2653
2654         /* find the suppplied image by name */
2655         if (RNA_struct_property_is_set(op->ptr, "id")) {
2656                 char imaname[MAX_ID_NAME - 2];
2657                 RNA_string_get(op->ptr, "id", imaname);
2658                 ima = BLI_findstring(&CTX_data_main(C)->image, imaname, offsetof(ID, name) + 2);
2659                 if (!ima) ima = CTX_data_edit_image(C);
2660         }
2661         
2662         if (!ima || !BKE_image_has_packedfile(ima))
2663                 return OPERATOR_CANCELLED;
2664
2665         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
2666                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
2667                 return OPERATOR_CANCELLED;
2668         }
2669
2670         if (G.fileflags & G_AUTOPACK)
2671                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
2672         
2673         /* XXX unpackImage frees image buffers */
2674         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
2675         
2676         unpackImage(op->reports, ima, method);
2677         
2678         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
2679
2680         return OPERATOR_FINISHED;
2681 }
2682
2683 static int image_unpack_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2684 {
2685         Image *ima = CTX_data_edit_image(C);
2686
2687         if (RNA_struct_property_is_set(op->ptr, "id"))
2688                 return image_unpack_exec(C, op);
2689                 
2690         if (!ima || !BKE_image_has_packedfile(ima))
2691                 return OPERATOR_CANCELLED;
2692
2693         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
2694                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
2695                 return OPERATOR_CANCELLED;
2696         }
2697
2698         if (G.fileflags & G_AUTOPACK)
2699                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
2700
2701         unpack_menu(C, "IMAGE_OT_unpack", ima->id.name + 2, ima->name, "textures", BKE_image_has_packedfile(ima) ? ((ImagePackedFile *)ima->packedfiles.first)->packedfile : NULL);
2702
2703         return OPERATOR_FINISHED;
2704 }
2705
2706 void IMAGE_OT_unpack(wmOperatorType *ot)
2707 {
2708         /* identifiers */
2709         ot->name = "Unpack Image";
2710         ot->description = "Save an image packed in the .blend file to disk"; 
2711         ot->idname = "IMAGE_OT_unpack";
2712         
2713         /* api callbacks */
2714         ot->exec = image_unpack_exec;
2715         ot->invoke = image_unpack_invoke;
2716
2717         /* flags */
2718         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2719         
2720         /* properties */
2721         RNA_def_enum(ot->srna, "method", rna_enum_unpack_method_items, PF_USE_LOCAL, "Method", "How to unpack");
2722         RNA_def_string(ot->srna, "id", NULL, MAX_ID_NAME - 2, "Image Name", "Image datablock name to unpack"); /* XXX, weark!, will fail with library, name collisions */
2723 }
2724
2725 /******************** sample image operator ********************/
2726
2727 typedef struct ImageSampleInfo {
2728         ARegionType *art;
2729         void *draw_handle;
2730         int x, y;
2731         int channels;
2732
2733         unsigned char col[4];
2734         float colf[4];
2735         float linearcol[4];
2736         int z;
2737         float zf;
2738
2739         unsigned char *colp;
2740         const float *colfp;
2741         int *zp;
2742         float *zfp;
2743
2744         int draw;
2745         int color_manage;
2746         int use_default_view;
2747 } ImageSampleInfo;
2748
2749 static void image_sample_draw(const bContext *C, ARegion *ar, void *arg_info)
2750 {
2751         ImageSampleInfo *info = arg_info;
2752         if (info->draw) {
2753                 Scene *scene = CTX_data_scene(C);
2754
2755                 ED_image_draw_info(scene, ar, info->color_manage, info->use_default_view, info->channels,
2756                                    info->x, info->y, info->colp, info->colfp, info->linearcol, info->zp, info->zfp);
2757         }
2758 }
2759
2760 /* Returns color in the display space, matching ED_space_node_color_sample(). */
2761 bool ED_space_image_color_sample(Scene *scene, SpaceImage *sima, ARegion *ar, int mval[2], float r_col[3])
2762 {
2763         const char *display_device = scene->display_settings.display_device;
2764         struct ColorManagedDisplay *display = IMB_colormanagement_display_get_named(display_device);
2765         void *lock;
2766         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2767         float fx, fy;
2768         bool ret = false;
2769
2770         if (ibuf == NULL) {
2771                 ED_space_image_release_buffer(sima, ibuf, lock);
2772                 return false;
2773         }
2774
2775         UI_view2d_region_to_view(&ar->v2d, mval[0], mval[1], &fx, &fy);
2776
2777         if (fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) {
2778                 const float *fp;
2779                 unsigned char *cp;
2780                 int x = (int)(fx * ibuf->x), y = (int)(fy * ibuf->y);
2781
2782                 CLAMP(x, 0, ibuf->x - 1);
2783                 CLAMP(y, 0, ibuf->y - 1);
2784
2785                 if (ibuf->rect_float) {
2786                         fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
2787                         copy_v3_v3(r_col, fp);
2788                         ret = true;
2789                 }
2790                 else if (ibuf->rect) {
2791                         cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
2792                         rgb_uchar_to_float(r_col, cp);
2793                         IMB_colormanagement_colorspace_to_scene_linear_v3(r_col, ibuf->rect_colorspace);
2794                         ret = true;
2795                 }
2796         }
2797
2798         if (ret) {
2799                 IMB_colormanagement_scene_linear_to_display_v3(r_col, display);
2800         }
2801
2802         ED_space_image_release_buffer(sima, ibuf, lock);
2803         return ret;
2804 }
2805
2806 static void image_sample_apply(bContext *C, wmOperator *op, const wmEvent *event)
2807 {
2808         SpaceImage *sima = CTX_wm_space_image(C);
2809         ARegion *ar = CTX_wm_region(C);
2810         void *lock;
2811         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2812         ImageSampleInfo *info = op->customdata;
2813         float fx, fy;
2814         Scene *scene = CTX_data_scene(C);
2815         CurveMapping *curve_mapping = scene->view_settings.curve_mapping;
2816
2817         if (ibuf == NULL) {
2818                 ED_space_image_release_buffer(sima, ibuf, lock);
2819                 info->draw = 0;
2820                 return;
2821         }
2822
2823         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &fx, &fy);
2824
2825         if (fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) {
2826                 const float *fp;
2827                 unsigned char *cp;
2828                 int x = (int)(fx * ibuf->x), y = (int)(fy * ibuf->y);
2829                 Image *image = ED_space_image(sima);
2830
2831                 CLAMP(x, 0, ibuf->x - 1);
2832                 CLAMP(y, 0, ibuf->y - 1);
2833
2834                 info->x = x;
2835                 info->y = y;
2836                 info->draw = 1;
2837                 info->channels = ibuf->channels;
2838
2839                 info->colp = NULL;
2840                 info->colfp = NULL;
2841                 info->zp = NULL;
2842                 info->zfp = NULL;
2843
2844                 info->use_default_view = (image->flag & IMA_VIEW_AS_RENDER) ? false : true;
2845
2846                 if (ibuf->rect) {
2847                         cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
2848
2849                         info->col[0] = cp[0];
2850                         info->col[1] = cp[1];
2851                         info->col[2] = cp[2];
2852                         info->col[3] = cp[3];
2853                         info->colp = info->col;
2854
2855                         info->colf[0] = (float)cp[0] / 255.0f;
2856                         info->colf[1] = (float)cp[1] / 255.0f;
2857                         info->colf[2] = (float)cp[2] / 255.0f;
2858                         info->colf[3] = (float)cp[3] / 255.0f;
2859                         info->colfp = info->colf;
2860
2861                         copy_v4_v4(info->linearcol, info->colf);
2862                         IMB_colormanagement_colorspace_to_scene_linear_v4(info->linearcol, false, ibuf->rect_colorspace);
2863
2864                         info->color_manage = true;
2865                 }
2866                 if (ibuf->rect_float) {
2867                         fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
2868
2869                         info->colf[0] = fp[0];
2870                         info->colf[1] = fp[1];
2871                         info->colf[2] = fp[2];
2872                         info->colf[3] = fp[3];
2873                         info->colfp = info->colf;
2874
2875                         copy_v4_v4(info->linearcol, info->colf);
2876
2877                         info->color_manage = true;
2878                 }
2879
2880                 if (ibuf->zbuf) {
2881                         info->z = ibuf->zbuf[y * ibuf->x + x];
2882                         info->zp = &info->z;
2883                 }
2884                 if (ibuf->zbuf_float) {
2885                         info->zf = ibuf->zbuf_float[y * ibuf->x + x];
2886                         info->zfp = &info->zf;
2887                 }
2888
2889                 if (curve_mapping && ibuf->channels == 4) {
2890                         /* we reuse this callback for set curves point operators */
2891                         if (RNA_struct_find_property(op->ptr, "point")) {
2892                                 int point = RNA_enum_get(op->ptr, "point");
2893
2894                                 if (point == 1) {
2895                                         curvemapping_set_black_white(curve_mapping, NULL, info->linearcol);
2896                                 }
2897                                 else if (point == 0) {
2898                                         curvemapping_set_black_white(curve_mapping, info->linearcol, NULL);
2899                                 }
2900                                 WM_event_add_notifier(C, NC_WINDOW, NULL);
2901                         }
2902                 }
2903
2904                 // XXX node curve integration ..
2905 #if 0
2906                 {
2907                         ScrArea *sa, *cur = curarea;
2908                         
2909                         node_curvemap_sample(fp);   /* sends global to node editor */
2910                         for (sa = G.curscreen->areabase.first; sa; sa = sa->next) {
2911                                 if (sa->spacetype == SPACE_NODE) {
2912                                         areawinset(sa->win);
2913                                         scrarea_do_windraw(sa);
2914                                 }
2915                         }
2916                         node_curvemap_sample(NULL);     /* clears global in node editor */
2917                         curarea = cur;
2918                 }
2919 #endif
2920         }
2921         else {
2922                 info->draw = 0;
2923         }
2924
2925         ED_space_image_release_buffer(sima, ibuf, lock);
2926         ED_area_tag_redraw(CTX_wm_area(C));
2927 }
2928
2929 static void image_sample_exit(bContext *C, wmOperator *op)
2930 {
2931         ImageSampleInfo *info = op->customdata;
2932
2933         ED_region_draw_cb_exit(info->art, info->draw_handle);
2934         ED_area_tag_redraw(CTX_wm_area(C));
2935         MEM_freeN(info);
2936 }
2937
2938 static int image_sample_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2939 {
2940         SpaceImage *sima = CTX_wm_space_image(C);
2941         ARegion *ar = CTX_wm_region(C);
2942         ImageSampleInfo *info;
2943
2944         if (ar->regiontype == RGN_TYPE_WINDOW) {
2945                 if (event->mval[1] <= 16 && ED_space_image_show_cache(sima)) {
2946                         return OPERATOR_PASS_THROUGH;
2947                 }
2948         }
2949
2950         if (!ED_space_image_has_buffer(sima))
2951                 return OPERATOR_CANCELLED;
2952         
2953         info = MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
2954         info->art = ar->type;
2955         info->draw_handle = ED_region_draw_cb_activate(ar->type, image_sample_draw, info, REGION_DRAW_POST_PIXEL);
2956         op->customdata = info;
2957
2958         image_sample_apply(C, op, event);
2959
2960         WM_event_add_modal_handler(C, op);
2961
2962         return OPERATOR_RUNNING_MODAL;
2963 }
2964
2965 static int image_sample_modal(bContext *C, wmOperator *op, const wmEvent *event)
2966 {
2967         switch (event->type) {
2968                 case LEFTMOUSE:
2969                 case RIGHTMOUSE: // XXX hardcoded
2970                         if (event->val == KM_RELEASE) {
2971                                 image_sample_exit(C, op);
2972                                 return OPERATOR_CANCELLED;
2973                         }
2974                         break;
2975                 case MOUSEMOVE:
2976                         image_sample_apply(C, op, event);
2977                         break;
2978         }
2979
2980         return OPERATOR_RUNNING_MODAL;
2981 }
2982
2983 static void image_sample_cancel(bContext *C, wmOperator *op)
2984 {
2985         image_sample_exit(C, op);
2986 }
2987
2988 void IMAGE_OT_sample(wmOperatorType *ot)
2989 {
2990         /* identifiers */
2991         ot->name = "Sample Color";
2992         ot->idname = "IMAGE_OT_sample";
2993         ot->description = "Use mouse to sample a color in current image";
2994         
2995         /* api callbacks */
2996         ot->invoke = image_sample_invoke;
2997         ot->modal = image_sample_modal;
2998         ot->cancel = image_sample_cancel;
2999         ot->poll = image_sample_poll;
3000
3001         /* flags */
3002         ot->flag = OPTYPE_BLOCKING;
3003 }
3004
3005 /******************** sample line operator ********************/
3006 static int image_sample_line_exec(bContext *C, wmOperator *op)
3007 {
3008         SpaceImage *sima = CTX_wm_space_image(C);
3009         ARegion *ar = CTX_wm_region(C);
3010         Scene *scene = CTX_data_scene(C);
3011
3012         int x_start = RNA_int_get(op->ptr, "xstart");
3013         int y_start = RNA_int_get(op->ptr, "ystart");
3014         int x_end = RNA_int_get(op->ptr, "xend");
3015         int y_end = RNA_int_get(op->ptr, "yend");
3016         
3017         void *lock;
3018         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
3019         Histogram *hist = &sima->sample_line_hist;
3020         
3021         float x1f, y1f, x2f, y2f;
3022         
3023         if (ibuf == NULL) {
3024                 ED_space_image_release_buffer(sima, ibuf, lock);
3025                 return OPERATOR_CANCELLED;
3026         }
3027         /* hmmmm */
3028         if (ibuf->channels < 3) {
3029                 ED_space_image_release_buffer(sima, ibuf, lock);
3030                 return OPERATOR_CANCELLED;
3031         }
3032         
3033         UI_view2d_region_to_view(&ar->v2d, x_start, y_start, &x1f, &y1f);
3034         UI_view2d_region_to_view(&ar->v2d, x_end, y_end, &x2f, &y2f);
3035
3036         hist->co[0][0] = x1f;
3037         hist->co[0][1] = y1f;
3038         hist->co[1][0] = x2f;
3039         hist->co[1][1] = y2f;
3040
3041         /* enable line drawing */
3042         hist->flag |= HISTO_FLAG_SAMPLELINE;
3043
3044         BKE_histogram_update_sample_line(hist, ibuf, &scene->view_settings, &scene->display_settings);
3045         
3046         /* reset y zoom */
3047         hist->ymax = 1.0f;
3048
3049         ED_space_image_release_buffer(sima, ibuf, lock);
3050         
3051         ED_area_tag_redraw(CTX_wm_area(C));
3052         
3053         return OPERATOR_FINISHED;
3054 }
3055
3056 static int image_sample_line_invoke(bContext *C, wmOperator *op, const wmEvent *event)
3057 {
3058         SpaceImage *sima = CTX_wm_space_image(C);
3059
3060         Histogram *hist = &sima->sample_line_hist;
3061         hist->flag &= ~HISTO_FLAG_SAMPLELINE;
3062
3063         if (!ED_space_image_has_buffer(sima))
3064                 return OPERATOR_CANCELLED;
3065         
3066         return WM_gesture_straightline_invoke(C, op, event);
3067 }
3068
3069 void IMAGE_OT_sample_line(wmOperatorType *ot)
3070 {
3071         /* identifiers */
3072         ot->name = "Sample Line";
3073         ot->idname = "IMAGE_OT_sample_line";
3074         ot->description = "Sample a line and show it in Scope panels";
3075         
3076         /* api callbacks */
3077         ot->invoke = image_sample_line_invoke;
3078         ot->modal = WM_gesture_straightline_modal;
3079         ot->exec = image_sample_line_exec;
3080         ot->poll = space_image_main_area_poll;
3081         ot->cancel = WM_gesture_straightline_cancel;
3082         
3083         /* flags */
3084         ot->flag = 0; /* no undo/register since this operates on the space */
3085         
3086         WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT);
3087 }
3088
3089 /******************** set curve point operator ********************/
3090
3091 void IMAGE_OT_curves_point_set(wmOperatorType *ot)
3092 {
3093         static EnumPropertyItem point_items[] = {
3094                 {0, "BLACK_POINT", 0, "Black Point", ""},
3095                 {1, "WHITE_POINT", 0, "White Point", ""},
3096                 {0, NULL, 0, NULL, NULL}
3097         };
3098
3099         /* identifiers */
3100         ot->name = "Set Curves Point";
3101         ot->idname = "IMAGE_OT_curves_point_set";
3102         ot->description = "Set black point or white point for curves";
3103
3104         /* flags */
3105         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3106         
3107         /* api callbacks */
3108         ot->invoke = image_sample_invoke;
3109         ot->modal = image_sample_modal;
3110         ot->cancel = image_sample_cancel;
3111         ot->poll = space_image_main_area_not_uv_brush_poll;
3112
3113         /* properties */
3114         RNA_def_enum(ot->srna, "point", point_items, 0, "Point", "Set black point or white point for curves");
3115 }
3116
3117 #if 0 /* Not ported to 2.5x yet */
3118 /******************** record composite operator *********************/
3119
3120 typedef struct RecordCompositeData {
3121         wmTimer *timer;
3122         int old_cfra;
3123         int sfra, efra;
3124 } RecordCompositeData;
3125
3126 static int image_record_composite_apply(bContext *C, wmOperator *op)
3127 {
3128         SpaceImage *sima = CTX_wm_space_image(C);
3129         RecordCompositeData *rcd = op->customdata;
3130         Scene *scene = CTX_data_scene(C);
3131         ImBuf *ibuf;
3132         
3133         WM_cursor_time(CTX_wm_window(C), scene->r.cfra);
3134
3135         // XXX scene->nodetree->test_break = blender_test_break;
3136         // XXX scene->nodetree->test_break = NULL;
3137         
3138         BKE_image_all_free_anim_ibufs(scene->r.cfra);
3139         ntreeCompositTagAnimated(scene->nodetree);
3140         ntreeCompositExecTree(scene->nodetree, &scene->r, 0, scene->r.cfra != rcd->old_cfra,
3141                               &scene->view_settings, &scene->display_settings);  /* 1 is no previews */
3142
3143         ED_area_tag_redraw(CTX_wm_area(C));
3144         
3145         ibuf = BKE_image_acquire_ibuf(sima->image, &sima->iuser, NULL);
3146         /* save memory in flipbooks */
3147         if (ibuf)
3148                 imb_freerectfloatImBuf(ibuf);
3149
3150         BKE_image_release_ibuf(sima->image, ibuf, NULL);
3151
3152         scene->r.cfra++;
3153
3154         return (scene->r.cfra <= rcd->efra);
3155 }
3156
3157 static int image_record_composite_init(bContext *C, wmOperator *op)
3158 {
3159         SpaceImage *sima = CTX_wm_space_image(C);
3160         Scene *scene = CTX_data_scene(C);
3161         RecordCompositeData *rcd;
3162
3163         if (sima->iuser.frames < 2)
3164                 return 0;
3165         if (scene->nodetree == NULL)
3166                 return 0;
3167         
3168         op->customdata = rcd = MEM_callocN(sizeof(RecordCompositeData), "ImageRecordCompositeData");
3169
3170         rcd->old_cfra = scene->r.cfra;
3171         rcd->sfra = sima->iuser.sfra;
3172         rcd->efra = sima->iuser.sfra + sima->iuser.frames - 1;
3173         scene->r.cfra = rcd->sfra;
3174
3175         return 1;
3176 }
3177
3178 static void image_record_composite_exit(bContext *C, wmOperator *op)
3179 {
3180         Scene *scene = CTX_data_scene(C);
3181         SpaceImage *sima = CTX_wm_space_image(C);
3182         RecordCompositeData *rcd = op->customdata;
3183
3184         scene->r.cfra = rcd->old_cfra;
3185
3186         WM_cursor_modal_restore(CTX_wm_window(C));
3187
3188         if (rcd->timer)
3189                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rcd->timer);
3190
3191         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
3192
3193         // XXX play_anim(0);
3194         // XXX allqueue(REDRAWNODE, 1);
3195
3196         MEM_freeN(rcd);
3197 }
3198
3199 static int image_record_composite_exec(bContext *C, wmOperator *op)
3200 {
3201         if (!image_record_composite_init(C, op))
3202                 return OPERATOR_CANCELLED;
3203         
3204         while (image_record_composite_apply(C, op)) {}
3205         
3206         image_record_composite_exit(C, op);
3207         
3208         return OPERATOR_FINISHED;
3209 }
3210
3211 static int image_record_composite_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
3212 {
3213         RecordCompositeData *rcd;
3214         
3215         if (!image_record_composite_init(C, op))
3216                 return OPERATOR_CANCELLED;
3217
3218         rcd = op->customdata;
3219         rcd->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.0f);
3220         WM_event_add_modal_handler(C, op);
3221
3222         if (!image_record_composite_apply(C, op))
3223                 return OPERATOR_FINISHED;
3224
3225         return OPERATOR_RUNNING_MODAL;
3226 }
3227
3228 static int image_record_composite_modal(bContext *C, wmOperator *op, const wmEvent *event)
3229 {
3230         RecordCompositeData *rcd = op->customdata;
3231
3232         switch (event->type) {
3233                 case TIMER:
3234                         if (rcd->timer == event->customdata) {
3235                                 if (!image_record_composite_apply(C, op)) {
3236                                         image_record_composite_exit(C, op);
3237                                         return OPERATOR_FINISHED;
3238                                 }
3239                         }
3240                         break;
3241                 case ESCKEY:
3242                         image_record_composite_exit(C, op);
3243                         return OPERATOR_FINISHED;
3244         }
3245
3246         return OPERATOR_RUNNING_MODAL;
3247 }
3248
3249 static void image_record_composite_cancel(bContext *C, wmOperator *op)
3250 {
3251         image_record_composite_exit(C, op);
3252         return OPERATOR_CANCELLED;
3253 }
3254
3255 void IMAGE_OT_record_composite(wmOperatorType *ot)
3256 {
3257         /* identifiers */
3258         ot->name = "Record Composite";
3259         ot->idname = "IMAGE_OT_record_composite";
3260         
3261         /* api callbacks */
3262         ot->exec = image_record_composite_exec;
3263         ot->invoke = image_record_composite_invoke;
3264         ot->modal = image_record_composite_modal;
3265         ot->cancel = image_record_composite_cancel;
3266         ot->poll = space_image_buffer_exists_poll;
3267 }
3268
3269 #endif
3270
3271 /********************* cycle render slot operator *********************/
3272
3273 static int image_cycle_render_slot_poll(bContext *C)
3274 {