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