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>
13 #include "base/base_export.h"
14 #include "base/logging.h"
15 #include "base/mac/scoped_cftyperef.h"
18 #import <Foundation/Foundation.h>
22 #include <CoreFoundation/CoreFoundation.h>
30 #include <CoreText/CoreText.h>
32 #include <ApplicationServices/ApplicationServices.h>
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
42 #define CR_FORWARD_ENUM(_type, _name) _type _name
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
;
50 typedef CR_FORWARD_ENUM(unsigned int, NSSearchPathDirectory
);
51 typedef unsigned int NSSearchPathDomainMask
;
54 typedef struct OpaqueSecTrustRef
* SecACLRef
;
55 typedef struct OpaqueSecTrustedApplicationRef
* SecTrustedApplicationRef
;
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();
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
,
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
,
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
,
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
);
180 #if !defined(__OBJC__)
181 #define OBJC_CPP_CLASS_DECL(x) class x;
183 #define OBJC_CPP_CLASS_DECL(x)
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
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) \
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) \
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
);
242 CF_TO_NS_CAST_DECL(CTFont
, UIFont
);
244 CF_TO_NS_CAST_DECL(CTFont
, NSFont
);
247 #undef CF_TO_NS_CAST_DECL
248 #undef CF_TO_NS_MUTABLE_CAST_DECL
249 #undef OBJC_CPP_CLASS_DECL
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.
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);
271 T
CFCast(const CFTypeRef
& cf_val
);
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
);
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
);
292 CF_CAST_DECL(CFString
);
294 CF_CAST_DECL(CFUUID
);
296 CF_CAST_DECL(CGColor
);
298 CF_CAST_DECL(CTFont
);
301 CF_CAST_DECL(SecACL
);
302 CF_CAST_DECL(SecTrustedApplication
);
306 #if defined(__OBJC__)
308 // ObjCCast<>() and ObjCCastStrict<>() cast a basic id to a more
309 // specific (NSObject-derived) type. The compatibility of the passed
310 // object is found by checking if it's a kind of the requested type
311 // identifier. If the supplied object is not compatible with the
312 // requested return type, ObjCCast<>() returns nil and
313 // ObjCCastStrict<>() will DCHECK. Providing a nil pointer to either
314 // variant results in nil being returned without triggering any DCHECK.
316 // The strict variant is useful when retrieving a value from a
317 // collection which only has values of a specific type, e.g. an
318 // NSArray of NSStrings. The non-strict variant is useful when
319 // retrieving values from data that you can't fully control. For
320 // example, a plist read from disk may be beyond your exclusive
321 // control, so you'd only want to check that the values you retrieve
322 // from it are of the expected types, but not crash if they're not.
325 // NSString* version = base::mac::ObjCCast<NSString>(
326 // [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]);
328 // NSString* str = base::mac::ObjCCastStrict<NSString>(
329 // [ns_arr_of_ns_strs objectAtIndex:0]);
331 T
* ObjCCast(id objc_val
) {
332 if ([objc_val isKindOfClass
:[T
class]]) {
333 return reinterpret_cast<T
*>(objc_val
);
339 T
* ObjCCastStrict(id objc_val
) {
340 T
* rv
= ObjCCast
<T
>(objc_val
);
341 DCHECK(objc_val
== nil
|| rv
);
345 #endif // defined(__OBJC__)
347 // Helper function for GetValueFromDictionary to create the error message
348 // that appears when a type mismatch is encountered.
349 BASE_EXPORT
std::string
GetValueFromDictionaryErrorMessage(
350 CFStringRef key
, const std::string
& expected_type
, CFTypeRef value
);
352 // Utility function to pull out a value from a dictionary, check its type, and
353 // return it. Returns NULL if the key is not present or of the wrong type.
355 T
GetValueFromDictionary(CFDictionaryRef dict
, CFStringRef key
) {
356 CFTypeRef value
= CFDictionaryGetValue(dict
, key
);
357 T value_specific
= CFCast
<T
>(value
);
359 if (value
&& !value_specific
) {
360 std::string expected_type
= TypeNameForCFType(value_specific
);
361 DLOG(WARNING
) << GetValueFromDictionaryErrorMessage(key
,
366 return value_specific
;
369 // Converts |path| to an autoreleased NSString. Returns nil if |path| is empty.
370 BASE_EXPORT NSString
* FilePathToNSString(const FilePath
& path
);
372 // Converts |str| to a FilePath. Returns an empty path if |str| is nil.
373 BASE_EXPORT FilePath
NSStringToFilePath(NSString
* str
);
378 // Stream operations for CFTypes. They can be used with NSTypes as well
379 // by using the NSToCFCast methods above.
380 // e.g. LOG(INFO) << base::mac::NSToCFCast(@"foo");
381 // Operator << can not be overloaded for ObjectiveC types as the compiler
382 // can not distinguish between overloads for id with overloads for void*.
383 BASE_EXPORT
extern std::ostream
& operator<<(std::ostream
& o
,
384 const CFErrorRef err
);
385 BASE_EXPORT
extern std::ostream
& operator<<(std::ostream
& o
,
386 const CFStringRef str
);
388 #endif // BASE_MAC_FOUNDATION_UTIL_H_