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