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