static kern_return_t CopyUserVisibleNameForEthernetPort(io_object_t interface, CFMutableDictionaryRef interfaceInfo, CFStringRef *userVisibleName) // Given an Ethernet device (interface) and a dictionary of // information about the device (interfaceInfo), guess at the // user-visible name for the device. // // I'm somewhat unhappy with this code (both its length and its style) // but there really isn't a better solution right now. Apple // is actively working on a better way to do this. { kern_return_t err; kern_return_t junk; io_object_t controller; io_object_t bus; CFStringRef bsdName; CFMutableDictionaryRef controllerDict; assert(interface != 0 ); assert(interfaceInfo != NULL); assert( userVisibleName != NULL); assert(*userVisibleName == NULL); // Look up the parent service, and the parent of that. controller = 0; bus = 0; bsdName = NULL; controllerDict = NULL; err = IORegistryEntryGetParentEntry(interface, kIOServicePlane, &controller); if (err == 0) { err = IORegistryEntryGetParentEntry(controller, kIOServicePlane, &bus); } // Establish dictionary for the controller and bsdName for the device. if (err == 0) { err = IORegistryEntryCreateCFProperties(controller, &controllerDict, NULL, kNilOptions ); } if (err == 0) { bsdName = (CFStringRef) IORegistryEntryCreateCFProperty(interface, CFSTR(kIOBSDNameKey), NULL, kNilOptions); if (bsdName == NULL) { err = -1; } } // Now handle all of the wacky special cases. if (err == 0) { CFStringRef tmpStr; // Set userVisibleName to a reference to the port's user-visible name, // handling all of the special cases. if ( CFEqualString(bsdName, CFSTR("en0")) ) { // built-in ethernet junk = CFQDictionarySetNumber(interfaceInfo, kSortOrderKey, kBuiltInEthernetSortOrder); assert(junk == 0); *userVisibleName = (CFStringRef) CFQRetain( kMoreSCPortLabelEthernetBuiltIn ); } else if ( CFDictionaryGetValueIfPresent(controllerDict, CFSTR(kIOClassKey), (const void **) &tmpStr) && CFEqualString(tmpStr, CFSTR("AirPortDriver"))) { // airport CFDictionarySetValue(interfaceInfo, kSCPropNetInterfaceHardware, kSCEntNetAirPort); junk = CFQDictionarySetNumber(interfaceInfo, kSortOrderKey, kAirPortSortOrder); assert(junk == 0); *userVisibleName = (CFStringRef) CFQRetain( kMoreSCPortLabelAirPort ); } else { CFStringRef nameProperty; CFMutableDictionaryRef busDict; // Some other type of Ethernet-like device. busDict = NULL; nameProperty = NULL; err = IORegistryEntryCreateCFProperties(bus, &busDict, NULL, kNilOptions); if (err == 0) { CFDataRef nameData; nameData = (CFDataRef) CFDictionaryGetValue(busDict, CFSTR("name")); if (nameData == NULL) { nameProperty = NULL; } else { nameProperty = CreateStringFromData(nameData); if (nameProperty == NULL) { err = -1; } } } if (err == 0) { if ( (nameProperty != NULL) && (CFEqualString(nameProperty, CFSTR("radio"))) ) { // non-airport wireless (assuming someone writes a driver) junk = CFQDictionarySetNumber(interfaceInfo, kSortOrderKey, kWirelessSortOrder); assert(junk == 0); *userVisibleName = (CFStringRef) CFQRetain( kMoreSCPortLabelWireless ); } else if ( CFDictionaryGetValueIfPresent(controllerDict, CFSTR(kIOProviderClassKey), (const void **) &tmpStr) && CFEqualString(tmpStr, CFSTR("IOPCIDevice"))) { CFDataRef slotNameAsData; CFStringRef slotName; CFNumberRef portNum; SInt32 junkNum; // It's on a PCI bus. junk = CFQDictionarySetNumber(interfaceInfo, kSortOrderKey, kEthernetPCISortOrder); assert(junk == 0); // Get "AAPL,slot-name" property from I/O Registry and copy it into // our interfaceInfo dictionary. But first, mutate the slot name // into a user-visible name version. slotName = NULL; slotNameAsData = (CFDataRef) IORegistryEntryCreateCFProperty(bus, CFSTR("AAPL,slot-name"), NULL, kNilOptions); if (slotNameAsData != NULL) { slotName = CreateStringFromData(slotNameAsData); } if (slotName != NULL) { CFStringRef tmp; tmp = CopyUserVisibleSlotName(slotName); if (tmp != NULL) { CFQRelease(slotName); slotName = tmp; } } if (slotName == NULL) { CFDictionarySetValue(interfaceInfo, CFSTR("AAPL,slot-name"), CFSTR("unknown")); } else { CFDictionarySetValue(interfaceInfo, CFSTR("AAPL,slot-name"), slotName); } CFQRelease(slotName); // Now get the IOChildIndex property to decide whether it's a single // or multi-port Ethernet card. portNum = (CFNumberRef) CFDictionaryGetValue(busDict, CFSTR("IOChildIndex")); if ( (portNum == NULL) || ! CFNumberGetValue(portNum, kCFNumberSInt32Type, &junkNum) ) { // single-port pci enet card // Either there is no IOChildIndex property, or it doesn't contain a // valid number. *userVisibleName = (CFStringRef) CFQRetain( kMoreSCPortLabelEthernetPCI ); } else { CFNumberRef portNumRef; SInt32 portNum; CFStringRef portNumString; // multi-port pci enet card // Get "IOChildIndex" property from I/O Registry and copy it into // our interfaceInfo dictionary. portNumString = NULL; portNumRef = (CFNumberRef) IORegistryEntryCreateCFProperty(bus, CFSTR("IOChildIndex"), NULL, kNilOptions); if ( (portNumRef != NULL) && CFNumberGetValue(portNumRef, kCFNumberSInt32Type, &portNum) ) { portNumString = CFStringCreateWithFormat(NULL, NULL, CFSTR("%ld"), portNum + 1); } if (portNumString == NULL) { CFDictionarySetValue(interfaceInfo, CFSTR("IOChildIndex"), CFSTR("unknown")); } else { CFDictionarySetValue(interfaceInfo, CFSTR("IOChildIndex"), portNumString); } CFQRelease(portNumString); CFQRelease(portNumRef); *userVisibleName = (CFStringRef) CFQRetain( kMoreSCPortLabelEthernetPCIMultiport ); } } else { CFStringRef bsdName; // unknown enet device - use a generic name and include its BSD name, // since we don't know what else to do bsdName = (CFStringRef) IORegistryEntryCreateCFProperty(interface, CFSTR(kIOBSDNameKey), NULL, kNilOptions); if (bsdName == NULL) { CFDictionarySetValue(interfaceInfo, CFSTR(kIOBSDNameKey), CFSTR("unknown")); } else { CFDictionarySetValue(interfaceInfo, CFSTR(kIOBSDNameKey), bsdName); } CFQRelease(bsdName); *userVisibleName = (CFStringRef) CFQRetain( kMoreSCPortLabelEthernet ); } } CFQRelease(nameProperty); CFQRelease(busDict); } } // Clean up. junk = IOObjectRelease(bus); assert(junk == 0); junk = IOObjectRelease(controller); assert(junk == 0); CFQRelease(controllerDict); CFQRelease(bsdName); assert( (err == 0) == (*userVisibleName != NULL) ); return err; }
static void tests(void) { CFErrorRef error = NULL; CFDataRef cfpassword = CFDataCreate(NULL, (uint8_t *) "FooFooFoo", 10); CFDataRef cfwrong_password = CFDataCreate(NULL, (uint8_t *) "NotFooFooFoo", 10); CFStringRef cfaccount = CFSTR("*****@*****.**"); CFMutableDictionaryRef changes = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault); SOSAccountRef alice_account = CreateAccountForLocalChanges(CFSTR("Alice"), CFSTR("TestSource")); SOSAccountRef bob_account = CreateAccountForLocalChanges(CFSTR("Bob"), CFSTR("TestSource")); SOSAccountRef carol_account = CreateAccountForLocalChanges(CFSTR("Carol"), CFSTR("TestSource")); ok(SOSAccountAssertUserCredentialsAndUpdate(bob_account, cfaccount, cfpassword, &error), "Credential setting (%@)", error); // Bob wins writing at this point, feed the changes back to alice. is(ProcessChangesUntilNoChange(changes, alice_account, bob_account, NULL), 1, "updates"); ok(SOSAccountAssertUserCredentialsAndUpdate(alice_account, cfaccount, cfpassword, &error), "Credential setting (%@)", error); CFReleaseNull(error); ok(SOSAccountTryUserCredentials(alice_account, cfaccount, cfpassword, &error), "Credential trying (%@)", error); CFReleaseNull(error); ok(!SOSAccountTryUserCredentials(alice_account, cfaccount, cfwrong_password, &error), "Credential failing (%@)", error); CFReleaseNull(cfwrong_password); is(error ? CFErrorGetCode(error) : 0, kSOSErrorWrongPassword, "Expected SOSErrorWrongPassword"); CFReleaseNull(error); ok(SOSAccountResetToOffering_wTxn(alice_account, &error), "Reset to offering (%@)", error); CFReleaseNull(error); is(ProcessChangesUntilNoChange(changes, alice_account, bob_account, NULL), 2, "updates"); ok(SOSAccountJoinCircles_wTxn(bob_account, &error), "Bob Applies (%@)", error); CFReleaseNull(error); is(ProcessChangesUntilNoChange(changes, alice_account, bob_account, NULL), 2, "updates"); { CFArrayRef applicants = SOSAccountCopyApplicants(alice_account, &error); ok(applicants && CFArrayGetCount(applicants) == 1, "See one applicant %@ (%@)", applicants, error); ok(SOSAccountAcceptApplicants(alice_account, applicants, &error), "Alice accepts (%@)", error); CFReleaseNull(error); CFReleaseNull(applicants); } is(ProcessChangesUntilNoChange(changes, alice_account, bob_account, NULL), 3, "updates"); accounts_agree("bob&alice pair", bob_account, alice_account); CFArrayRef peers = SOSAccountCopyPeers(alice_account, &error); ok(peers && CFArrayGetCount(peers) == 2, "See two peers %@ (%@)", peers, error); CFReleaseNull(peers); //bob now goes def while Alice does some stuff. ok(SOSAccountLeaveCircle(alice_account, &error), "ALICE LEAVES THE CIRCLE (%@)", error); ok(SOSAccountResetToOffering_wTxn(alice_account, &error), "Alice resets to offering again (%@)", error); is(ProcessChangesUntilNoChange(changes, alice_account, bob_account, NULL), 2, "updates"); accounts_agree("bob&alice pair", bob_account, alice_account); is(ProcessChangesUntilNoChange(changes, alice_account, bob_account, carol_account, NULL), 1, "updates"); ok(SOSAccountAssertUserCredentialsAndUpdate(carol_account, cfaccount, cfpassword, &error), "Credential setting (%@)", error); SOSAccountSetUserPublicTrustedForTesting(carol_account); ok(SOSAccountResetToOffering_wTxn(carol_account, &error), "Carol is going to push a reset to offering (%@)", error); int64_t valuePtr = 0; CFNumberRef gencount = CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &valuePtr); SOSCircleSetGeneration(carol_account->trusted_circle, gencount); SecKeyRef user_privkey = SOSUserKeygen(cfpassword, carol_account->user_key_parameters, &error); CFNumberRef genCountTest = SOSCircleGetGeneration(carol_account->trusted_circle); CFIndex testPtr; CFNumberGetValue(genCountTest, kCFNumberCFIndexType, &testPtr); ok(testPtr== 0); SOSCircleSignOldStyleResetToOfferingCircle(carol_account->trusted_circle, carol_account->my_identity, user_privkey, &error); SOSTransportCircleTestRemovePendingChange(carol_account->circle_transport, SOSCircleGetName(carol_account->trusted_circle), NULL); CFDataRef circle_data = SOSCircleCopyEncodedData(carol_account->trusted_circle, kCFAllocatorDefault, &error); if (circle_data) { SOSTransportCirclePostCircle(carol_account->circle_transport, SOSCircleGetName(carol_account->trusted_circle), circle_data, &error); } genCountTest = SOSCircleGetGeneration(carol_account->trusted_circle); CFNumberGetValue(genCountTest, kCFNumberCFIndexType, &testPtr); ok(testPtr== 0); ok(SOSAccountAssertUserCredentialsAndUpdate(bob_account, cfaccount, cfpassword, &error), "Credential setting (%@)", error); ok(SOSAccountAssertUserCredentialsAndUpdate(alice_account, cfaccount, cfpassword, &error), "Credential setting (%@)", error); SOSAccountSetUserPublicTrustedForTesting(alice_account); SOSAccountSetUserPublicTrustedForTesting(bob_account); is(ProcessChangesUntilNoChange(changes, carol_account, alice_account, bob_account, NULL), 2, "updates"); ok(kSOSCCNotInCircle == SOSAccountGetCircleStatus(alice_account, &error), "alice is not in the account (%@)", error); ok(kSOSCCNotInCircle == SOSAccountGetCircleStatus(bob_account, &error), "bob is not in the account (%@)", error); ok(kSOSCCInCircle == SOSAccountGetCircleStatus(carol_account, &error), "carol is in the account (%@)", error); CFReleaseNull(gencount); CFReleaseNull(bob_account); CFReleaseNull(alice_account); CFReleaseNull(cfpassword); SOSTestCleanup(); }
bool FLACMetadata::WriteMetadata(CFErrorRef *error) { UInt8 buf [PATH_MAX]; if(!CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX)) return false; // TODO: Use unique_ptr once the switch to C++11 STL is made std::auto_ptr<TagLib::FileStream> stream(new TagLib::FileStream(reinterpret_cast<const char *>(buf))); if(!stream->isOpen()) { if(error) { CFStringRef description = CFCopyLocalizedString(CFSTR("The file “%@” could not be opened for writing."), ""); CFStringRef failureReason = CFCopyLocalizedString(CFSTR("Input/output error"), ""); CFStringRef recoverySuggestion = CFCopyLocalizedString(CFSTR("The file may have been renamed, moved, deleted, or you may not have appropriate permissions."), ""); *error = CreateErrorForURL(AudioMetadataErrorDomain, AudioMetadataInputOutputError, description, mURL, failureReason, recoverySuggestion); CFRelease(description), description = nullptr; CFRelease(failureReason), failureReason = nullptr; CFRelease(recoverySuggestion), recoverySuggestion = nullptr; } return false; } TagLib::FLAC::File file(stream.get(), TagLib::ID3v2::FrameFactory::instance(), false); if(!file.isValid()) { if(error) { CFStringRef description = CFCopyLocalizedString(CFSTR("The file “%@” is not a valid FLAC file."), ""); CFStringRef failureReason = CFCopyLocalizedString(CFSTR("Not a FLAC file"), ""); CFStringRef recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""); *error = CreateErrorForURL(AudioMetadataErrorDomain, AudioMetadataInputOutputError, description, mURL, failureReason, recoverySuggestion); CFRelease(description), description = nullptr; CFRelease(failureReason), failureReason = nullptr; CFRelease(recoverySuggestion), recoverySuggestion = nullptr; } return false; } // ID3v1 and ID3v2 tags are only written if present, but a Xiph comment is always written if(file.ID3v1Tag()) SetID3v1TagFromMetadata(*this, file.ID3v1Tag()); if(file.ID3v2Tag()) SetID3v2TagFromMetadata(*this, file.ID3v2Tag()); SetXiphCommentFromMetadata(*this, file.xiphComment(true), false); // Remove existing cover art file.removePictures(); // Add album art for(auto attachedPicture : GetAttachedPictures()) { CGImageSourceRef imageSource = CGImageSourceCreateWithData(attachedPicture->GetData(), nullptr); if(nullptr == imageSource) { LOGGER_ERR("org.sbooth.AudioEngine.AudioMetadata.FLAC", "Skipping album art (unable to create image)"); continue; } TagLib::FLAC::Picture *picture = new TagLib::FLAC::Picture; picture->setData(TagLib::ByteVector((const char *)CFDataGetBytePtr(attachedPicture->GetData()), (TagLib::uint)CFDataGetLength(attachedPicture->GetData()))); picture->setType(static_cast<TagLib::FLAC::Picture::Type>(attachedPicture->GetType())); if(attachedPicture->GetDescription()) picture->setDescription(TagLib::StringFromCFString(attachedPicture->GetDescription())); // Convert the image's UTI into a MIME type CFStringRef mimeType = UTTypeCopyPreferredTagWithClass(CGImageSourceGetType(imageSource), kUTTagClassMIMEType); if(mimeType) { picture->setMimeType(TagLib::StringFromCFString(mimeType)); CFRelease(mimeType), mimeType = nullptr; } // Flesh out the height, width, and depth CFDictionaryRef imagePropertiesDictionary = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nullptr); if(imagePropertiesDictionary) { CFNumberRef imageWidth = (CFNumberRef)CFDictionaryGetValue(imagePropertiesDictionary, kCGImagePropertyPixelWidth); CFNumberRef imageHeight = (CFNumberRef)CFDictionaryGetValue(imagePropertiesDictionary, kCGImagePropertyPixelHeight); CFNumberRef imageDepth = (CFNumberRef)CFDictionaryGetValue(imagePropertiesDictionary, kCGImagePropertyDepth); int height, width, depth; // Ignore numeric conversion errors CFNumberGetValue(imageWidth, kCFNumberIntType, &width); CFNumberGetValue(imageHeight, kCFNumberIntType, &height); CFNumberGetValue(imageDepth, kCFNumberIntType, &depth); picture->setHeight(height); picture->setWidth(width); picture->setColorDepth(depth); CFRelease(imagePropertiesDictionary), imagePropertiesDictionary = nullptr; } file.addPicture(picture); CFRelease(imageSource), imageSource = nullptr; } if(!file.save()) { if(error) { CFStringRef description = CFCopyLocalizedString(CFSTR("The file “%@” is not a valid FLAC file."), ""); CFStringRef failureReason = CFCopyLocalizedString(CFSTR("Unable to write metadata"), ""); CFStringRef recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""); *error = CreateErrorForURL(AudioMetadataErrorDomain, AudioMetadataInputOutputError, description, mURL, failureReason, recoverySuggestion); CFRelease(description), description = nullptr; CFRelease(failureReason), failureReason = nullptr; CFRelease(recoverySuggestion), recoverySuggestion = nullptr; } return false; } MergeChangedMetadataIntoMetadata(); return true; }
void InbandTextTrackPrivateAVF::processCueAttributes(CFAttributedStringRef attributedString, GenericCueData* cueData) { // Some of the attributes we translate into per-cue WebVTT settings are are repeated on each part of an attributed string so only // process the first instance of each. enum AttributeFlags { Line = 1 << 0, Position = 1 << 1, Size = 1 << 2, Vertical = 1 << 3, Align = 1 << 4, FontName = 1 << 5 }; unsigned processed = 0; StringBuilder content; String attributedStringValue = CFAttributedStringGetString(attributedString); CFIndex length = attributedStringValue.length(); if (!length) return; CFRange effectiveRange = CFRangeMake(0, 0); while ((effectiveRange.location + effectiveRange.length) < length) { CFDictionaryRef attributes = CFAttributedStringGetAttributes(attributedString, effectiveRange.location + effectiveRange.length, &effectiveRange); if (!attributes) continue; StringBuilder tagStart; CFStringRef valueString; String tagEnd; CFIndex attributeCount = CFDictionaryGetCount(attributes); Vector<const void*> keys(attributeCount); Vector<const void*> values(attributeCount); CFDictionaryGetKeysAndValues(attributes, keys.data(), values.data()); for (CFIndex i = 0; i < attributeCount; ++i) { CFStringRef key = static_cast<CFStringRef>(keys[i]); CFTypeRef value = values[i]; if (CFGetTypeID(key) != CFStringGetTypeID() || !CFStringGetLength(key)) continue; if (CFStringCompare(key, kCMTextMarkupAttribute_Alignment, 0) == kCFCompareEqualTo) { valueString = static_cast<CFStringRef>(value); if (CFGetTypeID(valueString) != CFStringGetTypeID() || !CFStringGetLength(valueString)) continue; if (processed & Align) continue; processed |= Align; if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_Start, 0) == kCFCompareEqualTo) cueData->setAlign(GenericCueData::Start); else if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_Middle, 0) == kCFCompareEqualTo) cueData->setAlign(GenericCueData::Middle); else if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_End, 0) == kCFCompareEqualTo) cueData->setAlign(GenericCueData::End); else ASSERT_NOT_REACHED(); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_BoldStyle, 0) == kCFCompareEqualTo) { if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue) continue; tagStart.append("<b>"); tagEnd.insert("</b>", 0); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_ItalicStyle, 0) == kCFCompareEqualTo) { if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue) continue; tagStart.append("<i>"); tagEnd.insert("</i>", 0); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_UnderlineStyle, 0) == kCFCompareEqualTo) { if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue) continue; tagStart.append("<u>"); tagEnd.insert("</u>", 0); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_OrthogonalLinePositionPercentageRelativeToWritingDirection, 0) == kCFCompareEqualTo) { if (CFGetTypeID(value) != CFNumberGetTypeID()) continue; if (processed & Line) continue; processed |= Line; CFNumberRef valueNumber = static_cast<CFNumberRef>(value); double line; CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &line); cueData->setLine(line); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_TextPositionPercentageRelativeToWritingDirection, 0) == kCFCompareEqualTo) { if (CFGetTypeID(value) != CFNumberGetTypeID()) continue; if (processed & Position) continue; processed |= Position; CFNumberRef valueNumber = static_cast<CFNumberRef>(value); double position; CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &position); cueData->setPosition(position); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_WritingDirectionSizePercentage, 0) == kCFCompareEqualTo) { if (CFGetTypeID(value) != CFNumberGetTypeID()) continue; if (processed & Size) continue; processed |= Size; CFNumberRef valueNumber = static_cast<CFNumberRef>(value); double size; CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &size); cueData->setSize(size); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_VerticalLayout, 0) == kCFCompareEqualTo) { valueString = static_cast<CFStringRef>(value); if (CFGetTypeID(valueString) != CFStringGetTypeID() || !CFStringGetLength(valueString)) continue; if (CFStringCompare(valueString, kCMTextVerticalLayout_LeftToRight, 0) == kCFCompareEqualTo) tagStart.append(leftToRightMark); else if (CFStringCompare(valueString, kCMTextVerticalLayout_RightToLeft, 0) == kCFCompareEqualTo) tagStart.append(rightToLeftMark); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_BaseFontSizePercentageRelativeToVideoHeight, 0) == kCFCompareEqualTo) { if (CFGetTypeID(value) != CFNumberGetTypeID()) continue; CFNumberRef valueNumber = static_cast<CFNumberRef>(value); double baseFontSize; CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &baseFontSize); cueData->setBaseFontSize(baseFontSize); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_RelativeFontSize, 0) == kCFCompareEqualTo) { if (CFGetTypeID(value) != CFNumberGetTypeID()) continue; CFNumberRef valueNumber = static_cast<CFNumberRef>(value); double relativeFontSize; CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &relativeFontSize); cueData->setRelativeFontSize(relativeFontSize); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_FontFamilyName, 0) == kCFCompareEqualTo) { valueString = static_cast<CFStringRef>(value); if (CFGetTypeID(valueString) != CFStringGetTypeID() || !CFStringGetLength(valueString)) continue; if (processed & FontName) continue; processed |= FontName; cueData->setFontName(valueString); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_ForegroundColorARGB, 0) == kCFCompareEqualTo) { CFArrayRef arrayValue = static_cast<CFArrayRef>(value); if (CFGetTypeID(arrayValue) != CFArrayGetTypeID()) continue; RGBA32 color; if (!makeRGBA32FromARGBCFArray(arrayValue, color)) continue; cueData->setForegroundColor(color); } if (CFStringCompare(key, kCMTextMarkupAttribute_BackgroundColorARGB, 0) == kCFCompareEqualTo) { CFArrayRef arrayValue = static_cast<CFArrayRef>(value); if (CFGetTypeID(arrayValue) != CFArrayGetTypeID()) continue; RGBA32 color; if (!makeRGBA32FromARGBCFArray(arrayValue, color)) continue; cueData->setBackgroundColor(color); } if (CFStringCompare(key, kCMTextMarkupAttribute_CharacterBackgroundColorARGB, 0) == kCFCompareEqualTo) { CFArrayRef arrayValue = static_cast<CFArrayRef>(value); if (CFGetTypeID(arrayValue) != CFArrayGetTypeID()) continue; RGBA32 color; if (!makeRGBA32FromARGBCFArray(arrayValue, color)) continue; cueData->setHighlightColor(color); } } content.append(tagStart); content.append(attributedStringValue.substring(effectiveRange.location, effectiveRange.length)); content.append(tagEnd); } if (content.length()) cueData->setContent(content.toString()); }
pid_t HP_HogMode::GetOwnerFromPreference(bool inSendNotifications) const { pid_t theAnswer = -1; #if HogMode_UseCFPrefs // get the preference CFNumberRef theCFNumber = CACFPreferences::CopyNumberValue(mPrefName, false, true); if(theCFNumber != NULL) { // get the number pid_t theOwner = -1; CFNumberGetValue(theCFNumber, kCFNumberSInt32Type, &theOwner); // make sure the process exists if(theOwner == -1) { // hog mode is free theAnswer = -1; } else if(CAProcess::ProcessExists(theOwner)) { // it does, so set the return value theAnswer = theOwner; } else { // it doesn't, so delete the pref SetOwnerInPreference((pid_t)-1); if(inSendNotifications) { // signal that hog mode changed SendHogModeChangedNotification(); } } CFRelease(theCFNumber); } #else // get the owner from the preference SInt32 theOwner = -1; sSettingsStorage->CopySInt32Value(mPrefName, theOwner, SInt32(-1)); // make sure the process exists if(theOwner == -1) { // hog mode is free theAnswer = -1; } else if(CAProcess::ProcessExists(theOwner)) { // the process that owns hog mode exists theAnswer = theOwner; } else { // the process that owns hog mode doesn't exist, so delete the pref theAnswer = -1; SetOwnerInPreference((pid_t)-1); if(inSendNotifications) { // signal that hog mode changed SendHogModeChangedNotification(); } } #endif return theAnswer; }
void upsdrv_updateinfo(void) { CFPropertyListRef power_dictionary; CFStringRef power_source_state; CFNumberRef battery_voltage, battery_runtime; CFNumberRef current_capacity; CFBooleanRef is_charging; double max_capacity_value = 100.0, current_capacity_value; upsdebugx(1, "upsdrv_updateinfo()"); power_dictionary = copy_power_dictionary( g_power_key ); assert(power_dictionary); /* TODO: call dstate_datastale()? */ status_init(); /* Retrieve OL/OB state */ power_source_state = CFDictionaryGetValue(power_dictionary, CFSTR(kIOPSPowerSourceStateKey)); assert(power_source_state); CFRetain(power_source_state); upsdebugx(3, "Power Source State:"); if(nut_debug_level >= 3) CFShow(power_source_state); if(!CFStringCompare(power_source_state, CFSTR(kIOPSACPowerValue), 0)) { status_set("OL"); } else { status_set("OB"); } CFRelease(power_source_state); /* Retrieve CHRG state */ is_charging = CFDictionaryGetValue(power_dictionary, CFSTR(kIOPSIsChargingKey)); if(is_charging) { Boolean is_charging_value; is_charging_value = CFBooleanGetValue(is_charging); if(is_charging_value) { status_set("CHRG"); } } status_commit(); /* Retrieve battery voltage */ battery_voltage = CFDictionaryGetValue(power_dictionary, CFSTR(kIOPSVoltageKey)); if(battery_voltage) { int battery_voltage_value; CFNumberGetValue(battery_voltage, kCFNumberIntType, &battery_voltage_value); upsdebugx(2, "battery_voltage = %d mV", battery_voltage_value); dstate_setinfo("battery.voltage", "%.3f", battery_voltage_value/1000.0); } /* Retrieve battery runtime */ battery_runtime = CFDictionaryGetValue(power_dictionary, CFSTR(kIOPSTimeToEmptyKey)); if(battery_runtime) { double battery_runtime_value; CFNumberGetValue(battery_runtime, kCFNumberDoubleType, &battery_runtime_value); upsdebugx(2, "battery_runtime = %.f minutes", battery_runtime_value); if(battery_runtime_value > 0) { dstate_setinfo("battery.runtime", "%d", (int)(battery_runtime_value*60)); } else { dstate_delinfo("battery.runtime"); } } else { dstate_delinfo("battery.runtime"); } /* Retrieve current capacity */ current_capacity = CFDictionaryGetValue(power_dictionary, CFSTR(kIOPSCurrentCapacityKey)); if(current_capacity) { CFNumberGetValue(current_capacity, kCFNumberDoubleType, ¤t_capacity_value); upsdebugx(2, "Current Capacity = %.f/%.f units", current_capacity_value, max_capacity_value); if(max_capacity_value > 0) { dstate_setinfo("battery.charge", "%.f", 100.0 * current_capacity_value / max_capacity_value); } } /* TODO: it should be possible to set poll_interval (and maxage in the * server) to an absurdly large value, and use notify(3) to get * updates. */ /* * poll_interval = 2; */ dstate_dataok(); CFRelease(power_dictionary); }
/* Note that AC power sources also include a laptop battery it is charging. */ void power_osx::checkps(CFDictionaryRef dict, bool *have_ac, bool *have_battery, bool *charging) { CFStringRef strval; /* don't CFRelease() this. */ CFBooleanRef bval; CFNumberRef numval; bool charge = false; bool choose = false; bool is_ac = false; int secs = -1; int maxpct = -1; int pct = -1; if ((GETVAL(kIOPSIsPresentKey, &bval)) && (bval == kCFBooleanFalse)) { return; /* nothing to see here. */ } if (!GETVAL(kIOPSPowerSourceStateKey, &strval)) { return; } if (STRMATCH(strval, CFSTR(kIOPSACPowerValue))) { is_ac = *have_ac = true; } else if (!STRMATCH(strval, CFSTR(kIOPSBatteryPowerValue))) { return; /* not a battery? */ } if ((GETVAL(kIOPSIsChargingKey, &bval)) && (bval == kCFBooleanTrue)) { charge = true; } if (GETVAL(kIOPSMaxCapacityKey, &numval)) { SInt32 val = -1; CFNumberGetValue(numval, kCFNumberSInt32Type, &val); if (val > 0) { *have_battery = true; maxpct = (int)val; } } if (GETVAL(kIOPSMaxCapacityKey, &numval)) { SInt32 val = -1; CFNumberGetValue(numval, kCFNumberSInt32Type, &val); if (val > 0) { *have_battery = true; maxpct = (int)val; } } if (GETVAL(kIOPSTimeToEmptyKey, &numval)) { SInt32 val = -1; CFNumberGetValue(numval, kCFNumberSInt32Type, &val); /* Mac OS X reports 0 minutes until empty if you're plugged in. :( */ if ((val == 0) && (is_ac)) { val = -1; /* !!! FIXME: calc from timeToFull and capacity? */ } secs = (int)val; if (secs > 0) { secs *= 60; /* value is in minutes, so convert to seconds. */ } } if (GETVAL(kIOPSCurrentCapacityKey, &numval)) { SInt32 val = -1; CFNumberGetValue(numval, kCFNumberSInt32Type, &val); pct = (int)val; } if ((pct > 0) && (maxpct > 0)) { pct = (int)((((double)pct) / ((double)maxpct)) * 100.0); } if (pct > 100) { pct = 100; } /* * We pick the battery that claims to have the most minutes left. * (failing a report of minutes, we'll take the highest percent.) */ if ((secs < 0) && (nsecs_left < 0)) { if ((pct < 0) && (percent_left < 0)) { choose = true; /* at least we know there's a battery. */ } if (pct > percent_left) { choose = true; } } else if (secs > nsecs_left) { choose = true; } if (choose) { nsecs_left = secs; percent_left = pct; *charging = charge; } }
int ReadHashStateFile( const char *inFilePath, sHashState *inOutHashState ) { CFStringRef myReplicaDataFilePathRef; CFURLRef myReplicaDataFileRef; CFReadStreamRef myReadStreamRef; CFPropertyListRef myPropertyListRef; CFStringRef errorString; CFPropertyListFormat myPLFormat; struct stat sb; CFMutableDictionaryRef stateDict = NULL; CFStringRef keyString = NULL; CFDateRef dateValue = NULL; CFNumberRef numberValue = NULL; long aLongValue; short aShortValue; int returnValue = 0; if ( inFilePath == NULL || inOutHashState == NULL ) return -1; do { if ( stat( inFilePath, &sb ) != 0 ) { time_t now; // initialize the creation date. time( &now ); gmtime_r( &now, &inOutHashState->creationDate ); returnValue = -1; break; } myReplicaDataFilePathRef = CFStringCreateWithCString( kCFAllocatorDefault, inFilePath, kCFStringEncodingUTF8 ); if ( myReplicaDataFilePathRef == NULL ) { returnValue = -1; break; } myReplicaDataFileRef = CFURLCreateWithFileSystemPath( kCFAllocatorDefault, myReplicaDataFilePathRef, kCFURLPOSIXPathStyle, false ); CFRelease( myReplicaDataFilePathRef ); if ( myReplicaDataFileRef == NULL ) { returnValue = -1; break; } myReadStreamRef = CFReadStreamCreateWithFile( kCFAllocatorDefault, myReplicaDataFileRef ); CFRelease( myReplicaDataFileRef ); if ( myReadStreamRef == NULL ) { returnValue = -1; break; } CFReadStreamOpen( myReadStreamRef ); errorString = NULL; myPLFormat = kCFPropertyListXMLFormat_v1_0; myPropertyListRef = CFPropertyListCreateFromStream( kCFAllocatorDefault, myReadStreamRef, 0, kCFPropertyListMutableContainersAndLeaves, &myPLFormat, &errorString ); CFReadStreamClose( myReadStreamRef ); CFRelease( myReadStreamRef ); if ( errorString != NULL ) { char errMsg[256]; if ( CFStringGetCString( errorString, errMsg, sizeof(errMsg), kCFStringEncodingUTF8 ) ) DbgLog(kLogPlugin, "ReadHashStateFile: could not load the state file, error = %s", errMsg ); CFRelease( errorString ); } if ( myPropertyListRef == NULL ) { DbgLog(kLogPlugin, "ReadHashStateFile: could not load the hash state file because the property list is empty." ); returnValue = -1; break; } if ( CFGetTypeID(myPropertyListRef) != CFDictionaryGetTypeID() ) { CFRelease( myPropertyListRef ); DbgLog(kLogPlugin, "ReadHashStateFile: could not load the hash state file because the property list is not a dictionary." ); returnValue = -1; break; } stateDict = (CFMutableDictionaryRef)myPropertyListRef; keyString = CFStringCreateWithCString( kCFAllocatorDefault, "CreationDate", kCFStringEncodingUTF8 ); if ( keyString != NULL ) { if ( CFDictionaryGetValueIfPresent( stateDict, keyString, (const void **)&dateValue ) ) { pwsf_ConvertCFDateToBSDTime( dateValue, &inOutHashState->creationDate ); } CFRelease( keyString ); } keyString = CFStringCreateWithCString( kCFAllocatorDefault, "LastLoginDate", kCFStringEncodingUTF8 ); if ( keyString != NULL ) { if ( CFDictionaryGetValueIfPresent( stateDict, keyString, (const void **)&dateValue ) ) { pwsf_ConvertCFDateToBSDTime( dateValue, &inOutHashState->lastLoginDate ); } CFRelease( keyString ); } keyString = CFStringCreateWithCString( kCFAllocatorDefault, "FailedLoginCount", kCFStringEncodingUTF8 ); if ( keyString != NULL ) { if ( CFDictionaryGetValueIfPresent( stateDict, keyString, (const void **)&numberValue ) && CFGetTypeID(numberValue) == CFNumberGetTypeID() && CFNumberGetValue( (CFNumberRef)numberValue, kCFNumberLongType, &aLongValue) ) { inOutHashState->failedLoginAttempts = (UInt16)aLongValue; } CFRelease( keyString ); } keyString = CFStringCreateWithCString( kCFAllocatorDefault, "NewPasswordRequired", kCFStringEncodingUTF8 ); if ( keyString != NULL ) { if ( CFDictionaryGetValueIfPresent( stateDict, keyString, (const void **)&numberValue ) && CFGetTypeID(numberValue) == CFNumberGetTypeID() && CFNumberGetValue( (CFNumberRef)numberValue, kCFNumberSInt16Type, &aShortValue) ) { inOutHashState->newPasswordRequired = (UInt16)aShortValue; } CFRelease( keyString ); } CFRelease( stateDict ); } while( false ); return returnValue; }
tDirStatus OpenLDAPNode( CDSLocalPlugin *inPlugin, CFMutableDictionaryRef inNodeDict, tDataListPtr inNodeName, tDirReference *outDSRef, tDirNodeReference *outNodeRef ) { tDirStatus status = eDSNoErr; tDirReference ldapDirRef = 0; tDirNodeReference ldapNodeRef = 0; CFNumberRef ldapNodeRefNumber = NULL; try { CFNumberRef ldapDirRefNumber = (CFNumberRef)CFDictionaryGetValue( inNodeDict, CFSTR(kNodeLDAPDirRef) ); if ( ldapDirRefNumber != NULL ) CFNumberGetValue( ldapDirRefNumber, kCFNumberLongType, &ldapDirRef ); if ( ldapDirRef == 0 ) { status = inPlugin->GetDirServiceRef( &ldapDirRef ); if ( status != eDSNoErr ) throw( status ); ldapDirRefNumber = CFNumberCreate( NULL, kCFNumberLongType, &ldapDirRef ); CFDictionaryAddValue( inNodeDict, CFSTR(kNodeLDAPDirRef), ldapDirRefNumber ); CFRelease( ldapDirRefNumber ); } // Free prior LDAP node ldapNodeRefNumber = (CFNumberRef)CFDictionaryGetValue( inNodeDict, CFSTR(kNodeLDAPNodeRef) ); if ( ldapNodeRefNumber != NULL ) { CFNumberGetValue( ldapNodeRefNumber, kCFNumberLongType, &ldapNodeRef ); if ( ldapNodeRef != 0 ) { dsCloseDirNode( ldapNodeRef ); ldapNodeRef = 0; } CFDictionaryRemoveValue( inNodeDict, CFSTR(kNodeLDAPNodeRef) ); ldapNodeRefNumber = NULL; } status = dsOpenDirNode( ldapDirRef, inNodeName, &ldapNodeRef ); if ( status == eDSNoErr ) { ldapNodeRefNumber = CFNumberCreate( NULL, kCFNumberLongType, &ldapNodeRef ); CFDictionaryAddValue( inNodeDict, CFSTR(kNodeLDAPNodeRef), ldapNodeRefNumber ); CFRelease( ldapNodeRefNumber ); } } catch ( tDirStatus catchStatus ) { status = catchStatus; } *outDSRef = ldapDirRef; *outNodeRef = ldapNodeRef; return status; }
bool PluginPackage::fetchInfo() { if (!load()) return false; WTF::RetainPtr<CFDictionaryRef> mimeDict; WTF::RetainPtr<CFTypeRef> mimeTypesFileName = CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginMIMETypesFilename")); if (mimeTypesFileName && CFGetTypeID(mimeTypesFileName.get()) == CFStringGetTypeID()) { WTF::RetainPtr<CFStringRef> fileName = (CFStringRef)mimeTypesFileName.get(); WTF::RetainPtr<CFStringRef> homeDir = homeDirectoryPath().createCFString(); WTF::RetainPtr<CFStringRef> path = CFStringCreateWithFormat(0, 0, CFSTR("%@/Library/Preferences/%@"), homeDir.get(), fileName.get()); WTF::RetainPtr<CFDictionaryRef> plist = readPListFile(path.get(), /*createFile*/ false, m_module); if (plist) { // If the plist isn't localized, have the plug-in recreate it in the preferred language. WTF::RetainPtr<CFStringRef> localizationName = (CFStringRef)CFDictionaryGetValue(plist.get(), CFSTR("WebPluginLocalizationName")); CFLocaleRef locale = CFLocaleCopyCurrent(); if (localizationName != CFLocaleGetIdentifier(locale)) plist = readPListFile(path.get(), /*createFile*/ true, m_module); CFRelease(locale); } else { // Plist doesn't exist, ask the plug-in to create it. plist = readPListFile(path.get(), /*createFile*/ true, m_module); } mimeDict = (CFDictionaryRef)CFDictionaryGetValue(plist.get(), CFSTR("WebPluginMIMETypes")); } if (!mimeDict) mimeDict = (CFDictionaryRef)CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginMIMETypes")); if (mimeDict) { CFIndex propCount = CFDictionaryGetCount(mimeDict.get()); Vector<const void*, 128> keys(propCount); Vector<const void*, 128> values(propCount); CFDictionaryGetKeysAndValues(mimeDict.get(), keys.data(), values.data()); for (int i = 0; i < propCount; ++i) { String mimeType = (CFStringRef)keys[i]; mimeType = mimeType.lower(); WTF::RetainPtr<CFDictionaryRef> extensionsDict = (CFDictionaryRef)values[i]; WTF:RetainPtr<CFNumberRef> enabled = (CFNumberRef)CFDictionaryGetValue(extensionsDict.get(), CFSTR("WebPluginTypeEnabled")); if (enabled) { int enabledValue = 0; if (CFNumberGetValue(enabled.get(), kCFNumberIntType, &enabledValue) && enabledValue == 0) continue; } Vector<String> mimeExtensions; WTF::RetainPtr<CFArrayRef> extensions = (CFArrayRef)CFDictionaryGetValue(extensionsDict.get(), CFSTR("WebPluginExtensions")); if (extensions) { CFIndex extensionCount = CFArrayGetCount(extensions.get()); for (CFIndex i = 0; i < extensionCount; ++i) { String extension =(CFStringRef)CFArrayGetValueAtIndex(extensions.get(), i); extension = extension.lower(); mimeExtensions.append(extension); } } m_mimeToExtensions.set(mimeType, mimeExtensions); String description = (CFStringRef)CFDictionaryGetValue(extensionsDict.get(), CFSTR("WebPluginTypeDescription")); m_mimeToDescriptions.set(mimeType, description); } m_name = (CFStringRef)CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginName")); m_description = (CFStringRef)CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginDescription")); } else { int resFile = CFBundleOpenBundleResourceMap(m_module); UseResFile(resFile); Vector<String> mimes = stringListFromResourceId(MIMEListStringStringNumber); if (mimes.size() % 2 != 0) return false; Vector<String> descriptions = stringListFromResourceId(MIMEDescriptionStringNumber); if (descriptions.size() != mimes.size() / 2) return false; for (size_t i = 0; i < mimes.size(); i += 2) { String mime = mimes[i].lower(); Vector<String> extensions; mimes[i + 1].lower().split(UChar(','), extensions); m_mimeToExtensions.set(mime, extensions); m_mimeToDescriptions.set(mime, descriptions[i / 2]); } Vector<String> names = stringListFromResourceId(PluginNameOrDescriptionStringNumber); if (names.size() == 2) { m_description = names[0]; m_name = names[1]; } CFBundleCloseBundleResourceMap(m_module, resFile); } LOG(Plugin, "PluginPackage::fetchInfo(): Found plug-in '%s'", m_name.utf8().data()); if (isPluginBlacklisted()) { LOG(Plugin, "\tPlug-in is blacklisted!"); return false; } return true; }
static QVariant qtValue(CFPropertyListRef cfvalue) { if (!cfvalue) return QVariant(); CFTypeID typeId = CFGetTypeID(cfvalue); /* Sorted grossly from most to least frequent type. */ if (typeId == CFStringGetTypeID()) { return QSettingsPrivate::stringToVariant(QCFString::toQString(static_cast<CFStringRef>(cfvalue))); } else if (typeId == CFNumberGetTypeID()) { CFNumberRef cfnumber = static_cast<CFNumberRef>(cfvalue); if (CFNumberIsFloatType(cfnumber)) { double d; CFNumberGetValue(cfnumber, kCFNumberDoubleType, &d); return d; } else { int i; qint64 ll; if (CFNumberGetType(cfnumber) == kCFNumberIntType) { CFNumberGetValue(cfnumber, kCFNumberIntType, &i); return i; } CFNumberGetValue(cfnumber, kCFNumberLongLongType, &ll); return ll; } } else if (typeId == CFArrayGetTypeID()) { CFArrayRef cfarray = static_cast<CFArrayRef>(cfvalue); QList<QVariant> list; CFIndex size = CFArrayGetCount(cfarray); bool metNonString = false; for (CFIndex i = 0; i < size; ++i) { QVariant value = qtValue(CFArrayGetValueAtIndex(cfarray, i)); if (value.type() != QVariant::String) metNonString = true; list << value; } if (metNonString) return list; else return QVariant(list).toStringList(); } else if (typeId == CFBooleanGetTypeID()) { return (bool)CFBooleanGetValue(static_cast<CFBooleanRef>(cfvalue)); } else if (typeId == CFDataGetTypeID()) { CFDataRef cfdata = static_cast<CFDataRef>(cfvalue); return QByteArray(reinterpret_cast<const char *>(CFDataGetBytePtr(cfdata)), CFDataGetLength(cfdata)); } else if (typeId == CFDictionaryGetTypeID()) { CFDictionaryRef cfdict = static_cast<CFDictionaryRef>(cfvalue); CFTypeID arrayTypeId = CFArrayGetTypeID(); int size = (int)CFDictionaryGetCount(cfdict); QVarLengthArray<CFPropertyListRef> keys(size); QVarLengthArray<CFPropertyListRef> values(size); CFDictionaryGetKeysAndValues(cfdict, keys.data(), values.data()); QMultiMap<QString, QVariant> map; for (int i = 0; i < size; ++i) { QString key = QCFString::toQString(static_cast<CFStringRef>(keys[i])); if (CFGetTypeID(values[i]) == arrayTypeId) { CFArrayRef cfarray = static_cast<CFArrayRef>(values[i]); CFIndex arraySize = CFArrayGetCount(cfarray); for (CFIndex j = arraySize - 1; j >= 0; --j) map.insert(key, qtValue(CFArrayGetValueAtIndex(cfarray, j))); } else { map.insert(key, qtValue(values[i])); } } return map; } else if (typeId == CFDateGetTypeID()) { QDateTime dt; dt.setTime_t((uint)kCFAbsoluteTimeIntervalSince1970); return dt.addSecs((int)CFDateGetAbsoluteTime(static_cast<CFDateRef>(cfvalue))); } return QVariant(); }
SV* _org_warhound_mdi_Number2SV(CFTypeRef attrItem) { double thisnv; /* FIXME: Error check? What to do if it fails? */ CFNumberGetValue(attrItem, kCFNumberDoubleType, &thisnv); return newSVnv(thisnv); }
/* * 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 void initializeDb() { QFontDatabasePrivate *db = privateDb(); if(!db || db->count) return; #if defined(QT_MAC_USE_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5 if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) { QCFType<CTFontCollectionRef> collection = CTFontCollectionCreateFromAvailableFonts(0); if(!collection) return; QCFType<CFArrayRef> fonts = CTFontCollectionCreateMatchingFontDescriptors(collection); if(!fonts) return; QString foundry_name = "CoreText"; const int numFonts = CFArrayGetCount(fonts); for(int i = 0; i < numFonts; ++i) { CTFontDescriptorRef font = (CTFontDescriptorRef)CFArrayGetValueAtIndex(fonts, i); QCFString family_name = (CFStringRef)CTFontDescriptorCopyLocalizedAttribute(font, kCTFontFamilyNameAttribute, NULL); QCFString style_name = (CFStringRef)CTFontDescriptorCopyLocalizedAttribute(font, kCTFontStyleNameAttribute, NULL); QtFontFamily *family = db->family(family_name, true); if (QCFType<CFArrayRef> languages = (CFArrayRef) CTFontDescriptorCopyAttribute(font, kCTFontLanguagesAttribute)) { CFIndex length = CFArrayGetCount(languages); for (int i = 1; i < LanguageCount; ++i) { if (!languageForWritingSystem[i]) continue; QCFString lang = CFStringCreateWithCString(NULL, languageForWritingSystem[i], kCFStringEncodingASCII); if (CFArrayContainsValue(languages, CFRangeMake(0, length), lang)) family->writingSystems[i] = QtFontFamily::Supported; } } QtFontFoundry *foundry = family->foundry(foundry_name, true); QtFontStyle::Key styleKey; QString styleName = style_name; if(QCFType<CFDictionaryRef> styles = (CFDictionaryRef)CTFontDescriptorCopyAttribute(font, kCTFontTraitsAttribute)) { if(CFNumberRef weight = (CFNumberRef)CFDictionaryGetValue(styles, kCTFontWeightTrait)) { Q_ASSERT(CFNumberIsFloatType(weight)); double d; if(CFNumberGetValue(weight, kCFNumberDoubleType, &d)) { //qDebug() << "BOLD" << (QString)family_name << d; styleKey.weight = (d > 0.0) ? QFont::Bold : QFont::Normal; } } if(CFNumberRef italic = (CFNumberRef)CFDictionaryGetValue(styles, kCTFontSlantTrait)) { Q_ASSERT(CFNumberIsFloatType(italic)); double d; if(CFNumberGetValue(italic, kCFNumberDoubleType, &d)) { //qDebug() << "ITALIC" << (QString)family_name << d; if (d > 0.0) styleKey.style = QFont::StyleItalic; } } } QtFontStyle *style = foundry->style(styleKey, styleName, true); style->smoothScalable = true; if(QCFType<CFNumberRef> size = (CFNumberRef)CTFontDescriptorCopyAttribute(font, kCTFontSizeAttribute)) { //qDebug() << "WHEE"; int pixel_size=0; if(CFNumberIsFloatType(size)) { double d; CFNumberGetValue(size, kCFNumberDoubleType, &d); pixel_size = d; } else { CFNumberGetValue(size, kCFNumberIntType, &pixel_size); } //qDebug() << "SIZE" << (QString)family_name << pixel_size; if(pixel_size) style->pixelSize(pixel_size, true); } else { //qDebug() << "WTF?"; } } } else #endif { #ifndef QT_MAC_USE_COCOA FMFontIterator it; if (!FMCreateFontIterator(0, 0, kFMUseGlobalScopeOption, &it)) { while (true) { FMFont fmFont; if (FMGetNextFont(&it, &fmFont) != noErr) break; FMFontFamily fmFamily; FMFontStyle fmStyle; QString familyName; QtFontStyle::Key styleKey; ATSFontRef atsFont = FMGetATSFontRefFromFont(fmFont); if (!FMGetFontFamilyInstanceFromFont(fmFont, &fmFamily, &fmStyle)) { { //sanity check the font, and see if we can use it at all! --Sam ATSUFontID fontID; if(ATSUFONDtoFontID(fmFamily, 0, &fontID) != noErr) continue; } if (fmStyle & ::italic) styleKey.style = QFont::StyleItalic; if (fmStyle & ::bold) styleKey.weight = QFont::Bold; ATSFontFamilyRef familyRef = FMGetATSFontFamilyRefFromFontFamily(fmFamily); QCFString cfFamilyName;; ATSFontFamilyGetName(familyRef, kATSOptionFlagsDefault, &cfFamilyName); familyName = cfFamilyName; } else { QCFString cfFontName; ATSFontGetName(atsFont, kATSOptionFlagsDefault, &cfFontName); familyName = cfFontName; quint16 macStyle = 0; { uchar data[4]; ByteCount len = 4; if (ATSFontGetTable(atsFont, MAKE_TAG('h', 'e', 'a', 'd'), 44, 4, &data, &len) == noErr) macStyle = qFromBigEndian<quint16>(data); } if (macStyle & 1) styleKey.weight = QFont::Bold; if (macStyle & 2) styleKey.style = QFont::StyleItalic; } QtFontFamily *family = db->family(familyName, true); QtFontFoundry *foundry = family->foundry(QString(), true); QtFontStyle *style = foundry->style(styleKey, QString(), true); style->pixelSize(0, true); style->smoothScalable = true; initWritingSystems(family, atsFont); } FMDisposeFontIterator(&it); } #endif } }
static OSStatus DoLoadMemory( AuthorizationRef auth, const void * userData, CFDictionaryRef request, CFMutableDictionaryRef response, aslclient asl, aslmsg aslMsg ) // Implements the kGetUIDsCommand. Gets the process's three UIDs and // adds them to the response dictionary. { //asl_log(asl, aslMsg, ASL_LEVEL_DEBUG, "DoLoadMemory()"); // Pre-conditions if(auth == NULL || request == NULL || response == NULL) return kMemToolBadParameter; // CFShow(request); // load in the WoW ProcessID pid_t wowPID = 0; CFNumberRef cfPID = CFDictionaryGetValue(request, CFSTR(kWarcraftPID)); if(!CFNumberGetValue(cfPID, kCFNumberIntType, &wowPID) || wowPID <= 0) { return kMemToolBadPID; } // load in the memory address unsigned int address = 0; CFNumberRef cfAddress = CFDictionaryGetValue(request, CFSTR(kMemoryAddress)); if(!CFNumberGetValue(cfAddress, kCFNumberIntType, &address) || address == 0) { return kMemToolBadAddress; } // load in memory length vm_size_t length = 0; CFNumberRef cfLength = CFDictionaryGetValue(request, CFSTR(kMemoryLength)); if(!CFNumberGetValue(cfLength, kCFNumberIntType, &length) || length == 0) { return kMemToolBadLength; } bool memSuccess = false; if(wowPID && address && length) { //asl_log(asl, aslMsg, ASL_LEVEL_DEBUG, "Reading pid %d at address 0x%X for length %d", wowPID, address, length); // create buffer for our data Byte buffer[length]; int i; for(i=0; i<length; i++) buffer[i] = 0; // get a handle on the WoW task mach_port_t wowTask; task_for_pid(current_task(), wowPID, &wowTask); vm_size_t bytesRead = length; memSuccess = ((KERN_SUCCESS == vm_read_overwrite(wowTask, address, length, (vm_address_t)&buffer, &bytesRead)) && (bytesRead == length) ); //(KERN_SUCCESS == vm_write(wowTask, address, (vm_offset_t)&buffer, length)); if(memSuccess) { CFDataRef memoryContents = CFDataCreate(NULL, buffer, length); if(memoryContents != NULL) { // we got our memory! add it to the return dictionary CFDictionaryAddValue(response, CFSTR(kMemoryContents), memoryContents); CFRelease(memoryContents); return kMemToolNoError; } } } else { return kMemToolBadParameter; } return kMemToolUnknown; }
bool SFB::Audio::Metadata::SetFromDictionaryRepresentation(CFDictionaryRef dictionary) { if(nullptr == dictionary) return false; SetValue(kTitleKey, CFDictionaryGetValue(dictionary, kTitleKey)); SetValue(kAlbumTitleKey, CFDictionaryGetValue(dictionary, kAlbumTitleKey)); SetValue(kArtistKey, CFDictionaryGetValue(dictionary, kArtistKey)); SetValue(kAlbumArtistKey, CFDictionaryGetValue(dictionary, kAlbumArtistKey)); SetValue(kGenreKey, CFDictionaryGetValue(dictionary, kGenreKey)); SetValue(kComposerKey, CFDictionaryGetValue(dictionary, kComposerKey)); SetValue(kReleaseDateKey, CFDictionaryGetValue(dictionary, kReleaseDateKey)); SetValue(kCompilationKey, CFDictionaryGetValue(dictionary, kCompilationKey)); SetValue(kTrackNumberKey, CFDictionaryGetValue(dictionary, kTrackNumberKey)); SetValue(kTrackTotalKey, CFDictionaryGetValue(dictionary, kTrackTotalKey)); SetValue(kDiscNumberKey, CFDictionaryGetValue(dictionary, kDiscNumberKey)); SetValue(kDiscTotalKey, CFDictionaryGetValue(dictionary, kDiscTotalKey)); SetValue(kLyricsKey, CFDictionaryGetValue(dictionary, kLyricsKey)); SetValue(kBPMKey, CFDictionaryGetValue(dictionary, kBPMKey)); SetValue(kRatingKey, CFDictionaryGetValue(dictionary, kRatingKey)); SetValue(kCommentKey, CFDictionaryGetValue(dictionary, kCommentKey)); SetValue(kISRCKey, CFDictionaryGetValue(dictionary, kISRCKey)); SetValue(kMCNKey, CFDictionaryGetValue(dictionary, kMCNKey)); SetValue(kMusicBrainzReleaseIDKey, CFDictionaryGetValue(dictionary, kMusicBrainzReleaseIDKey)); SetValue(kMusicBrainzRecordingIDKey, CFDictionaryGetValue(dictionary, kMusicBrainzRecordingIDKey)); SetValue(kTitleSortOrderKey, CFDictionaryGetValue(dictionary, kTitleSortOrderKey)); SetValue(kAlbumTitleSortOrderKey, CFDictionaryGetValue(dictionary, kAlbumTitleSortOrderKey)); SetValue(kArtistSortOrderKey, CFDictionaryGetValue(dictionary, kArtistSortOrderKey)); SetValue(kAlbumArtistSortOrderKey, CFDictionaryGetValue(dictionary, kAlbumArtistSortOrderKey)); SetValue(kComposerSortOrderKey, CFDictionaryGetValue(dictionary, kComposerSortOrderKey)); SetValue(kGroupingKey, CFDictionaryGetValue(dictionary, kGroupingKey)); SetValue(kAdditionalMetadataKey, CFDictionaryGetValue(dictionary, kAdditionalMetadataKey)); SetValue(kReferenceLoudnessKey, CFDictionaryGetValue(dictionary, kReferenceLoudnessKey)); SetValue(kTrackGainKey, CFDictionaryGetValue(dictionary, kTrackGainKey)); SetValue(kTrackPeakKey, CFDictionaryGetValue(dictionary, kTrackPeakKey)); SetValue(kAlbumGainKey, CFDictionaryGetValue(dictionary, kAlbumGainKey)); SetValue(kAlbumPeakKey, CFDictionaryGetValue(dictionary, kAlbumPeakKey)); RemoveAllAttachedPictures(); CFArrayRef attachedPictures = (CFArrayRef)CFDictionaryGetValue(dictionary, kAttachedPicturesKey); for(CFIndex i = 0; i < CFArrayGetCount(attachedPictures); ++i) { CFDictionaryRef pictureDictionary = (CFDictionaryRef)CFArrayGetValueAtIndex(attachedPictures, i); CFDataRef pictureData = (CFDataRef)CFDictionaryGetValue(pictureDictionary, AttachedPicture::kDataKey); AttachedPicture::Type pictureType = AttachedPicture::Type::Other; CFNumberRef typeWrapper = (CFNumberRef)CFDictionaryGetValue(pictureDictionary, AttachedPicture::kTypeKey); if(nullptr != typeWrapper) CFNumberGetValue(typeWrapper, kCFNumberIntType, &pictureType); CFStringRef pictureDescription = (CFStringRef)CFDictionaryGetValue(pictureDictionary, AttachedPicture::kDescriptionKey); AttachPicture(std::make_shared<AttachedPicture>(pictureData, pictureType, pictureDescription)); } return true; }
static OSStatus DoSaveMemory( AuthorizationRef auth, const void * userData, CFDictionaryRef request, CFMutableDictionaryRef response, aslclient asl, aslmsg aslMsg ) // Implements the kLowNumberedPortsCommand. Opens three low-numbered ports // and adds them to the descriptor array in the response dictionary. { // Pre-conditions if(auth == NULL || request == NULL || response == NULL) return kMemToolBadParameter; // CFShow(request); // load in the WoW ProcessID pid_t wowPID = 0; CFNumberRef cfPID = CFDictionaryGetValue(request, CFSTR(kWarcraftPID)); if(!CFNumberGetValue(cfPID, kCFNumberIntType, &wowPID) || wowPID <= 0) { return kMemToolBadPID; } // load in the memory address unsigned int address = 0; CFNumberRef cfAddress = CFDictionaryGetValue(request, CFSTR(kMemoryAddress)); if(!CFNumberGetValue(cfAddress, kCFNumberIntType, &address) || address == 0) { return kMemToolBadAddress; } // load in memory length CFIndex length = 0; CFDataRef cfContents = CFDictionaryGetValue(request, CFSTR(kMemoryContents)); if( !(length = CFDataGetLength(cfContents))) { return kMemToolBadContents; } bool memSuccess = false; if(wowPID && address && cfContents && length) { asl_log(asl, aslMsg, ASL_LEVEL_DEBUG, "Writing to pid %d at address 0x%X with data length %ld", wowPID, address, length); // put our data into a local buffer Byte buffer[length]; CFDataGetBytes(cfContents, CFRangeMake(0, length), buffer); // get a handle on the WoW task mach_port_t wowTask; task_for_pid(current_task(), wowPID, &wowTask); memSuccess = (KERN_SUCCESS == vm_write(wowTask, address, (vm_offset_t)&buffer, length)); if(memSuccess) { asl_log(asl, aslMsg, ASL_LEVEL_DEBUG, "Write success!"); return kMemToolNoError; } } else { return kMemToolBadParameter; } return kMemToolUnknown; }
bool UserObjectImp::toBoolean(ExecState *exec) const { bool result = false; JSUserObject* jsObjPtr = KJSValueToJSObject(toObject(exec), exec); CFTypeRef cfValue = jsObjPtr ? jsObjPtr->CopyCFValue() : 0; if (cfValue) { CFTypeID cfType = CFGetTypeID(cfValue); // toPrimitive if (cfValue == GetCFNull()) { // } else if (cfType == CFBooleanGetTypeID()) { if (cfValue == kCFBooleanTrue) { result = true; } } else if (cfType == CFStringGetTypeID()) { if (CFStringGetLength((CFStringRef)cfValue)) { result = true; } } else if (cfType == CFNumberGetTypeID()) { if (cfValue != kCFNumberNaN) { double d; if (CFNumberGetValue((CFNumberRef)cfValue, kCFNumberDoubleType, &d)) { if (d != 0) { result = true; } } } } else if (cfType == CFArrayGetTypeID()) { if (CFArrayGetCount((CFArrayRef)cfValue)) { result = true; } } else if (cfType == CFDictionaryGetTypeID()) { if (CFDictionaryGetCount((CFDictionaryRef)cfValue)) { result = true; } } else if (cfType == CFSetGetTypeID()) { if (CFSetGetCount((CFSetRef)cfValue)) { result = true; } } else if (cfType == CFURLGetTypeID()) { CFURLRef absURL = CFURLCopyAbsoluteURL((CFURLRef)cfValue); if (absURL) { CFStringRef cfStr = CFURLGetString(absURL); if (cfStr && CFStringGetLength(cfStr)) { result = true; } ReleaseCFType(absURL); } } } if (jsObjPtr) jsObjPtr->Release(); ReleaseCFType(cfValue); return result; }
IOReturn IONetworkGetPacketFiltersMask( io_connect_t connect, const io_name_t filterGroup, UInt32 * filtersMask, IOOptionBits options ) { IOReturn kr; io_service_t service = 0; CFMutableDictionaryRef dict = 0; CFArrayRef keysArray = 0; CFStringRef group = 0; CFStringRef keys[2]; CFTypeRef value; do { *filtersMask = 0; // Locate our service provider. kr = IOConnectGetService( connect, &service ); if ( kr != kIOReturnSuccess ) break; if ( kIONetworkSupportedPacketFilters & options ) { io_service_t parentService; kr = IORegistryEntryGetParentEntry( service, kIOServicePlane, &parentService ); if ( kr != kIOReturnSuccess ) break; IOObjectRelease( service ); service = parentService; } // Fetch properties from registry. kr = IORegistryEntryCreateCFProperties( service, &dict, kCFAllocatorDefault, kNilOptions ); if ( kr != kIOReturnSuccess ) break; group = CFStringCreateWithCString( kCFAllocatorDefault, filterGroup, CFStringGetSystemEncoding() ); if ( group == 0 ) { kr = kIOReturnNoMemory; break; } // Create an array of keys to the value. keys[0] = (kIONetworkSupportedPacketFilters & options) ? CFSTR( kIOPacketFilters ) : CFSTR( kIORequiredPacketFilters ); keys[1] = group; keysArray = CFArrayCreate( NULL, (void *)keys, 2, &kCFTypeArrayCallBacks ); if ( keysArray == 0 ) { kr = kIOReturnNoMemory; break; } value = GetDictionaryValueUsingKeys( dict, keysArray, CFNumberGetTypeID() ); if ( value == 0 ) { kr = kIOReturnNotFound; break; } CFNumberGetValue( (CFNumberRef)value, kCFNumberSInt32Type, filtersMask ); } while ( 0 ); if ( dict ) CFRelease( dict ); if ( group ) CFRelease( group ); if ( keysArray ) CFRelease( keysArray ); if ( service ) IOObjectRelease( service ); return kr; }
UString UserObjectImp::toString(ExecState *exec) const { UString result; JSUserObject* jsObjPtr = KJSValueToJSObject(toObject(exec), exec); CFTypeRef cfValue = jsObjPtr ? jsObjPtr->CopyCFValue() : 0; if (cfValue) { CFTypeID cfType = CFGetTypeID(cfValue); if (cfValue == GetCFNull()) { // } else if (cfType == CFBooleanGetTypeID()) { if (cfValue == kCFBooleanTrue) { result = "true"; } else { result = "false"; } } else if (cfType == CFStringGetTypeID()) { result = CFStringToUString((CFStringRef)cfValue); } else if (cfType == CFNumberGetTypeID()) { if (cfValue == kCFNumberNaN) { result = "Nan"; } else if (CFNumberCompare(kCFNumberPositiveInfinity, (CFNumberRef)cfValue, 0) == 0) { result = "Infinity"; } else if (CFNumberCompare(kCFNumberNegativeInfinity, (CFNumberRef)cfValue, 0) == 0) { result = "-Infinity"; } else { CFStringRef cfNumStr; double d = 0; CFNumberGetValue((CFNumberRef)cfValue, kCFNumberDoubleType, &d); if (CFNumberIsFloatType((CFNumberRef)cfValue)) { cfNumStr = CFStringCreateWithFormat(0, 0, CFSTR("%f"), d); } else { cfNumStr = CFStringCreateWithFormat(0, 0, CFSTR("%.0f"), d); } result = CFStringToUString(cfNumStr); ReleaseCFType(cfNumStr); } } else if (cfType == CFArrayGetTypeID()) { // } else if (cfType == CFDictionaryGetTypeID()) { // } else if (cfType == CFSetGetTypeID()) { // } else if (cfType == CFURLGetTypeID()) { CFURLRef absURL = CFURLCopyAbsoluteURL((CFURLRef)cfValue); if (absURL) { CFStringRef cfStr = CFURLGetString(absURL); if (cfStr) { result = CFStringToUString(cfStr); } ReleaseCFType(absURL); } } } ReleaseCFType(cfValue); if (jsObjPtr) jsObjPtr->Release(); return result; }
void PsychHIDOSKbTriggerWait(int deviceIndex, int numScankeys, int* scanKeys) { pRecDevice deviceRecord; int i, numDeviceIndices; long KeysUsagePage; // This is the usage page of the target element: A key on a keyboard/keypad or a button. long KeysUsage; // This will contain the key code of the trigger key long KbDeviceUsagePages[NUMDEVICEUSAGES]= {kHIDPage_GenericDesktop, kHIDPage_GenericDesktop, kHIDPage_GenericDesktop, kHIDPage_GenericDesktop, kHIDPage_GenericDesktop, kHIDPage_GenericDesktop, kHIDPage_GenericDesktop}; long KbDeviceUsages[NUMDEVICEUSAGES]={kHIDUsage_GD_Keyboard, kHIDUsage_GD_Keypad, kHIDUsage_GD_Mouse, kHIDUsage_GD_Pointer, kHIDUsage_GD_Joystick, kHIDUsage_GD_GamePad, kHIDUsage_GD_MultiAxisController}; int numDeviceUsages=NUMDEVICEUSAGES; int deviceIndices[PSYCH_HID_MAX_KEYBOARD_DEVICES]; pRecDevice deviceRecords[PSYCH_HID_MAX_KEYBOARD_DEVICES]; psych_bool isDeviceSpecified, foundUserSpecifiedDevice; double *timeValueOutput; IOHIDQueueInterface **queue; HRESULT result; IOHIDDeviceInterface122** interface=NULL; // This requires Mac OS X 10.3 or higher IOReturn success; IOHIDElementCookie triggerCookie; uint32_t usage; // Assign single supported trigger key: if (numScankeys != 1) PsychErrorExitMsg(PsychError_user, "Sorry, the OS/X version of KbTriggerWait only supports one trigger key."); KeysUsage = (long) scanKeys[0]; // Optional deviceIndex specified? isDeviceSpecified = (deviceIndex >= 0) ? TRUE : FALSE; PsychHIDVerifyInit(); if(hidDataRef!=NULL) PsychErrorExitMsg(PsychError_user, "A queue is already running, you must call KbQueueRelease() before invoking KbTriggerWait."); //Choose the device index and its record PsychHIDGetDeviceListByUsages(numDeviceUsages, KbDeviceUsagePages, KbDeviceUsages, &numDeviceIndices, deviceIndices, deviceRecords); if(isDeviceSpecified){ //make sure that the device number provided by the user is really a keyboard or keypad. for(i=0;i<numDeviceIndices;i++){ if(foundUserSpecifiedDevice=(deviceIndices[i]==deviceIndex)) break; } if(!foundUserSpecifiedDevice) PsychErrorExitMsg(PsychError_user, "Specified device number is not a keyboard or keypad device."); }else{ // set the keyboard or keypad device to be the first keyboard device or, if no keyboard, the first keypad i=0; if(numDeviceIndices==0) PsychErrorExitMsg(PsychError_user, "No keyboard or keypad devices detected."); else{ deviceIndex=deviceIndices[i]; } } deviceRecord=deviceRecords[i]; #ifndef __LP64__ usage = deviceRecord->usage; #else usage = IOHIDDevice_GetUsage(deviceRecord); #endif KeysUsagePage = ((usage == kHIDUsage_GD_Keyboard) || (usage == kHIDUsage_GD_Keypad)) ? kHIDPage_KeyboardOrKeypad : kHIDPage_Button; //Allocate and init out return arguments. PsychAllocOutDoubleArg(1, FALSE, &timeValueOutput); if(!timeValueOutput) PsychErrorExitMsg(PsychError_system, "Failed to allocate memory for output."); interface = PsychHIDGetDeviceInterfacePtrFromIndex(deviceIndex); if(!interface) PsychErrorExitMsg(PsychError_system, "Could not get interface to device."); // The following bracketed clause will get a cookie corresponding to the // trigger. If multiple keys were of interest, the code could be modified // trivially to iterate over an array of KeysUsage to generate an array of // corresponding cookies { CFArrayRef elements=NULL; psych_bool usedDictionary=FALSE; { CFDictionaryRef dict=NULL; // The next few lines define a dictionary describing the key of interest // If they are omitted, the code will still work, but all elements will match // initially rather than just the one key of interest, so the code will be // slower since it will iterate through hundreds of keys CFStringRef keys[2] = {CFSTR("UsagePage"), CFSTR("Usage")}; CFNumberRef values[2]; values[0] = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &KeysUsagePage); values[1] = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &KeysUsage); if(values[0]!=NULL && values[1]!=NULL){ // Even if they are NULL, it will be ok since dict can be NULL at the expense of some loss of efficiency dict = CFDictionaryCreate(kCFAllocatorDefault, (const void**)keys, (const void**)values, 2, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } // copyMatchinfElements requires IOHIDDeviceInterface122, thus Mac OS X 10.3 or higher // elements would have to be obtained directly from IORegistry for 10.2 or earlier // If dict==NULL, all elements will match, leading to some inefficiency success = (*interface)->copyMatchingElements(interface, dict, &elements); if(dict){ usedDictionary=TRUE; CFRelease(dict); } if(values[0]) CFRelease(values[0]); if(values[1]) CFRelease(values[1]); if(!elements){ PsychErrorExitMsg(PsychError_user, "Specified key code not found on device (I)."); } } { // elements will only contain one element in this implementation, but has the // advantage of generalizing to future derived implementations that listen // for multiple keys CFIndex i; for (i=0; i<CFArrayGetCount(elements); i++) { long number; CFDictionaryRef element= CFArrayGetValueAtIndex(elements, i); CFTypeRef object; if(!element) continue; if(!usedDictionary){ // Verify tht we are dealing with a keypad or keyboard object = CFDictionaryGetValue(element, CFSTR(kIOHIDElementUsageKey)); if (object == 0 || CFGetTypeID(object) != CFNumberGetTypeID()) continue; if (!CFNumberGetValue((CFNumberRef) object, kCFNumberLongType,&number)) continue; if(number!=KeysUsage) continue; // See if element corresponds to the desired key object = CFDictionaryGetValue(element, CFSTR(kIOHIDElementUsagePageKey)); if (object == 0 || CFGetTypeID(object) != CFNumberGetTypeID()) continue; if (!CFNumberGetValue((CFNumberRef) object, kCFNumberLongType, &number)) continue; if(number!=KeysUsagePage) continue; } // Get the cookie for this element object= (CFDictionaryGetValue(element, CFSTR(kIOHIDElementCookieKey))); if (object == 0 || CFGetTypeID(object) != CFNumberGetTypeID()) continue; if(!CFNumberGetValue((CFNumberRef) object, kCFNumberLongType, &number)) continue; triggerCookie = (IOHIDElementCookie) number; break; } if(CFArrayGetCount(elements)==i){ CFRelease(elements); PsychErrorExitMsg(PsychError_user, "Specified key code not found on device (II)."); } CFRelease(elements); } } // Allocate for the queue queue=(*interface)->allocQueue(interface); if(!queue){ PsychErrorExitMsg(PsychError_system, "Failed to allocate event queue for detecting key press."); } // Create the queue result = (*queue)->create(queue, 0, 8); // 8 events can be stored before the earliest event is lost if (kIOReturnSuccess != result){ (*queue)->Release(queue); (*queue)=NULL; PsychErrorExitMsg(PsychError_system, "Failed to create event queue for detecting key press."); } // Add the trigger to the queue // If multiple keys were of interest, their cookies could be added in turn result = (*queue)->addElement(queue, triggerCookie, 0); if (kIOReturnSuccess != result){ result = (*queue)->dispose(queue); (*queue)->Release(queue); (*queue)=NULL; PsychErrorExitMsg(PsychError_system, "Failed to add trigger key to event queues."); } // Start the queue result = (*queue)->start(queue); if (kIOReturnSuccess != result){ result = (*queue)->dispose(queue); (*queue)->Release(queue); (*queue)=NULL; PsychErrorExitMsg(PsychError_system, "Failed to start event queues."); } // Watch for the trigger { IOHIDEventStruct event; while(1){ AbsoluteTime zeroTime = {0,0}; result = (*queue)->getNextEvent(queue, &event, zeroTime, 0); if(kIOReturnSuccess==result) break; PsychWaitIntervalSeconds((double)0.004); //surrender some time to other processes // If it were of interest to trigger selectively on key press or key release, // this could be evaluated by checking event.value (zero versus non-zero) // but this would put more code inside the loop // If multiple keys are registered via addElement (not the case here), the // cookie for the key responsible for the event can be obtained from // event.elementCookie } // If event.longValue is not NULL, the documentation indicates that it is up // to the caller to deallocate it. The circumstances under which a non-NULL // value would be generated are not specified. My guess is that some devices // might return a 64-bit value (e.g., a tracking device coordinate). // Keys, having only two states, shouldn't need this, but check and free to // be safe if ((event.longValueSize != 0) && (event.longValue != NULL)) free(event.longValue); // Set the time, using the same strategy as PsychTimeGlue's PsychGetPrecisionTimerSeconds // For code maintainability, it would be better if this conversion were performed // by a function in PsychTimeGlue { Nanoseconds timeNanoseconds=AbsoluteToNanoseconds(event.timestamp); UInt64 timeUInt64=UnsignedWideToUInt64(timeNanoseconds); double timeDouble=(double)timeUInt64; *timeValueOutput=timeDouble / 1000000000; } } // Clean up result = (*queue)->stop(queue); // Code from Apple sometimes removes elements from queue before disposing and sometimes does not // I can't see any reason to do so for a queue that's one line of code away from destruction // and therefore haven't result = (*queue)->dispose(queue); (*queue)->Release(queue); (*queue)=NULL; // Just in case queue is redefined as static in the future return; }
void wxHIDKeyboard::DoBuildCookies(CFArrayRef Array) { //Now go through each possible cookie int i; long nUsage; // bool bEOTriggered = false; for (i = 0; i < CFArrayGetCount(Array); ++i) { const void* ref = CFDictionaryGetValue( (CFDictionaryRef)CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementKey) ); if (ref != NULL) { DoBuildCookies((CFArrayRef) ref); } else { // // Get the usage # // CFNumberGetValue( (CFNumberRef) CFDictionaryGetValue((CFDictionaryRef) CFArrayGetValueAtIndex(Array, i), CFSTR(kIOHIDElementUsageKey) ), kCFNumberLongType, &nUsage); // // Now translate the usage # into a wx keycode // // // OK, this is strange - basically this kind of strange - // Starting from 0xEO these elements (like shift) appear twice in // the array! The ones at the end are bogus I guess - the funny part // is that besides the fact that the ones at the front have a Unit // and UnitExponent key with a value of 0 and a different cookie value, // there is no discernable difference between the two... // // Will the real shift please stand up? // // Something to spend a support request on, if I had one, LOL. // //if(nUsage == 0xE0) //{ // if(bEOTriggered) // break; // bEOTriggered = true; //} //Instead of that though we now just don't add duplicate keys if (nUsage >= kHIDUsage_KeyboardA && nUsage <= kHIDUsage_KeyboardZ) AddCookie(CFArrayGetValueAtIndex(Array, i), 'A' + (nUsage - kHIDUsage_KeyboardA) ); else if (nUsage >= kHIDUsage_Keyboard1 && nUsage <= kHIDUsage_Keyboard9) AddCookie(CFArrayGetValueAtIndex(Array, i), '1' + (nUsage - kHIDUsage_Keyboard1) ); else if (nUsage >= kHIDUsage_KeyboardF1 && nUsage <= kHIDUsage_KeyboardF12) AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_F1 + (nUsage - kHIDUsage_KeyboardF1) ); else if (nUsage >= kHIDUsage_KeyboardF13 && nUsage <= kHIDUsage_KeyboardF24) AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_F13 + (nUsage - kHIDUsage_KeyboardF13) ); else if (nUsage >= kHIDUsage_Keypad1 && nUsage <= kHIDUsage_Keypad9) AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_NUMPAD1 + (nUsage - kHIDUsage_Keypad1) ); else switch (nUsage) { //0's (wx & ascii go 0-9, but HID goes 1-0) case kHIDUsage_Keyboard0: AddCookie(CFArrayGetValueAtIndex(Array, i), '0'); break; case kHIDUsage_Keypad0: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_NUMPAD0); break; //Basic case kHIDUsage_KeyboardReturnOrEnter: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_RETURN); break; case kHIDUsage_KeyboardEscape: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_ESCAPE); break; case kHIDUsage_KeyboardDeleteOrBackspace: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_BACK); break; case kHIDUsage_KeyboardTab: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_TAB); break; case kHIDUsage_KeyboardSpacebar: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_SPACE); break; case kHIDUsage_KeyboardPageUp: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_PAGEUP); break; case kHIDUsage_KeyboardEnd: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_END); break; case kHIDUsage_KeyboardPageDown: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_PAGEDOWN); break; case kHIDUsage_KeyboardRightArrow: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_RIGHT); break; case kHIDUsage_KeyboardLeftArrow: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_LEFT); break; case kHIDUsage_KeyboardDownArrow: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_DOWN); break; case kHIDUsage_KeyboardUpArrow: AddCookie(CFArrayGetValueAtIndex(Array, i), WXK_UP); break; //LEDS case kHIDUsage_KeyboardCapsLock: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_CAPITAL); break; case kHIDUsage_KeypadNumLock: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_NUMLOCK); break; case kHIDUsage_KeyboardScrollLock: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_SCROLL); break; //Menu keys, Shift, other specials case kHIDUsage_KeyboardLeftControl: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_RAW_CONTROL); break; case kHIDUsage_KeyboardLeftShift: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_SHIFT); break; case kHIDUsage_KeyboardLeftAlt: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_ALT); break; case kHIDUsage_KeyboardLeftGUI: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_CONTROL); break; case kHIDUsage_KeyboardRightControl: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_RAW_RCONTROL); break; case kHIDUsage_KeyboardRightShift: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_RSHIFT); break; case kHIDUsage_KeyboardRightAlt: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_RALT); break; case kHIDUsage_KeyboardRightGUI: AddCookie(CFArrayGetValueAtIndex(Array, i),WXK_RCONTROL); break; //Default default: //not in wx keycodes - do nothing.... break; } //end mightly long switch } //end if the current element is not an array... } //end for loop for Array }//end buildcookies
CPDF_Font* CPDF_Document::AddMacFont(CTFontRef pFont, FX_BOOL bVert, FX_BOOL bTranslateName) { CTFontRef font = (CTFontRef)pFont; CTFontDescriptorRef descriptor = CTFontCopyFontDescriptor(font); if (descriptor == NULL) { return NULL; } CFX_ByteString basefont; FX_BOOL bCJK = FALSE; int flags = 0, italicangle = 0, ascend = 0, descend = 0, capheight = 0, bbox[4]; FXSYS_memset32(bbox, 0, sizeof(int) * 4); CFArrayRef languages = (CFArrayRef)CTFontDescriptorCopyAttribute(descriptor, kCTFontLanguagesAttribute); if (languages == NULL) { CFRelease(descriptor); return NULL; } CFX_DWordArray charSets; charSets.Add(FXFONT_CHINESEBIG5_CHARSET); charSets.Add(FXFONT_GB2312_CHARSET); charSets.Add(FXFONT_HANGEUL_CHARSET); charSets.Add(FXFONT_SHIFTJIS_CHARSET); if (IsHasCharSet(languages, charSets)) { bCJK = TRUE; } CFRelease(descriptor); CFDictionaryRef traits = (CFDictionaryRef)CTFontCopyTraits(font); if (traits == NULL) { CFRelease(languages); return NULL; } CFNumberRef sybolicTrait = (CFNumberRef)CFDictionaryGetValue(traits, kCTFontSymbolicTrait); CTFontSymbolicTraits trait = 0; CFNumberGetValue(sybolicTrait, kCFNumberSInt32Type, &trait); if (trait & kCTFontItalicTrait) { flags |= PDFFONT_ITALIC; } if (trait & kCTFontMonoSpaceTrait) { flags |= PDFFONT_FIXEDPITCH; } if (trait & kCTFontModernSerifsClass) { flags |= PDFFONT_SERIF; } if (trait & kCTFontScriptsClass) { flags |= PDFFONT_SCRIPT; } CFNumberRef weightTrait = (CFNumberRef)CFDictionaryGetValue(traits, kCTFontWeightTrait); Float32 weight = 0; CFNumberGetValue(weightTrait, kCFNumberFloat32Type, &weight); italicangle = CTFontGetSlantAngle(font); ascend = CTFontGetAscent(font); descend = CTFontGetDescent(font); capheight = CTFontGetCapHeight(font); CGRect box = CTFontGetBoundingBox(font); bbox[0] = box.origin.x; bbox[1] = box.origin.y; bbox[2] = box.origin.x + box.size.width; bbox[3] = box.origin.y + box.size.height; if (bTranslateName && bCJK) { CFStringRef postName = CTFontCopyPostScriptName(font); _CFString2CFXByteString(postName, basefont); CFRelease(postName); } if (basefont.IsEmpty()) { CFStringRef fullName = CTFontCopyFullName(font); _CFString2CFXByteString(fullName, basefont); CFRelease(fullName); } basefont.Replace(" ", ""); CPDF_Dictionary* pFontDict = NULL; CPDF_Dictionary* pBaseDict = FX_NEW CPDF_Dictionary; pFontDict = pBaseDict; if (!bCJK) { charSets.RemoveAll(); charSets.Add(FXFONT_ANSI_CHARSET); charSets.Add(FXFONT_DEFAULT_CHARSET); charSets.Add(FXFONT_SYMBOL_CHARSET); if (IsHasCharSet(languages, charSets)) { charSets.RemoveAll(); charSets.Add(FXFONT_SYMBOL_CHARSET); if (IsHasCharSet(languages, charSets)) { flags |= PDFFONT_SYMBOLIC; } else { flags |= PDFFONT_NONSYMBOLIC; } pBaseDict->SetAtName(FX_BSTRC("Encoding"), "WinAnsiEncoding"); } else { flags |= PDFFONT_NONSYMBOLIC; int i; for (i = 0; i < sizeof g_FX_CharsetUnicodes / sizeof(FX_CharsetUnicodes); i ++) { charSets.RemoveAll(); charSets.Add(g_FX_CharsetUnicodes[i].m_Charset); if (IsHasCharSet(languages, charSets)) { break; } } if (i < sizeof g_FX_CharsetUnicodes / sizeof(FX_CharsetUnicodes)) { CPDF_Dictionary* pEncoding = FX_NEW CPDF_Dictionary; pEncoding->SetAtName(FX_BSTRC("BaseEncoding"), "WinAnsiEncoding"); CPDF_Array* pArray = FX_NEW CPDF_Array; pArray->AddInteger(128); const FX_WCHAR* pUnicodes = g_FX_CharsetUnicodes[i].m_pUnicodes; for (int j = 0; j < 128; j ++) { CFX_ByteString name = PDF_AdobeNameFromUnicode(pUnicodes[j]); if (name.IsEmpty()) { pArray->AddName(FX_BSTRC(".notdef")); } else { pArray->AddName(name); } } pEncoding->SetAt(FX_BSTRC("Differences"), pArray); AddIndirectObject(pEncoding); pBaseDict->SetAtReference(FX_BSTRC("Encoding"), this, pEncoding); } } if (weight > 0.0 && trait & kCTFontItalicTrait) { basefont += ",BoldItalic"; } else if (weight > 0.0) { basefont += ",Bold"; } else if (trait & kCTFontItalicTrait) { basefont += ",Italic"; } pBaseDict->SetAtName("Subtype", "TrueType"); pBaseDict->SetAtName("BaseFont", basefont); pBaseDict->SetAtNumber("FirstChar", 32); pBaseDict->SetAtNumber("LastChar", 255); int char_widths[224]; FX_GetCharWidth(font, 32, 255, char_widths); CPDF_Array* pWidths = FX_NEW CPDF_Array; for (int i = 0; i < 224; i ++) { pWidths->AddInteger(char_widths[i]); } pBaseDict->SetAt("Widths", pWidths); } else { flags |= PDFFONT_NONSYMBOLIC; CPDF_Array* pArray = NULL; pFontDict = FX_NEW CPDF_Dictionary; CFX_ByteString cmap; CFX_ByteString ordering; int supplement; FX_BOOL bFound = FALSE; CPDF_Array* pWidthArray = FX_NEW CPDF_Array; charSets.RemoveAll(); charSets.Add(FXFONT_CHINESEBIG5_CHARSET); if (IsHasCharSet(languages, charSets)) { cmap = bVert ? "ETenms-B5-V" : "ETenms-B5-H"; ordering = "CNS1"; supplement = 4; pWidthArray->AddInteger(1); _InsertWidthArray(font, 0x20, 0x7e, pWidthArray); bFound = TRUE; } charSets.RemoveAll(); charSets.Add(FXFONT_GB2312_CHARSET); if (!bFound && IsHasCharSet(languages, charSets)) { cmap = bVert ? "GBK-EUC-V" : "GBK-EUC-H"; ordering = "GB1", supplement = 2; pWidthArray->AddInteger(7716); _InsertWidthArray(font, 0x20, 0x20, pWidthArray); pWidthArray->AddInteger(814); _InsertWidthArray(font, 0x21, 0x7e, pWidthArray); bFound = TRUE; } charSets.RemoveAll(); charSets.Add(FXFONT_HANGEUL_CHARSET); if (!bFound && IsHasCharSet(languages, charSets)) { cmap = bVert ? "KSCms-UHC-V" : "KSCms-UHC-H"; ordering = "Korea1"; supplement = 2; pWidthArray->AddInteger(1); _InsertWidthArray(font, 0x20, 0x7e, pWidthArray); bFound = TRUE; } charSets.RemoveAll(); charSets.Add(FXFONT_SHIFTJIS_CHARSET); if (!bFound && IsHasCharSet(languages, charSets)) { cmap = bVert ? "90ms-RKSJ-V" : "90ms-RKSJ-H"; ordering = "Japan1"; supplement = 5; pWidthArray->AddInteger(231); _InsertWidthArray(font, 0x20, 0x7d, pWidthArray); pWidthArray->AddInteger(326); _InsertWidthArray(font, 0xa0, 0xa0, pWidthArray); pWidthArray->AddInteger(327); _InsertWidthArray(font, 0xa1, 0xdf, pWidthArray); pWidthArray->AddInteger(631); _InsertWidthArray(font, 0x7e, 0x7e, pWidthArray); } pBaseDict->SetAtName("Subtype", "Type0"); pBaseDict->SetAtName("BaseFont", basefont); pBaseDict->SetAtName("Encoding", cmap); pFontDict->SetAt("W", pWidthArray); pFontDict->SetAtName("Type", "Font"); pFontDict->SetAtName("Subtype", "CIDFontType2"); pFontDict->SetAtName("BaseFont", basefont); CPDF_Dictionary* pCIDSysInfo = FX_NEW CPDF_Dictionary; pCIDSysInfo->SetAtString("Registry", "Adobe"); pCIDSysInfo->SetAtString("Ordering", ordering); pCIDSysInfo->SetAtInteger("Supplement", supplement); pFontDict->SetAt("CIDSystemInfo", pCIDSysInfo); pArray = FX_NEW CPDF_Array; pBaseDict->SetAt("DescendantFonts", pArray); AddIndirectObject(pFontDict); pArray->AddReference(this, pFontDict); } AddIndirectObject(pBaseDict); CPDF_Dictionary* pFontDesc = FX_NEW CPDF_Dictionary; pFontDesc->SetAtName("Type", "FontDescriptor"); pFontDesc->SetAtName("FontName", basefont); pFontDesc->SetAtInteger("Flags", flags); CPDF_Array* pBBox = FX_NEW CPDF_Array; for (int i = 0; i < 4; i ++) { pBBox->AddInteger(bbox[i]); } pFontDesc->SetAt("FontBBox", pBBox); pFontDesc->SetAtInteger("ItalicAngle", italicangle); pFontDesc->SetAtInteger("Ascent", ascend); pFontDesc->SetAtInteger("Descent", descend); pFontDesc->SetAtInteger("CapHeight", capheight); CGFloat fStemV = 0; int16_t min_width = SHRT_MAX; static const UniChar stem_chars[] = {'i', 'I', '!', '1'}; const size_t count = sizeof(stem_chars) / sizeof(stem_chars[0]); CGGlyph glyphs[count]; CGRect boundingRects[count]; if (CTFontGetGlyphsForCharacters(font, stem_chars, glyphs, count)) { CTFontGetBoundingRectsForGlyphs(font, kCTFontHorizontalOrientation, glyphs, boundingRects, count); for (size_t i = 0; i < count; i++) { int16_t width = boundingRects[i].size.width; if (width > 0 && width < min_width) { min_width = width; fStemV = min_width; } } } pFontDesc->SetAtInteger("StemV", fStemV); AddIndirectObject(pFontDesc); pFontDict->SetAtReference("FontDescriptor", this, pFontDesc); CFRelease(traits); CFRelease(languages); return LoadFont(pBaseDict); }
// ---------------------------------------------------------------------------- // wxHIDDevice::Create // // nClass is the HID Page such as // kHIDPage_GenericDesktop // nType is the HID Usage such as // kHIDUsage_GD_Joystick,kHIDUsage_GD_Mouse,kHIDUsage_GD_Keyboard // nDev is the device number to use // // ---------------------------------------------------------------------------- bool wxHIDDevice::Create (int nClass, int nType, int nDev) { //Create the mach port if(IOMasterPort(bootstrap_port, &m_pPort) != kIOReturnSuccess) { wxLogSysError(wxT("Could not create mach port")); return false; } //Dictionary that will hold first //the matching dictionary for determining which kind of devices we want, //then later some registry properties from an iterator (see below) // //The call to IOServiceMatching filters down the //the services we want to hid services (and also eats the //dictionary up for us (consumes one reference)) CFMutableDictionaryRef pDictionary = IOServiceMatching(kIOHIDDeviceKey); if(pDictionary == NULL) { wxLogSysError( wxT("IOServiceMatching(kIOHIDDeviceKey) failed") ); return false; } //Here we'll filter down the services to what we want if (nType != -1) { CFNumberRef pType = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &nType); CFDictionarySetValue(pDictionary, CFSTR(kIOHIDPrimaryUsageKey), pType); CFRelease(pType); } if (nClass != -1) { CFNumberRef pClass = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &nClass); CFDictionarySetValue(pDictionary, CFSTR(kIOHIDPrimaryUsagePageKey), pClass); CFRelease(pClass); } //Now get the matching services io_iterator_t pIterator; if( IOServiceGetMatchingServices(m_pPort, pDictionary, &pIterator) != kIOReturnSuccess ) { wxLogSysError(wxT("No Matching HID Services")); return false; } //Were there any devices matched? if(pIterator == 0) return false; // No devices found //Now we iterate through them io_object_t pObject; while ( (pObject = IOIteratorNext(pIterator)) != 0) { if(--nDev != 0) { IOObjectRelease(pObject); continue; } if ( IORegistryEntryCreateCFProperties ( pObject, &pDictionary, kCFAllocatorDefault, kNilOptions ) != KERN_SUCCESS ) { wxLogDebug(wxT("IORegistryEntryCreateCFProperties failed")); } // // Now we get the attributes of each "product" in the iterator // //Get [product] name CFStringRef cfsProduct = (CFStringRef) CFDictionaryGetValue(pDictionary, CFSTR(kIOHIDProductKey)); m_szProductName = wxCFStringRef( wxCFRetain(cfsProduct) ).AsString(); //Get the Product ID Key CFNumberRef cfnProductId = (CFNumberRef) CFDictionaryGetValue(pDictionary, CFSTR(kIOHIDProductIDKey)); if (cfnProductId) { CFNumberGetValue(cfnProductId, kCFNumberIntType, &m_nProductId); } //Get the Vendor ID Key CFNumberRef cfnVendorId = (CFNumberRef) CFDictionaryGetValue(pDictionary, CFSTR(kIOHIDVendorIDKey)); if (cfnVendorId) { CFNumberGetValue(cfnVendorId, kCFNumberIntType, &m_nManufacturerId); } // // End attribute getting // //Create the interface (good grief - long function names!) SInt32 nScore; IOCFPlugInInterface** ppPlugin; if(IOCreatePlugInInterfaceForService(pObject, kIOHIDDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &ppPlugin, &nScore) != kIOReturnSuccess) { wxLogSysError(wxT("Could not create HID Interface for product")); return false; } //Now, the final thing we can check before we fall back to asserts //(because the dtor only checks if the device is ok, so if anything //fails from now on the dtor will delete the device anyway, so we can't break from this). //Get the HID interface from the plugin to the mach port if((*ppPlugin)->QueryInterface(ppPlugin, CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID), (void**) &m_ppDevice) != S_OK) { wxLogSysError(wxT("Could not get device interface from HID interface")); return false; } //release the plugin (*ppPlugin)->Release(ppPlugin); //open the HID interface... if ( (*m_ppDevice)->open(m_ppDevice, 0) != S_OK ) { wxLogDebug(wxT("HID device: open failed")); } // //Now the hard part - in order to scan things we need "cookies" // CFArrayRef cfaCookies = (CFArrayRef)CFDictionaryGetValue(pDictionary, CFSTR(kIOHIDElementKey)); BuildCookies(cfaCookies); //cleanup CFRelease(pDictionary); IOObjectRelease(pObject); //iterator cleanup IOObjectRelease(pIterator); return true; } //iterator cleanup IOObjectRelease(pIterator); return false; //no device }//end Create()
// Callback passed to the VideoToolbox decoder for returning data. // This needs to be static because the API takes a C-style pair of // function and userdata pointers. This validates parameters and // forwards the decoded image back to an object method. static void PlatformCallback(void* decompressionOutputRefCon, CFDictionaryRef frameInfo, OSStatus status, VDADecodeInfoFlags infoFlags, CVImageBufferRef image) { LOG("AppleVDADecoder[%s] status %d flags %d retainCount %ld", __func__, status, infoFlags, CFGetRetainCount(frameInfo)); // Validate our arguments. // According to Apple's TN2267 // The output callback is still called for all flushed frames, // but no image buffers will be returned. // FIXME: Distinguish between errors and empty flushed frames. if (status != noErr || !image) { NS_WARNING("AppleVDADecoder decoder returned no data"); return; } MOZ_ASSERT(CFGetTypeID(image) == CVPixelBufferGetTypeID(), "AppleVDADecoder returned an unexpected image type"); if (infoFlags & kVDADecodeInfo_FrameDropped) { NS_WARNING(" ...frame dropped..."); return; } AppleVDADecoder* decoder = static_cast<AppleVDADecoder*>(decompressionOutputRefCon); AutoCFRelease<CFNumberRef> ptsref = (CFNumberRef)CFDictionaryGetValue(frameInfo, CFSTR("FRAME_PTS")); AutoCFRelease<CFNumberRef> dtsref = (CFNumberRef)CFDictionaryGetValue(frameInfo, CFSTR("FRAME_DTS")); AutoCFRelease<CFNumberRef> durref = (CFNumberRef)CFDictionaryGetValue(frameInfo, CFSTR("FRAME_DURATION")); AutoCFRelease<CFNumberRef> boref = (CFNumberRef)CFDictionaryGetValue(frameInfo, CFSTR("FRAME_OFFSET")); AutoCFRelease<CFNumberRef> kfref = (CFNumberRef)CFDictionaryGetValue(frameInfo, CFSTR("FRAME_KEYFRAME")); int64_t dts; int64_t pts; int64_t duration; int64_t byte_offset; char is_sync_point; CFNumberGetValue(ptsref, kCFNumberSInt64Type, &pts); CFNumberGetValue(dtsref, kCFNumberSInt64Type, &dts); CFNumberGetValue(durref, kCFNumberSInt64Type, &duration); CFNumberGetValue(boref, kCFNumberSInt64Type, &byte_offset); CFNumberGetValue(kfref, kCFNumberSInt8Type, &is_sync_point); nsAutoPtr<AppleVDADecoder::AppleFrameRef> frameRef( new AppleVDADecoder::AppleFrameRef( media::TimeUnit::FromMicroseconds(dts), media::TimeUnit::FromMicroseconds(pts), media::TimeUnit::FromMicroseconds(duration), byte_offset, is_sync_point == 1)); // Forward the data back to an object method which can access // the correct MP4Reader callback. decoder->OutputFrame(image, frameRef); }
int PortBurn_GetStatus(void *handle, float *out_fraction_complete) { PBHandle *h = (PBHandle *)handle; CFDictionaryRef status; CFStringRef stateRef; CFNumberRef fracRef; CFNumberRef trackNumRef; float frac = 0.0; int trackNum = 0; *out_fraction_complete = h->frac; if (!h) return pbErrNoHandle; if (!h->burn) return pbErrNotCurrentlyBurning; status = DRBurnCopyStatus(h->burn); if (!status) return pbErrCannotGetBurnStatus; trackNumRef = (CFNumberRef) CFDictionaryGetValue(status, kDRStatusCurrentTrackKey); if (trackNumRef != NULL) { CFNumberGetValue(trackNumRef, kCFNumberIntType, &trackNum); } fracRef = (CFNumberRef) CFDictionaryGetValue(status, kDRStatusPercentCompleteKey); if (fracRef != NULL) { CFNumberGetValue(fracRef, kCFNumberFloatType, &frac); } stateRef = (CFStringRef) CFDictionaryGetValue(status, kDRStatusStateKey); if (stateRef == NULL) { /* Stick with the last percentage */ return pbSuccess; } if (CFEqual(stateRef, kDRStatusStateNone)) { /* Stick with the last percentage */ return pbSuccess; } if (CFEqual(stateRef, kDRStatusStatePreparing)) { /* This takes about 1 second */ h->frac = 0.01; } if (CFEqual(stateRef, kDRStatusStateSessionOpen)) { /* This takes about 3 seconds */ h->frac = 0.02; } if (CFEqual(stateRef, kDRStatusStateTrackOpen) || CFEqual(stateRef, kDRStatusStateTrackWrite) || CFEqual(stateRef, kDRStatusStateTrackClose) || CFEqual(stateRef, kDRStatusStateSessionClose)) { /* The fraction ("percentage") complete will be valid during the majority of this range */ float newFrac = 0.0; if (frac > 0.0 && frac <= 1.0) newFrac = frac; /* Scale it to the range 0.05 - 0.99 */ newFrac = 0.05 + 0.94 * newFrac; /* Only use that value if it's larger than the previous value */ if (newFrac > h->frac) h->frac = newFrac; } if (CFEqual(stateRef, kDRStatusStateDone)) { /* Returning a fraction complete of 1.0 means we're done! */ h->frac = 1.0; } if (CFEqual(stateRef, kDRStatusStateFailed)) { CFRelease(status); return pbErrBurnFailed; } *out_fraction_complete = h->frac; CFRelease(status); return pbSuccess; }
bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, MissingGlyphSearcher *callback) { bool result = false; #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5) if (MacOSVersionIsAtLeast(10, 5, 0)) { /* Determine fallback font using CoreText. This uses the language isocode * to find a suitable font. CoreText is available from 10.5 onwards. */ char lang[16]; if (strcmp(language_isocode, "zh_TW") == 0) { /* Traditional Chinese */ strecpy(lang, "zh-Hant", lastof(lang)); } else if (strcmp(language_isocode, "zh_CN") == 0) { /* Simplified Chinese */ strecpy(lang, "zh-Hans", lastof(lang)); } else { /* Just copy the first part of the isocode. */ strecpy(lang, language_isocode, lastof(lang)); char *sep = strchr(lang, '_'); if (sep != NULL) *sep = '\0'; } /* Create a font descriptor matching the wanted language and latin (english) glyphs. */ CFStringRef lang_codes[2]; lang_codes[0] = CFStringCreateWithCString(kCFAllocatorDefault, lang, kCFStringEncodingUTF8); lang_codes[1] = CFSTR("en"); CFArrayRef lang_arr = CFArrayCreate(kCFAllocatorDefault, (const void **)lang_codes, lengthof(lang_codes), &kCFTypeArrayCallBacks); CFDictionaryRef lang_attribs = CFDictionaryCreate(kCFAllocatorDefault, (const void**)&kCTFontLanguagesAttribute, (const void **)&lang_arr, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CTFontDescriptorRef lang_desc = CTFontDescriptorCreateWithAttributes(lang_attribs); CFRelease(lang_arr); CFRelease(lang_attribs); CFRelease(lang_codes[0]); /* Get array of all font descriptors for the wanted language. */ CFSetRef mandatory_attribs = CFSetCreate(kCFAllocatorDefault, (const void **)&kCTFontLanguagesAttribute, 1, &kCFTypeSetCallBacks); CFArrayRef descs = CTFontDescriptorCreateMatchingFontDescriptors(lang_desc, mandatory_attribs); CFRelease(mandatory_attribs); CFRelease(lang_desc); for (CFIndex i = 0; descs != NULL && i < CFArrayGetCount(descs); i++) { CTFontDescriptorRef font = (CTFontDescriptorRef)CFArrayGetValueAtIndex(descs, i); /* Get font traits. */ CFDictionaryRef traits = (CFDictionaryRef)CTFontDescriptorCopyAttribute(font, kCTFontTraitsAttribute); CTFontSymbolicTraits symbolic_traits; CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(traits, kCTFontSymbolicTrait), kCFNumberIntType, &symbolic_traits); CFRelease(traits); /* Skip symbol fonts and vertical fonts. */ if ((symbolic_traits & kCTFontClassMaskTrait) == (CTFontStylisticClass)kCTFontSymbolicClass || (symbolic_traits & kCTFontVerticalTrait)) continue; /* Skip bold fonts (especially Arial Bold, which looks worse than regular Arial). */ if (symbolic_traits & kCTFontBoldTrait) continue; /* Select monospaced fonts if asked for. */ if (((symbolic_traits & kCTFontMonoSpaceTrait) == kCTFontMonoSpaceTrait) != callback->Monospace()) continue; /* Get font name. */ char name[128]; CFStringRef font_name = (CFStringRef)CTFontDescriptorCopyAttribute(font, kCTFontDisplayNameAttribute); CFStringGetCString(font_name, name, lengthof(name), kCFStringEncodingUTF8); CFRelease(font_name); /* There are some special fonts starting with an '.' and the last * resort font that aren't usable. Skip them. */ if (name[0] == '.' || strncmp(name, "LastResort", 10) == 0) continue; /* Save result. */ callback->SetFontNames(settings, name); if (!callback->FindMissingGlyphs(NULL)) { DEBUG(freetype, 2, "CT-Font for %s: %s", language_isocode, name); result = true; break; } } if (descs != NULL) CFRelease(descs); } else #endif { /* Create a font iterator and iterate over all fonts that * are available to the application. */ ATSFontIterator itr; ATSFontRef font; ATSFontIteratorCreate(kATSFontContextLocal, NULL, NULL, kATSOptionFlagsDefaultScope, &itr); while (!result && ATSFontIteratorNext(itr, &font) == noErr) { /* Get font name. */ char name[128]; CFStringRef font_name; ATSFontGetName(font, kATSOptionFlagsDefault, &font_name); CFStringGetCString(font_name, name, lengthof(name), kCFStringEncodingUTF8); bool monospace = IsMonospaceFont(font_name); CFRelease(font_name); /* Select monospaced fonts if asked for. */ if (monospace != callback->Monospace()) continue; /* We only want the base font and not bold or italic variants. */ if (strstr(name, "Italic") != NULL || strstr(name, "Bold")) continue; /* Skip some inappropriate or ugly looking fonts that have better alternatives. */ if (name[0] == '.' || strncmp(name, "Apple Symbols", 13) == 0 || strncmp(name, "LastResort", 10) == 0) continue; /* Save result. */ callback->SetFontNames(settings, name); if (!callback->FindMissingGlyphs(NULL)) { DEBUG(freetype, 2, "ATS-Font for %s: %s", language_isocode, name); result = true; break; } } ATSFontIteratorRelease(&itr); } if (!result) { /* For some OS versions, the font 'Arial Unicode MS' does not report all languages it * supports. If we didn't find any other font, just try it, maybe we get lucky. */ callback->SetFontNames(settings, "Arial Unicode MS"); result = !callback->FindMissingGlyphs(NULL); } callback->FindMissingGlyphs(NULL); return result; }
bool CBaseTexture::LoadFromFile(const CStdString& texturePath, unsigned int maxWidth, unsigned int maxHeight, bool autoRotate, unsigned int *originalWidth, unsigned int *originalHeight) { if (URIUtils::GetExtension(texturePath).Equals(".dds")) { // special case for DDS images CDDSImage image; if (image.ReadFile(texturePath)) { Update(image.GetWidth(), image.GetHeight(), 0, image.GetFormat(), image.GetData(), false); return true; } return false; } #if defined(__APPLE__) && defined(__arm__) XFILE::CFile file; UInt8 *imageBuff = NULL; int64_t imageBuffSize = 0; //open path and read data to buffer //this handles advancedsettings.xml pathsubstitution //and resulting networking if (file.Open(texturePath, 0)) { imageBuffSize =file.GetLength(); imageBuff = new UInt8[imageBuffSize]; imageBuffSize = file.Read(imageBuff, imageBuffSize); file.Close(); } else { CLog::Log(LOGERROR, "Texture manager unable to open file %s", texturePath.c_str()); return false; } if (imageBuffSize <= 0) { CLog::Log(LOGERROR, "Texture manager read texture file failed."); delete [] imageBuff; return false; } // create the image from buffer; CGImageSourceRef imageSource; // create a CFDataRef using CFDataCreateWithBytesNoCopy and kCFAllocatorNull for deallocator. // this allows us to do a nocopy reference and we handle the free of imageBuff CFDataRef cfdata = CFDataCreateWithBytesNoCopy(NULL, imageBuff, imageBuffSize, kCFAllocatorNull); imageSource = CGImageSourceCreateWithData(cfdata, NULL); if (imageSource == nil) { CLog::Log(LOGERROR, "Texture manager unable to load file: %s", CSpecialProtocol::TranslatePath(texturePath).c_str()); CFRelease(cfdata); delete [] imageBuff; return false; } CGImageRef image = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL); int rotate = 0; if (autoRotate) { // get the orientation of the image for displaying it correctly CFDictionaryRef imagePropertiesDictionary = CGImageSourceCopyPropertiesAtIndex(imageSource,0, NULL); if (imagePropertiesDictionary != nil) { CFNumberRef orientation = (CFNumberRef)CFDictionaryGetValue(imagePropertiesDictionary, kCGImagePropertyOrientation); if (orientation != nil) { int value = 0; CFNumberGetValue(orientation, kCFNumberIntType, &value); if (value) rotate = value - 1; } CFRelease(imagePropertiesDictionary); } } CFRelease(imageSource); unsigned int width = CGImageGetWidth(image); unsigned int height = CGImageGetHeight(image); m_hasAlpha = (CGImageGetAlphaInfo(image) != kCGImageAlphaNone); if (originalWidth) *originalWidth = width; if (originalHeight) *originalHeight = height; // check texture size limits and limit to screen size - preserving aspectratio of image if ( width > g_Windowing.GetMaxTextureSize() || height > g_Windowing.GetMaxTextureSize() ) { float aspect; if ( width > height ) { aspect = (float)width / (float)height; width = g_Windowing.GetWidth(); height = (float)width / (float)aspect; } else { aspect = (float)height / (float)width; height = g_Windowing.GetHeight(); width = (float)height / (float)aspect; } CLog::Log(LOGDEBUG, "Texture manager texture clamp:new texture size: %i x %i", width, height); } Allocate(width, height, XB_FMT_A8R8G8B8); m_orientation = rotate; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(m_pixels, width, height, 8, GetPitch(), colorSpace, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host); CGColorSpaceRelease(colorSpace); // Flip so that it isn't upside-down //CGContextTranslateCTM(context, 0, height); //CGContextScaleCTM(context, 1.0f, -1.0f); #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5 CGContextClearRect(context, CGRectMake(0, 0, width, height)); #else #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5 // (just a way of checking whether we're running in 10.5 or later) if (CGContextDrawLinearGradient == 0) CGContextClearRect(context, CGRectMake(0, 0, width, height)); else #endif CGContextSetBlendMode(context, kCGBlendModeCopy); #endif //CGContextSetBlendMode(context, kCGBlendModeCopy); CGContextDrawImage(context, CGRectMake(0, 0, width, height), image); CGContextRelease(context); CGImageRelease(image); CFRelease(cfdata); delete [] imageBuff; #else DllImageLib dll; if (!dll.Load()) return false; ImageInfo image; memset(&image, 0, sizeof(image)); unsigned int width = maxWidth ? std::min(maxWidth, g_Windowing.GetMaxTextureSize()) : g_Windowing.GetMaxTextureSize(); unsigned int height = maxHeight ? std::min(maxHeight, g_Windowing.GetMaxTextureSize()) : g_Windowing.GetMaxTextureSize(); if(!dll.LoadImage(texturePath.c_str(), width, height, &image)) { CLog::Log(LOGERROR, "Texture manager unable to load file: %s", texturePath.c_str()); return false; } m_hasAlpha = NULL != image.alpha; Allocate(image.width, image.height, XB_FMT_A8R8G8B8); if (autoRotate && image.exifInfo.Orientation) m_orientation = image.exifInfo.Orientation - 1; if (originalWidth) *originalWidth = image.originalwidth; if (originalHeight) *originalHeight = image.originalheight; unsigned int dstPitch = GetPitch(); unsigned int srcPitch = ((image.width + 1)* 3 / 4) * 4; // bitmap row length is aligned to 4 bytes unsigned char *dst = m_pixels; unsigned char *src = image.texture + (m_imageHeight - 1) * srcPitch; for (unsigned int y = 0; y < m_imageHeight; y++) { unsigned char *dst2 = dst; unsigned char *src2 = src; for (unsigned int x = 0; x < m_imageWidth; x++, dst2 += 4, src2 += 3) { dst2[0] = src2[0]; dst2[1] = src2[1]; dst2[2] = src2[2]; dst2[3] = 0xff; } src -= srcPitch; dst += dstPitch; } if(image.alpha) { dst = m_pixels + 3; src = image.alpha + (m_imageHeight - 1) * m_imageWidth; for (unsigned int y = 0; y < m_imageHeight; y++) { unsigned char *dst2 = dst; unsigned char *src2 = src; for (unsigned int x = 0; x < m_imageWidth; x++, dst2+=4, src2++) *dst2 = *src2; src -= m_imageWidth; dst += dstPitch; } } dll.ReleaseImage(&image); #endif ClampToEdge(); return true; }
/* * Return a Python dict of tuples for disk I/O information */ static PyObject* get_disk_io_counters(PyObject* self, PyObject* args) { PyObject* py_retdict = PyDict_New(); PyObject* py_disk_info; CFDictionaryRef parent_dict; CFDictionaryRef props_dict; CFDictionaryRef stats_dict; io_registry_entry_t parent; io_registry_entry_t disk; io_iterator_t disk_list; /* Get list of disks */ if (IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching(kIOMediaClass), &disk_list) != kIOReturnSuccess) { Py_DECREF(py_retdict); PyErr_SetString(PyExc_RuntimeError, "Unable to get the list of disks."); return NULL; } /* Iterate over disks */ while ((disk = IOIteratorNext(disk_list)) != 0) { parent_dict = NULL; props_dict = NULL; stats_dict = NULL; if (IORegistryEntryGetParentEntry(disk, kIOServicePlane, &parent) != kIOReturnSuccess) { PyErr_SetString(PyExc_RuntimeError, "Unable to get the disk's parent."); Py_DECREF(py_retdict); IOObjectRelease(disk); return NULL; } if (IOObjectConformsTo(parent, "IOBlockStorageDriver")) { if(IORegistryEntryCreateCFProperties( disk, (CFMutableDictionaryRef *) &parent_dict, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) { PyErr_SetString(PyExc_RuntimeError, "Unable to get the parent's properties."); Py_DECREF(py_retdict); IOObjectRelease(disk); IOObjectRelease(parent); return NULL; } if (IORegistryEntryCreateCFProperties(parent, (CFMutableDictionaryRef *) &props_dict, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) { PyErr_SetString(PyExc_RuntimeError, "Unable to get the disk properties."); Py_DECREF(py_retdict); IOObjectRelease(disk); return NULL; } const int kMaxDiskNameSize = 64; CFStringRef disk_name_ref = (CFStringRef)CFDictionaryGetValue( parent_dict, CFSTR(kIOBSDNameKey)); char disk_name[kMaxDiskNameSize]; CFStringGetCString(disk_name_ref, disk_name, kMaxDiskNameSize, CFStringGetSystemEncoding()); stats_dict = (CFDictionaryRef)CFDictionaryGetValue( props_dict, CFSTR(kIOBlockStorageDriverStatisticsKey)); if (stats_dict == NULL) { PyErr_SetString(PyExc_RuntimeError, "Unable to get disk stats."); Py_DECREF(py_retdict); CFRelease(props_dict); IOObjectRelease(disk); IOObjectRelease(parent); return NULL; } CFNumberRef number; int64_t reads, writes, read_bytes, write_bytes, read_time, write_time = 0; /* Get disk reads/writes */ if ((number = (CFNumberRef)CFDictionaryGetValue( stats_dict, CFSTR(kIOBlockStorageDriverStatisticsReadsKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &reads); } if ((number = (CFNumberRef)CFDictionaryGetValue( stats_dict, CFSTR(kIOBlockStorageDriverStatisticsWritesKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &writes); } /* Get disk bytes read/written */ if ((number = (CFNumberRef)CFDictionaryGetValue( stats_dict, CFSTR(kIOBlockStorageDriverStatisticsBytesReadKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &read_bytes); } if ((number = (CFNumberRef)CFDictionaryGetValue( stats_dict, CFSTR(kIOBlockStorageDriverStatisticsBytesWrittenKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &write_bytes); } /* Get disk time spent reading/writing (nanoseconds) */ if ((number = (CFNumberRef)CFDictionaryGetValue( stats_dict, CFSTR(kIOBlockStorageDriverStatisticsTotalReadTimeKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &read_time); } if ((number = (CFNumberRef)CFDictionaryGetValue( stats_dict, CFSTR(kIOBlockStorageDriverStatisticsTotalWriteTimeKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &write_time); } // Read/Write time on OS X comes back in nanoseconds and in psutil // we've standardized on milliseconds so do the conversion. py_disk_info = Py_BuildValue("(KKKKKK)", reads, writes, read_bytes, write_bytes, read_time / 1000, write_time / 1000); PyDict_SetItemString(py_retdict, disk_name, py_disk_info); Py_XDECREF(py_disk_info); CFRelease(parent_dict); IOObjectRelease(parent); CFRelease(props_dict); IOObjectRelease(disk); } } IOObjectRelease (disk_list); return py_retdict; }
void find_led_cookies(IOHIDDeviceInterface122** handle) { IOHIDElementCookie cookie; CFTypeRef object; long number; long usage; long usagePage; CFArrayRef elements; CFDictionaryRef element; IOReturn result; if (!handle || !(*handle)) { return; } result = (*handle)->copyMatchingElements(handle, NULL, &elements); if (result != kIOReturnSuccess) { fprintf(stderr, "Failed to copy cookies.\n"); exit(1); } CFIndex i; for (i = 0; i < CFArrayGetCount(elements); i++) { element = CFArrayGetValueAtIndex(elements, i); object = (CFDictionaryGetValue(element, CFSTR(kIOHIDElementCookieKey))); if (object == 0 || CFGetTypeID(object) != CFNumberGetTypeID()) { continue; } if (!CFNumberGetValue((CFNumberRef) object, kCFNumberLongType, &number)) { continue; } cookie = (IOHIDElementCookie)number; object = CFDictionaryGetValue(element, CFSTR(kIOHIDElementUsageKey)); if (object == 0 || CFGetTypeID(object) != CFNumberGetTypeID()) { continue; } if (!CFNumberGetValue((CFNumberRef)object, kCFNumberLongType, &number)) { continue; } usage = number; object = CFDictionaryGetValue(element,CFSTR(kIOHIDElementUsagePageKey)); if (object == 0 || CFGetTypeID(object) != CFNumberGetTypeID()) { continue; } if (!CFNumberGetValue((CFNumberRef)object, kCFNumberLongType, &number)) { continue; } usagePage = number; if (usagePage == kHIDPage_LEDs) { switch (usage) { case kHIDUsage_LED_NumLock: numlock_cookie = cookie; break; case kHIDUsage_LED_CapsLock: capslock_cookie = cookie; break; default: break; } } } return; }