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