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