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
// Returns true if this process is marked as a "Background only process".
68
BASE_EXPORT bool IsBackgroundOnlyProcess();
70
// Returns the path to a resource within the framework bundle.
71
BASE_EXPORT FilePath PathForFrameworkBundleResource(CFStringRef resourceName);
73
// Returns the creator code associated with the CFBundleRef at bundle.
74
OSType CreatorCodeForCFBundleRef(CFBundleRef bundle);
76
// Returns the creator code associated with this application, by calling
77
// CreatorCodeForCFBundleRef for the application's main bundle. If this
78
// information cannot be determined, returns kUnknownType ('????'). This
79
// does not respect the override app bundle because it's based on CFBundle
80
// instead of NSBundle, and because callers probably don't want the override
81
// app bundle's creator code anyway.
82
BASE_EXPORT OSType CreatorCodeForApplication();
84
// Searches for directories for the given key in only the given |domain_mask|.
85
// If found, fills result (which must always be non-NULL) with the
86
// first found directory and returns true. Otherwise, returns false.
87
BASE_EXPORT bool GetSearchPathDirectory(NSSearchPathDirectory directory,
88
NSSearchPathDomainMask domain_mask,
91
// Searches for directories for the given key in only the local domain.
92
// If found, fills result (which must always be non-NULL) with the
93
// first found directory and returns true. Otherwise, returns false.
94
BASE_EXPORT bool GetLocalDirectory(NSSearchPathDirectory directory,
97
// Searches for directories for the given key in only the user domain.
98
// If found, fills result (which must always be non-NULL) with the
99
// first found directory and returns true. Otherwise, returns false.
100
BASE_EXPORT bool GetUserDirectory(NSSearchPathDirectory directory,
103
// Returns the ~/Library directory.
104
BASE_EXPORT FilePath GetUserLibraryPath();
106
// Takes a path to an (executable) binary and tries to provide the path to an
107
// application bundle containing it. It takes the outermost bundle that it can
108
// find (so for "/Foo/Bar.app/.../Baz.app/..." it produces "/Foo/Bar.app").
109
// |exec_name| - path to the binary
110
// returns - path to the application bundle, or empty on error
111
BASE_EXPORT FilePath GetAppBundlePath(const FilePath& exec_name);
113
#define TYPE_NAME_FOR_CF_TYPE_DECL(TypeCF) \
114
BASE_EXPORT std::string TypeNameForCFType(TypeCF##Ref);
116
TYPE_NAME_FOR_CF_TYPE_DECL(CFArray);
117
TYPE_NAME_FOR_CF_TYPE_DECL(CFBag);
118
TYPE_NAME_FOR_CF_TYPE_DECL(CFBoolean);
119
TYPE_NAME_FOR_CF_TYPE_DECL(CFData);
120
TYPE_NAME_FOR_CF_TYPE_DECL(CFDate);
121
TYPE_NAME_FOR_CF_TYPE_DECL(CFDictionary);
122
TYPE_NAME_FOR_CF_TYPE_DECL(CFNull);
123
TYPE_NAME_FOR_CF_TYPE_DECL(CFNumber);
124
TYPE_NAME_FOR_CF_TYPE_DECL(CFSet);
125
TYPE_NAME_FOR_CF_TYPE_DECL(CFString);
126
TYPE_NAME_FOR_CF_TYPE_DECL(CFURL);
127
TYPE_NAME_FOR_CF_TYPE_DECL(CFUUID);
129
TYPE_NAME_FOR_CF_TYPE_DECL(CGColor);
131
TYPE_NAME_FOR_CF_TYPE_DECL(CTFont);
132
TYPE_NAME_FOR_CF_TYPE_DECL(CTRun);
134
#undef TYPE_NAME_FOR_CF_TYPE_DECL
136
// Retain/release calls for memory management in C++.
137
BASE_EXPORT void NSObjectRetain(void* obj);
138
BASE_EXPORT void NSObjectRelease(void* obj);
140
// CFTypeRefToNSObjectAutorelease transfers ownership of a Core Foundation
141
// object (one derived from CFTypeRef) to the Foundation memory management
142
// system. In a traditional managed-memory environment, cf_object is
143
// autoreleased and returned as an NSObject. In a garbage-collected
144
// environment, cf_object is marked as eligible for garbage collection.
146
// This function should only be used to convert a concrete CFTypeRef type to
147
// its equivalent "toll-free bridged" NSObject subclass, for example,
148
// converting a CFStringRef to NSString.
150
// By calling this function, callers relinquish any ownership claim to
151
// cf_object. In a managed-memory environment, the object's ownership will be
152
// managed by the innermost NSAutoreleasePool, so after this function returns,
153
// callers should not assume that cf_object is valid any longer than the
154
// returned NSObject.
156
// Returns an id, typed here for C++'s sake as a void*.
157
BASE_EXPORT void* CFTypeRefToNSObjectAutorelease(CFTypeRef cf_object);
159
// Returns the base bundle ID, which can be set by SetBaseBundleID but
160
// defaults to a reasonable string. This never returns NULL. BaseBundleID
161
// returns a pointer to static storage that must not be freed.
162
BASE_EXPORT const char* BaseBundleID();
164
// Sets the base bundle ID to override the default. The implementation will
165
// make its own copy of new_base_bundle_id.
166
BASE_EXPORT void SetBaseBundleID(const char* new_base_bundle_id);
171
#if !defined(__OBJC__)
172
#define OBJC_CPP_CLASS_DECL(x) class x;
174
#define OBJC_CPP_CLASS_DECL(x)
177
// Convert toll-free bridged CFTypes to NSTypes and vice-versa. This does not
178
// autorelease |cf_val|. This is useful for the case where there is a CFType in
179
// a call that expects an NSType and the compiler is complaining about const
181
// The calls are used like this:
182
// NSString *foo = CFToNSCast(CFSTR("Hello"));
183
// CFStringRef foo2 = NSToCFCast(@"Hello");
184
// The macro magic below is to enforce safe casting. It could possibly have
185
// been done using template function specialization, but template function
186
// specialization doesn't always work intuitively,
187
// (http://www.gotw.ca/publications/mill17.htm) so the trusty combination
188
// of macros and function overloading is used instead.
190
#define CF_TO_NS_CAST_DECL(TypeCF, TypeNS) \
191
OBJC_CPP_CLASS_DECL(TypeNS) \
195
BASE_EXPORT TypeNS* CFToNSCast(TypeCF##Ref cf_val); \
196
BASE_EXPORT TypeCF##Ref NSToCFCast(TypeNS* ns_val); \
200
#define CF_TO_NS_MUTABLE_CAST_DECL(name) \
201
CF_TO_NS_CAST_DECL(CF##name, NS##name) \
202
OBJC_CPP_CLASS_DECL(NSMutable##name) \
206
BASE_EXPORT NSMutable##name* CFToNSCast(CFMutable##name##Ref cf_val); \
207
BASE_EXPORT CFMutable##name##Ref NSToCFCast(NSMutable##name* ns_val); \
211
// List of toll-free bridged types taken from:
212
// http://www.cocoadev.com/index.pl?TollFreeBridged
214
CF_TO_NS_MUTABLE_CAST_DECL(Array);
215
CF_TO_NS_MUTABLE_CAST_DECL(AttributedString);
216
CF_TO_NS_CAST_DECL(CFCalendar, NSCalendar);
217
CF_TO_NS_MUTABLE_CAST_DECL(CharacterSet);
218
CF_TO_NS_MUTABLE_CAST_DECL(Data);
219
CF_TO_NS_CAST_DECL(CFDate, NSDate);
220
CF_TO_NS_MUTABLE_CAST_DECL(Dictionary);
221
CF_TO_NS_CAST_DECL(CFError, NSError);
222
CF_TO_NS_CAST_DECL(CFLocale, NSLocale);
223
CF_TO_NS_CAST_DECL(CFNumber, NSNumber);
224
CF_TO_NS_CAST_DECL(CFRunLoopTimer, NSTimer);
225
CF_TO_NS_CAST_DECL(CFTimeZone, NSTimeZone);
226
CF_TO_NS_MUTABLE_CAST_DECL(Set);
227
CF_TO_NS_CAST_DECL(CFReadStream, NSInputStream);
228
CF_TO_NS_CAST_DECL(CFWriteStream, NSOutputStream);
229
CF_TO_NS_MUTABLE_CAST_DECL(String);
230
CF_TO_NS_CAST_DECL(CFURL, NSURL);
233
CF_TO_NS_CAST_DECL(CTFont, UIFont);
235
CF_TO_NS_CAST_DECL(CTFont, NSFont);
238
#undef CF_TO_NS_CAST_DECL
239
#undef CF_TO_NS_MUTABLE_CAST_DECL
240
#undef OBJC_CPP_CLASS_DECL
245
// CFCast<>() and CFCastStrict<>() cast a basic CFTypeRef to a more
246
// specific CoreFoundation type. The compatibility of the passed
247
// object is found by comparing its opaque type against the
248
// requested type identifier. If the supplied object is not
249
// compatible with the requested return type, CFCast<>() returns
250
// NULL and CFCastStrict<>() will DCHECK. Providing a NULL pointer
251
// to either variant results in NULL being returned without
252
// triggering any DCHECK.
255
// CFNumberRef some_number = base::mac::CFCast<CFNumberRef>(
256
// CFArrayGetValueAtIndex(array, index));
258
// CFTypeRef hello = CFSTR("hello world");
259
// CFStringRef some_string = base::mac::CFCastStrict<CFStringRef>(hello);
262
T CFCast(const CFTypeRef& cf_val);
265
T CFCastStrict(const CFTypeRef& cf_val);
267
#define CF_CAST_DECL(TypeCF) \
268
template<> BASE_EXPORT TypeCF##Ref \
269
CFCast<TypeCF##Ref>(const CFTypeRef& cf_val);\
271
template<> BASE_EXPORT TypeCF##Ref \
272
CFCastStrict<TypeCF##Ref>(const CFTypeRef& cf_val);
274
CF_CAST_DECL(CFArray);
276
CF_CAST_DECL(CFBoolean);
277
CF_CAST_DECL(CFData);
278
CF_CAST_DECL(CFDate);
279
CF_CAST_DECL(CFDictionary);
280
CF_CAST_DECL(CFNull);
281
CF_CAST_DECL(CFNumber);
283
CF_CAST_DECL(CFString);
285
CF_CAST_DECL(CFUUID);
287
CF_CAST_DECL(CGColor);
289
CF_CAST_DECL(CTFont);
292
CF_CAST_DECL(SecACL);
293
CF_CAST_DECL(SecTrustedApplication);
297
#if defined(__OBJC__)
299
// ObjCCast<>() and ObjCCastStrict<>() cast a basic id to a more
300
// specific (NSObject-derived) type. The compatibility of the passed
301
// object is found by checking if it's a kind of the requested type
302
// identifier. If the supplied object is not compatible with the
303
// requested return type, ObjCCast<>() returns nil and
304
// ObjCCastStrict<>() will DCHECK. Providing a nil pointer to either
305
// variant results in nil being returned without triggering any DCHECK.
307
// The strict variant is useful when retrieving a value from a
308
// collection which only has values of a specific type, e.g. an
309
// NSArray of NSStrings. The non-strict variant is useful when
310
// retrieving values from data that you can't fully control. For
311
// example, a plist read from disk may be beyond your exclusive
312
// control, so you'd only want to check that the values you retrieve
313
// from it are of the expected types, but not crash if they're not.
316
// NSString* version = base::mac::ObjCCast<NSString>(
317
// [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]);
319
// NSString* str = base::mac::ObjCCastStrict<NSString>(
320
// [ns_arr_of_ns_strs objectAtIndex:0]);
322
T* ObjCCast(id objc_val) {
323
if ([objc_val isKindOfClass:[T class]]) {
324
return reinterpret_cast<T*>(objc_val);
330
T* ObjCCastStrict(id objc_val) {
331
T* rv = ObjCCast<T>(objc_val);
332
DCHECK(objc_val == nil || rv);
336
#endif // defined(__OBJC__)
338
// Helper function for GetValueFromDictionary to create the error message
339
// that appears when a type mismatch is encountered.
340
BASE_EXPORT std::string GetValueFromDictionaryErrorMessage(
341
CFStringRef key, const std::string& expected_type, CFTypeRef value);
343
// Utility function to pull out a value from a dictionary, check its type, and
344
// return it. Returns NULL if the key is not present or of the wrong type.
346
T GetValueFromDictionary(CFDictionaryRef dict, CFStringRef key) {
347
CFTypeRef value = CFDictionaryGetValue(dict, key);
348
T value_specific = CFCast<T>(value);
350
if (value && !value_specific) {
351
std::string expected_type = TypeNameForCFType(value_specific);
352
DLOG(WARNING) << GetValueFromDictionaryErrorMessage(key,
357
return value_specific;
360
// Converts |path| to an autoreleased NSString. Returns nil if |path| is empty.
361
BASE_EXPORT NSString* FilePathToNSString(const FilePath& path);
363
// Converts |str| to a FilePath. Returns an empty path if |str| is nil.
364
BASE_EXPORT FilePath NSStringToFilePath(NSString* str);
369
// Stream operations for CFTypes. They can be used with NSTypes as well
370
// by using the NSToCFCast methods above.
371
// e.g. LOG(INFO) << base::mac::NSToCFCast(@"foo");
372
// Operator << can not be overloaded for ObjectiveC types as the compiler
373
// can not distinguish between overloads for id with overloads for void*.
374
BASE_EXPORT extern std::ostream& operator<<(std::ostream& o,
375
const CFErrorRef err);
376
BASE_EXPORT extern std::ostream& operator<<(std::ostream& o,
377
const CFStringRef str);
379
#endif // BASE_MAC_FOUNDATION_UTIL_H_