Corrected View Selected operator for image editor so now it works
[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_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 /********************** view all operator *********************/
441
442 /* Updates the fields of the View2D member of the SpaceImage struct.
443  * Default behavior is to reset the position of the image and set the zoom to 1
444  * If the image will not fit within the window rectangle, the zoom is adjusted */
445
446 static int view_all_exec(bContext *C, wmOperator *UNUSED(op))
447 {
448         SpaceImage *sima;
449         ARegion *ar;
450         float aspx, aspy, zoomx, zoomy, w, h;
451         int width, height;
452
453         /* retrieve state */
454         sima= CTX_wm_space_image(C);
455         ar= CTX_wm_region(C);
456
457         ED_space_image_size(sima, &width, &height);
458         ED_space_image_aspect(sima, &aspx, &aspy);
459
460         w= width*aspx;
461         h= height*aspy;
462         
463         /* check if the image will fit in the image with zoom==1 */
464         width = ar->winrct.xmax - ar->winrct.xmin + 1;
465         height = ar->winrct.ymax - ar->winrct.ymin + 1;
466
467         if((w >= width || h >= height) && (width > 0 && height > 0)) {
468                 /* find the zoom value that will fit the image in the image space */
469                 zoomx= width/w;
470                 zoomy= height/h;
471                 sima_zoom_set(sima, ar, 1.0f/power_of_2(1/MIN2(zoomx, zoomy)));
472         }
473         else
474                 sima_zoom_set(sima, ar, 1.0f);
475
476         sima->xof= sima->yof= 0.0f;
477
478         ED_region_tag_redraw(CTX_wm_region(C));
479         
480         return OPERATOR_FINISHED;
481 }
482
483 void IMAGE_OT_view_all(wmOperatorType *ot)
484 {
485         /* identifiers */
486         ot->name= "View All";
487         ot->idname= "IMAGE_OT_view_all";
488         
489         /* api callbacks */
490         ot->exec= view_all_exec;
491         ot->poll= space_image_main_area_poll;
492 }
493
494 /********************** view selected operator *********************/
495
496 static int view_selected_exec(bContext *C, wmOperator *UNUSED(op))
497 {
498         SpaceImage *sima;
499         ARegion *ar;
500         Scene *scene;
501         Object *obedit;
502         Image *ima;
503         float size, min[2], max[2], d[2], aspx, aspy;
504         int width, height;
505
506         /* retrieve state */
507         sima= CTX_wm_space_image(C);
508         ar= CTX_wm_region(C);
509         scene= (Scene*)CTX_data_scene(C);
510         obedit= CTX_data_edit_object(C);
511
512         ima= ED_space_image(sima);
513         ED_space_image_size(sima, &width, &height);
514         ED_image_aspect(ima, &aspx, &aspy);
515
516         width= width*aspx;
517         height= height*aspy;
518
519         /* get bounds */
520         if(!ED_uvedit_minmax(scene, ima, obedit, min, max))
521                 return OPERATOR_CANCELLED;
522
523         /* adjust offset and zoom */
524         sima->xof= (int)(((min[0] + max[0])*0.5f - 0.5f)*width);
525         sima->yof= (int)(((min[1] + max[1])*0.5f - 0.5f)*height);
526
527         d[0]= max[0] - min[0];
528         d[1]= max[1] - min[1];
529         size= 0.5f*MAX2(d[0], d[1])*MAX2(width, height)/256.0f;
530         
531         if(size<=0.01f) size= 0.01f;
532         sima_zoom_set(sima, ar, 0.7f/size);
533
534         ED_region_tag_redraw(CTX_wm_region(C));
535         
536         return OPERATOR_FINISHED;
537 }
538
539 static int view_selected_poll(bContext *C)
540 {
541         return (space_image_main_area_poll(C) && ED_operator_uvedit(C));
542 }
543
544 void IMAGE_OT_view_selected(wmOperatorType *ot)
545 {
546         /* identifiers */
547         ot->name= "View Center";
548         ot->idname= "IMAGE_OT_view_selected";
549         
550         /* api callbacks */
551         ot->exec= view_selected_exec;
552         ot->poll= view_selected_poll;
553 }
554
555 /********************** view zoom in/out operator *********************/
556
557 static int view_zoom_in_exec(bContext *C, wmOperator *UNUSED(op))
558 {
559         SpaceImage *sima= CTX_wm_space_image(C);
560         ARegion *ar= CTX_wm_region(C);
561
562         sima_zoom_set_factor(sima, ar, 1.25f);
563
564         ED_region_tag_redraw(CTX_wm_region(C));
565         
566         return OPERATOR_FINISHED;
567 }
568
569 void IMAGE_OT_view_zoom_in(wmOperatorType *ot)
570 {
571         /* identifiers */
572         ot->name= "View Zoom In";
573         ot->idname= "IMAGE_OT_view_zoom_in";
574         
575         /* api callbacks */
576         ot->exec= view_zoom_in_exec;
577         ot->poll= space_image_main_area_poll;
578 }
579
580 static int view_zoom_out_exec(bContext *C, wmOperator *UNUSED(op))
581 {
582         SpaceImage *sima= CTX_wm_space_image(C);
583         ARegion *ar= CTX_wm_region(C);
584
585         sima_zoom_set_factor(sima, ar, 0.8f);
586
587         ED_region_tag_redraw(CTX_wm_region(C));
588         
589         return OPERATOR_FINISHED;
590 }
591
592 void IMAGE_OT_view_zoom_out(wmOperatorType *ot)
593 {
594         /* identifiers */
595         ot->name= "View Zoom Out";
596         ot->idname= "IMAGE_OT_view_zoom_out";
597         
598         /* api callbacks */
599         ot->exec= view_zoom_out_exec;
600         ot->poll= space_image_main_area_poll;
601 }
602
603 /********************** view zoom ratio operator *********************/
604
605 static int view_zoom_ratio_exec(bContext *C, wmOperator *op)
606 {
607         SpaceImage *sima= CTX_wm_space_image(C);
608         ARegion *ar= CTX_wm_region(C);
609
610         sima_zoom_set(sima, ar, RNA_float_get(op->ptr, "ratio"));
611         
612         /* ensure pixel exact locations for draw */
613         sima->xof= (int)sima->xof;
614         sima->yof= (int)sima->yof;
615
616         /* XXX notifier? */
617 #if 0
618         if(image_preview_active(curarea, NULL, NULL)) {
619                 /* recalculates new preview rect */
620                 scrarea_do_windraw(curarea);
621                 image_preview_event(2);
622         }
623 #endif
624
625         ED_region_tag_redraw(CTX_wm_region(C));
626         
627         return OPERATOR_FINISHED;
628 }
629
630 void IMAGE_OT_view_zoom_ratio(wmOperatorType *ot)
631 {
632         /* identifiers */
633         ot->name= "View Zoom Ratio";
634         ot->idname= "IMAGE_OT_view_zoom_ratio";
635         
636         /* api callbacks */
637         ot->exec= view_zoom_ratio_exec;
638         ot->poll= space_image_main_area_poll;
639         
640         /* properties */
641         RNA_def_float(ot->srna, "ratio", 0.0f, 0.0f, FLT_MAX,
642                 "Ratio", "Zoom ratio, 1.0 is 1:1, higher is zoomed in, lower is zoomed out.", -FLT_MAX, FLT_MAX);
643 }
644
645 /**************** load/replace/save callbacks ******************/
646
647 /* XXX make dynamic */
648 static const EnumPropertyItem image_file_type_items[] = {
649                 {R_TARGA, "TARGA", 0, "Targa", ""},
650                 {R_RAWTGA, "TARGA RAW", 0, "Targa Raw", ""},
651                 {R_PNG, "PNG", 0, "PNG", ""},
652 #ifdef WITH_DDS
653                 {R_DDS, "DDS", 0, "DirectDraw Surface", ""},
654 #endif
655                 {R_BMP, "BMP", 0, "BMP", ""},
656                 {R_JPEG90, "JPEG", 0, "Jpeg", ""},
657 #ifdef WITH_OPENJPEG
658                 {R_JP2, "JPEG_2000", 0, "Jpeg 2000", ""},
659 #endif
660                 {R_IRIS, "IRIS", 0, "Iris", ""},
661 #ifdef WITH_TIFF
662                 {R_TIFF, "TIFF", 0, "Tiff", ""},
663 #endif
664 #ifdef WITH_DDS
665                 {R_RADHDR, "RADIANCE_HDR", 0, "Radiance HDR", ""},
666 #endif
667 #ifdef WITH_CINEON
668                 {R_CINEON, "CINEON", 0, "Cineon", ""},
669                 {R_DPX, "DPX", 0, "DPX", ""},
670 #endif
671 #ifdef WITH_OPENEXR
672                 {R_OPENEXR, "OPENEXR", 0, "OpenEXR", ""},
673         /* saving sequences of multilayer won't work, they copy buffers  */
674         /*if(ima->source==IMA_SRC_SEQUENCE && ima->type==IMA_TYPE_MULTILAYER);
675         else*/
676                 {R_MULTILAYER, "MULTILAYER", 0, "MultiLayer", ""},
677 #endif  
678                 {0, NULL, 0, NULL, NULL}};
679
680 static void image_filesel(bContext *C, wmOperator *op, const char *path)
681 {
682         RNA_string_set(op->ptr, "filepath", path);
683         WM_event_add_fileselect(C, op); 
684 }
685
686 /******************** open image operator ********************/
687
688 static void open_init(bContext *C, wmOperator *op)
689 {
690         PropertyPointerRNA *pprop;
691
692         op->customdata= pprop= MEM_callocN(sizeof(PropertyPointerRNA), "OpenPropertyPointerRNA");
693         uiIDContextProperty(C, &pprop->ptr, &pprop->prop);
694 }
695
696 static int open_cancel(bContext *UNUSED(C), wmOperator *op)
697 {
698         MEM_freeN(op->customdata);
699         op->customdata= NULL;
700         return OPERATOR_CANCELLED;
701 }
702
703 static int open_exec(bContext *C, wmOperator *op)
704 {
705         SpaceImage *sima= CTX_wm_space_image(C); /* XXX other space types can call */
706         Scene *scene= CTX_data_scene(C);
707         Object *obedit= CTX_data_edit_object(C);
708         ImageUser *iuser= NULL;
709         PropertyPointerRNA *pprop;
710         PointerRNA idptr;
711         Image *ima= NULL;
712         char str[FILE_MAX];
713
714         RNA_string_get(op->ptr, "filepath", str);
715         /* default to frame 1 if there's no scene in context */
716
717         errno= 0;
718
719         ima= BKE_add_image_file(str);
720
721         if(!ima) {
722                 if(op->customdata) MEM_freeN(op->customdata);
723                 BKE_reportf(op->reports, RPT_ERROR, "Can't read: \"%s\", %s.", str, errno ? strerror(errno) : "Unsupported image format");
724                 return OPERATOR_CANCELLED;
725         }
726         
727         if(!op->customdata)
728                 open_init(C, op);
729
730         /* hook into UI */
731         pprop= op->customdata;
732
733         if(pprop->prop) {
734                 /* when creating new ID blocks, use is already 1, but RNA
735                  * pointer se also increases user, so this compensates it */
736                 ima->id.us--;
737
738                 RNA_id_pointer_create(&ima->id, &idptr);
739                 RNA_property_pointer_set(&pprop->ptr, pprop->prop, idptr);
740                 RNA_property_update(C, &pprop->ptr, pprop->prop);
741         }
742         else if(sima) {
743                 ED_space_image_set(C, sima, scene, obedit, ima);
744                 iuser= &sima->iuser;
745         }
746         else {
747                 Tex *tex= CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
748                 if(tex && tex->type==TEX_IMAGE)
749                         iuser= &tex->iuser;
750                 
751         }
752         
753         /* initialize because of new image */
754         if(iuser) {
755                 iuser->sfra= 1;
756                 iuser->offset= 0;
757                 iuser->fie_ima= 2;
758         }
759
760         /* XXX unpackImage frees image buffers */
761         ED_preview_kill_jobs(C);
762         
763         BKE_image_signal(ima, iuser, IMA_SIGNAL_RELOAD);
764         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
765         
766         MEM_freeN(op->customdata);
767
768         return OPERATOR_FINISHED;
769 }
770
771 static int open_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
772 {
773         SpaceImage *sima= CTX_wm_space_image(C); /* XXX other space types can call */
774         char *path=U.textudir;
775         Image *ima= NULL;
776
777         if(sima) {
778                 ima= sima->image;
779         }
780
781         if (ima==NULL) {
782                 Tex *tex= CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
783                 if(tex && tex->type==TEX_IMAGE)
784                         ima= tex->ima;
785         }
786
787         if(ima)
788                 path= ima->name;
789         
790
791         if(!RNA_property_is_set(op->ptr, "relative_path"))
792                 RNA_boolean_set(op->ptr, "relative_path", U.flag & USER_RELPATHS);
793
794         if(RNA_property_is_set(op->ptr, "filepath"))
795                 return open_exec(C, op);
796         
797         open_init(C, op);
798
799         image_filesel(C, op, path);
800
801         return OPERATOR_RUNNING_MODAL;
802 }
803
804 /* called by other space types too */
805 void IMAGE_OT_open(wmOperatorType *ot)
806 {
807         /* identifiers */
808         ot->name= "Open Image";
809         ot->description= "Open image";
810         ot->idname= "IMAGE_OT_open";
811         
812         /* api callbacks */
813         ot->exec= open_exec;
814         ot->invoke= open_invoke;
815         ot->cancel= open_cancel;
816
817         /* flags */
818         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
819
820         /* properties */
821         WM_operator_properties_filesel(ot, FOLDERFILE|IMAGEFILE|MOVIEFILE, FILE_SPECIAL, FILE_OPENFILE, WM_FILESEL_FILEPATH|WM_FILESEL_RELPATH);
822 }
823
824 /******************** replace image operator ********************/
825
826 static int replace_exec(bContext *C, wmOperator *op)
827 {
828         SpaceImage *sima= CTX_wm_space_image(C);
829         char str[FILE_MAX];
830
831         if(!sima->image)
832                 return OPERATOR_CANCELLED;
833         
834         RNA_string_get(op->ptr, "filepath", str);
835         BLI_strncpy(sima->image->name, str, sizeof(sima->image->name)); /* we cant do much if the str is longer then 240 :/ */
836
837         /* XXX unpackImage frees image buffers */
838         ED_preview_kill_jobs(C);
839         
840         BKE_image_signal(sima->image, &sima->iuser, IMA_SIGNAL_RELOAD);
841         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, sima->image);
842
843         return OPERATOR_FINISHED;
844 }
845
846 static int replace_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
847 {
848         SpaceImage *sima= CTX_wm_space_image(C);
849
850         if(!sima->image)
851                 return OPERATOR_CANCELLED;
852
853         if(RNA_property_is_set(op->ptr, "filepath"))
854                 return replace_exec(C, op);
855
856         if(!RNA_property_is_set(op->ptr, "relative_path"))
857                 RNA_boolean_set(op->ptr, "relative_path", (strncmp(sima->image->name, "//", 2))==0);
858
859         image_filesel(C, op, sima->image->name);
860
861         return OPERATOR_RUNNING_MODAL;
862 }
863
864 void IMAGE_OT_replace(wmOperatorType *ot)
865 {
866         /* identifiers */
867         ot->name= "Replace Image";
868         ot->idname= "IMAGE_OT_replace";
869         
870         /* api callbacks */
871         ot->exec= replace_exec;
872         ot->invoke= replace_invoke;
873         ot->poll= space_image_poll;
874
875         /* flags */
876         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
877
878         /* properties */
879         WM_operator_properties_filesel(ot, FOLDERFILE|IMAGEFILE|MOVIEFILE, FILE_SPECIAL, FILE_OPENFILE, WM_FILESEL_FILEPATH|WM_FILESEL_RELPATH);
880 }
881
882 /******************** save image as operator ********************/
883
884 /* assumes name is FILE_MAX */
885 /* ima->name and ibuf->name should end up the same */
886 static void save_image_doit(bContext *C, SpaceImage *sima, Scene *scene, wmOperator *op, char *path, int do_newpath)
887 {
888         Image *ima= ED_space_image(sima);
889         void *lock;
890         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
891
892         if (ibuf) {
893                 Main *bmain= CTX_data_main(C);
894                 const short relative= (RNA_struct_find_property(op->ptr, "relative_path") && RNA_boolean_get(op->ptr, "relative_path"));
895                 const short save_copy= (RNA_struct_find_property(op->ptr, "copy") && RNA_boolean_get(op->ptr, "copy"));
896                 short ok= FALSE;
897
898                 BLI_path_abs(path, bmain->name);
899                 /* old global to ensure a 2nd save goes to same dir */
900                 BLI_strncpy(G.ima, path, sizeof(G.ima));
901
902                 WM_cursor_wait(1);
903
904                 if(ima->type == IMA_TYPE_R_RESULT) {
905                         /* enforce user setting for RGB or RGBA, but skip BW */
906                         if(scene->r.planes==32) {
907                                 ibuf->depth= 32;
908                         }
909                         else if(scene->r.planes==24) {
910                                 ibuf->depth= 24;
911                         }
912                 }
913                 else {
914                         /* TODO, better solution, if a 24bit image is painted onto it may contain alpha */
915                         if(ibuf->userflags & IB_BITMAPDIRTY) { /* it has been painted onto */
916                                 /* checks each pixel, not ideal */
917                                 ibuf->depth= BKE_alphatest_ibuf(ibuf) ? 32 : 24;
918                         }
919                 }
920
921                 if(scene->r.scemode & R_EXTENSION)  {
922                         BKE_add_image_extension(path, sima->imtypenr);
923                 }
924                 
925                 if(sima->imtypenr==R_MULTILAYER) {
926                         RenderResult *rr= BKE_image_acquire_renderresult(scene, ima);
927                         if(rr) {
928                                 RE_WriteRenderResult(rr, path, scene->r.quality);
929                                 ok= TRUE;
930                         }
931                         else {
932                                 BKE_report(op->reports, RPT_ERROR, "Did not write, no Multilayer Image");
933                         }
934                         BKE_image_release_renderresult(scene, ima);
935                 }
936                 else if (BKE_write_ibuf(ibuf, path, sima->imtypenr, scene->r.subimtype, scene->r.quality)) {
937                         ok= TRUE;
938                 }
939
940                 if(ok)  {
941                         if(relative)
942                                 BLI_path_rel(path, bmain->name); /* only after saving */
943
944                         if(ibuf->name[0]==0) {
945                                 BLI_strncpy(ibuf->name, path, sizeof(ibuf->name));
946                                 BLI_strncpy(ima->name, path, sizeof(ima->name));
947                         }
948
949                         if(!save_copy) {
950                                 if(do_newpath) {
951                                         BLI_strncpy(ima->name, path, sizeof(ima->name));
952                                         BLI_strncpy(ibuf->name, path, sizeof(ibuf->name));
953                                 }
954
955                                 ibuf->userflags &= ~IB_BITMAPDIRTY;
956
957                                 /* change type? */
958                                 if(ima->type==IMA_TYPE_R_RESULT) {
959                                         ima->type= IMA_TYPE_IMAGE;
960
961                                         /* workaround to ensure the render result buffer is no longer used
962                                          * by this image, otherwise can crash when a new render result is
963                                          * created. */
964                                         if(ibuf->rect && !(ibuf->mall & IB_rect))
965                                                 imb_freerectImBuf(ibuf);
966                                         if(ibuf->rect_float && !(ibuf->mall & IB_rectfloat))
967                                                 imb_freerectfloatImBuf(ibuf);
968                                         if(ibuf->zbuf && !(ibuf->mall & IB_zbuf))
969                                                 IMB_freezbufImBuf(ibuf);
970                                         if(ibuf->zbuf_float && !(ibuf->mall & IB_zbuffloat))
971                                                 IMB_freezbuffloatImBuf(ibuf);
972                                 }
973                                 if( ELEM(ima->source, IMA_SRC_GENERATED, IMA_SRC_VIEWER)) {
974                                         ima->source= IMA_SRC_FILE;
975                                         ima->type= IMA_TYPE_IMAGE;
976                                 }
977                         }
978                 }
979                 else {
980                         BKE_reportf(op->reports, RPT_ERROR, "Couldn't write image: %s", path);
981                 }
982
983
984                 WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, sima->image);
985
986                 WM_cursor_wait(0);
987         }
988
989         ED_space_image_release_buffer(sima, lock);
990 }
991
992 static int save_as_exec(bContext *C, wmOperator *op)
993 {
994         SpaceImage *sima= CTX_wm_space_image(C);
995         Scene *scene= CTX_data_scene(C);
996         Image *ima = ED_space_image(sima);
997         char str[FILE_MAX];
998
999         if(!ima)
1000                 return OPERATOR_CANCELLED;
1001
1002         sima->imtypenr= RNA_enum_get(op->ptr, "file_type");
1003         RNA_string_get(op->ptr, "filepath", str);
1004
1005         save_image_doit(C, sima, scene, op, str, TRUE);
1006
1007         return OPERATOR_FINISHED;
1008 }
1009
1010
1011 static int save_as_check(bContext *UNUSED(C), wmOperator *op)
1012 {
1013         char filepath[FILE_MAX];
1014         RNA_string_get(op->ptr, "filepath", filepath);
1015         if(BKE_add_image_extension(filepath, RNA_enum_get(op->ptr, "file_type"))) {
1016                 RNA_string_set(op->ptr, "filepath", filepath);
1017                 return TRUE;
1018         }
1019         return FALSE;
1020 }
1021
1022 static int save_as_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1023 {
1024         SpaceImage *sima= CTX_wm_space_image(C);
1025         Image *ima = ED_space_image(sima);
1026         Scene *scene= CTX_data_scene(C);
1027         ImBuf *ibuf;
1028         char filename[FILE_MAX];
1029         
1030         void *lock;
1031
1032         if(!RNA_property_is_set(op->ptr, "relative_path"))
1033                 RNA_boolean_set(op->ptr, "relative_path", U.flag & USER_RELPATHS);
1034
1035         if(RNA_property_is_set(op->ptr, "filepath"))
1036                 return save_as_exec(C, op);
1037         
1038         if(!ima)
1039                 return OPERATOR_CANCELLED;
1040
1041         /* always opens fileselect */
1042         ibuf= ED_space_image_acquire_buffer(sima, &lock);
1043
1044         if(ibuf) {
1045                 /* cant save multilayer sequence, ima->rr isn't valid for a specific frame */
1046                 if(ima->rr && !(ima->source==IMA_SRC_SEQUENCE && ima->type==IMA_TYPE_MULTILAYER))
1047                         sima->imtypenr= R_MULTILAYER;
1048                 else if(ima->type==IMA_TYPE_R_RESULT)
1049                         sima->imtypenr= scene->r.imtype;
1050                 else if (ima->source == IMA_SRC_GENERATED)
1051                         sima->imtypenr= R_PNG;
1052                 else
1053                         sima->imtypenr= BKE_ftype_to_imtype(ibuf->ftype);
1054
1055                 RNA_enum_set(op->ptr, "file_type", sima->imtypenr);
1056                 
1057                 if(ibuf->name[0]==0)
1058                         if ( (G.ima[0] == '/') && (G.ima[1] == '/') && (G.ima[2] == '\0') ) {
1059                                 BLI_strncpy(filename, "//untitled", FILE_MAX);
1060                         } else {
1061                                 BLI_strncpy(filename, G.ima, FILE_MAX);
1062                         }
1063                 else
1064                         BLI_strncpy(filename, ibuf->name, FILE_MAX);
1065                 
1066                 /* enable save_copy by default for render results */
1067                 if(ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE) && !RNA_property_is_set(op->ptr, "copy")) {
1068                         RNA_boolean_set(op->ptr, "copy", TRUE);
1069                 }
1070
1071                 // XXX note: we can give default menu enums to operator for this 
1072                 image_filesel(C, op, filename);
1073
1074                 ED_space_image_release_buffer(sima, lock);
1075                 
1076                 return OPERATOR_RUNNING_MODAL;
1077         }
1078
1079         ED_space_image_release_buffer(sima, lock);
1080
1081         return OPERATOR_CANCELLED;
1082 }
1083
1084 void IMAGE_OT_save_as(wmOperatorType *ot)
1085 {
1086         /* identifiers */
1087         ot->name= "Save As Image";
1088         ot->idname= "IMAGE_OT_save_as";
1089         
1090         /* api callbacks */
1091         ot->exec= save_as_exec;
1092         ot->check= save_as_check;
1093         ot->invoke= save_as_invoke;
1094         ot->poll= space_image_buffer_exists_poll;
1095
1096         /* flags */
1097         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1098
1099         /* properties */
1100         RNA_def_enum(ot->srna, "file_type", image_file_type_items, R_PNG, "File Type", "File type to save image as.");
1101         WM_operator_properties_filesel(ot, FOLDERFILE|IMAGEFILE|MOVIEFILE, FILE_SPECIAL, FILE_SAVE, WM_FILESEL_FILEPATH|WM_FILESEL_RELPATH);
1102
1103         RNA_def_boolean(ot->srna, "copy", 0, "Copy", "Create a new image file without modifying the current image in blender");
1104 }
1105
1106 /******************** save image operator ********************/
1107
1108 static int save_exec(bContext *C, wmOperator *op)
1109 {
1110         Main *bmain= CTX_data_main(C);
1111         SpaceImage *sima= CTX_wm_space_image(C);
1112         Image *ima = ED_space_image(sima);
1113         void *lock;
1114         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
1115         Scene *scene= CTX_data_scene(C);
1116         RenderResult *rr;
1117         char name[FILE_MAX];
1118
1119         if(!ima || !ibuf) {
1120                 ED_space_image_release_buffer(sima, lock);
1121                 return OPERATOR_CANCELLED;
1122         }
1123
1124         /* if exists, saves over without fileselect */
1125         
1126         BLI_strncpy(name, ima->name, FILE_MAX);
1127         if(name[0]==0)
1128                 BLI_strncpy(name, G.ima, FILE_MAX);
1129         else
1130                 BLI_path_abs(name, bmain->name);
1131         
1132         if(BLI_exists(name) && BLI_is_writable(name)) {
1133                 rr= BKE_image_acquire_renderresult(scene, ima);
1134
1135                 if(rr)
1136                         sima->imtypenr= R_MULTILAYER;
1137                 else 
1138                         sima->imtypenr= BKE_ftype_to_imtype(ibuf->ftype);
1139
1140                 BKE_image_release_renderresult(scene, ima);
1141                 ED_space_image_release_buffer(sima, lock);
1142                 
1143                 save_image_doit(C, sima, scene, op, name, FALSE);
1144         }
1145         else {
1146                 ED_space_image_release_buffer(sima, lock);
1147
1148                 BKE_report(op->reports, RPT_ERROR, "Can not save image.");
1149                 return OPERATOR_CANCELLED;
1150         }
1151
1152         return OPERATOR_FINISHED;
1153 }
1154
1155 void IMAGE_OT_save(wmOperatorType *ot)
1156 {
1157         /* identifiers */
1158         ot->name= "Save Image";
1159         ot->idname= "IMAGE_OT_save";
1160         
1161         /* api callbacks */
1162         ot->exec= save_exec;
1163         ot->poll= space_image_file_exists_poll;
1164
1165         /* flags */
1166         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1167 }
1168
1169 /******************* save sequence operator ********************/
1170
1171 static int save_sequence_exec(bContext *C, wmOperator *op)
1172 {
1173         Main *bmain= CTX_data_main(C);
1174         SpaceImage *sima= CTX_wm_space_image(C);
1175         ImBuf *ibuf;
1176         int tot= 0;
1177         char di[FILE_MAX], fi[FILE_MAX];
1178         
1179         if(sima->image==NULL)
1180                 return OPERATOR_CANCELLED;
1181
1182         if(sima->image->source!=IMA_SRC_SEQUENCE) {
1183                 BKE_report(op->reports, RPT_ERROR, "Can only save sequence on image sequences.");
1184                 return OPERATOR_CANCELLED;
1185         }
1186
1187         if(sima->image->type==IMA_TYPE_MULTILAYER) {
1188                 BKE_report(op->reports, RPT_ERROR, "Can't save multilayer sequences.");
1189                 return OPERATOR_CANCELLED;
1190         }
1191         
1192         /* get total */
1193         for(ibuf= sima->image->ibufs.first; ibuf; ibuf= ibuf->next) 
1194                 if(ibuf->userflags & IB_BITMAPDIRTY)
1195                         tot++;
1196         
1197         if(tot==0) {
1198                 BKE_report(op->reports, RPT_WARNING, "No images have been changed.");
1199                 return OPERATOR_CANCELLED;
1200         }
1201
1202         /* get a filename for menu */
1203         for(ibuf= sima->image->ibufs.first; ibuf; ibuf= ibuf->next) 
1204                 if(ibuf->userflags & IB_BITMAPDIRTY)
1205                         break;
1206         
1207         BLI_strncpy(di, ibuf->name, FILE_MAX);
1208         BLI_splitdirstring(di, fi);
1209         
1210         BKE_reportf(op->reports, RPT_INFO, "%d Image(s) will be saved in %s", tot, di);
1211
1212         for(ibuf= sima->image->ibufs.first; ibuf; ibuf= ibuf->next) {
1213                 if(ibuf->userflags & IB_BITMAPDIRTY) {
1214                         char name[FILE_MAX];
1215                         BLI_strncpy(name, ibuf->name, sizeof(name));
1216                         
1217                         BLI_path_abs(name, bmain->name);
1218
1219                         if(0 == IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat)) {
1220                                 BKE_reportf(op->reports, RPT_ERROR, "Could not write image %s.", name);
1221                                 break;
1222                         }
1223
1224                         BKE_reportf(op->reports, RPT_INFO, "Saved: %s\n", ibuf->name);
1225                         ibuf->userflags &= ~IB_BITMAPDIRTY;
1226                 }
1227         }
1228
1229         return OPERATOR_FINISHED;
1230 }
1231
1232 void IMAGE_OT_save_sequence(wmOperatorType *ot)
1233 {
1234         /* identifiers */
1235         ot->name= "Save Sequence";
1236         ot->idname= "IMAGE_OT_save_sequence";
1237         
1238         /* api callbacks */
1239         ot->exec= save_sequence_exec;
1240         ot->poll= space_image_buffer_exists_poll;
1241
1242         /* flags */
1243         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1244 }
1245
1246 /******************** reload image operator ********************/
1247
1248 static int reload_exec(bContext *C, wmOperator *UNUSED(op))
1249 {
1250         Image *ima= CTX_data_edit_image(C);
1251         SpaceImage *sima= CTX_wm_space_image(C);
1252
1253         if(!ima)
1254                 return OPERATOR_CANCELLED;
1255
1256         /* XXX unpackImage frees image buffers */
1257         ED_preview_kill_jobs(C);
1258         
1259         // XXX other users?
1260         BKE_image_signal(ima, (sima)? &sima->iuser: NULL, IMA_SIGNAL_RELOAD);
1261
1262         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1263         
1264         return OPERATOR_FINISHED;
1265 }
1266
1267 void IMAGE_OT_reload(wmOperatorType *ot)
1268 {
1269         /* identifiers */
1270         ot->name= "Reload Image";
1271         ot->idname= "IMAGE_OT_reload";
1272         
1273         /* api callbacks */
1274         ot->exec= reload_exec;
1275
1276         /* flags */
1277         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1278 }
1279
1280 /********************** new image operator *********************/
1281
1282 static int image_new_exec(bContext *C, wmOperator *op)
1283 {
1284         SpaceImage *sima;
1285         Scene *scene;
1286         Object *obedit;
1287         Image *ima;
1288         PointerRNA ptr, idptr;
1289         PropertyRNA *prop;
1290         char name[MAX_ID_NAME-2];
1291         float color[4];
1292         int width, height, floatbuf, uvtestgrid, alpha;
1293
1294         /* retrieve state */
1295         sima= CTX_wm_space_image(C);
1296         scene= (Scene*)CTX_data_scene(C);
1297         obedit= CTX_data_edit_object(C);
1298
1299         RNA_string_get(op->ptr, "name", name);
1300         width= RNA_int_get(op->ptr, "width");
1301         height= RNA_int_get(op->ptr, "height");
1302         floatbuf= RNA_boolean_get(op->ptr, "float");
1303         uvtestgrid= RNA_boolean_get(op->ptr, "uv_test_grid");
1304         RNA_float_get_array(op->ptr, "color", color);
1305         alpha= RNA_boolean_get(op->ptr, "alpha");
1306         
1307         if (!floatbuf && scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
1308                 linearrgb_to_srgb_v3_v3(color, color);
1309
1310         if(!alpha)
1311                 color[3]= 1.0f;
1312
1313         ima = BKE_add_image_size(width, height, name, alpha ? 32 : 24, floatbuf, uvtestgrid, color);
1314
1315         if(!ima)
1316                 return OPERATOR_CANCELLED;
1317
1318         /* hook into UI */
1319         uiIDContextProperty(C, &ptr, &prop);
1320
1321         if(prop) {
1322                 /* when creating new ID blocks, use is already 1, but RNA
1323                  * pointer se also increases user, so this compensates it */
1324                 ima->id.us--;
1325
1326                 RNA_id_pointer_create(&ima->id, &idptr);
1327                 RNA_property_pointer_set(&ptr, prop, idptr);
1328                 RNA_property_update(C, &ptr, prop);
1329         }
1330         else if(sima)
1331                 ED_space_image_set(C, sima, scene, obedit, ima);
1332
1333         // XXX other users?
1334         BKE_image_signal(ima, (sima)? &sima->iuser: NULL, IMA_SIGNAL_USER_NEW_IMAGE);
1335         
1336         return OPERATOR_FINISHED;
1337 }
1338
1339 /* XXX, Ton is not a fan of OK buttons but using this function to avoid undo/redo bug while in mesh-editmode, - campbell */
1340 static int image_new_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1341 {
1342         return WM_operator_props_dialog_popup(C, op, 300, 100);
1343
1344 }
1345
1346 void IMAGE_OT_new(wmOperatorType *ot)
1347 {
1348         PropertyRNA *prop;
1349         static float default_color[4]= {0.0f, 0.0f, 0.0f, 1.0f};
1350         
1351         /* identifiers */
1352         ot->name= "New Image";
1353         ot->description= "Create a new image";
1354         ot->idname= "IMAGE_OT_new";
1355         
1356         /* api callbacks */
1357         ot->exec= image_new_exec;
1358         ot->invoke= image_new_invoke;
1359         
1360         /* flags */
1361         ot->flag= OPTYPE_UNDO;
1362
1363         /* properties */
1364         RNA_def_string(ot->srna, "name", "untitled", MAX_ID_NAME-2, "Name", "Image datablock name.");
1365         RNA_def_int(ot->srna, "width", 1024, 1, INT_MAX, "Width", "Image width.", 1, 16384);
1366         RNA_def_int(ot->srna, "height", 1024, 1, INT_MAX, "Height", "Image height.", 1, 16384);
1367         prop= RNA_def_float_color(ot->srna, "color", 4, NULL, 0.0f, FLT_MAX, "Color", "Default fill color.", 0.0f, 1.0f);
1368         RNA_def_property_float_array_default(prop, default_color);
1369         RNA_def_boolean(ot->srna, "alpha", 1, "Alpha", "Create an image with an alpha channel.");
1370         RNA_def_boolean(ot->srna, "uv_test_grid", 0, "UV Test Grid", "Fill the image with a grid for UV map testing.");
1371         RNA_def_boolean(ot->srna, "float", 0, "32 bit Float", "Create image with 32 bit floating point bit depth.");
1372 }
1373
1374 /********************* invert operators *********************/
1375
1376 static int image_invert_poll(bContext *C)
1377 {
1378         Image *ima= CTX_data_edit_image(C);
1379         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1380         
1381         if( ibuf != NULL )
1382                 return 1;
1383         return 0;
1384 }
1385
1386 static int image_invert_exec(bContext *C, wmOperator *op)
1387 {
1388         Image *ima= CTX_data_edit_image(C);
1389         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1390
1391         // flags indicate if this channel should be inverted
1392         const short r= RNA_boolean_get(op->ptr, "invert_r");
1393         const short g= RNA_boolean_get(op->ptr, "invert_g");
1394         const short b= RNA_boolean_get(op->ptr, "invert_b");
1395         const short a= RNA_boolean_get(op->ptr, "invert_a");
1396
1397         int i;
1398
1399         if( ibuf == NULL) // TODO: this should actually never happen, but does for render-results -> cleanup
1400                 return OPERATOR_CANCELLED;
1401
1402         /* TODO: make this into an IMB_invert_channels(ibuf,r,g,b,a) method!? */
1403         if (ibuf->rect_float) {
1404                 
1405                 float *fp = (float *) ibuf->rect_float;
1406                 for( i = ibuf->x * ibuf->y; i > 0; i--, fp+=4 ) {
1407                         if( r ) fp[0] = 1.0f - fp[0];
1408                         if( g ) fp[1] = 1.0f - fp[1];
1409                         if( b ) fp[2] = 1.0f - fp[2];
1410                         if( a ) fp[3] = 1.0f - fp[3];
1411                 }
1412
1413                 if(ibuf->rect) {
1414                         IMB_rect_from_float(ibuf);
1415                 }
1416         }
1417         else if(ibuf->rect) {
1418                 
1419                 char *cp = (char *) ibuf->rect;
1420                 for( i = ibuf->x * ibuf->y; i > 0; i--, cp+=4 ) {
1421                         if( r ) cp[0] = 255 - cp[0];
1422                         if( g ) cp[1] = 255 - cp[1];
1423                         if( b ) cp[2] = 255 - cp[2];
1424                         if( a ) cp[3] = 255 - cp[3];
1425                 }
1426         }
1427         else {
1428                 return OPERATOR_CANCELLED;
1429         }
1430
1431         ibuf->userflags |= IB_BITMAPDIRTY;
1432         if(ibuf->mipmap[0])
1433                 ibuf->userflags |= IB_MIPMAP_INVALID;
1434
1435         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1436         return OPERATOR_FINISHED;
1437 }
1438
1439 void IMAGE_OT_invert(wmOperatorType *ot)
1440 {
1441         /* identifiers */
1442         ot->name= "Invert Channels";
1443         ot->idname= "IMAGE_OT_invert";
1444         
1445         /* api callbacks */
1446         ot->exec= image_invert_exec;
1447         ot->poll= image_invert_poll;
1448         
1449         /* properties */
1450         RNA_def_boolean(ot->srna, "invert_r", 0, "Red", "Invert Red Channel");
1451         RNA_def_boolean(ot->srna, "invert_g", 0, "Green", "Invert Green Channel");
1452         RNA_def_boolean(ot->srna, "invert_b", 0, "Blue", "Invert Blue Channel");
1453         RNA_def_boolean(ot->srna, "invert_a", 0, "Alpha", "Invert Alpha Channel");
1454         
1455         /* flags */
1456         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1457 }
1458
1459 /********************* pack operator *********************/
1460
1461 static int pack_test(bContext *C, wmOperator *op)
1462 {
1463         Image *ima= CTX_data_edit_image(C);
1464         int as_png= RNA_boolean_get(op->ptr, "as_png");
1465
1466         if(!ima)
1467                 return 0;
1468         if(!as_png && ima->packedfile)
1469                 return 0;
1470
1471         if(ima->source==IMA_SRC_SEQUENCE || ima->source==IMA_SRC_MOVIE) {
1472                 BKE_report(op->reports, RPT_ERROR, "Packing movies or image sequences not supported.");
1473                 return 0;
1474         }
1475
1476         return 1;
1477 }
1478
1479 static int pack_exec(bContext *C, wmOperator *op)
1480 {
1481         Image *ima= CTX_data_edit_image(C);
1482         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1483         int as_png= RNA_boolean_get(op->ptr, "as_png");
1484
1485         if(!pack_test(C, op))
1486                 return OPERATOR_CANCELLED;
1487         
1488         if(!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1489                 BKE_report(op->reports, RPT_ERROR, "Can't pack edited image from disk, only as internal PNG.");
1490                 return OPERATOR_CANCELLED;
1491         }
1492
1493         if(as_png)
1494                 BKE_image_memorypack(ima);
1495         else
1496                 ima->packedfile= newPackedFile(op->reports, ima->name);
1497
1498         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1499         
1500         return OPERATOR_FINISHED;
1501 }
1502
1503 static int pack_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1504 {
1505         Image *ima= CTX_data_edit_image(C);
1506         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1507         uiPopupMenu *pup;
1508         uiLayout *layout;
1509         int as_png= RNA_boolean_get(op->ptr, "as_png");
1510
1511         if(!pack_test(C, op))
1512                 return OPERATOR_CANCELLED;
1513         
1514         if(!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1515                 pup= uiPupMenuBegin(C, "OK", ICON_QUESTION);
1516                 layout= uiPupMenuLayout(pup);
1517                 uiItemBooleanO(layout, "Can't pack edited image from disk. Pack as internal PNG?", ICON_NONE, op->idname, "as_png", 1);
1518                 uiPupMenuEnd(C, pup);
1519
1520                 return OPERATOR_CANCELLED;
1521         }
1522
1523         return pack_exec(C, op);
1524 }
1525
1526 void IMAGE_OT_pack(wmOperatorType *ot)
1527 {
1528         /* identifiers */
1529         ot->name= "Pack Image";
1530         ot->description= "Pack an image as embedded data into the .blend file"; 
1531         ot->idname= "IMAGE_OT_pack";
1532         
1533         /* api callbacks */
1534         ot->exec= pack_exec;
1535         ot->invoke= pack_invoke;
1536
1537         /* flags */
1538         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1539
1540         /* properties */
1541         RNA_def_boolean(ot->srna, "as_png", 0, "Pack As PNG", "Pack image as lossless PNG.");
1542 }
1543
1544 /********************* unpack operator *********************/
1545
1546 static int image_unpack_exec(bContext *C, wmOperator *op)
1547 {
1548         Image *ima= CTX_data_edit_image(C);
1549         int method= RNA_enum_get(op->ptr, "method");
1550
1551         /* find the suppplied image by name */
1552         if (RNA_property_is_set(op->ptr, "id")) {
1553                 char imaname[MAX_ID_NAME-2];
1554                 RNA_string_get(op->ptr, "id", imaname);
1555                 ima = BLI_findstring(&CTX_data_main(C)->image, imaname, offsetof(ID, name) + 2);
1556                 if (!ima) ima = CTX_data_edit_image(C);
1557         }
1558         
1559         if(!ima || !ima->packedfile)
1560                 return OPERATOR_CANCELLED;
1561
1562         if(ima->source==IMA_SRC_SEQUENCE || ima->source==IMA_SRC_MOVIE) {
1563                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported.");
1564                 return OPERATOR_CANCELLED;
1565         }
1566
1567         if(G.fileflags & G_AUTOPACK)
1568                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save.");
1569         
1570         /* XXX unpackImage frees image buffers */
1571         ED_preview_kill_jobs(C);
1572         
1573         unpackImage(op->reports, ima, method);
1574         
1575         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1576
1577         return OPERATOR_FINISHED;
1578 }
1579
1580 static int image_unpack_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1581 {
1582         Image *ima= CTX_data_edit_image(C);
1583
1584         if(RNA_property_is_set(op->ptr, "id"))
1585                 return image_unpack_exec(C, op);
1586                 
1587         if(!ima || !ima->packedfile)
1588                 return OPERATOR_CANCELLED;
1589
1590         if(ima->source==IMA_SRC_SEQUENCE || ima->source==IMA_SRC_MOVIE) {
1591                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported.");
1592                 return OPERATOR_CANCELLED;
1593         }
1594
1595         if(G.fileflags & G_AUTOPACK)
1596                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save.");
1597
1598         unpack_menu(C, "IMAGE_OT_unpack", ima->id.name+2, ima->name, "textures", ima->packedfile);
1599
1600         return OPERATOR_FINISHED;
1601 }
1602
1603 void IMAGE_OT_unpack(wmOperatorType *ot)
1604 {
1605         /* identifiers */
1606         ot->name= "Unpack Image";
1607         ot->description= "Save an image packed in the .blend file to disk"; 
1608         ot->idname= "IMAGE_OT_unpack";
1609         
1610         /* api callbacks */
1611         ot->exec= image_unpack_exec;
1612         ot->invoke= image_unpack_invoke;
1613
1614         /* flags */
1615         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1616         
1617         /* properties */
1618         RNA_def_enum(ot->srna, "method", unpack_method_items, PF_USE_LOCAL, "Method", "How to unpack.");
1619         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 */
1620 }
1621
1622 /******************** sample image operator ********************/
1623
1624 typedef struct ImageSampleInfo {
1625         ARegionType *art;
1626         void *draw_handle;
1627         int x, y;
1628         int channels;
1629
1630         char col[4];
1631         float colf[4];
1632         int z;
1633         float zf;
1634
1635         char *colp;
1636         float *colfp;
1637         int *zp;
1638         float *zfp;
1639
1640         int draw;
1641 } ImageSampleInfo;
1642
1643 static void sample_draw(const bContext *UNUSED(C), ARegion *ar, void *arg_info)
1644 {
1645         ImageSampleInfo *info= arg_info;
1646         if(info->draw) {
1647                 /* no color management needed for images (color_manage=0) */
1648                 draw_image_info(ar, 0, info->channels, info->x, info->y, info->colp, info->colfp, info->zp, info->zfp);
1649         }
1650 }
1651
1652 static void sample_apply(bContext *C, wmOperator *op, wmEvent *event)
1653 {
1654         SpaceImage *sima= CTX_wm_space_image(C);
1655         ARegion *ar= CTX_wm_region(C);
1656         void *lock;
1657         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
1658         ImageSampleInfo *info= op->customdata;
1659         float fx, fy;
1660         
1661         if(ibuf == NULL) {
1662                 ED_space_image_release_buffer(sima, lock);
1663                 return;
1664         }
1665
1666         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &fx, &fy);
1667
1668         if(fx>=0.0f && fy>=0.0f && fx<1.0f && fy<1.0f) {
1669                 float *fp;
1670                 char *cp;
1671                 int x= (int)(fx*ibuf->x), y= (int)(fy*ibuf->y);
1672
1673                 CLAMP(x, 0, ibuf->x-1);
1674                 CLAMP(y, 0, ibuf->y-1);
1675
1676                 info->x= x;
1677                 info->y= y;
1678                 info->draw= 1;
1679                 info->channels= ibuf->channels;
1680
1681                 info->colp= NULL;
1682                 info->colfp= NULL;
1683                 info->zp= NULL;
1684                 info->zfp= NULL;
1685                 
1686                 if(ibuf->rect) {
1687                         cp= (char *)(ibuf->rect + y*ibuf->x + x);
1688
1689                         info->col[0]= cp[0];
1690                         info->col[1]= cp[1];
1691                         info->col[2]= cp[2];
1692                         info->col[3]= cp[3];
1693                         info->colp= info->col;
1694
1695                         info->colf[0]= (float)cp[0]/255.0f;
1696                         info->colf[1]= (float)cp[1]/255.0f;
1697                         info->colf[2]= (float)cp[2]/255.0f;
1698                         info->colf[3]= (float)cp[3]/255.0f;
1699                         info->colfp= info->colf;
1700                 }
1701                 if(ibuf->rect_float) {
1702                         fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
1703
1704                         info->colf[0]= fp[0];
1705                         info->colf[1]= fp[1];
1706                         info->colf[2]= fp[2];
1707                         info->colf[3]= fp[3];
1708                         info->colfp= info->colf;
1709                 }
1710
1711                 if(ibuf->zbuf) {
1712                         info->z= ibuf->zbuf[y*ibuf->x + x];
1713                         info->zp= &info->z;
1714                 }
1715                 if(ibuf->zbuf_float) {
1716                         info->zf= ibuf->zbuf_float[y*ibuf->x + x];
1717                         info->zfp= &info->zf;
1718                 }
1719                 
1720                 if(sima->cumap && ibuf->channels==4) {
1721                         /* we reuse this callback for set curves point operators */
1722                         if(RNA_struct_find_property(op->ptr, "point")) {
1723                                 int point= RNA_enum_get(op->ptr, "point");
1724
1725                                 if(point == 1) {
1726                                         curvemapping_set_black_white(sima->cumap, NULL, info->colfp);
1727                                         if(ibuf->rect_float)
1728                                                 curvemapping_do_ibuf(sima->cumap, ibuf);
1729                                 }
1730                                 else if(point == 0) {
1731                                         curvemapping_set_black_white(sima->cumap, info->colfp, NULL);
1732                                         if(ibuf->rect_float)
1733                                                 curvemapping_do_ibuf(sima->cumap, ibuf);
1734                                 }
1735                         }
1736                 }
1737                                 
1738                 // XXX node curve integration ..
1739 #if 0
1740                 {
1741                         ScrArea *sa, *cur= curarea;
1742                         
1743                         node_curvemap_sample(fp);       /* sends global to node editor */
1744                         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
1745                                 if(sa->spacetype==SPACE_NODE) {
1746                                         areawinset(sa->win);
1747                                         scrarea_do_windraw(sa);
1748                                 }
1749                         }
1750                         node_curvemap_sample(NULL);             /* clears global in node editor */
1751                         curarea= cur;
1752                 }
1753 #endif
1754         }
1755         else
1756                 info->draw= 0;
1757
1758         ED_space_image_release_buffer(sima, lock);
1759         ED_area_tag_redraw(CTX_wm_area(C));
1760 }
1761
1762 static void sample_exit(bContext *C, wmOperator *op)
1763 {
1764         ImageSampleInfo *info= op->customdata;
1765
1766         ED_region_draw_cb_exit(info->art, info->draw_handle);
1767         ED_area_tag_redraw(CTX_wm_area(C));
1768         MEM_freeN(info);
1769 }
1770
1771 static int sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1772 {
1773         SpaceImage *sima= CTX_wm_space_image(C);
1774         ARegion *ar= CTX_wm_region(C);
1775         ImageSampleInfo *info;
1776
1777         if(!ED_space_image_has_buffer(sima))
1778                 return OPERATOR_CANCELLED;
1779         
1780         info= MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
1781         info->art= ar->type;
1782         info->draw_handle = ED_region_draw_cb_activate(ar->type, sample_draw, info, REGION_DRAW_POST_PIXEL);
1783         op->customdata= info;
1784
1785         sample_apply(C, op, event);
1786
1787         WM_event_add_modal_handler(C, op);
1788
1789         return OPERATOR_RUNNING_MODAL;
1790 }
1791
1792 static int sample_modal(bContext *C, wmOperator *op, wmEvent *event)
1793 {
1794         switch(event->type) {
1795                 case LEFTMOUSE:
1796                 case RIGHTMOUSE: // XXX hardcoded
1797                         sample_exit(C, op);
1798                         return OPERATOR_CANCELLED;
1799                 case MOUSEMOVE:
1800                         sample_apply(C, op, event);
1801                         break;
1802         }
1803
1804         return OPERATOR_RUNNING_MODAL;
1805 }
1806
1807 static int sample_cancel(bContext *C, wmOperator *op)
1808 {
1809         sample_exit(C, op);
1810         return OPERATOR_CANCELLED;
1811 }
1812
1813 void IMAGE_OT_sample(wmOperatorType *ot)
1814 {
1815         /* identifiers */
1816         ot->name= "Sample Color";
1817         ot->idname= "IMAGE_OT_sample";
1818         
1819         /* api callbacks */
1820         ot->invoke= sample_invoke;
1821         ot->modal= sample_modal;
1822         ot->cancel= sample_cancel;
1823         ot->poll= space_image_main_area_poll;
1824
1825         /* flags */
1826         ot->flag= OPTYPE_BLOCKING;
1827 }
1828
1829 /******************** sample line operator ********************/
1830 static int sample_line_exec(bContext *C, wmOperator *op)
1831 {
1832         SpaceImage *sima= CTX_wm_space_image(C);
1833         ARegion *ar= CTX_wm_region(C);
1834         Scene *scene= CTX_data_scene(C);
1835         
1836         int x_start= RNA_int_get(op->ptr, "xstart");
1837         int y_start= RNA_int_get(op->ptr, "ystart");
1838         int x_end= RNA_int_get(op->ptr, "xend");
1839         int y_end= RNA_int_get(op->ptr, "yend");
1840         
1841         void *lock;
1842         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
1843         Histogram *hist= &sima->sample_line_hist;
1844         
1845         float x1f, y1f, x2f, y2f;
1846         int x1, y1, x2, y2;
1847         int i, x, y;
1848         float *fp;
1849         float rgb[3];
1850         unsigned char *cp;
1851         
1852         if (ibuf == NULL) {
1853                 ED_space_image_release_buffer(sima, lock);
1854                 return OPERATOR_CANCELLED;
1855         }
1856         /* hmmmm */
1857         if (ibuf->channels < 3) {
1858                 ED_space_image_release_buffer(sima, lock);
1859                 return OPERATOR_CANCELLED;
1860         }
1861         
1862         UI_view2d_region_to_view(&ar->v2d, x_start, y_start, &x1f, &y1f);
1863         UI_view2d_region_to_view(&ar->v2d, x_end, y_end, &x2f, &y2f);
1864         x1= 0.5f+ x1f*ibuf->x;
1865         x2= 0.5f+ x2f*ibuf->x;
1866         y1= 0.5f+ y1f*ibuf->y;
1867         y2= 0.5f+ y2f*ibuf->y;
1868         
1869         hist->channels = 3;
1870         hist->x_resolution = 256;
1871         hist->xmax = 1.0f;
1872         hist->ymax = 1.0f;
1873         
1874         for (i=0; i<256; i++) {
1875                 x= (int)(0.5f + x1 + (float)i*(x2-x1)/255.0f);
1876                 y= (int)(0.5f + y1 + (float)i*(y2-y1)/255.0f);
1877                 
1878                 if (x<0 || y<0 || x>=ibuf->x || y>=ibuf->y) {
1879                         hist->data_luma[i] = hist->data_r[i] = hist->data_g[i]= hist->data_b[i] = 0.0f;
1880                 } else {
1881                         if (ibuf->rect_float) {
1882                                 fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
1883
1884                                 if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
1885                                         linearrgb_to_srgb_v3_v3(rgb, fp);
1886                                 else
1887                                         copy_v3_v3(rgb, fp);
1888
1889                                 hist->data_r[i] = rgb[0];
1890                                 hist->data_g[i] = rgb[1];
1891                                 hist->data_b[i] = rgb[2];
1892                                 hist->data_luma[i] = (0.299f*rgb[0] + 0.587f*rgb[1] + 0.114f*rgb[2]);
1893                         }
1894                         else if (ibuf->rect) {
1895                                 cp= (unsigned char *)(ibuf->rect + y*ibuf->x + x);
1896                                 hist->data_r[i] = (float)cp[0]/255.0f;
1897                                 hist->data_g[i] = (float)cp[1]/255.0f;
1898                                 hist->data_b[i] = (float)cp[2]/255.0f;
1899                                 hist->data_luma[i] = (0.299f*cp[0] + 0.587f*cp[1] + 0.114f*cp[2])/255;
1900                         }
1901                 }
1902         }
1903         
1904         ED_space_image_release_buffer(sima, lock);
1905         
1906         ED_area_tag_redraw(CTX_wm_area(C));
1907         
1908         return OPERATOR_FINISHED;
1909 }
1910
1911 static int sample_line_invoke(bContext *C, wmOperator *op, wmEvent *event)
1912 {
1913         SpaceImage *sima= CTX_wm_space_image(C);
1914         
1915         if(!ED_space_image_has_buffer(sima))
1916                 return OPERATOR_CANCELLED;
1917         
1918         return WM_gesture_straightline_invoke(C, op, event);
1919 }
1920
1921 void IMAGE_OT_sample_line(wmOperatorType *ot)
1922 {
1923         /* identifiers */
1924         ot->name= "Sample Line";
1925         ot->idname= "IMAGE_OT_sample_line";
1926         
1927         /* api callbacks */
1928         ot->invoke= sample_line_invoke;
1929         ot->modal= WM_gesture_straightline_modal;
1930         ot->exec= sample_line_exec;
1931         ot->poll= space_image_main_area_poll;
1932         ot->cancel= WM_gesture_straightline_cancel;
1933         
1934         /* flags */
1935         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1936         
1937         WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT);
1938 }
1939
1940 /******************** set curve point operator ********************/
1941
1942 void IMAGE_OT_curves_point_set(wmOperatorType *ot)
1943 {
1944         static EnumPropertyItem point_items[]= {
1945                 {0, "BLACK_POINT", 0, "Black Point", ""},
1946                 {1, "WHITE_POINT", 0, "White Point", ""},
1947                 {0, NULL, 0, NULL, NULL}};
1948
1949         /* identifiers */
1950         ot->name= "Set Curves Point";
1951         ot->idname= "IMAGE_OT_curves_point_set";
1952
1953         /* flags */
1954         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1955         
1956         /* api callbacks */
1957         ot->invoke= sample_invoke;
1958         ot->modal= sample_modal;
1959         ot->cancel= sample_cancel;
1960         ot->poll= space_image_main_area_poll;
1961
1962         /* properties */
1963         RNA_def_enum(ot->srna, "point", point_items, 0, "Point", "Set black point or white point for curves.");
1964 }
1965
1966 /******************** record composite operator *********************/
1967
1968 typedef struct RecordCompositeData {
1969         wmTimer *timer;
1970         int old_cfra;
1971         int sfra, efra;
1972 } RecordCompositeData;
1973
1974 static int record_composite_apply(bContext *C, wmOperator *op)
1975 {
1976         SpaceImage *sima= CTX_wm_space_image(C);
1977         RecordCompositeData *rcd= op->customdata;
1978         Scene *scene= CTX_data_scene(C);
1979         ImBuf *ibuf;
1980         
1981         WM_timecursor(CTX_wm_window(C), scene->r.cfra);
1982
1983         // XXX scene->nodetree->test_break= blender_test_break;
1984         // XXX scene->nodetree->test_break= NULL;
1985         
1986         BKE_image_all_free_anim_ibufs(scene->r.cfra);
1987         ntreeCompositTagAnimated(scene->nodetree);
1988         ntreeCompositExecTree(scene->nodetree, &scene->r, scene->r.cfra != rcd->old_cfra);      /* 1 is no previews */
1989
1990         ED_area_tag_redraw(CTX_wm_area(C));
1991         
1992         ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
1993         /* save memory in flipbooks */
1994         if(ibuf)
1995                 imb_freerectfloatImBuf(ibuf);
1996         
1997         scene->r.cfra++;
1998
1999         return (scene->r.cfra <= rcd->efra);
2000 }
2001
2002 static int record_composite_init(bContext *C, wmOperator *op)
2003 {
2004         SpaceImage *sima= CTX_wm_space_image(C);
2005         Scene *scene= CTX_data_scene(C);
2006         RecordCompositeData *rcd;
2007
2008         if(sima->iuser.frames < 2)
2009                 return 0;
2010         if(scene->nodetree == NULL)
2011                 return 0;
2012         
2013         op->customdata= rcd= MEM_callocN(sizeof(RecordCompositeData), "ImageRecordCompositeData");
2014
2015         rcd->old_cfra= scene->r.cfra;
2016         rcd->sfra= sima->iuser.sfra;
2017         rcd->efra= sima->iuser.sfra + sima->iuser.frames-1;
2018         scene->r.cfra= rcd->sfra;
2019
2020         return 1;
2021 }
2022
2023 static void record_composite_exit(bContext *C, wmOperator *op)
2024 {
2025         Scene *scene= CTX_data_scene(C);
2026         SpaceImage *sima= CTX_wm_space_image(C);
2027         RecordCompositeData *rcd= op->customdata;
2028
2029         scene->r.cfra= rcd->old_cfra;
2030
2031         WM_cursor_restore(CTX_wm_window(C));
2032
2033         if(rcd->timer)
2034                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rcd->timer);
2035
2036         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, sima->image);
2037
2038         // XXX play_anim(0);
2039         // XXX allqueue(REDRAWNODE, 1);
2040
2041         MEM_freeN(rcd);
2042 }
2043
2044 static int record_composite_exec(bContext *C, wmOperator *op)
2045 {
2046         if(!record_composite_init(C, op))
2047                 return OPERATOR_CANCELLED;
2048         
2049         while(record_composite_apply(C, op))
2050                 ;
2051         
2052         record_composite_exit(C, op);
2053         
2054         return OPERATOR_FINISHED;
2055 }
2056
2057 static int record_composite_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2058 {
2059         RecordCompositeData *rcd;
2060         
2061         if(!record_composite_init(C, op))
2062                 return OPERATOR_CANCELLED;
2063
2064         rcd= op->customdata;
2065         rcd->timer= WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.0f);
2066         WM_event_add_modal_handler(C, op);
2067
2068         if(!record_composite_apply(C, op))
2069                 return OPERATOR_FINISHED;
2070
2071         return OPERATOR_RUNNING_MODAL;
2072 }
2073
2074 static int record_composite_modal(bContext *C, wmOperator *op, wmEvent *event)
2075 {
2076         RecordCompositeData *rcd= op->customdata;
2077
2078         switch(event->type) {
2079                 case TIMER:
2080                         if(rcd->timer == event->customdata) {
2081                                 if(!record_composite_apply(C, op)) {
2082                                         record_composite_exit(C, op);
2083                                         return OPERATOR_FINISHED;
2084                                 }
2085                         }
2086                         break;
2087                 case ESCKEY:
2088                         record_composite_exit(C, op);
2089                         return OPERATOR_FINISHED;
2090         }
2091
2092         return OPERATOR_RUNNING_MODAL;
2093 }
2094
2095 static int record_composite_cancel(bContext *C, wmOperator *op)
2096 {
2097         record_composite_exit(C, op);
2098         return OPERATOR_CANCELLED;
2099 }
2100
2101 void IMAGE_OT_record_composite(wmOperatorType *ot)
2102 {
2103         /* identifiers */
2104         ot->name= "Record Composite";
2105         ot->idname= "IMAGE_OT_record_composite";
2106         
2107         /* api callbacks */
2108         ot->exec= record_composite_exec;
2109         ot->invoke= record_composite_invoke;
2110         ot->modal= record_composite_modal;
2111         ot->cancel= record_composite_cancel;
2112         ot->poll= space_image_buffer_exists_poll;
2113 }
2114
2115 /********************* cycle render slot operator *********************/
2116
2117 static int cycle_render_slot_poll(bContext *C)
2118 {
2119         Image *ima= CTX_data_edit_image(C);
2120
2121         return (ima && ima->type == IMA_TYPE_R_RESULT);
2122 }
2123
2124 static int cycle_render_slot_exec(bContext *C, wmOperator *op)
2125 {
2126         Image *ima= CTX_data_edit_image(C);
2127         int a, slot, cur= ima->render_slot;
2128         const short use_reverse= RNA_boolean_get(op->ptr, "reverse");
2129
2130         for(a=1; a<IMA_MAX_RENDER_SLOT; a++) {
2131                 slot= (cur + (use_reverse ? -a:a))%IMA_MAX_RENDER_SLOT;
2132                 if(slot<0) slot+=IMA_MAX_RENDER_SLOT;
2133
2134                 if(ima->renders[slot] || slot == ima->last_render_slot) {
2135                         ima->render_slot= slot;
2136                         break;
2137                 }
2138                 else if((slot - 1) == ima->last_render_slot && slot < IMA_MAX_RENDER_SLOT) {
2139                         ima->render_slot= slot;
2140                         break;
2141                 }
2142         }
2143
2144         if(a == IMA_MAX_RENDER_SLOT)
2145                 ima->render_slot= ((cur == 1)? 0: 1);
2146         
2147         WM_event_add_notifier(C, NC_IMAGE|ND_DRAW, NULL);
2148
2149         /* no undo push for browsing existing */
2150         if(ima->renders[ima->render_slot] || ima->render_slot==ima->last_render_slot)
2151                 return OPERATOR_CANCELLED;
2152         
2153         return OPERATOR_FINISHED;
2154 }
2155
2156 void IMAGE_OT_cycle_render_slot(wmOperatorType *ot)
2157 {
2158         /* identifiers */
2159         ot->name= "Cycle Render Slot";
2160         ot->idname= "IMAGE_OT_cycle_render_slot";
2161         
2162         /* api callbacks */
2163         ot->exec= cycle_render_slot_exec;
2164         ot->poll= cycle_render_slot_poll;
2165
2166         /* flags */
2167         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2168
2169         RNA_def_boolean(ot->srna, "reverse", 0, "Cycle in Reverse", "");
2170 }
2171
2172 /******************** TODO ********************/
2173
2174 /* XXX notifier? */
2175
2176 /* goes over all ImageUsers, and sets frame numbers if auto-refresh is set */
2177
2178 void ED_image_update_frame(const Main *mainp, int cfra)
2179 {
2180         wmWindowManager *wm;
2181         wmWindow *win;
2182         Tex *tex;
2183         
2184         /* texture users */
2185         for(tex= mainp->tex.first; tex; tex= tex->id.next) {
2186                 if(tex->type==TEX_IMAGE && tex->ima) {
2187                         if(ELEM(tex->ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
2188                                 if(tex->iuser.flag & IMA_ANIM_ALWAYS)
2189                                         BKE_image_user_calc_frame(&tex->iuser, cfra, 0);
2190                         }
2191                 }
2192         }
2193         
2194         /* image window, compo node users */
2195         for(wm=mainp->wm.first; wm; wm= wm->id.next) { /* only 1 wm */
2196                 for(win= wm->windows.first; win; win= win->next) {
2197                         ScrArea *sa;
2198                         for(sa= win->screen->areabase.first; sa; sa= sa->next) {
2199                                 if(sa->spacetype==SPACE_VIEW3D) {
2200                                         View3D *v3d= sa->spacedata.first;
2201                                         BGpic *bgpic;
2202                                         for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
2203                                                 if(bgpic->iuser.flag & IMA_ANIM_ALWAYS)
2204                                                         BKE_image_user_calc_frame(&bgpic->iuser, cfra, 0);
2205                                 }
2206                                 else if(sa->spacetype==SPACE_IMAGE) {
2207                                         SpaceImage *sima= sa->spacedata.first;
2208                                         if(sima->iuser.flag & IMA_ANIM_ALWAYS)
2209                                                 BKE_image_user_calc_frame(&sima->iuser, cfra, 0);
2210                                 }
2211                                 else if(sa->spacetype==SPACE_NODE) {
2212                                         SpaceNode *snode= sa->spacedata.first;
2213                                         if((snode->treetype==NTREE_COMPOSIT) && (snode->nodetree)) {
2214                                                 bNode *node;
2215                                                 for(node= snode->nodetree->nodes.first; node; node= node->next) {
2216                                                         if(node->id && node->type==CMP_NODE_IMAGE) {
2217                                                                 Image *ima= (Image *)node->id;
2218                                                                 ImageUser *iuser= node->storage;
2219                                                                 if(ELEM(ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE))
2220                                                                         if(iuser->flag & IMA_ANIM_ALWAYS)
2221                                                                                 BKE_image_user_calc_frame(iuser, cfra, 0);
2222                                                         }
2223                                                 }
2224                                         }
2225                                 }
2226                         }
2227                 }
2228         }
2229 }
2230