Exemplo n.º 1
0
pascal OSErr MoreFESetComment(const FSSpecPtr pFSSpecPtr, const Str255 pCommentStr, const AEIdleUPP pIdleProcUPP){
	AppleEvent tAppleEvent = {
		typeNull, nil
	};                                              // If you always init AEDescs, it's always safe to dispose of them.
	AEBuildError tAEBuildError;
	AEDesc tAEDesc = {
		typeNull, nil
	};
	OSErr anErr = noErr;

	anErr = MoreAEOCreateObjSpecifierFromFSSpec(pFSSpecPtr, &tAEDesc);
	if (noErr == anErr) {
		char *dataPtr = NewPtr(pCommentStr[ 0 ]);

		CopyPascalStringToC(pCommentStr, dataPtr);
		anErr = AEBuildAppleEvent(
		        kAECoreSuite, kAESetData,
		        typeApplSignature, &gFinderSignature, sizeof( OSType ),
		        kAutoGenerateReturnID, kAnyTransactionID,
		        &tAppleEvent, &tAEBuildError,
		        "'----':obj {form:prop,want:type(prop),seld:type(comt),from:(@)},data:'TEXT'(@)",
		        &tAEDesc, dataPtr);

		DisposePtr(dataPtr);

		if (noErr == anErr) {
			// Send the event. In this case we don't care about the reply
			anErr = MoreAESendEventNoReturnValue(pIdleProcUPP, &tAppleEvent);
			(void) MoreAEDisposeDesc(&tAppleEvent); // always dispose of AEDescs when you are finished with them
		}
	}
	return anErr;
}
Exemplo n.º 2
0
/*	SetPopMatch(theDialog, popupItemNumber, selStr)

 	Sets currently selected item to that which matches string (case insensitive).
	Returns item number or zero if there is no match.

	Thread Safety: SetPopMatch is not thread-safe.
*/
int
SetPopMatch(DialogPtr theDialog, int popupItemNumber, const char *selStr)
{
	ControlHandle controlH;
	MenuHandle mH;
	int numMenuItems;
	int i;
	unsigned char temp[256];
	char itemText[256];
	int result;
	int err;

	if (err = XOPGetDialogItemAsControl(theDialog, popupItemNumber, &controlH))
		return 0;
	
	mH = GetPopMenuHandle(theDialog, popupItemNumber);
	if (mH == NULL)
		return 0;
	
	result = 0;
	numMenuItems = CountMenuItems(mH);
	for (i=1; i<=numMenuItems; i++) {
		GetMenuItemText(mH, i, temp);
		CopyPascalStringToC(temp, itemText);
		if (CmpStr(itemText,selStr) == 0) {
			result = i;
			SetControlValue(controlH, result);
			InvalDBox(theDialog, popupItemNumber);		// This can move heap.
			break;
		}
	}
	return result;
}
NS_IMETHODIMP
nsSafariProfileMigrator::GetSourceHomePageURL(nsACString& aResult)
{
    aResult.Truncate();

    ICInstance internetConfig;
    OSStatus error = ::ICStart(&internetConfig, 'FRFX');
    if (error != noErr)
        return NS_ERROR_FAILURE;

    ICAttr dummy;
    Str255 homePagePValue;
    long prefSize = sizeof(homePagePValue);
    error = ::ICGetPref(internetConfig, kICWWWHomePage, &dummy,
                        homePagePValue, &prefSize);
    if (error != noErr)
        return NS_ERROR_FAILURE;

    char homePageValue[256] = "";
    CopyPascalStringToC((ConstStr255Param)homePagePValue, homePageValue);
    aResult.Assign(homePageValue);

    ::ICStop(internetConfig);

    return NS_OK;
}
Exemplo n.º 4
0
/*	GetPopMenu(theDialog,popupItemNumber,selItem,selStr)

 	Returns currently selected item number and string.
	Pass NULL for selStr if you don't care about it.

	Thread Safety: GetPopMenu is not thread-safe.
*/
void
GetPopMenu(DialogPtr theDialog, int popupItemNumber, int *selItem, char *selStr)
{
	ControlHandle controlH;
	MenuHandle mH;
	int err;
	
	*selItem = 1;
	if (selStr != NULL)
		*selStr = 0;

	if (err = XOPGetDialogItemAsControl(theDialog, popupItemNumber, &controlH))
		return;
	
	*selItem = GetControlValue(controlH);
	
	if (selStr != NULL) {
		mH = GetPopMenuHandle(theDialog, popupItemNumber);
		if (mH != NULL) {
			unsigned char temp[256];
			GetMenuItemText(mH, *selItem, temp);
			CopyPascalStringToC(temp, selStr);
		}
	}	
}
Exemplo n.º 5
0
internal void
CarbonApplicationLaunched(ProcessSerialNumber PSN)
{
    Str255 ProcessName = {};
    ProcessInfoRec ProcessInfo = {};
    ProcessInfo.processInfoLength = sizeof(ProcessInfoRec);
    ProcessInfo.processName = ProcessName;

    /* NOTE(koekeishiya): Deprecated, consider switching to
     * CFDictionaryRef ProcessInformationCopyDictionary(const ProcessSerialNumber *PSN, UInt32 infoToReturn) */
    GetProcessInformation(&PSN, &ProcessInfo);

    char ProcessNameCString[256] = {0};
    if(ProcessInfo.processName)
        CopyPascalStringToC(ProcessInfo.processName, ProcessNameCString);
    std::string Name = ProcessNameCString;

    /* NOTE(koekeishiya): Check if we should care about this process. */
    if((!IsProcessWhitelisted(Name)) &&
       ((ProcessInfo.processMode & modeOnlyBackground) != 0))
        return;

    pid_t PID = 0;
    GetProcessPID(&PSN, &PID);

    /*
    printf("Carbon: Application launched %s\n", Name.c_str());
    printf("%d: modeReserved\n", ProcessInfo.processMode & modeReserved);
    printf("%d: modeControlPanel\n", ProcessInfo.processMode & modeControlPanel);
    printf("%d: modeLaunchDontSwitch\n", ProcessInfo.processMode & modeLaunchDontSwitch);
    printf("%d: modeDeskAccessory\n", ProcessInfo.processMode & modeDeskAccessory);
    printf("%d: modeMultiLaunch\n", ProcessInfo.processMode & modeMultiLaunch);
    printf("%d: modeNeedSuspendResume\n", ProcessInfo.processMode & modeNeedSuspendResume);
    printf("%d: modeCanBackground\n", ProcessInfo.processMode & modeCanBackground);
    printf("%d: modeDoesActivateOnFGSwitch\n", ProcessInfo.processMode & modeDoesActivateOnFGSwitch);
    printf("%d: modeOnlyBackground\n", ProcessInfo.processMode & modeOnlyBackground);
    printf("%d: modeGetFrontClicks\n", ProcessInfo.processMode & modeGetFrontClicks);
    printf("%d: modeGetAppDiedMsg\n", ProcessInfo.processMode & modeGetAppDiedMsg);
    printf("%d: mode32BitCompatible\n", ProcessInfo.processMode & mode32BitCompatible);
    printf("%d: modeHighLevelEventAware\n", ProcessInfo.processMode & modeHighLevelEventAware);
    printf("%d: modeLocalAndRemoteHLEvents\n", ProcessInfo.processMode & modeLocalAndRemoteHLEvents);
    printf("%d: modeStationeryAware\n", ProcessInfo.processMode & modeStationeryAware);
    printf("%d: modeUseTextEditServices\n", ProcessInfo.processMode & modeUseTextEditServices);
    printf("%d: modeDisplayManagerAware\n", ProcessInfo.processMode & modeDisplayManagerAware);
    */

    (*Applications)[PID] = AXLibConstructApplication(PID, Name);
    ax_application *Application = &(*Applications)[PID];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(),
    ^{
        if(AXLibInitializeApplication(Application->PID))
            AXLibInitializedApplication(Application);
    });
Exemplo n.º 6
0
/*	GetDText(theDialog, theItem, theText)

	Gets text from text item in dialog.
	Returns the number of characters in the text.

	Thread Safety: GetDText is not thread-safe.
*/
int
GetDText(DialogPtr theDialog, int theItem, char *theText)
{
	short type;
	Handle item;
	Rect box;

	// According to Apple, this is the correct routine to use to get a handle
	// to pass to GetDialogItemText, even if embedding (kDialogFlagsUseControlHierarchy)
	// is on.
	GetDialogItem(theDialog, theItem, &type, &item, &box);

	GetDialogItemText(item, (unsigned char*)theText);
	CopyPascalStringToC((unsigned char*)theText, theText);
	return strlen(theText);
}
Exemplo n.º 7
0
std::string GetFileComment(std::string spath) {
	const char *path = spath.c_str();
	OSErr err = noErr;
	FSRef fileRef;
	FSSpec fileSpec;
	unsigned char *comment;
	char cStrCmt[ 255 ] = "\0";
	AEIdleUPP inIdleProc = NewAEIdleUPP(&MyAEIdleCallback);

	// see if the file in question exists and we can write it
	if (access(path, R_OK | F_OK) == - 1) {
		return "";
	}

	// get file reference from path
	err = FSPathMakeRef( (const UInt8 *) path, &fileRef, NULL);
	if (err != noErr) {
		return "";
	}

	// retrieve filespec from file ref
	err = FSGetCatalogInfo(&fileRef, NULL, NULL, NULL, &fileSpec, NULL);
	if (err != noErr) {
		return "";
	}

	// call the apple event routine. I'm not going to pretend I understand what's going on
	// in all those horribly kludgy functions, but at least it works.
	err = MoreFEGetComment(&fileSpec, comment, inIdleProc);
	if (err) {
		return "";
	}
	// convert pascal string to c string
	// strncpy((char *)&cStrCmt, (unsigned char *)&comment+1, comment[0]);
	// comment=(unsigned char *)p2cstr((unsigned char *)&cStrCmt);
	CopyPascalStringToC(comment, cStrCmt);

	// if there is no comment, we don't print out anything
	if (!strlen( (char *) &cStrCmt) )
		return "";

	// print out the comment
	if (!false)
		return std::string( (const char *) &cStrCmt);
	else
		return std::string( (const char *) &cStrCmt);
}
Exemplo n.º 8
0
/* FSSpec -> FSRef -> URL(Unix) -> HPFS+ */
int PathToFile(char *pathName, int pathNameMax, FSSpec *where,UInt32 encoding) {        
        CFURLRef sillyThing;
        CFStringRef filePath;
        FSSpec	failureRetry;
        FSRef	theFSRef;
        OSErr	error;
        Boolean isDirectory=false,retryWithDirectory=false;
        char	rememberName[256];
        
        *pathName = 0x00;
        error = FSpMakeFSRef (where, &theFSRef);
        if (error != noErr) {
            retryWithDirectory = true;
            failureRetry = *where;
            CopyCStringToPascal(":",failureRetry.name);
            CopyPascalStringToC(where->name,(char *) &rememberName);
            error = FSpMakeFSRef(&failureRetry,&theFSRef);
            if (error != noErr) 
                return -1;
	}
        
        sillyThing =  CFURLCreateFromFSRef (kCFAllocatorDefault, &theFSRef);
        isDirectory = CFURLHasDirectoryPath(sillyThing);
        
        filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
        CFRelease(sillyThing);
        
  		CFMutableStringRef mutableStr= CFStringCreateMutableCopy(NULL, 0, filePath);
          CFRelease(filePath);
  
  		// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
  		if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
  			CFStringNormalize(mutableStr, kCFStringNormalizationFormKC); // pre-combined
  
          CFStringGetCString (mutableStr, pathName,pathNameMax, encoding);
        
        if (retryWithDirectory) {
            strcat(pathName,":");
            strcat(pathName,rememberName);
            isDirectory = false;
        }
        if (isDirectory)
            strcat(pathName,":");
        return 0;
}
Exemplo n.º 9
0
void
UpdateItemCount()
{
    ControlID 		controlID = { kNSLSample, kServicesCountText };
    ControlRef		control;
    Str255 		countStr;
    char                count[16];
    UInt32		itemCount;
    static UInt32	previousItemCount = 0;
    OSStatus 		err = noErr;
    
    err = GetControlByID(gMainWindow, &controlID, &control);
    if (err == noErr)
    {
        err = GetDataBrowserItemCount(gDataBrowserControl, 0, true, kDataBrowserItemAnyState, &itemCount);
        
        // Only update if the count has actually changed since last time.
        if (err == noErr && previousItemCount != itemCount)
        {        
            previousItemCount = itemCount;
            NumToString (itemCount, countStr); 
            CopyPascalStringToC(countStr, count);
            
            if (itemCount == 1)
            {
                strcat(count, " Item");
                SetControlData(control, kControlNoPart, kControlEditTextTextTag, strlen(count), count);
                ShowControl(control);
            }
            else
            {
                strcat(count, " Items");
                SetControlData(control, kControlNoPart, kControlEditTextTextTag, strlen(count), count);
                ShowControl(control);
            }
            
            DrawOneControl(control);
            DrawOneControl(gDataBrowserControl);
        }
    }
}
int dir_Lookup(char *pathString, int pathStringLength, int index,
  /* outputs: */
  char *name, int *nameLength, int *creationDate, int *modificationDate,
  int *isDirectory, squeakFileOffsetType *sizeIfFile) {
	/* Lookup the index-th entry of the directory with the given path, starting
	   at the root of the file system. Set the name, name length, creation date,
	   creation time, directory flag, and file size (if the entry is a file).
	   Return:	0 	if a entry is found at the given index
	   			1	if the directory has fewer than index entries
	   			2	if the given path has bad syntax or does not reach a directory
	*/

	int okay;
	HVolumeParam volumeParams;
    FSSpec      spec;
    long        parentDirectory;
    OSErr       err;
    Str255      longFileName;
    
	/* default return values */
	*name             = 0;
	*nameLength       = 0;
	*creationDate     = 0;
	*modificationDate = 0;
	*isDirectory      = false;
	*sizeIfFile       = 0;

	if ((pathStringLength == 0)) {
		/* get volume info */
		volumeParams.ioNamePtr = (unsigned char *) name;
		volumeParams.ioVRefNum = 0;
		volumeParams.ioVolIndex = index;
		okay = PBHGetVInfoSync((HParmBlkPtr) &volumeParams) == noErr;
		if (okay) {
			CopyPascalStringToC((ConstStr255Param) name,name);
			*nameLength       = strlen(name);
			*creationDate     = convertToSqueakTime(volumeParams.ioVCrDate);
			*modificationDate = convertToSqueakTime(volumeParams.ioVLsMod);
			*isDirectory      = true;
			*sizeIfFile       = 0;
			return ENTRY_FOUND;
		} else {
			return NO_MORE_ENTRIES;
		}
	} else {
		/* get file or directory info */
		if (!equalsLastPath(pathString, pathStringLength)) {
 			/* lookup and cache the refNum for this path */
			err = lookupPath(pathString, pathStringLength, &spec,false,true);
 			if (err == noErr) 
				recordPath(pathString, pathStringLength, &spec);
			else 
				return BAD_PATH;
		}
	    spec = lastSpec;
				*sizeIfFile   = 0;
		okay = fetchFileInfo(index,&spec,(unsigned char *) name,true,&parentDirectory,isDirectory,creationDate,modificationDate,sizeIfFile,&longFileName);
		if (okay == noErr) {
			CopyPascalStringToC((ConstStr255Param) longFileName,name);
			*nameLength       = strlen(name);
			*creationDate     = convertToSqueakTime(*creationDate);
			*modificationDate = convertToSqueakTime(*modificationDate);
			return ENTRY_FOUND;
		} else
			return okay == fnfErr ? NO_MORE_ENTRIES : BAD_PATH;
	}
}
Exemplo n.º 11
0
  FT_GetFile_From_Mac_Name( const char*  fontName,
                            FSSpec*      pathSpec,
                            FT_Long*     face_index )
  {
    OptionBits            options = kFMUseGlobalScopeOption;

    FMFontFamilyIterator  famIter;
    OSStatus              status = FMCreateFontFamilyIterator( NULL, NULL,
                                                               options,
                                                               &famIter );
    FMFont                the_font = 0;
    FMFontFamily          family   = 0;


    if ( !fontName || !face_index )
      return FT_THROW( Invalid_Argument );

    *face_index = 0;
    while ( status == 0 && !the_font )
    {
      status = FMGetNextFontFamily( &famIter, &family );
      if ( status == 0 )
      {
        int                           stat2;
        FMFontFamilyInstanceIterator  instIter;
        Str255                        famNameStr;
        char                          famName[256];


        /* get the family name */
        FMGetFontFamilyName( family, famNameStr );
        CopyPascalStringToC( famNameStr, famName );

        /* iterate through the styles */
        FMCreateFontFamilyInstanceIterator( family, &instIter );

        *face_index = 0;
        stat2       = 0;

        while ( stat2 == 0 && !the_font )
        {
          FMFontStyle  style;
          FMFontSize   size;
          FMFont       font;


          stat2 = FMGetNextFontFamilyInstance( &instIter, &font,
                                               &style, &size );
          if ( stat2 == 0 && size == 0 )
          {
            char  fullName[256];


            /* build up a complete face name */
            ft_strcpy( fullName, famName );
            if ( style & bold )
              ft_strcat( fullName, " Bold" );
            if ( style & italic )
              ft_strcat( fullName, " Italic" );

            /* compare with the name we are looking for */
            if ( ft_strcmp( fullName, fontName ) == 0 )
            {
              /* found it! */
              the_font = font;
            }
            else
              ++(*face_index);
          }
        }

        FMDisposeFontFamilyInstanceIterator( &instIter );
      }
    }

    FMDisposeFontFamilyIterator( &famIter );

    if ( the_font )
    {
      FMGetFontContainer( the_font, pathSpec );
      return FT_Err_Ok;
    }
    else
      return FT_THROW( Unknown_File_Format );
  }
Exemplo n.º 12
0
/*
    PsychInitFontList()
    
    Build a list of records describing installed fonts.
    
    
*/
void PsychInitFontList(void)
{
    ATSFontRef			tempATSFontRef;
    //for font structures
    PsychFontStructPtrType	fontListHead, fontRecord, previousFontRecord;
    //for ATI font iteration
    ATSFontIterator		fontIterator;
    OSStatus			halt;
    //for font field names
    CFStringRef 		cfFontName;
    int				i;
    psych_bool			resultOK;
    //for font file
    //OSErr			osError;
    OSStatus			osStatus;			
    FSSpec			fontFileSpec;
    FSRef			fontFileRef;
    //for the font metrics
    ATSFontMetrics		horizontalMetrics;
    ATSFontMetrics		verticalMetrics;
    //for info from Font Manager 
    FMFontStyle			fmStyle;
    OSStatus			fmStatus;
    Str255				fmFontFamilyNamePString;
    //whatever
    Str255			fontFamilyQuickDrawNamePString;
    TextEncoding		textEncoding;
    OSStatus			scriptInfoOK;
    ScriptCode			scriptCode;
    LangCode			languageCode;
    OSStatus			localOK;
    LocaleRef			locale;
	psych_bool				trouble = FALSE;

    fontListHead=PsychFontListHeadKeeper(FALSE, NULL); //get the font list head.
    if(fontListHead) PsychErrorExitMsg(PsychError_internal, "Attempt to set new font list head when one is already set.");
        
    fontRecord=NULL;
    halt= ATSFontIteratorCreate(PSYCH_ATS_ITERATOR_CONTEXT, NULL, NULL, PSYCH_ATS_ITERATOR_SCOPE, &fontIterator);
    i=0;
	
    while(halt==noErr){
        halt=ATSFontIteratorNext(fontIterator, &tempATSFontRef);

        if(halt==noErr){
            //create a new  font  font structure.  Set the next field  to NULL as  soon as we allocate the font so that if 
            //we break with an error then we can find the end when we  walk down the linked list. 
            fontRecord=(PsychFontStructPtrType)malloc(sizeof(PsychFontStructType));
            fontRecord->next=NULL;

            //Get  FM and ATS font and font family references from the ATS font reference, which we get from iteration.
            fontRecord->fontATSRef=tempATSFontRef; 
            fontRecord->fontFMRef=FMGetFontFromATSFontRef(fontRecord->fontATSRef);
            fmStatus=FMGetFontFamilyInstanceFromFont(fontRecord->fontFMRef, &(fontRecord->fontFamilyFMRef), &fmStyle);
            fontRecord->fontFamilyATSRef=FMGetATSFontFamilyRefFromFontFamily(fontRecord->fontFamilyFMRef);
            //get the font name and set the the corresponding field of the struct
            if (ATSFontGetName(fontRecord->fontATSRef, kATSOptionFlagsDefault, &cfFontName)!=noErr) {
				if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to query font name in ATSFontGetName! OS-X font handling screwed up?!? Skipped this entry...\n");
				trouble = TRUE;
				continue;
            }
            
            resultOK=CFStringGetCString(cfFontName, (char*) fontRecord->fontFMName, 255, kCFStringEncodingASCII);
            if(!resultOK){
                CFRelease(cfFontName);
				if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to convert fontFMName CF string to char string. Defective font?!? Skipped this entry...\n");
				trouble = TRUE;
				continue;
            }
            CFRelease(cfFontName);

            //get the font postscript name and set the corresponding field of the struct
            if (ATSFontGetPostScriptName(fontRecord->fontATSRef, kATSOptionFlagsDefault, &cfFontName)!=noErr) {
                if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: The following font makes trouble: %s. Please REMOVE the offending font file from your font folders and restart Matlab. Skipped entry for now...\n", fontRecord->fontFMName);
				trouble = TRUE;
				continue;
            }

            resultOK=CFStringGetCString(cfFontName, (char*) fontRecord->fontPostScriptName, 255, kCFStringEncodingASCII); //kCFStringEncodingASCII matches MATLAB for 0-127
            if(!resultOK){
                CFRelease(cfFontName);
				if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to convert fontPostScriptName CF string to char string for font %s. Defective font?!? Skipped this entry...\n", fontRecord->fontFMName);
				trouble = TRUE;
				continue;
            }
            CFRelease(cfFontName);

            //get the QuickDraw name of the font
            ATSFontFamilyGetQuickDrawName(fontRecord->fontFamilyATSRef, fontFamilyQuickDrawNamePString);
            CopyPascalStringToC(fontFamilyQuickDrawNamePString, (char*) fontRecord->fontFamilyQuickDrawName);

            //get the font file used for this font
            osStatus= ATSFontGetFileSpecification(fontRecord->fontATSRef, &fontFileSpec);
            if(osStatus != noErr) {
				if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to get the font file specifier for font %s. Defective font?!? Skipped this entry...\n", fontRecord->fontFMName);
				trouble = TRUE;
				continue;
			}

            FSpMakeFSRef(&fontFileSpec, &fontFileRef);
            osStatus= FSRefMakePath(&fontFileRef, (UInt8*) fontRecord->fontFile, (UInt32)(kPsychMaxFontFileNameChars - 1));
            if(osStatus!=noErr){
				if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to get the font file path for font %s. Defective font?!? Skipped this entry...\n", fontRecord->fontFMName);
				trouble = TRUE;
				continue;
            }

            //get the font metrics of this font.
            //Explicit copy between fields to make it clear what is going one, will likely have to mix & match between native and Psych structures for different
            //platforms.
            ATSFontGetHorizontalMetrics(fontRecord->fontATSRef, kATSOptionFlagsDefault, &horizontalMetrics);
            ATSFontGetVerticalMetrics(fontRecord->fontATSRef, kATSOptionFlagsDefault, &verticalMetrics);
            //horizontal
            fontRecord->horizontalMetrics.ascent=			horizontalMetrics.ascent;
            fontRecord->horizontalMetrics.descent=			horizontalMetrics.descent;
            fontRecord->horizontalMetrics.leading=			horizontalMetrics.leading;
            fontRecord->horizontalMetrics.avgAdvanceWidth=		horizontalMetrics.avgAdvanceWidth;
            fontRecord->horizontalMetrics.minLeftSideBearing=		horizontalMetrics.minLeftSideBearing;
            fontRecord->horizontalMetrics.minRightSideBearing=		horizontalMetrics.minRightSideBearing;
            fontRecord->horizontalMetrics.stemWidth=			horizontalMetrics.stemWidth;
            fontRecord->horizontalMetrics.stemHeight=			horizontalMetrics.stemHeight;
            fontRecord->horizontalMetrics.capHeight=			horizontalMetrics.capHeight;
            fontRecord->horizontalMetrics.xHeight=			horizontalMetrics.xHeight;
            fontRecord->horizontalMetrics.italicAngle=			horizontalMetrics.italicAngle;
            fontRecord->horizontalMetrics.underlinePosition=		horizontalMetrics.underlinePosition;
            fontRecord->horizontalMetrics.underlineThickness=		horizontalMetrics.underlineThickness;
            fontRecord->horizontalMetrics.underlineThickness=		horizontalMetrics.underlineThickness;
            //vertical
            fontRecord->verticalMetrics.ascent=				verticalMetrics.ascent;
            fontRecord->verticalMetrics.descent=			verticalMetrics.descent;
            fontRecord->verticalMetrics.leading=			verticalMetrics.leading;
            fontRecord->verticalMetrics.avgAdvanceWidth=		verticalMetrics.avgAdvanceWidth;
            fontRecord->verticalMetrics.minLeftSideBearing=		verticalMetrics.minLeftSideBearing;
            fontRecord->verticalMetrics.minRightSideBearing=		verticalMetrics.minRightSideBearing;
            fontRecord->verticalMetrics.stemWidth=			verticalMetrics.stemWidth;
            fontRecord->verticalMetrics.stemHeight=			verticalMetrics.stemHeight;
            fontRecord->verticalMetrics.capHeight=			verticalMetrics.capHeight;
            fontRecord->verticalMetrics.xHeight=			verticalMetrics.xHeight;
            fontRecord->verticalMetrics.italicAngle=			verticalMetrics.italicAngle;
            fontRecord->verticalMetrics.underlinePosition=		verticalMetrics.underlinePosition;
            fontRecord->verticalMetrics.underlineThickness=		verticalMetrics.underlineThickness;
            fontRecord->verticalMetrics.underlineThickness=		verticalMetrics.underlineThickness;
            //use Font Manager to get the FM  font family name font style
            fmStatus=FMGetFontFamilyName(fontRecord->fontFamilyFMRef, fmFontFamilyNamePString);
            CopyPascalStringToC(fmFontFamilyNamePString, (char*) fontRecord->fontFMFamilyName);
            fontRecord->fontFMStyle=fmStyle;
            fontRecord->fontFMNumStyles=PsychFindNumFMFontStylesFromStyle(fmStyle);
            fontRecord->fontFMNumStyles= fontRecord->fontFMNumStyles ? fontRecord->fontFMNumStyles : 1; //because the name is "normal" even if there are no styles.  
            //get the locale info which is a property of the font family
            textEncoding=ATSFontFamilyGetEncoding(fontRecord->fontFamilyATSRef);
            scriptInfoOK=RevertTextEncodingToScriptInfo(textEncoding, &scriptCode, &languageCode, NULL);
            localOK=LocaleRefFromLangOrRegionCode(languageCode, kTextRegionDontCare, &locale); 
            localOK=LocaleRefGetPartString(locale, kLocaleLanguageMask, 255, (char*) fontRecord->locale.language);			fontRecord->locale.language[255]='\0'; 
            localOK=LocaleRefGetPartString(locale, kLocaleLanguageVariantMask, 255, (char*) fontRecord->locale.languageVariant);	fontRecord->locale.languageVariant[255]='\0';
            localOK=LocaleRefGetPartString(locale, kLocaleRegionMask, 255, (char*) fontRecord->locale.region);			fontRecord->locale.region[255]='\0';
            localOK=LocaleRefGetPartString(locale, kLocaleRegionVariantMask, 255, (char*) fontRecord->locale.regionVariant);	fontRecord->locale.regionVariant[255]='\0';
            localOK=LocaleRefGetPartString(locale, kLocaleAllPartsMask, 255, (char*) fontRecord->locale.fullName);		fontRecord->locale.fullName[255]='\0';

			// Init for fontRecord (nearly) finished.
			
			// Set this fontRecord as head of font-list, or enqueue it in existing list:
            if(i==0) {
                PsychFontListHeadKeeper(TRUE, fontRecord); 
            }
			else {
                previousFontRecord->next=fontRecord;
            }
			
			// Set the font number field of the struct
            fontRecord->fontNumber=i+1;

            // Increment the font index and update the next font pointer
            ++i;
            previousFontRecord=fontRecord;
        }else if(halt == kATSIterationScopeModified){
            //exit because the font database changed during this loop.
            PsychFreeFontList();
            PsychErrorExitMsg(PsychError_internal, "The system font database was modified during font list setup. Please 'clear all' and restart your script.");
        }
		// Next parse iteration in system font database...
    }
	
    if(halt != kATSIterationCompleted){
        PsychFreeFontList();
        PsychErrorExitMsg(PsychError_internal, "Font iteration terminated prematurely. OS-X Font database corrupted?!?");
    }
	
	// Did we get a hand on at least one font?
	if (i==0) {
		if (PsychPrefStateGet_Verbosity() > 0) {
			printf("PTB-ERROR: In font initialization: Could not even retrieve one valid font from the system! The OS-X font database must be corrupt.\n");
			printf("PTB-ERROR: Will try to continue but will likely crash if your code tries to call any of the font handling or text drawing functions.\n");
			trouble = TRUE;
		}
	}
	
	if (trouble && PsychPrefStateGet_Verbosity() > 0) {
		printf("PTB-HINT: Go to the Application folder and open the 'Font Book' application. It allows you to check and repair your font database.\n");
	} 

    ATSFontIteratorRelease(&fontIterator);

    // Font database ready for use.
	return;
}
Exemplo n.º 13
0
/********************> LoadTGA() <*****/
bool upload_image(const unsigned char* filePath, bool hasalpha)
{
	if(visibleloading){
		loadscreencolor=1;
		pgame->LoadingScreen();
	}

#if 1

	// for Windows, just use TGA loader for now
	char fileName[ 256];
	CopyPascalStringToC( filePath, fileName);
/*
	// change extension to .TGA
	int len = strlen( fileName);
	if (len > 3)
	{
		fileName[ len - 3] = 't';
		fileName[ len - 2] = 'g';
		fileName[ len - 1] = 'a';
	}
*/
//	return (LoadTGA( fileName) != NULL);
	return (LoadImage(fileName, texture));

#else

	OSStatus err;
	ComponentResult cr;

	/*FSRef fsref;
	Boolean isdir;
	err = FSPathMakeRef((const UInt8*)filePath, &fsref, &isdir);
	if(err)return;

	FSSpec fsspec;
	err = FSGetCatalogInfo(&fsref, kFSCatInfoNone, NULL, NULL, &fsspec, NULL);
	if(err)return;
	*/

	//Boolean isdir;
	FSSpec fsspec;
	//err = FSMakeFSSpec (0, 0, (const unsigned char*)filePath, &fsspec);
	err = FSMakeFSSpec (0, 0, filePath, &fsspec);
	//err=FSPathMakeFSSpec((const UInt8*)filePath,&fsspec,&isdir);*/
	if(err)return;

	GraphicsImportComponent gi;
	err = GetGraphicsImporterForFile(&fsspec, &gi);
	if(err)return;

	Rect natbounds;
	cr = GraphicsImportGetNaturalBounds(gi, &natbounds);

	size_t buffersize = 4 * natbounds.bottom * natbounds.right;
	//void* buf = malloc(buffersize);
	texture.sizeX=natbounds.right;
	texture.sizeY=natbounds.bottom;
	/*if(hasalpha)*/texture.bpp = 32;
	//if(!hasalpha)texture.bpp = 24;

	GWorldPtr gw;
	err = QTNewGWorldFromPtr(&gw, k32ARGBPixelFormat, &natbounds, NULL, NULL,
		0, texture.data, 4 * natbounds.right);
	if(err)return;

	cr = GraphicsImportSetGWorld(gi, gw, NULL);

	natbounds.top = natbounds.bottom;
	natbounds.bottom = 0;

	cr = GraphicsImportSetBoundsRect(gi, &natbounds);

	cr = GraphicsImportDraw(gi);

	err = CloseComponent(gi);
	if(err)return;

	/*glTexImage2D(textureTarget, 0, GL_RGBA, natbounds.right, natbounds.top, 0,
	GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, buf);
	*/

	//free(buf);
	DisposeGWorld(gw);

	// Loop Through The Image Data
	GLuint			imageSize;									// Used To Store The Image Size When Setting Aside Ram
	GLuint			temp;										// Temporary Variable
	GLuint			bytesPerPixel;										// Temporary Variable
	bytesPerPixel=texture.bpp/8;
	imageSize = texture.sizeX * texture.sizeY * bytesPerPixel;
	int alltrans=10;

	for( GLuint i = 0; i < int( imageSize ); i += 4 )
	{
		// Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
		temp = texture.data[i];					// Temporarily Store The Value At Image Data 'i'
		texture.data[i] = texture.data[i + 1];	// Set The 1st Byte To The Value Of The 3rd Byte
		texture.data[i + 1] = texture.data[i + 2];				// Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
		texture.data[i + 2] = texture.data[i + 3];
		texture.data[i + 3] = temp;
	}

	int tempplace;
	tempplace=0;
	if(!hasalpha){
		for( GLuint i = 0; i < int( imageSize ); i += 4 )
		{
			texture.data[i + 3] = 255;
			/*texture.data[tempplace] = texture.data[i];	// Set The 1st Byte To The Value Of The 3rd Byte
			texture.data[tempplace + 1] = texture.data[i + 1];				// Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
			texture.data[tempplace + 2] = texture.data[i + 2];
			tempplace+=3;*/
		}
	}

	if(texdetail>1){
		int which=0;
		float temp;
		float howmany;
		for( GLuint k = 0; k < int( imageSize); k += bytesPerPixel*texture.sizeX*texdetail )
		{
			for( GLuint i = 0; i < int( imageSize/texture.sizeY ); i += bytesPerPixel*texdetail )
			{
				for( GLuint b = 0; b < bytesPerPixel ; b ++ ){	
					temp=0;
					howmany=0;
					for( GLuint l = 0; l < texdetail*texture.sizeX ; l +=texture.sizeX ){
						for( GLuint j = 0; j < texdetail ; j ++ )
						{
							temp += (int)texture.data[k+i+j*bytesPerPixel+l*bytesPerPixel+b];	// Set The 1st Byte To The Value Of The 3rd Byte
							howmany++;
						}
					}
					texture.data[which+b]=GLubyte(temp/howmany);
				}
				which+=bytesPerPixel;
			}
		}
		texture.sizeX/=texdetail;
		texture.sizeY/=texdetail;
	}

	return true;

#endif
}
Exemplo n.º 14
0
int printOnOSXPascal(unsigned char *string) {
	CopyPascalStringToC((ConstStr255Param) string,(char*) string);
	printOnOSX((char*) string);
	CopyCStringToPascal((char*)string,(void *) string);
}
Exemplo n.º 15
0
/*
    PsychInitFontList()
    
    Build a list of records describing installed fonts.
    
    
*/
void PsychInitFontList(void)
{
    ATSFontRef			tempATSFontRef;
#ifdef __LP64__
    CTFontRef           tempCTFontRef;
#endif
    //for font structures
    PsychFontStructPtrType	fontListHead, fontRecord, previousFontRecord;
    //for ATI font iteration
    ATSFontIterator		fontIterator;
    OSStatus			halt;
    //for font field names
    CFStringRef 		cfFontName;
    int                 i, j;
    psych_bool			resultOK;
    //for font file
    OSStatus			osStatus;			
    FSSpec              fontFileSpec;
    FSRef               fontFileRef;
    //for the font metrics
    ATSFontMetrics		horizontalMetrics;
    ATSFontMetrics		verticalMetrics;
    //for info from Font Manager 
    FMFontStyle			fmStyle;
    OSStatus			fmStatus;
    Str255				fmFontFamilyNamePString;
    //whatever
    Str255              fontFamilyQuickDrawNamePString;
    TextEncoding		textEncoding;
    OSStatus			scriptInfoOK;
    ScriptCode			scriptCode;
    LangCode			languageCode;
    OSStatus			localOK;
    LocaleRef			locale;
	psych_bool			trouble = FALSE;

    fontListHead=PsychFontListHeadKeeper(FALSE, NULL); //get the font list head.
    if(fontListHead) PsychErrorExitMsg(PsychError_internal, "Attempt to set new font list head when one is already set.");
        
    fontRecord = NULL;
    fontIterator = NULL;
    halt = ATSFontIteratorCreate(PSYCH_ATS_ITERATOR_CONTEXT, NULL, NULL, PSYCH_ATS_ITERATOR_SCOPE, &fontIterator);
    i = 0;
	
    while (halt==noErr) {
        // Give repair hints early and obnoxiously. Experience shows we might crash during enumeration of a
        // corrupt OSX font database, so make sure we get out the helpful message as early as possible. Doing
        // this (just) at the end of enumeration might be too late - we might never get there...
        if (trouble && PsychPrefStateGet_Verbosity() > 0) {
            printf("\nPTB-HINT: ========================================================================================================================\n");
            printf("PTB-HINT: Go to the Application folder and open the 'Font Book' application. It allows you to check and repair your font database.\n");
            printf("PTB-HINT: Run its 'Validate' function on all installed fonts. Another thing you could try is downloading and running the free\n");
            printf("PTB-HINT: FontNuke application (Google will find it for you) to regenerate corrupt OSX font caches. Good luck!\n");
            printf("PTB-HINT: ========================================================================================================================\n\n");
        }

        halt=ATSFontIteratorNext(fontIterator, &tempATSFontRef);
        if(halt==noErr){
            //create a new  font  font structure.  Set the next field  to NULL as  soon as we allocate the font so that if 
            //we break with an error then we can find the end when we  walk down the linked list. 
            fontRecord=(PsychFontStructPtrType) calloc(1, sizeof(PsychFontStructType));
            fontRecord->next=NULL;

            //Get  FM and ATS font and font family references from the ATS font reference, which we get from iteration.
            fontRecord->fontATSRef=tempATSFontRef; 
            fontRecord->fontFMRef=FMGetFontFromATSFontRef(fontRecord->fontATSRef);

#ifndef __LP64__
            fmStatus=FMGetFontFamilyInstanceFromFont(fontRecord->fontFMRef, &(fontRecord->fontFamilyFMRef), &fmStyle);
            fontRecord->fontFamilyATSRef = FMGetATSFontFamilyRefFromFontFamily(fontRecord->fontFamilyFMRef);
#else            
            // Create CTFont from given ATSFontRef. Available since OSX 10.5
            tempCTFontRef = CTFontCreateWithPlatformFont(fontRecord->fontATSRef, 0.0, NULL, NULL);
            if (tempCTFontRef) {
                // Get font family name from CTFont:
                CFStringRef cfFamilyName = CTFontCopyFamilyName(tempCTFontRef);
                
                // Retrieve symbolic traits of font -- the closest equivalent of the fmStyle from the
                // good'ol fontManager:
                CTFontSymbolicTraits ctTraits = CTFontGetSymbolicTraits(tempCTFontRef);
                
                // Remap new trait constants to old constants for later Screen('TextStyle') matching.
                fmStyle = 0;
                if (ctTraits & kCTFontBoldTrait) fmStyle |= 1;
                if (ctTraits & kCTFontItalicTrait) fmStyle |= 2;
                if (ctTraits & kCTFontCondensedTrait) fmStyle |= 32;
                if (ctTraits & kCTFontExpandedTrait) fmStyle |= 64;
                
                // CTFont no longer needed:
                CFRelease(tempCTFontRef);
                
                // Convert to C-String and assign:
                resultOK = cfFamilyName && CFStringGetCString(cfFamilyName, (char*) fontRecord->fontFMFamilyName, 255, kCFStringEncodingASCII);
                if(!resultOK){
                    if (cfFamilyName) CFRelease(cfFamilyName);
                    if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to retrieve font family name for font... Defective font?!? Skipped this entry...\n");
                    trouble = TRUE;
                    continue;
                }
                
                // Get ATSRef for font family:
                fontRecord->fontFamilyATSRef = ATSFontFamilyFindFromName(cfFamilyName, kATSOptionFlagsDefault);
                CFRelease(cfFamilyName);
            }
            else {
                if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to retrieve CTFontRef for font... Defective font?!? Skipped this entry...\n");
                trouble = TRUE;
                continue;
            }
#endif

            //get the font name and set the the corresponding field of the struct
            if (ATSFontGetName(fontRecord->fontATSRef, kATSOptionFlagsDefault, &cfFontName)!=noErr) {
				if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to query font name in ATSFontGetName! OS-X font handling screwed up?!? Skipped this entry...\n");
				trouble = TRUE;
				continue;
            }
            
            resultOK = cfFontName && CFStringGetCString(cfFontName, (char*) fontRecord->fontFMName, 255, kCFStringEncodingASCII);
            if(!resultOK){
                if (cfFontName) CFRelease(cfFontName);
				if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to convert fontFMName CF string to char string. Defective font?!? Skipped this entry...\n");
				trouble = TRUE;
				continue;
            }
            CFRelease(cfFontName);

            //get the font postscript name and set the corresponding field of the struct
            if (ATSFontGetPostScriptName(fontRecord->fontATSRef, kATSOptionFlagsDefault, &cfFontName)!=noErr) {
                if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: The following font makes trouble: %s. Please REMOVE the offending font file from your font folders and restart Matlab. Skipped entry for now...\n", fontRecord->fontFMName);
				trouble = TRUE;
				continue;
            }

            resultOK = cfFontName && CFStringGetCString(cfFontName, (char*) fontRecord->fontPostScriptName, 255, kCFStringEncodingASCII); //kCFStringEncodingASCII matches MATLAB for 0-127
            if(!resultOK){
                if (cfFontName) CFRelease(cfFontName);
				if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to convert fontPostScriptName CF string to char string for font %s. Defective font?!? Skipped this entry...\n", fontRecord->fontFMName);
				trouble = TRUE;
				continue;
            }
            CFRelease(cfFontName);

            // Get the QuickDraw name of the font:
            fontRecord->fontFamilyQuickDrawName[0] = 0;
            fontFamilyQuickDrawNamePString[0] = 0;
            ATSFontFamilyGetQuickDrawName(fontRecord->fontFamilyATSRef, fontFamilyQuickDrawNamePString);
            #ifndef __LP64__
            CopyPascalStringToC(fontFamilyQuickDrawNamePString, (char*) fontRecord->fontFamilyQuickDrawName);
            #else
            for (j = 0; j < fontFamilyQuickDrawNamePString[0]; j++) fontRecord->fontFamilyQuickDrawName[j] = fontFamilyQuickDrawNamePString[j+1];
            fontRecord->fontFamilyQuickDrawName[j] = 0;
            #endif

            #ifndef __LP64__
            // Get the font file used for this font
            osStatus = ATSFontGetFileSpecification(fontRecord->fontATSRef, &fontFileSpec);
            if(osStatus != noErr) {
				if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to get the font file specifier for font %s. Defective font?!? Skipped this entry...\n", fontRecord->fontFMName);
				trouble = TRUE;
				continue;
			}

            FSpMakeFSRef(&fontFileSpec, &fontFileRef);
            #else
            // 64-Bit version, available since OSX 10.5:
            osStatus = ATSFontGetFileReference(fontRecord->fontATSRef, &fontFileRef);
            if(osStatus != noErr) {
				if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to get the font file specifier for font %s. Defective font?!? Skipped this entry...\n", fontRecord->fontFMName);
				trouble = TRUE;
				continue;
			}
            #endif

            osStatus= FSRefMakePath(&fontFileRef, (UInt8*) fontRecord->fontFile, (UInt32)(kPsychMaxFontFileNameChars - 1));
            if(osStatus!=noErr){
				if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to get the font file path for font %s. Defective font?!? Skipped this entry...\n", fontRecord->fontFMName);
				trouble = TRUE;
				continue;
            }

            //get the font metrics of this font.
            //Explicit copy between fields to make it clear what is going one, will likely have to mix & match between native and Psych structures for different
            //platforms.
            ATSFontGetHorizontalMetrics(fontRecord->fontATSRef, kATSOptionFlagsDefault, &horizontalMetrics);
            ATSFontGetVerticalMetrics(fontRecord->fontATSRef, kATSOptionFlagsDefault, &verticalMetrics);
            //horizontal
            fontRecord->horizontalMetrics.ascent=			horizontalMetrics.ascent;
            fontRecord->horizontalMetrics.descent=			horizontalMetrics.descent;
            fontRecord->horizontalMetrics.leading=			horizontalMetrics.leading;
            fontRecord->horizontalMetrics.avgAdvanceWidth=		horizontalMetrics.avgAdvanceWidth;
            fontRecord->horizontalMetrics.minLeftSideBearing=		horizontalMetrics.minLeftSideBearing;
            fontRecord->horizontalMetrics.minRightSideBearing=		horizontalMetrics.minRightSideBearing;
            fontRecord->horizontalMetrics.stemWidth=			horizontalMetrics.stemWidth;
            fontRecord->horizontalMetrics.stemHeight=			horizontalMetrics.stemHeight;
            fontRecord->horizontalMetrics.capHeight=			horizontalMetrics.capHeight;
            fontRecord->horizontalMetrics.xHeight=			horizontalMetrics.xHeight;
            fontRecord->horizontalMetrics.italicAngle=			horizontalMetrics.italicAngle;
            fontRecord->horizontalMetrics.underlinePosition=		horizontalMetrics.underlinePosition;
            fontRecord->horizontalMetrics.underlineThickness=		horizontalMetrics.underlineThickness;
            fontRecord->horizontalMetrics.underlineThickness=		horizontalMetrics.underlineThickness;
            //vertical
            fontRecord->verticalMetrics.ascent=				verticalMetrics.ascent;
            fontRecord->verticalMetrics.descent=			verticalMetrics.descent;
            fontRecord->verticalMetrics.leading=			verticalMetrics.leading;
            fontRecord->verticalMetrics.avgAdvanceWidth=		verticalMetrics.avgAdvanceWidth;
            fontRecord->verticalMetrics.minLeftSideBearing=		verticalMetrics.minLeftSideBearing;
            fontRecord->verticalMetrics.minRightSideBearing=		verticalMetrics.minRightSideBearing;
            fontRecord->verticalMetrics.stemWidth=			verticalMetrics.stemWidth;
            fontRecord->verticalMetrics.stemHeight=			verticalMetrics.stemHeight;
            fontRecord->verticalMetrics.capHeight=			verticalMetrics.capHeight;
            fontRecord->verticalMetrics.xHeight=			verticalMetrics.xHeight;
            fontRecord->verticalMetrics.italicAngle=			verticalMetrics.italicAngle;
            fontRecord->verticalMetrics.underlinePosition=		verticalMetrics.underlinePosition;
            fontRecord->verticalMetrics.underlineThickness=		verticalMetrics.underlineThickness;
            fontRecord->verticalMetrics.underlineThickness=		verticalMetrics.underlineThickness;

            // On 32-Bit use Font Manager to get the FM  font family name font style.
            // This has been already done above for 64-Bit:
            #ifndef __LP64__
            fmStatus=FMGetFontFamilyName(fontRecord->fontFamilyFMRef, fmFontFamilyNamePString);
            if(fmStatus!=noErr){
				if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: In font initialization: Failed to get the fontFMFamilyName for font %s. Defective font?!? Skipped this entry...\n", fontRecord->fontFMName);
				trouble = TRUE;
				continue;
            }
            CopyPascalStringToC(fmFontFamilyNamePString, (char*) fontRecord->fontFMFamilyName);
            #endif
            
            fontRecord->fontFMStyle=fmStyle;
            fontRecord->fontFMNumStyles=PsychFindNumFMFontStylesFromStyle(fmStyle);
            fontRecord->fontFMNumStyles= fontRecord->fontFMNumStyles ? fontRecord->fontFMNumStyles : 1; //because the name is "normal" even if there are no styles.  
            // Get the locale info which is a property of the font family:
            // No error checking is done here, because many (most?) fonts miss the information,
            // so we would error-out all the time and this is non-critical for us:
            textEncoding=ATSFontFamilyGetEncoding(fontRecord->fontFamilyATSRef);
            scriptInfoOK=RevertTextEncodingToScriptInfo(textEncoding, &scriptCode, &languageCode, NULL);
            localOK=LocaleRefFromLangOrRegionCode(languageCode, kTextRegionDontCare, &locale); 
            localOK |= LocaleRefGetPartString(locale, kLocaleLanguageMask, 255, (char*) fontRecord->locale.language);			fontRecord->locale.language[255]='\0'; 
            localOK |= LocaleRefGetPartString(locale, kLocaleLanguageVariantMask, 255, (char*) fontRecord->locale.languageVariant);	fontRecord->locale.languageVariant[255]='\0';
            localOK |= LocaleRefGetPartString(locale, kLocaleRegionMask, 255, (char*) fontRecord->locale.region);			fontRecord->locale.region[255]='\0';
            localOK |= LocaleRefGetPartString(locale, kLocaleRegionVariantMask, 255, (char*) fontRecord->locale.regionVariant);	fontRecord->locale.regionVariant[255]='\0';
            localOK |= LocaleRefGetPartString(locale, kLocaleAllPartsMask, 255, (char*) fontRecord->locale.fullName);		fontRecord->locale.fullName[255]='\0';
            
			// Init for fontRecord (nearly) finished.
			
			// Set this fontRecord as head of font-list, or enqueue it in existing list:
            if(i==0) {
                PsychFontListHeadKeeper(TRUE, fontRecord); 
            }
			else {
                previousFontRecord->next=fontRecord;
            }
			
			// Set the font number field of the struct
            fontRecord->fontNumber=i+1;

            // Increment the font index and update the next font pointer
            ++i;
            previousFontRecord=fontRecord;
        }else if(halt == kATSIterationScopeModified){
            //exit because the font database changed during this loop.
            PsychFreeFontList();
            if (fontIterator) ATSFontIteratorRelease(&fontIterator);
            PsychErrorExitMsg(PsychError_system, "The system font database was modified during font list setup. Please 'clear all' and restart your script.");
        }
		// Next parse iteration in system font database...
    }
	
    if (fontIterator) ATSFontIteratorRelease(&fontIterator);
    
    if(halt != kATSIterationCompleted){
        PsychFreeFontList();
        trouble = TRUE;
        if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: Font iteration during enumeration terminated prematurely. OS-X Font database corrupted?!?");
    }
	
	// Did we get a hand on at least one font?
	if (i==0) {
        PsychFreeFontList();
        trouble = TRUE;
		if (PsychPrefStateGet_Verbosity() > 0) {
			printf("PTB-ERROR: In font initialization: Could not even retrieve one valid font from the system! The OS-X font database must be corrupt.\n");
			printf("PTB-ERROR: Will try to continue but will likely abort if your code tries to call any of the font handling or text drawing functions.\n");
		}
	}
	
	if (trouble && PsychPrefStateGet_Verbosity() > 0) {
		printf("PTB-HINT: ========================================================================================================================\n");
		printf("PTB-HINT: Go to the Application folder and open the 'Font Book' application. It allows you to check and repair your font database.\n");
        printf("PTB-HINT: Run its 'Validate' function on all installed fonts. Another thing you could try is downloading and running the free\n");
        printf("PTB-HINT: FontNuke application (Google will find it for you) to regenerate corrupt OSX font caches. Good luck!\n");
		printf("PTB-HINT: ========================================================================================================================\n");
	} 

    // Font database ready for use.
	return;
}