| 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 "base/nsimage_cache_mac.h" | |
| 6 | |
| 7 #import <AppKit/AppKit.h> | |
| 8 | |
| 9 #include "base/logging.h" | |
| 10 #include "base/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 nsimage_cache { | |
| 22 | |
| 23 static NSMutableDictionary* image_cache = nil; | |
| 24 | |
| 25 NSImage* ImageNamed(NSString* name) { | |
| 26 DCHECK(name); | |
| 27 | |
| 28 // NOTE: to make this thread safe, we'd have to sync on the cache and | |
| 29 // also force all the bundle calls on the main thread. | |
| 30 | |
| 31 if (!image_cache) { | |
| 32 image_cache = [[NSMutableDictionary alloc] init]; | |
| 33 DCHECK(image_cache); | |
| 34 } | |
| 35 | |
| 36 NSImage* result = [image_cache objectForKey:name]; | |
| 37 if (!result) { | |
| 38 DVLOG_IF(1, [[name pathExtension] length] == 0) << "Suggest including the " | |
| 39 "extension in the image name"; | |
| 40 | |
| 41 NSString* path = [mac_util::MainAppBundle() pathForImageResource:name]; | |
| 42 if (path) { | |
| 43 @try { | |
| 44 result = [[[NSImage alloc] initWithContentsOfFile:path] autorelease]; | |
| 45 if (result) { | |
| 46 // Auto-template images with names ending in "Template". | |
| 47 NSString* extensionlessName = [name stringByDeletingPathExtension]; | |
| 48 if ([extensionlessName hasSuffix:@"Template"]) | |
| 49 [result setTemplate:YES]; | |
| 50 | |
| 51 [image_cache setObject:result forKey:name]; | |
| 52 } | |
| 53 } | |
| 54 @catch (id err) { | |
| 55 DLOG(ERROR) << "Failed to load the image for name '" | |
| 56 << [name UTF8String] << "' from path '" << [path UTF8String] | |
| 57 << "', error: " << [[err description] UTF8String]; | |
| 58 result = nil; | |
| 59 } | |
| 60 } | |
| 61 } | |
| 62 | |
| 63 // TODO: if we ever limit the cache size, this should retain & autorelease | |
| 64 // the image. | |
| 65 return result; | |
| 66 } | |
| 67 | |
| 68 void Clear(void) { | |
| 69 // NOTE: to make this thread safe, we'd have to sync on the cache. | |
| 70 [image_cache removeAllObjects]; | |
| 71 } | |
| 72 | |
| 73 } // namespace nsimage_cache | |
| OLD | NEW |