1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61
   62
   63
   64
   65
   66
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   78
   79
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  124
  125
  126
  127
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  139
  140
  141
  142
  143
  144
  145
  146
  147
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
  166
  167
  168
  169
  170
  171
  172
  173
  174
  175
  176
  177
  178
  179
  180
  181
  182
  183
  184
  185
  186
  187

ash / wallpaper / wallpaper_utils / wallpaper_file_utils.cc [blame]

// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "ash/wallpaper/wallpaper_utils/wallpaper_file_utils.h"

#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/memory/ref_counted_memory.h"
#include "base/memory/scoped_refptr.h"
#include "base/threading/thread_restrictions.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkPixmap.h"
#include "third_party/skia/include/encode/SkJpegEncoder.h"
#include "ui/gfx/codec/jpeg_codec.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"

namespace ash {
namespace {

// Default quality for encoding wallpaper.
constexpr int kDefaultEncodingQuality = 90;

// Encodes `image_skia` to jpg with `image_metadata` encoded in the header.
// `output` will be in an undefined state on failure.
bool EncodeImage(const gfx::ImageSkia& image_skia,
                 const std::string& image_metadata,
                 scoped_refptr<base::RefCountedBytes>* output) {
  base::AssertLongCPUWorkAllowed();
  SkBitmap bitmap = *(image_skia.bitmap());
  DCHECK(!bitmap.drawsNothing());
  *output = base::MakeRefCounted<base::RefCountedBytes>();

  if (image_metadata.empty()) {
    std::optional<std::vector<uint8_t>> data =
        gfx::JPEGCodec::Encode(bitmap, kDefaultEncodingQuality);
    if (!data) {
      return false;
    }
    (*output)->as_vector() = std::move(data.value());
    return true;
  }

  SkPixmap pixmap;
  if (!bitmap.peekPixels(&pixmap)) {
    LOG(WARNING) << "Failed to read bitmap pixels";
    return false;
  }

  auto xmp_metadata = SkData::MakeWithCString(image_metadata.c_str());

  std::optional<std::vector<uint8_t>> data = gfx::JPEGCodec::Encode(
      pixmap, kDefaultEncodingQuality, SkJpegEncoder::Downsample::k420,
      xmp_metadata.get());
  if (!data) {
    return false;
  }
  (*output)->as_vector() = std::move(data.value());
  return true;
}

// Resizes `image` to a resolution which is nearest to `preferred_width` and
// `preferred_height` while respecting the `layout` choice. Returns empty
// `ImageSkia` on failure.
gfx::ImageSkia ResizeImage(const gfx::ImageSkia& image_skia,
                           const WallpaperLayout layout,
                           const gfx::Size preferred_size) {
  const int width = image_skia.width();
  const int height = image_skia.height();
  const int preferred_width = preferred_size.width();
  const int preferred_height = preferred_size.height();
  int resized_width;
  int resized_height;

  if (layout == WALLPAPER_LAYOUT_CENTER_CROPPED) {
    // Do not resize wallpaper if it is smaller than preferred size.
    if (width < preferred_width || height < preferred_height) {
      DVLOG(1) << "Skip resize. Size=" << image_skia.size().ToString()
               << " Preferred_Size="
               << gfx::Size(preferred_width, preferred_height).ToString();
      return gfx::ImageSkia();
    }

    // TODO(esum): This is the same scaling logic as what's in
    // ash::CenterCropImage(). Remove this code duplication.
    double horizontal_ratio = static_cast<double>(preferred_width) / width;
    double vertical_ratio = static_cast<double>(preferred_height) / height;
    if (vertical_ratio > horizontal_ratio) {
      resized_width =
          base::ClampRound(static_cast<double>(width) * vertical_ratio);
      resized_height = preferred_height;
    } else {
      resized_width = preferred_width;
      resized_height =
          base::ClampRound(static_cast<double>(height) * horizontal_ratio);
    }
  } else if (layout == WALLPAPER_LAYOUT_STRETCH) {
    resized_width = preferred_width;
    resized_height = preferred_height;
  } else {
    resized_width = width;
    resized_height = height;
  }

  return gfx::ImageSkiaOperations::CreateResizedImage(
      image_skia, skia::ImageOperations::RESIZE_LANCZOS3,
      gfx::Size(resized_width, resized_height));
}

bool SaveWallpaper(const gfx::ImageSkia& image,
                   const base::FilePath& path,
                   const std::string& image_metadata) {
  scoped_refptr<base::RefCountedBytes> data;
  if (!EncodeImage(image, image_metadata, &data)) {
    LOG(WARNING) << "Encoding wallpaper image failed";
    return false;
  }

  // Write to `temp_path` to reduce the chance of read/write
  // collisions from different sequences. This avoids issues with policy
  // wallpaper at login: b/280578317.
  base::FilePath temp_path;
  if (!base::CreateTemporaryFileInDir(path.DirName(), &temp_path)) {
    LOG(WARNING) << "Failed to create temporary file";
    return false;
  }

  if (!base::WriteFile(temp_path, base::span(*data))) {
    LOG(WARNING) << "Failed to write wallpaper data to temporary file";
    base::DeleteFile(temp_path);
    return false;
  }

  if (!base::Move(temp_path, path)) {
    LOG(WARNING) << "Failed to copy temporary wallpaper data to " << path;
    base::DeleteFile(temp_path);
    return false;
  }

  return true;
}

}  // namespace

bool ResizeAndSaveWallpaper(const gfx::ImageSkia& image,
                            const base::FilePath& path,
                            const WallpaperLayout layout,
                            const gfx::Size preferred_size,
                            const std::string& image_metadata) {
  if (layout == WALLPAPER_LAYOUT_CENTER) {
    // TODO(b/325498873) remove this.
    if (base::PathExists(path)) {
      DVLOG(1) << "Deleting path " << path;
      base::DeleteFile(path);
    }
    DVLOG(1) << "Skipping resize and save for WALLPAPER_LAYOUT_CENTER path "
             << path;
    return false;
  }

  gfx::ImageSkia resized_image = ResizeImage(image, layout, preferred_size);
  if (resized_image.isNull()) {
    LOG(WARNING) << "Failed to resize image";
    return false;
  }

  return SaveWallpaper(resized_image, path, image_metadata);
}

void CreateDirectoryAndLogError(const base::FilePath& directory) {
  DCHECK(!directory.empty());
  base::File::Error error;
  if (!base::CreateDirectoryAndGetError(directory, &error)) {
    LOG(WARNING) << "Failed to create wallpaper directory: " << error;
  }
}

}  // namespace ash