// Writes a wchar_t out as length field + UTF-16 stream void WriteUnicodeString ( std::ostream &output, const wchar_t *unicode ) { if ( unicode ) { #ifdef TARGET_OS_MACOSX // wchar_t = UTF-32, so we need to convert CFStringRef utf16 = CFStringCreateWithBytes(NULL, (UInt8 *)unicode, wcslen(unicode)*sizeof(wchar_t), kUTF32Encoding, false); int size = CFStringGetLength(utf16); WritePackedInt(output, size); for(int i = 0; i < size; ++ i) { WriteNetworkValue( output, CFStringGetCharacterAtIndex(utf16, i) ); } CFRelease(utf16); #elif defined( TARGET_OS_LINUX ) // wchar_t is 4 byes on linux, so we need to convert int size = wcslen(unicode); size_t bufferSize = sizeof(unsigned short) * size * 2; size_t outBytesLeft = bufferSize; size_t inBytesLeft = size * sizeof(wchar_t); char *inBuf = (char *) unicode; char *buf = new char[ outBytesLeft ]; char *outBuf = buf; iconv_t utf32_to_utf16 = iconv_open( "UTF16LE", "UTF32LE" ); if( utf32_to_utf16 == (iconv_t) -1 ) { perror("Failed to open iconv from UTF32LE -> UTF16LE" ); delete[] buf; return; } size_t result = iconv( utf32_to_utf16, &inBuf, &inBytesLeft, &outBuf, &outBytesLeft ); if( result == (size_t) -1 ) { perror( "Failed to convert from UTF32LE -> UTF16LE" ); delete[] buf; return; } iconv_close( utf32_to_utf16 ); int bytesConverted = bufferSize - outBytesLeft; WritePackedInt(output, bytesConverted / sizeof(unsigned short) ); output.write( buf, bytesConverted ); delete[] buf; #else // assume Windows and wchar_t = UTF-16 int size = wcslen(unicode); WritePackedInt(output, size); for(int i = 0; i < size; ++ i) { WriteNetworkValue( output, unicode[i] ); } #endif } else { int size = -1; WritePackedInt(output, size); } }
Boolean DAMountContainsArgument( CFStringRef arguments, CFStringRef argument ) { CFBooleanRef argumentValue; CFBooleanRef argumentsValue; argumentsValue = NULL; if ( CFStringHasPrefix( argument, CFSTR( "no" ) ) ) { argument = CFStringCreateWithSubstring( kCFAllocatorDefault, argument, CFRangeMake( 2, CFStringGetLength( argument ) - 2 ) ); argumentValue = kCFBooleanFalse; } else { argument = CFRetain( argument ); argumentValue = kCFBooleanTrue; } if ( argument ) { CFArrayRef argumentList; CFIndex argumentListCount; CFIndex argumentListIndex; argumentList = CFStringCreateArrayBySeparatingStrings( kCFAllocatorDefault, arguments, CFSTR( "," ) ); if ( argumentList ) { argumentListCount = CFArrayGetCount( argumentList ); for ( argumentListIndex = 0; argumentListIndex < argumentListCount; argumentListIndex++ ) { CFStringRef compare; compare = CFArrayGetValueAtIndex( argumentList, argumentListIndex ); if ( compare ) { CFBooleanRef compareValue; if ( CFStringHasPrefix( compare, CFSTR( "no" ) ) ) { compare = CFStringCreateWithSubstring( kCFAllocatorDefault, compare, CFRangeMake( 2, CFStringGetLength( compare ) - 2 ) ); compareValue = kCFBooleanFalse; } else { compare = CFRetain( compare ); compareValue = kCFBooleanTrue; } if ( compare ) { if ( CFEqual( compare, CFSTR( FSTAB_RO ) ) ) { CFRelease( compare ); compare = CFRetain( kDAFileSystemMountArgumentNoWrite ); compareValue = compareValue; } if ( CFEqual( compare, CFSTR( FSTAB_RW ) ) ) { CFRelease( compare ); compare = CFRetain( kDAFileSystemMountArgumentNoWrite ); compareValue = ( compareValue == kCFBooleanTrue ) ? kCFBooleanFalse : kCFBooleanTrue; } } if ( compare ) { if ( CFEqual( argument, compare ) ) { argumentsValue = compareValue; } CFRelease( compare ); } } } CFRelease( argumentList ); } CFRelease( argument ); } return ( argumentValue == argumentsValue ) ? TRUE : FALSE; }
/************************************************************************* * * hu_XMLSearchForProductNameByVendorProductID( inVendorID, inProductID, outCStr ) * * Purpose: Find an product string in the <HID_device_usage_strings.plist> resource ( XML ) file * * Inputs: inVendorID - the elements vendor ID * inProductID - the elements product ID * outCStr - address where result will be returned * * Returns: Boolean - if successful */ static Boolean hu_XMLSearchForProductNameByVendorProductID(long inVendorID, long inProductID, char *outCStr) { Boolean results = FALSE; if ( !gUsageCFPropertyListRef ) { gUsageCFPropertyListRef = hu_XMLLoad( CFSTR( "HID_device_usage_strings"), CFSTR("plist") ); } if ( gUsageCFPropertyListRef ) { if ( CFDictionaryGetTypeID() == CFGetTypeID(gUsageCFPropertyListRef) ) { // first we make our vendor ID key CFStringRef vendorKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%ld"), inVendorID); if ( vendorKeyCFStringRef ) { // and use it to look up our vendor dictionary CFDictionaryRef vendorCFDictionaryRef; if ( CFDictionaryGetValueIfPresent(gUsageCFPropertyListRef, vendorKeyCFStringRef, (const void **) &vendorCFDictionaryRef) ) { // pull our vendor name our of that dictionary CFStringRef vendorCFStringRef = NULL; if ( CFDictionaryGetValueIfPresent(vendorCFDictionaryRef, kNameKeyCFStringRef, (const void **) &vendorCFStringRef) ) { #if FAKE_MISSING_NAMES CFRetain(vendorCFStringRef); // so we can CFRelease it later } else { vendorCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "V: %@"), vendorKeyCFStringRef); #endif } // now we make our product ID key CFStringRef productKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "%ld"), inProductID); if ( productKeyCFStringRef ) { // and use that key to look up our product dictionary in the vendor dictionary CFDictionaryRef productCFDictionaryRef; if ( CFDictionaryGetValueIfPresent(vendorCFDictionaryRef, productKeyCFStringRef, (const void **) &productCFDictionaryRef) ) { // pull our product name our of the product dictionary CFStringRef productCFStringRef = NULL; if ( CFDictionaryGetValueIfPresent(productCFDictionaryRef, kNameKeyCFStringRef, (const void **) &productCFStringRef) ) { #if FAKE_MISSING_NAMES CFRetain(productCFStringRef); // so we can CFRelease it later } else { productCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "P: %@"), kNameKeyCFStringRef); #endif } CFStringRef fullCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "%@ %@"), vendorCFStringRef, productCFStringRef); if ( fullCFStringRef ) { // CFShow( fullCFStringRef ); results = CFStringGetCString(fullCFStringRef, outCStr, CFStringGetLength( fullCFStringRef) * sizeof(UniChar) + 1, kCFStringEncodingUTF8); CFRelease(fullCFStringRef); } #if FAKE_MISSING_NAMES if ( productCFStringRef ) { CFRelease(productCFStringRef); } #endif } CFRelease(productKeyCFStringRef); } #if FAKE_MISSING_NAMES if ( vendorCFStringRef ) { CFRelease(vendorCFStringRef); } #endif } CFRelease(vendorKeyCFStringRef); } } // ++ CFRelease( gUsageCFPropertyListRef ); // Leak this ! } return (results); } // hu_XMLSearchForProductNameByVendorProductID
//http://iphonedevwiki.net/index.php/Lockdownd void get_device_infos(CFMutableDictionaryRef out) { CC_SHA1_CTX sha1ctx; uint8_t udid[20]; char udid1[100]; CFStringRef serial; CFStringRef imei; CFStringRef macwifi; CFStringRef macbt; CFStringRef hw = copy_hardware_model(); if (hw != NULL) { CFDictionaryAddValue(out, CFSTR("hwModel"), hw); CFRelease(hw); } serial = copy_device_serial_number(); imei = copy_device_imei(); macwifi = copy_wifi_mac_address(); macbt = copy_bluetooth_mac_address(); CFMutableStringRef udidInput = CFStringCreateMutable(kCFAllocatorDefault, 0); if (serial != NULL) { CFStringAppend(udidInput, serial); CFDictionaryAddValue(out, CFSTR("serialNumber"), serial); CFRelease(serial); } uint64_t _ecid = 0; CFNumberRef ecid = copyNumberFromChosen(CFSTR("unique-chip-id")); if (ecid != NULL) { CFDictionaryAddValue(out, CFSTR("ECID"), ecid); } if (ecid != NULL && useNewUDID(hw)) { CFNumberGetValue(ecid, kCFNumberSInt64Type, &_ecid); CFStringAppendFormat(udidInput, NULL, CFSTR("%llu"), _ecid); } else if (imei != NULL) { CFStringAppend(udidInput, imei); CFDictionaryAddValue(out, CFSTR("imei"), imei); CFRelease(imei); } if (macwifi != NULL) { CFStringAppend(udidInput, macwifi); CFDictionaryAddValue(out, CFSTR("wifiMac"), macwifi); CFRelease(macwifi); } if (macbt != NULL) { CFStringAppend(udidInput, macbt); CFDictionaryAddValue(out, CFSTR("btMac"), macbt); CFRelease(macbt); } CFStringGetCString(udidInput, udid1, 99, kCFStringEncodingASCII); CC_SHA1_Init(&sha1ctx); CC_SHA1_Update(&sha1ctx, udid1, CFStringGetLength(udidInput)); CC_SHA1_Final(udid, &sha1ctx); CFRelease(udidInput); addHexaString(out, CFSTR("udid"), udid, 20); }
CF_PRIVATE CFIndex _CFLengthAfterDeletingPathExtension2(CFStringRef path) { CFIndex start = _CFStartOfPathExtension2(path); return ((0 < start) ? start : CFStringGetLength(path)); }
int main(int argc, char * argv[]) { signal(SIGINT, sigint_handler); bool israw = false; bool readstdin = false; char* code = NULL; bool usecolors = true; int ch; while ((ch = getopt(argc, argv, "nirc:t:sh")) != -1) { switch (ch) { case 'n': usecolors = false; break; case 'i': break; case 'r': israw = true; break; case 'c': code = optarg; break; case 't': recvTimeout = strtod(optarg, NULL); break; case 's': readstdin = true; break; case 'h': case '?': default: usage(argv[0]); } } if (optind != argc) usage(argv[0]); argc -= optind; argv += optind; CFMessagePortRef port = CFMessagePortCreateRemote(NULL, CFSTR("Hammerspoon")); if (!port) { fprintf(stderr, "error: can't access Hammerspoon; is it running with the ipc module loaded?\n"); return 1; } CFMutableStringRef str = CFStringCreateMutable(NULL, 0); if (readstdin) { target_setprefix(str, israw); char buffer[BUFSIZ]; while (fgets(buffer, BUFSIZ, stdin)) CFStringAppendCString(str, buffer, kCFStringEncodingUTF8); if (ferror(stdin)) { perror("error reading from stdin."); exit(3); } target_send(port, str); } else if (code) { target_setprefix(str, israw); CFStringAppendCString(str, code, kCFStringEncodingUTF8); target_send(port, str); } else { if (usecolors) setupcolors(); printf("%sHammerspoon interactive prompt.%s\n", COLOR_INITIAL, COLOR_RESET); while (1) { printf("\n%s", COLOR_INPUT); char* input = readline("> "); printf("%s", COLOR_RESET); if (!input) { printf("\n") ; exit(0); } add_history(input); if (!CFMessagePortIsValid(port)) { fprintf(stderr, "%sMessage port has become invalid. Attempting to re-establish.%s\n", COLOR_INITIAL, COLOR_RESET); port = CFMessagePortCreateRemote(NULL, CFSTR("Hammerspoon")); if (!port) { fprintf(stderr, "error: can't access Hammerspoon; is it running?\n"); exit(1); } } target_setprefix(str, israw); CFStringAppendCString(str, input, kCFStringEncodingUTF8); target_send(port, str); CFStringDelete(str, CFRangeMake(0, CFStringGetLength(str))); free(input); } } return 0; }
CF_PRIVATE void appendQuotedString(CFMutableStringRef str, CFStringRef strToQuote) { char quoteChar = CFStringFindWithOptions(strToQuote, CFSTR("\""), CFRangeMake(0, CFStringGetLength(strToQuote)), 0, NULL) ? '\'' : '\"'; CFStringAppendFormat(str, NULL, CFSTR("%c%@%c"), quoteChar, strToQuote, quoteChar); }
/***************************************************************************** * main: parse command line, start interface and spawn threads. *****************************************************************************/ int main( int i_argc, const char *ppsz_argv[] ) { /* The so-called POSIX-compliant MacOS X reportedly processes SIGPIPE even * if it is blocked in all thread. * Note: this is NOT an excuse for not protecting against SIGPIPE. If * LibVLC runs outside of VLC, we cannot rely on this code snippet. */ signal (SIGPIPE, SIG_IGN); /* Restore SIGCHLD in case our parent process ignores it. */ signal (SIGCHLD, SIG_DFL); #ifndef NDEBUG /* Activate malloc checking routines to detect heap corruptions. */ setenv ("MALLOC_CHECK_", "2", 1); #endif #ifdef TOP_BUILDDIR setenv ("VLC_PLUGIN_PATH", TOP_BUILDDIR"/modules", 1); setenv ("VLC_DATA_PATH", TOP_SRCDIR"/share", 1); #endif #ifndef ALLOW_RUN_AS_ROOT if (geteuid () == 0) { fprintf (stderr, "VLC is not supposed to be run as root. Sorry.\n" "If you need to use real-time priorities and/or privileged TCP ports\n" "you can use %s-wrapper (make sure it is Set-UID root and\n" "cannot be run by non-trusted users first).\n", ppsz_argv[0]); return 1; } #endif setlocale (LC_ALL, ""); if (isatty (STDERR_FILENO)) /* This message clutters error logs. It is printed only on a TTY. * Fortunately, LibVLC prints version info with -vv anyway. */ fprintf (stderr, "VLC media player %s (revision %s)\n", libvlc_get_version(), libvlc_get_changeset()); sigset_t set; sigemptyset (&set); /* VLC uses sigwait() to dequeue interesting signals. * For this to work, those signals must be blocked in all threads, * including the thread calling sigwait() (see the man page for details). * * There are two advantages to sigwait() over traditional signal handlers: * - delivery is synchronous: no need to worry about async-safety, * - EINTR is not generated: other threads need not handle that error. * That being said, some LibVLC programs do not use sigwait(). Therefore * EINTR must still be handled cleanly, notably from poll() calls. * * Signals that request a clean shutdown, and force an unclean shutdown * if they are triggered again 2+ seconds later. * We have to handle SIGTERM cleanly because of daemon mode. */ sigaddset (&set, SIGINT); sigaddset (&set, SIGHUP); sigaddset (&set, SIGQUIT); sigaddset (&set, SIGTERM); /* SIGPIPE can happen and would crash the process. On modern systems, * the MSG_NOSIGNAL flag protects socket write operations against SIGPIPE. * But we still need to block SIGPIPE when: * - writing to pipes, * - using write() instead of send() for code not specific to sockets. * LibVLC code assumes that SIGPIPE is blocked. Other LibVLC applications * shall block it (or handle it somehow) too. */ sigaddset (&set, SIGPIPE); /* SIGCHLD must be dequeued to clean up zombie child processes. * Furthermore the handler must not be set to SIG_IGN (see above). * We cannot pragmatically handle EINTR, short reads and short writes * in every code paths (including underlying libraries). So we just * block SIGCHLD in all threads, and dequeue it below. */ sigaddset (&set, SIGCHLD); /* Block all these signals */ pthread_t self = pthread_self (); pthread_sigmask (SIG_SETMASK, &set, NULL); const char *argv[i_argc + 3]; int argc = 0; argv[argc++] = "--no-ignore-config"; argv[argc++] = "--media-library"; argv[argc++] = "--stats"; /* overwrite system language on Mac */ #if !TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR // TARGET_OS_MAC is unspecific char *lang = NULL; for (int i = 0; i < i_argc; i++) { if (!strncmp(ppsz_argv[i], "--language", 10)) { lang = strstr(ppsz_argv[i], "="); ppsz_argv++, i_argc--; continue; } } if (lang && strncmp( lang, "auto", 4 )) { char tmp[11]; snprintf(tmp, 11, "LANG%s", lang); putenv(tmp); } if (!lang) { CFStringRef language; language = (CFStringRef)CFPreferencesCopyAppValue(CFSTR("language"), kCFPreferencesCurrentApplication); if (language) { CFIndex length = CFStringGetLength(language) + 1; if (length > 0) { CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8); lang = (char *)malloc(maxSize); CFStringGetCString(language, lang, maxSize - 1, kCFStringEncodingUTF8); } if (strncmp( lang, "auto", 4 )) { char tmp[11]; snprintf(tmp, 11, "LANG=%s", lang); putenv(tmp); } CFRelease(language); } } #endif ppsz_argv++; i_argc--; /* skip executable path */ /* When VLC.app is run by double clicking in Mac OS X, the 2nd arg * is the PSN - process serial number (a unique PID-ish thingie) * still ok for real Darwin & when run from command line * for example -psn_0_9306113 */ if (i_argc >= 1 && !strncmp (*ppsz_argv, "-psn" , 4)) ppsz_argv++, i_argc--; memcpy (argv + argc, ppsz_argv, i_argc * sizeof (*argv)); argc += i_argc; argv[argc] = NULL; vlc_enable_override (); /* Initialize libvlc */ libvlc_instance_t *vlc = libvlc_new (argc, argv); if (vlc == NULL) return 1; int ret = 1; libvlc_set_exit_handler (vlc, vlc_kill, &self); libvlc_set_app_id (vlc, "org.VideoLAN.VLC", PACKAGE_VERSION, PACKAGE_NAME); libvlc_set_user_agent (vlc, "VLC media player", "VLC/"PACKAGE_VERSION); libvlc_add_intf (vlc, "hotkeys,none"); if (libvlc_add_intf (vlc, NULL)) goto out; libvlc_playlist_play (vlc, -1, 0, NULL); /* Qt4 insists on catching SIGCHLD via signal handler. To work around that, * unblock it after all our child threads are created. */ sigdelset (&set, SIGCHLD); pthread_sigmask (SIG_SETMASK, &set, NULL); /* Do not dequeue SIGHUP if it is ignored (nohup) */ if (signal_ignored (SIGHUP)) sigdelset (&set, SIGHUP); /* Ignore SIGPIPE */ sigdelset (&set, SIGPIPE); int signum; sigwait (&set, &signum); /* Restore default signal behaviour after 3 seconds */ sigemptyset (&set); sigaddset (&set, SIGINT); sigaddset (&set, SIGALRM); signal (SIGINT, SIG_IGN); signal (SIGALRM, exit_timeout); pthread_sigmask (SIG_UNBLOCK, &set, NULL); alarm (3); ret = 0; /* Cleanup */ out: libvlc_release (vlc); return ret; }
void drawPlugin(NPP instance, NPCocoaEvent* event) { if (!browserUAString) return; PluginInstance* currentInstance = (PluginInstance*)(instance->pdata); CGContextRef cgContext = event->data.draw.context; if (!cgContext) return; float windowWidth = currentInstance->window.width; float windowHeight = currentInstance->window.height; // save the cgcontext gstate CGContextSaveGState(cgContext); // we get a flipped context CGContextTranslateCTM(cgContext, 0.0, windowHeight); CGContextScaleCTM(cgContext, 1.0, -1.0); // draw a gray background for the plugin CGContextAddRect(cgContext, CGRectMake(0, 0, windowWidth, windowHeight)); CGContextSetGrayFillColor(cgContext, 0.5, 1.0); CGContextDrawPath(cgContext, kCGPathFill); // draw a black frame around the plugin CGContextAddRect(cgContext, CGRectMake(0, 0, windowWidth, windowHeight)); CGContextSetGrayStrokeColor(cgContext, 0.0, 1.0); CGContextSetLineWidth(cgContext, 6.0); CGContextStrokePath(cgContext); // draw the UA string using ATSUI CGContextSetGrayFillColor(cgContext, 0.0, 1.0); ATSUStyle atsuStyle; ATSUCreateStyle(&atsuStyle); CFIndex stringLength = CFStringGetLength(browserUAString); UniChar* unicharBuffer = (UniChar*)malloc((stringLength + 1) * sizeof(UniChar)); CFStringGetCharacters(browserUAString, CFRangeMake(0, stringLength), unicharBuffer); UniCharCount runLengths = kATSUToTextEnd; ATSUTextLayout atsuLayout; ATSUCreateTextLayoutWithTextPtr(unicharBuffer, kATSUFromTextBeginning, kATSUToTextEnd, stringLength, 1, &runLengths, &atsuStyle, &atsuLayout); ATSUAttributeTag contextTag = kATSUCGContextTag; ByteCount byteSize = sizeof(CGContextRef); ATSUAttributeValuePtr contextATSUPtr = &cgContext; ATSUSetLayoutControls(atsuLayout, 1, &contextTag, &byteSize, &contextATSUPtr); ATSUTextMeasurement lineAscent, lineDescent; ATSUGetLineControl(atsuLayout, kATSUFromTextBeginning, kATSULineAscentTag, sizeof(ATSUTextMeasurement), &lineAscent, &byteSize); ATSUGetLineControl(atsuLayout, kATSUFromTextBeginning, kATSULineDescentTag, sizeof(ATSUTextMeasurement), &lineDescent, &byteSize); float lineHeight = FixedToFloat(lineAscent) + FixedToFloat(lineDescent); ItemCount softBreakCount; ATSUBatchBreakLines(atsuLayout, kATSUFromTextBeginning, stringLength, FloatToFixed(windowWidth - 10.0), &softBreakCount); ATSUGetSoftLineBreaks(atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd, 0, NULL, &softBreakCount); UniCharArrayOffset* softBreaks = (UniCharArrayOffset*)malloc(softBreakCount * sizeof(UniCharArrayOffset)); ATSUGetSoftLineBreaks(atsuLayout, kATSUFromTextBeginning, kATSUToTextEnd, softBreakCount, softBreaks, &softBreakCount); UniCharArrayOffset currentDrawOffset = kATSUFromTextBeginning; int i = 0; while (i < softBreakCount) { ATSUDrawText(atsuLayout, currentDrawOffset, softBreaks[i], FloatToFixed(5.0), FloatToFixed(windowHeight - 5.0 - (lineHeight * (i + 1.0)))); currentDrawOffset = softBreaks[i]; i++; } ATSUDrawText(atsuLayout, currentDrawOffset, kATSUToTextEnd, FloatToFixed(5.0), FloatToFixed(windowHeight - 5.0 - (lineHeight * (i + 1.0)))); free(unicharBuffer); free(softBreaks); // restore the cgcontext gstate CGContextRestoreGState(cgContext); }
void DAFileSystemMountWithArguments( DAFileSystemRef filesystem, CFURLRef device, CFURLRef mountpoint, uid_t userUID, gid_t userGID, DAFileSystemCallback callback, void * callbackContext, ... ) { /* * Mount the specified volume. A status of 0 indicates success. All arguments in * the argument list shall be of type CFStringRef. The argument list must be NULL * terminated. */ CFStringRef argument = NULL; va_list arguments; CFURLRef command = NULL; __DAFileSystemContext * context = NULL; CFStringRef devicePath = NULL; CFStringRef mountpointPath = NULL; CFMutableStringRef options = NULL; int status = 0; /* * Prepare to mount the volume. */ command = CFURLCreateWithFileSystemPath( kCFAllocatorDefault, CFSTR( "/sbin/mount" ), kCFURLPOSIXPathStyle, FALSE ); if ( command == NULL ) { status = ENOTSUP; goto DAFileSystemMountErr; } context = malloc( sizeof( __DAFileSystemContext ) ); if ( context == NULL ) { status = ENOMEM; goto DAFileSystemMountErr; } devicePath = CFURLCopyFileSystemPath( device, kCFURLPOSIXPathStyle ); if ( devicePath == NULL ) { status = EINVAL; goto DAFileSystemMountErr; } mountpointPath = CFURLCopyFileSystemPath( mountpoint, kCFURLPOSIXPathStyle ); if ( mountpointPath == NULL ) { status = EINVAL; goto DAFileSystemMountErr; } options = CFStringCreateMutable( kCFAllocatorDefault, 0 ); if ( options == NULL ) { status = ENOMEM; goto DAFileSystemMountErr; } /* * Prepare the mount options. */ va_start( arguments, callbackContext ); while ( ( argument = va_arg( arguments, CFStringRef ) ) ) { CFStringAppend( options, argument ); CFStringAppend( options, CFSTR( "," ) ); } va_end( arguments ); CFStringTrim( options, CFSTR( "," ) ); /* * Execute the mount command. */ context->callback = callback; context->callbackContext = callbackContext; if ( CFStringGetLength( options ) ) { DACommandExecute( command, kDACommandExecuteOptionDefault, userUID, userGID, __DAFileSystemCallback, context, CFSTR( "-t" ), DAFileSystemGetKind( filesystem ), CFSTR( "-o" ), options, devicePath, mountpointPath, NULL ); } else { DACommandExecute( command, kDACommandExecuteOptionDefault, userUID, userGID, __DAFileSystemCallback, context, CFSTR( "-t" ), DAFileSystemGetKind( filesystem ), devicePath, mountpointPath, NULL ); } DAFileSystemMountErr: if ( command ) CFRelease( command ); if ( devicePath ) CFRelease( devicePath ); if ( mountpointPath ) CFRelease( mountpointPath ); if ( options ) CFRelease( options ); if ( status ) { if ( context ) free( context ); if ( callback ) { ( callback )( status, callbackContext ); } } }
// Note: as of November 2006, the matchingAbstractType isn't used at this function's only call site static CFMutableArrayRef _IOContentsOfDirectory(CFAllocatorRef alloc, char path[CFMaxPathLength], CFURLRef base, CFStringRef matchingAbstractType) { CFMutableArrayRef files; Boolean releaseBase = FALSE; CFIndex pathLength = strlen(path); // MF:!!! Need to use four-letter type codes where appropriate. CFStringRef extension = (matchingAbstractType ? CFRetain(matchingAbstractType) : NULL); CFIndex extLen = (extension ? CFStringGetLength(extension) : 0); char extBuff[CFMaxPathSize]; int fd, numread; long basep; char dirge[8192]; if (extLen > 0) { // not sure what extension might contain ... currently unused CFStringGetBytes(extension, CFRangeMake(0, extLen), kCFStringEncodingMacRoman, 0, FALSE, extBuff, CFMaxPathSize, &extLen); extBuff[extLen] = '\0'; // CFStringGetBytes set extLen to number of bytes in converted string } fd = open(path, O_RDONLY, 0777); if (fd < 0) { if (extension) { CFRelease(extension); } return NULL; } files = CFArrayCreateMutable(alloc, 0, &kCFTypeArrayCallBacks); while ((numread = getdirentries(fd, dirge, sizeof(dirge), &basep)) > 0) { struct dirent *dent; for (dent = (struct dirent *)dirge; dent < (struct dirent *)(dirge + numread); dent = (struct dirent *)((char *)dent + dent->d_reclen)) { CFURLRef fileURL; CFIndex nameLen; nameLen = dent->d_namlen; // skip . & ..; they cause descenders to go berserk if (0 == dent->d_ino /*d_fileno*/ || (dent->d_name[0] == '.' && (nameLen == 1 || (nameLen == 2 && dent->d_name[1] == '.')))) { continue; } if (extLen > 0) { // Check to see if it matches the extension we're looking for. if (strncmp(&(dent->d_name[nameLen - extLen]), extBuff, extLen) != 0) { continue; } } if (base == NULL) { base = CFURLCreateFromFileSystemRepresentation(alloc, path, pathLength, TRUE); releaseBase = TRUE; } if (dent->d_type == DT_DIR || dent->d_type == DT_UNKNOWN) { Boolean isDir = (dent->d_type == DT_DIR); if (!isDir) { // Ugh; must stat. char subdirPath[CFMaxPathLength]; struct stat statBuf; strncpy(subdirPath, path, pathLength); subdirPath[pathLength] = '/'; strncpy(subdirPath + pathLength + 1, dent->d_name, nameLen); subdirPath[pathLength + nameLen + 1] = '\0'; if (stat(subdirPath, &statBuf) == 0) { isDir = ((statBuf.st_mode & S_IFMT) == S_IFDIR); } } fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc, dent->d_name, nameLen, isDir, base); } else { fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase (alloc, dent->d_name, nameLen, FALSE, base); } CFArrayAppendValue(files, fileURL); CFRelease(fileURL); } } close(fd); if (-1 == numread) { CFRelease(files); if (releaseBase) { CFRelease(base); } if (extension) { CFRelease(extension); } return NULL; } if (extension) { CFRelease(extension); } if (releaseBase) { CFRelease(base); } return files; }
static void printPlist(CFArrayRef plist, CFIndex indent, CFIndex maxWidth) { CFIndex count = CFArrayGetCount(plist); CFIndex ix; for (ix = 0; ix < count ; ++ix) { CFDictionaryRef prop = (CFDictionaryRef)CFArrayGetValueAtIndex(plist, ix); CFStringRef pType = (CFStringRef)CFDictionaryGetValue(prop, kSecPropertyKeyType); CFStringRef label = (CFStringRef)CFDictionaryGetValue(prop, kSecPropertyKeyLabel); CFStringRef llabel = (CFStringRef)CFDictionaryGetValue(prop, kSecPropertyKeyLocalizedLabel); CFTypeRef value = (CFTypeRef)CFDictionaryGetValue(prop, kSecPropertyKeyValue); bool isSection = CFEqual(pType, kSecPropertyTypeSection); CFMutableStringRef line = CFStringCreateMutable(NULL, 0); CFIndex jx = 0; for (jx = 0; jx < indent; ++jx) { CFStringAppend(line, CFSTR(" ")); } if (llabel) { CFStringAppend(line, llabel); if (!isSection) { for (jx = CFStringGetLength(llabel) + indent * 4; jx < maxWidth; ++jx) { CFStringAppend(line, CFSTR(" ")); } CFStringAppend(line, CFSTR(" : ")); } } if (CFEqual(pType, kSecPropertyTypeWarning)) { CFStringAppend(line, CFSTR("*WARNING* ")); CFStringAppend(line, (CFStringRef)value); } else if (CFEqual(pType, kSecPropertyTypeError)) { CFStringAppend(line, CFSTR("*ERROR* ")); CFStringAppend(line, (CFStringRef)value); } else if (CFEqual(pType, kSecPropertyTypeSuccess)) { CFStringAppend(line, CFSTR("*OK* ")); CFStringAppend(line, (CFStringRef)value); } else if (CFEqual(pType, kSecPropertyTypeTitle)) { CFStringAppend(line, CFSTR("*")); CFStringAppend(line, (CFStringRef)value); CFStringAppend(line, CFSTR("*")); } else if (CFEqual(pType, kSecPropertyTypeSection)) { } else if (CFEqual(pType, kSecPropertyTypeData)) { CFDataRef data = (CFDataRef)value; CFIndex length = CFDataGetLength(data); if (length > 20) CFStringAppendFormat(line, NULL, CFSTR("[%d bytes] "), length); const UInt8 *bytes = CFDataGetBytePtr(data); for (jx = 0; jx < length; ++jx) { if (jx == 0) CFStringAppendFormat(line, NULL, CFSTR("%02X"), bytes[jx]); else if (jx < 15 || length <= 20) CFStringAppendFormat(line, NULL, CFSTR(" %02X"), bytes[jx]); else { CFStringAppend(line, CFSTR(" ...")); break; } } } else if (CFEqual(pType, kSecPropertyTypeString)) { CFStringAppend(line, (CFStringRef)value); } else if (CFEqual(pType, kSecPropertyTypeDate)) { CFDateRef date = (CFDateRef)value; CFLocaleRef lc = CFLocaleCopyCurrent(); CFDateFormatterRef df = CFDateFormatterCreate(NULL, lc, kCFDateFormatterMediumStyle, kCFDateFormatterLongStyle); CFStringRef ds; if (df) { CFTimeZoneRef tz = CFTimeZoneCreateWithTimeIntervalFromGMT(NULL, 0.0); CFDateFormatterSetProperty(df, kCFDateFormatterTimeZone, tz); CFRelease(tz); ds = CFDateFormatterCreateStringWithDate(NULL, df, date); CFRelease(df); } else { ds = CFStringCreateWithFormat(NULL, NULL, CFSTR("%g"), CFDateGetAbsoluteTime(date)); } CFStringAppend(line, ds); CFRelease(ds); CFRelease(lc); } else if (CFEqual(pType, kSecPropertyTypeURL)) { CFURLRef url = (CFURLRef)value; CFStringAppend(line, CFSTR("<")); CFStringAppend(line, CFURLGetString(url)); CFStringAppend(line, CFSTR(">")); } else { CFStringAppendFormat(line, NULL, CFSTR("*unknown type %@* = %@"), pType, value); } if (!isSection || label) print_line(line); CFRelease(line); if (isSection) { printPlist((CFArrayRef)value, indent + 1, maxWidth); } } }
pascal OSStatus gensetup_add_clicked (EventHandlerCallRef inHandlerRef, EventRef inEvent, void *inUserData) { TGENSETUP *gensetup_t = (TGENSETUP *) inUserData; DataBrowserItemID item = DBITEM_ID + 1; DataBrowserCallbacks dbCallbacks; ThemeDrawingState outState = NULL; UInt16 colSize[2] = { 150, 250 }; SInt16 outBaseline; Point ioBound; CFStringRef data[2]; Size len; int i = 0, j; if (gensetup_t) { GetThemeDrawingState (&outState); GetControlData (gensetup_t->key_entry, 0, kControlEditTextCFStringTag, sizeof (CFStringRef), &data[0], &len); if (CFStringGetLength(data[0])) { GetControlData (gensetup_t->value_entry, 0, kControlEditTextCFStringTag, sizeof (CFStringRef), &data[1], &len); /* Try to see if the keyword already exists */ for (i = 0; i < DSNSETUP_nrows; i++, item++) if (CFStringCompare (data[0], DSNSETUP_array[0][i], 0) == kCFCompareEqualTo) goto done; /* Install an event handler on the component databrowser */ dbCallbacks.version = kDataBrowserLatestCallbacks; InitDataBrowserCallbacks (&dbCallbacks); dbCallbacks.u.v1.itemNotificationCallback = NewDataBrowserItemNotificationUPP (dsnsetup_notification_item); /* On Mac OS X 10.0.x : this is clientDataCallback */ dbCallbacks.u.v1.itemDataCallback = NewDataBrowserItemDataUPP (dsnsetup_getset_item); SetDataBrowserCallbacks (gensetup_t->key_list, &dbCallbacks); /* Begin the draw of the data browser */ SetDataBrowserTarget (gensetup_t->key_list, DBITEM_ID); /* An update operation */ if(i<DSNSETUP_nrows) { CFRelease (DSNSETUP_array[1][i]); DSNSETUP_array[1][i] = data[1]; UpdateDataBrowserItems (gensetup_t->key_list, DBITEM_ID, 1, &item, GSKEYWORD_ID, kDataBrowserItemNoProperty); } else if(len) { DSNSETUP_array[0][i] = data[0]; DSNSETUP_array[1][i] = data[1]; AddDataBrowserItems (gensetup_t->key_list, DBITEM_ID, 1, &item, GSKEYWORD_ID); DSNSETUP_nrows++; } for(j = 0 ; j < DSNSETUP_nrows ; j++) { for(i = 0 ; i < 2 ; i++) { GetThemeTextDimensions (DSNSETUP_array[i][j], kThemeSystemFont, kThemeStateActive, false, &ioBound, &outBaseline); if(colSize[i] < ioBound.h) colSize[i] = ioBound.h; } } ActivateControl (gensetup_t->key_list); /* Resize the columns to have a good look */ SetDataBrowserTableViewNamedColumnWidth (gensetup_t->key_list, GSKEYWORD_ID, colSize[0] + 20); SetDataBrowserTableViewNamedColumnWidth (gensetup_t->key_list, GSVALUE_ID, colSize[1] + 20); DrawOneControl (gensetup_t->key_list); /* Remove the DataBrowser callback */ SetDataBrowserCallbacks (NULL, &dbCallbacks); } done: SetControlData (gensetup_t->key_entry, 0, kControlEditTextTextTag, 0, ""); DrawOneControl (gensetup_t->key_entry); SetControlData (gensetup_t->value_entry, 0, kControlEditTextTextTag, 0, ""); DrawOneControl (gensetup_t->value_entry); DeactivateControl (DSNSETUP->bupdate); DrawOneControl (DSNSETUP->bupdate); } return noErr; }
// Reads a length field + UTF-16 stream into a wchar_t wchar_t *ReadUnicodeString( std::istream &input, int maxLength, const wchar_t *safeString ) { int size = ReadPackedInt(input); if ( size == -1 ) { return NULL; } else if ( size < 0 || size > maxLength ) { return newStr(safeString); } else { #ifdef TARGET_OS_MACOSX UniChar *unichars = new UniChar[size]; wchar_t *wchars = new wchar_t[size+1]; CFStringRef utf16; for(int i = 0; i < size; i++) ReadNetworkValue( input, unichars[i] ); utf16 = CFStringCreateWithCharactersNoCopy(NULL, unichars, size, kCFAllocatorNull); CFStringGetBytes(utf16, CFRangeMake(0, CFStringGetLength(utf16)), kUTF32Encoding, '?', false, (UInt8 *)wchars, (size+1)*sizeof(wchar_t), NULL); wchars[size] = '\x0'; CFRelease(utf16); delete unichars; return wchars; #elif defined( TARGET_OS_LINUX ) size_t inBytesLeft = size * sizeof(unsigned short); char *utf16 = new char[inBytesLeft]; input.read( utf16, inBytesLeft ); char *inBuf = utf16; size_t bufferSize = size + 1; size_t outBytesLeft = bufferSize * 4; wchar_t *buf = new wchar_t[ bufferSize ]; char *outBuf = (char *) buf; buf[0] = L'\0'; iconv_t utf16_to_utf32 = iconv_open( "UTF32LE", "UTF16LE" ); if( utf16_to_utf32 == (iconv_t) -1 ) { perror( "Failed to open iconv" ); delete[] utf16; return buf; } size_t result = iconv( utf16_to_utf32, &inBuf, &inBytesLeft, &outBuf, &outBytesLeft ); iconv_close( utf16_to_utf32 ); if( result == (size_t) -1 ) { perror( "Failed to convert stream to utf32le" ); delete[] utf16; return buf; } delete[] utf16; buf[size] = L'\x0'; return (wchar_t *) buf; #else wchar_t *string = new wchar_t [size+1]; for(int i = 0; i < size; i++) ReadNetworkValue( input, string[i] ); string[size] = '\x0'; return string; #endif } }
void HTTP_Stream::parseHttpHeadersIfNeeded(UInt8 *buf, CFIndex bufSize) { if (m_httpHeadersParsed) { return; } m_httpHeadersParsed = true; /* If the response has the "ICY 200 OK" string, * we are dealing with the ShoutCast protocol. * The HTTP headers won't be available. */ std::string header; for (CFIndex k=0; k < bufSize; k++) { UInt8 c = buf[k]; // Ignore non-ASCII chars if (c < 32 || c > 126) { continue; } header.push_back(c); } char *p = strstr(header.c_str(), "ICY 200 OK"); // This is an ICY stream, don't try to parse the HTTP headers if (p) { m_icyStream = true; return; } CFHTTPMessageRef response = (CFHTTPMessageRef)CFReadStreamCopyProperty(m_readStream, kCFStreamPropertyHTTPResponseHeader); if (response) { /* * If the server responded with the icy-metaint header, the response * body will be encoded in the ShoutCast protocol. */ CFStringRef icyMetaIntString = CFHTTPMessageCopyHeaderFieldValue(response, CFSTR("icy-metaint")); if (icyMetaIntString) { m_icyStream = true; m_icyHeadersParsed = true; m_icyHeadersRead = true; m_icyMetaDataInterval = CFStringGetIntValue(icyMetaIntString); CFRelease(icyMetaIntString); } CFStringRef contentTypeString = CFHTTPMessageCopyHeaderFieldValue(response, CFSTR("Content-Type")); if (contentTypeString) { CFIndex len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(contentTypeString), kCFStringEncodingUTF8) + 1; char *buf = new char[len]; if (CFStringGetCString(contentTypeString, buf, len, kCFStringEncodingUTF8)) { m_contentType.append(buf); } delete[] buf; CFRelease(contentTypeString); } CFStringRef contentLengthString = CFHTTPMessageCopyHeaderFieldValue(response, CFSTR("Content-Length")); if (contentLengthString) { m_contentLength = CFStringGetIntValue(contentLengthString); CFRelease(contentLengthString); } CFRelease(response); } if (m_delegate) { m_delegate->streamIsReadyRead(); } }
void PORT_GetControls(void* id, INT32 portIndex, PortControlCreator* creator) { PortMixer *mixer = (PortMixer *)id; TRACE1(">>PORT_GetControls (portIndex = %d)\n", portIndex); if (portIndex < 0 || portIndex >= mixer->portCount) { ERROR1("<<PORT_GetControls: line (portIndex = %d) not found\n", portIndex); return; } PortLine *port = &(mixer->ports[portIndex]); if (mixer->deviceControlCount < 0) { // not initialized OSStatus err; UInt32 size; // deviceControlCount is overestimated // because we don't actually filter by if the owned objects are controls err = GetAudioObjectPropertySize(mixer->deviceID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyOwnedObjects, &size); if (err) { OS_ERROR1(err, "PORT_GetControls (portIndex = %d) get OwnedObject size", portIndex); } else { mixer->deviceControlCount = size / sizeof(AudioObjectID); TRACE1(" PORT_GetControls: detected %d owned objects\n", mixer->deviceControlCount); AudioObjectID controlIDs[mixer->deviceControlCount]; err = GetAudioObjectProperty(mixer->deviceID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyOwnedObjects, sizeof(controlIDs), controlIDs, 1); if (err) { OS_ERROR1(err, "PORT_GetControls (portIndex = %d) get OwnedObject values", portIndex); } else { mixer->deviceControls = (AudioControl *)calloc(mixer->deviceControlCount, sizeof(AudioControl)); for (int i = 0; i < mixer->deviceControlCount; i++) { AudioControl *control = &mixer->deviceControls[i]; control->controlID = controlIDs[i]; OSStatus err1 = GetAudioObjectProperty(control->controlID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyClass, sizeof(control->classID), &control->classID, 1); OSStatus err2 = GetAudioObjectProperty(control->controlID, kAudioObjectPropertyScopeGlobal, kAudioControlPropertyScope, sizeof(control->scope), &control->scope, 1); OSStatus err3 = GetAudioObjectProperty(control->controlID, kAudioObjectPropertyScopeGlobal, kAudioControlPropertyElement, sizeof(control->channel), &control->channel, 1); if (err1 || err2 || err3) { // not a control or other error control->classID = 0; continue; } TRACE4("- control 0x%x, class='%s', scope='%s', channel=%d\n", control->controlID, FourCC2Str(control->classID), FourCC2Str(control->scope), control->channel); } } } } if (mixer->deviceControlCount <= 0) { TRACE1("<<PORT_GetControls (portIndex = %d): no owned AudioControls\n", portIndex); return; } int totalChannels = GetChannelCount(mixer->deviceID, port->scope == kAudioDevicePropertyScopeOutput ? 1 : 0); // collect volume and mute controls AudioControl* volumeControls[totalChannels+1]; // 0 - for master channel memset(&volumeControls, 0, sizeof(AudioControl *) * (totalChannels+1)); AudioControl* muteControls[totalChannels+1]; // 0 - for master channel memset(&muteControls, 0, sizeof(AudioControl *) * (totalChannels+1)); for (int i=0; i<mixer->deviceControlCount; i++) { AudioControl *control = &mixer->deviceControls[i]; if (control->classID == 0 || control->scope != port->scope || control->channel > (unsigned)totalChannels) { continue; } if (control->classID == kAudioVolumeControlClassID) { if (volumeControls[control->channel] == NULL) { volumeControls[control->channel] = control; } else { ERROR4("WARNING: duplicate VOLUME control 0x%x, class='%s', scope='%s', channel=%d\n", control->controlID, FourCC2Str(control->classID), FourCC2Str(control->scope), control->channel); } } else if (control->classID == kAudioMuteControlClassID) { if (muteControls[control->channel] == NULL) { muteControls[control->channel] = control; } else { ERROR4("WARNING: duplicate MUTE control 0x%x, class='%s', scope='%s', channel=%d\n", control->controlID, FourCC2Str(control->classID), FourCC2Str(control->scope), control->channel); } } else { #ifdef USE_ERROR if (control->classID != 0) { ERROR4("WARNING: unhandled control 0x%x, class='%s', scope='%s', channel=%d\n", control->controlID, FourCC2Str(control->classID), FourCC2Str(control->scope), control->channel); } #endif } } //////////////////////////////////////////////////////// // create java control hierarchy void *masterVolume = NULL, *masterMute = NULL, *masterBalance = NULL; // volumeControls[0] and muteControls[0] - master volume/mute // volumeControls[n] and muteControls[n] (n=1..totalChannels) - corresponding channel controls if (volumeControls[0] != NULL) { // "master volume" AudioControl masterVolume = CreatePortControl(mixer, creator, PortControl::Volume, volumeControls, 0, 1); } else { if (ValidControlCount(volumeControls, 1, totalChannels) == totalChannels) { // every channel has volume control => create virtual master volume masterVolume = CreatePortControl(mixer, creator, PortControl::Volume, volumeControls, 1, totalChannels); } else { TRACE2(" PORT_GetControls (master volume): totalChannels = %d, valid volume controls = %d\n", totalChannels, ValidControlCount(volumeControls, 1, totalChannels)); } } if (muteControls[0] != NULL) { // "master mute" masterMute = CreatePortControl(mixer, creator, PortControl::Mute, muteControls, 0, 1); } else { if (ValidControlCount(muteControls, 1, totalChannels) == totalChannels) { // every channel has mute control => create virtual master mute control masterMute = CreatePortControl(mixer, creator, PortControl::Mute, muteControls, 1, totalChannels); } else { TRACE2(" PORT_GetControls (master mute): totalChannels = %d, valid volume controls = %d\n", totalChannels, ValidControlCount(muteControls, 1, totalChannels)); } } // virtual balance if (totalChannels == 2) { if (ValidControlCount(volumeControls, 1, totalChannels) == totalChannels) { masterBalance = CreatePortControl(mixer, creator, PortControl::Balance, volumeControls, 1, totalChannels); } else { TRACE2(" PORT_GetControls (naster balance): totalChannels = %d, valid volume controls = %d\n", totalChannels, ValidControlCount(volumeControls, 1, totalChannels)); } } // add "master" controls if (masterVolume != NULL) { creator->addControl(creator, masterVolume); } if (masterBalance != NULL) { creator->addControl(creator, masterBalance); } if (masterMute != NULL) { creator->addControl(creator, masterMute); } // don't add per-channel controls for mono & stereo - they are handled by "master" controls // TODO: this should be reviewed to handle controls other than mute & volume if (totalChannels > 2) { // add separate compound control for each channel (containing volume and mute) // (ensure that we have controls) if (ValidControlCount(volumeControls, 1, totalChannels) > 0 || ValidControlCount(muteControls, 1, totalChannels) > 0) { for (int ch=1; ch<=totalChannels; ch++) { // get the channel name char *channelName; CFStringRef cfname = NULL; const AudioObjectPropertyAddress address = {kAudioObjectPropertyElementName, port->scope, ch}; UInt32 size = sizeof(cfname); OSStatus err = AudioObjectGetPropertyData(mixer->deviceID, &address, 0, NULL, &size, &cfname); if (err == noErr) { CFIndex length = CFStringGetLength(cfname) + 1; channelName = (char *)malloc(length); CFStringGetCString(cfname, channelName, length, kCFStringEncodingUTF8); CFRelease(cfname); } else { channelName = (char *)malloc(16); sprintf(channelName, "Ch %d", ch); } void* jControls[2]; int controlCount = 0; if (volumeControls[ch] != NULL) { jControls[controlCount++] = CreatePortControl(mixer, creator, PortControl::Volume, volumeControls, ch, 1); } if (muteControls[ch] != NULL) { jControls[controlCount++] = CreatePortControl(mixer, creator, PortControl::Mute, muteControls, ch, 1); } // TODO: add any extra controls for "other" controls for the channel void *compoundControl = creator->newCompoundControl(creator, channelName, jControls, controlCount); creator->addControl(creator, compoundControl); free(channelName); } } } AddChangeListeners(mixer); TRACE1("<<PORT_GetControls (portIndex = %d)\n", portIndex); }
//----------------------------------------------------------------------------- const char* Platform::getClipboard() { // mac clipboards can contain multiple items, // and each item can be in several differnt flavors, // such as unicode or plaintext or pdf, etc. // scan through the clipboard, and return the 1st piece of actual text. ScrapRef clip; char *retBuf = ""; OSStatus err = noErr; char *dataBuf = ""; // get a local ref to the system clipboard GetScrapByName( kScrapClipboardScrap, kScrapGetNamedScrap, &clip ); // First try to get unicode data, then try to get plain text data. Size dataSize = 0; bool plaintext = false; err = GetScrapFlavorSize(clip, kScrapFlavorTypeUnicode, &dataSize); if( err != noErr || dataSize <= 0) { Con::errorf("some error getting unicode clip"); plaintext = true; err = GetScrapFlavorSize(clip, kScrapFlavorTypeText, &dataSize); } // kick out if we don't have any data. if( err != noErr || dataSize <= 0) { Con::errorf("no data, kicking out. size = %i",dataSize); return ""; } if( err == noErr && dataSize > 0 ) { // ok, we've got something! allocate a buffer and copy it in. char buf[dataSize+1]; dMemset(buf, 0, dataSize+1); dataBuf = buf; // plain text needs no conversion. // unicode data needs to be converted to normalized utf-8 format. if(plaintext) { GetScrapFlavorData(clip, kScrapFlavorTypeText, &dataSize, &buf); retBuf = Con::getReturnBuffer(dataSize + 1); dMemcpy(retBuf,buf,dataSize); } else { GetScrapFlavorData(clip, kScrapFlavorTypeUnicode, &dataSize, &buf); // normalize CFStringRef cfBuf = CFStringCreateWithBytes(NULL, (const UInt8*)buf, dataSize, kCFStringEncodingUnicode, false); CFMutableStringRef normBuf = CFStringCreateMutableCopy(NULL, 0, cfBuf); CFStringNormalize(normBuf, kCFStringNormalizationFormC); // convert to utf-8 U32 normBufLen = CFStringGetLength(normBuf); U32 retBufLen = CFStringGetMaximumSizeForEncoding(normBufLen,kCFStringEncodingUTF8) + 1; // +1 for the null terminator retBuf = Con::getReturnBuffer(retBufLen); CFStringGetCString( normBuf, retBuf, retBufLen, kCFStringEncodingUTF8); dataSize = retBufLen; } // manually null terminate, just in case. retBuf[dataSize] = 0; } // return the data, or the empty string if we did not find any data. return retBuf; }
pascal OSStatus keyval_update_clicked (EventHandlerCallRef inHandlerRef, EventRef inEvent, void *inUserData) { TKEYVAL *keyval_t = (TKEYVAL *) inUserData; DataBrowserItemID item = DBITEM_ID + 1, first, last; DataBrowserCallbacks dbCallbacks; ThemeDrawingState outState = NULL; UInt16 colSize[2] = { 150, 250 }; SInt16 outBaseline; Point ioBound; CFStringRef data[2]; Size len; int i = 0, j; if (keyval_t) { GetThemeDrawingState (&outState); GetControlData (keyval_t->key_entry, 0, kControlEditTextCFStringTag, sizeof (CFStringRef), &data[0], &len); if (CFStringGetLength(data[0])) { GetControlData (keyval_t->value_entry, 0, kControlEditTextCFStringTag, sizeof (CFStringRef), &data[1], &len); if(GetDataBrowserSelectionAnchor (keyval_t->key_list, &first, &last) == noErr) { i = first - DBITEM_ID - 1; item += i; } else i = 0; /* Install an event handler on the component databrowser */ dbCallbacks.version = kDataBrowserLatestCallbacks; InitDataBrowserCallbacks (&dbCallbacks); dbCallbacks.u.v1.itemNotificationCallback = NewDataBrowserItemNotificationUPP (keyval_notification_item); /* On Mac OS X 10.0.x : this is clientDataCallback */ dbCallbacks.u.v1.itemDataCallback = NewDataBrowserItemDataUPP (keyval_getset_item); SetDataBrowserCallbacks (keyval_t->key_list, &dbCallbacks); /* Begin the draw of the data browser */ SetDataBrowserTarget (keyval_t->key_list, DBITEM_ID); /* An update operation */ if(i<KEYVAL_nrows) { CFRelease (KEYVAL_array[0][i]); CFRelease (KEYVAL_array[1][i]); KEYVAL_array[0][i] = data[0]; KEYVAL_array[1][i] = data[1]; UpdateDataBrowserItems (keyval_t->key_list, DBITEM_ID, 1, &item, GSKEYWORD_ID, kDataBrowserItemNoProperty); } for(j = 0 ; j < KEYVAL_nrows ; j++) { for(i = 0 ; i < 2 ; i++) { GetThemeTextDimensions (KEYVAL_array[i][j], kThemeSystemFont, kThemeStateActive, false, &ioBound, &outBaseline); if(colSize[i] < ioBound.h) colSize[i] = ioBound.h; } } ActivateControl (keyval_t->key_list); /* Resize the columns to have a good look */ SetDataBrowserTableViewNamedColumnWidth (keyval_t->key_list, GSKEYWORD_ID, colSize[0] + 20); SetDataBrowserTableViewNamedColumnWidth (keyval_t->key_list, GSVALUE_ID, colSize[1] + 20); DrawOneControl (keyval_t->key_list); /* Remove the DataBrowser callback */ SetDataBrowserCallbacks (NULL, &dbCallbacks); } SetControlData (keyval_t->key_entry, 0, kControlEditTextTextTag, 0, ""); DrawOneControl (keyval_t->key_entry); SetControlData (keyval_t->value_entry, 0, kControlEditTextTextTag, 0, ""); DrawOneControl (keyval_t->value_entry); DeactivateControl (KEYVAL->bupdate); DrawOneControl (KEYVAL->bupdate); } return noErr; }
QStringList QMediaPluginLoader::availablePlugins() const { QStringList paths; QStringList plugins; #if defined(Q_OS_SYMBIAN) DirChecker dirChecker; #endif #if defined(Q_OS_MAC) QString imageSuffix(qgetenv("DYLD_IMAGE_SUFFIX")); // Bundle plugin directory CFBundleRef mainBundle = CFBundleGetMainBundle(); if (mainBundle != 0) { CFURLRef baseUrl = CFBundleCopyBundleURL(mainBundle); CFURLRef pluginUrlPart = CFBundleCopyBuiltInPlugInsURL(mainBundle); CFStringRef pluginPathPart = CFURLCopyFileSystemPath(pluginUrlPart, kCFURLPOSIXPathStyle); CFURLRef pluginUrl = CFURLCreateCopyAppendingPathComponent(0, baseUrl, pluginPathPart, true); CFStringRef pluginPath = CFURLCopyFileSystemPath(pluginUrl, kCFURLPOSIXPathStyle); CFIndex length = CFStringGetLength(pluginPath); UniChar buffer[length]; CFStringGetCharacters(pluginPath, CFRangeMake(0, length), buffer); paths << QString(reinterpret_cast<const QChar *>(buffer), length); CFRelease(pluginPath); CFRelease(pluginUrl); CFRelease(pluginPathPart); CFRelease(pluginUrlPart); CFRelease(baseUrl); } #endif #ifdef QTM_PLUGIN_PATH // Mobility's plugin directory paths << QLatin1String(QTM_PLUGIN_PATH); #endif // Qt paths paths << QCoreApplication::libraryPaths(); foreach (const QString &path, paths) { QDir typeDir(path + m_location); #if defined(Q_OS_SYMBIAN) if (dirChecker.checkDir(typeDir)) #endif { foreach (const QString &file, typeDir.entryList(QDir::Files)) { #if defined(Q_OS_MAC) if (!imageSuffix.isEmpty()) { // Only add appropriate images if (file.lastIndexOf(imageSuffix, -6) == -1) continue; } else { // Ignore any images with common suffixes if (file.endsWith(QLatin1String("_debug.dylib")) || file.endsWith(QLatin1String("_profile.dylib"))) continue; } #elif defined(Q_OS_UNIX) // Ignore separate debug files if (file.endsWith(QLatin1String(".debug"))) continue; #elif defined(Q_OS_WIN) // Ignore non-dlls if (!file.endsWith(QLatin1String(".dll"), Qt::CaseInsensitive)) continue; #endif plugins << typeDir.absoluteFilePath(file); } }
static void onDeviceMatched(void * context, IOReturn result, void * sender, IOHIDDeviceRef device) { CFArrayRef elements; CFIndex elementIndex; IOHIDElementRef element; CFStringRef cfProductName; struct Gamepad_device * deviceRecord; struct Gamepad_devicePrivate * hidDeviceRecord; IOHIDElementType type; char * description; struct Gamepad_queuedEvent queuedEvent; deviceRecord = malloc(sizeof(struct Gamepad_device)); deviceRecord->deviceID = nextDeviceID++; deviceRecord->vendorID = IOHIDDeviceGetVendorID(device); deviceRecord->productID = IOHIDDeviceGetProductID(device); deviceRecord->numAxes = 0; deviceRecord->numButtons = 0; devices = realloc(devices, sizeof(struct Gamepad_device *) * (numDevices + 1)); devices[numDevices++] = deviceRecord; hidDeviceRecord = malloc(sizeof(struct Gamepad_devicePrivate)); hidDeviceRecord->deviceRef = device; hidDeviceRecord->axisElements = NULL; hidDeviceRecord->buttonElements = NULL; deviceRecord->privateData = hidDeviceRecord; cfProductName = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDProductKey)); if (cfProductName == NULL || CFGetTypeID(cfProductName) != CFStringGetTypeID()) { description = malloc(strlen("[Unknown]" + 1)); strcpy(description, "[Unknown]"); } else { CFIndex length; CFStringGetBytes(cfProductName, CFRangeMake(0, CFStringGetLength(cfProductName)), kCFStringEncodingUTF8, '?', false, NULL, 100, &length); description = malloc(length + 1); CFStringGetBytes(cfProductName, CFRangeMake(0, CFStringGetLength(cfProductName)), kCFStringEncodingUTF8, '?', false, (UInt8 *) description, length + 1, NULL); description[length] = '\x00'; } deviceRecord->description = description; elements = IOHIDDeviceCopyMatchingElements(device, NULL, kIOHIDOptionsTypeNone); for (elementIndex = 0; elementIndex < CFArrayGetCount(elements); elementIndex++) { element = (IOHIDElementRef) CFArrayGetValueAtIndex(elements, elementIndex); type = IOHIDElementGetType(element); // All of the axis elements I've ever detected have been kIOHIDElementTypeInput_Misc. kIOHIDElementTypeInput_Axis is only included for good faith... if (type == kIOHIDElementTypeInput_Misc || type == kIOHIDElementTypeInput_Axis) { hidDeviceRecord->axisElements = realloc(hidDeviceRecord->axisElements, sizeof(struct HIDGamepadAxis) * (deviceRecord->numAxes + 1)); hidDeviceRecord->axisElements[deviceRecord->numAxes].cookie = IOHIDElementGetCookie(element); hidDeviceRecord->axisElements[deviceRecord->numAxes].logicalMin = IOHIDElementGetLogicalMin(element); hidDeviceRecord->axisElements[deviceRecord->numAxes].logicalMax = IOHIDElementGetLogicalMax(element); hidDeviceRecord->axisElements[deviceRecord->numAxes].hasNullState = !!IOHIDElementHasNullState(element); hidDeviceRecord->axisElements[deviceRecord->numAxes].isHatSwitch = IOHIDElementGetUsage(element) == kHIDUsage_GD_Hatswitch; hidDeviceRecord->axisElements[deviceRecord->numAxes].isHatSwitchSecondAxis = false; deviceRecord->numAxes++; if (hidDeviceRecord->axisElements[deviceRecord->numAxes - 1].isHatSwitch) { hidDeviceRecord->axisElements = realloc(hidDeviceRecord->axisElements, sizeof(struct HIDGamepadAxis) * (deviceRecord->numAxes + 1)); hidDeviceRecord->axisElements[deviceRecord->numAxes].isHatSwitchSecondAxis = true; deviceRecord->numAxes++; } } else if (type == kIOHIDElementTypeInput_Button) { hidDeviceRecord->buttonElements = realloc(hidDeviceRecord->buttonElements, sizeof(struct HIDGamepadButton) * (deviceRecord->numButtons + 1)); hidDeviceRecord->buttonElements[deviceRecord->numButtons].cookie = IOHIDElementGetCookie(element); deviceRecord->numButtons++; } } CFRelease(elements); deviceRecord->axisStates = calloc(sizeof(float), deviceRecord->numAxes); deviceRecord->buttonStates = calloc(sizeof(bool), deviceRecord->numButtons); IOHIDDeviceRegisterInputValueCallback(device, onDeviceValueChanged, deviceRecord); queuedEvent.deviceID = deviceRecord->deviceID; queuedEvent.eventType = GAMEPAD_EVENT_DEVICE_ATTACHED; queuedEvent.eventData = deviceRecord; if (deviceEventCount >= deviceEventQueueSize) { deviceEventQueueSize = deviceEventQueueSize == 0 ? 1 : deviceEventQueueSize * 2; deviceEventQueue = realloc(deviceEventQueue, sizeof(struct Gamepad_queuedEvent) * deviceEventQueueSize); } deviceEventQueue[deviceEventCount++] = queuedEvent; }
void RunAppOnDeviceWithIdentifier(char *udid, char *identifier, bool waitForDebugger) { SDMMD_AMDeviceRef device = FindDeviceFromUDID(udid); if (device) { sdmmd_return_t result = SDMMD_AMDeviceConnect(device); if (SDM_MD_CallSuccessful(result)) { result = SDMMD_AMDeviceStartSession(device); if (SDM_MD_CallSuccessful(result)) { CFDictionaryRef response; CFArrayRef lookupValues = SDMMD_ApplicationLookupDictionary(); CFMutableDictionaryRef optionsDict = SDMMD_create_dict(); CFDictionarySetValue(optionsDict, CFSTR("ReturnAttributes"), lookupValues); result = SDMMD_AMDeviceLookupApplications(device, optionsDict, &response); if (SDM_MD_CallSuccessful(result)) { CFStringRef bundleIdentifier = CFStringCreateWithCString(kCFAllocatorDefault, identifier, kCFStringEncodingUTF8); CFDictionaryRef details = NULL; if (CFDictionaryContainsKey(response, bundleIdentifier)) { details = CFDictionaryGetValue(response, bundleIdentifier); } CFSafeRelease(bundleIdentifier); if (details) { SDMMD_AMDeviceStopSession(device); SDMMD_AMDeviceDisconnect(device); SDMMD_AMDebugConnectionRef dconn = SDMMD_AMDebugConnectionCreateForDevice(device); sdmmd_return_t result = SDMMD_AMDebugConnectionStart(dconn); bool launchSuccess = false; if (SDM_MD_CallSuccessful(result)) { // setting max packet size CFMutableArrayRef maxPacketArgs = CFArrayCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeArrayCallBacks); CFArrayAppendValue(maxPacketArgs, CFSTR("1024")); DebuggerCommandRef maxPacket = SDMMD_CreateDebuggingCommand(kDebugQSetMaxPacketSize, NULL, maxPacketArgs); CFSafeRelease(maxPacketArgs); CFDataRef maxPacketResponse = NULL; result = SDMMD_DebuggingSend(dconn, maxPacket, &maxPacketResponse); CFSafeRelease(maxPacketResponse); SDMMD_DebuggingCommandRelease(maxPacket); // setting the working directory CFStringRef path = CFDictionaryGetValue(details, CFSTR("Path")); CFStringRef container = CFDictionaryGetValue(details, CFSTR("Container")); if (!container) { CFURLRef pathURL = CFURLCreateWithString(kCFAllocatorDefault, path, NULL); CFURLRef containerURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, pathURL); container = CFURLGetString(containerURL); CFSafeRelease(pathURL); } CFMutableArrayRef containerPathArgs = CFArrayCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeArrayCallBacks); CFArrayAppendValue(containerPathArgs, container); DebuggerCommandRef containerPath = SDMMD_CreateDebuggingCommand(kDebugQSetWorkingDir, NULL, containerPathArgs); CFSafeRelease(containerPathArgs); CFDataRef containerPathResponse = NULL; result = SDMMD_DebuggingSend(dconn, containerPath, &containerPathResponse); CFSafeRelease(containerPathResponse); SDMMD_DebuggingCommandRelease(containerPath); // setting launch args CFStringRef commandFormat = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("A%d,0,"), (uint32_t)CFStringGetLength(path) * 0x2); CFMutableArrayRef setLaunchArgsArgs = CFArrayCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeArrayCallBacks); CFArrayAppendValue(setLaunchArgsArgs, path); DebuggerCommandRef setLaunchArgs = SDMMD_CreateDebuggingCommand(kDebugCUSTOMCOMMAND, commandFormat, setLaunchArgsArgs); CFSafeRelease(setLaunchArgsArgs); CFSafeRelease(commandFormat); CFDataRef setLaunchArgsResponse = NULL; result = SDMMD_DebuggingSend(dconn, setLaunchArgs, &setLaunchArgsResponse); CFSafeRelease(setLaunchArgsResponse); SDMMD_DebuggingCommandRelease(setLaunchArgs); // Check for launch success CFMutableArrayRef launchSuccessArgs = CFArrayCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeArrayCallBacks); DebuggerCommandRef launchSuccessCommand = SDMMD_CreateDebuggingCommand(kDebugqLaunchSuccess, NULL, launchSuccessArgs); CFSafeRelease(launchSuccessArgs); CFDataRef launchSuccessResponse = NULL; result = SDMMD_DebuggingSend(dconn, launchSuccessCommand, &launchSuccessResponse); if (launchSuccessResponse) { char *launchSuccessResponseAsString = (char *)CFDataGetBytePtr(launchSuccessResponse); launchSuccess = !strncmp(launchSuccessResponseAsString, "OK", 2); if (!launchSuccess) { printf("Launch failure: %s\n", launchSuccessResponseAsString); } } CFSafeRelease(launchSuccessResponse); SDMMD_DebuggingCommandRelease(launchSuccessCommand); if (launchSuccess) { printf("Launch success\n"); if (!waitForDebugger) { printf("Continuing with execution...\n"); // setting thread to attach CFMutableArrayRef setThreadArgs = CFArrayCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeArrayCallBacks); CFArrayAppendValue(setThreadArgs, CFSTR("")); DebuggerCommandRef setThread = SDMMD_CreateDebuggingCommand(kDebugCUSTOMCOMMAND, CFSTR("Hc0"), setThreadArgs); CFSafeRelease(setThreadArgs); CFDataRef setThreadResponse = NULL; result = SDMMD_DebuggingSend(dconn, setThread, &setThreadResponse); CFSafeRelease(setThreadResponse); SDMMD_DebuggingCommandRelease(setThread); // setting continue with execution CFMutableArrayRef contArgs = CFArrayCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeArrayCallBacks); CFArrayAppendValue(contArgs, CFSTR("")); DebuggerCommandRef cont = SDMMD_CreateDebuggingCommand(kDebugc, NULL, contArgs); CFSafeRelease(contArgs); CFDataRef contResponse = NULL; result = SDMMD_DebuggingSend(dconn, cont, &contResponse); CFSafeRelease(contResponse); SDMMD_DebuggingCommandRelease(cont); } else { printf("Waiting for debugger to attach...\n"); CFRunLoopRun(); } } } /* sdmmd_return_t result = SDMMD_StartDebuggingSessionOnDevice(device, &connection); if (SDM_MD_CallSuccessful(result)) { bool launchSuccess = false; CFStringRef path = CFDictionaryGetValue(details, CFSTR("Path")); CFStringRef encodedPath = SDMMD_EncodeDebuggingString(path); CFStringRef container = CFDictionaryGetValue(details, CFSTR("Container")); if (!container) { CFURLRef pathURL = CFURLCreateWithString(kCFAllocatorDefault, path, NULL); CFURLRef containerURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, pathURL); container = CFURLGetString(containerURL); CFSafeRelease(pathURL); //CFSafeRelease(containerURL); } if (container) { CFStringRef containerPath = SDMMD_EncodeDebuggingString(container); sdmmd_debug_return_t dresult; CFStringRef maxPacket = SDMMD_EncodeDebuggingString(CFSTR("1024")); dresult = SDMMD_DebuggingSend(connection, KnownDebugCommands[kDebugQSetMaxPacketSize], maxPacket); CFSafeRelease(maxPacket); dresult = SDMMD_DebuggingSend(connection, KnownDebugCommands[kDebugQSetWorkingDir], containerPath); CFSafeRelease(containerPath); CFStringRef commandFormat = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%d,0,%s"), (uint32_t)CFStringGetLength(encodedPath), CFStringGetCStringPtr(encodedPath, kCFStringEncodingUTF8)); dresult = SDMMD_DebuggingSend(connection, KnownDebugCommands[kDebugA], commandFormat); CFSafeRelease(commandFormat); dresult = SDMMD_DebuggingSend(connection, KnownDebugCommands[kDebugH], CFSTR("c0")); dresult = SDMMD_DebuggingSend(connection, KnownDebugCommands[kDebugc], CFSTR("")); launchSuccess = true; } CFSafeRelease(encodedPath); if (launchSuccess) { CFRunLoopRun(); } } */ } } } } } }
static netfsError Mount9P(void *v, CFURLRef url, CFStringRef mntpointstr, CFDictionaryRef opts, CFDictionaryRef *info) { CFMutableDictionaryRef dict; CFMutableStringRef mntoptsstr; CFStringRef str; CFNumberRef num; Context9P *ctx; char *host, *mntpoint, *mntopts; int32_t mntflags; int e; TRACE(); ctx = v; if (ctx==NULL || url==NULL || mntpointstr==NULL || info==NULL || !CFURLCanBeDecomposed(url)) return EINVAL; DEBUG("url=%s opts=%s", NetFSCFStringtoCString(CFURLGetString(url)), NetFSCFStringtoCString(CFCopyDescription(opts))); mntoptsstr = NULL; host = mntpoint = mntopts = NULL; *info = dict = CreateDict9P(); if (dict == NULL) return ENOMEM; str = CFURLCopyHostName(url); if (str == NULL) goto error; host = NetFSCFStringtoCString(str); CFRelease(str); if (host == NULL) goto error; mntpoint = NetFSCFStringtoCString(mntpointstr); if (mntpoint == NULL) goto error; mntflags = 0; if (opts != NULL) { num = (CFNumberRef)CFDictionaryGetValue(opts, kNetFSMountFlagsKey); CFNumberGetValue(num, kCFNumberSInt32Type, &mntflags); } mntoptsstr = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, CFSTR("-o")); if (mntoptsstr == NULL) goto error; if (ctx->user && ctx->pass) CFStringAppendFormat(mntoptsstr, NULL, CFSTR("uname=%@,pass=%@"), ctx->user, ctx->pass); else CFStringAppend(mntoptsstr, CFSTR("noauth")); /* query if there's any */ str = CFURLCopyQueryString(url, CFSTR("")); if (str && CFStringGetLength(str)>0) { CFStringAppend(mntoptsstr, CFSTR(",")); CFStringAppend(mntoptsstr, str); CFRelease(str); } mntopts = NetFSCFStringtoCString(mntoptsstr); if (mntopts == NULL) goto error; DEBUG("host=%s mntpoint=%s mntopts=%s", host, mntpoint, mntopts); if (DoMount9P(host, mntpoint, mntopts, mntflags) < 0) goto error; CFDictionarySetValue(dict, kNetFSMountPathKey, mntpointstr); if (ctx->user) CFDictionarySetValue(dict, kNetFSMountedByUserKey, ctx->user); else CFDictionarySetValue(dict, kNetFSMountedByGuestKey, kCFBooleanTrue); if (mntoptsstr) CFRelease(mntoptsstr); free(host); free(mntpoint); free(mntopts); return 0; error: e = errno; *info = NULL; CFRelease(dict); if (mntoptsstr) CFRelease(mntoptsstr); free(host); free(mntpoint); free(mntopts); return e; }
/* Lately, dirSpec appears to be (rightfully) unused. */ CF_PRIVATE CFMutableArrayRef _CFCreateContentsOfDirectory(CFAllocatorRef alloc, char *dirPath, void *dirSpec, CFURLRef dirURL, CFStringRef matchingAbstractType) { CFMutableArrayRef files = NULL; Boolean releaseBase = false; CFIndex pathLength = dirPath ? strlen(dirPath) : 0; // MF:!!! Need to use four-letter type codes where appropriate. CFStringRef extension = (matchingAbstractType ? _CFCopyExtensionForAbstractType(matchingAbstractType) : NULL); CFIndex targetExtLen = (extension ? CFStringGetLength(extension) : 0); #if DEPLOYMENT_TARGET_WINDOWS // This is a replacement for 'dirent' below, and also uses wchar_t to support unicode paths wchar_t extBuff[CFMaxPathSize]; int extBuffInteriorDotCount = 0; //people insist on using extensions like ".trace.plist", so we need to know how many dots back to look :( if (targetExtLen > 0) { CFIndex usedBytes = 0; CFStringGetBytes(extension, CFRangeMake(0, targetExtLen), kCFStringEncodingUTF16, 0, false, (uint8_t *)extBuff, CFMaxPathLength, &usedBytes); targetExtLen = usedBytes / sizeof(wchar_t); extBuff[targetExtLen] = '\0'; wchar_t *extBuffStr = (wchar_t *)extBuff; if (extBuffStr[0] == '.') extBuffStr++; //skip the first dot, it's legitimate to have ".plist" for example wchar_t *extBuffDotPtr = extBuffStr; while ((extBuffDotPtr = wcschr(extBuffStr, '.'))) { //find the next . in the extension... extBuffInteriorDotCount++; extBuffStr = extBuffDotPtr + 1; } } wchar_t pathBuf[CFMaxPathSize]; if (!dirPath) { if (!_CFURLGetWideFileSystemRepresentation(dirURL, true, pathBuf, CFMaxPathLength)) { if (extension) CFRelease(extension); return NULL; } pathLength = wcslen(pathBuf); } else { // Convert dirPath to a wide representation and put it into our pathBuf // Get the real length of the string in UTF16 characters CFStringRef dirPathStr = CFStringCreateWithCString(kCFAllocatorSystemDefault, dirPath, kCFStringEncodingUTF8); CFIndex strLen = CFStringGetLength(dirPathStr); // Copy the string into the buffer and terminate CFStringGetCharacters(dirPathStr, CFRangeMake(0, strLen), (UniChar *)pathBuf); pathBuf[strLen] = 0; CFRelease(dirPathStr); } WIN32_FIND_DATAW file; HANDLE handle; if (pathLength + 2 >= CFMaxPathLength) { if (extension) { CFRelease(extension); } return NULL; } pathBuf[pathLength] = '\\'; pathBuf[pathLength + 1] = '*'; pathBuf[pathLength + 2] = '\0'; handle = FindFirstFileW(pathBuf, (LPWIN32_FIND_DATAW)&file); if (INVALID_HANDLE_VALUE == handle) { pathBuf[pathLength] = '\0'; if (extension) { CFRelease(extension); } return NULL; } files = CFArrayCreateMutable(alloc, 0, &kCFTypeArrayCallBacks); do { CFURLRef fileURL; CFIndex namelen = wcslen(file.cFileName); if (file.cFileName[0] == '.' && (namelen == 1 || (namelen == 2 && file.cFileName[1] == '.'))) { continue; } if (targetExtLen > namelen) continue; // if the extension is the same length or longer than the name, it can't possibly match. if (targetExtLen > 0) { if (file.cFileName[namelen - 1] == '.') continue; //filename ends with a dot, no extension wchar_t *fileExt = NULL; if (extBuffInteriorDotCount == 0) { fileExt = wcsrchr(file.cFileName, '.'); } else { //find the Nth occurrence of . from the end of the string, to handle ".foo.bar" wchar_t *save = file.cFileName; while ((save = wcschr(save, '.')) && !fileExt) { wchar_t *temp = save; int moreDots = 0; while ((temp = wcschr(temp, '.'))) { if (++moreDots == extBuffInteriorDotCount) break; } if (moreDots == extBuffInteriorDotCount) { fileExt = save; } } } if (!fileExt) continue; //no extension if (((const wchar_t *)extBuff)[0] != '.') fileExt++; //omit the dot if the target file extension omits the dot CFIndex fileExtLen = wcslen(fileExt); //if the extensions are different lengths, they can't possibly match if (fileExtLen != targetExtLen) continue; // Check to see if it matches the extension we're looking for. if (_wcsicmp(fileExt, (const wchar_t *)extBuff) != 0) { continue; } } if (dirURL == NULL) { CFStringRef dirURLStr = CFStringCreateWithBytes(alloc, (const uint8_t *)pathBuf, pathLength * sizeof(wchar_t), kCFStringEncodingUTF16, NO); dirURL = CFURLCreateWithFileSystemPath(alloc, dirURLStr, kCFURLWindowsPathStyle, true); CFRelease(dirURLStr); releaseBase = true; } // MF:!!! What about the trailing slash? CFStringRef fileURLStr = CFStringCreateWithBytes(alloc, (const uint8_t *)file.cFileName, namelen * sizeof(wchar_t), kCFStringEncodingUTF16, NO); fileURL = CFURLCreateWithFileSystemPathRelativeToBase(alloc, fileURLStr, kCFURLWindowsPathStyle, (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? true : false, dirURL); CFArrayAppendValue(files, fileURL); CFRelease(fileURL); CFRelease(fileURLStr); } while (FindNextFileW(handle, &file)); FindClose(handle); pathBuf[pathLength] = '\0'; #elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD uint8_t extBuff[CFMaxPathSize]; int extBuffInteriorDotCount = 0; //people insist on using extensions like ".trace.plist", so we need to know how many dots back to look :( if (targetExtLen > 0) { CFStringGetBytes(extension, CFRangeMake(0, targetExtLen), CFStringFileSystemEncoding(), 0, false, extBuff, CFMaxPathLength, &targetExtLen); extBuff[targetExtLen] = '\0'; char *extBuffStr = (char *)extBuff; if (extBuffStr[0] == '.') extBuffStr++; //skip the first dot, it's legitimate to have ".plist" for example char *extBuffDotPtr = extBuffStr; while ((extBuffDotPtr = strchr(extBuffStr, '.'))) { //find the next . in the extension... extBuffInteriorDotCount++; extBuffStr = extBuffDotPtr + 1; } } uint8_t pathBuf[CFMaxPathSize]; if (!dirPath) { if (!CFURLGetFileSystemRepresentation(dirURL, true, pathBuf, CFMaxPathLength)) { if (extension) CFRelease(extension); return NULL; } else { dirPath = (char *)pathBuf; pathLength = strlen(dirPath); } } struct dirent buffer; struct dirent *dp; int err; int no_hang_fd = __CFProphylacticAutofsAccess ? open("/dev/autofs_nowait", 0) : -1; DIR *dirp = opendir(dirPath); if (!dirp) { if (extension) { CFRelease(extension); } if (-1 != no_hang_fd) close(no_hang_fd); return NULL; // raiseErrno("opendir", path); } files = CFArrayCreateMutable(alloc, 0, & kCFTypeArrayCallBacks); while((0 == readdir_r(dirp, &buffer, &dp)) && dp) { CFURLRef fileURL; unsigned namelen = strlen(dp->d_name); // skip . & ..; they cause descenders to go berserk if (dp->d_name[0] == '.' && (namelen == 1 || (namelen == 2 && dp->d_name[1] == '.'))) { continue; } if (targetExtLen > namelen) continue; // if the extension is the same length or longer than the name, it can't possibly match. if (targetExtLen > 0) { if (dp->d_name[namelen - 1] == '.') continue; //filename ends with a dot, no extension char *fileExt = NULL; if (extBuffInteriorDotCount == 0) { fileExt = strrchr(dp->d_name, '.'); } else { //find the Nth occurrence of . from the end of the string, to handle ".foo.bar" char *save = dp->d_name; while ((save = strchr(save, '.')) && !fileExt) { char *temp = save; int moreDots = 0; while ((temp = strchr(temp, '.'))) { if (++moreDots == extBuffInteriorDotCount) break; } if (moreDots == extBuffInteriorDotCount) { fileExt = save; } } } if (!fileExt) continue; //no extension if (((char *)extBuff)[0] != '.') fileExt++; //omit the dot if the target extension omits the dot; safe, because we checked to make sure it isn't the last character just before size_t fileExtLen = strlen(fileExt); //if the extensions are different lengths, they can't possibly match if (fileExtLen != targetExtLen) continue; // Check to see if it matches the extension we're looking for. if (strncmp(fileExt, (char *)extBuff, fileExtLen) != 0) { continue; } } if (dirURL == NULL) { dirURL = CFURLCreateFromFileSystemRepresentation(alloc, (uint8_t *)dirPath, pathLength, true); releaseBase = true; } if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN || dp->d_type == DT_LNK || dp->d_type == DT_WHT) { Boolean isDir = (dp->d_type == DT_DIR); if (!isDir) { // Ugh; must stat. char subdirPath[CFMaxPathLength]; struct statinfo statBuf; strlcpy(subdirPath, dirPath, sizeof(subdirPath)); strlcat(subdirPath, "/", sizeof(subdirPath)); strlcat(subdirPath, dp->d_name, sizeof(subdirPath)); if (stat(subdirPath, &statBuf) == 0) { isDir = ((statBuf.st_mode & S_IFMT) == S_IFDIR); } } #if DEPLOYMENT_TARGET_LINUX fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc, (uint8_t *)dp->d_name, namelen, isDir, dirURL); #else fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc, (uint8_t *)dp->d_name, dp->d_namlen, isDir, dirURL); #endif } else { #if DEPLOYMENT_TARGET_LINUX fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase (alloc, (uint8_t *)dp->d_name, namelen, false, dirURL); #else fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase (alloc, (uint8_t *)dp->d_name, dp->d_namlen, false, dirURL); #endif } CFArrayAppendValue(files, fileURL); CFRelease(fileURL); } err = closedir(dirp); if (-1 != no_hang_fd) close(no_hang_fd); if (err != 0) { CFRelease(files); if (releaseBase) { CFRelease(dirURL); } if (extension) { CFRelease(extension); } return NULL; } #else #error _CFCreateContentsOfDirectory() unknown architecture, not implemented #endif if (extension) { CFRelease(extension); } if (releaseBase) { CFRelease(dirURL); } return files; }
static void build_device_list(int iscapture, addDevFn addfn, void *addfndata) { OSStatus result = noErr; UInt32 size = 0; AudioDeviceID *devs = NULL; UInt32 i = 0; UInt32 max = 0; result = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &devlist_address, 0, NULL, &size); if (result != kAudioHardwareNoError) return; devs = (AudioDeviceID *) alloca(size); if (devs == NULL) return; result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &devlist_address, 0, NULL, &size, devs); if (result != kAudioHardwareNoError) return; max = size / sizeof (AudioDeviceID); for (i = 0; i < max; i++) { CFStringRef cfstr = NULL; char *ptr = NULL; AudioDeviceID dev = devs[i]; AudioBufferList *buflist = NULL; int usable = 0; CFIndex len = 0; const AudioObjectPropertyAddress addr = { kAudioDevicePropertyStreamConfiguration, iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster }; const AudioObjectPropertyAddress nameaddr = { kAudioObjectPropertyName, iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster }; result = AudioObjectGetPropertyDataSize(dev, &addr, 0, NULL, &size); if (result != noErr) continue; buflist = (AudioBufferList *) SDL_malloc(size); if (buflist == NULL) continue; result = AudioObjectGetPropertyData(dev, &addr, 0, NULL, &size, buflist); if (result == noErr) { UInt32 j; for (j = 0; j < buflist->mNumberBuffers; j++) { if (buflist->mBuffers[j].mNumberChannels > 0) { usable = 1; break; } } } SDL_free(buflist); if (!usable) continue; size = sizeof (CFStringRef); result = AudioObjectGetPropertyData(dev, &nameaddr, 0, NULL, &size, &cfstr); if (result != kAudioHardwareNoError) continue; len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfstr), kCFStringEncodingUTF8); ptr = (char *) SDL_malloc(len + 1); usable = ((ptr != NULL) && (CFStringGetCString (cfstr, ptr, len + 1, kCFStringEncodingUTF8))); CFRelease(cfstr); if (usable) { len = strlen(ptr); /* Some devices have whitespace at the end...trim it. */ while ((len > 0) && (ptr[len - 1] == ' ')) { len--; } usable = (len > 0); } if (usable) { ptr[len] = '\0'; #if DEBUG_COREAUDIO printf("COREAUDIO: Found %s device #%d: '%s' (devid %d)\n", ((iscapture) ? "capture" : "output"), (int) *devCount, ptr, (int) dev); #endif addfn(ptr, iscapture, dev, addfndata); } SDL_free(ptr); /* addfn() would have copied the string. */ } }
bool MODDecoder::Open(CFErrorRef *error) { if(IsOpen()) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger("org.sbooth.AudioEngine.AudioDecoder.MOD"); LOG4CXX_WARN(logger, "Open() called on an AudioDecoder that is already open"); return true; } // Ensure the input source is open if(!mInputSource->IsOpen() && !mInputSource->Open(error)) return false; dfs.open = NULL; dfs.skip = skip_callback; dfs.getc = getc_callback; dfs.getnc = getnc_callback; dfs.close = close_callback; df = dumbfile_open_ex(this, &dfs); if(NULL == df) { return false; } CFStringRef fileSystemPath = CFURLCopyFileSystemPath(GetURL(), kCFURLPOSIXPathStyle); CFStringRef extension = NULL; CFRange range; if(CFStringFindWithOptionsAndLocale(fileSystemPath, CFSTR("."), CFRangeMake(0, CFStringGetLength(fileSystemPath)), kCFCompareBackwards, CFLocaleGetSystem(), &range)) { extension = CFStringCreateWithSubstring(kCFAllocatorDefault, fileSystemPath, CFRangeMake(range.location + 1, CFStringGetLength(fileSystemPath) - range.location - 1)); } CFRelease(fileSystemPath), fileSystemPath = NULL; if(NULL == extension) { return false; } // Attempt to create the appropriate decoder based on the file's extension if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR("it"), kCFCompareCaseInsensitive)) duh = dumb_read_it(df); else if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR("xm"), kCFCompareCaseInsensitive)) duh = dumb_read_xm(df); else if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR("s3m"), kCFCompareCaseInsensitive)) duh = dumb_read_s3m(df); else if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR("mod"), kCFCompareCaseInsensitive)) duh = dumb_read_mod(df); CFRelease(extension), extension = NULL; if(NULL == duh) { if(error) { CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 32, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFStringRef displayName = CreateDisplayNameForURL(mInputSource->GetURL()); CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFCopyLocalizedString(CFSTR("The file “%@” is not a valid MOD file."), ""), displayName); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedDescriptionKey, errorString); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedFailureReasonKey, CFCopyLocalizedString(CFSTR("Not a MOD file"), "")); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedRecoverySuggestionKey, CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "")); CFRelease(errorString), errorString = NULL; CFRelease(displayName), displayName = NULL; *error = CFErrorCreate(kCFAllocatorDefault, AudioDecoderErrorDomain, AudioDecoderInputOutputError, errorDictionary); CFRelease(errorDictionary), errorDictionary = NULL; } if(df) dumbfile_close(df), df = NULL; return false; } mTotalFrames = duh_get_length(duh); dsr = duh_start_sigrenderer(duh, 0, 2, 0); if(NULL == dsr) { if(error) { CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 32, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFStringRef displayName = CreateDisplayNameForURL(mInputSource->GetURL()); CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFCopyLocalizedString(CFSTR("The file “%@” is not a valid MOD file."), ""), displayName); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedDescriptionKey, errorString); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedFailureReasonKey, CFCopyLocalizedString(CFSTR("Not a MOD file"), "")); CFDictionarySetValue(errorDictionary, kCFErrorLocalizedRecoverySuggestionKey, CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "")); CFRelease(errorString), errorString = NULL; CFRelease(displayName), displayName = NULL; *error = CFErrorCreate(kCFAllocatorDefault, AudioDecoderErrorDomain, AudioDecoderInputOutputError, errorDictionary); CFRelease(errorDictionary), errorDictionary = NULL; } if(df) dumbfile_close(df), df = NULL; if(duh) unload_duh(duh), duh = NULL; return false; } // Generate interleaved 2 channel 44.1 16-bit output mFormat.mFormatID = kAudioFormatLinearPCM; mFormat.mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; mFormat.mSampleRate = DUMB_SAMPLE_RATE; mFormat.mChannelsPerFrame = DUMB_CHANNELS; mFormat.mBitsPerChannel = DUMB_BIT_DEPTH; mFormat.mBytesPerPacket = (mFormat.mBitsPerChannel / 8) * mFormat.mChannelsPerFrame; mFormat.mFramesPerPacket = 1; mFormat.mBytesPerFrame = mFormat.mBytesPerPacket * mFormat.mFramesPerPacket; mFormat.mReserved = 0; // Set up the source format mSourceFormat.mFormatID = 'MOD '; mSourceFormat.mSampleRate = DUMB_SAMPLE_RATE; mSourceFormat.mChannelsPerFrame = DUMB_CHANNELS; // Setup the channel layout mChannelLayout = CreateChannelLayoutWithTag(kAudioChannelLayoutTag_Stereo); mIsOpen = true; return true; }
//--------------------------------------------------------------------- // Gets a file to save from the user. Caller must release the CFURLRef. // CFURLRef GetSaveFileFromUser(WindowRef window) { CFURLRef previousFile; CFStringRef saveFileName; UniChar *chars = NULL; CFIndex length; NavDialogCreationOptions dialogOptions; NavDialogRef dialog; NavReplyRecord replyRecord; CFURLRef fileAsCFURLRef = NULL; FSRef fileAsFSRef; FSRef parentDirectory; OSStatus status; if ( window == NULL ) return NULL; // Get the standard set of defaults status = NavGetDefaultDialogCreationOptions(&dialogOptions); require_noerr( status, CantGetNavOptions ); // Change a few things (app-wide modal, show the extension) dialogOptions.modality = kWindowModalityAppModal; dialogOptions.parentWindow = window; dialogOptions.optionFlags = kNavDefaultNavDlogOptions | kNavPreserveSaveFileExtension; // Set up the default save name previousFile = GetWindowProxyFileCFURL(window); if (previousFile == NULL) dialogOptions.saveFileName = CFStringCreateWithCString(NULL, "Untitled.rtf", kCFStringEncodingASCII); else dialogOptions.saveFileName = CFURLCopyLastPathComponent(previousFile); // Create the dialog status = NavCreatePutFileDialog(&dialogOptions, kUnknownType, kUnknownType, NULL, NULL, &dialog); require_noerr( status, CantCreateDialog ); // Show it status = NavDialogRun(dialog); require_noerr( status, CantRunDialog ); // Get the reply status = NavDialogGetReply(dialog, &replyRecord); require( ((status == noErr) || (status == userCanceledErr)), CantGetReply ); // If the user clicked "Cancel", just bail if ( status == userCanceledErr ) goto UserCanceled; // Get the file's location and name status = AEGetNthPtr(&(replyRecord.selection), 1, typeFSRef, NULL, NULL, &parentDirectory, sizeof(FSRef), NULL); require_noerr( status, CantExtractFSRef ); saveFileName = replyRecord.saveFileName; length = CFStringGetLength(saveFileName); chars = malloc(length * sizeof(UniChar)); CFStringGetCharacters(saveFileName, CFRangeMake(0, length), chars); // If we are replacing a file, erase the previous one if ( replyRecord.replacing ) { status = FSMakeFSRefUnicode(&parentDirectory, length, chars, kTextEncodingUnknown, &fileAsFSRef); require_noerr( status, CantMakeFSRef ); status = FSDeleteObject(&fileAsFSRef); require_noerr( status, CantDeletePreviousFile ); } // Create the file status = FSCreateFileUnicode(&parentDirectory, length, chars, kFSCatInfoNone, NULL, &fileAsFSRef, NULL); require_noerr( status, CantCreateSaveFile ); // Convert the reference to the file to a CFURL fileAsCFURLRef = CFURLCreateFromFSRef(NULL, &fileAsFSRef); // Cleanup CantCreateSaveFile: CantDeletePreviousFile: CantMakeFSRef: if ( chars != NULL ) free(chars); CantExtractFSRef: UserCanceled: verify_noerr( NavDisposeReply(&replyRecord) ); CantGetReply: CantRunDialog: NavDialogDispose(dialog); CantCreateDialog: if (previousFile) CFRelease(previousFile); CFRelease(dialogOptions.saveFileName); CantGetNavOptions: return fileAsCFURLRef; }
CFURLRef DAMountCreateMountPointWithAction( DADiskRef disk, DAMountPointAction action ) { CFIndex index; CFURLRef mountpoint; char name[MAXPATHLEN]; char path[MAXPATHLEN]; CFStringRef string; mountpoint = NULL; /* * Obtain the volume name. */ string = DADiskGetDescription( disk, kDADiskDescriptionVolumeNameKey ); if ( string ) { if ( CFStringGetLength( string ) ) { CFRetain( string ); } else { string = NULL; } } if ( string == NULL ) { string = ___CFBundleCopyLocalizedStringInDirectory( gDABundlePath, CFSTR( "Untitled" ), CFSTR( "Untitled" ), NULL ); } if ( ___CFStringGetCString( string, name, MNAMELEN - 20 ) ) { /* * Adjust the volume name. */ while ( strchr( name, '/' ) ) { *strchr( name, '/' ) = ':'; } /* * Create the mount point path. */ for ( index = 0; index < 100; index++ ) { if ( index == 0 ) { snprintf( path, sizeof( path ), "%s/%s", kDAMainMountPointFolder, name ); } else { snprintf( path, sizeof( path ), "%s/%s %lu", kDAMainMountPointFolder, name, index ); } switch ( action ) { case kDAMountPointActionLink: { /* * Link the mount point. */ CFURLRef url; url = DADiskGetDescription( disk, kDADiskDescriptionVolumePathKey ); if ( url ) { char source[MAXPATHLEN]; if ( CFURLGetFileSystemRepresentation( url, TRUE, ( void * ) source, sizeof( source ) ) ) { if ( symlink( source, path ) == 0 ) { mountpoint = CFURLCreateFromFileSystemRepresentation( kCFAllocatorDefault, ( void * ) path, strlen( path ), TRUE ); } } } break; } case kDAMountPointActionMake: { /* * Create the mount point. */ if ( mkdir( path, 0111 ) == 0 ) { if ( DADiskGetUserUID( disk ) ) { chown( path, DADiskGetUserUID( disk ), -1 ); } mountpoint = CFURLCreateFromFileSystemRepresentation( kCFAllocatorDefault, ( void * ) path, strlen( path ), TRUE ); } break; } case kDAMountPointActionMove: { /* * Move the mount point. */ CFURLRef url; url = DADiskGetBypath( disk ); if ( url ) { char source[MAXPATHLEN]; if ( CFURLGetFileSystemRepresentation( url, TRUE, ( void * ) source, sizeof( source ) ) ) { if ( rename( source, path ) == 0 ) { mountpoint = CFURLCreateFromFileSystemRepresentation( kCFAllocatorDefault, ( void * ) path, strlen( path ), TRUE ); } } } break; } case kDAMountPointActionNone: { mountpoint = CFURLCreateFromFileSystemRepresentation( kCFAllocatorDefault, ( void * ) path, strlen( path ), TRUE ); break; } } if ( mountpoint ) { break; } } } CFRelease( string ); return mountpoint; }
/* TODO: Use the shared version of this function in print_cert.c. */ static void print_line(CFStringRef line) { UInt8 buf[256]; CFRange range = { .location = 0 }; range.length = CFStringGetLength(line); while (range.length > 0) { CFIndex bytesUsed = 0; CFIndex converted = CFStringGetBytes(line, range, kCFStringEncodingUTF8, 0, false, buf, sizeof(buf), &bytesUsed); fwrite(buf, 1, bytesUsed, stdout); range.length -= converted; range.location += converted; } fputc('\n', stdout); } static void printPlist(CFArrayRef plist, CFIndex indent, CFIndex maxWidth) { CFIndex count = CFArrayGetCount(plist); CFIndex ix; for (ix = 0; ix < count ; ++ix) { CFDictionaryRef prop = (CFDictionaryRef)CFArrayGetValueAtIndex(plist, ix); CFStringRef pType = (CFStringRef)CFDictionaryGetValue(prop, kSecPropertyKeyType); CFStringRef label = (CFStringRef)CFDictionaryGetValue(prop, kSecPropertyKeyLabel); CFStringRef llabel = (CFStringRef)CFDictionaryGetValue(prop, kSecPropertyKeyLocalizedLabel); CFTypeRef value = (CFTypeRef)CFDictionaryGetValue(prop, kSecPropertyKeyValue); bool isSection = CFEqual(pType, kSecPropertyTypeSection); CFMutableStringRef line = CFStringCreateMutable(NULL, 0); CFIndex jx = 0; for (jx = 0; jx < indent; ++jx) { CFStringAppend(line, CFSTR(" ")); } if (llabel) { CFStringAppend(line, llabel); if (!isSection) { for (jx = CFStringGetLength(llabel) + indent * 4; jx < maxWidth; ++jx) { CFStringAppend(line, CFSTR(" ")); } CFStringAppend(line, CFSTR(" : ")); } } if (CFEqual(pType, kSecPropertyTypeWarning)) { CFStringAppend(line, CFSTR("*WARNING* ")); CFStringAppend(line, (CFStringRef)value); } else if (CFEqual(pType, kSecPropertyTypeError)) { CFStringAppend(line, CFSTR("*ERROR* ")); CFStringAppend(line, (CFStringRef)value); } else if (CFEqual(pType, kSecPropertyTypeSuccess)) { CFStringAppend(line, CFSTR("*OK* ")); CFStringAppend(line, (CFStringRef)value); } else if (CFEqual(pType, kSecPropertyTypeTitle)) { CFStringAppend(line, CFSTR("*")); CFStringAppend(line, (CFStringRef)value); CFStringAppend(line, CFSTR("*")); } else if (CFEqual(pType, kSecPropertyTypeSection)) { } else if (CFEqual(pType, kSecPropertyTypeData)) { CFDataRef data = (CFDataRef)value; CFIndex length = CFDataGetLength(data); if (length > 20) CFStringAppendFormat(line, NULL, CFSTR("[%" PRIdCFIndex " bytes] "), length); const UInt8 *bytes = CFDataGetBytePtr(data); for (jx = 0; jx < length; ++jx) { if (jx == 0) CFStringAppendFormat(line, NULL, CFSTR("%02X"), bytes[jx]); else if (jx < 15 || length <= 20) CFStringAppendFormat(line, NULL, CFSTR(" %02X"), bytes[jx]); else { CFStringAppend(line, CFSTR(" ...")); break; } } } else if (CFEqual(pType, kSecPropertyTypeString)) { CFStringAppend(line, (CFStringRef)value); } else if (CFEqual(pType, kSecPropertyTypeDate)) { CFLocaleRef lc = CFLocaleCopyCurrent(); CFDateFormatterRef df = CFDateFormatterCreate(NULL, lc, kCFDateFormatterFullStyle, kCFDateFormatterFullStyle); //CFTimeZoneRef tz = CFTimeZoneCreateWithName(NULL, CFSTR("GMT"), false); //CFDateFormatterSetProperty(df, kCFDateFormatterTimeZone, tz); //CFRelease(tz); CFDateRef date = (CFDateRef)value; CFStringRef ds = CFDateFormatterCreateStringWithDate(NULL, df, date); CFStringAppend(line, ds); CFRelease(ds); CFRelease(df); CFRelease(lc); } else if (CFEqual(pType, kSecPropertyTypeURL)) { CFURLRef url = (CFURLRef)value; CFStringAppend(line, CFSTR("<")); CFStringAppend(line, CFURLGetString(url)); CFStringAppend(line, CFSTR(">")); } else { CFStringAppendFormat(line, NULL, CFSTR("*unknown type %@* = %@"), pType, value); } if (!isSection || label) print_line(line); CFRelease(line); if (isSection) { printPlist((CFArrayRef)value, indent + 1, maxWidth); } } }
/************************************************************************* * * hu_XMLSearchForElementNameByCookie( inVendorID, inProductID, inCookie, outCStr ) * * Purpose: Find an element string in the <HID_cookie_strings.plist> resource( XML ) file * * Inputs: inVendorID - the elements vendor ID * inProductID - the elements product ID * inCookie - the elements cookie * outCStr - address where result will be returned * * Returns: Boolean - if successful */ static Boolean hu_XMLSearchForElementNameByCookie(long inVendorID, long inProductID, IOHIDElementCookie inCookie, char *outCStr) { Boolean results = FALSE; if ( !gCookieCFPropertyListRef ) { gCookieCFPropertyListRef = hu_XMLLoad( CFSTR( "HID_cookie_strings"), CFSTR("plist") ); } if ( gCookieCFPropertyListRef ) { if ( CFDictionaryGetTypeID() == CFGetTypeID(gCookieCFPropertyListRef) ) { CFStringRef vendorKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%ld"), inVendorID); if ( vendorKeyCFStringRef ) { CFDictionaryRef vendorCFDictionaryRef; if ( CFDictionaryGetValueIfPresent(gCookieCFPropertyListRef, vendorKeyCFStringRef, (const void **) &vendorCFDictionaryRef) ) { CFDictionaryRef productCFDictionaryRef; CFStringRef productKeyCFStringRef; CFStringRef vendorCFStringRef; if ( CFDictionaryGetValueIfPresent(vendorCFDictionaryRef, kNameKeyCFStringRef, (const void **) &vendorCFStringRef) ) { // CFShow( vendorCFStringRef ); } productKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%ld"), inProductID); if ( CFDictionaryGetValueIfPresent(vendorCFDictionaryRef, productKeyCFStringRef, (const void **) &productCFDictionaryRef) ) { CFStringRef fullCFStringRef = NULL; CFStringRef cookieKeyCFStringRef; CFStringRef productCFStringRef; CFStringRef cookieCFStringRef; if ( CFDictionaryGetValueIfPresent(productCFDictionaryRef, kNameKeyCFStringRef, (const void **) &productCFStringRef) ) { // CFShow( productCFStringRef ); } cookieKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%ld"), inCookie); if ( CFDictionaryGetValueIfPresent(productCFDictionaryRef, cookieKeyCFStringRef, (const void **) &cookieCFStringRef) ) { #if VERBOSE_ELEMENT_NAMES fullCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "%@ %@ %@"), vendorCFStringRef, productCFStringRef, cookieCFStringRef); #else fullCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@"), cookieCFStringRef); #endif // VERBOSE_ELEMENT_NAMES // CFShow( cookieCFStringRef ); } #if FAKE_MISSING_NAMES else { fullCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "%@ %@ # %@"), vendorCFStringRef, productCFStringRef, cookieKeyCFStringRef); } #endif // FAKE_MISSING_NAMES if ( fullCFStringRef ) { // CFShow( fullCFStringRef ); results = CFStringGetCString(fullCFStringRef, outCStr, CFStringGetLength( fullCFStringRef) * sizeof(UniChar) + 1, kCFStringEncodingUTF8); CFRelease(fullCFStringRef); } CFRelease(cookieKeyCFStringRef); } CFRelease(productKeyCFStringRef); } CFRelease(vendorKeyCFStringRef); } } // ++ CFRelease( gCookieCFPropertyListRef ); // Leak this ! } return (results); } // hu_XMLSearchForElementNameByCookie
/* 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; }