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