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