当前位置: 首页>>代码示例>>C++>>正文


C++ CFRetain函数代码示例

本文整理汇总了C++中CFRetain函数的典型用法代码示例。如果您正苦于以下问题:C++ CFRetain函数的具体用法?C++ CFRetain怎么用?C++ CFRetain使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了CFRetain函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: druProgressCallback

/*
	druProgressCallback
	
	DRNotificationCallback to handle burn or erase progress.
*/
void
druProgressCallback(DRNotificationCenterRef center,void *observer,CFStringRef name,DRTypeRef object,CFDictionaryRef taskStatus)
{
#pragma unused(center, name, object)
	druBurnStatus	*status = (druBurnStatus*)observer;
	CFStringRef		currentState = NULL;
	CFNumberRef		progressRef = NULL;
	CFNumberRef		currentTrackRef = NULL;
	float			progress = 0.0;
	int				currentTrack = 0;
	char			buffer[sizeof(status->stage)];
	
	/* Get information from the status dictionary. */
	currentState = CFDictionaryGetValue(taskStatus,kDRStatusStateKey);
	progressRef = CFDictionaryGetValue(taskStatus,kDRStatusPercentCompleteKey);
	currentTrackRef = CFDictionaryGetValue(taskStatus,kDRStatusCurrentTrackKey);
	
	/* Fetch values from CFNumbers. */
	if (progressRef != NULL)
		CFNumberGetValue(progressRef,kCFNumberFloatType,&progress);
	if (currentTrackRef != NULL)
		CFNumberGetValue(currentTrackRef,kCFNumberIntType,&currentTrack);
	
	/* Check to see if primary burn state has changed. (Preparing, Writing, Verifying, etc) */
	if (status->lastState == NULL ||
		!CFEqual(status->lastState,currentState) ||
		((currentTrackRef != NULL) && !CFEqual(status->lastTrack,currentTrackRef)))
	{
		/* Yes - did we have a previous state? */
		if (status->lastState != NULL)
		{
			/* Forget about the old state. */
			if (status->lastState) CFRelease(status->lastState);
			if (status->lastTrack) CFRelease(status->lastTrack);
		}
		
		/* If the burn was successful, stop the runloop. */
		if (CFEqual(currentState,kDRStatusStateDone))
		{
			status->completionStatus = (CFDictionaryRef)CFRetain(taskStatus);
			status->success = 1;
			CFRunLoopStop(CFRunLoopGetCurrent());
			return;
		}
		
		/* If the burn was unsuccessful, print a failure message (localized)
			and stop the runloop. */
		if (CFEqual(currentState,kDRStatusStateFailed))
		{
			status->completionStatus = (CFDictionaryRef)CFRetain(taskStatus);
			status->success = 0;
			CFRunLoopStop(CFRunLoopGetCurrent());
			return;
		}
		
		/* Remember the new state. */
		status->lastState = CFStringCreateCopy(NULL,currentState);
		if (currentTrackRef) status->lastTrack = CFRetain(currentTrackRef);
		
		/* Translate the stage into a user-visible string.
			
			We only display a few of the possible states - the others are
			brief and the user doesn't really care about them.
		*/
		buffer[0] = 0;
		if (CFEqual(currentState,kDRStatusStatePreparing))
		{
			if (currentTrack == 0)
				snprintf(buffer,sizeof(buffer),"Preparing...");
			else
				snprintf(buffer,sizeof(buffer),"Preparing track %d ...", currentTrack);
		}
		else if (CFEqual(currentState,kDRStatusStateTrackWrite))
		{
			if (currentTrack != 0)
				snprintf(buffer,sizeof(buffer),"Writing track %d ...", currentTrack);
		}
		else if (CFEqual(currentState,kDRStatusStateSessionClose) ||
				 CFEqual(currentState,kDRStatusStateTrackClose))
		{
			snprintf(buffer,sizeof(buffer),"Closing...");
		}
		else if (CFEqual(currentState,kDRStatusStateVerifying))
		{
			if (currentTrack != 0)
				snprintf(buffer,sizeof(buffer),"Verifying...");
		}
		else if (CFEqual(currentState,kDRStatusStateErasing))
		{
			snprintf(buffer,sizeof(buffer),"Erasing...");
		}
		
		/* Change the stage string - the progress bar will catch this. */
		if (buffer[0] != 0 && strcmp(status->stage,buffer))
			strncpy(status->stage, buffer, sizeof(status->stage));
//.........这里部分代码省略.........
开发者ID:fruitsamples,项目名称:audioburntest,代码行数:101,代码来源:dru_burning.c

示例2: CreateURLCFString

CFStringRef CreateURLCFString(CFStringRef Domain, CFStringRef Username,
                              CFStringRef Password, CFStringRef ServerName,
                              CFStringRef Path, CFStringRef PortNumber)
{
	CFMutableDictionaryRef mutableDict = NULL;
	int error;
	CFMutableStringRef urlString = NULL;
	
	mutableDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, 
											&kCFTypeDictionaryValueCallBacks);
	if (mutableDict == NULL) {
		smb_log_info("%s: CFDictionaryCreateMutable failed, syserr = %s", 
					 ASL_LEVEL_ERR, __FUNCTION__, strerror(errno));	
		return NULL;
	}
	
	if (Domain && Username) {
		CFMutableStringRef tempString = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, Domain);
		
		if (tempString) {
			CFStringAppend(tempString, CFSTR("\\"));
			CFStringAppend(tempString, Username);
			Username = tempString;
		}
        else {
			CFRetain(Username);
		}
	} else if (Username) {
		CFRetain(Username);
	}
    
	if (Username) {
		CFDictionarySetValue(mutableDict, kNetFSUserNameKey, Username);
		CFRelease(Username);
	}
    
	if (Password) {
		CFDictionarySetValue(mutableDict, kNetFSPasswordKey, Password);
	}
    
	if (ServerName) {
		CFDictionarySetValue(mutableDict, kNetFSHostKey, ServerName);
	}
    
	if (Path) {
		CFDictionarySetValue (mutableDict, kNetFSPathKey, Path);
	}
    
	if (PortNumber) {
		CFDictionarySetValue (mutableDict, kNetFSAlternatePortKey, PortNumber);
	}
    
	error = smb_dictionary_to_urlstring(mutableDict, &urlString);
	CFRelease(mutableDict);
    
	if (error) {
		errno = error;
	}
    
	return urlString;
}
开发者ID:aosm,项目名称:smb,代码行数:61,代码来源:parse_url.c

示例3: druPromptForDevice

/*
	druPromptForDevice
	
	Interactively asks the user to select a device from the devices which are
	currently attached.  If only one device is connected, the device is
	automatically chosen and nothing is printed.
	
	The optional filter function is called to filter devices.  If you wish to
	suppress a device, the filter function should return 0.
	
	The returned device is retained by this routine.
*/
DRDeviceRef
druPromptForDevice(char *promptString, druDeviceFilterProc filter)
{
	CFArrayRef	deviceList = DRCopyDeviceArray();
	CFIndex		deviceCount = CFArrayGetCount(deviceList);
	DRDeviceRef	device;
	CFIndex		selection;
	char		userInput[10];
	
	/* Can't proceed without at least one drive. */
	if (deviceCount == 0)
	{
		printf("Sorry, no CD/DVD drives were found.\n");
		exit(1);
	}
	
	/* Filter the list. */
	if (filter != NULL)
	{
		CFMutableArrayRef	filteredList = CFArrayCreateMutableCopy(NULL,0,deviceList);
		
		for (selection=deviceCount-1; selection>=0; --selection)
			if ((*filter)((DRDeviceRef)CFArrayGetValueAtIndex(filteredList,selection)) == 0)
				CFArrayRemoveValueAtIndex(filteredList,selection);
		
		CFRelease(deviceList);
		deviceList = filteredList;
		deviceCount = CFArrayGetCount(deviceList);
	}
	
	/* Can't proceed without at least one drive. */
	if (deviceCount == 0)
	{
		printf("Sorry, no eligible drives were found.\n");
		exit(1);
	}
	
	/* If there's only one device, which is actually true for many machines (those with
		an internal CD burner and no external burners attached) then the choice
		is obvious, and we don't need to display a menu. */
	if (deviceCount == 1)
	{
		device = (DRDeviceRef)CFArrayGetValueAtIndex(deviceList,0);
		CFRetain(device);
		CFRelease(deviceList);
		return device;
	}
	
	/* Display a menu of devices. */
	printf("Available devices:\n");
	druDisplayDeviceList(deviceList);
	
	/* Display the prompt. */
	if (promptString == NULL)
		promptString = "Please select a device:";
	printf("%s ", promptString);
	fflush(stdout);
	
	/* Get user input. */
	userInput[0] = 0;
	selection = atoi(fgets(userInput,sizeof(userInput),stdin)) - 1;
	if (selection < 0 || selection >= deviceCount)
	{
		printf("Aborted.\n");
		exit(1);
	}
	
	/* Return the selected device. */
	device = (DRDeviceRef)CFArrayGetValueAtIndex(deviceList,selection);
	CFRetain(device);
	CFRelease(deviceList);
	return device;
}
开发者ID:fruitsamples,项目名称:audioburntest,代码行数:85,代码来源:dru_devices.c

示例4: wxDockEventHandler

//-----------------------------------------------------------------------------
// wxDockEventHandler
//
// This is the global Mac/Carbon event handler for the dock.
// We need this for two reasons:
// 1) To handle wxTaskBarIcon menu events (see below for why)
// 2) To handle events from the dock when it requests a menu
//-----------------------------------------------------------------------------
pascal OSStatus
wxDockEventHandler(EventHandlerCallRef WXUNUSED(inHandlerCallRef),
                   EventRef inEvent,
                   void *pData)
{
    // Get the parameters we want from the event
    wxDockTaskBarIcon* pTB = (wxDockTaskBarIcon*) pData;
    const UInt32 eventClass = GetEventClass(inEvent);
    const UInt32 eventKind = GetEventKind(inEvent);

    OSStatus err = eventNotHandledErr;

    // Handle wxTaskBar menu events (note that this is a global event handler
    // so it will actually get called by all commands/menus)
    if ((eventClass == kEventClassCommand) && (eventKind == kEventCommandProcess || eventKind == kEventCommandUpdateStatus ))
    {
        // if we have no taskbar menu quickly pass it back to wxApp
        if (pTB->m_pMenu != NULL)
        {
            // This is the real reason why we need this. Normally menus
            // get handled in wxMacAppEventHandler
            // However, in the case of a taskbar menu call
            // command.menu.menuRef IS NULL!
            // Which causes the wxApp handler just to skip it.

            // get the HICommand from the event
            HICommand command;
            if (GetEventParameter(inEvent, kEventParamDirectObject,
                typeHICommand, NULL,sizeof(HICommand), NULL, &command ) == noErr)
            {
                // Obtain the REAL menuRef and the menuItemIndex in the real menuRef
                //
                // NOTE: menuRef is generally used here for submenus, as
                // GetMenuItemRefCon could give an incorrect wxMenuItem if we pass
                // just the top level wxTaskBar menu
                MenuItemIndex menuItemIndex;
                MenuRef menuRef;
                MenuRef taskbarMenuRef = MAC_WXHMENU(pTB->m_pMenu->GetHMenu());

                // the next command is only successful if it was a command from the taskbar menu
                // otherwise we pass it on
                if (GetIndMenuItemWithCommandID(taskbarMenuRef,command.commandID,
                    1, &menuRef, &menuItemIndex ) == noErr)
                {
                    wxMenu* itemMenu = wxFindMenuFromMacMenu( menuRef ) ;
                    int id = wxMacCommandToId( command.commandID ) ;
                    wxMenuItem *item = NULL;

                    if (id != 0) // get the wxMenuItem reference from the MenuRef
                        GetMenuItemRefCon( menuRef, menuItemIndex, (URefCon*) &item );

                    if (item && itemMenu )
                    {
                        if ( eventKind == kEventCommandProcess )
                        {
                            if ( itemMenu->HandleCommandProcess( item ) )
                                err = noErr;
                        }
                        else if ( eventKind == kEventCommandUpdateStatus )
                        {
                            if ( itemMenu->HandleCommandUpdateStatus( item ) )
                                err = noErr;
                        }
                    }
                }
            }
        } //end if noErr on getting HICommand from event
    }
    else if ((eventClass == kEventClassApplication) && (eventKind == kEventAppGetDockTileMenu ))
    {
        // process the right click events
        // NB: This may result in double or even triple-creation of the menus
        // We need to do this for 2.4 compat, however
        wxTaskBarIconEvent downevt(wxEVT_TASKBAR_RIGHT_DOWN, NULL);
        pTB->m_parent->ProcessEvent(downevt);

        wxTaskBarIconEvent upevt(wxEVT_TASKBAR_RIGHT_UP, NULL);
        pTB->m_parent->ProcessEvent(upevt);

        // create popup menu
        wxMenu* menu = pTB->DoCreatePopupMenu();

        if (menu != NULL)
        {
            // note to self - a MenuRef *is* a MenuHandle
            MenuRef hMenu = MAC_WXHMENU(menu->GetHMenu());

            // When SetEventParameter is called it will decrement
            // the reference count of the menu - we need to make
            // sure it stays around in the wxMenu class here
            CFRetain(hMenu);

//.........这里部分代码省略.........
开发者ID:vdm113,项目名称:wxWidgets-ICC-patch,代码行数:101,代码来源:taskbar.cpp

示例5: _CFCreateHomeDirectoryURLForUser

static CFURLRef _CFCreateHomeDirectoryURLForUser(CFStringRef uName) {
#if defined(__MACH__) || defined(__svr4__) || defined(__hpux__) || defined(__LINUX__) || defined(__FREEBSD__)
    if (!uName) {
        if (geteuid() != __CFEUID || getuid() != __CFUID || !__CFHomeDirectory)
            _CFUpdateUserInfo();
        if (__CFHomeDirectory) CFRetain(__CFHomeDirectory);
        return __CFHomeDirectory;
    } else {
        struct passwd *upwd = NULL;
        char buf[128], *user;
        SInt32 len = CFStringGetLength(uName), size = CFStringGetMaximumSizeForEncoding(len, kCFPlatformInterfaceStringEncoding);
        CFIndex usedSize;
        if (size < 127) {
            user = buf;
        } else {
            user = CFAllocatorAllocate(kCFAllocatorDefault, size+1, 0);
            if (__CFOASafe) __CFSetLastAllocationEventName(user, "CFUtilities (temp)");
        }
        if (CFStringGetBytes(uName, CFRangeMake(0, len), kCFPlatformInterfaceStringEncoding, 0, true, user, size, &usedSize) == len) {
            user[usedSize] = '\0';
            upwd = getpwnam(user);
        }
        if (buf != user) {
            CFAllocatorDeallocate(kCFAllocatorDefault, user);
        }
        return _CFCopyHomeDirURLForUser(upwd);
    }
#elif defined(__WIN32__)
#warning CF: Windows home directory goop disabled
    return NULL;
#if 0
    CFString *user = !uName ? CFUserName() : uName;

    if (!uName || CFEqual(user, CFUserName())) {
        const char *cpath = getenv("HOMEPATH");
        const char *cdrive = getenv("HOMEDRIVE");
        if (cdrive && cpath) {
            char fullPath[CFMaxPathSize];
            CFStringRef str;
            strcpy(fullPath, cdrive);
            strncat(fullPath, cpath, CFMaxPathSize-strlen(cdrive)-1);
            str = CFStringCreateWithCString(NULL, fullPath, kCFPlatformInterfaceStringEncoding);
            home = CFURLCreateWithFileSystemPath(NULL, str, kCFURLWindowsPathStyle, true);
            CFRelease(str);
        }
    }
    if (!home) {
        struct _USER_INFO_2 *userInfo;
        HINSTANCE hinstDll = GetModuleHandleA("NETAPI32");
        if (!hinstDll)
            hinstDll = LoadLibraryEx("NETAPI32", NULL, 0);
        if (hinstDll) {
            FARPROC lpfn = GetProcAddress(hinstDll, "NetUserGetInfo");
            if (lpfn) {
                unsigned namelen = CFStringGetLength(user);
                UniChar *username;
                username = CFAllocatorAllocate(kCFAllocatorDefault, sizeof(UniChar) * (namelen + 1), 0);
                if (__CFOASafe) __CFSetLastAllocationEventName(username, "CFUtilities (temp)");
                CFStringGetCharacters(user, CFRangeMake(0, namelen), username);
                if (!(*lpfn)(NULL, (LPWSTR)username, 2, (LPBYTE *)&userInfo)) {
                    UInt32 len = 0;
                    CFMutableStringRef str;
                    while (userInfo->usri2_home_dir[len] != 0) len ++;
                    str = CFStringCreateMutable(NULL, len+1);
                    CFStringAppendCharacters(str, userInfo->usri2_home_dir, len);
                    home = CFURLCreateWithFileSystemPath(NULL, str, kCFURLWindowsPathStyle, true);
                    CFRelease(str);
                }
                CFAllocatorDeallocate(kCFAllocatorDefault, username);
            }
        } else {
        }
    }
    // We could do more here (as in KB Article Q101507). If that article is to
    // be believed, we should only run into this case on Win95, or through
    // user error.
    if (CFStringGetLength(CFURLGetPath(home)) == 0) {
        CFRelease(home);
        home=NULL;
    }
#endif

#else
#error Dont know how to compute users home directories on this platform
#endif
}
开发者ID:0x4d52,项目名称:JavaScriptCore-X,代码行数:86,代码来源:CFPlatform.c

示例6: CreateNewMenu

void PopupMenu::createPlatformMenu()
{
   OSStatus err = CreateNewMenu( mData->tag, kMenuAttrAutoDisable,&(mData->mMenu));
   CFRetain(mData->mMenu);
   AssertFatal(err == noErr, "Could not create Carbon MenuRef");
}
开发者ID:03050903,项目名称:Torque3D,代码行数:6,代码来源:popupMenu.cpp

示例7: ScrollingTextViewHandler

/*----------------------------------------------------------------------------------------------------------*/
pascal OSStatus ScrollingTextViewHandler(EventHandlerCallRef inCaller, EventRef inEvent, void* inRefcon)
	{
	OSStatus result = eventNotHandledErr;
	ScrollingTextBoxData* myData = (ScrollingTextBoxData*)inRefcon;

	switch (GetEventClass(inEvent))
		{

		case kEventClassHIObject:
			switch (GetEventKind(inEvent))
				{
				case kEventHIObjectConstruct:
					{
					// allocate some instance data
					myData = (ScrollingTextBoxData*) calloc(1, sizeof(ScrollingTextBoxData));

					// get our superclass instance
					HIViewRef epView;
					GetEventParameter(inEvent, kEventParamHIObjectInstance, typeHIObjectRef, NULL, sizeof(epView), NULL, &epView);

					// remember our superclass in our instance data and initialize other fields
					myData->view = epView;

					// set the control ID so that we can find it later with HIViewFindByID
					result = SetControlID(myData->view, &kScrollingTextBoxViewID);

					// store our instance data into the event
					result = SetEventParameter(inEvent, kEventParamHIObjectInstance, typeVoidPtr, sizeof(myData), &myData);

					break;
					}

				case kEventHIObjectDestruct:
					{
					if (myData->theTimer != NULL) RemoveEventLoopTimer(myData->theTimer);
					CFRelease(myData->theText);
					free(myData);
					result = noErr;
					break;
					}

				case kEventHIObjectInitialize:
					{
					// always begin kEventHIObjectInitialize by calling through to the previous handler
					result = CallNextEventHandler(inCaller, inEvent);

					// if that succeeded, do our own initialization
					if (result == noErr)
						{
						GetEventParameter(inEvent, kEventParamScrollingText, typeCFStringRef, NULL, sizeof(myData->theText), NULL, &myData->theText);
						CFRetain(myData->theText);
						GetEventParameter(inEvent, kEventParamAutoScroll, typeBoolean, NULL, sizeof(myData->autoScroll), NULL, &myData->autoScroll);
						GetEventParameter(inEvent, kEventParamDelayBeforeAutoScroll, typeUInt32, NULL, sizeof(myData->delayBeforeAutoScroll), NULL, &myData->delayBeforeAutoScroll);
						GetEventParameter(inEvent, kEventParamDelayBetweenAutoScroll, typeUInt32, NULL, sizeof(myData->delayBetweenAutoScroll), NULL, &myData->delayBetweenAutoScroll);
						GetEventParameter(inEvent, kEventParamAutoScrollAmount, typeSInt16, NULL, sizeof(myData->autoScrollAmount), NULL, &myData->autoScrollAmount);
						myData->theTimer = NULL;
						}
					break;
					}

				default:
					break;
				}
			break;

		case kEventClassScrollable:
			switch (GetEventKind(inEvent))
				{
				case kEventScrollableGetInfo:
					{
					// we're being asked to return information about the scrolled view that we set as Event Parameters
					HISize imageSize = {50.0, myData->height};
					SetEventParameter(inEvent, kEventParamImageSize, typeHISize, sizeof(imageSize), &imageSize);
					HISize lineSize = {50.0, 20.0};
					SetEventParameter(inEvent, kEventParamLineSize, typeHISize, sizeof(lineSize), &lineSize);

					HIRect bounds;
					HIViewGetBounds(myData->view, &bounds);
					SetEventParameter(inEvent, kEventParamViewSize, typeHISize, sizeof(bounds.size), &bounds.size);
					SetEventParameter(inEvent, kEventParamOrigin, typeHIPoint, sizeof(myData->originPoint), &myData->originPoint);
					result = noErr;
					break;
					}

				case kEventScrollableScrollTo:
					{
					// we're being asked to scroll, we just do a sanity check and ask for a redraw
					HIPoint where;
					GetEventParameter(inEvent, kEventParamOrigin, typeHIPoint, NULL, sizeof(where), NULL, &where);

					HIViewSetNeedsDisplay(myData->view, true);

					myData->originPoint.y = (where.y < 0.0)?0.0:where.y;
					HIViewSetBoundsOrigin(myData->view, 0, myData->originPoint.y);

					break;
					}

				default:
//.........这里部分代码省略.........
开发者ID:0b1kn00b,项目名称:xcross,代码行数:101,代码来源:HIScrollingTextBox.c

示例8: WKCAImageQueueRetain

static CAImageQueueRef WKCAImageQueueRetain(CAImageQueueRef iq) 
{
    if (iq)
        return (CAImageQueueRef)CFRetain(iq);
    return 0;
}
开发者ID:1833183060,项目名称:wke,代码行数:6,代码来源:WKCAImageQueue.cpp

示例9: IOMasterPort

/*
  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 == nullptr)
        qDebug("IOServiceMatching returned a nullptr 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 == nullptr) {
        qDebug("IONotificationPortCreate return a nullptr IONotificationPortRef.");
        return false;
    }

    notificationRunLoopSource = IONotificationPortGetRunLoopSource(notificationPortRef);
    if (notificationRunLoopSource == nullptr) {
        qDebug("IONotificationPortGetRunLoopSource returned nullptr 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;
}
开发者ID:Antropovi,项目名称:qreal,代码行数:91,代码来源:qextserialenumerator_osx.cpp

示例10: __DAMountMapCreate1

static CFDictionaryRef __DAMountMapCreate1( CFAllocatorRef allocator, struct fstab * fs )
{
    CFMutableDictionaryRef map = NULL;

    if ( strcmp( fs->fs_type, FSTAB_SW ) )
    {
        char * idAsCString = fs->fs_spec;

        strsep( &idAsCString, "=" );

        if ( idAsCString )
        {
            CFStringRef idAsString;

            idAsString = CFStringCreateWithCString( kCFAllocatorDefault, idAsCString, kCFStringEncodingUTF8 );

            if ( idAsString )
            {
                CFTypeRef id = NULL;

                if ( strcmp( fs->fs_spec, "UUID" ) == 0 )
                {
                    id = ___CFUUIDCreateFromString( kCFAllocatorDefault, idAsString );
                }
                else if ( strcmp( fs->fs_spec, "LABEL" ) == 0 )
                {
                    id = CFRetain( idAsString );
                }
                else if ( strcmp( fs->fs_spec, "DEVICE" ) == 0 )
                {
                    id = ___CFDictionaryCreateFromXMLString( kCFAllocatorDefault, idAsString );
                }

                if ( id )
                {
                    map = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks );

                    if ( map )
                    {
                        CFMutableStringRef options;

                        options = CFStringCreateMutable( kCFAllocatorDefault, 0 );

                        if ( options )
                        {
                            char *       argument  = NULL;
                            char *       arguments = fs->fs_mntops;
                            CFBooleanRef automatic = NULL;

                            while ( ( argument = strsep( &arguments, "," ) ) )
                            {
                                if ( strcmp( argument, "auto" ) == 0 )
                                {
                                    automatic = kCFBooleanTrue;
                                }
                                else if ( strcmp( argument, "noauto" ) == 0 )
                                {
                                    automatic = kCFBooleanFalse;
                                }
                                else
                                {
                                    CFStringAppendCString( options, argument, kCFStringEncodingUTF8 );    
                                    CFStringAppendCString( options, ",", kCFStringEncodingUTF8 );
                                }
                            }

                            if ( automatic )
                            {
                                CFDictionarySetValue( map, kDAMountMapMountAutomaticKey, automatic );
                            }

                            if ( CFStringGetLength( options ) )
                            {
                                CFStringTrim( options, CFSTR( "," ) );

                                CFDictionarySetValue( map, kDAMountMapMountOptionsKey, options );
                            }

                            CFRelease( options );
                        }

                        if ( strcmp( fs->fs_file, "none" ) )
                        {
                            CFURLRef path;

                            path = CFURLCreateFromFileSystemRepresentation( kCFAllocatorDefault, ( void * ) fs->fs_file, strlen( fs->fs_file ), TRUE );

                            if ( path )
                            {
                                CFDictionarySetValue( map, kDAMountMapMountPathKey, path );

                                CFRelease( path );
                            }
                        }

                        if ( strcmp( fs->fs_vfstype, "auto" ) )
                        {
                            CFStringRef kind;

                            kind = CFStringCreateWithCString( kCFAllocatorDefault, fs->fs_vfstype, kCFStringEncodingUTF8 );
//.........这里部分代码省略.........
开发者ID:carriercomm,项目名称:osx-2,代码行数:101,代码来源:DASupport.c

示例11: _CFCopyExtensionForAbstractType

__private_extern__ CFStringRef _CFCopyExtensionForAbstractType(CFStringRef abstractType) {
    return (abstractType ? CFRetain(abstractType) : NULL);
}
开发者ID:0x4d52,项目名称:JavaScriptCore-X,代码行数:3,代码来源:CFFileUtilities.c

示例12: TSICTStringCreateWithNumberAndFormat

TStringIRep* TSICTStringCreateWithNumberAndFormat(CFNumberRef number, TSITStringFormat format)
{
    CFRetain(number);
    TSITStringTag tag = kTSITStringTagNumber;
    CFDataRef data;
    CFNumberType numType = CFNumberGetType(number);

    switch(numType) {
        case kCFNumberCharType:
        {
            int value;
            if (CFNumberGetValue(number, kCFNumberIntType, &value)) {
                if (value == 0 || value == 1) {
                    tag = kTSITStringTagBool;
                } else {
                    tag = kTSITStringTagString;
                }
            }
            break;
        }
        case kCFNumberFloat32Type:
        case kCFNumberFloat64Type:
        case kCFNumberFloatType:
        case kCFNumberDoubleType:
        {
            tag = kTSITStringTagFloat;
            break;
        }
    }

    if (tag == kTSITStringTagBool) {
        bool value;
        CFNumberGetValue(number, kCFNumberIntType, &value);
        if (value) {
            data = CFDataCreate(kCFAllocatorDefault, (UInt8*)"true", 4);
        } else {
            data = CFDataCreate(kCFAllocatorDefault, (UInt8*)"false", 5);
        }
    } else if (tag == kTSITStringTagFloat) {
        char buf[32];
        char *p, *e;
        double value;

        CFNumberGetValue(number, numType, &value);
        sprintf(buf, "%#.15g", value);

        e = buf + strlen(buf);
        p = e;
        while (p[-1]=='0' && ('0' <= p[-2] && p[-2] <= '9')) {
            p--;
        }
        memmove(p, e, strlen(e)+1);

        data = CFDataCreate(kCFAllocatorDefault, (UInt8*)buf, (CFIndex)strlen(buf));
    } else {
        char buf[32];
        SInt64 value;
        CFNumberGetValue(number, numType, &value);
        sprintf(buf, "%lli", value);
        data = CFDataCreate(kCFAllocatorDefault, (UInt8*)buf, (CFIndex)strlen(buf));
    }

    TStringIRep* rep = TSICTStringCreateWithDataOfTypeAndFormat(data, tag, format);
    CFRelease(data);
    CFRelease(number);
    return rep;
}
开发者ID:4justinstewart,项目名称:Polity,代码行数:67,代码来源:TSICTString.c

示例13: __DAStagePeek

static void __DAStagePeek( DADiskRef disk )
{
    /*
     * We commence the "peek" stage if the conditions are right.
     */

    CFMutableArrayRef candidates;

    candidates = CFArrayCreateMutable( kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks );

    if ( candidates )
    {
        DASessionRef session;
        CFArrayRef   sessionList;
        CFIndex      sessionListCount;
        CFIndex      sessionListIndex;

        sessionList      = gDASessionList;
        sessionListCount = CFArrayGetCount( sessionList );

        for ( sessionListIndex = 0; sessionListIndex < sessionListCount; sessionListIndex++ )
        {
            DACallbackRef callback;
            CFArrayRef    callbackList;
            CFIndex       callbackListCount;
            CFIndex       callbackListIndex;
            
            session = ( void * ) CFArrayGetValueAtIndex( sessionList, sessionListIndex );

            callbackList      = DASessionGetCallbackRegister( session );
            callbackListCount = CFArrayGetCount( callbackList );

            for ( callbackListIndex = 0; callbackListIndex < callbackListCount; callbackListIndex++ )
            {
                callback = ( void * ) CFArrayGetValueAtIndex( callbackList, callbackListIndex );

                if ( DACallbackGetKind( callback ) == _kDADiskPeekCallback )
                {
                    CFArrayAppendValue( candidates, callback );
                }
            }
        }

        CFArraySortValues( candidates, CFRangeMake( 0, CFArrayGetCount( candidates ) ), __DAStagePeekCompare, NULL );

        /*
         * Commence the peek.
         */

        CFRetain( disk );

        DADiskSetContext( disk, candidates );

        DADiskSetState( disk, kDADiskStateStagedPeek, TRUE );

        DADiskSetState( disk, kDADiskStateCommandActive, TRUE );

        __DAStagePeekCallback( NULL, disk );

        CFRelease( candidates );
    }
}
开发者ID:alexzhang2015,项目名称:osx-10.9,代码行数:62,代码来源:DAStage.c

示例14:

//_____________________________________________________________________________
//
void	AUElement::SetName (CFStringRef inName) 
{ 
	if (mElementName) CFRelease (mElementName);
	mElementName = inName; 
	if (mElementName) CFRetain (mElementName);
}
开发者ID:AdamDiment,项目名称:CocoaSampleCode,代码行数:8,代码来源:AUScopeElement.cpp

示例15: SCPreferencesCreateWithOptions

SCPreferencesRef
SCPreferencesCreateWithOptions(CFAllocatorRef	allocator,
			       CFStringRef	name,
			       CFStringRef	prefsID,
			       AuthorizationRef	authorization,
			       CFDictionaryRef	options)
{
	CFDataRef			authorizationData	= NULL;
	SCPreferencesPrivateRef		prefsPrivate;

	if (options != NULL) {
		if (!isA_CFDictionary(options)) {
			_SCErrorSet(kSCStatusInvalidArgument);
			return NULL;
		}
	}

	if (authorization != NULL) {
		CFMutableDictionaryRef	authorizationDict;
		CFBundleRef		bundle;
		CFStringRef		bundleID	= NULL;

		authorizationDict =  CFDictionaryCreateMutable(NULL,
							       0,
							       &kCFTypeDictionaryKeyCallBacks,
							       &kCFTypeDictionaryValueCallBacks);
#if	!TARGET_OS_IPHONE
		if (authorization != kSCPreferencesUseEntitlementAuthorization) {
			CFDataRef			data;
			AuthorizationExternalForm	extForm;
			OSStatus			os_status;

			os_status = AuthorizationMakeExternalForm(authorization, &extForm);
			if (os_status != errAuthorizationSuccess) {
				SCLog(TRUE, LOG_INFO, CFSTR("_SCHelperOpen AuthorizationMakeExternalForm() failed"));
				_SCErrorSet(kSCStatusInvalidArgument);
				CFRelease(authorizationDict);
				return NULL;
			}

			data = CFDataCreate(NULL, (const UInt8 *)extForm.bytes, sizeof(extForm.bytes));
			CFDictionaryAddValue(authorizationDict,
					     kSCHelperAuthAuthorization,
					     data);
			CFRelease(data);
		}
#endif

		/* get the application/executable/bundle name */
		bundle = CFBundleGetMainBundle();
		if (bundle != NULL) {
			bundleID = CFBundleGetIdentifier(bundle);
			if (bundleID != NULL) {
				CFRetain(bundleID);
			} else {
				CFURLRef	url;

				url = CFBundleCopyExecutableURL(bundle);
				if (url != NULL) {
					bundleID = CFURLCopyPath(url);
					CFRelease(url);
				}
			}

			if (bundleID != NULL) {
				if (CFEqual(bundleID, CFSTR("/"))) {
					CFRelease(bundleID);
					bundleID = NULL;
				}
			}
		}
		if (bundleID == NULL) {
			bundleID = CFStringCreateWithFormat(NULL, NULL, CFSTR("Unknown(%d)"), getpid());
		}
		CFDictionaryAddValue(authorizationDict,
				     kSCHelperAuthCallerInfo,
				     bundleID);
		CFRelease(bundleID);

		if (authorizationDict != NULL) {
			_SCSerialize((CFPropertyListRef)authorizationDict,
				     &authorizationData,
				     NULL,
				     NULL);
			CFRelease(authorizationDict);
		}
	}

	prefsPrivate = __SCPreferencesCreate(allocator, name, prefsID, authorizationData, options);
	if (authorizationData != NULL) CFRelease(authorizationData);

	return (SCPreferencesRef)prefsPrivate;
}
开发者ID:010001111,项目名称:darling,代码行数:93,代码来源:SCPOpen.c


注:本文中的CFRetain函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。