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