KeyID COSXKeyState::CKeyResource::getKeyID(UInt8 c) { if (c == 0) { return kKeyNone; } else if (c >= 32 && c < 127) { // ASCII return static_cast<KeyID>(c); } else { // handle special keys switch (c) { case 0x01: return kKeyHome; case 0x02: return kKeyKP_Enter; case 0x03: return kKeyKP_Enter; case 0x04: return kKeyEnd; case 0x05: return kKeyHelp; case 0x08: return kKeyBackSpace; case 0x09: return kKeyTab; case 0x0b: return kKeyPageUp; case 0x0c: return kKeyPageDown; case 0x0d: return kKeyReturn; case 0x10: // OS X maps all the function keys (F1, etc) to this one key. // we can't determine the right key here so we have to do it // some other way. return kKeyNone; case 0x1b: return kKeyEscape; case 0x1c: return kKeyLeft; case 0x1d: return kKeyRight; case 0x1e: return kKeyUp; case 0x1f: return kKeyDown; case 0x7f: return kKeyDelete; case 0x06: case 0x07: case 0x0a: case 0x0e: case 0x0f: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1a: // discard other control characters return kKeyNone; default: // not special or unknown break; } // create string with character char str[2]; str[0] = static_cast<char>(c); str[1] = 0; #if defined(MAC_OS_X_VERSION_10_5) // get current keyboard script TISInputSourceRef isref = TISCopyCurrentKeyboardInputSource(); CFArrayRef langs = (CFArrayRef) TISGetInputSourceProperty(isref, kTISPropertyInputSourceLanguages); CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)CFArrayGetValueAtIndex(langs, 0)); #else CFStringEncoding encoding = GetScriptManagerVariable(smKeyScript); #endif // convert to unicode CFStringRef cfString = CFStringCreateWithCStringNoCopy( kCFAllocatorDefault, str, encoding, kCFAllocatorNull); // sometimes CFStringCreate...() returns NULL (e.g. Apple Korean // encoding with char value 214). if it did then make no key, // otherwise CFStringCreateMutableCopy() will crash. if (cfString == NULL) { return kKeyNone; } // convert to precomposed CFMutableStringRef mcfString = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, cfString); CFRelease(cfString); CFStringNormalize(mcfString, kCFStringNormalizationFormC); // check result int unicodeLength = CFStringGetLength(mcfString); if (unicodeLength == 0) { CFRelease(mcfString); return kKeyNone; } if (unicodeLength > 1) { // FIXME -- more than one character, we should handle this CFRelease(mcfString); return kKeyNone; } // get unicode character UniChar uc = CFStringGetCharacterAtIndex(mcfString, 0); CFRelease(mcfString); // convert to KeyID return static_cast<KeyID>(uc); } }
GLboolean renderspu_SystemVBoxCreateWindow(VisualInfo *visual, GLboolean showIt, WindowInfo *window) { CRASSERT(visual); CRASSERT(window); WindowAttributes winAttr = kWindowNoShadowAttribute | kWindowCompositingAttribute | kWindowIgnoreClicksAttribute | kWindowStandardHandlerAttribute | kWindowLiveResizeAttribute; WindowClass winClass = kOverlayWindowClass; Rect windowRect; OSStatus status = noErr; window->visual = visual; window->nativeWindow = NULL; if(window->window && IsValidWindowPtr(window->window)) { EventRef evt; status = CreateEvent(NULL, kEventClassVBox, kEventVBoxDisposeWindow, 0, kEventAttributeNone, &evt); CHECK_CARBON_RC_RETURN (status, "Render SPU (renderspu_SystemVBoxCreateWindow): CreateEvent Failed", false); status = SetEventParameter(evt, kEventParamWindowRef, typeWindowRef, sizeof (window->window), &window->window); CHECK_CARBON_RC_RETURN (status, "Render SPU (renderspu_SystemVBoxCreateWindow): SetEventParameter Failed", false); status = PostEventToQueue(GetMainEventQueue(), evt, kEventPriorityStandard); CHECK_CARBON_RC_RETURN (status, "Render SPU (renderspu_SystemVBoxCreateWindow): PostEventToQueue Failed", false); } windowRect.left = window->x; windowRect.top = window->y; windowRect.right = window->x + window->BltInfo.width; windowRect.bottom = window->y + window->BltInfo.height; status = CreateNewWindow(winClass, winAttr, &windowRect, &window->window); CHECK_CARBON_RC_RETURN (status, "Render SPU (renderspu_SystemVBoxCreateWindow): CreateNewWindow Failed", GL_FALSE); /* We set a title for debugging purposes */ CFStringRef title_string; title_string = CFStringCreateWithCStringNoCopy(NULL, window->title, kCFStringEncodingMacRoman, NULL); SetWindowTitleWithCFString(window->BltInfo.window, title_string); CFRelease(title_string); /* The parent has to be in its own group */ WindowRef parent = NULL; if (render_spu_parent_window_id) { parent = HIViewGetWindow ((HIViewRef)render_spu_parent_window_id); SetWindowGroup (parent, render_spu.pParentGroup); } /* Add the new window to the master group */ SetWindowGroup(window->window, render_spu.pMasterGroup); /* This will be initialized on the first attempt to attach the global * context to this new window */ window->bufferName = -1; window->dummyContext = NULL; window->hVisibleRegion = 0; if(showIt) renderspu_SystemShowWindow(window, GL_TRUE); crDebug("Render SPU (renderspu_SystemVBoxCreateWindow): actual window (x, y, width, height): %d, %d, %d, %d", window->x, window->y, window->BltInfo.width, window->BltInfo.height); return GL_TRUE; }
static CFStringRef copyVPNInterfaceNAP (char *interface_buf) { CFStringRef interf_key; CFMutableArrayRef interf_keys; CFDictionaryRef dict = NULL; CFIndex i; const void * keys_q[128]; void ** keys = (__typeof__(keys))keys_q; const void * values_q[128]; void ** values = (__typeof__(values))values_q; CFIndex n; CFStringRef vpn_if = NULL; CFStringRef result = NULL; if (!interface_buf) { return NULL; } if (gDynamicStore) { vpn_if = CFStringCreateWithCStringNoCopy(NULL, interface_buf, kCFStringEncodingASCII, kCFAllocatorNull); if (!vpn_if) { // if we could not initialize interface CFString goto done; } interf_keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); // get State:/Network/Interface/<vpn_if>/Airport interf_key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL, kSCDynamicStoreDomainState, vpn_if, kSCEntNetAirPort); CFArrayAppendValue(interf_keys, interf_key); CFRelease(interf_key); dict = SCDynamicStoreCopyMultiple(gDynamicStore, interf_keys, NULL); CFRelease(interf_keys); if (!dict) { // if we could not access the SCDynamicStore goto done; } // look for the service which matches the provided prefixes n = CFDictionaryGetCount(dict); if (n <= 0) { goto done; } if (n > (CFIndex)(sizeof(keys_q) / sizeof(CFTypeRef))) { keys = CFAllocatorAllocate(NULL, n * sizeof(CFTypeRef), 0); values = CFAllocatorAllocate(NULL, n * sizeof(CFTypeRef), 0); } CFDictionaryGetKeysAndValues(dict, (const void **)keys, (const void **)values); for (i=0; i < n; i++) { CFStringRef s_key = (CFStringRef)keys[i]; CFDictionaryRef s_dict = (CFDictionaryRef)values[i]; CFDictionaryRef i_dict = NULL; CFStringRef nap; if (!isA_CFString(s_key) || !isA_CFDictionary(s_dict)) { continue; } i_dict = CFDictionaryGetValue(s_dict, KEY_VPNNETWORKLOCATION_INTERFINFO); if (!isA_CFDictionary(i_dict)) { continue; } nap = CFDictionaryGetValue(i_dict, KEY_VPNNETWORKLOCATION_SSID); if (nap) { result = CFStringCreateCopy(NULL, nap); SCLog(TRUE, LOG_INFO, CFSTR("%s: found nap %@, interf %s"), __FUNCTION__, result, interface_buf); goto done; } } done : if (vpn_if) CFRelease(vpn_if); if (keys != (__typeof__(keys))keys_q) { CFAllocatorDeallocate(NULL, keys); CFAllocatorDeallocate(NULL, values); } if (dict) CFRelease(dict); } return result; }
void ArchHooks_MacOSX::DumpDebugInfo() { // Get system version RString sSystemVersion; { long major = 0, minor = 0, bugFix = 0; Gestalt( gestaltSystemVersionMajor, &major ); Gestalt( gestaltSystemVersionMinor, &minor ); Gestalt( gestaltSystemVersionBugFix, &bugFix ); if( bugFix ) sSystemVersion = ssprintf( "Mac OS X %ld.%ld.%ld", major, minor, bugFix ); else sSystemVersion = ssprintf( "Mac OS X %ld.%ld", major, minor ); } size_t size; #define GET_PARAM( name, var ) (size = sizeof(var), sysctlbyname(name, &var, &size, NULL, 0) ) // Get memory float fRam; char ramPower; { uint64_t iRam = 0; GET_PARAM( "hw.memsize", iRam ); if( iRam >= 1073741824 ) { fRam = float( double(iRam) / 1073741824.0 ); ramPower = 'G'; } else { fRam = float( double(iRam) / 1048576.0 ); ramPower = 'M'; } } // Get processor information int iMaxCPUs = 0; int iCPUs = 0; float fFreq; char freqPower; RString sModel; do { char szModel[128]; uint64_t iFreq; GET_PARAM( "hw.logicalcpu_max", iMaxCPUs ); GET_PARAM( "hw.logicalcpu", iCPUs ); GET_PARAM( "hw.cpufrequency", iFreq ); if( iFreq >= 1000000000 ) { fFreq = float( double(iFreq) / 1000000000.0 ); freqPower = 'G'; } else { fFreq = float( double(iFreq) / 1000000.0 ); freqPower = 'M'; } if( GET_PARAM("hw.model", szModel) ) { sModel = "Unknown"; break; } sModel = szModel; CFURLRef urlRef = CFBundleCopyResourceURL( CFBundleGetMainBundle(), CFSTR("Hardware.plist"), NULL, NULL ); if( urlRef == NULL ) break; CFDataRef dataRef = NULL; SInt32 error; CFURLCreateDataAndPropertiesFromResource( NULL, urlRef, &dataRef, NULL, NULL, &error ); CFRelease( urlRef ); if( dataRef == NULL ) break; // This also works with binary property lists for some reason. CFPropertyListRef plRef = CFPropertyListCreateFromXMLData( NULL, dataRef, kCFPropertyListImmutable, NULL ); CFRelease( dataRef ); if( plRef == NULL ) break; if( CFGetTypeID(plRef) != CFDictionaryGetTypeID() ) { CFRelease( plRef ); break; } CFStringRef keyRef = CFStringCreateWithCStringNoCopy( NULL, szModel, kCFStringEncodingMacRoman, kCFAllocatorNull ); CFStringRef modelRef = (CFStringRef)CFDictionaryGetValue( (CFDictionaryRef)plRef, keyRef ); if( modelRef ) sModel = CFStringGetCStringPtr( modelRef, kCFStringEncodingMacRoman ); CFRelease( keyRef ); CFRelease( plRef ); } while( false ); #undef GET_PARAM // Send all of the information to the log LOG->Info( "Model: %s (%d/%d)", sModel.c_str(), iCPUs, iMaxCPUs ); LOG->Info( "Clock speed %.2f %cHz", fFreq, freqPower ); LOG->Info( "%s", sSystemVersion.c_str()); LOG->Info( "Memory: %.2f %cB", fRam, ramPower ); }
int checkVPNInterfaceOrServiceBlocked (const char *location, char *interface_buf) { // check to see if interface is captive: if so, bail if the interface is not ready. if (check_interface_captive_and_not_ready(gDynamicStore, interface_buf)) { // TODO: perhaps we should wait for a few seconds? return true; } // return 1, if this is a delete event, and; // TODO: add support for IPv6 <rdar://problem/5920237> // walk Setup:/Network/Service/* and check if there are service entries referencing this interface. e.g. Setup:/Network/Service/44DB8790-0177-4F17-8D4E-37F9413D1D87/Interface:DeviceName == interface, other_serv_found = 1 // Setup:/Network/Interface/"interface"/AirPort:'PowerEnable' == 0 || Setup:/Network/Interface/"interface"/IPv4 is missing, interf_down = 1 if (gDynamicStore) { CFStringRef interf_key; CFMutableArrayRef interf_keys; CFStringRef pattern; CFMutableArrayRef patterns; CFDictionaryRef dict = NULL; CFIndex i; const void * keys_q[128]; const void ** keys = keys_q; const void * values_q[128]; const void ** values = values_q; CFIndex n; CFStringRef vpn_if; int other_serv_found = 0, interf_down = 0; vpn_if = CFStringCreateWithCStringNoCopy(NULL, interface_buf, kCFStringEncodingASCII, kCFAllocatorNull); if (!vpn_if) { // if we could not initialize interface CFString syslog(LOG_NOTICE, "%s: failed to initialize interface CFString", location); goto done; } interf_keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); // get Setup:/Network/Interface/<vpn_if>/Airport interf_key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL, kSCDynamicStoreDomainSetup, vpn_if, kSCEntNetAirPort); CFArrayAppendValue(interf_keys, interf_key); CFRelease(interf_key); // get State:/Network/Interface/<vpn_if>/Airport interf_key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL, kSCDynamicStoreDomainState, vpn_if, kSCEntNetAirPort); CFArrayAppendValue(interf_keys, interf_key); CFRelease(interf_key); // get Setup:/Network/Service/*/Interface pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainSetup, kSCCompAnyRegex, kSCEntNetInterface); CFArrayAppendValue(patterns, pattern); CFRelease(pattern); // get Setup:/Network/Service/*/IPv4 pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainSetup, kSCCompAnyRegex, kSCEntNetIPv4); CFArrayAppendValue(patterns, pattern); CFRelease(pattern); dict = SCDynamicStoreCopyMultiple(gDynamicStore, interf_keys, patterns); CFRelease(interf_keys); CFRelease(patterns); if (!dict) { // if we could not access the SCDynamicStore syslog(LOG_NOTICE, "%s: failed to initialize SCDynamicStore dictionary", location); CFRelease(vpn_if); goto done; } // look for the service which matches the provided prefixes n = CFDictionaryGetCount(dict); if (n <= 0) { syslog(LOG_NOTICE, "%s: empty SCDynamicStore dictionary", location); CFRelease(vpn_if); goto done; } if (n > (CFIndex)(sizeof(keys_q) / sizeof(CFTypeRef))) { keys = CFAllocatorAllocate(NULL, n * sizeof(CFTypeRef), 0); values = CFAllocatorAllocate(NULL, n * sizeof(CFTypeRef), 0); } CFDictionaryGetKeysAndValues(dict, keys, values); for (i=0; i < n; i++) { CFStringRef s_key = (CFStringRef)keys[i]; CFDictionaryRef s_dict = (CFDictionaryRef)values[i]; CFStringRef s_if; if (!isA_CFString(s_key) || !isA_CFDictionary(s_dict)) { continue; } if (CFStringHasSuffix(s_key, kSCEntNetInterface)) { // is a Service Interface entity s_if = CFDictionaryGetValue(s_dict, kSCPropNetInterfaceDeviceName); if (isA_CFString(s_if) && CFEqual(vpn_if, s_if)) { CFArrayRef components; CFStringRef serviceIDRef = NULL, serviceKey = NULL; other_serv_found = 1; // extract service ID components = CFStringCreateArrayBySeparatingStrings(NULL, s_key, CFSTR("/")); if (CFArrayGetCount(components) > 3) { serviceIDRef = CFArrayGetValueAtIndex(components, 3); //if (new key) Setup:/Network/Service/service_id/IPv4 is missing, then interf_down = 1 serviceKey = SCDynamicStoreKeyCreateNetworkServiceEntity(0, kSCDynamicStoreDomainSetup, serviceIDRef, kSCEntNetIPv4); if (!serviceKey || !CFDictionaryGetValue(dict, serviceKey)) { syslog(LOG_NOTICE, "%s: detected disabled IPv4 Config", location); interf_down = 1; } if (serviceKey) CFRelease(serviceKey); } if (components) CFRelease(components); if (interf_down) break; } continue; } else if (CFStringHasSuffix(s_key, kSCEntNetAirPort)) { // Interface/<vpn_if>/Airport entity if (CFStringHasPrefix(s_key, kSCDynamicStoreDomainSetup)) { CFBooleanRef powerEnable = CFDictionaryGetValue(s_dict, kSCPropNetAirPortPowerEnabled); if (isA_CFBoolean(powerEnable) && CFEqual(powerEnable, kCFBooleanFalse)) { syslog(LOG_NOTICE, "%s: detected AirPort, PowerEnable == FALSE", location); interf_down = 1; break; } } else if (CFStringHasPrefix(s_key, kSCDynamicStoreDomainState)) { UInt16 temp; CFNumberRef airStatus = CFDictionaryGetValue(s_dict, CFSTR("Power Status")); if (isA_CFNumber(airStatus) && CFNumberGetValue(airStatus, kCFNumberShortType, &temp)) { if (temp ==0) { syslog(LOG_NOTICE, "%s: detected AirPort, PowerStatus == 0", location); } } } continue; } } if (vpn_if) CFRelease(vpn_if); if (keys != keys_q) { CFAllocatorDeallocate(NULL, keys); CFAllocatorDeallocate(NULL, values); } done : if (dict) CFRelease(dict); return (other_serv_found == 0 || interf_down == 1); } return 0; }
/* Resolve IPv4/IPv6 address */ PJ_DEF(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *nodename, unsigned *count, pj_addrinfo ai[]) { #if defined(PJ_SOCK_HAS_GETADDRINFO) && PJ_SOCK_HAS_GETADDRINFO!=0 char nodecopy[PJ_MAX_HOSTNAME]; pj_bool_t has_addr = PJ_FALSE; unsigned i; #if defined(PJ_GETADDRINFO_USE_CFHOST) && PJ_GETADDRINFO_USE_CFHOST!=0 CFStringRef hostname; CFHostRef hostRef; pj_status_t status = PJ_SUCCESS; #else int rc; struct addrinfo hint, *res, *orig_res; #endif PJ_ASSERT_RETURN(nodename && count && *count && ai, PJ_EINVAL); PJ_ASSERT_RETURN(nodename->ptr && nodename->slen, PJ_EINVAL); PJ_ASSERT_RETURN(af==PJ_AF_INET || af==PJ_AF_INET6 || af==PJ_AF_UNSPEC, PJ_EINVAL); /* Check if nodename is IP address */ pj_bzero(&ai[0], sizeof(ai[0])); if ((af==PJ_AF_INET || af==PJ_AF_UNSPEC) && pj_inet_pton(PJ_AF_INET, nodename, &ai[0].ai_addr.ipv4.sin_addr) == PJ_SUCCESS) { af = PJ_AF_INET; has_addr = PJ_TRUE; } else if ((af==PJ_AF_INET6 || af==PJ_AF_UNSPEC) && pj_inet_pton(PJ_AF_INET6, nodename, &ai[0].ai_addr.ipv6.sin6_addr) == PJ_SUCCESS) { af = PJ_AF_INET6; has_addr = PJ_TRUE; } if (has_addr) { pj_str_t tmp; tmp.ptr = ai[0].ai_canonname; pj_strncpy_with_null(&tmp, nodename, PJ_MAX_HOSTNAME); ai[0].ai_addr.addr.sa_family = (pj_uint16_t)af; *count = 1; return PJ_SUCCESS; } /* Copy node name to null terminated string. */ if (nodename->slen >= PJ_MAX_HOSTNAME) return PJ_ENAMETOOLONG; pj_memcpy(nodecopy, nodename->ptr, nodename->slen); nodecopy[nodename->slen] = '\0'; #if defined(PJ_GETADDRINFO_USE_CFHOST) && PJ_GETADDRINFO_USE_CFHOST!=0 hostname = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, nodecopy, kCFStringEncodingASCII, kCFAllocatorNull); hostRef = CFHostCreateWithName(kCFAllocatorDefault, hostname); if (CFHostStartInfoResolution(hostRef, kCFHostAddresses, nil)) { CFArrayRef addrRef = CFHostGetAddressing(hostRef, nil); i = 0; if (addrRef != nil) { CFIndex idx, naddr; naddr = CFArrayGetCount(addrRef); for (idx = 0; idx < naddr && i < *count; idx++) { struct sockaddr *addr; addr = (struct sockaddr *) CFDataGetBytePtr(CFArrayGetValueAtIndex(addrRef, idx)); /* This should not happen. */ pj_assert(addr); /* Ignore unwanted address families */ if (af!=PJ_AF_UNSPEC && addr->sa_family != af) continue; /* Store canonical name */ pj_ansi_strcpy(ai[i].ai_canonname, nodecopy); /* Store address */ PJ_ASSERT_ON_FAIL(sizeof(*addr) <= sizeof(pj_sockaddr), continue); pj_memcpy(&ai[i].ai_addr, addr, sizeof(*addr)); PJ_SOCKADDR_RESET_LEN(&ai[i].ai_addr); i++; } } *count = i; } else {
extern MyInfoRef StartWWAN(ConnectClientCallBack clientCB, void *refCon) { char host[] = kTestHost; int portNum = kTestPort; CFDataRef addressData; MyStreamInfoPtr myInfoPtr; CFStreamClientContext ctxt = {0, NULL, NULL, NULL, NULL}; Boolean errorOccurred = FALSE; myInfoPtr = malloc(sizeof(MyStreamInfo)); if (!myInfoPtr) { return NULL; } // init the allocated memory memset(myInfoPtr, 0, sizeof(MyStreamInfo)); myInfoPtr->clientCB = clientCB; myInfoPtr->refCon = refCon; ctxt.info = myInfoPtr; // Check for a dotted-quad address, if so skip any host lookups in_addr_t addr = inet_addr(host); if (addr != INADDR_NONE) { // Create the streams from numberical host struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_len= sizeof(sin); sin.sin_family = AF_INET; sin.sin_addr.s_addr = addr; sin.sin_port = htons(portNum); addressData = CFDataCreate(NULL, (UInt8 *)&sin, sizeof(sin)); CFSocketSignature sig = { AF_INET, SOCK_STREAM, IPPROTO_TCP, addressData }; // Create the streams. CFStreamCreatePairWithPeerSocketSignature(kCFAllocatorDefault, &sig, &(myInfoPtr->rStreamRef), &(myInfoPtr->wStreamRef)); CFRelease(addressData); } else { // Create the streams from ascii host name CFStringRef hostStr = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, host, kCFStringEncodingUTF8, kCFAllocatorNull); CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, hostStr, portNum, &(myInfoPtr->rStreamRef), &(myInfoPtr->wStreamRef)); } myInfoPtr->isConnected = FALSE; myInfoPtr->isStreamInitd = TRUE; myInfoPtr->isClientSet = FALSE; // Inform the streams to kill the socket when it is done with it. // This effects the write stream too since the pair shares the // one socket. CFWriteStreamSetProperty(myInfoPtr->wStreamRef, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue); // set up the client if (!CFWriteStreamSetClient(myInfoPtr->wStreamRef, kCFStreamEventOpenCompleted | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, MyCFWriteStreamClientCallBack, &ctxt)) { printf("CFWriteStreamSetClient failed\n"); errorOccurred = TRUE; } else myInfoPtr->isClientSet = TRUE; if (!errorOccurred) { // schedule the stream CFWriteStreamScheduleWithRunLoop(myInfoPtr->wStreamRef, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); // Try to open the stream. if (!CFWriteStreamOpen(myInfoPtr->wStreamRef)) { printf("CFWriteStreamOpen failed\n"); errorOccurred = TRUE; } } if (!errorOccurred) { // everything worked so far, so run the runloop - when the callback gets called, it will stop the run loop printf("CFWriteStreamOpen returned with no error - calling CFRunLoopRun\n"); CFRunLoopRun(); if (myInfoPtr->errorOccurred) errorOccurred = TRUE; printf("after CFRunLoopRun - returning\n"); } if (errorOccurred) { myInfoPtr->isConnected = FALSE; CleanupAfterWAAN(myInfoPtr); CloseStreams(myInfoPtr); if (myInfoPtr->isStreamInitd) { CFRelease(myInfoPtr->rStreamRef); CFRelease(myInfoPtr->wStreamRef); myInfoPtr->isStreamInitd = FALSE; } free(myInfoPtr); return NULL; } return (MyInfoRef)myInfoPtr; }
//------------------------------------------------------------------------ bool platform_support::init(unsigned width, unsigned height, unsigned flags) { if(m_specific->m_sys_format == pix_format_undefined) { return false; } m_window_flags = flags; // application EventTypeSpec eventType; EventHandlerUPP handlerUPP; eventType.eventClass = kEventClassApplication; eventType.eventKind = kEventAppQuit; handlerUPP = NewEventHandlerUPP(DoAppQuit); InstallApplicationEventHandler (handlerUPP, 1, &eventType, nil, nil); eventType.eventClass = kEventClassMouse; eventType.eventKind = kEventMouseDown; handlerUPP = NewEventHandlerUPP(DoMouseDown); InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); eventType.eventKind = kEventMouseUp; handlerUPP = NewEventHandlerUPP(DoMouseUp); InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); eventType.eventKind = kEventMouseDragged; handlerUPP = NewEventHandlerUPP(DoMouseDragged); InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); eventType.eventClass = kEventClassKeyboard; eventType.eventKind = kEventRawKeyDown; handlerUPP = NewEventHandlerUPP(DoKeyDown); InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); eventType.eventKind = kEventRawKeyUp; handlerUPP = NewEventHandlerUPP(DoKeyUp); InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); eventType.eventKind = kEventRawKeyRepeat; handlerUPP = NewEventHandlerUPP(DoKeyDown); // 'key repeat' is translated to 'key down' InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); WindowAttributes windowAttrs; Rect bounds; // window windowAttrs = kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute | kWindowStandardHandlerAttribute; SetRect (&bounds, 0, 0, width, height); OffsetRect (&bounds, 100, 100); CreateNewWindow (kDocumentWindowClass, windowAttrs, &bounds, &m_specific->m_window); if(m_specific->m_window == nil) { return false; } // I assume the text is ASCII. // Change to kCFStringEncodingMacRoman, kCFStringEncodingISOLatin1, kCFStringEncodingUTF8 or what else you need. SetWindowTitleWithCFString (m_specific->m_window, CFStringCreateWithCStringNoCopy (nil, m_caption, kCFStringEncodingASCII, nil)); eventType.eventClass = kEventClassWindow; eventType.eventKind = kEventWindowClose; handlerUPP = NewEventHandlerUPP(DoWindowClose); InstallWindowEventHandler (m_specific->m_window, handlerUPP, 1, &eventType, this, NULL); eventType.eventKind = kEventWindowDrawContent; handlerUPP = NewEventHandlerUPP(DoWindowDrawContent); InstallWindowEventHandler (m_specific->m_window, handlerUPP, 1, &eventType, this, NULL); // Periodic task // Instead of an idle function I use the Carbon event timer. // You may decide to change the wait value which is currently 50 milliseconds. EventLoopRef mainLoop; EventLoopTimerUPP timerUPP; EventLoopTimerRef theTimer; mainLoop = GetMainEventLoop(); timerUPP = NewEventLoopTimerUPP (DoPeriodicTask); InstallEventLoopTimer (mainLoop, 0, 50 * kEventDurationMillisecond, timerUPP, this, &theTimer); m_specific->create_pmap(width, height, &m_rbuf_window); m_initial_width = width; m_initial_height = height; on_init(); on_resize(width, height); m_specific->m_redraw_flag = true; ShowWindow (m_specific->m_window); SetPortWindowPort (m_specific->m_window); return true; }
bool LoadTexture(IplTexture *tex, const char *filename, const char *subdir) { ComponentInstance fileImporter; OSErr error; ImageDescriptionHandle imageInfo; ComponentResult err; CFStringRef name = CFStringCreateWithCStringNoCopy(NULL, filename, kCFStringEncodingASCII, NULL); CFStringRef _subdir = CFStringCreateWithCStringNoCopy(NULL, subdir, kCFStringEncodingASCII, NULL); CFURLRef texture_url = CFBundleCopyResourceURL( CFBundleGetMainBundle(), name, NULL, _subdir); // Create the data reference so we can get the file's graphics importer. Handle dataRef; OSType dataRefType; dataRef = NewHandle(sizeof(AliasHandle)); // The second parameter to QTNewDataReferenceFromCFURL is flags. // It should be set to 0. error = QTNewDataReferenceFromCFURL(texture_url, 0, &dataRef, &dataRefType); if(error != noErr) { //DisposeHandle(dataRef); //CFRelease(texture_url); return false; } // Get the importer for the file so we can read the information. error = GetGraphicsImporterForDataRef(dataRef, dataRefType, &fileImporter); // Retrieve information about the image imageInfo = (ImageDescriptionHandle)NewHandle(sizeof(ImageDescription)); err = GraphicsImportGetImageDescription(fileImporter, &imageInfo); unsigned width = ((**imageInfo).width); unsigned height = ((**imageInfo).height); IplImage *im = tex->getIm(); if (im && (im->width != width || im->height!=height)) cvReleaseImage(&im); if (im==0) { im = cvCreateImage(cvSize(width,height), IPL_DEPTH_8U, 4); //memset(im->imageData, 0x8f, 30*im->widthStep ); //memset(im->imageData+ 50*im->widthStep, 0xff, 30*im->widthStep); tex->setImage(im); //return true; } tex->update(); void *imageData = im->imageData; // Get the boundary rectangle of the image Rect imageRect; err = GraphicsImportGetNaturalBounds(fileImporter, &imageRect); // Create an offscreen buffer to hold the image. // Apparently QuickTime requires a GWorld to // decompress a texture file. long bytesPerRow = im->widthStep; //static GWorldPtr offscreenBuffer=0; if (offscreenBuffer==0) { error = QTNewGWorldFromPtr(&offscreenBuffer, k32RGBAPixelFormat, &imageRect, NULL, NULL, kNativeEndianPixMap, imageData, bytesPerRow); assert(error == noErr); } // Draw the image into the offscreen buffer err = GraphicsImportSetGWorld(fileImporter, offscreenBuffer, NULL); assert(err == noErr); err = GraphicsImportDraw(fileImporter); assert(err == noErr); // Cleanup error = CloseComponent(fileImporter); DisposeHandle((Handle)imageInfo); DisposeHandle(dataRef); DisposeGWorld(offscreenBuffer); return true; }