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