| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2009 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 "chrome/browser/cocoa/nsimage_cache.h" | |
| 6 | |
| 7 #include "base/logging.h" | |
| 8 #include "base/mac_util.h" | |
| 9 | |
| 10 // When C++ exceptions are disabled, the C++ library defines |try| and | |
| 11 // |catch| so as to allow exception-expecting C++ code to build properly when | |
| 12 // language support for exceptions is not present. These macros interfere | |
| 13 // with the use of |@try| and |@catch| in Objective-C files such as this one. | |
| 14 // Undefine these macros here, after everything has been #included, since | |
| 15 // there will be no C++ uses and only Objective-C uses from this point on. | |
| 16 #undef try | |
| 17 #undef catch | |
| 18 | |
| 19 namespace nsimage_cache { | |
| 20 | |
| 21 static NSMutableDictionary *image_cache = nil; | |
| 22 | |
| 23 NSImage *ImageNamed(NSString *name) { | |
| 24 DCHECK(name); | |
| 25 | |
| 26 // NOTE: to make this thread safe, we'd have to sync on the cache and | |
| 27 // also force all the bundle calls on the main thread. | |
| 28 | |
| 29 if (!image_cache) { | |
| 30 image_cache = [[NSMutableDictionary alloc] init]; | |
| 31 DCHECK(image_cache); | |
| 32 } | |
| 33 | |
| 34 NSImage *result = [image_cache objectForKey:name]; | |
| 35 if (!result) { | |
| 36 DLOG_IF(INFO, [[name pathExtension] length] == 0) | |
| 37 << "Suggest including the extension in the image name"; | |
| 38 | |
| 39 NSString *path = [mac_util::MainAppBundle() pathForImageResource:name]; | |
| 40 if (path) { | |
| 41 @try { | |
| 42 result = [[[NSImage alloc] initWithContentsOfFile:path] autorelease]; | |
| 43 if (result) | |
| 44 [image_cache setObject:result forKey:name]; | |
| 45 } | |
| 46 @catch (id err) { | |
| 47 DLOG(ERROR) << "Failed to load the image for name '" | |
| 48 << [name UTF8String] << "' from path '" << [path UTF8String] | |
| 49 << "', error: " << [err description]; | |
| 50 result = nil; | |
| 51 } | |
| 52 } | |
| 53 } | |
| 54 | |
| 55 // TODO: if we ever limit the cache size, this should retain & autorelease | |
| 56 // the image. | |
| 57 return result; | |
| 58 } | |
| 59 | |
| 60 void Clear(void) { | |
| 61 // NOTE: to make this thread safe, we'd have to sync on the cache. | |
| 62 [image_cache removeAllObjects]; | |
| 63 } | |
| 64 | |
| 65 } // namespace nsimage_cache | |
| OLD | NEW |