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