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