Fix race on creating the default typeface.
authorbungeman@google.com <bungeman@google.com@2bbb7eff-a529-9590-31e7-b0007b416f81>
Thu, 9 Jan 2014 17:13:32 +0000 (17:13 +0000)
committerbungeman@google.com <bungeman@google.com@2bbb7eff-a529-9590-31e7-b0007b416f81>
Thu, 9 Jan 2014 17:13:32 +0000 (17:13 +0000)
BUG=skia:1906
R=mtklein@google.com, reed@google.com

Review URL: https://codereview.chromium.org/113543005

git-svn-id: http://skia.googlecode.com/svn/trunk@12993 2bbb7eff-a529-9590-31e7-b0007b416f81

include/core/SkTypeface.h
src/core/SkTypeface.cpp

index d873e69b9d0800ee32caf6725a7ecae60dbaafa2..04838dad98d21200596d6a999ad096c8fde9cc84 100644 (file)
@@ -334,6 +334,8 @@ protected:
                                   size_t length, void* data) const = 0;
 
 private:
+    static void create_default_typeface(Style style);
+
     SkFontID    fUniqueID;
     Style       fStyle;
     bool        fIsFixedPitch;
index 09a64324af2ea25cfef458b059dc1b65ce865eb3..d15caeb86f594493b3a743f947bec985ece9c286 100644 (file)
@@ -8,6 +8,7 @@
 #include "SkAdvancedTypefaceMetrics.h"
 #include "SkFontDescriptor.h"
 #include "SkFontHost.h"
+#include "SkOnce.h"
 #include "SkStream.h"
 #include "SkTypeface.h"
 
@@ -69,24 +70,32 @@ protected:
     }
 };
 
-SkTypeface* SkTypeface::GetDefaultTypeface(Style style) {
-    // we keep a reference to this guy for all time, since if we return its
-    // fontID, the font cache may later on ask to resolve that back into a
-    // typeface object.
-    static const uint32_t FONT_STYLE_COUNT = 4;
-    static SkTypeface* gDefaultTypefaces[FONT_STYLE_COUNT];
-    SkASSERT((unsigned)style < FONT_STYLE_COUNT);
-
-    // mask off any other bits to avoid a crash in SK_RELEASE
-    style = (Style)(style & 0x03);
+static SkTypeface* gDefaultTypefaces[] = { NULL, NULL, NULL, NULL };
+static const size_t FONT_STYLE_COUNT = SK_ARRAY_COUNT(gDefaultTypefaces);
+static SkOnceFlag gDefaultTypefaceOnce[FONT_STYLE_COUNT] = {
+    SK_ONCE_INIT, SK_ONCE_INIT, SK_ONCE_INIT, SK_ONCE_INIT
+};
+template <uintmax_t N> struct SkTIsPow2 {
+    static const bool value = (N & (N - 1)) == 0;
+};
+SK_COMPILE_ASSERT(SkTIsPow2<FONT_STYLE_COUNT>::value, FONT_STYLE_COUNT_not_power_of_2);
 
+void SkTypeface::create_default_typeface(Style style) {
     if (NULL == gDefaultTypefaces[style]) {
         gDefaultTypefaces[style] = SkFontHost::CreateTypeface(NULL, NULL, style);
     }
     if (NULL == gDefaultTypefaces[style]) {
         gDefaultTypefaces[style] = SkNEW(SkEmptyTypeface);
     }
+}
+
+SkTypeface* SkTypeface::GetDefaultTypeface(Style style) {
+    SkASSERT((size_t)style < FONT_STYLE_COUNT);
+
+    // mask off any other bits to avoid a crash in SK_RELEASE
+    style = (Style)(style & (FONT_STYLE_COUNT - 1));
 
+    SkOnce(&gDefaultTypefaceOnce[style], SkTypeface::create_default_typeface, style);
     return gDefaultTypefaces[style];
 }