Merging r43909 through r43951 from trunk into soc-2011-tomato
[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         /* XXX unpackImage frees image buffers */
890         ED_preview_kill_jobs(C);
891         
892         BKE_image_signal(sima->image, &sima->iuser, IMA_SIGNAL_RELOAD);
893         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, sima->image);
894
895         return OPERATOR_FINISHED;
896 }
897
898 static int image_replace_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
899 {
900         SpaceImage *sima= CTX_wm_space_image(C);
901
902         if(!sima->image)
903                 return OPERATOR_CANCELLED;
904
905         if(RNA_struct_property_is_set(op->ptr, "filepath"))
906                 return image_replace_exec(C, op);
907
908         if(!RNA_struct_property_is_set(op->ptr, "relative_path"))
909                 RNA_boolean_set(op->ptr, "relative_path", (strncmp(sima->image->name, "//", 2))==0);
910
911         image_filesel(C, op, sima->image->name);
912
913         return OPERATOR_RUNNING_MODAL;
914 }
915
916 void IMAGE_OT_replace(wmOperatorType *ot)
917 {
918         /* identifiers */
919         ot->name= "Replace Image";
920         ot->idname= "IMAGE_OT_replace";
921         
922         /* api callbacks */
923         ot->exec= image_replace_exec;
924         ot->invoke= image_replace_invoke;
925         ot->poll= space_image_poll;
926
927         /* flags */
928         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
929
930         /* properties */
931         WM_operator_properties_filesel(ot, FOLDERFILE|IMAGEFILE|MOVIEFILE, FILE_SPECIAL, FILE_OPENFILE, WM_FILESEL_FILEPATH|WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY);
932 }
933
934 /******************** save image as operator ********************/
935
936 typedef struct {
937         /* matching scene->r settings */
938         //short planes, imtype, subimtype, quality;
939         ImageFormatData im_format;
940         char filepath[FILE_MAX]; /* keep absolute */
941 } SaveImageOptions;
942
943 static void save_image_options_defaults(SaveImageOptions *simopts)
944 {
945         memset(&simopts->im_format, 0, sizeof(simopts->im_format));
946         simopts->im_format.planes= R_IMF_PLANES_RGB;
947         simopts->im_format.imtype= R_IMF_IMTYPE_PNG;
948         simopts->im_format.quality= 90;
949         simopts->im_format.compress= 90;
950         simopts->filepath[0]= '\0';
951 }
952
953 static char imtype_best_depth(ImBuf *ibuf, const char imtype)
954 {
955         const char depth_ok= BKE_imtype_valid_depths(imtype);
956
957         if (ibuf->rect_float) {
958                 if (depth_ok & R_IMF_CHAN_DEPTH_32) return R_IMF_CHAN_DEPTH_32;
959                 if (depth_ok & R_IMF_CHAN_DEPTH_24) return R_IMF_CHAN_DEPTH_24;
960                 if (depth_ok & R_IMF_CHAN_DEPTH_16) return R_IMF_CHAN_DEPTH_16;
961                 if (depth_ok & R_IMF_CHAN_DEPTH_12) return R_IMF_CHAN_DEPTH_12;
962                 return R_IMF_CHAN_DEPTH_8;
963         }
964         else {
965                 if (depth_ok & R_IMF_CHAN_DEPTH_8) return R_IMF_CHAN_DEPTH_8;
966                 if (depth_ok & R_IMF_CHAN_DEPTH_12) return R_IMF_CHAN_DEPTH_12;
967                 if (depth_ok & R_IMF_CHAN_DEPTH_16) return R_IMF_CHAN_DEPTH_16;
968                 if (depth_ok & R_IMF_CHAN_DEPTH_24) return R_IMF_CHAN_DEPTH_24;
969                 if (depth_ok & R_IMF_CHAN_DEPTH_32) return R_IMF_CHAN_DEPTH_32;
970                 return R_IMF_CHAN_DEPTH_8; /* fallback, should not get here */
971         }
972 }
973
974 static int save_image_options_init(SaveImageOptions *simopts, SpaceImage *sima, Scene *scene, const short guess_path)
975 {
976         void *lock;
977         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
978
979         if(ibuf) {
980                 Image *ima= sima->image;
981                 short is_depth_set= FALSE;
982
983                 simopts->im_format.planes= ibuf->planes;
984
985                 if(ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE)) {
986                         /* imtype */
987                         simopts->im_format= scene->r.im_format;
988                         is_depth_set= TRUE;
989                 }
990                 else if (ima->source == IMA_SRC_GENERATED) {
991                         simopts->im_format.imtype= R_IMF_IMTYPE_PNG;
992                 }
993                 else {
994                         simopts->im_format.imtype= BKE_ftype_to_imtype(ibuf->ftype);
995                 }
996                 //simopts->subimtype= scene->r.subimtype; /* XXX - this is lame, we need to make these available too! */
997                 simopts->im_format.quality= ibuf->ftype & 0xff;
998
999                 BLI_strncpy(simopts->filepath, ibuf->name, sizeof(simopts->filepath));
1000
1001                 /* sanitize all settings */
1002
1003                 /* unlikely but just incase */
1004                 if (ELEM3(simopts->im_format.planes, R_IMF_PLANES_BW, R_IMF_PLANES_RGB, R_IMF_PLANES_RGBA) == 0) {
1005                         simopts->im_format.planes= R_IMF_PLANES_RGBA;
1006                 }
1007
1008                 /* depth, account for float buffer and format support */
1009                 if (is_depth_set == FALSE) {
1010                         simopts->im_format.depth= imtype_best_depth(ibuf, simopts->im_format.imtype);
1011                 }
1012
1013                 /* some formats dont use quality so fallback to scenes quality */
1014                 if (simopts->im_format.quality == 0) {
1015                         simopts->im_format.quality= scene->r.im_format.quality;
1016                 }
1017
1018                 /* check for empty path */
1019                 if(guess_path && simopts->filepath[0]==0) {
1020                         if ( (G.ima[0] == '/') && (G.ima[1] == '/') && (G.ima[2] == '\0') ) {
1021                                 BLI_strncpy(simopts->filepath, "//untitled", FILE_MAX);
1022                         } else {
1023                                 BLI_strncpy(simopts->filepath, G.ima, FILE_MAX);
1024                         }
1025                         BLI_path_abs(simopts->filepath, G.main->name);
1026                 }
1027         }
1028
1029         ED_space_image_release_buffer(sima, lock);
1030
1031         return (ibuf != NULL);
1032 }
1033
1034 static void save_image_options_from_op(SaveImageOptions *simopts, wmOperator *op)
1035 {
1036         if (op->customdata) {
1037                 simopts->im_format= *(ImageFormatData *)op->customdata;
1038         }
1039
1040         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
1041                 RNA_string_get(op->ptr, "filepath", simopts->filepath);
1042                 BLI_path_abs(simopts->filepath, G.main->name);
1043         }
1044 }
1045
1046 static void save_image_options_to_op(SaveImageOptions *simopts, wmOperator *op)
1047 {
1048         if (op->customdata) {
1049                 *(ImageFormatData *)op->customdata= simopts->im_format;
1050         }
1051
1052         RNA_string_set(op->ptr, "filepath", simopts->filepath);
1053 }
1054
1055 /* assumes name is FILE_MAX */
1056 /* ima->name and ibuf->name should end up the same */
1057 static void save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveImageOptions *simopts, int do_newpath)
1058 {
1059         Image *ima= ED_space_image(sima);
1060         void *lock;
1061         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
1062
1063         if (ibuf) {
1064                 const char *relbase= ID_BLEND_PATH(CTX_data_main(C), &ima->id);
1065                 const short relative= (RNA_struct_find_property(op->ptr, "relative_path") && RNA_boolean_get(op->ptr, "relative_path"));
1066                 const short save_copy= (RNA_struct_find_property(op->ptr, "copy") && RNA_boolean_get(op->ptr, "copy"));
1067                 short ok= FALSE;
1068
1069                 /* old global to ensure a 2nd save goes to same dir */
1070                 BLI_strncpy(G.ima, simopts->filepath, sizeof(G.ima));
1071
1072                 WM_cursor_wait(1);
1073
1074                 if(ima->type == IMA_TYPE_R_RESULT) {
1075                         /* enforce user setting for RGB or RGBA, but skip BW */
1076                         if(simopts->im_format.planes==R_IMF_PLANES_RGBA) {
1077                                 ibuf->planes= R_IMF_PLANES_RGBA;
1078                         }
1079                         else if(simopts->im_format.planes==R_IMF_PLANES_RGB) {
1080                                 ibuf->planes= R_IMF_PLANES_RGB;
1081                         }
1082                 }
1083                 else {
1084                         /* TODO, better solution, if a 24bit image is painted onto it may contain alpha */
1085                         if(ibuf->userflags & IB_BITMAPDIRTY) { /* it has been painted onto */
1086                                 /* checks each pixel, not ideal */
1087                                 ibuf->planes= BKE_alphatest_ibuf(ibuf) ? 32 : 24;
1088                         }
1089                 }
1090                 
1091                 if(simopts->im_format.imtype==R_IMF_IMTYPE_MULTILAYER) {
1092                         Scene *scene= CTX_data_scene(C);
1093                         RenderResult *rr= BKE_image_acquire_renderresult(scene, ima);
1094                         if(rr) {
1095                                 RE_WriteRenderResult(op->reports, rr, simopts->filepath, simopts->im_format.quality);
1096                                 ok= TRUE;
1097                         }
1098                         else {
1099                                 BKE_report(op->reports, RPT_ERROR, "Did not write, no Multilayer Image");
1100                         }
1101                         BKE_image_release_renderresult(scene, ima);
1102                 }
1103                 else {
1104                         if (BKE_write_ibuf_as(ibuf, simopts->filepath, &simopts->im_format, save_copy)) {
1105                                 ok= TRUE;
1106                         }
1107                 }
1108
1109                 if (ok) {
1110                         if(!save_copy) {
1111                                 if(do_newpath) {
1112                                         BLI_strncpy(ibuf->name, simopts->filepath, sizeof(ibuf->name));
1113                                         BLI_strncpy(ima->name, simopts->filepath, sizeof(ima->name));
1114                                 }
1115
1116                                 ibuf->userflags &= ~IB_BITMAPDIRTY;
1117
1118                                 /* change type? */
1119                                 if(ima->type==IMA_TYPE_R_RESULT) {
1120                                         ima->type= IMA_TYPE_IMAGE;
1121
1122                                         /* workaround to ensure the render result buffer is no longer used
1123                                          * by this image, otherwise can crash when a new render result is
1124                                          * created. */
1125                                         if(ibuf->rect && !(ibuf->mall & IB_rect))
1126                                                 imb_freerectImBuf(ibuf);
1127                                         if(ibuf->rect_float && !(ibuf->mall & IB_rectfloat))
1128                                                 imb_freerectfloatImBuf(ibuf);
1129                                         if(ibuf->zbuf && !(ibuf->mall & IB_zbuf))
1130                                                 IMB_freezbufImBuf(ibuf);
1131                                         if(ibuf->zbuf_float && !(ibuf->mall & IB_zbuffloat))
1132                                                 IMB_freezbuffloatImBuf(ibuf);
1133                                 }
1134                                 if( ELEM(ima->source, IMA_SRC_GENERATED, IMA_SRC_VIEWER)) {
1135                                         ima->source= IMA_SRC_FILE;
1136                                         ima->type= IMA_TYPE_IMAGE;
1137                                 }
1138
1139                                 /* only image path, never ibuf */
1140                                 if(relative) {
1141                                         BLI_path_rel(ima->name, relbase); /* only after saving */
1142                                 }
1143                         }
1144                 }
1145                 else {
1146                         BKE_reportf(op->reports, RPT_ERROR, "Couldn't write image: %s", simopts->filepath);
1147                 }
1148
1149
1150                 WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, sima->image);
1151
1152                 WM_cursor_wait(0);
1153         }
1154
1155         ED_space_image_release_buffer(sima, lock);
1156 }
1157
1158 static void image_save_as_free(wmOperator *op)
1159 {
1160         if (op->customdata) {
1161                 MEM_freeN(op->customdata);
1162                 op->customdata= NULL;
1163         }
1164 }
1165
1166 static int image_save_as_exec(bContext *C, wmOperator *op)
1167 {
1168         SpaceImage *sima= CTX_wm_space_image(C);
1169         SaveImageOptions simopts;
1170
1171         save_image_options_defaults(&simopts);
1172
1173         /* just incase to initialize values,
1174          * these should be set on invoke or by the caller. */
1175         save_image_options_init(&simopts, sima, CTX_data_scene(C), 0);
1176
1177         save_image_options_from_op(&simopts, op);
1178
1179         save_image_doit(C, sima, op, &simopts, TRUE);
1180
1181         image_save_as_free(op);
1182         return OPERATOR_FINISHED;
1183 }
1184
1185
1186 static int image_save_as_check(bContext *UNUSED(C), wmOperator *op)
1187 {
1188         ImageFormatData *imf= op->customdata;
1189         char filepath[FILE_MAX];
1190         RNA_string_get(op->ptr, "filepath", filepath);
1191         if(BKE_add_image_extension(filepath, imf->imtype)) {
1192                 RNA_string_set(op->ptr, "filepath", filepath);
1193                 return TRUE;
1194         }
1195         return FALSE;
1196 }
1197
1198 static int image_save_as_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1199 {
1200         SpaceImage *sima= CTX_wm_space_image(C);
1201         Image *ima = ED_space_image(sima);
1202         Scene *scene= CTX_data_scene(C);
1203         SaveImageOptions simopts;
1204
1205         if(RNA_struct_property_is_set(op->ptr, "filepath"))
1206                 return image_save_as_exec(C, op);
1207
1208         if (save_image_options_init(&simopts, sima, scene, TRUE) == 0)
1209                 return OPERATOR_CANCELLED;
1210         save_image_options_to_op(&simopts, op);
1211
1212         /* enable save_copy by default for render results */
1213         if(ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE) && !RNA_struct_property_is_set(op->ptr, "copy")) {
1214                 RNA_boolean_set(op->ptr, "copy", TRUE);
1215         }
1216
1217         op->customdata= MEM_mallocN(sizeof(simopts.im_format), __func__);
1218         memcpy(op->customdata, &simopts.im_format, sizeof(simopts.im_format));
1219
1220         image_filesel(C, op, simopts.filepath);
1221
1222         return OPERATOR_RUNNING_MODAL;
1223 }
1224
1225 static int image_save_as_cancel(bContext *UNUSED(C), wmOperator *op)
1226 {
1227         image_save_as_free(op);
1228
1229         return OPERATOR_CANCELLED;
1230 }
1231
1232 static int image_save_as_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop)
1233 {
1234         const char *prop_id= RNA_property_identifier(prop);
1235
1236         return !(strcmp(prop_id, "filepath") == 0 ||
1237                  strcmp(prop_id, "directory") == 0 ||
1238                  strcmp(prop_id, "filename") == 0 ||
1239                  /* when saving a copy, relative path has no effect */
1240                  ((strcmp(prop_id, "relative_path") == 0) && RNA_boolean_get(ptr, "copy"))
1241                  );
1242 }
1243
1244 static void image_save_as_draw(bContext *UNUSED(C), wmOperator *op)
1245 {
1246         uiLayout *layout= op->layout;
1247         ImageFormatData *imf= op->customdata;
1248         PointerRNA ptr;
1249
1250         /* image template */
1251         RNA_pointer_create(NULL, &RNA_ImageFormatSettings, imf, &ptr);
1252         uiTemplateImageSettings(layout, &ptr);
1253
1254         /* main draw call */
1255         RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);
1256         uiDefAutoButsRNA(layout, &ptr, image_save_as_draw_check_prop, '\0');
1257 }
1258
1259 void IMAGE_OT_save_as(wmOperatorType *ot)
1260 {
1261 //      PropertyRNA *prop;
1262
1263         /* identifiers */
1264         ot->name= "Save As Image";
1265         ot->idname= "IMAGE_OT_save_as";
1266         
1267         /* api callbacks */
1268         ot->exec= image_save_as_exec;
1269         ot->check= image_save_as_check;
1270         ot->invoke= image_save_as_invoke;
1271         ot->cancel= image_save_as_cancel;
1272         ot->ui= image_save_as_draw;
1273         ot->poll= space_image_buffer_exists_poll;
1274
1275         /* flags */
1276         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1277
1278         /* properties */
1279         RNA_def_boolean(ot->srna, "copy", 0, "Copy", "Create a new image file without modifying the current image in blender");
1280
1281         WM_operator_properties_filesel(ot, FOLDERFILE|IMAGEFILE|MOVIEFILE, FILE_SPECIAL, FILE_SAVE, WM_FILESEL_FILEPATH|WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY);
1282 }
1283
1284 /******************** save image operator ********************/
1285
1286 static int image_save_exec(bContext *C, wmOperator *op)
1287 {
1288         SpaceImage *sima= CTX_wm_space_image(C);
1289         Scene *scene= CTX_data_scene(C);
1290         SaveImageOptions simopts;
1291
1292         if (save_image_options_init(&simopts, sima, scene, FALSE) == 0)
1293                 return OPERATOR_CANCELLED;
1294         save_image_options_from_op(&simopts, op);
1295
1296         if (BLI_exists(simopts.filepath) && BLI_file_is_writable(simopts.filepath)) {
1297                 save_image_doit(C, sima, op, &simopts, FALSE);
1298         }
1299         else {
1300                 BKE_reportf(op->reports, RPT_ERROR, "Can not save image, path '%s' is not writable", simopts.filepath);
1301                 return OPERATOR_CANCELLED;
1302         }
1303
1304         return OPERATOR_FINISHED;
1305 }
1306
1307 void IMAGE_OT_save(wmOperatorType *ot)
1308 {
1309         /* identifiers */
1310         ot->name= "Save Image";
1311         ot->idname= "IMAGE_OT_save";
1312         
1313         /* api callbacks */
1314         ot->exec= image_save_exec;
1315         ot->poll= space_image_file_exists_poll;
1316
1317         /* flags */
1318         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1319 }
1320
1321 /******************* save sequence operator ********************/
1322
1323 static int image_save_sequence_exec(bContext *C, wmOperator *op)
1324 {
1325         Main *bmain= CTX_data_main(C);
1326         SpaceImage *sima= CTX_wm_space_image(C);
1327         ImBuf *ibuf;
1328         int tot= 0;
1329         char di[FILE_MAX], fi[FILE_MAX];
1330         
1331         if(sima->image==NULL)
1332                 return OPERATOR_CANCELLED;
1333
1334         if(sima->image->source!=IMA_SRC_SEQUENCE) {
1335                 BKE_report(op->reports, RPT_ERROR, "Can only save sequence on image sequences");
1336                 return OPERATOR_CANCELLED;
1337         }
1338
1339         if(sima->image->type==IMA_TYPE_MULTILAYER) {
1340                 BKE_report(op->reports, RPT_ERROR, "Can't save multilayer sequences");
1341                 return OPERATOR_CANCELLED;
1342         }
1343         
1344         /* get total */
1345         for(ibuf= sima->image->ibufs.first; ibuf; ibuf= ibuf->next) 
1346                 if(ibuf->userflags & IB_BITMAPDIRTY)
1347                         tot++;
1348         
1349         if(tot==0) {
1350                 BKE_report(op->reports, RPT_WARNING, "No images have been changed");
1351                 return OPERATOR_CANCELLED;
1352         }
1353
1354         /* get a filename for menu */
1355         for(ibuf= sima->image->ibufs.first; ibuf; ibuf= ibuf->next) 
1356                 if(ibuf->userflags & IB_BITMAPDIRTY)
1357                         break;
1358         
1359         BLI_strncpy(di, ibuf->name, FILE_MAX);
1360         BLI_splitdirstring(di, fi);
1361         
1362         BKE_reportf(op->reports, RPT_INFO, "%d Image(s) will be saved in %s", tot, di);
1363
1364         for(ibuf= sima->image->ibufs.first; ibuf; ibuf= ibuf->next) {
1365                 if(ibuf->userflags & IB_BITMAPDIRTY) {
1366                         char name[FILE_MAX];
1367                         BLI_strncpy(name, ibuf->name, sizeof(name));
1368                         
1369                         BLI_path_abs(name, bmain->name);
1370
1371                         if(0 == IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat)) {
1372                                 BKE_reportf(op->reports, RPT_ERROR, "Could not write image %s", name);
1373                                 break;
1374                         }
1375
1376                         BKE_reportf(op->reports, RPT_INFO, "Saved: %s\n", ibuf->name);
1377                         ibuf->userflags &= ~IB_BITMAPDIRTY;
1378                 }
1379         }
1380
1381         return OPERATOR_FINISHED;
1382 }
1383
1384 void IMAGE_OT_save_sequence(wmOperatorType *ot)
1385 {
1386         /* identifiers */
1387         ot->name= "Save Sequence";
1388         ot->idname= "IMAGE_OT_save_sequence";
1389         
1390         /* api callbacks */
1391         ot->exec= image_save_sequence_exec;
1392         ot->poll= space_image_buffer_exists_poll;
1393
1394         /* flags */
1395         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1396 }
1397
1398 /******************** reload image operator ********************/
1399
1400 static int image_reload_exec(bContext *C, wmOperator *UNUSED(op))
1401 {
1402         Image *ima= CTX_data_edit_image(C);
1403         SpaceImage *sima= CTX_wm_space_image(C);
1404
1405         if(!ima)
1406                 return OPERATOR_CANCELLED;
1407
1408         /* XXX unpackImage frees image buffers */
1409         ED_preview_kill_jobs(C);
1410         
1411         // XXX other users?
1412         BKE_image_signal(ima, (sima)? &sima->iuser: NULL, IMA_SIGNAL_RELOAD);
1413
1414         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1415         
1416         return OPERATOR_FINISHED;
1417 }
1418
1419 void IMAGE_OT_reload(wmOperatorType *ot)
1420 {
1421         /* identifiers */
1422         ot->name= "Reload Image";
1423         ot->idname= "IMAGE_OT_reload";
1424         
1425         /* api callbacks */
1426         ot->exec= image_reload_exec;
1427
1428         /* flags */
1429         ot->flag= OPTYPE_REGISTER; /* no undo, image buffer is not handled by undo */
1430 }
1431
1432 /********************** new image operator *********************/
1433
1434 static int image_new_exec(bContext *C, wmOperator *op)
1435 {
1436         SpaceImage *sima;
1437         Scene *scene;
1438         Object *obedit;
1439         Image *ima;
1440         PointerRNA ptr, idptr;
1441         PropertyRNA *prop;
1442         char name[MAX_ID_NAME-2];
1443         float color[4];
1444         int width, height, floatbuf, uvtestgrid, alpha;
1445
1446         /* retrieve state */
1447         sima= CTX_wm_space_image(C);
1448         scene= CTX_data_scene(C);
1449         obedit= CTX_data_edit_object(C);
1450
1451         RNA_string_get(op->ptr, "name", name);
1452         width= RNA_int_get(op->ptr, "width");
1453         height= RNA_int_get(op->ptr, "height");
1454         floatbuf= RNA_boolean_get(op->ptr, "float");
1455         uvtestgrid= RNA_boolean_get(op->ptr, "uv_test_grid");
1456         RNA_float_get_array(op->ptr, "color", color);
1457         alpha= RNA_boolean_get(op->ptr, "alpha");
1458         
1459         if (!floatbuf && scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
1460                 linearrgb_to_srgb_v3_v3(color, color);
1461
1462         if(!alpha)
1463                 color[3]= 1.0f;
1464
1465         ima = BKE_add_image_size(width, height, name, alpha ? 32 : 24, floatbuf, uvtestgrid, color);
1466
1467         if(!ima)
1468                 return OPERATOR_CANCELLED;
1469
1470         /* hook into UI */
1471         uiIDContextProperty(C, &ptr, &prop);
1472
1473         if(prop) {
1474                 /* when creating new ID blocks, use is already 1, but RNA
1475                  * pointer se also increases user, so this compensates it */
1476                 ima->id.us--;
1477
1478                 RNA_id_pointer_create(&ima->id, &idptr);
1479                 RNA_property_pointer_set(&ptr, prop, idptr);
1480                 RNA_property_update(C, &ptr, prop);
1481         }
1482         else if(sima)
1483                 ED_space_image_set(sima, scene, obedit, ima);
1484
1485         // XXX other users?
1486         BKE_image_signal(ima, (sima)? &sima->iuser: NULL, IMA_SIGNAL_USER_NEW_IMAGE);
1487         
1488         return OPERATOR_FINISHED;
1489 }
1490
1491 /* XXX, Ton is not a fan of OK buttons but using this function to avoid undo/redo bug while in mesh-editmode, - campbell */
1492 static int image_new_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1493 {
1494         return WM_operator_props_dialog_popup(C, op, 300, 100);
1495
1496 }
1497
1498 void IMAGE_OT_new(wmOperatorType *ot)
1499 {
1500         PropertyRNA *prop;
1501         static float default_color[4]= {0.0f, 0.0f, 0.0f, 1.0f};
1502         
1503         /* identifiers */
1504         ot->name= "New Image";
1505         ot->description= "Create a new image";
1506         ot->idname= "IMAGE_OT_new";
1507         
1508         /* api callbacks */
1509         ot->exec= image_new_exec;
1510         ot->invoke= image_new_invoke;
1511         
1512         /* flags */
1513         ot->flag= OPTYPE_UNDO;
1514
1515         /* properties */
1516         RNA_def_string(ot->srna, "name", "untitled", MAX_ID_NAME-2, "Name", "Image datablock name");
1517         RNA_def_int(ot->srna, "width", 1024, 1, INT_MAX, "Width", "Image width", 1, 16384);
1518         RNA_def_int(ot->srna, "height", 1024, 1, INT_MAX, "Height", "Image height", 1, 16384);
1519         prop= RNA_def_float_color(ot->srna, "color", 4, NULL, 0.0f, FLT_MAX, "Color", "Default fill color", 0.0f, 1.0f);
1520         RNA_def_property_float_array_default(prop, default_color);
1521         RNA_def_boolean(ot->srna, "alpha", 1, "Alpha", "Create an image with an alpha channel");
1522         RNA_def_boolean(ot->srna, "uv_test_grid", 0, "UV Test Grid", "Fill the image with a grid for UV map testing");
1523         RNA_def_boolean(ot->srna, "float", 0, "32 bit Float", "Create image with 32 bit floating point bit depth");
1524 }
1525
1526 /********************* invert operators *********************/
1527
1528 static int image_invert_poll(bContext *C)
1529 {
1530         Image *ima= CTX_data_edit_image(C);
1531         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1532         
1533         if( ibuf != NULL )
1534                 return 1;
1535         return 0;
1536 }
1537
1538 static int image_invert_exec(bContext *C, wmOperator *op)
1539 {
1540         Image *ima= CTX_data_edit_image(C);
1541         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1542
1543         // flags indicate if this channel should be inverted
1544         const short r= RNA_boolean_get(op->ptr, "invert_r");
1545         const short g= RNA_boolean_get(op->ptr, "invert_g");
1546         const short b= RNA_boolean_get(op->ptr, "invert_b");
1547         const short a= RNA_boolean_get(op->ptr, "invert_a");
1548
1549         int i;
1550
1551         if( ibuf == NULL) // TODO: this should actually never happen, but does for render-results -> cleanup
1552                 return OPERATOR_CANCELLED;
1553
1554         /* TODO: make this into an IMB_invert_channels(ibuf,r,g,b,a) method!? */
1555         if (ibuf->rect_float) {
1556                 
1557                 float *fp = (float *) ibuf->rect_float;
1558                 for( i = ibuf->x * ibuf->y; i > 0; i--, fp+=4 ) {
1559                         if( r ) fp[0] = 1.0f - fp[0];
1560                         if( g ) fp[1] = 1.0f - fp[1];
1561                         if( b ) fp[2] = 1.0f - fp[2];
1562                         if( a ) fp[3] = 1.0f - fp[3];
1563                 }
1564
1565                 if(ibuf->rect) {
1566                         IMB_rect_from_float(ibuf);
1567                 }
1568         }
1569         else if(ibuf->rect) {
1570                 
1571                 char *cp = (char *) ibuf->rect;
1572                 for( i = ibuf->x * ibuf->y; i > 0; i--, cp+=4 ) {
1573                         if( r ) cp[0] = 255 - cp[0];
1574                         if( g ) cp[1] = 255 - cp[1];
1575                         if( b ) cp[2] = 255 - cp[2];
1576                         if( a ) cp[3] = 255 - cp[3];
1577                 }
1578         }
1579         else {
1580                 return OPERATOR_CANCELLED;
1581         }
1582
1583         ibuf->userflags |= IB_BITMAPDIRTY;
1584         if(ibuf->mipmap[0])
1585                 ibuf->userflags |= IB_MIPMAP_INVALID;
1586
1587         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1588         return OPERATOR_FINISHED;
1589 }
1590
1591 void IMAGE_OT_invert(wmOperatorType *ot)
1592 {
1593         /* identifiers */
1594         ot->name= "Invert Channels";
1595         ot->idname= "IMAGE_OT_invert";
1596         
1597         /* api callbacks */
1598         ot->exec= image_invert_exec;
1599         ot->poll= image_invert_poll;
1600         
1601         /* properties */
1602         RNA_def_boolean(ot->srna, "invert_r", 0, "Red", "Invert Red Channel");
1603         RNA_def_boolean(ot->srna, "invert_g", 0, "Green", "Invert Green Channel");
1604         RNA_def_boolean(ot->srna, "invert_b", 0, "Blue", "Invert Blue Channel");
1605         RNA_def_boolean(ot->srna, "invert_a", 0, "Alpha", "Invert Alpha Channel");
1606         
1607         /* flags */
1608         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1609 }
1610
1611 /********************* pack operator *********************/
1612
1613 static int image_pack_test(bContext *C, wmOperator *op)
1614 {
1615         Image *ima= CTX_data_edit_image(C);
1616         int as_png= RNA_boolean_get(op->ptr, "as_png");
1617
1618         if(!ima)
1619                 return 0;
1620         if(!as_png && ima->packedfile)
1621                 return 0;
1622
1623         if(ima->source==IMA_SRC_SEQUENCE || ima->source==IMA_SRC_MOVIE) {
1624                 BKE_report(op->reports, RPT_ERROR, "Packing movies or image sequences not supported");
1625                 return 0;
1626         }
1627
1628         return 1;
1629 }
1630
1631 static int image_pack_exec(bContext *C, wmOperator *op)
1632 {
1633         struct Main *bmain= CTX_data_main(C);
1634         Image *ima= CTX_data_edit_image(C);
1635         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1636         int as_png= RNA_boolean_get(op->ptr, "as_png");
1637
1638         if(!image_pack_test(C, op))
1639                 return OPERATOR_CANCELLED;
1640         
1641         if(!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1642                 BKE_report(op->reports, RPT_ERROR, "Can't pack edited image from disk, only as internal PNG");
1643                 return OPERATOR_CANCELLED;
1644         }
1645
1646         if(as_png)
1647                 BKE_image_memorypack(ima);
1648         else
1649                 ima->packedfile= newPackedFile(op->reports, ima->name, ID_BLEND_PATH(bmain, &ima->id));
1650
1651         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1652         
1653         return OPERATOR_FINISHED;
1654 }
1655
1656 static int image_pack_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1657 {
1658         Image *ima= CTX_data_edit_image(C);
1659         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1660         uiPopupMenu *pup;
1661         uiLayout *layout;
1662         int as_png= RNA_boolean_get(op->ptr, "as_png");
1663
1664         if(!image_pack_test(C, op))
1665                 return OPERATOR_CANCELLED;
1666         
1667         if(!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
1668                 pup= uiPupMenuBegin(C, "OK", ICON_QUESTION);
1669                 layout= uiPupMenuLayout(pup);
1670                 uiItemBooleanO(layout, "Can't pack edited image from disk. Pack as internal PNG?", ICON_NONE, op->idname, "as_png", 1);
1671                 uiPupMenuEnd(C, pup);
1672
1673                 return OPERATOR_CANCELLED;
1674         }
1675
1676         return image_pack_exec(C, op);
1677 }
1678
1679 void IMAGE_OT_pack(wmOperatorType *ot)
1680 {
1681         /* identifiers */
1682         ot->name= "Pack Image";
1683         ot->description= "Pack an image as embedded data into the .blend file"; 
1684         ot->idname= "IMAGE_OT_pack";
1685         
1686         /* api callbacks */
1687         ot->exec= image_pack_exec;
1688         ot->invoke= image_pack_invoke;
1689
1690         /* flags */
1691         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1692
1693         /* properties */
1694         RNA_def_boolean(ot->srna, "as_png", 0, "Pack As PNG", "Pack image as lossless PNG");
1695 }
1696
1697 /********************* unpack operator *********************/
1698
1699 static int image_unpack_exec(bContext *C, wmOperator *op)
1700 {
1701         Image *ima= CTX_data_edit_image(C);
1702         int method= RNA_enum_get(op->ptr, "method");
1703
1704         /* find the suppplied image by name */
1705         if (RNA_struct_property_is_set(op->ptr, "id")) {
1706                 char imaname[MAX_ID_NAME-2];
1707                 RNA_string_get(op->ptr, "id", imaname);
1708                 ima = BLI_findstring(&CTX_data_main(C)->image, imaname, offsetof(ID, name) + 2);
1709                 if (!ima) ima = CTX_data_edit_image(C);
1710         }
1711         
1712         if(!ima || !ima->packedfile)
1713                 return OPERATOR_CANCELLED;
1714
1715         if(ima->source==IMA_SRC_SEQUENCE || ima->source==IMA_SRC_MOVIE) {
1716                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
1717                 return OPERATOR_CANCELLED;
1718         }
1719
1720         if(G.fileflags & G_AUTOPACK)
1721                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
1722         
1723         /* XXX unpackImage frees image buffers */
1724         ED_preview_kill_jobs(C);
1725         
1726         unpackImage(op->reports, ima, method);
1727         
1728         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, ima);
1729
1730         return OPERATOR_FINISHED;
1731 }
1732
1733 static int image_unpack_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1734 {
1735         Image *ima= CTX_data_edit_image(C);
1736
1737         if(RNA_struct_property_is_set(op->ptr, "id"))
1738                 return image_unpack_exec(C, op);
1739                 
1740         if(!ima || !ima->packedfile)
1741                 return OPERATOR_CANCELLED;
1742
1743         if(ima->source==IMA_SRC_SEQUENCE || ima->source==IMA_SRC_MOVIE) {
1744                 BKE_report(op->reports, RPT_ERROR, "Unpacking movies or image sequences not supported");
1745                 return OPERATOR_CANCELLED;
1746         }
1747
1748         if(G.fileflags & G_AUTOPACK)
1749                 BKE_report(op->reports, RPT_WARNING, "AutoPack is enabled, so image will be packed again on file save");
1750
1751         unpack_menu(C, "IMAGE_OT_unpack", ima->id.name+2, ima->name, "textures", ima->packedfile);
1752
1753         return OPERATOR_FINISHED;
1754 }
1755
1756 void IMAGE_OT_unpack(wmOperatorType *ot)
1757 {
1758         /* identifiers */
1759         ot->name= "Unpack Image";
1760         ot->description= "Save an image packed in the .blend file to disk"; 
1761         ot->idname= "IMAGE_OT_unpack";
1762         
1763         /* api callbacks */
1764         ot->exec= image_unpack_exec;
1765         ot->invoke= image_unpack_invoke;
1766
1767         /* flags */
1768         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1769         
1770         /* properties */
1771         RNA_def_enum(ot->srna, "method", unpack_method_items, PF_USE_LOCAL, "Method", "How to unpack");
1772         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 */
1773 }
1774
1775 /******************** sample image operator ********************/
1776
1777 typedef struct ImageSampleInfo {
1778         ARegionType *art;
1779         void *draw_handle;
1780         int x, y;
1781         int channels;
1782
1783         unsigned char col[4];
1784         float colf[4];
1785         int z;
1786         float zf;
1787
1788         unsigned char *colp;
1789         float *colfp;
1790         int *zp;
1791         float *zfp;
1792
1793         int draw;
1794 } ImageSampleInfo;
1795
1796 static void image_sample_draw(const bContext *UNUSED(C), ARegion *ar, void *arg_info)
1797 {
1798         ImageSampleInfo *info= arg_info;
1799         if(info->draw) {
1800                 /* no color management needed for images (color_manage=0) */
1801                 ED_image_draw_info(ar, 0, info->channels, info->x, info->y, info->colp, info->colfp, info->zp, info->zfp);
1802         }
1803 }
1804
1805 static void image_sample_apply(bContext *C, wmOperator *op, wmEvent *event)
1806 {
1807         SpaceImage *sima= CTX_wm_space_image(C);
1808         ARegion *ar= CTX_wm_region(C);
1809         void *lock;
1810         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
1811         ImageSampleInfo *info= op->customdata;
1812         float fx, fy;
1813         
1814         if(ibuf == NULL) {
1815                 ED_space_image_release_buffer(sima, lock);
1816                 return;
1817         }
1818
1819         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &fx, &fy);
1820
1821         if(fx>=0.0f && fy>=0.0f && fx<1.0f && fy<1.0f) {
1822                 float *fp;
1823                 unsigned char *cp;
1824                 int x= (int)(fx*ibuf->x), y= (int)(fy*ibuf->y);
1825
1826                 CLAMP(x, 0, ibuf->x-1);
1827                 CLAMP(y, 0, ibuf->y-1);
1828
1829                 info->x= x;
1830                 info->y= y;
1831                 info->draw= 1;
1832                 info->channels= ibuf->channels;
1833
1834                 info->colp= NULL;
1835                 info->colfp= NULL;
1836                 info->zp= NULL;
1837                 info->zfp= NULL;
1838                 
1839                 if(ibuf->rect) {
1840                         cp= (unsigned char *)(ibuf->rect + y*ibuf->x + x);
1841
1842                         info->col[0]= cp[0];
1843                         info->col[1]= cp[1];
1844                         info->col[2]= cp[2];
1845                         info->col[3]= cp[3];
1846                         info->colp= info->col;
1847
1848                         info->colf[0]= (float)cp[0]/255.0f;
1849                         info->colf[1]= (float)cp[1]/255.0f;
1850                         info->colf[2]= (float)cp[2]/255.0f;
1851                         info->colf[3]= (float)cp[3]/255.0f;
1852                         info->colfp= info->colf;
1853                 }
1854                 if(ibuf->rect_float) {
1855                         fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
1856
1857                         info->colf[0]= fp[0];
1858                         info->colf[1]= fp[1];
1859                         info->colf[2]= fp[2];
1860                         info->colf[3]= fp[3];
1861                         info->colfp= info->colf;
1862                 }
1863
1864                 if(ibuf->zbuf) {
1865                         info->z= ibuf->zbuf[y*ibuf->x + x];
1866                         info->zp= &info->z;
1867                 }
1868                 if(ibuf->zbuf_float) {
1869                         info->zf= ibuf->zbuf_float[y*ibuf->x + x];
1870                         info->zfp= &info->zf;
1871                 }
1872                 
1873                 if(sima->cumap && ibuf->channels==4) {
1874                         /* we reuse this callback for set curves point operators */
1875                         if(RNA_struct_find_property(op->ptr, "point")) {
1876                                 int point= RNA_enum_get(op->ptr, "point");
1877
1878                                 if(point == 1) {
1879                                         curvemapping_set_black_white(sima->cumap, NULL, info->colfp);
1880                                         if(ibuf->rect_float)
1881                                                 curvemapping_do_ibuf(sima->cumap, ibuf);
1882                                 }
1883                                 else if(point == 0) {
1884                                         curvemapping_set_black_white(sima->cumap, info->colfp, NULL);
1885                                         if(ibuf->rect_float)
1886                                                 curvemapping_do_ibuf(sima->cumap, ibuf);
1887                                 }
1888                         }
1889                 }
1890                                 
1891                 // XXX node curve integration ..
1892 #if 0
1893                 {
1894                         ScrArea *sa, *cur= curarea;
1895                         
1896                         node_curvemap_sample(fp);       /* sends global to node editor */
1897                         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
1898                                 if(sa->spacetype==SPACE_NODE) {
1899                                         areawinset(sa->win);
1900                                         scrarea_do_windraw(sa);
1901                                 }
1902                         }
1903                         node_curvemap_sample(NULL);             /* clears global in node editor */
1904                         curarea= cur;
1905                 }
1906 #endif
1907         }
1908         else
1909                 info->draw= 0;
1910
1911         ED_space_image_release_buffer(sima, lock);
1912         ED_area_tag_redraw(CTX_wm_area(C));
1913 }
1914
1915 static void image_sample_exit(bContext *C, wmOperator *op)
1916 {
1917         ImageSampleInfo *info= op->customdata;
1918
1919         ED_region_draw_cb_exit(info->art, info->draw_handle);
1920         ED_area_tag_redraw(CTX_wm_area(C));
1921         MEM_freeN(info);
1922 }
1923
1924 static int image_sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1925 {
1926         SpaceImage *sima= CTX_wm_space_image(C);
1927         ARegion *ar= CTX_wm_region(C);
1928         ImageSampleInfo *info;
1929
1930         if(!ED_space_image_has_buffer(sima))
1931                 return OPERATOR_CANCELLED;
1932         
1933         info= MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
1934         info->art= ar->type;
1935         info->draw_handle = ED_region_draw_cb_activate(ar->type, image_sample_draw, info, REGION_DRAW_POST_PIXEL);
1936         op->customdata= info;
1937
1938         image_sample_apply(C, op, event);
1939
1940         WM_event_add_modal_handler(C, op);
1941
1942         return OPERATOR_RUNNING_MODAL;
1943 }
1944
1945 static int image_sample_modal(bContext *C, wmOperator *op, wmEvent *event)
1946 {
1947         switch(event->type) {
1948                 case LEFTMOUSE:
1949                 case RIGHTMOUSE: // XXX hardcoded
1950                         image_sample_exit(C, op);
1951                         return OPERATOR_CANCELLED;
1952                 case MOUSEMOVE:
1953                         image_sample_apply(C, op, event);
1954                         break;
1955         }
1956
1957         return OPERATOR_RUNNING_MODAL;
1958 }
1959
1960 static int image_sample_cancel(bContext *C, wmOperator *op)
1961 {
1962         image_sample_exit(C, op);
1963         return OPERATOR_CANCELLED;
1964 }
1965
1966 void IMAGE_OT_sample(wmOperatorType *ot)
1967 {
1968         /* identifiers */
1969         ot->name= "Sample Color";
1970         ot->idname= "IMAGE_OT_sample";
1971         
1972         /* api callbacks */
1973         ot->invoke= image_sample_invoke;
1974         ot->modal= image_sample_modal;
1975         ot->cancel= image_sample_cancel;
1976         ot->poll= space_image_image_sample_poll;
1977
1978         /* flags */
1979         ot->flag= OPTYPE_BLOCKING;
1980 }
1981
1982 /******************** sample line operator ********************/
1983 static int image_sample_line_exec(bContext *C, wmOperator *op)
1984 {
1985         SpaceImage *sima= CTX_wm_space_image(C);
1986         ARegion *ar= CTX_wm_region(C);
1987         Scene *scene= CTX_data_scene(C);
1988         
1989         int x_start= RNA_int_get(op->ptr, "xstart");
1990         int y_start= RNA_int_get(op->ptr, "ystart");
1991         int x_end= RNA_int_get(op->ptr, "xend");
1992         int y_end= RNA_int_get(op->ptr, "yend");
1993         
1994         void *lock;
1995         ImBuf *ibuf= ED_space_image_acquire_buffer(sima, &lock);
1996         Histogram *hist= &sima->sample_line_hist;
1997         
1998         float x1f, y1f, x2f, y2f;
1999         int x1, y1, x2, y2;
2000         int i, x, y;
2001         float *fp;
2002         float rgb[3];
2003         unsigned char *cp;
2004         
2005         if (ibuf == NULL) {
2006                 ED_space_image_release_buffer(sima, lock);
2007                 return OPERATOR_CANCELLED;
2008         }
2009         /* hmmmm */
2010         if (ibuf->channels < 3) {
2011                 ED_space_image_release_buffer(sima, lock);
2012                 return OPERATOR_CANCELLED;
2013         }
2014         
2015         UI_view2d_region_to_view(&ar->v2d, x_start, y_start, &x1f, &y1f);
2016         UI_view2d_region_to_view(&ar->v2d, x_end, y_end, &x2f, &y2f);
2017         x1= 0.5f+ x1f*ibuf->x;
2018         x2= 0.5f+ x2f*ibuf->x;
2019         y1= 0.5f+ y1f*ibuf->y;
2020         y2= 0.5f+ y2f*ibuf->y;
2021         
2022         hist->channels = 3;
2023         hist->x_resolution = 256;
2024         hist->xmax = 1.0f;
2025         hist->ymax = 1.0f;
2026         
2027         for (i=0; i<256; i++) {
2028                 x= (int)(0.5f + x1 + (float)i*(x2-x1)/255.0f);
2029                 y= (int)(0.5f + y1 + (float)i*(y2-y1)/255.0f);
2030                 
2031                 if (x<0 || y<0 || x>=ibuf->x || y>=ibuf->y) {
2032                         hist->data_luma[i] = hist->data_r[i] = hist->data_g[i]= hist->data_b[i] = 0.0f;
2033                 } else {
2034                         if (ibuf->rect_float) {
2035                                 fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
2036
2037                                 if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2038                                         linearrgb_to_srgb_v3_v3(rgb, fp);
2039                                 else
2040                                         copy_v3_v3(rgb, fp);
2041
2042                                 hist->data_r[i] = rgb[0];
2043                                 hist->data_g[i] = rgb[1];
2044                                 hist->data_b[i] = rgb[2];
2045                                 hist->data_luma[i] = rgb_to_luma(rgb);
2046                         }
2047                         else if (ibuf->rect) {
2048                                 cp= (unsigned char *)(ibuf->rect + y*ibuf->x + x);
2049                                 hist->data_r[i] = (float)cp[0]/255.0f;
2050                                 hist->data_g[i] = (float)cp[1]/255.0f;
2051                                 hist->data_b[i] = (float)cp[2]/255.0f;
2052                                 hist->data_luma[i] = (float)rgb_to_luma_byte(cp)/255.0f;
2053                         }
2054                 }
2055         }
2056         
2057         ED_space_image_release_buffer(sima, lock);
2058         
2059         ED_area_tag_redraw(CTX_wm_area(C));
2060         
2061         return OPERATOR_FINISHED;
2062 }
2063
2064 static int image_sample_line_invoke(bContext *C, wmOperator *op, wmEvent *event)
2065 {
2066         SpaceImage *sima= CTX_wm_space_image(C);
2067         
2068         if(!ED_space_image_has_buffer(sima))
2069                 return OPERATOR_CANCELLED;
2070         
2071         return WM_gesture_straightline_invoke(C, op, event);
2072 }
2073
2074 void IMAGE_OT_sample_line(wmOperatorType *ot)
2075 {
2076         /* identifiers */
2077         ot->name= "Sample Line";
2078         ot->idname= "IMAGE_OT_sample_line";
2079         
2080         /* api callbacks */
2081         ot->invoke= image_sample_line_invoke;
2082         ot->modal= WM_gesture_straightline_modal;
2083         ot->exec= image_sample_line_exec;
2084         ot->poll= space_image_main_area_poll;
2085         ot->cancel= WM_gesture_straightline_cancel;
2086         
2087         /* flags */
2088         ot->flag= 0; /* no undo/register since this operates on the space */
2089         
2090         WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT);
2091 }
2092
2093 /******************** set curve point operator ********************/
2094
2095 void IMAGE_OT_curves_point_set(wmOperatorType *ot)
2096 {
2097         static EnumPropertyItem point_items[]= {
2098                 {0, "BLACK_POINT", 0, "Black Point", ""},
2099                 {1, "WHITE_POINT", 0, "White Point", ""},
2100                 {0, NULL, 0, NULL, NULL}};
2101
2102         /* identifiers */
2103         ot->name= "Set Curves Point";
2104         ot->idname= "IMAGE_OT_curves_point_set";
2105
2106         /* flags */
2107         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2108         
2109         /* api callbacks */
2110         ot->invoke= image_sample_invoke;
2111         ot->modal= image_sample_modal;
2112         ot->cancel= image_sample_cancel;
2113         ot->poll= space_image_main_area_not_uv_brush_poll;
2114
2115         /* properties */
2116         RNA_def_enum(ot->srna, "point", point_items, 0, "Point", "Set black point or white point for curves");
2117 }
2118
2119 /******************** record composite operator *********************/
2120
2121 typedef struct RecordCompositeData {
2122         wmTimer *timer;
2123         int old_cfra;
2124         int sfra, efra;
2125 } RecordCompositeData;
2126
2127 static int image_record_composite_apply(bContext *C, wmOperator *op)
2128 {
2129         SpaceImage *sima= CTX_wm_space_image(C);
2130         RecordCompositeData *rcd= op->customdata;
2131         Scene *scene= CTX_data_scene(C);
2132         ImBuf *ibuf;
2133         
2134         WM_timecursor(CTX_wm_window(C), scene->r.cfra);
2135
2136         // XXX scene->nodetree->test_break= blender_test_break;
2137         // XXX scene->nodetree->test_break= NULL;
2138         
2139         BKE_image_all_free_anim_ibufs(scene->r.cfra);
2140         ntreeCompositTagAnimated(scene->nodetree);
2141         ntreeCompositExecTree(scene->nodetree, &scene->r, scene->r.cfra != rcd->old_cfra);      /* 1 is no previews */
2142
2143         ED_area_tag_redraw(CTX_wm_area(C));
2144         
2145         ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
2146         /* save memory in flipbooks */
2147         if(ibuf)
2148                 imb_freerectfloatImBuf(ibuf);
2149         
2150         scene->r.cfra++;
2151
2152         return (scene->r.cfra <= rcd->efra);
2153 }
2154
2155 static int image_record_composite_init(bContext *C, wmOperator *op)
2156 {
2157         SpaceImage *sima= CTX_wm_space_image(C);
2158         Scene *scene= CTX_data_scene(C);
2159         RecordCompositeData *rcd;
2160
2161         if(sima->iuser.frames < 2)
2162                 return 0;
2163         if(scene->nodetree == NULL)
2164                 return 0;
2165         
2166         op->customdata= rcd= MEM_callocN(sizeof(RecordCompositeData), "ImageRecordCompositeData");
2167
2168         rcd->old_cfra= scene->r.cfra;
2169         rcd->sfra= sima->iuser.sfra;
2170         rcd->efra= sima->iuser.sfra + sima->iuser.frames-1;
2171         scene->r.cfra= rcd->sfra;
2172
2173         return 1;
2174 }
2175
2176 static void image_record_composite_exit(bContext *C, wmOperator *op)
2177 {
2178         Scene *scene= CTX_data_scene(C);
2179         SpaceImage *sima= CTX_wm_space_image(C);
2180         RecordCompositeData *rcd= op->customdata;
2181
2182         scene->r.cfra= rcd->old_cfra;
2183
2184         WM_cursor_restore(CTX_wm_window(C));
2185
2186         if(rcd->timer)
2187                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rcd->timer);
2188
2189         WM_event_add_notifier(C, NC_IMAGE|NA_EDITED, sima->image);
2190
2191         // XXX play_anim(0);
2192         // XXX allqueue(REDRAWNODE, 1);
2193
2194         MEM_freeN(rcd);
2195 }
2196
2197 static int image_record_composite_exec(bContext *C, wmOperator *op)
2198 {
2199         if(!image_record_composite_init(C, op))
2200                 return OPERATOR_CANCELLED;
2201         
2202         while(image_record_composite_apply(C, op))
2203                 ;
2204         
2205         image_record_composite_exit(C, op);
2206         
2207         return OPERATOR_FINISHED;
2208 }
2209
2210 static int image_record_composite_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2211 {
2212         RecordCompositeData *rcd;
2213         
2214         if(!image_record_composite_init(C, op))
2215                 return OPERATOR_CANCELLED;
2216
2217         rcd= op->customdata;
2218         rcd->timer= WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.0f);
2219         WM_event_add_modal_handler(C, op);
2220
2221         if(!image_record_composite_apply(C, op))
2222                 return OPERATOR_FINISHED;
2223
2224         return OPERATOR_RUNNING_MODAL;
2225 }
2226
2227 static int image_record_composite_modal(bContext *C, wmOperator *op, wmEvent *event)
2228 {
2229         RecordCompositeData *rcd= op->customdata;
2230
2231         switch(event->type) {
2232                 case TIMER:
2233                         if(rcd->timer == event->customdata) {
2234                                 if(!image_record_composite_apply(C, op)) {
2235                                         image_record_composite_exit(C, op);
2236                                         return OPERATOR_FINISHED;
2237                                 }
2238                         }
2239                         break;
2240                 case ESCKEY:
2241                         image_record_composite_exit(C, op);
2242                         return OPERATOR_FINISHED;
2243         }
2244
2245         return OPERATOR_RUNNING_MODAL;
2246 }
2247
2248 static int image_record_composite_cancel(bContext *C, wmOperator *op)
2249 {
2250         image_record_composite_exit(C, op);
2251         return OPERATOR_CANCELLED;
2252 }
2253
2254 void IMAGE_OT_record_composite(wmOperatorType *ot)
2255 {
2256         /* identifiers */
2257         ot->name= "Record Composite";
2258         ot->idname= "IMAGE_OT_record_composite";
2259         
2260         /* api callbacks */
2261         ot->exec= image_record_composite_exec;
2262         ot->invoke= image_record_composite_invoke;
2263         ot->modal= image_record_composite_modal;
2264         ot->cancel= image_record_composite_cancel;
2265         ot->poll= space_image_buffer_exists_poll;
2266 }
2267
2268 /********************* cycle render slot operator *********************/
2269
2270 static int image_cycle_render_slot_poll(bContext *C)
2271 {
2272         Image *ima= CTX_data_edit_image(C);
2273
2274         return (ima && ima->type == IMA_TYPE_R_RESULT);
2275 }
2276
2277 static int image_cycle_render_slot_exec(bContext *C, wmOperator *op)
2278 {
2279         Image *ima= CTX_data_edit_image(C);
2280         int a, slot, cur= ima->render_slot;
2281         const short use_reverse= RNA_boolean_get(op->ptr, "reverse");
2282
2283         for(a=1; a<IMA_MAX_RENDER_SLOT; a++) {
2284                 slot= (cur + (use_reverse ? -a:a))%IMA_MAX_RENDER_SLOT;
2285                 if(slot<0) slot+=IMA_MAX_RENDER_SLOT;
2286
2287                 if(ima->renders[slot] || slot == ima->last_render_slot) {
2288                         ima->render_slot= slot;
2289                         break;
2290                 }
2291                 else if((slot - 1) == ima->last_render_slot && slot < IMA_MAX_RENDER_SLOT) {
2292                         ima->render_slot= slot;
2293                         break;
2294                 }
2295         }
2296
2297         if(a == IMA_MAX_RENDER_SLOT)
2298                 ima->render_slot= ((cur == 1)? 0: 1);
2299         
2300         WM_event_add_notifier(C, NC_IMAGE|ND_DRAW, NULL);
2301
2302         /* no undo push for browsing existing */
2303         if(ima->renders[ima->render_slot] || ima->render_slot==ima->last_render_slot)
2304                 return OPERATOR_CANCELLED;
2305         
2306         return OPERATOR_FINISHED;
2307 }
2308
2309 void IMAGE_OT_cycle_render_slot(wmOperatorType *ot)
2310 {
2311         /* identifiers */
2312         ot->name= "Cycle Render Slot";
2313         ot->idname= "IMAGE_OT_cycle_render_slot";
2314         
2315         /* api callbacks */
2316         ot->exec= image_cycle_render_slot_exec;
2317         ot->poll= image_cycle_render_slot_poll;
2318
2319         /* flags */
2320         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2321
2322         RNA_def_boolean(ot->srna, "reverse", 0, "Cycle in Reverse", "");
2323 }
2324
2325 /******************** TODO ********************/
2326
2327 /* XXX notifier? */
2328
2329 /* goes over all ImageUsers, and sets frame numbers if auto-refresh is set */
2330
2331 void ED_image_update_frame(const Main *mainp, int cfra)
2332 {
2333         wmWindowManager *wm;
2334         wmWindow *win;
2335         Tex *tex;
2336         
2337         /* texture users */
2338         for(tex= mainp->tex.first; tex; tex= tex->id.next) {
2339                 if(tex->type==TEX_IMAGE && tex->ima) {
2340                         if(ELEM(tex->ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
2341                                 if(tex->iuser.flag & IMA_ANIM_ALWAYS)
2342                                         BKE_image_user_calc_frame(&tex->iuser, cfra, 0);
2343                         }
2344                 }
2345         }
2346         
2347         /* image window, compo node users */
2348         for(wm=mainp->wm.first; wm; wm= wm->id.next) { /* only 1 wm */
2349                 for(win= wm->windows.first; win; win= win->next) {
2350                         ScrArea *sa;
2351                         for(sa= win->screen->areabase.first; sa; sa= sa->next) {
2352                                 if(sa->spacetype==SPACE_VIEW3D) {
2353                                         View3D *v3d= sa->spacedata.first;
2354                                         BGpic *bgpic;
2355                                         for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
2356                                                 if(bgpic->iuser.flag & IMA_ANIM_ALWAYS)
2357                                                         BKE_image_user_calc_frame(&bgpic->iuser, cfra, 0);
2358                                 }
2359                                 else if(sa->spacetype==SPACE_IMAGE) {
2360                                         SpaceImage *sima= sa->spacedata.first;
2361                                         if(sima->iuser.flag & IMA_ANIM_ALWAYS)
2362                                                 BKE_image_user_calc_frame(&sima->iuser, cfra, 0);
2363                                 }
2364                                 else if(sa->spacetype==SPACE_NODE) {
2365                                         SpaceNode *snode= sa->spacedata.first;
2366                                         if((snode->treetype==NTREE_COMPOSIT) && (snode->nodetree)) {
2367                                                 bNode *node;
2368                                                 for(node= snode->nodetree->nodes.first; node; node= node->next) {
2369                                                         if(node->id && node->type==CMP_NODE_IMAGE) {
2370                                                                 Image *ima= (Image *)node->id;
2371                                                                 ImageUser *iuser= node->storage;
2372                                                                 if(ELEM(ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE))
2373                                                                         if(iuser->flag & IMA_ANIM_ALWAYS)
2374                                                                                 BKE_image_user_calc_frame(iuser, cfra, 0);
2375                                                         }
2376                                                 }
2377                                         }
2378                                 }
2379                         }
2380                 }
2381         }
2382 }
2383