int odkerb_get_im_handle(char *service_principal_id, char *realm, char *im_type, char im_handle[], size_t im_handle_size) { int retval = -1; int is_cross_realm; CFStringRef cfAllegedShortName = NULL; CFStringRef cfRealm = NULL; CFStringRef cfPrincipalID = NULL; ODRecordRef cfUserRecord = NULL; CFStringRef cfConfigRecordName = NULL; ODNodeRef cfSearchNode = NULL; CFStringRef cfIMType = NULL; ODKERB_PARAM_ASSERT(service_principal_id != 0); ODKERB_PARAM_ASSERT(realm != 0); ODKERB_PARAM_ASSERT(im_type != 0); ODKERB_PARAM_ASSERT(im_handle != 0); ODKERB_PARAM_ASSERT(im_handle_size > 0); *im_handle = '\0'; /* configure the short name and realm first because they may be used * in the failure handler to fabricate the IM handle */ cfAllegedShortName = odkerb_create_short_name(service_principal_id); if (cfAllegedShortName == NULL) { ODKERB_LOG_ERRNO(LOG_ERR, ENOMEM); goto failure; } cfRealm = CFStringCreateWithCString(kCFAllocatorDefault, realm, kCFStringEncodingUTF8); if (cfRealm == NULL) { ODKERB_LOG_ERRNO(LOG_ERR, ENOMEM); goto failure; } is_cross_realm = odkerb_has_foreign_realm(service_principal_id); if (is_cross_realm) { cfPrincipalID = odkerb_create_alleged_principal_id(service_principal_id); } else { cfPrincipalID = CFStringCreateWithCString(kCFAllocatorDefault, service_principal_id, kCFStringEncodingUTF8); if (cfPrincipalID == 0) ODKERB_LOG_ERRNO(LOG_ERR, ENOMEM); } if (cfPrincipalID == 0) goto failure; if (odkerb_copy_user_record_with_alt_security_identity(cfPrincipalID, &cfUserRecord) != 0) { cfConfigRecordName = odkerb_create_config_record_name(cfPrincipalID); if (odkerb_copy_search_node_with_config_record_name(cfConfigRecordName, &cfSearchNode) != 0) goto failure; if (odkerb_copy_user_record_with_short_name(cfAllegedShortName, cfSearchNode, &cfUserRecord) != 0) goto failure; } cfIMType = CFStringCreateWithCString(kCFAllocatorDefault, im_type, kCFStringEncodingUTF8); if (cfIMType == NULL) { ODKERB_LOG_ERRNO(LOG_ERR, ENOMEM); goto failure; } if (odkerb_get_im_handle_with_user_record(cfUserRecord, cfIMType, cfRealm, cfAllegedShortName, im_handle, im_handle_size) != 0) goto failure; retval = 0; failure: if (retval != 0) { if (is_cross_realm) { ODKERB_LOG_CFSTRING(LOG_WARNING, "Unable to construct IM handle for cross-realm user", cfPrincipalID); } else { if (odkerb_get_fabricated_im_handle(cfUserRecord, cfAllegedShortName, cfRealm, im_handle, im_handle_size) == 0) retval = 0; } } CF_SAFE_RELEASE(cfIMType); CF_SAFE_RELEASE(cfUserRecord); CF_SAFE_RELEASE(cfSearchNode); CF_SAFE_RELEASE(cfConfigRecordName); CF_SAFE_RELEASE(cfPrincipalID); CF_SAFE_RELEASE(cfRealm); CF_SAFE_RELEASE(cfAllegedShortName); return retval; }
void CAAUParameter::Init (AudioUnit au, AudioUnitParameterID param, AudioUnitScope scope, AudioUnitElement element) { mAudioUnit = au; mParameterID = param; mScope = scope; mElement = element; UInt32 propertySize = sizeof(mParamInfo); OSStatus err = AudioUnitGetProperty(au, kAudioUnitProperty_ParameterInfo, scope, param, &mParamInfo, &propertySize); if (err) memset(&mParamInfo, 0, sizeof(mParamInfo)); if (mParamInfo.flags & kAudioUnitParameterFlag_HasCFNameString) { mParamName = mParamInfo.cfNameString; if (!(mParamInfo.flags & kAudioUnitParameterFlag_CFNameRelease)) CFRetain (mParamName); } else mParamName = CFStringCreateWithCString(NULL, mParamInfo.name, kCFStringEncodingUTF8); char* str = 0; switch (mParamInfo.unit) { case kAudioUnitParameterUnit_Boolean: str = "T/F"; break; case kAudioUnitParameterUnit_Percent: case kAudioUnitParameterUnit_EqualPowerCrossfade: str = "%"; break; case kAudioUnitParameterUnit_Seconds: str = "Secs"; break; case kAudioUnitParameterUnit_SampleFrames: str = "Samps"; break; case kAudioUnitParameterUnit_Phase: case kAudioUnitParameterUnit_Degrees: str = "Degr."; break; case kAudioUnitParameterUnit_Hertz: str = "Hz"; break; case kAudioUnitParameterUnit_Cents: case kAudioUnitParameterUnit_AbsoluteCents: str = "Cents"; break; case kAudioUnitParameterUnit_RelativeSemiTones: str = "S-T"; break; case kAudioUnitParameterUnit_MIDINoteNumber: case kAudioUnitParameterUnit_MIDIController: str = "MIDI"; //these are inclusive, so add one value here mNumIndexedParams = short(mParamInfo.maxValue+1 - mParamInfo.minValue); break; case kAudioUnitParameterUnit_Decibels: str = "dB"; break; case kAudioUnitParameterUnit_MixerFaderCurve1: case kAudioUnitParameterUnit_LinearGain: str = "Gain"; break; case kAudioUnitParameterUnit_Pan: str = "L/R"; break; case kAudioUnitParameterUnit_Meters: str = "Mtrs"; break; case kAudioUnitParameterUnit_Octaves: str = "8ve"; break; case kAudioUnitParameterUnit_BPM: str = "BPM"; break; case kAudioUnitParameterUnit_Beats: str = "Beats"; break; case kAudioUnitParameterUnit_Milliseconds: str = "msecs"; break; case kAudioUnitParameterUnit_Ratio: str = "Ratio"; break; case kAudioUnitParameterUnit_Indexed: { propertySize = sizeof(mNamedParams); err = AudioUnitGetProperty (au, kAudioUnitProperty_ParameterValueStrings, scope, param, &mNamedParams, &propertySize); if (!err && mNamedParams) { mNumIndexedParams = CFArrayGetCount(mNamedParams); } else { //these are inclusive, so add one value here mNumIndexedParams = short(mParamInfo.maxValue+1 - mParamInfo.minValue); } str = NULL; } break; case kAudioUnitParameterUnit_CustomUnit: { CFStringRef unitName = mParamInfo.unitName; static char paramStr[256]; CFStringGetCString (unitName, paramStr, 256, kCFStringEncodingUTF8); if (mParamInfo.flags & kAudioUnitParameterFlag_CFNameRelease) CFRelease (unitName); str = paramStr; break; } case kAudioUnitParameterUnit_Generic: case kAudioUnitParameterUnit_Rate: default: str = NULL; break; } if (str) mParamTag = CFStringCreateWithCString(NULL, str, kCFStringEncodingUTF8); else mParamTag = NULL; }
const char * /* O - Localized message */ _cupsMessageLookup(cups_array_t *a, /* I - Message array */ const char *m) /* I - Message */ { _cups_message_t key, /* Search key */ *match; /* Matching message */ /* * Lookup the message string; if it doesn't exist in the catalog, * then return the message that was passed to us... */ key.id = (char *)m; match = (_cups_message_t *)cupsArrayFind(a, &key); #if defined(__APPLE__) && defined(CUPS_BUNDLEDIR) if (!match && cupsArrayUserData(a)) { /* * Try looking the string up in the cups.strings dictionary... */ CFDictionaryRef dict; /* cups.strings dictionary */ CFStringRef cfm, /* Message as a CF string */ cfstr; /* Localized text as a CF string */ dict = (CFDictionaryRef)cupsArrayUserData(a); cfm = CFStringCreateWithCString(kCFAllocatorDefault, m, kCFStringEncodingUTF8); match = calloc(1, sizeof(_cups_message_t)); match->id = strdup(m); cfstr = cfm ? CFDictionaryGetValue(dict, cfm) : NULL; if (cfstr) { char buffer[1024]; /* Message buffer */ CFStringGetCString(cfstr, buffer, sizeof(buffer), kCFStringEncodingUTF8); match->str = strdup(buffer); DEBUG_printf(("1_cupsMessageLookup: Found \"%s\" as \"%s\"...", m, buffer)); } else { match->str = strdup(m); DEBUG_printf(("1_cupsMessageLookup: Did not find \"%s\"...", m)); } cupsArrayAdd(a, match); if (cfm) CFRelease(cfm); } #endif /* __APPLE__ && CUPS_BUNDLEDIR */ if (match && match->str) return (match->str); else return (m); }
int main (int argc, const char * argv[]) { if(argc >= 2) { CGPDFDocumentRef doc = CGPDFDocumentCreateWithProvider(CGDataProviderCreateWithFilename(argv[1])); size_t pages = CGPDFDocumentGetNumberOfPages(doc); printf("%lu pages\n", pages); for(size_t i = 1; i <= pages; i++) { char filename[1024]; snprintf(filename, 1024, "%s.%03lu.png", argv[1], i); printf("writing file: %s\n", filename); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, SIZE, SIZE, 8, 4 * SIZE, colorSpace, kCGImageAlphaPremultipliedLast); CGColorSpaceRelease(colorSpace); CGContextDrawPDFDocument(context, CGRectMake(0, 0, SIZE, SIZE), doc, (int)i); CGImageRef image = CGBitmapContextCreateImage(context); CGImageDestinationRef dest = CGImageDestinationCreateWithURL(CFURLCreateWithFileSystemPath(kCFAllocatorDefault, CFStringCreateWithCString(kCFAllocatorDefault, filename, kCFStringEncodingASCII), kCFURLPOSIXPathStyle, false), kUTTypePNG, 1, NULL); CGImageDestinationAddImage(dest, image, NULL); CGImageDestinationFinalize(dest); CGImageRelease(image); CGContextRelease(context); } CGPDFDocumentRelease(doc); } else { printf("pdf2png [filename]\n"); return 1; } return 0; }
OSStatus FSGetCatalogInfo(const FSRef* ref, uint32_t infoBits, FSCatalogInfo* infoOut, HFSUniStr255* nameOut, FSSpecPtr fsspec, FSRef* parentDir) { std::string path; if (!FSRefMakePath(ref, path)) return fnfErr; if (nameOut) { CFStringRef cfstr = CFStringCreateWithCString(NULL, path.c_str(), kCFStringEncodingUTF8); nameOut->length = std::min<size_t>(path.length(), 255); CFStringGetCharacters(cfstr, CFRangeMake(0, nameOut->length), nameOut->unicode); CFRelease(cfstr); } if (parentDir) { memcpy(parentDir, ref, sizeof(FSRef)); ino_t* last = std::find(parentDir->inodes, parentDir->inodes+FSRef_MAX_DEPTH, 0); if (last != parentDir->inodes) *(last-1) = 0; } if (infoOut && infoBits != kFSCatInfoNone) { struct stat st; memset(infoOut, 0, sizeof(*infoOut)); if (::stat(path.c_str(), &st) != 0) return makeOSStatus(errno); if (infoBits & kFSCatInfoNodeFlags) { if (S_ISDIR(st.st_mode)) infoOut->nodeFlags = 4; } if (infoBits & (kFSCatInfoParentDirID|kFSCatInfoNodeID)) { if (infoBits & kFSCatInfoNodeID) infoOut->nodeID = ref->inodes[0]; for (int i = FSRef_MAX_DEPTH-1; i > 0; i--) { if (ref->inodes[i] == 0) continue; if (infoBits & kFSCatInfoParentDirID) infoOut->parentDirID = ref->inodes[i-1]; if (infoBits & kFSCatInfoNodeID) infoOut->nodeID = ref->inodes[i]; } } if (infoBits & kFSCatInfoDataSizes) { infoOut->dataLogicalSize = st.st_size; infoOut->dataPhysicalSize = st.st_blocks*512; } int uaccess; if (st.st_uid == getuid()) uaccess = st.st_mode & 0700; else if (hasgid(st.st_gid)) uaccess = st.st_mode & 070; else uaccess = st.st_mode & 07; if (infoBits & kFSCatInfoPermissions) { const uid_t uid = getuid(); infoOut->fsPermissionInfo.userID = st.st_uid; infoOut->fsPermissionInfo.groupID = st.st_gid; infoOut->fsPermissionInfo.mode = st.st_mode & 07777; infoOut->fsPermissionInfo.userAccess = uaccess; } if (infoBits & kFSCatInfoUserPrivs) { if (!(uaccess & 2)) infoOut->userPrivileges |= 0x4; // kioACUserNoMakeChangesMask if (getuid() != st.st_uid) infoOut->userPrivileges |= 0x80; // kioACUserNotOwnerMask } if (infoBits & kFSCatInfoCreateDate) infoOut->createDate = Darling::time_tToUTC(st.st_ctime); if (infoBits & kFSCatInfoContentMod) infoOut->attributeModDate = infoOut->contentModDate = Darling::time_tToUTC(st.st_mtime); if (infoBits & kFSCatInfoAccessDate) infoOut->accessDate = Darling::time_tToUTC(st.st_atime); } return noErr; }
static cairo_status_t _cairo_quartz_font_create_toy(cairo_toy_font_face_t *toy_face, const cairo_matrix_t *font_matrix, const cairo_matrix_t *ctm, const cairo_font_options_t *options, cairo_scaled_font_t **font_out) { const char *family = toy_face->family; char *full_name = malloc(strlen(family) + 64); // give us a bit of room to tack on Bold, Oblique, etc. CFStringRef cgFontName = NULL; CGFontRef cgFont = NULL; int loop; cairo_status_t status; cairo_font_face_t *face; cairo_scaled_font_t *scaled_font; quartz_font_ensure_symbols(); if (!_cairo_quartz_font_symbols_present) return _cairo_error (CAIRO_STATUS_NO_MEMORY); /* handle CSS-ish faces */ if (!strcmp(family, "serif") || !strcmp(family, "Times Roman")) family = "Times"; else if (!strcmp(family, "sans-serif") || !strcmp(family, "sans")) family = "Helvetica"; else if (!strcmp(family, "cursive")) family = "Apple Chancery"; else if (!strcmp(family, "fantasy")) family = "Papyrus"; else if (!strcmp(family, "monospace") || !strcmp(family, "mono")) family = "Courier"; /* Try to build up the full name, e.g. "Helvetica Bold Oblique" first, * then drop the bold, then drop the slant, then drop both.. finally * just use "Helvetica". And if Helvetica doesn't exist, give up. */ for (loop = 0; loop < 5; loop++) { if (loop == 4) family = "Helvetica"; strcpy (full_name, family); if (loop < 3 && (loop & 1) == 0) { if (toy_face->weight == CAIRO_FONT_WEIGHT_BOLD) strcat (full_name, " Bold"); } if (loop < 3 && (loop & 2) == 0) { if (toy_face->slant == CAIRO_FONT_SLANT_ITALIC) strcat (full_name, " Italic"); else if (toy_face->slant == CAIRO_FONT_SLANT_OBLIQUE) strcat (full_name, " Oblique"); } if (CGFontCreateWithFontNamePtr) { cgFontName = CFStringCreateWithCString (NULL, full_name, kCFStringEncodingASCII); cgFont = CGFontCreateWithFontNamePtr (cgFontName); CFRelease (cgFontName); } else { cgFont = CGFontCreateWithNamePtr (full_name); } if (cgFont) break; } if (!cgFont) { /* Give up */ return CAIRO_STATUS_NO_MEMORY; } face = cairo_quartz_font_face_create_for_cgfont (cgFont); CGFontRelease (cgFont); if (face->status) return face->status; status = _cairo_quartz_font_face_scaled_font_create (face, font_matrix, ctm, options, &scaled_font); cairo_font_face_destroy (face); if (status) return status; *font_out = scaled_font; return CAIRO_STATUS_SUCCESS; }
int main(int argc, char* argv[]) { const char *scriptPath = "testapi.js"; if (argc > 1) { scriptPath = argv[1]; } // Test garbage collection with a fresh context context = JSGlobalContextCreate(NULL); TestInitializeFinalize = true; testInitializeFinalize(); JSGlobalContextRelease(context); JSGarbageCollect(context); TestInitializeFinalize = false; ASSERT(Base_didFinalize); JSClassDefinition globalObjectClassDefinition = kJSClassDefinitionEmpty; globalObjectClassDefinition.initialize = globalObject_initialize; globalObjectClassDefinition.staticValues = globalObject_staticValues; globalObjectClassDefinition.staticFunctions = globalObject_staticFunctions; globalObjectClassDefinition.attributes = kJSClassAttributeNoAutomaticPrototype; JSClassRef globalObjectClass = JSClassCreate(&globalObjectClassDefinition); context = JSGlobalContextCreate(globalObjectClass); JSObjectRef globalObject = JSContextGetGlobalObject(context); ASSERT(JSValueIsObject(context, globalObject)); JSValueRef jsUndefined = JSValueMakeUndefined(context); JSValueRef jsNull = JSValueMakeNull(context); JSValueRef jsTrue = JSValueMakeBoolean(context, true); JSValueRef jsFalse = JSValueMakeBoolean(context, false); JSValueRef jsZero = JSValueMakeNumber(context, 0); JSValueRef jsOne = JSValueMakeNumber(context, 1); JSValueRef jsOneThird = JSValueMakeNumber(context, 1.0 / 3.0); JSObjectRef jsObjectNoProto = JSObjectMake(context, NULL, NULL); JSObjectSetPrototype(context, jsObjectNoProto, JSValueMakeNull(context)); // FIXME: test funny utf8 characters JSStringRef jsEmptyIString = JSStringCreateWithUTF8CString(""); JSValueRef jsEmptyString = JSValueMakeString(context, jsEmptyIString); JSStringRef jsOneIString = JSStringCreateWithUTF8CString("1"); JSValueRef jsOneString = JSValueMakeString(context, jsOneIString); UniChar singleUniChar = 65; // Capital A CFMutableStringRef cfString = CFStringCreateMutableWithExternalCharactersNoCopy(kCFAllocatorDefault, &singleUniChar, 1, 1, kCFAllocatorNull); JSStringRef jsCFIString = JSStringCreateWithCFString(cfString); JSValueRef jsCFString = JSValueMakeString(context, jsCFIString); CFStringRef cfEmptyString = CFStringCreateWithCString(kCFAllocatorDefault, "", kCFStringEncodingUTF8); JSStringRef jsCFEmptyIString = JSStringCreateWithCFString(cfEmptyString); JSValueRef jsCFEmptyString = JSValueMakeString(context, jsCFEmptyIString); CFIndex cfStringLength = CFStringGetLength(cfString); UniChar buffer[cfStringLength]; CFStringGetCharacters(cfString, CFRangeMake(0, cfStringLength), buffer); JSStringRef jsCFIStringWithCharacters = JSStringCreateWithCharacters(buffer, cfStringLength); JSValueRef jsCFStringWithCharacters = JSValueMakeString(context, jsCFIStringWithCharacters); JSStringRef jsCFEmptyIStringWithCharacters = JSStringCreateWithCharacters(buffer, CFStringGetLength(cfEmptyString)); JSValueRef jsCFEmptyStringWithCharacters = JSValueMakeString(context, jsCFEmptyIStringWithCharacters); ASSERT(JSValueGetType(context, jsUndefined) == kJSTypeUndefined); ASSERT(JSValueGetType(context, jsNull) == kJSTypeNull); ASSERT(JSValueGetType(context, jsTrue) == kJSTypeBoolean); ASSERT(JSValueGetType(context, jsFalse) == kJSTypeBoolean); ASSERT(JSValueGetType(context, jsZero) == kJSTypeNumber); ASSERT(JSValueGetType(context, jsOne) == kJSTypeNumber); ASSERT(JSValueGetType(context, jsOneThird) == kJSTypeNumber); ASSERT(JSValueGetType(context, jsEmptyString) == kJSTypeString); ASSERT(JSValueGetType(context, jsOneString) == kJSTypeString); ASSERT(JSValueGetType(context, jsCFString) == kJSTypeString); ASSERT(JSValueGetType(context, jsCFStringWithCharacters) == kJSTypeString); ASSERT(JSValueGetType(context, jsCFEmptyString) == kJSTypeString); ASSERT(JSValueGetType(context, jsCFEmptyStringWithCharacters) == kJSTypeString); JSObjectRef myObject = JSObjectMake(context, MyObject_class(context), NULL); JSStringRef myObjectIString = JSStringCreateWithUTF8CString("MyObject"); JSObjectSetProperty(context, globalObject, myObjectIString, myObject, kJSPropertyAttributeNone, NULL); JSStringRelease(myObjectIString); JSValueRef exception; // Conversions that throw exceptions exception = NULL; ASSERT(NULL == JSValueToObject(context, jsNull, &exception)); ASSERT(exception); exception = NULL; // FIXME <rdar://4668451> - On i386 the isnan(double) macro tries to map to the isnan(float) function, // causing a build break with -Wshorten-64-to-32 enabled. The issue is known by the appropriate team. // After that's resolved, we can remove these casts ASSERT(isnan((float)JSValueToNumber(context, jsObjectNoProto, &exception))); ASSERT(exception); exception = NULL; ASSERT(!JSValueToStringCopy(context, jsObjectNoProto, &exception)); ASSERT(exception); ASSERT(JSValueToBoolean(context, myObject)); exception = NULL; ASSERT(!JSValueIsEqual(context, jsObjectNoProto, JSValueMakeNumber(context, 1), &exception)); ASSERT(exception); exception = NULL; JSObjectGetPropertyAtIndex(context, myObject, 0, &exception); ASSERT(1 == JSValueToNumber(context, exception, NULL)); assertEqualsAsBoolean(jsUndefined, false); assertEqualsAsBoolean(jsNull, false); assertEqualsAsBoolean(jsTrue, true); assertEqualsAsBoolean(jsFalse, false); assertEqualsAsBoolean(jsZero, false); assertEqualsAsBoolean(jsOne, true); assertEqualsAsBoolean(jsOneThird, true); assertEqualsAsBoolean(jsEmptyString, false); assertEqualsAsBoolean(jsOneString, true); assertEqualsAsBoolean(jsCFString, true); assertEqualsAsBoolean(jsCFStringWithCharacters, true); assertEqualsAsBoolean(jsCFEmptyString, false); assertEqualsAsBoolean(jsCFEmptyStringWithCharacters, false); assertEqualsAsNumber(jsUndefined, nan("")); assertEqualsAsNumber(jsNull, 0); assertEqualsAsNumber(jsTrue, 1); assertEqualsAsNumber(jsFalse, 0); assertEqualsAsNumber(jsZero, 0); assertEqualsAsNumber(jsOne, 1); assertEqualsAsNumber(jsOneThird, 1.0 / 3.0); assertEqualsAsNumber(jsEmptyString, 0); assertEqualsAsNumber(jsOneString, 1); assertEqualsAsNumber(jsCFString, nan("")); assertEqualsAsNumber(jsCFStringWithCharacters, nan("")); assertEqualsAsNumber(jsCFEmptyString, 0); assertEqualsAsNumber(jsCFEmptyStringWithCharacters, 0); ASSERT(sizeof(JSChar) == sizeof(UniChar)); assertEqualsAsCharactersPtr(jsUndefined, "undefined"); assertEqualsAsCharactersPtr(jsNull, "null"); assertEqualsAsCharactersPtr(jsTrue, "true"); assertEqualsAsCharactersPtr(jsFalse, "false"); assertEqualsAsCharactersPtr(jsZero, "0"); assertEqualsAsCharactersPtr(jsOne, "1"); assertEqualsAsCharactersPtr(jsOneThird, "0.3333333333333333"); assertEqualsAsCharactersPtr(jsEmptyString, ""); assertEqualsAsCharactersPtr(jsOneString, "1"); assertEqualsAsCharactersPtr(jsCFString, "A"); assertEqualsAsCharactersPtr(jsCFStringWithCharacters, "A"); assertEqualsAsCharactersPtr(jsCFEmptyString, ""); assertEqualsAsCharactersPtr(jsCFEmptyStringWithCharacters, ""); assertEqualsAsUTF8String(jsUndefined, "undefined"); assertEqualsAsUTF8String(jsNull, "null"); assertEqualsAsUTF8String(jsTrue, "true"); assertEqualsAsUTF8String(jsFalse, "false"); assertEqualsAsUTF8String(jsZero, "0"); assertEqualsAsUTF8String(jsOne, "1"); assertEqualsAsUTF8String(jsOneThird, "0.3333333333333333"); assertEqualsAsUTF8String(jsEmptyString, ""); assertEqualsAsUTF8String(jsOneString, "1"); assertEqualsAsUTF8String(jsCFString, "A"); assertEqualsAsUTF8String(jsCFStringWithCharacters, "A"); assertEqualsAsUTF8String(jsCFEmptyString, ""); assertEqualsAsUTF8String(jsCFEmptyStringWithCharacters, ""); ASSERT(JSValueIsStrictEqual(context, jsTrue, jsTrue)); ASSERT(!JSValueIsStrictEqual(context, jsOne, jsOneString)); ASSERT(JSValueIsEqual(context, jsOne, jsOneString, NULL)); ASSERT(!JSValueIsEqual(context, jsTrue, jsFalse, NULL)); CFStringRef cfJSString = JSStringCopyCFString(kCFAllocatorDefault, jsCFIString); CFStringRef cfJSEmptyString = JSStringCopyCFString(kCFAllocatorDefault, jsCFEmptyIString); ASSERT(CFEqual(cfJSString, cfString)); ASSERT(CFEqual(cfJSEmptyString, cfEmptyString)); CFRelease(cfJSString); CFRelease(cfJSEmptyString); CFRelease(cfString); CFRelease(cfEmptyString); jsGlobalValue = JSObjectMake(context, NULL, NULL); JSValueProtect(context, jsGlobalValue); JSGarbageCollect(context); ASSERT(JSValueIsObject(context, jsGlobalValue)); JSValueUnprotect(context, jsGlobalValue); JSStringRef goodSyntax = JSStringCreateWithUTF8CString("x = 1;"); JSStringRef badSyntax = JSStringCreateWithUTF8CString("x := 1;"); ASSERT(JSCheckScriptSyntax(context, goodSyntax, NULL, 0, NULL)); ASSERT(!JSCheckScriptSyntax(context, badSyntax, NULL, 0, NULL)); JSValueRef result; JSValueRef v; JSObjectRef o; JSStringRef string; result = JSEvaluateScript(context, goodSyntax, NULL, NULL, 1, NULL); ASSERT(result); ASSERT(JSValueIsEqual(context, result, jsOne, NULL)); exception = NULL; result = JSEvaluateScript(context, badSyntax, NULL, NULL, 1, &exception); ASSERT(!result); ASSERT(JSValueIsObject(context, exception)); JSStringRef array = JSStringCreateWithUTF8CString("Array"); JSObjectRef arrayConstructor = JSValueToObject(context, JSObjectGetProperty(context, globalObject, array, NULL), NULL); JSStringRelease(array); result = JSObjectCallAsConstructor(context, arrayConstructor, 0, NULL, NULL); ASSERT(result); ASSERT(JSValueIsObject(context, result)); ASSERT(JSValueIsInstanceOfConstructor(context, result, arrayConstructor, NULL)); ASSERT(!JSValueIsInstanceOfConstructor(context, JSValueMakeNull(context), arrayConstructor, NULL)); o = JSValueToObject(context, result, NULL); exception = NULL; ASSERT(JSValueIsUndefined(context, JSObjectGetPropertyAtIndex(context, o, 0, &exception))); ASSERT(!exception); JSObjectSetPropertyAtIndex(context, o, 0, JSValueMakeNumber(context, 1), &exception); ASSERT(!exception); exception = NULL; ASSERT(1 == JSValueToNumber(context, JSObjectGetPropertyAtIndex(context, o, 0, &exception), &exception)); ASSERT(!exception); JSStringRef functionBody; JSObjectRef function; exception = NULL; functionBody = JSStringCreateWithUTF8CString("rreturn Array;"); JSStringRef line = JSStringCreateWithUTF8CString("line"); ASSERT(!JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, &exception)); ASSERT(JSValueIsObject(context, exception)); v = JSObjectGetProperty(context, JSValueToObject(context, exception, NULL), line, NULL); assertEqualsAsNumber(v, 2); // FIXME: Lexer::setCode bumps startingLineNumber by 1 -- we need to change internal callers so that it doesn't have to (saying '0' to mean '1' in the API would be really confusing -- it's really confusing internally, in fact) JSStringRelease(functionBody); JSStringRelease(line); exception = NULL; functionBody = JSStringCreateWithUTF8CString("return Array;"); function = JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, &exception); JSStringRelease(functionBody); ASSERT(!exception); ASSERT(JSObjectIsFunction(context, function)); v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, NULL); ASSERT(v); ASSERT(JSValueIsEqual(context, v, arrayConstructor, NULL)); exception = NULL; function = JSObjectMakeFunction(context, NULL, 0, NULL, jsEmptyIString, NULL, 0, &exception); ASSERT(!exception); v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, &exception); ASSERT(v && !exception); ASSERT(JSValueIsUndefined(context, v)); exception = NULL; v = NULL; JSStringRef foo = JSStringCreateWithUTF8CString("foo"); JSStringRef argumentNames[] = { foo }; functionBody = JSStringCreateWithUTF8CString("return foo;"); function = JSObjectMakeFunction(context, foo, 1, argumentNames, functionBody, NULL, 1, &exception); ASSERT(function && !exception); JSValueRef arguments[] = { JSValueMakeNumber(context, 2) }; v = JSObjectCallAsFunction(context, function, NULL, 1, arguments, &exception); JSStringRelease(foo); JSStringRelease(functionBody); string = JSValueToStringCopy(context, function, NULL); assertEqualsAsUTF8String(JSValueMakeString(context, string), "function foo(foo) \n{\n return foo;\n}"); JSStringRelease(string); JSStringRef print = JSStringCreateWithUTF8CString("print"); JSObjectRef printFunction = JSObjectMakeFunctionWithCallback(context, print, print_callAsFunction); JSObjectSetProperty(context, globalObject, print, printFunction, kJSPropertyAttributeNone, NULL); JSStringRelease(print); ASSERT(!JSObjectSetPrivate(printFunction, (void*)1)); ASSERT(!JSObjectGetPrivate(printFunction)); JSStringRef myConstructorIString = JSStringCreateWithUTF8CString("MyConstructor"); JSObjectRef myConstructor = JSObjectMakeConstructor(context, NULL, myConstructor_callAsConstructor); JSObjectSetProperty(context, globalObject, myConstructorIString, myConstructor, kJSPropertyAttributeNone, NULL); JSStringRelease(myConstructorIString); ASSERT(!JSObjectSetPrivate(myConstructor, (void*)1)); ASSERT(!JSObjectGetPrivate(myConstructor)); string = JSStringCreateWithUTF8CString("Derived"); JSObjectRef derivedConstructor = JSObjectMakeConstructor(context, Derived_class(context), NULL); JSObjectSetProperty(context, globalObject, string, derivedConstructor, kJSPropertyAttributeNone, NULL); JSStringRelease(string); o = JSObjectMake(context, NULL, NULL); JSObjectSetProperty(context, o, jsOneIString, JSValueMakeNumber(context, 1), kJSPropertyAttributeNone, NULL); JSObjectSetProperty(context, o, jsCFIString, JSValueMakeNumber(context, 1), kJSPropertyAttributeDontEnum, NULL); JSPropertyNameArrayRef nameArray = JSObjectCopyPropertyNames(context, o); size_t expectedCount = JSPropertyNameArrayGetCount(nameArray); size_t count; for (count = 0; count < expectedCount; ++count) JSPropertyNameArrayGetNameAtIndex(nameArray, count); JSPropertyNameArrayRelease(nameArray); ASSERT(count == 1); // jsCFString should not be enumerated JSClassDefinition nullDefinition = kJSClassDefinitionEmpty; nullDefinition.attributes = kJSClassAttributeNoAutomaticPrototype; JSClassRef nullClass = JSClassCreate(&nullDefinition); JSClassRelease(nullClass); nullDefinition = kJSClassDefinitionEmpty; nullClass = JSClassCreate(&nullDefinition); JSClassRelease(nullClass); functionBody = JSStringCreateWithUTF8CString("return this;"); function = JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, NULL); JSStringRelease(functionBody); v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, NULL); ASSERT(JSValueIsEqual(context, v, globalObject, NULL)); v = JSObjectCallAsFunction(context, function, o, 0, NULL, NULL); ASSERT(JSValueIsEqual(context, v, o, NULL)); char* scriptUTF8 = createStringWithContentsOfFile(scriptPath); if (!scriptUTF8) printf("FAIL: Test script could not be loaded.\n"); else { JSStringRef script = JSStringCreateWithUTF8CString(scriptUTF8); result = JSEvaluateScript(context, script, NULL, NULL, 1, &exception); if (JSValueIsUndefined(context, result)) printf("PASS: Test script executed successfully.\n"); else { printf("FAIL: Test script returned unexpected value:\n"); JSStringRef exceptionIString = JSValueToStringCopy(context, exception, NULL); CFStringRef exceptionCF = JSStringCopyCFString(kCFAllocatorDefault, exceptionIString); CFShow(exceptionCF); CFRelease(exceptionCF); JSStringRelease(exceptionIString); } JSStringRelease(script); free(scriptUTF8); } // Clear out local variables pointing at JSObjectRefs to allow their values to be collected function = NULL; v = NULL; o = NULL; globalObject = NULL; JSStringRelease(jsEmptyIString); JSStringRelease(jsOneIString); JSStringRelease(jsCFIString); JSStringRelease(jsCFEmptyIString); JSStringRelease(jsCFIStringWithCharacters); JSStringRelease(jsCFEmptyIStringWithCharacters); JSStringRelease(goodSyntax); JSStringRelease(badSyntax); JSGlobalContextRelease(context); JSGarbageCollect(context); JSClassRelease(globalObjectClass); printf("PASS: Program exited normally.\n"); return 0; }
void IGraphicsCarbon::CreateTextEntry(IControl* pControl, IText* pText, IRECT* pTextRect, const char* pString, IParam* pParam) { ControlRef control = 0; if (!pControl || mTextEntryView || !mIsComposited) return; Rect r = { pTextRect->T, pTextRect->L, pTextRect->B, pTextRect->R }; // these adjustments should make it the same as the cocoa one, i.e. the same size as the pTextRect, but with the extra blue rim often this is too small //Rect r = { pTextRect->T+4, pTextRect->L+3, pTextRect->B-3, pTextRect->R -3 }; if (CreateEditUnicodeTextControl(NULL, &r, NULL, false, NULL, &control) != noErr) return; HIViewAddSubview(mView, control); const EventTypeSpec events[] = { { kEventClassKeyboard, kEventRawKeyDown }, { kEventClassKeyboard, kEventRawKeyRepeat } }; InstallControlEventHandler(control, TextEntryHandler, GetEventTypeCount(events), events, this, &mTextEntryHandler); mTextEntryView = control; if (pString[0] != '\0') { CFStringRef str = CFStringCreateWithCString(NULL, pString, kCFStringEncodingUTF8); if (str) { SetControlData(mTextEntryView, kControlEditTextPart, kControlEditTextCFStringTag, sizeof(str), &str); CFRelease(str); } ControlEditTextSelectionRec sel; sel.selStart = 0; sel.selEnd = strlen(pString); SetControlData(mTextEntryView, kControlEditTextPart, kControlEditTextSelectionTag, sizeof(sel), &sel); } int just = 0; switch ( pText->mAlign ) { case IText::kAlignNear: just = teJustLeft; break; case IText::kAlignCenter: just = teCenter; break; case IText::kAlignFar: just = teJustRight; break; default: just = teCenter; break; } ControlFontStyleRec font = { kControlUseJustMask | kControlUseSizeMask | kControlUseFontMask, 0, pText->mSize, 0, 0, just, 0, 0 }; CFStringRef str = CFStringCreateWithCString(NULL, pText->mFont, kCFStringEncodingUTF8); font.font = ATSFontFamilyFindFromName(str, kATSOptionFlagsDefault); SetControlData(mTextEntryView, kControlEditTextPart, kControlFontStyleTag, sizeof(font), &font); CFRelease(str); Boolean singleLineStyle = true; SetControlData(mTextEntryView, kControlEditTextPart, kControlEditTextSingleLineTag, sizeof (Boolean), &singleLineStyle); HIViewSetVisible(mTextEntryView, true); HIViewAdvanceFocus(mTextEntryView, 0); SetKeyboardFocus(mWindow, mTextEntryView, kControlEditTextPart); SetUserFocusWindow(mWindow); mEdControl = pControl; mEdParam = pParam; }
MenuRef IGraphicsCarbon::CreateMenu(IPopupMenu* pMenu) { MenuRef menuRef = 0; ResID menuID = UniqueID ('MENU'); int numItems = pMenu->GetNItems(); if (numItems && CreateNewMenu(menuID, kMenuAttrCondenseSeparators, &menuRef) == noErr) { for (int i = 0; i < numItems; ++i) { IPopupMenuItem* menuItem = pMenu->GetItem(i); if (menuItem->GetIsSeparator()) { AppendMenuItemTextWithCFString(menuRef, CFSTR(""), kMenuItemAttrSeparator, 0, NULL); } else { CFStringRef itemString = CFStringCreateWithCString(NULL, menuItem->GetText(), kCFStringEncodingUTF8); if (pMenu->GetPrefix()) { CFStringRef prefixString = 0; switch (pMenu->GetPrefix()) { case 0: prefixString = CFStringCreateWithCString(NULL, "", kCFStringEncodingUTF8); break; case 1: prefixString = CFStringCreateWithFormat(NULL, 0, CFSTR("%1d: "),i+1); break; case 2: prefixString = CFStringCreateWithFormat(NULL, 0, CFSTR("%02d: "),i+1); break; case 3: prefixString = CFStringCreateWithFormat(NULL, 0, CFSTR("%03d: "),i+1); break; } CFMutableStringRef newItemString = CFStringCreateMutable(0, 0); CFStringAppend (newItemString, prefixString); CFStringAppend (newItemString, itemString); CFRelease (itemString); CFRelease (prefixString); itemString = newItemString; } if (itemString == 0) continue; MenuItemAttributes itemAttribs = kMenuItemAttrIgnoreMeta; if (!menuItem->GetEnabled()) { itemAttribs |= kMenuItemAttrDisabled; } if (menuItem->GetIsTitle()) { itemAttribs |= kMenuItemAttrSectionHeader; } InsertMenuItemTextWithCFString(menuRef, itemString, i, itemAttribs, 0); if (menuItem->GetChecked()) { CheckMenuItem(menuRef, i+1, true); } if (menuItem->GetSubmenu()) { MenuRef submenu = CreateMenu(menuItem->GetSubmenu()); if (submenu) { SetMenuItemHierarchicalMenu(menuRef, i+1, submenu); CFRelease (submenu); } } CFRelease (itemString); } } // if (pMenu->getStyle() & kCheckStyle && !multipleCheck) // CheckMenuItem (menuRef, pMenu->getCurrentIndex (true) + 1, true); SetMenuItemRefCon(menuRef, 0, (int32_t)pMenu); //swell collision #undef InsertMenu InsertMenu(menuRef, kInsertHierarchicalMenu); #define InsertMenu SWELL_InsertMenu } return menuRef; }
void I_Error (char *error, ...) { va_list argptr; atexit_listentry_t *entry; boolean exit_gui_popup; if (already_quitting) { fprintf(stderr, "Warning: recursive call to I_Error detected.\n"); exit(-1); } else { already_quitting = true; } // Message first. va_start(argptr, error); //fprintf(stderr, "\nError: "); vfprintf(stderr, error, argptr); fprintf(stderr, "\n\n"); va_end(argptr); fflush(stderr); // Shutdown. Here might be other errors. entry = exit_funcs; while (entry != NULL) { if (entry->run_on_error) { entry->func(); } entry = entry->next; } exit_gui_popup = !M_ParmExists("-nogui"); #ifdef _WIN32 // On Windows, pop up a dialog box with the error message. if (exit_gui_popup) { char msgbuf[512]; wchar_t wmsgbuf[512]; va_start(argptr, error); memset(msgbuf, 0, sizeof(msgbuf)); M_vsnprintf(msgbuf, sizeof(msgbuf), error, argptr); va_end(argptr); MultiByteToWideChar(CP_ACP, 0, msgbuf, strlen(msgbuf) + 1, wmsgbuf, sizeof(wmsgbuf)); MessageBoxW(NULL, wmsgbuf, L"", MB_OK); } #endif #ifdef __MACOSX__ if (exit_gui_popup && !I_ConsoleStdout()) { CFStringRef message; char msgbuf[512]; int i; va_start(argptr, error); memset(msgbuf, 0, sizeof(msgbuf)); M_vsnprintf(msgbuf, sizeof(msgbuf), error, argptr); va_end(argptr); // The CoreFoundation message box wraps text lines, so replace // newline characters with spaces so that multiline messages // are continuous. for (i = 0; msgbuf[i] != '\0'; ++i) { if (msgbuf[i] == '\n') { msgbuf[i] = ' '; } } message = CFStringCreateWithCString(NULL, msgbuf, kCFStringEncodingUTF8); CFUserNotificationDisplayNotice(0, kCFUserNotificationCautionAlertLevel, NULL, NULL, NULL, CFSTR(PACKAGE_STRING), message, NULL); } #endif // abort(); exit(-1); }
/***************************************************************************** * NetBrowserInfoCopyDescription * - * Make CF happy. *****************************************************************************/ CFStringRef NetBrowserInfoCopyDescription(const void *value) { (void)value; return CFStringCreateWithCString(NULL, "NetBrowserInfo: No useful description", kCFStringEncodingUTF8); }
bool8 NPClientDialog(void) { OSStatus err; IBNibRef nibRef; npclient.dialogcancel = true; npclient.dialogsheet = false; npclient.configsaved = false; err = CreateNibReference(kMacS9XCFString, &nibRef); if (err == noErr) { err = CreateWindowFromNib(nibRef, CFSTR("Connect"), &mRef); if (err == noErr) { err = CreateWindowFromNib(nibRef, CFSTR("PlayerList"), &sRef); if (err == noErr) { EventHandlerRef eref, seref; EventLoopTimerRef tref; EventHandlerUPP eventUPP, sheetUPP; EventLoopTimerUPP timerUPP; EventTypeSpec windowEvents[] = { { kEventClassCommand, kEventCommandProcess } }; CFStringRef ref; HIViewRef ctl, root; HIViewID cid; unsigned char pstr[256]; npclient.dialogprocess = kNPCDialogInit; eventUPP = NewEventHandlerUPP(NPClientDialogEventHandler); err = InstallWindowEventHandler(mRef, eventUPP, GetEventTypeCount(windowEvents), windowEvents, (void *) mRef, &eref); timerUPP = NewEventLoopTimerUPP(NPClientDialogTimerHandler); err = InstallEventLoopTimer(GetCurrentEventLoop(), 0.0f, 0.1f, timerUPP, (void *) mRef, &tref); sheetUPP = NewEventHandlerUPP(NPClientSheetEventHandler); err = InstallWindowEventHandler(sRef, sheetUPP, GetEventTypeCount(windowEvents), windowEvents, (void *) sRef, &seref); root = HIViewGetRoot(mRef); cid.id = 0; cid.signature = 'CHAS'; HIViewFindByID(root, cid, &ctl); HIViewSetVisible(ctl, false); cid.signature = 'SVIP'; HIViewFindByID(root, cid, &ctl); ConvertCString(npServerIP, pstr); SetEditTextText(ctl, pstr, false); cid.signature = 'CLNM'; HIViewFindByID(root, cid, &ctl); ref = CFStringCreateWithCString(kCFAllocatorDefault, npName, MAC_PATH_ENCODING); if (ref) { SetEditTextCFString(ctl, ref, false); CFRelease(ref); } else SetEditTextCFString(ctl, CFSTR("unknown"), false); MoveWindowPosition(mRef, kWindowClient, false); ShowWindow(mRef); err = HIViewAdvanceFocus(root, 0); err = RunAppModalLoopForWindow(mRef); HideWindow(mRef); SaveWindowPosition(mRef, kWindowClient); err = RemoveEventHandler(seref); DisposeEventHandlerUPP(sheetUPP); err = RemoveEventLoopTimer(tref); DisposeEventLoopTimerUPP(timerUPP); err = RemoveEventHandler(eref); DisposeEventHandlerUPP(eventUPP); ReleaseWindow(sRef); } ReleaseWindow(mRef); } DisposeNibReference(nibRef); } return (!npclient.dialogcancel); }
void MacQTStartRecording(char *path) { OSStatus err; CFStringRef str; CFURLRef url; memset(&sqt, 0, sizeof(sqt)); // storage str = CFStringCreateWithCString(kCFAllocatorDefault, path, MAC_PATH_ENCODING); url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, str, kCFURLPOSIXPathStyle, false); err = QTNewDataReferenceFromCFURL(url, 0, &(sqt.dataRef), &(sqt.dataRefType)); CheckError(err, 21); CFRelease(url); CFRelease(str); err = CreateMovieStorage(sqt.dataRef, sqt.dataRefType, 'TVOD', smSystemScript, createMovieFileDeleteCurFile | newMovieActive, &(sqt.dataHandler), &(sqt.movie)); CheckError(err, 22); // video MacQTOpenVideoComponent(&(sqt.vci)); SCTemporalSettings ts; err = SCGetInfo(sqt.vci, scTemporalSettingsType, &ts); ts.frameRate = FixRatio(Memory.ROMFramesPerSecond, 1); if (ts.keyFrameRate < 1) ts.keyFrameRate = Memory.ROMFramesPerSecond; sqt.keyFrame = sqt.keyFrameCount = ts.keyFrameRate; sqt.frameSkip = sqt.frameSkipCount = (macQTMovFlag & 0xFF00) >> 8; err = SCSetInfo(sqt.vci, scTemporalSettingsType, &ts); sqt.frame.top = 0; sqt.frame.left = 0; sqt.frame.right = ((macQTMovFlag & kMovDoubleSize) ? 2 : 1) * SNES_WIDTH; sqt.frame.bottom = ((macQTMovFlag & kMovDoubleSize) ? 2 : 1) * ((macQTMovFlag & kMovExtendedHeight) ? SNES_HEIGHT_EXTENDED : SNES_HEIGHT); sqt.pw = sqt.ph = 0; sqt.firstFrame = true; Rect rct; SetRect(&rct, 0, 0, SNES_WIDTH * 2, SNES_HEIGHT_EXTENDED * 2 + 4); InitGWorld(&(sqt.bw), &rct, 16); sqt.vTrack = NewMovieTrack(sqt.movie, FixRatio(sqt.frame.right, 1), FixRatio(sqt.frame.bottom, 1), kNoVolume); CheckError(GetMoviesError(), 23); sqt.vMedia = NewTrackMedia(sqt.vTrack, VideoMediaType, Memory.ROMFramesPerSecond, nil, 0); CheckError(GetMoviesError(), 24); err = BeginMediaEdits(sqt.vMedia); CheckError(err, 25); // sound sqt.soundDesc = (SoundDescriptionHandle) NewHandleClear(sizeof(SoundDescription)); CheckError(MemError(), 26); (**sqt.soundDesc).descSize = sizeof(SoundDescription); #ifdef __BIG_ENDIAN__ (**sqt.soundDesc).dataFormat = Settings.SixteenBitSound ? k16BitBigEndianFormat : k8BitOffsetBinaryFormat; #else (**sqt.soundDesc).dataFormat = Settings.SixteenBitSound ? k16BitLittleEndianFormat : k8BitOffsetBinaryFormat; #endif (**sqt.soundDesc).numChannels = Settings.Stereo ? 2 : 1; (**sqt.soundDesc).sampleSize = Settings.SixteenBitSound ? 16 : 8; (**sqt.soundDesc).sampleRate = (UnsignedFixed) FixRatio(Settings.SoundPlaybackRate, 1); sqt.samplesPerSec = Settings.SoundPlaybackRate / Memory.ROMFramesPerSecond; sqt.soundBufferSize = sqt.samplesPerSec; if (Settings.SixteenBitSound) sqt.soundBufferSize <<= 1; if (Settings.Stereo) sqt.soundBufferSize <<= 1; sqt.soundBuffer = NewHandleClear(sqt.soundBufferSize); CheckError(MemError(), 27); HLock(sqt.soundBuffer); sqt.sTrack = NewMovieTrack(sqt.movie, 0, 0, kFullVolume); CheckError(GetMoviesError(), 28); sqt.sMedia = NewTrackMedia(sqt.sTrack, SoundMediaType, Settings.SoundPlaybackRate, nil, 0); CheckError(GetMoviesError(), 29); err = BeginMediaEdits(sqt.sMedia); CheckError(err, 30); }
static void basic_engine_shape (PangoEngineShape *engine, PangoFont *font, const char *text, gint length, const PangoAnalysis *analysis, PangoGlyphString *glyphs) { const char *p; char *copy; CTLineRef line; CFStringRef cstr; CFDictionaryRef attributes; CFAttributedStringRef attstr; PangoCoreTextFont *cfont = PANGO_CORE_TEXT_FONT (font); PangoCoverage *coverage; CFArrayRef runs; CTRunRef run; CTRunStatus run_status; CFIndex i, glyph_count; const CGGlyph *cgglyphs; CFTypeRef keys[] = { (CFTypeRef) kCTFontAttributeName }; CFTypeRef values[] = { pango_core_text_font_get_ctfont (cfont) }; attributes = CFDictionaryCreate (kCFAllocatorDefault, (const void **)keys, (const void **)values, 1, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); copy = g_strndup (text, length + 1); copy[length] = 0; cstr = CFStringCreateWithCString (kCFAllocatorDefault, copy, kCFStringEncodingUTF8); g_free (copy); attstr = CFAttributedStringCreate (kCFAllocatorDefault, cstr, attributes); line = CTLineCreateWithAttributedString (attstr); runs = CTLineGetGlyphRuns (line); /* Since Pango divides things into runs already, we assume there is * only a single run in this line. */ run = CFArrayGetValueAtIndex (runs, 0); run_status = CTRunGetStatus (run); glyph_count = CTRunGetGlyphCount (run); cgglyphs = CTRunGetGlyphsPtr (run); p = text; pango_glyph_string_set_size (glyphs, glyph_count); coverage = pango_font_get_coverage (PANGO_FONT (cfont), analysis->language); for (i = 0; i < glyph_count; i++) { CFIndex real_i, prev_i; gunichar wc; gunichar mirrored_ch; wc = g_utf8_get_char (p); if (analysis->level % 2) if (pango_get_mirror_char (wc, &mirrored_ch)) wc = mirrored_ch; if (run_status & kCTRunStatusRightToLeft) { real_i = glyph_count - i - 1; prev_i = real_i + 1; } else { real_i = i; prev_i = real_i - 1; } if (wc == 0xa0) /* non-break-space */ wc = 0x20; if (pango_is_zero_width (wc)) { set_glyph (font, glyphs, real_i, p - text, PANGO_GLYPH_EMPTY); } else { PangoCoverageLevel result; result = pango_coverage_get (coverage, wc); if (result != PANGO_COVERAGE_NONE) { set_glyph (font, glyphs, real_i, p - text, cgglyphs[real_i]); if (g_unichar_type (wc) == G_UNICODE_NON_SPACING_MARK) { if (i > 0) { PangoRectangle logical_rect, ink_rect; glyphs->glyphs[real_i].geometry.width = MAX (glyphs->glyphs[prev_i].geometry.width, glyphs->glyphs[prev_i].geometry.width); glyphs->glyphs[prev_i].geometry.width = 0; glyphs->log_clusters[real_i] = glyphs->log_clusters[prev_i]; /* Some heuristics to try to guess how overstrike glyphs are * done and compensate */ pango_font_get_glyph_extents (font, glyphs->glyphs[real_i].glyph, &ink_rect, &logical_rect); if (logical_rect.width == 0 && ink_rect.x == 0) glyphs->glyphs[real_i].geometry.x_offset = (glyphs->glyphs[real_i].geometry.width - ink_rect.width) / 2; } } } else { set_glyph (font, glyphs, real_i, p - text, PANGO_GET_UNKNOWN_GLYPH (wc)); } } p = g_utf8_next_char (p); } CFRelease (line); CFRelease (attstr); CFRelease (cstr); CFRelease (attributes); pango_coverage_unref (coverage); }
int recovery_grestore(string *args, struct shell_state *sh) { int ret; if (args[1] == "") { ifNotQuiet cout << "args[1] must be RestoreBundlePath" << endl; return SHELL_CONTINUE; } // check for trailing / if ( args[1].at(args[1].length() - 1) != '/' ) args[1] = args[1] + '/'; // firmware 1.0 // string temp = args[1] + "694-5259-38.dmg"; // firmware 1.0.1 // string temp = args[1] + "009-7662-6.dmg"; // firmware 1.0.2 string temp = args[1] + "009-7698-4.dmg"; // firmware 1.1.1? // string temp = args[1] + "022-3629-9.dmg"; ifNotQuiet cout << "Entering G-Restore ... " << endl; // Send ramdisk to the phone ifVerbose cout << "Sending ramdisk '"<< temp << "'" << endl; CFStringRef ramdisk = CFStringCreateWithCString(kCFAllocatorDefault, temp.c_str(), kCFStringEncodingMacRoman); ret = sendFileToDevice(sh->recovery_dev, ramdisk); CFRelease(ramdisk); ifVerbose cout << "sendFileToDevice: " << ret << endl; if (ret != 0) { ifNotQuiet cout << "Send ramdisk failed. Aborting." << endl; return SHELL_CONTINUE; } // load ramdisk on the phone ifVerbose cout << "Loading ramdisk." << endl; ret = sendCommandToDevice(sh->recovery_dev, CFSTR("ramdisk")); ifVerbose cout << "sendCommandToDevice 'ramdisk': " << ret << endl; if (ret != 0) { ifNotQuiet cout << "Load ramdisk failed. Aborting." << endl; return SHELL_CONTINUE; } // firmware 1.0 // temp = args[1] + "kernelcache.restore.release.s5l8900xrb"; // firmware 1.0.1, 1.0.2, 1.1.1 temp = args[1]+ "kernelcache.release.s5l8900xrb"; // Send the kernelcache ifVerbose cout << "Sending kernelcache '"<< temp << "'" << endl; CFStringRef kerncache = CFStringCreateWithCString(kCFAllocatorDefault, temp.c_str(), kCFStringEncodingMacRoman); ret = sendFileToDevice(sh->recovery_dev, kerncache); CFRelease(kerncache); ifVerbose cout << "sendFileToDevice: " << ret << endl; if (ret != 0) { ifNotQuiet cout << "Send kernelcache failed. Aborting." << endl; return SHELL_CONTINUE; } //check for custom bootargs if( args[2] != "" ) D("grestore does not yet except custom bootargs."); ifVerbose cout << "Setting bootargs: setenv boot-args rd=md0 -v" << endl; ret = sendCommandToDevice(sh->recovery_dev, CFSTR("setenv boot-args rd=md0 -v")); ifVerbose cout << "sendCommandToDevice: " << ret << endl; if (ret != 0) { ifNotQuiet cout << "Setevn command failed. Aborting." << endl; return SHELL_CONTINUE; } ifVerbose cout << "Loading kernelcache (command: bootx)" << endl; ret = sendCommandToDevice(sh->recovery_dev, CFSTR("bootx")); ifVerbose cout << "sendCommandToDevice: " << ret << endl; if (ret != 0) { ifNotQuiet cout << "failed (" << ret << ") Aborting." << endl; return SHELL_CONTINUE; } ifNotQuiet cout << "G-Restore Completed. \nExit iPHUC or reconnect in order to continue in restore mode." << endl; return SHELL_CONTINUE; }
hid_device * HID_API_EXPORT hid_open_path(const char *path) { int i; hid_device *dev = NULL; CFIndex num_devices; dev = new_hid_device(); /* Set up the HID Manager if it hasn't been done */ if (hid_init() < 0) return NULL; /* give the IOHIDManager a chance to update itself */ process_pending_events(); CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr); num_devices = CFSetGetCount(device_set); IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef)); CFSetGetValues(device_set, (const void **) device_array); for (i = 0; i < num_devices; i++) { char cbuf[BUF_LEN]; size_t len; IOHIDDeviceRef os_dev = device_array[i]; len = make_path(os_dev, cbuf, sizeof(cbuf)); if (!strcmp(cbuf, path)) { // Matched Paths. Open this Device. IOReturn ret = IOHIDDeviceOpen(os_dev, kIOHIDOptionsTypeNone); if (ret == kIOReturnSuccess) { char str[32]; free(device_array); CFRetain(os_dev); CFRelease(device_set); dev->device_handle = os_dev; /* Create the buffers for receiving data */ dev->max_input_report_len = (CFIndex) get_max_report_length(os_dev); dev->input_report_buf = calloc(dev->max_input_report_len, sizeof(uint8_t)); /* Create the Run Loop Mode for this device. printing the reference seems to work. */ sprintf(str, "HIDAPI_%p", os_dev); dev->run_loop_mode = CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII); /* Attach the device to a Run Loop */ IOHIDDeviceRegisterInputReportCallback( os_dev, dev->input_report_buf, dev->max_input_report_len, &hid_report_callback, dev); IOHIDManagerRegisterDeviceRemovalCallback(hid_mgr, hid_device_removal_callback, NULL); /* Start the read thread */ pthread_create(&dev->thread, NULL, read_thread, dev); /* Wait here for the read thread to be initialized. */ pthread_barrier_wait(&dev->barrier); return dev; } else { goto return_error; } } } return_error: free(device_array); CFRelease(device_set); free_hid_device(dev); return NULL; }
int Tcl_MacOSXOpenVersionedBundleResources( Tcl_Interp *interp, const char *bundleName, const char *bundleVersion, int hasResourceFile, size_t maxPathLen, char *libraryPath) { #ifdef HAVE_COREFOUNDATION CFBundleRef bundleRef, versionedBundleRef = NULL; CFStringRef bundleNameRef; CFURLRef libURL; libraryPath[0] = '\0'; bundleNameRef = CFStringCreateWithCString(NULL, bundleName, kCFStringEncodingUTF8); bundleRef = CFBundleGetBundleWithIdentifier(bundleNameRef); CFRelease(bundleNameRef); if (bundleVersion && bundleRef) { /* * Create bundle from bundleVersion subdirectory of 'Versions'. */ CFURLRef bundleURL = CFBundleCopyBundleURL(bundleRef); if (bundleURL) { CFStringRef bundleVersionRef = CFStringCreateWithCString(NULL, bundleVersion, kCFStringEncodingUTF8); if (bundleVersionRef) { CFComparisonResult versionComparison = kCFCompareLessThan; CFStringRef bundleTailRef = CFURLCopyLastPathComponent( bundleURL); if (bundleTailRef) { versionComparison = CFStringCompare(bundleTailRef, bundleVersionRef, 0); CFRelease(bundleTailRef); } if (versionComparison != kCFCompareEqualTo) { CFURLRef versURL = CFURLCreateCopyAppendingPathComponent( NULL, bundleURL, CFSTR("Versions"), TRUE); if (versURL) { CFURLRef versionedBundleURL = CFURLCreateCopyAppendingPathComponent( NULL, versURL, bundleVersionRef, TRUE); if (versionedBundleURL) { versionedBundleRef = CFBundleCreate(NULL, versionedBundleURL); if (versionedBundleRef) { bundleRef = versionedBundleRef; } CFRelease(versionedBundleURL); } CFRelease(versURL); } } CFRelease(bundleVersionRef); } CFRelease(bundleURL); } } if (bundleRef) { if (hasResourceFile) { (void) OpenResourceMap(bundleRef); } libURL = CFBundleCopyResourceURL(bundleRef, CFSTR("Scripts"), NULL, NULL); if (libURL) { /* * FIXME: This is a quick fix, it is probably not right for * internationalization. */ CFURLGetFileSystemRepresentation(libURL, TRUE, (unsigned char *) libraryPath, maxPathLen); CFRelease(libURL); } if (versionedBundleRef) { #if MAC_OS_X_VERSION_MIN_REQUIRED < 1050 /* * Workaround CFBundle bug in Tiger and earlier. [Bug 2569449] */ if (tclMacOSXDarwinRelease >= 9) #endif { CFRelease(versionedBundleRef); } } } if (libraryPath[0]) { return TCL_OK; } #endif /* HAVE_COREFOUNDATION */ return TCL_ERROR; }
bool Shell::OpenWindow(const char* name, bool attach_opengl) { Rect content_bounds = { 60, 20, 60 + 768, 20 + 1024 }; OSStatus result = CreateNewWindow(kDocumentWindowClass, kWindowStandardDocumentAttributes | kWindowStandardHandlerAttribute | kWindowLiveResizeAttribute, &content_bounds, &window); if (result != noErr) return false; CFStringRef window_title = CFStringCreateWithCString(NULL, name, kCFStringEncodingUTF8); if (result != noErr) return false; result = SetWindowTitleWithCFString(window, window_title); if (result != noErr) { CFRelease(window_title); return false; } CFRelease(window_title); ShowWindow(window); if (attach_opengl) { static GLint attributes[] = { AGL_RGBA, AGL_DOUBLEBUFFER, AGL_ALPHA_SIZE, 8, AGL_DEPTH_SIZE, 24, AGL_STENCIL_SIZE, 8, AGL_ACCELERATED, AGL_NONE }; AGLPixelFormat pixel_format = aglChoosePixelFormat(NULL, 0, attributes); if (pixel_format == NULL) return false; window_port = GetWindowPort(window); if (window_port == NULL) return false; gl_context = aglCreateContext(pixel_format, NULL); if (gl_context == NULL) return false; aglSetDrawable(gl_context, window_port); aglSetCurrentContext(gl_context); aglDestroyPixelFormat(pixel_format); // Set up the GL state. glClearColor(0, 0, 0, 1); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 1024, 768, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); opengl_attached = true; } return true; }
int Plugin::load(const char *fname) { strcpy(pathfile, fname); #if defined(_WIN32) module = LoadLibrary(pathfile); #elif defined(__linux__) module = dlopen(pathfile, RTLD_LAZY); #elif defined(__APPLE__) /* creates the path to the bundle. In OSX vsts are stored inside the * so-called bundles, just a directory with '.vst' extension. Finally * we open the bundle with CFBundleCreate. */ CFStringRef pathStr = CFStringCreateWithCString(NULL, pathfile, kCFStringEncodingASCII); CFURLRef bundleUrl = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, pathStr, kCFURLPOSIXPathStyle, true); if(bundleUrl == NULL) { gLog("[plugin] unable to create URL reference for plugin\n"); status = 0; return 0; } module = CFBundleCreate(kCFAllocatorDefault, bundleUrl); #endif if (module) { /* release (free) any old string */ #ifdef __APPLE__ CFRelease(pathStr); CFRelease(bundleUrl); #endif //strcpy(pathfile, fname); ??????????? status = 1; return 1; } else { #if defined(_WIN32) gLog("[plugin] unable to load %s, error: %d\n", fname, (int) GetLastError()); #elif defined(__linux__) gLog("[plugin] unable to load %s, error: %s\n", fname, dlerror()); #elif defined(__APPLE__) gLog("[plugin] unable to create bundle reference\n"); CFRelease(pathStr); CFRelease(bundleUrl); #endif status = 0; return 0; } }
SCBondStatusRef SCBondInterfaceCopyStatus(SCBondInterfaceRef bond) { int bond_if_active; int bond_if_status; CFIndex i; struct if_bond_status_req *ibsr_p = NULL; char if_name[IFNAMSIZ]; CFIndex n; CFNumberRef num; int s; struct if_bond_status *scan_p; SCBondStatusRef status = NULL; CFMutableDictionaryRef status_bond; CFMutableDictionaryRef status_interfaces; if (!isA_SCBondInterface(bond)) { _SCErrorSet(kSCStatusInvalidArgument); return NULL; } s = inet_dgram_socket(); if (s == -1) { _SCErrorSet(errno); goto done; } _SC_cfstring_to_cstring(SCNetworkInterfaceGetBSDName(bond), if_name, sizeof(if_name), kCFStringEncodingASCII); if (siocgifmedia(s, if_name, &bond_if_status, &bond_if_active) == -1) { _SCErrorSet(errno); switch (errno) { case EBUSY : case ENXIO : break; default : SCLog(TRUE, LOG_ERR, CFSTR("siocgifmedia(%s) failed: %s"), if_name, strerror(errno)); } goto done; } ibsr_p = if_bond_status_req_copy(s, if_name); if (ibsr_p == NULL) { _SCErrorSet(errno); goto done; } status_bond = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); status_interfaces = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); n = ibsr_p->ibsr_total; for (i = 0, scan_p = (struct if_bond_status *)ibsr_p->ibsr_buffer; i < n; i++, scan_p++) { int collecting = 0; int distributing = 0; SCNetworkInterfaceRef interface; CFStringRef interface_name; struct if_bond_partner_state * ps; CFMutableDictionaryRef status_interface; int status_val; ps = &scan_p->ibs_partner_state; if (lacp_actor_partner_state_in_sync(scan_p->ibs_state)) { /* we're in-sync */ status_val = kSCBondStatusOK; if (lacp_actor_partner_state_in_sync(ps->ibps_state)) { /* partner is also in-sync */ if (lacp_actor_partner_state_collecting(scan_p->ibs_state) && lacp_actor_partner_state_distributing(ps->ibps_state)) { /* we're able to collect (receive) frames */ collecting = 1; } if (lacp_actor_partner_state_distributing(scan_p->ibs_state) && lacp_actor_partner_state_collecting(ps->ibps_state)) { /* we're able to distribute (transmit) frames */ distributing = 1; } } } else { int active = 0; int status = 0; static lacp_system zeroes = { {0, 0, 0, 0, 0, 0}}; if (siocgifmedia(s, scan_p->ibs_if_name, &status, &active) == -1) { switch (errno) { case EBUSY : case ENXIO : break; default : SCLog(TRUE, LOG_ERR, CFSTR("siocgifmedia(%s) failed: %s"), if_name, strerror(errno)); break; } } if (((status & IFM_AVALID) == 0) || ((status & IFM_ACTIVE) == 0) || ((active & IFM_FDX ) == 0)) { /* link down or not full-duplex */ status_val = kSCBondStatusLinkInvalid; } else if ((ps->ibps_system_priority == 0) && (bcmp(&zeroes, &ps->ibps_system, sizeof(zeroes)) == 0)) { /* no one on the other end of the link */ status_val = kSCBondStatusNoPartner; } else if (active != bond_if_active) { /* the link speed was different */ status_val = kSCBondStatusLinkInvalid; } else { /* partner is not in the active group */ status_val = kSCBondStatusNotInActiveGroup; } } // interface strlcpy(if_name, scan_p->ibs_if_name, sizeof(if_name)); interface_name = CFStringCreateWithCString(NULL, if_name, kCFStringEncodingASCII); interface = _SCNetworkInterfaceCreateWithBSDName(NULL, interface_name, kIncludeNoVirtualInterfaces); CFRelease(interface_name); // interface status status_interface = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); num = CFNumberCreate(NULL, kCFNumberIntType, &status_val); CFDictionarySetValue(status_interface, kSCBondStatusDeviceAggregationStatus, num); CFRelease(num); num = CFNumberCreate(NULL, kCFNumberIntType, &collecting); CFDictionarySetValue(status_interface, kSCBondStatusDeviceCollecting, num); CFRelease(num); num = CFNumberCreate(NULL, kCFNumberIntType, &distributing); CFDictionarySetValue(status_interface, kSCBondStatusDeviceDistributing, num); CFRelease(num); CFDictionarySetValue(status_interfaces, interface, status_interface); CFRelease(interface); CFRelease(status_interface); } status = __SCBondStatusCreatePrivate(NULL, bond, status_bond, status_interfaces); CFRelease(status_bond); CFRelease(status_interfaces); done: if (s != -1) { close(s); } if (ibsr_p != NULL) { free(ibsr_p); } return (SCBondStatusRef)status; }
pascal OSStatus wxMacCarbonFontPanelHandler(EventHandlerCallRef WXUNUSED(nextHandler), EventRef event, void *userData) { OSStatus result = eventNotHandledErr ; wxFontDialog *fontdialog = (wxFontDialog*) userData ; wxFontData& fontdata= fontdialog->GetFontData() ; wxMacCarbonEvent cEvent( event ); switch(cEvent.GetKind()) { case kEventFontSelection : { bool setup = false ; #if wxOSX_USE_CORE_TEXT if ( UMAGetSystemVersion() >= 0x1050 ) { CTFontDescriptorRef descr; if ( cEvent.GetParameter<CTFontDescriptorRef>( kEventParamCTFontDescriptor, typeCTFontDescriptorRef, &descr ) == noErr ) { wxFont font; wxNativeFontInfo fontinfo; fontinfo.Init(descr); font.Create(fontinfo); fontdata.SetChosenFont( font ) ; setup = true; } } #endif #if wxOSX_USE_ATSU_TEXT ATSUFontID fontId = 0 ; if ( !setup && (cEvent.GetParameter<ATSUFontID>(kEventParamATSUFontID, &fontId) == noErr) ) { FMFontStyle fontStyle = cEvent.GetParameter<FMFontStyle>(kEventParamFMFontStyle); FMFontSize fontSize = cEvent.GetParameter<FMFontSize>(kEventParamFMFontSize); CFStringRef cfName = NULL; #if 1 FMFontFamily fontFamily = cEvent.GetParameter<FMFontFamily>(kEventParamFMFontFamily); ATSFontFamilyRef atsfontfamilyref = FMGetATSFontFamilyRefFromFontFamily( fontFamily ) ; OSStatus err = ATSFontFamilyGetName( atsfontfamilyref , kATSOptionFlagsDefault , &cfName ) ; if ( err != noErr ) { wxFAIL_MSG("ATSFontFamilyGetName failed"); } #else // we don't use the ATSU naming anymore ByteCount actualLength = 0; char *c = NULL; OSStatus err = ATSUFindFontName(fontId , kFontFamilyName, kFontUnicodePlatform, kFontNoScriptCode, kFontNoLanguageCode , 0 , NULL , &actualLength , NULL ); if ( err == noErr) { actualLength += 1 ; char *c = (char*)malloc( actualLength ); err = ATSUFindFontName(fontId, kFontFamilyName, kFontUnicodePlatform, kFontNoScriptCode, kFontNoLanguageCode, actualLength, c , NULL, NULL); cfName = CFStringCreateWithCharacters(NULL, (UniChar*) c, (actualLength-1) >> 1); } else { err = ATSUFindFontName(fontId , kFontFamilyName, kFontNoPlatformCode, kFontNoScriptCode, kFontNoLanguageCode , 0 , NULL , &actualLength , NULL ); if ( err == noErr ) { actualLength += 1 ; c = (char*)malloc(actualLength); err = ATSUFindFontName(fontId, kFontFamilyName, kFontNoPlatformCode, kFontNoScriptCode, kFontNoLanguageCode, actualLength, c , NULL, NULL); c[actualLength-1] = 0; cfName = CFStringCreateWithCString(NULL, c, kCFStringEncodingMacRoman ); } } if ( c!=NULL ) free(c); #endif if ( cfName!=NULL ) { fontdata.m_chosenFont.SetFaceName(wxCFStringRef(cfName).AsString(wxLocale::GetSystemEncoding())); fontdata.m_chosenFont.SetPointSize(fontSize); fontdata.m_chosenFont.SetStyle(fontStyle & italic ? wxFONTSTYLE_ITALIC : wxFONTSTYLE_NORMAL); fontdata.m_chosenFont.SetUnderlined((fontStyle & underline)!=0); fontdata.m_chosenFont.SetWeight(fontStyle & bold ? wxFONTWEIGHT_BOLD : wxFONTWEIGHT_NORMAL); } }
CFArrayRef _SCBondInterfaceCopyActive(void) { struct ifaddrs *ifap; struct ifaddrs *ifp; int s; CFMutableArrayRef bonds = NULL; if (getifaddrs(&ifap) == -1) { _SCErrorSet(errno); SCLog(TRUE, LOG_ERR, CFSTR("getifaddrs() failed: %s"), strerror(errno)); return NULL; } s = inet_dgram_socket(); if (s == -1) { _SCErrorSet(errno); goto done; } bonds = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); for (ifp = ifap; ifp != NULL; ifp = ifp->ifa_next) { SCBondInterfaceRef bond; CFStringRef bond_if; struct if_bond_status_req *ibsr_p; struct if_data *if_data; int int_val; CFNumberRef mode; CFMutableArrayRef members = NULL; if_data = (struct if_data *)ifp->ifa_data; if (if_data == NULL || ifp->ifa_addr->sa_family != AF_LINK || if_data->ifi_type != IFT_IEEE8023ADLAG) { continue; } ibsr_p = if_bond_status_req_copy(s, ifp->ifa_name); if (ibsr_p == NULL) { if (errno == EBUSY) { continue; } _SCErrorSet(errno); SCLog(TRUE, LOG_ERR, CFSTR("if_bond_status_req_copy(%s) failed: %s"), ifp->ifa_name, strerror(errno)); CFRelease(bonds); bonds = NULL; goto done; } // create the bond interface bond_if = CFStringCreateWithCString(NULL, ifp->ifa_name, kCFStringEncodingASCII); bond = (SCBondInterfaceRef)_SCBondInterfaceCreatePrivate(NULL, bond_if); CFRelease(bond_if); // set the mode int_val = ibsr_p->ibsr_mode; mode = CFNumberCreate(NULL, kCFNumberIntType, &int_val); assert(mode != NULL); _SCBondInterfaceSetMode(bond, mode); CFRelease(mode); // add member interfaces if (ibsr_p->ibsr_total > 0) { int i; struct if_bond_status * ibs_p; // iterate over each member interface ibs_p = (struct if_bond_status *)ibsr_p->ibsr_buffer; for (i = 0; i < ibsr_p->ibsr_total; i++) { CFStringRef member; member = CFStringCreateWithCString(NULL, ibs_p[i].ibs_if_name, kCFStringEncodingASCII); add_interface(&members, member); CFRelease(member); } } free(ibsr_p); if (members != NULL) { _SCBondInterfaceSetMemberInterfaces(bond, members); CFRelease(members); } // add bond CFArrayAppendValue(bonds, bond); CFRelease(bond); } done : if (s != -1) { (void) close(s); } freeifaddrs(ifap); return bonds; }
mailstream_low * mailstream_low_cfstream_open_voip_timeout(const char * hostname, int16_t port, int voip_enabled, time_t timeout) { #if HAVE_CFNETWORK mailstream_low * s; struct mailstream_cfstream_data * cfstream_data; CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFStringRef hostString; CFOptionFlags readFlags; CFOptionFlags writeFlags; int r; hostString = CFStringCreateWithCString(NULL, hostname, kCFStringEncodingUTF8); CFStreamCreatePairWithSocketToHost(NULL, hostString, port, &readStream, &writeStream); CFRelease(hostString); #if TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR if (voip_enabled) { CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP); CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP); } #endif #if !TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR CFDictionaryRef proxySettings = CFNetworkCopySystemProxySettings(); CFNumberRef nbEnabled = CFDictionaryGetValue(proxySettings, kCFNetworkProxiesSOCKSEnable); if (numberIntValue(nbEnabled)) { CFReadStreamSetProperty(readStream, kCFStreamPropertySOCKSProxy, proxySettings); CFWriteStreamSetProperty(writeStream, kCFStreamPropertySOCKSProxy, proxySettings); } CFRelease(proxySettings); #endif cfstream_data = cfstream_data_new(readStream, writeStream); s = mailstream_low_new(cfstream_data, mailstream_cfstream_driver); mailstream_low_set_timeout(s, timeout); //fprintf(stderr, "open %s %i -> %p\n", hostname, port, s); /* setup streams */ cfstream_data->streamContext.info = s; readFlags = kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered; writeFlags = kCFStreamEventOpenCompleted | kCFStreamEventCanAcceptBytes | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered; CFReadStreamSetClient(cfstream_data->readStream, readFlags, readStreamCallback, &cfstream_data->streamContext); CFWriteStreamSetClient(cfstream_data->writeStream, writeFlags, writeStreamCallback, &cfstream_data->streamContext); CFRelease(readStream); CFRelease(writeStream); readStream = NULL; writeStream = NULL; /* setup cancel */ cfstream_data->cancelContext.info = s; cfstream_data->cancelContext.perform = cancelPerform; cfstream_data->cancelSource = CFRunLoopSourceCreate(NULL, 0, &cfstream_data->cancelContext); r = low_open(s); if (r < 0) { mailstream_low_cfstream_close(s); return NULL; } return s; #else return NULL; #endif }
/* * Creates a vector of driver bundle info structures from the hot-plug driver * directory. * * Returns NULL on error and a pointer to an allocated HPDriver vector on * success. The caller must free the HPDriver with a call to * HPDriversRelease(). */ static HPDriverVector HPDriversGetFromDirectory(const char *driverBundlePath) { #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "Entering HPDriversGetFromDirectory: %s", driverBundlePath); #endif int readersNumber = 0; HPDriverVector bundleVector = NULL; CFArrayRef bundleArray; CFStringRef driverBundlePathString = CFStringCreateWithCString(kCFAllocatorDefault, driverBundlePath, kCFStringEncodingMacRoman); CFURLRef pluginUrl = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, driverBundlePathString, kCFURLPOSIXPathStyle, TRUE); CFRelease(driverBundlePathString); if (!pluginUrl) { Log1(PCSC_LOG_ERROR, "error getting plugin directory URL"); return NULL; } bundleArray = CFBundleCreateBundlesFromDirectory(kCFAllocatorDefault, pluginUrl, NULL); if (!bundleArray) { Log1(PCSC_LOG_ERROR, "error getting plugin directory bundles"); return NULL; } CFRelease(pluginUrl); size_t bundleArraySize = CFArrayGetCount(bundleArray); size_t i; /* get the number of readers (including aliases) */ for (i = 0; i < bundleArraySize; i++) { CFBundleRef currBundle = (CFBundleRef) CFArrayGetValueAtIndex(bundleArray, i); CFDictionaryRef dict = CFBundleGetInfoDictionary(currBundle); const void * blobValue = CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_MANUKEY_NAME)); if (!blobValue) { Log1(PCSC_LOG_ERROR, "error getting vendor ID from bundle"); return NULL; } if (CFGetTypeID(blobValue) == CFArrayGetTypeID()) { /* alias found, each reader count as 1 */ CFArrayRef propertyArray = blobValue; readersNumber += CFArrayGetCount(propertyArray); } else /* No alias, only one reader supported */ readersNumber++; } #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "Total of %d readers supported", readersNumber); #endif /* The last entry is an end marker (m_vendorId = 0) * see checks in HPDriversMatchUSBDevices:503 * and HPDriverVectorRelease:376 */ readersNumber++; bundleVector = calloc(readersNumber, sizeof(HPDriver)); if (!bundleVector) { Log1(PCSC_LOG_ERROR, "memory allocation failure"); return NULL; } HPDriver *driverBundle = bundleVector; for (i = 0; i < bundleArraySize; i++) { CFBundleRef currBundle = (CFBundleRef) CFArrayGetValueAtIndex(bundleArray, i); CFDictionaryRef dict = CFBundleGetInfoDictionary(currBundle); CFURLRef bundleUrl = CFBundleCopyBundleURL(currBundle); CFStringRef bundlePath = CFURLCopyPath(bundleUrl); driverBundle->m_libPath = strdup(CFStringGetCStringPtr(bundlePath, CFStringGetSystemEncoding())); const void * blobValue = CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_MANUKEY_NAME)); if (!blobValue) { Log1(PCSC_LOG_ERROR, "error getting vendor ID from bundle"); return bundleVector; } if (CFGetTypeID(blobValue) == CFArrayGetTypeID()) { CFArrayRef vendorArray = blobValue; CFArrayRef productArray; CFArrayRef friendlyNameArray; char *libPath = driverBundle->m_libPath; #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "Driver with aliases: %s", libPath); #endif /* get list of ProductID */ productArray = CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_PRODKEY_NAME)); if (!productArray) { Log1(PCSC_LOG_ERROR, "error getting product ID from bundle"); return bundleVector; } /* get list of FriendlyName */ friendlyNameArray = CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_NAMEKEY_NAME)); if (!friendlyNameArray) { Log1(PCSC_LOG_ERROR, "error getting product ID from bundle"); return bundleVector; } int reader_nb = CFArrayGetCount(vendorArray); if (reader_nb != CFArrayGetCount(productArray)) { Log3(PCSC_LOG_ERROR, "Malformed Info.plist: %d vendors and %ld products", reader_nb, CFArrayGetCount(productArray)); return bundleVector; } if (reader_nb != CFArrayGetCount(friendlyNameArray)) { Log3(PCSC_LOG_ERROR, "Malformed Info.plist: %d vendors and %ld friendlynames", reader_nb, CFArrayGetCount(friendlyNameArray)); return bundleVector; } int j; for (j=0; j<reader_nb; j++) { CFStringRef strValue = CFArrayGetValueAtIndex(vendorArray, j); driverBundle->m_vendorId = strtoul(CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()), NULL, 16); strValue = CFArrayGetValueAtIndex(productArray, j); driverBundle->m_productId = strtoul(CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()), NULL, 16); strValue = CFArrayGetValueAtIndex(friendlyNameArray, j); const char *cstr = CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()); driverBundle->m_friendlyName = strdup(cstr); if (!driverBundle->m_libPath) driverBundle->m_libPath = strdup(libPath); #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "VendorID: 0x%04X", driverBundle->m_vendorId); Log2(PCSC_LOG_DEBUG, "ProductID: 0x%04X", driverBundle->m_productId); Log2(PCSC_LOG_DEBUG, "Friendly name: %s", driverBundle->m_friendlyName); Log2(PCSC_LOG_DEBUG, "Driver: %s", driverBundle->m_libPath); #endif /* go to next bundle in the vector */ driverBundle++; } } else { CFStringRef strValue = blobValue; #ifdef DEBUG_HOTPLUG Log3(PCSC_LOG_DEBUG, "Driver without alias: %s %s", driverBundle->m_friendlyName, driverBundle->m_libPath); #endif driverBundle->m_vendorId = strtoul(CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()), NULL, 16); strValue = (CFStringRef) CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_PRODKEY_NAME)); if (!strValue) { Log1(PCSC_LOG_ERROR, "error getting product ID from bundle"); return bundleVector; } driverBundle->m_productId = strtoul(CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()), NULL, 16); strValue = (CFStringRef) CFDictionaryGetValue(dict, CFSTR(PCSCLITE_HP_NAMEKEY_NAME)); if (!strValue) { Log1(PCSC_LOG_ERROR, "error getting product friendly name from bundle"); driverBundle->m_friendlyName = strdup("unnamed device"); } else { const char *cstr = CFStringGetCStringPtr(strValue, CFStringGetSystemEncoding()); driverBundle->m_friendlyName = strdup(cstr); } #ifdef DEBUG_HOTPLUG Log2(PCSC_LOG_DEBUG, "VendorID: 0x%04X", driverBundle->m_vendorId); Log2(PCSC_LOG_DEBUG, "ProductID: 0x%04X", driverBundle->m_productId); Log2(PCSC_LOG_DEBUG, "Friendly name: %s", driverBundle->m_friendlyName); Log2(PCSC_LOG_DEBUG, "Driver: %s", driverBundle->m_libPath); #endif /* go to next bundle in the vector */ driverBundle++; } } CFRelease(bundleArray); return bundleVector; }
void sdl_osd_interface::init(running_machine &machine) { // call our parent osd_interface::init(machine); sdl_options &options = downcast<sdl_options &>(machine.options()); const char *stemp; // determine if we are benchmarking, and adjust options appropriately int bench = options.bench(); astring error_string; if (bench > 0) { options.set_value(OPTION_THROTTLE, false, OPTION_PRIORITY_MAXIMUM, error_string); options.set_value(OPTION_SOUND, false, OPTION_PRIORITY_MAXIMUM, error_string); options.set_value(SDLOPTION_VIDEO, "none", OPTION_PRIORITY_MAXIMUM, error_string); options.set_value(OPTION_SECONDS_TO_RUN, bench, OPTION_PRIORITY_MAXIMUM, error_string); assert(!error_string); } // Some driver options - must be before audio init! stemp = options.audio_driver(); if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) != 0) { mame_printf_verbose("Setting SDL audiodriver '%s' ...\n", stemp); osd_setenv(SDLENV_AUDIODRIVER, stemp, 1); } stemp = options.video_driver(); if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) != 0) { mame_printf_verbose("Setting SDL videodriver '%s' ...\n", stemp); osd_setenv(SDLENV_VIDEODRIVER, stemp, 1); } if (SDL_VERSION_ATLEAST(1,3,0)) { stemp = options.render_driver(); if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) != 0) { mame_printf_verbose("Setting SDL renderdriver '%s' ...\n", stemp); osd_setenv(SDLENV_RENDERDRIVER, stemp, 1); } } /* Set the SDL environment variable for drivers wanting to load the * lib at startup. */ #if USE_OPENGL /* FIXME: move lib loading code from drawogl.c here */ stemp = options.gl_lib(); if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) != 0) { osd_setenv("SDL_VIDEO_GL_DRIVER", stemp, 1); mame_printf_verbose("Setting SDL_VIDEO_GL_DRIVER = '%s' ...\n", stemp); } #endif /* get number of processors */ stemp = options.numprocessors(); sdl_num_processors = 0; if (strcmp(stemp, "auto") != 0) { sdl_num_processors = atoi(stemp); if (sdl_num_processors < 1) { mame_printf_warning("Warning: numprocessors < 1 doesn't make much sense. Assuming auto ...\n"); sdl_num_processors = 0; } } /* Initialize SDL */ if (!SDLMAME_INIT_IN_WORKER_THREAD) { #if (SDL_VERSION_ATLEAST(1,3,0)) if (SDL_InitSubSystem(SDL_INIT_TIMER|SDL_INIT_AUDIO| SDL_INIT_VIDEO| SDL_INIT_JOYSTICK|SDL_INIT_NOPARACHUTE)) { #else if (SDL_Init(SDL_INIT_TIMER|SDL_INIT_AUDIO| SDL_INIT_VIDEO| SDL_INIT_JOYSTICK|SDL_INIT_NOPARACHUTE)) { #endif mame_printf_error("Could not initialize SDL %s\n", SDL_GetError()); exit(-1); } osd_sdl_info(); } // must be before sdlvideo_init! machine.add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(FUNC(osd_exit), &machine)); defines_verbose(); if (!SDLMAME_HAS_DEBUGGER) if (machine.debug_flags & DEBUG_FLAG_OSD_ENABLED) { mame_printf_error("sdlmame: -debug not supported on X11-less builds\n\n"); osd_exit(machine); exit(-1); } if (sdlvideo_init(machine)) { osd_exit(machine); mame_printf_error("sdlvideo_init: Initialization failed!\n\n\n"); fflush(stderr); fflush(stdout); exit(-1); } sdlinput_init(machine); sdlaudio_init(machine); sdloutput_init(machine); #ifdef SDLMAME_NETWORK sdlnetdev_init(machine); #endif if (options.oslog()) machine.add_logerror_callback(output_oslog); /* now setup watchdog */ int watchdog_timeout = options.watchdog(); int str = options.seconds_to_run(); /* only enable watchdog if seconds_to_run is enabled *and* relatively short (time taken from ui.c) */ if ((watchdog_timeout != 0) && (str > 0) && (str < 60*5 )) { m_watchdog = auto_alloc(machine, watchdog); m_watchdog->setTimeout(watchdog_timeout); } #if (SDL_VERSION_ATLEAST(1,3,0)) SDL_EventState(SDL_TEXTINPUT, SDL_TRUE); #else SDL_EnableUNICODE(SDL_TRUE); #endif } #ifdef SDLMAME_UNIX #define POINT_SIZE 144.0 #ifdef SDLMAME_MACOSX #define EXTRA_HEIGHT 1.0 #define EXTRA_WIDTH 1.15 //------------------------------------------------- // font_open - attempt to "open" a handle to the // font with the given name //------------------------------------------------- osd_font sdl_osd_interface::font_open(const char *_name, int &height) { CFStringRef font_name = NULL; CTFontRef ct_font = NULL; CTFontDescriptorRef font_descriptor; CGAffineTransform affine_transform = CGAffineTransformIdentity; astring name(_name); if (name == "default") { name = "LucidaGrande"; } /* handle bdf fonts in the core */ if (name.len() > 4) if (name.toupper().substr(name.len()-4,4) == ".BDF" ) return NULL; font_name = CFStringCreateWithCString( NULL, _name, kCFStringEncodingUTF8 ); if( font_name != NULL ) { font_descriptor = CTFontDescriptorCreateWithNameAndSize( font_name, POINT_SIZE ); if( font_descriptor != NULL ) { ct_font = CTFontCreateWithFontDescriptor( font_descriptor, POINT_SIZE, &affine_transform ); CFRelease( font_descriptor ); } } CFRelease( font_name ); if (!ct_font) { printf("WARNING: Couldn't find/open font %s, using MAME default\n", name.cstr()); return NULL; } CFStringRef real_name = CTFontCopyPostScriptName( ct_font ); char real_name_c_string[255]; CFStringGetCString ( real_name, real_name_c_string, 255, kCFStringEncodingUTF8 ); mame_printf_verbose("Matching font: %s\n", real_name_c_string); CFRelease( real_name ); CGFloat line_height = 0.0; line_height += CTFontGetAscent(ct_font); line_height += CTFontGetDescent(ct_font); line_height += CTFontGetLeading(ct_font); height = ceilf(line_height * EXTRA_HEIGHT); return (osd_font)ct_font; }
bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, const char *str) { bool result = false; #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. */ strecpy(settings->small_font, name, lastof(settings->small_font)); strecpy(settings->medium_font, name, lastof(settings->medium_font)); strecpy(settings->large_font, name, lastof(settings->large_font)); 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. */ /* Extract a UniChar represenation of the sample string. */ CFStringRef cf_str = CFStringCreateWithCString(kCFAllocatorDefault, str, 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); /* Create a text layout object from the sample string using the text style. */ UniCharCount run_len = kATSUToTextEnd; ATSUTextLayout text_layout; ATSUCreateTextLayoutWithTextPtr(string, kATSUFromTextBeginning, kATSUToTextEnd, str_len, 1, &run_len, &style, &text_layout); /* Try to match a font for the sample text. ATSUMatchFontsToText stops after * it finds the first continous character run not renderable with the currently * selected font starting at offset. The matching needs to be repeated until * the end of the string is reached to make sure the fallback font matches for * all characters in the string and not only the first run. */ UniCharArrayOffset offset = kATSUFromTextBeginning; OSStatus os_err; do { ATSUFontID font; UniCharCount run_len; os_err = ATSUMatchFontsToText(text_layout, offset, kATSUToTextEnd, &font, &offset, &run_len); if (os_err == kATSUFontsMatched) { /* Found a better fallback font. Update the text layout * object with the new font. */ ATSUAttributeTag tag = kATSUFontTag; ByteCount size = sizeof(font); ATSUAttributeValuePtr val = &font; ATSUSetAttributes(style, 1, &tag, &size, &val); offset += run_len; } /* Exit if the end of the string is reached or some other error occured. */ } while (os_err == kATSUFontsMatched && offset < (UniCharArrayOffset)str_len); if (os_err == noErr || os_err == kATSUFontsMatched) { /* ATSUMatchFontsToText exited normally. Extract font * out of the text layout object. */ ATSUFontID font; ByteCount act_len; ATSUGetAttribute(style, kATSUFontTag, sizeof(font), &font, &act_len); /* Get unique font name. The result is not a c-string, we have * to leave space for a \0 and terminate it ourselves. */ char name[128]; ATSUFindFontName(font, kFontUniqueName, kFontNoPlatformCode, kFontNoScriptCode, kFontNoLanguageCode, 127, name, &act_len, NULL); name[act_len > 127 ? 127 : act_len] = '\0'; /* Save Result. */ strecpy(settings->small_font, name, lastof(settings->small_font)); strecpy(settings->medium_font, name, lastof(settings->medium_font)); strecpy(settings->large_font, name, lastof(settings->large_font)); DEBUG(freetype, 2, "ATSUI-Font for %s: %s", language_isocode, name); result = true; } ATSUDisposeTextLayout(text_layout); ATSUDisposeStyle(style); CFRelease(cf_str); #endif } if (result && strncmp(settings->medium_font, "Geeza Pro", 9) == 0) { /* The font 'Geeza Pro' is often found for arabic characters, but * it has the 'tiny' problem of not having any latin characters. * 'Arial Unicode MS' on the other hand has arabic and latin glyphs, * but seems to 'forget' to inform the OS about this fact. Manually * substitute the latter for the former if it is loadable. */ bool ft_init = _library != NULL; FT_Face face; /* Init FreeType if needed. */ if ((ft_init || FT_Init_FreeType(&_library) == FT_Err_Ok) && GetFontByFaceName("Arial Unicode MS", &face) == FT_Err_Ok) { FT_Done_Face(face); strecpy(settings->small_font, "Arial Unicode MS", lastof(settings->small_font)); strecpy(settings->medium_font, "Arial Unicode MS", lastof(settings->medium_font)); strecpy(settings->large_font, "Arial Unicode MS", lastof(settings->large_font)); DEBUG(freetype, 1, "Replacing font 'Geeza Pro' with 'Arial Unicode MS'"); } if (!ft_init) { /* Uninit FreeType if we did the init. */ FT_Done_FreeType(_library); _library = NULL; } } return result; }
/* * Given a mime-type, return the file extension if there is one * * Returns: 1 on success, 0 on failure */ int mime_get_os_ext_from_mimetype(char *mime_type, char *file_ext, int file_ext_len) { #ifdef _WINDOWS int ret; LPTSTR x, mime_type_lpt, file_ext_lpt; mime_type_lpt = utf8_to_lptstr(mime_type); if(mime_type_lpt){ if(file_ext){ file_ext_lpt = (LPTSTR) fs_get(file_ext_len * sizeof(TCHAR)); file_ext_lpt[0] = '\0'; } else file_ext_lpt = NULL; } ret = mswin_reg_mime_ext(mime_type_lpt, file_ext_lpt, (size_t) file_ext_len); /* convert answer back to UTF-8 */ if(ret && file_ext_lpt && file_ext){ char *u; u = lptstr_to_utf8(file_ext_lpt); if(u){ strncpy(file_ext, u, file_ext_len); file_ext[file_ext_len-1] = '\0'; fs_give((void **) &u); } } if(mime_type_lpt) fs_give((void **) &mime_type_lpt); if(file_ext_lpt) fs_give((void **) &file_ext_lpt); return ret; #elif OSX_TARGET if(!mime_os_specific_access()) return(0); #ifdef AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER CFStringRef mime_ref = NULL, type_id_ref = NULL, ext_ref = NULL; if(!mime_type || !*mime_type) return 0; /* This for if we built on OS X >= 10.3 but run on < 10.3 */ if(&UTTypeCreatePreferredIdentifierForTag == NULL) return 0; if((mime_ref = CFStringCreateWithCString(NULL, mime_type, kCFStringEncodingASCII)) == NULL) return 0; if((type_id_ref = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mime_ref, NULL)) == NULL) return 0; if((ext_ref = UTTypeCopyPreferredTagWithClass(type_id_ref, kUTTagClassFilenameExtension)) == NULL) return 0; if((CFStringGetCString(ext_ref, file_ext, (CFIndex)file_ext_len - 1, kCFStringEncodingASCII)) == false) return 0; file_ext[file_ext_len - 1] = '\0'; return 1; #else return 0; #endif /* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER */ #else return 0; #endif /* OSX_TARGET */ }
// ---------------------------------------------------------------------------- // process_prefs // ---------------------------------------------------------------------------- int ipsec_process_prefs(struct vpn_params *params) { char *errstr, c; CFStringRef string; if (ipsec_conf) { CFRelease(ipsec_conf); ipsec_conf = NULL; } ipsec_conf = (CFMutableDictionaryRef)CFDictionaryGetValue(params->serverRef, kRASEntIPSec); if (ipsec_conf == NULL) { vpnlog(LOG_ERR, "IPSec plugin: IPSec dictionary not present\n"); goto fail; } ipsec_conf = CFDictionaryCreateMutableCopy(NULL, 0, ipsec_conf); remoteaddress[0] = 0; string = CFDictionaryGetValue(ipsec_conf, kRASPropIPSecRemoteAddress); if (isString(string)) CFStringGetCString(string, remoteaddress, sizeof(remoteaddress), kCFStringEncodingUTF8); if (inet_aton(remoteaddress, &peer_address) == 0) { if (pipe(resolverfds) < 0) { vpnlog(LOG_ERR, "IPSec plugin: failed to create pipe for gethostbyname\n"); goto fail; } if (pthread_create(&resolverthread, NULL, ipsec_resolver_thread, NULL)) { vpnlog(LOG_ERR, "IPSec plugin: failed to create thread for gethostbyname...\n"); close(resolverfds[0]); close(resolverfds[1]); goto fail; } while (read(resolverfds[0], &c, 1) != 1) { if (got_terminate()) { pthread_cancel(resolverthread); break; } } close(resolverfds[0]); close(resolverfds[1]); if (got_terminate()) goto fail; if (c) { vpnlog(LOG_ERR, "IPSec plugin: Host '%s' not found...\n", remoteaddress); goto fail; } string = CFStringCreateWithCString(0, addr2ascii(AF_INET, &peer_address, sizeof(peer_address), 0), kCFStringEncodingASCII); CFDictionarySetValue(ipsec_conf, kRASPropIPSecRemoteAddress, string); CFRelease(string); } // verify the dictionary if (IPSecValidateConfiguration(ipsec_conf, &errstr)) { vpnlog(LOG_ERR, "IPSec plugin: Incorrect preferences (%s)\n", errstr); goto fail; } return 0; fail: if (ipsec_conf) { CFRelease(ipsec_conf); ipsec_conf = NULL; } return -1; }
const char * /* O - Language ID */ _cupsAppleLanguage(const char *locale, /* I - Locale ID */ char *language,/* I - Language ID buffer */ size_t langsize) /* I - Size of language ID buffer */ { int i; /* Looping var */ CFStringRef localeid, /* CF locale identifier */ langid; /* CF language identifier */ /* * Copy the locale name and convert, as needed, to the Apple-specific * locale identifier... */ switch (strlen(locale)) { default : /* * Invalid locale... */ strlcpy(language, "en", langsize); break; case 2 : strlcpy(language, locale, langsize); break; case 5 : strlcpy(language, locale, langsize); if (language[2] == '-') { /* * Convert ll-cc to ll_CC... */ language[2] = '_'; language[3] = toupper(language[3] & 255); language[4] = toupper(language[4] & 255); } break; } for (i = 0; i < (int)(sizeof(apple_language_locale) / sizeof(apple_language_locale[0])); i ++) if (!strcmp(locale, apple_language_locale[i].locale)) { strlcpy(language, apple_language_locale[i].language, sizeof(language)); break; } /* * Attempt to map the locale ID to a language ID... */ if ((localeid = CFStringCreateWithCString(kCFAllocatorDefault, language, kCFStringEncodingASCII)) != NULL) { if ((langid = CFLocaleCreateCanonicalLanguageIdentifierFromString( kCFAllocatorDefault, localeid)) != NULL) { CFStringGetCString(langid, language, langsize, kCFStringEncodingASCII); CFRelease(langid); } CFRelease(localeid); } /* * Return what we got... */ return (language); }
// --------------------------------------------------------------------------- // // ------------ void bXMapSHPExport::dump(char* path) { _bTrace_("bXMapSHPExport::dump",true); extype et; bArray arr(sizeof(extype),_gapp->typesMgr()->count()); bArray sel(*(_gapp->selMgr()->elements())); int status; char tname[FILENAME_MAX]; char name[FILENAME_MAX]; CFStringRef cfs; //double reso=_gapp->document()->dist_resolution(); double reso=GetRawPrecisionCoef(_gapp); d2dvertex origin=_gapp->document()->get_origin(); int asrid=_gapp->document()->srid(); int tsrid=_gapp->document()->srid(); bGenericExt* fexp=_gapp->xmapMgr()->find('FExp'); if(fexp) { fexp_prm prm= {0,NULL,NULL,tsrid}; fexp->process(kExtProcessCallGetData,&prm); tsrid=prm.srid; } for(int i=1; i<=arr.count(); i++) { et.tp=_gapp->typesMgr()->get(i); if(TypeIsExportProtected(et.tp)) { _tw_("Can't process export protected type"); continue; } if ( (et.tp->nb_sel()>0) ||( (sel.count()==0) && (et.tp->nb_live()>0) )) { status=et.tp->kind(); et.tp->name(tname); cfs=CFStringCreateWithCString(kCFAllocatorDefault,tname,kCFStringEncodingMacRoman); CFStringGetCString(cfs,tname,FILENAME_MAX,kCFStringEncodingUTF8); CFRelease(cfs); sprintf(name,"%s.shp",tname); et.shp=wtbl_falloc( kTableShape, path, name, true, &reso, &origin.x, &origin.y, &tsrid, &asrid, &status); status=0; sprintf(name,"%s.dbf",tname); et.dbf=wtbl_falloc( kTableDBF, path, name, true, &reso, &origin.x, &origin.y, &tsrid, &asrid, &status); if((et.shp==NULL)||(et.dbf==NULL)) { et.tp=NULL; } else { et.flds=new bArray(sizeof(fieldindex)); field_create(et.tp,et.dbf,et.flds); } } else { et.tp=NULL; et.shp=NULL; et.dbf=NULL; et.flds=NULL; } arr.put(i,&et); } if(sel.count()>0) { objs_dump(arr,sel); } else { objs_dump(arr); } for(int i=1; i<=arr.count(); i++) { arr.get(i,&et); if(et.shp) { wtbl_free(et.shp); } if(et.dbf) { wtbl_free(et.dbf); } if(et.flds) { fieldindex fx; for(int j=1; j<=et.flds->count(); j++) { et.flds->get(j,&fx); if(fx.val) { free(fx.val); } } delete et.flds; } } }