/*! * @brief Escape a string for passing to JavaScript scripts. */ CFMutableStringRef escapeForJavaScript(CFMutableStringRef theString) { CFRange range = CFRangeMake(0, CFStringGetLength(theString)); CFIndex delta; //We need to escape a few things to get our string to the javascript without trouble delta = CFStringFindAndReplace(theString, CFSTR("\\"), CFSTR("\\\\"), range, 0); range.length += delta; delta = CFStringFindAndReplace(theString, CFSTR("\""), CFSTR("\\\""), range, 0); range.length += delta; delta = CFStringFindAndReplace(theString, CFSTR("\n"), CFSTR(""), range, 0); range.length -= delta; delta = CFStringFindAndReplace(theString, CFSTR("\r"), CFSTR("<br />"), range, 0); range.length += delta * 5; return theString; }
void write_gdb_prep_cmds(AMDeviceRef device, CFURLRef disk_app_url) { CFMutableStringRef cmds = CFStringCreateMutableCopy(NULL, 0, GDB_PREP_CMDS); CFRange range = { 0, CFStringGetLength(cmds) }; CFStringRef ds_path = copy_device_support_path(device); CFStringFindAndReplace(cmds, CFSTR("{ds_path}"), ds_path, range, 0); range.length = CFStringGetLength(cmds); if (args) { CFStringRef cf_args = CFStringCreateWithCString(NULL, args, kCFStringEncodingASCII); CFStringFindAndReplace(cmds, CFSTR("{args}"), cf_args, range, 0); CFRelease(cf_args); } else { CFStringFindAndReplace(cmds, CFSTR(" {args}"), CFSTR(""), range, 0); } range.length = CFStringGetLength(cmds); CFStringRef bundle_identifier = copy_disk_app_identifier(disk_app_url); CFURLRef device_app_url = copy_device_app_url(device, bundle_identifier); CFStringRef device_app_path = CFURLCopyFileSystemPath(device_app_url, kCFURLPOSIXPathStyle); CFStringFindAndReplace(cmds, CFSTR("{device_app}"), device_app_path, range, 0); range.length = CFStringGetLength(cmds); CFStringRef disk_app_path = CFURLCopyFileSystemPath(disk_app_url, kCFURLPOSIXPathStyle); CFStringFindAndReplace(cmds, CFSTR("{disk_app}"), disk_app_path, range, 0); range.length = CFStringGetLength(cmds); CFURLRef device_container_url = CFURLCreateCopyDeletingLastPathComponent(NULL, device_app_url); CFStringRef device_container_path = CFURLCopyFileSystemPath(device_container_url, kCFURLPOSIXPathStyle); CFMutableStringRef dcp_noprivate = CFStringCreateMutableCopy(NULL, 0, device_container_path); range.length = CFStringGetLength(dcp_noprivate); CFStringFindAndReplace(dcp_noprivate, CFSTR("/private/var/"), CFSTR("/var/"), range, 0); range.length = CFStringGetLength(cmds); CFStringFindAndReplace(cmds, CFSTR("{device_container}"), dcp_noprivate, range, 0); range.length = CFStringGetLength(cmds); CFURLRef disk_container_url = CFURLCreateCopyDeletingLastPathComponent(NULL, disk_app_url); CFStringRef disk_container_path = CFURLCopyFileSystemPath(disk_container_url, kCFURLPOSIXPathStyle); CFStringFindAndReplace(cmds, CFSTR("{disk_container}"), disk_container_path, range, 0); CFDataRef cmds_data = CFStringCreateExternalRepresentation(NULL, cmds, kCFStringEncodingASCII, 0); FILE *out = fopen(PREP_CMDS_PATH, "w"); fwrite(CFDataGetBytePtr(cmds_data), CFDataGetLength(cmds_data), 1, out); fclose(out); CFRelease(cmds); if (ds_path != NULL) CFRelease(ds_path); CFRelease(bundle_identifier); CFRelease(device_app_url); CFRelease(device_app_path); CFRelease(disk_app_path); CFRelease(device_container_url); CFRelease(device_container_path); CFRelease(dcp_noprivate); CFRelease(disk_container_url); CFRelease(disk_container_path); CFRelease(cmds_data); }
OSStatus PosixPathToParentFSRefAndName(const char *path, FSRef &outParentDir, CFStringRef &outFileName) { // convert C string to CFString #if !TARGET_OS_WIN32 CFStringRef cfFullPath = CFStringCreateWithCString(NULL, path, kCFStringEncodingUTF8); #else CFStringRef cfFullPath = CFStringCreateWithCString(NULL, path, kCFStringEncodingWindowsLatin1); #endif // convert CF string to URL CFURLRef fullurl = CFURLCreateWithFileSystemPath(NULL, cfFullPath, TARGET_OS_WIN32 ? kCFURLWindowsPathStyle : kCFURLPOSIXPathStyle, false); CFRelease(cfFullPath); // get the directory portion of the URL CFURLRef dirurl = CFURLCreateCopyDeletingLastPathComponent(NULL, fullurl); // get the directory's FSSpec OSStatus err = CFURLGetFSRef(dirurl, &outParentDir) ? OSStatus(noErr) : OSStatus(fnfErr); CFRelease(dirurl); CFStringRef lastPathComponent = CFURLCopyLastPathComponent(fullurl); CFRelease(fullurl); CFMutableStringRef filename = CFStringCreateMutableCopy(NULL, 0, lastPathComponent); CFRelease(lastPathComponent); // convert colons (legal in POSIX paths, illegal in File Manager) to slashes CFStringFindAndReplace(filename, CFSTR(":"), CFSTR("/"), CFRangeMake(0, CFStringGetLength(filename)), 0); outFileName = filename; return err; }
// ImageCodecDrawBand // The base image decompressor calls your image decompressor component's ImageCodecDrawBand function // to decompress a band or frame. Your component must implement this function. If the ImageSubCodecDecompressRecord // structure specifies a progress function or data-loading function, the base image decompressor will never call ImageCodecDrawBand // at interrupt time. If the ImageSubCodecDecompressRecord structure specifies a progress function, the base image decompressor // handles codecProgressOpen and codecProgressClose calls, and your image decompressor component must not implement these functions. // If not, the base image decompressor may call the ImageCodecDrawBand function at interrupt time. // When the base image decompressor calls your ImageCodecDrawBand function, your component must perform the decompression specified // by the fields of the ImageSubCodecDecompressRecord structure. The structure includes any changes your component made to it // when performing the ImageCodecBeginBand function. If your component supports asynchronous scheduled decompression, // it may receive more than one ImageCodecBeginBand call before receiving an ImageCodecDrawBand call. pascal ComponentResult TextSubCodecDrawBand(TextSubGlobals glob, ImageSubCodecDecompressRecord *drp) { TextSubDecompressRecord *myDrp = (TextSubDecompressRecord *)drp->userDecompressRecord; CGImageAlphaInfo alphaFormat = (myDrp->pixelFormat == k32ARGBPixelFormat) ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaPremultipliedLast; CGContextRef c = CGBitmapContextCreate(drp->baseAddr, myDrp->width, myDrp->height, 8, drp->rowBytes, glob->colorSpace, alphaFormat); CGContextClearRect(c, CGRectMake(0,0, myDrp->width, myDrp->height)); CFMutableStringRef buf; if (drp->codecData[0] == '\n' && myDrp->dataSize == 1) goto leave; // skip empty packets if (myDrp->dataSize > kMaxSubPacketSize) goto leave; // skip very large packets, they probably cause stack overflows buf = (CFMutableStringRef)CFStringCreateWithBytesNoCopy(NULL, (UInt8*)drp->codecData, myDrp->dataSize, kCFStringEncodingUTF8, false, kCFAllocatorNull); if (!buf) goto leave; if (glob->translateSRT) { CFStringRef origBuf = buf; buf = CFStringCreateMutableCopy(NULL, 0, buf); CFRelease(origBuf); if (!buf) goto leave; CFStringFindAndReplace(buf, CFSTR("<i>"), CFSTR("{\\i1}"), CFRangeMake(0,CFStringGetLength(buf)), 0); CFStringFindAndReplace(buf, CFSTR("</i>"), CFSTR("{\\i0}"), CFRangeMake(0,CFStringGetLength(buf)), 0); CFStringFindAndReplace(buf, CFSTR("<"), CFSTR("{"), CFRangeMake(0,CFStringGetLength(buf)), 0); CFStringFindAndReplace(buf, CFSTR(">"), CFSTR("}"), CFRangeMake(0,CFStringGetLength(buf)), 0); } SubRendererRenderPacket(glob->ssa, c, buf, myDrp->width, myDrp->height); if (IsTransparentSubtitleHackEnabled()) ConvertImageToQDTransparent(drp->baseAddr, myDrp->pixelFormat, drp->rowBytes, myDrp->width, myDrp->height); CFRelease(buf); leave: CGContextRelease(c); return noErr; }
/** * Returns a new string in which each occurrence of @c stringToFind in @c subject has been replaced with @c replacement. * * @c stringToFind matches even if a different UTF-8 encoding or Unicode character decomposition is used. */ VuoText VuoText_replace(VuoText subject, VuoText stringToFind, VuoText replacement) { CFMutableStringRef subjectCF = CFStringCreateMutable(NULL, 0); CFStringAppendCString(subjectCF, subject, kCFStringEncodingUTF8); CFStringRef stringToFindCF = CFStringCreateWithCString(NULL, stringToFind, kCFStringEncodingUTF8); CFStringRef replacementCF = CFStringCreateWithCString(NULL, replacement, kCFStringEncodingUTF8); CFStringFindAndReplace(subjectCF, stringToFindCF, replacementCF, CFRangeMake(0,CFStringGetLength(subjectCF)), kCFCompareNonliteral); VuoText replacedSubject = VuoText_makeFromMacString(subjectCF); CFRelease(replacementCF); CFRelease(stringToFindCF); CFRelease(subjectCF); return replacedSubject; }
static void pamGssMapAttribute(const void *key, const void *value, void *context) { CFMutableDictionaryRef mappedAttrs = (CFMutableDictionaryRef)context; CFStringRef mappedKey; if (CFEqual(key, CFSTR("kCUIAttrCredentialSecIdentity"))) { mappedKey = CFRetain(kGSSICCertificate); } else { mappedKey = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef)key); if (mappedKey == NULL) return; /* Map CredUI credential to something for gss_aapl_initial_cred */ CFStringFindAndReplace((CFMutableStringRef)mappedKey, CFSTR("kCUIAttrCredential"), CFSTR("kGSSIC"), CFRangeMake(0, CFStringGetLength(mappedKey)), 0); } CFDictionarySetValue(mappedAttrs, mappedKey, value); CFRelease(mappedKey); }
void stringManipulation(void) { CFMutableStringRef strChange; CFStringRef strOuter, find, replace, find2, replace2, find3, replace3, bigger, smaller, result; CFComparisonResult comp; CFLocaleRef curLocale; Boolean isHyphenationSupported = false; show(CFSTR("------------------String Manipulations---------------")); // Create a simple immutable string from a Pascal string and convert it to Unicode strOuter = CFStringCreateWithCString(NULL, "Hello Cruel World", kCFStringEncodingASCII); strChange = CFStringCreateMutableCopy(NULL, CFStringGetLength(strOuter), strOuter); find = CFStringCreateWithCString(NULL, "Cruel", kCFStringEncodingASCII); replace = CFStringCreateWithCString(NULL, "Cool", kCFStringEncodingASCII); find2 = CFStringCreateWithCString(NULL, "Keep", kCFStringEncodingASCII); replace2 = CFStringCreateWithCString(NULL, "Be", kCFStringEncodingASCII); find3 = CFStringCreateWithCString(NULL, "Change.", kCFStringEncodingASCII); replace3 = CFStringCreateWithCString(NULL, "Ball.", kCFStringEncodingASCII); bigger = CFStringCreateWithCString(NULL, "version 2.5", kCFStringEncodingASCII); smaller = CFStringCreateWithCString(NULL, "version 2.0", kCFStringEncodingASCII); show(CFSTR("String Outer : %@"), strOuter); show(CFSTR("String Find : %@"), find); show(CFSTR("String Replace : %@"), replace); CFStringFindAndReplace(strChange, find, replace, CFRangeMake(0, CFStringGetLength(strChange)), 0); show(CFSTR("Replaced : %@"), strChange); CFStringAppendCString(strChange, "! Keep the change.", kCFStringEncodingASCII); show(CFSTR("Appended : %@"), strChange); curLocale = CFLocaleCopyCurrent (); isHyphenationSupported = CFStringIsHyphenationAvailableForLocale(curLocale); show(CFSTR("Is Hyphenation supported for this locale? %@"), ((isHyphenationSupported) ? CFSTR ("Yes") : CFSTR("No"))); CFStringUppercase(strChange, curLocale); show(CFSTR("Upper Cased : %@"), strChange); CFStringLowercase(strChange, curLocale); show(CFSTR("Lower Cased : %@"), strChange); CFStringCapitalize(strChange, curLocale); show(CFSTR("Capitalized : %@"), strChange); CFStringUppercase(strChange, curLocale); show(CFSTR("Up Cased (again) : %@"), strChange); CFStringFindAndReplace(strChange, find2, replace2, CFRangeMake(0, CFStringGetLength(strChange)), 0); show(CFSTR("Replaced? : %@"), strChange); CFStringFindAndReplace(strChange, find2, replace2, CFRangeMake(0, CFStringGetLength(strChange)), kCFCompareCaseInsensitive); show(CFSTR("Case insensitive : %@"), strChange); CFStringCapitalize(strChange, curLocale); show(CFSTR("Capitalized : %@"), strChange); CFStringFindAndReplace(strChange, replace2, find2, CFRangeMake(0, CFStringGetLength(strChange)), kCFCompareAnchored); show(CFSTR("Should Be Unchanged: %@"), strChange); CFStringFindAndReplace(strChange, find3, replace3, CFRangeMake(0, CFStringGetLength(strChange)), kCFCompareAnchored|kCFCompareBackwards); show(CFSTR("Should Be Changed : %@"), strChange); show(CFSTR("Which is bigger %@ or %@?"), bigger, smaller); comp = CFStringCompare(bigger, smaller, 0); result = (comp == kCFCompareGreaterThan) ? bigger : smaller; show(CFSTR("Base Compare Says : %@"), result); comp = CFStringCompare(bigger, smaller, kCFCompareNumerically); result = (comp == kCFCompareGreaterThan) ? bigger : smaller; show(CFSTR("Numerical Compare : %@"), result); CFRelease(curLocale); CFRelease(replace); CFRelease(find); CFRelease(replace2); CFRelease(find2); CFRelease(replace3); CFRelease(find3); CFRelease(bigger); CFRelease(smaller); CFRelease(strChange); }
void StartDebuggingAndDetach(char *udid, char *app_path) { SDMMD_AMDeviceRef device = FindDeviceFromUDID(udid); if (device) { CFStringRef bundleId = CFStringCreateWithBytes(kCFAllocatorDefault, (UInt8 *)app_path, strlen(app_path), kCFStringEncodingUTF8, false); CFURLRef relative_url = CFURLCreateWithFileSystemPath(NULL, bundleId, kCFURLPOSIXPathStyle, false); CFURLRef disk_app_url = CFURLCopyAbsoluteURL(relative_url); CFStringRef bundle_identifier = copy_disk_app_identifier(disk_app_url); SDMMD_AMDebugConnectionRef debug = SDMMD_AMDebugConnectionCreateForDevice(device); SDMMD_AMDebugConnectionStart(debug); uintptr_t socket = SDMMD_AMDServiceConnectionGetSocket(debug->connection); CFSocketContext context = { 0, (void*)socket, NULL, NULL, NULL }; CFSocketRef fdvendor = CFSocketCreate(NULL, AF_UNIX, 0, 0, kCFSocketAcceptCallBack, &socket_callback, &context); int yes = 1; setsockopt(CFSocketGetNative(fdvendor), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); struct sockaddr_un address; memset(&address, 0, sizeof(address)); address.sun_family = AF_UNIX; strcpy(address.sun_path, SDM_LLDB_SOCKET); address.sun_len = SUN_LEN(&address); CFDataRef address_data = CFDataCreate(NULL, (const UInt8 *)&address, sizeof(address)); unlink(SDM_LLDB_SOCKET); CFSocketSetAddress(fdvendor, address_data); CFRelease(address_data); CFRunLoopAddSource(CFRunLoopGetMain(), CFSocketCreateRunLoopSource(NULL, fdvendor, 0), kCFRunLoopCommonModes); SDMMD_AMDeviceRef device = SDMMD_AMDServiceConnectionGetDevice(debug->connection); CFMutableStringRef cmds = CFStringCreateMutableCopy(NULL, 0, LLDB_PREP_CMDS); CFRange range = { 0, CFStringGetLength(cmds) }; CFURLRef device_app_url = copy_device_app_url(device, bundle_identifier); CFStringRef device_app_path = CFURLCopyFileSystemPath(device_app_url, kCFURLPOSIXPathStyle); CFStringFindAndReplace(cmds, CFSTR("{DEVICE_PATH}"), device_app_path, range, 0); range.length = CFStringGetLength(cmds); CFStringRef disk_app_path = CFURLCopyFileSystemPath(disk_app_url, kCFURLPOSIXPathStyle); CFStringFindAndReplace(cmds, CFSTR("{APP_PATH}"), disk_app_path, range, 0); range.length = CFStringGetLength(cmds); CFURLRef device_container_url = CFURLCreateCopyDeletingLastPathComponent(NULL, device_app_url); CFStringRef device_container_path = CFURLCopyFileSystemPath(device_container_url, kCFURLPOSIXPathStyle); CFMutableStringRef dcp_noprivate = CFStringCreateMutableCopy(NULL, 0, device_container_path); range.length = CFStringGetLength(dcp_noprivate); CFStringFindAndReplace(dcp_noprivate, CFSTR("/private/var/"), CFSTR("/var/"), range, 0); range.length = CFStringGetLength(cmds); CFStringFindAndReplace(cmds, CFSTR("{device_container}"), dcp_noprivate, range, 0); range.length = CFStringGetLength(cmds); CFURLRef disk_container_url = CFURLCreateCopyDeletingLastPathComponent(NULL, disk_app_url); CFStringRef disk_container_path = CFURLCopyFileSystemPath(disk_container_url, kCFURLPOSIXPathStyle); CFStringFindAndReplace(cmds, CFSTR("{disk_container}"), disk_container_path, range, 0); CFDataRef cmds_data = CFStringCreateExternalRepresentation(NULL, cmds, kCFStringEncodingASCII, 0); FILE *out = fopen(PREP_CMDS_PATH, "w"); fwrite(CFDataGetBytePtr(cmds_data), CFDataGetLength(cmds_data), 1, out); fclose(out); CFSafeRelease(cmds); CFSafeRelease(bundle_identifier); CFSafeRelease(device_app_url); CFSafeRelease(device_app_path); CFSafeRelease(disk_app_path); CFSafeRelease(device_container_url); CFSafeRelease(device_container_path); CFSafeRelease(dcp_noprivate); CFSafeRelease(disk_container_url); CFSafeRelease(disk_container_path); CFSafeRelease(cmds_data); signal(SIGHUP, exit); pid_t parent = getpid(); int pid = fork(); if (pid == 0) { system("xcrun -sdk iphoneos lldb /tmp/sdmmd-lldb-prep"); kill(parent, SIGHUP); _exit(0); } CFRunLoopRun(); } }
static CFStringRef copy_default_name(void) { CFStringRef model; size_t n; CFMutableStringRef str; // get HW model name model = _SC_hw_model(TRUE); if (model == NULL) { return NULL; } // start off with the [trunated] HW model str = CFStringCreateMutable(NULL, 0); CFStringAppend(str, model); // truncate as needed n = CFStringGetLength(str); if (n > (NETBIOS_NAME_LEN - 1)) { CFStringReplace(str, CFRangeMake(NETBIOS_NAME_LEN, n - (NETBIOS_NAME_LEN - 1)), CFSTR("")); n = NETBIOS_NAME_LEN - 1; } // // if there is room for at least one byte (two hex characters) // of the MAC address than append that to the NetBIOS name. // // NETBIOS_NAME_LEN max length // -1 the last byte is reserved // -3 "-XX" // if (n < (NETBIOS_NAME_LEN - 1 - 3)) { SCNetworkInterfaceRef interface; interface = _SCNetworkInterfaceCreateWithBSDName(NULL, CFSTR("en0"), kIncludeNoVirtualInterfaces); if (interface != NULL) { CFMutableStringRef en0_MAC; en0_MAC = (CFMutableStringRef)SCNetworkInterfaceGetHardwareAddressString(interface); if (en0_MAC != NULL) { CFIndex en0_MAC_len; // remove ":" characters from MAC address string en0_MAC = CFStringCreateMutableCopy(NULL, 0, en0_MAC); CFStringFindAndReplace(en0_MAC, CFSTR(":"), CFSTR(""), CFRangeMake(0, CFStringGetLength(en0_MAC)), 0); // // compute how may bytes (characters) to append // ... and limit that number to 6 // // NETBIOS_NAME_LEN max length // -1 the last byte is reserved // -n "iMac" // -1 "-" // n = ((NETBIOS_NAME_LEN - 1 - n - 1) / 2) * 2; if (n > 6) { n = 6; } // remove what we don't want en0_MAC_len = CFStringGetLength(en0_MAC); if (en0_MAC_len > n) { CFStringDelete(en0_MAC, CFRangeMake(0, en0_MAC_len - n)); } // append CFStringAppendFormat(str, NULL, CFSTR("-%@"), en0_MAC); CFRelease(en0_MAC); } CFRelease(interface); } } CFStringUppercase(str, NULL); return str; }
// performs a locale sensitive date formatting operation on the struct tm parameter nsresult nsDateTimeFormatMac::FormatTMTime(nsILocale* locale, const nsDateFormatSelector dateFormatSelector, const nsTimeFormatSelector timeFormatSelector, const struct tm* tmTime, nsAString& stringOut) { nsresult res = NS_OK; // set up locale data (void) Initialize(locale); // return, nothing to format if (dateFormatSelector == kDateFormatNone && timeFormatSelector == kTimeFormatNone) { stringOut.Truncate(); return NS_OK; } NS_ASSERTION(tmTime->tm_mon >= 0, "tm is not set correctly"); NS_ASSERTION(tmTime->tm_mday >= 1, "tm is not set correctly"); NS_ASSERTION(tmTime->tm_hour >= 0, "tm is not set correctly"); NS_ASSERTION(tmTime->tm_min >= 0, "tm is not set correctly"); NS_ASSERTION(tmTime->tm_sec >= 0, "tm is not set correctly"); NS_ASSERTION(tmTime->tm_wday >= 0, "tm is not set correctly"); // Got the locale for the formatter: CFLocaleRef formatterLocale; if (!locale) { formatterLocale = CFLocaleCopyCurrent(); } else { CFStringRef localeStr = CFStringCreateWithCharacters(nullptr, reinterpret_cast<const UniChar*>(mLocale.get()), mLocale.Length()); formatterLocale = CFLocaleCreate(nullptr, localeStr); CFRelease(localeStr); } // Get the date style for the formatter: CFDateFormatterStyle dateStyle; switch (dateFormatSelector) { case kDateFormatLong: dateStyle = kCFDateFormatterLongStyle; break; case kDateFormatShort: dateStyle = kCFDateFormatterShortStyle; break; case kDateFormatYearMonth: case kDateFormatWeekday: dateStyle = kCFDateFormatterNoStyle; // formats handled below break; case kDateFormatNone: dateStyle = kCFDateFormatterNoStyle; break; default: NS_ERROR("Unknown nsDateFormatSelector"); res = NS_ERROR_FAILURE; dateStyle = kCFDateFormatterNoStyle; } // Get the time style for the formatter: CFDateFormatterStyle timeStyle; switch (timeFormatSelector) { case kTimeFormatSeconds: case kTimeFormatSecondsForce24Hour: // 24 hour part fixed below timeStyle = kCFDateFormatterMediumStyle; break; case kTimeFormatNoSeconds: case kTimeFormatNoSecondsForce24Hour: // 24 hour part fixed below timeStyle = kCFDateFormatterShortStyle; break; case kTimeFormatNone: timeStyle = kCFDateFormatterNoStyle; break; default: NS_ERROR("Unknown nsTimeFormatSelector"); res = NS_ERROR_FAILURE; timeStyle = kCFDateFormatterNoStyle; } // Create the formatter and fix up its formatting as necessary: CFDateFormatterRef formatter = CFDateFormatterCreate(nullptr, formatterLocale, dateStyle, timeStyle); CFRelease(formatterLocale); if (dateFormatSelector == kDateFormatYearMonth || dateFormatSelector == kDateFormatWeekday) { CFStringRef dateFormat = dateFormatSelector == kDateFormatYearMonth ? CFSTR("yyyy/MM ") : CFSTR("EEE "); CFStringRef oldFormat = CFDateFormatterGetFormat(formatter); CFMutableStringRef newFormat = CFStringCreateMutableCopy(nullptr, 0, oldFormat); CFStringInsert(newFormat, 0, dateFormat); CFDateFormatterSetFormat(formatter, newFormat); CFRelease(newFormat); // note we don't own oldFormat } if (timeFormatSelector == kTimeFormatSecondsForce24Hour || timeFormatSelector == kTimeFormatNoSecondsForce24Hour) { // Replace "h" with "H", and remove "a": CFStringRef oldFormat = CFDateFormatterGetFormat(formatter); CFMutableStringRef newFormat = CFStringCreateMutableCopy(nullptr, 0, oldFormat); CFIndex replaceCount = CFStringFindAndReplace(newFormat, CFSTR("h"), CFSTR("H"), CFRangeMake(0, CFStringGetLength(newFormat)), 0); NS_ASSERTION(replaceCount <= 2, "Unexpected number of \"h\" occurrences"); replaceCount = CFStringFindAndReplace(newFormat, CFSTR("a"), CFSTR(""), CFRangeMake(0, CFStringGetLength(newFormat)), 0); NS_ASSERTION(replaceCount <= 1, "Unexpected number of \"a\" occurrences"); CFDateFormatterSetFormat(formatter, newFormat); CFRelease(newFormat); // note we don't own oldFormat } // Now get the formatted date: CFGregorianDate date; date.second = tmTime->tm_sec; date.minute = tmTime->tm_min; date.hour = tmTime->tm_hour; date.day = tmTime->tm_mday; // Mac is 1-based, tm is 1-based date.month = tmTime->tm_mon + 1; // Mac is 1-based, tm is 0-based date.year = tmTime->tm_year + 1900; CFTimeZoneRef timeZone = CFTimeZoneCopySystem(); // tmTime is in local time CFAbsoluteTime absTime = CFGregorianDateGetAbsoluteTime(date, timeZone); CFRelease(timeZone); CFStringRef formattedDate = CFDateFormatterCreateStringWithAbsoluteTime(nullptr, formatter, absTime); CFIndex stringLen = CFStringGetLength(formattedDate); AutoTArray<UniChar, 256> stringBuffer; stringBuffer.SetLength(stringLen + 1); CFStringGetCharacters(formattedDate, CFRangeMake(0, stringLen), stringBuffer.Elements()); stringOut.Assign(reinterpret_cast<char16_t*>(stringBuffer.Elements()), stringLen); CFRelease(formattedDate); CFRelease(formatter); return res; }
extern void INXUnescape(CFMutableStringRef s) { CFStringFindAndReplace(s, CFSTR("\\\""), CFSTR("\""), CFRangeMake(0, CFStringGetLength(s)), 0); CFStringFindAndReplace(s, CFSTR("\\\\"), CFSTR("\\"), CFRangeMake(0, CFStringGetLength(s)), 0); }
/* Parses command line options for the VM options, properties, main class, and main class args and returns them in the VMLaunchOptions structure. */ VMLaunchOptions * NewVMLaunchOptions(int argc, const char **currentArg) { int ArgIndex = 0; /* The following Strings are used to convert the command line -cp to -Djava.class.path= */ CFStringRef classPathOption = CFSTR("-cp"); CFStringRef classPathDefine = CFSTR("-Djava.class.path="); /* vmOptionsCFArrayRef will temporarly hold a list of VM options and properties to be passed in when creating the JVM */ CFMutableArrayRef vmOptionsCFArrayRef = CFArrayCreateMutable(NULL,0,&kCFTypeArrayCallBacks); /* mainArgsCFArrayRef will temporarly hold a list of arguments to be passed to the main method of the main class */ CFMutableArrayRef mainArgsCFArrayRef = CFArrayCreateMutable(NULL,0,&kCFTypeArrayCallBacks); /* Allocated the structure that will be used to return the launch options */ VMLaunchOptions * vmLaunchOptions = malloc(sizeof(VMLaunchOptions)); /* Start with the first arg, not the path to the tool */ ArgIndex++; currentArg++; /* JVM options start with - */ while(ArgIndex < argc && **currentArg == '-') { CFMutableStringRef option = CFStringCreateMutable(NULL, 0); CFStringAppendCString(option, *currentArg, kCFStringEncodingUTF8); /* If the option string is '-cp', replace it with '-Djava.class.path=' and append then next option which contains the actuall class path. */ CFRange rangeToSearch = CFRangeMake(0,CFStringGetLength(option)); if (CFStringFindAndReplace(option, classPathOption, classPathDefine, rangeToSearch, kCFCompareAnchored) != 0) { /* So the option was -cp, and we replaced it with -Djava.class.path= */ /* Now append the next option which is the actuall class path */ currentArg++; ArgIndex++; if (ArgIndex < argc) { CFStringAppendCString(option, *currentArg, kCFStringEncodingUTF8); } else { /* We shouldn't reach here unless the last arg was -cp */ fprintf(stderr, "[JavaAppLauncher Error] Error parsing class path.\n"); /* Release the option CFString heresince the break; statement is going */ /* to skip the release in this loop */ CFRelease(option); break; } } /* Add this to our list of JVM options */ CFArrayAppendValue(vmOptionsCFArrayRef,option); /* When an object is added to a CFArray the array retains a reference to it, this means */ /* we need to release the object so that the memory will be freed when we release the CFArray. */ CFRelease(option); /* On to the next one */ currentArg++; ArgIndex++; } /* Now we know how many JVM options there are and they are all in a CFArray of CFStrings. */ vmLaunchOptions->nOptions = CFArrayGetCount(vmOptionsCFArrayRef); /* We only need to do this if there are options */ if ( vmLaunchOptions->nOptions > 0) { int index; /* Allocate some memory for the array of JavaVMOptions */ JavaVMOption * option = malloc(vmLaunchOptions->nOptions*sizeof(JavaVMOption)); vmLaunchOptions->options = option; /* Itterate over each option adding it to the JavaVMOptions array */ for(index = 0;index < vmLaunchOptions->nOptions; index++, option++) { /* Allocate enough memory for each optionString char* to hold the max possible lengh a UTF8 */ /* encoded copy of the string would require */ CFStringRef optionStringRef = (CFStringRef)CFArrayGetValueAtIndex(vmOptionsCFArrayRef,index); CFIndex optionStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(optionStringRef), kCFStringEncodingUTF8); option->extraInfo = NULL; option->optionString = malloc(optionStringSize+1); /* Now copy the option into the the optionString char* buffer in a UTF8 encoding */ if (!CFStringGetCString(optionStringRef, (char *)option->optionString, optionStringSize, kCFStringEncodingUTF8)) { fprintf(stderr, "[JavaAppLauncher Error] Error parsing JVM options.\n"); exit(-1); } } } else { vmLaunchOptions->options = NULL; } /* Now we know how many args for main there are and they are all in a CFArray of CFStrings. */ vmLaunchOptions->numberOfArgs = CFArrayGetCount(mainArgsCFArrayRef); /* We only need to do this if there are args */ if ( vmLaunchOptions->numberOfArgs > 0) { int index; char ** arg; /* Allocate some memory for the array of char *'s */ vmLaunchOptions->args = malloc(vmLaunchOptions->numberOfArgs*sizeof(char *)); for(index = 0, arg = vmLaunchOptions->args;index < vmLaunchOptions->numberOfArgs; index++, arg++) { /* Allocate enough memory for each arg char* to hold the max possible lengh a UTF8 */ /* encoded copy of the string would require */ CFStringRef argStringRef = (CFStringRef)CFArrayGetValueAtIndex(mainArgsCFArrayRef,index); CFIndex argStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(argStringRef), kCFStringEncodingUTF8); *arg = (char*)malloc(argStringSize+1); /* Now copy the arg into the the args char* buffer in a UTF8 encoding */ if (!CFStringGetCString(argStringRef, *arg, argStringSize, kCFStringEncodingUTF8)) { fprintf(stderr, "[JavaAppLauncher Error] Error parsing args.\n"); exit(-1); } } } else { vmLaunchOptions->args = NULL; } /* Free the Array's holding our options and args */ /* Releaseing an array also releases its references to the objects it contains */ CFRelease(vmOptionsCFArrayRef); CFRelease(mainArgsCFArrayRef); return vmLaunchOptions; }
CFStringRef createXMLStringFromWebArchiveData(CFDataRef webArchiveData) { CFErrorRef error = 0; CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0; RetainPtr<CFMutableDictionaryRef> propertyList = adoptCF((CFMutableDictionaryRef)CFPropertyListCreateWithData(kCFAllocatorDefault, webArchiveData, kCFPropertyListMutableContainersAndLeaves, &format, &error)); if (!propertyList) { if (error) return CFErrorCopyDescription(error); return static_cast<CFStringRef>(CFRetain(CFSTR("An unknown error occurred converting data to property list."))); } RetainPtr<CFMutableArrayRef> resources = adoptCF(CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks)); CFArrayAppendValue(resources.get(), propertyList.get()); while (CFArrayGetCount(resources.get())) { RetainPtr<CFMutableDictionaryRef> resourcePropertyList = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(resources.get(), 0); CFArrayRemoveValueAtIndex(resources.get(), 0); CFMutableDictionaryRef mainResource = (CFMutableDictionaryRef)CFDictionaryGetValue(resourcePropertyList.get(), CFSTR("WebMainResource")); normalizeWebResourceURL((CFMutableStringRef)CFDictionaryGetValue(mainResource, CFSTR("WebResourceURL"))); convertWebResourceDataToString(mainResource); // Add subframeArchives to list for processing CFMutableArrayRef subframeArchives = (CFMutableArrayRef)CFDictionaryGetValue(resourcePropertyList.get(), CFSTR("WebSubframeArchives")); // WebSubframeArchivesKey in WebArchive.m if (subframeArchives) CFArrayAppendArray(resources.get(), subframeArchives, CFRangeMake(0, CFArrayGetCount(subframeArchives))); CFMutableArrayRef subresources = (CFMutableArrayRef)CFDictionaryGetValue(resourcePropertyList.get(), CFSTR("WebSubresources")); // WebSubresourcesKey in WebArchive.m if (!subresources) continue; CFIndex subresourcesCount = CFArrayGetCount(subresources); for (CFIndex i = 0; i < subresourcesCount; ++i) { CFMutableDictionaryRef subresourcePropertyList = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(subresources, i); normalizeWebResourceURL((CFMutableStringRef)CFDictionaryGetValue(subresourcePropertyList, CFSTR("WebResourceURL"))); convertWebResourceResponseToDictionary(subresourcePropertyList); convertWebResourceDataToString(subresourcePropertyList); } // Sort the subresources so they're always in a predictable order for the dump CFArraySortValues(subresources, CFRangeMake(0, CFArrayGetCount(subresources)), compareResourceURLs, 0); } error = 0; RetainPtr<CFDataRef> xmlData = adoptCF(CFPropertyListCreateData(kCFAllocatorDefault, propertyList.get(), kCFPropertyListXMLFormat_v1_0, 0, &error)); if (!xmlData) { if (error) return CFErrorCopyDescription(error); return static_cast<CFStringRef>(CFRetain(CFSTR("An unknown error occurred converting property list to data."))); } RetainPtr<CFStringRef> xmlString = adoptCF(CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, xmlData.get(), kCFStringEncodingUTF8)); RetainPtr<CFMutableStringRef> string = adoptCF(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, xmlString.get())); // Replace "Apple Computer" with "Apple" in the DTD declaration. CFStringFindAndReplace(string.get(), CFSTR("-//Apple Computer//"), CFSTR("-//Apple//"), CFRangeMake(0, CFStringGetLength(string.get())), 0); return string.leakRef(); }
Boolean GetMetadataForFile(void* thisInterface, CFMutableDictionaryRef attributes, CFStringRef contentTypeUTI, CFStringRef pathToFile) { Boolean success = false; CFDictionaryRef tempDictRef; CFStringRef tempTitleRef; CFArrayRef tempContentRef; // load the document at the specified location CFURLRef pathToFileURL; pathToFileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, pathToFile, kCFURLPOSIXPathStyle, false); tempDictRef = (CFDictionaryRef)CreatePropertiesFromXMLFile(pathToFileURL); CFRelease(pathToFileURL); if (tempDictRef) { CFStringRef tempBrdNameRef; CFStringRef tempDatNumberRef; CFNumberRef tempLengthRef; CFDateRef tempCreatedDateRef; CFDateRef tempModifiedDateRef; CFDictionarySetValue(attributes, kMDItemCreator, CFSTR("BathyScaphe")); // set the kMDItemTitle attribute to the Title tempTitleRef = CFDictionaryGetValue(tempDictRef, CFSTR("Title")); if (tempTitleRef != NULL) { CFDictionarySetValue(attributes, kMDItemTitle, tempTitleRef); CFDictionarySetValue(attributes, kMDItemDisplayName, tempTitleRef); } tempBrdNameRef = CFDictionaryGetValue(tempDictRef, CFSTR("BoardName")); if (tempBrdNameRef != NULL) CFDictionarySetValue(attributes, CFSTR("jp_tsawada2_bathyscaphe_thread_BoardName"), tempBrdNameRef); tempDatNumberRef = CFDictionaryGetValue(tempDictRef, CFSTR("dat")); if (tempDatNumberRef != NULL) CFDictionarySetValue(attributes, CFSTR("jp_tsawada2_bathyscaphe_thread_DatNumber"), tempDatNumberRef); tempLengthRef = CFDictionaryGetValue(tempDictRef, CFSTR("Length")); if (tempLengthRef != NULL) CFDictionarySetValue(attributes, CFSTR("jp_tsawada2_bathyscaphe_thread_DatSize"), tempLengthRef); tempCreatedDateRef = CFDictionaryGetValue(tempDictRef, CFSTR("CreatedDate")); if (tempCreatedDateRef != NULL) CFDictionarySetValue(attributes, kMDItemContentCreationDate, tempCreatedDateRef); tempModifiedDateRef = CFDictionaryGetValue(tempDictRef, CFSTR("ModifiedDate")); if (tempModifiedDateRef != NULL) CFDictionarySetValue(attributes, kMDItemContentModificationDate, tempModifiedDateRef); tempContentRef = CFDictionaryGetValue(tempDictRef, CFSTR("Contents")); if (tempContentRef) { CFIndex i, count_; CFNumberRef countRef_; CFMutableStringRef cont_ = CFStringCreateMutable(kCFAllocatorDefault, 0); CFMutableArrayRef nameArray_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); CFDictionaryRef obj; CFNumberRef statusStr; count_ = CFArrayGetCount(tempContentRef); countRef_ = CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &count_); CFDictionarySetValue(attributes, CFSTR("jp_tsawada2_bathyscaphe_thread_ResCount"), countRef_); CFRelease(countRef_); for (i=0; i<count_; i++) { obj = CFArrayGetValueAtIndex(tempContentRef, i); if (obj == NULL) continue; statusStr = CFDictionaryGetValue(obj, CFSTR("Status")); if (isNotAbonedRes(statusStr)) { CFStringRef msg_; CFStringRef name_; msg_ = CFDictionaryGetValue(obj, CFSTR("Message")); if (msg_) { CFStringAppend(cont_, msg_); } name_ = CFDictionaryGetValue(obj, CFSTR("Name")); if (name_) { Boolean already_ = CFArrayContainsValue(nameArray_, CFRangeMake(0, CFArrayGetCount(nameArray_)), name_); if (already_ == false) CFArrayAppendValue(nameArray_, name_); } } } CFStringFindAndReplace(cont_, CFSTR(" <br> "), CFSTR(""), CFRangeMake(0, CFStringGetLength(cont_)), 0); CFStringTrimWhitespace(cont_); CFIndex len; CFRange searchRange; CFRange resultRange; CFRange gtRange; len = CFStringGetLength(cont_); searchRange = CFRangeMake(0, len); while (1) { Boolean found_ = CFStringFindWithOptions(cont_, CFSTR("<a "), searchRange, kCFCompareCaseInsensitive, &resultRange); if (found_ == false) break; // Start searching next to "<" searchRange.location = resultRange.location + resultRange.length; searchRange.length = (len - searchRange.location); found_ = CFStringFindWithOptions(cont_, CFSTR("</a>"), searchRange, kCFCompareCaseInsensitive, >Range); if (found_ == false) break; resultRange.length = gtRange.location + gtRange.length - resultRange.location; CFStringDelete(cont_, resultRange); searchRange.length -= resultRange.length; len -= resultRange.length; if (searchRange.location >= len) break; } CFDictionarySetValue(attributes, kMDItemTextContent, cont_); CFDictionarySetValue(attributes, kMDItemContributors, nameArray_); CFRelease(cont_); CFRelease(nameArray_); } // release the loaded document CFRelease(tempDictRef); // return YES so that the attributes are imported success = true; } return success; }