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