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