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