lottie: take a copy of the data before parsing.
[platform/core/uifw/lottie-player.git] / src / lottie / lottieloader.cpp
1 #include "lottieloader.h"
2 #include "lottieparser.h"
3
4 #include <fstream>
5 #include <unordered_map>
6
7 using namespace std;
8
9 class LottieFileCache {
10 public:
11     static LottieFileCache &get()
12     {
13         static LottieFileCache CACHE;
14
15         return CACHE;
16     }
17     std::shared_ptr<LOTModel> find(const std::string &key);
18     void add(const std::string &key, std::shared_ptr<LOTModel> value);
19
20 private:
21     LottieFileCache() = default;
22
23     std::unordered_map<std::string, std::shared_ptr<LOTModel>> mHash;
24 };
25
26 std::shared_ptr<LOTModel> LottieFileCache::find(const std::string &key)
27 {
28     auto search = mHash.find(key);
29     if (search != mHash.end()) {
30         return search->second;
31     } else {
32         return nullptr;
33     }
34 }
35
36 void LottieFileCache::add(const std::string &key, std::shared_ptr<LOTModel> value)
37 {
38     mHash[key] = std::move(value);
39 }
40
41 bool LottieLoader::load(const std::string &path)
42 {
43     LottieFileCache &fileCache = LottieFileCache::get();
44
45     mModel = fileCache.find(path);
46     if (mModel) return true;
47
48     std::ifstream f;
49     f.open(path);
50
51     if (!f.is_open()) {
52         vCritical << "failed to open file = " << path.c_str();
53         return false;
54     } else {
55         std::stringstream buf;
56         buf << f.rdbuf();
57
58         LottieParser parser(const_cast<char *>(buf.str().data()));
59         mModel = parser.model();
60         fileCache.add(path, mModel);
61
62         f.close();
63     }
64
65     return true;
66 }
67
68 bool LottieLoader::loadFromData(const char *jsonData, const char *key)
69 {
70     LottieFileCache &fileCache = LottieFileCache::get();
71     std::string keyString(key);
72
73     mModel = fileCache.find(std::string(keyString));
74     if (mModel) return true;
75
76     LottieParser parser(const_cast<char *>(std::string(jsonData).c_str()));
77     mModel = parser.model();
78     fileCache.add(keyString, mModel);
79
80     return true;
81 }
82
83 std::shared_ptr<LOTModel> LottieLoader::model()
84 {
85     return mModel;
86 }