1 /*
2  * Copyright 2014 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 "Resources.h"
9 #include "SkBitmap.h"
10 #include "SkCommandLineFlags.h"
11 #include "SkData.h"
12 #include "SkImage.h"
13 #include "SkImageGenerator.h"
14 #include "SkOSFile.h"
15 #include "SkOSPath.h"
16 #include "SkStream.h"
17 #include "SkTypeface.h"
18 
19 DEFINE_string2(resourcePath, i, "resources", "Directory with test resources: images, fonts, etc.");
20 
GetResourcePath(const char * resource)21 SkString GetResourcePath(const char* resource) {
22     return SkOSPath::Join(FLAGS_resourcePath[0], resource);
23 }
24 
SetResourcePath(const char * resource)25 void SetResourcePath(const char* resource) {
26     FLAGS_resourcePath.set(0, resource);
27 }
28 
GetResourceAsBitmap(const char * resource,SkBitmap * dst)29 bool GetResourceAsBitmap(const char* resource, SkBitmap* dst) {
30     SkString resourcePath = GetResourcePath(resource);
31     sk_sp<SkData> resourceData(SkData::MakeFromFileName(resourcePath.c_str()));
32     std::unique_ptr<SkImageGenerator> gen(SkImageGenerator::MakeFromEncoded(resourceData));
33     if (!gen) {
34         return false;
35     }
36     SkPMColor ctStorage[256];
37     sk_sp<SkColorTable> ctable(new SkColorTable(ctStorage, 256));
38     int count = ctable->count();
39     return dst->tryAllocPixels(gen->getInfo(), nullptr, ctable.get()) &&
40         gen->getPixels(gen->getInfo().makeColorSpace(nullptr), dst->getPixels(), dst->rowBytes(),
41                        const_cast<SkPMColor*>(ctable->readColors()), &count);
42 }
43 
GetResourceAsImage(const char * resource)44 sk_sp<SkImage> GetResourceAsImage(const char* resource) {
45     SkString path = GetResourcePath(resource);
46     sk_sp<SkData> resourceData(SkData::MakeFromFileName(path.c_str()));
47     return SkImage::MakeFromEncoded(resourceData);
48 }
49 
GetResourceAsStream(const char * resource)50 SkStreamAsset* GetResourceAsStream(const char* resource) {
51     SkString resourcePath = GetResourcePath(resource);
52     std::unique_ptr<SkFILEStream> stream(new SkFILEStream(resourcePath.c_str()));
53     if (!stream->isValid()) {
54         SkDebugf("Resource %s not found.\n", resource);
55         return nullptr;
56     }
57     return stream.release();
58 }
59 
GetResourceAsData(const char * resource)60 sk_sp<SkData> GetResourceAsData(const char* resource) {
61     SkString resourcePath = GetResourcePath(resource);
62     return SkData::MakeFromFileName(resourcePath.c_str());
63 }
64 
MakeResourceAsTypeface(const char * resource)65 sk_sp<SkTypeface> MakeResourceAsTypeface(const char* resource) {
66     std::unique_ptr<SkStreamAsset> stream(GetResourceAsStream(resource));
67     if (!stream) {
68         return nullptr;
69     }
70     return SkTypeface::MakeFromStream(stream.release());
71 }
72