Fix #36981, Removing Sample line fails during render.
[blender.git] / source / blender / editors / space_image / image_ops.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2002-2009, Xavier Thomas
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/space_image/image_ops.c
27  *  \ingroup spimage
28  */
29
30
31 #include <stddef.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <errno.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_math.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_utildefines.h"
41
42 #include "BLF_translation.h"
43
44 #include "DNA_object_types.h"
45 #include "DNA_node_types.h"
46 #include "DNA_packedFile_types.h"
47 #include "DNA_scene_types.h"
48
49 #include "BKE_colortools.h"
50 #include "BKE_context.h"
51 #include "BKE_icons.h"
52 #include "BKE_image.h"
53 #include "BKE_global.h"
54 #include "BKE_library.h"
55 #include "BKE_main.h"
56 #include "BKE_node.h"
57 #include "BKE_packedFile.h"
58 #include "BKE_report.h"
59 #include "BKE_screen.h"
60
61 #include "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         WM_event_add_notifier(C, NC_IMAGE | NA_ADDED, ima);
1808         
1809         return OPERATOR_FINISHED;
1810 }
1811
1812 /* XXX, Ton is not a fan of OK buttons but using this function to avoid undo/redo bug while in mesh-editmode, - campbell */
1813 /* XXX Note: the WM_operator_props_dialog_popup() doesn't work for uiIDContextProperty(), image is not being that way */
1814 static int image_new_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1815 {
1816         /* Better for user feedback. */
1817         RNA_string_set(op->ptr, "name", DATA_(IMA_DEF_NAME));
1818         return WM_operator_props_dialog_popup(C, op, 15 * UI_UNIT_X, 5 * UI_UNIT_Y);
1819 }
1820
1821 void IMAGE_OT_new(wmOperatorType *ot)
1822 {
1823         PropertyRNA *prop;
1824         static float default_color[4] = {0.0f, 0.0f, 0.0f, 1.0f};
1825         
1826         /* identifiers */
1827         ot->name = "New Image";
1828         ot->description = "Create a new image";
1829         ot->idname = "IMAGE_OT_new";
1830         
1831         /* api callbacks */
1832         ot->exec = image_new_exec;
1833         ot->invoke = image_new_invoke;
1834         
1835         /* flags */
1836         ot->flag = OPTYPE_UNDO;
1837
1838         /* properties */
1839         RNA_def_string(ot->srna, "name", IMA_DEF_NAME, MAX_ID_NAME - 2, "Name", "Image datablock name");
1840         RNA_def_int(ot->srna, "width", 1024, 1, INT_MAX, "Width", "Image width", 1, 16384);
1841         RNA_def_int(ot->srna, "height", 1024, 1, INT_MAX, "Height", "Image height", 1, 16384);
1842         prop = RNA_def_float_color(ot->srna, "color", 4, NULL, 0.0f, FLT_MAX, "Color", "Default fill color", 0.0f, 1.0f);
1843         RNA_def_property_subtype(prop, PROP_COLOR_GAMMA);
1844         RNA_def_property_float_array_default(prop, default_color);
1845         RNA_def_boolean(ot->srna, "alpha", 1, "Alpha", "Create an image with an alpha channel");
1846         RNA_def_enum(ot->srna, "generated_type", image_generated_type_items, IMA_GENTYPE_BLANK,
1847                      "Generated Type", "Fill the image with a grid for UV map testing");
1848         RNA_def_boolean(ot->srna, "float", 0, "32 bit Float", "Create image with 32 bit floating point bit depth");
1849 }
1850
1851 #undef IMA_DEF_NAME
1852
1853 /********************* invert operators *********************/
1854
1855 static int image_invert_poll(bContext *C)
1856 {
1857         Image *ima = CTX_data_edit_image(C);
1858
1859         return BKE_image_has_ibuf(ima, NULL);
1860 }
1861
1862 static int image_invert_exec(bContext *C, wmOperator *op)
1863 {
1864         Image *ima = CTX_data_edit_image(C);
1865         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
1866
1867         /* flags indicate if this channel should be inverted */
1868         const short r = RNA_boolean_get(op->ptr, "invert_r");
1869         const short g = RNA_boolean_get(op->ptr, "invert_g");
1870         const short b = RNA_boolean_get(op->ptr, "invert_b");
1871         const short a = RNA_boolean_get(op->ptr, "invert_a");
1872
1873         int i;
1874
1875         if (ibuf == NULL)  /* TODO: this should actually never happen, but does for render-results -> cleanup */
1876                 return OPERATOR_CANCELLED;
1877
1878         /* TODO: make this into an IMB_invert_channels(ibuf,r,g,b,a) method!? */
1879         if (ibuf->rect_float) {
1880                 
1881                 float *fp = (float *) ibuf->rect_float;
1882                 for (i = ibuf->x * ibuf->y; i > 0; i--, fp += 4) {
1883                         if (r) fp[0] = 1.0f - fp[0];
1884                         if (g) fp[1] = 1.0f - fp[1];
1885                         if (b) fp[2] = 1.0f - fp[2];
1886                         if (a) fp[3] = 1.0f - fp[3];
1887                 }
1888
1889                 if (ibuf->rect) {
1890                         IMB_rect_from_float(ibuf);
1891                 }
1892         }
1893         else if (ibuf->rect) {
1894                 
1895                 char *cp = (char *) ibuf->rect;
1896                 for (i = ibuf->x * ibuf->y; i > 0; i--, cp += 4) {
1897                         if (r) cp[0] = 255 - cp[0];
1898                         if (g) cp[1] = 255 - cp[1];
1899                         if (b) cp[2] = 255 - cp[2];
1900                         if (a) cp[3] = 255 - cp[3];
1901                 }
1902         }
1903         else {
1904                 BKE_image_release_ibuf(ima, ibuf, NULL);
1905                 return OPERATOR_CANCELLED;
1906         }
1907
1908         ibuf->userflags |= IB_BITMAPDIRTY;
1909         if (ibuf->mipmap[0])
1910                 ibuf->userflags |= IB_MIPMAP_INVALID;
1911
1912         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1913
1914         BKE_image_release_ibuf(ima, ibuf, NULL);
1915
1916         return OPERATOR_FINISHED;
1917 }
1918
1919 void IMAGE_OT_invert(wmOperatorType *ot)
1920 {
1921         PropertyRNA *prop;
1922
1923         /* identifiers */
1924         ot->name = "Invert Channels";
1925         ot->idname = "IMAGE_OT_invert";
1926         ot->description = "Invert image's channels";
1927         
1928         /* api callbacks */
1929         ot->exec = image_invert_exec;
1930         ot->poll = image_invert_poll;
1931         
1932         /* properties */
1933         prop = RNA_def_boolean(ot->srna, "invert_r", 0, "Red", "Invert Red Channel");
1934         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1935         prop = RNA_def_boolean(ot->srna, "invert_g", 0, "Green", "Invert Green Channel");
1936         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1937         prop = RNA_def_boolean(ot->srna, "invert_b", 0, "Blue", "Invert Blue Channel");
1938         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1939         prop = RNA_def_boolean(ot->srna, "invert_a", 0, "Alpha", "Invert Alpha Channel");
1940         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1941         
1942         /* flags */
1943         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1944 }
1945
1946 /********************* pack operator *********************/
1947
1948 static int image_pack_test(bContext *C, wmOperator *op)
1949 {
1950         Image *ima = CTX_data_edit_image(C);
1951         int as_png = RNA_boolean_get(op->ptr, "as_png");
1952
1953         if (!ima)
1954                 return 0;
1955         if (!as_png && ima->packedfile)
1956                 return 0;
1957
1958         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
1959                 BKE_report(op->reports, RPT_ERROR, "Packing movies or image sequences not supported");
1960                 return 0;
1961         }
1962
1963         return 1;
1964 }
1965
1966 static int image_pack_exec(bContext *C, wmOperator *op)
1967 {
1968         struct Main *bmain = CTX_data_main(C);
1969         Image *ima = CTX_data_edit_image(C);
1970         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
1971         int as_png = RNA_boolean_get(op->ptr, "as_png");
1972
1973         if (!image_pack_test(C, op))
1974                 return OPERATOR_CANCELLED;
1975         
1976         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1977                 BKE_report(op->reports, RPT_ERROR, "Cannot pack edited image from disk, only as internal PNG");
1978                 return OPERATOR_CANCELLED;
1979         }
1980
1981         if (as_png)
1982                 BKE_image_memorypack(ima);
1983         else
1984                 ima->packedfile = newPackedFile(op->reports, ima->name, ID_BLEND_PATH(bmain, &ima->id));
1985
1986         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1987
1988         BKE_image_release_ibuf(ima, ibuf, NULL);
1989
1990         return OPERATOR_FINISHED;
1991 }
1992
1993 static int image_pack_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1994 {
1995         Image *ima = CTX_data_edit_image(C);
1996         ImBuf *ibuf;
1997         uiPopupMenu *pup;
1998         uiLayout *layout;
1999         int as_png = RNA_boolean_get(op->ptr, "as_png");
2000
2001         if (!image_pack_test(C, op))
2002                 return OPERATOR_CANCELLED;
2003
2004         ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
2005
2006         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
2007                 pup = uiPupMenuBegin(C, IFACE_("OK"), ICON_QUESTION);
2008                 layout = uiPupMenuLayout(pup);
2009                 uiItemBooleanO(layout, IFACE_("Can't pack edited image from disk, pack as internal PNG?"), ICON_NONE,
2010                                op->idname, "as_png", 1);
2011                 uiPupMenuEnd(C, pup);
2012
2013                 BKE_image_release_ibuf(ima, ibuf, NULL);
2014
2015                 return OPERATOR_CANCELLED;
2016         }
2017
2018         BKE_image_release_ibuf(ima, ibuf, NULL);
2019
2020         return image_pack_exec(C, op);
2021 }
2022
2023 void IMAGE_OT_pack(wmOperatorType *ot)
2024 {
2025         /* identifiers */
2026         ot->name = "Pack Image";
2027         ot->description = "Pack an image as embedded data into the .blend file"; 
2028         ot->idname = "IMAGE_OT_pack";
2029         
2030         /* api callbacks */
2031         ot->exec = image_pack_exec;
2032         ot->invoke = image_pack_invoke;
2033
2034         /* flags */
2035         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2036
2037         /* properties */
2038         RNA_def_boolean(ot->srna, "as_png", 0, "Pack As PNG", "Pack image as lossless PNG");
2039 }
2040
2041 /********************* unpack operator *********************/
2042
2043 static int image_unpack_exec(bContext *C, wmOperator *op)
2044 {
2045         Image *ima = CTX_data_edit_image(C);
2046         int method = RNA_enum_get(op->ptr, "method");
2047
2048         /* find the suppplied image by name */
2049         if (RNA_struct_property_is_set(op->ptr, "id")) {
2050                 char imaname[MAX_ID_NAME - 2];
2051                 RNA_string_get(op->ptr, "id", imaname);
2052                 ima = BLI_findstring(&CTX_data_main(C)->image, imaname, offsetof(ID, name) + 2);
2053                 if (!ima) ima = CTX_data_edit_image(C);
2054         }
2055         
2056         if (!ima || !ima->packedfile)
2057                 return OPERATOR_CANCELLED;
2058
2059         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
2060                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
2061                 return OPERATOR_CANCELLED;
2062         }
2063
2064         if (G.fileflags & G_AUTOPACK)
2065                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
2066         
2067         /* XXX unpackImage frees image buffers */
2068         ED_preview_kill_jobs(C);
2069         
2070         unpackImage(op->reports, ima, method);
2071         
2072         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
2073
2074         return OPERATOR_FINISHED;
2075 }
2076
2077 static int image_unpack_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2078 {
2079         Image *ima = CTX_data_edit_image(C);
2080
2081         if (RNA_struct_property_is_set(op->ptr, "id"))
2082                 return image_unpack_exec(C, op);
2083                 
2084         if (!ima || !ima->packedfile)
2085                 return OPERATOR_CANCELLED;
2086
2087         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
2088                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
2089                 return OPERATOR_CANCELLED;
2090         }
2091
2092         if (G.fileflags & G_AUTOPACK)
2093                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
2094
2095         unpack_menu(C, "IMAGE_OT_unpack", ima->id.name + 2, ima->name, "textures", ima->packedfile);
2096
2097         return OPERATOR_FINISHED;
2098 }
2099
2100 void IMAGE_OT_unpack(wmOperatorType *ot)
2101 {
2102         /* identifiers */
2103         ot->name = "Unpack Image";
2104         ot->description = "Save an image packed in the .blend file to disk"; 
2105         ot->idname = "IMAGE_OT_unpack";
2106         
2107         /* api callbacks */
2108         ot->exec = image_unpack_exec;
2109         ot->invoke = image_unpack_invoke;
2110
2111         /* flags */
2112         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2113         
2114         /* properties */
2115         RNA_def_enum(ot->srna, "method", unpack_method_items, PF_USE_LOCAL, "Method", "How to unpack");
2116         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 */
2117 }
2118
2119 /******************** sample image operator ********************/
2120
2121 typedef struct ImageSampleInfo {
2122         ARegionType *art;
2123         void *draw_handle;
2124         int x, y;
2125         int channels;
2126
2127         unsigned char col[4];
2128         float colf[4];
2129         float linearcol[4];
2130         int z;
2131         float zf;
2132
2133         unsigned char *colp;
2134         float *colfp;
2135         int *zp;
2136         float *zfp;
2137
2138         int draw;
2139         int color_manage;
2140         int use_default_view;
2141 } ImageSampleInfo;
2142
2143 static void image_sample_draw(const bContext *C, ARegion *ar, void *arg_info)
2144 {
2145         ImageSampleInfo *info = arg_info;
2146         if (info->draw) {
2147                 Scene *scene = CTX_data_scene(C);
2148
2149                 ED_image_draw_info(scene, ar, info->color_manage, info->use_default_view, info->channels,
2150                                    info->x, info->y, info->colp, info->colfp, info->linearcol, info->zp, info->zfp);
2151         }
2152 }
2153
2154 /* returns color in SRGB */
2155 /* matching ED_space_node_color_sample() */
2156 int ED_space_image_color_sample(SpaceImage *sima, ARegion *ar, int mval[2], float r_col[3])
2157 {
2158         void *lock;
2159         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2160         float fx, fy;
2161         int ret = FALSE;
2162
2163         if (ibuf == NULL) {
2164                 ED_space_image_release_buffer(sima, ibuf, lock);
2165                 return FALSE;
2166         }
2167
2168         UI_view2d_region_to_view(&ar->v2d, mval[0], mval[1], &fx, &fy);
2169
2170         if (fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) {
2171                 float *fp;
2172                 unsigned char *cp;
2173                 int x = (int)(fx * ibuf->x), y = (int)(fy * ibuf->y);
2174
2175                 CLAMP(x, 0, ibuf->x - 1);
2176                 CLAMP(y, 0, ibuf->y - 1);
2177
2178                 if (ibuf->rect_float) {
2179                         fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
2180                         linearrgb_to_srgb_v3_v3(r_col, fp);
2181                         ret = TRUE;
2182                 }
2183                 else if (ibuf->rect) {
2184                         cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
2185                         rgb_uchar_to_float(r_col, cp);
2186                         ret = TRUE;
2187                 }
2188         }
2189
2190         ED_space_image_release_buffer(sima, ibuf, lock);
2191         return ret;
2192 }
2193
2194 static void image_sample_apply(bContext *C, wmOperator *op, const wmEvent *event)
2195 {
2196         SpaceImage *sima = CTX_wm_space_image(C);
2197         ARegion *ar = CTX_wm_region(C);
2198         void *lock;
2199         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2200         ImageSampleInfo *info = op->customdata;
2201         float fx, fy;
2202         Scene *scene = CTX_data_scene(C);
2203         CurveMapping *curve_mapping = scene->view_settings.curve_mapping;
2204
2205         if (ibuf == NULL) {
2206                 ED_space_image_release_buffer(sima, ibuf, lock);
2207                 info->draw = 0;
2208                 return;
2209         }
2210
2211         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &fx, &fy);
2212
2213         if (fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) {
2214                 float *fp;
2215                 unsigned char *cp;
2216                 int x = (int)(fx * ibuf->x), y = (int)(fy * ibuf->y);
2217                 Image *image = ED_space_image(sima);
2218
2219                 CLAMP(x, 0, ibuf->x - 1);
2220                 CLAMP(y, 0, ibuf->y - 1);
2221
2222                 info->x = x;
2223                 info->y = y;
2224                 info->draw = 1;
2225                 info->channels = ibuf->channels;
2226
2227                 info->colp = NULL;
2228                 info->colfp = NULL;
2229                 info->zp = NULL;
2230                 info->zfp = NULL;
2231
2232                 info->use_default_view = (image->flag & IMA_VIEW_AS_RENDER) ? FALSE : TRUE;
2233
2234                 if (ibuf->rect) {
2235                         cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
2236
2237                         info->col[0] = cp[0];
2238                         info->col[1] = cp[1];
2239                         info->col[2] = cp[2];
2240                         info->col[3] = cp[3];
2241                         info->colp = info->col;
2242
2243                         info->colf[0] = (float)cp[0] / 255.0f;
2244                         info->colf[1] = (float)cp[1] / 255.0f;
2245                         info->colf[2] = (float)cp[2] / 255.0f;
2246                         info->colf[3] = (float)cp[3] / 255.0f;
2247                         info->colfp = info->colf;
2248
2249                         copy_v4_v4(info->linearcol, info->colf);
2250                         IMB_colormanagement_colorspace_to_scene_linear_v4(info->linearcol, false, ibuf->rect_colorspace);
2251
2252                         info->color_manage = TRUE;
2253                 }
2254                 if (ibuf->rect_float) {
2255                         fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
2256
2257                         info->colf[0] = fp[0];
2258                         info->colf[1] = fp[1];
2259                         info->colf[2] = fp[2];
2260                         info->colf[3] = fp[3];
2261                         info->colfp = info->colf;
2262
2263                         copy_v4_v4(info->linearcol, info->colf);
2264
2265                         info->color_manage = TRUE;
2266                 }
2267
2268                 if (ibuf->zbuf) {
2269                         info->z = ibuf->zbuf[y * ibuf->x + x];
2270                         info->zp = &info->z;
2271                 }
2272                 if (ibuf->zbuf_float) {
2273                         info->zf = ibuf->zbuf_float[y * ibuf->x + x];
2274                         info->zfp = &info->zf;
2275                 }
2276
2277                 if (curve_mapping && ibuf->channels == 4) {
2278                         /* we reuse this callback for set curves point operators */
2279                         if (RNA_struct_find_property(op->ptr, "point")) {
2280                                 int point = RNA_enum_get(op->ptr, "point");
2281
2282                                 if (point == 1) {
2283                                         curvemapping_set_black_white(curve_mapping, NULL, info->colfp);
2284                                 }
2285                                 else if (point == 0) {
2286                                         curvemapping_set_black_white(curve_mapping, info->colfp, NULL);
2287                                 }
2288                         }
2289                 }
2290
2291                 // XXX node curve integration ..
2292 #if 0
2293                 {
2294                         ScrArea *sa, *cur = curarea;
2295                         
2296                         node_curvemap_sample(fp);   /* sends global to node editor */
2297                         for (sa = G.curscreen->areabase.first; sa; sa = sa->next) {
2298                                 if (sa->spacetype == SPACE_NODE) {
2299                                         areawinset(sa->win);
2300                                         scrarea_do_windraw(sa);
2301                                 }
2302                         }
2303                         node_curvemap_sample(NULL);     /* clears global in node editor */
2304                         curarea = cur;
2305                 }
2306 #endif
2307         }
2308         else {
2309                 info->draw = 0;
2310         }
2311
2312         ED_space_image_release_buffer(sima, ibuf, lock);
2313         ED_area_tag_redraw(CTX_wm_area(C));
2314 }
2315
2316 static void image_sample_exit(bContext *C, wmOperator *op)
2317 {
2318         ImageSampleInfo *info = op->customdata;
2319
2320         ED_region_draw_cb_exit(info->art, info->draw_handle);
2321         ED_area_tag_redraw(CTX_wm_area(C));
2322         MEM_freeN(info);
2323 }
2324
2325 static int image_sample_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2326 {
2327         SpaceImage *sima = CTX_wm_space_image(C);
2328         ARegion *ar = CTX_wm_region(C);
2329         ImageSampleInfo *info;
2330
2331         if (!ED_space_image_has_buffer(sima))
2332                 return OPERATOR_CANCELLED;
2333         
2334         info = MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
2335         info->art = ar->type;
2336         info->draw_handle = ED_region_draw_cb_activate(ar->type, image_sample_draw, info, REGION_DRAW_POST_PIXEL);
2337         op->customdata = info;
2338
2339         image_sample_apply(C, op, event);
2340
2341         WM_event_add_modal_handler(C, op);
2342
2343         return OPERATOR_RUNNING_MODAL;
2344 }
2345
2346 static int image_sample_modal(bContext *C, wmOperator *op, const wmEvent *event)
2347 {
2348         switch (event->type) {
2349                 case LEFTMOUSE:
2350                 case RIGHTMOUSE: // XXX hardcoded
2351                         image_sample_exit(C, op);
2352                         return OPERATOR_CANCELLED;
2353                 case MOUSEMOVE:
2354                         image_sample_apply(C, op, event);
2355                         break;
2356         }
2357
2358         return OPERATOR_RUNNING_MODAL;
2359 }
2360
2361 static int image_sample_cancel(bContext *C, wmOperator *op)
2362 {
2363         image_sample_exit(C, op);
2364         return OPERATOR_CANCELLED;
2365 }
2366
2367 void IMAGE_OT_sample(wmOperatorType *ot)
2368 {
2369         /* identifiers */
2370         ot->name = "Sample Color";
2371         ot->idname = "IMAGE_OT_sample";
2372         ot->description = "Use mouse to sample a color in current image";
2373         
2374         /* api callbacks */
2375         ot->invoke = image_sample_invoke;
2376         ot->modal = image_sample_modal;
2377         ot->cancel = image_sample_cancel;
2378         ot->poll = image_sample_poll;
2379
2380         /* flags */
2381         ot->flag = OPTYPE_BLOCKING;
2382 }
2383
2384 /******************** sample line operator ********************/
2385 static int image_sample_line_exec(bContext *C, wmOperator *op)
2386 {
2387         SpaceImage *sima = CTX_wm_space_image(C);
2388         ARegion *ar = CTX_wm_region(C);
2389         Scene *scene = CTX_data_scene(C);
2390
2391         int x_start = RNA_int_get(op->ptr, "xstart");
2392         int y_start = RNA_int_get(op->ptr, "ystart");
2393         int x_end = RNA_int_get(op->ptr, "xend");
2394         int y_end = RNA_int_get(op->ptr, "yend");
2395         
2396         void *lock;
2397         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2398         Histogram *hist = &sima->sample_line_hist;
2399         
2400         float x1f, y1f, x2f, y2f;
2401         
2402         if (ibuf == NULL) {
2403                 ED_space_image_release_buffer(sima, ibuf, lock);
2404                 return OPERATOR_CANCELLED;
2405         }
2406         /* hmmmm */
2407         if (ibuf->channels < 3) {
2408                 ED_space_image_release_buffer(sima, ibuf, lock);
2409                 return OPERATOR_CANCELLED;
2410         }
2411         
2412         UI_view2d_region_to_view(&ar->v2d, x_start, y_start, &x1f, &y1f);
2413         UI_view2d_region_to_view(&ar->v2d, x_end, y_end, &x2f, &y2f);
2414
2415         hist->co[0][0] = x1f;
2416         hist->co[0][1] = y1f;
2417         hist->co[1][0] = x2f;
2418         hist->co[1][1] = y2f;
2419
2420         /* enable line drawing */
2421         hist->flag |= HISTO_FLAG_SAMPLELINE;
2422
2423         BKE_histogram_update_sample_line(hist, ibuf, &scene->view_settings, &scene->display_settings);
2424         
2425         /* reset y zoom */
2426         hist->ymax = 1.0f;
2427
2428         ED_space_image_release_buffer(sima, ibuf, lock);
2429         
2430         ED_area_tag_redraw(CTX_wm_area(C));
2431         
2432         return OPERATOR_FINISHED;
2433 }
2434
2435 static int image_sample_line_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2436 {
2437         SpaceImage *sima = CTX_wm_space_image(C);
2438
2439         Histogram *hist = &sima->sample_line_hist;
2440         hist->flag &= ~HISTO_FLAG_SAMPLELINE;
2441
2442         if (!ED_space_image_has_buffer(sima))
2443                 return OPERATOR_CANCELLED;
2444         
2445         return WM_gesture_straightline_invoke(C, op, event);
2446 }
2447
2448 void IMAGE_OT_sample_line(wmOperatorType *ot)
2449 {
2450         /* identifiers */
2451         ot->name = "Sample Line";
2452         ot->idname = "IMAGE_OT_sample_line";
2453         ot->description = "Sample a line and show it in Scope panels";
2454         
2455         /* api callbacks */
2456         ot->invoke = image_sample_line_invoke;
2457         ot->modal = WM_gesture_straightline_modal;
2458         ot->exec = image_sample_line_exec;
2459         ot->poll = space_image_main_area_poll;
2460         ot->cancel = WM_gesture_straightline_cancel;
2461         
2462         /* flags */
2463         ot->flag = 0; /* no undo/register since this operates on the space */
2464         
2465         WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT);
2466 }
2467
2468 /******************** set curve point operator ********************/
2469
2470 void IMAGE_OT_curves_point_set(wmOperatorType *ot)
2471 {
2472         static EnumPropertyItem point_items[] = {
2473                 {0, "BLACK_POINT", 0, "Black Point", ""},
2474                 {1, "WHITE_POINT", 0, "White Point", ""},
2475                 {0, NULL, 0, NULL, NULL}
2476         };
2477
2478         /* identifiers */
2479         ot->name = "Set Curves Point";
2480         ot->idname = "IMAGE_OT_curves_point_set";
2481         ot->description = "Set black point or white point for curves";
2482
2483         /* flags */
2484         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2485         
2486         /* api callbacks */
2487         ot->invoke = image_sample_invoke;
2488         ot->modal = image_sample_modal;
2489         ot->cancel = image_sample_cancel;
2490         ot->poll = space_image_main_area_not_uv_brush_poll;
2491
2492         /* properties */
2493         RNA_def_enum(ot->srna, "point", point_items, 0, "Point", "Set black point or white point for curves");
2494 }
2495
2496 #if 0 /* Not ported to 2.5x yet */
2497 /******************** record composite operator *********************/
2498
2499 typedef struct RecordCompositeData {
2500         wmTimer *timer;
2501         int old_cfra;
2502         int sfra, efra;
2503 } RecordCompositeData;
2504
2505 static int image_record_composite_apply(bContext *C, wmOperator *op)
2506 {
2507         SpaceImage *sima = CTX_wm_space_image(C);
2508         RecordCompositeData *rcd = op->customdata;
2509         Scene *scene = CTX_data_scene(C);
2510         ImBuf *ibuf;
2511         
2512         WM_cursor_time(CTX_wm_window(C), scene->r.cfra);
2513
2514         // XXX scene->nodetree->test_break = blender_test_break;
2515         // XXX scene->nodetree->test_break = NULL;
2516         
2517         BKE_image_all_free_anim_ibufs(scene->r.cfra);
2518         ntreeCompositTagAnimated(scene->nodetree);
2519         ntreeCompositExecTree(scene->nodetree, &scene->r, 0, scene->r.cfra != rcd->old_cfra,
2520                               &scene->view_settings, &scene->display_settings);  /* 1 is no previews */
2521
2522         ED_area_tag_redraw(CTX_wm_area(C));
2523         
2524         ibuf = BKE_image_acquire_ibuf(sima->image, &sima->iuser, NULL);
2525         /* save memory in flipbooks */
2526         if (ibuf)
2527                 imb_freerectfloatImBuf(ibuf);
2528
2529         BKE_image_release_ibuf(sima->image, ibuf, NULL);
2530
2531         scene->r.cfra++;
2532
2533         return (scene->r.cfra <= rcd->efra);
2534 }
2535
2536 static int image_record_composite_init(bContext *C, wmOperator *op)
2537 {
2538         SpaceImage *sima = CTX_wm_space_image(C);
2539         Scene *scene = CTX_data_scene(C);
2540         RecordCompositeData *rcd;
2541
2542         if (sima->iuser.frames < 2)
2543                 return 0;
2544         if (scene->nodetree == NULL)
2545                 return 0;
2546         
2547         op->customdata = rcd = MEM_callocN(sizeof(RecordCompositeData), "ImageRecordCompositeData");
2548
2549         rcd->old_cfra = scene->r.cfra;
2550         rcd->sfra = sima->iuser.sfra;
2551         rcd->efra = sima->iuser.sfra + sima->iuser.frames - 1;
2552         scene->r.cfra = rcd->sfra;
2553
2554         return 1;
2555 }
2556
2557 static void image_record_composite_exit(bContext *C, wmOperator *op)
2558 {
2559         Scene *scene = CTX_data_scene(C);
2560         SpaceImage *sima = CTX_wm_space_image(C);
2561         RecordCompositeData *rcd = op->customdata;
2562
2563         scene->r.cfra = rcd->old_cfra;
2564
2565         WM_cursor_modal_restore(CTX_wm_window(C));
2566
2567         if (rcd->timer)
2568                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rcd->timer);
2569
2570         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
2571
2572         // XXX play_anim(0);
2573         // XXX allqueue(REDRAWNODE, 1);
2574
2575         MEM_freeN(rcd);
2576 }
2577
2578 static int image_record_composite_exec(bContext *C, wmOperator *op)
2579 {
2580         if (!image_record_composite_init(C, op))
2581                 return OPERATOR_CANCELLED;
2582         
2583         while (image_record_composite_apply(C, op)) {}
2584         
2585         image_record_composite_exit(C, op);
2586         
2587         return OPERATOR_FINISHED;
2588 }
2589
2590 static int image_record_composite_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2591 {
2592         RecordCompositeData *rcd;
2593         
2594         if (!image_record_composite_init(C, op))
2595                 return OPERATOR_CANCELLED;
2596
2597         rcd = op->customdata;
2598         rcd->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.0f);
2599         WM_event_add_modal_handler(C, op);
2600
2601         if (!image_record_composite_apply(C, op))
2602                 return OPERATOR_FINISHED;
2603
2604         return OPERATOR_RUNNING_MODAL;
2605 }
2606
2607 static int image_record_composite_modal(bContext *C, wmOperator *op, const wmEvent *event)
2608 {
2609         RecordCompositeData *rcd = op->customdata;
2610
2611         switch (event->type) {
2612                 case TIMER:
2613                         if (rcd->timer == event->customdata) {
2614                                 if (!image_record_composite_apply(C, op)) {
2615                                         image_record_composite_exit(C, op);
2616                                         return OPERATOR_FINISHED;
2617                                 }
2618                         }
2619                         break;
2620                 case ESCKEY:
2621                         image_record_composite_exit(C, op);
2622                         return OPERATOR_FINISHED;
2623         }
2624
2625         return OPERATOR_RUNNING_MODAL;
2626 }
2627
2628 static int image_record_composite_cancel(bContext *C, wmOperator *op)
2629 {
2630         image_record_composite_exit(C, op);
2631         return OPERATOR_CANCELLED;
2632 }
2633
2634 void IMAGE_OT_record_composite(wmOperatorType *ot)
2635 {
2636         /* identifiers */
2637         ot->name = "Record Composite";
2638         ot->idname = "IMAGE_OT_record_composite";
2639         
2640         /* api callbacks */
2641         ot->exec = image_record_composite_exec;
2642         ot->invoke = image_record_composite_invoke;
2643         ot->modal = image_record_composite_modal;
2644         ot->cancel = image_record_composite_cancel;
2645         ot->poll = space_image_buffer_exists_poll;
2646 }
2647
2648 #endif
2649
2650 /********************* cycle render slot operator *********************/
2651
2652 static int image_cycle_render_slot_poll(bContext *C)
2653 {
2654         Image *ima = CTX_data_edit_image(C);
2655
2656         return (ima && ima->type == IMA_TYPE_R_RESULT);
2657 }
2658
2659 static int image_cycle_render_slot_exec(bContext *C, wmOperator *op)
2660 {
2661         Image *ima = CTX_data_edit_image(C);
2662         int a, slot, cur = ima->render_slot;
2663         const short use_reverse = RNA_boolean_get(op->ptr, "reverse");
2664
2665         for (a = 1; a < IMA_MAX_RENDER_SLOT; a++) {
2666                 slot = (cur + (use_reverse ? -a : a)) % IMA_MAX_RENDER_SLOT;
2667                 if (slot < 0) slot += IMA_MAX_RENDER_SLOT;
2668
2669                 if (ima->renders[slot] || slot == ima->last_render_slot) {
2670                         ima->render_slot = slot;
2671                         break;
2672                 }
2673         }
2674
2675         if (a == IMA_MAX_RENDER_SLOT)
2676                 ima->render_slot = ((cur == 1) ? 0 : 1);
2677         
2678         WM_event_add_notifier(C, NC_IMAGE | ND_DRAW, NULL);
2679
2680         /* no undo push for browsing existing */
2681         if (ima->renders[ima->render_slot] || ima->render_slot == ima->last_render_slot)
2682                 return OPERATOR_CANCELLED;
2683         
2684         return OPERATOR_FINISHED;
2685 }
2686
2687 void IMAGE_OT_cycle_render_slot(wmOperatorType *ot)
2688 {
2689         /* identifiers */
2690         ot->name = "Cycle Render Slot";
2691         ot->idname = "IMAGE_OT_cycle_render_slot";
2692         ot->description = "Cycle through all non-void render slots";
2693         
2694         /* api callbacks */
2695         ot->exec = image_cycle_render_slot_exec;
2696         ot->poll = image_cycle_render_slot_poll;
2697
2698         /* flags */
2699         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2700
2701         RNA_def_boolean(ot->srna, "reverse", 0, "Cycle in Reverse", "");
2702 }