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