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