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