Invoke LeakSanitizer on teardown of RenderFrameImplTest
[chromium-blink-merge.git] / base / mac / foundation_util.h
blob353ed7c6318d6ecf986bf65d51fb329def4d2088
1 // Copyright (c) 2012 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.
5 #ifndef BASE_MAC_FOUNDATION_UTIL_H_
6 #define BASE_MAC_FOUNDATION_UTIL_H_
8 #include <CoreFoundation/CoreFoundation.h>
10 #include <string>
11 #include <vector>
13 #include "base/base_export.h"
14 #include "base/logging.h"
15 #include "base/mac/scoped_cftyperef.h"
17 #if defined(__OBJC__)
18 #import <Foundation/Foundation.h>
19 @class NSFont;
20 @class UIFont;
21 #else // __OBJC__
22 #include <CoreFoundation/CoreFoundation.h>
23 class NSBundle;
24 class NSFont;
25 class NSString;
26 class UIFont;
27 #endif // __OBJC__
29 #if defined(OS_IOS)
30 #include <CoreText/CoreText.h>
31 #else
32 #include <ApplicationServices/ApplicationServices.h>
33 #endif
35 // Adapted from NSObjCRuntime.h NS_ENUM definition (used in Foundation starting
36 // with the OS X 10.8 SDK and the iOS 6.0 SDK).
37 #if __has_extension(cxx_strong_enums) && \
38 (defined(OS_IOS) || (defined(MAC_OS_X_VERSION_10_8) && \
39 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8))
40 #define CR_FORWARD_ENUM(_type, _name) enum _name : _type _name
41 #else
42 #define CR_FORWARD_ENUM(_type, _name) _type _name
43 #endif
45 // Adapted from NSPathUtilities.h and NSObjCRuntime.h.
46 #if __LP64__ || NS_BUILD_32_LIKE_64
47 typedef CR_FORWARD_ENUM(unsigned long, NSSearchPathDirectory);
48 typedef unsigned long NSSearchPathDomainMask;
49 #else
50 typedef CR_FORWARD_ENUM(unsigned int, NSSearchPathDirectory);
51 typedef unsigned int NSSearchPathDomainMask;
52 #endif
54 typedef struct OpaqueSecTrustRef* SecACLRef;
55 typedef struct OpaqueSecTrustedApplicationRef* SecTrustedApplicationRef;
57 namespace base {
59 class FilePath;
61 namespace mac {
63 // Returns true if the application is running from a bundle
64 BASE_EXPORT bool AmIBundled();
65 BASE_EXPORT void SetOverrideAmIBundled(bool value);
67 #if defined(UNIT_TEST)
68 // This is required because instantiating some tests requires checking the
69 // directory structure, which sets the AmIBundled cache state. Individual tests
70 // may or may not be bundled, and this would trip them up if the cache weren't
71 // cleared. This should not be called from individual tests, just from test
72 // instantiation code that gets a path from PathService.
73 BASE_EXPORT void ClearAmIBundledCache();
74 #endif
76 // Returns true if this process is marked as a "Background only process".
77 BASE_EXPORT bool IsBackgroundOnlyProcess();
79 // Returns the path to a resource within the framework bundle.
80 BASE_EXPORT FilePath PathForFrameworkBundleResource(CFStringRef resourceName);
82 // Returns the creator code associated with the CFBundleRef at bundle.
83 OSType CreatorCodeForCFBundleRef(CFBundleRef bundle);
85 // Returns the creator code associated with this application, by calling
86 // CreatorCodeForCFBundleRef for the application's main bundle. If this
87 // information cannot be determined, returns kUnknownType ('????'). This
88 // does not respect the override app bundle because it's based on CFBundle
89 // instead of NSBundle, and because callers probably don't want the override
90 // app bundle's creator code anyway.
91 BASE_EXPORT OSType CreatorCodeForApplication();
93 // Searches for directories for the given key in only the given |domain_mask|.
94 // If found, fills result (which must always be non-NULL) with the
95 // first found directory and returns true. Otherwise, returns false.
96 BASE_EXPORT bool GetSearchPathDirectory(NSSearchPathDirectory directory,
97 NSSearchPathDomainMask domain_mask,
98 FilePath* result);
100 // Searches for directories for the given key in only the local domain.
101 // If found, fills result (which must always be non-NULL) with the
102 // first found directory and returns true. Otherwise, returns false.
103 BASE_EXPORT bool GetLocalDirectory(NSSearchPathDirectory directory,
104 FilePath* result);
106 // Searches for directories for the given key in only the user domain.
107 // If found, fills result (which must always be non-NULL) with the
108 // first found directory and returns true. Otherwise, returns false.
109 BASE_EXPORT bool GetUserDirectory(NSSearchPathDirectory directory,
110 FilePath* result);
112 // Returns the ~/Library directory.
113 BASE_EXPORT FilePath GetUserLibraryPath();
115 // Takes a path to an (executable) binary and tries to provide the path to an
116 // application bundle containing it. It takes the outermost bundle that it can
117 // find (so for "/Foo/Bar.app/.../Baz.app/..." it produces "/Foo/Bar.app").
118 // |exec_name| - path to the binary
119 // returns - path to the application bundle, or empty on error
120 BASE_EXPORT FilePath GetAppBundlePath(const FilePath& exec_name);
122 #define TYPE_NAME_FOR_CF_TYPE_DECL(TypeCF) \
123 BASE_EXPORT std::string TypeNameForCFType(TypeCF##Ref);
125 TYPE_NAME_FOR_CF_TYPE_DECL(CFArray);
126 TYPE_NAME_FOR_CF_TYPE_DECL(CFBag);
127 TYPE_NAME_FOR_CF_TYPE_DECL(CFBoolean);
128 TYPE_NAME_FOR_CF_TYPE_DECL(CFData);
129 TYPE_NAME_FOR_CF_TYPE_DECL(CFDate);
130 TYPE_NAME_FOR_CF_TYPE_DECL(CFDictionary);
131 TYPE_NAME_FOR_CF_TYPE_DECL(CFNull);
132 TYPE_NAME_FOR_CF_TYPE_DECL(CFNumber);
133 TYPE_NAME_FOR_CF_TYPE_DECL(CFSet);
134 TYPE_NAME_FOR_CF_TYPE_DECL(CFString);
135 TYPE_NAME_FOR_CF_TYPE_DECL(CFURL);
136 TYPE_NAME_FOR_CF_TYPE_DECL(CFUUID);
138 TYPE_NAME_FOR_CF_TYPE_DECL(CGColor);
140 TYPE_NAME_FOR_CF_TYPE_DECL(CTFont);
141 TYPE_NAME_FOR_CF_TYPE_DECL(CTRun);
143 #undef TYPE_NAME_FOR_CF_TYPE_DECL
145 // Retain/release calls for memory management in C++.
146 BASE_EXPORT void NSObjectRetain(void* obj);
147 BASE_EXPORT void NSObjectRelease(void* obj);
149 // CFTypeRefToNSObjectAutorelease transfers ownership of a Core Foundation
150 // object (one derived from CFTypeRef) to the Foundation memory management
151 // system. In a traditional managed-memory environment, cf_object is
152 // autoreleased and returned as an NSObject. In a garbage-collected
153 // environment, cf_object is marked as eligible for garbage collection.
155 // This function should only be used to convert a concrete CFTypeRef type to
156 // its equivalent "toll-free bridged" NSObject subclass, for example,
157 // converting a CFStringRef to NSString.
159 // By calling this function, callers relinquish any ownership claim to
160 // cf_object. In a managed-memory environment, the object's ownership will be
161 // managed by the innermost NSAutoreleasePool, so after this function returns,
162 // callers should not assume that cf_object is valid any longer than the
163 // returned NSObject.
165 // Returns an id, typed here for C++'s sake as a void*.
166 BASE_EXPORT void* CFTypeRefToNSObjectAutorelease(CFTypeRef cf_object);
168 // Returns the base bundle ID, which can be set by SetBaseBundleID but
169 // defaults to a reasonable string. This never returns NULL. BaseBundleID
170 // returns a pointer to static storage that must not be freed.
171 BASE_EXPORT const char* BaseBundleID();
173 // Sets the base bundle ID to override the default. The implementation will
174 // make its own copy of new_base_bundle_id.
175 BASE_EXPORT void SetBaseBundleID(const char* new_base_bundle_id);
177 } // namespace mac
178 } // namespace base
180 #if !defined(__OBJC__)
181 #define OBJC_CPP_CLASS_DECL(x) class x;
182 #else // __OBJC__
183 #define OBJC_CPP_CLASS_DECL(x)
184 #endif // __OBJC__
186 // Convert toll-free bridged CFTypes to NSTypes and vice-versa. This does not
187 // autorelease |cf_val|. This is useful for the case where there is a CFType in
188 // a call that expects an NSType and the compiler is complaining about const
189 // casting problems.
190 // The calls are used like this:
191 // NSString *foo = CFToNSCast(CFSTR("Hello"));
192 // CFStringRef foo2 = NSToCFCast(@"Hello");
193 // The macro magic below is to enforce safe casting. It could possibly have
194 // been done using template function specialization, but template function
195 // specialization doesn't always work intuitively,
196 // (http://www.gotw.ca/publications/mill17.htm) so the trusty combination
197 // of macros and function overloading is used instead.
199 #define CF_TO_NS_CAST_DECL(TypeCF, TypeNS) \
200 OBJC_CPP_CLASS_DECL(TypeNS) \
202 namespace base { \
203 namespace mac { \
204 BASE_EXPORT TypeNS* CFToNSCast(TypeCF##Ref cf_val); \
205 BASE_EXPORT TypeCF##Ref NSToCFCast(TypeNS* ns_val); \
209 #define CF_TO_NS_MUTABLE_CAST_DECL(name) \
210 CF_TO_NS_CAST_DECL(CF##name, NS##name) \
211 OBJC_CPP_CLASS_DECL(NSMutable##name) \
213 namespace base { \
214 namespace mac { \
215 BASE_EXPORT NSMutable##name* CFToNSCast(CFMutable##name##Ref cf_val); \
216 BASE_EXPORT CFMutable##name##Ref NSToCFCast(NSMutable##name* ns_val); \
220 // List of toll-free bridged types taken from:
221 // http://www.cocoadev.com/index.pl?TollFreeBridged
223 CF_TO_NS_MUTABLE_CAST_DECL(Array);
224 CF_TO_NS_MUTABLE_CAST_DECL(AttributedString);
225 CF_TO_NS_CAST_DECL(CFCalendar, NSCalendar);
226 CF_TO_NS_MUTABLE_CAST_DECL(CharacterSet);
227 CF_TO_NS_MUTABLE_CAST_DECL(Data);
228 CF_TO_NS_CAST_DECL(CFDate, NSDate);
229 CF_TO_NS_MUTABLE_CAST_DECL(Dictionary);
230 CF_TO_NS_CAST_DECL(CFError, NSError);
231 CF_TO_NS_CAST_DECL(CFLocale, NSLocale);
232 CF_TO_NS_CAST_DECL(CFNumber, NSNumber);
233 CF_TO_NS_CAST_DECL(CFRunLoopTimer, NSTimer);
234 CF_TO_NS_CAST_DECL(CFTimeZone, NSTimeZone);
235 CF_TO_NS_MUTABLE_CAST_DECL(Set);
236 CF_TO_NS_CAST_DECL(CFReadStream, NSInputStream);
237 CF_TO_NS_CAST_DECL(CFWriteStream, NSOutputStream);
238 CF_TO_NS_MUTABLE_CAST_DECL(String);
239 CF_TO_NS_CAST_DECL(CFURL, NSURL);
241 #if defined(OS_IOS)
242 CF_TO_NS_CAST_DECL(CTFont, UIFont);
243 #else
244 CF_TO_NS_CAST_DECL(CTFont, NSFont);
245 #endif
247 #undef CF_TO_NS_CAST_DECL
248 #undef CF_TO_NS_MUTABLE_CAST_DECL
249 #undef OBJC_CPP_CLASS_DECL
251 namespace base {
252 namespace mac {
254 // CFCast<>() and CFCastStrict<>() cast a basic CFTypeRef to a more
255 // specific CoreFoundation type. The compatibility of the passed
256 // object is found by comparing its opaque type against the
257 // requested type identifier. If the supplied object is not
258 // compatible with the requested return type, CFCast<>() returns
259 // NULL and CFCastStrict<>() will DCHECK. Providing a NULL pointer
260 // to either variant results in NULL being returned without
261 // triggering any DCHECK.
263 // Example usage:
264 // CFNumberRef some_number = base::mac::CFCast<CFNumberRef>(
265 // CFArrayGetValueAtIndex(array, index));
267 // CFTypeRef hello = CFSTR("hello world");
268 // CFStringRef some_string = base::mac::CFCastStrict<CFStringRef>(hello);
270 template<typename T>
271 T CFCast(const CFTypeRef& cf_val);
273 template<typename T>
274 T CFCastStrict(const CFTypeRef& cf_val);
276 #define CF_CAST_DECL(TypeCF) \
277 template<> BASE_EXPORT TypeCF##Ref \
278 CFCast<TypeCF##Ref>(const CFTypeRef& cf_val);\
280 template<> BASE_EXPORT TypeCF##Ref \
281 CFCastStrict<TypeCF##Ref>(const CFTypeRef& cf_val);
283 CF_CAST_DECL(CFArray);
284 CF_CAST_DECL(CFBag);
285 CF_CAST_DECL(CFBoolean);
286 CF_CAST_DECL(CFData);
287 CF_CAST_DECL(CFDate);
288 CF_CAST_DECL(CFDictionary);
289 CF_CAST_DECL(CFNull);
290 CF_CAST_DECL(CFNumber);
291 CF_CAST_DECL(CFSet);
292 CF_CAST_DECL(CFString);
293 CF_CAST_DECL(CFURL);
294 CF_CAST_DECL(CFUUID);
296 CF_CAST_DECL(CGColor);
298 CF_CAST_DECL(CTFont);
299 CF_CAST_DECL(CTFontDescriptor);
300 CF_CAST_DECL(CTRun);
302 CF_CAST_DECL(SecACL);
303 CF_CAST_DECL(SecTrustedApplication);
305 #undef CF_CAST_DECL
307 #if defined(__OBJC__)
309 // ObjCCast<>() and ObjCCastStrict<>() cast a basic id to a more
310 // specific (NSObject-derived) type. The compatibility of the passed
311 // object is found by checking if it's a kind of the requested type
312 // identifier. If the supplied object is not compatible with the
313 // requested return type, ObjCCast<>() returns nil and
314 // ObjCCastStrict<>() will DCHECK. Providing a nil pointer to either
315 // variant results in nil being returned without triggering any DCHECK.
317 // The strict variant is useful when retrieving a value from a
318 // collection which only has values of a specific type, e.g. an
319 // NSArray of NSStrings. The non-strict variant is useful when
320 // retrieving values from data that you can't fully control. For
321 // example, a plist read from disk may be beyond your exclusive
322 // control, so you'd only want to check that the values you retrieve
323 // from it are of the expected types, but not crash if they're not.
325 // Example usage:
326 // NSString* version = base::mac::ObjCCast<NSString>(
327 // [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]);
329 // NSString* str = base::mac::ObjCCastStrict<NSString>(
330 // [ns_arr_of_ns_strs objectAtIndex:0]);
331 template<typename T>
332 T* ObjCCast(id objc_val) {
333 if ([objc_val isKindOfClass:[T class]]) {
334 return reinterpret_cast<T*>(objc_val);
336 return nil;
339 template<typename T>
340 T* ObjCCastStrict(id objc_val) {
341 T* rv = ObjCCast<T>(objc_val);
342 DCHECK(objc_val == nil || rv);
343 return rv;
346 #endif // defined(__OBJC__)
348 // Helper function for GetValueFromDictionary to create the error message
349 // that appears when a type mismatch is encountered.
350 BASE_EXPORT std::string GetValueFromDictionaryErrorMessage(
351 CFStringRef key, const std::string& expected_type, CFTypeRef value);
353 // Utility function to pull out a value from a dictionary, check its type, and
354 // return it. Returns NULL if the key is not present or of the wrong type.
355 template<typename T>
356 T GetValueFromDictionary(CFDictionaryRef dict, CFStringRef key) {
357 CFTypeRef value = CFDictionaryGetValue(dict, key);
358 T value_specific = CFCast<T>(value);
360 if (value && !value_specific) {
361 std::string expected_type = TypeNameForCFType(value_specific);
362 DLOG(WARNING) << GetValueFromDictionaryErrorMessage(key,
363 expected_type,
364 value);
367 return value_specific;
370 // Converts |path| to an autoreleased NSString. Returns nil if |path| is empty.
371 BASE_EXPORT NSString* FilePathToNSString(const FilePath& path);
373 // Converts |str| to a FilePath. Returns an empty path if |str| is nil.
374 BASE_EXPORT FilePath NSStringToFilePath(NSString* str);
376 } // namespace mac
377 } // namespace base
379 // Stream operations for CFTypes. They can be used with NSTypes as well
380 // by using the NSToCFCast methods above.
381 // e.g. LOG(INFO) << base::mac::NSToCFCast(@"foo");
382 // Operator << can not be overloaded for ObjectiveC types as the compiler
383 // can not distinguish between overloads for id with overloads for void*.
384 BASE_EXPORT extern std::ostream& operator<<(std::ostream& o,
385 const CFErrorRef err);
386 BASE_EXPORT extern std::ostream& operator<<(std::ostream& o,
387 const CFStringRef str);
389 #endif // BASE_MAC_FOUNDATION_UTIL_H_