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