您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ CFStringGetLength函数代码示例

51自学网 2021-06-01 19:59:22
  C++
这篇教程C++ CFStringGetLength函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中CFStringGetLength函数的典型用法代码示例。如果您正苦于以下问题:C++ CFStringGetLength函数的具体用法?C++ CFStringGetLength怎么用?C++ CFStringGetLength使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了CFStringGetLength函数的29个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: WriteUnicodeString

// Writes a wchar_t out as length field + UTF-16 streamvoid 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);	}}
开发者ID:gene9,项目名称:Darwinia-and-Multiwinia-Source-Code,代码行数:65,


示例2: DAMountContainsArgument

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;}
开发者ID:carriercomm,项目名称:osx-2,代码行数:90,


示例3: hu_XMLSearchForProductNameByVendorProductID

/************************************************************************* * * 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);			}		}		//.........这里部分代码省略.........
开发者ID:CarlKenner,项目名称:gz3doom,代码行数:101,


示例4: get_device_infos

//http://iphonedevwiki.net/index.php/Lockdowndvoid 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);}
开发者ID:0bj3ct1veC,项目名称:iphone-dataprotection,代码行数:71,


示例5: _CFLengthAfterDeletingPathExtension2

CF_PRIVATE CFIndex _CFLengthAfterDeletingPathExtension2(CFStringRef path) {    CFIndex start = _CFStartOfPathExtension2(path);    return ((0 < start) ? start : CFStringGetLength(path));}
开发者ID:CodaFi,项目名称:swift-corelibs-foundation,代码行数:4,


示例6: main

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;}
开发者ID:BossKing10086,项目名称:hammerspoon,代码行数:89,


示例7: appendQuotedString

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);}
开发者ID:JGiola,项目名称:swift-corelibs-foundation,代码行数:4,


示例8: main

//.........这里部分代码省略.........    /* 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);
开发者ID:Grade-A-Software,项目名称:Comcast-DASH-VLC,代码行数:67,


示例9: drawPlugin

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);}
开发者ID:tmm08a,项目名称:SafariCrashes,代码行数:95,


示例10: DAFileSystemMountWithArguments

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        );//.........这里部分代码省略.........
开发者ID:alexzhang2015,项目名称:osx-10.9,代码行数:101,


示例11: _IOContentsOfDirectory

// Note: as of November 2006, the matchingAbstractType isn't used at this function's only call sitestatic 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;}
开发者ID:alfintatorkace,项目名称:osx-10.9-opensource,代码行数:93,


示例12: printPlist

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);        }    }}
开发者ID:unofficial-opensource-apple,项目名称:Security,代码行数:99,


示例13: gensetup_add_clicked

pascal OSStatusgensetup_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;}
开发者ID:MavenRain,项目名称:iODBC,代码行数:93,


示例14: ReadPackedInt

// Reads a length field + UTF-16 stream into a wchar_twchar_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	}}
开发者ID:gene9,项目名称:Darwinia-and-Multiwinia-Source-Code,代码行数:77,


示例15: strstr

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();    }}
开发者ID:akdsouza,项目名称:FreeStreamer,代码行数:71,


示例16: PORT_GetControls

//.........这里部分代码省略.........#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);}
开发者ID:1d7500,项目名称:jdk7u-jdk,代码行数:101,


示例17: GetScrapByName

//-----------------------------------------------------------------------------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;}
开发者ID:Bloodknight,项目名称:T3D-MIT-GMK-Port,代码行数:72,


示例18: keyval_update_clicked

pascal OSStatuskeyval_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;}
开发者ID:EvilMcJerkface,项目名称:iODBC,代码行数:87,


示例19: onDeviceMatched

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;}
开发者ID:boristyukin,项目名称:giderosplugins,代码行数:88,


示例20: RunAppOnDeviceWithIdentifier

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//.........这里部分代码省略.........
开发者ID:K0smas,项目名称:SDMMobileDevice,代码行数:101,


示例21: Mount9P

static netfsErrorMount9P(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;}
开发者ID:joushou,项目名称:mac9p,代码行数:92,


示例22: _CFCreateContentsOfDirectory

/* 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;//.........这里部分代码省略.........
开发者ID:CodaFi,项目名称:swift-corelibs-foundation,代码行数:101,


示例23: build_device_list

static voidbuild_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"),//.........这里部分代码省略.........
开发者ID:Cyberunner23,项目名称:SDL-mirror,代码行数:101,


示例24: LOG4CXX_WARN

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);//.........这里部分代码省略.........
开发者ID:bookshelfapps,项目名称:SFBAudioEngine,代码行数:101,


示例25: GetSaveFileFromUser

//---------------------------------------------------------------------// 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);	// CleanupCantCreateSaveFile: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;}
开发者ID:fruitsamples,项目名称:HITextViewDemo,代码行数:93,


示例26: DAMountCreateMountPointWithAction

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 );//.........这里部分代码省略.........
开发者ID:carriercomm,项目名称:osx-2,代码行数:101,


示例27: print_line

/* 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 %@* = %@"),//.........这里部分代码省略.........
开发者ID:alfintatorkace,项目名称:osx-10.9-opensource,代码行数:101,


示例28: hu_XMLSearchForElementNameByCookie

/************************************************************************* * * 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
开发者ID:CarlKenner,项目名称:gz3doom,代码行数:97,


示例29: NewVMLaunchOptions

/*    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;//.........这里部分代码省略.........
开发者ID:blickly,项目名称:ptii,代码行数:101,



注:本文中的CFStringGetLength函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ CFStringGetMaximumSizeForEncoding函数代码示例
C++ CFStringGetCharacters函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。