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