1 /*
2  * Copyright 2017 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "SkKeyedImage.h"
9 
10 #include "SkImage_Base.h"
11 
12 SkBitmapKey SkBitmapKeyFromImage(const SkImage* image) {
13     if (!image) {
14         return {{0, 0, 0, 0}, 0};
15     }
16     if (const SkBitmap* bm = as_IB(image)->onPeekBitmap()) {
17         SkIPoint o = bm->pixelRefOrigin();
18         return {image->bounds().makeOffset(o.x(), o.y()), bm->getGenerationID()};
19     }
20     return {image->bounds(), image->uniqueID()};
21 }
22 
23 SkKeyedImage::SkKeyedImage(sk_sp<SkImage> i) : fImage(std::move(i)) {
24     fKey = SkBitmapKeyFromImage(fImage.get());
25 }
26 
27 SkKeyedImage::SkKeyedImage(const SkBitmap& bm) : fImage(SkImage::MakeFromBitmap(bm)) {
28     if (fImage) {
29         fKey = {bm.getSubset(), bm.getGenerationID()};
30     }
31 }
32 
33 SkKeyedImage SkKeyedImage::subset(SkIRect subset) const {
34     SkKeyedImage img;
35     if (fImage && subset.intersect(fImage->bounds())) {
36         img.fImage = fImage->makeSubset(subset);
37         if (img.fImage) {
38             img.fKey = {subset.makeOffset(fKey.fSubset.x(), fKey.fSubset.y()), fKey.fID};
39         }
40     }
41     return img;
42 }
43 
44 sk_sp<SkImage> SkKeyedImage::release() {
45     sk_sp<SkImage> image = std::move(fImage);
46     SkASSERT(nullptr == fImage);
47     fKey = {{0, 0, 0, 0}, 0};
48     return image;
49 }
50