Interface / Particles: Fix bad alignment in Rotation panel, sub layout missed the...
[blender.git] / source / blender / editors / space_image / image_ops.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2002-2009, Xavier Thomas
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/space_image/image_ops.c
27  *  \ingroup spimage
28  */
29
30
31 #include <stddef.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <errno.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_math.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_utildefines.h"
41
42 #include "BLF_translation.h"
43
44 #include "DNA_object_types.h"
45 #include "DNA_node_types.h"
46 #include "DNA_packedFile_types.h"
47 #include "DNA_scene_types.h"
48
49 #include "BKE_colortools.h"
50 #include "BKE_context.h"
51 #include "BKE_icons.h"
52 #include "BKE_image.h"
53 #include "BKE_global.h"
54 #include "BKE_library.h"
55 #include "BKE_main.h"
56 #include "BKE_node.h"
57 #include "BKE_packedFile.h"
58 #include "BKE_report.h"
59 #include "BKE_screen.h"
60
61 #include "GPU_draw.h"
62
63 #include "IMB_colormanagement.h"
64 #include "IMB_imbuf.h"
65 #include "IMB_imbuf_types.h"
66
67 #include "RE_pipeline.h"
68
69 #include "RNA_access.h"
70 #include "RNA_define.h"
71 #include "RNA_enum_types.h"
72
73 #include "ED_image.h"
74 #include "ED_render.h"
75 #include "ED_screen.h"
76 #include "ED_space_api.h"
77 #include "ED_uvedit.h"
78 #include "ED_util.h"
79
80 #include "UI_interface.h"
81 #include "UI_resources.h"
82 #include "UI_view2d.h"
83
84 #include "WM_api.h"
85 #include "WM_types.h"
86
87 #include "PIL_time.h"
88
89 #include "image_intern.h"
90 #include "ED_sculpt.h"
91
92 /******************** view navigation utilities *********************/
93
94 static void sima_zoom_set(SpaceImage *sima, ARegion *ar, float zoom, const float location[2])
95 {
96         float oldzoom = sima->zoom;
97         int width, height;
98
99         sima->zoom = zoom;
100
101         if (sima->zoom < 0.1f || sima->zoom > 4.0f) {
102                 /* check zoom limits */
103                 ED_space_image_get_size(sima, &width, &height);
104
105                 width *= sima->zoom;
106                 height *= sima->zoom;
107
108                 if ((width < 4) && (height < 4))
109                         sima->zoom = oldzoom;
110                 else if (BLI_rcti_size_x(&ar->winrct) <= sima->zoom)
111                         sima->zoom = oldzoom;
112                 else if (BLI_rcti_size_y(&ar->winrct) <= sima->zoom)
113                         sima->zoom = oldzoom;
114         }
115
116         if ((U.uiflag & USER_ZOOM_TO_MOUSEPOS) && location) {
117                 float aspx, aspy, w, h;
118
119                 ED_space_image_get_size(sima, &width, &height);
120                 ED_space_image_get_aspect(sima, &aspx, &aspy);
121
122                 w = width * aspx;
123                 h = height * aspy;
124
125                 sima->xof += ((location[0] - 0.5f) * w - sima->xof) * (sima->zoom - oldzoom) / sima->zoom;
126                 sima->yof += ((location[1] - 0.5f) * h - sima->yof) * (sima->zoom - oldzoom) / sima->zoom;
127         }
128 }
129
130 static void sima_zoom_set_factor(SpaceImage *sima, ARegion *ar, float zoomfac, const float location[2])
131 {
132         sima_zoom_set(sima, ar, sima->zoom * zoomfac, location);
133 }
134
135 #if 0 // currently unused
136 static int image_poll(bContext *C)
137 {
138         return (CTX_data_edit_image(C) != NULL);
139 }
140 #endif
141
142 static int space_image_buffer_exists_poll(bContext *C)
143 {
144         SpaceImage *sima = CTX_wm_space_image(C);
145         if (sima && sima->spacetype == SPACE_IMAGE)
146                 if (ED_space_image_has_buffer(sima))
147                         return 1;
148         return 0;
149 }
150
151 static int space_image_file_exists_poll(bContext *C)
152 {
153         if (space_image_buffer_exists_poll(C)) {
154                 Main *bmain = CTX_data_main(C);
155                 SpaceImage *sima = CTX_wm_space_image(C);
156                 ImBuf *ibuf;
157                 void *lock;
158                 int ret = FALSE;
159                 char name[FILE_MAX];
160
161                 ibuf = ED_space_image_acquire_buffer(sima, &lock);
162                 if (ibuf) {
163                         BLI_strncpy(name, ibuf->name, FILE_MAX);
164                         BLI_path_abs(name, bmain->name);
165
166                         if (BLI_exists(name) == FALSE) {
167                                 CTX_wm_operator_poll_msg_set(C, "image file not found");
168                         }
169                         else if (!BLI_file_is_writable(name)) {
170                                 CTX_wm_operator_poll_msg_set(C, "image path can't be written to");
171                         }
172                         else {
173                                 ret = TRUE;
174                         }
175                 }
176                 ED_space_image_release_buffer(sima, ibuf, lock);
177
178                 return ret;
179         }
180         return 0;
181 }
182
183 static int space_image_poll(bContext *C)
184 {
185         SpaceImage *sima = CTX_wm_space_image(C);
186         if (sima && sima->spacetype == SPACE_IMAGE && sima->image)
187                 return 1;
188         return 0;
189 }
190
191 int space_image_main_area_poll(bContext *C)
192 {
193         SpaceImage *sima = CTX_wm_space_image(C);
194         // XXX ARegion *ar = CTX_wm_region(C);
195
196         if (sima)
197                 return 1;  // XXX (ar && ar->type->regionid == RGN_TYPE_WINDOW);
198         
199         return 0;
200 }
201
202 /* For IMAGE_OT_curves_point_set to avoid sampling when in uv smooth mode or editmode */
203 static int space_image_main_area_not_uv_brush_poll(bContext *C)
204 {
205         SpaceImage *sima = CTX_wm_space_image(C);
206         Scene *scene = CTX_data_scene(C);
207         ToolSettings *toolsettings = scene->toolsettings;
208
209         if (sima && !toolsettings->uvsculpt && !scene->obedit)
210                 return 1;
211
212         return 0;
213 }
214
215 static int image_sample_poll(bContext *C)
216 {
217         SpaceImage *sima = CTX_wm_space_image(C);
218         if (sima) {
219                 Scene *scene = CTX_data_scene(C);
220                 Object *obedit = CTX_data_edit_object(C);
221                 ToolSettings *toolsettings = scene->toolsettings;
222
223                 if (obedit) {
224                         if (ED_space_image_show_uvedit(sima, obedit) && (toolsettings->use_uv_sculpt))
225                                 return FALSE;
226                 }
227                 else if (sima->mode != SI_MODE_VIEW) {
228                         return FALSE;
229                 }
230
231                 return space_image_main_area_poll(C);
232         }
233         else {
234                 return FALSE;
235         }
236 }
237 /********************** view pan operator *********************/
238
239 typedef struct ViewPanData {
240         float x, y;
241         float xof, yof;
242         int event_type;
243 } ViewPanData;
244
245 static void image_view_pan_init(bContext *C, wmOperator *op, const wmEvent *event)
246 {
247         SpaceImage *sima = CTX_wm_space_image(C);
248         ViewPanData *vpd;
249
250         op->customdata = vpd = MEM_callocN(sizeof(ViewPanData), "ImageViewPanData");
251         WM_cursor_modal_set(CTX_wm_window(C), BC_NSEW_SCROLLCURSOR);
252
253         vpd->x = event->x;
254         vpd->y = event->y;
255         vpd->xof = sima->xof;
256         vpd->yof = sima->yof;
257         vpd->event_type = event->type;
258
259         WM_event_add_modal_handler(C, op);
260 }
261
262 static void image_view_pan_exit(bContext *C, wmOperator *op, bool cancel)
263 {
264         SpaceImage *sima = CTX_wm_space_image(C);
265         ViewPanData *vpd = op->customdata;
266
267         if (cancel) {
268                 sima->xof = vpd->xof;
269                 sima->yof = vpd->yof;
270                 ED_region_tag_redraw(CTX_wm_region(C));
271         }
272
273         WM_cursor_modal_restore(CTX_wm_window(C));
274         MEM_freeN(op->customdata);
275 }
276
277 static int image_view_pan_exec(bContext *C, wmOperator *op)
278 {
279         SpaceImage *sima = CTX_wm_space_image(C);
280         float offset[2];
281
282         RNA_float_get_array(op->ptr, "offset", offset);
283         sima->xof += offset[0];
284         sima->yof += offset[1];
285
286         ED_region_tag_redraw(CTX_wm_region(C));
287
288         /* XXX notifier? */
289 #if 0
290         if (image_preview_active(curarea, NULL, NULL)) {
291                 /* recalculates new preview rect */
292                 scrarea_do_windraw(curarea);
293                 image_preview_event(2);
294         }
295 #endif
296         
297         return OPERATOR_FINISHED;
298 }
299
300 static int image_view_pan_invoke(bContext *C, wmOperator *op, const wmEvent *event)
301 {
302         if (event->type == MOUSEPAN) {
303                 SpaceImage *sima = CTX_wm_space_image(C);
304                 float offset[2];
305                 
306                 offset[0] = (event->prevx - event->x) / sima->zoom;
307                 offset[1] = (event->prevy - event->y) / sima->zoom;
308                 RNA_float_set_array(op->ptr, "offset", offset);
309
310                 image_view_pan_exec(C, op);
311                 return OPERATOR_FINISHED;
312         }
313         else {
314                 image_view_pan_init(C, op, event);
315                 return OPERATOR_RUNNING_MODAL;
316         }
317 }
318
319 static int image_view_pan_modal(bContext *C, wmOperator *op, const wmEvent *event)
320 {
321         SpaceImage *sima = CTX_wm_space_image(C);
322         ViewPanData *vpd = op->customdata;
323         float offset[2];
324
325         switch (event->type) {
326                 case MOUSEMOVE:
327                         sima->xof = vpd->xof;
328                         sima->yof = vpd->yof;
329                         offset[0] = (vpd->x - event->x) / sima->zoom;
330                         offset[1] = (vpd->y - event->y) / sima->zoom;
331                         RNA_float_set_array(op->ptr, "offset", offset);
332                         image_view_pan_exec(C, op);
333                         break;
334                 default:
335                         if (event->type == vpd->event_type && event->val == KM_RELEASE) {
336                                 image_view_pan_exit(C, op, false);
337                                 return OPERATOR_FINISHED;
338                         }
339                         break;
340         }
341
342         return OPERATOR_RUNNING_MODAL;
343 }
344
345 static void image_view_pan_cancel(bContext *C, wmOperator *op)
346 {
347         image_view_pan_exit(C, op, true);
348 }
349
350 void IMAGE_OT_view_pan(wmOperatorType *ot)
351 {
352         /* identifiers */
353         ot->name = "View Pan";
354         ot->idname = "IMAGE_OT_view_pan";
355         ot->description = "Pan the view";
356         
357         /* api callbacks */
358         ot->exec = image_view_pan_exec;
359         ot->invoke = image_view_pan_invoke;
360         ot->modal = image_view_pan_modal;
361         ot->cancel = image_view_pan_cancel;
362         ot->poll = space_image_main_area_poll;
363
364         /* flags */
365         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_POINTER;
366         
367         /* properties */
368         RNA_def_float_vector(ot->srna, "offset", 2, NULL, -FLT_MAX, FLT_MAX,
369                              "Offset", "Offset in floating point units, 1.0 is the width and height of the image", -FLT_MAX, FLT_MAX);
370 }
371
372 /********************** view zoom operator *********************/
373
374 typedef struct ViewZoomData {
375         float origx, origy;
376         float zoom;
377         int event_type;
378         float location[2];
379
380         /* needed for continuous zoom */
381         wmTimer *timer;
382         double timer_lastdraw;
383
384         /* */
385         SpaceImage *sima;
386         ARegion *ar;
387 } ViewZoomData;
388
389 static void image_view_zoom_init(bContext *C, wmOperator *op, const wmEvent *event)
390 {
391         SpaceImage *sima = CTX_wm_space_image(C);
392         ARegion *ar = CTX_wm_region(C);
393         ViewZoomData *vpd;
394
395         op->customdata = vpd = MEM_callocN(sizeof(ViewZoomData), "ImageViewZoomData");
396         WM_cursor_modal_set(CTX_wm_window(C), BC_NSEW_SCROLLCURSOR);
397
398         vpd->origx = event->x;
399         vpd->origy = event->y;
400         vpd->zoom = sima->zoom;
401         vpd->event_type = event->type;
402
403         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &vpd->location[0], &vpd->location[1]);
404
405         if (U.viewzoom == USER_ZOOM_CONT) {
406                 /* needs a timer to continue redrawing */
407                 vpd->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.01f);
408                 vpd->timer_lastdraw = PIL_check_seconds_timer();
409         }
410
411         vpd->sima = sima;
412         vpd->ar = ar;
413
414         WM_event_add_modal_handler(C, op);
415 }
416
417 static void image_view_zoom_exit(bContext *C, wmOperator *op, bool cancel)
418 {
419         SpaceImage *sima = CTX_wm_space_image(C);
420         ViewZoomData *vpd = op->customdata;
421
422         if (cancel) {
423                 sima->zoom = vpd->zoom;
424                 ED_region_tag_redraw(CTX_wm_region(C));
425         }
426
427         if (vpd->timer)
428                 WM_event_remove_timer(CTX_wm_manager(C), vpd->timer->win, vpd->timer);
429
430         WM_cursor_modal_restore(CTX_wm_window(C));
431         MEM_freeN(op->customdata);
432 }
433
434 static int image_view_zoom_exec(bContext *C, wmOperator *op)
435 {
436         SpaceImage *sima = CTX_wm_space_image(C);
437         ARegion *ar = CTX_wm_region(C);
438
439         sima_zoom_set_factor(sima, ar, RNA_float_get(op->ptr, "factor"), NULL);
440
441         ED_region_tag_redraw(CTX_wm_region(C));
442
443         /* XXX notifier? */
444 #if 0
445         if (image_preview_active(curarea, NULL, NULL)) {
446                 /* recalculates new preview rect */
447                 scrarea_do_windraw(curarea);
448                 image_preview_event(2);
449         }
450 #endif
451         
452         return OPERATOR_FINISHED;
453 }
454
455 enum {
456         VIEW_PASS = 0,
457         VIEW_APPLY,
458         VIEW_CONFIRM
459 };
460
461 static int image_view_zoom_invoke(bContext *C, wmOperator *op, const wmEvent *event)
462 {
463         if (event->type == MOUSEZOOM || event->type == MOUSEPAN) {
464                 SpaceImage *sima = CTX_wm_space_image(C);
465                 ARegion *ar = CTX_wm_region(C);
466                 float delta, factor, location[2];
467
468                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &location[0], &location[1]);
469
470                 delta = event->prevx - event->x + event->prevy - event->y;
471
472                 if (U.uiflag & USER_ZOOM_INVERT)
473                         delta *= -1;
474
475                 factor = 1.0f + delta / 300.0f;
476                 RNA_float_set(op->ptr, "factor", factor);
477                 sima_zoom_set(sima, ar, sima->zoom * factor, location);
478                 ED_region_tag_redraw(CTX_wm_region(C));
479                 
480                 return OPERATOR_FINISHED;
481         }
482         else {
483                 image_view_zoom_init(C, op, event);
484                 return OPERATOR_RUNNING_MODAL;
485         }
486 }
487
488 static void image_zoom_apply(ViewZoomData *vpd, wmOperator *op, const int x, const int y, const short viewzoom, const short zoom_invert)
489 {
490         float factor;
491
492         if (viewzoom == USER_ZOOM_CONT) {
493                 double time = PIL_check_seconds_timer();
494                 float time_step = (float)(time - vpd->timer_lastdraw);
495                 float fac;
496                 float zfac;
497
498                 if (U.uiflag & USER_ZOOM_HORIZ) {
499                         fac = (float)(x - vpd->origx);
500                 }
501                 else {
502                         fac = (float)(y - vpd->origy);
503                 }
504
505                 if (zoom_invert) {
506                         fac = -fac;
507                 }
508
509                 /* oldstyle zoom */
510                 zfac = 1.0f + ((fac / 20.0f) * time_step);
511                 vpd->timer_lastdraw = time;
512                 /* this is the final zoom, but instead make it into a factor */
513                 //zoom = vpd->sima->zoom * zfac;
514                 factor = (vpd->sima->zoom * zfac) / vpd->zoom;
515         }
516         else {
517                 /* for now do the same things for scale and dolly */
518                 float delta = x - vpd->origx + y - vpd->origy;
519
520                 if (zoom_invert)
521                         delta *= -1.0f;
522
523                 factor = 1.0f + delta / 300.0f;
524         }
525
526         RNA_float_set(op->ptr, "factor", factor);
527         sima_zoom_set(vpd->sima, vpd->ar, vpd->zoom * factor, vpd->location);
528         ED_region_tag_redraw(vpd->ar);
529 }
530
531 static int image_view_zoom_modal(bContext *C, wmOperator *op, const wmEvent *event)
532 {
533         ViewZoomData *vpd = op->customdata;
534         short event_code = VIEW_PASS;
535
536         /* execute the events */
537         if (event->type == TIMER && event->customdata == vpd->timer) {
538                 /* continuous zoom */
539                 event_code = VIEW_APPLY;
540         }
541         else if (event->type == MOUSEMOVE) {
542                 event_code = VIEW_APPLY;
543         }
544         else if (event->type == vpd->event_type && event->val == KM_RELEASE) {
545                 event_code = VIEW_CONFIRM;
546         }
547
548         if (event_code == VIEW_APPLY) {
549                 image_zoom_apply(vpd, op, event->x, event->y, U.viewzoom, (U.uiflag & USER_ZOOM_INVERT) != 0);
550         }
551         else if (event_code == VIEW_CONFIRM) {
552                 image_view_zoom_exit(C, op, false);
553                 return OPERATOR_FINISHED;
554         }
555
556         return OPERATOR_RUNNING_MODAL;
557 }
558
559 static void image_view_zoom_cancel(bContext *C, wmOperator *op)
560 {
561         image_view_zoom_exit(C, op, true);
562 }
563
564 void IMAGE_OT_view_zoom(wmOperatorType *ot)
565 {
566         /* identifiers */
567         ot->name = "View Zoom";
568         ot->idname = "IMAGE_OT_view_zoom";
569         ot->description = "Zoom in/out the image";
570         
571         /* api callbacks */
572         ot->exec = image_view_zoom_exec;
573         ot->invoke = image_view_zoom_invoke;
574         ot->modal = image_view_zoom_modal;
575         ot->cancel = image_view_zoom_cancel;
576         ot->poll = space_image_main_area_poll;
577
578         /* flags */
579         ot->flag = OPTYPE_BLOCKING;
580         
581         /* properties */
582         RNA_def_float(ot->srna, "factor", 0.0f, -FLT_MAX, FLT_MAX,
583                       "Factor", "Zoom factor, values higher than 1.0 zoom in, lower values zoom out", -FLT_MAX, FLT_MAX);
584 }
585
586 /********************** NDOF operator *********************/
587
588 /* Combined pan/zoom from a 3D mouse device.
589  * Z zooms, XY pans
590  * "view" (not "paper") control -- user moves the viewpoint, not the image being viewed
591  * that explains the negative signs in the code below
592  */
593
594 static int image_view_ndof_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
595 {
596         if (event->type != NDOF_MOTION)
597                 return OPERATOR_CANCELLED;
598         else {
599                 SpaceImage *sima = CTX_wm_space_image(C);
600                 ARegion *ar = CTX_wm_region(C);
601
602                 wmNDOFMotionData *ndof = (wmNDOFMotionData *) event->customdata;
603
604                 float dt = ndof->dt;
605                 /* tune these until it feels right */
606                 const float zoom_sensitivity = 0.5f; // 50% per second (I think)
607                 const float pan_sensitivity = 300.f; // screen pixels per second
608
609                 float pan_x = pan_sensitivity * dt * ndof->tvec[0] / sima->zoom;
610                 float pan_y = pan_sensitivity * dt * ndof->tvec[1] / sima->zoom;
611
612                 /* "mouse zoom" factor = 1 + (dx + dy) / 300
613                  * what about "ndof zoom" factor? should behave like this:
614                  * at rest -> factor = 1
615                  * move forward -> factor > 1
616                  * move backward -> factor < 1
617                  */
618                 float zoom_factor = 1.f + zoom_sensitivity * dt * -ndof->tvec[2];
619
620                 if (U.ndof_flag & NDOF_ZOOM_INVERT)
621                         zoom_factor = -zoom_factor;
622
623                 sima_zoom_set_factor(sima, ar, zoom_factor, NULL);
624                 sima->xof += pan_x;
625                 sima->yof += pan_y;
626
627                 ED_region_tag_redraw(ar);
628
629                 return OPERATOR_FINISHED;
630         }
631 }
632
633 void IMAGE_OT_view_ndof(wmOperatorType *ot)
634 {
635         /* identifiers */
636         ot->name = "NDOF Pan/Zoom";
637         ot->idname = "IMAGE_OT_view_ndof";
638         ot->description = "Use a 3D mouse device to pan/zoom the view";
639         
640         /* api callbacks */
641         ot->invoke = image_view_ndof_invoke;
642 }
643
644 /********************** view all operator *********************/
645
646 /* Updates the fields of the View2D member of the SpaceImage struct.
647  * Default behavior is to reset the position of the image and set the zoom to 1
648  * If the image will not fit within the window rectangle, the zoom is adjusted */
649
650 static int image_view_all_exec(bContext *C, wmOperator *op)
651 {
652         SpaceImage *sima;
653         ARegion *ar;
654         float aspx, aspy, zoomx, zoomy, w, h;
655         int width, height;
656         int fit_view = RNA_boolean_get(op->ptr, "fit_view");
657
658         /* retrieve state */
659         sima = CTX_wm_space_image(C);
660         ar = CTX_wm_region(C);
661
662         ED_space_image_get_size(sima, &width, &height);
663         ED_space_image_get_aspect(sima, &aspx, &aspy);
664
665         w = width * aspx;
666         h = height * aspy;
667         
668         /* check if the image will fit in the image with (zoom == 1) */
669         width  = BLI_rcti_size_x(&ar->winrct) + 1;
670         height = BLI_rcti_size_y(&ar->winrct) + 1;
671
672         if (fit_view) {
673                 const int margin = 5; /* margin from border */
674
675                 zoomx = (float) width / (w + 2 * margin);
676                 zoomy = (float) height / (h + 2 * margin);
677
678                 sima_zoom_set(sima, ar, min_ff(zoomx, zoomy), NULL);
679         }
680         else {
681                 if ((w >= width || h >= height) && (width > 0 && height > 0)) {
682                         zoomx = (float) width / w;
683                         zoomy = (float) height / h;
684
685                         /* find the zoom value that will fit the image in the image space */
686                         sima_zoom_set(sima, ar, 1.0f / power_of_2(1.0f / min_ff(zoomx, zoomy)), NULL);
687                 }
688                 else
689                         sima_zoom_set(sima, ar, 1.0f, NULL);
690         }
691
692         sima->xof = sima->yof = 0.0f;
693
694         ED_region_tag_redraw(CTX_wm_region(C));
695         
696         return OPERATOR_FINISHED;
697 }
698
699 void IMAGE_OT_view_all(wmOperatorType *ot)
700 {
701         PropertyRNA *prop;
702
703         /* identifiers */
704         ot->name = "View All";
705         ot->idname = "IMAGE_OT_view_all";
706         ot->description = "View the entire image";
707         
708         /* api callbacks */
709         ot->exec = image_view_all_exec;
710         ot->poll = space_image_main_area_poll;
711
712         /* properties */
713         prop = RNA_def_boolean(ot->srna, "fit_view", 0, "Fit View", "Fit frame to the viewport");
714         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
715 }
716
717 /********************** view selected operator *********************/
718
719 static int image_view_selected_exec(bContext *C, wmOperator *UNUSED(op))
720 {
721         SpaceImage *sima;
722         ARegion *ar;
723         Scene *scene;
724         Object *obedit;
725         Image *ima;
726         float size, min[2], max[2], d[2], aspx, aspy;
727         int width, height;
728
729         /* retrieve state */
730         sima = CTX_wm_space_image(C);
731         ar = CTX_wm_region(C);
732         scene = CTX_data_scene(C);
733         obedit = CTX_data_edit_object(C);
734
735         ima = ED_space_image(sima);
736         ED_space_image_get_size(sima, &width, &height);
737         ED_space_image_get_aspect(sima, &aspx, &aspy);
738
739         width = width * aspx;
740         height = height * aspy;
741
742         /* get bounds */
743         if (!ED_uvedit_minmax(scene, ima, obedit, min, max))
744                 return OPERATOR_CANCELLED;
745
746         /* adjust offset and zoom */
747         sima->xof = (int)(((min[0] + max[0]) * 0.5f - 0.5f) * width);
748         sima->yof = (int)(((min[1] + max[1]) * 0.5f - 0.5f) * height);
749
750         d[0] = max[0] - min[0];
751         d[1] = max[1] - min[1];
752         size = 0.5f * MAX2(d[0], d[1]) * MAX2(width, height) / 256.0f;
753         
754         if (size <= 0.01f) size = 0.01f;
755         sima_zoom_set(sima, ar, 0.7f / size, NULL);
756
757         ED_region_tag_redraw(CTX_wm_region(C));
758         
759         return OPERATOR_FINISHED;
760 }
761
762 static int image_view_selected_poll(bContext *C)
763 {
764         return (space_image_main_area_poll(C) && ED_operator_uvedit(C));
765 }
766
767 void IMAGE_OT_view_selected(wmOperatorType *ot)
768 {
769         /* identifiers */
770         ot->name = "View Center";
771         ot->idname = "IMAGE_OT_view_selected";
772         ot->description = "View all selected UVs";
773         
774         /* api callbacks */
775         ot->exec = image_view_selected_exec;
776         ot->poll = image_view_selected_poll;
777 }
778
779 /********************** view zoom in/out operator *********************/
780
781 static int image_view_zoom_in_exec(bContext *C, wmOperator *op)
782 {
783         SpaceImage *sima = CTX_wm_space_image(C);
784         ARegion *ar = CTX_wm_region(C);
785         float location[2];
786
787         RNA_float_get_array(op->ptr, "location", location);
788
789         sima_zoom_set_factor(sima, ar, 1.25f, location);
790
791         ED_region_tag_redraw(CTX_wm_region(C));
792         
793         return OPERATOR_FINISHED;
794 }
795
796 static int image_view_zoom_in_invoke(bContext *C, wmOperator *op, const wmEvent *event)
797 {
798         ARegion *ar = CTX_wm_region(C);
799         float location[2];
800
801         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &location[0], &location[1]);
802         RNA_float_set_array(op->ptr, "location", location);
803
804         return image_view_zoom_in_exec(C, op);
805 }
806
807 void IMAGE_OT_view_zoom_in(wmOperatorType *ot)
808 {
809         /* identifiers */
810         ot->name = "View Zoom In";
811         ot->idname = "IMAGE_OT_view_zoom_in";
812         ot->description = "Zoom in the image (centered around 2D cursor)";
813         
814         /* api callbacks */
815         ot->invoke = image_view_zoom_in_invoke;
816         ot->exec = image_view_zoom_in_exec;
817         ot->poll = space_image_main_area_poll;
818
819         /* properties */
820         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX, "Location", "Cursor location in screen coordinates", -10.0f, 10.0f);
821 }
822
823 static int image_view_zoom_out_exec(bContext *C, wmOperator *op)
824 {
825         SpaceImage *sima = CTX_wm_space_image(C);
826         ARegion *ar = CTX_wm_region(C);
827         float location[2];
828
829         RNA_float_get_array(op->ptr, "location", location);
830
831         sima_zoom_set_factor(sima, ar, 0.8f, location);
832
833         ED_region_tag_redraw(CTX_wm_region(C));
834         
835         return OPERATOR_FINISHED;
836 }
837
838 static int image_view_zoom_out_invoke(bContext *C, wmOperator *op, const wmEvent *event)
839 {
840         ARegion *ar = CTX_wm_region(C);
841         float location[2];
842
843         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &location[0], &location[1]);
844         RNA_float_set_array(op->ptr, "location", location);
845
846         return image_view_zoom_out_exec(C, op);
847 }
848
849 void IMAGE_OT_view_zoom_out(wmOperatorType *ot)
850 {
851         /* identifiers */
852         ot->name = "View Zoom Out";
853         ot->idname = "IMAGE_OT_view_zoom_out";
854         ot->description = "Zoom out the image (centered around 2D cursor)";
855         
856         /* api callbacks */
857         ot->invoke = image_view_zoom_out_invoke;
858         ot->exec = image_view_zoom_out_exec;
859         ot->poll = space_image_main_area_poll;
860
861         /* properties */
862         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX, "Location", "Cursor location in screen coordinates", -10.0f, 10.0f);
863 }
864
865 /********************** view zoom ratio operator *********************/
866
867 static int image_view_zoom_ratio_exec(bContext *C, wmOperator *op)
868 {
869         SpaceImage *sima = CTX_wm_space_image(C);
870         ARegion *ar = CTX_wm_region(C);
871
872         sima_zoom_set(sima, ar, RNA_float_get(op->ptr, "ratio"), NULL);
873         
874         /* ensure pixel exact locations for draw */
875         sima->xof = (int)sima->xof;
876         sima->yof = (int)sima->yof;
877
878         /* XXX notifier? */
879 #if 0
880         if (image_preview_active(curarea, NULL, NULL)) {
881                 /* recalculates new preview rect */
882                 scrarea_do_windraw(curarea);
883                 image_preview_event(2);
884         }
885 #endif
886
887         ED_region_tag_redraw(CTX_wm_region(C));
888         
889         return OPERATOR_FINISHED;
890 }
891
892 void IMAGE_OT_view_zoom_ratio(wmOperatorType *ot)
893 {
894         /* identifiers */
895         ot->name = "View Zoom Ratio";
896         ot->idname = "IMAGE_OT_view_zoom_ratio";
897         ot->description = "Set zoom ratio of the view";
898         
899         /* api callbacks */
900         ot->exec = image_view_zoom_ratio_exec;
901         ot->poll = space_image_main_area_poll;
902         
903         /* properties */
904         RNA_def_float(ot->srna, "ratio", 0.0f, -FLT_MAX, FLT_MAX,
905                       "Ratio", "Zoom ratio, 1.0 is 1:1, higher is zoomed in, lower is zoomed out", -FLT_MAX, FLT_MAX);
906 }
907
908 /**************** load/replace/save callbacks ******************/
909 static void image_filesel(bContext *C, wmOperator *op, const char *path)
910 {
911         RNA_string_set(op->ptr, "filepath", path);
912         WM_event_add_fileselect(C, op); 
913 }
914
915 /******************** open image operator ********************/
916
917 static void image_open_init(bContext *C, wmOperator *op)
918 {
919         PropertyPointerRNA *pprop;
920
921         op->customdata = pprop = MEM_callocN(sizeof(PropertyPointerRNA), "OpenPropertyPointerRNA");
922         uiIDContextProperty(C, &pprop->ptr, &pprop->prop);
923 }
924
925 static void image_open_cancel(bContext *UNUSED(C), wmOperator *op)
926 {
927         MEM_freeN(op->customdata);
928         op->customdata = NULL;
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 void image_save_as_cancel(bContext *UNUSED(C), wmOperator *op)
1509 {
1510         image_save_as_free(op);
1511 }
1512
1513 static bool image_save_as_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop)
1514 {
1515         const char *prop_id = RNA_property_identifier(prop);
1516
1517         return !(STREQ(prop_id, "filepath") ||
1518                  STREQ(prop_id, "directory") ||
1519                  STREQ(prop_id, "filename") ||
1520                  /* when saving a copy, relative path has no effect */
1521                  ((STREQ(prop_id, "relative_path")) && RNA_boolean_get(ptr, "copy"))
1522                  );
1523 }
1524
1525 static void image_save_as_draw(bContext *UNUSED(C), wmOperator *op)
1526 {
1527         uiLayout *layout = op->layout;
1528         ImageFormatData *imf = op->customdata;
1529         PointerRNA ptr;
1530
1531         /* image template */
1532         RNA_pointer_create(NULL, &RNA_ImageFormatSettings, imf, &ptr);
1533         uiTemplateImageSettings(layout, &ptr, FALSE);
1534
1535         /* main draw call */
1536         RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);
1537         uiDefAutoButsRNA(layout, &ptr, image_save_as_draw_check_prop, '\0');
1538 }
1539
1540 static int image_save_as_poll(bContext *C)
1541 {
1542         if (space_image_buffer_exists_poll(C)) {
1543                 if (G.is_rendering) {
1544                         /* no need to NULL check here */
1545                         SpaceImage *sima = CTX_wm_space_image(C);
1546                         Image *ima = ED_space_image(sima);
1547
1548                         if (ima->source == IMA_SRC_VIEWER) {
1549                                 CTX_wm_operator_poll_msg_set(C, "can't save image while rendering");
1550                                 return FALSE;
1551                         }
1552                 }
1553                 return TRUE;
1554         }
1555         return FALSE;
1556 }
1557
1558 void IMAGE_OT_save_as(wmOperatorType *ot)
1559 {
1560 //      PropertyRNA *prop;
1561
1562         /* identifiers */
1563         ot->name = "Save As Image";
1564         ot->idname = "IMAGE_OT_save_as";
1565         ot->description = "Save the image with another name and/or settings";
1566         
1567         /* api callbacks */
1568         ot->exec = image_save_as_exec;
1569         ot->check = image_save_as_check;
1570         ot->invoke = image_save_as_invoke;
1571         ot->cancel = image_save_as_cancel;
1572         ot->ui = image_save_as_draw;
1573         ot->poll = image_save_as_poll;
1574
1575         /* flags */
1576         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1577
1578         /* properties */
1579         RNA_def_boolean(ot->srna, "save_as_render", 0, "Save As Render", "Apply render part of display transform when saving byte image");
1580         RNA_def_boolean(ot->srna, "copy", 0, "Copy", "Create a new image file without modifying the current image in blender");
1581
1582         WM_operator_properties_filesel(ot, FOLDERFILE | IMAGEFILE | MOVIEFILE, FILE_SPECIAL, FILE_SAVE,
1583                                        WM_FILESEL_FILEPATH | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY);
1584 }
1585
1586 /******************** save image operator ********************/
1587
1588 static int image_save_exec(bContext *C, wmOperator *op)
1589 {
1590         SpaceImage *sima = CTX_wm_space_image(C);
1591         Scene *scene = CTX_data_scene(C);
1592         SaveImageOptions simopts;
1593
1594         save_image_options_defaults(&simopts);
1595         if (save_image_options_init(&simopts, sima, scene, false, false) == 0)
1596                 return OPERATOR_CANCELLED;
1597         save_image_options_from_op(&simopts, op);
1598
1599         if (BLI_exists(simopts.filepath) && BLI_file_is_writable(simopts.filepath)) {
1600                 save_image_doit(C, sima, op, &simopts, FALSE);
1601         }
1602         else {
1603                 BKE_reportf(op->reports, RPT_ERROR, "Cannot save image, path '%s' is not writable", simopts.filepath);
1604                 return OPERATOR_CANCELLED;
1605         }
1606
1607         return OPERATOR_FINISHED;
1608 }
1609
1610 void IMAGE_OT_save(wmOperatorType *ot)
1611 {
1612         /* identifiers */
1613         ot->name = "Save Image";
1614         ot->idname = "IMAGE_OT_save";
1615         ot->description = "Save the image with current name and settings";
1616         
1617         /* api callbacks */
1618         ot->exec = image_save_exec;
1619         ot->poll = space_image_file_exists_poll;
1620
1621         /* flags */
1622         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1623 }
1624
1625 /******************* save sequence operator ********************/
1626
1627 static int image_save_sequence_exec(bContext *C, wmOperator *op)
1628 {
1629         Main *bmain = CTX_data_main(C);
1630         SpaceImage *sima = CTX_wm_space_image(C);
1631         ImBuf *ibuf;
1632         int tot = 0;
1633         char di[FILE_MAX];
1634         
1635         if (sima->image == NULL)
1636                 return OPERATOR_CANCELLED;
1637
1638         if (sima->image->source != IMA_SRC_SEQUENCE) {
1639                 BKE_report(op->reports, RPT_ERROR, "Can only save sequence on image sequences");
1640                 return OPERATOR_CANCELLED;
1641         }
1642
1643         if (sima->image->type == IMA_TYPE_MULTILAYER) {
1644                 BKE_report(op->reports, RPT_ERROR, "Cannot save multilayer sequences");
1645                 return OPERATOR_CANCELLED;
1646         }
1647         
1648         /* get total */
1649         for (ibuf = sima->image->ibufs.first; ibuf; ibuf = ibuf->next)
1650                 if (ibuf->userflags & IB_BITMAPDIRTY)
1651                         tot++;
1652         
1653         if (tot == 0) {
1654                 BKE_report(op->reports, RPT_WARNING, "No images have been changed");
1655                 return OPERATOR_CANCELLED;
1656         }
1657
1658         /* get a filename for menu */
1659         for (ibuf = sima->image->ibufs.first; ibuf; ibuf = ibuf->next)
1660                 if (ibuf->userflags & IB_BITMAPDIRTY)
1661                         break;
1662
1663         BLI_split_dir_part(ibuf->name, di, sizeof(di));
1664         BKE_reportf(op->reports, RPT_INFO, "%d image(s) will be saved in %s", tot, di);
1665
1666         for (ibuf = sima->image->ibufs.first; ibuf; ibuf = ibuf->next) {
1667                 if (ibuf->userflags & IB_BITMAPDIRTY) {
1668                         char name[FILE_MAX];
1669                         BLI_strncpy(name, ibuf->name, sizeof(name));
1670                         
1671                         BLI_path_abs(name, bmain->name);
1672
1673                         if (0 == IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat)) {
1674                                 BKE_reportf(op->reports, RPT_ERROR, "Could not write image %s", name);
1675                                 break;
1676                         }
1677
1678                         BKE_reportf(op->reports, RPT_INFO, "Saved %s", ibuf->name);
1679                         ibuf->userflags &= ~IB_BITMAPDIRTY;
1680                 }
1681         }
1682
1683         return OPERATOR_FINISHED;
1684 }
1685
1686 void IMAGE_OT_save_sequence(wmOperatorType *ot)
1687 {
1688         /* identifiers */
1689         ot->name = "Save Sequence";
1690         ot->idname = "IMAGE_OT_save_sequence";
1691         ot->description = "Save a sequence of images";
1692         
1693         /* api callbacks */
1694         ot->exec = image_save_sequence_exec;
1695         ot->poll = space_image_buffer_exists_poll;
1696
1697         /* flags */
1698         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1699 }
1700
1701 /******************** reload image operator ********************/
1702
1703 static int image_reload_exec(bContext *C, wmOperator *UNUSED(op))
1704 {
1705         Image *ima = CTX_data_edit_image(C);
1706         SpaceImage *sima = CTX_wm_space_image(C);
1707
1708         if (!ima)
1709                 return OPERATOR_CANCELLED;
1710
1711         /* XXX unpackImage frees image buffers */
1712         ED_preview_kill_jobs(C);
1713         
1714         // XXX other users?
1715         BKE_image_signal(ima, (sima) ? &sima->iuser : NULL, IMA_SIGNAL_RELOAD);
1716
1717         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1718         
1719         return OPERATOR_FINISHED;
1720 }
1721
1722 void IMAGE_OT_reload(wmOperatorType *ot)
1723 {
1724         /* identifiers */
1725         ot->name = "Reload Image";
1726         ot->idname = "IMAGE_OT_reload";
1727         ot->description = "Reload current image from disk";
1728         
1729         /* api callbacks */
1730         ot->exec = image_reload_exec;
1731
1732         /* flags */
1733         ot->flag = OPTYPE_REGISTER; /* no undo, image buffer is not handled by undo */
1734 }
1735
1736 /********************** new image operator *********************/
1737 #define IMA_DEF_NAME N_("Untitled")
1738
1739 static int image_new_exec(bContext *C, wmOperator *op)
1740 {
1741         SpaceImage *sima;
1742         Scene *scene;
1743         Object *obedit;
1744         Image *ima;
1745         Main *bmain;
1746         PointerRNA ptr, idptr;
1747         PropertyRNA *prop;
1748         char _name[MAX_ID_NAME - 2];
1749         char *name = _name;
1750         float color[4];
1751         int width, height, floatbuf, gen_type, alpha;
1752
1753         /* retrieve state */
1754         sima = CTX_wm_space_image(C);
1755         scene = CTX_data_scene(C);
1756         obedit = CTX_data_edit_object(C);
1757         bmain = CTX_data_main(C);
1758
1759         prop = RNA_struct_find_property(op->ptr, "name");
1760         RNA_property_string_get(op->ptr, prop, name);
1761         if (!RNA_property_is_set(op->ptr, prop)) {
1762                 /* Default value, we can translate! */
1763                 name = (char *)DATA_(name);
1764         }
1765         width = RNA_int_get(op->ptr, "width");
1766         height = RNA_int_get(op->ptr, "height");
1767         floatbuf = RNA_boolean_get(op->ptr, "float");
1768         gen_type = RNA_enum_get(op->ptr, "generated_type");
1769         RNA_float_get_array(op->ptr, "color", color);
1770         alpha = RNA_boolean_get(op->ptr, "alpha");
1771         
1772         if (!alpha)
1773                 color[3] = 1.0f;
1774
1775         ima = BKE_image_add_generated(bmain, width, height, name, alpha ? 32 : 24, floatbuf, gen_type, color);
1776
1777         if (!ima)
1778                 return OPERATOR_CANCELLED;
1779
1780         /* hook into UI */
1781         uiIDContextProperty(C, &ptr, &prop);
1782
1783         if (prop) {
1784                 /* when creating new ID blocks, use is already 1, but RNA
1785                  * pointer se also increases user, so this compensates it */
1786                 ima->id.us--;
1787
1788                 RNA_id_pointer_create(&ima->id, &idptr);
1789                 RNA_property_pointer_set(&ptr, prop, idptr);
1790                 RNA_property_update(C, &ptr, prop);
1791         }
1792         else if (sima) {
1793                 ED_space_image_set(sima, scene, obedit, ima);
1794         }
1795         else {
1796                 Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
1797                 if (tex && tex->type == TEX_IMAGE) {
1798                         if (tex->ima)
1799                                 id_us_min(&tex->ima->id);
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         prop = RNA_def_int(ot->srna, "width", 1024, 1, INT_MAX, "Width", "Image width", 1, 16384);
1841         RNA_def_property_subtype(prop, PROP_PIXEL);
1842         prop = RNA_def_int(ot->srna, "height", 1024, 1, INT_MAX, "Height", "Image height", 1, 16384);
1843         RNA_def_property_subtype(prop, PROP_PIXEL);
1844         prop = RNA_def_float_color(ot->srna, "color", 4, NULL, 0.0f, FLT_MAX, "Color", "Default fill color", 0.0f, 1.0f);
1845         RNA_def_property_subtype(prop, PROP_COLOR_GAMMA);
1846         RNA_def_property_float_array_default(prop, default_color);
1847         RNA_def_boolean(ot->srna, "alpha", 1, "Alpha", "Create an image with an alpha channel");
1848         RNA_def_enum(ot->srna, "generated_type", image_generated_type_items, IMA_GENTYPE_BLANK,
1849                      "Generated Type", "Fill the image with a grid for UV map testing");
1850         RNA_def_boolean(ot->srna, "float", 0, "32 bit Float", "Create image with 32 bit floating point bit depth");
1851 }
1852
1853 #undef IMA_DEF_NAME
1854
1855 /********************* invert operators *********************/
1856
1857 static int image_invert_poll(bContext *C)
1858 {
1859         Image *ima = CTX_data_edit_image(C);
1860
1861         return BKE_image_has_ibuf(ima, NULL);
1862 }
1863
1864 static int image_invert_exec(bContext *C, wmOperator *op)
1865 {
1866         Image *ima = CTX_data_edit_image(C);
1867         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
1868         SpaceImage *sima = CTX_wm_space_image(C);
1869         /* undo is supported only on image paint mode currently */
1870         bool support_undo = ((sima != NULL) && (sima->mode == SI_MODE_PAINT));
1871
1872         /* flags indicate if this channel should be inverted */
1873         const short r = RNA_boolean_get(op->ptr, "invert_r");
1874         const short g = RNA_boolean_get(op->ptr, "invert_g");
1875         const short b = RNA_boolean_get(op->ptr, "invert_b");
1876         const short a = RNA_boolean_get(op->ptr, "invert_a");
1877
1878         int i;
1879
1880         if (ibuf == NULL)  /* TODO: this should actually never happen, but does for render-results -> cleanup */
1881                 return OPERATOR_CANCELLED;
1882
1883         if (support_undo) {
1884                 ED_undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
1885                                          ED_image_undo_restore, ED_image_undo_free);
1886                 /* not strictly needed, because we only imapaint_dirty_region to invalidate all tiles
1887                  * but better do this right in case someone copies this for a tool that uses partial redraw better */
1888                 ED_imapaint_clear_partial_redraw();
1889                 ED_imapaint_dirty_region(ima, ibuf, 0, 0, ibuf->x, ibuf->y);
1890         }
1891         /* TODO: make this into an IMB_invert_channels(ibuf,r,g,b,a) method!? */
1892         if (ibuf->rect_float) {
1893                 
1894                 float *fp = (float *) ibuf->rect_float;
1895                 for (i = ibuf->x * ibuf->y; i > 0; i--, fp += 4) {
1896                         if (r) fp[0] = 1.0f - fp[0];
1897                         if (g) fp[1] = 1.0f - fp[1];
1898                         if (b) fp[2] = 1.0f - fp[2];
1899                         if (a) fp[3] = 1.0f - fp[3];
1900                 }
1901
1902                 if (ibuf->rect) {
1903                         IMB_rect_from_float(ibuf);
1904                 }
1905         }
1906         else if (ibuf->rect) {
1907                 
1908                 char *cp = (char *) ibuf->rect;
1909                 for (i = ibuf->x * ibuf->y; i > 0; i--, cp += 4) {
1910                         if (r) cp[0] = 255 - cp[0];
1911                         if (g) cp[1] = 255 - cp[1];
1912                         if (b) cp[2] = 255 - cp[2];
1913                         if (a) cp[3] = 255 - cp[3];
1914                 }
1915         }
1916         else {
1917                 BKE_image_release_ibuf(ima, ibuf, NULL);
1918                 return OPERATOR_CANCELLED;
1919         }
1920
1921         ibuf->userflags |= IB_BITMAPDIRTY | IB_DISPLAY_BUFFER_INVALID;
1922
1923         if (ibuf->mipmap[0])
1924                 ibuf->userflags |= IB_MIPMAP_INVALID;
1925
1926         if (support_undo)
1927                 ED_undo_paint_push_end(UNDO_PAINT_IMAGE);
1928
1929         /* force GPU reupload, all image is invalid */
1930         GPU_free_image(ima);
1931
1932         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1933
1934         BKE_image_release_ibuf(ima, ibuf, NULL);
1935
1936         return OPERATOR_FINISHED;
1937 }
1938
1939 void IMAGE_OT_invert(wmOperatorType *ot)
1940 {
1941         PropertyRNA *prop;
1942
1943         /* identifiers */
1944         ot->name = "Invert Channels";
1945         ot->idname = "IMAGE_OT_invert";
1946         ot->description = "Invert image's channels";
1947         
1948         /* api callbacks */
1949         ot->exec = image_invert_exec;
1950         ot->poll = image_invert_poll;
1951         
1952         /* properties */
1953         prop = RNA_def_boolean(ot->srna, "invert_r", 0, "Red", "Invert Red Channel");
1954         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1955         prop = RNA_def_boolean(ot->srna, "invert_g", 0, "Green", "Invert Green Channel");
1956         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1957         prop = RNA_def_boolean(ot->srna, "invert_b", 0, "Blue", "Invert Blue Channel");
1958         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1959         prop = RNA_def_boolean(ot->srna, "invert_a", 0, "Alpha", "Invert Alpha Channel");
1960         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1961         
1962         /* flags */
1963         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1964 }
1965
1966 /********************* pack operator *********************/
1967
1968 static int image_pack_test(bContext *C, wmOperator *op)
1969 {
1970         Image *ima = CTX_data_edit_image(C);
1971         int as_png = RNA_boolean_get(op->ptr, "as_png");
1972
1973         if (!ima)
1974                 return 0;
1975         if (!as_png && ima->packedfile)
1976                 return 0;
1977
1978         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
1979                 BKE_report(op->reports, RPT_ERROR, "Packing movies or image sequences not supported");
1980                 return 0;
1981         }
1982
1983         return 1;
1984 }
1985
1986 static int image_pack_exec(bContext *C, wmOperator *op)
1987 {
1988         struct Main *bmain = CTX_data_main(C);
1989         Image *ima = CTX_data_edit_image(C);
1990         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
1991         int as_png = RNA_boolean_get(op->ptr, "as_png");
1992
1993         if (!image_pack_test(C, op))
1994                 return OPERATOR_CANCELLED;
1995         
1996         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1997                 BKE_report(op->reports, RPT_ERROR, "Cannot pack edited image from disk, only as internal PNG");
1998                 return OPERATOR_CANCELLED;
1999         }
2000
2001         if (as_png)
2002                 BKE_image_memorypack(ima);
2003         else
2004                 ima->packedfile = newPackedFile(op->reports, ima->name, ID_BLEND_PATH(bmain, &ima->id));
2005
2006         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
2007
2008         BKE_image_release_ibuf(ima, ibuf, NULL);
2009
2010         return OPERATOR_FINISHED;
2011 }
2012
2013 static int image_pack_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2014 {
2015         Image *ima = CTX_data_edit_image(C);
2016         ImBuf *ibuf;
2017         uiPopupMenu *pup;
2018         uiLayout *layout;
2019         int as_png = RNA_boolean_get(op->ptr, "as_png");
2020
2021         if (!image_pack_test(C, op))
2022                 return OPERATOR_CANCELLED;
2023
2024         ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
2025
2026         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
2027                 pup = uiPupMenuBegin(C, IFACE_("OK"), ICON_QUESTION);
2028                 layout = uiPupMenuLayout(pup);
2029                 uiItemBooleanO(layout, IFACE_("Can't pack edited image from disk, pack as internal PNG?"), ICON_NONE,
2030                                op->idname, "as_png", 1);
2031                 uiPupMenuEnd(C, pup);
2032
2033                 BKE_image_release_ibuf(ima, ibuf, NULL);
2034
2035                 return OPERATOR_CANCELLED;
2036         }
2037
2038         BKE_image_release_ibuf(ima, ibuf, NULL);
2039
2040         return image_pack_exec(C, op);
2041 }
2042
2043 void IMAGE_OT_pack(wmOperatorType *ot)
2044 {
2045         /* identifiers */
2046         ot->name = "Pack Image";
2047         ot->description = "Pack an image as embedded data into the .blend file"; 
2048         ot->idname = "IMAGE_OT_pack";
2049         
2050         /* api callbacks */
2051         ot->exec = image_pack_exec;
2052         ot->invoke = image_pack_invoke;
2053
2054         /* flags */
2055         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2056
2057         /* properties */
2058         RNA_def_boolean(ot->srna, "as_png", 0, "Pack As PNG", "Pack image as lossless PNG");
2059 }
2060
2061 /********************* unpack operator *********************/
2062
2063 static int image_unpack_exec(bContext *C, wmOperator *op)
2064 {
2065         Image *ima = CTX_data_edit_image(C);
2066         int method = RNA_enum_get(op->ptr, "method");
2067
2068         /* find the suppplied image by name */
2069         if (RNA_struct_property_is_set(op->ptr, "id")) {
2070                 char imaname[MAX_ID_NAME - 2];
2071                 RNA_string_get(op->ptr, "id", imaname);
2072                 ima = BLI_findstring(&CTX_data_main(C)->image, imaname, offsetof(ID, name) + 2);
2073                 if (!ima) ima = CTX_data_edit_image(C);
2074         }
2075         
2076         if (!ima || !ima->packedfile)
2077                 return OPERATOR_CANCELLED;
2078
2079         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
2080                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
2081                 return OPERATOR_CANCELLED;
2082         }
2083
2084         if (G.fileflags & G_AUTOPACK)
2085                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
2086         
2087         /* XXX unpackImage frees image buffers */
2088         ED_preview_kill_jobs(C);
2089         
2090         unpackImage(op->reports, ima, method);
2091         
2092         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
2093
2094         return OPERATOR_FINISHED;
2095 }
2096
2097 static int image_unpack_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2098 {
2099         Image *ima = CTX_data_edit_image(C);
2100
2101         if (RNA_struct_property_is_set(op->ptr, "id"))
2102                 return image_unpack_exec(C, op);
2103                 
2104         if (!ima || !ima->packedfile)
2105                 return OPERATOR_CANCELLED;
2106
2107         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
2108                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
2109                 return OPERATOR_CANCELLED;
2110         }
2111
2112         if (G.fileflags & G_AUTOPACK)
2113                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
2114
2115         unpack_menu(C, "IMAGE_OT_unpack", ima->id.name + 2, ima->name, "textures", ima->packedfile);
2116
2117         return OPERATOR_FINISHED;
2118 }
2119
2120 void IMAGE_OT_unpack(wmOperatorType *ot)
2121 {
2122         /* identifiers */
2123         ot->name = "Unpack Image";
2124         ot->description = "Save an image packed in the .blend file to disk"; 
2125         ot->idname = "IMAGE_OT_unpack";
2126         
2127         /* api callbacks */
2128         ot->exec = image_unpack_exec;
2129         ot->invoke = image_unpack_invoke;
2130
2131         /* flags */
2132         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2133         
2134         /* properties */
2135         RNA_def_enum(ot->srna, "method", unpack_method_items, PF_USE_LOCAL, "Method", "How to unpack");
2136         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 */
2137 }
2138
2139 /******************** sample image operator ********************/
2140
2141 typedef struct ImageSampleInfo {
2142         ARegionType *art;
2143         void *draw_handle;
2144         int x, y;
2145         int channels;
2146
2147         unsigned char col[4];
2148         float colf[4];
2149         float linearcol[4];
2150         int z;
2151         float zf;
2152
2153         unsigned char *colp;
2154         float *colfp;
2155         int *zp;
2156         float *zfp;
2157
2158         int draw;
2159         int color_manage;
2160         int use_default_view;
2161 } ImageSampleInfo;
2162
2163 static void image_sample_draw(const bContext *C, ARegion *ar, void *arg_info)
2164 {
2165         ImageSampleInfo *info = arg_info;
2166         if (info->draw) {
2167                 Scene *scene = CTX_data_scene(C);
2168
2169                 ED_image_draw_info(scene, ar, info->color_manage, info->use_default_view, info->channels,
2170                                    info->x, info->y, info->colp, info->colfp, info->linearcol, info->zp, info->zfp);
2171         }
2172 }
2173
2174 /* returns color in SRGB */
2175 /* matching ED_space_node_color_sample() */
2176 int ED_space_image_color_sample(SpaceImage *sima, ARegion *ar, int mval[2], float r_col[3])
2177 {
2178         void *lock;
2179         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2180         float fx, fy;
2181         int ret = FALSE;
2182
2183         if (ibuf == NULL) {
2184                 ED_space_image_release_buffer(sima, ibuf, lock);
2185                 return FALSE;
2186         }
2187
2188         UI_view2d_region_to_view(&ar->v2d, mval[0], mval[1], &fx, &fy);
2189
2190         if (fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) {
2191                 float *fp;
2192                 unsigned char *cp;
2193                 int x = (int)(fx * ibuf->x), y = (int)(fy * ibuf->y);
2194
2195                 CLAMP(x, 0, ibuf->x - 1);
2196                 CLAMP(y, 0, ibuf->y - 1);
2197
2198                 if (ibuf->rect_float) {
2199                         fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
2200                         linearrgb_to_srgb_v3_v3(r_col, fp);
2201                         ret = TRUE;
2202                 }
2203                 else if (ibuf->rect) {
2204                         cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
2205                         rgb_uchar_to_float(r_col, cp);
2206                         ret = TRUE;
2207                 }
2208         }
2209
2210         ED_space_image_release_buffer(sima, ibuf, lock);
2211         return ret;
2212 }
2213
2214 static void image_sample_apply(bContext *C, wmOperator *op, const wmEvent *event)
2215 {
2216         SpaceImage *sima = CTX_wm_space_image(C);
2217         ARegion *ar = CTX_wm_region(C);
2218         void *lock;
2219         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2220         ImageSampleInfo *info = op->customdata;
2221         float fx, fy;
2222         Scene *scene = CTX_data_scene(C);
2223         CurveMapping *curve_mapping = scene->view_settings.curve_mapping;
2224
2225         if (ibuf == NULL) {
2226                 ED_space_image_release_buffer(sima, ibuf, lock);
2227                 info->draw = 0;
2228                 return;
2229         }
2230
2231         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &fx, &fy);
2232
2233         if (fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) {
2234                 float *fp;
2235                 unsigned char *cp;
2236                 int x = (int)(fx * ibuf->x), y = (int)(fy * ibuf->y);
2237                 Image *image = ED_space_image(sima);
2238
2239                 CLAMP(x, 0, ibuf->x - 1);
2240                 CLAMP(y, 0, ibuf->y - 1);
2241
2242                 info->x = x;
2243                 info->y = y;
2244                 info->draw = 1;
2245                 info->channels = ibuf->channels;
2246
2247                 info->colp = NULL;
2248                 info->colfp = NULL;
2249                 info->zp = NULL;
2250                 info->zfp = NULL;
2251
2252                 info->use_default_view = (image->flag & IMA_VIEW_AS_RENDER) ? FALSE : TRUE;
2253
2254                 if (ibuf->rect) {
2255                         cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
2256
2257                         info->col[0] = cp[0];
2258                         info->col[1] = cp[1];
2259                         info->col[2] = cp[2];
2260                         info->col[3] = cp[3];
2261                         info->colp = info->col;
2262
2263                         info->colf[0] = (float)cp[0] / 255.0f;
2264                         info->colf[1] = (float)cp[1] / 255.0f;
2265                         info->colf[2] = (float)cp[2] / 255.0f;
2266                         info->colf[3] = (float)cp[3] / 255.0f;
2267                         info->colfp = info->colf;
2268
2269                         copy_v4_v4(info->linearcol, info->colf);
2270                         IMB_colormanagement_colorspace_to_scene_linear_v4(info->linearcol, false, ibuf->rect_colorspace);
2271
2272                         info->color_manage = TRUE;
2273                 }
2274                 if (ibuf->rect_float) {
2275                         fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
2276
2277                         info->colf[0] = fp[0];
2278                         info->colf[1] = fp[1];
2279                         info->colf[2] = fp[2];
2280                         info->colf[3] = fp[3];
2281                         info->colfp = info->colf;
2282
2283                         copy_v4_v4(info->linearcol, info->colf);
2284
2285                         info->color_manage = TRUE;
2286                 }
2287
2288                 if (ibuf->zbuf) {
2289                         info->z = ibuf->zbuf[y * ibuf->x + x];
2290                         info->zp = &info->z;
2291                 }
2292                 if (ibuf->zbuf_float) {
2293                         info->zf = ibuf->zbuf_float[y * ibuf->x + x];
2294                         info->zfp = &info->zf;
2295                 }
2296
2297                 if (curve_mapping && ibuf->channels == 4) {
2298                         /* we reuse this callback for set curves point operators */
2299                         if (RNA_struct_find_property(op->ptr, "point")) {
2300                                 int point = RNA_enum_get(op->ptr, "point");
2301
2302                                 if (point == 1) {
2303                                         curvemapping_set_black_white(curve_mapping, NULL, info->colfp);
2304                                 }
2305                                 else if (point == 0) {
2306                                         curvemapping_set_black_white(curve_mapping, info->colfp, NULL);
2307                                 }
2308                         }
2309                 }
2310
2311                 // XXX node curve integration ..
2312 #if 0
2313                 {
2314                         ScrArea *sa, *cur = curarea;
2315                         
2316                         node_curvemap_sample(fp);   /* sends global to node editor */
2317                         for (sa = G.curscreen->areabase.first; sa; sa = sa->next) {
2318                                 if (sa->spacetype == SPACE_NODE) {
2319                                         areawinset(sa->win);
2320                                         scrarea_do_windraw(sa);
2321                                 }
2322                         }
2323                         node_curvemap_sample(NULL);     /* clears global in node editor */
2324                         curarea = cur;
2325                 }
2326 #endif
2327         }
2328         else {
2329                 info->draw = 0;
2330         }
2331
2332         ED_space_image_release_buffer(sima, ibuf, lock);
2333         ED_area_tag_redraw(CTX_wm_area(C));
2334 }
2335
2336 static void image_sample_exit(bContext *C, wmOperator *op)
2337 {
2338         ImageSampleInfo *info = op->customdata;
2339
2340         ED_region_draw_cb_exit(info->art, info->draw_handle);
2341         ED_area_tag_redraw(CTX_wm_area(C));
2342         MEM_freeN(info);
2343 }
2344
2345 static int image_sample_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2346 {
2347         SpaceImage *sima = CTX_wm_space_image(C);
2348         ARegion *ar = CTX_wm_region(C);
2349         ImageSampleInfo *info;
2350
2351         if (!ED_space_image_has_buffer(sima))
2352                 return OPERATOR_CANCELLED;
2353         
2354         info = MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
2355         info->art = ar->type;
2356         info->draw_handle = ED_region_draw_cb_activate(ar->type, image_sample_draw, info, REGION_DRAW_POST_PIXEL);
2357         op->customdata = info;
2358
2359         image_sample_apply(C, op, event);
2360
2361         WM_event_add_modal_handler(C, op);
2362
2363         return OPERATOR_RUNNING_MODAL;
2364 }
2365
2366 static int image_sample_modal(bContext *C, wmOperator *op, const wmEvent *event)
2367 {
2368         switch (event->type) {
2369                 case LEFTMOUSE:
2370                 case RIGHTMOUSE: // XXX hardcoded
2371                         image_sample_exit(C, op);
2372                         return OPERATOR_CANCELLED;
2373                 case MOUSEMOVE:
2374                         image_sample_apply(C, op, event);
2375                         break;
2376         }
2377
2378         return OPERATOR_RUNNING_MODAL;
2379 }
2380
2381 static void image_sample_cancel(bContext *C, wmOperator *op)
2382 {
2383         image_sample_exit(C, op);
2384 }
2385
2386 void IMAGE_OT_sample(wmOperatorType *ot)
2387 {
2388         /* identifiers */
2389         ot->name = "Sample Color";
2390         ot->idname = "IMAGE_OT_sample";
2391         ot->description = "Use mouse to sample a color in current image";
2392         
2393         /* api callbacks */
2394         ot->invoke = image_sample_invoke;
2395         ot->modal = image_sample_modal;
2396         ot->cancel = image_sample_cancel;
2397         ot->poll = image_sample_poll;
2398
2399         /* flags */
2400         ot->flag = OPTYPE_BLOCKING;
2401 }
2402
2403 /******************** sample line operator ********************/
2404 static int image_sample_line_exec(bContext *C, wmOperator *op)
2405 {
2406         SpaceImage *sima = CTX_wm_space_image(C);
2407         ARegion *ar = CTX_wm_region(C);
2408         Scene *scene = CTX_data_scene(C);
2409
2410         int x_start = RNA_int_get(op->ptr, "xstart");
2411         int y_start = RNA_int_get(op->ptr, "ystart");
2412         int x_end = RNA_int_get(op->ptr, "xend");
2413         int y_end = RNA_int_get(op->ptr, "yend");
2414         
2415         void *lock;
2416         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2417         Histogram *hist = &sima->sample_line_hist;
2418         
2419         float x1f, y1f, x2f, y2f;
2420         
2421         if (ibuf == NULL) {
2422                 ED_space_image_release_buffer(sima, ibuf, lock);
2423                 return OPERATOR_CANCELLED;
2424         }
2425         /* hmmmm */
2426         if (ibuf->channels < 3) {
2427                 ED_space_image_release_buffer(sima, ibuf, lock);
2428                 return OPERATOR_CANCELLED;
2429         }
2430         
2431         UI_view2d_region_to_view(&ar->v2d, x_start, y_start, &x1f, &y1f);
2432         UI_view2d_region_to_view(&ar->v2d, x_end, y_end, &x2f, &y2f);
2433
2434         hist->co[0][0] = x1f;
2435         hist->co[0][1] = y1f;
2436         hist->co[1][0] = x2f;
2437         hist->co[1][1] = y2f;
2438
2439         /* enable line drawing */
2440         hist->flag |= HISTO_FLAG_SAMPLELINE;
2441
2442         BKE_histogram_update_sample_line(hist, ibuf, &scene->view_settings, &scene->display_settings);
2443         
2444         /* reset y zoom */
2445         hist->ymax = 1.0f;
2446
2447         ED_space_image_release_buffer(sima, ibuf, lock);
2448         
2449         ED_area_tag_redraw(CTX_wm_area(C));
2450         
2451         return OPERATOR_FINISHED;
2452 }
2453
2454 static int image_sample_line_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2455 {
2456         SpaceImage *sima = CTX_wm_space_image(C);
2457
2458         Histogram *hist = &sima->sample_line_hist;
2459         hist->flag &= ~HISTO_FLAG_SAMPLELINE;
2460
2461         if (!ED_space_image_has_buffer(sima))
2462                 return OPERATOR_CANCELLED;
2463         
2464         return WM_gesture_straightline_invoke(C, op, event);
2465 }
2466
2467 void IMAGE_OT_sample_line(wmOperatorType *ot)
2468 {
2469         /* identifiers */
2470         ot->name = "Sample Line";
2471         ot->idname = "IMAGE_OT_sample_line";
2472         ot->description = "Sample a line and show it in Scope panels";
2473         
2474         /* api callbacks */
2475         ot->invoke = image_sample_line_invoke;
2476         ot->modal = WM_gesture_straightline_modal;
2477         ot->exec = image_sample_line_exec;
2478         ot->poll = space_image_main_area_poll;
2479         ot->cancel = WM_gesture_straightline_cancel;
2480         
2481         /* flags */
2482         ot->flag = 0; /* no undo/register since this operates on the space */
2483         
2484         WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT);
2485 }
2486
2487 /******************** set curve point operator ********************/
2488
2489 void IMAGE_OT_curves_point_set(wmOperatorType *ot)
2490 {
2491         static EnumPropertyItem point_items[] = {
2492                 {0, "BLACK_POINT", 0, "Black Point", ""},
2493                 {1, "WHITE_POINT", 0, "White Point", ""},
2494                 {0, NULL, 0, NULL, NULL}
2495         };
2496
2497         /* identifiers */
2498         ot->name = "Set Curves Point";
2499         ot->idname = "IMAGE_OT_curves_point_set";
2500         ot->description = "Set black point or white point for curves";
2501
2502         /* flags */
2503         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2504         
2505         /* api callbacks */
2506         ot->invoke = image_sample_invoke;
2507         ot->modal = image_sample_modal;
2508         ot->cancel = image_sample_cancel;
2509         ot->poll = space_image_main_area_not_uv_brush_poll;
2510
2511         /* properties */
2512         RNA_def_enum(ot->srna, "point", point_items, 0, "Point", "Set black point or white point for curves");
2513 }
2514
2515 #if 0 /* Not ported to 2.5x yet */
2516 /******************** record composite operator *********************/
2517
2518 typedef struct RecordCompositeData {
2519         wmTimer *timer;
2520         int old_cfra;
2521         int sfra, efra;
2522 } RecordCompositeData;
2523
2524 static int image_record_composite_apply(bContext *C, wmOperator *op)
2525 {
2526         SpaceImage *sima = CTX_wm_space_image(C);
2527         RecordCompositeData *rcd = op->customdata;
2528         Scene *scene = CTX_data_scene(C);
2529         ImBuf *ibuf;
2530         
2531         WM_cursor_time(CTX_wm_window(C), scene->r.cfra);
2532
2533         // XXX scene->nodetree->test_break = blender_test_break;
2534         // XXX scene->nodetree->test_break = NULL;
2535         
2536         BKE_image_all_free_anim_ibufs(scene->r.cfra);
2537         ntreeCompositTagAnimated(scene->nodetree);
2538         ntreeCompositExecTree(scene->nodetree, &scene->r, 0, scene->r.cfra != rcd->old_cfra,
2539                               &scene->view_settings, &scene->display_settings);  /* 1 is no previews */
2540
2541         ED_area_tag_redraw(CTX_wm_area(C));
2542         
2543         ibuf = BKE_image_acquire_ibuf(sima->image, &sima->iuser, NULL);
2544         /* save memory in flipbooks */
2545         if (ibuf)
2546                 imb_freerectfloatImBuf(ibuf);
2547
2548         BKE_image_release_ibuf(sima->image, ibuf, NULL);
2549
2550         scene->r.cfra++;
2551
2552         return (scene->r.cfra <= rcd->efra);
2553 }
2554
2555 static int image_record_composite_init(bContext *C, wmOperator *op)
2556 {
2557         SpaceImage *sima = CTX_wm_space_image(C);
2558         Scene *scene = CTX_data_scene(C);
2559         RecordCompositeData *rcd;
2560
2561         if (sima->iuser.frames < 2)
2562                 return 0;
2563         if (scene->nodetree == NULL)
2564                 return 0;
2565         
2566         op->customdata = rcd = MEM_callocN(sizeof(RecordCompositeData), "ImageRecordCompositeData");
2567
2568         rcd->old_cfra = scene->r.cfra;
2569         rcd->sfra = sima->iuser.sfra;
2570         rcd->efra = sima->iuser.sfra + sima->iuser.frames - 1;
2571         scene->r.cfra = rcd->sfra;
2572
2573         return 1;
2574 }
2575
2576 static void image_record_composite_exit(bContext *C, wmOperator *op)
2577 {
2578         Scene *scene = CTX_data_scene(C);
2579         SpaceImage *sima = CTX_wm_space_image(C);
2580         RecordCompositeData *rcd = op->customdata;
2581
2582         scene->r.cfra = rcd->old_cfra;
2583
2584         WM_cursor_modal_restore(CTX_wm_window(C));
2585
2586         if (rcd->timer)
2587                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rcd->timer);
2588
2589         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
2590
2591         // XXX play_anim(0);
2592         // XXX allqueue(REDRAWNODE, 1);
2593
2594         MEM_freeN(rcd);
2595 }
2596
2597 static int image_record_composite_exec(bContext *C, wmOperator *op)
2598 {
2599         if (!image_record_composite_init(C, op))
2600                 return OPERATOR_CANCELLED;
2601         
2602         while (image_record_composite_apply(C, op)) {}
2603         
2604         image_record_composite_exit(C, op);
2605         
2606         return OPERATOR_FINISHED;
2607 }
2608
2609 static int image_record_composite_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2610 {
2611         RecordCompositeData *rcd;
2612         
2613         if (!image_record_composite_init(C, op))
2614                 return OPERATOR_CANCELLED;
2615
2616         rcd = op->customdata;
2617         rcd->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.0f);
2618         WM_event_add_modal_handler(C, op);
2619
2620         if (!image_record_composite_apply(C, op))
2621                 return OPERATOR_FINISHED;
2622
2623         return OPERATOR_RUNNING_MODAL;
2624 }
2625
2626 static int image_record_composite_modal(bContext *C, wmOperator *op, const wmEvent *event)
2627 {
2628         RecordCompositeData *rcd = op->customdata;
2629
2630         switch (event->type) {
2631                 case TIMER:
2632                         if (rcd->timer == event->customdata) {
2633                                 if (!image_record_composite_apply(C, op)) {
2634                                         image_record_composite_exit(C, op);
2635                                         return OPERATOR_FINISHED;
2636                                 }
2637                         }
2638                         break;
2639                 case ESCKEY:
2640                         image_record_composite_exit(C, op);
2641                         return OPERATOR_FINISHED;
2642         }
2643
2644         return OPERATOR_RUNNING_MODAL;
2645 }
2646
2647 static void image_record_composite_cancel(bContext *C, wmOperator *op)
2648 {
2649         image_record_composite_exit(C, op);
2650         return OPERATOR_CANCELLED;
2651 }
2652
2653 void IMAGE_OT_record_composite(wmOperatorType *ot)
2654 {
2655         /* identifiers */
2656         ot->name = "Record Composite";
2657         ot->idname = "IMAGE_OT_record_composite";
2658         
2659         /* api callbacks */
2660         ot->exec = image_record_composite_exec;
2661         ot->invoke = image_record_composite_invoke;
2662         ot->modal = image_record_composite_modal;
2663         ot->cancel = image_record_composite_cancel;
2664         ot->poll = space_image_buffer_exists_poll;
2665 }
2666
2667 #endif
2668
2669 /********************* cycle render slot operator *********************/
2670
2671 static int image_cycle_render_slot_poll(bContext *C)
2672 {
2673         Image *ima = CTX_data_edit_image(C);
2674
2675         return (ima && ima->type == IMA_TYPE_R_RESULT);
2676 }
2677
2678 static int image_cycle_render_slot_exec(bContext *C, wmOperator *op)
2679 {
2680         Image *ima = CTX_data_edit_image(C);
2681         int a, slot, cur = ima->render_slot;
2682         const short use_reverse = RNA_boolean_get(op->ptr, "reverse");
2683
2684         for (a = 1; a < IMA_MAX_RENDER_SLOT; a++) {
2685                 slot = (cur + (use_reverse ? -a : a)) % IMA_MAX_RENDER_SLOT;
2686                 if (slot < 0) slot += IMA_MAX_RENDER_SLOT;
2687
2688                 if (ima->renders[slot] || slot == ima->last_render_slot) {
2689                         ima->render_slot = slot;
2690                         break;
2691                 }
2692         }
2693
2694         if (a == IMA_MAX_RENDER_SLOT)
2695                 ima->render_slot = ((cur == 1) ? 0 : 1);
2696         
2697         WM_event_add_notifier(C, NC_IMAGE | ND_DRAW, NULL);
2698
2699         /* no undo push for browsing existing */
2700         if (ima->renders[ima->render_slot] || ima->render_slot == ima->last_render_slot)
2701                 return OPERATOR_CANCELLED;
2702         
2703         return OPERATOR_FINISHED;
2704 }
2705
2706 void IMAGE_OT_cycle_render_slot(wmOperatorType *ot)
2707 {
2708         /* identifiers */
2709         ot->name = "Cycle Render Slot";
2710         ot->idname = "IMAGE_OT_cycle_render_slot";
2711         ot->description = "Cycle through all non-void render slots";
2712         
2713         /* api callbacks */
2714         ot->exec = image_cycle_render_slot_exec;
2715         ot->poll = image_cycle_render_slot_poll;
2716
2717         /* flags */
2718         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2719
2720         RNA_def_boolean(ot->srna, "reverse", 0, "Cycle in Reverse", "");
2721 }