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