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