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