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