1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this
4  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 
6 #ifndef nsStringBundle_h__
7 #define nsStringBundle_h__
8 
9 #include "mozilla/Mutex.h"
10 #include "nsIStringBundle.h"
11 #include "nsIMemoryReporter.h"
12 #include "nsCOMPtr.h"
13 #include "nsString.h"
14 #include "nsCOMArray.h"
15 
16 class nsIPersistentProperties;
17 
18 class nsStringBundleBase : public nsIStringBundle, public nsIMemoryReporter {
19  public:
20   MOZ_DEFINE_MALLOC_SIZE_OF(MallocSizeOf)
21 
22   nsresult ParseProperties(nsIPersistentProperties**);
23 
24   NS_DECL_THREADSAFE_ISUPPORTS
25   NS_DECL_NSISTRINGBUNDLE
26   NS_DECL_NSIMEMORYREPORTER
27 
28   virtual nsresult LoadProperties() = 0;
29 
BundleURL()30   const nsCString& BundleURL() const { return mPropertiesURL; }
31 
32   // Returns true if this bundle has more than one reference. If it has only
33   // a single reference, it is assumed to be held alive by the bundle cache.
IsShared()34   bool IsShared() const { return mRefCnt > 1; }
35 
Cast(nsIStringBundle * aBundle)36   static nsStringBundleBase* Cast(nsIStringBundle* aBundle) {
37     return static_cast<nsStringBundleBase*>(aBundle);
38   }
39 
40   template <typename T, typename... Args>
41   static already_AddRefed<T> Create(Args... args);
42 
43  protected:
44   nsStringBundleBase(const char* aURLSpec);
45 
46   virtual ~nsStringBundleBase();
47 
48   virtual nsresult GetStringImpl(const nsACString& aName,
49                                  nsAString& aResult) = 0;
50 
51   virtual nsresult GetSimpleEnumerationImpl(nsISimpleEnumerator** elements) = 0;
52 
53   void RegisterMemoryReporter();
54 
55   nsCString mPropertiesURL;
56   mozilla::Mutex mMutex;
57   bool mAttemptedLoad;
58   bool mLoaded;
59 
60   size_t SizeOfIncludingThisIfUnshared(
61       mozilla::MallocSizeOf aMallocSizeOf) const override;
62 
63  public:
64   static nsresult FormatString(const char16_t* formatStr,
65                                const nsTArray<nsString>& aParams,
66                                nsAString& aResult);
67 };
68 
69 class nsStringBundle : public nsStringBundleBase {
70  public:
71   NS_DECL_ISUPPORTS_INHERITED
72 
73   nsCOMPtr<nsIPersistentProperties> mProps;
74 
75   nsresult LoadProperties() override;
76 
77   size_t SizeOfIncludingThis(
78       mozilla::MallocSizeOf aMallocSizeOf) const override;
79 
80  protected:
81   friend class nsStringBundleBase;
82 
83   explicit nsStringBundle(const char* aURLSpec);
84 
85   virtual ~nsStringBundle();
86 
87   nsresult GetStringImpl(const nsACString& aName, nsAString& aResult) override;
88 
89   nsresult GetSimpleEnumerationImpl(nsISimpleEnumerator** elements) override;
90 };
91 
92 #endif
93