static OSStatus CreateCFArrayFromAEDescList(
	const AEDescList *	descList, 
	CFArrayRef *		itemsPtr
)
	// This routine's input is an AEDescList that contains replies 
	// from the "properties of every login item" event.  Each element 
	// of the list is an AERecord with two important properties, 
	// "path" and "hidden".  This routine creates a CFArray that 
	// corresponds to this list.  Each element of the CFArray 
	// contains two properties, kLIAEURL and 
	// kLIAEHidden, that are derived from the corresponding 
	// AERecord properties.
	//
	// On entry, descList must not be NULL
	// On entry,  itemsPtr must not be NULL
	// On entry, *itemsPtr must be NULL
	// On success, *itemsPtr will be a valid CFArray
	// On error, *itemsPtr will be NULL
{
	OSStatus			err;
	CFMutableArrayRef	result;
	long				itemCount;
	long				itemIndex;
	AEKeyword			junkKeyword;
	DescType			junkType;
	Size				junkSize;
	
	assert( itemsPtr != NULL);
	assert(*itemsPtr == NULL);

	result = NULL;
	
	// Create a place for the result.
	
    err = noErr;
    result = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    if (result == NULL) {
        err = coreFoundationUnknownErr;
    }
	
	// For each element in the descriptor list...
	
	if (err == noErr) {
		err = AECountItems(descList, &itemCount);
	}
	if (err == noErr) {
		for (itemIndex = 1; itemIndex <= itemCount; itemIndex++) {
		  if (itemIndex == 4) {
			  int notused = 0;
				notused++;
			}
			AERecord 			thisItem;
			UInt8 				thisPath[1024];
			Size				thisPathSize;
			FSRef				thisItemRef;
			CFURLRef			thisItemURL;
			Boolean				thisItemHidden;
			CFDictionaryRef		thisItemDict;
			
			thisItem = kAENull;
			thisItemURL = NULL;
			thisItemDict = NULL;
			
			// Get this element's AERecord.
			
			err = AEGetNthDesc(descList, itemIndex, typeAERecord, &junkKeyword, &thisItem);

			if (err != noErr) {
			  err = noErr;
				continue;
			}

			// Extract the path and create a CFURL.

			if (err == noErr) {
				err = AEGetKeyPtr(
					&thisItem, 
					propPath, 
					typeUTF8Text, 
					&junkType, 
					thisPath, 
					sizeof(thisPath) - 1, 		// to ensure that we can always add null terminator
					&thisPathSize
				);
			}
			
			if (err == noErr) {
				thisPath[thisPathSize] = 0;
				
				err = FSPathMakeRef(thisPath, &thisItemRef, NULL);
				
				if (err == noErr) {
					thisItemURL = CFURLCreateFromFSRef(NULL, &thisItemRef);
				} else {
					err = noErr;			// swallow error and create an imprecise URL
					
					thisItemURL = CFURLCreateFromFileSystemRepresentation(
						NULL,
						thisPath,
						thisPathSize,
						false
					);
				}
				if (thisItemURL == NULL) {
					err = coreFoundationUnknownErr;
				}
			}
			
			// Extract the hidden flag.
			
			if (err == noErr) {
				err = AEGetKeyPtr(
					&thisItem, 
					propHidden, 
					typeBoolean, 
					&junkType, 
					&thisItemHidden, 
					sizeof(thisItemHidden),
					&junkSize
				);
                
                // Work around <rdar://problem/4052117> by assuming that hidden 
                // is false if we can't get its value.
                
                if (err != noErr) {
                    thisItemHidden = false;
                    err = noErr;
                }
			}

			// Create the CFDictionary for this item.
			
			if (err == noErr) {
				CFStringRef keys[2];
				CFTypeRef	values[2];
				
				keys[0] = kLIAEURL;
				keys[1] = kLIAEHidden;
				
				values[0] = thisItemURL;
				values[1] = (thisItemHidden ? kCFBooleanTrue : kCFBooleanFalse);

				thisItemDict = CFDictionaryCreate(
					NULL,
					(const void **) keys,
					values,
					2,
					&kCFTypeDictionaryKeyCallBacks,
					&kCFTypeDictionaryValueCallBacks
				);
				if (thisItemDict == NULL) {
					err = coreFoundationUnknownErr;
				}
			}
			
			// Add it to the results array.
			
			if (err == noErr) {
				CFArrayAppendValue(result, thisItemDict);
			}
						
			AEDisposeDescQ(&thisItem);
			CFQRelease(thisItemURL);
			CFQRelease(thisItemDict);
						
			if (err != noErr) {
				break;
			}
		}
	}

	// Clean up.
	
	if (err != noErr) {
		CFQRelease(result);
		result = NULL;
	}
	*itemsPtr = result;
	assert( (err == noErr) == (*itemsPtr != NULL) );

	return err;
}
CFURLRef GetOpenDialogForUser(kDialogType type, char* title, char* message)
{
	NavDialogCreationOptions dialogOptions;
	NavDialogRef dialog = NULL;
	NavReplyRecord replyRecord;
	CFURLRef fileAsCFURLRef = NULL;
	FSRef fileAsFSRef;
	OSStatus status;
	
	CFAllocatorRef alloc_default = kCFAllocatorDefault;  // = NULL;

	// Get the standard set of defaults
	status = NavGetDefaultDialogCreationOptions(&dialogOptions);
	require_noerr( status, CantGetNavOptions );

	dialogOptions.optionFlags = kNavNoTypePopup + kNavSupportPackages + kNavAllowOpenPackages;


	if (title != NULL) {
		CFStringRef cftitle = CFStringCreateWithCString(alloc_default,title,kCFStringEncodingMacRoman);
		dialogOptions.windowTitle = cftitle;
	}

	if (message != NULL) {
		CFStringRef cfmessage = CFStringCreateWithCString(alloc_default,message,kCFStringEncodingMacRoman);
		dialogOptions.message = cfmessage;
	}


	// Make the window app-wide modal
	dialogOptions.modality = kWindowModalityAppModal;

	// Create the dialog
	if (type == kDialogFile) {
		status = NavCreateGetFileDialog(&dialogOptions, NULL, NULL, NULL, NULL, NULL, &dialog);
	} else if (type == kDialogFolder) {
		status = NavCreateChooseFolderDialog(&dialogOptions, NULL, NULL, NULL, &dialog);
	}
	require_noerr( status, CantCreateDialog );

	// Show it
	status = NavDialogRun(dialog);
	require_noerr( status, CantRunDialog );

	// Get the reply
	status = NavDialogGetReply(dialog, &replyRecord);
	require( ((status == noErr) || (status == userCanceledErr)), CantGetReply );

	// If the user clicked "Cancel", just bail
	if ( status == userCanceledErr ) goto UserCanceled;

	// Get the file
	status = AEGetNthPtr(&(replyRecord.selection), 1, typeFSRef, NULL, NULL, &fileAsFSRef, sizeof(FSRef), NULL);
	require_noerr( status, CantExtractFSRef );

	// Convert it to a CFURL
	fileAsCFURLRef = CFURLCreateFromFSRef(NULL, &fileAsFSRef);

	// Cleanup
CantExtractFSRef:
UserCanceled:
	verify_noerr( NavDisposeReply(&replyRecord) );
CantGetReply:
CantRunDialog:
	NavDialogDispose(dialog);
CantCreateDialog:
CantGetNavOptions:
    return fileAsCFURLRef;
}
ofFileDialogResult ofFileSaveDialog(string defaultName, string messageName){
	
	ofFileDialogResult results;
	
	//----------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------       OSX
	//----------------------------------------------------------------------------------------
#ifdef TARGET_OSX
	
	short fRefNumOut;
	FSRef output_file;
	OSStatus err;
	
	NavDialogCreationOptions options;
	NavGetDefaultDialogCreationOptions( &options );
	
	options.optionFlags = kNavNoTypePopup + kNavSupportPackages + kNavAllowOpenPackages;
	options.modality = kWindowModalityAppModal;
	
	options.optionFlags = kNavDefaultNavDlogOptions;
	options.message = CFStringCreateWithCString(NULL, messageName.c_str(), kCFStringEncodingASCII);;
	options.saveFileName = CFStringCreateWithCString(NULL, defaultName.c_str(), kCFStringEncodingASCII);
	NavDialogRef dialog;
	
	err = NavCreatePutFileDialog(&options, '.mov', 'Moov', NULL, NULL, &dialog);
	
	//printf("NavCreatePutFileDialog returned %i\n", err );
	
	err = NavDialogRun(dialog);
	//printf("NavDialogRun returned %i\n", err );
	
	NavUserAction action;
	action = NavDialogGetUserAction( dialog );
	//printf("got action %i\n", action);
	if (action == kNavUserActionNone || action == kNavUserActionCancel) {
		
		return results;
	}
	
	// get dialog reply
	NavReplyRecord reply;
	err = NavDialogGetReply(dialog, &reply);
	if ( err != noErr )
		return results;
	
	if ( reply.replacing )
	{
		printf("need to replace\n");
	}
	
	AEKeyword keyword;
	DescType actual_type;
	Size actual_size;
	FSRef output_dir;
	err = AEGetNthPtr(&(reply.selection), 1, typeFSRef, &keyword, &actual_type,
					  &output_dir, sizeof(output_file), &actual_size);
	
	//printf("AEGetNthPtr returned %i\n", err );
	
	
	CFURLRef cfUrl = CFURLCreateFromFSRef( kCFAllocatorDefault, &output_dir );
	CFStringRef cfString = NULL;
	if ( cfUrl != NULL )
	{
		cfString = CFURLCopyFileSystemPath( cfUrl, kCFURLPOSIXPathStyle );
		CFRelease( cfUrl );
	}
	
	// copy from a CFString into a local c string (http://www.carbondev.com/site/?page=CStrings+)
	const int kBufferSize = 255;
	
	char folderURL[kBufferSize];
	Boolean bool1 = CFStringGetCString(cfString,folderURL,kBufferSize,kCFStringEncodingMacRoman);
	
	char fileName[kBufferSize];
	Boolean bool2 = CFStringGetCString(reply.saveFileName,fileName,kBufferSize,kCFStringEncodingMacRoman);
	
	// append strings together
	
	string url1 = folderURL;
	string url2 = fileName;
	string finalURL = url1 + "/" + url2;
	
	results.filePath = finalURL.c_str();
	
	//printf("url %s\n", finalURL.c_str());
	
	// cleanup dialog
	NavDialogDispose(dialog);
	
#endif
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------
	
	//----------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------   windoze
	//----------------------------------------------------------------------------------------
#ifdef TARGET_WIN32
	
	
	wchar_t fileName[MAX_PATH] = L"";
	char * extension;
	OPENFILENAME ofn;
    memset(&ofn, 0, sizeof(OPENFILENAME));
	ofn.lStructSize = sizeof(OPENFILENAME);
	HWND hwnd = WindowFromDC(wglGetCurrentDC());
	ofn.hwndOwner = hwnd;
	ofn.hInstance = GetModuleHandle(0);
	ofn.nMaxFileTitle = 31;
	ofn.lpstrFile = fileName;
	ofn.nMaxFile = MAX_PATH;
	ofn.lpstrFilter = _T("All Files (*.*)\0*.*\0");
	ofn.lpstrDefExt = _T("");	// we could do .rxml here?
	ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY;
	ofn.lpstrTitle = _T("Select Output File");

	if (GetSaveFileName(&ofn)){
		results.filePath = convertWideToNarrow(fileName);
	}

#endif
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------


	//----------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------   linux
	//----------------------------------------------------------------------------------------
#if defined( TARGET_LINUX ) && defined (OF_USING_GTK)

	gtkFileDialog(GTK_FILE_CHOOSER_ACTION_SAVE, messageName,defaultName);

#endif
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------
	//----------------------------------------------------------------------------------------

	if( results.filePath.length() > 0 ){
		results.bSuccess = true;
		results.fileName = ofFileUtils::getFilenameFromPath(results.filePath);		
	}
	
	return results;	
}
Пример #4
0
static pascal OSStatus MultiCartEventHandler (EventHandlerCallRef inHandlerRef, EventRef inEvent, void *inUserData)
{
	OSStatus	err, result = eventNotHandledErr;
	WindowRef	window = (WindowRef) inUserData;
	static int	index = -1;

	switch (GetEventClass(inEvent))
	{
		case kEventClassCommand:
		{
			switch (GetEventKind(inEvent))
			{
				HICommand	tHICommand;

				case kEventCommandUpdateStatus:
				{
					err = GetEventParameter(inEvent, kEventParamDirectObject, typeHICommand, NULL, sizeof(HICommand), NULL, &tHICommand);
					if (err == noErr && tHICommand.commandID == 'clos')
					{
						UpdateMenuCommandStatus(false);
						result = noErr;
					}

					break;
				}

				case kEventCommandProcess:
				{
					err = GetEventParameter(inEvent, kEventParamDirectObject, typeHICommand, NULL, sizeof(HICommand), NULL, &tHICommand);
					if (err == noErr)
					{
						HIViewRef	ctl, root;
						HIViewID	cid;
						FSRef		ref;
						bool8		r;

						root = HIViewGetRoot(window);

						switch (tHICommand.commandID)
						{
							case 'Cho0':
							case 'Cho1':
							{
								index = (tHICommand.commandID & 0xFF) - '0';
								r = NavBeginOpenROMImageSheet(window, NULL);
								result = noErr;
								break;
							}

							case 'NvDn':
							{
								r = NavEndOpenROMImageSheet(&ref);
								if (r)
								{
									CFStringRef	str;
									CFURLRef	url;

									url = CFURLCreateFromFSRef(kCFAllocatorDefault, &ref);
									str = CFURLCopyLastPathComponent(url);
									cid.signature = 'MNAM';
									cid.id = index;
									HIViewFindByID(root, cid, &ctl);
									SetStaticTextCFString(ctl, str, true);
									CFRelease(str);
									str = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
									if (multiCartPath[index])
										CFRelease(multiCartPath[index]);
									multiCartPath[index] = str;
									CFRelease(url);
								}

								index = -1;
								result = noErr;
								break;
							}

							case 'Cle0':
							case 'Cle1':
							{
								index = (tHICommand.commandID & 0xFF) - '0';
								cid.signature = 'MNAM';
								cid.id = index;
								HIViewFindByID(root, cid, &ctl);
								SetStaticTextCFString(ctl, CFSTR(""), true);
								if (multiCartPath[index])
								{
									CFRelease(multiCartPath[index]);
									multiCartPath[index] = NULL;
								}

								index = -1;
								result = noErr;
								break;
							}

							case 'SWAP':
							{
								CFStringRef	str;
								CFURLRef	url;

								str = multiCartPath[0];
								multiCartPath[0] = multiCartPath[1];
								multiCartPath[1] = str;

								cid.signature = 'MNAM';

								for (int i = 0; i < 2; i++)
								{
									cid.id = i;
									HIViewFindByID(root, cid, &ctl);

									if (multiCartPath[i])
									{
										url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, multiCartPath[i], kCFURLPOSIXPathStyle, false);
										str = CFURLCopyLastPathComponent(url);
										SetStaticTextCFString(ctl, str, true);
										CFRelease(str);
										CFRelease(url);
									}
									else
										SetStaticTextCFString(ctl, CFSTR(""), true);
								}

								result = noErr;
								break;
							}

							case 'ok  ':
							{
								QuitAppModalLoopForWindow(window);
								multiCartDialogResult = true;
								result = noErr;
								break;
							}

							case 'not!':
							{
								QuitAppModalLoopForWindow(window);
								multiCartDialogResult = false;
								result = noErr;
								break;
							}
						}
					}
				}
			}
		}
	}

	return (result);
}
Пример #5
0
static OSStatus DoFSRefSave(const OurSaveDialogData *dialogDataP, 
                                    NavReplyRecord* reply, AEDesc *actualDescP)
{
    OSStatus 	err = noErr;
    FSRef 	fileRefParent;
	    
    if ((err = AEGetDescData( actualDescP, &fileRefParent, sizeof( FSRef ) )) == noErr )
    {
        // get the name data and its length:	
        HFSUniStr255	nameBuffer;
        UniCharCount 	sourceLength = 0;
        
        sourceLength = (UniCharCount)CFStringGetLength( reply->saveFileName );
        
        CFStringGetCharacters( reply->saveFileName, CFRangeMake( 0, sourceLength ), 
                                                        (UniChar*)&nameBuffer.unicode );
        
        if ( sourceLength > 0 )
        {	
            if ( reply->replacing )
            {
                // delete the file we are replacing:
                FSRef fileToDelete;
                if ((err = FSMakeFSRefUnicode( &fileRefParent, sourceLength, nameBuffer.unicode, 
                                    kTextEncodingUnicodeDefault, &fileToDelete )) == noErr )
                {
                    err = FSDeleteObject( &fileToDelete );
                    if ( err == fBsyErr ){
                        DoErrorAlert(fBsyErr, kMyDeleteErrorFormatStrKey);
                    }
                }
            }
                            
            if ( err == noErr )
            {
                // create the file based on Unicode, but we can write the file's data with an FSSpec:
                FSSpec newFileSpec;

                // get the FSSpec back so we can write the file's data
                if ((err = FSCreateFileUnicode( &fileRefParent, sourceLength, 
                                                    nameBuffer.unicode,
                                                    kFSCatInfoNone,
                                                    NULL,
                                                    NULL,	
                                                    &newFileSpec)) == noErr)
                {
                    FInfo fileInfo;
                    fileInfo.fdType = kFileTypePDF;
                    fileInfo.fdCreator = kFileCreator;
                    err = FSpSetFInfo( &newFileSpec, &fileInfo );
                    // now that we have the FSSpec, we can proceed with the save operation:
                    if(!err){
                        FSRef fsRef;
                        err = FSpMakeFSRef(&newFileSpec, &fsRef);	// make an FSRef
                        if(!err){
                            CFURLRef saveURL = CFURLCreateFromFSRef(NULL, &fsRef);
                            if(saveURL){
                                // delete the file we just made for making the FSRef
                                err = FSpDelete(&newFileSpec);	
                                if(!err)
                                    err = MakePDFDocument(dialogDataP->parentWindow, 
                                                            dialogDataP->documentDataP, 
                                                            saveURL);
                                if(!err)
                                    err = NavCompleteSave( reply, kNavTranslateInPlace );
                                
                                if(err){
                                    // an error ocurred saving the file, so delete the copy 
                                    // left over:
                                    (void)FSpDelete( &newFileSpec );
                                    DoErrorAlert(err, kMyWriteErrorFormatStrKey);
                                }
                                CFRelease(saveURL);
                            }else{
                                // delete the file we just made for making the FSRe
                               (void)FSpDelete(&newFileSpec);
                                err = kCantCreateSaveURL;
                                DoErrorAlert(err, kMyCreateURLErrorFormatStrKey);
                            }
                        }
                    }
                }
            }
        }
    }
    return err;
}
Пример #6
0
/*!
    \internal

    Returns the canonicalized form of \a path (i.e., with all symlinks
    resolved, and all redundant path elements removed.
*/
QString QFSFileEnginePrivate::canonicalized(const QString &path)
{
    if (path.isEmpty())
        return path;

    // FIXME let's see if this stuff works, then we might be able to remove some of the other code.
#if defined(Q_OS_UNIX) && !defined(Q_OS_SYMBIAN)
    if (path.size() == 1 && path.at(0) == QLatin1Char('/'))
        return path;
#endif
#if defined(Q_OS_LINUX) || defined(Q_OS_SYMBIAN) || defined(Q_OS_MAC)
    // ... but Linux with uClibc does not have it
#if !defined(__UCLIBC__)
    char *ret = 0;
#if defined(Q_OS_MAC) && !defined(Q_OS_IPHONE)
    // Mac OS X 10.5.x doesn't support the realpath(X,0) extension we use here.
    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_6) {
        ret = realpath(path.toLocal8Bit().constData(), (char*)0);
    } else {
        // on 10.5 we can use FSRef to resolve the file path.
        FSRef fsref;
        if (FSPathMakeRef((const UInt8 *)QDir::cleanPath(path).toUtf8().data(), &fsref, 0) == noErr) {
            CFURLRef urlref = CFURLCreateFromFSRef(NULL, &fsref);
            CFStringRef canonicalPath = CFURLCopyFileSystemPath(urlref, kCFURLPOSIXPathStyle);
            QString ret = QCFString::toQString(canonicalPath);
            CFRelease(canonicalPath);
            CFRelease(urlref);
            return ret;
        }
    }
#else
    ret = realpath(path.toLocal8Bit().constData(), (char*)0);
#endif
    if (ret) {
        QString canonicalPath = QDir::cleanPath(QString::fromLocal8Bit(ret));
        free(ret);
        return canonicalPath;
    }
#endif
#endif

    QFileInfo fi;
    const QChar slash(QLatin1Char('/'));
    QString tmpPath = path;
    int separatorPos = 0;
    QSet<QString> nonSymlinks;
    QSet<QString> known;

    known.insert(path);
    do {
#ifdef Q_OS_WIN
        // UNC, skip past the first two elements
        if (separatorPos == 0 && tmpPath.startsWith(QLatin1String("//")))
            separatorPos = tmpPath.indexOf(slash, 2);
        if (separatorPos != -1)
#endif
        separatorPos = tmpPath.indexOf(slash, separatorPos + 1);
        QString prefix = separatorPos == -1 ? tmpPath : tmpPath.left(separatorPos);
        if (
#ifdef Q_OS_SYMBIAN
            // Symbian doesn't support directory symlinks, so do not check for link unless we
            // are handling the last path element. This not only slightly improves performance,
            // but also saves us from lot of unnecessary platform security check failures
            // when dealing with files under *:/private directories.
            separatorPos == -1 &&
#endif
            !nonSymlinks.contains(prefix)) {
            fi.setFile(prefix);
            if (fi.isSymLink()) {
                QString target = fi.symLinkTarget();
                if (separatorPos != -1) {
                    if (fi.isDir() && !target.endsWith(slash))
                        target.append(slash);
                    target.append(tmpPath.mid(separatorPos));
                }
                tmpPath = QDir::cleanPath(target);
                separatorPos = 0;

                if (known.contains(tmpPath))
                    return QString();
                known.insert(tmpPath);
            } else {
                nonSymlinks.insert(prefix);
            }
        }
    } while (separatorPos != -1);

    return QDir::cleanPath(tmpPath);
}
Пример #7
0
//---------------------------------------------------------------------
// Gets a file to save from the user. Caller must release the CFURLRef.
//
CFURLRef GetSaveFileFromUser(WindowRef window)
{
	CFURLRef previousFile;
	CFStringRef saveFileName;
	UniChar *chars = NULL;
    CFIndex length;
	NavDialogCreationOptions dialogOptions;
	NavDialogRef dialog;
	NavReplyRecord replyRecord;
	CFURLRef fileAsCFURLRef = NULL;
	FSRef fileAsFSRef;
	FSRef parentDirectory;
	OSStatus status;

	if ( window == NULL ) return NULL;

	// Get the standard set of defaults
	status = NavGetDefaultDialogCreationOptions(&dialogOptions);
	require_noerr( status, CantGetNavOptions );

	// Change a few things (app-wide modal, show the extension)
	dialogOptions.modality = kWindowModalityAppModal;
	dialogOptions.parentWindow = window;
	dialogOptions.optionFlags = kNavDefaultNavDlogOptions | kNavPreserveSaveFileExtension;

	// Set up the default save name
	previousFile = GetWindowProxyFileCFURL(window);
	if (previousFile == NULL)
		dialogOptions.saveFileName = CFStringCreateWithCString(NULL, "Untitled.rtf", kCFStringEncodingASCII);
	else	
		dialogOptions.saveFileName = CFURLCopyLastPathComponent(previousFile);

	// Create the dialog
	status = NavCreatePutFileDialog(&dialogOptions, kUnknownType, kUnknownType, NULL, NULL, &dialog);
	require_noerr( status, CantCreateDialog );

	// Show it
	status = NavDialogRun(dialog);
	require_noerr( status, CantRunDialog );
	
	// Get the reply
	status = NavDialogGetReply(dialog, &replyRecord);
	require( ((status == noErr) || (status == userCanceledErr)), CantGetReply );

	// If the user clicked "Cancel", just bail
	if ( status == userCanceledErr ) goto UserCanceled;

	// Get the file's location and name
	status = AEGetNthPtr(&(replyRecord.selection), 1, typeFSRef, NULL, NULL, &parentDirectory, sizeof(FSRef), NULL);
	require_noerr( status, CantExtractFSRef );

	saveFileName = replyRecord.saveFileName;
    length = CFStringGetLength(saveFileName);
	chars = malloc(length * sizeof(UniChar));
	CFStringGetCharacters(saveFileName, CFRangeMake(0, length), chars);

    // If we are replacing a file, erase the previous one
    if ( replyRecord.replacing ) {

		status = FSMakeFSRefUnicode(&parentDirectory, length, chars, kTextEncodingUnknown, &fileAsFSRef);
		require_noerr( status, CantMakeFSRef );

        status = FSDeleteObject(&fileAsFSRef);
		require_noerr( status, CantDeletePreviousFile );
    }

    // Create the file
	status = FSCreateFileUnicode(&parentDirectory, length, chars, kFSCatInfoNone, NULL, &fileAsFSRef, NULL);
	require_noerr( status, CantCreateSaveFile );

	// Convert the reference to the file to a CFURL
	fileAsCFURLRef = CFURLCreateFromFSRef(NULL, &fileAsFSRef);

	// Cleanup
CantCreateSaveFile:
CantDeletePreviousFile:
CantMakeFSRef:
	if ( chars != NULL ) free(chars);
CantExtractFSRef:
UserCanceled:
	verify_noerr( NavDisposeReply(&replyRecord) );
CantGetReply:
CantRunDialog:
	NavDialogDispose(dialog);
CantCreateDialog:
	if (previousFile) CFRelease(previousFile);
	CFRelease(dialogOptions.saveFileName);
CantGetNavOptions:
    return fileAsCFURLRef;
}
Пример #8
0
// This routine's input is an AEDescList that contains replies
// from the "properties of every login item" event.  Each element
// of the list is an AERecord with two important properties,
// "path" and "hidden".  This routine creates a CFArray that
// corresponds to this list.  Each element of the CFArray
// contains two properties, kLIAEURL and
// kLIAEHidden, that are derived from the corresponding
// AERecord properties.
//
// On entry, descList must not be NULL
// On entry,  itemsPtr must not be NULL
// On entry, *itemsPtr must be NULL
// On success, *itemsPtr will be a valid CFArray
// On error, *itemsPtr will be NULL
static OSStatus CreateCFArrayFromAEDescList(const AEDescList *descList, CFArrayRef *itemsPtr) {
  if (!descList || !itemsPtr) return paramErr;
  check(*itemsPtr == NULL);

  // Create a place for the result.
  OSStatus err = noErr;
  CFMutableArrayRef result = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  if (result == NULL)
    err = coreFoundationUnknownErr;

  // For each element in the descriptor list...
  long itemCount;
  if (err == noErr)
    err = AECountItems(descList, &itemCount);

  if (err == noErr) {
    for (long itemIndex = 1; itemIndex <= itemCount; itemIndex++) {
      UInt8 thisPath[1024];
      Size thisPathSize;
      FSRef thisItemRef;
      CFURLRef thisItemURL;
      Boolean thisItemHidden;
      CFDictionaryRef thisItemDict;
      AERecord thisItem = WBAEEmptyDesc();

      thisItemURL = NULL;
      thisItemDict = NULL;

      // Get this element's AERecord.
      AEKeyword junkKeyword;
      err = AEGetNthDesc(descList, itemIndex, typeAERecord, &junkKeyword, &thisItem);

      // Extract the path and create a CFURL.
      if (err == noErr) {
        err = AEGetKeyPtr(&thisItem,
                          propPath, typeUTF8Text,
                          NULL, thisPath,
                          sizeof(thisPath) - 1, 		// to ensure that we can always add null terminator
                          &thisPathSize);
      }
      if (err == noErr) {
        thisPath[thisPathSize] = 0;
        /* resolve symlink */
        err = FSPathMakeRef(thisPath, &thisItemRef, NULL);

        if (err == noErr) {
          thisItemURL = CFURLCreateFromFSRef(NULL, &thisItemRef);
        } else {
          err = noErr;			// swallow error and create an imprecise URL

          thisItemURL = CFURLCreateFromFileSystemRepresentation(NULL,
                                                                thisPath,
                                                                thisPathSize,
                                                                false);
        }
        if (thisItemURL == NULL) {
          err = coreFoundationUnknownErr;
        }
      }

      // Extract the hidden flag.
      if (err == noErr) {
        err = AEGetKeyPtr(&thisItem,
                          propHidden, typeBoolean,
                          NULL, &thisItemHidden,
                          sizeof(thisItemHidden), NULL);

        // Work around <rdar://problem/4052117> by assuming that hidden
        // is false if we can't get its value.
        if (err != noErr) {
          thisItemHidden = false;
          err = noErr;
        }
      }

      // Create the CFDictionary for this item.
      if (err == noErr) {
        CFStringRef keys[2];
        CFTypeRef values[2];

        keys[0] = kWBLoginItemURL;
        keys[1] = kWBLoginItemHidden;

        values[0] = thisItemURL;
        values[1] = (thisItemHidden ? kCFBooleanTrue : kCFBooleanFalse);

        thisItemDict = CFDictionaryCreate(kCFAllocatorDefault,
                                          (const void **) keys, values, 2,
                                          &kCFTypeDictionaryKeyCallBacks,
                                          &kCFTypeDictionaryValueCallBacks);
        if (thisItemDict == NULL) {
          err = coreFoundationUnknownErr;
        }
      }

      // Add it to the results array.
      if (err == noErr) {
        CFArrayAppendValue(result, thisItemDict);
      }

      WBAEDisposeDesc(&thisItem);
      if (thisItemURL) CFRelease(thisItemURL);
      if (thisItemDict) CFRelease(thisItemDict);

      if (err != noErr) {
        break;
      }
    }
  }

  // Clean up.
  if (err != noErr) {
    if (result) CFRelease(result);
    result = NULL;
  }
  *itemsPtr = result;
  check( (err == noErr) == (*itemsPtr != NULL) );

  return err;
}
//static
QFileSystemEntry QFileSystemEngine::canonicalName(const QFileSystemEntry &entry, QFileSystemMetaData &data)
{
    if (entry.isEmpty() || entry.isRoot())
        return entry;

#if !defined(Q_OS_MAC) && !defined(Q_OS_QNX) && !defined(Q_OS_ANDROID) && _POSIX_VERSION < 200809L
    // realpath(X,0) is not supported
    Q_UNUSED(data);
    return QFileSystemEntry(slowCanonicalized(absoluteName(entry).filePath()));
#else
    char *ret = 0;
# if defined(Q_OS_MACX)
    // When using -mmacosx-version-min=10.4, we get the legacy realpath implementation,
    // which does not work properly with the realpath(X,0) form. See QTBUG-28282.
    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_6) {
        ret = (char*)malloc(PATH_MAX + 1);
        if (ret && realpath(entry.nativeFilePath().constData(), (char*)ret) == 0) {
            const int savedErrno = errno; // errno is checked below, and free() might change it
            free(ret);
            errno = savedErrno;
            ret = 0;
        }
    } else {
        // on 10.5 we can use FSRef to resolve the file path.
        QString path = QDir::cleanPath(entry.filePath());
        FSRef fsref;
        if (FSPathMakeRef((const UInt8 *)path.toUtf8().data(), &fsref, 0) == noErr) {
            CFURLRef urlref = CFURLCreateFromFSRef(NULL, &fsref);
            CFStringRef canonicalPath = CFURLCopyFileSystemPath(urlref, kCFURLPOSIXPathStyle);
            QString ret = QCFString::toQString(canonicalPath);
            CFRelease(canonicalPath);
            CFRelease(urlref);
            return QFileSystemEntry(ret);
        }
    }
# else
#  if _POSIX_VERSION >= 200801L
    ret = realpath(entry.nativeFilePath().constData(), (char*)0);
#  else
    ret = (char*)malloc(PATH_MAX + 1);
    if (realpath(entry.nativeFilePath().constData(), (char*)ret) == 0) {
        const int savedErrno = errno; // errno is checked below, and free() might change it
        free(ret);
        errno = savedErrno;
        ret = 0;
    }
#  endif
# endif
    if (ret) {
        data.knownFlagsMask |= QFileSystemMetaData::ExistsAttribute;
        data.entryFlags |= QFileSystemMetaData::ExistsAttribute;
        QString canonicalPath = QDir::cleanPath(QString::fromLocal8Bit(ret));
        free(ret);
        return QFileSystemEntry(canonicalPath);
    } else if (errno == ENOENT) { // file doesn't exist
        data.knownFlagsMask |= QFileSystemMetaData::ExistsAttribute;
        data.entryFlags &= ~(QFileSystemMetaData::ExistsAttribute);
        return QFileSystemEntry();
    }
    return entry;
#endif
}
Пример #10
0
OSStatus CheckLogoutRequirement(int *finalAction)
{
    char                    path[MAXPATHLEN];
    FSRef                   infoPlistFileRef;
    Boolean                 isDirectory, result;
    CFURLRef                xmlURL = NULL;
    CFDataRef               xmlDataIn = NULL;
    CFPropertyListRef       propertyListRef = NULL;
    CFStringRef             restartKey = CFSTR("IFPkgFlagRestartAction");
    CFStringRef             currentValue = NULL;
//    CFStringRef             valueRestartRequired = CFSTR("RequiredRestart");
    CFStringRef             valueLogoutRequired = CFSTR("RequiredLogout");
    CFStringRef             valueNoRestart = CFSTR("NoRestart");
    CFStringRef             errorString = NULL;
    OSStatus                err = noErr;
#ifdef SANDBOX
    char                    *p;
    group                   *grp = NULL;
    int                     i;
    Boolean                 isMember = false;
#endif  // SANDBOX
    
    *finalAction = restartRequired;

    if (OSVersion < 0x1040) {
        return noErr;   // Always require restart on OS 10.3.9
    }
    
#ifdef SANDBOX
    grp = getgrnam("boinc_master");
    if (loginName && grp) {
        i = 0;
        while ((p = grp->gr_mem[i]) != NULL) {   // Step through all users in group boinc_master
            if (strcmp(p, loginName) == 0) {
                isMember = true;                // Logged in user is a member of group boinc_master
                break;
            }
        ++i;
        }
    }

    if (!isMember && !currentUserCanRunBOINC) {
        *finalAction = nothingrequired;
        return noErr;
    }
#endif  // SANDBOX
    
    getcwd(path, sizeof(path));
    strlcat(path, "/Contents/Info.plist", sizeof(path));

    err = FSPathMakeRef((UInt8*)path, &infoPlistFileRef, &isDirectory);
    if (err)
        return err;
        
    xmlURL = CFURLCreateFromFSRef(NULL, &infoPlistFileRef);
    if (xmlURL == NULL)
        return -1;

    // Read XML Data from file
    result = CFURLCreateDataAndPropertiesFromResource(NULL, xmlURL, &xmlDataIn, NULL, NULL, &err);
    if (err == noErr)
        if (!result)
            err = coreFoundationUnknownErr;
	
    if (err == noErr) { // Convert XML Data to internal CFPropertyListRef / CFDictionaryRef format
        propertyListRef = CFPropertyListCreateFromXMLData(NULL, xmlDataIn, kCFPropertyListMutableContainersAndLeaves, &errorString);
        if (propertyListRef == NULL)
            err = coreFoundationUnknownErr;
    }
    
    if (err == noErr) { // Get current value for our key
        currentValue = (CFStringRef)CFDictionaryGetValue((CFDictionaryRef)propertyListRef, restartKey);
        if (currentValue == NULL)
            err = coreFoundationUnknownErr;
    }    
    
    if (err == noErr) {
        if (CFStringCompare(currentValue, valueLogoutRequired, 0) == kCFCompareEqualTo)
            *finalAction = logoutRequired;
        else if (CFStringCompare(currentValue, valueNoRestart, 0) == kCFCompareEqualTo)
            *finalAction = launchWhenDone;
    }
   
    if (xmlURL)
        CFRelease(xmlURL);
    if (xmlDataIn)
        CFRelease(xmlDataIn);
    if (propertyListRef)
        CFRelease(propertyListRef);

    return err;
}
Пример #11
0
static pascal OSStatus PreferencesEventHandler (EventHandlerCallRef inHandlerRef, EventRef inEvent, void *inUserData)
{
	OSStatus	err, result = eventNotHandledErr;
	WindowRef	tWindowRef = (WindowRef) inUserData;

	switch (GetEventClass(inEvent))
	{
		case kEventClassWindow:
		{
			switch (GetEventKind(inEvent))
			{
				case kEventWindowClose:
				{
					QuitAppModalLoopForWindow(tWindowRef);
					result = noErr;
					break;
				}
			}

			break;
		}

		case kEventClassCommand:
		{
			switch (GetEventKind(inEvent))
			{
				HICommand	tHICommand;

				case kEventCommandUpdateStatus:
				{
					err = GetEventParameter(inEvent, kEventParamDirectObject, typeHICommand, NULL, sizeof(HICommand), NULL, &tHICommand);
					if (err == noErr && tHICommand.commandID == 'clos')
					{
						UpdateMenuCommandStatus(true);
						result = noErr;
					}

					break;
				}

				case kEventCommandProcess:
				{
					HIViewRef	ctl, root;
					HIViewID	cid;
					SInt32		value;
					FSRef		ref;
					bool8		r;

					root = HIViewGetRoot(tWindowRef);

					err = GetEventParameter(inEvent, kEventParamDirectObject, typeHICommand, NULL, sizeof(HICommand), NULL, &tHICommand);
					if (err == noErr)
					{
						switch (tHICommand.commandID)
						{
							case 'S_EF':
							{
								HideWindow(tWindowRef);
								ConfigureSoundEffects();
								ShowWindow(tWindowRef);

								result = noErr;
								break;
							}

							case 'G_FL':
							{
								if (systemVersion >= 0x1040)
								{
									HideWindow(tWindowRef);
									ConfigureCoreImageFilter();
									ShowWindow(tWindowRef);
								}

								result = noErr;
								break;
							}

							case 'G__7':
							{
								cid.signature = 'grap';
								cid.id = iNibGGLStretch;
								HIViewFindByID(root, cid, &ctl);
								value = GetControl32BitValue(ctl);

								cid.id = iNibGAspectRatio;
								HIViewFindByID(root, cid, &ctl);
								if (value)
									ActivateControl(ctl);
								else
									DeactivateControl(ctl);

								result = noErr;
								break;
							}

							case 'G_13':
							{
								cid.signature = 'grap';
								cid.id = iNibGScreenCurvature;
								HIViewFindByID(root, cid, &ctl);
								value = GetControl32BitValue(ctl);

								cid.id = iNibGCurvatureWarp;
								HIViewFindByID(root, cid, &ctl);
								if (value)
									ActivateControl(ctl);
								else
									DeactivateControl(ctl);

								result = noErr;
								break;
							}

							case 'S__3':
							{
								cid.signature = 'snd_';
								cid.id = iNibSStereo;
								HIViewFindByID(root, cid, &ctl);
								value = GetControl32BitValue(ctl);

								cid.id = iNibSReverseStereo;
								HIViewFindByID(root, cid, &ctl);
								if (value)
									ActivateControl(ctl);
								else
									DeactivateControl(ctl);

								result = noErr;
								break;
							}

							case 'F_FL':
							{
								UInt32	modifierkey;

								err = GetEventParameter(inEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(UInt32), NULL, &modifierkey);
								if (err == noErr)
								{
									if (modifierkey & optionKey)
									{
										CFStringRef	str;
										MenuRef		menu;

										str = CFCopyLocalizedString(CFSTR("NoneSelected"), "NoneSelected");

										cid.signature = 'othe';
										cid.id = iNibOSaveFolder;
										HIViewFindByID(root, cid, &ctl);
										SetControl32BitValue(ctl, 3);
										err = GetControlData(ctl, kControlMenuPart, kControlPopupButtonMenuRefTag, sizeof(MenuRef), &menu, NULL);
										err = SetMenuItemTextWithCFString(menu, iNibSaveFolderNameMenuItem, str);
										DisableMenuItem(menu, iNibSaveFolderNameMenuItem);
										HIViewSetNeedsDisplay(ctl, true);

										CFRelease(str);

										if (saveFolderPath)
											CFRelease(saveFolderPath);
										saveFolderPath = NULL;
									}
									else
										r = NavBeginChooseFolderSheet(tWindowRef);
								}

								result = noErr;
								break;
							}

							case 'NvDn':
							{
								r = NavEndChooseFolderSheet(&ref);
								if (r)
								{
									CFStringRef	str;
									CFURLRef	url;
									MenuRef		menu;

									url = CFURLCreateFromFSRef(kCFAllocatorDefault, &ref);
									str = CFURLCopyLastPathComponent(url);

									cid.signature = 'othe';
									cid.id = iNibOSaveFolder;
									HIViewFindByID(root, cid, &ctl);
									SetControl32BitValue(ctl, iNibSaveFolderNameMenuItem);
									err = GetControlData(ctl, kControlMenuPart, kControlPopupButtonMenuRefTag, sizeof(MenuRef), &menu, NULL);
									err = SetMenuItemTextWithCFString(menu, iNibSaveFolderNameMenuItem, str);
									EnableMenuItem(menu, iNibSaveFolderNameMenuItem);
									HIViewSetNeedsDisplay(ctl, true);

									CFRelease(str);

									str = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
									if (saveFolderPath)
										CFRelease(saveFolderPath);
									saveFolderPath = str;

									CFRelease(url);
								}

								result = noErr;
								break;
							}
						}
					}

					break;
				}
			}

			break;
		}
	}

	return (result);
}
Пример #12
0
URL_TYPE createURLByMakingDirectoryAtURLWithName(URL_TYPE parent, STRING_TYPE name) {
	CFURLRef newDirectory = NULL;

	CFAllocatorRef allocator = parent ? CFGetAllocator(parent) : name ? CFGetAllocator(name) : kCFAllocatorDefault;

	if (parent) parent = CFRetain(parent);
	else {
		char *cwdBytes = alloca(PATH_MAX);
		getcwd(cwdBytes, PATH_MAX);
		parent = CFURLCreateFromFileSystemRepresentation(allocator, (const unsigned char *)cwdBytes, strlen(cwdBytes), /*isDirectory*/ true);
		if (!name) {
			newDirectory = parent;
			goto end;
		}
	}
	if (!parent)
		NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: parent directory URL is NULL (please tell the Growl developers)\n"), parent);
	else {
		if (name)
			name = CFRetain(name);
		else {
			name = CFURLCopyLastPathComponent(parent);
			CFURLRef newParent = CFURLCreateCopyDeletingLastPathComponent(allocator, parent);
			CFRelease(parent);
			parent = newParent;
		}

		if (!name)
			NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: name of directory to create is NULL (please tell the Growl developers)\n"), parent);
		else {
			FSRef parentRef;
			if (!CFURLGetFSRef(parent, &parentRef))
				NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: could not create FSRef for parent directory at %@ (please tell the Growl developers)\n"), parent);
			else {
				FSRef newDirectoryRef;

				struct HFSUniStr255 nameUnicode;
				CFIndex nameLength = CFStringGetLength(name);
				CFRange range = { 0, (nameLength < USHRT_MAX ? nameLength : USHRT_MAX) };
				CFStringGetCharacters(name, range, nameUnicode.unicode);
				nameUnicode.length = range.length;

				struct FSRefParam refPB = {
					.ref              = &parentRef,
					.nameLength       = nameUnicode.length,
					.name             = nameUnicode.unicode,
					.whichInfo        = kFSCatInfoNone,
					.catInfo          = NULL,
					.textEncodingHint = kTextEncodingUnknown,
					.newRef           = &newDirectoryRef,
				};
				
				OSStatus err = PBCreateDirectoryUnicodeSync(&refPB);
				if (err == dupFNErr) {
					//dupFNErr == file (or folder) exists already. this is fine.
					err = PBMakeFSRefUnicodeSync(&refPB);
				}
				if (err == noErr) {
					NSLog(CFSTR("PBCreateDirectoryUnicodeSync or PBMakeFSRefUnicodeSync returned %li; calling CFURLCreateFromFSRef"), (long)err); //XXX
					newDirectory = CFURLCreateFromFSRef(allocator, &newDirectoryRef);
					NSLog(CFSTR("CFURLCreateFromFSRef returned %@"), newDirectory); //XXX
				} else
					NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: could not create directory '%@' in parent directory at %@: FSCreateDirectoryUnicode returned %li (please tell the Growl developers)"), name, parent, (long)err);
			}

			CFRelease(parent);
		} //if (name)
		CFRelease(name);
	} //if (parent)

end:
	return newDirectory;
}

#ifndef COPYFORK_BUFSIZE
#	define COPYFORK_BUFSIZE 5242880U /*5 MiB*/
#endif

static OSStatus copyFork(const struct HFSUniStr255 *forkName, const FSRef *srcFile, const FSRef *destDir, const struct HFSUniStr255 *destName, FSRef *outDestFile) {
	OSStatus err, closeErr;
	struct FSForkIOParam srcPB = {
		.ref = srcFile,
		.forkNameLength = forkName->length,
		.forkName = forkName->unicode,
		.permissions = fsRdPerm,
	};
	unsigned char debuggingPathBuf[PATH_MAX] = "";
	OSStatus debuggingPathErr;

	err = PBOpenForkSync(&srcPB);
	if (err != noErr) {
		debuggingPathErr = FSRefMakePath(srcFile, debuggingPathBuf, PATH_MAX);
		if (debuggingPathErr != noErr)
			snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr);
		NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBOpenForkSync (source: %s) returned %li"), debuggingPathBuf, (long)err);
	} else {
		FSRef destFile;

		/*the first thing to do is get the name of the destination file, if one
		 *	wasn't provided.
		 *and while we're at it, we get the catalogue info as well.
		 */
		struct FSCatalogInfo catInfo;
		struct FSRefParam refPB = {
			.ref       = srcFile,
			.whichInfo = kFSCatInfoGettableInfo & kFSCatInfoSettableInfo,
			.catInfo   = &catInfo,
			.spec      = NULL,
			.parentRef = NULL,
			.outName   = destName ? NULL : (struct HFSUniStr255 *)(destName = alloca(sizeof(struct HFSUniStr255))),
		};

		err = PBGetCatalogInfoSync(&refPB);
		if (err != noErr) {
			debuggingPathErr = FSRefMakePath(srcFile, debuggingPathBuf, PATH_MAX);
			if (debuggingPathErr != noErr)
				snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr);
			NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBGetCatalogInfoSync (source: %s) returned %li"), debuggingPathBuf, (long)err);
		} else {
			refPB.ref              = destDir;
			refPB.nameLength       = destName->length;
			refPB.name             = destName->unicode;
			refPB.textEncodingHint = kTextEncodingUnknown;
			refPB.newRef           = &destFile;

			const char *functionName = "PBMakeFSRefUnicodeSync"; //for error-reporting message

			err = PBMakeFSRefUnicodeSync(&refPB);
			if ((err != noErr) && (err != fnfErr)) {
			handleMakeFSRefError:
				debuggingPathErr = FSRefMakePath(destDir, debuggingPathBuf, PATH_MAX);
				if (debuggingPathErr != noErr)
					snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for destination directory: FSRefMakePath returned %li)", (long)debuggingPathErr);

				//get filename too
				CFStringRef debuggingFilename = CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
																				   destName->unicode,
																				   destName->length,
																				   /*contentsDeallocator*/ kCFAllocatorNull);
				if (!debuggingFilename)
					debuggingFilename = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, "(could not get filename for destination file: CFStringCreateWithCharactersNoCopy returned NULL)", kCFStringEncodingASCII, /*contentsDeallocator*/ kCFAllocatorNull);

				NSLog(CFSTR("in copyFork in CFGrowlAdditions: %s (destination: %s/%@) returned %li"), functionName, debuggingPathBuf, debuggingFilename, (long)err);

				if (debuggingFilename) CFRelease(debuggingFilename);
			} else {
				//that file doesn't exist in that folder; create it.
				err = PBCreateFileUnicodeSync(&refPB);
				if (err == noErr) {
					/*make sure the Finder knows about the new file.
					 *FNNotify returns a status code too, but this isn't an
					 *	essential step, so we just ignore it.
					 */
					FNNotify(destDir, kFNDirectoryModifiedMessage, kNilOptions);
				} else if (err == dupFNErr) {
					/*dupFNErr: the file already exists.
					 *we can safely ignore this error.
					 */
					err = noErr;
				} else {
					functionName = "PBCreateFileUnicodeSync";
					goto handleMakeFSRefError;
				}
			}
		}
		if (err == noErr) {
			if (outDestFile)
				memcpy(outDestFile, &destFile, sizeof(destFile));

			struct FSForkIOParam destPB = {
				.ref            = &destFile,
				.forkNameLength = forkName->length,
				.forkName       = forkName->unicode,
				.permissions    = fsWrPerm,
			};
			err = PBOpenForkSync(&destPB);
			NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBOpenForkSync (dest) returned %li"), (long)err);
			if (err != noErr) {
				debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
				if (debuggingPathErr != noErr)
					snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for dest file: FSRefMakePath returned %li)", (long)debuggingPathErr);
				NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBOpenForkSync (destination: %s) returned %li"), debuggingPathBuf, (long)err);
			} else {
				void *buf = malloc(COPYFORK_BUFSIZE);
				if (buf) {
					srcPB.buffer = destPB.buffer = buf;
					srcPB.requestCount = COPYFORK_BUFSIZE;
					while (err == noErr) {
						err = PBReadForkSync(&srcPB);
						if (err == eofErr) {
							err = noErr;
							if (srcPB.actualCount == 0)
								break;
						}
						if (err != noErr) {
							debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
							if (debuggingPathErr != noErr)
								snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr);
							NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBReadForkSync (source: %s) returned %li"), debuggingPathBuf, (long)err);
						} else {
							destPB.requestCount = srcPB.actualCount;
							err = PBWriteForkSync(&destPB);
							if (err != noErr) {
								debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
								if (debuggingPathErr != noErr)
									snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for dest file: FSRefMakePath returned %li)", (long)debuggingPathErr);
								NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBWriteForkSync (destination: %s) returned %li"), debuggingPathBuf, (long)err);
							}
						}
					}

					free(buf);
				}

				closeErr = PBCloseForkSync(&destPB);
				if (closeErr != noErr) {
					debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
					if (debuggingPathErr != noErr)
						snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for dest file: FSRefMakePath returned %li)", (long)debuggingPathErr);
					NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBCloseForkSync (destination: %s) returned %li"), debuggingPathBuf, (long)err);
				}
				if (err == noErr) err = closeErr;
			}
		}

		closeErr = PBCloseForkSync(&srcPB);
		if (closeErr != noErr) {
			debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
			if (debuggingPathErr != noErr)
				snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr);
			NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBCloseForkSync (source: %s) returned %li"), debuggingPathBuf, (long)err);
		}
		if (err == noErr) err = closeErr;
	}

	return err;
}

static OSStatus GrowlCopyObjectSync(const FSRef *fileRef, const FSRef *destRef, FSRef *destFileRef) {
	OSStatus err;
	struct HFSUniStr255 forkName;
	struct FSForkIOParam forkPB = {
		.ref = fileRef,
		.forkIterator = {
			.initialize = 0L
		},
		.outForkName = &forkName,
	};
	
	do {
		err = PBIterateForksSync(&forkPB);
		NSLog(CFSTR("PBIterateForksSync returned %li"), (long)err);
		if (err != noErr) {
			if (err != errFSNoMoreItems)
				NSLog(CFSTR("in GrowlCopyObjectSync in CFGrowlAdditions: PBIterateForksSync returned %li"), (long)err);
		} else {
			err = copyFork(&forkName, fileRef, destRef, /*destName*/ NULL, /*outDestFile*/ destFileRef);
			//copyFork prints its own error messages
		}
	} while (err == noErr);
	if (err == errFSNoMoreItems) err = noErr;

	return err;
}

CFURLRef createURLByCopyingFileFromURLToDirectoryURL(CFURLRef file, CFURLRef dest) {
	CFURLRef destFileURL = NULL;

	FSRef fileRef, destRef, destFileRef;
	Boolean gotFileRef = CFURLGetFSRef(file, &fileRef);
	Boolean gotDestRef = CFURLGetFSRef(dest, &destRef);
	if (!gotFileRef)
		NSLog(CFSTR("in createURLByCopyingFileFromURLToDirectoryURL in CFGrowlAdditions: CFURLGetFSRef failed with source URL %@"), file);
	else if (!gotDestRef)
		NSLog(CFSTR("in createURLByCopyingFileFromURLToDirectoryURL in CFGrowlAdditions: CFURLGetFSRef failed with destination URL %@"), dest);
	else {
		OSStatus err;

		/*
		 * 10.2 has a problem with weak symbols in frameworks so we use
		 * MAC_OS_X_VERSION_MIN_REQUIRED >= 10.3.
		 */
#if defined(NSAppKitVersionNumber10_3) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3
		if (FSCopyObjectSync) {
			err = FSCopyObjectSync(&fileRef, &destRef, /*destName*/ NULL, &destFileRef, kFSFileOperationOverwrite);
		} else {
#endif
			err = GrowlCopyObjectSync(&fileRef, &destRef, &destFileRef);
#if defined(NSAppKitVersionNumber10_3) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3
		}
#endif

		if (err == noErr)
			destFileURL = CFURLCreateFromFSRef(kCFAllocatorDefault, &destFileRef);
		else
			NSLog(CFSTR("in createURLByCopyingFileFromURLToDirectoryURL in CFGrowlAdditions: CopyObjectSync returned %li for source URL %@"), (long)err, file);
	}

	return destFileURL;
}
Пример #13
0
//-----------------------------------------------------------------------------
FILE* openFileDialog (const char* fileName, int dialogType, void* dataRef)
{																			//zz-osx debug
	FILE* filePtr = NULL;
	
	NavDialogCreationOptions dialogOptions;
	NavDialogRef dialog;
	NavReplyRecord replyRecord;
	CFURLRef fileAsCFURLRef = NULL;
	FSRef fileAsFSRef;
	OSStatus status;
	bool result = false;
	
	unsigned char filePath[1024];
	char msg[4096];
	
	// Get the standard set of defaults
	status = NavGetDefaultDialogCreationOptions (&dialogOptions);
	require_noerr( status, CantGetNavOptions );
	
	// Make the	window app-wide modal
	dialogOptions.modality = kWindowModalityAppModal;
	
	//	dialogOptions.location = fileName;
	
	// Create the dialog
	status = NavCreateGetFileDialog (&dialogOptions, NULL, NULL, NULL, NULL, NULL, &dialog);
	require_noerr( status, CantCreateDialog );
	
	// Show it
	status = NavDialogRun (dialog);
	require_noerr( status, CantRunDialog );
	
	// Get the reply
	status = NavDialogGetReply (dialog, &replyRecord);
	require( ((status == noErr) || (status == userCanceledErr)), CantGetReply );
	
	// If the user clicked "Cancel", just bail
	if ( status == userCanceledErr ) goto UserCanceled;
	
	// Get the file
	status = AEGetNthPtr ( &(replyRecord.selection), 1, typeFSRef, NULL, NULL, &fileAsFSRef, sizeof(FSRef), NULL);
	require_noerr( status, CantExtractFSRef );
	
	// Convert it to a CFURL
	fileAsCFURLRef = CFURLCreateFromFSRef(NULL, &fileAsFSRef);
	
	result = CFURLGetFileSystemRepresentation(fileAsCFURLRef, true, filePath, 1024);
	
	if (!result)
		npPostMsg("err 9824 - cannot convert file dialog path", kNPmsgErr, dataRef);
	else
	{
		// printf ("\nFile Path: %s\n", filePath);
		
		sprintf (msg, "%s", filePath);
		
		filePtr = fopen (msg, "r");
		
		if (filePtr != NULL)
		{
			sprintf (msg, "File Open: %s", filePath);
			npPostMsg (msg, kNPmsgCtrl, dataRef);
		}
		else
			npPostMsg ("err 2995 - File Pointer is NULL", kNPmsgErr, dataRef);
		
		return filePtr;
	}
	
	// Cleanup
CantExtractFSRef:
UserCanceled:
	verify_noerr( NavDisposeReply(&replyRecord) );
CantGetReply:
CantRunDialog:
	NavDialogDispose(dialog);
CantCreateDialog:
CantGetNavOptions:
	// return fileAsCFURLRef;	//part of original sample, does not apply here
	
	return NULL;
}
CFURLRef GetSaveDialogForUser(char* title, char* message)
{
	NavDialogCreationOptions dialogOptions;
	FSRef output_file;
	CFURLRef fileAsCFURLRef = NULL;
	OSStatus status;
	CFAllocatorRef alloc_default = kCFAllocatorDefault;
	
	
	AEKeyword keyword;
	DescType actual_type;
	Size actual_size;
	FSRef output_dir;
	NavReplyRecord reply;
	CFIndex len;

	// Get the standard set of defaults
	status = NavGetDefaultDialogCreationOptions( &dialogOptions );
	require_noerr( status, CantGetNavOptions );

	dialogOptions.optionFlags = kNavNoTypePopup + kNavSupportPackages + kNavAllowOpenPackages;

	  // = NULL;

	if (title != NULL) {
		CFStringRef cftitle = CFStringCreateWithCString(alloc_default,title,kCFStringEncodingMacRoman);
		dialogOptions.windowTitle = cftitle;
	}

	if (message != NULL) {
		CFStringRef cfmessage = CFStringCreateWithCString(alloc_default,message,kCFStringEncodingMacRoman);
		dialogOptions.message = cfmessage;
	}
	// Make the window app-wide modal
	dialogOptions.modality = kWindowModalityAppModal;

	NavDialogRef dialog;
	status = NavCreatePutFileDialog ( &dialogOptions, NULL, NULL, NULL, NULL, &dialog);
	require_noerr( status, CantCreateDialog );

	status = NavDialogRun(dialog);
	require_noerr( status, CantRunDialog );

	// get dialog reply
	status = NavDialogGetReply(dialog, &reply);
	require( ((status == noErr) || (status == userCanceledErr)), CantGetReply );

	//get file directory
	status = AEGetNthPtr(&(reply.selection), 1, typeFSRef, &keyword, &actual_type,
						 &output_dir, sizeof(output_file), &actual_size);
	require_noerr( status, CantExtractFSRef );

	UInt8 output_dir_name[1024];
	FSRefMakePath(&output_dir, output_dir_name, 1024 );

	// now get filename
	len = CFStringGetLength(reply.saveFileName);
	if (len > 255)
		len = 255;
	UniChar output_filename[255];
	CFStringGetCharacters(reply.saveFileName, CFRangeMake(0, len), output_filename);

	// need to unlink the old file
	if ( reply.replacing )
	{
		FSRef oldfile;

		status = FSMakeFSRefUnicode(&output_dir, len, output_filename,
								 kTextEncodingUnicodeDefault,
								 &oldfile);
		if (status == noErr) status = FSDeleteObject(&oldfile);
		//overwrite failed!
		require_noerr( status, UserCanceled );
	}

	//create fsref again to new file (NOTE: this actually makes a file...)
	status = FSCreateFileUnicode( &output_dir, len, output_filename, kFSCatInfoNone,
								 NULL, &output_file, NULL );
	require_noerr( status, CantExtractFSRef );

	// Convert it to a CFURL
	fileAsCFURLRef = CFURLCreateFromFSRef(NULL, &output_file);

CantExtractFSRef:
UserCanceled:
	verify_noerr( NavDisposeReply(&reply) );
CantGetReply:
CantRunDialog:
	// cleanup dialog
	NavDialogDispose(dialog);
CantCreateDialog:
CantGetNavOptions:
    return fileAsCFURLRef;
}
Пример #15
0
static OSStatus LoadFrameworkBundle(CFStringRef framework, CFBundleRef *bundlePtr)
{
	OSStatus 	err;
	FSRef 		frameworksFolderRef;
	CFURLRef	baseURL;
	CFURLRef	bundleURL;
	
	*bundlePtr = nil;
	
	baseURL = nil;
	bundleURL = nil;

	// Find the frameworks folder and create a URL for it.
	
	err = FSFindFolder(kOnAppropriateDisk, kFrameworksFolderType, true, &frameworksFolderRef);
	if (err == noErr) {
		baseURL = CFURLCreateFromFSRef(kCFAllocatorSystemDefault, &frameworksFolderRef);
		if (baseURL == nil) {
			err = coreFoundationUnknownErr;
		}
	}
	
	// Append the name of the framework to the URL.
	
	if (err == noErr) {
		bundleURL = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, baseURL, framework, false);
		if (bundleURL == nil) {
			err = coreFoundationUnknownErr;
		}
	}
	
	// Create a bundle based on that URL and load the bundle into memory.
	// We never unload the bundle, which is reasonable in this case because 
	// the sample assumes that you'll be calling functions from this 
	// framework throughout the life of your application.
	if (err == noErr) {
		*bundlePtr = CFBundleCreate(kCFAllocatorSystemDefault, bundleURL);
		if (*bundlePtr == nil) {
			err = coreFoundationUnknownErr;
		}
	}

	// first check if bundle is already loaded - if it is, there's no need
	// to load it
	if (!CFBundleIsExecutableLoaded(*bundlePtr))
	{
		if (err == noErr) {
		    if ( ! CFBundleLoadExecutable( *bundlePtr ) ) {
				err = coreFoundationUnknownErr;
		    }
		}
	}

	// Clean up.
	
	if (err != noErr && *bundlePtr != nil) {
		CFRelease(*bundlePtr);
		*bundlePtr = nil;
	}
	if (bundleURL != nil) {
		CFRelease(bundleURL);
	}	
	if (baseURL != nil) {
		CFRelease(baseURL);
	}	
	
	return err;
}
Пример #16
0
static int quicklyMakePath(char *pathString, int pathStringLength,char *dst, Boolean resolveAlias) {
	CFStringRef 	filePath;
        CFURLRef 	sillyThing,firstPartOfPath;
        FSRef		theFSRef;   
        Boolean		isFolder,isAlias;
        OSErr		err;
        
        filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,
                    (UInt8 *)pathString,pathStringLength,gCurrentVMEncoding,false);
        if (filePath == nil)
            return -1;
		CFMutableStringRef str= CFStringCreateMutableCopy(NULL, 0, filePath);
		// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
		if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
			CFStringNormalize(str, kCFStringNormalizationFormKC); // canonical decomposition

		sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault, str, kCFURLHFSPathStyle,false);
		if (sillyThing == NULL) {
			CFRelease(filePath);
			return -2;
		}
		CFRelease(str);
        
        if (!CFURLGetFSRef(sillyThing,&theFSRef)) {
            firstPartOfPath = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault,sillyThing);
            if (!CFURLGetFSRef(firstPartOfPath,&theFSRef)) {
                CFRelease(firstPartOfPath);
                CFRelease(filePath);
                CFRelease(sillyThing);
                return -1;
            } else {
                CFStringRef lastPathPart;
                char	 lastpart[256];
                
                CFRelease(filePath);
                CFRelease(firstPartOfPath);
                lastPathPart = CFURLCopyLastPathComponent(sillyThing);
                CFRelease(sillyThing);
                
                err = noErr;
                if (resolveAlias) 
                    err = FSResolveAliasFile (&theFSRef,true,&isFolder,&isAlias);

                if (err) 
                    return 2;
                
                err = FSRefMakePath(&theFSRef,(UInt8 *)dst,1000); 
                CFStringGetCString(lastPathPart,lastpart,256, kCFStringEncodingUTF8);
                CFRelease(lastPathPart);
                if (strlen(dst)+1+strlen(lastpart) < 1000) {
                    strcat(dst,"/");
                    strcat(dst,lastpart);
                    
#if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__)
        filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)dst,strlen(dst),gCurrentVMEncoding,false);
        if (filePath == nil) 
            return 2;
        sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLPOSIXPathStyle,true);
		CFRelease(filePath);
        filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
        CFStringGetCString (filePath,dst,1000, gCurrentVMEncoding);
		CFRelease(sillyThing);
        CFRelease(filePath);        
#endif

                    return 0;
                } else
                    return 2;
            }
        }
        
        CFRelease(filePath);
        CFRelease(sillyThing);
        
        if (resolveAlias) 
            err = FSResolveAliasFile (&theFSRef,true,&isFolder,&isAlias);

#if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__)
		sillyThing = CFURLCreateFromFSRef(kCFAllocatorDefault,&theFSRef);
        filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
        CFStringGetCString (filePath,dst,1000, gCurrentVMEncoding);
		CFRelease(sillyThing);
        CFRelease(filePath);        
        return 0;
#else
        err = FSRefMakePath(&theFSRef,(UInt8 *)dst,1000); 
        return err;
#endif 
}
Пример #17
0
static OSStatus InputCallback (void 			*inRefCon, 
					AudioUnitRenderActionFlags 	*ioActionFlags, 
					const AudioTimeStamp 		*inTimeStamp, 
					UInt32 						inBusNumber, 
					UInt32 						inNumberFrames, 
					AudioBufferList 			*ioData)
{
													#if CA_AU_PROFILE_TIME 
														UInt64 now = CAHostTimeBase::GetTheCurrentTime(); 
													#endif

	CAAudioFile &readFile = *(static_cast<CAAudioFile*>(inRefCon));

#if !CAAF_USE_EXTAUDIOFILE
	if (SInt64(inTimeStamp->mSampleTime) > readFile.GetNumberPackets()) {
#else
	if (SInt64(inTimeStamp->mSampleTime) > readFile.GetNumberFrames()) {
#endif
#if DEBUG
	printf ("reading past end of input\n");
#endif
		return -1;
	}

	readFile.Seek (SInt64(inTimeStamp->mSampleTime));
	readFile.Read (inNumberFrames, ioData);

													#if CA_AU_PROFILE_TIME 
														sReadTime += (CAHostTimeBase::GetTheCurrentTime() - now); 
													#endif

	return noErr;
}

static OSStatus FConvInputCallback (void 			*inRefCon, 
					AudioUnitRenderActionFlags 	*ioActionFlags, 
					const AudioTimeStamp 		*inTimeStamp, 
					UInt32 						inBusNumber, 
					UInt32 						inNumberFrames, 
					AudioBufferList 			*ioData)
{
												#if CA_AU_PROFILE_TIME 
													UInt64 now = CAHostTimeBase::GetTheCurrentTime(); 
												#endif

	CAAudioFile &readFile = *(static_cast<CAAudioFile*>(inRefCon));

		// this test is ONLY needed in case of processing with a Format Converter type of AU
		// in all other cases, the CAAUProcessor class will NEVER call you for input
		// beyond the end of the file....

#if !CAAF_USE_EXTAUDIOFILE
	if (SInt64(inTimeStamp->mSampleTime) >= readFile.GetNumberPackets()) {
#else
	if (SInt64(inTimeStamp->mSampleTime) >= readFile.GetNumberFrames()) {
#endif
		return -1;
	}
	
	readFile.Seek (SInt64(inTimeStamp->mSampleTime));
	UInt32 readPackets = inNumberFrames;
		
		// also, have to do this for a format converter AU - otherwise we'd just read what we're told
#if !CAAF_USE_EXTAUDIOFILE
	if (SInt64(inTimeStamp->mSampleTime + inNumberFrames) > readFile.GetNumberPackets()) {
#else
	if (SInt64(inTimeStamp->mSampleTime + inNumberFrames) > readFile.GetNumberFrames()) {
#endif
		// first set this to zero as we're only going to read a partial number of frames
		AudioBuffer *buf = ioData->mBuffers;
		for (UInt32 i = ioData->mNumberBuffers; i--; ++buf)
			memset((Byte *)buf->mData, 0, buf->mDataByteSize);
#if !CAAF_USE_EXTAUDIOFILE
		readPackets = UInt32 (readFile.GetNumberPackets() - SInt64(inTimeStamp->mSampleTime));
#else
		readPackets = UInt32 (readFile.GetNumberFrames() - SInt64(inTimeStamp->mSampleTime));
#endif
	}
	
	readFile.Read (readPackets, ioData);

													#if CA_AU_PROFILE_TIME 
														sReadTime += (CAHostTimeBase::GetTheCurrentTime() - now); 
													#endif

	return noErr;
}

struct ReadBuffer {
	AUOutputBL *readData;
	UInt32 readFrames;
};

static OSStatus MemoryInputCallback (void		*inRefCon, 
					AudioUnitRenderActionFlags 	*ioActionFlags, 
					const AudioTimeStamp 		*inTimeStamp, 
					UInt32 						inBusNumber, 
					UInt32 						inNumberFrames, 
					AudioBufferList 			*ioData)
{
													#if CA_AU_PROFILE_TIME 
														UInt64 now = CAHostTimeBase::GetTheCurrentTime(); 
													#endif

	ReadBuffer *readBuffer = (ReadBuffer*)inRefCon;
	
	if (((readBuffer->readFrames + inNumberFrames) * sizeof(Float32)) > (readBuffer->readData->ABL()->mBuffers[0].mDataByteSize)) 
	{
		// going past read size
		AudioBuffer *buf = ioData->mBuffers;
		for (UInt32 i = ioData->mNumberBuffers; i--; ++buf)
			memset((Byte *)buf->mData, 0, buf->mDataByteSize);
	}
	else
	{
		AudioBuffer *buf = ioData->mBuffers;
		AudioBuffer *rBuf = readBuffer->readData->ABL()->mBuffers;
		for (UInt32 i = ioData->mNumberBuffers; i--; ++buf, ++rBuf) {
			AudioBuffer readB = *rBuf;
			readB.mData = static_cast<Float32*>(rBuf->mData) + readBuffer->readFrames;
			memcpy (buf->mData, readB.mData, buf->mDataByteSize);
		}
		readBuffer->readFrames += inNumberFrames;
	}

													#if CA_AU_PROFILE_TIME 
														sReadTime += (CAHostTimeBase::GetTheCurrentTime() - now); 
													#endif

	return noErr;
}

#pragma mark __Utility Helpers

CFPropertyListRef	 ReadPresetFromPresetFile (char* filePath)
{	
	if (!filePath)
		return NULL;
	
	FSRef ref;
	if (FSPathMakeRef((UInt8 *)filePath, &ref, NULL))
		return NULL;
		
	CFDataRef			resourceData = NULL;
	CFPropertyListRef   theData = NULL;
	CFStringRef			errString = NULL;
	CFURLRef			fileURL = CFURLCreateFromFSRef (kCFAllocatorDefault, &ref);
		if (fileURL == NULL) {
			goto home;
		}
		
	SInt32				result;
    
   // Read the XML file.
   Boolean status; status = CFURLCreateDataAndPropertiesFromResource (kCFAllocatorDefault, fileURL,
                                                                &resourceData,	// place to put file data
                                                                NULL, NULL, &result);
        if (status == false || result) {
            goto home;
        }
    
	theData = CFPropertyListCreateFromXMLData (kCFAllocatorDefault, resourceData,  
													kCFPropertyListImmutable, &errString);
        if (theData == NULL || errString) {
            if (theData)
				CFRelease (theData);
			theData = NULL;
			goto home;
       }
	
home:
	if (fileURL)
		CFRelease (fileURL);
	if (resourceData)
		CFRelease (resourceData);
    if (errString)
		CFRelease (errString);
		
	return theData;
}

#pragma mark __the setup code

#define OFFLINE_AU_CMD 		"[-au TYPE SUBTYPE MANU] The Audio Unit component description\n\t"
#define INPUT_FILE	 		"[-i /Path/To/File] The file that is to be processed.\n\t"
#define OUTPUT_FILE			"[-o /Path/To/File/To/Create] This will be in the same format as the input file\n\t"
#define AU_PRESET_CMD		"[-p /Path/To/AUPreset/File] Specify an AU Preset File to establish the state of the AU\n\t"
#define SHORT_MEM_CMD		"[-m] Just reads and processes the first half second of the input file\n\t"
#define USE_MAX_FRAMES		"[-f max_frames] default is 32768 (512 for aufc units)"
 
static char* usageStr = "Usage: AU Process\n\t" 
				OFFLINE_AU_CMD 
				INPUT_FILE
				OUTPUT_FILE
				AU_PRESET_CMD
				SHORT_MEM_CMD
				USE_MAX_FRAMES;

static int		StrToOSType(const char *str, OSType &t)
{
	char buf[4];
	const char *p = str;
	int x;
	for (int i = 0; i < 4; ++i) {
		if (*p != '\\') {
			if ((buf[i] = *p++) == '\0')
				goto fail;
		} else {
			if (*++p != 'x') goto fail;
			if (sscanf(++p, "%02X", &x) != 1) goto fail;
			buf[i] = x;
			p += 2;
		}
	}
	t = EndianU32_BtoN(*(UInt32 *)buf);
	return p - str;
fail:
	return 0;
}