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