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