Add purgeAsNeeded calls before addResource calls

https://codereview.chromium.org/19591003/



git-svn-id: http://skia.googlecode.com/svn/trunk@10145 2bbb7eff-a529-9590-31e7-b0007b416f81
diff --git a/src/gpu/GrContext.cpp b/src/gpu/GrContext.cpp
index ee8d9f7..72cb2b3 100644
--- a/src/gpu/GrContext.cpp
+++ b/src/gpu/GrContext.cpp
@@ -390,6 +390,9 @@
     }
 
     if (NULL != texture) {
+        // Adding a resource could put us overbudget. Try to free up the
+        // necessary space before adding it.
+        fTextureCache->purgeAsNeeded(1, texture->sizeInBytes());
         fTextureCache->addResource(resourceKey, texture);
     }
 
@@ -449,6 +452,9 @@
         GrTexture* texture = fGpu->createTexture(desc, NULL, 0);
         if (NULL != texture) {
             GrResourceKey key = GrTexture::ComputeScratchKey(texture->desc());
+            // Adding a resource could put us overbudget. Try to free up the
+            // necessary space before adding it.
+            fTextureCache->purgeAsNeeded(1, texture->sizeInBytes());
             // Make the resource exclusive so future 'find' calls don't return it
             fTextureCache->addResource(key, texture, GrResourceCache::kHide_OwnershipFlag);
             resource = texture;
@@ -489,9 +495,9 @@
     // the same texture).
     if (texture->getCacheEntry()->key().isScratch()) {
         fTextureCache->makeNonExclusive(texture->getCacheEntry());
+        this->purgeCache();
     }
 
-    this->purgeCache();
 }
 
 void GrContext::purgeCache() {