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