OSStatus DoSetPermissions(COMMAND_PROC_ARGUMENTS) { #pragma unused (auth) #pragma unused (userData) 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 CFDictionaryRef CFDictionaryRef infos = CFDictionaryGetValue(request, CFSTR(kInfos)) ; assert(infos != NULL) ; assert(CFGetTypeID(infos) == CFDictionaryGetTypeID()) ; CFIndex nPaths = CFDictionaryGetCount(infos) ; CFMutableDictionaryRef errorDescriptions = CFDictionaryCreateMutable( NULL, nPaths, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks ) ; CFMutableDictionaryRef originalModes = CFDictionaryCreateMutable( NULL, nPaths, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks ) ; CFIndex i ; int nSucceeded = 0 ; const void ** paths = (const void **)malloc( nPaths * sizeof(const void *)) ; const void ** modeNums = (const void **)malloc( nPaths * sizeof(const void *)) ; if ((paths != NULL) && (modeNums != NULL)) { CFDictionaryGetKeysAndValues( infos, paths, modeNums ) ; for (i=0; i<nPaths; i++) { // Process each path Boolean ok = true ; int retval ; // Get path, assert that it's a string anc convert to a C string CFStringRef path = paths[i] ; assert(CFGetTypeID(path) == CFStringGetTypeID()) ; char pathC[MAX_PATH_CHARS] ; if (ok) { ok = CFStringGetCString( path, pathC, MAX_PATH_CHARS, kCFStringEncodingASCII ) ; if (!ok) { CFDictionaryAddValue(errorDescriptions, path, CFSTR("Name too long")) ; } } // Read current permissions for path, wrap as CFNumber and add to results dictionary if (ok) { struct stat rawStats ; retval = stat(pathC, &rawStats) ; ok = (retval == 0) ; if (ok) { // rawStats.st_mode is of type mode_t which is an unsigned short. // Unfortunately, the available kCFNumberTypes don't have unsigned short. // And I have found that if I give CFNumberCreate an unsigned short and // tell it that it's an available kCFNumberType, which has more bits, // the undefined bits get encoded as garbage, changing the value. // First assigning the unsigned short to an int fixes it. int originalMode = rawStats.st_mode ; CFNumberRef fileModeCF = CFNumberCreate( NULL, kCFNumberIntType, &originalMode ) ; CFDictionaryAddValue( originalModes, path, fileModeCF) ; CFRelease(fileModeCF) ; } else { CFStringRef errString = CFStringCreateWithFormat( NULL, NULL, CFSTR("stat64 failed. errno: %d"), errno ) ; CFDictionaryAddValue(errorDescriptions, path, errString) ; CFQRelease(errString) ; ok = false ; } // Get new fileMode from Info, assert that it's a CFNumberRef and // unwrap object to get value mode_t fileModeValue ; if (ok) { CFNumberRef fileModeCF = modeNums[i] ; assert(fileModeCF != NULL) ; assert(CFGetTypeID(fileModeCF) == CFNumberGetTypeID()) ; ok = CFNumberGetValue( fileModeCF, kCFNumberIntType, &fileModeValue ) ; } // Set the new file mode if (ok) { retval = chmod(pathC, fileModeValue) ; asl_log( asl, aslMsg, ASL_LEVEL_DEBUG, "chmod returned %d setting %o for %s", retval, fileModeValue, pathC ) ; if (retval < 0) { CFStringRef errString = CFStringCreateWithFormat( NULL, NULL, CFSTR("Setting Permissions failed with errno=%d"), errno ) ; CFDictionaryAddValue(errorDescriptions, path, errString) ; CFQRelease(errString) ; } else { nSucceeded++ ; } } } } } // Add the original modes to the response CFDictionaryAddValue(response, CFSTR(kInfos), originalModes) ; CFRelease(originalModes) ; free(paths) ; free(modeNums) ; // Add the errorDescriptions to the response too CFDictionaryAddValue(response, CFSTR(kErrorDescriptions), errorDescriptions) ; CFRelease(errorDescriptions) ; asl_log( asl, aslMsg, ASL_LEVEL_DEBUG, "DoSetPermissions succeeded setting %d/%d requested paths", nSucceeded, (int)nPaths ) ; // Return the number of paths on which setting permissions failed retval = (OSStatus)(nPaths - nSucceeded) ; 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); const 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; }
static void vprintf_stderr_common(const char* format, va_list args) { #if USE(CF) && !OS(WINDOWS) if (strstr(format, "%@")) { CFStringRef cfFormat = CFStringCreateWithCString(NULL, format, kCFStringEncodingUTF8); #if COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wformat-nonliteral" #endif CFStringRef str = CFStringCreateWithFormatAndArguments(NULL, NULL, cfFormat, args); #if COMPILER(CLANG) #pragma clang diagnostic pop #endif CFIndex length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char* buffer = (char*)malloc(length + 1); CFStringGetCString(str, buffer, length, kCFStringEncodingUTF8); #if USE(APPLE_SYSTEM_LOG) asl_log(0, 0, ASL_LEVEL_NOTICE, "%s", buffer); #endif fputs(buffer, stderr); free(buffer); CFRelease(str); CFRelease(cfFormat); return; } #if USE(APPLE_SYSTEM_LOG) va_list copyOfArgs; va_copy(copyOfArgs, args); asl_vlog(0, 0, ASL_LEVEL_NOTICE, format, copyOfArgs); va_end(copyOfArgs); #endif // Fall through to write to stderr in the same manner as other platforms. #elif PLATFORM(BLACKBERRY) BBLOGV(BlackBerry::Platform::LogLevelCritical, format, args); #elif HAVE(ISDEBUGGERPRESENT) if (IsDebuggerPresent()) { size_t size = 1024; do { char* buffer = (char*)malloc(size); if (buffer == NULL) break; if (_vsnprintf(buffer, size, format, args) != -1) { #if OS(WINCE) // WinCE only supports wide chars wchar_t* wideBuffer = (wchar_t*)malloc(size * sizeof(wchar_t)); if (wideBuffer == NULL) break; for (unsigned int i = 0; i < size; ++i) { if (!(wideBuffer[i] = buffer[i])) break; } OutputDebugStringW(wideBuffer); free(wideBuffer); #else OutputDebugStringA(buffer); #endif free(buffer); break; } free(buffer); size *= 2; } while (size > 1024); } #endif #if !PLATFORM(BLACKBERRY) vfprintf(stderr, format, args); #endif }
void fill_pathname_application_path(char *s, size_t len) { size_t i; #ifdef __APPLE__ CFBundleRef bundle = CFBundleGetMainBundle(); #endif #ifdef _WIN32 DWORD ret; wchar_t ws[PATH_MAX_LENGTH] = {0}; #endif #ifdef __HAIKU__ image_info info; int32_t cookie = 0; #endif (void)i; if (!len) return; #ifdef _WIN32 ret = GetModuleFileName(GetModuleHandle(NULL), s, len - 1); s[ret] = '\0'; #elif defined(__APPLE__) if (bundle) { CFURLRef bundle_url = CFBundleCopyBundleURL(bundle); CFStringRef bundle_path = CFURLCopyPath(bundle_url); CFStringGetCString(bundle_path, s, len, kCFStringEncodingUTF8); CFRelease(bundle_path); CFRelease(bundle_url); retro_assert(strlcat(s, "nobin", len) < len); return; } #elif defined(__HAIKU__) while (get_next_image_info(0, &cookie, &info) == B_OK) { if (info.type == B_APP_IMAGE) { strlcpy(s, info.name, len); return; } } #else { pid_t pid; static const char *exts[] = { "exe", "file", "path/a.out" }; char link_path[255]; link_path[0] = *s = '\0'; pid = getpid(); /* Linux, BSD and Solaris paths. Not standardized. */ for (i = 0; i < ARRAY_SIZE(exts); i++) { ssize_t ret; snprintf(link_path, sizeof(link_path), "/proc/%u/%s", (unsigned)pid, exts[i]); ret = readlink(link_path, s, len - 1); if (ret >= 0) { s[ret] = '\0'; return; } } } RARCH_ERR("Cannot resolve application path! This should not happen.\n"); #endif }
// Returns a pointer to an array of strings with the device names std::vector<std::string> cdio_get_devices() { io_object_t next_media; mach_port_t master_port; kern_return_t kern_result; io_iterator_t media_iterator; CFMutableDictionaryRef classes_to_match; std::vector<std::string> drives; kern_result = IOMasterPort(MACH_PORT_NULL, &master_port); if (kern_result != KERN_SUCCESS) return drives; classes_to_match = IOServiceMatching(kIOCDMediaClass); if (classes_to_match == nullptr) return drives; CFDictionarySetValue(classes_to_match, CFSTR(kIOMediaEjectableKey), kCFBooleanTrue); kern_result = IOServiceGetMatchingServices(master_port, classes_to_match, &media_iterator); if (kern_result != KERN_SUCCESS) return drives; next_media = IOIteratorNext(media_iterator); if (next_media != 0) { CFTypeRef str_bsd_path; do { str_bsd_path = IORegistryEntryCreateCFProperty(next_media, CFSTR(kIOBSDNameKey), kCFAllocatorDefault, 0); if (str_bsd_path == nullptr) { IOObjectRelease(next_media); continue; } if (CFGetTypeID(str_bsd_path) == CFStringGetTypeID()) { size_t buf_size = CFStringGetLength((CFStringRef)str_bsd_path) * 4 + 1; char* buf = new char[buf_size]; if (CFStringGetCString((CFStringRef)str_bsd_path, buf, buf_size, kCFStringEncodingUTF8)) { // Below, by appending 'r' to the BSD node name, we indicate // a raw disk. Raw disks receive I/O requests directly and // don't go through a buffer cache. drives.push_back(std::string(_PATH_DEV "r") + buf); } delete[] buf; } CFRelease(str_bsd_path); IOObjectRelease(next_media); } while ((next_media = IOIteratorNext(media_iterator)) != 0); } IOObjectRelease(media_iterator); return drives; }
nuiHTTPResponse* nuiHTTPRequest::SendRequest() { char* pUrl = mUrl.Export(); CFStringRef originalURLString = CFStringCreateWithCString(kCFAllocatorDefault, pUrl, kCFStringEncodingUTF8); CFStringRef preprocessedString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, originalURLString, CFSTR(""), kCFStringEncodingUTF8); CFStringRef urlString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, preprocessedString, NULL, NULL, kCFStringEncodingUTF8); free(pUrl); CFURLRef url = CFURLCreateWithString(kCFAllocatorDefault, urlString, NULL); CFRelease(urlString); char* pMeth = mMethod.Export(); CFStringRef method = CFStringCreateWithCString(kCFAllocatorDefault, pMeth, kCFStringEncodingUTF8); free(pMeth); CFHTTPMessageRef req = CFHTTPMessageCreateRequest(kCFAllocatorDefault, method, url, kCFHTTPVersion1_1); CFStringRef userAgentField = CFSTR("User-Agent"); CFStringRef userAgentName = CFSTR("nuiHTTP/2.0"); CFHTTPMessageSetHeaderFieldValue(req, userAgentField, userAgentName); CFRelease(userAgentField); CFRelease(userAgentName); nuiHTTPHeaderMap::const_iterator end = mHeaders.end(); for (nuiHTTPHeaderMap::const_iterator it = mHeaders.begin(); it != end; ++it) { char* pName = it->first.Export(); char* pVal = it->second.Export(); CFStringRef fieldName = CFStringCreateWithCString(kCFAllocatorDefault, pName, kCFStringEncodingUTF8); CFStringRef fieldValue = CFStringCreateWithCString(kCFAllocatorDefault, pVal, kCFStringEncodingUTF8); CFHTTPMessageSetHeaderFieldValue(req, fieldName, fieldValue); CFRelease(fieldName); CFRelease(fieldValue); delete pName; delete pVal; } CFDataRef body = NULL; if (mBody.size()) { body = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, (UInt8*)&mBody[0], mBody.size(), kCFAllocatorNull); CFHTTPMessageSetBody(req, body); } CFReadStreamRef readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, req); CFReadStreamOpen(readStream); std::vector<char> buf; CFIndex pos = 0; CFIndex size = 0; bool cont = true; do { buf.resize(pos + 1024); size = CFReadStreamRead(readStream, (UInt8*)&buf[pos], 1024); if (size == -1) { return NULL; } else if (size == 0) { if (CFReadStreamGetStatus(readStream) == kCFStreamStatusAtEnd) cont = false; else nglThread::MsSleep(10); } pos += size; } while (cont); CFHTTPMessageRef responseHeader = (CFHTTPMessageRef)CFReadStreamCopyProperty(readStream, kCFStreamPropertyHTTPResponseHeader); CFStringRef statusLine = CFHTTPMessageCopyResponseStatusLine(responseHeader); CFIndex strSize = CFStringGetLength(statusLine)+1; char* pStatus = new char[strSize]; CFStringGetCString(statusLine, pStatus, strSize, kCFStringEncodingUTF8); nglString status(pStatus); UInt32 statusCode = CFHTTPMessageGetResponseStatusCode(responseHeader); nuiHTTPResponse* pResponse = new nuiHTTPResponse(statusCode, status); pResponse->SetBody(&buf[0], pos); delete[] pStatus; CFDictionaryRef dict = CFHTTPMessageCopyAllHeaderFields(responseHeader); CFIndex valueCount = CFDictionaryGetCount(dict); const CFStringRef* pNames = new CFStringRef[valueCount]; const CFStringRef* pValues = new CFStringRef[valueCount]; CFDictionaryGetKeysAndValues(dict, (const void**)pNames, (const void**)pValues); for (CFIndex i = 0; i< valueCount; i++) { strSize = CFStringGetLength(pNames[i])+1; char* pName = new char[strSize]; CFStringGetCString(pNames[i], pName, strSize, kCFStringEncodingUTF8); strSize = CFStringGetLength(pValues[i])+1; char* pVal = new char[strSize]; CFStringGetCString(pValues[i], pVal, strSize, kCFStringEncodingUTF8); nglString name(pName); nglString val(pVal); pResponse->AddHeader(name, val); delete[] pName; delete[] pVal; } delete[] pNames; delete[] pValues; CFRelease(responseHeader); CFRelease(url); CFRelease(method); CFRelease(req); CFRelease(readStream); CFRelease(dict); CFRelease(statusLine); if (body) CFRelease(body); return pResponse; }
// utility routine to dump element info void HIDDumpElementInfo(IOHIDElementRef inIOHIDElementRef) { if (inIOHIDElementRef) { printf(" Element: %p = { ", inIOHIDElementRef); #if false IOHIDDeviceRef tIOHIDDeviceRef = IOHIDElementGetDevice(inIOHIDElementRef); printf("Device: %p, ", tIOHIDDeviceRef); #endif // if 0 IOHIDElementRef parentIOHIDElementRef = IOHIDElementGetParent(inIOHIDElementRef); printf("parent: %p, ", parentIOHIDElementRef); #if false CFArrayRef childrenCFArrayRef = IOHIDElementGetChildren(inIOHIDElementRef); printf("children: %p: { ", childrenCFArrayRef); fflush(stdout); CFShow(childrenCFArrayRef); fflush(stdout); printf(" }, "); #endif // if 0 IOHIDElementCookie tIOHIDElementCookie = IOHIDElementGetCookie(inIOHIDElementRef); printf("cookie: 0x%08lX, ", (long unsigned int) tIOHIDElementCookie); IOHIDElementType tIOHIDElementType = IOHIDElementGetType(inIOHIDElementRef); switch (tIOHIDElementType) { case kIOHIDElementTypeInput_Misc: { printf("type: Misc, "); break; } case kIOHIDElementTypeInput_Button: { printf("type: Button, "); break; } case kIOHIDElementTypeInput_Axis: { printf("type: Axis, "); break; } case kIOHIDElementTypeInput_ScanCodes: { printf("type: ScanCodes, "); break; } case kIOHIDElementTypeOutput: { printf("type: Output, "); break; } case kIOHIDElementTypeFeature: { printf("type: Feature, "); break; } case kIOHIDElementTypeCollection: { IOHIDElementCollectionType tIOHIDElementCollectionType = IOHIDElementGetCollectionType(inIOHIDElementRef); switch (tIOHIDElementCollectionType) { case kIOHIDElementCollectionTypePhysical: { printf("type: Physical Collection, "); break; } case kIOHIDElementCollectionTypeApplication: { printf("type: Application Collection, "); break; } case kIOHIDElementCollectionTypeLogical: { printf("type: Logical Collection, "); break; } case kIOHIDElementCollectionTypeReport: { printf("type: Report Collection, "); break; } case kIOHIDElementCollectionTypeNamedArray: { printf("type: Named Array Collection, "); break; } case kIOHIDElementCollectionTypeUsageSwitch: { printf("type: Usage Switch Collection, "); break; } case kIOHIDElementCollectionTypeUsageModifier: { printf("type: Usage Modifier Collection, "); break; } default: { printf("type: %p Collection, ", (void *) tIOHIDElementCollectionType); break; } } // switch break; } default: { printf("type: %p, ", (void *) tIOHIDElementType); break; } } /* switch */ uint32_t usagePage = IOHIDElementGetUsagePage(inIOHIDElementRef); uint32_t usage = IOHIDElementGetUsage(inIOHIDElementRef); printf("usage: 0x%04lX:0x%04lX, ", (long unsigned int) usagePage, (long unsigned int) usage); CFStringRef tCFStringRef = HIDCopyUsageName(usagePage, usage); if (tCFStringRef) { char usageString[256] = ""; (void) CFStringGetCString(tCFStringRef, usageString, sizeof(usageString), kCFStringEncodingUTF8); printf("\"%s\", ", usageString); CFRelease(tCFStringRef); } CFStringRef nameCFStringRef = IOHIDElementGetName(inIOHIDElementRef); char buffer[256]; if ( nameCFStringRef && CFStringGetCString(nameCFStringRef, buffer, sizeof(buffer), kCFStringEncodingUTF8) ) { printf("name: %s, ", buffer); } uint32_t reportID = IOHIDElementGetReportID(inIOHIDElementRef); uint32_t reportSize = IOHIDElementGetReportSize(inIOHIDElementRef); uint32_t reportCount = IOHIDElementGetReportCount(inIOHIDElementRef); printf("report: { ID: %lu, Size: %lu, Count: %lu }, ", (long unsigned int) reportID, (long unsigned int) reportSize, (long unsigned int) reportCount); uint32_t unit = IOHIDElementGetUnit(inIOHIDElementRef); uint32_t unitExp = IOHIDElementGetUnitExponent(inIOHIDElementRef); if (unit || unitExp) { printf("unit: %lu * 10^%lu, ", (long unsigned int) unit, (long unsigned int) unitExp); } CFIndex logicalMin = IOHIDElementGetLogicalMin(inIOHIDElementRef); CFIndex logicalMax = IOHIDElementGetLogicalMax(inIOHIDElementRef); if (logicalMin != logicalMax) { printf("logical: {min: %ld, max: %ld}, ", logicalMin, logicalMax); } CFIndex physicalMin = IOHIDElementGetPhysicalMin(inIOHIDElementRef); CFIndex physicalMax = IOHIDElementGetPhysicalMax(inIOHIDElementRef); if (physicalMin != physicalMax) { printf("physical: {min: %ld, max: %ld}, ", physicalMin, physicalMax); } Boolean isVirtual = IOHIDElementIsVirtual(inIOHIDElementRef); if (isVirtual) { printf("isVirtual, "); } Boolean isRelative = IOHIDElementIsRelative(inIOHIDElementRef); if (isRelative) { printf("isRelative, "); } Boolean isWrapping = IOHIDElementIsWrapping(inIOHIDElementRef); if (isWrapping) { printf("isWrapping, "); } Boolean isArray = IOHIDElementIsArray(inIOHIDElementRef); if (isArray) { printf("isArray, "); } Boolean isNonLinear = IOHIDElementIsNonLinear(inIOHIDElementRef); if (isNonLinear) { printf("isNonLinear, "); } Boolean hasPreferredState = IOHIDElementHasPreferredState(inIOHIDElementRef); if (hasPreferredState) { printf("hasPreferredState, "); } Boolean hasNullState = IOHIDElementHasNullState(inIOHIDElementRef); if (hasNullState) { printf("hasNullState, "); } printf(" }\n"); } } // HIDDumpElementInfo
void GourceSettings::importGourceSettings(ConfFile& conffile, ConfSection* gource_settings) { setGourceDefaults(); if(gource_settings == 0) gource_settings = conffile.getSection(default_section_name); if(gource_settings == 0) { gource_settings = conffile.addSection("gource"); } ConfEntry* entry = 0; //hide flags std::vector<std::string> hide_fields; if((entry = gource_settings->getEntry("hide")) != 0) { if(!entry->hasValue()) conffile.missingValueException(entry); std::string hide_string = entry->getString(); size_t sep; while((sep = hide_string.find(",")) != std::string::npos) { if(sep == 0 && hide_string.size()==1) break; if(sep == 0) { hide_string = hide_string.substr(sep+1, hide_string.size()-1); continue; } std::string hide_field = hide_string.substr(0, sep); hide_fields.push_back(hide_field); hide_string = hide_string.substr(sep+1, hide_string.size()-1); } if(hide_string.size() > 0 && hide_string != ",") hide_fields.push_back(hide_string); //validate field list for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) { std::string hide_field = (*it); if( hide_field != "date" && hide_field != "users" && hide_field != "tree" && hide_field != "files" && hide_field != "usernames" && hide_field != "filenames" && hide_field != "dirnames" && hide_field != "bloom" && hide_field != "progress" && hide_field != "mouse" && hide_field != "root") { std::string unknown_hide_option = std::string("unknown option hide ") + hide_field; conffile.entryException(entry, unknown_hide_option); } } } //check hide booleans for(std::map<std::string,std::string>::iterator it = arg_types.begin(); it != arg_types.end(); it++) { if(it->first.find("hide-") == 0 && it->second == "bool") { if(gource_settings->getBool(it->first)) { std::string hide_field = it->first.substr(5, it->first.size()-5); hide_fields.push_back(hide_field); } } } if(hide_fields.size()>0) { for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) { std::string hidestr = (*it); if(hidestr == "date") hide_date = true; else if(hidestr == "users") hide_users = true; else if(hidestr == "tree") hide_tree = true; else if(hidestr == "files") hide_files = true; else if(hidestr == "usernames") hide_usernames = true; else if(hidestr == "filenames") hide_filenames = true; else if(hidestr == "dirnames") hide_dirnames = true; else if(hidestr == "bloom") hide_bloom = true; else if(hidestr == "progress") hide_progress = true; else if(hidestr == "root") hide_root = true; else if(hidestr == "mouse") { hide_mouse = true; hide_progress = true; } } } if((entry = gource_settings->getEntry("date-format")) != 0) { if(!entry->hasValue()) conffile.missingValueException(entry); date_format = entry->getString(); } if(gource_settings->getBool("disable-auto-rotate")) { disable_auto_rotate=true; } if(gource_settings->getBool("disable-auto-skip")) { auto_skip_seconds = -1.0; } if(gource_settings->getBool("loop")) { loop = true; } if((entry = gource_settings->getEntry("git-branch")) != 0) { if(!entry->hasValue()) conffile.missingValueException(entry); git_branch = entry->getString(); } if(gource_settings->getBool("colour-images")) { colour_user_images = true; } if((entry = gource_settings->getEntry("crop")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify crop (vertical,horizontal)"); std::string crop = entry->getString(); if(crop == "vertical") { crop_vertical = true; } else if (crop == "horizontal") { crop_horizontal = true; } else { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("log-format")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify log-format (format)"); log_format = entry->getString(); if(log_format == "cvs") { conffile.entryException(entry, "please use either 'cvs2cl' or 'cvs-exp'"); } if( log_format != "git" && log_format != "cvs-exp" && log_format != "cvs2cl" && log_format != "svn" && log_format != "custom" && log_format != "hg" && log_format != "bzr" && log_format != "apache") { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("default-user-image")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify default-user-image (image path)"); default_user_image = entry->getString(); } if((entry = gource_settings->getEntry("user-image-dir")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify user-image-dir (directory)"); user_image_dir = entry->getString(); //append slash if(user_image_dir[user_image_dir.size()-1] != '/') { user_image_dir += std::string("/"); } //get jpg and png images in dir DIR *dp; struct dirent *dirp; user_image_map.clear(); if((dp = opendir(gGourceSettings.user_image_dir.c_str())) != 0) { while ((dirp = readdir(dp)) != 0) { std::string dirfile = std::string(dirp->d_name); size_t extpos = 0; if( (extpos=dirfile.rfind(".jpg")) == std::string::npos && (extpos=dirfile.rfind(".jpeg")) == std::string::npos && (extpos=dirfile.rfind(".png")) == std::string::npos) continue; std::string image_path = gGourceSettings.user_image_dir + dirfile; std::string name = dirfile.substr(0,extpos); #ifdef __APPLE__ CFMutableStringRef help = CFStringCreateMutable(kCFAllocatorDefault, 0); CFStringAppendCString(help, name.c_str(), kCFStringEncodingUTF8); CFStringNormalize(help, kCFStringNormalizationFormC); char data[4096]; CFStringGetCString(help, data, sizeof(data), kCFStringEncodingUTF8); name = data; #endif debugLog("%s => %s", name.c_str(), image_path.c_str()); user_image_map[name] = image_path; } closedir(dp); } } if((entry = gource_settings->getEntry("caption-file")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify caption file (filename)"); caption_file = entry->getString(); } if((entry = gource_settings->getEntry("caption-duration")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify caption duration (seconds)"); caption_duration = entry->getFloat(); if(caption_duration <= 0.0f) { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("caption-size")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify caption size"); caption_size = entry->getInt(); if(caption_size<1 || caption_size>100) { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("caption-offset")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify caption offset"); caption_offset = entry->getInt(); } if((entry = gource_settings->getEntry("caption-colour")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify caption colour (FFFFFF)"); int r,g,b; std::string colstring = entry->getString(); if(entry->isVec3()) { caption_colour = entry->getVec3(); } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) { caption_colour = vec3(r,g,b); caption_colour /= 255.0f; } else { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("bloom-intensity")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-intensity (float)"); bloom_intensity = entry->getFloat(); if(bloom_intensity<=0.0f) { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("bloom-multiplier")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-multiplier (float)"); bloom_multiplier = entry->getFloat(); if(bloom_multiplier<=0.0f) { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("elasticity")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify elasticity (float)"); elasticity = entry->getFloat(); if(elasticity<=0.0f) { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("font-size")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify font size"); font_size = entry->getInt(); if(font_size<1 || font_size>100) { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("hash-seed")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify hash seed (integer)"); gStringHashSeed = entry->getInt(); } if((entry = gource_settings->getEntry("font-colour")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify font colour (FFFFFF)"); int r,g,b; std::string colstring = entry->getString(); if(entry->isVec3()) { font_colour = entry->getVec3(); } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) { font_colour = vec3(r,g,b); font_colour /= 255.0f; } else { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("background-colour")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify background colour (FFFFFF)"); int r,g,b; std::string colstring = entry->getString(); if(entry->isVec3()) { background_colour = entry->getVec3(); } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) { background_colour = vec3(r,g,b); background_colour /= 255.0f; } else { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("highlight-colour")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify highlight colour (FFFFFF)"); int r,g,b; std::string colstring = entry->getString(); if(entry->isVec3()) { highlight_colour = entry->getVec3(); } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) { highlight_colour = vec3(r,g,b); highlight_colour /= 255.0f; } else { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("selection-colour")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify selection colour (FFFFFF)"); int r,g,b; std::string colstring = entry->getString(); if(entry->isVec3()) { selection_colour = entry->getVec3(); } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) { selection_colour = vec3(r,g,b); selection_colour /= 255.0f; } else { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("dir-colour")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify dir colour (FFFFFF)"); int r,g,b; std::string colstring = entry->getString(); if(entry->isVec3()) { dir_colour = entry->getVec3(); } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) { dir_colour = vec3(r,g,b); dir_colour /= 255.0f; } else { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("background-image")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify background image (image path)"); background_image = entry->getString(); } if((entry = gource_settings->getEntry("title")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify title"); title = entry->getString(); } if((entry = gource_settings->getEntry("logo")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify logo (image path)"); logo = entry->getString(); } if((entry = gource_settings->getEntry("logo-offset")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify logo-offset (XxY)"); std::string logo_offset_str = entry->getString(); int posx = 0; int posy = 0; if(parseRectangle(logo_offset_str, posx, posy)) { logo_offset = vec2(posx, posy); } else { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("seconds-per-day")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify seconds-per-day (seconds)"); float seconds_per_day = entry->getFloat(); if(seconds_per_day<=0.0f) { conffile.invalidValueException(entry); } // convert seconds-per-day to days-per-second days_per_second = 1.0 / seconds_per_day; } if((entry = gource_settings->getEntry("auto-skip-seconds")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify auto-skip-seconds (seconds)"); auto_skip_seconds = entry->getFloat(); if(auto_skip_seconds <= 0.0) { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("file-idle-time")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify file-idle-time (seconds)"); std::string file_idle_str = entry->getString(); file_idle_time = (float) atoi(file_idle_str.c_str()); if(file_idle_time<0.0f || (file_idle_time == 0.0f && file_idle_str[0] != '0') ) { conffile.invalidValueException(entry); } if(file_idle_time==0.0f) { file_idle_time = 86400.0f; } } if((entry = gource_settings->getEntry("user-idle-time")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify user-idle-time (seconds)"); user_idle_time = entry->getFloat(); if(user_idle_time < 0.0f) { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("time-scale")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify time-scale (scale)"); time_scale = entry->getFloat(); if(time_scale <= 0.0f || time_scale > 4.0f) { conffile.entryException(entry, "time-scale outside of range 0.0 - 4.0"); } } if((entry = gource_settings->getEntry("start-position")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify start-position (float,random)"); if(entry->getString() == "random") { srand(time(0)); start_position = (rand() % 1000) / 1000.0f; } else { start_position = entry->getFloat(); if(start_position<=0.0 || start_position>=1.0) { conffile.entryException(entry, "start-position outside of range 0.0 - 1.0 (non-inclusive)"); } } } if((entry = gource_settings->getEntry("stop-position")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify stop-position (float)"); stop_position = entry->getFloat(); if(stop_position<=0.0 || stop_position>1.0) { conffile.entryException(entry, "stop-position outside of range 0.0 - 1.0 (inclusive)"); } } if((entry = gource_settings->getEntry("stop-at-time")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify stop-at-time (seconds)"); stop_at_time = entry->getFloat(); if(stop_at_time <= 0.0) { conffile.invalidValueException(entry); } } if(gource_settings->getBool("key")) { show_key = true; } if(gource_settings->getBool("ffp")) { ffp = true; } if(gource_settings->getBool("realtime")) { days_per_second = 1.0 / 86400.0; } if(gource_settings->getBool("dont-stop")) { dont_stop = true; } if(gource_settings->getBool("stop-at-end")) { stop_at_end = true; } //NOTE: this no longer does anything if(gource_settings->getBool("stop-on-idle")) { stop_on_idle = true; } if((entry = gource_settings->getEntry("max-files")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify max-files (number)"); max_files = entry->getInt(); if( max_files<0 || (max_files == 0 && entry->getString() != "0") ) { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("max-file-lag")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify max-file-lag (seconds)"); max_file_lag = entry->getFloat(); if(max_file_lag==0.0) { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("user-friction")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify user-friction (seconds)"); user_friction = entry->getFloat(); if(user_friction<=0.0) { conffile.invalidValueException(entry); } user_friction = 1.0 / user_friction; } if((entry = gource_settings->getEntry("user-scale")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify user-scale (scale)"); user_scale = entry->getFloat(); if(user_scale<=0.0 || user_scale>100.0) { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("max-user-speed")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify max-user-speed (units)"); max_user_speed = entry->getFloat(); if(max_user_speed<=0) { conffile.invalidValueException(entry); } } if( gource_settings->getBool("highlight-users") || gource_settings->getBool("highlight-all-users")) { highlight_all_users = true; } if(gource_settings->getBool("highlight-dirs")) { highlight_dirs = true; } if((entry = gource_settings->getEntry("camera-mode")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify camera-mode (overview,track)"); camera_mode = entry->getString(); if(camera_mode != "overview" && camera_mode != "track") { conffile.invalidValueException(entry); } } if((entry = gource_settings->getEntry("padding")) != 0) { if(!entry->hasValue()) conffile.entryException(entry, "specify padding (float)"); padding = entry->getFloat(); if(padding <= 0.0f || padding >= 2.0f) { conffile.invalidValueException(entry); } } // multi-value entries if((entry = gource_settings->getEntry("highlight-user")) != 0) { ConfEntryList* highlight_user_entries = gource_settings->getEntries("highlight-user"); for(ConfEntryList::iterator it = highlight_user_entries->begin(); it != highlight_user_entries->end(); it++) { entry = *it; if(!entry->hasValue()) conffile.entryException(entry, "specify highlight-user (user)"); highlight_users.push_back(entry->getString()); } } if((entry = gource_settings->getEntry("follow-user")) != 0) { ConfEntryList* follow_user_entries = gource_settings->getEntries("follow-user"); for(ConfEntryList::iterator it = follow_user_entries->begin(); it != follow_user_entries->end(); it++) { entry = *it; if(!entry->hasValue()) conffile.entryException(entry, "specify follow-user (user)"); follow_users.push_back(entry->getString()); } } if(gource_settings->getBool("file-extensions")) { file_extensions=true; } if((entry = gource_settings->getEntry("file-filter")) != 0) { ConfEntryList* filters = gource_settings->getEntries("file-filter"); for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) { entry = *it; if(!entry->hasValue()) conffile.entryException(entry, "specify file-filter (regex)"); std::string filter_string = entry->getString(); Regex* r = new Regex(filter_string, 1); if(!r->isValid()) { delete r; conffile.entryException(entry, "invalid file-filter regular expression"); } file_filters.push_back(r); } } if((entry = gource_settings->getEntry("user-filter")) != 0) { ConfEntryList* filters = gource_settings->getEntries("user-filter"); for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) { entry = *it; if(!entry->hasValue()) conffile.entryException(entry, "specify user-filter (regex)"); std::string filter_string = entry->getString(); Regex* r = new Regex(filter_string, 1); if(!r->isValid()) { delete r; conffile.entryException(entry, "invalid user-filter regular expression"); } user_filters.push_back(r); } } //validate path if(gource_settings->hasValue("path")) { path = gource_settings->getString("path"); default_path = false; } if(path == "-") { if(log_format.size() == 0) { throw ConfFileException("log-format required when reading from STDIN", "", 0); } #ifdef _WIN32 DWORD available_bytes; HANDLE stdin_handle = GetStdHandle(STD_INPUT_HANDLE); while(PeekNamedPipe(stdin_handle, 0, 0, 0, &available_bytes, 0) && available_bytes==0 && !std::cin.fail()) { SDL_Delay(100); } #else while(std::cin.peek() == EOF && !std::cin.fail()) SDL_Delay(100); #endif std::cin.clear(); } //remove trailing slash and check if path is a directory if(path.size() && (path[path.size()-1] == '\\' || path[path.size()-1] == '/')) { path = path.substr(0,path.size()-1); } #ifdef _WIN32 //on windows, pre-open console window if we think this is a directory the //user is trying to open, as system() commands will create a console window //if there isn't one anyway. bool isdir = false; if(path.size()>0) { struct stat fileinfo; int rc = stat(path.c_str(), &fileinfo); if(rc==0 && fileinfo.st_mode & S_IFDIR) isdir = true; } if(path.size()==0 || isdir) { SDLAppCreateWindowsConsole(); } #endif }
// ---------------------------------------------------------------------------- // process_prefs // ---------------------------------------------------------------------------- int process_prefs(struct vpn_params *params) { char pathStr[MAXPATHLEN]; SCPreferencesRef prefs = 0; CFPropertyListRef servers_list; char text[512] = ""; // open the prefs file prefs = SCPreferencesCreate(0, CFSTR("vpnd"), kRASServerPrefsFileName); if (prefs == NULL) { CFStringGetCString(kRASServerPrefsFileName, pathStr, MAXPATHLEN, kCFStringEncodingMacRoman); snprintf(text, sizeof(text), "Unable to read vpnd prefs file '%s'\n", pathStr); goto fail; } // get servers list from the plist servers_list = SCPreferencesGetValue(prefs, kRASServers); if (servers_list == NULL) { snprintf(text, sizeof(text), "Could not get servers dictionary\n"); goto fail; } // retrieve the information for the given Server ID params->serverIDRef = CFStringCreateWithCString(0, params->server_id, kCFStringEncodingMacRoman); if (params->serverIDRef == NULL) { snprintf(text, sizeof(text), "Could not create CFString for server ID\n"); goto fail; } params->serverRef = CFDictionaryGetValue(servers_list, params->serverIDRef); if (params->serverRef == NULL || isDictionary(params->serverRef) == 0) { snprintf(text, sizeof(text), "Server ID '%.64s' invalid\n", params->server_id); params->serverRef = 0; goto fail; } CFRetain(params->serverRef); CFRelease(prefs); prefs = 0; // process the dictionaries if (process_server_prefs(params)) goto fail; if (process_interface_prefs(params)) goto fail; switch (params->server_type) { case SERVER_TYPE_PPP: if (ppp_process_prefs(params)) { snprintf(text, sizeof(text), "Error while reading PPP preferences\n"); goto fail; } break; case SERVER_TYPE_IPSEC: if (ipsec_process_prefs(params)) { snprintf(text, sizeof(text), "Error while reading IPSec preferences\n"); goto fail; } break; } return 0; fail: vpnlog(LOG_ERR, text[0] ? text : "Error while reading preferences\n"); if (params->serverIDRef) { CFRelease(params->serverIDRef); params->serverIDRef = 0; } if (params->serverRef) { CFRelease(params->serverRef); params->serverRef = 0; } if (prefs) CFRelease(prefs); return -1; }
CF_PRIVATE void *_CFBundleDLLGetSymbolByName(CFBundleRef bundle, CFStringRef symbolName) { void *result = NULL; char buff[1024]; if (CFStringGetCString(symbolName, buff, 1024, kCFStringEncodingWindowsLatin1)) result = GetProcAddress(bundle->_hModule, buff); return result; }
static int disk_read (void) { #if HAVE_IOKIT_IOKITLIB_H io_registry_entry_t disk; io_registry_entry_t disk_child; io_iterator_t disk_list; CFDictionaryRef props_dict; CFDictionaryRef stats_dict; CFDictionaryRef child_dict; CFStringRef tmp_cf_string_ref; kern_return_t status; signed long long read_ops; signed long long read_byt; signed long long read_tme; signed long long write_ops; signed long long write_byt; signed long long write_tme; int disk_major; int disk_minor; char disk_name[DATA_MAX_NAME_LEN]; char disk_name_bsd[DATA_MAX_NAME_LEN]; /* Get the list of all disk objects. */ if (IOServiceGetMatchingServices (io_master_port, IOServiceMatching (kIOBlockStorageDriverClass), &disk_list) != kIOReturnSuccess) { ERROR ("disk plugin: IOServiceGetMatchingServices failed."); return (-1); } while ((disk = IOIteratorNext (disk_list)) != 0) { props_dict = NULL; stats_dict = NULL; child_dict = NULL; /* `disk_child' must be released */ if ((status = IORegistryEntryGetChildEntry (disk, kIOServicePlane, &disk_child)) != kIOReturnSuccess) { /* This fails for example for DVD/CD drives.. */ DEBUG ("IORegistryEntryGetChildEntry (disk) failed: 0x%08x", status); IOObjectRelease (disk); continue; } /* We create `props_dict' => we need to release it later */ if (IORegistryEntryCreateCFProperties (disk, (CFMutableDictionaryRef *) &props_dict, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) { ERROR ("disk-plugin: IORegistryEntryCreateCFProperties failed."); IOObjectRelease (disk_child); IOObjectRelease (disk); continue; } if (props_dict == NULL) { DEBUG ("IORegistryEntryCreateCFProperties (disk) failed."); IOObjectRelease (disk_child); IOObjectRelease (disk); continue; } /* tmp_cf_string_ref doesn't need to be released. */ tmp_cf_string_ref = (CFStringRef) CFDictionaryGetValue (props_dict, CFSTR(kIOBSDNameKey)); if (!tmp_cf_string_ref) { DEBUG ("disk plugin: CFDictionaryGetValue(" "kIOBSDNameKey) failed."); CFRelease (props_dict); IOObjectRelease (disk_child); IOObjectRelease (disk); continue; } assert (CFGetTypeID (tmp_cf_string_ref) == CFStringGetTypeID ()); memset (disk_name_bsd, 0, sizeof (disk_name_bsd)); CFStringGetCString (tmp_cf_string_ref, disk_name_bsd, sizeof (disk_name_bsd), kCFStringEncodingUTF8); if (disk_name_bsd[0] == 0) { ERROR ("disk plugin: CFStringGetCString() failed."); CFRelease (props_dict); IOObjectRelease (disk_child); IOObjectRelease (disk); continue; } DEBUG ("disk plugin: disk_name_bsd = \"%s\"", disk_name_bsd); stats_dict = (CFDictionaryRef) CFDictionaryGetValue (props_dict, CFSTR (kIOBlockStorageDriverStatisticsKey)); if (stats_dict == NULL) { DEBUG ("disk plugin: CFDictionaryGetValue (" "%s) failed.", kIOBlockStorageDriverStatisticsKey); CFRelease (props_dict); IOObjectRelease (disk_child); IOObjectRelease (disk); continue; } if (IORegistryEntryCreateCFProperties (disk_child, (CFMutableDictionaryRef *) &child_dict, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) { DEBUG ("disk plugin: IORegistryEntryCreateCFProperties (" "disk_child) failed."); IOObjectRelease (disk_child); CFRelease (props_dict); IOObjectRelease (disk); continue; } /* kIOBSDNameKey */ disk_major = (int) dict_get_value (child_dict, kIOBSDMajorKey); disk_minor = (int) dict_get_value (child_dict, kIOBSDMinorKey); read_ops = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsReadsKey); read_byt = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsBytesReadKey); read_tme = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsTotalReadTimeKey); write_ops = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsWritesKey); write_byt = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsBytesWrittenKey); /* This property describes the number of nanoseconds spent * performing writes since the block storage driver was * instantiated. It is one of the statistic entries listed * under the top-level kIOBlockStorageDriverStatisticsKey * property table. It has an OSNumber value. */ write_tme = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsTotalWriteTimeKey); if (use_bsd_name) sstrncpy (disk_name, disk_name_bsd, sizeof (disk_name)); else ssnprintf (disk_name, sizeof (disk_name), "%i-%i", disk_major, disk_minor); DEBUG ("disk plugin: disk_name = \"%s\"", disk_name); if ((read_byt != -1LL) || (write_byt != -1LL)) disk_submit (disk_name, "disk_octets", read_byt, write_byt); if ((read_ops != -1LL) || (write_ops != -1LL)) disk_submit (disk_name, "disk_ops", read_ops, write_ops); if ((read_tme != -1LL) || (write_tme != -1LL)) disk_submit (disk_name, "disk_time", read_tme / 1000, write_tme / 1000); CFRelease (child_dict); IOObjectRelease (disk_child); CFRelease (props_dict); IOObjectRelease (disk); } IOObjectRelease (disk_list); /* #endif HAVE_IOKIT_IOKITLIB_H */ #elif KERNEL_LINUX FILE *fh; char buffer[1024]; char *fields[32]; int numfields; int fieldshift = 0; int minor = 0; derive_t read_sectors = 0; derive_t write_sectors = 0; derive_t read_ops = 0; derive_t read_merged = 0; derive_t read_time = 0; derive_t write_ops = 0; derive_t write_merged = 0; derive_t write_time = 0; gauge_t in_progress = NAN; int is_disk = 0; diskstats_t *ds, *pre_ds; if ((fh = fopen ("/proc/diskstats", "r")) == NULL) { fh = fopen ("/proc/partitions", "r"); if (fh == NULL) { ERROR ("disk plugin: fopen (/proc/{diskstats,partitions}) failed."); return (-1); } /* Kernel is 2.4.* */ fieldshift = 1; } #if HAVE_LIBUDEV handle_udev = udev_new(); #endif while (fgets (buffer, sizeof (buffer), fh) != NULL) { char *disk_name; char *output_name; char *alt_name; numfields = strsplit (buffer, fields, 32); if ((numfields != (14 + fieldshift)) && (numfields != 7)) continue; minor = atoll (fields[1]); disk_name = fields[2 + fieldshift]; for (ds = disklist, pre_ds = disklist; ds != NULL; pre_ds = ds, ds = ds->next) if (strcmp (disk_name, ds->name) == 0) break; if (ds == NULL) { if ((ds = (diskstats_t *) calloc (1, sizeof (diskstats_t))) == NULL) continue; if ((ds->name = strdup (disk_name)) == NULL) { free (ds); continue; } if (pre_ds == NULL) disklist = ds; else pre_ds->next = ds; } is_disk = 0; if (numfields == 7) { /* Kernel 2.6, Partition */ read_ops = atoll (fields[3]); read_sectors = atoll (fields[4]); write_ops = atoll (fields[5]); write_sectors = atoll (fields[6]); } else if (numfields == (14 + fieldshift)) { read_ops = atoll (fields[3 + fieldshift]); write_ops = atoll (fields[7 + fieldshift]); read_sectors = atoll (fields[5 + fieldshift]); write_sectors = atoll (fields[9 + fieldshift]); if ((fieldshift == 0) || (minor == 0)) { is_disk = 1; read_merged = atoll (fields[4 + fieldshift]); read_time = atoll (fields[6 + fieldshift]); write_merged = atoll (fields[8 + fieldshift]); write_time = atoll (fields[10+ fieldshift]); in_progress = atof (fields[11 + fieldshift]); } } else { DEBUG ("numfields = %i; => unknown file format.", numfields); continue; } { derive_t diff_read_sectors; derive_t diff_write_sectors; /* If the counter wraps around, it's only 32 bits.. */ if (read_sectors < ds->read_sectors) diff_read_sectors = 1 + read_sectors + (UINT_MAX - ds->read_sectors); else diff_read_sectors = read_sectors - ds->read_sectors; if (write_sectors < ds->write_sectors) diff_write_sectors = 1 + write_sectors + (UINT_MAX - ds->write_sectors); else diff_write_sectors = write_sectors - ds->write_sectors; ds->read_bytes += 512 * diff_read_sectors; ds->write_bytes += 512 * diff_write_sectors; ds->read_sectors = read_sectors; ds->write_sectors = write_sectors; } /* Calculate the average time an io-op needs to complete */ if (is_disk) { derive_t diff_read_ops; derive_t diff_write_ops; derive_t diff_read_time; derive_t diff_write_time; if (read_ops < ds->read_ops) diff_read_ops = 1 + read_ops + (UINT_MAX - ds->read_ops); else diff_read_ops = read_ops - ds->read_ops; DEBUG ("disk plugin: disk_name = %s; read_ops = %"PRIi64"; " "ds->read_ops = %"PRIi64"; diff_read_ops = %"PRIi64";", disk_name, read_ops, ds->read_ops, diff_read_ops); if (write_ops < ds->write_ops) diff_write_ops = 1 + write_ops + (UINT_MAX - ds->write_ops); else diff_write_ops = write_ops - ds->write_ops; if (read_time < ds->read_time) diff_read_time = 1 + read_time + (UINT_MAX - ds->read_time); else diff_read_time = read_time - ds->read_time; if (write_time < ds->write_time) diff_write_time = 1 + write_time + (UINT_MAX - ds->write_time); else diff_write_time = write_time - ds->write_time; if (diff_read_ops != 0) ds->avg_read_time += disk_calc_time_incr ( diff_read_time, diff_read_ops); if (diff_write_ops != 0) ds->avg_write_time += disk_calc_time_incr ( diff_write_time, diff_write_ops); ds->read_ops = read_ops; ds->read_time = read_time; ds->write_ops = write_ops; ds->write_time = write_time; } /* if (is_disk) */ /* Don't write to the RRDs if we've just started.. */ ds->poll_count++; if (ds->poll_count <= 2) { DEBUG ("disk plugin: (ds->poll_count = %i) <= " "(min_poll_count = 2); => Not writing.", ds->poll_count); continue; } if ((read_ops == 0) && (write_ops == 0)) { DEBUG ("disk plugin: ((read_ops == 0) && " "(write_ops == 0)); => Not writing."); continue; } output_name = disk_name; #if HAVE_LIBUDEV alt_name = disk_udev_attr_name (handle_udev, disk_name, conf_udev_name_attr); #else alt_name = NULL; #endif if (alt_name != NULL) output_name = alt_name; if ((ds->read_bytes != 0) || (ds->write_bytes != 0)) disk_submit (output_name, "disk_octets", ds->read_bytes, ds->write_bytes); if ((ds->read_ops != 0) || (ds->write_ops != 0)) disk_submit (output_name, "disk_ops", read_ops, write_ops); if ((ds->avg_read_time != 0) || (ds->avg_write_time != 0)) disk_submit (output_name, "disk_time", ds->avg_read_time, ds->avg_write_time); if (is_disk) { disk_submit (output_name, "disk_merged", read_merged, write_merged); submit_in_progress (output_name, in_progress); } /* if (is_disk) */ /* release udev-based alternate name, if allocated */ free(alt_name); } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */ #if HAVE_LIBUDEV udev_unref(handle_udev); #endif fclose (fh); /* #endif defined(KERNEL_LINUX) */ #elif HAVE_LIBKSTAT # if HAVE_KSTAT_IO_T_WRITES && HAVE_KSTAT_IO_T_NWRITES && HAVE_KSTAT_IO_T_WTIME # define KIO_ROCTETS reads # define KIO_WOCTETS writes # define KIO_ROPS nreads # define KIO_WOPS nwrites # define KIO_RTIME rtime # define KIO_WTIME wtime # elif HAVE_KSTAT_IO_T_NWRITTEN && HAVE_KSTAT_IO_T_WRITES && HAVE_KSTAT_IO_T_WTIME # define KIO_ROCTETS nread # define KIO_WOCTETS nwritten # define KIO_ROPS reads # define KIO_WOPS writes # define KIO_RTIME rtime # define KIO_WTIME wtime # else # error "kstat_io_t does not have the required members" # endif static kstat_io_t kio; int i; if (kc == NULL) return (-1); for (i = 0; i < numdisk; i++) { if (kstat_read (kc, ksp[i], &kio) == -1) continue; if (strncmp (ksp[i]->ks_class, "disk", 4) == 0) { disk_submit (ksp[i]->ks_name, "disk_octets", kio.KIO_ROCTETS, kio.KIO_WOCTETS); disk_submit (ksp[i]->ks_name, "disk_ops", kio.KIO_ROPS, kio.KIO_WOPS); /* FIXME: Convert this to microseconds if necessary */ disk_submit (ksp[i]->ks_name, "disk_time", kio.KIO_RTIME, kio.KIO_WTIME); } else if (strncmp (ksp[i]->ks_class, "partition", 9) == 0) { disk_submit (ksp[i]->ks_name, "disk_octets", kio.KIO_ROCTETS, kio.KIO_WOCTETS); disk_submit (ksp[i]->ks_name, "disk_ops", kio.KIO_ROPS, kio.KIO_WOPS); } } /* #endif defined(HAVE_LIBKSTAT) */ #elif defined(HAVE_LIBSTATGRAB) sg_disk_io_stats *ds; # if HAVE_LIBSTATGRAB_0_90 size_t disks; # else int disks; #endif int counter; char name[DATA_MAX_NAME_LEN]; if ((ds = sg_get_disk_io_stats(&disks)) == NULL) return (0); for (counter=0; counter < disks; counter++) { strncpy(name, ds->disk_name, sizeof(name)); name[sizeof(name)-1] = '\0'; /* strncpy doesn't terminate longer strings */ disk_submit (name, "disk_octets", ds->read_bytes, ds->write_bytes); ds++; } /* #endif defined(HAVE_LIBSTATGRAB) */ #elif defined(HAVE_PERFSTAT) derive_t read_sectors; derive_t write_sectors; derive_t read_time; derive_t write_time; derive_t read_ops; derive_t write_ops; perfstat_id_t firstpath; int rnumdisk; int i; if ((numdisk = perfstat_disk(NULL, NULL, sizeof(perfstat_disk_t), 0)) < 0) { char errbuf[1024]; WARNING ("disk plugin: perfstat_disk: %s", sstrerror (errno, errbuf, sizeof (errbuf))); return (-1); } if (numdisk != pnumdisk || stat_disk==NULL) { if (stat_disk!=NULL) free(stat_disk); stat_disk = (perfstat_disk_t *)calloc(numdisk, sizeof(perfstat_disk_t)); } pnumdisk = numdisk; firstpath.name[0]='\0'; if ((rnumdisk = perfstat_disk(&firstpath, stat_disk, sizeof(perfstat_disk_t), numdisk)) < 0) { char errbuf[1024]; WARNING ("disk plugin: perfstat_disk : %s", sstrerror (errno, errbuf, sizeof (errbuf))); return (-1); } for (i = 0; i < rnumdisk; i++) { read_sectors = stat_disk[i].rblks*stat_disk[i].bsize; write_sectors = stat_disk[i].wblks*stat_disk[i].bsize; disk_submit (stat_disk[i].name, "disk_octets", read_sectors, write_sectors); read_ops = stat_disk[i].xrate; write_ops = stat_disk[i].xfers - stat_disk[i].xrate; disk_submit (stat_disk[i].name, "disk_ops", read_ops, write_ops); read_time = stat_disk[i].rserv; read_time *= ((double)(_system_configuration.Xint)/(double)(_system_configuration.Xfrac)) / 1000000.0; write_time = stat_disk[i].wserv; write_time *= ((double)(_system_configuration.Xint)/(double)(_system_configuration.Xfrac)) / 1000000.0; disk_submit (stat_disk[i].name, "disk_time", read_time, write_time); } #endif /* defined(HAVE_PERFSTAT) */ return (0); } /* int disk_read */
void PcapLiveDeviceList::setDnsServers() { #ifdef WIN32 FIXED_INFO * fixedInfo; ULONG ulOutBufLen; DWORD dwRetVal; IP_ADDR_STRING * pIPAddr; uint8_t buf1[sizeof(FIXED_INFO)]; fixedInfo = (FIXED_INFO *) buf1; ulOutBufLen = sizeof( FIXED_INFO ); dwRetVal = GetNetworkParams( fixedInfo, &ulOutBufLen ); uint8_t buf2[ulOutBufLen]; if(ERROR_BUFFER_OVERFLOW == dwRetVal) { fixedInfo = (FIXED_INFO *)buf2; } if ((dwRetVal = GetNetworkParams( fixedInfo, &ulOutBufLen )) != 0) LOG_ERROR("Call to GetNetworkParams failed. Return Value: %08lx\n", dwRetVal); else { m_DnsServers.push_back(IPv4Address(fixedInfo->DnsServerList.IpAddress.String)); int i = 1; LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, fixedInfo->DnsServerList.IpAddress.String ); pIPAddr = fixedInfo->DnsServerList.Next; while ( pIPAddr ) { m_DnsServers.push_back(IPv4Address(pIPAddr->IpAddress.String)); LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, pIPAddr->IpAddress.String); pIPAddr = pIPAddr -> Next; } } #elif LINUX std::string command = "nmcli dev list | grep IP4.DNS"; std::string dnsServersInfo = executeShellCommand(command); if (dnsServersInfo == "") { LOG_DEBUG("Error retrieving DNS server list: call to nmcli gave no output"); return; } std::istringstream stream(dnsServersInfo); std::string line; int i = 1; while(std::getline(stream, line)) { std::istringstream lineStream(line); std::string headline; std::string dnsIP; lineStream >> headline; lineStream >> dnsIP; IPv4Address dnsIPAddr(dnsIP); if (!dnsIPAddr.isValid()) continue; if (std::find(m_DnsServers.begin(), m_DnsServers.end(), dnsIPAddr) == m_DnsServers.end()) { m_DnsServers.push_back(dnsIPAddr); LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, dnsIPAddr.toString().c_str()); } } #elif MAC_OS_X SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, CFSTR("iked"), NULL, NULL); if (dynRef == NULL) { LOG_DEBUG("Couldn't set DNS server list: failed to retrieve SCDynamicStore"); return; } CFDictionaryRef dnsDict = (CFDictionaryRef)SCDynamicStoreCopyValue(dynRef,CFSTR("State:/Network/Global/DNS")); if (dnsDict == NULL) { LOG_DEBUG("Couldn't set DNS server list: failed to get DNS dictionary"); CFRelease(dynRef); return; } CFArrayRef serverAddresses = (CFArrayRef)CFDictionaryGetValue(dnsDict, CFSTR("ServerAddresses")); if (serverAddresses == NULL) { LOG_DEBUG("Couldn't set DNS server list: server addresses array is null"); CFRelease(dynRef); CFRelease(dnsDict); return; } CFIndex count = CFArrayGetCount(serverAddresses); for (CFIndex i = 0; i < count; i++) { CFStringRef serverAddress = (CFStringRef)CFArrayGetValueAtIndex(serverAddresses, i); if (serverAddress == NULL) continue; uint8_t buf[20]; char* serverAddressCString = (char*)buf; CFStringGetCString(serverAddress, serverAddressCString, 20, kCFStringEncodingUTF8); m_DnsServers.push_back(IPv4Address(serverAddressCString)); LOG_DEBUG("Default DNS server IP #%d: %s\n", (int)(i+1), serverAddressCString); } CFRelease(dynRef); CFRelease(dnsDict); #endif }
//http://iphonedevwiki.net/index.php/Lockdownd void get_device_infos(CFMutableDictionaryRef out) { CC_SHA1_CTX sha1ctx; uint8_t udid[20]; char udid1[100]; CFStringRef serial; CFStringRef imei; CFStringRef macwifi; CFStringRef macbt; CFStringRef hw = copy_hardware_model(); if (hw != NULL) { CFDictionaryAddValue(out, CFSTR("hwModel"), hw); CFRelease(hw); } serial = copy_device_serial_number(); imei = copy_device_imei(); macwifi = copy_wifi_mac_address(); macbt = copy_bluetooth_mac_address(); CFMutableStringRef udidInput = CFStringCreateMutable(kCFAllocatorDefault, 0); if (serial != NULL) { CFStringAppend(udidInput, serial); CFDictionaryAddValue(out, CFSTR("serialNumber"), serial); CFRelease(serial); } uint64_t _ecid = 0; CFNumberRef ecid = copyNumberFromChosen(CFSTR("unique-chip-id")); if (ecid != NULL) { CFDictionaryAddValue(out, CFSTR("ECID"), ecid); } if (ecid != NULL && useNewUDID(hw)) { CFNumberGetValue(ecid, kCFNumberSInt64Type, &_ecid); CFStringAppendFormat(udidInput, NULL, CFSTR("%llu"), _ecid); } else if (imei != NULL) { CFStringAppend(udidInput, imei); CFDictionaryAddValue(out, CFSTR("imei"), imei); CFRelease(imei); } if (macwifi != NULL) { CFStringAppend(udidInput, macwifi); CFDictionaryAddValue(out, CFSTR("wifiMac"), macwifi); CFRelease(macwifi); } if (macbt != NULL) { CFStringAppend(udidInput, macbt); CFDictionaryAddValue(out, CFSTR("btMac"), macbt); CFRelease(macbt); } CFStringGetCString(udidInput, udid1, 99, kCFStringEncodingASCII); CC_SHA1_Init(&sha1ctx); CC_SHA1_Update(&sha1ctx, udid1, CFStringGetLength(udidInput)); CC_SHA1_Final(udid, &sha1ctx); CFRelease(udidInput); addHexaString(out, CFSTR("udid"), udid, 20); }
//----------------------------------------------------------------------------- const char* Platform::getClipboard() { // mac clipboards can contain multiple items, // and each item can be in several differnt flavors, // such as unicode or plaintext or pdf, etc. // scan through the clipboard, and return the 1st piece of actual text. ScrapRef clip; char *retBuf = ""; OSStatus err = noErr; char *dataBuf = ""; // get a local ref to the system clipboard GetScrapByName( kScrapClipboardScrap, kScrapGetNamedScrap, &clip ); // First try to get unicode data, then try to get plain text data. Size dataSize = 0; bool plaintext = false; err = GetScrapFlavorSize(clip, kScrapFlavorTypeUnicode, &dataSize); if( err != noErr || dataSize <= 0) { Con::errorf("some error getting unicode clip"); plaintext = true; err = GetScrapFlavorSize(clip, kScrapFlavorTypeText, &dataSize); } // kick out if we don't have any data. if( err != noErr || dataSize <= 0) { Con::errorf("no data, kicking out. size = %i",dataSize); return ""; } if( err == noErr && dataSize > 0 ) { // ok, we've got something! allocate a buffer and copy it in. char buf[dataSize+1]; dMemset(buf, 0, dataSize+1); dataBuf = buf; // plain text needs no conversion. // unicode data needs to be converted to normalized utf-8 format. if(plaintext) { GetScrapFlavorData(clip, kScrapFlavorTypeText, &dataSize, &buf); retBuf = Con::getReturnBuffer(dataSize + 1); dMemcpy(retBuf,buf,dataSize); } else { GetScrapFlavorData(clip, kScrapFlavorTypeUnicode, &dataSize, &buf); // normalize CFStringRef cfBuf = CFStringCreateWithBytes(NULL, (const UInt8*)buf, dataSize, kCFStringEncodingUnicode, false); CFMutableStringRef normBuf = CFStringCreateMutableCopy(NULL, 0, cfBuf); CFStringNormalize(normBuf, kCFStringNormalizationFormC); // convert to utf-8 U32 normBufLen = CFStringGetLength(normBuf); U32 retBufLen = CFStringGetMaximumSizeForEncoding(normBufLen,kCFStringEncodingUTF8) + 1; // +1 for the null terminator retBuf = Con::getReturnBuffer(retBufLen); CFStringGetCString( normBuf, retBuf, retBufLen, kCFStringEncodingUTF8); dataSize = retBufLen; } // manually null terminate, just in case. retBuf[dataSize] = 0; } // return the data, or the empty string if we did not find any data. return retBuf; }
static void vprintf_stderr_common(const char* format, va_list args) { #if USE(CF) && !OS(WINDOWS) if (strstr(format, "%@")) { CFStringRef cfFormat = CFStringCreateWithCString(NULL, format, kCFStringEncodingUTF8); #if COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wformat-nonliteral" #endif CFStringRef str = CFStringCreateWithFormatAndArguments(NULL, NULL, cfFormat, args); #if COMPILER(CLANG) #pragma clang diagnostic pop #endif CFIndex length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char* buffer = (char*)malloc(length + 1); CFStringGetCString(str, buffer, length, kCFStringEncodingUTF8); #if USE(APPLE_SYSTEM_LOG) asl_log(0, 0, ASL_LEVEL_NOTICE, "%s", buffer); #endif fputs(buffer, stderr); free(buffer); CFRelease(str); CFRelease(cfFormat); return; } #if USE(APPLE_SYSTEM_LOG) va_list copyOfArgs; va_copy(copyOfArgs, args); asl_vlog(0, 0, ASL_LEVEL_NOTICE, format, copyOfArgs); va_end(copyOfArgs); #endif // Fall through to write to stderr in the same manner as other platforms. #elif HAVE(ISDEBUGGERPRESENT) if (IsDebuggerPresent()) { size_t size = 1024; do { char* buffer = (char*)malloc(size); if (buffer == NULL) break; if (vsnprintf(buffer, size, format, args) != -1) { OutputDebugStringA(buffer); free(buffer); break; } free(buffer); size *= 2; } while (size > 1024); } #endif vfprintf(stderr, format, args); }
/************************************************************************* * * hu_XMLSearchForProductNameByVendorProductID( inVendorID, inProductID, outCStr ) * * Purpose: Find an product string in the <HID_device_usage_strings.plist> resource ( XML ) file * * Inputs: inVendorID - the elements vendor ID * inProductID - the elements product ID * outCStr - address where result will be returned * * Returns: Boolean - if successful */ static Boolean hu_XMLSearchForProductNameByVendorProductID(long inVendorID, long inProductID, char *outCStr) { Boolean results = FALSE; if ( !gUsageCFPropertyListRef ) { gUsageCFPropertyListRef = hu_XMLLoad( CFSTR( "HID_device_usage_strings"), CFSTR("plist") ); } if ( gUsageCFPropertyListRef ) { if ( CFDictionaryGetTypeID() == CFGetTypeID(gUsageCFPropertyListRef) ) { // first we make our vendor ID key CFStringRef vendorKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%ld"), inVendorID); if ( vendorKeyCFStringRef ) { // and use it to look up our vendor dictionary CFDictionaryRef vendorCFDictionaryRef; if ( CFDictionaryGetValueIfPresent(gUsageCFPropertyListRef, vendorKeyCFStringRef, (const void **) &vendorCFDictionaryRef) ) { // pull our vendor name our of that dictionary CFStringRef vendorCFStringRef = NULL; if ( CFDictionaryGetValueIfPresent(vendorCFDictionaryRef, kNameKeyCFStringRef, (const void **) &vendorCFStringRef) ) { #if FAKE_MISSING_NAMES CFRetain(vendorCFStringRef); // so we can CFRelease it later } else { vendorCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "V: %@"), vendorKeyCFStringRef); #endif } // now we make our product ID key CFStringRef productKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "%ld"), inProductID); if ( productKeyCFStringRef ) { // and use that key to look up our product dictionary in the vendor dictionary CFDictionaryRef productCFDictionaryRef; if ( CFDictionaryGetValueIfPresent(vendorCFDictionaryRef, productKeyCFStringRef, (const void **) &productCFDictionaryRef) ) { // pull our product name our of the product dictionary CFStringRef productCFStringRef = NULL; if ( CFDictionaryGetValueIfPresent(productCFDictionaryRef, kNameKeyCFStringRef, (const void **) &productCFStringRef) ) { #if FAKE_MISSING_NAMES CFRetain(productCFStringRef); // so we can CFRelease it later } else { productCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "P: %@"), kNameKeyCFStringRef); #endif } CFStringRef fullCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "%@ %@"), vendorCFStringRef, productCFStringRef); if ( fullCFStringRef ) { // CFShow( fullCFStringRef ); results = CFStringGetCString(fullCFStringRef, outCStr, CFStringGetLength( fullCFStringRef) * sizeof(UniChar) + 1, kCFStringEncodingUTF8); CFRelease(fullCFStringRef); } #if FAKE_MISSING_NAMES if ( productCFStringRef ) { CFRelease(productCFStringRef); } #endif } CFRelease(productKeyCFStringRef); } #if FAKE_MISSING_NAMES if ( vendorCFStringRef ) { CFRelease(vendorCFStringRef); } #endif } CFRelease(vendorKeyCFStringRef); } } // ++ CFRelease( gUsageCFPropertyListRef ); // Leak this ! } return (results); } // hu_XMLSearchForProductNameByVendorProductID
int main(int argc, const char * argv[]) { #if TARGET_OS_MAC { thread_extended_policy_data_t theFixedPolicy; theFixedPolicy.timeshare = false; // set to true for a non-fixed thread thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_EXTENDED_POLICY, (thread_policy_t)&theFixedPolicy, THREAD_EXTENDED_POLICY_COUNT); // We keep a reference to the spawning thread's priority around (initialized in the constructor), // and set the importance of the child thread relative to the spawning thread's priority. thread_precedence_policy_data_t thePrecedencePolicy; thePrecedencePolicy.importance = 63 - 36; thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_PRECEDENCE_POLICY, (thread_policy_t)&thePrecedencePolicy, THREAD_PRECEDENCE_POLICY_COUNT); } #endif // These are the variables that are set up from the input parsing char* srcFilePath = NULL; char* auPresetFile = NULL; OSType manu, subType, type = 0; UInt32 numFrames = 4096; for (int i = 1; i < argc; ++i) { if (strcmp (argv[i], "-au") == 0) { if ( (i + 3) < argc ) { StrToOSType (argv[i + 1], type); StrToOSType (argv[i + 2], subType); StrToOSType (argv[i + 3], manu); i += 3; } else { printf ("Which Audio Unit:\n%s", usageStr); exit(1); } } else if (strcmp (argv[i], "-i") == 0) { srcFilePath = const_cast<char*>(argv[++i]); } else if (strcmp (argv[i], "-p") == 0) { auPresetFile = const_cast<char*>(argv[++i]); } else if (strcmp (argv[i], "-f") == 0) { sscanf(argv[++i], "%ld", &numFrames); } else { printf ("%s\n", usageStr); exit(1); } } if (!type || !srcFilePath) { printf ("%s\n", usageStr); exit(1); } CAComponentDescription desc(type, subType, manu); CFPropertyListRef presetDict = ReadPresetFromPresetFile(auPresetFile); #pragma mark - #pragma mark __ The driving code #pragma mark - try { CAComponent comp(desc); // CAAUProcessor's constructor throws... so make sure the component is valid if (comp.IsValid() == false) { printf ("Can't Find Component\n"); desc.Print(); exit(1); } CAAUProcessor processor(comp); processor.AU().Comp().Print(); CAAudioFile srcFile; srcFile.Open(srcFilePath); UInt64 numInputSamples = srcFile.GetNumberFrames(); Float64 inputSecs = (numInputSamples / srcFile.GetFileDataFormat().mSampleRate); CAStreamBasicDescription procFormat (srcFile.GetFileDataFormat()); procFormat.SetCanonical (srcFile.GetFileDataFormat().NumberChannels(), false); printf ("Processing file: %s, %.1f secs [proc: %ld frames]\n", srcFilePath, inputSecs, numFrames); #if VERBOSE printf("\t"); procFormat.Print(); #endif srcFile.SetClientFormat (procFormat); AUOutputBL outputList(procFormat); // read the entire file into memory ReadBuffer* readBuf = new ReadBuffer; readBuf->readData = new AUOutputBL(procFormat); readBuf->totalInputFrames = numInputSamples; readBuf->readData->Allocate (numInputSamples); readBuf->readData->Prepare(); UInt32 readSamps = (UInt32)numInputSamples; srcFile.Read (readSamps, readBuf->readData->ABL()); AURenderCallbackStruct inputCallback; inputCallback.inputProc = MemoryInputCallback; inputCallback.inputProcRefCon = readBuf; OSStatus result; require_noerr (result = processor.EstablishInputCallback (inputCallback), home); require_noerr (result = processor.SetMaxFramesPerRender (numFrames), home); require_noerr (result = processor.Initialize (procFormat, numInputSamples), home); if (presetDict) { require_noerr (result = processor.SetAUPreset (presetDict), home); CFRelease (presetDict); } // this does ALL of the preflighting.. could be specialise for an OfflineAU type // to do this piecemeal and do a progress bar by using the OfflineAUPreflight method readBuf->lastInputFrames = 0; require_noerr (result = processor.Preflight (), home); float mean; // now do the processing.... { const int kThrasherSize = 4000000; char* thrasher = new char[kThrasherSize]; bool isDone = false; UInt32 numMeasures = 0; Float64 totalMSqrd = 0; Float64 totalM = 0; int i = 0; int discardResults = 3; // this is the render loop while (!isDone) { bool isSilence, postProcess; outputList.Prepare(); // have to do this every time... readBuf->lastInputFrames = 0; sLastReadTime = 0; memset (thrasher, numMeasures, kThrasherSize); UInt64 now = CAHostTimeBase::GetTheCurrentTime(); require_noerr (result = processor.Render (outputList.ABL(), numFrames, isSilence, &isDone, &postProcess), home); UInt64 renderTime = (CAHostTimeBase::GetTheCurrentTime() - now); if (i++ < discardResults) continue; if (!readBuf->lastInputFrames) break; Float64 renderTimeSecs = CAHostTimeBase::ConvertToNanos (renderTime - sLastReadTime) / 1.0e9; Float64 cpuTime = (renderTimeSecs / (readBuf->lastInputFrames / procFormat.mSampleRate)) * 100.; numMeasures++; totalMSqrd += (cpuTime * cpuTime); totalM += cpuTime; if (cpuTime > sMaxTime) sMaxTime = cpuTime; if (cpuTime < sMinTime) sMinTime = cpuTime; #if VERBOSE // printf ("current measure: %.2f\n", cpuTime); if (numMeasures % 5 == 0) { Float64 mean = totalM / numMeasures; // stdDev = (sum of Xsquared -((sum of X)*(sum of X)/N)) / (N-1)) Float64 stdDev = sqrt ((totalMSqrd - ((totalM * totalM) / numMeasures)) / (numMeasures-1.0)); printf ("ave: %.2f, min: %.2f, max: %.2f, stdev: %.2f, numMeasures: %ld, current: %f\n", mean, sMinTime, sMaxTime, stdDev, numMeasures, cpuTime); } #endif } delete [] thrasher; mean = totalM / numMeasures; // stdDev = (sum of Xsquared -((sum of X)*(sum of X)/N)) / (N-1)) Float64 stdDev = sqrt ((totalMSqrd - ((totalM * totalM) / numMeasures)) / (numMeasures-1.0)); printf ("ave: %.2f, min: %.2f, max: %.2f, sd: %.2f, sd / mean: %.2f%%\n", mean, sMinTime, sMaxTime, stdDev, (stdDev / mean * 100.)); } // we don't care about post-processing home: if (result) { printf ("Exit with bad result:%ld\n", result); exit(result); } if (readBuf) { delete readBuf->readData; delete readBuf; } CFStringRef str = comp.GetCompName(); UInt32 compNameLen = CFStringGetLength (str); CFStringRef presetName = NULL; if (auPresetFile) { CFPropertyListRef dict; if (processor.AU().GetAUPreset (dict) == noErr) { presetName = (CFStringRef)CFDictionaryGetValue((CFDictionaryRef)dict, CFSTR("name")); CFRelease (dict); } } UInt32 presetLen = presetName ? CFStringGetLength(presetName) : 0; UInt32 groupID = comp.Desc().componentSubType; char* cstr = (char*)malloc (compNameLen + presetLen + 2 + 1); CFStringGetCString (str, cstr, (CFStringGetLength (str) + 1), kCFStringEncodingASCII); if (presetName) { cstr[compNameLen] = ':'; cstr[compNameLen+1] = ':'; CFStringGetCString (presetName, cstr + compNameLen + 2, (CFStringGetLength (presetName) + 1), kCFStringEncodingASCII); int len = strlen(cstr); for (int i = 0; i < len; ++i) groupID += cstr[i]; } PerfResult("AU Profile", EndianU32_NtoB(groupID), cstr, mean, "%realtime"); free (cstr); } catch (CAXException &e) { char buf[256]; printf("Error: %s (%s)\n", e.mOperation, e.FormatError(buf)); exit(1); } catch (...) { printf("An unknown error occurred\n"); exit(1); } return 0; }
/************************************************************************* * * hu_XMLSearchForElementNameByUsage( inVendorID, inProductID, inUsagePage, inUsage, outCStr ) * * Purpose: Find an element string in the <HID_device_usage_strings.plist> resource( XML ) file * * Inputs: inVendorID - the elements vendor ID * inProductID - the elements product ID * inUsagePage - the elements usage page * inUsage - the elements usage * outCStr - address where result will be returned * * Returns: Boolean - if successful */ static Boolean hu_XMLSearchForElementNameByUsage(long inVendorID, long inProductID, long inUsagePage, long inUsage, char *outCStr) { Boolean results = FALSE; if ( !gUsageCFPropertyListRef ) { gUsageCFPropertyListRef = hu_XMLLoad( CFSTR( "HID_device_usage_strings"), CFSTR("plist") ); } if ( gUsageCFPropertyListRef ) { if ( CFDictionaryGetTypeID() == CFGetTypeID(gUsageCFPropertyListRef) ) { CFStringRef vendorKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%ld"), inVendorID); if ( vendorKeyCFStringRef ) { CFDictionaryRef vendorCFDictionaryRef; if ( CFDictionaryGetValueIfPresent(gUsageCFPropertyListRef, vendorKeyCFStringRef, (const void **) &vendorCFDictionaryRef) ) { CFStringRef vendorCFStringRef = NULL; if ( CFDictionaryGetValueIfPresent(vendorCFDictionaryRef, kNameKeyCFStringRef, (const void **) &vendorCFStringRef) ) { vendorCFStringRef = CFStringCreateCopy(kCFAllocatorDefault, vendorCFStringRef); } else { vendorCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("v: %ld"), inVendorID); // CFShow( vendorCFStringRef ); } CFStringRef productKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "%ld"), inProductID); CFDictionaryRef productCFDictionaryRef; if ( CFDictionaryGetValueIfPresent(vendorCFDictionaryRef, productKeyCFStringRef, (const void **) &productCFDictionaryRef) ) { CFStringRef fullCFStringRef = NULL; CFStringRef productCFStringRef; if ( CFDictionaryGetValueIfPresent(productCFDictionaryRef, kNameKeyCFStringRef, (const void **) &productCFStringRef) ) { // CFShow( productCFStringRef ); } CFStringRef usageKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "%ld:%ld"), inUsagePage, inUsage); CFStringRef usageCFStringRef; if ( CFDictionaryGetValueIfPresent(productCFDictionaryRef, usageKeyCFStringRef, (const void **) &usageCFStringRef) ) { #if VERBOSE_ELEMENT_NAMES fullCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "%@ %@ %@"), vendorCFStringRef, productCFStringRef, usageCFStringRef); #else fullCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@"), usageCFStringRef); #endif // VERBOSE_ELEMENT_NAMES // CFShow( usageCFStringRef ); } #if FAKE_MISSING_NAMES else { fullCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR( "%@ %@ # %@"), vendorCFStringRef, productCFStringRef, usageKeyCFStringRef); } #endif // FAKE_MISSING_NAMES if ( fullCFStringRef ) { // CFShow( fullCFStringRef ); results = CFStringGetCString(fullCFStringRef, outCStr, CFStringGetLength( fullCFStringRef) * sizeof(UniChar) + 1, kCFStringEncodingUTF8); CFRelease(fullCFStringRef); } CFRelease(usageKeyCFStringRef); } if ( vendorCFStringRef ) { CFRelease(vendorCFStringRef); } CFRelease(productKeyCFStringRef); } CFRelease(vendorKeyCFStringRef); } } // ++ CFRelease( gUsageCFPropertyListRef ); // Leak this ! } return (results); } // hu_XMLSearchForElementNameByUsage
int main(int argc, char **argv) { nsresult rv; char *lastSlash; char iniPath[MAXPATHLEN]; char greDir[MAXPATHLEN]; bool greFound = false; CFBundleRef appBundle = CFBundleGetMainBundle(); if (!appBundle) return 1; CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(appBundle); if (!resourcesURL) return 1; CFURLRef absResourcesURL = CFURLCopyAbsoluteURL(resourcesURL); CFRelease(resourcesURL); if (!absResourcesURL) return 1; CFURLRef iniFileURL = CFURLCreateCopyAppendingPathComponent(kCFAllocatorDefault, absResourcesURL, CFSTR("application.ini"), false); CFRelease(absResourcesURL); if (!iniFileURL) return 1; CFStringRef iniPathStr = CFURLCopyFileSystemPath(iniFileURL, kCFURLPOSIXPathStyle); CFRelease(iniFileURL); if (!iniPathStr) return 1; CFStringGetCString(iniPathStr, iniPath, sizeof(iniPath), kCFStringEncodingUTF8); CFRelease(iniPathStr); printf("iniPath = %s\n", iniPath); //////////////////////////////////////// if (!getExePath(greDir)) { return 1; } /*if (!getFrameworkPath(greDir)) { return 1; }*/ /*if (realpath(tmpPath, greDir)) { greFound = true; }*/ printf("greDir = %s\n", greDir); if (access(greDir, R_OK | X_OK) == 0) greFound = true; if (!greFound) { printf("Could not find the Mozilla runtime.\n"); return 1; } rv = XPCOMGlueStartup(greDir); if (NS_FAILED(rv)) { printf("Couldn't load XPCOM.\n"); return 1; } printf("Glue startup OK.\n"); ///////////////////////////////////////////////////// static const nsDynamicFunctionLoad kXULFuncs[] = { { "XRE_CreateAppData", (NSFuncPtr*) &XRE_CreateAppData }, { "XRE_FreeAppData", (NSFuncPtr*) &XRE_FreeAppData }, { "XRE_main", (NSFuncPtr*) &XRE_main }, { nullptr, nullptr } }; rv = XPCOMGlueLoadXULFunctions(kXULFuncs); if (NS_FAILED(rv)) { printf("Couldn't load XRE functions.\n"); return 1; } NS_LogInit(); int retval; nsXREAppData *pAppData = NULL; { nsCOMPtr<nsIFile> iniFile; // nsIFile *pIniFile; rv = NS_NewNativeLocalFile(nsDependentCString(iniPath), PR_FALSE, getter_AddRefs(iniFile)); //&pIniFile); //NS_ADDREF(pIniFile); if (NS_FAILED(rv)) { printf("Couldn't find application.ini file.\n"); return 1; } rv = XRE_CreateAppData(iniFile, &pAppData); //rv = XRE_CreateAppData(pIniFile, &pAppData); if (NS_FAILED(rv)) { printf("Error: couldn't parse application.ini.\n"); return 1; } } NS_ASSERTION(pAppData->directory, "Failed to get app directory."); { nsAutoString path; pAppData->directory->GetPath(path); nsAutoCString nsstr; ::CopyUTF16toUTF8(path, nsstr); printf("appData.directory=%s\n", nsstr.get()); } if (!pAppData->xreDirectory) { char xreDir[MAXPATHLEN]; if (!getFrameworkPath(xreDir)) return 1; rv = NS_NewNativeLocalFile(nsDependentCString(xreDir), PR_FALSE, &pAppData->xreDirectory); } printf("### ENTERING XRE_MAIN ###\n"); retval = XRE_main(argc, argv, pAppData, 0); printf("### LEAVING XRE_MAIN ###\n"); NS_LogTerm(); return retval; }
static void HIDGetDeviceInfo(io_object_t hidDevice, CFMutableDictionaryRef hidProperties, recDevice * pDevice) { CFMutableDictionaryRef usbProperties = 0; io_registry_entry_t parent1, parent2; /* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also * get dictionary for usb properties: step up two levels and get CF dictionary for USB properties */ if ((KERN_SUCCESS == IORegistryEntryGetParentEntry(hidDevice, kIOServicePlane, &parent1)) && (KERN_SUCCESS == IORegistryEntryGetParentEntry(parent1, kIOServicePlane, &parent2)) && (KERN_SUCCESS == IORegistryEntryCreateCFProperties(parent2, &usbProperties, kCFAllocatorDefault, kNilOptions))) { if (usbProperties) { CFTypeRef refCF = 0; /* get device info * try hid dictionary first, if fail then go to usb dictionary */ /* get product name */ refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductKey)); if (!refCF) refCF = CFDictionaryGetValue(usbProperties, CFSTR("USB Product Name")); if (refCF) { if (!CFStringGetCString (refCF, pDevice->product, 256, CFStringGetSystemEncoding())) SDL_SetError ("CFStringGetCString error retrieving pDevice->product."); } /* get usage page and usage */ refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDPrimaryUsagePageKey)); if (refCF) { if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->usagePage)) SDL_SetError ("CFNumberGetValue error retrieving pDevice->usagePage."); refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDPrimaryUsageKey)); if (refCF) if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->usage)) SDL_SetError ("CFNumberGetValue error retrieving pDevice->usage."); } refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDVendorIDKey)); if (refCF) { if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->guid.data[0])) SDL_SetError ("CFNumberGetValue error retrieving pDevice->guid."); } refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductIDKey)); if (refCF) { if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->guid.data[8])) SDL_SetError ("CFNumberGetValue error retrieving pDevice->guid[8]."); } if (NULL == refCF) { /* get top level element HID usage page or usage */ /* use top level element instead */ CFTypeRef refCFTopElement = 0; refCFTopElement = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDElementKey)); { /* refCFTopElement points to an array of element dictionaries */ CFRange range = { 0, CFArrayGetCount(refCFTopElement) }; CFArrayApplyFunction(refCFTopElement, range, HIDTopLevelElementHandler, pDevice); } } CFRelease(usbProperties); } else SDL_SetError ("IORegistryEntryCreateCFProperties failed to create usbProperties."); if (kIOReturnSuccess != IOObjectRelease(parent2)) SDL_SetError("IOObjectRelease error with parent2."); if (kIOReturnSuccess != IOObjectRelease(parent1)) SDL_SetError("IOObjectRelease error with parent1."); } }
// utility routine to dump device info void HIDDumpDeviceInfo(IOHIDDeviceRef inIOHIDDeviceRef) { char cstring[256]; printf("Device: %p = { ", inIOHIDDeviceRef); char manufacturer[256] = ""; // name of manufacturer CFStringRef tCFStringRef = IOHIDDevice_GetManufacturer(inIOHIDDeviceRef); if (tCFStringRef) { (void) CFStringGetCString(tCFStringRef, manufacturer, sizeof(manufacturer), kCFStringEncodingUTF8); } char product[256] = ""; // name of product tCFStringRef = IOHIDDevice_GetProduct(inIOHIDDeviceRef); if (tCFStringRef) { (void) CFStringGetCString(tCFStringRef, product, sizeof(product), kCFStringEncodingUTF8); } printf("%s - %s, ", manufacturer, product); long vendorID = IOHIDDevice_GetVendorID(inIOHIDDeviceRef); if (vendorID) { if ( HIDGetVendorNameFromVendorID(vendorID, cstring) ) { printf(" vendorID: 0x%04lX (\"%s\"), ", vendorID, cstring); } else { printf(" vendorID: 0x%04lX, ", vendorID); } } long productID = IOHIDDevice_GetProductID(inIOHIDDeviceRef); if (productID) { if ( HIDGetProductNameFromVendorProductID(vendorID, productID, cstring) ) { printf(" productID: 0x%04lX (\"%s\"), ", productID, cstring); } else { printf(" productID: 0x%04lX, ", productID); } } 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); tCFStringRef = HIDCopyUsageName(usagePage, usage); if (tCFStringRef) { (void) CFStringGetCString(tCFStringRef, cstring, sizeof(cstring), kCFStringEncodingUTF8); printf("\"%s\", ", cstring); CFRelease(tCFStringRef); } tCFStringRef = IOHIDDevice_GetTransport(inIOHIDDeviceRef); if (tCFStringRef) { (void) 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) { (void) 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 false 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 // if false 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); } printf("}\n"); fflush(stdout); } // HIDDumpDeviceInfo
QString Q3FileDialog::macGetSaveFileName(const QString &start, const QString &filter, QString *, QWidget *parent, const char* /*name*/, const QString& caption, QString *selectedFilter) { OSErr err; QString retstr; NavDialogCreationOptions options; NavGetDefaultDialogCreationOptions(&options); static const int w = 450, h = 350; options.optionFlags |= kNavDontConfirmReplacement; options.modality = kWindowModalityAppModal; options.location.h = options.location.v = -1; QString workingDir; QString initialSelection; if (!start.isEmpty()) { Q3UrlOperator u(encodeFileName(start)); if (u.isLocalFile() && QFileInfo(u.path()).isDir()) { workingDir = start; } else { if (u.isLocalFile()) { QFileInfo fi(u.dirPath()); if (fi.exists()) { workingDir = u.dirPath(); initialSelection = u.fileName(); } } else { workingDir = u.toString(); } } if (!initialSelection.isEmpty()) options.saveFileName = CFStringCreateWithCharacters(0, (UniChar *)initialSelection.unicode(), initialSelection.length()); } if(!caption.isEmpty()) options.windowTitle = CFStringCreateWithCharacters(NULL, (UniChar *)caption.unicode(), caption.length()); if(parent && parent->isVisible()) { Qt::WindowType wt = parent->window()->windowType(); if (wt != Qt::Desktop && wt != Qt::Sheet && wt != Qt::Drawer) { options.modality = kWindowModalityWindowModal; options.parentWindow = qt_mac_window_for(parent); } else { parent = parent->window(); QString s = parent->windowTitle(); options.clientName = CFStringCreateWithCharacters(NULL, (UniChar *)s.unicode(), s.length()); options.location.h = (parent->x() + (parent->width() / 2)) - (w / 2); options.location.v = (parent->y() + (parent->height() / 2)) - (h / 2); QRect r = QApplication::desktop()->screenGeometry( QApplication::desktop()->screenNumber(parent)); if(options.location.h + w > r.right()) options.location.h -= (options.location.h + w) - r.right() + 10; if(options.location.v + h > r.bottom()) options.location.v -= (options.location.v + h) - r.bottom() + 10; } } else if(QWidget *p = qApp->mainWidget()) { static int last_screen = -1; int scr = QApplication::desktop()->screenNumber(p); if(last_screen != scr) { QRect r = QApplication::desktop()->screenGeometry(scr); options.location.h = (r.x() + (r.width() / 2)) - (w / 2); options.location.v = (r.y() + (r.height() / 2)) - (h / 2); } } QList<qt_mac_filter_name*> filts = makeFiltersList(filter); qt_mac_nav_filter_type t; t.index = 0; t.filts = &filts; if(filts.count() > 1) { int i = 0; CFStringRef *arr = (CFStringRef *)malloc(sizeof(CFStringRef) * filts.count()); for (QList<qt_mac_filter_name*>::Iterator it = filts.begin(); it != filts.end(); ++it) { QString rg = (*it)->description; arr[i++] = CFStringCreateWithCharacters(NULL, (UniChar *)rg.unicode(), rg.length()); } options.popupExtension = CFArrayCreate(NULL, (const void **)arr, filts.count(), NULL); } NavDialogRef dlg; if(NavCreatePutFileDialog(&options, 'cute', kNavGenericSignature, make_navProcUPP(), (void *) (filts.isEmpty() ? NULL : &t), &dlg)) { qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__); return retstr; } if (!workingDir.isEmpty()) { FSRef fsref; if (qt_mac_create_fsref(workingDir, &fsref) == noErr) { AEDesc desc; if (AECreateDesc(typeFSRef, &fsref, sizeof(FSRef), &desc) == noErr) NavCustomControl(dlg, kNavCtlSetLocation, (void*)&desc); } } NavDialogRun(dlg); if (selectedFilter) { NavMenuItemSpec navSpec; bzero(&navSpec, sizeof(NavMenuItemSpec)); qt_mac_filter_name *sel_filt_name = makeFiltersList(*selectedFilter).at(0); for (int i = 0; i < filts.count(); ++i) { const qt_mac_filter_name *filter = filts.at(i); if (sel_filt_name->description == filter->description && sel_filt_name->regxp == filter->regxp && sel_filt_name->filter == filter->filter) { navSpec.menuType = i; break; } } NavCustomControl(dlg, kNavCtlSelectCustomType, &navSpec); } if(options.modality == kWindowModalityWindowModal) { //simulate modality QWidget modal_widg(parent, __FILE__ "__modal_dlg", Qt::WType_TopLevel | Qt::WStyle_Customize | Qt::WStyle_DialogBorder); modal_widg.createWinId(); QApplicationPrivate::enterModal(&modal_widg); while(g_nav_blocking) qApp->processEvents(QEventLoop::WaitForMoreEvents); QApplicationPrivate::leaveModal(&modal_widg); } if(NavDialogGetUserAction(dlg) != kNavUserActionSaveAs) { NavDialogDispose(dlg); return retstr; } NavReplyRecord ret; NavDialogGetReply(dlg, &ret); NavDialogDispose(dlg); long count; err = AECountItems(&(ret.selection), &count); if(!ret.validRecord || err != noErr || !count) { NavDisposeReply(&ret); return retstr; } AEKeyword keyword; DescType type; Size size; FSRef ref; err = AEGetNthPtr(&(ret.selection), 1, typeFSRef, &keyword, &type, &ref, sizeof(ref), &size); if(err == noErr) { if(!str_buffer) { qAddPostRoutine(cleanup_str_buffer); str_buffer = (UInt8 *)malloc(1024); } FSRefMakePath(&ref, str_buffer, 1024); retstr = QString::fromUtf8((const char *)str_buffer); //now filename CFStringGetCString(ret.saveFileName, (char *)str_buffer, 1024, kCFStringEncodingUTF8); retstr += QLatin1String("/") + QString::fromUtf8((const char *)str_buffer); } NavDisposeReply(&ret); if(selectedFilter) *selectedFilter = filts.at(t.index)->filter; while (!filts.isEmpty()) delete filts.takeFirst(); return retstr; }
static void build_device_list(int iscapture, COREAUDIO_DeviceList ** devices, int *devCount) { OSStatus result = noErr; UInt32 size = 0; AudioObjectPropertyAddress propaddr; AudioObjectID *devs = NULL; UInt32 i = 0; UInt32 max = 0; free_device_list(devices, devCount); propaddr.mSelector = kAudioHardwarePropertyDevices; propaddr.mScope = kAudioObjectPropertyScopeGlobal; propaddr.mElement = kAudioObjectPropertyElementMaster; result = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &propaddr, 0, NULL, &size); if (result != kAudioHardwareNoError) return; devs = (AudioDeviceID *) alloca(size); if (devs == NULL) return; max = size / sizeof(AudioDeviceID); *devices = (COREAUDIO_DeviceList *) SDL_malloc(max * sizeof(**devices)); if (*devices == NULL) return; result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propaddr, 0, NULL, &size, devs); if (result != kAudioHardwareNoError) return; for (i = 0; i < max; i++) { CFStringRef cfstr = NULL; char *ptr = NULL; AudioObjectID dev = devs[i]; AudioBufferList *buflist = NULL; int usable = 0; CFIndex len = 0; propaddr.mSelector = kAudioDevicePropertyStreamConfiguration; propaddr.mScope = iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; propaddr.mElement = kAudioObjectPropertyElementMaster; result = AudioObjectGetPropertyDataSize(dev, &propaddr, 0, NULL, &size); if (result != noErr) continue; buflist = (AudioBufferList *) SDL_malloc(size); if (buflist == NULL) continue; result = AudioObjectGetPropertyData(dev, &propaddr, 0, NULL, &size, buflist); if (result == noErr) { UInt32 j; for (j = 0; j < buflist->mNumberBuffers; j++) { if (buflist->mBuffers[j].mNumberChannels > 0) { usable = 1; break; } } } SDL_free(buflist); if (!usable) continue; size = sizeof(CFStringRef); propaddr.mSelector = kAudioDevicePropertyDeviceNameCFString; propaddr.mScope = iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; propaddr.mElement = kAudioObjectPropertyElementMaster; result = AudioObjectGetPropertyData(dev, &propaddr, 0, NULL, &size, &cfstr); if (result != kAudioHardwareNoError) continue; len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfstr), kCFStringEncodingUTF8); ptr = (char *) SDL_malloc(len + 1); usable = ((ptr != NULL) && (CFStringGetCString (cfstr, ptr, len + 1, kCFStringEncodingUTF8))); CFRelease(cfstr); if (usable) { len = strlen(ptr); /* Some devices have whitespace at the end...trim it. */ while ((len > 0) && (ptr[len - 1] == ' ')) { len--; } usable = (len > 0); } if (!usable) { SDL_free(ptr); } else { ptr[len] = '\0'; #if DEBUG_COREAUDIO printf("COREAUDIO: Found %s device #%d: '%s' (devid %d)\n", ((iscapture) ? "capture" : "output"), (int) *devCount, ptr, (int) dev); #endif (*devices)[*devCount].id = dev; (*devices)[*devCount].name = ptr; (*devCount)++; } } }
SecKeyRef SecKeyGenerateSymmetric(CFDictionaryRef parameters, CFErrorRef *error) { OSStatus result = paramErr; // default result for an early exit SecKeyRef key = NULL; SecKeychainRef keychain = NULL; SecAccessRef access; CFStringRef label; CFStringRef appLabel; CFStringRef appTag; CFStringRef dateLabel = NULL; CSSM_ALGORITHMS algorithm; uint32 keySizeInBits; CSSM_KEYUSE keyUsage; uint32 keyAttr = CSSM_KEYATTR_RETURN_DEFAULT; CSSM_KEYCLASS keyClass; CFTypeRef value; Boolean isPermanent; Boolean isExtractable; // verify keychain parameter if (!CFDictionaryGetValueIfPresent(parameters, kSecUseKeychain, (const void **)&keychain)) keychain = NULL; else if (SecKeychainGetTypeID() != CFGetTypeID(keychain)) { keychain = NULL; goto errorExit; } else CFRetain(keychain); // verify permanent parameter if (!CFDictionaryGetValueIfPresent(parameters, kSecAttrIsPermanent, (const void **)&value)) isPermanent = false; else if (!value || (CFBooleanGetTypeID() != CFGetTypeID(value))) goto errorExit; else isPermanent = CFEqual(kCFBooleanTrue, value); if (isPermanent) { if (keychain == NULL) { // no keychain was specified, so use the default keychain result = SecKeychainCopyDefault(&keychain); } keyAttr |= CSSM_KEYATTR_PERMANENT; } // verify extractable parameter if (!CFDictionaryGetValueIfPresent(parameters, kSecAttrIsExtractable, (const void **)&value)) isExtractable = true; // default to extractable if value not specified else if (!value || (CFBooleanGetTypeID() != CFGetTypeID(value))) goto errorExit; else isExtractable = CFEqual(kCFBooleanTrue, value); if (isExtractable) keyAttr |= CSSM_KEYATTR_EXTRACTABLE; // verify access parameter if (!CFDictionaryGetValueIfPresent(parameters, kSecAttrAccess, (const void **)&access)) access = NULL; else if (SecAccessGetTypeID() != CFGetTypeID(access)) goto errorExit; // verify label parameter if (!CFDictionaryGetValueIfPresent(parameters, kSecAttrLabel, (const void **)&label)) label = (dateLabel = utilCopyDefaultKeyLabel()); // no label provided, so use default else if (CFStringGetTypeID() != CFGetTypeID(label)) goto errorExit; // verify application label parameter if (!CFDictionaryGetValueIfPresent(parameters, kSecAttrApplicationLabel, (const void **)&appLabel)) appLabel = (dateLabel) ? dateLabel : (dateLabel = utilCopyDefaultKeyLabel()); else if (CFStringGetTypeID() != CFGetTypeID(appLabel)) goto errorExit; // verify application tag parameter if (!CFDictionaryGetValueIfPresent(parameters, kSecAttrApplicationTag, (const void **)&appTag)) appTag = NULL; else if (CFStringGetTypeID() != CFGetTypeID(appTag)) goto errorExit; utilGetKeyParametersFromCFDict(parameters, &algorithm, &keySizeInBits, &keyUsage, &keyClass); if (!keychain) { // the generated key will not be stored in any keychain result = SecKeyGenerate(keychain, algorithm, keySizeInBits, 0, keyUsage, keyAttr, access, &key); } else { // we can set the label attributes on the generated key if it's a keychain item size_t labelBufLen = (label) ? (size_t)CFStringGetMaximumSizeForEncoding(CFStringGetLength(label), kCFStringEncodingUTF8) + 1 : 0; char *labelBuf = (char *)malloc(labelBufLen); size_t appLabelBufLen = (appLabel) ? (size_t)CFStringGetMaximumSizeForEncoding(CFStringGetLength(appLabel), kCFStringEncodingUTF8) + 1 : 0; char *appLabelBuf = (char *)malloc(appLabelBufLen); size_t appTagBufLen = (appTag) ? (size_t)CFStringGetMaximumSizeForEncoding(CFStringGetLength(appTag), kCFStringEncodingUTF8) + 1 : 0; char *appTagBuf = (char *)malloc(appTagBufLen); if (label && !CFStringGetCString(label, labelBuf, labelBufLen-1, kCFStringEncodingUTF8)) labelBuf[0]=0; if (appLabel && !CFStringGetCString(appLabel, appLabelBuf, appLabelBufLen-1, kCFStringEncodingUTF8)) appLabelBuf[0]=0; if (appTag && !CFStringGetCString(appTag, appTagBuf, appTagBufLen-1, kCFStringEncodingUTF8)) appTagBuf[0]=0; SecKeychainAttribute attrs[] = { { kSecKeyPrintName, strlen(labelBuf), (char *)labelBuf }, { kSecKeyLabel, strlen(appLabelBuf), (char *)appLabelBuf }, { kSecKeyApplicationTag, strlen(appTagBuf), (char *)appTagBuf } }; SecKeychainAttributeList attributes = { sizeof(attrs) / sizeof(attrs[0]), attrs }; if (!appTag) --attributes.count; result = SecKeyGenerateWithAttributes(&attributes, keychain, algorithm, keySizeInBits, 0, keyUsage, keyAttr, access, &key); free(labelBuf); free(appLabelBuf); free(appTagBuf); } errorExit: if (result && error) { *error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainOSStatus, result, NULL); } if (dateLabel) CFRelease(dateLabel); if (keychain) CFRelease(keychain); return key; }
/* * Update the counters associated with a single disk. */ static void update_disk_stats(struct diskstat *disk, CFDictionaryRef pproperties, CFDictionaryRef properties) { CFDictionaryRef statistics; CFStringRef name; CFNumberRef number; memset(disk, 0, sizeof(struct diskstat)); /* Get name from the drive properties */ name = (CFStringRef) CFDictionaryGetValue(pproperties, CFSTR(kIOBSDNameKey)); if(name == NULL) return; /* Not much we can do with no name */ CFStringGetCString(name, disk->name, DEVNAMEMAX, CFStringGetSystemEncoding()); /* Get the blocksize from the drive properties */ number = (CFNumberRef) CFDictionaryGetValue(pproperties, CFSTR(kIOMediaPreferredBlockSizeKey)); if(number == NULL) return; /* Not much we can do with no number */ CFNumberGetValue(number, kCFNumberSInt64Type, &disk->blocksize); /* Get the statistics from the device properties. */ statistics = (CFDictionaryRef) CFDictionaryGetValue(properties, CFSTR(kIOBlockStorageDriverStatisticsKey)); if (statistics) { number = (CFNumberRef) CFDictionaryGetValue(statistics, CFSTR(kIOBlockStorageDriverStatisticsReadsKey)); if (number) CFNumberGetValue(number, kCFNumberSInt64Type, &disk->read); number = (CFNumberRef) CFDictionaryGetValue(statistics, CFSTR(kIOBlockStorageDriverStatisticsWritesKey)); if (number) CFNumberGetValue(number, kCFNumberSInt64Type, &disk->write); number = (CFNumberRef) CFDictionaryGetValue(statistics, CFSTR(kIOBlockStorageDriverStatisticsBytesReadKey)); if (number) CFNumberGetValue(number, kCFNumberSInt64Type, &disk->read_bytes); number = (CFNumberRef) CFDictionaryGetValue(statistics, CFSTR(kIOBlockStorageDriverStatisticsBytesWrittenKey)); if (number) CFNumberGetValue(number, kCFNumberSInt64Type, &disk->write_bytes); number = (CFNumberRef) CFDictionaryGetValue(statistics, CFSTR(kIOBlockStorageDriverStatisticsLatentReadTimeKey)); if (number) CFNumberGetValue(number, kCFNumberSInt64Type, &disk->read_time); number = (CFNumberRef) CFDictionaryGetValue(statistics, CFSTR(kIOBlockStorageDriverStatisticsLatentWriteTimeKey)); if (number) CFNumberGetValue(number, kCFNumberSInt64Type, &disk->write_time); } }
static OSStatus SetKeyLabelAndTag(SecKeyRef keyRef, CFTypeRef label, CFDataRef tag) { int numToModify = 0; if (label != NULL) { numToModify += 1; } if (tag != NULL) { numToModify += 1; } if (numToModify == 0) { return noErr; } SecKeychainAttributeList attrList; SecKeychainAttribute attributes[numToModify]; int i = 0; if (label != NULL) { if (CFStringGetTypeID() == CFGetTypeID(label)) { CFStringRef label_string = static_cast<CFStringRef>(label); attributes[i].tag = kSecKeyPrintName; attributes[i].data = (void*) CFStringGetCStringPtr(label_string, kCFStringEncodingUTF8); if (NULL == attributes[i].data) { CFIndex buffer_length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(label_string), kCFStringEncodingUTF8); attributes[i].data = alloca((size_t)buffer_length); if (NULL == attributes[i].data) { UnixError::throwMe(ENOMEM); } if (!CFStringGetCString(label_string, static_cast<char *>(attributes[i].data), buffer_length, kCFStringEncodingUTF8)) { MacOSError::throwMe(paramErr); } } attributes[i].length = strlen(static_cast<char *>(attributes[i].data)); } else if (CFDataGetTypeID() == CFGetTypeID(label)) { // 10.6 bug compatibility CFDataRef label_data = static_cast<CFDataRef>(label); attributes[i].tag = kSecKeyLabel; attributes[i].data = (void*) CFDataGetBytePtr(label_data); attributes[i].length = CFDataGetLength(label_data); } else { MacOSError::throwMe(paramErr); } i++; } if (tag != NULL) { attributes[i].tag = kSecKeyApplicationTag; attributes[i].data = (void*) CFDataGetBytePtr(tag); attributes[i].length = CFDataGetLength(tag); i++; } attrList.count = numToModify; attrList.attr = attributes; return SecKeychainItemModifyAttributesAndData((SecKeychainItemRef) keyRef, &attrList, 0, NULL); }
static gchar* get_darwin_locale (void) { static gchar *darwin_locale = NULL; CFLocaleRef locale = NULL; CFStringRef locale_language = NULL; CFStringRef locale_country = NULL; CFStringRef locale_script = NULL; CFStringRef locale_cfstr = NULL; CFIndex bytes_converted; CFIndex bytes_written; CFIndex len; int i; if (darwin_locale != NULL) return g_strdup (darwin_locale); locale = CFLocaleCopyCurrent (); if (locale) { locale_language = CFLocaleGetValue (locale, kCFLocaleLanguageCode); if (locale_language != NULL && CFStringGetBytes(locale_language, CFRangeMake (0, CFStringGetLength (locale_language)), kCFStringEncodingMacRoman, 0, FALSE, NULL, 0, &bytes_converted) > 0) { len = bytes_converted + 1; locale_country = CFLocaleGetValue (locale, kCFLocaleCountryCode); if (locale_country != NULL && CFStringGetBytes (locale_country, CFRangeMake (0, CFStringGetLength (locale_country)), kCFStringEncodingMacRoman, 0, FALSE, NULL, 0, &bytes_converted) > 0) { len += bytes_converted + 1; locale_script = CFLocaleGetValue (locale, kCFLocaleScriptCode); if (locale_script != NULL && CFStringGetBytes (locale_script, CFRangeMake (0, CFStringGetLength (locale_script)), kCFStringEncodingMacRoman, 0, FALSE, NULL, 0, &bytes_converted) > 0) { len += bytes_converted + 1; } darwin_locale = (char *) malloc (len + 1); CFStringGetBytes (locale_language, CFRangeMake (0, CFStringGetLength (locale_language)), kCFStringEncodingMacRoman, 0, FALSE, (UInt8 *) darwin_locale, len, &bytes_converted); darwin_locale[bytes_converted] = '-'; bytes_written = bytes_converted + 1; if (locale_script != NULL && CFStringGetBytes (locale_script, CFRangeMake (0, CFStringGetLength (locale_script)), kCFStringEncodingMacRoman, 0, FALSE, (UInt8 *) &darwin_locale[bytes_written], len - bytes_written, &bytes_converted) > 0) { darwin_locale[bytes_written + bytes_converted] = '-'; bytes_written += bytes_converted + 1; } CFStringGetBytes (locale_country, CFRangeMake (0, CFStringGetLength (locale_country)), kCFStringEncodingMacRoman, 0, FALSE, (UInt8 *) &darwin_locale[bytes_written], len - bytes_written, &bytes_converted); darwin_locale[bytes_written + bytes_converted] = '\0'; } } if (darwin_locale == NULL) { locale_cfstr = CFLocaleGetIdentifier (locale); if (locale_cfstr) { len = CFStringGetMaximumSizeForEncoding (CFStringGetLength (locale_cfstr), kCFStringEncodingMacRoman) + 1; darwin_locale = (char *) malloc (len); if (!CFStringGetCString (locale_cfstr, darwin_locale, len, kCFStringEncodingMacRoman)) { free (darwin_locale); CFRelease (locale); darwin_locale = NULL; return NULL; } for (i = 0; i < strlen (darwin_locale); i++) if (darwin_locale [i] == '_') darwin_locale [i] = '-'; } } CFRelease (locale); } return g_strdup (darwin_locale); }
OSStatus LLFilePicker::doNavSaveDialog(ESaveFilter filter, const std::string& filename) { OSStatus error = noErr; NavDialogRef navRef = NULL; NavReplyRecord navReply; memset(&navReply, 0, sizeof(navReply)); // Setup the type, creator, and extension OSType type, creator; CFStringRef extension = NULL; switch (filter) { case FFSAVE_WAV: type = 'WAVE'; creator = 'TVOD'; extension = CFSTR(".wav"); break; case FFSAVE_TGA: type = 'TPIC'; creator = 'prvw'; extension = CFSTR(".tga"); break; case FFSAVE_BMP: type = 'BMPf'; creator = 'prvw'; extension = CFSTR(".bmp"); break; case FFSAVE_JPEG: type = 'JPEG'; creator = 'prvw'; extension = CFSTR(".jpeg"); break; case FFSAVE_PNG: type = 'PNG '; creator = 'prvw'; extension = CFSTR(".png"); break; case FFSAVE_AVI: type = '\?\?\?\?'; creator = '\?\?\?\?'; extension = CFSTR(".mov"); break; case FFSAVE_ANIM: type = '\?\?\?\?'; creator = '\?\?\?\?'; extension = CFSTR(".xaf"); break; #ifdef _CORY_TESTING case FFSAVE_GEOMETRY: type = '\?\?\?\?'; creator = '\?\?\?\?'; extension = CFSTR(".slg"); break; #endif case FFSAVE_RAW: type = '\?\?\?\?'; creator = '\?\?\?\?'; extension = CFSTR(".raw"); break; case FFSAVE_J2C: type = '\?\?\?\?'; creator = 'prvw'; extension = CFSTR(".j2c"); break; case FFSAVE_ALL: default: type = '\?\?\?\?'; creator = '\?\?\?\?'; extension = CFSTR(""); break; } // Create the dialog error = NavCreatePutFileDialog(&mNavOptions, type, creator, NULL, NULL, &navRef); if (error == noErr) { CFStringRef nameString = NULL; bool hasExtension = true; // Create a CFString of the initial file name if (!filename.empty()) nameString = CFStringCreateWithCString(NULL, filename.c_str(), kCFStringEncodingUTF8); else nameString = CFSTR("Untitled"); // Add the extension if one was not provided if (nameString && !CFStringHasSuffix(nameString, extension)) { CFStringRef tempString = nameString; hasExtension = false; nameString = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@%@"), tempString, extension); CFRelease(tempString); } // Set the name in the dialog if (nameString) { error = NavDialogSetSaveFileName(navRef, nameString); CFRelease(nameString); } else { error = paramErr; } } gViewerWindow->mWindow->beforeDialog(); // Run the dialog if (error == noErr) error = NavDialogRun(navRef); gViewerWindow->mWindow->afterDialog(); if (error == noErr) error = NavDialogGetReply(navRef, &navReply); if (navRef) NavDialogDispose(navRef); if (error == noErr && navReply.validRecord) { SInt32 count = 0; // AE indexes are 1 based... error = AECountItems(&navReply.selection, &count); if (count > 0) { // Get the FSRef to the containing folder FSRef fsRef; AEKeyword theAEKeyword; DescType typeCode; Size actualSize = 0; memset(&fsRef, 0, sizeof(fsRef)); error = AEGetNthPtr(&navReply.selection, 1, typeFSRef, &theAEKeyword, &typeCode, &fsRef, sizeof(fsRef), &actualSize); if (error == noErr) { char path[PATH_MAX]; /*Flawfinder: ignore*/ char newFileName[SINGLE_FILENAME_BUFFER_SIZE]; /*Flawfinder: ignore*/ error = FSRefMakePath(&fsRef, (UInt8*)path, PATH_MAX); if (error == noErr) { if (CFStringGetCString(navReply.saveFileName, newFileName, sizeof(newFileName), kCFStringEncodingUTF8)) { mFiles.push_back(std::string(path) + "/" + std::string(newFileName)); } else { error = paramErr; } } else { error = paramErr; } } } } return error; }
PsychError SCREENComputer(void) { const char *majorStructFieldNames[]={"macintosh", "windows", "osx" ,"linux", "kern", "hw", "processUserLongName", "processUserShortName", "consoleUserName", "machineName", "localHostName", "location", "MACAddress", "system", "gstreamer", "supported" }; const char *kernStructFieldNames[]={"ostype", "osrelease", "osrevision", "version","hostname"}; const char *hwStructFieldNames[]={"machine", "model", "ncpu", "physmem", "usermem", "busfreq", "cpufreq"}; int numMajorStructDimensions=-1, numKernStructDimensions=-1, numHwStructDimensions=-1; int numMajorStructFieldNames=16, numKernStructFieldNames=5, numHwStructFieldNames=7; PsychGenericScriptType *kernStruct, *hwStruct, *majorStruct; //char tempStr[CTL_MAXNAME]; //this seems like a bug in Darwin, CTL_MAXNAME is shorter than the longest name. char tempStr[256], *ethernetMACStr; size_t tempIntSize, tempStrSize, tempULongIntSize; int mib[2]; int tempInt; psych_uint64 tempULongInt; char *tempStrPtr; CFStringRef tempCFStringRef; psych_bool stringSuccess; int stringLengthChars, ethernetMACStrSizeBytes; long gestaltResult; OSErr gestaltError; int i,strIndex, bcdDigit, lengthSystemVersionString; int osMajor, osMinor, osBugfix; char systemVersionStr[256]; //all subfunctions should have these two lines PsychPushHelp(useString, synopsisString, seeAlsoString); if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);}; PsychErrorExit(PsychCapNumOutputArgs(1)); PsychErrorExit(PsychCapNumInputArgs(0)); //fill the major struct PsychAllocOutStructArray(1, FALSE, numMajorStructDimensions, numMajorStructFieldNames, majorStructFieldNames, &majorStruct); PsychSetStructArrayDoubleElement("macintosh", 0, 0, majorStruct); PsychSetStructArrayDoubleElement("windows", 0, 0, majorStruct); PsychSetStructArrayDoubleElement("linux", 0, 0, majorStruct); PsychSetStructArrayDoubleElement("osx", 0, 1, majorStruct); // Official support status: PsychSetStructArrayStringElement("supported", 0, (char*) PsychSupportStatus(), majorStruct); // GStreamer availability and rough version: #if defined(PTB_USE_GSTREAMER) #if GST_CHECK_VERSION(1,0,0) PsychSetStructArrayDoubleElement("gstreamer", 0, 1 * 10000 + 0 * 100 + 0, majorStruct); #else PsychSetStructArrayDoubleElement("gstreamer", 0, 0 * 10000 + 10 * 100 + 0, majorStruct); #endif #else PsychSetStructArrayDoubleElement("gstreamer", 0, 0, majorStruct); #endif //fill the kern struct and implant it within the major struct PsychAllocOutStructArray(-1, FALSE, numKernStructDimensions, numKernStructFieldNames, kernStructFieldNames, &kernStruct); mib[0]=CTL_KERN; mib[1]=KERN_OSTYPE; tempStrSize=sizeof(tempStr); ReportSysctlError(sysctl(mib, 2, tempStr, &tempStrSize, NULL, 0)); PsychSetStructArrayStringElement("ostype", 0, tempStr, kernStruct); mib[1]=KERN_OSRELEASE; tempStrSize=sizeof(tempStr); ReportSysctlError(sysctl(mib, 2, tempStr, &tempStrSize, NULL, 0)); PsychSetStructArrayStringElement("osrelease", 0, tempStr, kernStruct); mib[1]=KERN_OSREV; tempIntSize=sizeof(tempInt); ReportSysctlError(sysctl(mib, 2, &tempInt, &tempIntSize, NULL, 0)); PsychSetStructArrayDoubleElement("osrevision", 0, (double)tempInt, kernStruct); mib[1]=KERN_VERSION; tempStrSize=sizeof(tempStr); ReportSysctlError(sysctl(mib, 2, tempStr, &tempStrSize, NULL, 0)); PsychSetStructArrayStringElement("version", 0, tempStr, kernStruct); mib[1]=KERN_HOSTNAME; tempStrSize=sizeof(tempStr); ReportSysctlError(sysctl(mib, 2, tempStr, &tempStrSize, NULL, 0)); PsychSetStructArrayStringElement("hostname", 0, tempStr, kernStruct); PsychSetStructArrayStructElement("kern",0, kernStruct, majorStruct); //fill the hw struct and implant it within the major struct PsychAllocOutStructArray(-1, FALSE, numHwStructDimensions, numHwStructFieldNames, hwStructFieldNames, &hwStruct); mib[0]=CTL_HW; mib[1]=HW_MACHINE; tempStrSize=sizeof(tempStr); ReportSysctlError(sysctl(mib, 2, tempStr, &tempStrSize, NULL, 0)); PsychSetStructArrayStringElement("machine", 0, tempStr, hwStruct); mib[1]=HW_MODEL; tempStrSize=sizeof(tempStr); ReportSysctlError(sysctl(mib, 2, tempStr, &tempStrSize, NULL, 0)); PsychSetStructArrayStringElement("model", 0, tempStr, hwStruct); mib[1]=HW_NCPU; tempIntSize=sizeof(tempInt); ReportSysctlError(sysctl(mib, 2, &tempInt, &tempIntSize, NULL, 0)); PsychSetStructArrayDoubleElement("ncpu", 0, (double)tempInt, hwStruct); mib[1]=HW_MEMSIZE; tempULongIntSize=sizeof(tempULongInt); tempULongInt = 0; ReportSysctlError(sysctl(mib, 2, &tempULongInt, &tempULongIntSize, NULL, 0)); PsychSetStructArrayDoubleElement("physmem", 0, (double)tempULongInt, hwStruct); mib[1]=HW_USERMEM; tempULongIntSize=sizeof(tempULongInt); tempULongInt = 0; ReportSysctlError(sysctlbyname("hw.usermem", &tempULongInt, &tempULongIntSize, NULL, 0)); PsychSetStructArrayDoubleElement("usermem", 0, (double)tempULongInt, hwStruct); mib[1]=HW_BUS_FREQ; tempULongIntSize=sizeof(tempULongInt); tempULongInt = 0; ReportSysctlError(sysctlbyname("hw.busfrequency", &tempULongInt, &tempULongIntSize, NULL, 0)); PsychSetStructArrayDoubleElement("busfreq", 0, (double)tempULongInt, hwStruct); mib[1]=HW_CPU_FREQ; tempULongIntSize=sizeof(tempULongInt); tempULongInt = 0; ReportSysctlError(sysctlbyname("hw.cpufrequency", &tempULongInt, &tempULongIntSize, NULL, 0)); PsychSetStructArrayDoubleElement("cpufreq", 0, (double)tempULongInt, hwStruct); PsychSetStructArrayStructElement("hw",0, hwStruct, majorStruct); //fill in the process user, console user and machine name in the root struct. tempCFStringRef = SCDynamicStoreCopyComputerName(NULL, NULL); if (tempCFStringRef) { stringLengthChars=(int) CFStringGetMaximumSizeForEncoding(CFStringGetLength(tempCFStringRef), kCFStringEncodingASCII); tempStrPtr=malloc(sizeof(char) * (stringLengthChars+1)); stringSuccess= CFStringGetCString(tempCFStringRef, tempStrPtr, stringLengthChars+1, kCFStringEncodingASCII); if(stringSuccess) { PsychSetStructArrayStringElement("machineName", 0, tempStrPtr, majorStruct); } else { PsychSetStructArrayStringElement("machineName", 0, "UNKNOWN! QUERY FAILED DUE TO EMPTY OR PROBLEMATIC NAME.", majorStruct); } free(tempStrPtr); CFRelease(tempCFStringRef); } else { PsychSetStructArrayStringElement("machineName", 0, "UNKNOWN! QUERY FAILED DUE TO EMPTY OR PROBLEMATIC NAME.", majorStruct); } struct passwd* thisUser = getpwuid(getuid()); if (thisUser) { PsychSetStructArrayStringElement("processUserShortName", 0, thisUser->pw_name, majorStruct); } else { PsychSetStructArrayStringElement("processUserShortName", 0, "UNKNOWN! QUERY FAILED DUE TO EMPTY OR PROBLEMATIC NAME.", majorStruct); } PsychSetStructArrayStringElement("processUserLongName", 0, PsychCocoaGetFullUsername(), majorStruct); tempCFStringRef= SCDynamicStoreCopyConsoleUser(NULL, NULL, NULL); if (tempCFStringRef) { stringLengthChars=(int) CFStringGetMaximumSizeForEncoding(CFStringGetLength(tempCFStringRef), kCFStringEncodingASCII); tempStrPtr=malloc(sizeof(char) * (stringLengthChars+1)); stringSuccess= CFStringGetCString(tempCFStringRef, tempStrPtr, stringLengthChars+1, kCFStringEncodingASCII); if(stringSuccess) { PsychSetStructArrayStringElement("consoleUserName", 0, tempStrPtr, majorStruct); } else { PsychSetStructArrayStringElement("consoleUserName", 0, "UNKNOWN! QUERY FAILED DUE TO EMPTY OR PROBLEMATIC NAME.", majorStruct); } free(tempStrPtr); CFRelease(tempCFStringRef); } else { PsychSetStructArrayStringElement("consoleUserName", 0, "UNKNOWN! QUERY FAILED DUE TO EMPTY OR PROBLEMATIC NAME.", majorStruct); } tempCFStringRef= SCDynamicStoreCopyLocalHostName(NULL); if (tempCFStringRef) { stringLengthChars=(int) CFStringGetMaximumSizeForEncoding(CFStringGetLength(tempCFStringRef), kCFStringEncodingASCII); tempStrPtr=malloc(sizeof(char) * (stringLengthChars+1)); stringSuccess= CFStringGetCString(tempCFStringRef, tempStrPtr, stringLengthChars+1, kCFStringEncodingASCII); if(stringSuccess) { PsychSetStructArrayStringElement("localHostName", 0, tempStrPtr, majorStruct); } else { PsychSetStructArrayStringElement("localHostName", 0, "UNKNOWN! QUERY FAILED DUE TO EMPTY OR PROBLEMATIC NAME.", majorStruct); } free(tempStrPtr); CFRelease(tempCFStringRef); } else { PsychSetStructArrayStringElement("localHostName", 0, "UNKNOWN! QUERY FAILED DUE TO EMPTY OR PROBLEMATIC NAME.", majorStruct); } tempCFStringRef= SCDynamicStoreCopyLocation(NULL); if (tempCFStringRef) { stringLengthChars=(int) CFStringGetMaximumSizeForEncoding(CFStringGetLength(tempCFStringRef), kCFStringEncodingASCII); tempStrPtr=malloc(sizeof(char) * (stringLengthChars+1)); stringSuccess= CFStringGetCString(tempCFStringRef, tempStrPtr, stringLengthChars+1, kCFStringEncodingASCII); if(stringSuccess) { PsychSetStructArrayStringElement("location", 0, tempStrPtr, majorStruct); } else { PsychSetStructArrayStringElement("location", 0, "UNKNOWN! QUERY FAILED DUE TO EMPTY OR PROBLEMATIC NAME.", majorStruct); } free(tempStrPtr); CFRelease(tempCFStringRef); } else { PsychSetStructArrayStringElement("location", 0, "UNKNOWN! QUERY FAILED DUE TO EMPTY OR PROBLEMATIC NAME.", majorStruct); } //Add the ethernet MAC address of the primary ethernet interface to the stuct. This can serve as a unique identifier for the computer. ethernetMACStrSizeBytes=GetPrimaryEthernetAddressStringLengthBytes(TRUE)+1; ethernetMACStr=(char*) malloc(sizeof(char) * ethernetMACStrSizeBytes); GetPrimaryEthernetAddressString(ethernetMACStr, TRUE, TRUE); PsychSetStructArrayStringElement("MACAddress", 0, ethernetMACStr, majorStruct); free(ethernetMACStr); //Add the system version string: PsychCocoaGetOSXVersion(&osMajor, &osMinor, &osBugfix); sprintf(systemVersionStr, "Mac OS %i.%i.%i", osMajor, osMinor, osBugfix); //embed it in the return struct PsychSetStructArrayStringElement("system", 0, systemVersionStr, majorStruct); return(PsychError_none); }
/* PsychInitFontList() Build a list of records describing installed fonts. */ void PsychInitFontList(void) { ATSFontRef tempATSFontRef; CTFontRef tempCTFontRef; //for font structures PsychFontStructPtrType fontListHead, fontRecord, previousFontRecord; //for ATI font iteration ATSFontIterator fontIterator; OSStatus halt; //for font field names CFStringRef cfFontName; int i, j; psych_bool resultOK; //for font file OSStatus osStatus; FSSpec fontFileSpec; FSRef fontFileRef; //for the font metrics ATSFontMetrics horizontalMetrics; ATSFontMetrics verticalMetrics; //for info from Font Manager FMFontStyle fmStyle; OSStatus fmStatus; Str255 fmFontFamilyNamePString; //whatever Str255 fontFamilyQuickDrawNamePString; TextEncoding textEncoding; OSStatus scriptInfoOK; ScriptCode scriptCode; LangCode languageCode; OSStatus localOK; LocaleRef locale; psych_bool trouble = FALSE; psych_bool reportTrouble = TRUE; fontListHead=PsychFontListHeadKeeper(FALSE, NULL); //get the font list head. if(fontListHead) PsychErrorExitMsg(PsychError_internal, "Attempt to set new font list head when one is already set."); fontRecord = NULL; fontIterator = NULL; halt = ATSFontIteratorCreate(PSYCH_ATS_ITERATOR_CONTEXT, NULL, NULL, PSYCH_ATS_ITERATOR_SCOPE, &fontIterator); i = 0; while (halt==noErr) { // Give repair hints early. Experience shows we might crash during enumeration of a // corrupt OSX font database, so make sure we get out the helpful message as early as possible. Doing // this (just) at the end of enumeration might be too late - we might never get there... // However, allow user to suppress the hint, as this happens quite regularly on 32-Bit OSX: if (reportTrouble && trouble && PsychPrefStateGet_Verbosity() > 2) { reportTrouble = FALSE; // Only show this hint once, not for every invalid font. printf("\nPTB-HINT: =============================================================================================================================\n"); printf("PTB-HINT: At least one font on this system has issues and can not be accessed by Psychtoolbox. If you want to know which font(s) make\n"); printf("PTB-HINT: trouble, do a 'clear all' and rerun your script with Screen()'s verbosity level set to at least 4 for more diagnostic output.\n"); printf("PTB-HINT: The following tips may help you to resolve font issues:\n"); printf("PTB-HINT: Go to the Application folder and open the 'Font Book' application. It allows you to check and repair your font database.\n"); printf("PTB-HINT: Run its 'Validate' function on all installed fonts. Another thing you could try is downloading and running the free\n"); printf("PTB-HINT: FontNuke application (Google will find it for you) to regenerate corrupt OSX font caches. Good luck!\n"); printf("PTB-HINT: You can suppress this hint by choosing a verbosity level for Screen() of 2 or lower.\n"); printf("PTB-HINT: =============================================================================================================================\n\n"); } halt=ATSFontIteratorNext(fontIterator, &tempATSFontRef); if(halt==noErr){ //create a new font font structure. Set the next field to NULL as soon as we allocate the font so that if //we break with an error then we can find the end when we walk down the linked list. fontRecord=(PsychFontStructPtrType) calloc(1, sizeof(PsychFontStructType)); fontRecord->next=NULL; //Get FM and ATS font and font family references from the ATS font reference, which we get from iteration. fontRecord->fontATSRef=tempATSFontRef; fontRecord->fontFMRef=FMGetFontFromATSFontRef(fontRecord->fontATSRef); // Create CTFont from given ATSFontRef. Available since OSX 10.5 tempCTFontRef = CTFontCreateWithPlatformFont(fontRecord->fontATSRef, 0.0, NULL, NULL); if (tempCTFontRef) { // Get font family name from CTFont: CFStringRef cfFamilyName = CTFontCopyFamilyName(tempCTFontRef); // Retrieve symbolic traits of font -- the closest equivalent of the fmStyle from the // good'ol fontManager: CTFontSymbolicTraits ctTraits = CTFontGetSymbolicTraits(tempCTFontRef); // Remap new trait constants to old constants for later Screen('TextStyle') matching. fmStyle = 0; if (ctTraits & kCTFontBoldTrait) fmStyle |= 1; if (ctTraits & kCTFontItalicTrait) fmStyle |= 2; if (ctTraits & kCTFontCondensedTrait) fmStyle |= 32; if (ctTraits & kCTFontExpandedTrait) fmStyle |= 64; // CTFont no longer needed: CFRelease(tempCTFontRef); // Convert to C-String and assign: resultOK = cfFamilyName && CFStringGetCString(cfFamilyName, (char*) fontRecord->fontFMFamilyName, 255, kCFStringEncodingASCII); if(!resultOK){ if (cfFamilyName) CFRelease(cfFamilyName); if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-WARNING: In font initialization: Failed to retrieve font family name for font... Defective font?!? Skipped this entry...\n"); trouble = TRUE; continue; } // Get ATSRef for font family: fontRecord->fontFamilyATSRef = ATSFontFamilyFindFromName(cfFamilyName, kATSOptionFlagsDefault); CFRelease(cfFamilyName); } else { if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-WARNING: In font initialization: Failed to retrieve CTFontRef for font... Defective font?!? Skipped this entry...\n"); trouble = TRUE; continue; } //get the font name and set the the corresponding field of the struct if (ATSFontGetName(fontRecord->fontATSRef, kATSOptionFlagsDefault, &cfFontName)!=noErr) { if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-WARNING: In font initialization: Failed to query font name in ATSFontGetName! OS-X font handling screwed up?!? Skipped this entry...\n"); trouble = TRUE; continue; } resultOK = cfFontName && CFStringGetCString(cfFontName, (char*) fontRecord->fontFMName, 255, kCFStringEncodingASCII); if(!resultOK){ if (cfFontName) CFRelease(cfFontName); if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-WARNING: In font initialization: Failed to convert fontFMName CF string to char string. Defective font?!? Skipped this entry...\n"); trouble = TRUE; continue; } CFRelease(cfFontName); //get the font postscript name and set the corresponding field of the struct if (ATSFontGetPostScriptName(fontRecord->fontATSRef, kATSOptionFlagsDefault, &cfFontName)!=noErr) { if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-WARNING: In font initialization: The following font makes trouble: %s. Please REMOVE the offending font file from your font folders and restart Matlab. Skipped entry for now...\n", fontRecord->fontFMName); trouble = TRUE; continue; } resultOK = cfFontName && CFStringGetCString(cfFontName, (char*) fontRecord->fontPostScriptName, 255, kCFStringEncodingASCII); //kCFStringEncodingASCII matches MATLAB for 0-127 if(!resultOK){ if (cfFontName) CFRelease(cfFontName); if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-WARNING: In font initialization: Failed to convert fontPostScriptName CF string to char string for font %s. Defective font?!? Skipped this entry...\n", fontRecord->fontFMName); trouble = TRUE; continue; } CFRelease(cfFontName); // Get the QuickDraw name of the font: fontRecord->fontFamilyQuickDrawName[0] = 0; fontFamilyQuickDrawNamePString[0] = 0; ATSFontFamilyGetQuickDrawName(fontRecord->fontFamilyATSRef, fontFamilyQuickDrawNamePString); for (j = 0; j < fontFamilyQuickDrawNamePString[0]; j++) fontRecord->fontFamilyQuickDrawName[j] = fontFamilyQuickDrawNamePString[j+1]; fontRecord->fontFamilyQuickDrawName[j] = 0; osStatus = ATSFontGetFileReference(fontRecord->fontATSRef, &fontFileRef); if(osStatus != noErr) { if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-WARNING: In font initialization: Failed to get the font file specifier for font %s. Defective font?!? Skipped this entry...\n", fontRecord->fontFMName); trouble = TRUE; continue; } osStatus= FSRefMakePath(&fontFileRef, (UInt8*) fontRecord->fontFile, (UInt32)(kPsychMaxFontFileNameChars - 1)); if(osStatus!=noErr){ if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-WARNING: In font initialization: Failed to get the font file path for font %s. Defective font?!? Skipped this entry...\n", fontRecord->fontFMName); trouble = TRUE; continue; } //get the font metrics of this font. //Explicit copy between fields to make it clear what is going one, will likely have to mix & match between native and Psych structures for different //platforms. ATSFontGetHorizontalMetrics(fontRecord->fontATSRef, kATSOptionFlagsDefault, &horizontalMetrics); ATSFontGetVerticalMetrics(fontRecord->fontATSRef, kATSOptionFlagsDefault, &verticalMetrics); //horizontal fontRecord->horizontalMetrics.ascent= horizontalMetrics.ascent; fontRecord->horizontalMetrics.descent= horizontalMetrics.descent; fontRecord->horizontalMetrics.leading= horizontalMetrics.leading; fontRecord->horizontalMetrics.avgAdvanceWidth= horizontalMetrics.avgAdvanceWidth; fontRecord->horizontalMetrics.minLeftSideBearing= horizontalMetrics.minLeftSideBearing; fontRecord->horizontalMetrics.minRightSideBearing= horizontalMetrics.minRightSideBearing; fontRecord->horizontalMetrics.stemWidth= horizontalMetrics.stemWidth; fontRecord->horizontalMetrics.stemHeight= horizontalMetrics.stemHeight; fontRecord->horizontalMetrics.capHeight= horizontalMetrics.capHeight; fontRecord->horizontalMetrics.xHeight= horizontalMetrics.xHeight; fontRecord->horizontalMetrics.italicAngle= horizontalMetrics.italicAngle; fontRecord->horizontalMetrics.underlinePosition= horizontalMetrics.underlinePosition; fontRecord->horizontalMetrics.underlineThickness= horizontalMetrics.underlineThickness; fontRecord->horizontalMetrics.underlineThickness= horizontalMetrics.underlineThickness; //vertical fontRecord->verticalMetrics.ascent= verticalMetrics.ascent; fontRecord->verticalMetrics.descent= verticalMetrics.descent; fontRecord->verticalMetrics.leading= verticalMetrics.leading; fontRecord->verticalMetrics.avgAdvanceWidth= verticalMetrics.avgAdvanceWidth; fontRecord->verticalMetrics.minLeftSideBearing= verticalMetrics.minLeftSideBearing; fontRecord->verticalMetrics.minRightSideBearing= verticalMetrics.minRightSideBearing; fontRecord->verticalMetrics.stemWidth= verticalMetrics.stemWidth; fontRecord->verticalMetrics.stemHeight= verticalMetrics.stemHeight; fontRecord->verticalMetrics.capHeight= verticalMetrics.capHeight; fontRecord->verticalMetrics.xHeight= verticalMetrics.xHeight; fontRecord->verticalMetrics.italicAngle= verticalMetrics.italicAngle; fontRecord->verticalMetrics.underlinePosition= verticalMetrics.underlinePosition; fontRecord->verticalMetrics.underlineThickness= verticalMetrics.underlineThickness; fontRecord->verticalMetrics.underlineThickness= verticalMetrics.underlineThickness; fontRecord->fontFMStyle=fmStyle; fontRecord->fontFMNumStyles=PsychFindNumFMFontStylesFromStyle(fmStyle); fontRecord->fontFMNumStyles= fontRecord->fontFMNumStyles ? fontRecord->fontFMNumStyles : 1; //because the name is "normal" even if there are no styles. // Get the locale info which is a property of the font family: // No error checking is done here, because many (most?) fonts miss the information, // so we would error-out all the time and this is non-critical for us: textEncoding=ATSFontFamilyGetEncoding(fontRecord->fontFamilyATSRef); scriptInfoOK=RevertTextEncodingToScriptInfo(textEncoding, &scriptCode, &languageCode, NULL); localOK=LocaleRefFromLangOrRegionCode(languageCode, kTextRegionDontCare, &locale); localOK |= LocaleRefGetPartString(locale, kLocaleLanguageMask, 255, (char*) fontRecord->locale.language); fontRecord->locale.language[255]='\0'; localOK |= LocaleRefGetPartString(locale, kLocaleLanguageVariantMask, 255, (char*) fontRecord->locale.languageVariant); fontRecord->locale.languageVariant[255]='\0'; localOK |= LocaleRefGetPartString(locale, kLocaleRegionMask, 255, (char*) fontRecord->locale.region); fontRecord->locale.region[255]='\0'; localOK |= LocaleRefGetPartString(locale, kLocaleRegionVariantMask, 255, (char*) fontRecord->locale.regionVariant); fontRecord->locale.regionVariant[255]='\0'; localOK |= LocaleRefGetPartString(locale, kLocaleAllPartsMask, 255, (char*) fontRecord->locale.fullName); fontRecord->locale.fullName[255]='\0'; // Init for fontRecord (nearly) finished. // Set this fontRecord as head of font-list, or enqueue it in existing list: if(i==0) { PsychFontListHeadKeeper(TRUE, fontRecord); } else { previousFontRecord->next=fontRecord; } // Set the font number field of the struct fontRecord->fontNumber=i+1; // Increment the font index and update the next font pointer ++i; previousFontRecord=fontRecord; }else if(halt == kATSIterationScopeModified){ //exit because the font database changed during this loop. PsychFreeFontList(); if (fontIterator) ATSFontIteratorRelease(&fontIterator); PsychErrorExitMsg(PsychError_system, "The system font database was modified during font list setup. Please 'clear all' and restart your script."); } // Next parse iteration in system font database... } if (fontIterator) ATSFontIteratorRelease(&fontIterator); if (halt != kATSIterationCompleted) { PsychFreeFontList(); trouble = TRUE; if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: Font iteration during enumeration terminated prematurely. OS-X Font database corrupted?!?"); } // Did we get a hand on at least one font? if (i==0) { PsychFreeFontList(); trouble = TRUE; if (PsychPrefStateGet_Verbosity() > 0) { printf("PTB-ERROR: In font initialization: Could not even retrieve one valid font from the system! The OS-X font database must be corrupt.\n"); printf("PTB-ERROR: Will try to continue but will likely abort if your code tries to call any of the font handling or text drawing functions.\n"); } } // If there was some trouble and it wasn't reported yet, then report it now at the end if either // verbosity level is at least 3 (our default level), or if the error was especially serious and // lead to a premature abortion of font iteration or complete failure to find even a single valid // font. In the latter cases, we must report the trouble, regardless of verbosity level. In the // former case, probably only a few fonts had trouble, so we allow the user to suppress such messages // by lowering the verbosity to warning level or lower: if (reportTrouble && trouble && ((PsychPrefStateGet_Verbosity() > 2) || (halt != kATSIterationCompleted) || (i == 0))) { printf("PTB-HINT: =============================================================================================================================\n"); printf("PTB-HINT: At least one font on this system has issues and can not be accessed by Psychtoolbox. If you want to know which font(s) make\n"); printf("PTB-HINT: trouble, do a 'clear all' and rerun your script with Screen()'s verbosity level set to at least 4 for more diagnostic output.\n"); printf("PTB-HINT: The following tips may help you to resolve font issues:\n"); printf("PTB-HINT: Go to the Application folder and open the 'Font Book' application. It allows you to check and repair your font database.\n"); printf("PTB-HINT: Run its 'Validate' function on all installed fonts. Another thing you could try is downloading and running the free\n"); printf("PTB-HINT: FontNuke application (Google will find it for you) to regenerate corrupt OSX font caches. Good luck!\n"); printf("PTB-HINT: In case of non-fatal errors, you can suppress this hint by choosing a verbosity level for Screen() of 2 or lower.\n"); printf("PTB-HINT: =============================================================================================================================\n"); } // Font database ready for use. return; }