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