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