Image cache rewrite to using generic movie cache
[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                 simopts->im_format.planes = ibuf->planes;
1237
1238                 if (ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE)) {
1239                         /* imtype */
1240                         simopts->im_format = scene->r.im_format;
1241                         is_depth_set = TRUE;
1242                 }
1243                 else {
1244                         if (ima->source == IMA_SRC_GENERATED) {
1245                                 simopts->im_format.imtype = R_IMF_IMTYPE_PNG;
1246                         }
1247                         else {
1248                                 BKE_imbuf_to_image_format(&simopts->im_format, ibuf);
1249                                 simopts->im_format.quality = ibuf->ftype & 0xff;
1250                         }
1251                         simopts->im_format.quality = ibuf->ftype & 0xff;
1252                 }
1253                 //simopts->subimtype = scene->r.subimtype; /* XXX - this is lame, we need to make these available too! */
1254
1255                 BLI_strncpy(simopts->filepath, ibuf->name, sizeof(simopts->filepath));
1256
1257                 /* sanitize all settings */
1258
1259                 /* unlikely but just in case */
1260                 if (ELEM3(simopts->im_format.planes, R_IMF_PLANES_BW, R_IMF_PLANES_RGB, R_IMF_PLANES_RGBA) == 0) {
1261                         simopts->im_format.planes = R_IMF_PLANES_RGBA;
1262                 }
1263
1264                 /* depth, account for float buffer and format support */
1265                 if (is_depth_set == FALSE) {
1266                         simopts->im_format.depth = imtype_best_depth(ibuf, simopts->im_format.imtype);
1267                 }
1268
1269                 /* some formats don't use quality so fallback to scenes quality */
1270                 if (simopts->im_format.quality == 0) {
1271                         simopts->im_format.quality = scene->r.im_format.quality;
1272                 }
1273
1274                 /* check for empty path */
1275                 if (guess_path && simopts->filepath[0] == 0) {
1276                         const bool is_prev_save = !STREQ(G.ima, "//");
1277                         if (save_as_render) {
1278                                 if (is_prev_save) {
1279                                         BLI_strncpy(simopts->filepath, G.ima, sizeof(simopts->filepath));
1280                                 }
1281                                 else {
1282                                         BLI_strncpy(simopts->filepath, "//untitled", sizeof(simopts->filepath));
1283                                         BLI_path_abs(simopts->filepath, G.main->name);
1284                                 }
1285                         }
1286                         else {
1287                                 BLI_snprintf(simopts->filepath, sizeof(simopts->filepath), "//%s", ima->id.name + 2);
1288                                 BLI_path_abs(simopts->filepath, is_prev_save ? G.ima : G.main->name);
1289                         }
1290                 }
1291
1292                 /* color management */
1293                 BKE_color_managed_display_settings_copy(&simopts->im_format.display_settings, &scene->display_settings);
1294                 BKE_color_managed_view_settings_copy(&simopts->im_format.view_settings, &scene->view_settings);
1295         }
1296
1297         ED_space_image_release_buffer(sima, ibuf, lock);
1298
1299         return (ibuf != NULL);
1300 }
1301
1302 static void save_image_options_from_op(SaveImageOptions *simopts, wmOperator *op)
1303 {
1304         if (op->customdata) {
1305                 BKE_color_managed_view_settings_free(&simopts->im_format.view_settings);
1306
1307                 simopts->im_format = *(ImageFormatData *)op->customdata;
1308         }
1309
1310         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
1311                 RNA_string_get(op->ptr, "filepath", simopts->filepath);
1312                 BLI_path_abs(simopts->filepath, G.main->name);
1313         }
1314 }
1315
1316 static void save_image_options_to_op(SaveImageOptions *simopts, wmOperator *op)
1317 {
1318         if (op->customdata) {
1319                 BKE_color_managed_view_settings_free(&((ImageFormatData *)op->customdata)->view_settings);
1320
1321                 *(ImageFormatData *)op->customdata = simopts->im_format;
1322         }
1323
1324         RNA_string_set(op->ptr, "filepath", simopts->filepath);
1325 }
1326
1327 /* assumes name is FILE_MAX */
1328 /* ima->name and ibuf->name should end up the same */
1329 static void save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveImageOptions *simopts, int do_newpath)
1330 {
1331         Image *ima = ED_space_image(sima);
1332         void *lock;
1333         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
1334
1335         if (ibuf) {
1336                 ImBuf *colormanaged_ibuf;
1337                 const char *relbase = ID_BLEND_PATH(CTX_data_main(C), &ima->id);
1338                 const short relative = (RNA_struct_find_property(op->ptr, "relative_path") && RNA_boolean_get(op->ptr, "relative_path"));
1339                 const short save_copy = (RNA_struct_find_property(op->ptr, "copy") && RNA_boolean_get(op->ptr, "copy"));
1340                 const bool save_as_render = (RNA_struct_find_property(op->ptr, "save_as_render") && RNA_boolean_get(op->ptr, "save_as_render"));
1341                 ImageFormatData *imf = &simopts->im_format;
1342                 short ok = FALSE;
1343
1344                 /* old global to ensure a 2nd save goes to same dir */
1345                 BLI_strncpy(G.ima, simopts->filepath, sizeof(G.ima));
1346
1347                 WM_cursor_wait(1);
1348
1349                 if (ima->type == IMA_TYPE_R_RESULT) {
1350                         /* enforce user setting for RGB or RGBA, but skip BW */
1351                         if (simopts->im_format.planes == R_IMF_PLANES_RGBA) {
1352                                 ibuf->planes = R_IMF_PLANES_RGBA;
1353                         }
1354                         else if (simopts->im_format.planes == R_IMF_PLANES_RGB) {
1355                                 ibuf->planes = R_IMF_PLANES_RGB;
1356                         }
1357                 }
1358                 else {
1359                         /* TODO, better solution, if a 24bit image is painted onto it may contain alpha */
1360                         if (ibuf->userflags & IB_BITMAPDIRTY) { /* it has been painted onto */
1361                                 /* checks each pixel, not ideal */
1362                                 ibuf->planes = BKE_imbuf_alpha_test(ibuf) ? 32 : 24;
1363                         }
1364                 }
1365
1366                 colormanaged_ibuf = IMB_colormanagement_imbuf_for_write(ibuf, save_as_render, true, &imf->view_settings, &imf->display_settings, imf);
1367
1368                 if (simopts->im_format.imtype == R_IMF_IMTYPE_MULTILAYER) {
1369                         Scene *scene = CTX_data_scene(C);
1370                         RenderResult *rr = BKE_image_acquire_renderresult(scene, ima);
1371                         if (rr) {
1372                                 RE_WriteRenderResult(op->reports, rr, simopts->filepath, simopts->im_format.exr_codec);
1373                                 ok = TRUE;
1374                         }
1375                         else {
1376                                 BKE_report(op->reports, RPT_ERROR, "Did not write, no Multilayer Image");
1377                         }
1378                         BKE_image_release_renderresult(scene, ima);
1379                 }
1380                 else {
1381                         if (BKE_imbuf_write_as(colormanaged_ibuf, simopts->filepath, &simopts->im_format, save_copy)) {
1382                                 ok = TRUE;
1383                         }
1384                 }
1385
1386                 if (ok) {
1387                         if (!save_copy) {
1388                                 if (do_newpath) {
1389                                         BLI_strncpy(ibuf->name, simopts->filepath, sizeof(ibuf->name));
1390                                         BLI_strncpy(ima->name, simopts->filepath, sizeof(ima->name));
1391                                 }
1392
1393                                 ibuf->userflags &= ~IB_BITMAPDIRTY;
1394
1395                                 /* change type? */
1396                                 if (ima->type == IMA_TYPE_R_RESULT) {
1397                                         ima->type = IMA_TYPE_IMAGE;
1398
1399                                         /* workaround to ensure the render result buffer is no longer used
1400                                          * by this image, otherwise can crash when a new render result is
1401                                          * created. */
1402                                         if (ibuf->rect && !(ibuf->mall & IB_rect))
1403                                                 imb_freerectImBuf(ibuf);
1404                                         if (ibuf->rect_float && !(ibuf->mall & IB_rectfloat))
1405                                                 imb_freerectfloatImBuf(ibuf);
1406                                         if (ibuf->zbuf && !(ibuf->mall & IB_zbuf))
1407                                                 IMB_freezbufImBuf(ibuf);
1408                                         if (ibuf->zbuf_float && !(ibuf->mall & IB_zbuffloat))
1409                                                 IMB_freezbuffloatImBuf(ibuf);
1410                                 }
1411                                 if (ELEM(ima->source, IMA_SRC_GENERATED, IMA_SRC_VIEWER)) {
1412                                         ima->source = IMA_SRC_FILE;
1413                                         ima->type = IMA_TYPE_IMAGE;
1414                                 }
1415
1416                                 /* only image path, never ibuf */
1417                                 if (relative) {
1418                                         BLI_path_rel(ima->name, relbase); /* only after saving */
1419                                 }
1420
1421                                 IMB_colormanagment_colorspace_from_ibuf_ftype(&ima->colorspace_settings, ibuf);
1422                         }
1423                 }
1424                 else {
1425                         BKE_reportf(op->reports, RPT_ERROR, "Could not write image %s", simopts->filepath);
1426                 }
1427
1428
1429                 WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
1430
1431                 WM_cursor_wait(0);
1432
1433                 if (colormanaged_ibuf != ibuf)
1434                         IMB_freeImBuf(colormanaged_ibuf);
1435         }
1436
1437         ED_space_image_release_buffer(sima, ibuf, lock);
1438 }
1439
1440 static void image_save_as_free(wmOperator *op)
1441 {
1442         if (op->customdata) {
1443                 ImageFormatData *im_format = (ImageFormatData *)op->customdata;
1444                 BKE_color_managed_view_settings_free(&im_format->view_settings);
1445
1446                 MEM_freeN(op->customdata);
1447                 op->customdata = NULL;
1448         }
1449 }
1450
1451 static int image_save_as_exec(bContext *C, wmOperator *op)
1452 {
1453         SpaceImage *sima = CTX_wm_space_image(C);
1454         SaveImageOptions simopts;
1455
1456         save_image_options_defaults(&simopts);
1457
1458         /* just in case to initialize values,
1459          * these should be set on invoke or by the caller. */
1460         save_image_options_init(&simopts, sima, CTX_data_scene(C), false, false);
1461
1462         save_image_options_from_op(&simopts, op);
1463
1464         save_image_doit(C, sima, op, &simopts, TRUE);
1465
1466         image_save_as_free(op);
1467         return OPERATOR_FINISHED;
1468 }
1469
1470
1471 static bool image_save_as_check(bContext *UNUSED(C), wmOperator *op)
1472 {
1473         ImageFormatData *imf = op->customdata;
1474         return WM_operator_filesel_ensure_ext_imtype(op, imf);
1475 }
1476
1477 static int image_save_as_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1478 {
1479         SpaceImage *sima = CTX_wm_space_image(C);
1480         Image *ima = ED_space_image(sima);
1481         Scene *scene = CTX_data_scene(C);
1482         SaveImageOptions simopts;
1483         const bool save_as_render = ((ima->source == IMA_SRC_VIEWER) || (ima->flag & IMA_VIEW_AS_RENDER));
1484
1485         if (RNA_struct_property_is_set(op->ptr, "filepath"))
1486                 return image_save_as_exec(C, op);
1487
1488         save_image_options_defaults(&simopts);
1489
1490         if (save_image_options_init(&simopts, sima, scene, true, save_as_render) == 0)
1491                 return OPERATOR_CANCELLED;
1492         save_image_options_to_op(&simopts, op);
1493
1494         /* enable save_copy by default for render results */
1495         if (ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE) && !RNA_struct_property_is_set(op->ptr, "copy")) {
1496                 RNA_boolean_set(op->ptr, "copy", TRUE);
1497         }
1498
1499         RNA_boolean_set(op->ptr, "save_as_render", save_as_render);
1500
1501         op->customdata = MEM_mallocN(sizeof(simopts.im_format), __func__);
1502         memcpy(op->customdata, &simopts.im_format, sizeof(simopts.im_format));
1503
1504         image_filesel(C, op, simopts.filepath);
1505
1506         return OPERATOR_RUNNING_MODAL;
1507 }
1508
1509 static void image_save_as_cancel(bContext *UNUSED(C), wmOperator *op)
1510 {
1511         image_save_as_free(op);
1512 }
1513
1514 static bool image_save_as_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop)
1515 {
1516         const char *prop_id = RNA_property_identifier(prop);
1517
1518         return !(STREQ(prop_id, "filepath") ||
1519                  STREQ(prop_id, "directory") ||
1520                  STREQ(prop_id, "filename") ||
1521                  /* when saving a copy, relative path has no effect */
1522                  ((STREQ(prop_id, "relative_path")) && RNA_boolean_get(ptr, "copy"))
1523                  );
1524 }
1525
1526 static void image_save_as_draw(bContext *UNUSED(C), wmOperator *op)
1527 {
1528         uiLayout *layout = op->layout;
1529         ImageFormatData *imf = op->customdata;
1530         PointerRNA ptr;
1531
1532         /* image template */
1533         RNA_pointer_create(NULL, &RNA_ImageFormatSettings, imf, &ptr);
1534         uiTemplateImageSettings(layout, &ptr, FALSE);
1535
1536         /* main draw call */
1537         RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);
1538         uiDefAutoButsRNA(layout, &ptr, image_save_as_draw_check_prop, '\0');
1539 }
1540
1541 static int image_save_as_poll(bContext *C)
1542 {
1543         if (space_image_buffer_exists_poll(C)) {
1544                 if (G.is_rendering) {
1545                         /* no need to NULL check here */
1546                         SpaceImage *sima = CTX_wm_space_image(C);
1547                         Image *ima = ED_space_image(sima);
1548
1549                         if (ima->source == IMA_SRC_VIEWER) {
1550                                 CTX_wm_operator_poll_msg_set(C, "can't save image while rendering");
1551                                 return FALSE;
1552                         }
1553                 }
1554                 return TRUE;
1555         }
1556         return FALSE;
1557 }
1558
1559 void IMAGE_OT_save_as(wmOperatorType *ot)
1560 {
1561 //      PropertyRNA *prop;
1562
1563         /* identifiers */
1564         ot->name = "Save As Image";
1565         ot->idname = "IMAGE_OT_save_as";
1566         ot->description = "Save the image with another name and/or settings";
1567         
1568         /* api callbacks */
1569         ot->exec = image_save_as_exec;
1570         ot->check = image_save_as_check;
1571         ot->invoke = image_save_as_invoke;
1572         ot->cancel = image_save_as_cancel;
1573         ot->ui = image_save_as_draw;
1574         ot->poll = image_save_as_poll;
1575
1576         /* flags */
1577         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1578
1579         /* properties */
1580         RNA_def_boolean(ot->srna, "save_as_render", 0, "Save As Render", "Apply render part of display transform when saving byte image");
1581         RNA_def_boolean(ot->srna, "copy", 0, "Copy", "Create a new image file without modifying the current image in blender");
1582
1583         WM_operator_properties_filesel(ot, FOLDERFILE | IMAGEFILE | MOVIEFILE, FILE_SPECIAL, FILE_SAVE,
1584                                        WM_FILESEL_FILEPATH | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY);
1585 }
1586
1587 /******************** save image operator ********************/
1588
1589 static int image_save_exec(bContext *C, wmOperator *op)
1590 {
1591         SpaceImage *sima = CTX_wm_space_image(C);
1592         Scene *scene = CTX_data_scene(C);
1593         SaveImageOptions simopts;
1594
1595         save_image_options_defaults(&simopts);
1596         if (save_image_options_init(&simopts, sima, scene, false, false) == 0)
1597                 return OPERATOR_CANCELLED;
1598         save_image_options_from_op(&simopts, op);
1599
1600         if (BLI_exists(simopts.filepath) && BLI_file_is_writable(simopts.filepath)) {
1601                 save_image_doit(C, sima, op, &simopts, FALSE);
1602         }
1603         else {
1604                 BKE_reportf(op->reports, RPT_ERROR, "Cannot save image, path '%s' is not writable", simopts.filepath);
1605                 return OPERATOR_CANCELLED;
1606         }
1607
1608         return OPERATOR_FINISHED;
1609 }
1610
1611 void IMAGE_OT_save(wmOperatorType *ot)
1612 {
1613         /* identifiers */
1614         ot->name = "Save Image";
1615         ot->idname = "IMAGE_OT_save";
1616         ot->description = "Save the image with current name and settings";
1617         
1618         /* api callbacks */
1619         ot->exec = image_save_exec;
1620         ot->poll = space_image_file_exists_poll;
1621
1622         /* flags */
1623         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1624 }
1625
1626 /******************* save sequence operator ********************/
1627
1628 static int image_save_sequence_exec(bContext *C, wmOperator *op)
1629 {
1630         Main *bmain = CTX_data_main(C);
1631         SpaceImage *sima = CTX_wm_space_image(C);
1632         ImBuf *ibuf, *first_ibuf = NULL;
1633         int tot = 0;
1634         char di[FILE_MAX];
1635         struct MovieCacheIter *iter;
1636         
1637         if (sima->image == NULL)
1638                 return OPERATOR_CANCELLED;
1639
1640         if (sima->image->source != IMA_SRC_SEQUENCE) {
1641                 BKE_report(op->reports, RPT_ERROR, "Can only save sequence on image sequences");
1642                 return OPERATOR_CANCELLED;
1643         }
1644
1645         if (sima->image->type == IMA_TYPE_MULTILAYER) {
1646                 BKE_report(op->reports, RPT_ERROR, "Cannot save multilayer sequences");
1647                 return OPERATOR_CANCELLED;
1648         }
1649         
1650         /* get total dirty buffers and first dirty buffer which is used for menu */
1651         ibuf = NULL;
1652         if (sima->image->cache != NULL) {
1653                 iter = IMB_moviecacheIter_new(sima->image->cache);
1654                 while (!IMB_moviecacheIter_done(iter)) {
1655                         ibuf = IMB_moviecacheIter_getImBuf(iter);
1656                         if (ibuf->userflags & IB_BITMAPDIRTY) {
1657                                 if (first_ibuf == NULL) {
1658                                         first_ibuf = ibuf;
1659                                 }
1660                                 tot++;
1661                         }
1662                         IMB_moviecacheIter_step(iter);
1663                 }
1664                 IMB_moviecacheIter_free(iter);
1665         }
1666         
1667         if (tot == 0) {
1668                 BKE_report(op->reports, RPT_WARNING, "No images have been changed");
1669                 return OPERATOR_CANCELLED;
1670         }
1671
1672         /* get a filename for menu */
1673         BLI_split_dir_part(first_ibuf->name, di, sizeof(di));
1674         BKE_reportf(op->reports, RPT_INFO, "%d image(s) will be saved in %s", tot, di);
1675
1676         iter = IMB_moviecacheIter_new(sima->image->cache);
1677         while (!IMB_moviecacheIter_done(iter)) {
1678                 ibuf = IMB_moviecacheIter_getImBuf(iter);
1679
1680                 if (ibuf->userflags & IB_BITMAPDIRTY) {
1681                         char name[FILE_MAX];
1682                         BLI_strncpy(name, ibuf->name, sizeof(name));
1683
1684                         BLI_path_abs(name, bmain->name);
1685
1686                         if (0 == IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat)) {
1687                                 BKE_reportf(op->reports, RPT_ERROR, "Could not write image %s", name);
1688                                 break;
1689                         }
1690
1691                         BKE_reportf(op->reports, RPT_INFO, "Saved %s", ibuf->name);
1692                         ibuf->userflags &= ~IB_BITMAPDIRTY;
1693                 }
1694
1695                 IMB_moviecacheIter_step(iter);
1696         }
1697         IMB_moviecacheIter_free(iter);
1698
1699         return OPERATOR_FINISHED;
1700 }
1701
1702 void IMAGE_OT_save_sequence(wmOperatorType *ot)
1703 {
1704         /* identifiers */
1705         ot->name = "Save Sequence";
1706         ot->idname = "IMAGE_OT_save_sequence";
1707         ot->description = "Save a sequence of images";
1708         
1709         /* api callbacks */
1710         ot->exec = image_save_sequence_exec;
1711         ot->poll = space_image_buffer_exists_poll;
1712
1713         /* flags */
1714         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1715 }
1716
1717 /******************** reload image operator ********************/
1718
1719 static int image_reload_exec(bContext *C, wmOperator *UNUSED(op))
1720 {
1721         Image *ima = CTX_data_edit_image(C);
1722         SpaceImage *sima = CTX_wm_space_image(C);
1723
1724         if (!ima)
1725                 return OPERATOR_CANCELLED;
1726
1727         /* XXX unpackImage frees image buffers */
1728         ED_preview_kill_jobs(C);
1729         
1730         // XXX other users?
1731         BKE_image_signal(ima, (sima) ? &sima->iuser : NULL, IMA_SIGNAL_RELOAD);
1732
1733         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1734         
1735         return OPERATOR_FINISHED;
1736 }
1737
1738 void IMAGE_OT_reload(wmOperatorType *ot)
1739 {
1740         /* identifiers */
1741         ot->name = "Reload Image";
1742         ot->idname = "IMAGE_OT_reload";
1743         ot->description = "Reload current image from disk";
1744         
1745         /* api callbacks */
1746         ot->exec = image_reload_exec;
1747
1748         /* flags */
1749         ot->flag = OPTYPE_REGISTER; /* no undo, image buffer is not handled by undo */
1750 }
1751
1752 /********************** new image operator *********************/
1753 #define IMA_DEF_NAME N_("Untitled")
1754
1755 static int image_new_exec(bContext *C, wmOperator *op)
1756 {
1757         SpaceImage *sima;
1758         Scene *scene;
1759         Object *obedit;
1760         Image *ima;
1761         Main *bmain;
1762         PointerRNA ptr, idptr;
1763         PropertyRNA *prop;
1764         char _name[MAX_ID_NAME - 2];
1765         char *name = _name;
1766         float color[4];
1767         int width, height, floatbuf, gen_type, alpha;
1768
1769         /* retrieve state */
1770         sima = CTX_wm_space_image(C);
1771         scene = CTX_data_scene(C);
1772         obedit = CTX_data_edit_object(C);
1773         bmain = CTX_data_main(C);
1774
1775         prop = RNA_struct_find_property(op->ptr, "name");
1776         RNA_property_string_get(op->ptr, prop, name);
1777         if (!RNA_property_is_set(op->ptr, prop)) {
1778                 /* Default value, we can translate! */
1779                 name = (char *)DATA_(name);
1780         }
1781         width = RNA_int_get(op->ptr, "width");
1782         height = RNA_int_get(op->ptr, "height");
1783         floatbuf = RNA_boolean_get(op->ptr, "float");
1784         gen_type = RNA_enum_get(op->ptr, "generated_type");
1785         RNA_float_get_array(op->ptr, "color", color);
1786         alpha = RNA_boolean_get(op->ptr, "alpha");
1787         
1788         if (!alpha)
1789                 color[3] = 1.0f;
1790
1791         ima = BKE_image_add_generated(bmain, width, height, name, alpha ? 32 : 24, floatbuf, gen_type, color);
1792
1793         if (!ima)
1794                 return OPERATOR_CANCELLED;
1795
1796         /* hook into UI */
1797         uiIDContextProperty(C, &ptr, &prop);
1798
1799         if (prop) {
1800                 /* when creating new ID blocks, use is already 1, but RNA
1801                  * pointer se also increases user, so this compensates it */
1802                 ima->id.us--;
1803
1804                 RNA_id_pointer_create(&ima->id, &idptr);
1805                 RNA_property_pointer_set(&ptr, prop, idptr);
1806                 RNA_property_update(C, &ptr, prop);
1807         }
1808         else if (sima) {
1809                 ED_space_image_set(sima, scene, obedit, ima);
1810         }
1811         else {
1812                 Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
1813                 if (tex && tex->type == TEX_IMAGE) {
1814                         if (tex->ima)
1815                                 id_us_min(&tex->ima->id);
1816                         tex->ima = ima;
1817                         ED_area_tag_redraw(CTX_wm_area(C));
1818                 }
1819         }
1820
1821         BKE_image_signal(ima, (sima) ? &sima->iuser : NULL, IMA_SIGNAL_USER_NEW_IMAGE);
1822         
1823         WM_event_add_notifier(C, NC_IMAGE | NA_ADDED, ima);
1824         
1825         return OPERATOR_FINISHED;
1826 }
1827
1828 /* XXX, Ton is not a fan of OK buttons but using this function to avoid undo/redo bug while in mesh-editmode, - campbell */
1829 /* XXX Note: the WM_operator_props_dialog_popup() doesn't work for uiIDContextProperty(), image is not being that way */
1830 static int image_new_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1831 {
1832         /* Better for user feedback. */
1833         RNA_string_set(op->ptr, "name", DATA_(IMA_DEF_NAME));
1834         return WM_operator_props_dialog_popup(C, op, 15 * UI_UNIT_X, 5 * UI_UNIT_Y);
1835 }
1836
1837 void IMAGE_OT_new(wmOperatorType *ot)
1838 {
1839         PropertyRNA *prop;
1840         static float default_color[4] = {0.0f, 0.0f, 0.0f, 1.0f};
1841         
1842         /* identifiers */
1843         ot->name = "New Image";
1844         ot->description = "Create a new image";
1845         ot->idname = "IMAGE_OT_new";
1846         
1847         /* api callbacks */
1848         ot->exec = image_new_exec;
1849         ot->invoke = image_new_invoke;
1850         
1851         /* flags */
1852         ot->flag = OPTYPE_UNDO;
1853
1854         /* properties */
1855         RNA_def_string(ot->srna, "name", IMA_DEF_NAME, MAX_ID_NAME - 2, "Name", "Image datablock name");
1856         prop = RNA_def_int(ot->srna, "width", 1024, 1, INT_MAX, "Width", "Image width", 1, 16384);
1857         RNA_def_property_subtype(prop, PROP_PIXEL);
1858         prop = RNA_def_int(ot->srna, "height", 1024, 1, INT_MAX, "Height", "Image height", 1, 16384);
1859         RNA_def_property_subtype(prop, PROP_PIXEL);
1860         prop = RNA_def_float_color(ot->srna, "color", 4, NULL, 0.0f, FLT_MAX, "Color", "Default fill color", 0.0f, 1.0f);
1861         RNA_def_property_subtype(prop, PROP_COLOR_GAMMA);
1862         RNA_def_property_float_array_default(prop, default_color);
1863         RNA_def_boolean(ot->srna, "alpha", 1, "Alpha", "Create an image with an alpha channel");
1864         RNA_def_enum(ot->srna, "generated_type", image_generated_type_items, IMA_GENTYPE_BLANK,
1865                      "Generated Type", "Fill the image with a grid for UV map testing");
1866         RNA_def_boolean(ot->srna, "float", 0, "32 bit Float", "Create image with 32 bit floating point bit depth");
1867 }
1868
1869 #undef IMA_DEF_NAME
1870
1871 /********************* invert operators *********************/
1872
1873 static int image_invert_poll(bContext *C)
1874 {
1875         Image *ima = CTX_data_edit_image(C);
1876
1877         return BKE_image_has_ibuf(ima, NULL);
1878 }
1879
1880 static int image_invert_exec(bContext *C, wmOperator *op)
1881 {
1882         Image *ima = CTX_data_edit_image(C);
1883         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
1884         SpaceImage *sima = CTX_wm_space_image(C);
1885         /* undo is supported only on image paint mode currently */
1886         bool support_undo = ((sima != NULL) && (sima->mode == SI_MODE_PAINT));
1887
1888         /* flags indicate if this channel should be inverted */
1889         const short r = RNA_boolean_get(op->ptr, "invert_r");
1890         const short g = RNA_boolean_get(op->ptr, "invert_g");
1891         const short b = RNA_boolean_get(op->ptr, "invert_b");
1892         const short a = RNA_boolean_get(op->ptr, "invert_a");
1893
1894         int i;
1895
1896         if (ibuf == NULL)  /* TODO: this should actually never happen, but does for render-results -> cleanup */
1897                 return OPERATOR_CANCELLED;
1898
1899         if (support_undo) {
1900                 ED_undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
1901                                          ED_image_undo_restore, ED_image_undo_free);
1902                 /* not strictly needed, because we only imapaint_dirty_region to invalidate all tiles
1903                  * but better do this right in case someone copies this for a tool that uses partial redraw better */
1904                 ED_imapaint_clear_partial_redraw();
1905                 ED_imapaint_dirty_region(ima, ibuf, 0, 0, ibuf->x, ibuf->y);
1906         }
1907         /* TODO: make this into an IMB_invert_channels(ibuf,r,g,b,a) method!? */
1908         if (ibuf->rect_float) {
1909                 
1910                 float *fp = (float *) ibuf->rect_float;
1911                 for (i = ibuf->x * ibuf->y; i > 0; i--, fp += 4) {
1912                         if (r) fp[0] = 1.0f - fp[0];
1913                         if (g) fp[1] = 1.0f - fp[1];
1914                         if (b) fp[2] = 1.0f - fp[2];
1915                         if (a) fp[3] = 1.0f - fp[3];
1916                 }
1917
1918                 if (ibuf->rect) {
1919                         IMB_rect_from_float(ibuf);
1920                 }
1921         }
1922         else if (ibuf->rect) {
1923                 
1924                 char *cp = (char *) ibuf->rect;
1925                 for (i = ibuf->x * ibuf->y; i > 0; i--, cp += 4) {
1926                         if (r) cp[0] = 255 - cp[0];
1927                         if (g) cp[1] = 255 - cp[1];
1928                         if (b) cp[2] = 255 - cp[2];
1929                         if (a) cp[3] = 255 - cp[3];
1930                 }
1931         }
1932         else {
1933                 BKE_image_release_ibuf(ima, ibuf, NULL);
1934                 return OPERATOR_CANCELLED;
1935         }
1936
1937         ibuf->userflags |= IB_BITMAPDIRTY | IB_DISPLAY_BUFFER_INVALID;
1938
1939         if (ibuf->mipmap[0])
1940                 ibuf->userflags |= IB_MIPMAP_INVALID;
1941
1942         if (support_undo)
1943                 ED_undo_paint_push_end(UNDO_PAINT_IMAGE);
1944
1945         /* force GPU reupload, all image is invalid */
1946         GPU_free_image(ima);
1947
1948         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1949
1950         BKE_image_release_ibuf(ima, ibuf, NULL);
1951
1952         return OPERATOR_FINISHED;
1953 }
1954
1955 void IMAGE_OT_invert(wmOperatorType *ot)
1956 {
1957         PropertyRNA *prop;
1958
1959         /* identifiers */
1960         ot->name = "Invert Channels";
1961         ot->idname = "IMAGE_OT_invert";
1962         ot->description = "Invert image's channels";
1963         
1964         /* api callbacks */
1965         ot->exec = image_invert_exec;
1966         ot->poll = image_invert_poll;
1967         
1968         /* properties */
1969         prop = RNA_def_boolean(ot->srna, "invert_r", 0, "Red", "Invert Red Channel");
1970         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1971         prop = RNA_def_boolean(ot->srna, "invert_g", 0, "Green", "Invert Green Channel");
1972         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1973         prop = RNA_def_boolean(ot->srna, "invert_b", 0, "Blue", "Invert Blue Channel");
1974         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1975         prop = RNA_def_boolean(ot->srna, "invert_a", 0, "Alpha", "Invert Alpha Channel");
1976         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1977         
1978         /* flags */
1979         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1980 }
1981
1982 /********************* pack operator *********************/
1983
1984 static int image_pack_test(bContext *C, wmOperator *op)
1985 {
1986         Image *ima = CTX_data_edit_image(C);
1987         int as_png = RNA_boolean_get(op->ptr, "as_png");
1988
1989         if (!ima)
1990                 return 0;
1991         if (!as_png && ima->packedfile)
1992                 return 0;
1993
1994         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
1995                 BKE_report(op->reports, RPT_ERROR, "Packing movies or image sequences not supported");
1996                 return 0;
1997         }
1998
1999         return 1;
2000 }
2001
2002 static int image_pack_exec(bContext *C, wmOperator *op)
2003 {
2004         struct Main *bmain = CTX_data_main(C);
2005         Image *ima = CTX_data_edit_image(C);
2006         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
2007         int as_png = RNA_boolean_get(op->ptr, "as_png");
2008
2009         if (!image_pack_test(C, op))
2010                 return OPERATOR_CANCELLED;
2011         
2012         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
2013                 BKE_report(op->reports, RPT_ERROR, "Cannot pack edited image from disk, only as internal PNG");
2014                 return OPERATOR_CANCELLED;
2015         }
2016
2017         if (as_png)
2018                 BKE_image_memorypack(ima);
2019         else
2020                 ima->packedfile = newPackedFile(op->reports, ima->name, ID_BLEND_PATH(bmain, &ima->id));
2021
2022         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
2023
2024         BKE_image_release_ibuf(ima, ibuf, NULL);
2025
2026         return OPERATOR_FINISHED;
2027 }
2028
2029 static int image_pack_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2030 {
2031         Image *ima = CTX_data_edit_image(C);
2032         ImBuf *ibuf;
2033         uiPopupMenu *pup;
2034         uiLayout *layout;
2035         int as_png = RNA_boolean_get(op->ptr, "as_png");
2036
2037         if (!image_pack_test(C, op))
2038                 return OPERATOR_CANCELLED;
2039
2040         ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
2041
2042         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
2043                 pup = uiPupMenuBegin(C, IFACE_("OK"), ICON_QUESTION);
2044                 layout = uiPupMenuLayout(pup);
2045                 uiItemBooleanO(layout, IFACE_("Can't pack edited image from disk, pack as internal PNG?"), ICON_NONE,
2046                                op->idname, "as_png", 1);
2047                 uiPupMenuEnd(C, pup);
2048
2049                 BKE_image_release_ibuf(ima, ibuf, NULL);
2050
2051                 return OPERATOR_CANCELLED;
2052         }
2053
2054         BKE_image_release_ibuf(ima, ibuf, NULL);
2055
2056         return image_pack_exec(C, op);
2057 }
2058
2059 void IMAGE_OT_pack(wmOperatorType *ot)
2060 {
2061         /* identifiers */
2062         ot->name = "Pack Image";
2063         ot->description = "Pack an image as embedded data into the .blend file"; 
2064         ot->idname = "IMAGE_OT_pack";
2065         
2066         /* api callbacks */
2067         ot->exec = image_pack_exec;
2068         ot->invoke = image_pack_invoke;
2069
2070         /* flags */
2071         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2072
2073         /* properties */
2074         RNA_def_boolean(ot->srna, "as_png", 0, "Pack As PNG", "Pack image as lossless PNG");
2075 }
2076
2077 /********************* unpack operator *********************/
2078
2079 static int image_unpack_exec(bContext *C, wmOperator *op)
2080 {
2081         Image *ima = CTX_data_edit_image(C);
2082         int method = RNA_enum_get(op->ptr, "method");
2083
2084         /* find the suppplied image by name */
2085         if (RNA_struct_property_is_set(op->ptr, "id")) {
2086                 char imaname[MAX_ID_NAME - 2];
2087                 RNA_string_get(op->ptr, "id", imaname);
2088                 ima = BLI_findstring(&CTX_data_main(C)->image, imaname, offsetof(ID, name) + 2);
2089                 if (!ima) ima = CTX_data_edit_image(C);
2090         }
2091         
2092         if (!ima || !ima->packedfile)
2093                 return OPERATOR_CANCELLED;
2094
2095         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
2096                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
2097                 return OPERATOR_CANCELLED;
2098         }
2099
2100         if (G.fileflags & G_AUTOPACK)
2101                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
2102         
2103         /* XXX unpackImage frees image buffers */
2104         ED_preview_kill_jobs(C);
2105         
2106         unpackImage(op->reports, ima, method);
2107         
2108         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
2109
2110         return OPERATOR_FINISHED;
2111 }
2112
2113 static int image_unpack_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2114 {
2115         Image *ima = CTX_data_edit_image(C);
2116
2117         if (RNA_struct_property_is_set(op->ptr, "id"))
2118                 return image_unpack_exec(C, op);
2119                 
2120         if (!ima || !ima->packedfile)
2121                 return OPERATOR_CANCELLED;
2122
2123         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
2124                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
2125                 return OPERATOR_CANCELLED;
2126         }
2127
2128         if (G.fileflags & G_AUTOPACK)
2129                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
2130
2131         unpack_menu(C, "IMAGE_OT_unpack", ima->id.name + 2, ima->name, "textures", ima->packedfile);
2132
2133         return OPERATOR_FINISHED;
2134 }
2135
2136 void IMAGE_OT_unpack(wmOperatorType *ot)
2137 {
2138         /* identifiers */
2139         ot->name = "Unpack Image";
2140         ot->description = "Save an image packed in the .blend file to disk"; 
2141         ot->idname = "IMAGE_OT_unpack";
2142         
2143         /* api callbacks */
2144         ot->exec = image_unpack_exec;
2145         ot->invoke = image_unpack_invoke;
2146
2147         /* flags */
2148         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2149         
2150         /* properties */
2151         RNA_def_enum(ot->srna, "method", unpack_method_items, PF_USE_LOCAL, "Method", "How to unpack");
2152         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 */
2153 }
2154
2155 /******************** sample image operator ********************/
2156
2157 typedef struct ImageSampleInfo {
2158         ARegionType *art;
2159         void *draw_handle;
2160         int x, y;
2161         int channels;
2162
2163         unsigned char col[4];
2164         float colf[4];
2165         float linearcol[4];
2166         int z;
2167         float zf;
2168
2169         unsigned char *colp;
2170         float *colfp;
2171         int *zp;
2172         float *zfp;
2173
2174         int draw;
2175         int color_manage;
2176         int use_default_view;
2177 } ImageSampleInfo;
2178
2179 static void image_sample_draw(const bContext *C, ARegion *ar, void *arg_info)
2180 {
2181         ImageSampleInfo *info = arg_info;
2182         if (info->draw) {
2183                 Scene *scene = CTX_data_scene(C);
2184
2185                 ED_image_draw_info(scene, ar, info->color_manage, info->use_default_view, info->channels,
2186                                    info->x, info->y, info->colp, info->colfp, info->linearcol, info->zp, info->zfp);
2187         }
2188 }
2189
2190 /* returns color in SRGB */
2191 /* matching ED_space_node_color_sample() */
2192 int ED_space_image_color_sample(SpaceImage *sima, ARegion *ar, int mval[2], float r_col[3])
2193 {
2194         void *lock;
2195         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2196         float fx, fy;
2197         int ret = FALSE;
2198
2199         if (ibuf == NULL) {
2200                 ED_space_image_release_buffer(sima, ibuf, lock);
2201                 return FALSE;
2202         }
2203
2204         UI_view2d_region_to_view(&ar->v2d, mval[0], mval[1], &fx, &fy);
2205
2206         if (fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) {
2207                 float *fp;
2208                 unsigned char *cp;
2209                 int x = (int)(fx * ibuf->x), y = (int)(fy * ibuf->y);
2210
2211                 CLAMP(x, 0, ibuf->x - 1);
2212                 CLAMP(y, 0, ibuf->y - 1);
2213
2214                 if (ibuf->rect_float) {
2215                         fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
2216                         linearrgb_to_srgb_v3_v3(r_col, fp);
2217                         ret = TRUE;
2218                 }
2219                 else if (ibuf->rect) {
2220                         cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
2221                         rgb_uchar_to_float(r_col, cp);
2222                         ret = TRUE;
2223                 }
2224         }
2225
2226         ED_space_image_release_buffer(sima, ibuf, lock);
2227         return ret;
2228 }
2229
2230 static void image_sample_apply(bContext *C, wmOperator *op, const wmEvent *event)
2231 {
2232         SpaceImage *sima = CTX_wm_space_image(C);
2233         ARegion *ar = CTX_wm_region(C);
2234         void *lock;
2235         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2236         ImageSampleInfo *info = op->customdata;
2237         float fx, fy;
2238         Scene *scene = CTX_data_scene(C);
2239         CurveMapping *curve_mapping = scene->view_settings.curve_mapping;
2240
2241         if (ibuf == NULL) {
2242                 ED_space_image_release_buffer(sima, ibuf, lock);
2243                 info->draw = 0;
2244                 return;
2245         }
2246
2247         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &fx, &fy);
2248
2249         if (fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) {
2250                 float *fp;
2251                 unsigned char *cp;
2252                 int x = (int)(fx * ibuf->x), y = (int)(fy * ibuf->y);
2253                 Image *image = ED_space_image(sima);
2254
2255                 CLAMP(x, 0, ibuf->x - 1);
2256                 CLAMP(y, 0, ibuf->y - 1);
2257
2258                 info->x = x;
2259                 info->y = y;
2260                 info->draw = 1;
2261                 info->channels = ibuf->channels;
2262
2263                 info->colp = NULL;
2264                 info->colfp = NULL;
2265                 info->zp = NULL;
2266                 info->zfp = NULL;
2267
2268                 info->use_default_view = (image->flag & IMA_VIEW_AS_RENDER) ? FALSE : TRUE;
2269
2270                 if (ibuf->rect) {
2271                         cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
2272
2273                         info->col[0] = cp[0];
2274                         info->col[1] = cp[1];
2275                         info->col[2] = cp[2];
2276                         info->col[3] = cp[3];
2277                         info->colp = info->col;
2278
2279                         info->colf[0] = (float)cp[0] / 255.0f;
2280                         info->colf[1] = (float)cp[1] / 255.0f;
2281                         info->colf[2] = (float)cp[2] / 255.0f;
2282                         info->colf[3] = (float)cp[3] / 255.0f;
2283                         info->colfp = info->colf;
2284
2285                         copy_v4_v4(info->linearcol, info->colf);
2286                         IMB_colormanagement_colorspace_to_scene_linear_v4(info->linearcol, false, ibuf->rect_colorspace);
2287
2288                         info->color_manage = TRUE;
2289                 }
2290                 if (ibuf->rect_float) {
2291                         fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
2292
2293                         info->colf[0] = fp[0];
2294                         info->colf[1] = fp[1];
2295                         info->colf[2] = fp[2];
2296                         info->colf[3] = fp[3];
2297                         info->colfp = info->colf;
2298
2299                         copy_v4_v4(info->linearcol, info->colf);
2300
2301                         info->color_manage = TRUE;
2302                 }
2303
2304                 if (ibuf->zbuf) {
2305                         info->z = ibuf->zbuf[y * ibuf->x + x];
2306                         info->zp = &info->z;
2307                 }
2308                 if (ibuf->zbuf_float) {
2309                         info->zf = ibuf->zbuf_float[y * ibuf->x + x];
2310                         info->zfp = &info->zf;
2311                 }
2312
2313                 if (curve_mapping && ibuf->channels == 4) {
2314                         /* we reuse this callback for set curves point operators */
2315                         if (RNA_struct_find_property(op->ptr, "point")) {
2316                                 int point = RNA_enum_get(op->ptr, "point");
2317
2318                                 if (point == 1) {
2319                                         curvemapping_set_black_white(curve_mapping, NULL, info->colfp);
2320                                 }
2321                                 else if (point == 0) {
2322                                         curvemapping_set_black_white(curve_mapping, info->colfp, NULL);
2323                                 }
2324                         }
2325                 }
2326
2327                 // XXX node curve integration ..
2328 #if 0
2329                 {
2330                         ScrArea *sa, *cur = curarea;
2331                         
2332                         node_curvemap_sample(fp);   /* sends global to node editor */
2333                         for (sa = G.curscreen->areabase.first; sa; sa = sa->next) {
2334                                 if (sa->spacetype == SPACE_NODE) {
2335                                         areawinset(sa->win);
2336                                         scrarea_do_windraw(sa);
2337                                 }
2338                         }
2339                         node_curvemap_sample(NULL);     /* clears global in node editor */
2340                         curarea = cur;
2341                 }
2342 #endif
2343         }
2344         else {
2345                 info->draw = 0;
2346         }
2347
2348         ED_space_image_release_buffer(sima, ibuf, lock);
2349         ED_area_tag_redraw(CTX_wm_area(C));
2350 }
2351
2352 static void image_sample_exit(bContext *C, wmOperator *op)
2353 {
2354         ImageSampleInfo *info = op->customdata;
2355
2356         ED_region_draw_cb_exit(info->art, info->draw_handle);
2357         ED_area_tag_redraw(CTX_wm_area(C));
2358         MEM_freeN(info);
2359 }
2360
2361 static int image_sample_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2362 {
2363         SpaceImage *sima = CTX_wm_space_image(C);
2364         ARegion *ar = CTX_wm_region(C);
2365         ImageSampleInfo *info;
2366
2367         if (!ED_space_image_has_buffer(sima))
2368                 return OPERATOR_CANCELLED;
2369         
2370         info = MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
2371         info->art = ar->type;
2372         info->draw_handle = ED_region_draw_cb_activate(ar->type, image_sample_draw, info, REGION_DRAW_POST_PIXEL);
2373         op->customdata = info;
2374
2375         image_sample_apply(C, op, event);
2376
2377         WM_event_add_modal_handler(C, op);
2378
2379         return OPERATOR_RUNNING_MODAL;
2380 }
2381
2382 static int image_sample_modal(bContext *C, wmOperator *op, const wmEvent *event)
2383 {
2384         switch (event->type) {
2385                 case LEFTMOUSE:
2386                 case RIGHTMOUSE: // XXX hardcoded
2387                         image_sample_exit(C, op);
2388                         return OPERATOR_CANCELLED;
2389                 case MOUSEMOVE:
2390                         image_sample_apply(C, op, event);
2391                         break;
2392         }
2393
2394         return OPERATOR_RUNNING_MODAL;
2395 }
2396
2397 static void image_sample_cancel(bContext *C, wmOperator *op)
2398 {
2399         image_sample_exit(C, op);
2400 }
2401
2402 void IMAGE_OT_sample(wmOperatorType *ot)
2403 {
2404         /* identifiers */
2405         ot->name = "Sample Color";
2406         ot->idname = "IMAGE_OT_sample";
2407         ot->description = "Use mouse to sample a color in current image";
2408         
2409         /* api callbacks */
2410         ot->invoke = image_sample_invoke;
2411         ot->modal = image_sample_modal;
2412         ot->cancel = image_sample_cancel;
2413         ot->poll = image_sample_poll;
2414
2415         /* flags */
2416         ot->flag = OPTYPE_BLOCKING;
2417 }
2418
2419 /******************** sample line operator ********************/
2420 static int image_sample_line_exec(bContext *C, wmOperator *op)
2421 {
2422         SpaceImage *sima = CTX_wm_space_image(C);
2423         ARegion *ar = CTX_wm_region(C);
2424         Scene *scene = CTX_data_scene(C);
2425
2426         int x_start = RNA_int_get(op->ptr, "xstart");
2427         int y_start = RNA_int_get(op->ptr, "ystart");
2428         int x_end = RNA_int_get(op->ptr, "xend");
2429         int y_end = RNA_int_get(op->ptr, "yend");
2430         
2431         void *lock;
2432         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2433         Histogram *hist = &sima->sample_line_hist;
2434         
2435         float x1f, y1f, x2f, y2f;
2436         
2437         if (ibuf == NULL) {
2438                 ED_space_image_release_buffer(sima, ibuf, lock);
2439                 return OPERATOR_CANCELLED;
2440         }
2441         /* hmmmm */
2442         if (ibuf->channels < 3) {
2443                 ED_space_image_release_buffer(sima, ibuf, lock);
2444                 return OPERATOR_CANCELLED;
2445         }
2446         
2447         UI_view2d_region_to_view(&ar->v2d, x_start, y_start, &x1f, &y1f);
2448         UI_view2d_region_to_view(&ar->v2d, x_end, y_end, &x2f, &y2f);
2449
2450         hist->co[0][0] = x1f;
2451         hist->co[0][1] = y1f;
2452         hist->co[1][0] = x2f;
2453         hist->co[1][1] = y2f;
2454
2455         /* enable line drawing */
2456         hist->flag |= HISTO_FLAG_SAMPLELINE;
2457
2458         BKE_histogram_update_sample_line(hist, ibuf, &scene->view_settings, &scene->display_settings);
2459         
2460         /* reset y zoom */
2461         hist->ymax = 1.0f;
2462
2463         ED_space_image_release_buffer(sima, ibuf, lock);
2464         
2465         ED_area_tag_redraw(CTX_wm_area(C));
2466         
2467         return OPERATOR_FINISHED;
2468 }
2469
2470 static int image_sample_line_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2471 {
2472         SpaceImage *sima = CTX_wm_space_image(C);
2473
2474         Histogram *hist = &sima->sample_line_hist;
2475         hist->flag &= ~HISTO_FLAG_SAMPLELINE;
2476
2477         if (!ED_space_image_has_buffer(sima))
2478                 return OPERATOR_CANCELLED;
2479         
2480         return WM_gesture_straightline_invoke(C, op, event);
2481 }
2482
2483 void IMAGE_OT_sample_line(wmOperatorType *ot)
2484 {
2485         /* identifiers */
2486         ot->name = "Sample Line";
2487         ot->idname = "IMAGE_OT_sample_line";
2488         ot->description = "Sample a line and show it in Scope panels";
2489         
2490         /* api callbacks */
2491         ot->invoke = image_sample_line_invoke;
2492         ot->modal = WM_gesture_straightline_modal;
2493         ot->exec = image_sample_line_exec;
2494         ot->poll = space_image_main_area_poll;
2495         ot->cancel = WM_gesture_straightline_cancel;
2496         
2497         /* flags */
2498         ot->flag = 0; /* no undo/register since this operates on the space */
2499         
2500         WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT);
2501 }
2502
2503 /******************** set curve point operator ********************/
2504
2505 void IMAGE_OT_curves_point_set(wmOperatorType *ot)
2506 {
2507         static EnumPropertyItem point_items[] = {
2508                 {0, "BLACK_POINT", 0, "Black Point", ""},
2509                 {1, "WHITE_POINT", 0, "White Point", ""},
2510                 {0, NULL, 0, NULL, NULL}
2511         };
2512
2513         /* identifiers */
2514         ot->name = "Set Curves Point";
2515         ot->idname = "IMAGE_OT_curves_point_set";
2516         ot->description = "Set black point or white point for curves";
2517
2518         /* flags */
2519         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2520         
2521         /* api callbacks */
2522         ot->invoke = image_sample_invoke;
2523         ot->modal = image_sample_modal;
2524         ot->cancel = image_sample_cancel;
2525         ot->poll = space_image_main_area_not_uv_brush_poll;
2526
2527         /* properties */
2528         RNA_def_enum(ot->srna, "point", point_items, 0, "Point", "Set black point or white point for curves");
2529 }
2530
2531 #if 0 /* Not ported to 2.5x yet */
2532 /******************** record composite operator *********************/
2533
2534 typedef struct RecordCompositeData {
2535         wmTimer *timer;
2536         int old_cfra;
2537         int sfra, efra;
2538 } RecordCompositeData;
2539
2540 static int image_record_composite_apply(bContext *C, wmOperator *op)
2541 {
2542         SpaceImage *sima = CTX_wm_space_image(C);
2543         RecordCompositeData *rcd = op->customdata;
2544         Scene *scene = CTX_data_scene(C);
2545         ImBuf *ibuf;
2546         
2547         WM_cursor_time(CTX_wm_window(C), scene->r.cfra);
2548
2549         // XXX scene->nodetree->test_break = blender_test_break;
2550         // XXX scene->nodetree->test_break = NULL;
2551         
2552         BKE_image_all_free_anim_ibufs(scene->r.cfra);
2553         ntreeCompositTagAnimated(scene->nodetree);
2554         ntreeCompositExecTree(scene->nodetree, &scene->r, 0, scene->r.cfra != rcd->old_cfra,
2555                               &scene->view_settings, &scene->display_settings);  /* 1 is no previews */
2556
2557         ED_area_tag_redraw(CTX_wm_area(C));
2558         
2559         ibuf = BKE_image_acquire_ibuf(sima->image, &sima->iuser, NULL);
2560         /* save memory in flipbooks */
2561         if (ibuf)
2562                 imb_freerectfloatImBuf(ibuf);
2563
2564         BKE_image_release_ibuf(sima->image, ibuf, NULL);
2565
2566         scene->r.cfra++;
2567
2568         return (scene->r.cfra <= rcd->efra);
2569 }
2570
2571 static int image_record_composite_init(bContext *C, wmOperator *op)
2572 {
2573         SpaceImage *sima = CTX_wm_space_image(C);
2574         Scene *scene = CTX_data_scene(C);
2575         RecordCompositeData *rcd;
2576
2577         if (sima->iuser.frames < 2)
2578                 return 0;
2579         if (scene->nodetree == NULL)
2580                 return 0;
2581         
2582         op->customdata = rcd = MEM_callocN(sizeof(RecordCompositeData), "ImageRecordCompositeData");
2583
2584         rcd->old_cfra = scene->r.cfra;
2585         rcd->sfra = sima->iuser.sfra;
2586         rcd->efra = sima->iuser.sfra + sima->iuser.frames - 1;
2587         scene->r.cfra = rcd->sfra;
2588
2589         return 1;
2590 }
2591
2592 static void image_record_composite_exit(bContext *C, wmOperator *op)
2593 {
2594         Scene *scene = CTX_data_scene(C);
2595         SpaceImage *sima = CTX_wm_space_image(C);
2596         RecordCompositeData *rcd = op->customdata;
2597
2598         scene->r.cfra = rcd->old_cfra;
2599
2600         WM_cursor_modal_restore(CTX_wm_window(C));
2601
2602         if (rcd->timer)
2603                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rcd->timer);
2604
2605         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
2606
2607         // XXX play_anim(0);
2608         // XXX allqueue(REDRAWNODE, 1);
2609
2610         MEM_freeN(rcd);
2611 }
2612
2613 static int image_record_composite_exec(bContext *C, wmOperator *op)
2614 {
2615         if (!image_record_composite_init(C, op))
2616                 return OPERATOR_CANCELLED;
2617         
2618         while (image_record_composite_apply(C, op)) {}
2619         
2620         image_record_composite_exit(C, op);
2621         
2622         return OPERATOR_FINISHED;
2623 }
2624
2625 static int image_record_composite_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2626 {
2627         RecordCompositeData *rcd;
2628         
2629         if (!image_record_composite_init(C, op))
2630                 return OPERATOR_CANCELLED;
2631
2632         rcd = op->customdata;
2633         rcd->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.0f);
2634         WM_event_add_modal_handler(C, op);
2635
2636         if (!image_record_composite_apply(C, op))
2637                 return OPERATOR_FINISHED;
2638
2639         return OPERATOR_RUNNING_MODAL;
2640 }
2641
2642 static int image_record_composite_modal(bContext *C, wmOperator *op, const wmEvent *event)
2643 {
2644         RecordCompositeData *rcd = op->customdata;
2645
2646         switch (event->type) {
2647                 case TIMER:
2648                         if (rcd->timer == event->customdata) {
2649                                 if (!image_record_composite_apply(C, op)) {
2650                                         image_record_composite_exit(C, op);
2651                                         return OPERATOR_FINISHED;
2652                                 }
2653                         }
2654                         break;
2655                 case ESCKEY:
2656                         image_record_composite_exit(C, op);
2657                         return OPERATOR_FINISHED;
2658         }
2659
2660         return OPERATOR_RUNNING_MODAL;
2661 }
2662
2663 static void image_record_composite_cancel(bContext *C, wmOperator *op)
2664 {
2665         image_record_composite_exit(C, op);
2666         return OPERATOR_CANCELLED;
2667 }
2668
2669 void IMAGE_OT_record_composite(wmOperatorType *ot)
2670 {
2671         /* identifiers */
2672         ot->name = "Record Composite";
2673         ot->idname = "IMAGE_OT_record_composite";
2674         
2675         /* api callbacks */
2676         ot->exec = image_record_composite_exec;
2677         ot->invoke = image_record_composite_invoke;
2678         ot->modal = image_record_composite_modal;
2679         ot->cancel = image_record_composite_cancel;
2680         ot->poll = space_image_buffer_exists_poll;
2681 }
2682
2683 #endif
2684
2685 /********************* cycle render slot operator *********************/
2686
2687 static int image_cycle_render_slot_poll(bContext *C)
2688 {
2689         Image *ima = CTX_data_edit_image(C);
2690
2691         return (ima && ima->type == IMA_TYPE_R_RESULT);
2692 }
2693
2694 static int image_cycle_render_slot_exec(bContext *C, wmOperator *op)
2695 {
2696         Image *ima = CTX_data_edit_image(C);
2697         int a, slot, cur = ima->render_slot;
2698         const short use_reverse = RNA_boolean_get(op->ptr, "reverse");
2699
2700         for (a = 1; a < IMA_MAX_RENDER_SLOT; a++) {
2701                 slot = (cur + (use_reverse ? -a : a)) % IMA_MAX_RENDER_SLOT;
2702                 if (slot < 0) slot += IMA_MAX_RENDER_SLOT;
2703
2704                 if (ima->renders[slot] || slot == ima->last_render_slot) {
2705                         ima->render_slot = slot;
2706                         break;
2707                 }
2708         }
2709
2710         if (a == IMA_MAX_RENDER_SLOT)
2711                 ima->render_slot = ((cur == 1) ? 0 : 1);
2712         
2713         WM_event_add_notifier(C, NC_IMAGE | ND_DRAW, NULL);
2714
2715         /* no undo push for browsing existing */
2716         if (ima->renders[ima->render_slot] || ima->render_slot == ima->last_render_slot)
2717                 return OPERATOR_CANCELLED;
2718         
2719         return OPERATOR_FINISHED;
2720 }
2721
2722 void IMAGE_OT_cycle_render_slot(wmOperatorType *ot)
2723 {
2724         /* identifiers */
2725         ot->name = "Cycle Render Slot";
2726         ot->idname = "IMAGE_OT_cycle_render_slot";
2727         ot->description = "Cycle through all non-void render slots";
2728         
2729         /* api callbacks */
2730         ot->exec = image_cycle_render_slot_exec;
2731         ot->poll = image_cycle_render_slot_poll;
2732
2733         /* flags */
2734         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2735
2736         RNA_def_boolean(ot->srna, "reverse", 0, "Cycle in Reverse", "");
2737 }