foundation_util.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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.
  4. #ifndef BASE_MAC_FOUNDATION_UTIL_H_
  5. #define BASE_MAC_FOUNDATION_UTIL_H_
  6. #include <AvailabilityMacros.h>
  7. #include <CoreFoundation/CoreFoundation.h>
  8. #include <string>
  9. #include <vector>
  10. #include "base/base_export.h"
  11. #include "base/logging.h"
  12. #include "base/mac/scoped_cftyperef.h"
  13. #include "build/build_config.h"
  14. #if defined(__OBJC__)
  15. #import <Foundation/Foundation.h>
  16. @class NSFont;
  17. @class UIFont;
  18. #else // __OBJC__
  19. #include <CoreFoundation/CoreFoundation.h>
  20. class NSBundle;
  21. class NSFont;
  22. class NSString;
  23. class UIFont;
  24. #endif // __OBJC__
  25. #if defined(OS_IOS)
  26. #include <CoreText/CoreText.h>
  27. #else
  28. #include <ApplicationServices/ApplicationServices.h>
  29. #endif
  30. // Adapted from NSPathUtilities.h and NSObjCRuntime.h.
  31. #if __LP64__ || NS_BUILD_32_LIKE_64
  32. enum NSSearchPathDirectory : unsigned long;
  33. typedef unsigned long NSSearchPathDomainMask;
  34. #else
  35. enum NSSearchPathDirectory : unsigned int;
  36. typedef unsigned int NSSearchPathDomainMask;
  37. #endif
  38. typedef struct CF_BRIDGED_TYPE(id) __SecCertificate* SecCertificateRef;
  39. typedef struct CF_BRIDGED_TYPE(id) __SecKey* SecKeyRef;
  40. typedef struct CF_BRIDGED_TYPE(id) __SecPolicy* SecPolicyRef;
  41. namespace base {
  42. class FilePath;
  43. namespace mac {
  44. // Returns true if the application is running from a bundle
  45. BASE_EXPORT bool AmIBundled();
  46. BASE_EXPORT void SetOverrideAmIBundled(bool value);
  47. #if defined(UNIT_TEST)
  48. // This is required because instantiating some tests requires checking the
  49. // directory structure, which sets the AmIBundled cache state. Individual tests
  50. // may or may not be bundled, and this would trip them up if the cache weren't
  51. // cleared. This should not be called from individual tests, just from test
  52. // instantiation code that gets a path from PathService.
  53. BASE_EXPORT void ClearAmIBundledCache();
  54. #endif
  55. // Returns true if this process is marked as a "Background only process".
  56. BASE_EXPORT bool IsBackgroundOnlyProcess();
  57. // Returns the path to a resource within the framework bundle.
  58. BASE_EXPORT FilePath PathForFrameworkBundleResource(CFStringRef resourceName);
  59. // Returns the creator code associated with the CFBundleRef at bundle.
  60. OSType CreatorCodeForCFBundleRef(CFBundleRef bundle);
  61. // Returns the creator code associated with this application, by calling
  62. // CreatorCodeForCFBundleRef for the application's main bundle. If this
  63. // information cannot be determined, returns kUnknownType ('????'). This
  64. // does not respect the override app bundle because it's based on CFBundle
  65. // instead of NSBundle, and because callers probably don't want the override
  66. // app bundle's creator code anyway.
  67. BASE_EXPORT OSType CreatorCodeForApplication();
  68. // Searches for directories for the given key in only the given |domain_mask|.
  69. // If found, fills result (which must always be non-NULL) with the
  70. // first found directory and returns true. Otherwise, returns false.
  71. BASE_EXPORT bool GetSearchPathDirectory(NSSearchPathDirectory directory,
  72. NSSearchPathDomainMask domain_mask,
  73. FilePath* result);
  74. // Searches for directories for the given key in only the local domain.
  75. // If found, fills result (which must always be non-NULL) with the
  76. // first found directory and returns true. Otherwise, returns false.
  77. BASE_EXPORT bool GetLocalDirectory(NSSearchPathDirectory directory,
  78. FilePath* result);
  79. // Searches for directories for the given key in only the user domain.
  80. // If found, fills result (which must always be non-NULL) with the
  81. // first found directory and returns true. Otherwise, returns false.
  82. BASE_EXPORT bool GetUserDirectory(NSSearchPathDirectory directory,
  83. FilePath* result);
  84. // Returns the ~/Library directory.
  85. BASE_EXPORT FilePath GetUserLibraryPath();
  86. // Takes a path to an (executable) binary and tries to provide the path to an
  87. // application bundle containing it. It takes the outermost bundle that it can
  88. // find (so for "/Foo/Bar.app/.../Baz.app/..." it produces "/Foo/Bar.app").
  89. // |exec_name| - path to the binary
  90. // returns - path to the application bundle, or empty on error
  91. BASE_EXPORT FilePath GetAppBundlePath(const FilePath& exec_name);
  92. #define TYPE_NAME_FOR_CF_TYPE_DECL(TypeCF) \
  93. BASE_EXPORT std::string TypeNameForCFType(TypeCF##Ref)
  94. TYPE_NAME_FOR_CF_TYPE_DECL(CFArray);
  95. TYPE_NAME_FOR_CF_TYPE_DECL(CFBag);
  96. TYPE_NAME_FOR_CF_TYPE_DECL(CFBoolean);
  97. TYPE_NAME_FOR_CF_TYPE_DECL(CFData);
  98. TYPE_NAME_FOR_CF_TYPE_DECL(CFDate);
  99. TYPE_NAME_FOR_CF_TYPE_DECL(CFDictionary);
  100. TYPE_NAME_FOR_CF_TYPE_DECL(CFNull);
  101. TYPE_NAME_FOR_CF_TYPE_DECL(CFNumber);
  102. TYPE_NAME_FOR_CF_TYPE_DECL(CFSet);
  103. TYPE_NAME_FOR_CF_TYPE_DECL(CFString);
  104. TYPE_NAME_FOR_CF_TYPE_DECL(CFURL);
  105. TYPE_NAME_FOR_CF_TYPE_DECL(CFUUID);
  106. TYPE_NAME_FOR_CF_TYPE_DECL(CGColor);
  107. TYPE_NAME_FOR_CF_TYPE_DECL(CTFont);
  108. TYPE_NAME_FOR_CF_TYPE_DECL(CTRun);
  109. TYPE_NAME_FOR_CF_TYPE_DECL(SecCertificate);
  110. TYPE_NAME_FOR_CF_TYPE_DECL(SecKey);
  111. TYPE_NAME_FOR_CF_TYPE_DECL(SecPolicy);
  112. #undef TYPE_NAME_FOR_CF_TYPE_DECL
  113. // Retain/release calls for memory management in C++.
  114. BASE_EXPORT void NSObjectRetain(void* obj);
  115. BASE_EXPORT void NSObjectRelease(void* obj);
  116. // Returns the base bundle ID, which can be set by SetBaseBundleID but
  117. // defaults to a reasonable string. This never returns NULL. BaseBundleID
  118. // returns a pointer to static storage that must not be freed.
  119. BASE_EXPORT const char* BaseBundleID();
  120. // Sets the base bundle ID to override the default. The implementation will
  121. // make its own copy of new_base_bundle_id.
  122. BASE_EXPORT void SetBaseBundleID(const char* new_base_bundle_id);
  123. } // namespace mac
  124. } // namespace base
  125. #if !defined(__OBJC__)
  126. #define OBJC_CPP_CLASS_DECL(x) class x;
  127. #else // __OBJC__
  128. #define OBJC_CPP_CLASS_DECL(x)
  129. #endif // __OBJC__
  130. // Convert toll-free bridged CFTypes to NSTypes and vice-versa. This does not
  131. // autorelease |cf_val|. This is useful for the case where there is a CFType in
  132. // a call that expects an NSType and the compiler is complaining about const
  133. // casting problems.
  134. // The calls are used like this:
  135. // NSString *foo = CFToNSCast(CFSTR("Hello"));
  136. // CFStringRef foo2 = NSToCFCast(@"Hello");
  137. // The macro magic below is to enforce safe casting. It could possibly have
  138. // been done using template function specialization, but template function
  139. // specialization doesn't always work intuitively,
  140. // (http://www.gotw.ca/publications/mill17.htm) so the trusty combination
  141. // of macros and function overloading is used instead.
  142. #define CF_TO_NS_CAST_DECL(TypeCF, TypeNS) \
  143. OBJC_CPP_CLASS_DECL(TypeNS) \
  144. \
  145. namespace base { \
  146. namespace mac { \
  147. BASE_EXPORT TypeNS* CFToNSCast(TypeCF##Ref cf_val); \
  148. BASE_EXPORT TypeCF##Ref NSToCFCast(TypeNS* ns_val); \
  149. } \
  150. }
  151. #define CF_TO_NS_MUTABLE_CAST_DECL(name) \
  152. CF_TO_NS_CAST_DECL(CF##name, NS##name) \
  153. OBJC_CPP_CLASS_DECL(NSMutable##name) \
  154. \
  155. namespace base { \
  156. namespace mac { \
  157. BASE_EXPORT NSMutable##name* CFToNSCast(CFMutable##name##Ref cf_val); \
  158. BASE_EXPORT CFMutable##name##Ref NSToCFCast(NSMutable##name* ns_val); \
  159. } \
  160. }
  161. // List of toll-free bridged types taken from:
  162. // http://www.cocoadev.com/index.pl?TollFreeBridged
  163. CF_TO_NS_MUTABLE_CAST_DECL(Array)
  164. CF_TO_NS_MUTABLE_CAST_DECL(AttributedString)
  165. CF_TO_NS_CAST_DECL(CFCalendar, NSCalendar)
  166. CF_TO_NS_MUTABLE_CAST_DECL(CharacterSet)
  167. CF_TO_NS_MUTABLE_CAST_DECL(Data)
  168. CF_TO_NS_CAST_DECL(CFDate, NSDate)
  169. CF_TO_NS_MUTABLE_CAST_DECL(Dictionary)
  170. CF_TO_NS_CAST_DECL(CFError, NSError)
  171. CF_TO_NS_CAST_DECL(CFLocale, NSLocale)
  172. CF_TO_NS_CAST_DECL(CFNumber, NSNumber)
  173. CF_TO_NS_CAST_DECL(CFRunLoopTimer, NSTimer)
  174. CF_TO_NS_CAST_DECL(CFTimeZone, NSTimeZone)
  175. CF_TO_NS_MUTABLE_CAST_DECL(Set)
  176. CF_TO_NS_CAST_DECL(CFReadStream, NSInputStream)
  177. CF_TO_NS_CAST_DECL(CFWriteStream, NSOutputStream)
  178. CF_TO_NS_MUTABLE_CAST_DECL(String)
  179. CF_TO_NS_CAST_DECL(CFURL, NSURL)
  180. #if defined(OS_IOS)
  181. CF_TO_NS_CAST_DECL(CTFont, UIFont)
  182. #else
  183. CF_TO_NS_CAST_DECL(CTFont, NSFont)
  184. #endif
  185. #undef CF_TO_NS_CAST_DECL
  186. #undef CF_TO_NS_MUTABLE_CAST_DECL
  187. #undef OBJC_CPP_CLASS_DECL
  188. namespace base {
  189. namespace mac {
  190. // CFCast<>() and CFCastStrict<>() cast a basic CFTypeRef to a more
  191. // specific CoreFoundation type. The compatibility of the passed
  192. // object is found by comparing its opaque type against the
  193. // requested type identifier. If the supplied object is not
  194. // compatible with the requested return type, CFCast<>() returns
  195. // NULL and CFCastStrict<>() will DCHECK. Providing a NULL pointer
  196. // to either variant results in NULL being returned without
  197. // triggering any DCHECK.
  198. //
  199. // Example usage:
  200. // CFNumberRef some_number = base::mac::CFCast<CFNumberRef>(
  201. // CFArrayGetValueAtIndex(array, index));
  202. //
  203. // CFTypeRef hello = CFSTR("hello world");
  204. // CFStringRef some_string = base::mac::CFCastStrict<CFStringRef>(hello);
  205. template<typename T>
  206. T CFCast(const CFTypeRef& cf_val);
  207. template<typename T>
  208. T CFCastStrict(const CFTypeRef& cf_val);
  209. #define CF_CAST_DECL(TypeCF) \
  210. template <> \
  211. BASE_EXPORT TypeCF##Ref CFCast<TypeCF##Ref>(const CFTypeRef& cf_val); \
  212. \
  213. template <> \
  214. BASE_EXPORT TypeCF##Ref CFCastStrict<TypeCF##Ref>(const CFTypeRef& cf_val)
  215. CF_CAST_DECL(CFArray);
  216. CF_CAST_DECL(CFBag);
  217. CF_CAST_DECL(CFBoolean);
  218. CF_CAST_DECL(CFData);
  219. CF_CAST_DECL(CFDate);
  220. CF_CAST_DECL(CFDictionary);
  221. CF_CAST_DECL(CFNull);
  222. CF_CAST_DECL(CFNumber);
  223. CF_CAST_DECL(CFSet);
  224. CF_CAST_DECL(CFString);
  225. CF_CAST_DECL(CFURL);
  226. CF_CAST_DECL(CFUUID);
  227. CF_CAST_DECL(CGColor);
  228. CF_CAST_DECL(CTFont);
  229. CF_CAST_DECL(CTFontDescriptor);
  230. CF_CAST_DECL(CTRun);
  231. CF_CAST_DECL(SecCertificate);
  232. CF_CAST_DECL(SecKey);
  233. CF_CAST_DECL(SecPolicy);
  234. #undef CF_CAST_DECL
  235. #if defined(__OBJC__)
  236. // ObjCCast<>() and ObjCCastStrict<>() cast a basic id to a more
  237. // specific (NSObject-derived) type. The compatibility of the passed
  238. // object is found by checking if it's a kind of the requested type
  239. // identifier. If the supplied object is not compatible with the
  240. // requested return type, ObjCCast<>() returns nil and
  241. // ObjCCastStrict<>() will DCHECK. Providing a nil pointer to either
  242. // variant results in nil being returned without triggering any DCHECK.
  243. //
  244. // The strict variant is useful when retrieving a value from a
  245. // collection which only has values of a specific type, e.g. an
  246. // NSArray of NSStrings. The non-strict variant is useful when
  247. // retrieving values from data that you can't fully control. For
  248. // example, a plist read from disk may be beyond your exclusive
  249. // control, so you'd only want to check that the values you retrieve
  250. // from it are of the expected types, but not crash if they're not.
  251. //
  252. // Example usage:
  253. // NSString* version = base::mac::ObjCCast<NSString>(
  254. // [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]);
  255. //
  256. // NSString* str = base::mac::ObjCCastStrict<NSString>(
  257. // [ns_arr_of_ns_strs objectAtIndex:0]);
  258. template<typename T>
  259. T* ObjCCast(id objc_val) {
  260. if ([objc_val isKindOfClass:[T class]]) {
  261. return reinterpret_cast<T*>(objc_val);
  262. }
  263. return nil;
  264. }
  265. template<typename T>
  266. T* ObjCCastStrict(id objc_val) {
  267. T* rv = ObjCCast<T>(objc_val);
  268. DCHECK(objc_val == nil || rv);
  269. return rv;
  270. }
  271. #endif // defined(__OBJC__)
  272. // Helper function for GetValueFromDictionary to create the error message
  273. // that appears when a type mismatch is encountered.
  274. BASE_EXPORT std::string GetValueFromDictionaryErrorMessage(
  275. CFStringRef key, const std::string& expected_type, CFTypeRef value);
  276. // Utility function to pull out a value from a dictionary, check its type, and
  277. // return it. Returns NULL if the key is not present or of the wrong type.
  278. template<typename T>
  279. T GetValueFromDictionary(CFDictionaryRef dict, CFStringRef key) {
  280. CFTypeRef value = CFDictionaryGetValue(dict, key);
  281. T value_specific = CFCast<T>(value);
  282. if (value && !value_specific) {
  283. std::string expected_type = TypeNameForCFType(value_specific);
  284. DLOG(WARNING) << GetValueFromDictionaryErrorMessage(key,
  285. expected_type,
  286. value);
  287. }
  288. return value_specific;
  289. }
  290. // Converts |path| to an autoreleased NSURL. Returns nil if |path| is empty.
  291. BASE_EXPORT NSURL* FilePathToNSURL(const FilePath& path);
  292. // Converts |path| to an autoreleased NSString. Returns nil if |path| is empty.
  293. BASE_EXPORT NSString* FilePathToNSString(const FilePath& path);
  294. // Converts |str| to a FilePath. Returns an empty path if |str| is nil.
  295. BASE_EXPORT FilePath NSStringToFilePath(NSString* str);
  296. // Converts a non-null |path| to a CFURLRef. |path| must not be empty.
  297. //
  298. // This function only uses manually-owned resources, so it does not depend on an
  299. // NSAutoreleasePool being set up on the current thread.
  300. BASE_EXPORT base::ScopedCFTypeRef<CFURLRef> FilePathToCFURL(
  301. const FilePath& path);
  302. #if defined(__OBJC__)
  303. // Converts |range| to an NSRange, returning the new range in |range_out|.
  304. // Returns true if conversion was successful, false if the values of |range|
  305. // could not be converted to NSUIntegers.
  306. BASE_EXPORT bool CFRangeToNSRange(CFRange range,
  307. NSRange* range_out) WARN_UNUSED_RESULT;
  308. #endif // defined(__OBJC__)
  309. } // namespace mac
  310. } // namespace base
  311. // Stream operations for CFTypes. They can be used with NSTypes as well
  312. // by using the NSToCFCast methods above.
  313. // e.g. LOG(INFO) << base::mac::NSToCFCast(@"foo");
  314. // Operator << can not be overloaded for ObjectiveC types as the compiler
  315. // can not distinguish between overloads for id with overloads for void*.
  316. BASE_EXPORT extern std::ostream& operator<<(std::ostream& o,
  317. const CFErrorRef err);
  318. BASE_EXPORT extern std::ostream& operator<<(std::ostream& o,
  319. const CFStringRef str);
  320. BASE_EXPORT extern std::ostream& operator<<(std::ostream& o, CFRange);
  321. #if defined(__OBJC__)
  322. BASE_EXPORT extern std::ostream& operator<<(std::ostream& o, id);
  323. BASE_EXPORT extern std::ostream& operator<<(std::ostream& o, NSRange);
  324. BASE_EXPORT extern std::ostream& operator<<(std::ostream& o, SEL);
  325. #if !defined(OS_IOS)
  326. BASE_EXPORT extern std::ostream& operator<<(std::ostream& o, NSPoint);
  327. BASE_EXPORT extern std::ostream& operator<<(std::ostream& o, NSRect);
  328. BASE_EXPORT extern std::ostream& operator<<(std::ostream& o, NSSize);
  329. #endif
  330. #endif
  331. #endif // BASE_MAC_FOUNDATION_UTIL_H_