Overte C++ Documentation
ScriptCache.h
1 //
2 // ScriptCache.h
3 // libraries/script-engine/src
4 //
5 // Created by Brad Hefta-Gaub on 2015-03-30
6 // Copyright 2015 High Fidelity, Inc.
7 // Copyright 2023 Overte e.V.
8 //
9 // Distributed under the Apache License, Version 2.0.
10 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
11 // SPDX-License-Identifier: Apache-2.0
12 //
13 
16 
17 #ifndef hifi_ScriptCache_h
18 #define hifi_ScriptCache_h
19 
20 #include <mutex>
21 #include <DependencyManager.h>
22 
23 using contentAvailableCallback = std::function<void(const QString& scriptOrURL, const QString& contents, bool isURL, bool contentAvailable, const QString& status)>;
24 
25 class ScriptUser {
26 public:
27  virtual ~ScriptUser() = default;
28  virtual void scriptContentsAvailable(const QUrl& url, const QString& scriptContents) = 0;
29  virtual void errorInLoadingScript(const QUrl& url) = 0;
30 };
31 
32 class ScriptRequest {
33 public:
34  static const int MAX_RETRIES { 5 };
35  static const int START_DELAY_BETWEEN_RETRIES { 200 };
36  std::vector<contentAvailableCallback> scriptUsers { };
37  int numRetries { 0 };
38  int maxRetries { MAX_RETRIES };
39 };
40 
42 class ScriptCache : public QObject, public Dependency {
43  Q_OBJECT
44  SINGLETON_DEPENDENCY
45 
46  using Mutex = std::mutex;
47  using Lock = std::unique_lock<Mutex>;
48 
49 public:
50  static const QString STATUS_INLINE;
51  static const QString STATUS_CACHED;
52  static bool isSuccessStatus(const QString& status) {
53  return status == "Success" || status == STATUS_INLINE || status == STATUS_CACHED;
54  }
55 
56  void clearCache();
57  Q_INVOKABLE void clearATPScriptsFromCache();
58  void getScriptContents(const QString& scriptOrURL, contentAvailableCallback contentAvailable, bool forceDownload = false, int maxRetries = ScriptRequest::MAX_RETRIES);
59 
60  void deleteScript(const QUrl& unnormalizedURL);
61 
62 private:
63  void scriptContentAvailable(int maxRetries); // new version
64  ScriptCache(QObject* parent = NULL);
65 
66  Mutex _containerLock;
67  QMap<QUrl, ScriptRequest> _activeScriptRequests;
68 
69  QHash<QUrl, QVariantMap> _scriptCache;
70  QMultiMap<QUrl, ScriptUser*> _scriptUsers;
71 };
72 
73 #endif // hifi_ScriptCache_h
74 
Dependency for for loading and caching scripts.
Definition: ScriptCache.h:42