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