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

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

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

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

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

示例1: DoStatPaths

OSStatus DoStatPaths(COMMAND_PROC_ARGUMENTS) {	OSStatus retval = noErr;		// Pre-conditions        // userData may be NULL	assert(request != NULL);	assert(response != NULL);    // asl may be NULL    // aslMsg may be NULL		// Get Info from arguments and assert that it's a CFArrayRef	CFArrayRef infos = CFDictionaryGetValue(request, CFSTR(kInfos)) ;	assert(infos != NULL) ;	assert(CFGetTypeID(infos) == CFArrayGetTypeID()) ;		CFIndex nFiles = CFArrayGetCount(infos) ;	CFIndex i ;	int nSucceeded = 0 ;	CFMutableDictionaryRef statDatas = CFDictionaryCreateMutable(																NULL,																nFiles,																&kCFTypeDictionaryKeyCallBacks,																&kCFTypeDictionaryValueCallBacks	) ;	CFMutableDictionaryRef errorCodes = CFDictionaryCreateMutable(															   NULL,															   nFiles,															   &kCFTypeDictionaryKeyCallBacks,															   &kCFTypeDictionaryValueCallBacks															   ) ;	for (i=0; i<nFiles; i++) {		CFStringRef path = CFArrayGetValueAtIndex(infos, i) ;		assert(CFGetTypeID(path) == CFStringGetTypeID()) ;				int errorCode = 0 ;				char pathC[SSY_UNIX_PATH_UTILS_MAX_PATH_CHARS] ;		if (errorCode == 0) {			Boolean ok = CFStringGetCString(										 path,										 pathC,										 SSY_UNIX_PATH_UTILS_MAX_PATH_CHARS,										 kCFStringEncodingASCII										 ) ;			if (!ok) {				errorCode = SSYAuthorizedTasksPathTooLong ;			}		}				if (errorCode == 0) {			struct stat aStat ;			int result = stat(pathC, &aStat) ;			if (result == 0) {				CFDataRef statData = CFDataCreate (												   kCFAllocatorDefault,												   (UInt8*)&aStat,												   sizeof(aStat)												   ) ;				CFDictionaryAddValue(statDatas, path, statData) ;				CFQRelease(statData) ;			}			else {				errorCode = errno ;			}		}						if (errorCode == 0) {			nSucceeded++ ;		}		else {			CFNumberRef errorNumber = CFNumberCreate(													 kCFAllocatorDefault,													 kCFNumberIntType,													 &errorCode													 ) ;			CFDictionaryAddValue(errorCodes, path, errorNumber) ;			CFQRelease(errorNumber) ;		}	}			CFDictionaryAddValue(response, CFSTR(kStatDatas), statDatas) ;	CFRelease(statDatas) ;	CFDictionaryAddValue(response, CFSTR(kErrorCodes), errorCodes) ;	CFRelease(errorCodes) ;		asl_log(			asl,			aslMsg,			ASL_LEVEL_DEBUG,			"DoStatPaths did good %d/%d requested files",			nSucceeded,			(int)nFiles			) ;		// Return the number of file copy operations that failed	retval = nFiles - nSucceeded ;		return retval ;}	
开发者ID:gwerz,项目名称:AuthorizedTasksInCocoa,代码行数:100,


示例2: CGFontCopyTableTags

boolScaledFontMac::GetFontFileData(FontFileDataOutput aDataCallback, void *aBaton){    // We'll reconstruct a TTF font from the tables we can get from the CGFont    CFArrayRef tags = CGFontCopyTableTags(mFont);    CFIndex count = CFArrayGetCount(tags);    TableRecord *records = new TableRecord[count];    uint32_t offset = 0;    offset += sizeof(uint32_t)*3;    offset += sizeof(uint32_t)*4*count;    bool CFF = false;    for (CFIndex i = 0; i<count; i++) {        uint32_t tag = (uint32_t)(uintptr_t)CFArrayGetValueAtIndex(tags, i);        if (tag == 0x43464620) // 'CFF '            CFF = true;        CFDataRef data = CGFontCopyTableForTag(mFont, tag);        records[i].tag = tag;        records[i].offset = offset;        records[i].data = data;        records[i].length = CFDataGetLength(data);        bool skipChecksumAdjust = (tag == 0x68656164); // 'head'        records[i].checkSum = CalcTableChecksum(reinterpret_cast<const uint32_t*>(CFDataGetBytePtr(data)),                                                records[i].length, skipChecksumAdjust);        offset += records[i].length;        // 32 bit align the tables        offset = (offset + 3) & ~3;    }    CFRelease(tags);    struct writeBuf buf(offset);    // write header/offset table    if (CFF) {      buf.writeElement(CFSwapInt32HostToBig(0x4f54544f));    } else {      buf.writeElement(CFSwapInt32HostToBig(0x00010000));    }    buf.writeElement(CFSwapInt16HostToBig(count));    buf.writeElement(CFSwapInt16HostToBig((1<<maxPow2LessThan(count))*16));    buf.writeElement(CFSwapInt16HostToBig(maxPow2LessThan(count)));    buf.writeElement(CFSwapInt16HostToBig(count*16-((1<<maxPow2LessThan(count))*16)));    // write table record entries    for (CFIndex i = 0; i<count; i++) {        buf.writeElement(CFSwapInt32HostToBig(records[i].tag));        buf.writeElement(CFSwapInt32HostToBig(records[i].checkSum));        buf.writeElement(CFSwapInt32HostToBig(records[i].offset));        buf.writeElement(CFSwapInt32HostToBig(records[i].length));    }    // write tables    int checkSumAdjustmentOffset = 0;    for (CFIndex i = 0; i<count; i++) {        if (records[i].tag == 0x68656164) {            checkSumAdjustmentOffset = buf.offset + 2*4;        }        buf.writeMem(CFDataGetBytePtr(records[i].data), CFDataGetLength(records[i].data));        buf.align();        CFRelease(records[i].data);    }    delete[] records;    // clear the checksumAdjust field before checksumming the whole font    memset(&buf.data[checkSumAdjustmentOffset], 0, sizeof(uint32_t));    uint32_t fontChecksum = CFSwapInt32HostToBig(0xb1b0afba - CalcTableChecksum(reinterpret_cast<const uint32_t*>(buf.data), offset));    // set checkSumAdjust to the computed checksum    memcpy(&buf.data[checkSumAdjustmentOffset], &fontChecksum, sizeof(fontChecksum));    // we always use an index of 0    aDataCallback(buf.data, buf.offset, 0, mSize, aBaton);    return true;}
开发者ID:abotalov,项目名称:gecko-dev,代码行数:74,


示例3: mongoc_secure_transport_setup_certificate

boolmongoc_secure_transport_setup_certificate (   mongoc_stream_tls_secure_transport_t *secure_transport,   mongoc_ssl_opt_t *opt){   bool success;   CFArrayRef items;   SecIdentityRef id;   SecKeyRef key = NULL;   SecCertificateRef cert = NULL;   SecExternalItemType type = kSecItemTypeCertificate;   if (!opt->pem_file) {      TRACE ("%s",             "No private key provided, the server won't be able to verify us");      return false;   }   success = _mongoc_secure_transport_import_pem (      opt->pem_file, opt->pem_pwd, &items, &type);   if (!success) {      MONGOC_ERROR ("Can't find certificate in: '%s'", opt->pem_file);      return false;   }   if (type != kSecItemTypeAggregate) {      MONGOC_ERROR ("Cannot work with keys of type /"%d/". Please file a JIRA",                    type);      CFRelease (items);      return false;   }   for (CFIndex i = 0; i < CFArrayGetCount (items); ++i) {      CFTypeID item_id = CFGetTypeID (CFArrayGetValueAtIndex (items, i));      if (item_id == SecCertificateGetTypeID ()) {         cert = (SecCertificateRef) CFArrayGetValueAtIndex (items, i);      } else if (item_id == SecKeyGetTypeID ()) {         key = (SecKeyRef) CFArrayGetValueAtIndex (items, i);      }   }   if (!cert || !key) {      MONGOC_ERROR ("Couldn't find valid private key");      CFRelease (items);      return false;   }   id = SecIdentityCreate (kCFAllocatorDefault, cert, key);   secure_transport->my_cert =      CFArrayCreateMutable (kCFAllocatorDefault, 2, &kCFTypeArrayCallBacks);   CFArrayAppendValue (secure_transport->my_cert, id);   CFArrayAppendValue (secure_transport->my_cert, cert);   CFRelease (id);   /*    *  Secure Transport assumes the following:    *    * The certificate references remain valid for the lifetime of the    * session.    *    * The identity specified in certRefs[0] is capable of signing.    */   success = !SSLSetCertificate (secure_transport->ssl_ctx_ref,                                 secure_transport->my_cert);   TRACE ("Setting client certificate %s", success ? "succeeded" : "failed");   CFRelease (items);   return true;}
开发者ID:cran,项目名称:mongolite,代码行数:69,


示例4: pango_core_text_family_list_faces

static voidpango_core_text_family_list_faces (PangoFontFamily  *family,                                   PangoFontFace  ***faces,                                   int              *n_faces){  PangoCoreTextFamily *ctfamily = PANGO_CORE_TEXT_FAMILY (family);  if (ctfamily->n_faces < 0)    {      GList *l;      GList *faces = NULL;      GList *synthetic_faces = NULL;      GHashTable *italic_faces;      const char *real_family = get_real_family (ctfamily->family_name);      CTFontCollectionRef collection;      CFArrayRef ctfaces;      CFArrayRef font_descriptors;      CFDictionaryRef attributes;      CFIndex i, count;      CFTypeRef keys[] = {          (CFTypeRef) kCTFontFamilyNameAttribute      };      CFStringRef values[] = {          CFStringCreateWithCString (kCFAllocatorDefault,                                     real_family,                                     kCFStringEncodingUTF8)      };      CTFontDescriptorRef descriptors[1];      attributes = CFDictionaryCreate (kCFAllocatorDefault,                                       (const void **)keys,                                       (const void **)values,                                       1,                                       &kCFTypeDictionaryKeyCallBacks,                                       &kCFTypeDictionaryValueCallBacks);      descriptors[0] = CTFontDescriptorCreateWithAttributes (attributes);      font_descriptors = CFArrayCreate (kCFAllocatorDefault,                                        (const void **)descriptors,                                        1,                                        &kCFTypeArrayCallBacks);      collection = CTFontCollectionCreateWithFontDescriptors (font_descriptors,                                                              NULL);      ctfaces = CTFontCollectionCreateMatchingFontDescriptors (collection);      italic_faces = g_hash_table_new (g_direct_hash, g_direct_equal);      count = CFArrayGetCount (ctfaces);      for (i = 0; i < count; i++)        {          PangoCoreTextFace *face;          CTFontDescriptorRef desc = CFArrayGetValueAtIndex (ctfaces, i);          face = pango_core_text_face_from_ct_font_descriptor (desc);          face->family = ctfamily;          faces = g_list_prepend (faces, face);          if (face->traits & kCTFontItalicTrait              || pango_core_text_face_is_oblique (face))            g_hash_table_insert (italic_faces,				 GINT_TO_POINTER ((gint)face->weight),                                 face);        }      CFRelease (font_descriptors);      CFRelease (attributes);      CFRelease (ctfaces);      /* For all fonts for which a non-synthetic italic variant does       * not exist on the system, we create synthesized versions here.       */      for (l = faces; l; l = l->next)        {          PangoCoreTextFace *face = l->data;          if (!g_hash_table_lookup (italic_faces,                                    GINT_TO_POINTER ((gint)face->weight)))            {              PangoCoreTextFace *italic_face;              italic_face = g_object_new (PANGO_TYPE_CORE_TEXT_FACE, NULL);              italic_face->family = ctfamily;              italic_face->postscript_name = g_strdup (face->postscript_name);              italic_face->weight = face->weight;              italic_face->traits = face->traits | kCTFontItalicTrait;              italic_face->synthetic_italic = TRUE;              italic_face->coverage = pango_coverage_ref (face->coverage);              /* Try to create a sensible face name. */              if (strcasecmp (face->style_name, "regular") == 0)                italic_face->style_name = g_strdup ("Oblique");              else                italic_face->style_name = g_strdup_printf ("%s Oblique",                                                           face->style_name);//.........这里部分代码省略.........
开发者ID:alexp-sssup,项目名称:pango,代码行数:101,


示例5: __CFArrayValidateRange

CF_INLINE void __CFArrayValidateRange(CFArrayRef array, CFRange range, const char *func) {    CFAssert3(0 <= range.location && range.location <= CFArrayGetCount(array), __kCFLogAssertion, "%s(): range.location index (%ld) out of bounds (0, %ld)", func, range.location, CFArrayGetCount(array));    CFAssert2(0 <= range.length, __kCFLogAssertion, "%s(): range.length (%ld) cannot be less than zero", func, range.length);    CFAssert3(range.location + range.length <= CFArrayGetCount(array), __kCFLogAssertion, "%s(): ending index (%ld) out of bounds (0, %ld)", func, range.location + range.length, CFArrayGetCount(array));}
开发者ID:ArtSabintsev,项目名称:swift-corelibs-foundation,代码行数:5,


示例6: SCREENReadNormalizedGammaTable

//.........这里部分代码省略.........	screenNumber = -1 * screenNumber;    }    else {        PsychCopyInScreenNumberArg(1, TRUE, &screenNumber);    }    if ((PSYCH_SYSTEM == PSYCH_LINUX) && (physicalDisplay > -1)) {        // Affect one specific display output for given screen:        outputId = physicalDisplay;    }    else {        // Other OS'es, and Linux with default setting: Affect all outputs        // for a screen.        outputId = -1;    }    // Retrieve gamma table:    PsychReadNormalizedGammaTable(screenNumber, outputId, &numEntries, &redTable, &greenTable, &blueTable);	    // Copy it out to runtime:    PsychAllocOutDoubleMatArg(1, FALSE, numEntries, 3, 0, &gammaTable);    for(i=0;i<numEntries;i++){        gammaTable[PsychIndexElementFrom3DArray(numEntries, 3, 0, i, 0, 0)]=(double)redTable[i];        gammaTable[PsychIndexElementFrom3DArray(numEntries, 3, 0, i, 1, 0)]=(double)greenTable[i];        gammaTable[PsychIndexElementFrom3DArray(numEntries, 3, 0, i, 2, 0)]=(double)blueTable[i];    }    // Copy out optional DAC resolution value:    PsychCopyOutDoubleArg(2, FALSE, (double) PsychGetDacBitsFromDisplay(screenNumber));	    // We default to the assumption that the real size of the hardware LUT is identical to    // the size of the returned LUT:    reallutsize = numEntries;	    #if PSYCH_SYSTEM == PSYCH_OSX		// On OS-X we query the real LUT size from the OS and return that value:		CGDirectDisplayID	displayID;		CFMutableDictionaryRef properties;		CFNumberRef cfGammaLength;		SInt32 lutslotcount;		io_service_t displayService;		kern_return_t kr;		CFMutableArrayRef framebufferTimings0 = 0;		CFDataRef framebufferTimings1 = 0;		IODetailedTimingInformationV2 *framebufferTiming = NULL;				// Retrieve display handle for screen:		PsychGetCGDisplayIDFromScreenNumber(&displayID, screenNumber);				// Retrieve low-level IOKit service port for this display:		displayService = CGDisplayIOServicePort(displayID);						// Obtain the properties from that service		kr = IORegistryEntryCreateCFProperties(displayService, &properties, NULL, 0);		if((kr == kIOReturnSuccess) && ((cfGammaLength = (CFNumberRef) CFDictionaryGetValue(properties, CFSTR(kIOFBGammaCountKey)))!=NULL))		{			CFNumberGetValue(cfGammaLength, kCFNumberSInt32Type, &lutslotcount);			CFRelease(properties);			reallutsize = (int) lutslotcount;		}		else {			// Failed!			if (PsychPrefStateGet_Verbosity()>1) printf("PTB-WARNING: Failed to query real size of video LUT for screen %i! Will return safe default of %i slots./n", screenNumber, reallutsize);		}			if (PsychPrefStateGet_Verbosity()>9) {						CGDisplayModeRef currentMode;			CFNumberRef n;			int modeId;			currentMode = CGDisplayCopyDisplayMode(displayID);            modeId = (int) CGDisplayModeGetIODisplayModeID(currentMode);            CGDisplayModeRelease(currentMode);            			printf("Current mode has id %i/n/n", modeId);			kr = IORegistryEntryCreateCFProperties(displayService, &properties, NULL, 0);			if((kr == kIOReturnSuccess) && ((framebufferTimings0 = (CFMutableArrayRef) CFDictionaryGetValue(properties, CFSTR(kIOFBDetailedTimingsKey) ) )!=NULL))			{				for (i=0; i<CFArrayGetCount(framebufferTimings0); i++) {					if ((framebufferTimings1 = CFArrayGetValueAtIndex(framebufferTimings0, i)) != NULL) {						if ((framebufferTiming = (IODetailedTimingInformationV2*) CFDataGetBytePtr(framebufferTimings1)) != NULL) {							printf("[%i] : VActive =  %li, VBL = %li, VSYNC = %li, VSYNCWIDTH = %li , VBORDERBOT = %li, VTOTAL = %li /n", i, framebufferTiming->verticalActive, framebufferTiming->verticalBlanking, framebufferTiming->verticalSyncOffset, framebufferTiming->verticalSyncPulseWidth, framebufferTiming->verticalBorderBottom, framebufferTiming->verticalActive + framebufferTiming->verticalBlanking);						}					}				}				CFRelease(properties);			}			else {				// Failed!				if (PsychPrefStateGet_Verbosity()>1) printf("PTB-WARNING: Failed to query STUFF for screen %i --> %p!/n", screenNumber, properties);			}			}    #endif	    // Copy out optional real LUT size (number of slots):    PsychCopyOutDoubleArg(3, FALSE, (double) reallutsize);    return(PsychError_none);}
开发者ID:AlanFreeman,项目名称:Psychtoolbox-3,代码行数:101,


示例7: convertWebResourceDataToString

static void convertWebResourceDataToString(CFMutableDictionaryRef resource){    CFMutableStringRef mimeType = (CFMutableStringRef)CFDictionaryGetValue(resource, CFSTR("WebResourceMIMEType"));    CFStringLowercase(mimeType, CFLocaleGetSystem());    convertMIMEType(mimeType);    CFArrayRef supportedMIMETypes = supportedNonImageMIMETypes();    if (CFStringHasPrefix(mimeType, CFSTR("text/")) || CFArrayContainsValue(supportedMIMETypes, CFRangeMake(0, CFArrayGetCount(supportedMIMETypes)), mimeType)) {        CFStringRef textEncodingName = static_cast<CFStringRef>(CFDictionaryGetValue(resource, CFSTR("WebResourceTextEncodingName")));        CFStringEncoding stringEncoding;        if (textEncodingName && CFStringGetLength(textEncodingName))            stringEncoding = CFStringConvertIANACharSetNameToEncoding(textEncodingName);        else            stringEncoding = kCFStringEncodingUTF8;        CFDataRef data = static_cast<CFDataRef>(CFDictionaryGetValue(resource, CFSTR("WebResourceData")));        RetainPtr<CFStringRef> dataAsString = adoptCF(CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, data, stringEncoding));        if (dataAsString)            CFDictionarySetValue(resource, CFSTR("WebResourceData"), dataAsString.get());    }}
开发者ID:3163504123,项目名称:phantomjs,代码行数:21,


示例8: SetFallbackFont

bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, MissingGlyphSearcher *callback){	const char *str;	bool result = false;	callback->FindMissingGlyphs(&str);#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)	if (MacOSVersionIsAtLeast(10, 5, 0)) {		/* Determine fallback font using CoreText. This uses the language isocode		 * to find a suitable font. CoreText is available from 10.5 onwards. */		char lang[16];		if (strcmp(language_isocode, "zh_TW") == 0) {			/* Traditional Chinese */			strecpy(lang, "zh-Hant", lastof(lang));		} else if (strcmp(language_isocode, "zh_CN") == 0) {			/* Simplified Chinese */			strecpy(lang, "zh-Hans", lastof(lang));		} else if (strncmp(language_isocode, "ur", 2) == 0) {			/* The urdu alphabet is variant of persian. As OS X has no default			 * font that advertises an urdu language code, search for persian			 * support instead. */			strecpy(lang, "fa", lastof(lang));		} else {			/* Just copy the first part of the isocode. */			strecpy(lang, language_isocode, lastof(lang));			char *sep = strchr(lang, '_');			if (sep != NULL) *sep = '/0';		}		CFStringRef lang_code;		lang_code = CFStringCreateWithCString(kCFAllocatorDefault, lang, kCFStringEncodingUTF8);		/* Create a font iterator and iterate over all fonts that		 * are available to the application. */		ATSFontIterator itr;		ATSFontRef font;		ATSFontIteratorCreate(kATSFontContextLocal, NULL, NULL, kATSOptionFlagsUnRestrictedScope, &itr);		while (!result && ATSFontIteratorNext(itr, &font) == noErr) {			/* Get CoreText font handle. */			CTFontRef font_ref = CTFontCreateWithPlatformFont(font, 0.0, NULL, NULL);			CFArrayRef langs = CTFontCopySupportedLanguages(font_ref);			if (langs != NULL) {				/* Font has a list of supported languages. */				for (CFIndex i = 0; i < CFArrayGetCount(langs); i++) {					CFStringRef lang = (CFStringRef)CFArrayGetValueAtIndex(langs, i);					if (CFStringCompare(lang, lang_code, kCFCompareAnchored) == kCFCompareEqualTo) {						/* Lang code is supported by font, get full font name. */						CFStringRef font_name = CTFontCopyFullName(font_ref);						char name[128];						CFStringGetCString(font_name, name, lengthof(name), kCFStringEncodingUTF8);						CFRelease(font_name);						/* Skip some inappropriate or ugly looking fonts that have better alternatives. */						if (strncmp(name, "Courier", 7) == 0 || strncmp(name, "Apple Symbols", 13) == 0 ||								strncmp(name, ".Aqua", 5) == 0 || strncmp(name, "LastResort", 10) == 0 ||								strncmp(name, "GB18030 Bitmap", 14) == 0) continue;						/* Save result. */						callback->SetFontNames(settings, name);						DEBUG(freetype, 2, "CT-Font for %s: %s", language_isocode, name);						result = true;						break;					}				}				CFRelease(langs);			}			CFRelease(font_ref);		}		ATSFontIteratorRelease(&itr);		CFRelease(lang_code);	} else#endif	{#if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) && !__LP64__		/* Determine fallback font using ATSUI. This uses a string sample with		 * missing characters. This is not failure-proof, but a better way like		 * using the isocode as in the CoreText code path is not available.		 * ATSUI was deprecated with 10.6 and is only partially available in		 * 64-bit mode. */		/* Remove all control characters in the range from SCC_CONTROL_START to		 * SCC_CONTROL_END as well as all ASCII < 0x20 from the string as it will		 * mess with the automatic font detection */		char buff[256]; // This length is enough to find a suitable replacement font		strecpy(buff, str, lastof(buff));		str_validate(buff, lastof(buff), SVS_ALLOW_NEWLINE);		/* Extract a UniChar representation of the sample string. */		CFStringRef cf_str = CFStringCreateWithCString(kCFAllocatorDefault, buff, kCFStringEncodingUTF8);		if (cf_str == NULL) {			/* Something went wrong. Corrupt/invalid sample string? */			return false;		}		CFIndex str_len = CFStringGetLength(cf_str);		UniChar string[str_len];		CFStringGetCharacters(cf_str, CFRangeMake(0, str_len), string);		/* Create a default text style with the default font. */		ATSUStyle style;		ATSUCreateStyle(&style);//.........这里部分代码省略.........
开发者ID:koreapyj,项目名称:openttd-yapp,代码行数:101,


示例9: keychain_iter_start

static intkeychain_iter_start(hx509_context context,		    hx509_certs certs, void *data, void **cursor){#ifndef __APPLE_TARGET_EMBEDDED__    struct ks_keychain *ctx = data;#endif    struct iter *iter;    iter = calloc(1, sizeof(*iter));    if (iter == NULL) {	hx509_set_error_string(context, 0, ENOMEM, "out of memory");	return ENOMEM;    }#ifndef __APPLE_TARGET_EMBEDDED__    if (ctx->anchors) {        CFArrayRef anchors;	int ret;	int i;	ret = hx509_certs_init(context, "MEMORY:ks-file-create",			       0, NULL, &iter->certs);	if (ret) {	    free(iter);	    return ret;	}	ret = SecTrustCopyAnchorCertificates(&anchors);	if (ret != 0) {	    hx509_certs_free(&iter->certs);	    free(iter);	    hx509_set_error_string(context, 0, ENOMEM,				   "Can't get trust anchors from Keychain");	    return ENOMEM;	}	for (i = 0; i < CFArrayGetCount(anchors); i++) {	    SecCertificateRef cr;	    hx509_cert cert;	    CFDataRef dataref;	    cr = (SecCertificateRef)CFArrayGetValueAtIndex(anchors, i);	    dataref = SecCertificateCopyData(cr);	    if (dataref == NULL)		continue;	    ret = hx509_cert_init_data(context, CFDataGetBytePtr(dataref), CFDataGetLength(dataref), &cert);	    CFRelease(dataref);	    if (ret)		continue;	    ret = hx509_certs_add(context, iter->certs, cert);	    hx509_cert_free(cert);	}	CFRelease(anchors);	if (ret != 0) {	    hx509_certs_free(&iter->certs);	    free(iter);	    hx509_set_error_string(context, 0, ret,				   "Failed to add cert");	    return ret;	}    }    if (iter->certs) {	int ret;	ret = hx509_certs_start_seq(context, iter->certs, &iter->cursor);	if (ret) {	    hx509_certs_free(&iter->certs);	    free(iter);	    return ret;	}    } else#endif    {	OSStatus ret;	const void *keys[] = {	    kSecClass,	    kSecReturnRef,	    kSecMatchLimit	};	const void *values[] = {	    kSecClassCertificate,	    kCFBooleanTrue,	    kSecMatchLimitAll	};	CFDictionaryRef secQuery;	secQuery = CFDictionaryCreate(NULL, keys, values,				      sizeof(keys) / sizeof(*keys),				      &kCFTypeDictionaryKeyCallBacks,				      &kCFTypeDictionaryValueCallBacks);		ret = SecItemCopyMatching(secQuery, (CFTypeRef *)&iter->search);	CFRelease(secQuery);	if (ret) {	    free(iter);	    return ENOMEM;//.........这里部分代码省略.........
开发者ID:aosm,项目名称:Heimdal,代码行数:101,


示例10: createXMLStringFromWebArchiveData

CFStringRef createXMLStringFromWebArchiveData(CFDataRef webArchiveData){    CFErrorRef error = 0;    CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;    RetainPtr<CFMutableDictionaryRef> propertyList = adoptCF((CFMutableDictionaryRef)CFPropertyListCreateWithData(kCFAllocatorDefault, webArchiveData, kCFPropertyListMutableContainersAndLeaves, &format, &error));    if (!propertyList) {        if (error)            return CFErrorCopyDescription(error);        return static_cast<CFStringRef>(CFRetain(CFSTR("An unknown error occurred converting data to property list.")));    }    RetainPtr<CFMutableArrayRef> resources = adoptCF(CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));    CFArrayAppendValue(resources.get(), propertyList.get());    while (CFArrayGetCount(resources.get())) {        RetainPtr<CFMutableDictionaryRef> resourcePropertyList = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(resources.get(), 0);        CFArrayRemoveValueAtIndex(resources.get(), 0);        CFMutableDictionaryRef mainResource = (CFMutableDictionaryRef)CFDictionaryGetValue(resourcePropertyList.get(), CFSTR("WebMainResource"));        normalizeWebResourceURL((CFMutableStringRef)CFDictionaryGetValue(mainResource, CFSTR("WebResourceURL")));        convertWebResourceDataToString(mainResource);        // Add subframeArchives to list for processing        CFMutableArrayRef subframeArchives = (CFMutableArrayRef)CFDictionaryGetValue(resourcePropertyList.get(), CFSTR("WebSubframeArchives")); // WebSubframeArchivesKey in WebArchive.m        if (subframeArchives)            CFArrayAppendArray(resources.get(), subframeArchives, CFRangeMake(0, CFArrayGetCount(subframeArchives)));        CFMutableArrayRef subresources = (CFMutableArrayRef)CFDictionaryGetValue(resourcePropertyList.get(), CFSTR("WebSubresources")); // WebSubresourcesKey in WebArchive.m        if (!subresources)            continue;        CFIndex subresourcesCount = CFArrayGetCount(subresources);        for (CFIndex i = 0; i < subresourcesCount; ++i) {            CFMutableDictionaryRef subresourcePropertyList = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(subresources, i);            normalizeWebResourceURL((CFMutableStringRef)CFDictionaryGetValue(subresourcePropertyList, CFSTR("WebResourceURL")));            convertWebResourceResponseToDictionary(subresourcePropertyList);            convertWebResourceDataToString(subresourcePropertyList);        }        // Sort the subresources so they're always in a predictable order for the dump        CFArraySortValues(subresources, CFRangeMake(0, CFArrayGetCount(subresources)), compareResourceURLs, 0);    }    error = 0;    RetainPtr<CFDataRef> xmlData = adoptCF(CFPropertyListCreateData(kCFAllocatorDefault, propertyList.get(), kCFPropertyListXMLFormat_v1_0, 0, &error));    if (!xmlData) {        if (error)            return CFErrorCopyDescription(error);        return static_cast<CFStringRef>(CFRetain(CFSTR("An unknown error occurred converting property list to data.")));    }    RetainPtr<CFStringRef> xmlString = adoptCF(CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, xmlData.get(), kCFStringEncodingUTF8));    RetainPtr<CFMutableStringRef> string = adoptCF(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, xmlString.get()));    // Replace "Apple Computer" with "Apple" in the DTD declaration.    CFStringFindAndReplace(string.get(), CFSTR("-//Apple Computer//"), CFSTR("-//Apple//"), CFRangeMake(0, CFStringGetLength(string.get())), 0);    return string.leakRef();}
开发者ID:3163504123,项目名称:phantomjs,代码行数:61,


示例11: keychain_query

static intkeychain_query(hx509_context context,	       hx509_certs certs,	       void *data,	       const hx509_query *query,	       hx509_cert *retcert){    CFArrayRef identities = NULL;    hx509_cert cert = NULL;    CFIndex n, count;    int ret;    int kdcLookupHack = 0;    /*     * First to course filtering using security framework ....     */#define FASTER_FLAGS (HX509_QUERY_MATCH_PERSISTENT|HX509_QUERY_PRIVATE_KEY)    if ((query->match & FASTER_FLAGS) == 0)	return HX509_UNIMPLEMENTED_OPERATION;    CFMutableDictionaryRef secQuery = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,  &kCFTypeDictionaryValueCallBacks);    /*     * XXX this is so broken, SecItem doesn't find the kdc certificte,     * and kdc certificates happend to be searched by friendly name,     * so find that and mundge on the structure.     */    if ((query->match & HX509_QUERY_MATCH_FRIENDLY_NAME) &&	(query->match & HX509_QUERY_PRIVATE_KEY) && 	strcmp(query->friendlyname, "O=System Identity,CN=com.apple.kerberos.kdc") == 0)    {	((hx509_query *)query)->match &= ~HX509_QUERY_PRIVATE_KEY;	kdcLookupHack = 1;    }    if (kdcLookupHack || (query->match & HX509_QUERY_MATCH_PERSISTENT)) {	CFDictionaryAddValue(secQuery, kSecClass, kSecClassCertificate);    } else	CFDictionaryAddValue(secQuery, kSecClass, kSecClassIdentity);    CFDictionaryAddValue(secQuery, kSecReturnRef, kCFBooleanTrue);    CFDictionaryAddValue(secQuery, kSecMatchLimit, kSecMatchLimitAll);    if (query->match & HX509_QUERY_MATCH_PERSISTENT) {	CFDataRef refdata = CFDataCreateWithBytesNoCopy(NULL, query->persistent->data, query->persistent->length, kCFAllocatorNull);	CFDictionaryAddValue(secQuery, kSecValuePersistentRef, refdata);	CFRelease(refdata);    }    OSStatus status = SecItemCopyMatching(secQuery, (CFTypeRef *)&identities);    CFRelease(secQuery);    if (status || identities == NULL) {	hx509_clear_error_string(context);	return HX509_CERT_NOT_FOUND;    }        heim_assert(CFArrayGetTypeID() == CFGetTypeID(identities), "return value not an array");    /*     * ... now do hx509 filtering     */    count = CFArrayGetCount(identities);    for (n = 0; n < count; n++) {	CFTypeRef secitem = (CFTypeRef)CFArrayGetValueAtIndex(identities, n);#ifndef __APPLE_TARGET_EMBEDDED__	if (query->match & HX509_QUERY_MATCH_PERSISTENT) {	    SecIdentityRef other = NULL;	    OSStatus osret;	    osret = SecIdentityCreateWithCertificate(NULL, (SecCertificateRef)secitem, &other);	    if (osret == noErr) {		ret = hx509_cert_init_SecFramework(context, (void *)other, &cert);		CFRelease(other);		if (ret)		    continue;	    } else {		ret = hx509_cert_init_SecFramework(context, (void *)secitem, &cert);		if (ret)		    continue;	    }	} else#endif        {	    ret = hx509_cert_init_SecFramework(context, (void *)secitem, &cert);	    if (ret)		continue;	}	if (_hx509_query_match_cert(context, query, cert)) {#ifndef __APPLE_TARGET_EMBEDDED__	    /* certtool/keychain doesn't glue togheter the cert with keys for system keys *///.........这里部分代码省略.........
开发者ID:aosm,项目名称:Heimdal,代码行数:101,


示例12: qtValue

static QVariant qtValue(CFPropertyListRef cfvalue){    if (!cfvalue)        return QVariant();    CFTypeID typeId = CFGetTypeID(cfvalue);    /*        Sorted grossly from most to least frequent type.    */    if (typeId == CFStringGetTypeID()) {        return QSettingsPrivate::stringToVariant(QCFString::toQString(static_cast<CFStringRef>(cfvalue)));    } else if (typeId == CFNumberGetTypeID()) {        CFNumberRef cfnumber = static_cast<CFNumberRef>(cfvalue);        if (CFNumberIsFloatType(cfnumber)) {            double d;            CFNumberGetValue(cfnumber, kCFNumberDoubleType, &d);            return d;        } else {            int i;            qint64 ll;            if (CFNumberGetValue(cfnumber, kCFNumberIntType, &i))                return i;            CFNumberGetValue(cfnumber, kCFNumberLongLongType, &ll);            return ll;        }    } else if (typeId == CFArrayGetTypeID()) {        CFArrayRef cfarray = static_cast<CFArrayRef>(cfvalue);        QList<QVariant> list;        CFIndex size = CFArrayGetCount(cfarray);        bool metNonString = false;        for (CFIndex i = 0; i < size; ++i) {            QVariant value = qtValue(CFArrayGetValueAtIndex(cfarray, i));            if (value.type() != QVariant::String)                metNonString = true;            list << value;        }        if (metNonString)            return list;        else            return QVariant(list).toStringList();    } else if (typeId == CFBooleanGetTypeID()) {        return (bool)CFBooleanGetValue(static_cast<CFBooleanRef>(cfvalue));    } else if (typeId == CFDataGetTypeID()) {        CFDataRef cfdata = static_cast<CFDataRef>(cfvalue);        return QByteArray(reinterpret_cast<const char *>(CFDataGetBytePtr(cfdata)),                          CFDataGetLength(cfdata));    } else if (typeId == CFDictionaryGetTypeID()) {        CFDictionaryRef cfdict = static_cast<CFDictionaryRef>(cfvalue);        CFTypeID arrayTypeId = CFArrayGetTypeID();        int size = (int)CFDictionaryGetCount(cfdict);        QVarLengthArray<CFPropertyListRef> keys(size);        QVarLengthArray<CFPropertyListRef> values(size);        CFDictionaryGetKeysAndValues(cfdict, keys.data(), values.data());        QMultiMap<QString, QVariant> map;        for (int i = 0; i < size; ++i) {            QString key = QCFString::toQString(static_cast<CFStringRef>(keys[i]));            if (CFGetTypeID(values[i]) == arrayTypeId) {                CFArrayRef cfarray = static_cast<CFArrayRef>(values[i]);                CFIndex arraySize = CFArrayGetCount(cfarray);                for (CFIndex j = arraySize - 1; j >= 0; --j)                    map.insert(key, qtValue(CFArrayGetValueAtIndex(cfarray, j)));            } else {                map.insert(key, qtValue(values[i]));            }        }        return map;    } else if (typeId == CFDateGetTypeID()) {        QDateTime dt;        dt.setTime_t((uint)kCFAbsoluteTimeIntervalSince1970);        return dt.addSecs((int)CFDateGetAbsoluteTime(static_cast<CFDateRef>(cfvalue)));    }    return QVariant();}
开发者ID:3163504123,项目名称:phantomjs,代码行数:77,


示例13: GetDataFromPasteboard

// Sorry for the very long code, all nicer OS X APIs are coded in Objective C and not C!// Also it does very thorough error handlingbool GetDataFromPasteboard( PasteboardRef inPasteboard, char* flavorText /* out */, const int bufSize ){    OSStatus            err = noErr;    PasteboardSyncFlags syncFlags;    ItemCount           itemCount;    syncFlags = PasteboardSynchronize( inPasteboard );    //require_action( syncFlags & kPasteboardModified, PasteboardOutOfSync,    //               err = badPasteboardSyncErr );    err = PasteboardGetItemCount( inPasteboard, &itemCount );    require_noerr( err, CantGetPasteboardItemCount );    for (UInt32 itemIndex = 1; itemIndex <= itemCount; itemIndex++)    {        PasteboardItemID    itemID;        CFArrayRef          flavorTypeArray;        CFIndex             flavorCount;        err = PasteboardGetItemIdentifier( inPasteboard, itemIndex, &itemID );        require_noerr( err, CantGetPasteboardItemIdentifier );        err = PasteboardCopyItemFlavors( inPasteboard, itemID, &flavorTypeArray );        require_noerr( err, CantCopyPasteboardItemFlavors );        flavorCount = CFArrayGetCount( flavorTypeArray );        for (CFIndex flavorIndex = 0; flavorIndex < flavorCount; flavorIndex++)        {            CFStringRef             flavorType;            CFDataRef               flavorData;            CFIndex                 flavorDataSize;            flavorType = (CFStringRef)CFArrayGetValueAtIndex(flavorTypeArray, flavorIndex);            // we're only interested by text...            if (UTTypeConformsTo(flavorType, CFSTR("public.utf8-plain-text")))            {                err = PasteboardCopyItemFlavorData( inPasteboard, itemID,                                                   flavorType, &flavorData );                require_noerr( err, CantCopyFlavorData );                flavorDataSize = CFDataGetLength( flavorData );                flavorDataSize = (flavorDataSize<254) ? flavorDataSize : 254;                if (flavorDataSize+2 > bufSize)                {                    fprintf(stderr, "Cannot copy clipboard, contents is too big!/n");                    return false;                }                for (short dataIndex = 0; dataIndex <= flavorDataSize; dataIndex++)                {                    char byte = *(CFDataGetBytePtr( flavorData ) + dataIndex);                    flavorText[dataIndex] = byte;                }                flavorText[flavorDataSize] = '/0';                flavorText[flavorDataSize+1] = '/n';                CFRelease (flavorData);                return true;            }            continue;            CantCopyFlavorData:   fprintf(stderr, "Cannot copy clipboard, CantCopyFlavorData!/n");        }        CFRelease (flavorTypeArray);        continue;    CantCopyPasteboardItemFlavors:   fprintf(stderr, "Cannot copy clipboard, CantCopyPasteboardItemFlavors!/n");   continue;    CantGetPasteboardItemIdentifier: fprintf(stderr, "Cannot copy clipboard, CantGetPasteboardItemIdentifier!/n"); continue;    }    fprintf(stderr, "Cannot copy clipboard, found no acceptable flavour!/n");    return false;    CantGetPasteboardItemCount:  fprintf(stderr, "Cannot copy clipboard, CantGetPasteboardItemCount!/n"); return false;    //PasteboardOutOfSync:         fprintf(stderr, "Cannot copy clipboard, PasteboardOutOfSync!/n");        return false;}
开发者ID:Arnaud474,项目名称:Warmux,代码行数:81,


示例14: HIDDumpDeviceInfo

//.........这里部分代码省略.........		printf( "	productID:	0x%04lX, ", productID );#else		if ( HIDGetProductNameFromVendorProductID( vendorID, productID, cstring ) ) {			printf( "	productID:	0x%04lX (/"%s/"), ", productID, cstring );		} else {			printf( "	productID:	0x%04lX, ", productID );		}#endif	}	uint32_t usagePage = IOHIDDevice_GetUsagePage( inIOHIDDeviceRef );	uint32_t usage = IOHIDDevice_GetUsage( inIOHIDDeviceRef );	if ( !usagePage || !usage ) {		usagePage = IOHIDDevice_GetPrimaryUsagePage( inIOHIDDeviceRef );		usage = IOHIDDevice_GetPrimaryUsage( inIOHIDDeviceRef );	}	printf( "usage: 0x%04lX:0x%04lX, ", (long unsigned int) usagePage, (long unsigned int) usage );#if 1	tCFStringRef = HIDCopyUsageName( usagePage, usage );	if ( tCFStringRef ) {		verify( CFStringGetCString( tCFStringRef, cstring, sizeof( cstring ), kCFStringEncodingUTF8 ) );		printf( "/"%s/", ", cstring );		CFRelease( tCFStringRef );	}#endif#if 1	tCFStringRef = IOHIDDevice_GetTransport( inIOHIDDeviceRef );	if ( tCFStringRef ) {		verify( CFStringGetCString( tCFStringRef, cstring, sizeof( cstring ), kCFStringEncodingUTF8 ) );		printf( "Transport: /"%s/", ", cstring );	}	long vendorIDSource = IOHIDDevice_GetVendorIDSource( inIOHIDDeviceRef );	if ( vendorIDSource ) {		printf( "VendorIDSource: %ld, ", vendorIDSource );	}	long version = IOHIDDevice_GetVersionNumber( inIOHIDDeviceRef );	if ( version ) {		printf( "version: %ld, ", version );	}	tCFStringRef = IOHIDDevice_GetSerialNumber( inIOHIDDeviceRef );	if ( tCFStringRef ) {		verify( CFStringGetCString( tCFStringRef, cstring, sizeof( cstring ), kCFStringEncodingUTF8 ) );		printf( "SerialNumber: /"%s/", ", cstring );	}	long country = IOHIDDevice_GetCountryCode( inIOHIDDeviceRef );	if ( country ) {		printf( "CountryCode: %ld, ", country );	}	long locationID = IOHIDDevice_GetLocationID( inIOHIDDeviceRef );	if ( locationID ) {		printf( "locationID: 0x%08lX, ", locationID );	}#if 0	CFArrayRef pairs = IOHIDDevice_GetUsagePairs( inIOHIDDeviceRef );	if ( pairs ) {		CFIndex idx, cnt = CFArrayGetCount(pairs);		for ( idx = 0; idx < cnt; idx++ ) {			const void * pair = CFArrayGetValueAtIndex(pairs, idx);			CFShow( pair );		}	}#endif	long maxInputReportSize = IOHIDDevice_GetMaxInputReportSize( inIOHIDDeviceRef );	if ( maxInputReportSize ) {		printf( "MaxInputReportSize: %ld, ", maxInputReportSize );	}	long maxOutputReportSize = IOHIDDevice_GetMaxOutputReportSize( inIOHIDDeviceRef );	if ( maxOutputReportSize ) {		printf( "MaxOutputReportSize: %ld, ", maxOutputReportSize );	}	long maxFeatureReportSize = IOHIDDevice_GetMaxFeatureReportSize( inIOHIDDeviceRef );	if ( maxFeatureReportSize ) {		printf( "MaxFeatureReportSize: %ld, ", maxOutputReportSize );	}	long reportInterval = IOHIDDevice_GetReportInterval( inIOHIDDeviceRef );	if ( reportInterval ) {		printf( "ReportInterval: %ld, ", reportInterval );	}	IOHIDQueueRef queueRef = IOHIDDevice_GetQueue( inIOHIDDeviceRef );	if ( queueRef ) {		printf( "queue: %p, ", queueRef);	}	IOHIDTransactionRef transactionRef = IOHIDDevice_GetTransaction( inIOHIDDeviceRef );	if ( transactionRef ) {		printf( "transaction: %p, ", transactionRef);	}#endif	printf( "}/n" );	fflush( stdout );}   // HIDDumpDeviceInfo
开发者ID:2mc,项目名称:supercollider,代码行数:101,


示例15: PasteboardCreate

char *osd_get_clipboard_text(void){	char *result = NULL; /* core expects a malloced C string of uft8 data */	PasteboardRef pasteboard_ref;	OSStatus err;	PasteboardSyncFlags sync_flags;	PasteboardItemID item_id;	CFIndex flavor_count;	CFArrayRef flavor_type_array;	CFIndex flavor_index;	ItemCount item_count;	UInt32 item_index;	Boolean	success = false;	err = PasteboardCreate(kPasteboardClipboard, &pasteboard_ref);	if (!err)	{		sync_flags = PasteboardSynchronize( pasteboard_ref );		err = PasteboardGetItemCount(pasteboard_ref, &item_count );		for (item_index=1; item_index<=item_count; item_index++)		{			err = PasteboardGetItemIdentifier(pasteboard_ref, item_index, &item_id);			if (!err)			{				err = PasteboardCopyItemFlavors(pasteboard_ref, item_id, &flavor_type_array);				if (!err)				{					flavor_count = CFArrayGetCount(flavor_type_array);					for (flavor_index = 0; flavor_index < flavor_count; flavor_index++)					{						CFStringRef flavor_type;						CFDataRef flavor_data;						CFStringEncoding encoding;						CFStringRef string_ref;						CFDataRef data_ref;						CFIndex length;						CFRange range;						flavor_type = (CFStringRef)CFArrayGetValueAtIndex(flavor_type_array, flavor_index);						if (UTTypeConformsTo (flavor_type, kUTTypeUTF16PlainText))							encoding = kCFStringEncodingUTF16;						else if (UTTypeConformsTo (flavor_type, kUTTypeUTF8PlainText))							encoding = kCFStringEncodingUTF8;						else if (UTTypeConformsTo (flavor_type, kUTTypePlainText))							encoding = kCFStringEncodingMacRoman;						else							continue;						err = PasteboardCopyItemFlavorData(pasteboard_ref, item_id, flavor_type, &flavor_data);						if( !err )						{							string_ref = CFStringCreateFromExternalRepresentation (kCFAllocatorDefault, flavor_data, encoding);							data_ref = CFStringCreateExternalRepresentation (kCFAllocatorDefault, string_ref, kCFStringEncodingUTF8, '?');							length = CFDataGetLength (data_ref);							range = CFRangeMake (0,length);							result = (char *)osd_malloc_array (length+1);							if (result != NULL)							{								CFDataGetBytes (data_ref, range, (unsigned char *)result);								result[length] = 0;								success = true;								break;							}							CFRelease(data_ref);							CFRelease(string_ref);							CFRelease(flavor_data);						}					}					CFRelease(flavor_type_array);				}			}			if (success)				break;		}		CFRelease(pasteboard_ref);	}	return result;}
开发者ID:LibXenonProject,项目名称:mame-lx,代码行数:94,


示例16: GetPreferredLanguages

// Because language preferences are set on a per-user basis, we// must get the preferred languages while set to the current // user, before the Apple Installer switches us to root.// So we get the preferred languages here and write them to a// temporary file to be retrieved by our PostInstall app.static void GetPreferredLanguages() {    DIR *dirp;    struct dirent *dp;    char searchPath[MAXPATHLEN];    char savedWD[MAXPATHLEN];    struct stat sbuf;    CFMutableArrayRef supportedLanguages;    CFStringRef aLanguage;    char shortLanguage[32];    CFArrayRef preferredLanguages;    int i, j, k;    char * language;    char *uscore;    FILE *f;    getcwd(savedWD, sizeof(savedWD));    system("rm -dfR /tmp/BOINC_payload");    mkdir("/tmp/BOINC_payload", 0777);    chdir("/tmp/BOINC_payload");    system("cpio -i < /tmp/expanded_BOINC.pkg/BOINC.pkg/Payload");    chdir(savedWD);    // Create an array of all our supported languages    supportedLanguages = CFArrayCreateMutable(kCFAllocatorDefault, 100, &kCFTypeArrayCallBacks);        aLanguage = CFStringCreateWithCString(NULL, "en", kCFStringEncodingMacRoman);    CFArrayAppendValue(supportedLanguages, aLanguage);    CFRelease(aLanguage);    aLanguage = NULL;    dirp = opendir(Catalogs_Dir);    if (!dirp) goto cleanup;    while (true) {        dp = readdir(dirp);        if (dp == NULL)            break;                  // End of list        if (dp->d_name[0] == '.')            continue;               // Ignore names beginning with '.'        strlcpy(searchPath, Catalogs_Dir, sizeof(searchPath));        strlcat(searchPath, dp->d_name, sizeof(searchPath));        strlcat(searchPath, "/", sizeof(searchPath));        strlcat(searchPath, Catalog_Name, sizeof(searchPath));        strlcat(searchPath, ".mo", sizeof(searchPath));        if (stat(searchPath, &sbuf) != 0) continue;//        printf("Adding %s to supportedLanguages array/n", dp->d_name);        aLanguage = CFStringCreateWithCString(NULL, dp->d_name, kCFStringEncodingMacRoman);        CFArrayAppendValue(supportedLanguages, aLanguage);        CFRelease(aLanguage);        aLanguage = NULL;                // If it has a region code ("it_IT") also try without region code ("it")        // TODO: Find a more general solution        strlcpy(shortLanguage, dp->d_name, sizeof(shortLanguage));        uscore = strchr(shortLanguage, '_');        if (uscore) {            *uscore = '/0';            aLanguage = CFStringCreateWithCString(NULL, shortLanguage, kCFStringEncodingMacRoman);            CFArrayAppendValue(supportedLanguages, aLanguage);            CFRelease(aLanguage);            aLanguage = NULL;        }    }        closedir(dirp);    // Write a temp file to tell our PostInstall.app our preferred languages    f = fopen("/tmp/BOINC_preferred_languages", "w");    for (i=0; i<MAX_LANGUAGES_TO_TRY; ++i) {            preferredLanguages = CFBundleCopyLocalizationsForPreferences(supportedLanguages, NULL );        #if 0   // For testing        int c = CFArrayGetCount(preferredLanguages);        for (k=0; k<c; ++k) {        CFStringRef s = (CFStringRef)CFArrayGetValueAtIndex(preferredLanguages, k);            printf("Preferred language %u is %s/n", k, CFStringGetCStringPtr(s, kCFStringEncodingMacRoman));        }#endif        for (j=0; j<CFArrayGetCount(preferredLanguages); ++j) {            aLanguage = (CFStringRef)CFArrayGetValueAtIndex(preferredLanguages, j);            language = (char *)CFStringGetCStringPtr(aLanguage, kCFStringEncodingMacRoman);            if (f) {                fprintf(f, "%s/n", language);            }                        // Remove all copies of this language from our list of supported languages             // so we can get the next preferred language in order of priority            for (k=CFArrayGetCount(supportedLanguages)-1; k>=0; --k) {                if (CFStringCompare(aLanguage, (CFStringRef)CFArrayGetValueAtIndex(supportedLanguages, k), 0) == kCFCompareEqualTo) {//.........这里部分代码省略.........
开发者ID:justinlynn,项目名称:boinc-v2,代码行数:101,


示例17: macosxSetScreenResolution

bool macosxSetScreenResolution(QSize resolution, QPoint screenPoint){	CGDirectDisplayID display = displayAtPoint(screenPoint);	if (display == kCGNullDirectDisplay)	{		return false;	}#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060	if (CGDisplayCopyAllDisplayModes != NULL)	{		bool ok = false;		CGDisplayModeRef currentMainDisplayMode = CGDisplayCopyDisplayMode(display);		CFStringRef currentPixelEncoding = CGDisplayModeCopyPixelEncoding(currentMainDisplayMode);		CFArrayRef displayModes = CGDisplayCopyAllDisplayModes(display, NULL);		for (CFIndex i = 0, c = CFArrayGetCount(displayModes); i < c; i++)		{			bool isEqual = false;			CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(displayModes, i);			CFStringRef pixelEncoding = CGDisplayModeCopyPixelEncoding(mode);			if (CFStringCompare(pixelEncoding, currentPixelEncoding, 0) == kCFCompareEqualTo			    && CGDisplayModeGetWidth(mode) == (size_t)resolution.width()			    && CGDisplayModeGetHeight(mode) == (size_t)resolution.height())			{				isEqual = true;			}			CFRelease(pixelEncoding);			if (isEqual)			{				CGDisplaySetDisplayMode(display, mode, NULL);				ok = true;				break;			}		}		CFRelease(currentPixelEncoding);		CFRelease(displayModes);		return ok;	}	else#endif	{		CFDictionaryRef currentMainDisplayMode = CGDisplayCurrentMode(display);		int bpp;		dictget(currentMainDisplayMode, Int, kCGDisplayBitsPerPixel, &bpp);		boolean_t exactMatch = false;		CFDictionaryRef bestMode = CGDisplayBestModeForParameters(display, bpp, resolution.width(), resolution.height(), &exactMatch);		if (bestMode != NULL)		{			if (!exactMatch)			{				qWarning("No optimal display mode for requested parameters.");			}			CGDisplaySwitchToMode(display, bestMode);			return true;		}		else		{			qWarning("Bad resolution change: Invalid display.");			return false;		}	}}
开发者ID:C1annad,项目名称:warzone2100,代码行数:63,


示例18: message

int wxFileDialog::ShowModal(){    m_paths.Empty();    m_fileNames.Empty();        OSErr err;    NavDialogCreationOptions dialogCreateOptions;    // set default options    ::NavGetDefaultDialogCreationOptions(&dialogCreateOptions);    // this was always unset in the old code    dialogCreateOptions.optionFlags &= ~kNavSelectDefaultLocation;    wxCFStringRef message(m_message, GetFont().GetEncoding());    dialogCreateOptions.windowTitle = message;    wxCFStringRef defaultFileName(m_fileName, GetFont().GetEncoding());    dialogCreateOptions.saveFileName = defaultFileName;    NavDialogRef dialog;    NavObjectFilterUPP navFilterUPP = NULL;    OpenUserDataRec myData( this );                dialogCreateOptions.popupExtension = myData.GetMenuItems();        if (HasFdFlag(wxFD_SAVE))    {        dialogCreateOptions.optionFlags |= kNavDontAutoTranslate;        dialogCreateOptions.optionFlags |= kNavDontAddTranslateItems;        if (dialogCreateOptions.popupExtension == NULL)            dialogCreateOptions.optionFlags |= kNavNoTypePopup;        // The extension is important        if ( dialogCreateOptions.popupExtension == NULL || CFArrayGetCount(dialogCreateOptions.popupExtension)<2)            dialogCreateOptions.optionFlags |= kNavPreserveSaveFileExtension;        if (!(m_windowStyle & wxFD_OVERWRITE_PROMPT))            dialogCreateOptions.optionFlags |= kNavDontConfirmReplacement;        err = ::NavCreatePutFileDialog(            &dialogCreateOptions,            kNavGenericSignature, // Suppresses the 'Default' (top) menu item            kNavGenericSignature,            sStandardNavEventFilter,            &myData, // for defaultLocation            &dialog );    }    else    {        // let the user select bundles/programs in dialogs        dialogCreateOptions.optionFlags |= kNavSupportPackages;        navFilterUPP = NewNavObjectFilterUPP(CrossPlatformFilterCallback);        err = ::NavCreateGetFileDialog(            &dialogCreateOptions,            NULL, // NavTypeListHandle            sStandardNavEventFilter,            NULL, // NavPreviewUPP            navFilterUPP,            (void *) &myData, // inClientData            &dialog );    }        SetupExtraControls(NavDialogGetWindow(dialog));        if (err == noErr)    {        wxDialog::OSXBeginModalDialog();        err = ::NavDialogRun(dialog);        wxDialog::OSXEndModalDialog();    }    // clean up filter related data, etc.    if (navFilterUPP)        ::DisposeNavObjectFilterUPP(navFilterUPP);    if (err != noErr)    {        ::NavDialogDispose(dialog);        return wxID_CANCEL;    }    NavReplyRecord navReply;    err = ::NavDialogGetReply(dialog, &navReply);    if (err == noErr && navReply.validRecord)    {        AEKeyword   theKeyword;        DescType    actualType;        Size        actualSize;        FSRef       theFSRef;        wxString thePath ;        long count;        m_filterIndex = myData.GetCurrentFilter();        ::AECountItems( &navReply.selection, &count );        for (long i = 1; i <= count; ++i)        {            err = ::AEGetNthPtr(                &(navReply.selection), i, typeFSRef, &theKeyword, &actualType,//.........这里部分代码省略.........
开发者ID:BloodRedd,项目名称:gamekit,代码行数:101,


示例19: macosxAppendAvailableScreenResolutions

bool macosxAppendAvailableScreenResolutions(QList<QSize> &resolutions, QSize minSize, QPoint screenPoint){	CGDirectDisplayID display = displayAtPoint(screenPoint);	if (display == kCGNullDirectDisplay)	{		return false;	}#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060	bool modern = (CGDisplayCopyAllDisplayModes != NULL); // where 'modern' means >= 10.6#endif	CFArrayRef displayModes;#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060	if (modern)	{		displayModes = CGDisplayCopyAllDisplayModes(display, NULL);	}	else#endif	{		displayModes = CGDisplayAvailableModes(display);	}#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060	CFStringRef currentPixelEncoding = NULL;#endif	double currentRefreshRate;	int curBPP, curBPS, curSPP;#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060	if (modern)	{		CGDisplayModeRef currentDisplayMode = CGDisplayCopyDisplayMode(display);		currentRefreshRate = CGDisplayModeGetRefreshRate(currentDisplayMode);		currentPixelEncoding = CGDisplayModeCopyPixelEncoding(currentDisplayMode);		CFRelease(currentDisplayMode);	}	else#endif	{		CFDictionaryRef currentDisplayMode = CGDisplayCurrentMode(display);		dictget(currentDisplayMode, Double, kCGDisplayRefreshRate, &currentRefreshRate);		dictget(currentDisplayMode, Int, kCGDisplayBitsPerPixel, &curBPP);		dictget(currentDisplayMode, Int, kCGDisplayBitsPerSample, &curBPS);		dictget(currentDisplayMode, Int, kCGDisplaySamplesPerPixel, &curSPP);	}	for (CFIndex j = 0, c = CFArrayGetCount(displayModes); j < c; j++)	{		int width, height;		double refreshRate;		bool pixelEncodingsEqual;#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060		if (modern)		{			CGDisplayModeRef displayMode = (CGDisplayModeRef)CFArrayGetValueAtIndex(displayModes, j);			width = (int)CGDisplayModeGetWidth(displayMode);			height = (int)CGDisplayModeGetHeight(displayMode);			refreshRate = CGDisplayModeGetRefreshRate(displayMode);			CFStringRef pixelEncoding = CGDisplayModeCopyPixelEncoding(displayMode);			pixelEncodingsEqual = (CFStringCompare(pixelEncoding, currentPixelEncoding, 0) == kCFCompareEqualTo);			CFRelease(pixelEncoding);		}		else#endif		{			CFDictionaryRef displayMode = (CFDictionaryRef)CFArrayGetValueAtIndex(displayModes, j);			dictget(displayMode, Int, kCGDisplayWidth, &width);			dictget(displayMode, Int, kCGDisplayHeight, &height);			dictget(displayMode, Double, kCGDisplayRefreshRate, &refreshRate);			int bpp, bps, spp;			dictget(displayMode, Int, kCGDisplayBitsPerPixel, &bpp);			dictget(displayMode, Int, kCGDisplayBitsPerSample, &bps);			dictget(displayMode, Int, kCGDisplaySamplesPerPixel, &spp);			pixelEncodingsEqual = (bpp == curBPP && bps == curBPS && spp == curSPP);		}		QSize res(width, height);		if (!resolutions.contains(res)		    && width >= minSize.width() && height >= minSize.height()		    && refreshRate == currentRefreshRate && pixelEncodingsEqual)		{			resolutions += res;		}	}#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060	if (modern)	{		CFRelease(currentPixelEncoding);		CFRelease(displayModes);	}#endif	return true;}
开发者ID:C1annad,项目名称:warzone2100,代码行数:98,


示例20: PrintCFTypeInternalFormat

//.........这里部分代码省略.........				Float32 number;				CFNumberGetValue(value, numberType, &number);				printf("%.f/n",number);				break;			};			case kCFNumberFloat64Type: {				Float64 number;				CFNumberGetValue(value, numberType, &number);				printf("%.f/n",number);				break;			};			case kCFNumberCharType: {				char number;				CFNumberGetValue(value, numberType, &number);				printf("%c/n",number);				break;			};			case kCFNumberShortType: {				short number;				CFNumberGetValue(value, numberType, &number);				printf("%hd/n",number);				break;			};			case kCFNumberIntType: {				int number;				CFNumberGetValue(value, numberType, &number);				printf("%d/n",number);				break;			};			case kCFNumberLongType: {				long number;				CFNumberGetValue(value, numberType, &number);				printf("%ld/n",number);				break;			};			case kCFNumberLongLongType: {				long long number;				CFNumberGetValue(value, numberType, &number);				printf("%qd/n",number);				break;			};			case kCFNumberFloatType: {				float number;				CFNumberGetValue(value, numberType, &number);				printf("%.f/n",number);				break;			};			case kCFNumberDoubleType: {				double number;				CFNumberGetValue(value, numberType, &number);				printf("%.f/n",number);				break;			};			case kCFNumberCFIndexType: {				CFIndex number;				CFNumberGetValue(value, numberType, &number);				printf("%ld/n",number);				break;			};			case kCFNumberNSIntegerType: {				NSInteger number;				CFNumberGetValue(value, numberType, &number);				printf("%ld/n",(long)number);				break;			};			case kCFNumberCGFloatType: {				CGFloat number;				CFNumberGetValue(value, numberType, &number);				printf("%.f/n",number);				break;			};			default: {				break;			};		}	}	CFSafeRelease(numberType);		CFStringRef arrayType = CFCopyTypeIDDescription(CFArrayGetTypeID());	if (CFStringCompare(valueType, arrayType, 0x0) == kCFCompareEqualTo) {		foundType = true;		CFIndex count = CFArrayGetCount(value);		printf("[/n");		for (CFIndex i = 0x0; i < count; i++) {			CFTypeRef item = CFArrayGetValueAtIndex(value, i);			PrintDepth(depth+0x1,"");			PrintCFTypeInternalFormat(item, depth+0x1);		}		PrintDepth(depth,"]/n");	}	CFSafeRelease(arrayType);		if (!foundType) {		CFStringRef description = CFCopyDescription(value);		printf("%s/n",(char*)CFStringGetCStringPtr(description,kCFStringEncodingUTF8));		CFSafeRelease(description);	}		CFSafeRelease(valueType);}
开发者ID:darling0825,项目名称:Core-Lib,代码行数:101,


示例21: LOG

void InbandTextTrackPrivateAVF::processCue(CFArrayRef attributedStrings, double time){    if (!client())        return;    LOG(Media, "InbandTextTrackPrivateAVF::processCue - %li cues at time %.2f/n", attributedStrings ? CFArrayGetCount(attributedStrings) : 0, time);    if (m_pendingCueStatus != None) {        // Cues do not have an explicit duration, they are displayed until the next "cue" (which might be empty) is emitted.        m_currentCueEndTime = time;        if (m_currentCueEndTime >= m_currentCueStartTime) {            for (size_t i = 0; i < m_cues.size(); i++) {                GenericCueData* cueData = m_cues[i].get();                if (m_pendingCueStatus == Valid) {                    cueData->setEndTime(m_currentCueEndTime);                    cueData->setStatus(GenericCueData::Complete);                    LOG(Media, "InbandTextTrackPrivateAVF::processCue(%p) - updating cue: start=%.2f, end=%.2f, content=/"%s/"", this, cueData->startTime(), m_currentCueEndTime, cueData->content().utf8().data());                    client()->updateGenericCue(this, cueData);                } else {                    // We have to assume that the implicit duration is invalid for cues delivered during a seek because the AVF decode pipeline may not                    // see every cue, so DO NOT update cue duration while seeking.                    LOG(Media, "InbandTextTrackPrivateAVF::processCue(%p) - ignoring cue delivered during seek: start=%.2f, end=%.2f, content=/"%s/"", this, cueData->startTime(), m_currentCueEndTime, cueData->content().utf8().data());                }            }        } else            LOG(Media, "InbandTextTrackPrivateAVF::processCue negative length cue(s) ignored: start=%.2f, end=%.2f/n", m_currentCueStartTime, m_currentCueEndTime);        resetCueValues();    }    if (!attributedStrings)        return;    CFIndex count = CFArrayGetCount(attributedStrings);    if (!count)        return;    for (CFIndex i = 0; i < count; i++) {        CFAttributedStringRef attributedString = static_cast<CFAttributedStringRef>(CFArrayGetValueAtIndex(attributedStrings, i));        if (!attributedString || !CFAttributedStringGetLength(attributedString))            continue;        RefPtr<GenericCueData> cueData = GenericCueData::create();        processCueAttributes(attributedString, cueData.get());        if (!cueData->content().length())            continue;        m_cues.append(cueData);        m_currentCueStartTime = time;        cueData->setStartTime(m_currentCueStartTime);        cueData->setEndTime(numeric_limits<double>::infinity());                // AVFoundation cue "position" is to the center of the text so adjust relative to the edge because we will use it to        // set CSS "left".        if (cueData->position() >= 0 && cueData->size() > 0)            cueData->setPosition(cueData->position() - cueData->size() / 2);                LOG(Media, "InbandTextTrackPrivateAVF::processCue(%p) - adding cue for time = %.2f, position =  %.2f, line =  %.2f", this, cueData->startTime(), cueData->position(), cueData->line());        cueData->setStatus(GenericCueData::Partial);        client()->addGenericCue(this, cueData.release());        m_pendingCueStatus = seeking() ? DeliveredDuringSeek : Valid;    }}
开发者ID:3163504123,项目名称:phantomjs,代码行数:70,


示例22: configSet

voidconfigSet(CFMutableArrayRef config, CFStringRef key, CFStringRef value){	CFMutableStringRef	pref;	CFIndex			configLen	= CFArrayGetCount(config);	CFIndex			i;	CFIndex			n;	CFMutableStringRef	newValue;	CFRange			range;	CFStringRef		specialChars	= CFSTR(" /"'$!|//<>`{}[]");	boolean_t		mustQuote	= FALSE;	/* create search prefix */	pref = CFStringCreateMutableCopy(NULL, 0, key);	CFStringAppend(pref, CFSTR("="));	/*	 * create new / replacement value	 *	 * Note: Since the configuration file may be processed by a	 *       shell script we need to ensure that, if needed, the	 *       string is properly quoted.	 */	newValue = CFStringCreateMutableCopy(NULL, 0, value);	n = CFStringGetLength(specialChars);	for (i = 0; i < n; i++) {		CFStringRef	specialChar;		specialChar = CFStringCreateWithSubstring(NULL, specialChars, CFRangeMake(i, 1));		range = CFStringFind(newValue, specialChar, 0);		CFRelease(specialChar);		if (range.location != kCFNotFound) {			/* this string has at least one special character */			mustQuote = TRUE;			break;		}	}	if (mustQuote) {		CFStringRef	charsToQuote	= CFSTR("///"$`");		/*		 * in addition to quoting the entire string we also need to escape the		 * space " " and backslash "/" characters		 */		n = CFStringGetLength(charsToQuote);		for (i = 0; i < n; i++) {			CFStringRef	quoteChar;			CFArrayRef	matches;			quoteChar = CFStringCreateWithSubstring(NULL, charsToQuote, CFRangeMake(i, 1));			range     = CFRangeMake(0, CFStringGetLength(newValue));			matches   = CFStringCreateArrayWithFindResults(NULL,								       newValue,								       quoteChar,								       range,								       0);			CFRelease(quoteChar);			if (matches) {				CFIndex	j = CFArrayGetCount(matches);				while (--j >= 0) {					const CFRange	*range;					range = CFArrayGetValueAtIndex(matches, j);					CFStringInsert(newValue, range->location, CFSTR("//"));				}				CFRelease(matches);			}		}		CFStringInsert(newValue, 0, CFSTR("/""));		CFStringAppend(newValue, CFSTR("/""));	}	/* locate existing key */	for (i = 0; i < configLen; i++) {		if (CFStringHasPrefix(CFArrayGetValueAtIndex(config, i), pref)) {			break;		}	}	CFStringAppend(pref, newValue);	CFRelease(newValue);	if (i < configLen) {		/* if replacing an existing entry */		CFArraySetValueAtIndex(config, i, pref);	} else {		/*		 * if new entry, insert it just prior to the last (emtpy)		 * array element.		 */		CFArrayInsertValueAtIndex(config, configLen-1, pref);	}	CFRelease(pref);	return;}
开发者ID:unofficial-opensource-apple,项目名称:configd_plugins,代码行数:100,


示例23: SecCmsSignedDataEncodeAfterData

/* * SecCmsSignedDataEncodeAfterData - do all the necessary things to a SignedData *     after all the encapsulated data was passed through the encoder. * * In detail: *  - create the signatures in all the SignerInfos * * Please note that nothing is done to the Certificates and CRLs in the message - this * is entirely the responsibility of our callers. */OSStatusSecCmsSignedDataEncodeAfterData(SecCmsSignedDataRef sigd){    SecCmsSignerInfoRef *signerinfos, signerinfo;    SecCmsContentInfoRef cinfo;    SECOidTag digestalgtag;    OSStatus ret = SECFailure;    OSStatus rv;    CSSM_DATA_PTR contentType;    int certcount;    int i, ci, n, rci, si;    PLArenaPool *poolp;    CFArrayRef certlist;    extern const SecAsn1Template SecCmsSignerInfoTemplate[];    poolp = sigd->cmsg->poolp;    cinfo = &(sigd->contentInfo);    /* did we have digest calculation going on? */    if (cinfo->digcx) {	rv = SecCmsDigestContextFinishMultiple(cinfo->digcx, (SecArenaPoolRef)poolp, &(sigd->digests));	if (rv != SECSuccess)	    goto loser;		/* error has been set by SecCmsDigestContextFinishMultiple */	cinfo->digcx = NULL;    }    signerinfos = sigd->signerInfos;    certcount = 0;    /* prepare all the SignerInfos (there may be none) */    for (i=0; i < SecCmsSignedDataSignerInfoCount(sigd); i++) {	signerinfo = SecCmsSignedDataGetSignerInfo(sigd, i);		/* find correct digest for this signerinfo */	digestalgtag = SecCmsSignerInfoGetDigestAlgTag(signerinfo);	n = SecCmsAlgArrayGetIndexByAlgTag(sigd->digestAlgorithms, digestalgtag);	if (n < 0 || sigd->digests == NULL || sigd->digests[n] == NULL) {	    /* oops - digest not found */	    PORT_SetError(SEC_ERROR_DIGEST_NOT_FOUND);	    goto loser;	}	/* XXX if our content is anything else but data, we need to force the	 * presence of signed attributes (RFC2630 5.3 "signedAttributes is a	 * collection...") */	/* pass contentType here as we want a contentType attribute */	if ((contentType = SecCmsContentInfoGetContentTypeOID(cinfo)) == NULL)	    goto loser;	/* sign the thing */	rv = SecCmsSignerInfoSign(signerinfo, sigd->digests[n], contentType);	if (rv != SECSuccess)	    goto loser;	/* while we're at it, count number of certs in certLists */	certlist = SecCmsSignerInfoGetCertList(signerinfo);	if (certlist)	    certcount += CFArrayGetCount(certlist);    }    /* Now we can get a timestamp, since we have all the digests */    // We force the setting of a callback, since this is the most usual case    if (!sigd->cmsg->tsaCallback)        SecCmsMessageSetTSACallback(sigd->cmsg, (SecCmsTSACallback)SecCmsTSADefaultCallback);            if (sigd->cmsg->tsaCallback && sigd->cmsg->tsaContext)    {        CSSM_DATA tsaResponse = {0,};        SecAsn1TSAMessageImprint messageImprint = {{{0},},{0,}};        // <rdar://problem/11073466> Add nonce support for timestamping client        uint64_t nonce = 0;        require_noerr(getRandomNonce(&nonce), tsxit);        dprintf("SecCmsSignedDataSignerInfoCount: %d/n", SecCmsSignedDataSignerInfoCount(sigd));        // Calculate hash of encDigest and put in messageImprint.hashedMessage        SecCmsSignerInfoRef signerinfo = SecCmsSignedDataGetSignerInfo(sigd, 0);    // NB - assume 1 signer only!        CSSM_DATA *encDigest = SecCmsSignerInfoGetEncDigest(signerinfo);        require_noerr(createTSAMessageImprint(sigd, encDigest, &messageImprint), tsxit);                // Callback to fire up XPC service to talk to TimeStamping server, etc.        require_noerr(rv =(*sigd->cmsg->tsaCallback)(sigd->cmsg->tsaContext, &messageImprint,                                                     nonce, &tsaResponse), tsxit);                require_noerr(rv = validateTSAResponseAndAddTimeStamp(signerinfo, &tsaResponse, nonce), tsxit);        /*//.........这里部分代码省略.........
开发者ID:alfintatorkace,项目名称:osx-10.9-opensource,代码行数:101,


示例24: _CFPreferencesCreateDomainList

__private_extern__ CFArrayRef  _CFPreferencesCreateDomainList(CFStringRef  userName, CFStringRef  hostName) {    CFAllocatorRef prefAlloc = __CFPreferencesAllocator();    CFArrayRef  domains;    CFMutableArrayRef  marray;    CFStringRef  *cachedDomainKeys;    CFPreferencesDomainRef *cachedDomains;    SInt32 idx, cnt;    CFStringRef  suffix;    UInt32 suffixLen;    CFURLRef prefDir = _preferencesDirectoryForUserHost(userName, hostName);        if (!prefDir) {        return NULL;    }    if (hostName == kCFPreferencesAnyHost) {        suffix = CFStringCreateWithCString(prefAlloc, ".plist", kCFStringEncodingASCII);    } else if (hostName == kCFPreferencesCurrentHost) {        CFStringRef hostID = _CFPreferencesGetByHostIdentifierString();        suffix = CFStringCreateWithFormat(prefAlloc, NULL, CFSTR(".%@.plist"), hostID);    } else {        suffix = CFStringCreateWithFormat(prefAlloc, NULL, CFSTR(".%@.plist"), hostName);   // sketchy - this allows someone to create a domain list for an arbitrary hostname.    }    suffixLen = CFStringGetLength(suffix);        domains = (CFArrayRef)CFURLCreatePropertyFromResource(prefAlloc, prefDir, kCFURLFileDirectoryContents, NULL);    CFRelease(prefDir);    if (domains){        marray = CFArrayCreateMutableCopy(prefAlloc, 0, domains);        CFRelease(domains);    } else {        marray = CFArrayCreateMutable(prefAlloc, 0, & kCFTypeArrayCallBacks);    }    for (idx = CFArrayGetCount(marray)-1; idx >= 0; idx --) {        CFURLRef  url = (CFURLRef)CFArrayGetValueAtIndex(marray, idx);        CFStringRef string = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);        if (!CFStringHasSuffix(string, suffix)) {            CFArrayRemoveValueAtIndex(marray, idx);        } else {            CFStringRef  dom = CFStringCreateWithSubstring(prefAlloc, string, CFRangeMake(0, CFStringGetLength(string) - suffixLen));            if (CFEqual(dom, CFSTR(".GlobalPreferences"))) {                CFArraySetValueAtIndex(marray, idx, kCFPreferencesAnyApplication);            } else {                CFArraySetValueAtIndex(marray, idx, dom);            }            CFRelease(dom);        }        CFRelease(string);    }    CFRelease(suffix);        // Now add any domains added in the cache; delete any that have been deleted in the cache    __CFSpinLock(&domainCacheLock);    if (!domainCache) {        __CFSpinUnlock(&domainCacheLock);        return marray;    }    cnt = CFDictionaryGetCount(domainCache);    cachedDomainKeys = (CFStringRef *)CFAllocatorAllocate(prefAlloc, 2 * cnt * sizeof(CFStringRef), 0);    cachedDomains = (CFPreferencesDomainRef *)(cachedDomainKeys + cnt);    CFDictionaryGetKeysAndValues(domainCache, (const void **)cachedDomainKeys, (const void **)cachedDomains);    __CFSpinUnlock(&domainCacheLock);    suffix = _CFPreferencesCachePrefixForUserHost(userName, hostName);    suffixLen = CFStringGetLength(suffix);        for (idx = 0; idx < cnt; idx ++) {        CFStringRef  domainKey = cachedDomainKeys[idx];        CFPreferencesDomainRef domain = cachedDomains[idx];        CFStringRef  domainName;        CFIndex keyCount = 0;                if (!CFStringHasPrefix(domainKey, suffix)) continue;        domainName = CFStringCreateWithSubstring(prefAlloc, domainKey, CFRangeMake(suffixLen, CFStringGetLength(domainKey) - suffixLen));        if (CFEqual(domainName, CFSTR("*"))) {            CFRelease(domainName);            domainName = (CFStringRef)CFRetain(kCFPreferencesAnyApplication);        } else if (CFEqual(domainName, kCFPreferencesCurrentApplication)) {            CFRelease(domainName);            domainName = (CFStringRef)CFRetain(_CFProcessNameString());        }        CFDictionaryRef d = _CFPreferencesDomainDeepCopyDictionary(domain);        keyCount = d ? CFDictionaryGetCount(d) : 0;        if (keyCount) CFRelease(d);        if (keyCount == 0) {            // Domain was deleted            SInt32 firstIndexOfValue = CFArrayGetFirstIndexOfValue(marray, CFRangeMake(0, CFArrayGetCount(marray)), domainName);            if (0 <= firstIndexOfValue) {                CFArrayRemoveValueAtIndex(marray, firstIndexOfValue);            }        } else if (!CFArrayContainsValue(marray, CFRangeMake(0, CFArrayGetCount(marray)), domainName)) {            CFArrayAppendValue(marray, domainName);        }        CFRelease(domainName);    }    CFRelease(suffix);    CFAllocatorDeallocate(prefAlloc, cachedDomainKeys);    return marray;}
开发者ID:Apple-FOSS-Mirror,项目名称:CF,代码行数:97,


示例25: HIDGetFirstDeviceElement

// get the first element of device passed in as parameter// returns NULL if no list exists or device does not exists or is NULLIOHIDElementRef HIDGetFirstDeviceElement( IOHIDDeviceRef inIOHIDDeviceRef, HIDElementTypeMask typeMask ){	IOHIDElementRef result = NULL;	if ( inIOHIDDeviceRef ) {		assert( IOHIDDeviceGetTypeID() == CFGetTypeID( inIOHIDDeviceRef ) );		gElementCFArrayRef = IOHIDDeviceCopyMatchingElements( inIOHIDDeviceRef, NULL, kIOHIDOptionsTypeNone );		if ( gElementCFArrayRef ) {			CFIndex idx, cnt = CFArrayGetCount( gElementCFArrayRef );			for ( idx = 0; idx < cnt; idx++ ) {				IOHIDElementRef tIOHIDElementRef = ( IOHIDElementRef ) CFArrayGetValueAtIndex( gElementCFArrayRef, idx );				if ( !tIOHIDElementRef ) {					continue;				}				IOHIDElementType type = IOHIDElementGetType( tIOHIDElementRef );				switch ( type ) {					case kIOHIDElementTypeInput_Misc:					case kIOHIDElementTypeInput_Button:					case kIOHIDElementTypeInput_Axis:					case kIOHIDElementTypeInput_ScanCodes:					{						if ( typeMask & kHIDElementTypeInput ) {							result = tIOHIDElementRef;						}						break;					}					case kIOHIDElementTypeOutput:					{						if ( typeMask & kHIDElementTypeOutput ) {							result = tIOHIDElementRef;						}						break;					}					case kIOHIDElementTypeFeature:					{						if ( typeMask & kHIDElementTypeFeature ) {							result = tIOHIDElementRef;						}						break;					}					case kIOHIDElementTypeCollection:					{						if ( typeMask & kHIDElementTypeCollection ) {							result = tIOHIDElementRef;						}						break;					}				}           // switch ( type )				if ( result ) {					break;  // DONE!				}			}               // next idx			CFRelease( gElementCFArrayRef );			gElementCFArrayRef = NULL;		}                   // 		if ( gElementCFArrayRef )	}                       // 	if ( inIOHIDDeviceRef )	return result;} /* HIDGetFirstDeviceElement */
开发者ID:2mc,项目名称:supercollider,代码行数:68,


示例26: _mongoc_secure_transport_RFC2253_from_cert

char *_mongoc_secure_transport_RFC2253_from_cert (SecCertificateRef cert){   CFTypeRef value;   bson_string_t *retval;   CFTypeRef subject_name;   CFDictionaryRef cert_dict;   cert_dict = SecCertificateCopyValues (cert, NULL, NULL);   if (!cert_dict) {      return NULL;   }   subject_name = CFDictionaryGetValue (cert_dict, kSecOIDX509V1SubjectName);   if (!subject_name) {      CFRelease (cert_dict);      return NULL;   }   subject_name = CFDictionaryGetValue (subject_name, kSecPropertyKeyValue);   if (!subject_name) {      CFRelease (cert_dict);      return NULL;   }   retval = bson_string_new ("");   ;   value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDCountryName);   _bson_append_cftyperef (retval, "C=", value);   value = _mongoc_secure_transport_dict_get (subject_name,                                              kSecOIDStateProvinceName);   _bson_append_cftyperef (retval, ",ST=", value);   value =      _mongoc_secure_transport_dict_get (subject_name, kSecOIDLocalityName);   _bson_append_cftyperef (retval, ",L=", value);   value =      _mongoc_secure_transport_dict_get (subject_name, kSecOIDOrganizationName);   _bson_append_cftyperef (retval, ",O=", value);   value = _mongoc_secure_transport_dict_get (subject_name,                                              kSecOIDOrganizationalUnitName);   if (value) {      /* Can be either one unit name, or array of unit names */      if (CFGetTypeID (value) == CFStringGetTypeID ()) {         _bson_append_cftyperef (retval, ",OU=", value);      } else if (CFGetTypeID (value) == CFArrayGetTypeID ()) {         CFIndex len = CFArrayGetCount (value);         if (len > 0) {            _bson_append_cftyperef (               retval, ",OU=", CFArrayGetValueAtIndex (value, 0));         }         if (len > 1) {            _bson_append_cftyperef (               retval, ",", CFArrayGetValueAtIndex (value, 1));         }         if (len > 2) {            _bson_append_cftyperef (               retval, ",", CFArrayGetValueAtIndex (value, 2));         }      }   }   value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDCommonName);   _bson_append_cftyperef (retval, ",CN=", value);   value =      _mongoc_secure_transport_dict_get (subject_name, kSecOIDStreetAddress);   _bson_append_cftyperef (retval, ",STREET", value);   CFRelease (cert_dict);   return bson_string_free (retval, false);}
开发者ID:cran,项目名称:mongolite,代码行数:77,


示例27: HIDGetNextDeviceElement

// get next element of given device in list given current element as parameter// will walk down each collection then to next element or collection (depthwise traverse)// returns NULL if end of list// uses mask of HIDElementTypeMask to restrict element found// use kHIDElementTypeIO to get previous HIDGetNextDeviceElement functionalityIOHIDElementRef HIDGetNextDeviceElement( IOHIDElementRef inIOHIDElementRef, HIDElementTypeMask typeMask ){	IOHIDElementRef result = NULL;	if ( inIOHIDElementRef ) {		assert( IOHIDElementGetTypeID() == CFGetTypeID( inIOHIDElementRef ) );		IOHIDDeviceRef tIOHIDDeviceRef = IOHIDElementGetDevice( inIOHIDElementRef );		if ( tIOHIDDeviceRef ) {			Boolean found = FALSE;			gElementCFArrayRef = IOHIDDeviceCopyMatchingElements( tIOHIDDeviceRef, NULL, kIOHIDOptionsTypeNone );			if ( gElementCFArrayRef ) {				CFIndex idx, cnt = CFArrayGetCount( gElementCFArrayRef );				for ( idx = 0; idx < cnt; idx++ ) {					IOHIDElementRef tIOHIDElementRef = ( IOHIDElementRef ) CFArrayGetValueAtIndex( gElementCFArrayRef, idx );					if ( !tIOHIDElementRef ) {						continue;					}					if ( !found ) {						if ( inIOHIDElementRef == tIOHIDElementRef ) {							found = TRUE;						}						continue;   // next element					} else {						// we've found the current element; now find the next one of the right type						IOHIDElementType type = IOHIDElementGetType( tIOHIDElementRef );						switch ( type ) {							case kIOHIDElementTypeInput_Misc:							case kIOHIDElementTypeInput_Button:							case kIOHIDElementTypeInput_Axis:							case kIOHIDElementTypeInput_ScanCodes:							{								if ( typeMask & kHIDElementTypeInput ) {									result = tIOHIDElementRef;								}								break;							}							case kIOHIDElementTypeOutput:							{								if ( typeMask & kHIDElementTypeOutput ) {									result = tIOHIDElementRef;								}								break;							}							case kIOHIDElementTypeFeature:							{								if ( typeMask & kHIDElementTypeFeature ) {									result = tIOHIDElementRef;								}								break;							}							case kIOHIDElementTypeCollection:							{								if ( typeMask & kHIDElementTypeCollection ) {									result = tIOHIDElementRef;								}								break;							}						}           // switch ( type )						if ( result ) {							break;  // DONE!						}					}               // if ( !found )				}                   // next idx				CFRelease( gElementCFArrayRef );				gElementCFArrayRef = NULL;			}                       // 		if ( gElementCFArrayRef )		}                           // 	if ( inIOHIDDeviceRef )	}                               // 	if ( inIOHIDElementRef )	return result;} /* HIDGetNextDeviceElement */
开发者ID:2mc,项目名称:supercollider,代码行数:85,


示例28: keychain_iter_start

static intkeychain_iter_start(hx509_context context,		    hx509_certs certs, void *data, void **cursor){    struct ks_keychain *ctx = data;    struct iter *iter;    iter = calloc(1, sizeof(*iter));    if (iter == NULL) {	hx509_set_error_string(context, 0, ENOMEM, "out of memory");	return ENOMEM;    }    if (ctx->anchors) {        CFArrayRef anchors;	int ret;	int i;	ret = hx509_certs_init(context, "MEMORY:ks-file-create",			       0, NULL, &iter->certs);	if (ret) {	    free(iter);	    return ret;	}	ret = SecTrustCopyAnchorCertificates(&anchors);	if (ret != 0) {	    hx509_certs_free(&iter->certs);	    free(iter);	    hx509_set_error_string(context, 0, ENOMEM,				   "Can't get trust anchors from Keychain");	    return ENOMEM;	}	for (i = 0; i < CFArrayGetCount(anchors); i++) {	    SecCertificateRef cr;	    hx509_cert cert;	    CSSM_DATA cssm;	    cr = (SecCertificateRef)CFArrayGetValueAtIndex(anchors, i);	    SecCertificateGetData(cr, &cssm);	    ret = hx509_cert_init_data(context, cssm.Data, cssm.Length, &cert);	    if (ret)		continue;	    ret = hx509_certs_add(context, iter->certs, cert);	    hx509_cert_free(cert);	}	CFRelease(anchors);    }    if (iter->certs) {	int ret;	ret = hx509_certs_start_seq(context, iter->certs, &iter->cursor);	if (ret) {	    hx509_certs_free(&iter->certs);	    free(iter);	    return ret;	}    } else {	OSStatus ret;	ret = SecKeychainSearchCreateFromAttributes(ctx->keychain,						    kSecCertificateItemClass,						    NULL,						    &iter->searchRef);	if (ret) {	    free(iter);	    hx509_set_error_string(context, 0, ret,				   "Failed to start search for attributes");	    return ENOMEM;	}    }    *cursor = iter;    return 0;}
开发者ID:0x24bin,项目名称:winexe-1,代码行数:78,


示例29: AddHIDElements

/* Call AddHIDElement() on all elements in an array of IOHIDElementRefs */static voidAddHIDElements(CFArrayRef array, recDevice *pDevice){    const CFRange range = { 0, CFArrayGetCount(array) };    CFArrayApplyFunction(array, range, AddHIDElement, pDevice);}
开发者ID:Helios-vmg,项目名称:CopperRat,代码行数:7,



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


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