Images: make it harder to accidentally undo image texture painting changes
[blender.git] / source / blender / editors / space_image / image_ops.c
index 11b34ff..03e1d80 100644 (file)
 
 #include "MEM_guardedalloc.h"
 
-#include "BLI_math.h"
 #include "BLI_blenlib.h"
+#include "BLI_ghash.h"
+#include "BLI_math.h"
+#include "BLI_string.h"
 #include "BLI_utildefines.h"
 
 #include "BLT_translation.h"
@@ -51,6 +53,7 @@
 #include "BKE_context.h"
 #include "BKE_icons.h"
 #include "BKE_image.h"
+#include "BKE_image_save.h"
 #include "BKE_global.h"
 #include "BKE_library.h"
 #include "BKE_main.h"
@@ -64,6 +67,7 @@
 #include "DEG_depsgraph.h"
 
 #include "GPU_draw.h"
+#include "GPU_state.h"
 #include "GPU_immediate.h"
 
 #include "IMB_colormanagement.h"
@@ -177,31 +181,59 @@ static void sima_zoom_set_from_bounds(SpaceImage *sima, ARegion *ar, const rctf
   sima_zoom_set(sima, ar, size, NULL);
 }
 
-#if 0  // currently unused
-static bool image_poll(bContext *C)
+static Image *image_from_context(const bContext *C)
 {
-  return (CTX_data_edit_image(C) != NULL);
+  /* Edit image is set by templates used throughout the interface, so image
+   * operations work outside the image editor. */
+  Image *ima = CTX_data_pointer_get_type(C, "edit_image", &RNA_Image).data;
+
+  if (ima) {
+    return ima;
+  }
+  else {
+    /* Image editor. */
+    SpaceImage *sima = CTX_wm_space_image(C);
+    return (sima) ? sima->image : NULL;
+  }
 }
-#endif
 
-static bool space_image_buffer_exists_poll(bContext *C)
+static ImageUser *image_user_from_context(const bContext *C)
 {
-  SpaceImage *sima = CTX_wm_space_image(C);
-  if (sima && ED_space_image_has_buffer(sima)) {
-    return true;
+  /* Edit image user is set by templates used throughout the interface, so
+   * image operations work outside the image editor. */
+  ImageUser *iuser = CTX_data_pointer_get_type(C, "edit_image_user", &RNA_ImageUser).data;
+
+  if (iuser) {
+    return iuser;
+  }
+  else {
+    /* Image editor. */
+    SpaceImage *sima = CTX_wm_space_image(C);
+    return (sima) ? &sima->iuser : NULL;
   }
-  return false;
 }
 
-static bool image_not_packed_poll(bContext *C)
+static bool image_buffer_exists_from_context(bContext *C)
 {
-  SpaceImage *sima = CTX_wm_space_image(C);
+  Image *ima = image_from_context(C);
+  ImageUser *iuser = image_user_from_context(C);
 
-  /* Do not run 'replace' on packed images, it does not give user expected results at all. */
-  if (sima && sima->image && BLI_listbase_is_empty(&sima->image->packedfiles)) {
-    return true;
+  if (ima == NULL) {
+    return false;
   }
-  return false;
+
+  void *lock;
+  ImBuf *ibuf = BKE_image_acquire_ibuf(ima, iuser, &lock);
+  const bool has_buffer = (ibuf && (ibuf->rect || ibuf->rect_float));
+  BKE_image_release_ibuf(ima, ibuf, lock);
+  return has_buffer;
+}
+
+static bool image_not_packed_poll(bContext *C)
+{
+  /* Do not run 'replace' on packed images, it does not give user expected results at all. */
+  Image *ima = image_from_context(C);
+  return (ima && BLI_listbase_is_empty(&ima->packedfiles));
 }
 
 static bool imbuf_format_writeable(const ImBuf *ibuf)
@@ -214,49 +246,39 @@ static bool imbuf_format_writeable(const ImBuf *ibuf)
 
 static bool space_image_file_exists_poll(bContext *C)
 {
-  if (space_image_buffer_exists_poll(C)) {
-    Main *bmain = CTX_data_main(C);
-    SpaceImage *sima = CTX_wm_space_image(C);
-    ImBuf *ibuf;
-    void *lock;
-    bool ret = false;
-    char name[FILE_MAX];
+  if (image_buffer_exists_from_context(C) == false) {
+    return false;
+  }
 
-    ibuf = ED_space_image_acquire_buffer(sima, &lock);
-    if (ibuf) {
-      BLI_strncpy(name, ibuf->name, FILE_MAX);
-      BLI_path_abs(name, BKE_main_blendfile_path(bmain));
+  Main *bmain = CTX_data_main(C);
+  Image *ima = image_from_context(C);
+  ImageUser *iuser = image_user_from_context(C);
+  void *lock;
+  ImBuf *ibuf = BKE_image_acquire_ibuf(ima, iuser, &lock);
+  bool ret = false;
 
-      if (BLI_exists(name) == false) {
-        CTX_wm_operator_poll_msg_set(C, "image file not found");
-      }
-      else if (!BLI_file_is_writable(name)) {
-        CTX_wm_operator_poll_msg_set(C, "image path can't be written to");
-      }
-      else if (!imbuf_format_writeable(ibuf)) {
-        CTX_wm_operator_poll_msg_set(C, "image format is read-only");
-      }
-      else {
-        ret = true;
-      }
-    }
-    ED_space_image_release_buffer(sima, ibuf, lock);
+  if (ibuf) {
+    char name[FILE_MAX];
+    BLI_strncpy(name, ibuf->name, FILE_MAX);
+    BLI_path_abs(name, BKE_main_blendfile_path(bmain));
 
-    return ret;
+    if (BLI_exists(name) == false) {
+      CTX_wm_operator_poll_msg_set(C, "image file not found");
+    }
+    else if (!BLI_file_is_writable(name)) {
+      CTX_wm_operator_poll_msg_set(C, "image path can't be written to");
+    }
+    else if (!imbuf_format_writeable(ibuf)) {
+      CTX_wm_operator_poll_msg_set(C, "image format is read-only");
+    }
+    else {
+      ret = true;
+    }
   }
-  return false;
-}
 
-#if 0 /* UNUSED */
-static bool space_image_poll(bContext *C)
-{
-  SpaceImage *sima = CTX_wm_space_image(C);
-  if (sima && sima->image) {
-    return true;
-  }
-  return false;
+  BKE_image_release_ibuf(ima, ibuf, lock);
+  return ret;
 }
-#endif
 
 bool space_image_main_region_poll(bContext *C)
 {
@@ -286,23 +308,23 @@ static bool space_image_main_area_not_uv_brush_poll(bContext *C)
 static bool image_sample_poll(bContext *C)
 {
   SpaceImage *sima = CTX_wm_space_image(C);
-  if (sima) {
-    Object *obedit = CTX_data_edit_object(C);
-    if (obedit) {
-      /* Disable when UV editing so it doesn't swallow all click events (use for setting cursor). */
-      if (ED_space_image_show_uvedit(sima, obedit)) {
-        return false;
-      }
-    }
-    else if (sima->mode != SI_MODE_VIEW) {
+  if (sima == NULL) {
+    return false;
+  }
+
+  Object *obedit = CTX_data_edit_object(C);
+  if (obedit) {
+    /* Disable when UV editing so it doesn't swallow all click events
+     * (use for setting cursor). */
+    if (ED_space_image_show_uvedit(sima, obedit)) {
       return false;
     }
-
-    return space_image_main_region_poll(C);
   }
-  else {
+  else if (sima->mode != SI_MODE_VIEW) {
     return false;
   }
+
+  return true;
 }
 /********************** view pan operator *********************/
 
@@ -355,15 +377,6 @@ static int image_view_pan_exec(bContext *C, wmOperator *op)
 
   ED_region_tag_redraw(CTX_wm_region(C));
 
-  /* XXX notifier? */
-#if 0
-  if (image_preview_active(curarea, NULL, NULL)) {
-    /* recalculates new preview rect */
-    scrarea_do_windraw(curarea);
-    image_preview_event(2);
-  }
-#endif
-
   return OPERATOR_FINISHED;
 }
 
@@ -520,15 +533,6 @@ static int image_view_zoom_exec(bContext *C, wmOperator *op)
 
   ED_region_tag_redraw(ar);
 
-  /* XXX notifier? */
-#if 0
-  if (image_preview_active(curarea, NULL, NULL)) {
-    /* recalculates new preview rect */
-    scrarea_do_windraw(curarea);
-    image_preview_event(2);
-  }
-#endif
-
   return OPERATOR_FINISHED;
 }
 
@@ -596,7 +600,7 @@ static void image_zoom_apply(ViewZoomData *vpd,
     zfac = 1.0f + ((fac / 20.0f) * time_step);
     vpd->timer_lastdraw = time;
     /* this is the final zoom, but instead make it into a factor */
-    //zoom = vpd->sima->zoom * zfac;
+    // zoom = vpd->sima->zoom * zfac;
     factor = (vpd->sima->zoom * zfac) / vpd->zoom;
   }
   else {
@@ -1005,15 +1009,6 @@ static int image_view_zoom_ratio_exec(bContext *C, wmOperator *op)
   sima->xof = (int)sima->xof;
   sima->yof = (int)sima->yof;
 
-  /* XXX notifier? */
-#if 0
-  if (image_preview_active(curarea, NULL, NULL)) {
-    /* recalculates new preview rect */
-    scrarea_do_windraw(curarea);
-    image_preview_event(2);
-  }
-#endif
-
   ED_region_tag_redraw(ar);
 
   return OPERATOR_FINISHED;
@@ -1143,9 +1138,10 @@ static void image_open_cancel(bContext *UNUSED(C), wmOperator *op)
 }
 
 /**
- * \brief Get a list of frames from the list of image files matching the first file name sequence pattern
- * \param ptr: [in] the RNA pointer containing the "directory" entry and "files" collection
- * \param frames_all: [out] the list of frame numbers found in the files matching the first one by name
+ * Get a list of frames from the list of image files matching the first file name sequence pattern.
+ * \param ptr[in]: The RNA pointer containing the "directory" entry and "files" collection.
+ * \param frames_all[out]: the list of frame numbers found in the files matching
+ * the first one by name.
  */
 static void image_sequence_get_frame_ranges(PointerRNA *ptr, ListBase *frames_all)
 {
@@ -1200,7 +1196,8 @@ static int image_cmp_frame(const void *a, const void *b)
 }
 
 /**
- * Return the start (offset) and the length of the sequence of continuous frames in the list of frames
+ * Return the start (offset) and the length of the sequence of
+ * continuous frames in the list of frames.
  *
  * \param frames: [in] the list of frame numbers, as a side-effect the list is sorted.
  * \param ofs: [out] offset the first frame number in the sequence.
@@ -1359,7 +1356,7 @@ static int image_open_exec(bContext *C, wmOperator *op)
 
     PointerRNA imaptr;
     RNA_id_pointer_create(&ima->id, &imaptr);
-    RNA_property_pointer_set(&iod->pprop.ptr, iod->pprop.prop, imaptr);
+    RNA_property_pointer_set(NULL, &iod->pprop.ptr, iod->pprop.prop, imaptr);
     RNA_property_update(C, &iod->pprop.ptr, iod->pprop.prop);
   }
 
@@ -1544,21 +1541,16 @@ void IMAGE_OT_open(wmOperatorType *ot)
 static int image_match_len_exec(bContext *C, wmOperator *UNUSED(op))
 {
   Scene *scene = CTX_data_scene(C);
-  Image *ima = CTX_data_pointer_get_type(C, "edit_image", &RNA_Image).data;
-  ImageUser *iuser = CTX_data_pointer_get_type(C, "edit_image_user", &RNA_ImageUser).data;
+  Image *ima = image_from_context(C);
+  ImageUser *iuser = image_user_from_context(C);
 
   if (!ima || !iuser) {
     /* Try to get a Texture, or a SpaceImage from context... */
-    SpaceImage *sima = CTX_wm_space_image(C);
     Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data;
     if (tex && tex->type == TEX_IMAGE) {
       ima = tex->ima;
       iuser = &tex->iuser;
     }
-    else if (sima) {
-      ima = sima->image;
-      iuser = &sima->iuser;
-    }
   }
 
   if (!ima || !iuser || !BKE_image_has_anim(ima)) {
@@ -1678,35 +1670,6 @@ void IMAGE_OT_replace(wmOperatorType *ot)
 
 /******************** save image as operator ********************/
 
-typedef struct {
-  /* Context within which image is saved. */
-  Main *bmain;
-  Scene *scene;
-
-  /* Matching scene->r settings */
-  ImageFormatData im_format;
-  char filepath[FILE_MAX]; /* keep absolute */
-
-  bool relative;
-  bool save_copy;
-  bool save_as_render;
-  bool do_newpath;
-} SaveImageOptions;
-
-static void save_image_options_defaults(SaveImageOptions *simopts, Main *bmain, Scene *scene)
-{
-  simopts->bmain = bmain;
-  simopts->scene = scene;
-
-  BKE_imformat_defaults(&simopts->im_format);
-  simopts->filepath[0] = '\0';
-
-  simopts->relative = false;
-  simopts->save_copy = false;
-  simopts->save_as_render = false;
-  simopts->do_newpath = false;
-}
-
 static char imtype_best_depth(ImBuf *ibuf, const char imtype)
 {
   const char depth_ok = BKE_imtype_valid_depths(imtype);
@@ -1746,8 +1709,8 @@ static char imtype_best_depth(ImBuf *ibuf, const char imtype)
   }
 }
 
-static int save_image_options_init(Main *bmain,
-                                   SaveImageOptions *simopts,
+static int image_save_options_init(Main *bmain,
+                                   ImageSaveOptions *opts,
                                    Image *ima,
                                    ImageUser *iuser,
                                    const bool guess_path,
@@ -1757,80 +1720,79 @@ static int save_image_options_init(Main *bmain,
   ImBuf *ibuf = BKE_image_acquire_ibuf(ima, iuser, &lock);
 
   if (ibuf) {
-    Scene *scene = simopts->scene;
+    Scene *scene = opts->scene;
     bool is_depth_set = false;
 
     if (ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE)) {
       /* imtype */
-      simopts->im_format = scene->r.im_format;
+      opts->im_format = scene->r.im_format;
       is_depth_set = true;
       if (!BKE_image_is_multiview(ima)) {
         /* In case multiview is disabled,
          * render settings would be invalid for render result in this area. */
-        simopts->im_format.stereo3d_format = *ima->stereo3d_format;
-        simopts->im_format.views_format = ima->views_format;
+        opts->im_format.stereo3d_format = *ima->stereo3d_format;
+        opts->im_format.views_format = ima->views_format;
       }
     }
     else {
       if (ima->source == IMA_SRC_GENERATED) {
-        simopts->im_format.imtype = R_IMF_IMTYPE_PNG;
-        simopts->im_format.compress = ibuf->foptions.quality;
-        simopts->im_format.planes = ibuf->planes;
+        opts->im_format.imtype = R_IMF_IMTYPE_PNG;
+        opts->im_format.compress = ibuf->foptions.quality;
+        opts->im_format.planes = ibuf->planes;
       }
       else {
-        BKE_imbuf_to_image_format(&simopts->im_format, ibuf);
+        BKE_imbuf_to_image_format(&opts->im_format, ibuf);
       }
 
       /* use the multiview image settings as the default */
-      simopts->im_format.stereo3d_format = *ima->stereo3d_format;
-      simopts->im_format.views_format = ima->views_format;
+      opts->im_format.stereo3d_format = *ima->stereo3d_format;
+      opts->im_format.views_format = ima->views_format;
     }
 
     ///* XXX - this is lame, we need to make these available too! */
-    //simopts->subimtype = scene->r.subimtype;
+    // opts->subimtype = scene->r.subimtype;
 
-    BLI_strncpy(simopts->filepath, ibuf->name, sizeof(simopts->filepath));
+    BLI_strncpy(opts->filepath, ibuf->name, sizeof(opts->filepath));
 
     /* sanitize all settings */
 
     /* unlikely but just in case */
-    if (ELEM(simopts->im_format.planes, R_IMF_PLANES_BW, R_IMF_PLANES_RGB, R_IMF_PLANES_RGBA) ==
-        0) {
-      simopts->im_format.planes = R_IMF_PLANES_RGBA;
+    if (ELEM(opts->im_format.planes, R_IMF_PLANES_BW, R_IMF_PLANES_RGB, R_IMF_PLANES_RGBA) == 0) {
+      opts->im_format.planes = R_IMF_PLANES_RGBA;
     }
 
     /* depth, account for float buffer and format support */
     if (is_depth_set == false) {
-      simopts->im_format.depth = imtype_best_depth(ibuf, simopts->im_format.imtype);
+      opts->im_format.depth = imtype_best_depth(ibuf, opts->im_format.imtype);
     }
 
     /* some formats don't use quality so fallback to scenes quality */
-    if (simopts->im_format.quality == 0) {
-      simopts->im_format.quality = scene->r.im_format.quality;
+    if (opts->im_format.quality == 0) {
+      opts->im_format.quality = scene->r.im_format.quality;
     }
 
     /* check for empty path */
-    if (guess_path && simopts->filepath[0] == 0) {
+    if (guess_path && opts->filepath[0] == 0) {
       const bool is_prev_save = !STREQ(G.ima, "//");
       if (save_as_render) {
         if (is_prev_save) {
-          BLI_strncpy(simopts->filepath, G.ima, sizeof(simopts->filepath));
+          BLI_strncpy(opts->filepath, G.ima, sizeof(opts->filepath));
         }
         else {
-          BLI_strncpy(simopts->filepath, "//untitled", sizeof(simopts->filepath));
-          BLI_path_abs(simopts->filepath, BKE_main_blendfile_path(bmain));
+          BLI_strncpy(opts->filepath, "//untitled", sizeof(opts->filepath));
+          BLI_path_abs(opts->filepath, BKE_main_blendfile_path(bmain));
         }
       }
       else {
-        BLI_snprintf(simopts->filepath, sizeof(simopts->filepath), "//%s", ima->id.name + 2);
-        BLI_path_abs(simopts->filepath, is_prev_save ? G.ima : BKE_main_blendfile_path(bmain));
+        BLI_snprintf(opts->filepath, sizeof(opts->filepath), "//%s", ima->id.name + 2);
+        BLI_path_abs(opts->filepath, is_prev_save ? G.ima : BKE_main_blendfile_path(bmain));
       }
     }
 
     /* color management */
-    BKE_color_managed_display_settings_copy(&simopts->im_format.display_settings,
+    BKE_color_managed_display_settings_copy(&opts->im_format.display_settings,
                                             &scene->display_settings);
-    BKE_color_managed_view_settings_copy(&simopts->im_format.view_settings, &scene->view_settings);
+    BKE_color_managed_view_settings_copy(&opts->im_format.view_settings, &scene->view_settings);
   }
 
   BKE_image_release_ibuf(ima, ibuf, lock);
@@ -1838,391 +1800,52 @@ static int save_image_options_init(Main *bmain,
   return (ibuf != NULL);
 }
 
-static void save_image_options_from_op(Main *bmain, SaveImageOptions *simopts, wmOperator *op)
+static void image_save_options_from_op(Main *bmain, ImageSaveOptions *opts, wmOperator *op)
 {
   if (op->customdata) {
-    BKE_color_managed_view_settings_free(&simopts->im_format.view_settings);
+    BKE_color_managed_view_settings_free(&opts->im_format.view_settings);
 
-    simopts->im_format = *(ImageFormatData *)op->customdata;
+    opts->im_format = *(ImageFormatData *)op->customdata;
   }
 
   if (RNA_struct_property_is_set(op->ptr, "filepath")) {
-    RNA_string_get(op->ptr, "filepath", simopts->filepath);
-    BLI_path_abs(simopts->filepath, BKE_main_blendfile_path(bmain));
+    RNA_string_get(op->ptr, "filepath", opts->filepath);
+    BLI_path_abs(opts->filepath, BKE_main_blendfile_path(bmain));
   }
 }
 
-static void save_image_options_to_op(SaveImageOptions *simopts, wmOperator *op)
+static void image_save_options_to_op(ImageSaveOptions *opts, wmOperator *op)
 {
   if (op->customdata) {
     BKE_color_managed_view_settings_free(&((ImageFormatData *)op->customdata)->view_settings);
 
-    *(ImageFormatData *)op->customdata = simopts->im_format;
-  }
-
-  RNA_string_set(op->ptr, "filepath", simopts->filepath);
-}
-
-static void save_image_post(ReportList *reports,
-                            Main *bmain,
-                            Image *ima,
-                            ImBuf *ibuf,
-                            int ok,
-                            SaveImageOptions *simopts,
-                            int save_copy,
-                            const char *filepath)
-{
-  if (!ok) {
-    BKE_reportf(reports, RPT_ERROR, "Could not write image: %s", strerror(errno));
-    return;
-  }
-
-  if (save_copy) {
-    return;
+    *(ImageFormatData *)op->customdata = opts->im_format;
   }
 
-  if (simopts->do_newpath) {
-    BLI_strncpy(ibuf->name, filepath, sizeof(ibuf->name));
-    BLI_strncpy(ima->name, filepath, sizeof(ima->name));
-  }
-
-  ibuf->userflags &= ~IB_BITMAPDIRTY;
-
-  /* change type? */
-  if (ima->type == IMA_TYPE_R_RESULT) {
-    ima->type = IMA_TYPE_IMAGE;
-
-    /* workaround to ensure the render result buffer is no longer used
-         * by this image, otherwise can crash when a new render result is
-         * created. */
-    if (ibuf->rect && !(ibuf->mall & IB_rect)) {
-      imb_freerectImBuf(ibuf);
-    }
-    if (ibuf->rect_float && !(ibuf->mall & IB_rectfloat)) {
-      imb_freerectfloatImBuf(ibuf);
-    }
-    if (ibuf->zbuf && !(ibuf->mall & IB_zbuf)) {
-      IMB_freezbufImBuf(ibuf);
-    }
-    if (ibuf->zbuf_float && !(ibuf->mall & IB_zbuffloat)) {
-      IMB_freezbuffloatImBuf(ibuf);
-    }
-  }
-  if (ELEM(ima->source, IMA_SRC_GENERATED, IMA_SRC_VIEWER)) {
-    ima->source = IMA_SRC_FILE;
-    ima->type = IMA_TYPE_IMAGE;
-  }
-
-  /* only image path, never ibuf */
-  if (simopts->relative) {
-    const char *relbase = ID_BLEND_PATH(simopts->bmain, &ima->id);
-    BLI_path_rel(ima->name, relbase); /* only after saving */
-  }
-
-  ColorManagedColorspaceSettings old_colorspace_settings;
-  BKE_color_managed_colorspace_settings_copy(&old_colorspace_settings, &ima->colorspace_settings);
-  IMB_colormanagement_colorspace_from_ibuf_ftype(&ima->colorspace_settings, ibuf);
-  if (!BKE_color_managed_colorspace_settings_equals(&old_colorspace_settings,
-                                                    &ima->colorspace_settings)) {
-    BKE_image_signal(bmain, ima, NULL, IMA_SIGNAL_COLORMANAGE);
-  }
+  RNA_string_set(op->ptr, "filepath", opts->filepath);
 }
 
-static void save_imbuf_post(ImBuf *ibuf, ImBuf *colormanaged_ibuf)
-{
-  if (colormanaged_ibuf != ibuf) {
-    /* This guys might be modified by image buffer write functions,
-     * need to copy them back from color managed image buffer to an
-     * original one, so file type of image is being properly updated.
-     */
-    ibuf->ftype = colormanaged_ibuf->ftype;
-    ibuf->foptions = colormanaged_ibuf->foptions;
-    ibuf->planes = colormanaged_ibuf->planes;
-
-    IMB_freeImBuf(colormanaged_ibuf);
-  }
-}
-
-/**
- * \return success.
- * \note ``ima->name`` and ``ibuf->name`` should end up the same.
- * \note for multiview the first ``ibuf`` is important to get the settings.
- */
-static bool save_image_doit(
-    ReportList *reports, Main *bmain, Image *ima, ImageUser *iuser, SaveImageOptions *simopts)
-{
-  void *lock;
-  ImBuf *ibuf = BKE_image_acquire_ibuf(ima, iuser, &lock);
-  RenderResult *rr = NULL;
-  bool ok = false;
-
-  if (ibuf == NULL || (ibuf->rect == NULL && ibuf->rect_float == NULL)) {
-    BKE_image_release_ibuf(ima, ibuf, &lock);
-    goto cleanup;
-  }
-
-  ImBuf *colormanaged_ibuf = NULL;
-  const bool save_copy = simopts->save_copy;
-  const bool save_as_render = simopts->save_as_render;
-  ImageFormatData *imf = &simopts->im_format;
-
-  if (ima->type == IMA_TYPE_R_RESULT) {
-    /* enforce user setting for RGB or RGBA, but skip BW */
-    if (simopts->im_format.planes == R_IMF_PLANES_RGBA) {
-      ibuf->planes = R_IMF_PLANES_RGBA;
-    }
-    else if (simopts->im_format.planes == R_IMF_PLANES_RGB) {
-      ibuf->planes = R_IMF_PLANES_RGB;
-    }
-  }
-  else {
-    /* TODO, better solution, if a 24bit image is painted onto it may contain alpha */
-    if ((simopts->im_format.planes == R_IMF_PLANES_RGBA) &&
-        /* it has been painted onto */
-        (ibuf->userflags & IB_BITMAPDIRTY)) {
-      /* checks each pixel, not ideal */
-      ibuf->planes = BKE_imbuf_alpha_test(ibuf) ? R_IMF_PLANES_RGBA : R_IMF_PLANES_RGB;
-    }
-  }
-
-  /* we need renderresult for exr and rendered multiview */
-  rr = BKE_image_acquire_renderresult(simopts->scene, ima);
-  bool is_mono = rr ? BLI_listbase_count_at_most(&rr->views, 2) < 2 :
-                      BLI_listbase_count_at_most(&ima->views, 2) < 2;
-  bool is_exr_rr = rr && ELEM(imf->imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER) &&
-                   RE_HasFloatPixels(rr);
-  bool is_multilayer = is_exr_rr && (imf->imtype == R_IMF_IMTYPE_MULTILAYER);
-  int layer = (iuser && !is_multilayer) ? iuser->layer : -1;
-
-  /* error handling */
-  if (!rr) {
-    if (imf->imtype == R_IMF_IMTYPE_MULTILAYER) {
-      BKE_report(reports, RPT_ERROR, "Did not write, no Multilayer Image");
-      BKE_image_release_ibuf(ima, ibuf, &lock);
-      goto cleanup;
-    }
-  }
-  else {
-    if (imf->views_format == R_IMF_VIEWS_STEREO_3D) {
-      if (!BKE_image_is_stereo(ima)) {
-        BKE_reportf(reports,
-                    RPT_ERROR,
-                    "Did not write, the image doesn't have a \"%s\" and \"%s\" views",
-                    STEREO_LEFT_NAME,
-                    STEREO_RIGHT_NAME);
-        BKE_image_release_ibuf(ima, ibuf, &lock);
-        goto cleanup;
-      }
-
-      /* it shouldn't ever happen*/
-      if ((BLI_findstring(&rr->views, STEREO_LEFT_NAME, offsetof(RenderView, name)) == NULL) ||
-          (BLI_findstring(&rr->views, STEREO_RIGHT_NAME, offsetof(RenderView, name)) == NULL)) {
-        BKE_reportf(reports,
-                    RPT_ERROR,
-                    "Did not write, the image doesn't have a \"%s\" and \"%s\" views",
-                    STEREO_LEFT_NAME,
-                    STEREO_RIGHT_NAME);
-        BKE_image_release_ibuf(ima, ibuf, &lock);
-        goto cleanup;
-      }
-    }
-    BKE_imbuf_stamp_info(rr, ibuf);
-  }
-
-  /* fancy multiview OpenEXR */
-  if (imf->views_format == R_IMF_VIEWS_MULTIVIEW && is_exr_rr) {
-    /* save render result */
-    ok = RE_WriteRenderResult(reports, rr, simopts->filepath, imf, NULL, layer);
-    save_image_post(reports, bmain, ima, ibuf, ok, simopts, true, simopts->filepath);
-    BKE_image_release_ibuf(ima, ibuf, &lock);
-  }
-  /* regular mono pipeline */
-  else if (is_mono) {
-    if (is_exr_rr) {
-      ok = RE_WriteRenderResult(reports, rr, simopts->filepath, imf, NULL, layer);
-    }
-    else {
-      colormanaged_ibuf = IMB_colormanagement_imbuf_for_write(
-          ibuf, save_as_render, true, &imf->view_settings, &imf->display_settings, imf);
-      ok = BKE_imbuf_write_as(colormanaged_ibuf, simopts->filepath, imf, save_copy);
-      save_imbuf_post(ibuf, colormanaged_ibuf);
-    }
-    save_image_post(
-        reports, bmain, ima, ibuf, ok, simopts, (is_exr_rr ? true : save_copy), simopts->filepath);
-    BKE_image_release_ibuf(ima, ibuf, &lock);
-  }
-  /* individual multiview images */
-  else if (imf->views_format == R_IMF_VIEWS_INDIVIDUAL) {
-    int i;
-    unsigned char planes = ibuf->planes;
-    const int totviews = (rr ? BLI_listbase_count(&rr->views) : BLI_listbase_count(&ima->views));
-
-    if (!is_exr_rr) {
-      BKE_image_release_ibuf(ima, ibuf, &lock);
-    }
-
-    for (i = 0; i < totviews; i++) {
-      char filepath[FILE_MAX];
-      bool ok_view = false;
-      const char *view = rr ? ((RenderView *)BLI_findlink(&rr->views, i))->name :
-                              ((ImageView *)BLI_findlink(&ima->views, i))->name;
-
-      if (is_exr_rr) {
-        BKE_scene_multiview_view_filepath_get(
-            &simopts->scene->r, simopts->filepath, view, filepath);
-        ok_view = RE_WriteRenderResult(reports, rr, filepath, imf, view, layer);
-        save_image_post(reports, bmain, ima, ibuf, ok_view, simopts, true, filepath);
-      }
-      else {
-        /* copy iuser to get the correct ibuf for this view */
-        ImageUser view_iuser;
-
-        if (iuser) {
-          /* copy iuser to get the correct ibuf for this view */
-          view_iuser = *iuser;
-        }
-        else {
-          BKE_imageuser_default(&view_iuser);
-        }
-
-        view_iuser.view = i;
-        view_iuser.flag &= ~IMA_SHOW_STEREO;
-
-        if (rr) {
-          BKE_image_multilayer_index(rr, &view_iuser);
-        }
-        else {
-          BKE_image_multiview_index(ima, &view_iuser);
-        }
-
-        ibuf = BKE_image_acquire_ibuf(ima, &view_iuser, &lock);
-        ibuf->planes = planes;
-
-        BKE_scene_multiview_view_filepath_get(
-            &simopts->scene->r, simopts->filepath, view, filepath);
-
-        colormanaged_ibuf = IMB_colormanagement_imbuf_for_write(
-            ibuf, save_as_render, true, &imf->view_settings, &imf->display_settings, imf);
-        ok_view = BKE_imbuf_write_as(colormanaged_ibuf, filepath, &simopts->im_format, save_copy);
-        save_imbuf_post(ibuf, colormanaged_ibuf);
-        save_image_post(reports, bmain, ima, ibuf, ok_view, simopts, true, filepath);
-        BKE_image_release_ibuf(ima, ibuf, lock);
-      }
-      ok &= ok_view;
-    }
-
-    if (is_exr_rr) {
-      BKE_image_release_ibuf(ima, ibuf, &lock);
-    }
-  }
-  /* stereo (multiview) images */
-  else if (simopts->im_format.views_format == R_IMF_VIEWS_STEREO_3D) {
-    if (imf->imtype == R_IMF_IMTYPE_MULTILAYER) {
-      ok = RE_WriteRenderResult(reports, rr, simopts->filepath, imf, NULL, layer);
-      save_image_post(reports, bmain, ima, ibuf, ok, simopts, true, simopts->filepath);
-      BKE_image_release_ibuf(ima, ibuf, &lock);
-    }
-    else {
-      ImBuf *ibuf_stereo[2] = {NULL};
-
-      unsigned char planes = ibuf->planes;
-      const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};
-      int i;
-
-      /* we need to get the specific per-view buffers */
-      BKE_image_release_ibuf(ima, ibuf, &lock);
-
-      for (i = 0; i < 2; i++) {
-        ImageUser view_iuser;
-
-        if (iuser) {
-          view_iuser = *iuser;
-        }
-        else {
-          BKE_imageuser_default(&view_iuser);
-        }
-
-        view_iuser.flag &= ~IMA_SHOW_STEREO;
-
-        if (rr) {
-          int id = BLI_findstringindex(&rr->views, names[i], offsetof(RenderView, name));
-          view_iuser.view = id;
-          BKE_image_multilayer_index(rr, &view_iuser);
-        }
-        else {
-          view_iuser.view = i;
-          BKE_image_multiview_index(ima, &view_iuser);
-        }
-
-        ibuf = BKE_image_acquire_ibuf(ima, &view_iuser, &lock);
-
-        if (ibuf == NULL) {
-          BKE_report(
-              reports, RPT_ERROR, "Did not write, unexpected error when saving stereo image");
-          goto cleanup;
-        }
-
-        ibuf->planes = planes;
-
-        /* color manage the ImBuf leaving it ready for saving */
-        colormanaged_ibuf = IMB_colormanagement_imbuf_for_write(
-            ibuf, save_as_render, true, &imf->view_settings, &imf->display_settings, imf);
-
-        BKE_imbuf_write_prepare(colormanaged_ibuf, imf);
-        IMB_prepare_write_ImBuf(IMB_isfloat(colormanaged_ibuf), colormanaged_ibuf);
-
-        /* duplicate buffer to prevent locker issue when using render result */
-        ibuf_stereo[i] = IMB_dupImBuf(colormanaged_ibuf);
-
-        save_imbuf_post(ibuf, colormanaged_ibuf);
-        BKE_image_release_ibuf(ima, ibuf, lock);
-      }
-
-      ibuf = IMB_stereo3d_ImBuf(imf, ibuf_stereo[0], ibuf_stereo[1]);
-
-      /* save via traditional path */
-      ok = BKE_imbuf_write_as(ibuf, simopts->filepath, imf, save_copy);
-
-      IMB_freeImBuf(ibuf);
-
-      for (i = 0; i < 2; i++) {
-        IMB_freeImBuf(ibuf_stereo[i]);
-      }
-    }
-  }
-
-cleanup:
-  if (rr) {
-    BKE_image_release_renderresult(simopts->scene, ima);
-  }
-
-  return ok;
-}
-
-static bool save_image_op(const bContext *C,
-                          SpaceImage *sima,
-                          wmOperator *op,
-                          SaveImageOptions *simopts)
+static bool save_image_op(const bContext *C, wmOperator *op, ImageSaveOptions *opts)
 {
   Main *bmain = CTX_data_main(C);
-  Image *ima = ED_space_image(sima);
-  ImageUser *iuser = &sima->iuser;
+  Image *ima = image_from_context(C);
+  ImageUser *iuser = image_user_from_context(C);
 
-  simopts->relative = (RNA_struct_find_property(op->ptr, "relative_path") &&
-                       RNA_boolean_get(op->ptr, "relative_path"));
-  simopts->save_copy = (RNA_struct_find_property(op->ptr, "copy") &&
-                        RNA_boolean_get(op->ptr, "copy"));
-  simopts->save_as_render = (RNA_struct_find_property(op->ptr, "save_as_render") &&
-                             RNA_boolean_get(op->ptr, "save_as_render"));
+  opts->relative = (RNA_struct_find_property(op->ptr, "relative_path") &&
+                    RNA_boolean_get(op->ptr, "relative_path"));
+  opts->save_copy = (RNA_struct_find_property(op->ptr, "copy") &&
+                     RNA_boolean_get(op->ptr, "copy"));
+  opts->save_as_render = (RNA_struct_find_property(op->ptr, "save_as_render") &&
+                          RNA_boolean_get(op->ptr, "save_as_render"));
 
   WM_cursor_wait(1);
 
-  bool ok = save_image_doit(op->reports, bmain, ima, iuser, simopts);
+  bool ok = BKE_image_save(op->reports, bmain, ima, iuser, opts);
 
   WM_cursor_wait(0);
 
   /* Remember file path for next save. */
-  BLI_strncpy(G.ima, simopts->filepath, sizeof(G.ima));
+  BLI_strncpy(G.ima, opts->filepath, sizeof(G.ima));
 
   WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
 
@@ -2244,19 +1867,20 @@ static int image_save_as_exec(bContext *C, wmOperator *op)
 {
   Main *bmain = CTX_data_main(C);
   Scene *scene = CTX_data_scene(C);
-  SpaceImage *sima = CTX_wm_space_image(C);
-  SaveImageOptions simopts;
+  Image *image = image_from_context(C);
+  ImageUser *iuser = image_user_from_context(C);
+  ImageSaveOptions opts;
 
-  save_image_options_defaults(&simopts, bmain, scene);
+  BKE_image_save_options_init(&opts, bmain, scene);
 
   /* just in case to initialize values,
    * these should be set on invoke or by the caller. */
-  save_image_options_init(bmain, &simopts, sima->image, &sima->iuser, false, false);
+  image_save_options_init(bmain, &opts, image, iuser, false, false);
 
-  save_image_options_from_op(bmain, &simopts, op);
-  simopts.do_newpath = true;
+  image_save_options_from_op(bmain, &opts, op);
+  opts.do_newpath = true;
 
-  save_image_op(C, sima, op, &simopts);
+  save_image_op(C, op, &opts);
 
   image_save_as_free(op);
   return OPERATOR_FINISHED;
@@ -2271,10 +1895,10 @@ static bool image_save_as_check(bContext *UNUSED(C), wmOperator *op)
 static int image_save_as_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
 {
   Main *bmain = CTX_data_main(C);
-  SpaceImage *sima = CTX_wm_space_image(C);
-  Image *ima = ED_space_image(sima);
+  Image *ima = image_from_context(C);
+  ImageUser *iuser = image_user_from_context(C);
   Scene *scene = CTX_data_scene(C);
-  SaveImageOptions simopts;
+  ImageSaveOptions opts;
   PropertyRNA *prop;
   const bool save_as_render = ((ima->source == IMA_SRC_VIEWER) ||
                                (ima->flag & IMA_VIEW_AS_RENDER));
@@ -2283,12 +1907,12 @@ static int image_save_as_invoke(bContext *C, wmOperator *op, const wmEvent *UNUS
     return image_save_as_exec(C, op);
   }
 
-  save_image_options_defaults(&simopts, bmain, scene);
+  BKE_image_save_options_init(&opts, bmain, scene);
 
-  if (save_image_options_init(bmain, &simopts, ima, &sima->iuser, true, save_as_render) == 0) {
+  if (image_save_options_init(bmain, &opts, ima, iuser, true, save_as_render) == 0) {
     return OPERATOR_CANCELLED;
   }
-  save_image_options_to_op(&simopts, op);
+  image_save_options_to_op(&opts, op);
 
   /* enable save_copy by default for render results */
   if (ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE) &&
@@ -2298,8 +1922,8 @@ static int image_save_as_invoke(bContext *C, wmOperator *op, const wmEvent *UNUS
 
   RNA_boolean_set(op->ptr, "save_as_render", save_as_render);
 
-  op->customdata = MEM_mallocN(sizeof(simopts.im_format), __func__);
-  memcpy(op->customdata, &simopts.im_format, sizeof(simopts.im_format));
+  op->customdata = MEM_mallocN(sizeof(opts.im_format), __func__);
+  memcpy(op->customdata, &opts.im_format, sizeof(opts.im_format));
 
   /* show multiview save options only if image has multiviews */
   prop = RNA_struct_find_property(op->ptr, "show_multiview");
@@ -2307,7 +1931,7 @@ static int image_save_as_invoke(bContext *C, wmOperator *op, const wmEvent *UNUS
   prop = RNA_struct_find_property(op->ptr, "use_multiview");
   RNA_property_boolean_set(op->ptr, prop, BKE_image_is_multiview(ima));
 
-  image_filesel(C, op, simopts.filepath);
+  image_filesel(C, op, opts.filepath);
 
   return OPERATOR_RUNNING_MODAL;
 }
@@ -2353,20 +1977,21 @@ static void image_save_as_draw(bContext *UNUSED(C), wmOperator *op)
 
 static bool image_save_as_poll(bContext *C)
 {
-  if (space_image_buffer_exists_poll(C)) {
-    if (G.is_rendering) {
-      /* no need to NULL check here */
-      SpaceImage *sima = CTX_wm_space_image(C);
-      Image *ima = ED_space_image(sima);
+  if (!image_buffer_exists_from_context(C)) {
+    return false;
+  }
 
-      if (ima->source == IMA_SRC_VIEWER) {
-        CTX_wm_operator_poll_msg_set(C, "can't save image while rendering");
-        return false;
-      }
+  if (G.is_rendering) {
+    /* no need to NULL check here */
+    Image *ima = image_from_context(C);
+
+    if (ima->source == IMA_SRC_VIEWER) {
+      CTX_wm_operator_poll_msg_set(C, "can't save image while rendering");
+      return false;
     }
-    return true;
   }
-  return false;
+
+  return true;
 }
 
 void IMAGE_OT_save_as(wmOperatorType *ot)
@@ -2413,31 +2038,43 @@ void IMAGE_OT_save_as(wmOperatorType *ot)
 static int image_save_exec(bContext *C, wmOperator *op)
 {
   Main *bmain = CTX_data_main(C);
-  SpaceImage *sima = CTX_wm_space_image(C);
+  Image *image = image_from_context(C);
+  ImageUser *iuser = image_user_from_context(C);
   Scene *scene = CTX_data_scene(C);
-  SaveImageOptions simopts;
+  ImageSaveOptions opts;
 
-  save_image_options_defaults(&simopts, bmain, scene);
-  if (save_image_options_init(bmain, &simopts, sima->image, &sima->iuser, false, false) == 0) {
+  BKE_image_save_options_init(&opts, bmain, scene);
+  if (image_save_options_init(bmain, &opts, image, iuser, false, false) == 0) {
     return OPERATOR_CANCELLED;
   }
-  save_image_options_from_op(bmain, &simopts, op);
+  image_save_options_from_op(bmain, &opts, op);
 
-  if (BLI_exists(simopts.filepath) && BLI_file_is_writable(simopts.filepath)) {
-    if (save_image_op(C, sima, op, &simopts)) {
+  if (BLI_exists(opts.filepath) && BLI_file_is_writable(opts.filepath)) {
+    if (save_image_op(C, op, &opts)) {
       /* report since this can be called from key-shortcuts */
-      BKE_reportf(op->reports, RPT_INFO, "Saved Image '%s'", simopts.filepath);
+      BKE_reportf(op->reports, RPT_INFO, "Saved Image '%s'", opts.filepath);
     }
   }
   else {
     BKE_reportf(
-        op->reports, RPT_ERROR, "Cannot save image, path '%s' is not writable", simopts.filepath);
+        op->reports, RPT_ERROR, "Cannot save image, path '%s' is not writable", opts.filepath);
     return OPERATOR_CANCELLED;
   }
 
   return OPERATOR_FINISHED;
 }
 
+static int image_save_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
+{
+  if (space_image_file_exists_poll(C)) {
+    return image_save_exec(C, op);
+  }
+  else {
+    WM_operator_name_call(C, "IMAGE_OT_save_as", WM_OP_INVOKE_DEFAULT, NULL);
+    return OPERATOR_CANCELLED;
+  }
+}
+
 void IMAGE_OT_save(wmOperatorType *ot)
 {
   /* identifiers */
@@ -2447,7 +2084,8 @@ void IMAGE_OT_save(wmOperatorType *ot)
 
   /* api callbacks */
   ot->exec = image_save_exec;
-  ot->poll = space_image_file_exists_poll;
+  ot->invoke = image_save_invoke;
+  ot->poll = image_save_as_poll;
 
   /* flags */
   ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -2458,30 +2096,30 @@ void IMAGE_OT_save(wmOperatorType *ot)
 static int image_save_sequence_exec(bContext *C, wmOperator *op)
 {
   Main *bmain = CTX_data_main(C);
-  SpaceImage *sima = CTX_wm_space_image(C);
+  Image *image = image_from_context(C);
   ImBuf *ibuf, *first_ibuf = NULL;
   int tot = 0;
   char di[FILE_MAX];
   struct MovieCacheIter *iter;
 
-  if (sima->image == NULL) {
+  if (image == NULL) {
     return OPERATOR_CANCELLED;
   }
 
-  if (sima->image->source != IMA_SRC_SEQUENCE) {
+  if (image->source != IMA_SRC_SEQUENCE) {
     BKE_report(op->reports, RPT_ERROR, "Can only save sequence on image sequences");
     return OPERATOR_CANCELLED;
   }
 
-  if (sima->image->type == IMA_TYPE_MULTILAYER) {
+  if (image->type == IMA_TYPE_MULTILAYER) {
     BKE_report(op->reports, RPT_ERROR, "Cannot save multilayer sequences");
     return OPERATOR_CANCELLED;
   }
 
   /* get total dirty buffers and first dirty buffer which is used for menu */
   ibuf = NULL;
-  if (sima->image->cache != NULL) {
-    iter = IMB_moviecacheIter_new(sima->image->cache);
+  if (image->cache != NULL) {
+    iter = IMB_moviecacheIter_new(image->cache);
     while (!IMB_moviecacheIter_done(iter)) {
       ibuf = IMB_moviecacheIter_getImBuf(iter);
       if (ibuf->userflags & IB_BITMAPDIRTY) {
@@ -2504,7 +2142,7 @@ static int image_save_sequence_exec(bContext *C, wmOperator *op)
   BLI_split_dir_part(first_ibuf->name, di, sizeof(di));
   BKE_reportf(op->reports, RPT_INFO, "%d image(s) will be saved in %s", tot, di);
 
-  iter = IMB_moviecacheIter_new(sima->image->cache);
+  iter = IMB_moviecacheIter_new(image->cache);
   while (!IMB_moviecacheIter_done(iter)) {
     ibuf = IMB_moviecacheIter_getImBuf(iter);
 
@@ -2539,7 +2177,138 @@ void IMAGE_OT_save_sequence(wmOperatorType *ot)
 
   /* api callbacks */
   ot->exec = image_save_sequence_exec;
-  ot->poll = space_image_buffer_exists_poll;
+  ot->poll = image_buffer_exists_from_context;
+
+  /* flags */
+  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+}
+
+/********************** save all operator **********************/
+
+static bool image_should_be_saved_when_modified(Image *ima)
+{
+  return !ELEM(ima->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE);
+}
+
+static bool image_should_be_saved(Image *ima)
+{
+  if (BKE_image_is_dirty(ima) && (ima->source == IMA_SRC_FILE)) {
+    return image_should_be_saved_when_modified(ima);
+  }
+  else {
+    return false;
+  }
+}
+
+static bool image_has_valid_path(Image *ima)
+{
+  return strchr(ima->name, '\\') || strchr(ima->name, '/');
+}
+
+bool ED_image_should_save_modified(const bContext *C)
+{
+  return ED_image_save_all_modified_info(C, NULL) > 0;
+}
+
+int ED_image_save_all_modified_info(const bContext *C, ReportList *reports)
+{
+  Main *bmain = CTX_data_main(C);
+  GSet *unique_paths = BLI_gset_str_new(__func__);
+
+  int num_saveable_images = 0;
+
+  for (Image *ima = bmain->images.first; ima; ima = ima->id.next) {
+    if (image_should_be_saved(ima)) {
+      if (BKE_image_has_packedfile(ima)) {
+        if (ima->id.lib == NULL) {
+          num_saveable_images++;
+        }
+        else {
+          BKE_reportf(reports,
+                      RPT_WARNING,
+                      "Packed library image: %s from library %s can't be saved",
+                      ima->id.name,
+                      ima->id.lib->name);
+        }
+      }
+      else {
+        if (image_has_valid_path(ima)) {
+          num_saveable_images++;
+          if (BLI_gset_haskey(unique_paths, ima->name)) {
+            BKE_reportf(reports,
+                        RPT_WARNING,
+                        "File path used by more than one saved image: %s",
+                        ima->name);
+          }
+          else {
+            BLI_gset_insert(unique_paths, BLI_strdup(ima->name));
+          }
+        }
+        else {
+          BKE_reportf(reports,
+                      RPT_WARNING,
+                      "Image %s can't be saved, no valid file path: %s",
+                      ima->id.name,
+                      ima->name);
+        }
+      }
+    }
+  }
+
+  BLI_gset_free(unique_paths, MEM_freeN);
+  return num_saveable_images;
+}
+
+bool ED_image_save_all_modified(const bContext *C, ReportList *reports)
+{
+  ED_image_save_all_modified_info(C, reports);
+
+  Main *bmain = CTX_data_main(C);
+  bool ok = true;
+
+  for (Image *ima = bmain->images.first; ima; ima = ima->id.next) {
+    if (image_should_be_saved(ima)) {
+      if (BKE_image_has_packedfile(ima)) {
+        BKE_image_memorypack(ima);
+      }
+      else {
+        if (image_has_valid_path(ima)) {
+          ImageSaveOptions opts;
+          Scene *scene = CTX_data_scene(C);
+          BKE_image_save_options_init(&opts, bmain, scene);
+          if (image_save_options_init(bmain, &opts, ima, NULL, false, false)) {
+            bool saved_successfully = BKE_image_save(reports, bmain, ima, NULL, &opts);
+            ok = ok && saved_successfully;
+          }
+        }
+      }
+    }
+  }
+  return ok;
+}
+
+static bool image_save_all_modified_poll(bContext *C)
+{
+  int num_files = ED_image_save_all_modified_info(C, NULL);
+  return num_files > 0;
+}
+
+static int image_save_all_modified_exec(bContext *C, wmOperator *op)
+{
+  ED_image_save_all_modified(C, op->reports);
+  return OPERATOR_FINISHED;
+}
+
+void IMAGE_OT_save_all_modified(wmOperatorType *ot)
+{
+  /* identifiers */
+  ot->name = "Save All Modified";
+  ot->idname = "IMAGE_OT_save_all_modified";
+  ot->description = "Save all modified images";
+
+  /* api callbacks */
+  ot->exec = image_save_all_modified_exec;
+  ot->poll = image_save_all_modified_poll;
 
   /* flags */
   ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -2550,8 +2319,8 @@ void IMAGE_OT_save_sequence(wmOperatorType *ot)
 static int image_reload_exec(bContext *C, wmOperator *UNUSED(op))
 {
   Main *bmain = CTX_data_main(C);
-  Image *ima = CTX_data_edit_image(C);
-  SpaceImage *sima = CTX_wm_space_image(C);
+  Image *ima = image_from_context(C);
+  ImageUser *iuser = image_user_from_context(C);
 
   if (!ima) {
     return OPERATOR_CANCELLED;
@@ -2560,7 +2329,7 @@ static int image_reload_exec(bContext *C, wmOperator *UNUSED(op))
   /* XXX unpackImage frees image buffers */
   ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
 
-  BKE_image_signal(bmain, ima, (sima) ? &sima->iuser : NULL, IMA_SIGNAL_RELOAD);
+  BKE_image_signal(bmain, ima, iuser, IMA_SIGNAL_RELOAD);
   DEG_id_tag_update(&ima->id, 0);
 
   WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
@@ -2672,7 +2441,7 @@ static int image_new_exec(bContext *C, wmOperator *op)
 
     PointerRNA imaptr;
     RNA_id_pointer_create(&ima->id, &imaptr);
-    RNA_property_pointer_set(&data->pprop.ptr, data->pprop.prop, imaptr);
+    RNA_property_pointer_set(NULL, &data->pprop.ptr, data->pprop.prop, imaptr);
     RNA_property_update(C, &data->pprop.ptr, data->pprop.prop);
   }
   else if (sima) {
@@ -2802,14 +2571,14 @@ void IMAGE_OT_new(wmOperatorType *ot)
 
 static bool image_invert_poll(bContext *C)
 {
-  Image *ima = CTX_data_edit_image(C);
+  Image *ima = image_from_context(C);
 
   return BKE_image_has_ibuf(ima, NULL);
 }
 
 static int image_invert_exec(bContext *C, wmOperator *op)
 {
-  Image *ima = CTX_data_edit_image(C);
+  Image *ima = image_from_context(C);
   ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
   SpaceImage *sima = CTX_wm_space_image(C);
   /* undo is supported only on image paint mode currently */
@@ -2882,7 +2651,8 @@ static int image_invert_exec(bContext *C, wmOperator *op)
     return OPERATOR_CANCELLED;
   }
 
-  ibuf->userflags |= IB_BITMAPDIRTY | IB_DISPLAY_BUFFER_INVALID;
+  ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
+  BKE_image_mark_dirty(ima, ibuf);
 
   if (ibuf->mipmap[0]) {
     ibuf->userflags |= IB_MIPMAP_INVALID;
@@ -2933,15 +2703,11 @@ void IMAGE_OT_invert(wmOperatorType *ot)
 
 static bool image_pack_test(bContext *C, wmOperator *op)
 {
-  Image *ima = CTX_data_edit_image(C);
-  const bool as_png = RNA_boolean_get(op->ptr, "as_png");
+  Image *ima = image_from_context(C);
 
   if (!ima) {
     return 0;
   }
-  if (!as_png && BKE_image_has_packedfile(ima)) {
-    return 0;
-  }
 
   if (ima->source == IMA_SRC_SEQUENCE || ima->source == IMA_SRC_MOVIE) {
     BKE_report(op->reports, RPT_ERROR, "Packing movies or image sequences not supported");
@@ -2954,20 +2720,13 @@ static bool image_pack_test(bContext *C, wmOperator *op)
 static int image_pack_exec(bContext *C, wmOperator *op)
 {
   struct Main *bmain = CTX_data_main(C);
-  Image *ima = CTX_data_edit_image(C);
-  ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
-  const bool as_png = RNA_boolean_get(op->ptr, "as_png");
+  Image *ima = image_from_context(C);
 
   if (!image_pack_test(C, op)) {
     return OPERATOR_CANCELLED;
   }
 
-  if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
-    BKE_report(op->reports, RPT_ERROR, "Cannot pack edited image from disk, only as internal PNG");
-    return OPERATOR_CANCELLED;
-  }
-
-  if (as_png) {
+  if (BKE_image_is_dirty(ima)) {
     BKE_image_memorypack(ima);
   }
   else {
@@ -2976,46 +2735,9 @@ static int image_pack_exec(bContext *C, wmOperator *op)
 
   WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
 
-  BKE_image_release_ibuf(ima, ibuf, NULL);
-
   return OPERATOR_FINISHED;
 }
 
-static int image_pack_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
-{
-  Image *ima = CTX_data_edit_image(C);
-  ImBuf *ibuf;
-  uiPopupMenu *pup;
-  uiLayout *layout;
-  const bool as_png = RNA_boolean_get(op->ptr, "as_png");
-
-  if (!image_pack_test(C, op)) {
-    return OPERATOR_CANCELLED;
-  }
-
-  ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
-
-  if (!as_png && (ibuf && (ibuf->userflags & IB_BITMAPDIRTY))) {
-    pup = UI_popup_menu_begin(C, IFACE_("OK"), ICON_QUESTION);
-    layout = UI_popup_menu_layout(pup);
-    uiItemBooleanO(layout,
-                   IFACE_("Can't pack edited image from disk, pack as internal PNG?"),
-                   ICON_NONE,
-                   op->idname,
-                   "as_png",
-                   1);
-    UI_popup_menu_end(C, pup);
-
-    BKE_image_release_ibuf(ima, ibuf, NULL);
-
-    return OPERATOR_INTERFACE;
-  }
-
-  BKE_image_release_ibuf(ima, ibuf, NULL);
-
-  return image_pack_exec(C, op);
-}
-
 void IMAGE_OT_pack(wmOperatorType *ot)
 {
   /* identifiers */
@@ -3025,20 +2747,16 @@ void IMAGE_OT_pack(wmOperatorType *ot)
 
   /* api callbacks */
   ot->exec = image_pack_exec;
-  ot->invoke = image_pack_invoke;
 
   /* flags */
   ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
-  /* properties */
-  RNA_def_boolean(ot->srna, "as_png", 0, "Pack As PNG", "Pack image as lossless PNG");
 }
 
 /********************* unpack operator *********************/
 
 static int image_unpack_exec(bContext *C, wmOperator *op)
 {
-  Image *ima = CTX_data_edit_image(C);
+  Image *ima = image_from_context(C);
   int method = RNA_enum_get(op->ptr, "method");
 
   /* find the suppplied image by name */
@@ -3047,7 +2765,7 @@ static int image_unpack_exec(bContext *C, wmOperator *op)
     RNA_string_get(op->ptr, "id", imaname);
     ima = BLI_findstring(&CTX_data_main(C)->images, imaname, offsetof(ID, name) + 2);
     if (!ima) {
-      ima = CTX_data_edit_image(C);
+      ima = image_from_context(C);
     }
   }
 
@@ -3078,7 +2796,7 @@ static int image_unpack_exec(bContext *C, wmOperator *op)
 
 static int image_unpack_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
 {
-  Image *ima = CTX_data_edit_image(C);
+  Image *ima = image_from_context(C);
 
   if (RNA_struct_property_is_set(op->ptr, "id")) {
     return image_unpack_exec(C, op);
@@ -3201,6 +2919,7 @@ static void image_sample_draw(const bContext *C, ARegion *ar, void *arg_info)
 
     glEnable(GL_COLOR_LOGIC_OP);
     glLogicOp(GL_XOR);
+    GPU_line_width(1.0f);
     imm_draw_box_wire_2d(pos,
                          (float)sample_rect_fl.xmin,
                          (float)sample_rect_fl.ymin,
@@ -3664,177 +3383,18 @@ void IMAGE_OT_curves_point_set(wmOperatorType *ot)
   RNA_def_property_flag(prop, PROP_SKIP_SAVE);
 }
 
-#if 0 /* Not ported to 2.5x yet */
-/******************** record composite operator *********************/
-
-typedef struct RecordCompositeData {
-  wmTimer *timer;
-  int old_cfra;
-  int sfra, efra;
-} RecordCompositeData;
-
-static int image_record_composite_apply(bContext *C, wmOperator *op)
-{
-  SpaceImage *sima = CTX_wm_space_image(C);
-  RecordCompositeData *rcd = op->customdata;
-  Scene *scene = CTX_data_scene(C);
-  ImBuf *ibuf;
-
-  WM_cursor_time(CTX_wm_window(C), scene->r.cfra);
-
-  // XXX scene->nodetree->test_break = BKE_blender_test_break;
-  // XXX scene->nodetree->test_break = NULL;
-
-  BKE_image_all_free_anim_ibufs(scene->r.cfra);
-  ntreeCompositTagAnimated(scene->nodetree);
-  ntreeCompositExecTree(scene->nodetree,
-                        &scene->r,
-                        0,
-                        scene->r.cfra != rcd->old_cfra,
-                        &scene->view_settings,
-                        &scene->display_settings); /* 1 is no previews */
-
-  ED_area_tag_redraw(CTX_wm_area(C));
-
-  ibuf = BKE_image_acquire_ibuf(sima->image, &sima->iuser, NULL);
-  /* save memory in flipbooks */
-  if (ibuf)
-    imb_freerectfloatImBuf(ibuf);
-
-  BKE_image_release_ibuf(sima->image, ibuf, NULL);
-
-  scene->r.cfra++;
-
-  return (scene->r.cfra <= rcd->efra);
-}
-
-static int image_record_composite_init(bContext *C, wmOperator *op)
-{
-  SpaceImage *sima = CTX_wm_space_image(C);
-  Scene *scene = CTX_data_scene(C);
-  RecordCompositeData *rcd;
-
-  if (sima->iuser.frames < 2)
-    return 0;
-  if (scene->nodetree == NULL)
-    return 0;
-
-  op->customdata = rcd = MEM_callocN(sizeof(RecordCompositeData), "ImageRecordCompositeData");
-
-  rcd->old_cfra = scene->r.cfra;
-  rcd->sfra = sima->iuser.sfra;
-  rcd->efra = sima->iuser.sfra + sima->iuser.frames - 1;
-  scene->r.cfra = rcd->sfra;
-
-  return 1;
-}
-
-static void image_record_composite_exit(bContext *C, wmOperator *op)
-{
-  Scene *scene = CTX_data_scene(C);
-  SpaceImage *sima = CTX_wm_space_image(C);
-  RecordCompositeData *rcd = op->customdata;
-
-  scene->r.cfra = rcd->old_cfra;
-
-  WM_cursor_modal_restore(CTX_wm_window(C));
-
-  if (rcd->timer)
-    WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rcd->timer);
-
-  WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, sima->image);
-
-  // XXX play_anim(0);
-  // XXX allqueue(REDRAWNODE, 1);
-
-  MEM_freeN(rcd);
-}
-
-static int image_record_composite_exec(bContext *C, wmOperator *op)
-{
-  if (!image_record_composite_init(C, op))
-    return OPERATOR_CANCELLED;
-
-  while (image_record_composite_apply(C, op)) {
-  }
-
-  image_record_composite_exit(C, op);
-
-  return OPERATOR_FINISHED;
-}
-
-static int image_record_composite_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
-{
-  RecordCompositeData *rcd;
-
-  if (!image_record_composite_init(C, op))
-    return OPERATOR_CANCELLED;
-
-  rcd = op->customdata;
-  rcd->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.0f);
-  WM_event_add_modal_handler(C, op);
-
-  if (!image_record_composite_apply(C, op))
-    return OPERATOR_FINISHED;
-
-  return OPERATOR_RUNNING_MODAL;
-}
-
-static int image_record_composite_modal(bContext *C, wmOperator *op, const wmEvent *event)
-{
-  RecordCompositeData *rcd = op->customdata;
-
-  switch (event->type) {
-    case TIMER:
-      if (rcd->timer == event->customdata) {
-        if (!image_record_composite_apply(C, op)) {
-          image_record_composite_exit(C, op);
-          return OPERATOR_FINISHED;
-        }
-      }
-      break;
-    case ESCKEY:
-      image_record_composite_exit(C, op);
-      return OPERATOR_FINISHED;
-  }
-
-  return OPERATOR_RUNNING_MODAL;
-}
-
-static void image_record_composite_cancel(bContext *C, wmOperator *op)
-{
-  image_record_composite_exit(C, op);
-  return OPERATOR_CANCELLED;
-}
-
-void IMAGE_OT_record_composite(wmOperatorType *ot)
-{
-  /* identifiers */
-  ot->name = "Record Composite";
-  ot->idname = "IMAGE_OT_record_composite";
-
-  /* api callbacks */
-  ot->exec = image_record_composite_exec;
-  ot->invoke = image_record_composite_invoke;
-  ot->modal = image_record_composite_modal;
-  ot->cancel = image_record_composite_cancel;
-  ot->poll = space_image_buffer_exists_poll;
-}
-
-#endif
-
 /********************* cycle render slot operator *********************/
 
 static bool image_cycle_render_slot_poll(bContext *C)
 {
-  Image *ima = CTX_data_edit_image(C);
+  Image *ima = image_from_context(C);
 
   return (ima && ima->type == IMA_TYPE_R_RESULT);
 }
 
 static int image_cycle_render_slot_exec(bContext *C, wmOperator *op)
 {
-  Image *ima = CTX_data_edit_image(C);
+  Image *ima = image_from_context(C);
   const int direction = RNA_boolean_get(op->ptr, "reverse") ? -1 : 1;
 
   if (!ED_image_slot_cycle(ima, direction)) {
@@ -3874,7 +3434,7 @@ void IMAGE_OT_cycle_render_slot(wmOperatorType *ot)
 static int image_clear_render_slot_exec(bContext *C, wmOperator *UNUSED(op))
 {
   SpaceImage *sima = CTX_wm_space_image(C);
-  Image *ima = CTX_data_edit_image(C);
+  Image *ima = image_from_context(C);
 
   if (!BKE_image_clear_renderslot(ima, &sima->iuser, ima->render_slot)) {
     return OPERATOR_CANCELLED;
@@ -3904,7 +3464,7 @@ void IMAGE_OT_clear_render_slot(wmOperatorType *ot)
 
 static int image_add_render_slot_exec(bContext *C, wmOperator *UNUSED(op))
 {
-  Image *ima = CTX_data_edit_image(C);
+  Image *ima = image_from_context(C);
 
   RenderSlot *slot = BKE_image_add_renderslot(ima, NULL);
   ima->render_slot = BLI_findindex(&ima->renderslots, slot);
@@ -3934,7 +3494,7 @@ void IMAGE_OT_add_render_slot(wmOperatorType *ot)
 static int image_remove_render_slot_exec(bContext *C, wmOperator *UNUSED(op))
 {
   SpaceImage *sima = CTX_wm_space_image(C);
-  Image *ima = CTX_data_edit_image(C);
+  Image *ima = image_from_context(C);
 
   if (!BKE_image_remove_renderslot(ima, &sima->iuser, ima->render_slot)) {
     return OPERATOR_CANCELLED;