svn merge ^/trunk/blender -r48527:48537
[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_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_size(sima, &width, &height);
112                 ED_space_image_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_size(sima, &width, &height);
569         ED_space_image_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_size(sima, &width, &height);
626         ED_image_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)
906                 path = ima->name;
907
908         if (RNA_struct_property_is_set(op->ptr, "filepath"))
909                 return image_open_exec(C, op);
910         
911         image_open_init(C, op);
912
913         image_filesel(C, op, path);
914
915         return OPERATOR_RUNNING_MODAL;
916 }
917
918 /* called by other space types too */
919 void IMAGE_OT_open(wmOperatorType *ot)
920 {
921         /* identifiers */
922         ot->name = "Open Image";
923         ot->description = "Open image";
924         ot->idname = "IMAGE_OT_open";
925         
926         /* api callbacks */
927         ot->exec = image_open_exec;
928         ot->invoke = image_open_invoke;
929         ot->cancel = image_open_cancel;
930
931         /* flags */
932         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
933
934         /* properties */
935         WM_operator_properties_filesel(ot, FOLDERFILE | IMAGEFILE | MOVIEFILE, FILE_SPECIAL, FILE_OPENFILE, WM_FILESEL_FILEPATH | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY);
936 }
937
938 /******************** Match movie length operator ********************/
939 static int image_match_len_exec(bContext *C, wmOperator *UNUSED(op))
940 {
941         Scene *scene = CTX_data_scene(C);
942         Image *ima = CTX_data_pointer_get_type(C, "edit_image", &RNA_Image).data;
943         ImageUser *iuser = CTX_data_pointer_get_type(C, "edit_image_user", &RNA_ImageUser).data;
944
945         if (!ima || !iuser) {
946                 /* Try to get a Texture, or a SpaceImage from context... */
947                 SpaceImage *sima = CTX_wm_space_image(C);
948                 Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
949                 if (tex && tex->type == TEX_IMAGE) {
950                         ima = tex->ima;
951                         iuser = &tex->iuser;
952                 }
953                 else if (sima) {
954                         ima = sima->image;
955                         iuser = &sima->iuser;
956                 }
957                 
958         }
959
960         if (!ima || !iuser || !ima->anim)
961                 return OPERATOR_CANCELLED;
962
963         iuser->frames = IMB_anim_get_duration(ima->anim, IMB_TC_RECORD_RUN);
964         BKE_image_user_frame_calc(iuser, scene->r.cfra, 0);
965
966         return OPERATOR_FINISHED;
967 }
968
969 /* called by other space types too */
970 void IMAGE_OT_match_movie_length(wmOperatorType *ot)
971 {
972         /* identifiers */
973         ot->name = "Match Movie Length";
974         ot->description = "Set image's users length to the one of this video";
975         ot->idname = "IMAGE_OT_match_movie_length";
976         
977         /* api callbacks */
978         ot->exec = image_match_len_exec;
979
980         /* flags */
981         ot->flag = OPTYPE_REGISTER /* | OPTYPE_UNDO */; /* Don't think we need undo for that. */
982 }
983
984 /******************** replace image operator ********************/
985
986 static int image_replace_exec(bContext *C, wmOperator *op)
987 {
988         SpaceImage *sima = CTX_wm_space_image(C);
989         char str[FILE_MAX];
990
991         if (!sima->image)
992                 return OPERATOR_CANCELLED;
993         
994         RNA_string_get(op->ptr, "filepath", str);
995
996         /* we cant do much if the str is longer then FILE_MAX :/ */
997         BLI_strncpy(sima->image->name, str, sizeof(sima->image->name));
998
999         if (BLI_testextensie_array(str, imb_ext_movie))
1000                 sima->image->source = IMA_SRC_MOVIE;
1001         else
1002                 sima->image->source = IMA_SRC_FILE;
1003
1004         /* XXX unpackImage frees image buffers */
1005         ED_preview_kill_jobs(C);
1006         
1007         BKE_image_signal(sima->image, &sima->iuser, IMA_SIGNAL_RELOAD);
1008         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
1009
1010         return OPERATOR_FINISHED;
1011 }
1012
1013 static int image_replace_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1014 {
1015         SpaceImage *sima = CTX_wm_space_image(C);
1016
1017         if (!sima->image)
1018                 return OPERATOR_CANCELLED;
1019
1020         if (RNA_struct_property_is_set(op->ptr, "filepath"))
1021                 return image_replace_exec(C, op);
1022
1023         if (!RNA_struct_property_is_set(op->ptr, "relative_path"))
1024                 RNA_boolean_set(op->ptr, "relative_path", (strncmp(sima->image->name, "//", 2)) == 0);
1025
1026         image_filesel(C, op, sima->image->name);
1027
1028         return OPERATOR_RUNNING_MODAL;
1029 }
1030
1031 void IMAGE_OT_replace(wmOperatorType *ot)
1032 {
1033         /* identifiers */
1034         ot->name = "Replace Image";
1035         ot->idname = "IMAGE_OT_replace";
1036         ot->description = "Replace current image by another one from disk";
1037         
1038         /* api callbacks */
1039         ot->exec = image_replace_exec;
1040         ot->invoke = image_replace_invoke;
1041         ot->poll = space_image_poll;
1042
1043         /* flags */
1044         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1045
1046         /* properties */
1047         WM_operator_properties_filesel(ot, FOLDERFILE | IMAGEFILE | MOVIEFILE, FILE_SPECIAL, FILE_OPENFILE, WM_FILESEL_FILEPATH | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY);
1048 }
1049
1050 /******************** save image as operator ********************/
1051
1052 typedef struct {
1053         /* matching scene->r settings */
1054         //short planes, imtype, subimtype, quality;
1055         ImageFormatData im_format;
1056         char filepath[FILE_MAX]; /* keep absolute */
1057 } SaveImageOptions;
1058
1059 static void save_image_options_defaults(SaveImageOptions *simopts)
1060 {
1061         BKE_imformat_defaults(&simopts->im_format);
1062         simopts->filepath[0] = '\0';
1063 }
1064
1065 static char imtype_best_depth(ImBuf *ibuf, const char imtype)
1066 {
1067         const char depth_ok = BKE_imtype_valid_depths(imtype);
1068
1069         if (ibuf->rect_float) {
1070                 if (depth_ok & R_IMF_CHAN_DEPTH_32) return R_IMF_CHAN_DEPTH_32;
1071                 if (depth_ok & R_IMF_CHAN_DEPTH_24) return R_IMF_CHAN_DEPTH_24;
1072                 if (depth_ok & R_IMF_CHAN_DEPTH_16) return R_IMF_CHAN_DEPTH_16;
1073                 if (depth_ok & R_IMF_CHAN_DEPTH_12) return R_IMF_CHAN_DEPTH_12;
1074                 return R_IMF_CHAN_DEPTH_8;
1075         }
1076         else {
1077                 if (depth_ok & R_IMF_CHAN_DEPTH_8) return R_IMF_CHAN_DEPTH_8;
1078                 if (depth_ok & R_IMF_CHAN_DEPTH_12) return R_IMF_CHAN_DEPTH_12;
1079                 if (depth_ok & R_IMF_CHAN_DEPTH_16) return R_IMF_CHAN_DEPTH_16;
1080                 if (depth_ok & R_IMF_CHAN_DEPTH_24) return R_IMF_CHAN_DEPTH_24;
1081                 if (depth_ok & R_IMF_CHAN_DEPTH_32) return R_IMF_CHAN_DEPTH_32;
1082                 return R_IMF_CHAN_DEPTH_8; /* fallback, should not get here */
1083         }
1084 }
1085
1086 static int save_image_options_init(bContext *C, SaveImageOptions *simopts, SpaceImage *sima, Scene *scene, const short guess_path)
1087 {
1088         void *lock;
1089         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
1090
1091         if (ibuf) {
1092                 wmWindow *win = CTX_wm_window(C);
1093                 const ColorManagedViewSettings *view_settings;
1094                 Image *ima = sima->image;
1095                 short is_depth_set = FALSE;
1096
1097                 simopts->im_format.planes = ibuf->planes;
1098
1099                 if (ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE)) {
1100                         /* imtype */
1101                         simopts->im_format = scene->r.im_format;
1102                         is_depth_set = TRUE;
1103                 }
1104                 else if (ima->source == IMA_SRC_GENERATED) {
1105                         simopts->im_format.imtype = R_IMF_IMTYPE_PNG;
1106                 }
1107                 else {
1108                         simopts->im_format.imtype = BKE_ftype_to_imtype(ibuf->ftype);
1109                 }
1110                 //simopts->subimtype= scene->r.subimtype; /* XXX - this is lame, we need to make these available too! */
1111                 simopts->im_format.quality = ibuf->ftype & 0xff;
1112
1113                 BLI_strncpy(simopts->filepath, ibuf->name, sizeof(simopts->filepath));
1114
1115                 /* sanitize all settings */
1116
1117                 /* unlikely but just in case */
1118                 if (ELEM3(simopts->im_format.planes, R_IMF_PLANES_BW, R_IMF_PLANES_RGB, R_IMF_PLANES_RGBA) == 0) {
1119                         simopts->im_format.planes = R_IMF_PLANES_RGBA;
1120                 }
1121
1122                 /* depth, account for float buffer and format support */
1123                 if (is_depth_set == FALSE) {
1124                         simopts->im_format.depth = imtype_best_depth(ibuf, simopts->im_format.imtype);
1125                 }
1126
1127                 /* some formats don't use quality so fallback to scenes quality */
1128                 if (simopts->im_format.quality == 0) {
1129                         simopts->im_format.quality = scene->r.im_format.quality;
1130                 }
1131
1132                 /* check for empty path */
1133                 if (guess_path && simopts->filepath[0] == 0) {
1134                         if ( (G.ima[0] == '/') && (G.ima[1] == '/') && (G.ima[2] == '\0') ) {
1135                                 BLI_strncpy(simopts->filepath, "//untitled", FILE_MAX);
1136                         }
1137                         else {
1138                                 BLI_strncpy(simopts->filepath, G.ima, FILE_MAX);
1139                         }
1140                         BLI_path_abs(simopts->filepath, G.main->name);
1141                 }
1142
1143                 /* color management */
1144                 view_settings = IMB_view_settings_get_effective(win, &sima->view_settings);
1145
1146                 BKE_color_managed_display_settings_copy(&simopts->im_format.display_settings, &win->display_settings);
1147                 BKE_color_managed_view_settings_copy(&simopts->im_format.view_settings, view_settings);
1148         }
1149
1150         ED_space_image_release_buffer(sima, lock);
1151
1152         return (ibuf != NULL);
1153 }
1154
1155 static void save_image_options_from_op(SaveImageOptions *simopts, wmOperator *op)
1156 {
1157         if (op->customdata) {
1158                 simopts->im_format = *(ImageFormatData *)op->customdata;
1159         }
1160
1161         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
1162                 RNA_string_get(op->ptr, "filepath", simopts->filepath);
1163                 BLI_path_abs(simopts->filepath, G.main->name);
1164         }
1165 }
1166
1167 static void save_image_options_to_op(SaveImageOptions *simopts, wmOperator *op)
1168 {
1169         if (op->customdata) {
1170                 *(ImageFormatData *)op->customdata = simopts->im_format;
1171         }
1172
1173         RNA_string_set(op->ptr, "filepath", simopts->filepath);
1174 }
1175
1176 static ImBuf *save_image_colormanaged_imbuf_acquire(ImBuf *ibuf, SaveImageOptions *simopts, void **cache_handle)
1177 {
1178         ImageFormatData *imf = &simopts->im_format;
1179         ImBuf *colormanaged_ibuf;
1180         int do_colormanagement;
1181
1182         *cache_handle = NULL;
1183         do_colormanagement = !BKE_imtype_supports_float(imf->imtype);
1184
1185         if (do_colormanagement) {
1186                 unsigned char *display_buffer =
1187                         IMB_display_buffer_acquire(ibuf, &imf->view_settings, &imf->display_settings, cache_handle);
1188
1189                 colormanaged_ibuf = IMB_allocImBuf(ibuf->x, ibuf->y, ibuf->planes, 0);
1190                 colormanaged_ibuf->rect = (unsigned int *) display_buffer;
1191         }
1192         else {
1193                 colormanaged_ibuf = ibuf;
1194         }
1195
1196         return colormanaged_ibuf;
1197 }
1198
1199 /* assumes name is FILE_MAX */
1200 /* ima->name and ibuf->name should end up the same */
1201 static void save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveImageOptions *simopts, int do_newpath)
1202 {
1203         Image *ima = ED_space_image(sima);
1204         void *lock;
1205         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
1206
1207         if (ibuf) {
1208                 void *cache_handle;
1209                 ImBuf *colormanaged_ibuf;
1210                 const char *relbase = ID_BLEND_PATH(CTX_data_main(C), &ima->id);
1211                 const short relative = (RNA_struct_find_property(op->ptr, "relative_path") && RNA_boolean_get(op->ptr, "relative_path"));
1212                 const short save_copy = (RNA_struct_find_property(op->ptr, "copy") && RNA_boolean_get(op->ptr, "copy"));
1213                 short ok = FALSE;
1214
1215                 /* old global to ensure a 2nd save goes to same dir */
1216                 BLI_strncpy(G.ima, simopts->filepath, sizeof(G.ima));
1217
1218                 WM_cursor_wait(1);
1219
1220                 if (ima->type == IMA_TYPE_R_RESULT) {
1221                         /* enforce user setting for RGB or RGBA, but skip BW */
1222                         if (simopts->im_format.planes == R_IMF_PLANES_RGBA) {
1223                                 ibuf->planes = R_IMF_PLANES_RGBA;
1224                         }
1225                         else if (simopts->im_format.planes == R_IMF_PLANES_RGB) {
1226                                 ibuf->planes = R_IMF_PLANES_RGB;
1227                         }
1228                 }
1229                 else {
1230                         /* TODO, better solution, if a 24bit image is painted onto it may contain alpha */
1231                         if (ibuf->userflags & IB_BITMAPDIRTY) { /* it has been painted onto */
1232                                 /* checks each pixel, not ideal */
1233                                 ibuf->planes = BKE_imbuf_alpha_test(ibuf) ? 32 : 24;
1234                         }
1235                 }
1236
1237                 colormanaged_ibuf = save_image_colormanaged_imbuf_acquire(ibuf, simopts, &cache_handle);
1238
1239                 if (simopts->im_format.imtype == R_IMF_IMTYPE_MULTILAYER) {
1240                         Scene *scene = CTX_data_scene(C);
1241                         RenderResult *rr = BKE_image_acquire_renderresult(scene, ima);
1242                         if (rr) {
1243                                 RE_WriteRenderResult(op->reports, rr, simopts->filepath, simopts->im_format.quality);
1244                                 ok = TRUE;
1245                         }
1246                         else {
1247                                 BKE_report(op->reports, RPT_ERROR, "Did not write, no Multilayer Image");
1248                         }
1249                         BKE_image_release_renderresult(scene, ima);
1250                 }
1251                 else {
1252                         if (BKE_imbuf_write_as(colormanaged_ibuf, simopts->filepath, &simopts->im_format, save_copy)) {
1253                                 ok = TRUE;
1254                         }
1255                 }
1256
1257                 if (ok) {
1258                         if (!save_copy) {
1259                                 if (do_newpath) {
1260                                         BLI_strncpy(ibuf->name, simopts->filepath, sizeof(ibuf->name));
1261                                         BLI_strncpy(ima->name, simopts->filepath, sizeof(ima->name));
1262                                 }
1263
1264                                 ibuf->userflags &= ~IB_BITMAPDIRTY;
1265
1266                                 /* change type? */
1267                                 if (ima->type == IMA_TYPE_R_RESULT) {
1268                                         ima->type = IMA_TYPE_IMAGE;
1269
1270                                         /* workaround to ensure the render result buffer is no longer used
1271                                          * by this image, otherwise can crash when a new render result is
1272                                          * created. */
1273                                         if (ibuf->rect && !(ibuf->mall & IB_rect))
1274                                                 imb_freerectImBuf(ibuf);
1275                                         if (ibuf->rect_float && !(ibuf->mall & IB_rectfloat))
1276                                                 imb_freerectfloatImBuf(ibuf);
1277                                         if (ibuf->zbuf && !(ibuf->mall & IB_zbuf))
1278                                                 IMB_freezbufImBuf(ibuf);
1279                                         if (ibuf->zbuf_float && !(ibuf->mall & IB_zbuffloat))
1280                                                 IMB_freezbuffloatImBuf(ibuf);
1281                                 }
1282                                 if (ELEM(ima->source, IMA_SRC_GENERATED, IMA_SRC_VIEWER)) {
1283                                         ima->source = IMA_SRC_FILE;
1284                                         ima->type = IMA_TYPE_IMAGE;
1285                                 }
1286
1287                                 /* only image path, never ibuf */
1288                                 if (relative) {
1289                                         BLI_path_rel(ima->name, relbase); /* only after saving */
1290                                 }
1291                         }
1292                 }
1293                 else {
1294                         BKE_reportf(op->reports, RPT_ERROR, "Couldn't write image: %s", simopts->filepath);
1295                 }
1296
1297
1298                 WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
1299
1300                 WM_cursor_wait(0);
1301
1302                 if (cache_handle) {
1303                         colormanaged_ibuf->rect = NULL;
1304                         IMB_freeImBuf(colormanaged_ibuf);
1305
1306                         IMB_display_buffer_release(cache_handle);
1307                 }
1308         }
1309
1310         ED_space_image_release_buffer(sima, lock);
1311 }
1312
1313 static void image_save_as_free(wmOperator *op)
1314 {
1315         if (op->customdata) {
1316                 MEM_freeN(op->customdata);
1317                 op->customdata = NULL;
1318         }
1319 }
1320
1321 static int image_save_as_exec(bContext *C, wmOperator *op)
1322 {
1323         SpaceImage *sima = CTX_wm_space_image(C);
1324         SaveImageOptions simopts;
1325
1326         save_image_options_defaults(&simopts);
1327
1328         /* just in case to initialize values,
1329          * these should be set on invoke or by the caller. */
1330         save_image_options_init(C, &simopts, sima, CTX_data_scene(C), 0);
1331
1332         save_image_options_from_op(&simopts, op);
1333
1334         save_image_doit(C, sima, op, &simopts, TRUE);
1335
1336         image_save_as_free(op);
1337         return OPERATOR_FINISHED;
1338 }
1339
1340
1341 static int image_save_as_check(bContext *UNUSED(C), wmOperator *op)
1342 {
1343         ImageFormatData *imf = op->customdata;
1344         return WM_operator_filesel_ensure_ext_imtype(op, imf->imtype);
1345 }
1346
1347 static int image_save_as_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1348 {
1349         SpaceImage *sima = CTX_wm_space_image(C);
1350         Image *ima = ED_space_image(sima);
1351         Scene *scene = CTX_data_scene(C);
1352         SaveImageOptions simopts;
1353
1354         if (RNA_struct_property_is_set(op->ptr, "filepath"))
1355                 return image_save_as_exec(C, op);
1356
1357         save_image_options_defaults(&simopts);
1358
1359         if (save_image_options_init(C, &simopts, sima, scene, TRUE) == 0)
1360                 return OPERATOR_CANCELLED;
1361         save_image_options_to_op(&simopts, op);
1362
1363         /* enable save_copy by default for render results */
1364         if (ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE) && !RNA_struct_property_is_set(op->ptr, "copy")) {
1365                 RNA_boolean_set(op->ptr, "copy", TRUE);
1366         }
1367
1368         op->customdata = MEM_mallocN(sizeof(simopts.im_format), __func__);
1369         memcpy(op->customdata, &simopts.im_format, sizeof(simopts.im_format));
1370
1371         image_filesel(C, op, simopts.filepath);
1372
1373         return OPERATOR_RUNNING_MODAL;
1374 }
1375
1376 static int image_save_as_cancel(bContext *UNUSED(C), wmOperator *op)
1377 {
1378         image_save_as_free(op);
1379
1380         return OPERATOR_CANCELLED;
1381 }
1382
1383 static int image_save_as_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop)
1384 {
1385         const char *prop_id = RNA_property_identifier(prop);
1386
1387         return !(strcmp(prop_id, "filepath") == 0 ||
1388                  strcmp(prop_id, "directory") == 0 ||
1389                  strcmp(prop_id, "filename") == 0 ||
1390                  /* when saving a copy, relative path has no effect */
1391                  ((strcmp(prop_id, "relative_path") == 0) && RNA_boolean_get(ptr, "copy"))
1392                  );
1393 }
1394
1395 static void image_save_as_draw(bContext *UNUSED(C), wmOperator *op)
1396 {
1397         uiLayout *layout = op->layout;
1398         ImageFormatData *imf = op->customdata;
1399         PointerRNA ptr;
1400
1401         /* image template */
1402         RNA_pointer_create(NULL, &RNA_ImageFormatSettings, imf, &ptr);
1403         uiTemplateImageSettings(layout, &ptr);
1404
1405         /* main draw call */
1406         RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);
1407         uiDefAutoButsRNA(layout, &ptr, image_save_as_draw_check_prop, '\0');
1408 }
1409
1410 void IMAGE_OT_save_as(wmOperatorType *ot)
1411 {
1412 //      PropertyRNA *prop;
1413
1414         /* identifiers */
1415         ot->name = "Save As Image";
1416         ot->idname = "IMAGE_OT_save_as";
1417         ot->description = "Save the image with another name and/or settings";
1418         
1419         /* api callbacks */
1420         ot->exec = image_save_as_exec;
1421         ot->check = image_save_as_check;
1422         ot->invoke = image_save_as_invoke;
1423         ot->cancel = image_save_as_cancel;
1424         ot->ui = image_save_as_draw;
1425         ot->poll = space_image_buffer_exists_poll;
1426
1427         /* flags */
1428         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1429
1430         /* properties */
1431         RNA_def_boolean(ot->srna, "copy", 0, "Copy", "Create a new image file without modifying the current image in blender");
1432
1433         WM_operator_properties_filesel(ot, FOLDERFILE | IMAGEFILE | MOVIEFILE, FILE_SPECIAL, FILE_SAVE, WM_FILESEL_FILEPATH | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY);
1434 }
1435
1436 /******************** save image operator ********************/
1437
1438 static int image_save_exec(bContext *C, wmOperator *op)
1439 {
1440         SpaceImage *sima = CTX_wm_space_image(C);
1441         Scene *scene = CTX_data_scene(C);
1442         SaveImageOptions simopts;
1443
1444         if (save_image_options_init(C, &simopts, sima, scene, FALSE) == 0)
1445                 return OPERATOR_CANCELLED;
1446         save_image_options_from_op(&simopts, op);
1447
1448         if (BLI_exists(simopts.filepath) && BLI_file_is_writable(simopts.filepath)) {
1449                 save_image_doit(C, sima, op, &simopts, FALSE);
1450         }
1451         else {
1452                 BKE_reportf(op->reports, RPT_ERROR, "Can not save image, path '%s' is not writable", simopts.filepath);
1453                 return OPERATOR_CANCELLED;
1454         }
1455
1456         return OPERATOR_FINISHED;
1457 }
1458
1459 void IMAGE_OT_save(wmOperatorType *ot)
1460 {
1461         /* identifiers */
1462         ot->name = "Save Image";
1463         ot->idname = "IMAGE_OT_save";
1464         ot->description = "Save the image with current name and settings";
1465         
1466         /* api callbacks */
1467         ot->exec = image_save_exec;
1468         ot->poll = space_image_file_exists_poll;
1469
1470         /* flags */
1471         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1472 }
1473
1474 /******************* save sequence operator ********************/
1475
1476 static int image_save_sequence_exec(bContext *C, wmOperator *op)
1477 {
1478         Main *bmain = CTX_data_main(C);
1479         SpaceImage *sima = CTX_wm_space_image(C);
1480         ImBuf *ibuf;
1481         int tot = 0;
1482         char di[FILE_MAX], fi[FILE_MAX];
1483         
1484         if (sima->image == NULL)
1485                 return OPERATOR_CANCELLED;
1486
1487         if (sima->image->source != IMA_SRC_SEQUENCE) {
1488                 BKE_report(op->reports, RPT_ERROR, "Can only save sequence on image sequences");
1489                 return OPERATOR_CANCELLED;
1490         }
1491
1492         if (sima->image->type == IMA_TYPE_MULTILAYER) {
1493                 BKE_report(op->reports, RPT_ERROR, "Can't save multilayer sequences");
1494                 return OPERATOR_CANCELLED;
1495         }
1496         
1497         /* get total */
1498         for (ibuf = sima->image->ibufs.first; ibuf; ibuf = ibuf->next)
1499                 if (ibuf->userflags & IB_BITMAPDIRTY)
1500                         tot++;
1501         
1502         if (tot == 0) {
1503                 BKE_report(op->reports, RPT_WARNING, "No images have been changed");
1504                 return OPERATOR_CANCELLED;
1505         }
1506
1507         /* get a filename for menu */
1508         for (ibuf = sima->image->ibufs.first; ibuf; ibuf = ibuf->next)
1509                 if (ibuf->userflags & IB_BITMAPDIRTY)
1510                         break;
1511         
1512         BLI_strncpy(di, ibuf->name, FILE_MAX);
1513         BLI_splitdirstring(di, fi);
1514         
1515         BKE_reportf(op->reports, RPT_INFO, "%d Image(s) will be saved in %s", tot, di);
1516
1517         for (ibuf = sima->image->ibufs.first; ibuf; ibuf = ibuf->next) {
1518                 if (ibuf->userflags & IB_BITMAPDIRTY) {
1519                         char name[FILE_MAX];
1520                         BLI_strncpy(name, ibuf->name, sizeof(name));
1521                         
1522                         BLI_path_abs(name, bmain->name);
1523
1524                         if (0 == IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat)) {
1525                                 BKE_reportf(op->reports, RPT_ERROR, "Could not write image %s", name);
1526                                 break;
1527                         }
1528
1529                         BKE_reportf(op->reports, RPT_INFO, "Saved: %s\n", ibuf->name);
1530                         ibuf->userflags &= ~IB_BITMAPDIRTY;
1531                 }
1532         }
1533
1534         return OPERATOR_FINISHED;
1535 }
1536
1537 void IMAGE_OT_save_sequence(wmOperatorType *ot)
1538 {
1539         /* identifiers */
1540         ot->name = "Save Sequence";
1541         ot->idname = "IMAGE_OT_save_sequence";
1542         ot->description = "Save a sequence of images";
1543         
1544         /* api callbacks */
1545         ot->exec = image_save_sequence_exec;
1546         ot->poll = space_image_buffer_exists_poll;
1547
1548         /* flags */
1549         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1550 }
1551
1552 /******************** reload image operator ********************/
1553
1554 static int image_reload_exec(bContext *C, wmOperator *UNUSED(op))
1555 {
1556         Image *ima = CTX_data_edit_image(C);
1557         SpaceImage *sima = CTX_wm_space_image(C);
1558
1559         if (!ima)
1560                 return OPERATOR_CANCELLED;
1561
1562         /* XXX unpackImage frees image buffers */
1563         ED_preview_kill_jobs(C);
1564         
1565         // XXX other users?
1566         BKE_image_signal(ima, (sima) ? &sima->iuser : NULL, IMA_SIGNAL_RELOAD);
1567
1568         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1569         
1570         return OPERATOR_FINISHED;
1571 }
1572
1573 void IMAGE_OT_reload(wmOperatorType *ot)
1574 {
1575         /* identifiers */
1576         ot->name = "Reload Image";
1577         ot->idname = "IMAGE_OT_reload";
1578         ot->description = "Reload current image from disk";
1579         
1580         /* api callbacks */
1581         ot->exec = image_reload_exec;
1582
1583         /* flags */
1584         ot->flag = OPTYPE_REGISTER; /* no undo, image buffer is not handled by undo */
1585 }
1586
1587 /********************** new image operator *********************/
1588
1589 static int image_new_exec(bContext *C, wmOperator *op)
1590 {
1591         SpaceImage *sima;
1592         Scene *scene;
1593         Object *obedit;
1594         Image *ima;
1595         PointerRNA ptr, idptr;
1596         PropertyRNA *prop;
1597         char name[MAX_ID_NAME - 2];
1598         float color[4];
1599         int width, height, floatbuf, uvtestgrid, alpha;
1600
1601         /* retrieve state */
1602         sima = CTX_wm_space_image(C);
1603         scene = CTX_data_scene(C);
1604         obedit = CTX_data_edit_object(C);
1605
1606         RNA_string_get(op->ptr, "name", name);
1607         width = RNA_int_get(op->ptr, "width");
1608         height = RNA_int_get(op->ptr, "height");
1609         floatbuf = RNA_boolean_get(op->ptr, "float");
1610         uvtestgrid = RNA_boolean_get(op->ptr, "uv_test_grid");
1611         RNA_float_get_array(op->ptr, "color", color);
1612         alpha = RNA_boolean_get(op->ptr, "alpha");
1613         
1614         if (!floatbuf && scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
1615                 linearrgb_to_srgb_v3_v3(color, color);
1616
1617         if (!alpha)
1618                 color[3] = 1.0f;
1619
1620         ima = BKE_image_add_generated(width, height, name, alpha ? 32 : 24, floatbuf, uvtestgrid, color);
1621
1622         if (!ima)
1623                 return OPERATOR_CANCELLED;
1624
1625         /* hook into UI */
1626         uiIDContextProperty(C, &ptr, &prop);
1627
1628         if (prop) {
1629                 /* when creating new ID blocks, use is already 1, but RNA
1630                  * pointer se also increases user, so this compensates it */
1631                 ima->id.us--;
1632
1633                 RNA_id_pointer_create(&ima->id, &idptr);
1634                 RNA_property_pointer_set(&ptr, prop, idptr);
1635                 RNA_property_update(C, &ptr, prop);
1636         }
1637         else if (sima)
1638                 ED_space_image_set(sima, scene, obedit, ima);
1639
1640         // XXX other users?
1641         BKE_image_signal(ima, (sima) ? &sima->iuser : NULL, IMA_SIGNAL_USER_NEW_IMAGE);
1642         
1643         return OPERATOR_FINISHED;
1644 }
1645
1646 /* XXX, Ton is not a fan of OK buttons but using this function to avoid undo/redo bug while in mesh-editmode, - campbell */
1647 static int image_new_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1648 {
1649         return WM_operator_props_dialog_popup(C, op, 300, 100);
1650
1651 }
1652
1653 void IMAGE_OT_new(wmOperatorType *ot)
1654 {
1655         PropertyRNA *prop;
1656         static float default_color[4] = {0.0f, 0.0f, 0.0f, 1.0f};
1657         
1658         /* identifiers */
1659         ot->name = "New Image";
1660         ot->description = "Create a new image";
1661         ot->idname = "IMAGE_OT_new";
1662         
1663         /* api callbacks */
1664         ot->exec = image_new_exec;
1665         ot->invoke = image_new_invoke;
1666         
1667         /* flags */
1668         ot->flag = OPTYPE_UNDO;
1669
1670         /* properties */
1671         RNA_def_string(ot->srna, "name", "untitled", MAX_ID_NAME - 2, "Name", "Image datablock name");
1672         RNA_def_int(ot->srna, "width", 1024, 1, INT_MAX, "Width", "Image width", 1, 16384);
1673         RNA_def_int(ot->srna, "height", 1024, 1, INT_MAX, "Height", "Image height", 1, 16384);
1674         prop = RNA_def_float_color(ot->srna, "color", 4, NULL, 0.0f, FLT_MAX, "Color", "Default fill color", 0.0f, 1.0f);
1675         RNA_def_property_float_array_default(prop, default_color);
1676         RNA_def_boolean(ot->srna, "alpha", 1, "Alpha", "Create an image with an alpha channel");
1677         RNA_def_boolean(ot->srna, "uv_test_grid", 0, "UV Test Grid", "Fill the image with a grid for UV map testing");
1678         RNA_def_boolean(ot->srna, "float", 0, "32 bit Float", "Create image with 32 bit floating point bit depth");
1679 }
1680
1681 /********************* invert operators *********************/
1682
1683 static int image_invert_poll(bContext *C)
1684 {
1685         Image *ima = CTX_data_edit_image(C);
1686         ImBuf *ibuf = BKE_image_get_ibuf(ima, NULL);
1687         
1688         if (ibuf != NULL)
1689                 return 1;
1690         return 0;
1691 }
1692
1693 static int image_invert_exec(bContext *C, wmOperator *op)
1694 {
1695         Image *ima = CTX_data_edit_image(C);
1696         ImBuf *ibuf = BKE_image_get_ibuf(ima, NULL);
1697
1698         // flags indicate if this channel should be inverted
1699         const short r = RNA_boolean_get(op->ptr, "invert_r");
1700         const short g = RNA_boolean_get(op->ptr, "invert_g");
1701         const short b = RNA_boolean_get(op->ptr, "invert_b");
1702         const short a = RNA_boolean_get(op->ptr, "invert_a");
1703
1704         int i;
1705
1706         if (ibuf == NULL)  // TODO: this should actually never happen, but does for render-results -> cleanup
1707                 return OPERATOR_CANCELLED;
1708
1709         /* TODO: make this into an IMB_invert_channels(ibuf,r,g,b,a) method!? */
1710         if (ibuf->rect_float) {
1711                 
1712                 float *fp = (float *) ibuf->rect_float;
1713                 for (i = ibuf->x * ibuf->y; i > 0; i--, fp += 4) {
1714                         if (r) fp[0] = 1.0f - fp[0];
1715                         if (g) fp[1] = 1.0f - fp[1];
1716                         if (b) fp[2] = 1.0f - fp[2];
1717                         if (a) fp[3] = 1.0f - fp[3];
1718                 }
1719
1720                 if (ibuf->rect) {
1721                         IMB_rect_from_float(ibuf);
1722                 }
1723         }
1724         else if (ibuf->rect) {
1725                 
1726                 char *cp = (char *) ibuf->rect;
1727                 for (i = ibuf->x * ibuf->y; i > 0; i--, cp += 4) {
1728                         if (r) cp[0] = 255 - cp[0];
1729                         if (g) cp[1] = 255 - cp[1];
1730                         if (b) cp[2] = 255 - cp[2];
1731                         if (a) cp[3] = 255 - cp[3];
1732                 }
1733         }
1734         else {
1735                 return OPERATOR_CANCELLED;
1736         }
1737
1738         ibuf->userflags |= IB_BITMAPDIRTY;
1739         if (ibuf->mipmap[0])
1740                 ibuf->userflags |= IB_MIPMAP_INVALID;
1741
1742         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1743         return OPERATOR_FINISHED;
1744 }
1745
1746 void IMAGE_OT_invert(wmOperatorType *ot)
1747 {
1748         /* identifiers */
1749         ot->name = "Invert Channels";
1750         ot->idname = "IMAGE_OT_invert";
1751         ot->description = "Invert image's channels";
1752         
1753         /* api callbacks */
1754         ot->exec = image_invert_exec;
1755         ot->poll = image_invert_poll;
1756         
1757         /* properties */
1758         RNA_def_boolean(ot->srna, "invert_r", 0, "Red", "Invert Red Channel");
1759         RNA_def_boolean(ot->srna, "invert_g", 0, "Green", "Invert Green Channel");
1760         RNA_def_boolean(ot->srna, "invert_b", 0, "Blue", "Invert Blue Channel");
1761         RNA_def_boolean(ot->srna, "invert_a", 0, "Alpha", "Invert Alpha Channel");
1762         
1763         /* flags */
1764         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1765 }
1766
1767 /********************* pack operator *********************/
1768
1769 static int image_pack_test(bContext *C, wmOperator *op)
1770 {
1771         Image *ima = CTX_data_edit_image(C);
1772         int as_png = RNA_boolean_get(op->ptr, "as_png");
1773
1774         if (!ima)
1775                 return 0;
1776         if (!as_png && ima->packedfile)
1777                 return 0;
1778
1779         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
1780                 BKE_report(op->reports, RPT_ERROR, "Packing movies or image sequences not supported");
1781                 return 0;
1782         }
1783
1784         return 1;
1785 }
1786
1787 static int image_pack_exec(bContext *C, wmOperator *op)
1788 {
1789         struct Main *bmain = CTX_data_main(C);
1790         Image *ima = CTX_data_edit_image(C);
1791         ImBuf *ibuf = BKE_image_get_ibuf(ima, NULL);
1792         int as_png = RNA_boolean_get(op->ptr, "as_png");
1793
1794         if (!image_pack_test(C, op))
1795                 return OPERATOR_CANCELLED;
1796         
1797         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1798                 BKE_report(op->reports, RPT_ERROR, "Can't pack edited image from disk, only as internal PNG");
1799                 return OPERATOR_CANCELLED;
1800         }
1801
1802         if (as_png)
1803                 BKE_image_memorypack(ima);
1804         else
1805                 ima->packedfile = newPackedFile(op->reports, ima->name, ID_BLEND_PATH(bmain, &ima->id));
1806
1807         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1808         
1809         return OPERATOR_FINISHED;
1810 }
1811
1812 static int image_pack_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1813 {
1814         Image *ima = CTX_data_edit_image(C);
1815         ImBuf *ibuf = BKE_image_get_ibuf(ima, NULL);
1816         uiPopupMenu *pup;
1817         uiLayout *layout;
1818         int as_png = RNA_boolean_get(op->ptr, "as_png");
1819
1820         if (!image_pack_test(C, op))
1821                 return OPERATOR_CANCELLED;
1822         
1823         if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1824                 pup = uiPupMenuBegin(C, "OK", ICON_QUESTION);
1825                 layout = uiPupMenuLayout(pup);
1826                 uiItemBooleanO(layout, "Can't pack edited image from disk. Pack as internal PNG?", ICON_NONE, op->idname, "as_png", 1);
1827                 uiPupMenuEnd(C, pup);
1828
1829                 return OPERATOR_CANCELLED;
1830         }
1831
1832         return image_pack_exec(C, op);
1833 }
1834
1835 void IMAGE_OT_pack(wmOperatorType *ot)
1836 {
1837         /* identifiers */
1838         ot->name = "Pack Image";
1839         ot->description = "Pack an image as embedded data into the .blend file"; 
1840         ot->idname = "IMAGE_OT_pack";
1841         
1842         /* api callbacks */
1843         ot->exec = image_pack_exec;
1844         ot->invoke = image_pack_invoke;
1845
1846         /* flags */
1847         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1848
1849         /* properties */
1850         RNA_def_boolean(ot->srna, "as_png", 0, "Pack As PNG", "Pack image as lossless PNG");
1851 }
1852
1853 /********************* unpack operator *********************/
1854
1855 static int image_unpack_exec(bContext *C, wmOperator *op)
1856 {
1857         Image *ima = CTX_data_edit_image(C);
1858         int method = RNA_enum_get(op->ptr, "method");
1859
1860         /* find the suppplied image by name */
1861         if (RNA_struct_property_is_set(op->ptr, "id")) {
1862                 char imaname[MAX_ID_NAME - 2];
1863                 RNA_string_get(op->ptr, "id", imaname);
1864                 ima = BLI_findstring(&CTX_data_main(C)->image, imaname, offsetof(ID, name) + 2);
1865                 if (!ima) ima = CTX_data_edit_image(C);
1866         }
1867         
1868         if (!ima || !ima->packedfile)
1869                 return OPERATOR_CANCELLED;
1870
1871         if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
1872                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
1873                 return OPERATOR_CANCELLED;
1874         }
1875
1876         if (G.fileflags & G_AUTOPACK)
1877                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
1878         
1879         /* XXX unpackImage frees image buffers */
1880         ED_preview_kill_jobs(C);
1881         
1882         unpackImage(op->reports, ima, method);
1883         
1884         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1885
1886         return OPERATOR_FINISHED;
1887 }
1888
1889 static int image_unpack_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1890 {
1891         Image *ima = CTX_data_edit_image(C);
1892
1893         if (RNA_struct_property_is_set(op->ptr, "id"))
1894                 return image_unpack_exec(C, op);
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         unpack_menu(C, "IMAGE_OT_unpack", ima->id.name + 2, ima->name, "textures", ima->packedfile);
1908
1909         return OPERATOR_FINISHED;
1910 }
1911
1912 void IMAGE_OT_unpack(wmOperatorType *ot)
1913 {
1914         /* identifiers */
1915         ot->name = "Unpack Image";
1916         ot->description = "Save an image packed in the .blend file to disk"; 
1917         ot->idname = "IMAGE_OT_unpack";
1918         
1919         /* api callbacks */
1920         ot->exec = image_unpack_exec;
1921         ot->invoke = image_unpack_invoke;
1922
1923         /* flags */
1924         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1925         
1926         /* properties */
1927         RNA_def_enum(ot->srna, "method", unpack_method_items, PF_USE_LOCAL, "Method", "How to unpack");
1928         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 */
1929 }
1930
1931 /******************** sample image operator ********************/
1932
1933 typedef struct ImageSampleInfo {
1934         ARegionType *art;
1935         void *draw_handle;
1936         int x, y;
1937         int channels;
1938
1939         unsigned char col[4];
1940         float colf[4];
1941         int z;
1942         float zf;
1943
1944         unsigned char *colp;
1945         float *colfp;
1946         int *zp;
1947         float *zfp;
1948
1949         int draw;
1950 } ImageSampleInfo;
1951
1952 static void image_sample_draw(const bContext *UNUSED(C), ARegion *ar, void *arg_info)
1953 {
1954         ImageSampleInfo *info = arg_info;
1955         if (info->draw) {
1956                 /* no color management needed for images (color_manage=0) */
1957                 ED_image_draw_info(ar, 0, info->channels, info->x, info->y, info->colp, info->colfp, info->zp, info->zfp);
1958         }
1959 }
1960
1961 static void image_sample_apply(bContext *C, wmOperator *op, wmEvent *event)
1962 {
1963         SpaceImage *sima = CTX_wm_space_image(C);
1964         ARegion *ar = CTX_wm_region(C);
1965         void *lock;
1966         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
1967         ImageSampleInfo *info = op->customdata;
1968         float fx, fy;
1969         
1970         if (ibuf == NULL) {
1971                 ED_space_image_release_buffer(sima, lock);
1972                 info->draw = 0;
1973                 return;
1974         }
1975
1976         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &fx, &fy);
1977
1978         if (fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) {
1979                 float *fp;
1980                 unsigned char *cp;
1981                 int x = (int)(fx * ibuf->x), y = (int)(fy * ibuf->y);
1982
1983                 CLAMP(x, 0, ibuf->x - 1);
1984                 CLAMP(y, 0, ibuf->y - 1);
1985
1986                 info->x = x;
1987                 info->y = y;
1988                 info->draw = 1;
1989                 info->channels = ibuf->channels;
1990
1991                 info->colp = NULL;
1992                 info->colfp = NULL;
1993                 info->zp = NULL;
1994                 info->zfp = NULL;
1995                 
1996                 if (ibuf->rect) {
1997                         cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
1998
1999                         info->col[0] = cp[0];
2000                         info->col[1] = cp[1];
2001                         info->col[2] = cp[2];
2002                         info->col[3] = cp[3];
2003                         info->colp = info->col;
2004
2005                         info->colf[0] = (float)cp[0] / 255.0f;
2006                         info->colf[1] = (float)cp[1] / 255.0f;
2007                         info->colf[2] = (float)cp[2] / 255.0f;
2008                         info->colf[3] = (float)cp[3] / 255.0f;
2009                         info->colfp = info->colf;
2010                 }
2011                 if (ibuf->rect_float) {
2012                         fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
2013
2014                         info->colf[0] = fp[0];
2015                         info->colf[1] = fp[1];
2016                         info->colf[2] = fp[2];
2017                         info->colf[3] = fp[3];
2018                         info->colfp = info->colf;
2019                 }
2020
2021                 if (ibuf->zbuf) {
2022                         info->z = ibuf->zbuf[y * ibuf->x + x];
2023                         info->zp = &info->z;
2024                 }
2025                 if (ibuf->zbuf_float) {
2026                         info->zf = ibuf->zbuf_float[y * ibuf->x + x];
2027                         info->zfp = &info->zf;
2028                 }
2029                 
2030                 if (sima->cumap && ibuf->channels == 4) {
2031                         /* we reuse this callback for set curves point operators */
2032                         if (RNA_struct_find_property(op->ptr, "point")) {
2033                                 int point = RNA_enum_get(op->ptr, "point");
2034
2035                                 if (point == 1) {
2036                                         curvemapping_set_black_white(sima->cumap, NULL, info->colfp);
2037                                         if (ibuf->rect_float)
2038                                                 curvemapping_do_ibuf(sima->cumap, ibuf);
2039                                 }
2040                                 else if (point == 0) {
2041                                         curvemapping_set_black_white(sima->cumap, info->colfp, NULL);
2042                                         if (ibuf->rect_float)
2043                                                 curvemapping_do_ibuf(sima->cumap, ibuf);
2044                                 }
2045                         }
2046                 }
2047                                 
2048                 // XXX node curve integration ..
2049 #if 0
2050                 {
2051                         ScrArea *sa, *cur = curarea;
2052                         
2053                         node_curvemap_sample(fp);   /* sends global to node editor */
2054                         for (sa = G.curscreen->areabase.first; sa; sa = sa->next) {
2055                                 if (sa->spacetype == SPACE_NODE) {
2056                                         areawinset(sa->win);
2057                                         scrarea_do_windraw(sa);
2058                                 }
2059                         }
2060                         node_curvemap_sample(NULL);     /* clears global in node editor */
2061                         curarea = cur;
2062                 }
2063 #endif
2064         }
2065         else {
2066                 info->draw = 0;
2067         }
2068
2069         ED_space_image_release_buffer(sima, lock);
2070         ED_area_tag_redraw(CTX_wm_area(C));
2071 }
2072
2073 static void image_sample_exit(bContext *C, wmOperator *op)
2074 {
2075         ImageSampleInfo *info = op->customdata;
2076
2077         ED_region_draw_cb_exit(info->art, info->draw_handle);
2078         ED_area_tag_redraw(CTX_wm_area(C));
2079         MEM_freeN(info);
2080 }
2081
2082 static int image_sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
2083 {
2084         SpaceImage *sima = CTX_wm_space_image(C);
2085         ARegion *ar = CTX_wm_region(C);
2086         ImageSampleInfo *info;
2087
2088         if (!ED_space_image_has_buffer(sima))
2089                 return OPERATOR_CANCELLED;
2090         
2091         info = MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
2092         info->art = ar->type;
2093         info->draw_handle = ED_region_draw_cb_activate(ar->type, image_sample_draw, info, REGION_DRAW_POST_PIXEL);
2094         op->customdata = info;
2095
2096         image_sample_apply(C, op, event);
2097
2098         WM_event_add_modal_handler(C, op);
2099
2100         return OPERATOR_RUNNING_MODAL;
2101 }
2102
2103 static int image_sample_modal(bContext *C, wmOperator *op, wmEvent *event)
2104 {
2105         switch (event->type) {
2106                 case LEFTMOUSE:
2107                 case RIGHTMOUSE: // XXX hardcoded
2108                         image_sample_exit(C, op);
2109                         return OPERATOR_CANCELLED;
2110                 case MOUSEMOVE:
2111                         image_sample_apply(C, op, event);
2112                         break;
2113         }
2114
2115         return OPERATOR_RUNNING_MODAL;
2116 }
2117
2118 static int image_sample_cancel(bContext *C, wmOperator *op)
2119 {
2120         image_sample_exit(C, op);
2121         return OPERATOR_CANCELLED;
2122 }
2123
2124 void IMAGE_OT_sample(wmOperatorType *ot)
2125 {
2126         /* identifiers */
2127         ot->name = "Sample Color";
2128         ot->idname = "IMAGE_OT_sample";
2129         ot->description = "Use mouse to sample a color in current image";
2130         
2131         /* api callbacks */
2132         ot->invoke = image_sample_invoke;
2133         ot->modal = image_sample_modal;
2134         ot->cancel = image_sample_cancel;
2135         ot->poll = space_image_image_sample_poll;
2136
2137         /* flags */
2138         ot->flag = OPTYPE_BLOCKING;
2139 }
2140
2141 /******************** sample line operator ********************/
2142 static int image_sample_line_exec(bContext *C, wmOperator *op)
2143 {
2144         SpaceImage *sima = CTX_wm_space_image(C);
2145         ARegion *ar = CTX_wm_region(C);
2146         Scene *scene = CTX_data_scene(C);
2147
2148         int x_start = RNA_int_get(op->ptr, "xstart");
2149         int y_start = RNA_int_get(op->ptr, "ystart");
2150         int x_end = RNA_int_get(op->ptr, "xend");
2151         int y_end = RNA_int_get(op->ptr, "yend");
2152         
2153         void *lock;
2154         ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
2155         Histogram *hist = &sima->sample_line_hist;
2156         
2157         float x1f, y1f, x2f, y2f;
2158         
2159         if (ibuf == NULL) {
2160                 ED_space_image_release_buffer(sima, lock);
2161                 return OPERATOR_CANCELLED;
2162         }
2163         /* hmmmm */
2164         if (ibuf->channels < 3) {
2165                 ED_space_image_release_buffer(sima, lock);
2166                 return OPERATOR_CANCELLED;
2167         }
2168         
2169         UI_view2d_region_to_view(&ar->v2d, x_start, y_start, &x1f, &y1f);
2170         UI_view2d_region_to_view(&ar->v2d, x_end, y_end, &x2f, &y2f);
2171
2172         hist->co[0][0] = x1f;
2173         hist->co[0][1] = y1f;
2174         hist->co[1][0] = x2f;
2175         hist->co[1][1] = y2f;
2176
2177         BKE_histogram_update_sample_line(hist, ibuf, (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) != 0);
2178         
2179         ED_space_image_release_buffer(sima, lock);
2180         
2181         ED_area_tag_redraw(CTX_wm_area(C));
2182         
2183         return OPERATOR_FINISHED;
2184 }
2185
2186 static int image_sample_line_invoke(bContext *C, wmOperator *op, wmEvent *event)
2187 {
2188         SpaceImage *sima = CTX_wm_space_image(C);
2189
2190         Histogram *hist = &sima->sample_line_hist;
2191         hist->flag &= ~HISTO_FLAG_SAMPLELINE;
2192
2193         if (!ED_space_image_has_buffer(sima))
2194                 return OPERATOR_CANCELLED;
2195         
2196         return WM_gesture_straightline_invoke(C, op, event);
2197 }
2198
2199 void IMAGE_OT_sample_line(wmOperatorType *ot)
2200 {
2201         /* identifiers */
2202         ot->name = "Sample Line";
2203         ot->idname = "IMAGE_OT_sample_line";
2204         ot->description = "Sample a line and show it in Scope panels";
2205         
2206         /* api callbacks */
2207         ot->invoke = image_sample_line_invoke;
2208         ot->modal = WM_gesture_straightline_modal;
2209         ot->exec = image_sample_line_exec;
2210         ot->poll = space_image_main_area_poll;
2211         ot->cancel = WM_gesture_straightline_cancel;
2212         
2213         /* flags */
2214         ot->flag = 0; /* no undo/register since this operates on the space */
2215         
2216         WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT);
2217 }
2218
2219 /******************** set curve point operator ********************/
2220
2221 void IMAGE_OT_curves_point_set(wmOperatorType *ot)
2222 {
2223         static EnumPropertyItem point_items[] = {
2224                 {0, "BLACK_POINT", 0, "Black Point", ""},
2225                 {1, "WHITE_POINT", 0, "White Point", ""},
2226                 {0, NULL, 0, NULL, NULL}
2227         };
2228
2229         /* identifiers */
2230         ot->name = "Set Curves Point";
2231         ot->idname = "IMAGE_OT_curves_point_set";
2232         ot->description = "Set black point or white point for curves";
2233
2234         /* flags */
2235         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2236         
2237         /* api callbacks */
2238         ot->invoke = image_sample_invoke;
2239         ot->modal = image_sample_modal;
2240         ot->cancel = image_sample_cancel;
2241         ot->poll = space_image_main_area_not_uv_brush_poll;
2242
2243         /* properties */
2244         RNA_def_enum(ot->srna, "point", point_items, 0, "Point", "Set black point or white point for curves");
2245 }
2246
2247 /******************** record composite operator *********************/
2248
2249 typedef struct RecordCompositeData {
2250         wmTimer *timer;
2251         int old_cfra;
2252         int sfra, efra;
2253 } RecordCompositeData;
2254
2255 static int image_record_composite_apply(bContext *C, wmOperator *op)
2256 {
2257         SpaceImage *sima = CTX_wm_space_image(C);
2258         RecordCompositeData *rcd = op->customdata;
2259         Scene *scene = CTX_data_scene(C);
2260         ImBuf *ibuf;
2261         
2262         WM_timecursor(CTX_wm_window(C), scene->r.cfra);
2263
2264         // XXX scene->nodetree->test_break= blender_test_break;
2265         // XXX scene->nodetree->test_break= NULL;
2266         
2267         BKE_image_all_free_anim_ibufs(scene->r.cfra);
2268         ntreeCompositTagAnimated(scene->nodetree);
2269         ntreeCompositExecTree(scene->nodetree, &scene->r, 0, scene->r.cfra != rcd->old_cfra);  /* 1 is no previews */
2270
2271         ED_area_tag_redraw(CTX_wm_area(C));
2272         
2273         ibuf = BKE_image_get_ibuf(sima->image, &sima->iuser);
2274         /* save memory in flipbooks */
2275         if (ibuf)
2276                 imb_freerectfloatImBuf(ibuf);
2277         
2278         scene->r.cfra++;
2279
2280         return (scene->r.cfra <= rcd->efra);
2281 }
2282
2283 static int image_record_composite_init(bContext *C, wmOperator *op)
2284 {
2285         SpaceImage *sima = CTX_wm_space_image(C);
2286         Scene *scene = CTX_data_scene(C);
2287         RecordCompositeData *rcd;
2288
2289         if (sima->iuser.frames < 2)
2290                 return 0;
2291         if (scene->nodetree == NULL)
2292                 return 0;
2293         
2294         op->customdata = rcd = MEM_callocN(sizeof(RecordCompositeData), "ImageRecordCompositeData");
2295
2296         rcd->old_cfra = scene->r.cfra;
2297         rcd->sfra = sima->iuser.sfra;
2298         rcd->efra = sima->iuser.sfra + sima->iuser.frames - 1;
2299         scene->r.cfra = rcd->sfra;
2300
2301         return 1;
2302 }
2303
2304 static void image_record_composite_exit(bContext *C, wmOperator *op)
2305 {
2306         Scene *scene = CTX_data_scene(C);
2307         SpaceImage *sima = CTX_wm_space_image(C);
2308         RecordCompositeData *rcd = op->customdata;
2309
2310         scene->r.cfra = rcd->old_cfra;
2311
2312         WM_cursor_restore(CTX_wm_window(C));
2313
2314         if (rcd->timer)
2315                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rcd->timer);
2316
2317         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
2318
2319         // XXX play_anim(0);
2320         // XXX allqueue(REDRAWNODE, 1);
2321
2322         MEM_freeN(rcd);
2323 }
2324
2325 static int image_record_composite_exec(bContext *C, wmOperator *op)
2326 {
2327         if (!image_record_composite_init(C, op))
2328                 return OPERATOR_CANCELLED;
2329         
2330         while (image_record_composite_apply(C, op))
2331                 ;
2332         
2333         image_record_composite_exit(C, op);
2334         
2335         return OPERATOR_FINISHED;
2336 }
2337
2338 static int image_record_composite_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2339 {
2340         RecordCompositeData *rcd;
2341         
2342         if (!image_record_composite_init(C, op))
2343                 return OPERATOR_CANCELLED;
2344
2345         rcd = op->customdata;
2346         rcd->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.0f);
2347         WM_event_add_modal_handler(C, op);
2348
2349         if (!image_record_composite_apply(C, op))
2350                 return OPERATOR_FINISHED;
2351
2352         return OPERATOR_RUNNING_MODAL;
2353 }
2354
2355 static int image_record_composite_modal(bContext *C, wmOperator *op, wmEvent *event)
2356 {
2357         RecordCompositeData *rcd = op->customdata;
2358
2359         switch (event->type) {
2360                 case TIMER:
2361                         if (rcd->timer == event->customdata) {
2362                                 if (!image_record_composite_apply(C, op)) {
2363                                         image_record_composite_exit(C, op);
2364                                         return OPERATOR_FINISHED;
2365                                 }
2366                         }
2367                         break;
2368                 case ESCKEY:
2369                         image_record_composite_exit(C, op);
2370                         return OPERATOR_FINISHED;
2371         }
2372
2373         return OPERATOR_RUNNING_MODAL;
2374 }
2375
2376 static int image_record_composite_cancel(bContext *C, wmOperator *op)
2377 {
2378         image_record_composite_exit(C, op);
2379         return OPERATOR_CANCELLED;
2380 }
2381
2382 void IMAGE_OT_record_composite(wmOperatorType *ot)
2383 {
2384         /* identifiers */
2385         ot->name = "Record Composite";
2386         ot->idname = "IMAGE_OT_record_composite";
2387         
2388         /* api callbacks */
2389         ot->exec = image_record_composite_exec;
2390         ot->invoke = image_record_composite_invoke;
2391         ot->modal = image_record_composite_modal;
2392         ot->cancel = image_record_composite_cancel;
2393         ot->poll = space_image_buffer_exists_poll;
2394 }
2395
2396 /********************* cycle render slot operator *********************/
2397
2398 static int image_cycle_render_slot_poll(bContext *C)
2399 {
2400         Image *ima = CTX_data_edit_image(C);
2401
2402         return (ima && ima->type == IMA_TYPE_R_RESULT);
2403 }
2404
2405 static int image_cycle_render_slot_exec(bContext *C, wmOperator *op)
2406 {
2407         Image *ima = CTX_data_edit_image(C);
2408         int a, slot, cur = ima->render_slot;
2409         const short use_reverse = RNA_boolean_get(op->ptr, "reverse");
2410
2411         for (a = 1; a < IMA_MAX_RENDER_SLOT; a++) {
2412                 slot = (cur + (use_reverse ? -a : a)) % IMA_MAX_RENDER_SLOT;
2413                 if (slot < 0) slot += IMA_MAX_RENDER_SLOT;
2414
2415                 if (ima->renders[slot] || slot == ima->last_render_slot) {
2416                         ima->render_slot = slot;
2417                         break;
2418                 }
2419         }
2420
2421         if (a == IMA_MAX_RENDER_SLOT)
2422                 ima->render_slot = ((cur == 1) ? 0 : 1);
2423         
2424         WM_event_add_notifier(C, NC_IMAGE | ND_DRAW, NULL);
2425
2426         /* no undo push for browsing existing */
2427         if (ima->renders[ima->render_slot] || ima->render_slot == ima->last_render_slot)
2428                 return OPERATOR_CANCELLED;
2429         
2430         return OPERATOR_FINISHED;
2431 }
2432
2433 void IMAGE_OT_cycle_render_slot(wmOperatorType *ot)
2434 {
2435         /* identifiers */
2436         ot->name = "Cycle Render Slot";
2437         ot->idname = "IMAGE_OT_cycle_render_slot";
2438         ot->description = "Cycle through all non-void render slots";
2439         
2440         /* api callbacks */
2441         ot->exec = image_cycle_render_slot_exec;
2442         ot->poll = image_cycle_render_slot_poll;
2443
2444         /* flags */
2445         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2446
2447         RNA_def_boolean(ot->srna, "reverse", 0, "Cycle in Reverse", "");
2448 }
2449
2450 /******************** TODO ********************/
2451
2452 /* XXX notifier? */
2453
2454 /* goes over all ImageUsers, and sets frame numbers if auto-refresh is set */
2455
2456 static void image_update_frame(struct Image *UNUSED(ima), struct ImageUser *iuser, void *customdata)
2457 {
2458         int cfra = *(int*)customdata;
2459
2460         BKE_image_user_check_frame_calc(iuser, cfra, 0);
2461 }
2462
2463 void ED_image_update_frame(const Main *mainp, int cfra)
2464 {
2465         BKE_image_walk_all_users(mainp, &cfra, image_update_frame);
2466 }
2467