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