44 *
55 */
66
7- #include < mach-o/dyld.h>
87#include < limits.h>
8+ #include < vector>
9+ #include < mach-o/dyld.h>
10+ #include < CoreFoundation/CoreFoundation.h>
11+ #include < CoreFoundation/CFBundle.h>
912#include " FilePath.h"
1013
1114namespace PokemonAutomation {
1215namespace Filesystem {
1316
1417
15- Path application_path (){
18+ Path application_binary_path (){
1619 char buffer[PATH_MAX ];
1720 uint32_t size = sizeof (buffer);
1821 if (_NSGetExecutablePath (buffer, &size) == 0 ) {
@@ -23,5 +26,54 @@ Path application_path(){
2326
2427
2528
29+ std::filesystem::path CFString_to_path (CFStringRef cfString) {
30+ if (!cfString) {
31+ return {};
32+ }
33+
34+ // 1. Get the exact buffer size needed for the file system representation
35+ CFIndex maxLength = CFStringGetMaximumSizeOfFileSystemRepresentation (cfString);
36+
37+ // 2. Allocate a buffer to store the raw file system bytes
38+ std::vector<char > buffer (maxLength);
39+
40+ // 3. Extract the file system representation directly into the buffer
41+ if (CFStringGetFileSystemRepresentation (cfString, buffer.data (), buffer.size ())) {
42+ return std::filesystem::path (buffer.data ());
43+ }
44+
45+ // Fallback: If file-system specific translation failed, try standard UTF-8 text extraction
46+ CFIndex length = CFStringGetLength (cfString);
47+ CFIndex maxSize = CFStringGetMaximumSizeForEncoding (length, kCFStringEncodingUTF8 ) + 1 ;
48+ std::vector<char > fallbackBuffer (maxSize);
49+
50+ if (CFStringGetCString (cfString, fallbackBuffer.data (), fallbackBuffer.size (), kCFStringEncodingUTF8 )) {
51+ return std::filesystem::path (fallbackBuffer.data ());
52+ }
53+
54+ return {};
55+ }
56+ Path application_working_path (){
57+ // Use CFBundle to find the .app bundle path.
58+ // Change working directory to the folder that hosts the .app bundle.
59+ CFURLRef bundleURL = CFBundleCopyBundleURL (CFBundleGetMainBundle ());
60+ if (bundleURL){
61+ CFStringRef cfPath = CFURLCopyFileSystemPath (bundleURL, kCFURLPOSIXPathStyle );
62+ CFRelease (bundleURL);
63+ if (cfPath){
64+ std::filesystem::path bundlePath = CFString_to_path (cfPath);
65+ CFRelease (cfPath);
66+ if (bundlePath.extension () == " .app" ){
67+ return std::filesystem::absolute (bundlePath).parent_path ().lexically_normal ();
68+ }
69+ }
70+ }
71+
72+ // Fallback
73+ return application_binary_path ();
74+ }
75+
76+
77+
2678}
2779}
0 commit comments