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