foundation_util.h 15 KB

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