blob: 4dbb9a4a7b787f1d9cf1521c022a6a800982b66d [file] [log] [blame]
tfarinabcbc1782014-06-18 14:32:48 -07001/*
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
Kevin Lubick93c869d2023-05-03 10:18:36 -04008#include "tools/Resources.h"
9
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "include/core/SkData.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "include/core/SkStream.h"
Kevin Lubick8b741882023-10-06 11:41:38 -040012#include "include/private/base/SkDebug.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "src/utils/SkOSPath.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050014#include "tools/flags/CommandLineFlags.h"
tfarinabcbc1782014-06-18 14:32:48 -070015
Kevin Lubick8b741882023-10-06 11:41:38 -040016#include <utility>
17
Mike Kleinc6142d82019-03-25 10:54:59 -050018static DEFINE_string2(resourcePath, i, "resources",
19 "Directory with test resources: images, fonts, etc.");
tfarinabcbc1782014-06-18 14:32:48 -070020
Hal Canary537d9c02018-01-30 11:30:48 -050021sk_sp<SkData> (*gResourceFactory)(const char*) = nullptr;
22
tfarinabcbc1782014-06-18 14:32:48 -070023SkString GetResourcePath(const char* resource) {
tfarinaa8e2e152014-07-28 19:26:58 -070024 return SkOSPath::Join(FLAGS_resourcePath[0], resource);
tfarinabcbc1782014-06-18 14:32:48 -070025}
caryclark936b7342014-07-11 12:14:51 -070026
27void SetResourcePath(const char* resource) {
28 FLAGS_resourcePath.set(0, resource);
29}
halcanary30b83d42014-10-26 05:23:53 -070030
Brian Osman2f160c22023-01-23 09:32:29 -050031std::unique_ptr<SkStreamAsset> GetResourceAsStream(const char* resource, bool useFileStream) {
32 if (useFileStream) {
33 auto path = GetResourcePath(resource);
34 return SkFILEStream::Make(path.c_str());
35 } else {
36 auto data = GetResourceAsData(resource);
37 return data ? std::unique_ptr<SkStreamAsset>(new SkMemoryStream(std::move(data)))
38 : nullptr;
39 }
bungeman3ffa1262015-04-30 17:12:58 -040040}
41
Hal Canarya4935102017-12-08 13:35:47 -050042sk_sp<SkData> GetResourceAsData(const char* resource) {
Hal Canaryfd9bcab2018-04-24 11:47:23 -040043 if (sk_sp<SkData> data = gResourceFactory
44 ? gResourceFactory(resource)
45 : SkData::MakeFromFileName(GetResourcePath(resource).c_str())) {
Hal Canary537d9c02018-01-30 11:30:48 -050046 return data;
Hal Canarya4935102017-12-08 13:35:47 -050047 }
Brian Salomon5b49d782018-08-28 10:22:50 -040048 SkDebugf("Resource \"%s\" not found.\n", GetResourcePath(resource).c_str());
Hal Canaryfd9bcab2018-04-24 11:47:23 -040049 #ifdef SK_TOOLS_REQUIRE_RESOURCES
50 SK_ABORT("missing resource");
51 #endif
Hal Canarya4935102017-12-08 13:35:47 -050052 return nullptr;
53}