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