Ejemplo n.º 1
0
static void TestISP(void)
	// A routine to test the ISP support routines.
{
	OSStatus err;
	CFStringRef setID;
	CFStringRef setID2;
	CFStringRef newSetID;
	
	setID = NULL;
	setID2 = NULL;
	newSetID = NULL;
	
	err = MoreSCFindSetByUserVisibleNameAndCopyID(CFSTR(kDefaultLocationName), &setID);
	if (err == noErr) {
		if (setID == NULL) {
			fprintf(stderr, "*** Couldn't find the set '%s'\n", kDefaultLocationName);
		} else if (!gRunQuiet) {
			fprintf(stderr, "Set ID for '%s' is\n", kDefaultLocationName);
			CFShow(setID);
		}
	}
	if (err == noErr) {
		err = MoreSCFindSetByUserVisibleNameAndCopyID(CFSTR("Who would give a set such a silly name"), &setID2);
		if (setID2 != NULL) {
			fprintf(stderr, "*** Found set that shouldn't exist\n");
		}
	}
	if (err == noErr) {
		MoreSCPPPDigest ppp;
		
		BlockZero(&ppp, sizeof(ppp));
		ppp.active            = true;
		ppp.authName          = CFSTR("Quinn");
		ppp.authPassword      = CFSTR("eskimo");
		ppp.commRemoteAddress = CFSTR("123 4567");

		err = MoreSCMakeNewDialupSet(NULL, CFSTR("Frog PPP"), NULL, &ppp, NULL, NULL, &newSetID);
	}
	if (err == noErr) {
		err = MoreSCDeleteSet(newSetID);
	}
	
	CFQRelease(newSetID);
	newSetID = NULL;

	PrintTestResult(err, "dialup");

    err = noErr;
	
	if (err == noErr) {
		MoreSCPPPDigest ppp;
		
		BlockZero(&ppp, sizeof(ppp));
		ppp.active            = true;
		ppp.authName          = CFSTR("Quinn");
		ppp.authPassword      = CFSTR("eskimo");

		err = MoreSCMakeNewPPPoESet(NULL, CFSTR("Frog PPPoE"), &ppp, NULL, NULL, &newSetID);
	}
	if (err == noErr) {
		err = MoreSCDeleteSet(newSetID);
	}
	
	CFQRelease(setID);
	CFQRelease(setID2);
	CFQRelease(newSetID);

	PrintTestResult(err, "PPPoE");
}
Ejemplo n.º 2
0
CF_INTERNAL
CFStringRef CFPlatformGetCurrentDirectory(void) {
    //TODO CFPlatformGetCurrentDirectory
    return CFSTR("");
}
/**
 * Get the MAC address of the first logical IP-enabled network interface
 *
 * @param out the output character array
 * @return CPL_OK on success or an error code
 */
cpl_return_t
cpl_platform_get_mac_address(cpl_mac_address_t* out)
{

#ifdef __unix__

	// From: http://stackoverflow.com/questions/1779715/how-to-get-mac-address-of-your-machine-using-a-c-program

	ifreq ifr;
	ifconf ifc;
	char buf[1024];
	int success = 0;

	int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	if (sock == -1) return CPL_E_PLATFORM_ERROR;

	ifc.ifc_len = sizeof(buf);
	ifc.ifc_buf = buf;
	if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) return CPL_E_PLATFORM_ERROR;

	ifreq* it = ifc.ifc_req;
	const ifreq* const end = it + (ifc.ifc_len / sizeof(ifreq));

	for (; it != end; ++it) {
		strcpy(ifr.ifr_name, it->ifr_name);
		if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
			if (! (ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
				if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
					success = 1;
					break;
				}
			}
		}
		else { /* ignore error */ }
	}

	if (success && out) {
		memcpy(out, ifr.ifr_hwaddr.sa_data, 6);
	}

	if (!success) return CPL_E_NOT_FOUND;

#elif defined(__APPLE__)

	/*
	 * Adapted from GetMACAddress.c:
	 *   http://opensource.apple.com/source/DirectoryService
	 *            /DirectoryService-621/CoreFramework/Private/GetMACAddress.c
	 *
	 * Copyright (c) 2003 Apple Computer, Inc. All rights reserved.
	 * 
	 * This file contains Original Code and/or Modifications of Original Code
	 * as defined in and that are subject to the Apple Public Source License
	 * Version 2.0 (the 'License'). You may not use this file except in
	 * compliance with the License. Please obtain a copy of the License at
	 * http://www.opensource.apple.com/apsl/ and read it before using this
	 * file.
	 * 
	 * The Original Code and all software distributed under the License are
	 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
	 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
	 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
	 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
	 * Please see the License for the specific language governing rights and
	 * limitations under the License.
	 */

	kern_return_t kernResult = KERN_FAILURE; 
	mach_port_t masterPort = MACH_PORT_NULL;
	CFMutableDictionaryRef classesToMatch = NULL;
	io_object_t intfService = MACH_PORT_NULL;
	io_object_t controllerService = MACH_PORT_NULL;
	io_iterator_t intfIterator = MACH_PORT_NULL;
	unsigned char macAddress[kIOEthernetAddressSize];
	io_iterator_t *matchingServices = &intfIterator;
	UInt8 *MACAddress = macAddress;

	// Create an iterator with Primary Ethernet interface
	kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
	if (kernResult != KERN_SUCCESS) return CPL_E_PLATFORM_ERROR;

	// Ethernet interfaces are instances of class kIOEthernetInterfaceClass
	classesToMatch = IOServiceMatching(kIOEthernetInterfaceClass);
	if (classesToMatch != NULL) {

		CFMutableDictionaryRef propertyMatch;
		propertyMatch = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
				&kCFTypeDictionaryKeyCallBacks,
				&kCFTypeDictionaryValueCallBacks);

		CFDictionarySetValue(propertyMatch,
				CFSTR(kIOPrimaryInterface), kCFBooleanTrue);
		CFDictionarySetValue(classesToMatch,
				CFSTR(kIOPropertyMatchKey), propertyMatch);

		CFRelease(propertyMatch);

		kernResult = IOServiceGetMatchingServices(masterPort,
				classesToMatch, matchingServices);    
	}


	// Given an iterator across a set of Ethernet interfaces, return the
	// MAC address of the first one.

	intfService = IOIteratorNext(intfIterator);
	if (intfService == MACH_PORT_NULL) {
			IOObjectRelease(intfIterator);
			return CPL_E_PLATFORM_ERROR;
	}

	CFDataRef MACAddressAsCFData = NULL;        
	kernResult = IORegistryEntryGetParentEntry(intfService,
			kIOServicePlane,
			&controllerService);

	if (kernResult != KERN_SUCCESS || controllerService == MACH_PORT_NULL) {
		IOObjectRelease(intfService);
		IOObjectRelease(intfIterator);
		return CPL_E_PLATFORM_ERROR;
	}

	MACAddressAsCFData = (CFDataRef) IORegistryEntryCreateCFProperty(
			controllerService,
			CFSTR(kIOMACAddress),
			kCFAllocatorDefault,
			0);

	if (MACAddressAsCFData != NULL) {
		CFDataGetBytes(MACAddressAsCFData,
				CFRangeMake(0, kIOEthernetAddressSize), MACAddress);
		CFRelease(MACAddressAsCFData);
	}
	else {
		IOObjectRelease(controllerService);
		IOObjectRelease(intfService);
		IOObjectRelease(intfIterator);
		return CPL_E_NOT_FOUND;
	}

	IOObjectRelease(controllerService);
	IOObjectRelease(intfService);
	IOObjectRelease(intfIterator);

	if (out) memcpy(out, macAddress, 6);
	

#elif defined(_WINDOWS)

	PIP_ADAPTER_ADDRESSES AdapterAddresses;
	ULONG family = AF_UNSPEC;
	ULONG flags = 0;
	ULONG outBufLen = 0;
	bool success = false;

	DWORD dwRetVal = GetAdaptersAddresses(family, flags, NULL, NULL, &outBufLen);
	if (dwRetVal == ERROR_NO_DATA) return CPL_E_NOT_FOUND;
	if (dwRetVal == 0 && outBufLen == 0) return CPL_E_NOT_FOUND;
	if (dwRetVal != ERROR_BUFFER_OVERFLOW) return CPL_E_PLATFORM_ERROR;

	AdapterAddresses = (IP_ADAPTER_ADDRESSES*)
		malloc(sizeof(IP_ADAPTER_ADDRESSES) * outBufLen);
	if (AdapterAddresses == NULL) return CPL_E_INSUFFICIENT_RESOURCES;

	dwRetVal = GetAdaptersAddresses(family, flags, NULL, AdapterAddresses,
		&outBufLen);
	if (dwRetVal != 0) { free(AdapterAddresses); return CPL_E_PLATFORM_ERROR; }

	for (PIP_ADAPTER_ADDRESSES p = AdapterAddresses; p != NULL; p = p->Next) {
		if (p->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue;
		if (p->PhysicalAddressLength != 6 /* Ethernet */) continue;

		success = true;
		if (out) memcpy(out, p->PhysicalAddress, 6);
		break;
	}

	free(AdapterAddresses);

	if (!success) return CPL_E_NOT_FOUND;

#else
#error "Not implemented for this platform"
#endif

	return CPL_OK;
}
Ejemplo n.º 4
0
ITunesController::~ITunesController()
{
	CFNotificationCenterRef center = CFNotificationCenterGetDistributedCenter();
	CFNotificationCenterRemoveObserver(center, this, CFSTR("com.apple.iTunes.playerInfo"), NULL);
}
Ejemplo n.º 5
0
#include <AudioToolbox/AudioFormat.h>
#include <CoreFoundation/CoreFoundation.h>

#include "HTTPInputSource.h"
#include "AudioDecoder.h"
#include "Logger.h"
#include "CFWrapper.h"
#include "CFErrorUtilities.h"
#include "CreateStringForOSType.h"
#include "LoopableRegionDecoder.h"

// ========================================
// Error Codes
// ========================================
const CFStringRef SFB::Audio::Decoder::ErrorDomain = CFSTR("org.sbooth.AudioEngine.ErrorDomain.AudioDecoder");

#pragma mark Static Methods

std::atomic_bool SFB::Audio::Decoder::sAutomaticallyOpenDecoders = ATOMIC_VAR_INIT(false);
std::vector<SFB::Audio::Decoder::SubclassInfo> SFB::Audio::Decoder::sRegisteredSubclasses;

CFArrayRef SFB::Audio::Decoder::CreateSupportedFileExtensions()
{
	CFMutableArrayRef supportedFileExtensions = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);

	for(auto subclassInfo : sRegisteredSubclasses) {
		SFB::CFArray decoderFileExtensions = subclassInfo.mCreateSupportedFileExtensions();
		CFArrayAppendArray(supportedFileExtensions, decoderFileExtensions, CFRangeMake(0, CFArrayGetCount(decoderFileExtensions)));
	}
Ejemplo n.º 6
0
// domain should already be locked.
static Boolean _writeXMLFile(CFURLRef url, CFMutableDictionaryRef dict, Boolean isWorldReadable, Boolean *tryAgain) {
    Boolean success = false;
    CFAllocatorRef alloc = __CFPreferencesAllocator();
    *tryAgain = false;
    if (CFDictionaryGetCount(dict) == 0) {
        // Destroy the file
        CFBooleanRef val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, url, kCFURLFileExists, NULL);
        if (val && CFBooleanGetValue(val)) {
            success = CFURLDestroyResource(url, NULL);
        } else {
            success = true;
        }
        if (val) CFRelease(val);
    } else {
        CFPropertyListFormat desiredFormat = __CFPreferencesShouldWriteXML() ? kCFPropertyListXMLFormat_v1_0 : kCFPropertyListBinaryFormat_v1_0;
        CFDataRef data = CFPropertyListCreateData(alloc, dict, desiredFormat, 0, NULL);
        if (data) {
            SInt32 mode;
#if DEPLOYMENT_TARGET_MACOSX
            mode = isWorldReadable ? S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH : S_IRUSR|S_IWUSR;
#else
	    mode = 0666;
#endif
#if DEPLOYMENT_TARGET_MACOSX
            {	// Try quick atomic way first, then fallback to slower ways and error cases
                CFStringRef scheme = CFURLCopyScheme(url);
                if (!scheme) {
                    *tryAgain = false;
                    CFRelease(data);
                    return false;
                } else if (CFStringCompare(scheme, CFSTR("file"), 0) == kCFCompareEqualTo) {
                    SInt32 length = CFDataGetLength(data);
                    const void *bytes = (0 == length) ? (const void *)"" : CFDataGetBytePtr(data);
                    Boolean atomicWriteSuccess = __CFWriteBytesToFileWithAtomicity(url, bytes, length, mode, true);
                    if (atomicWriteSuccess) {
                        CFRelease(scheme);
                        *tryAgain = false;
                        CFRelease(data);
                        return true;
                    }
                    if (!atomicWriteSuccess && thread_errno() == ENOSPC) {
                        CFRelease(scheme);
                        *tryAgain = false;
                        CFRelease(data);
                        return false;
                    }
                }
                CFRelease(scheme);
            }
#endif
            success = CFURLWriteDataAndPropertiesToResource(url, data, URLPropertyDictForPOSIXMode(mode), NULL);
            URLPropertyDictRelease();
            if (success) {
                CFDataRef readData;
                if (!CFURLCreateDataAndPropertiesFromResource(alloc, url, &readData, NULL, NULL, NULL) || !CFEqual(readData, data)) {
                    success = false;
                    *tryAgain = true;
                }
                if (readData) CFRelease(readData);
            } else {
                CFBooleanRef val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, url, kCFURLFileExists, NULL);
                if (!val || !CFBooleanGetValue(val)) {
                    CFURLRef tmpURL = CFURLCreateWithFileSystemPathRelativeToBase(alloc, CFSTR("."), kCFURLPOSIXPathStyle, true, url); // Just "." because url is not a directory URL
                    CFURLRef parentURL = tmpURL ? CFURLCopyAbsoluteURL(tmpURL) : NULL;
                    if (tmpURL) CFRelease(tmpURL);
                    if (val) CFRelease(val);
                    val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, parentURL, kCFURLFileExists, NULL);
                    if ((!val || !CFBooleanGetValue(val)) && _createDirectory(parentURL, isWorldReadable)) {
                        // parent directory didn't exist; now it does; try again to write
                        success = CFURLWriteDataAndPropertiesToResource(url, data, URLPropertyDictForPOSIXMode(mode), NULL);
                        URLPropertyDictRelease();
                        if (success) {
                            CFDataRef rdData;
                            if (!CFURLCreateDataAndPropertiesFromResource(alloc, url, &rdData, NULL, NULL, NULL) || !CFEqual(rdData, data)) {
                                success = false;
                                *tryAgain = true;
                            }
                            if (rdData) CFRelease(rdData);
                        }
                        
                    }
                    if (parentURL) CFRelease(parentURL);
                }
                if (val) CFRelease(val);
            }
            CFRelease(data);
        } else {
            // ???  This should never happen
            CFLog(__kCFLogAssertion, CFSTR("Could not generate XML data for property list"));
            success = false;
        }
    }
    return success;
}
Ejemplo n.º 7
0
static CFStringRef usage() {
       return CFRetain(CFSTR("[-stdin] <project> <dstroot>"));
}
Ejemplo n.º 8
0
GamepadManager::GamepadManager()
    :  bStateChanged(false)
{

    HidManager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
    IOHIDManagerOpen(HidManager, kIOHIDOptionsTypeNone);
    IOHIDManagerScheduleWithRunLoop(HidManager,
                                    CFRunLoopGetCurrent(),
                                    kCFRunLoopDefaultMode);


    // Setup device matching.
    CFStringRef keys[] = {  CFSTR(kIOHIDDeviceUsagePageKey),
                            CFSTR(kIOHIDDeviceUsageKey)
                         };

    int value;
    CFNumberRef values[2];
    CFDictionaryRef dictionaries[2];

    // Match joysticks.
    value = kHIDPage_GenericDesktop;
    values[0] = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &value);

    value = kHIDUsage_GD_Joystick;
    values[1] = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &value);

    dictionaries[0] = CFDictionaryCreate(kCFAllocatorDefault,
                                         (const void **) keys,
                                         (const void **) values,
                                         2,
                                         &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFRelease(values[0]);
    CFRelease(values[1]);

    // Match gamepads.
    value = kHIDPage_GenericDesktop;
    values[0] = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &value);

    value = kHIDUsage_GD_GamePad;
    values[1] = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &value);

    dictionaries[1] = CFDictionaryCreate(kCFAllocatorDefault,
                                         (const void **) keys,
                                         (const void **) values,
                                         2,
                                         &kCFTypeDictionaryKeyCallBacks,
                                         &kCFTypeDictionaryValueCallBacks);
    CFRelease(values[0]);
    CFRelease(values[1]);

    CFArrayRef array = CFArrayCreate(   kCFAllocatorDefault,
                                        (const void **) dictionaries,
                                        2,
                                        &kCFTypeArrayCallBacks);
    CFRelease(dictionaries[0]);
    CFRelease(dictionaries[1]);

    IOHIDManagerSetDeviceMatchingMultiple(HidManager, array);

    CFRelease(array);


    IOHIDManagerRegisterDeviceMatchingCallback(HidManager, staticOnDeviceMatched, this);
    IOHIDManagerRegisterDeviceRemovalCallback(HidManager, staticOnDeviceRemoved, this);

}
Ejemplo n.º 9
0
      AECreateDesc(typeAlias, (Ptr) (*file_alias),
                   GetHandleSize((Handle) file_alias), &file_list_element);
      HUnlock((Handle) file_alias);

      AEPutDesc(&file_list, 0, &file_list_element);
    }

  }

  UInt32 user_selection_type;
  MenuID menu_id;
  MenuItemIndex menu_item_index;

  IBNibRef nib_ref;
  err = CreateNibReference(CFSTR("ContextMenu"), &nib_ref);
  MenuRef carbon_context_menu;
  err = CreateMenuFromNib(nib_ref, CFSTR("ItemContextMenu"), &carbon_context_menu);
  // change double separators to just one separator:
  err = ChangeMenuAttributes(carbon_context_menu, kMenuAttrCondenseSeparators, NULL);

  DisposeNibReference(nib_ref);

  int num_submenu_items = 0;
  int menu_size = 0;
  for_each(BumpTopCommand* option, ordered_context_menu_items) {
    err = InsertMenuItemTextWithCFString(carbon_context_menu,
                                         CFStringFromQString(option->name()),
                                         menu_size,   // MenuItemIndex inAfterItem
                                         option->isSeparator() ? kMenuItemAttrSeparator : 0,  // MenuItemAttributes inAttributes
                                         0);  // MenuCommand inCommandID
Ejemplo n.º 10
0
void wxDrop_GetArgs(int *argc, char ***argv, int *in_terminal)
{
  *in_terminal = 1;

  MZ_REGISTER_STATIC(scheme_mac_argv);

  Install();
  while (!scheme_mac_ready) {
    EventRecord event;
    
    WaitNextEvent(highLevelEventMask, &event, 0x7FFFFFFF, 0L);
    if (event.what == kHighLevelEvent) {
      AEProcessAppleEvent(&event);
    }
  }

#ifdef OS_X
  {
    int from_finder;

    from_finder = (((*argc) > 1) && (strncmp((*argv)[1],"-psn_",5) == 0));
    if (from_finder) {
      /* Finder started app, or someone wants us to think so; set
	 *in_terminal to 0 and combine AE-based command-line with given
	 command line */
      int i, new_argc;
      char **new_argv;
      *in_terminal = 0;
      new_argc = (scheme_mac_argc - 1) + ((*argc) - 2) + 1;
      new_argv = (char **)malloc(new_argc * sizeof(char *));
      new_argv[0] = (*argv)[0];
      for (i = 2; i < (*argc); i++) {
	new_argv[i - 1] = (*argv)[i];
      }
      for (; i < new_argc + 1; i++) {
	new_argv[i - 1] = scheme_mac_argv[i - (*argc) + 1];
      }
      scheme_mac_argc = new_argc;
      scheme_mac_argv = new_argv;
    } else {
      /* command-line start; no AE arguments */
      scheme_mac_argc = *argc;
      scheme_mac_argv = *argv;
    }

    GetStarterInfo();

    /* Open the PLT_MrEd framework resources: */
    {
      CFBundleRef fwBundle;

      fwBundle = CFBundleGetBundleWithIdentifier(CFSTR("org.plt-scheme.PLT_MrEd"));
      if (fwBundle) {
	SInt16 refNum;
	SInt16 lRefNum;
	CFBundleOpenBundleResourceFiles(fwBundle, &refNum, &lRefNum);
      }
    }

  }
#endif  

  *argc = scheme_mac_argc;
  *argv = scheme_mac_argv;
}
Ejemplo n.º 11
0
void GamepadManager::onDeviceValueChanged(IOHIDValueRef value)
{

    IOHIDElementRef element = IOHIDValueGetElement(value);
    IOHIDDeviceRef device = IOHIDElementGetDevice(element);

    int vendorID = getIntDeviceProperty(device, CFSTR(kIOHIDVendorIDKey));
    int productID = getIntDeviceProperty(device, CFSTR(kIOHIDProductIDKey));
    OVR_UNUSED(productID);

    uint32_t usagePage = IOHIDElementGetUsagePage(element);
    uint32_t usage = IOHIDElementGetUsage(element);

    // The following controller mapping is based on the Logitech F710, however we use it for
    // all Logitech devices on the assumption that they're likely to share the same mapping.
    if (vendorID == Logitech_F710_VendorID)
    {
        // Logitech F710 mapping.
        if (usagePage == kHIDPage_Button)
        {
            bool buttonState = IOHIDValueGetIntegerValue(value);

            switch(usage)
            {
            case kHIDUsage_Button_1:
                manipulateBitField(State.Buttons, Gamepad_X, buttonState);
                break;
            case kHIDUsage_Button_2:
                manipulateBitField(State.Buttons, Gamepad_A, buttonState);
                break;
            case kHIDUsage_Button_3:
                manipulateBitField(State.Buttons, Gamepad_B, buttonState);
                break;
            case kHIDUsage_Button_4:
                manipulateBitField(State.Buttons, Gamepad_Y, buttonState);
                break;
            case 0x05:
                manipulateBitField(State.Buttons, Gamepad_L1, buttonState);
                break;
            case 0x06:
                manipulateBitField(State.Buttons, Gamepad_R1, buttonState);
                break;
            case 0x07:
                State.LT = buttonState ? 1.0f:0.0f;
                break;
            case 0x08:
                State.RT = buttonState ? 1.0f:0.0f;
                break;
            case 0x09:
                manipulateBitField(State.Buttons, Gamepad_Back, buttonState);
                break;
            case 0x0A:
                manipulateBitField(State.Buttons, Gamepad_Start, buttonState);
                break;
            case 0x0B:
                manipulateBitField(State.Buttons, Gamepad_LStick, buttonState);
                break;
            case 0x0C:
                manipulateBitField(State.Buttons, Gamepad_RStick, buttonState);
                break;
            default:
                return;
            }
        }
        else if (usagePage == kHIDPage_GenericDesktop)
        {
            float v;
            switch(usage)
            {
            case kHIDUsage_GD_X:
                v = mapAnalogAxis(value, element);
                if (!setStateIfDifferent(State.LX, v))
                    return;
                break;
            case kHIDUsage_GD_Y:
                v = mapAnalogAxis(value, element);
                if (!setStateIfDifferent(State.LY, -v))
                    return;
                break;
            case kHIDUsage_GD_Z:
                v = mapAnalogAxis(value, element);
                if (!setStateIfDifferent(State.RX, v))
                    return;
                break;
            case kHIDUsage_GD_Rz:
                v = mapAnalogAxis(value, element);
                if (!setStateIfDifferent(State.RY, -v))
                    return;
                break;
            case kHIDUsage_GD_Hatswitch:
            {
                CFIndex integerValue = IOHIDValueGetIntegerValue(value);

                manipulateBitField(State.Buttons,
                                   Gamepad_Up,
                                   integerValue == 7 || integerValue == 0 || integerValue == 1);
                manipulateBitField(State.Buttons,
                                   Gamepad_Down,
                                   integerValue == 3 || integerValue == 4 || integerValue == 5);
                manipulateBitField(State.Buttons,
                                   Gamepad_Left,
                                   integerValue == 5 || integerValue == 6 || integerValue == 7);
                manipulateBitField(State.Buttons,
                                   Gamepad_Right,
                                   integerValue == 1 || integerValue == 2 || integerValue == 3);
            }
            break;
            default:
                return;
            }
        }
    }
    // The following controller mapping is based on the Sony DualShock3, however we use it for
    // all Sony devices on the assumption that they're likely to share the same mapping.
    else if (vendorID == Sony_DualShock3_VendorID)
    {
        // PS3 Controller.
        if (usagePage == kHIDPage_Button)
        {
            bool buttonState = IOHIDValueGetIntegerValue(value);

            switch(usage)
            {
            case kHIDUsage_Button_1:
                manipulateBitField(State.Buttons, Gamepad_Back, buttonState);
                break;
            case kHIDUsage_Button_2:
                manipulateBitField(State.Buttons, Gamepad_LStick, buttonState);
                break;
            case kHIDUsage_Button_3:
                manipulateBitField(State.Buttons, Gamepad_RStick, buttonState);
                break;
            case kHIDUsage_Button_4:
                manipulateBitField(State.Buttons, Gamepad_Start, buttonState);
                break;
            case 0x05:
                manipulateBitField(State.Buttons, Gamepad_Up, buttonState);
                break;
            case 0x06:
                manipulateBitField(State.Buttons, Gamepad_Right, buttonState);
                break;
            case 0x07:
                manipulateBitField(State.Buttons, Gamepad_Down, buttonState);
                break;
            case 0x08:
                manipulateBitField(State.Buttons, Gamepad_Left, buttonState);
                break;
            case 0x09:
                State.LT = buttonState ? 1.0f:0.0f;
                break;
            case 0x0A:
                State.RT = buttonState ? 1.0f:0.0f;
                break;
            case 0x0B:
                manipulateBitField(State.Buttons, Gamepad_L1, buttonState);
                break;
            case 0x0C:
                manipulateBitField(State.Buttons, Gamepad_R1, buttonState);
                break;
            case 0x0D:
                // PS3 Triangle.
                manipulateBitField(State.Buttons, Gamepad_TRIANGLE, buttonState);
                break;
            case 0x0E:
                // PS3 Circle
                manipulateBitField(State.Buttons, Gamepad_CIRCLE, buttonState);
                break;
            case 0x0F:
                // PS3 Cross
                manipulateBitField(State.Buttons, Gamepad_CROSS, buttonState);
                break;
            case 0x10:
                // PS3 Square
                manipulateBitField(State.Buttons, Gamepad_SQUARE, buttonState);
                break;
            default:
                return;
            }
        }
        else if (usagePage == kHIDPage_GenericDesktop)
        {
            float v;
            switch(usage)
            {
            case kHIDUsage_GD_X:
                v = mapAnalogAxis(value, element);
                if (!setStateIfDifferent(State.LX, v))
                    return;
                break;
            case kHIDUsage_GD_Y:
                v = mapAnalogAxis(value, element);
                if (!setStateIfDifferent(State.LY, -v))
                    return;
                break;
            case kHIDUsage_GD_Z:
                v = mapAnalogAxis(value, element);
                if (!setStateIfDifferent(State.RX, v))
                    return;
                break;
            case kHIDUsage_GD_Rz:
                v = mapAnalogAxis(value, element);
                if (!setStateIfDifferent(State.RY, -v))
                    return;
                break;
            default:
                return;
            }
        }
    }

    bStateChanged = true;
}
Ejemplo n.º 12
0
bool QextSerialEnumeratorPrivate::getServiceDetailsOSX(io_object_t service, QextPortInfo *portInfo)
{
    bool retval = true;
    CFTypeRef bsdPathAsCFString = NULL;
    CFTypeRef productNameAsCFString = NULL;
    CFTypeRef vendorIdAsCFNumber = NULL;
    CFTypeRef productIdAsCFNumber = NULL;
    // check the name of the modem's callout device
    bsdPathAsCFString = IORegistryEntryCreateCFProperty(service, CFSTR(kIOCalloutDeviceKey),
                                                        kCFAllocatorDefault, 0);

    // wander up the hierarchy until we find the level that can give us the
    // vendor/product IDs and the product name, if available
    io_registry_entry_t parent;
    kern_return_t kernResult = IORegistryEntryGetParentEntry(service, kIOServicePlane, &parent);
    while (kernResult == KERN_SUCCESS && !vendorIdAsCFNumber && !productIdAsCFNumber) {
        if (!productNameAsCFString)
            productNameAsCFString = IORegistryEntrySearchCFProperty(parent,
                                                                    kIOServicePlane,
                                                                    CFSTR("Product Name"),
                                                                    kCFAllocatorDefault, 0);
        vendorIdAsCFNumber = IORegistryEntrySearchCFProperty(parent,
                                                             kIOServicePlane,
                                                             CFSTR(kUSBVendorID),
                                                             kCFAllocatorDefault, 0);
        productIdAsCFNumber = IORegistryEntrySearchCFProperty(parent,
                                                              kIOServicePlane,
                                                              CFSTR(kUSBProductID),
                                                              kCFAllocatorDefault, 0);
        io_registry_entry_t oldparent = parent;
        kernResult = IORegistryEntryGetParentEntry(parent, kIOServicePlane, &parent);
        IOObjectRelease(oldparent);
    }

    io_string_t ioPathName;
    IORegistryEntryGetPath(service, kIOServicePlane, ioPathName);
    portInfo->physName = ioPathName;

    if (bsdPathAsCFString) {
        char path[MAXPATHLEN];
        if (CFStringGetCString((CFStringRef)bsdPathAsCFString, path,
                               PATH_MAX, kCFStringEncodingUTF8))
            portInfo->portName = path;
        CFRelease(bsdPathAsCFString);
    }

    if (productNameAsCFString) {
        char productName[MAXPATHLEN];
        if (CFStringGetCString((CFStringRef)productNameAsCFString, productName,
                               PATH_MAX, kCFStringEncodingUTF8))
            portInfo->friendName = productName;
        CFRelease(productNameAsCFString);
    }

    if (vendorIdAsCFNumber) {
        SInt32 vID;
        if (CFNumberGetValue((CFNumberRef)vendorIdAsCFNumber, kCFNumberSInt32Type, &vID))
            portInfo->vendorID = vID;
        CFRelease(vendorIdAsCFNumber);
    }

    if (productIdAsCFNumber) {
        SInt32 pID;
        if (CFNumberGetValue((CFNumberRef)productIdAsCFNumber, kCFNumberSInt32Type, &pID))
            portInfo->productID = pID;
        CFRelease(productIdAsCFNumber);
    }
    IOObjectRelease(service);
    return retval;
}
Ejemplo n.º 13
0
/*
  Create matching dictionaries for the devices we want to get notifications for,
  and add them to the current run loop.  Invoke the callbacks that will be responding
  to these notifications once to arm them, and discover any devices that
  are currently connected at the time notifications are setup.
*/
bool QextSerialEnumeratorPrivate::setUpNotifications_sys(bool /*setup*/)
{
    kern_return_t kernResult;
    mach_port_t masterPort;
    CFRunLoopSourceRef notificationRunLoopSource;
    CFMutableDictionaryRef classesToMatch;
    CFMutableDictionaryRef cdcClassesToMatch;
    io_iterator_t portIterator;

    kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
    if (KERN_SUCCESS != kernResult) {
        qDebug() << "IOMasterPort returned:" << kernResult;
        return false;
    }

    classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
    if (classesToMatch == NULL)
        qDebug("IOServiceMatching returned a NULL dictionary.");
    else
        CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));

    if (!(cdcClassesToMatch = IOServiceNameMatching("AppleUSBCDC"))) {
        QESP_WARNING("couldn't create cdc matching dict");
        return false;
    }

    // Retain an additional reference since each call to IOServiceAddMatchingNotification consumes one.
    classesToMatch = (CFMutableDictionaryRef) CFRetain(classesToMatch);
    cdcClassesToMatch = (CFMutableDictionaryRef) CFRetain(cdcClassesToMatch);

    notificationPortRef = IONotificationPortCreate(masterPort);
    if (notificationPortRef == NULL) {
        qDebug("IONotificationPortCreate return a NULL IONotificationPortRef.");
        return false;
    }

    notificationRunLoopSource = IONotificationPortGetRunLoopSource(notificationPortRef);
    if (notificationRunLoopSource == NULL) {
        qDebug("IONotificationPortGetRunLoopSource returned NULL CFRunLoopSourceRef.");
        return false;
    }

    CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationRunLoopSource, kCFRunLoopDefaultMode);

    kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOMatchedNotification, classesToMatch,
                                                  deviceDiscoveredCallbackOSX, this, &portIterator);
    if (kernResult != KERN_SUCCESS) {
        qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
        return false;
    }

    // arm the callback, and grab any devices that are already connected
    deviceDiscoveredCallbackOSX(this, portIterator);

    kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOMatchedNotification, cdcClassesToMatch,
                                                  deviceDiscoveredCallbackOSX, this, &portIterator);
    if (kernResult != KERN_SUCCESS) {
        qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
        return false;
    }

    // arm the callback, and grab any devices that are already connected
    deviceDiscoveredCallbackOSX(this, portIterator);

    kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOTerminatedNotification, classesToMatch,
                                                  deviceTerminatedCallbackOSX, this, &portIterator);
    if (kernResult != KERN_SUCCESS) {
        qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
        return false;
    }

    // arm the callback, and clear any devices that are terminated
    deviceTerminatedCallbackOSX(this, portIterator);

    kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOTerminatedNotification, cdcClassesToMatch,
                                                  deviceTerminatedCallbackOSX, this, &portIterator);
    if (kernResult != KERN_SUCCESS) {
        qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
        return false;
    }

    // arm the callback, and clear any devices that are terminated
    deviceTerminatedCallbackOSX(this, portIterator);
    return true;
}
Ejemplo n.º 14
0
void I_Error (char *error, ...)
{
    va_list	argptr;

    if (already_quitting)
    {
        fprintf(stderr, "Warning: recursive call to I_Error detected.\n");
        exit(-1);
    }
    else
    {
        already_quitting = true;
    }
    
    // Message first.
    va_start(argptr, error);
    //fprintf(stderr, "\nError: ");
    vfprintf(stderr, error, argptr);
    fprintf(stderr, "\n\n");
    va_end(argptr);
    fflush(stderr);

    // Shutdown. Here might be other errors.

    if (demorecording)
    {
	G_CheckDemoStatus();
    }

    D_QuitNetGame ();
    I_ShutdownGraphics();
    S_Shutdown();
    
#ifdef _WIN32
    // On Windows, pop up a dialog box with the error message.
    {
        char msgbuf[512];
        wchar_t wmsgbuf[512];

        va_start(argptr, error);
        memset(msgbuf, 0, sizeof(msgbuf));
        vsnprintf(msgbuf, sizeof(msgbuf) - 1, error, argptr);
        va_end(argptr);

        MultiByteToWideChar(CP_ACP, 0,
                            msgbuf, strlen(msgbuf) + 1,
                            wmsgbuf, sizeof(wmsgbuf));

        MessageBoxW(NULL, wmsgbuf, L"", MB_OK);
    }
#endif

#ifdef __MACOSX__
    {
        CFStringRef message;
        char msgbuf[512];
	int i;

        va_start(argptr, error);
        memset(msgbuf, 0, sizeof(msgbuf));
        vsnprintf(msgbuf, sizeof(msgbuf) - 1, error, argptr);
        va_end(argptr);

	// The CoreFoundation message box wraps text lines, so replace
	// newline characters with spaces so that multiline messages
	// are continuous.

	for (i = 0; msgbuf[i] != '\0'; ++i)
        {
            if (msgbuf[i] == '\n')
            {
                msgbuf[i] = ' ';
            }
        }

        message = CFStringCreateWithCString(NULL, msgbuf,
                                            kCFStringEncodingUTF8);

        CFUserNotificationDisplayNotice(0,
                                        kCFUserNotificationCautionAlertLevel,
                                        NULL,
                                        NULL,
                                        NULL,
                                        CFSTR(PACKAGE_STRING),
                                        message,
                                        NULL);
    }
#endif

    // abort();

    exit(-1);
}
Ejemplo n.º 15
0
#include <SecureObjectSync/SOSInternal.h>
#include <SecureObjectSync/SOSKVSKeys.h>
#include <SecureObjectSync/SOSAccountPriv.h>
#include <SecureObjectSync/SOSTransport.h>
#include <SecureObjectSync/SOSTransportKeyParameterKVS.h>
#include <SecureObjectSync/SOSTransportCircleKVS.h>
#include <SecureObjectSync/SOSTransportMessageKVS.h>
#include <SOSCloudKeychainClient.h>
#include <utilities/debugging.h>

CFStringRef kKeyParameter = CFSTR("KeyParameter");
CFStringRef kCircle = CFSTR("Circle");
CFStringRef kMessage = CFSTR("Message");
CFStringRef kAlwaysKeys = CFSTR("AlwaysKeys");
CFStringRef kFirstUnlocked = CFSTR("FirstUnlockKeys");
CFStringRef kUnlocked = CFSTR("UnlockedKeys");



CFStringRef SOSInterestListCopyDescription(CFArrayRef interests)
{
    CFMutableStringRef description = CFStringCreateMutable(kCFAllocatorDefault, 0);
    CFStringAppendFormat(description, NULL, CFSTR("<Interest: "));
    
    CFArrayForEach(interests, ^(const void* string) {
        if (isString(string))
            CFStringAppendFormat(description, NULL, CFSTR(" '%@'"), string);
    });
    CFStringAppend(description, CFSTR(">"));
    
bool
_mongoc_secure_transport_import_pem (const char *filename, const char *passphrase, CFArrayRef *items, SecExternalItemType *type)
{
   SecExternalFormat format = kSecFormatPEMSequence;
   SecItemImportExportKeyParameters params;
   SecTransformRef sec_transform;
   CFReadStreamRef read_stream;
   CFDataRef dataref;
   CFErrorRef error;
   CFURLRef url;
   OSStatus res;


   if (!filename) {
      MONGOC_WARNING("%s", "No certificate provided");
      return false;
   }

   params.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
   params.flags = 0;
   params.passphrase = NULL;
   params.alertTitle = NULL;
   params.alertPrompt = NULL;
   params.accessRef = NULL;
   params.keyUsage = NULL;
   params.keyAttributes = NULL;

   if (passphrase) {
      params.passphrase = CFStringCreateWithCString (kCFAllocatorDefault, passphrase, kCFStringEncodingUTF8);
   }

   url = CFURLCreateFromFileSystemRepresentation (kCFAllocatorDefault, (const UInt8 *)filename, strlen (filename), false);
   read_stream = CFReadStreamCreateWithFile (kCFAllocatorDefault, url);
   sec_transform = SecTransformCreateReadTransformWithReadStream (read_stream);
   dataref = SecTransformExecute (sec_transform, &error);


   if (error) {
      CFStringRef str = CFErrorCopyDescription (error);
      MONGOC_WARNING ("Failed importing PEM '%s': %s", filename, CFStringGetCStringPtr (str, CFStringGetFastestEncoding(str)));
      CFRelease (str);
      CFRelease (sec_transform);
      CFRelease (read_stream);
      CFRelease (url);

      if (passphrase) {
         CFRelease (params.passphrase);
      }
      return false;
   }

   res = SecItemImport (dataref, CFSTR(".pem"), &format, type, 0, &params, NULL, items);
   CFRelease (dataref);
   CFRelease (sec_transform);
   CFRelease (read_stream);
   CFRelease (url);

   if (passphrase) {
      CFRelease (params.passphrase);
   }
   if (res) {
      return false;
   }

   return true;
}
Ejemplo n.º 17
0
/* __CFWriteBytesToFileWithAtomicity is a "safe save" facility. Write the bytes using the specified mode on the file to the provided URL. If the atomic flag is true, try to do it in a fashion that will enable a safe save.
 */
static Boolean __CFWriteBytesToFileWithAtomicity(CFURLRef url, const void *bytes, int length, SInt32 mode, Boolean atomic) {
    int fd = -1;
    char auxPath[CFMaxPathSize + 16];
    char cpath[CFMaxPathSize];
    uid_t owner = getuid();
    gid_t group = getgid();
    Boolean writingFileAsRoot = ((getuid() != geteuid()) && (geteuid() == 0));
    
    if (!CFURLGetFileSystemRepresentation(url, true, (uint8_t *)cpath, CFMaxPathSize)) {
        return false;
    }
    
    if (-1 == mode || writingFileAsRoot) {
        struct stat statBuf;
        if (0 == stat(cpath, &statBuf)) {
            mode = statBuf.st_mode;
            owner = statBuf.st_uid;
            group = statBuf.st_gid;
        } else {
            mode = 0664;
            if (writingFileAsRoot && (0 == strncmp(cpath, "/Library/Preferences", 20))) {
                owner = geteuid();
                group = 80;
            }
        }
    }
    
    if (atomic) {
        CFURLRef dir = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorSystemDefault, url);
        CFURLRef tempFile = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, dir, CFSTR("cf#XXXXX"), false);
        CFRelease(dir);
        if (!CFURLGetFileSystemRepresentation(tempFile, true, (uint8_t *)auxPath, CFMaxPathSize)) {
            CFRelease(tempFile);
            return false;
        }
        CFRelease(tempFile);
        fd = mkstemp(auxPath);
    } else {
        fd = open(cpath, O_WRONLY|O_CREAT|O_TRUNC, mode);
    }
    
    if (fd < 0) return false;
    
    if (length && (write(fd, bytes, length) != length || fsync(fd) < 0)) {
        int saveerr = thread_errno();
        close(fd);
        if (atomic)
            unlink(auxPath);
        thread_set_errno(saveerr);
        return false;
    }
    
    close(fd);
    
    if (atomic) {
        // preserve the mode as passed in originally
        chmod(auxPath, mode);
                
        if (0 != rename(auxPath, cpath)) {
            unlink(auxPath);
            return false;
        }
        
        // If the file was renamed successfully and we wrote it as root we need to reset the owner & group as they were.
        if (writingFileAsRoot) {
            chown(cpath, owner, group);
        }
    }
    return true;
}
Ejemplo n.º 18
0
MMBitmapRef copyMMBitmapFromDisplayInRect(MMRect rect)
{
#if defined(IS_MACOSX)

	size_t bytewidth;
	uint8_t bitsPerPixel, bytesPerPixel;
	uint8_t *buffer;

	CGDirectDisplayID displayID = CGMainDisplayID();

	//Replacement for CGDisplayBitsPerPixel. 
	CGDisplayModeRef mode = CGDisplayCopyDisplayMode(displayID);
	size_t depth = 0;
	
	CFStringRef pixEnc = CGDisplayModeCopyPixelEncoding(mode);
	if(CFStringCompare(pixEnc, CFSTR(IO32BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
		depth = 32;
	else if(CFStringCompare(pixEnc, CFSTR(IO16BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
		depth = 16;
	else if(CFStringCompare(pixEnc, CFSTR(IO8BitIndexedPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
		depth = 8;

	bitsPerPixel = (uint8_t) depth; 
	bytesPerPixel = bitsPerPixel / 8;
	/* Align width to padding. */
	bytewidth = ADD_PADDING(rect.size.width * bytesPerPixel);

	/* Convert Quartz point to postscript point. */
	rect.origin.y = CGDisplayPixelsHigh(displayID) - rect.origin.y - rect.size.height;

	CGImageRef image = CGDisplayCreateImageForRect(displayID, CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height));

    // Request access to the raw pixel data via the image's DataProvider.
    CGDataProviderRef provider = CGImageGetDataProvider(image);
    CFDataRef data = CGDataProviderCopyData(provider);

    size_t width, height;    
    width = CGImageGetWidth(image);
    height = CGImageGetHeight(image); 
    size_t bpp = CGImageGetBitsPerPixel(image) / 8;

    uint8 *pixels = malloc(width * height * bpp);
    memcpy(pixels, CFDataGetBytePtr(data), width * height * bpp);
    CFRelease(data); 
   	CGImageRelease(image); 

	return createMMBitmap(pixels, rect.size.width, rect.size.height, bytewidth,
	                      bitsPerPixel, bytesPerPixel);
#elif defined(USE_X11)
	MMBitmapRef bitmap;

	Display *display = XOpenDisplay(NULL);
	XImage *image = XGetImage(display,
	                          XDefaultRootWindow(display),
	                          (int)rect.origin.x,
	                          (int)rect.origin.y,
	                          (unsigned int)rect.size.width,
	                          (unsigned int)rect.size.height,
	                          AllPlanes, ZPixmap);
	XCloseDisplay(display);
	if (image == NULL) return NULL;

	bitmap = createMMBitmap((uint8_t *)image->data,
	                        rect.size.width,
	                        rect.size.height,
	                        (size_t)image->bytes_per_line,
	                        (uint8_t)image->bits_per_pixel,
	                        (uint8_t)image->bits_per_pixel / 8);
	image->data = NULL; /* Steal ownership of bitmap data so we don't have to
	                     * copy it. */
	XDestroyImage(image);

	return bitmap;
#elif defined(IS_WINDOWS)
	MMBitmapRef bitmap;
	void *data;
	HDC screen = NULL, screenMem = NULL;
	HBITMAP dib;
	BITMAPINFO bi;

	/* Initialize bitmap info. */
	bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
   	bi.bmiHeader.biWidth = (long)rect.size.width;
   	bi.bmiHeader.biHeight = -(long)rect.size.height; /* Non-cartesian, please */
   	bi.bmiHeader.biPlanes = 1;
   	bi.bmiHeader.biBitCount = 32;
   	bi.bmiHeader.biCompression = BI_RGB;
   	bi.bmiHeader.biSizeImage = (DWORD)(4 * rect.size.width * rect.size.height);
	bi.bmiHeader.biXPelsPerMeter = 0;
	bi.bmiHeader.biYPelsPerMeter = 0;
	bi.bmiHeader.biClrUsed = 0;
	bi.bmiHeader.biClrImportant = 0;

	screen = GetDC(NULL); /* Get entire screen */
	if (screen == NULL) return NULL;

	/* Get screen data in display device context. */
   	dib = CreateDIBSection(screen, &bi, DIB_RGB_COLORS, &data, NULL, 0);

	/* Copy the data into a bitmap struct. */
	if ((screenMem = CreateCompatibleDC(screen)) == NULL ||
	    SelectObject(screenMem, dib) == NULL ||
	    !BitBlt(screenMem, 
	            (int)rect.origin.x, 
	            (int)rect.origin.y, 
	            (int)rect.size.width,
	            (int)rect.size.height, screen, 0, 0, SRCCOPY)) {
		/* Error copying data. */
		ReleaseDC(NULL, screen);
		DeleteObject(dib);
		if (screenMem != NULL) DeleteDC(screenMem);

		return NULL;
	}

	bitmap = createMMBitmap(NULL,
	                        rect.size.width,
	                        rect.size.height,
	                        4 * rect.size.width,
	                        (uint8_t)bi.bmiHeader.biBitCount, 
	                        4);

	/* Copy the data to our pixel buffer. */
	if (bitmap != NULL) {
		bitmap->imageBuffer = malloc(bitmap->bytewidth * bitmap->height);
		memcpy(bitmap->imageBuffer, data, bitmap->bytewidth * bitmap->height);
	}

	ReleaseDC(NULL, screen);
	DeleteObject(dib);
	DeleteDC(screenMem);

	return bitmap;
#endif
}
static CFStringRef __CFUserNotificationCopyDescription(CFTypeRef cf) {
    CFMutableStringRef result;
    result = CFStringCreateMutable(CFGetAllocator(cf), 0);
    CFStringAppendFormat(result, NULL, CFSTR("<CFUserNotification %p>"), cf);
    return result;
}
Ejemplo n.º 20
0
void ConfigureCheat (void)
{
	if (!cartOpen)
		return;

	OSStatus	err;
	IBNibRef	nibRef;

	err = CreateNibReference(kMacS9XCFString, &nibRef);
	if (err == noErr)
	{
		err = CreateWindowFromNib(nibRef, CFSTR("CheatEntry"), &wRef);
		if (err == noErr)
		{
			DataBrowserCallbacks	callbacks;
			EventHandlerRef			eref;
			EventHandlerUPP			eUPP;
			EventTypeSpec			events[] = { { kEventClassCommand, kEventCommandProcess      },
												 { kEventClassCommand, kEventCommandUpdateStatus },
												 { kEventClassWindow,  kEventWindowClose         } };
			HIViewRef				ctl, root;
			HIViewID				cid;

			root = HIViewGetRoot(wRef);
			cid.id = 0;
			cid.signature = kDataBrowser;
			HIViewFindByID(root, cid, &dbRef);

		#ifdef MAC_PANTHER_SUPPORT
			if (systemVersion < 0x1040)
			{
				HISize	minSize;
				Rect	rct;

				GetWindowBounds(wRef, kWindowContentRgn, &rct);
				minSize.width  = (float) (rct.right  - rct.left);
				minSize.height = (float) (rct.bottom - rct.top );
				err = SetWindowResizeLimits(wRef, &minSize, NULL);
			}
		#endif

			callbacks.version = kDataBrowserLatestCallbacks;
			err = InitDataBrowserCallbacks(&callbacks);
			callbacks.u.v1.itemDataCallback = NewDataBrowserItemDataUPP(DBClientDataCallback);
			callbacks.u.v1.itemCompareCallback = NewDataBrowserItemCompareUPP(DBCompareCallBack);
			callbacks.u.v1.itemNotificationCallback = NewDataBrowserItemNotificationUPP(DBItemNotificationCallBack);
			err = SetDataBrowserCallbacks(dbRef, &callbacks);

			if (systemVersion >= 0x1040)
				err = DataBrowserChangeAttributes(dbRef, kDataBrowserAttributeListViewAlternatingRowColors, kDataBrowserAttributeNone);

			InitCheatItems();
			ImportCheatItems();

			DataBrowserItemID	*id;

			id = new DataBrowserItemID[MAX_CHEATS];
			if (!id)
				QuitWithFatalError(0, "cheat 01");

			numofcheats = 0;

			for (unsigned int i = 0; i < MAX_CHEATS; i++)
			{
				if (citem[i].valid)
				{
					id[numofcheats] = citem[i].id;
					numofcheats++;
				}
			}

			if (numofcheats)
				err = AddDataBrowserItems(dbRef, kDataBrowserNoItem, numofcheats, id, kDataBrowserItemNoProperty);

			delete [] id;

			cid.signature = kNewButton;
			HIViewFindByID(root, cid, &ctl);
			if (numofcheats == MAX_CHEATS)
				err = DeactivateControl(ctl);
			else
				err = ActivateControl(ctl);

			cid.signature = kAllButton;
			HIViewFindByID(root, cid, &ctl);
			if (numofcheats == 0)
				err = DeactivateControl(ctl);
			else
				err = ActivateControl(ctl);

			cid.signature = kDelButton;
			HIViewFindByID(root, cid, &ctl);
			err = DeactivateControl(ctl);

			eUPP = NewEventHandlerUPP(CheatEventHandler);
			err = InstallWindowEventHandler(wRef, eUPP, GetEventTypeCount(events), events, (void *) wRef, &eref);

			err = SetKeyboardFocus(wRef, dbRef, kControlFocusNextPart);

			MoveWindowPosition(wRef, kWindowCheatEntry, true);
			ShowWindow(wRef);
			err = RunAppModalLoopForWindow(wRef);
			HideWindow(wRef);
			SaveWindowPosition(wRef, kWindowCheatEntry);

			err = RemoveEventHandler(eref);
			DisposeEventHandlerUPP(eUPP);

			DisposeDataBrowserItemNotificationUPP(callbacks.u.v1.itemNotificationCallback);
			DisposeDataBrowserItemCompareUPP(callbacks.u.v1.itemCompareCallback);
			DisposeDataBrowserItemDataUPP(callbacks.u.v1.itemDataCallback);

			CFRelease(wRef);

			DetachCheatItems();
		}

		DisposeNibReference(nibRef);
	}
}
Ejemplo n.º 21
0
ITunesController::ITunesController()
{
	// TODO: Poll iTunes for current playing tune
	CFNotificationCenterRef center = CFNotificationCenterGetDistributedCenter();
	CFNotificationCenterAddObserver(center, this, ITunesController::iTunesCallback, CFSTR("com.apple.iTunes.playerInfo"), NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
}
Ejemplo n.º 22
0
static pascal OSStatus DBClientDataCallback (HIViewRef browser, DataBrowserItemID itemID, DataBrowserPropertyID property, DataBrowserItemDataRef itemData, Boolean changeValue)
{
	OSStatus 	err, result;
	CFStringRef	str;
	Boolean		r;
	uint32		address;
	uint8		value;
	char		code[256];

	result = noErr;

	switch (property)
	{
		case kCmCheckBox:
			ThemeButtonValue	buttonValue;

            if (changeValue)
			{
				err = GetDataBrowserItemDataButtonValue(itemData, &buttonValue);
				citem[itemID - 1].enabled = (buttonValue == kThemeButtonOn) ? true : false;
 	        }
			else
				err = SetDataBrowserItemDataButtonValue(itemData, citem[itemID - 1].enabled ? kThemeButtonOn : kThemeButtonOff);

			break;

		case kCmAddress:
			if (changeValue)
			{
				err = GetDataBrowserItemDataText(itemData, &str);
				r = CFStringGetCString(str, code, 256, CFStringGetSystemEncoding());
				CFRelease(str);
				if (r)
				{
					Boolean	translated;

					if (S9xProActionReplayToRaw(code, address, value) == NULL)
						translated = true;
					else
					if (S9xGameGenieToRaw(code, address, value) == NULL)
						translated = true;
					else
					{
						translated = false;
						if (sscanf(code, "%" SCNx32, &address) != 1)
							address = 0;
						else
							address &= 0xFFFFFF;
					}

					citem[itemID - 1].address = address;
					sprintf(code, "%06" PRIX32, address);
					str = CFStringCreateWithCString(kCFAllocatorDefault, code, CFStringGetSystemEncoding());
					err = SetDataBrowserItemDataText(itemData, str);
					CFRelease(str);

					if (translated)
					{
						DataBrowserItemID	id[1];

						citem[itemID - 1].value = value;
						id[0] = itemID;
						err = UpdateDataBrowserItems(browser, kDataBrowserNoItem, 1, id, kDataBrowserItemNoProperty, kCmValue);
					}
				}
			}
			else
			{
				sprintf(code, "%06" PRIX32, citem[itemID - 1].address);
				str = CFStringCreateWithCString(kCFAllocatorDefault, code, CFStringGetSystemEncoding());
				err = SetDataBrowserItemDataText(itemData, str);
				CFRelease(str);
			}

			break;

		case kCmValue:
			if (changeValue)
			{
				err = GetDataBrowserItemDataText(itemData, &str);
				r = CFStringGetCString(str, code, 256, CFStringGetSystemEncoding());
				CFRelease(str);
				if (r)
				{
					uint32	byte;

					if (sscanf(code, "%" SCNx32, &byte) == 1)
						citem[itemID - 1].value = (uint8) byte;
					else
					{
						citem[itemID - 1].value = 0;
						err = SetDataBrowserItemDataText(itemData, CFSTR("00"));
					}
				}
			}
			else
			{
				sprintf(code, "%02" PRIX8, citem[itemID - 1].value);
				str = CFStringCreateWithCString(kCFAllocatorDefault, code, CFStringGetSystemEncoding());
				err = SetDataBrowserItemDataText(itemData, str);
				CFRelease(str);
			}

			break;

		case kCmDescription:
			if (changeValue)
			{
				code[0] = 0;
				err = GetDataBrowserItemDataText(itemData, &str);
				strcpy(code, GetMultiByteCharacters(str, 19));
				CFRelease(str);

				if (code[0] == 0)
				{
					code[0] = ' ';
					code[1] = 0;
				}

				strcpy(citem[itemID - 1].description, code);
			}
			else
			{
				str = CFStringCreateWithCString(kCFAllocatorDefault, citem[itemID - 1].description, CFStringGetSystemEncoding());
				err = SetDataBrowserItemDataText(itemData, str);
				CFRelease(str);
			}

			break;

		case kDataBrowserItemIsActiveProperty:
			err = SetDataBrowserItemDataBooleanValue(itemData, true);
			break;

		case kDataBrowserItemIsEditableProperty:
			err = SetDataBrowserItemDataBooleanValue(itemData, true);
			break;

		default:
			result = errDataBrowserPropertyNotSupported;
	}

	return (result);
}
Ejemplo n.º 23
0
int main(int argc, const char **argv)
{
    CGIApplicationMain(argc, argv, CGIApplicationName, (id)CFSTR("TimeAppDelegate"));
}
Ejemplo n.º 24
0
extern void PrintPropertyList(CFPropertyListRef propList)
	// This routine prints a CFPropertyList in a nicely formatted way.
{
	PrintPropertyListCallback(CFSTR("ROOT"), propList, (void *) 0);
}
Ejemplo n.º 25
0
SFB::Audio::Decoder::unique_ptr SFB::Audio::Decoder::CreateDecoderForInputSource(InputSource::unique_ptr inputSource, CFStringRef mimeType, CFErrorRef *error)
{
	if(!inputSource)
		return nullptr;

	// Open the input source if it isn't already
	if(AutomaticallyOpenDecoders() && !inputSource->IsOpen() && !inputSource->Open(error))
		return nullptr;

#if 0
	// If the input is an instance of HTTPInputSource, use the MIME type from the server
	// This code is disabled because most HTTP servers don't send the correct MIME types
	HTTPInputSource *httpInputSource = dynamic_cast<HTTPInputSource *>(inputSource);
	bool releaseMIMEType = false;
	if(!mimeType && httpInputSource && httpInputSource->IsOpen()) {
		mimeType = httpInputSource->CopyContentMIMEType();
		if(mimeType)
			releaseMIMEType = true;
	}
#endif

	// The MIME type takes precedence over the file extension
	if(mimeType) {
		for(auto subclassInfo : sRegisteredSubclasses) {
			if(subclassInfo.mHandlesMIMEType(mimeType)) {
				unique_ptr decoder(subclassInfo.mCreateDecoder(std::move(inputSource)));
				if(!AutomaticallyOpenDecoders())
					return decoder;
				else {
					 if(decoder->Open(error))
						 return decoder;
					// Take back the input source for reuse if opening fails
					else
						 inputSource = std::move(decoder->mInputSource);
				}
			}
		}

#if 0
		if(releaseMIMEType)
			CFRelease(mimeType), mimeType = nullptr;
#endif
	}

	// If no MIME type was specified, use the extension-based resolvers

	CFURLRef inputURL = inputSource->GetURL();
	if(!inputURL)
		return nullptr;

	SFB::CFString pathExtension = CFURLCopyPathExtension(inputURL);
	if(!pathExtension) {
		if(error) {
			SFB::CFString description = CFCopyLocalizedString(CFSTR("The type of the file “%@” could not be determined."), "");
			SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Unknown file type"), "");
			SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may be missing or may not match the file's type."), "");
			
			*error = CreateErrorForURL(InputSource::ErrorDomain, InputSource::FileNotFoundError, description, inputURL, failureReason, recoverySuggestion);
		}

		return nullptr;
	}

	// TODO: Some extensions (.oga for example) support multiple audio codecs (Vorbis, FLAC, Speex)
	// and if openDecoder is false the wrong decoder type may be returned, since the file isn't analyzed
	// until Open() is called

	for(auto subclassInfo : sRegisteredSubclasses) {
		if(subclassInfo.mHandlesFilesWithExtension(pathExtension)) {
			unique_ptr decoder(subclassInfo.mCreateDecoder(std::move(inputSource)));
			if(!AutomaticallyOpenDecoders())
				return decoder;
			else {
				if(decoder->Open(error))
					return decoder;
				// Take back the input source for reuse if opening fails
				else
					inputSource = std::move(decoder->mInputSource);
			}
		}
	}

	return nullptr;
}
Ejemplo n.º 26
0
static void TestDuplicateAndDeleteService(void)
	// A test of the service duplication and deleting routines.
{
	OSStatus 	err;
	CFArrayRef  localServiceIDs;
	CFStringRef newServiceID;
	
	newServiceID = NULL;
	localServiceIDs = NULL;

	// Use NULL for the set ID to indicate that we're operating on
	// the current set.
	//
	// Can't use NULL for a service ID, so we have to come up with 
	// a valid service ID first.  We do this by choosing the first 
	// service ID.
	
	err = MoreSCCopyServiceIDs(NULL, &localServiceIDs, NULL);
	if (err == noErr) {
		assert( CFArrayGetCount(localServiceIDs) > 0 );
		err = MoreSCDuplicateService(NULL, (CFStringRef) CFArrayGetValueAtIndex(localServiceIDs, 0), CFSTR("Frog"), &newServiceID);
	}

	if (err == noErr) {
		if (!gRunQuiet) {
			fprintf(stderr, "New service ID is ");
			CFShow(newServiceID);
		}
		
		err = MoreSCDeleteService(NULL, newServiceID);
	}

	CFQRelease(localServiceIDs);
	CFQRelease(newServiceID);

	PrintTestResult(err, NULL);
}
Ejemplo n.º 27
0
static void HIDGetElementsCFArrayHandler (const void * value, void * parameter)
{
	if (CFGetTypeID (value) != CFDictionaryGetTypeID ())
      return;

   CFTypeRef refElement = CFTypeRef(value);
	long elementType, usagePage, usage;
	CFTypeRef refElementType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementTypeKey));
	CFTypeRef refUsagePage = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementUsagePageKey));
	CFTypeRef refUsage = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementUsageKey));
   bool isButton = false, isAxis = false;

   ControllerElement *theElement = NULL;
	if ((refElementType) && (CFNumberGetValue (refElementType, kCFNumberLongType, &elementType)))
	{
		/* look at types of interest */
		if ((elementType == kIOHIDElementTypeInput_Misc) || (elementType == kIOHIDElementTypeInput_Button) ||
			(elementType == kIOHIDElementTypeInput_Axis))
		{
			if (refUsagePage && CFNumberGetValue (refUsagePage, kCFNumberLongType, &usagePage) &&
				refUsage && CFNumberGetValue (refUsage, kCFNumberLongType, &usage))
			{
				switch (usagePage) /* only interested in kHIDPage_GenericDesktop and kHIDPage_Button */
				{
					case kHIDPage_GenericDesktop:
						{
							switch (usage) /* look at usage to determine function */
							{
								case kHIDUsage_GD_X:
                           theElement = gController.axes + AxisX;
                           break;
								case kHIDUsage_GD_Y:
                           theElement = gController.axes + AxisY;
                           break;
								case kHIDUsage_GD_Z:
                           theElement = gController.axes + AxisZ;
                           break;
								case kHIDUsage_GD_Rx:
                           theElement = gController.axes + AxisRx;
                           break;
								case kHIDUsage_GD_Ry:
                           theElement = gController.axes + AxisRy;
                           break;
								case kHIDUsage_GD_Rz:
                           theElement = gController.axes + AxisRz;
                           break;
								case kHIDUsage_GD_Slider:
                           theElement = gController.axes + AxisSlider0;
                           break;
								case kHIDUsage_GD_Dial:
								case kHIDUsage_GD_Wheel:
   								break;
							}							
						}
						break;
					case kHIDPage_Button:
                  {
                     ControllerElement e;
                     gController.buttons.push_back(e);
                     theElement = &gController.buttons.last();
                  }
						break;
					default:
						break;
				}
			}
		}
		else if (kIOHIDElementTypeCollection == elementType)
      {
         CFTypeRef refElementTop = CFDictionaryGetValue ((CFMutableDictionaryRef) refElement, CFSTR(kIOHIDElementKey));
         if (refElementTop)
         {
            CFTypeID type = CFGetTypeID (refElementTop);
            if (type == CFArrayGetTypeID()) /* if element is an array */
            {
               CFRange range = {0, CFArrayGetCount (refElementTop)};
               /* CountElementsCFArrayHandler called for each array member */
               CFArrayApplyFunction (refElementTop, range, HIDGetElementsCFArrayHandler, NULL);
            }
         }
      }
	}
	if (theElement) /* add to list */
	{
	   long number;
	   CFTypeRef refType;

	   refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementCookieKey));
	   if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
		   theElement->cookie = (IOHIDElementCookie) number;
	   refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementMinKey));
	   if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
		   theElement->minValue = number;

      refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementMaxKey));

	   if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
		   theElement->maxValue = number;
	  logprintf("Cookie = %d min = %d max = %d", theElement->cookie, theElement->minValue, theElement->maxValue);
	}
}
Ejemplo n.º 28
0
static void MergeStatusCodes(CFTypeRef key, CFTypeRef value, void* context)
{
    // Windows (and therefore .NET) certificate status codes are defined on an int32_t.
    // The top 32 bits will be used to convey error information, the bottom 32 bits
    // as a data aggregator for the status codes.
    uint64_t* pStatus = (uint64_t*)context;

    if (key == NULL)
    {
        return;
    }

    // If any error code was already set.
    if (*pStatus > INT_MAX)
    {
        return;
    }

    if (CFGetTypeID(key) != CFStringGetTypeID())
    {
        *pStatus |= PAL_X509ChainErrorUnknownValueType;
        return;
    }

    (void)value;
    CFStringRef keyString = (CFStringRef)key;

    if (CFEqual(keyString, CFSTR("NotValidBefore")) || CFEqual(keyString, CFSTR("ValidLeaf")) ||
        CFEqual(keyString, CFSTR("ValidIntermediates")) || CFEqual(keyString, CFSTR("ValidRoot")) ||
        CFEqual(keyString, CFSTR("TemporalValidity")))
        *pStatus |= PAL_X509ChainNotTimeValid;
    else if (CFEqual(keyString, CFSTR("Revocation")))
        *pStatus |= PAL_X509ChainRevoked;
    else if (CFEqual(keyString, CFSTR("KeyUsage")))
        *pStatus |= PAL_X509ChainNotValidForUsage;
    else if (CFEqual(keyString, CFSTR("AnchorTrusted")))
        *pStatus |= PAL_X509ChainUntrustedRoot;
    else if (CFEqual(keyString, CFSTR("BasicConstraints")))
        *pStatus |= PAL_X509ChainInvalidBasicConstraints;
    else if (CFEqual(keyString, CFSTR("UsageConstraints")))
        *pStatus |= PAL_X509ChainExplicitDistrust;
    else if (CFEqual(keyString, CFSTR("RevocationResponseRequired")))
        *pStatus |= PAL_X509ChainRevocationStatusUnknown;
    else if (CFEqual(keyString, CFSTR("MissingIntermediate")))
        *pStatus |= PAL_X509ChainPartialChain;
    else if (CFEqual(keyString, CFSTR("WeakLeaf")) || CFEqual(keyString, CFSTR("WeakIntermediates")) ||
             CFEqual(keyString, CFSTR("WeakRoot")) || CFEqual(keyString, CFSTR("WeakKeySize")))
    {
        // Because we won't report this out of a chain built by .NET on Windows,
        // don't report it here.
        //
        // (On Windows CERT_CHAIN_PARA.pStrongSignPara is NULL, so "strongness" checks
        // are not performed).
    }
    else if (CFEqual(keyString, CFSTR("StatusCodes")))
    {
        // 10.13 added a StatusCodes value which may be a numeric rehashing of the string data.
        // It doesn't represent a new error code, and we're still getting the old ones, so
        // just ignore it for now.
    }
    else if (CFEqual(keyString, CFSTR("NonEmptySubject")))
    {
        // Not a "problem" that we report.
    }
    else
    {
#ifdef DEBUGGING_UNKNOWN_VALUE
        printf("%s\n", CFStringGetCStringPtr(keyString, CFStringGetSystemEncoding()));
#endif
        *pStatus |= PAL_X509ChainErrorUnknownValue;
    }
}