| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2010 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 #include "app/mac/nsimage_cache.h" | |
| 6 | |
| 7 #import <AppKit/AppKit.h> | |
| 8 | |
| 9 #include "base/logging.h" | |
| 10 #include "base/mac/mac_util.h" | |
| 11 | |
| 12 // When C++ exceptions are disabled, the C++ library defines |try| and | |
| 13 // |catch| so as to allow exception-expecting C++ code to build properly when | |
| 14 // language support for exceptions is not present. These macros interfere | |
| 15 // with the use of |@try| and |@catch| in Objective-C files such as this one. | |
| 16 // Undefine these macros here, after everything has been #included, since | |
| 17 // there will be no C++ uses and only Objective-C uses from this point on. | |
| 18 #undef try | |
| 19 #undef catch | |
| 20 | |
| 21 namespace app { | |
| 22 namespace mac { | |
| 23 | |
| 24 static NSMutableDictionary* image_cache = nil; | |
| 25 | |
| 26 NSImage* GetCachedImageWithName(NSString* name) { | |
| 27 DCHECK(name); | |
| 28 | |
| 29 // NOTE: to make this thread safe, we'd have to sync on the cache and | |
| 30 // also force all the bundle calls on the main thread. | |
| 31 | |
| 32 if (!image_cache) { | |
| 33 image_cache = [[NSMutableDictionary alloc] init]; | |
| 34 DCHECK(image_cache); | |
| 35 } | |
| 36 | |
| 37 NSImage* result = [image_cache objectForKey:name]; | |
| 38 if (!result) { | |
| 39 DVLOG_IF(1, [[name pathExtension] length] == 0) << "Suggest including the " | |
| 40 "extension in the image name"; | |
| 41 | |
| 42 NSString* path = [base::mac::MainAppBundle() pathForImageResource:name]; | |
| 43 if (path) { | |
| 44 @try { | |
| 45 result = [[[NSImage alloc] initWithContentsOfFile:path] autorelease]; | |
| 46 if (result) { | |
| 47 // Auto-template images with names ending in "Template". | |
| 48 NSString* extensionlessName = [name stringByDeletingPathExtension]; | |
| 49 if ([extensionlessName hasSuffix:@"Template"]) | |
| 50 [result setTemplate:YES]; | |
| 51 | |
| 52 [image_cache setObject:result forKey:name]; | |
| 53 } | |
| 54 } | |
| 55 @catch (id err) { | |
| 56 DLOG(ERROR) << "Failed to load the image for name '" | |
| 57 << [name UTF8String] << "' from path '" << [path UTF8String] | |
| 58 << "', error: " << [[err description] UTF8String]; | |
| 59 result = nil; | |
| 60 } | |
| 61 } | |
| 62 } | |
| 63 | |
| 64 // TODO: if we ever limit the cache size, this should retain & autorelease | |
| 65 // the image. | |
| 66 return result; | |
| 67 } | |
| 68 | |
| 69 void ClearCachedImages(void) { | |
| 70 // NOTE: to make this thread safe, we'd have to sync on the cache. | |
| 71 [image_cache removeAllObjects]; | |
| 72 } | |
| 73 | |
| 74 } // namespace mac | |
| 75 } // namespace app | |
| OLD | NEW |