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