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