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