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