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