StAcroResourceContext::StAcroResourceContext(short resFile)
	: mCurResFile(resFile)
{
#if TARGET_API_MAC_CARBON
	mOldResFile = CurResFile();

	if( mCurResFile )
		UseResFile(mCurResFile);
			
#else

	mOldResFile = PreCarbonSetupResourceChain( );
	
#endif
}
Exemplo n.º 2
0
  /* Create a new FT_Face from a file spec to a suitcase file. */
  static FT_Error
  FT_New_Face_From_dfont( FT_Library  library,
                          FSSpec*     spec,
                          FT_Long     face_index,
                          FT_Face*    aface )
  {
    FT_Error  error = FT_Err_Ok;
    short     res_ref, res_index;
    Handle    fond;
    FSRef     hostContainerRef;


    error = FSpMakeFSRef( spec, &hostContainerRef );
    if ( error == noErr )
      error = FSOpenResourceFile( &hostContainerRef,
                                  0, NULL, fsRdPerm, &res_ref );

    if ( error != noErr )
      return FT_Err_Cannot_Open_Resource;

    UseResFile( res_ref );

    /* face_index may be -1, in which case we
       just need to do a sanity check */
    if ( face_index < 0 )
      res_index = 1;
    else
    {
      res_index = (short)( face_index + 1 );
      face_index = 0;
    }
    fond = Get1IndResource( 'FOND', res_index );
    if ( ResError() )
    {
      error = FT_Err_Cannot_Open_Resource;
      goto Error;
    }

    error = FT_New_Face_From_FOND( library, fond, face_index, aface );

  Error:
    CloseResFile( res_ref );
    return error;
  }
Exemplo n.º 3
0
  /* Create a new FT_Face from a file spec to a suitcase file. */
  static FT_Error
  FT_New_Face_From_Suitcase( FT_Library    library,
                             const UInt8*  pathname,
                             FT_Long       face_index,
                             FT_Face*      aface )
  {
    FT_Error       error = FT_ERR( Cannot_Open_Resource );
    ResFileRefNum  res_ref;
    ResourceIndex  res_index;
    Handle         fond;
    short          num_faces_in_res;


    if ( noErr != FT_FSPathMakeRes( pathname, &res_ref ) )
      return FT_THROW( Cannot_Open_Resource );

    UseResFile( res_ref );
    if ( ResError() )
      return FT_THROW( Cannot_Open_Resource );

    num_faces_in_res = 0;
    for ( res_index = 1; ; ++res_index )
    {
      short  num_faces_in_fond;


      fond = Get1IndResource( TTAG_FOND, res_index );
      if ( ResError() )
        break;

      num_faces_in_fond  = count_faces( fond, pathname );
      num_faces_in_res  += num_faces_in_fond;

      if ( 0 <= face_index && face_index < num_faces_in_fond && error )
        error = FT_New_Face_From_FOND( library, fond, face_index, aface );

      face_index -= num_faces_in_fond;
    }

    CloseResFile( res_ref );
    if ( !error && aface )
      (*aface)->num_faces = num_faces_in_res;
    return error;
  }
Exemplo n.º 4
0
OSErr CallImportPlug( 		MADLibrary		*inMADDriver,
													short					PlugNo,			// CODE du plug
													OSType				order,
													char					*AlienFile,
													MADMusic			*theNewMAD,
													PPInfoRec			*info)
{
	OSErr					myErr;
	short					fileID = 0;
	MADDriverSettings		driverSettings;
	CFragConnectionID		connID;
	Ptr						mainAddr;
	Str255					errName;
	static OSErr			(*mainPLUG)( OSType, char*, MADMusic*, PPInfoRec*, MADDriverSettings *);

	driverSettings.sysMemory = false;

	if( !EqualString( RSRCNAME, inMADDriver->ThePlug[ PlugNo].file.name, false, false))
	{
		fileID = FSpOpenResFile( &inMADDriver->ThePlug[ PlugNo].file, fsCurPerm);
		UseResFile( fileID);
	}
	
	myErr = GetDiskFragment( &inMADDriver->ThePlug[ PlugNo].file, 0, kCFragGoesToEOF, inMADDriver->ThePlug[ PlugNo].file.name, kLoadCFrag, &connID, (Ptr *) &mainPLUG, errName);

	if( myErr == noErr)
	{
		myErr = mainPLUG ( order, AlienFile, theNewMAD, info, &driverSettings);
		
//			DisposePtr( (Ptr) mainPLUG);
		
		CloseConnection( &connID);
	}

//	myErr = TESTmain( order, AlienFile, theNewMAD, info, &driverSettings);
	
	if( !EqualString( RSRCNAME, inMADDriver->ThePlug[ PlugNo].file.name, false, false))
		CloseResFile( fileID);
	
//	theNewMAD->currentDriver = NULL;
	
	return( myErr);
}
Exemplo n.º 5
0
static PyObject *Res_UseResFile(PyObject *_self, PyObject *_args)
{
    PyObject *_res = NULL;
    short refNum;
#ifndef UseResFile
    PyMac_PRECHECK(UseResFile);
#endif
    if (!PyArg_ParseTuple(_args, "h",
                          &refNum))
        return NULL;
    UseResFile(refNum);
    {
        OSErr _err = ResError();
        if (_err != noErr) return PyMac_Error(_err);
    }
    Py_INCREF(Py_None);
    _res = Py_None;
    return _res;
}
Exemplo n.º 6
0
int read_setting_i(void *handle, char const *key, int defvalue) {
    int fd;
    Handle h;
    int value;
    Str255 pkey;

    if (handle == NULL) goto out;
    fd = *(int *)handle;
    UseResFile(fd);
    if (ResError() != noErr) goto out;
    c2pstrcpy(pkey, key);
    h = Get1NamedResource(FOUR_CHAR_CODE('Int '), pkey);
    if (h == NULL) goto out;
    value = *(int *)*h;
    ReleaseResource(h);
    if (ResError() != noErr) goto out;
    return value;

  out:
    return defvalue;
}
Exemplo n.º 7
0
  /* Create a new FT_Face from a file spec to a suitcase file. */
  static FT_Error
  FT_New_Face_From_Suitcase( FT_Library    library,
                             const UInt8*  pathname,
                             FT_Long       face_index,
                             FT_Face*      aface )
  {
    FT_Error  error = FT_Err_Cannot_Open_Resource;
    short     res_ref, res_index;
    Handle    fond;
    short     num_faces_in_res, num_faces_in_fond;


    if ( noErr != FT_FSPathMakeRes( pathname, &res_ref ) )
      return FT_Err_Cannot_Open_Resource;

    UseResFile( res_ref );
    if ( ResError() )
      return FT_Err_Cannot_Open_Resource;

    num_faces_in_res = 0;
    for ( res_index = 1; ; ++res_index )
    {
      fond = Get1IndResource( 'FOND', res_index );
      if ( ResError() )
        break;

      num_faces_in_fond  = count_faces( fond, pathname );
      num_faces_in_res  += num_faces_in_fond;

      if ( 0 <= face_index && face_index < num_faces_in_fond && error )
        error = FT_New_Face_From_FOND( library, fond, face_index, aface );

      face_index -= num_faces_in_fond;
    }

    CloseResFile( res_ref );
    if ( FT_Err_Ok == error && NULL != aface )
      (*aface)->num_faces = num_faces_in_res;
    return error;
  }
Exemplo n.º 8
0
int read_setting_filename(void *handle, const char *key, Filename *result)
{
    int fd;
    AliasHandle h;
    Boolean changed;
    OSErr err;
    Str255 pkey;

    if (handle == NULL) goto out;
    fd = *(int *)handle;
    UseResFile(fd);
    if (ResError() != noErr) goto out;
    c2pstrcpy(pkey, key);
    h = (AliasHandle)Get1NamedResource(rAliasType, pkey);
    if (h == NULL) goto out;
    if ((*h)->userType == 'pTTY' && (*h)->aliasSize == sizeof(**h))
	memset(result, 0, sizeof(*result));
    else {
	err = ResolveAlias(NULL, h, &result->fss, &changed);
	if (err != noErr && err != fnfErr) goto out;
	if ((*h)->userType == 'pTTY') {
	    long dirid;
	    StrFileName fname;

	    /* Tail of record is pascal string contaning leafname */
	    if (FSpGetDirID(&result->fss, &dirid, FALSE) != noErr) goto out;
	    memcpy(fname, (char *)*h + (*h)->aliasSize,
		   GetHandleSize((Handle)h) - (*h)->aliasSize);
	    err = FSMakeFSSpec(result->fss.vRefNum, dirid, fname,
			       &result->fss);
	    if (err != noErr && err != fnfErr) goto out;
	}
    }
    ReleaseResource((Handle)h);
    if (ResError() != noErr) goto out;
    return 1;

  out:
    return 0;
}
Exemplo n.º 9
0
// pass resFile as -1 to use the current file
OSErr BetterAddResource(short resFile,Handle theData,ResType type,short *id,StringPtr name,short mode)
{
	short		oldResFile=::CurResFile();
	OSErr		err=noErr;
	
	if (resFile!=-1)
		UseResFile(resFile);
	// If this resource exists then we may have some problems
	if (ResourceExists(-1,type,*id))
	{
		switch (mode)
		{
			case kOverwriteResource:
				if (!DeleteResource(-1,type,*id))
					err=rmvResFailed;
				break;
				
			case kUniqueID:
				*id=Unique1ID(type);
				break;
				
			case kBottleIt:
				err=userCanceledErr;
				break;
		}
	}
	
	if (!err)
	{
		// Now there is space for the resource lets add it
		AddResource(theData,type,*id,name ? name:"\p");
		err=ResError();
		if (err==noErr)
		{
			WriteResource(theData);
			err=ResError();
		}
	}
Exemplo n.º 10
0
  /* Create a new FT_Face from a file spec to a suitcase file. */
  static FT_Error
  FT_New_Face_From_Suitcase( FT_Library  library,
                             FSSpec*     spec,
                             FT_Long     face_index,
                             FT_Face    *aface )
  {
    FT_Error  error = FT_Err_Ok;
    short     res_ref, res_index;
    Handle    fond;


    res_ref = FSpOpenResFile( spec, fsRdPerm );
    if ( ResError() )
      return FT_Err_Cannot_Open_Resource;
    UseResFile( res_ref );

    /* face_index may be -1, in which case we
       just need to do a sanity check */
    if ( face_index < 0 )
      res_index = 1;
    else
    {
      res_index = (short)( face_index + 1 );
      face_index = 0;
    }
    fond = Get1IndResource( 'FOND', res_index );
    if ( ResError() )
    {
      error = FT_Err_Cannot_Open_Resource;
      goto Error;
    }

    error = FT_New_Face_From_FOND( library, fond, face_index, aface );

  Error:
    CloseResFile( res_ref );
    return error;
  }
Exemplo n.º 11
0
void write_setting_s(void *handle, char const *key, char const *value) {
    int fd = *(int *)handle;
    Handle h;
    int id;
    OSErr error;
    Str255 pkey;

    UseResFile(fd);
    if (ResError() != noErr)
        fatalbox("Failed to open saved session (%d)", ResError());

    error = PtrToHand(value, &h, strlen(value));
    if (error != noErr)
	fatalbox("Failed to allocate memory");
    /* Put the data in a resource. */
    id = Unique1ID(FOUR_CHAR_CODE('TEXT'));
    if (ResError() != noErr)
	fatalbox("Failed to get ID for resource %s (%d)", key, ResError());
    c2pstrcpy(pkey, key);
    AddResource(h, FOUR_CHAR_CODE('TEXT'), id, pkey);
    if (ResError() != noErr)
	fatalbox("Failed to add resource %s (%d)", key, ResError());
}
Exemplo n.º 12
0
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	Name:	MyPDEInitialize

	Input Parameters:
		context			:	The plugins context
		parentUserPane		:	the user pane to your your controls into
		ref			:	the reference to this PDE
		printSession		:	this holds the PM tickets
		
	Output Parameters:
		flags			:	feature flags that are supported by this PDE
		err			:	returns the error status

	Description:
		Initializes client interface. Creates controls and sets initial values


	
	Change History (most recent first):
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
static 
OSStatus MyPDEInitialize(	PMPDEContext	context, 
                        PMPDEFlags*		flags,
                        PMPDERef		ref,
                        ControlRef		parentUserPane,
                        PMPrintSession	printSession)
{
    OSStatus err = noErr;
    PageSetupPDEOnlyContextPtr myContext = NULL;	// Pointer to global data block.

    DebugMessage("PageSetupPDE MyPDEInitialize called\n");
    
    myContext = (PageSetupPDEOnlyContextPtr) context;
    
    if ((myContext != NULL) && (printSession != NULL))
    {		
		WindowRef theWindow = NULL;
		short savedResFile = CurResFile();
		UseResFile(myContext->theResFile);

		theWindow = GetControlOwner(parentUserPane);	// get the windowref from the user pane
		
		// the user panes rect is the rect we should use to draw our
		// controls into. The printing system calculates the user pane
		// size based on the maxh and maxv sizes returned from the 
		// Prologue function
		
		// Note that we are using the AutoToggleProc variant of the Radio Button control
		// This allows a hit on this control to be automatically processed by the ControlMgr
	
		// get controls
		myContext->thePrintTitleControlRef = GetNewControl(kPageSetupPDEControlID, theWindow);
	
		// embed controls
		EmbedControl(myContext->thePrintTitleControlRef, parentUserPane);
	
		// set controls as visible
		SetControlVisibility(myContext->thePrintTitleControlRef, true, false);
	
		// Set default value
		SetControlValue(myContext->thePrintTitleControlRef, 0);
		
		// Set flags
		*flags = kPMPDENoFlags;
		
		// Initialize this plugins controls based on the information in the 
		// PageSetup or PrintSettings ticket.
		err = MyPDESync(context, printSession, kSyncDirectionSetUserInterface);
		if (err == kPMKeyNotFound)
			err = noErr;

		UseResFile(savedResFile);
	}
    else
		err = kPMInvalidPDEContext;

    DebugPrintErr(err, "PageSetupPDE Error from MyPDEInitialize returned %d\n");

	return (err);

}
char *QTTarg_GetStringFromUser (short thePromptStringIndex)
{
	short 			myItem;
	short 			mySavedResFile;
	GrafPtr			mySavedPort;
	DialogPtr		myDialog = NULL;
	short			myItemKind;
	Handle			myItemHandle;
	Rect			myItemRect;
	Str255			myString;
	char			*myCString = NULL;
	OSErr			myErr = noErr;

	//////////
	//
	// save the current resource file and graphics port
	//
	//////////

	mySavedResFile = CurResFile();
	GetPort(&mySavedPort);

	// set the application's resource file
	UseResFile(gAppResFile);

	//////////
	//
	// create the dialog box in which the user will enter a URL
	//
	//////////

	myDialog = GetNewDialog(kGetStr_DLOGID, NULL, (WindowPtr)-1L);
	if (myDialog == NULL)
		goto bail;

	QTFrame_ActivateController(QTFrame_GetFrontMovieWindow(), false);
	
	MacSetPort(GetDialogPort(myDialog));
	
	SetDialogDefaultItem(myDialog, kGetStr_OKButton);
	SetDialogCancelItem(myDialog, kGetStr_CancelButton);
	
	// set the prompt string	
	GetIndString(myString, kTextKindsResourceID, thePromptStringIndex);

	GetDialogItem(myDialog, kGetStr_StrLabelItem, &myItemKind, &myItemHandle, &myItemRect);
	SetDialogItemText(myItemHandle, myString);
	
	MacShowWindow(GetDialogWindow(myDialog));
	
	//////////
	//
	// display and handle events in the dialog box until the user clicks OK or Cancel
	//
	//////////
	
	do {
		ModalDialog(gModalFilterUPP, &myItem);
	} while ((myItem != kGetStr_OKButton) && (myItem != kGetStr_CancelButton));
	
	//////////
	//
	// handle the selected button
	//
	//////////
	
	if (myItem != kGetStr_OKButton) {
		myErr = userCanceledErr;
		goto bail;
	}
	
	// retrieve the edited text
	GetDialogItem(myDialog, kGetStr_StrTextItem, &myItemKind, &myItemHandle, &myItemRect);
	GetDialogItemText(myItemHandle, myString);
	myCString = QTUtils_ConvertPascalToCString(myString);
	
bail:
	// restore the previous resource file and graphics port
	MacSetPort(mySavedPort);
	UseResFile(mySavedResFile);
	
	if (myDialog != NULL)
		DisposeDialog(myDialog);

	return(myCString);
}
Exemplo n.º 14
0
bool PluginPackage::fetchInfo()
{
    if (!load())
        return false;

    WTF::RetainPtr<CFDictionaryRef> mimeDict;

    WTF::RetainPtr<CFTypeRef> mimeTypesFileName = CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginMIMETypesFilename"));
    if (mimeTypesFileName && CFGetTypeID(mimeTypesFileName.get()) == CFStringGetTypeID()) {

        WTF::RetainPtr<CFStringRef> fileName = (CFStringRef)mimeTypesFileName.get();
        WTF::RetainPtr<CFStringRef> homeDir = homeDirectoryPath().createCFString();
        WTF::RetainPtr<CFStringRef> path = CFStringCreateWithFormat(0, 0, CFSTR("%@/Library/Preferences/%@"), homeDir.get(), fileName.get());

        WTF::RetainPtr<CFDictionaryRef> plist = readPListFile(path.get(), /*createFile*/ false, m_module);
        if (plist) {
            // If the plist isn't localized, have the plug-in recreate it in the preferred language.
            WTF::RetainPtr<CFStringRef> localizationName =
                (CFStringRef)CFDictionaryGetValue(plist.get(), CFSTR("WebPluginLocalizationName"));
            CFLocaleRef locale = CFLocaleCopyCurrent();
            if (localizationName != CFLocaleGetIdentifier(locale))
                plist = readPListFile(path.get(), /*createFile*/ true, m_module);

            CFRelease(locale);
        } else {
            // Plist doesn't exist, ask the plug-in to create it.
            plist = readPListFile(path.get(), /*createFile*/ true, m_module);
        }

        mimeDict = (CFDictionaryRef)CFDictionaryGetValue(plist.get(), CFSTR("WebPluginMIMETypes"));
    }

    if (!mimeDict)
        mimeDict = (CFDictionaryRef)CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginMIMETypes"));

    if (mimeDict) {
        CFIndex propCount = CFDictionaryGetCount(mimeDict.get());
        Vector<const void*, 128> keys(propCount);
        Vector<const void*, 128> values(propCount);
        CFDictionaryGetKeysAndValues(mimeDict.get(), keys.data(), values.data());
        for (int i = 0; i < propCount; ++i) {
            String mimeType = (CFStringRef)keys[i];
            mimeType = mimeType.lower();

            WTF::RetainPtr<CFDictionaryRef> extensionsDict = (CFDictionaryRef)values[i];

            WTF:RetainPtr<CFNumberRef> enabled = (CFNumberRef)CFDictionaryGetValue(extensionsDict.get(), CFSTR("WebPluginTypeEnabled"));
            if (enabled) {
                int enabledValue = 0;
                if (CFNumberGetValue(enabled.get(), kCFNumberIntType, &enabledValue) && enabledValue == 0)
                    continue;
            }

            Vector<String> mimeExtensions;
            WTF::RetainPtr<CFArrayRef> extensions = (CFArrayRef)CFDictionaryGetValue(extensionsDict.get(), CFSTR("WebPluginExtensions"));
            if (extensions) {
                CFIndex extensionCount = CFArrayGetCount(extensions.get());
                for (CFIndex i = 0; i < extensionCount; ++i) {
                    String extension =(CFStringRef)CFArrayGetValueAtIndex(extensions.get(), i);
                    extension = extension.lower();
                    mimeExtensions.append(extension);
                }
            }
            m_mimeToExtensions.set(mimeType, mimeExtensions);

            String description = (CFStringRef)CFDictionaryGetValue(extensionsDict.get(), CFSTR("WebPluginTypeDescription"));
            m_mimeToDescriptions.set(mimeType, description);
        }

        m_name = (CFStringRef)CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginName"));
        m_description = (CFStringRef)CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginDescription"));

    } else {
        int resFile = CFBundleOpenBundleResourceMap(m_module);

        UseResFile(resFile);

        Vector<String> mimes = stringListFromResourceId(MIMEListStringStringNumber);

        if (mimes.size() % 2 != 0)
            return false;

        Vector<String> descriptions = stringListFromResourceId(MIMEDescriptionStringNumber);
        if (descriptions.size() != mimes.size() / 2)
            return false;

        for (size_t i = 0;  i < mimes.size(); i += 2) {
            String mime = mimes[i].lower();
            Vector<String> extensions;
            mimes[i + 1].lower().split(UChar(','), extensions);

            m_mimeToExtensions.set(mime, extensions);

            m_mimeToDescriptions.set(mime, descriptions[i / 2]);
        }

        Vector<String> names = stringListFromResourceId(PluginNameOrDescriptionStringNumber);
        if (names.size() == 2) {
            m_description = names[0];
            m_name = names[1];
        }

        CFBundleCloseBundleResourceMap(m_module, resFile);
    }

    LOG(Plugins, "PluginPackage::fetchInfo(): Found plug-in '%s'", m_name.utf8().data());
    if (isPluginBlacklisted()) {
        LOG(Plugins, "\tPlug-in is blacklisted!");
        return false;
    }

    return true;
}
Exemplo n.º 15
0
int
TclLoadFile(
    Tcl_Interp *interp,		/* Used for error reporting. */
    char *fileName,		/* Name of the file containing the desired
				 * code. */
    char *sym1, char *sym2,	/* Names of two procedures to look up in
				 * the file's symbol table. */
    Tcl_PackageInitProc **proc1Ptr,
    Tcl_PackageInitProc **proc2Ptr)
				/* Where to return the addresses corresponding
				 * to sym1 and sym2. */
{
    CFragConnectionID connID;
    Ptr dummy;
    OSErr err;
    CFragSymbolClass symClass;
    FSSpec fileSpec;
    short fragFileRef, saveFileRef;
    Handle fragResource;
    UInt32 offset = 0;
    UInt32 length = kCFragGoesToEOF;
    char packageName[255];
    Str255 errName;
    
    /*
     * First thing we must do is infer the package name from the sym1
     * variable.  This is kind of dumb since the caller actually knows
     * this value, it just doesn't give it to us.
     */
    strcpy(packageName, sym1);
    *packageName = (char) tolower(*packageName);
    packageName[strlen(packageName) - 5] = NULL;
    
    err = FSpLocationFromPath(strlen(fileName), fileName, &fileSpec);
    if (err != noErr) {
	interp->result = "could not locate shared library";
	return TCL_ERROR;
    }
    
    /*
     * See if this fragment has a 'cfrg' resource.  It will tell us were
     * to look for the fragment in the file.  If it doesn't exist we will
     * assume we have a ppc frag using the whole data fork.  If it does
     * exist we find the frag that matches the one we are looking for and
     * get the offset and size from the resource.
     */
    saveFileRef = CurResFile();
    SetResLoad(false);
    fragFileRef = FSpOpenResFile(&fileSpec, fsRdPerm);
    SetResLoad(true);
    if (fragFileRef != -1) {
	UseResFile(fragFileRef);
	fragResource = Get1Resource(kCFragResourceType, kCFragResourceID);
	HLock(fragResource);
	if (ResError() == noErr) {
	    CfrgItem* srcItem;
	    long itemCount, index;
	    Ptr itemStart;

	    itemCount = (*(CfrgHeaderPtrHand)fragResource)->itemCount;
	    itemStart = &(*(CfrgHeaderPtrHand)fragResource)->arrayStart;
	    for (index = 0; index < itemCount;
		 index++, itemStart += srcItem->itemSize) {
		srcItem = (CfrgItem*)itemStart;
		if (srcItem->archType != OUR_ARCH_TYPE) continue;
		if (!strncasecmp(packageName, (char *) srcItem->name + 1,
			srcItem->name[0])) {
		    offset = srcItem->codeOffset;
		    length = srcItem->codeLength;
		}
	    }
	}
	/*
	 * Close the resource file.  If the extension wants to reopen the
	 * resource fork it should use the tclMacLibrary.c file during it's
	 * construction.
	 */
	HUnlock(fragResource);
	ReleaseResource(fragResource);
	CloseResFile(fragFileRef);
	UseResFile(saveFileRef);
    }

    /*
     * Now we can attempt to load the fragement using the offset & length
     * obtained from the resource.  We don't worry about the main entry point
     * as we are going to search for specific entry points passed to us.
     */
    
    c2pstr(packageName);
    err = GetDiskFragment(&fileSpec, offset, length, (StringPtr) packageName,
	    kLoadCFrag, &connID, &dummy, errName);
    if (err != fragNoErr) {
	p2cstr(errName);
	Tcl_AppendResult(interp, "couldn't load file \"", fileName,
	    "\": ", errName, (char *) NULL);
	return TCL_ERROR;
    }
    
    c2pstr(sym1);
    err = FindSymbol(connID, (StringPtr) sym1, (Ptr *) proc1Ptr, &symClass);
    p2cstr((StringPtr) sym1);
    if (err != fragNoErr || symClass == kDataCFragSymbol) {
	interp->result =
	    "could not find Initialization routine in library";
	return TCL_ERROR;
    }

    c2pstr(sym2);
    err = FindSymbol(connID, (StringPtr) sym2, (Ptr *) proc2Ptr, &symClass);
    p2cstr((StringPtr) sym2);
    if (err != fragNoErr || symClass == kDataCFragSymbol) {
	*proc2Ptr = NULL;
    }
    
    return TCL_OK;
}
Exemplo n.º 16
0
pascal OSStatus TextControlProc(EventHandlerCallRef inHandlerCallRef,
                                EventRef inEvent, void *inUserData) {
	OSStatus result = eventNotHandledErr;
	UInt32 eventClass = GetEventClass(inEvent);
	UInt32 eventKind = GetEventKind(inEvent);
	cBitmapFontEditable* control = (cBitmapFontEditable*)inUserData;
  
	switch(eventClass) {
		case kEventClassKeyboard:
		{
			switch(eventKind) {
				case kEventRawKeyDown:
				case kEventRawKeyRepeat:
				{
					char macCharCode;
					UInt32 keyCode;
					UInt32 modifiers;
					GetEventParameter(inEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof (char), NULL, &macCharCode);
					GetEventParameter(inEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof (UInt32), NULL, &keyCode);
					GetEventParameter(inEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof (UInt32), NULL, &modifiers);

          VstKeyCode key;
          key.character = macCharCode;
          ((cBitmapFontEditable*)control)->onKeyDown(key);
          break;
				}
			}
			break;
		}
		case kEventClassMouse:
		{
			switch (eventKind)
			{
				case kEventMouseDown:
				{
					WindowRef window;
					GetEventParameter(inEvent, kEventParamWindowRef, typeWindowRef, NULL, sizeof(WindowRef), NULL, &window);
					HIPoint p;
					GetEventParameter(inEvent, kEventParamMouseLocation, typeHIPoint, NULL, sizeof(HIPoint), NULL, &p);
					Point point = { (short)p.y, (short)p.x };
					QDGlobalToLocalPoint(GetWindowPort(window), &point);
					CRect crect;
          control->getViewSize(crect);
          Rect rect;
          rect.top = crect.top;
          rect.left = crect.left;
          rect.right = crect.right;
          rect.bottom = crect.bottom;
					//TXNGetViewRect((cBitmap)textEdit->platformControl, &rect);
					if(PtInRect(point, &rect)) {
						EventRecord eventRecord;
						if(eventKind == kEventMouseDown && ConvertEventRefToEventRecord(inEvent, &eventRecord)) {
              // Mouse click received
            }
            else {
              VstKeyCode key;
              key.character = KEY_ESC;
              control->onKeyDown(key);
            }
            result = noErr;
					}
					break;
				}
			}
			break;
		}      
		case kEventClassWindow:
		{
			WindowRef window;
			if(GetEventParameter(inEvent, kEventParamDirectObject, typeWindowRef, NULL,
                           sizeof (WindowRef), NULL, &window) != noErr) {
				break;
      }
			switch(eventKind) {
				case kEventWindowDeactivated:
				{
					result = CallNextEventHandler(inHandlerCallRef, inEvent);
					ClearKeyboardFocus(window);
          
					// set up the correct drawing port for the window
					GrafPtr	savedPort;
					bool portChanged = QDSwapPort(GetWindowPort (window), &savedPort);
          
					// remember the current resource map ID
					short currentResID = CurResFile();
					short vstResFileID = control->pluginResID;
					// if it's different (and if it's valid), set the current resource map ID to our plugin's resource map
					if((vstResFileID != currentResID) && (vstResFileID > 0)) {
						UseResFile(vstResFileID);
          }
          
					VstKeyCode key;
          key.character = KEY_ESC;
          ((cBitmapFontEditable*)control)->onKeyDown(key);
          
					// revert the window port, if we changed it
					if(portChanged) {
						QDSwapPort(savedPort, NULL);
          }
          
					// revert the current resource map, if we changed it
					if((currentResID > 0) && (vstResFileID != currentResID) && (vstResFileID > 0)) {
						UseResFile(currentResID);
          }
          
					break;
				}
			}
			break;
		}
	}
	return result;
}
Exemplo n.º 17
0
bool NetscapePluginModule::tryLoad()
{
    m_module = adoptPtr(new Module(m_pluginPath));
    if (!m_module->load())
        return false;

    NP_InitializeFuncPtr initializeFuncPtr = m_module->functionPointer<NP_InitializeFuncPtr>("NP_Initialize");
    if (!initializeFuncPtr)
        return false;

#if !PLUGIN_ARCHITECTURE(X11)
    NP_GetEntryPointsFuncPtr getEntryPointsFuncPtr = m_module->functionPointer<NP_GetEntryPointsFuncPtr>("NP_GetEntryPoints");
    if (!getEntryPointsFuncPtr)
        return false;
#endif

    m_shutdownProcPtr = m_module->functionPointer<NPP_ShutdownProcPtr>("NP_Shutdown");
    if (!m_shutdownProcPtr)
        return false;

    m_pluginFuncs.size = sizeof(NPPluginFuncs);
    m_pluginFuncs.version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;

    // On Mac, NP_Initialize must be called first, then NP_GetEntryPoints. On Windows, the order is
    // reversed. Failing to follow this order results in crashes (e.g., in Silverlight on Mac and
    // in Flash and QuickTime on Windows).
#if PLUGIN_ARCHITECTURE(MAC)
#ifndef NP_NO_CARBON

#if COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#endif

    // Plugins (at least QT) require that you call UseResFile on the resource file before loading it.
    ResFileRefNum currentResourceFile = CurResFile();
    
    ResFileRefNum pluginResourceFile = m_module->bundleResourceMap();
    UseResFile(pluginResourceFile);

#endif
    bool result = initializeFuncPtr(netscapeBrowserFuncs()) == NPERR_NO_ERROR && getEntryPointsFuncPtr(&m_pluginFuncs) == NPERR_NO_ERROR;

#ifndef NP_NO_CARBON
    // Restore the resource file.
    UseResFile(currentResourceFile);

#if COMPILER(CLANG)
#pragma clang diagnostic pop
#endif

#endif

    return result;
#elif PLUGIN_ARCHITECTURE(WIN)
    if (getEntryPointsFuncPtr(&m_pluginFuncs) != NPERR_NO_ERROR || initializeFuncPtr(netscapeBrowserFuncs()) != NPERR_NO_ERROR)
        return false;
#elif PLUGIN_ARCHITECTURE(X11)
    if (initializeFuncPtr(netscapeBrowserFuncs(), &m_pluginFuncs) != NPERR_NO_ERROR)
        return false;
#endif

    return true;
}
Exemplo n.º 18
0
/*
**	GetCommentFromDesktopFile
**
**	Get a file or directory's Finder comment field (if any) from the
**	Desktop file's 'FCMT' resources.
*/
static	OSErr	GetCommentFromDesktopFile(short vRefNum,
										  long dirID,
										  ConstStr255Param name,
										  Str255 comment)
{
	OSErr error;
	short commentID;
	short realVRefNum;
	Str255 desktopName;
	short savedResFile;
	short dfRefNum;
	StringHandle commentHandle;
	
	/* Get the comment ID number */
	error = GetCommentID(vRefNum, dirID, name, &commentID);
	if ( error == noErr )
	{
		if ( commentID != 0 )	/* commentID == 0 means there's no comment */
		{
			error = DetermineVRefNum(name, vRefNum, &realVRefNum);
			if ( error == noErr )
			{
				error = GetDesktopFileName(realVRefNum, desktopName);
				if ( error == noErr )
				{
					savedResFile = CurResFile();
					/*
					**	Open the 'Desktop' file in the root directory. (because
					**	opening the resource file could preload unwanted resources,
					**	bracket the call with SetResLoad(s))
					*/
					SetResLoad(false);
					dfRefNum = HOpenResFile(realVRefNum, fsRtDirID, desktopName, fsRdPerm);
					SetResLoad(true);
					
					if ( dfRefNum != -1)
					{
						/* Get the comment resource */
						commentHandle = (StringHandle)Get1Resource(kFCMTResType,commentID);
						if ( commentHandle != NULL )
						{
							if ( GetHandleSize((Handle)commentHandle) > 0 )
							{
								BlockMoveData(*commentHandle, comment, *commentHandle[0] + 1);
							}
							else
							{
								error = afpItemNotFound;	/* no comment available */
							}
						}
						else
						{
							error = afpItemNotFound;	/* no comment available */
						}
						
						/* restore the resource chain and close the Desktop file */
						UseResFile(savedResFile);
						CloseResFile(dfRefNum);
					}
					else
					{
						error = afpItemNotFound;
					}
				}
				else
				{
					error = afpItemNotFound;
				}
			}
		}
		else
		{
			error = afpItemNotFound;	/* no comment available */
		}
	}
	
	return ( error );
}
Exemplo n.º 19
0
OSErr PAS_decodeResource(PASEntry *entry, FSSpec *outFile, short inRefNum)
{
	OSErr 			err = noErr;	
	short			outRefNum;
	PASResFork		info;
	SInt32			infoSize;
	short			oldResFile;
	
	PASResource		pasRes;
	SInt32			pasResSize;
	
	long			bufSize;
	Handle			buffer;
	long			counter=0;
	
	infoSize	=	sizeof(PASResFork);
	
	err = SetFPos(inRefNum, fsFromStart, (*entry).entryOffset );
	if (err != noErr)	return err;

	err	= FSRead( inRefNum, &infoSize, &info);
	if (err != noErr)	return err;

	if(infoSize != sizeof(PASResFork))
	{
		err = -1;
		goto error;
	}
	
	oldResFile=CurResFile();
	
	outRefNum = FSpOpenResFile(outFile, fsRdWrPerm);
	if (outRefNum < noErr)	return outRefNum;
				
	UseResFile(outRefNum);
	
	
	while (1)
	{
		pasResSize	=	sizeof(PASResource);
		err	= FSRead( inRefNum, &pasResSize, &pasRes);
		
		if (err != noErr)
		{
			if(err == eofErr)
				err = noErr;
				
			break;
		}
		
		bufSize	=	pasRes.length;
		buffer	=	NewHandle(bufSize);
		HLock(buffer);
		
		if(buffer == NULL)
		{
			/*  if we did not get our memory, try updateresfile */
		
			HUnlock(buffer);


			UpdateResFile(outRefNum);
			counter=0;
			
			buffer	=	NewHandle(bufSize);
			HLock(buffer);
			
			if(buffer == NULL)
			{
				err = memFullErr;
				break;
			}
		}
		
		err	= FSRead( inRefNum, &bufSize, &(**buffer));
		if (err != noErr && err != eofErr)	break;
		
		AddResource(buffer, pasRes.attrType, pasRes.attrID, pasRes.attrName);
		WriteResource(buffer);
		
		SetResAttrs(buffer, pasRes.attr);
		ChangedResource(buffer);	
		WriteResource(buffer);
		
		ReleaseResource(buffer);	
		
		if (counter++ > 100)
		{
			UpdateResFile(outRefNum);
			counter=0;
		}
	
	}

error:
		
	UseResFile(oldResFile);	
	CloseResFile(outRefNum);
		
	return err;
}
Exemplo n.º 20
0
Boolean QTInfo_EditAnnotation (Movie theMovie, OSType theType)
{
    DialogPtr		myDialog = NULL;
    short 			myItem;
    short 			mySavedResFile;
    GrafPtr			mySavedPort;
    Handle			myHandle = NULL;
    short			myItemKind;
    Handle			myItemHandle;
    UserData		myUserData = NULL;
    Rect			myItemRect;
    Str255			myString;
    Boolean			myIsChanged = false;
    OSErr			myErr = noErr;

    //////////
    //
    // save the current resource file and graphics port
    //
    //////////

    mySavedResFile = CurResFile();
    GetPort(&mySavedPort);

    // set the application's resource file
    UseResFile(gAppResFile);

    // get the movie user data
    myUserData = GetMovieUserData(theMovie);
    if (myUserData == NULL)
        goto bail;

    //////////
    //
    // create the dialog box in which the user will add or edit the annotation
    //
    //////////

    myDialog = GetNewDialog(kEditTextResourceID, NULL, (WindowPtr)-1L);
    if (myDialog == NULL)
        goto bail;

    MacSetPort(GetDialogPort(myDialog));

    SetDialogDefaultItem(myDialog, kEditTextItemOK);
    SetDialogCancelItem(myDialog, kEditTextItemCancel);

    // get a string for the specified annotation type
    switch (theType) {
    case kUserDataTextFullName:
        GetIndString(myString, kTextKindsResourceID, kTextKindsFullName);
        break;

    case kUserDataTextCopyright:
        GetIndString(myString, kTextKindsResourceID, kTextKindsCopyright);
        break;

    case kUserDataTextInformation:
        GetIndString(myString, kTextKindsResourceID, kTextKindsInformation);
        break;
    }

    GetDialogItem(myDialog, kEditTextItemEditLabel, &myItemKind, &myItemHandle, &myItemRect);
    SetDialogItemText(myItemHandle, myString);

    //////////
    //
    // set the current annotation of the specified type, if it exists
    //
    //////////

    myHandle = NewHandleClear(4);
    if (myHandle != NULL) {
        myErr = GetUserDataText(myUserData, myHandle, theType, 1, GetScriptManagerVariable(smRegionCode));
        if (myErr == noErr) {
            QTInfo_TextHandleToPString(myHandle, myString);
            GetDialogItem(myDialog, kEditTextItemEditBox, &myItemKind, &myItemHandle, &myItemRect);
            SetDialogItemText(myItemHandle, myString);
            SelectDialogItemText(myDialog, kEditTextItemEditBox, 0, myString[0]);
        }

        DisposeHandle(myHandle);
    }

    MacShowWindow(GetDialogWindow(myDialog));

    //////////
    //
    // display and handle events in the dialog box until the user clicks OK or Cancel
    //
    //////////

    do {
        ModalDialog(gModalFilterUPP, &myItem);
    } while ((myItem != kEditTextItemOK) && (myItem != kEditTextItemCancel));

    //////////
    //
    // handle the selected button
    //
    //////////

    if (myItem != kEditTextItemOK)
        goto bail;

    // retrieve the edited text
    myHandle = NewHandleClear(4);
    if (myHandle != NULL) {
        GetDialogItem(myDialog, kEditTextItemEditBox, &myItemKind, &myItemHandle, &myItemRect);
        GetDialogItemText(myItemHandle, myString);
        QTInfo_PStringToTextHandle(myString, myHandle);
        myErr = AddUserDataText(myUserData, myHandle, theType, 1, GetScriptManagerVariable(smRegionCode));
        myIsChanged = (myErr == noErr);
        DisposeHandle(myHandle);
    }

bail:
    // restore the previous resource file and graphics port
    MacSetPort(mySavedPort);
    UseResFile(mySavedResFile);

    if (myDialog != NULL)
        DisposeDialog(myDialog);

    return(myIsChanged);
}
Exemplo n.º 21
0
//////////////////////////////////////////////////////////////////////////////////////////////////
//
//  Given two path strings, srcPath and destPath, creates a MacOS Finder alias from file in srcPath
//  in the destPath, complete with custom icon and all.  Pretty neat.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
static void CreateAlias (char *srcPath, char *destPath)
{
  OSErr err;

  FSSpec sourceFSSpec;
  FSRef srcRef, destRef;
  OSType srcFileType = (OSType)NULL;
  OSType srcCreatorType = (OSType)NULL;
  FInfo srcFinderInfo, destFinderInfo;

  int fd;
  SInt16 rsrcRefNum;

  IconRef srcIconRef;
  IconFamilyHandle srcIconFamily;
  SInt16 theLabel;

  AliasHandle alias;
  short isSrcFolder;

  //find out if we're dealing with a folder alias
  isSrcFolder = UnixIsFolder(srcPath);
  if (isSrcFolder == -1)//error
  {
    fprintf(stderr, "UnixIsFolder(): Error doing a stat on %s\n", srcPath);
    exit(EX_IOERR);
  }

  ///////////////////// Get the FSRef's and FSSpec's for source and dest ///////////////////

  //get file ref to src
  err = FSPathMakeRef(srcPath, &srcRef, NULL);
  if (err != noErr)
  {
    fprintf(stderr, "FSPathMakeRef: Error %d getting file ref for source \"%s\"\n", err, srcPath);
    exit(EX_IOERR);
  }

  //retrieve source filespec from source file ref
  err = FSGetCatalogInfo (&srcRef, NULL, NULL, NULL, &sourceFSSpec, NULL);
  if (err != noErr)
  {
    fprintf(stderr, "FSGetCatalogInfo(): Error %d getting file spec from source FSRef\n", err);
    exit(EX_IOERR);
  }

  //get the finder info for the source if it's a folder
  if (!isSrcFolder)
  {
    err = FSGetFInfo (&srcRef, &srcFinderInfo);
    if (err != noErr)
    {
      fprintf(stderr, "FSpGetFInfo(): Error %d getting Finder info for source \"%s\"\n", err, srcPath);
      exit(EX_IOERR);
    }
    srcFileType = srcFinderInfo.fdType;
    srcCreatorType = srcFinderInfo.fdCreator;
  }

  //////////////// Get the source file's icon ///////////////////////

  if (!noCustomIconCopy)
  {
    err = GetIconRefFromFileInfo(
      &srcRef, 0, NULL, 0, NULL,
      kIconServicesNormalUsageFlag, &srcIconRef, &theLabel
    );

    if (err != noErr)
      fprintf(stderr, "GetIconRefFromFile(): Error getting source file's icon.\n");

    IconRefToIconFamily (srcIconRef, kSelectorAllAvailableData, &srcIconFamily);
  }

  ///////////////////// Create the relevant alias record ///////////////////

  if (makeRelativeAlias)
  {
    // The following code for making relative aliases was borrowed from Apple. See the following technote:
    //
    //  http://developer.apple.com/technotes/tn/tn1188.html
    //

    // create the new file
    err = myFSCreateResFile(destPath, 'TEMP', 'TEMP', &destRef);
    if (err != noErr)
    {
      fprintf(stderr, "FSpCreateResFile(): Error %d while creating file\n", err);
      exit(EX_CANTCREAT);
    }

    //create the alias record, relative to the new alias file
    err = FSNewAlias(&destRef, &srcRef, &alias);
    if (err != noErr)
    {
      fprintf(stderr, "NewAlias(): Error %d while creating relative alias\n", err);
      exit(EX_CANTCREAT);
    }

    // save the resource
    rsrcRefNum = FSOpenResFile(&destRef, fsRdWrPerm);
    if (rsrcRefNum == -1)
    {
      err = ResError();
      fprintf(stderr, "Error %d while opening resource fork for %s\n", err, (char *)&destPath);
      exit(EX_IOERR);
    }

    UseResFile(rsrcRefNum);
    Str255 rname;
    AddResource((Handle) alias, rAliasType, 0, NULL);

    if ((err = ResError()) != noErr)
    {
      fprintf(stderr, "Error %d while adding alias resource for %s", err, (char *)&destPath);
      exit(EX_IOERR);
    }
    if (!noCustomIconCopy)
    {
      //write the custom icon data
      AddResource( (Handle)srcIconFamily, kIconFamilyType, kCustomIconResource, "\p");
    }

    CloseResFile(rsrcRefNum);
  }
  else
  {
Exemplo n.º 22
0
/* アイコンプレビューのアップデート */
void DrawIPIconPreview(const IPIconRec *ipIcon)
{
	PicHandle	previewPict;
	Rect		r;
	Pattern		pat;
	Boolean		drawLarge=false,drawSmall=false,drawThumbnail=false;
	Handle		h;
	OSErr		err;
	IconSuiteRef	iconSuite=NULL;
	IconRef		iconRef;
    Rect        picRect;
	
	/* プレビューの大きさ */
	GetWindowPortBounds(gPreviewWindow,&r);
	
	/* まず背景 */
	switch (gListBackground)
	{
		case iBackWhite:
			EraseRect(&r);
			break;
		
		case iBackGray:
			GetIndPattern(&pat,0,4);
			FillRect(&r,&pat);
			break;
		
		case iBackBlack:
			PaintRect(&r);
			break;

		case iBackDesktop:
			#if !TARGET_API_MAC_CARBON
			{
				PixPatHandle	ppat;
				
				UseResFile(0);
	//			ppat=GetPixPat(16);
				ppat=LMGetDeskCPat();
				if (ppat==nil)
				{
					LMGetDeskPattern(&pat);
					FillRect(&r,&pat);
				}
				else
				{
					FillCRect(&r,ppat);
			//		DisposePixPat(ppat);
				}
				UseResFile(gApplRefNum);
			}
			#else
			EraseRect(&r);
			#endif
			break;

        default:
			EraseRect(&r);
			break;
}
	
	if (ipIcon!=NULL)
	{
		err=GetDataFromIPIcon(&h,ipIcon,kL1Data);
		drawLarge=(h!=nil);
		err=GetDataFromIPIcon(&h,ipIcon,kS1Data);
		drawSmall=(h!=nil);
		err=GetDataFromIPIcon(&h,ipIcon,kT32Data);
		drawThumbnail=(h!=nil);
	}
	
	if (drawThumbnail)
		previewPict = GetPicture(142);
	else
		previewPict = GetPicture(141);
    QDGetPictureBounds(previewPict, &picRect);
	DrawPicture(previewPict,&picRect);
	
	if (ipIcon==NULL) return;
	
	if (!isThumbnailIconsAvailable || !drawThumbnail)
	{
		iconSuite = ipIcon->iconSuite;
	}
	else
	{
		IconFamilyHandle	iconFamily;
		
		err=IPIconToIconFamily(ipIcon,&iconFamily);
		err=RegisterIconRefFromIconFamily(kIconPartyCreator,'TEMP',iconFamily,&iconRef);
	//	DisposeHandle((Handle)iconFamily);
	}
	
	if (isThumbnailIconsAvailable && drawThumbnail)
	{
		err=PlotIconRef(&iconPreviewRect[12],kAlignNone,kTransformNone,kIconServicesNormalUsageFlag,
					iconRef);
		err=ReleaseIconRef(iconRef);
	}
	else
	{
		if (iconSuite != NULL)
		{
			PlotIconSuite(&iconPreviewRect[0],kAlignNone,kTransformNone,iconSuite);
			PlotIconSuite(&iconPreviewRect[1],kAlignNone,kTransformSelected,iconSuite);
			
			if (drawLarge)
			{
				PlotIconSuite(&iconPreviewRect[4],kAlignNone,kTransformOpen,iconSuite);
				PlotIconSuite(&iconPreviewRect[5],kAlignNone,kTransformSelectedOpen,iconSuite);
				
				PlotIconSuite(&iconPreviewRect[8],kAlignNone,kTransformOffline,iconSuite);
				PlotIconSuite(&iconPreviewRect[9],kAlignNone,kTransformSelectedOffline,iconSuite);
			}
			PlotIconSuite(&iconPreviewRect[2],kAlignNone,kTransformNone,iconSuite);
			PlotIconSuite(&iconPreviewRect[3],kAlignNone,kTransformSelected,iconSuite);
			
			if (drawSmall)
			{
				PlotIconSuite(&iconPreviewRect[6],kAlignNone,kTransformOpen,iconSuite);
				PlotIconSuite(&iconPreviewRect[7],kAlignNone,kTransformSelectedOpen,iconSuite);
				
				PlotIconSuite(&iconPreviewRect[10],kAlignNone,kTransformOffline,iconSuite);
				PlotIconSuite(&iconPreviewRect[11],kAlignNone,kTransformSelectedOffline,iconSuite);
			}
		}
	}
}
Exemplo n.º 23
0
bool ExportPCM(AudacityProject *project,
               wxString format, bool stereo, wxString fName,
               bool selectionOnly, double t0, double t1)
{
    wxMessageBox("In process of being rewritten, sorry...");

#if 0

    double rate = project->GetRate();
    wxWindow *parent = project;
    TrackList *tracks = project->GetTracks();

    int header = SND_HEAD_NONE;
#ifdef __WXMAC__
    bool trackMarkers = false;
#endif

    if (format == "WAV")
        header = SND_HEAD_WAVE;
    else if (format == "AIFF")
        header = SND_HEAD_AIFF;
    else if (format == "IRCAM")
        header = SND_HEAD_IRCAM;
    else if (format == "AU")
        header = SND_HEAD_NEXT;
#ifdef __WXMAC__
    else if (format == "AIFF with track markers") {
        header = SND_HEAD_AIFF;
        trackMarkers = true;
    }
#endif


    // Use snd library to export file

    snd_node sndfile;
    snd_node sndbuffer;

    sndfile.device = SND_DEVICE_FILE;
    sndfile.write_flag = SND_WRITE;
    strcpy(sndfile.u.file.filename, (const char *) fName);
    sndfile.u.file.file = 0;
    sndfile.u.file.header = header;
    sndfile.u.file.byte_offset = 0;
    sndfile.u.file.end_offset = 0;
    sndfile.u.file.swap = 0;
    sndfile.format.channels = stereo ? 2 : 1;
    sndfile.format.mode = SND_MODE_PCM;  // SND_MODE_FLOAT
    sndfile.format.bits = 16;
    sndfile.format.srate = int (rate + 0.5);

    int err;
    long flags = 0;

    err = snd_open(&sndfile, &flags);
    if (err) {
        wxMessageBox("Could not write to file.");
        return false;
    }

    sndbuffer.device = SND_DEVICE_MEM;
    sndbuffer.write_flag = SND_READ;
    sndbuffer.u.mem.buffer_max = 0;
    sndbuffer.u.mem.buffer = 0;
    sndbuffer.u.mem.buffer_len = 0;
    sndbuffer.u.mem.buffer_pos = 0;
    sndbuffer.format.channels = stereo ? 2 : 1;
    sndbuffer.format.mode = SND_MODE_PCM;        // SND_MODE_FLOAT
    sndbuffer.format.bits = 16;
    sndbuffer.format.srate = int (rate + 0.5);

    double timeStep = 10.0;      // write in blocks of 10 secs

    wxProgressDialog *progress = NULL;
    wxYield();
    wxStartTimer();
    wxBusyCursor busy;
    bool cancelling = false;

    double t = t0;

    while (t < t1 && !cancelling) {

        double deltat = timeStep;
        if (t + deltat > t1)
            deltat = t1 - t;

        sampleCount numSamples = int (deltat * rate + 0.5);

        Mixer *mixer = new Mixer(stereo ? 2 : 1, numSamples, true, rate);
        wxASSERT(mixer);
        mixer->Clear();

        char *buffer = new char[numSamples * 2 * sndbuffer.format.channels];
        wxASSERT(buffer);

        TrackListIterator iter(tracks);
        VTrack *tr = iter.First();
        while (tr) {
            if (tr->GetKind() == VTrack::Wave) {
                if (tr->selected || !selectionOnly) {
                    if (tr->channel == VTrack::MonoChannel)
                        mixer->MixMono((WaveTrack *) tr, t, t + deltat);
                    if (tr->channel == VTrack::LeftChannel)
                        mixer->MixLeft((WaveTrack *) tr, t, t + deltat);
                    if (tr->channel == VTrack::RightChannel)
                        mixer->MixRight((WaveTrack *) tr, t, t + deltat);
                }
            }
            tr = iter.Next();
        }

        sampleType *mixed = mixer->GetBuffer();

        long b2 = snd_convert(&sndfile, buffer,   // to
                              &sndbuffer, mixed, numSamples);     // from

        snd_write(&sndfile, buffer, b2);

        t += deltat;

        if (!progress && wxGetElapsedTime(false) > 500) {

            wxString message;

            if (selectionOnly)
                message =
                    wxString::
                    Format("Exporting the selected audio as a %s file",
                           (const char *) format);
            else
                message =
                    wxString::
                    Format("Exporting the entire project as a %s file",
                           (const char *) format);

            progress =
                new wxProgressDialog("Export",
                                     message,
                                     1000,
                                     parent,
                                     wxPD_CAN_ABORT |
                                     wxPD_REMAINING_TIME | wxPD_AUTO_HIDE);
        }
        if (progress) {
            cancelling =
                !progress->Update(int (((t - t0) * 1000) / (t1 - t0) + 0.5));
        }

        delete mixer;
        delete[]buffer;
    }

    snd_close(&sndfile);

#ifdef __WXMAC__

    FSSpec spec;

    wxMacFilename2FSSpec(fName, &spec);

    if (trackMarkers) {
        // Export the label track as "CD Spin Doctor" files

        LabelTrack *labels = NULL;
        TrackListIterator iter(tracks);
        VTrack *t = iter.First();
        while (t && !labels) {
            if (t->GetKind() == VTrack::Label)
                labels = (LabelTrack *) t;
            t = iter.Next();
        }
        if (labels) {
            FSpCreateResFile(&spec, 'AIFF', AUDACITY_CREATOR, 0);
            int resFile = FSpOpenResFile(&spec, fsWrPerm);
            if (resFile == -1) {
                int x = ResError();
            }
            if (resFile != -1) {
                UseResFile(resFile);

                int numLabels = labels->mLabels.Count();
                for (int i = 0; i < numLabels; i++) {
                    int startBlock = (int) (labels->mLabels[i]->t * 75);
                    int lenBlock;
                    if (i < numLabels - 1)
                        lenBlock =
                            (int) ((labels->mLabels[i + 1]->t -
                                    labels->mLabels[i]->t) * 75);
                    else
                        lenBlock =
                            (int) ((tracks->GetMaxLen() -
                                    labels->mLabels[i]->t) * 75);
                    int startSample = startBlock * 1176 + 54;
                    int lenSample = lenBlock * 1176 + 54;

                    Handle theHandle = NewHandle(50);
                    HLock(theHandle);
                    char *data = (char *) (*theHandle);
                    *(int *) &data[0] = startSample;
                    *(int *) &data[4] = lenSample;
                    *(int *) &data[8] = startBlock;
                    *(int *) &data[12] = lenBlock;
                    *(short *) &data[16] = i + 1;

                    wxString title = labels->mLabels[i]->title;
                    if (title.Length() > 31)
                        title = title.Left(31);
                    data[18] = title.Length();
                    strcpy(&data[19], (const char *) title);

                    HUnlock(theHandle);
                    AddResource(theHandle, 'SdCv', 128 + i, "\p");
                }
                CloseResFile(resFile);

                wxMessageBox("Saved track information with file.");
            }
        }
    }

    FInfo finfo;
    if (FSpGetFInfo(&spec, &finfo) == noErr) {
        switch (header) {
        case SND_HEAD_AIFF:
            finfo.fdType = 'AIFF';
            break;
        case SND_HEAD_IRCAM:
            finfo.fdType = 'IRCA';
            break;
        case SND_HEAD_NEXT:
            finfo.fdType = 'AU  ';
            break;
        case SND_HEAD_WAVE:
            finfo.fdType = 'WAVE';
            break;
        }

        finfo.fdCreator = AUDACITY_CREATOR;

        FSpSetFInfo(&spec, &finfo);
    }
#endif

    if (progress)
        delete progress;

    return true;

#endif

    return false;

}
Exemplo n.º 24
0
static int
WriteTextResource(
    ClientData clientData,		/* Not used. */
    Tcl_Interp *interp,			/* Current interpreter. */
    int argc,				/* Number of arguments. */
    char **argv)			/* Argument strings. */
{
    char *errNum = "wrong # args: ";
    char *errBad = "bad argument: ";
    char *errStr;
    char *fileName = NULL, *rsrcName = NULL;
    char *data = NULL;
    int rsrcID = -1, i, protectIt = 0;
    short fileRef = -1;
    OSErr err;
    Handle dataHandle;
    Str255 resourceName;
    FSSpec fileSpec;

    /*
     * Process the arguments.
     */
    for (i = 1 ; i < argc ; i++) {
	if (!strcmp(argv[i], "-rsrc")) {
	    rsrcName = argv[i + 1];
	    i++;
	} else if (!strcmp(argv[i], "-rsrcid")) {
	    rsrcID = atoi(argv[i + 1]);
	    i++;
	} else if (!strcmp(argv[i], "-file")) {
	    fileName = argv[i + 1];
	    i++;
	} else if (!strcmp(argv[i], "-protected")) {
	    protectIt = 1;
	} else {
	    data = argv[i];
	}
    }
	
    if ((rsrcName == NULL && rsrcID < 0) ||
	    (fileName == NULL) || (data == NULL)) {
    	errStr = errBad;
    	goto sourceFmtErr;
    }

    /*
     * Open the resource file.
     */
    err = FSpLocationFromPath(strlen(fileName), fileName, &fileSpec);
    if (!(err == noErr || err == fnfErr)) {
	Tcl_AppendResult(interp, "couldn't validate file name", (char *) NULL);
	return TCL_ERROR;
    }
    
    if (err == fnfErr) {
	FSpCreateResFile(&fileSpec, 'WIsH', 'rsrc', smSystemScript);
    }
    fileRef = FSpOpenResFile(&fileSpec, fsRdWrPerm);
    if (fileRef == -1) {
	Tcl_AppendResult(interp, "couldn't open resource file", (char *) NULL);
	return TCL_ERROR;
    }
		
    UseResFile(fileRef);

    /*
     * Prepare data needed to create resource.
     */
    if (rsrcID < 0) {
	rsrcID = UniqueID('TEXT');
    }
    
    strcpy((char *) resourceName, rsrcName);
    c2pstr((char *) resourceName);
    
    dataHandle = NewHandle(strlen(data));
    HLock(dataHandle);
    strcpy(*dataHandle, data);
    HUnlock(dataHandle);
     
    /*
     * Add the resource to the file and close it.
     */
    AddResource(dataHandle, 'TEXT', rsrcID, resourceName);
    
    UpdateResFile(fileRef);
    if (protectIt) {
        SetResAttrs(Get1Resource('TEXT', rsrcID), resProtected);
    }
    
    CloseResFile(fileRef);
    return TCL_OK;
    
    sourceFmtErr:
    Tcl_AppendResult(interp, errStr, "error in \"", argv[0], "\"",
	    (char *) NULL);
    return TCL_ERROR;
}
Exemplo n.º 25
0
int CALLBACK WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR theCmdLine, int nCmdShow)
{
	HANDLE				myAccel;
	HWND				myWindowFrame;
	MSG					myMsg;
    WNDCLASSEX			myWC;
	char				myFileName[MAX_PATH];
	DWORD				myLength;
	OSErr				myErr = noErr;

	ghInst = hInstance;
	gCmdLine = theCmdLine;
	
	if (hPrevInstance == NULL) {
		LoadString(hInstance, IDS_APPNAME, gAppName, sizeof(gAppName));
		
		// register the frame window class
		myWC.cbSize        = sizeof(WNDCLASSEX);
		myWC.style         = CS_HREDRAW | CS_VREDRAW;
		myWC.lpfnWndProc   = (WNDPROC)QTFrame_FrameWndProc;
		myWC.cbClsExtra    = 0;
		myWC.cbWndExtra    = 0;
		myWC.hInstance     = hInstance;
		myWC.hIcon         = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPICON));
		myWC.hCursor       = LoadCursor(NULL, IDC_ARROW);
		myWC.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
		myWC.lpszMenuName  = gAppName;
		myWC.lpszClassName = gAppName;
		myWC.hIconSm       = LoadImage(hInstance, MAKEINTRESOURCE(IDI_APPICON), IMAGE_ICON, 16, 16, 0);
									 
		if (!RegisterClassEx(&myWC)) {
			if (!RegisterClass((LPWNDCLASS)&myWC.style))
        		return(0);
		}

		// register the movie child window class
		myWC.cbSize        = sizeof(WNDCLASSEX);
		myWC.style         = 0;
		myWC.lpfnWndProc   = (WNDPROC)QTFrame_MovieWndProc;
		myWC.cbClsExtra    = 0;
		myWC.cbWndExtra    = 0;
		myWC.hInstance     = hInstance;
		myWC.hIcon         = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CHILDICON));
		// to avoid having QuickTime VR "fight" with the system over the cursor,
		// we set the client area cursor to NULL; this means that for QuickTime
		// movies, we'll need to change the cursor to an arrow manually; see the
		// handling of the WM_MOUSEMOVE message in QTFrame_MovieWndProc
		myWC.hCursor       = NULL;
		myWC.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
		myWC.lpszMenuName  = NULL;
		myWC.lpszClassName = gChildName;
		myWC.hIconSm       = LoadImage(hInstance, MAKEINTRESOURCE(IDI_CHILDICON), IMAGE_ICON, 16, 16, 0);
									 
		if (!RegisterClassEx(&myWC)) {
			if (!RegisterClass((LPWNDCLASS)&myWC.style))
        		return(0);
		}
	}

	// load accelerators
	myAccel = LoadAccelerators(hInstance, gAppName);

	// initialize QuickTime Media Layer and QuickTime; alert the user and return 0 if unsuccessful
	myErr = InitializeQTML(0L);
	if (myErr != noErr) {
		MessageBox(NULL, "QuickTime is not installed on this computer. Exiting.", gAppName, MB_OK | MB_APPLMODAL);
		return(0);
	}
	
	myErr = EnterMovies();
	if (myErr != noErr) {
		MessageBox(NULL, "Could not initialize QuickTime. Exiting.", gAppName, MB_OK | MB_APPLMODAL);
		return(0);
	}

	// get the application's resource file, if it exists
	myLength = GetModuleFileName(NULL, myFileName, MAX_PATH);		// NULL means: the current process
	if (myLength != 0) {
		NativePathNameToFSSpec(myFileName, &gAppFSSpec, kFullNativePath);

		gAppResFile = FSpOpenResFile(&gAppFSSpec, fsRdWrPerm);
		if (gAppResFile != kInvalidFileRefNum)
			UseResFile(gAppResFile);
	}
	
	// do any application-specific initialization that must occur before the frame window is created
	QTApp_Init(kInitAppPhase_BeforeCreateFrameWindow);
	
	// create the main frame window
	myWindowFrame = CreateWindow(gAppName, gAppName, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
                               		CW_USEDEFAULT, 
                               		CW_USEDEFAULT,
                             		CW_USEDEFAULT, 
                             		CW_USEDEFAULT,
                             		NULL, 
                             		NULL, 
                             		hInstance, 
                             		NULL);
	ghWnd = myWindowFrame;
	
	// make sure we got a frame window
	if (myWindowFrame == NULL)
		return(0);
		
	// show the window
	ShowWindow(myWindowFrame, nCmdShow);
	UpdateWindow(myWindowFrame);
	
	// do any application-specific initialization that must occur after the frame window is created
	QTApp_Init(kInitAppPhase_AfterCreateFrameWindow);
	
	// get and process events until the user quits
    while (GetMessage(&myMsg, NULL, 0, 0)) {	
		if (!TranslateMDISysAccel(ghWndMDIClient, &myMsg)) {
        	if (!TranslateAccelerator(myWindowFrame, myAccel, &myMsg)) {
                TranslateMessage(&myMsg);
                DispatchMessage(&myMsg);
			}
		}
    }

	// close the application's resource file, if it was previously opened
	if (gAppResFile != kInvalidFileRefNum)
		CloseResFile(gAppResFile);

	// terminate the QuickTime Media Layer
	ExitMovies();
	TerminateQTML();

	return(myMsg.wParam);			// returns the value from PostQuitMessage
}
Exemplo n.º 26
0
/*
**	GetAPPLFromDesktopFile
**
**	Get a application's location from the
**	Desktop file's 'APPL' resources.
*/
static	OSErr	GetAPPLFromDesktopFile(ConstStr255Param volName,
									   short vRefNum,
									   OSType creator,
									   short *applVRefNum,
									   long *applParID,
									   Str255 applName)
{
	OSErr error;
	short realVRefNum;
	Str255 desktopName;
	short savedResFile;
	short dfRefNum;
	Handle applResHandle;
	Boolean foundCreator;
	Ptr applPtr;
	long applSize;
	
	error = DetermineVRefNum(volName, vRefNum, &realVRefNum);
	if ( error == noErr )
	{
		error = GetDesktopFileName(realVRefNum, desktopName);
		if ( error == noErr )
		{
			savedResFile = CurResFile();
			/*
			**	Open the 'Desktop' file in the root directory. (because
			**	opening the resource file could preload unwanted resources,
			**	bracket the call with SetResLoad(s))
			*/
			SetResLoad(false);
			dfRefNum = HOpenResFile(realVRefNum, fsRtDirID, desktopName, fsRdPerm);
			SetResLoad(true);
			
			if ( dfRefNum != -1)
			{
				/* Get 'APPL' resource ID 0 */
				applResHandle = Get1Resource(kAPPLResType, 0);
				if ( applResHandle != NULL )
				{
					applSize = GetHandleSize((Handle)applResHandle);
					if ( applSize != 0 )	/* make sure the APPL resource isn't empty */
					{
						foundCreator = false;
						applPtr = *applResHandle;
						
						/* APPL's don't have a count so I have to use the size as the bounds */
						while ( (foundCreator == false) &&
								(applPtr < (*applResHandle + applSize)) )
						{
							if ( ((APPLRecPtr)applPtr)->creator == creator )
							{
								foundCreator = true;
							}
							else
							{
								/* fun with pointer math... */
								applPtr += sizeof(OSType) +
										   sizeof(long) +
										   ((APPLRecPtr)applPtr)->applName[0] + 1;
								/* application mappings are word aligned within the resource */
								if ( ((unsigned long)applPtr % 2) != 0 )
								{
									applPtr += 1;
								}
							}
						}
						if ( foundCreator == true )
						{
							*applVRefNum = realVRefNum;
							*applParID = ((APPLRecPtr)applPtr)->parID;
							BlockMoveData(((APPLRecPtr)applPtr)->applName,
										  applName,
										  ((APPLRecPtr)applPtr)->applName[0] + 1);
							/* error is already noErr */
						}
						else
						{
							error = afpItemNotFound;	/* didn't find a creator match */
						}
					}
					else
					{
						error = afpItemNotFound;	/* no APPL mapping available */
					}
				}
				else
				{
					error = afpItemNotFound;	/* no APPL mapping available */
				}
				
				/* restore the resource chain and close the Desktop file */
				UseResFile(savedResFile);
				CloseResFile(dfRefNum);
			}
			else
			{
				error = afpItemNotFound;
			}
		}
	}
	
	return ( error );
}
Exemplo n.º 27
0
Arquivo: ftmac.c Projeto: 32767/libgdx
  /* Read Type 1 data from the POST resources inside the LWFN file,
     return a PFB buffer.  This is somewhat convoluted because the FT2
     PFB parser wants the ASCII header as one chunk, and the LWFN
     chunks are often not organized that way, so we glue chunks
     of the same type together. */
  static FT_Error
  read_lwfn( FT_Memory      memory,
             ResFileRefNum  res,
             FT_Byte**      pfb_data,
             FT_ULong*      size )
  {
    FT_Error       error = FT_Err_Ok;
    ResID          res_id;
    unsigned char  *buffer, *p, *size_p = NULL;
    FT_ULong       total_size = 0;
    FT_ULong       old_total_size = 0;
    FT_ULong       post_size, pfb_chunk_size;
    Handle         post_data;
    char           code, last_code;


    UseResFile( res );

    /* First pass: load all POST resources, and determine the size of */
    /* the output buffer.                                             */
    res_id    = 501;
    last_code = -1;

    for (;;)
    {
      post_data = Get1Resource( TTAG_POST, res_id++ );
      if ( post_data == NULL )
        break;  /* we are done */

      code = (*post_data)[0];

      if ( code != last_code )
      {
        if ( code == 5 )
          total_size += 2; /* just the end code */
        else
          total_size += 6; /* code + 4 bytes chunk length */
      }

      total_size += GetHandleSize( post_data ) - 2;
      last_code = code;

      /* detect integer overflows */
      if ( total_size < old_total_size )
      {
        error = FT_Err_Array_Too_Large;
        goto Error;
      }

      old_total_size = total_size;
    }

    if ( FT_ALLOC( buffer, (FT_Long)total_size ) )
      goto Error;

    /* Second pass: append all POST data to the buffer, add PFB fields. */
    /* Glue all consecutive chunks of the same type together.           */
    p              = buffer;
    res_id         = 501;
    last_code      = -1;
    pfb_chunk_size = 0;

    for (;;)
    {
      post_data = Get1Resource( TTAG_POST, res_id++ );
      if ( post_data == NULL )
        break;  /* we are done */

      post_size = (FT_ULong)GetHandleSize( post_data ) - 2;
      code = (*post_data)[0];

      if ( code != last_code )
      {
        if ( last_code != -1 )
        {
          /* we are done adding a chunk, fill in the size field */
          if ( size_p != NULL )
          {
            *size_p++ = (FT_Byte)(   pfb_chunk_size         & 0xFF );
            *size_p++ = (FT_Byte)( ( pfb_chunk_size >> 8  ) & 0xFF );
            *size_p++ = (FT_Byte)( ( pfb_chunk_size >> 16 ) & 0xFF );
            *size_p++ = (FT_Byte)( ( pfb_chunk_size >> 24 ) & 0xFF );
          }
          pfb_chunk_size = 0;
        }

        *p++ = 0x80;
        if ( code == 5 )
          *p++ = 0x03;  /* the end */
        else if ( code == 2 )
          *p++ = 0x02;  /* binary segment */
        else
          *p++ = 0x01;  /* ASCII segment */

        if ( code != 5 )
        {
          size_p = p;   /* save for later */
          p += 4;       /* make space for size field */
        }
      }

      ft_memcpy( p, *post_data + 2, post_size );
      pfb_chunk_size += post_size;
      p += post_size;
      last_code = code;
    }
Exemplo n.º 28
0
/*
**	GetIconFromDesktopFile
**
**	INPUT a pointer to a non-existent Handle, because we'll allocate one
**
**	search each BNDL resource for the right fileCreator and once we get it
**		find the 'FREF' type in BNDL
**		for each localID in the type, open the FREF resource
**			if the FREF is the desired fileType
**				get its icon localID
**				get the ICN# type in BNDL
**				get the icon resource number from the icon localID
**				get the icon resource type from the desktop mgr's iconType
**				get the icon of that type and number
*/
static	OSErr	GetIconFromDesktopFile(ConstStr255Param volName,
									   short vRefNum,
									   short iconType,
									   OSType fileCreator,
									   OSType fileType,
									   Handle *iconHandle)
{
	OSErr			error;
	short			realVRefNum;
	Str255			desktopName;
	short			savedResFile;
	short			dfRefNum;
	BNDLRecHandle	theBndl = NULL;
	BundleTypePtr	theBundleType;
	short			iconLocalID;
	short			iconRsrcID;
	OSType			iconRsrcType;
	Handle			returnIconHandle;	
	char			bndlState;
	
	*iconHandle = NULL;
	
	error = DetermineVRefNum(volName, vRefNum, &realVRefNum);
	if ( error == noErr )
	{
		error = GetDesktopFileName(realVRefNum, desktopName);
		if ( error == noErr )
		{
			savedResFile = CurResFile();
		
			/*
			**	Open the 'Desktop' file in the root directory. (because
			**	opening the resource file could preload unwanted resources,
			**	bracket the call with SetResLoad(s))
			*/
			SetResLoad(false);
			dfRefNum = HOpenResFile(realVRefNum, fsRtDirID, desktopName, fsRdPerm);
			SetResLoad(true);
		
			if ( dfRefNum != -1 )
			{
				/*
				**	Find the BNDL resource with the specified creator.
				*/
				error = FindBundleGivenCreator(fileCreator, &theBndl);
				if ( error == noErr )
				{
					/* Lock the BNDL resource so it won't be purged when other resources are loaded */
					bndlState = HGetState((Handle)theBndl);
					HLock((Handle)theBndl);
					
					/* Find the 'FREF' BundleType record in the BNDL resource. */
					error = FindTypeInBundle(kFREFResType, theBndl, &theBundleType);
					if ( error == noErr )
					{
						/* Find the local ID in the 'FREF' resource with the specified fileType */
						error = GetLocalIDFromFREF(theBundleType, fileType, &iconLocalID);
						if ( error == noErr )
						{
							/* Find the 'ICN#' BundleType record in the BNDL resource. */
							error = FindTypeInBundle(kIconFamResType, theBndl, &theBundleType);
							if ( error == noErr )
							{
								/* Find the icon's resource ID in the 'ICN#' BundleType record */
								error = GetIconRsrcIDFromLocalID(theBundleType, iconLocalID, &iconRsrcID);
								if ( error == noErr )
								{
									/* Map Desktop Manager icon type to resource type */
									iconRsrcType = DTIconToResIcon(iconType);
									
									if ( iconRsrcType != (OSType)0 )
									{
										/* Load the icon */
										returnIconHandle = Get1Resource(iconRsrcType, iconRsrcID);
										if ( returnIconHandle != NULL )
										{
											/* Copy the resource handle, and return the copy */
											HandToHand(&returnIconHandle);
											if ( MemError() == noErr )
											{
												*iconHandle = returnIconHandle;
											}
											else
											{
												error = afpItemNotFound;
											}
										}
										else
										{
											error = afpItemNotFound;
										}
									}
								}
							}
						}
					}
					/* Restore the state of the BNDL resource */ 
					HSetState((Handle)theBndl, bndlState);
				}
				/* Restore the resource chain and close the Desktop file */
				UseResFile(savedResFile);
				CloseResFile(dfRefNum);
			}
			else
			{
				error = ResError(); /* could not open Desktop file */
			}
		}
		if ( (error != noErr) && (error != memFullErr) )
		{
			error = afpItemNotFound;	/* force an error we should return */
		}
	}
	
	return ( error );
}
Exemplo n.º 29
0
boolean ploticoncustom (const Rect *r, short align, short transform, bigstring bsiconname) {
	
	/*
	7.0b9 PBS: plot a custom icon.
	*/
	
#ifdef MACVERSION

	short rnum;
	short resid = 128; /*Always 128 for custom icons*/
	short saveresfile;

	/*Get the resource reference for the file containing this icon.*/
	
	if (!customicongetrnum (bsiconname, &rnum)) { /*Already loaded?*/
	
		if (!customiconload (bsiconname, &rnum)) { /*Try to load it.*/
		
			return (false);
			} /*if*/
		} /*if*/
	
	saveresfile = CurResFile ();
	
	UseResFile (rnum);
	
	ploticonresource (r, align, transform, resid);
	
	UseResFile (saveresfile);
	
	return (true);

#endif

#ifdef WIN95VERSION
	HBITMAP hbm, oldbm;
	BITMAP bm;
	HDC hdcsrc, hdc;
	boolean flprinting;
	HDC hdcmask;
	HBITMAP hbmmask, oldmaskbm;
	COLORREF oldclr, oldclr2;
	bigstring bsfilepath;
	char cfilepath [256];
	
	copystring (BIGSTRING ("\x11" "Appearance\\Icons\\"), bsfilepath);
	
	pushstring (bsiconname, bsfilepath); /*add file name to folder path*/

	pushstring (BIGSTRING ("\x04" ".bmp"), bsfilepath); /*add .bmp file extension*/

	copyptocstring (bsfilepath, cfilepath);

	/*Load the image from a file.*/

	hbm = LoadImage (shellinstance, cfilepath, IMAGE_BITMAP, 16, 16, LR_LOADFROMFILE);

	if (hbm == NULL) /*Load failed, return false, use default icon.*/

		return (false);

	if (hbm)
		{
		hdc = getcurrentDC();

		flprinting = iscurrentportprintport ();

		if (hdc)
			{
			hdcsrc = CreateCompatibleDC (hdc);

			if (hdcsrc)
				{
				GetObject (hbm, sizeof (BITMAP), &bm);

				oldbm = (HBITMAP) SelectObject (hdcsrc, hbm);
				
				if (flprinting) {
				//	StretchBlt (hdc, r->left, r->top, r->right-r->left, r->bottom - r->top, hdcsrc, 0,0, bm.bmWidth, bm.bmHeight, SRCCOPY);
					}
				else {
					hdcmask = CreateCompatibleDC (hdc);
					hbmmask = CreateBitmap (bm.bmWidth, bm.bmHeight, 1, 1, NULL);

					if (hdcmask && hbmmask) {
						oldmaskbm = (HBITMAP) SelectObject (hdcmask, hbmmask);

						oldclr = SetBkColor (hdcsrc, RGB(255,255,255));

						BitBlt (hdcmask, 0,0,bm.bmWidth, bm.bmHeight, hdcsrc, 0,0, SRCCOPY);

						SetBkColor (hdcsrc,oldclr);

						eraserect (*r);

						oldclr = SetBkColor (hdc, RGB(255,255,255));
						oldclr2 = SetTextColor (hdc, RGB(0,0,0));

						BitBlt (hdc, r->left, r->bottom - bm.bmHeight, bm.bmWidth, bm.bmHeight, hdcsrc, 0,0, SRCINVERT);
						BitBlt (hdc, r->left, r->bottom - bm.bmHeight, bm.bmWidth, bm.bmHeight, hdcmask, 0,0, SRCAND);
						BitBlt (hdc, r->left, r->bottom - bm.bmHeight, bm.bmWidth, bm.bmHeight, hdcsrc, 0,0, SRCINVERT);

						SetBkColor (hdc,oldclr);
						SetTextColor (hdc,oldclr2);

						SelectObject (hdcmask, oldmaskbm);

	//					BitBlt (hdc, r->left, r->bottom - bm.bmHeight, bm.bmWidth, bm.bmHeight, hdcsrc, 0,0, SRCAND);
						}

					DeleteObject (hbmmask);
					DeleteDC (hdcmask);
					}

				SelectObject (hdcsrc, oldbm);
				DeleteDC (hdcsrc);
				}
			}

		DeleteObject (hbm);
		}

	return (true);	
#endif
	} /*ploticoncustom*/
Exemplo n.º 30
0
  /* Read Type 1 data from the POST resources inside the LWFN file,
     return a PFB buffer. This is somewhat convoluted because the FT2
     PFB parser wants the ASCII header as one chunk, and the LWFN
     chunks are often not organized that way, so we'll glue chunks
     of the same type together. */
  static FT_Error
  read_lwfn( FT_Memory  memory,
             FSSpec*    lwfn_spec,
             FT_Byte**  pfb_data,
             FT_ULong*  size )
  {
    FT_Error       error = FT_Err_Ok;
    short          res_ref, res_id;
    unsigned char  *buffer, *p, *size_p = NULL;
    FT_ULong       total_size = 0;
    FT_ULong       post_size, pfb_chunk_size;
    Handle         post_data;
    char           code, last_code;


    res_ref = FSpOpenResFile( lwfn_spec, fsRdPerm );
    if ( ResError() )
      return FT_Err_Out_Of_Memory;
    UseResFile( res_ref );

    /* First pass: load all POST resources, and determine the size of
       the output buffer. */
    res_id    = 501;
    last_code = -1;

    for (;;)
    {
      post_data = Get1Resource( 'POST', res_id++ );
      if ( post_data == NULL )
        break;  /* we're done */

      code = (*post_data)[0];

      if ( code != last_code )
      {
        if ( code == 5 )
          total_size += 2; /* just the end code */
        else
          total_size += 6; /* code + 4 bytes chunk length */
      }

      total_size += GetHandleSize( post_data ) - 2;
      last_code = code;
    }

    if ( FT_ALLOC( buffer, (FT_Long)total_size ) )
      goto Error;

    /* Second pass: append all POST data to the buffer, add PFB fields.
       Glue all consecutive chunks of the same type together. */
    p              = buffer;
    res_id         = 501;
    last_code      = -1;
    pfb_chunk_size = 0;

    for (;;)
    {
      post_data = Get1Resource( 'POST', res_id++ );
      if ( post_data == NULL )
        break;  /* we're done */

      post_size = (FT_ULong)GetHandleSize( post_data ) - 2;
      code = (*post_data)[0];

      if ( code != last_code )
      {
        if ( last_code != -1 )
        {
          /* we're done adding a chunk, fill in the size field */
          if ( size_p != NULL )
          {
            *size_p++ = (FT_Byte)(   pfb_chunk_size         & 0xFF );
            *size_p++ = (FT_Byte)( ( pfb_chunk_size >> 8  ) & 0xFF );
            *size_p++ = (FT_Byte)( ( pfb_chunk_size >> 16 ) & 0xFF );
            *size_p++ = (FT_Byte)( ( pfb_chunk_size >> 24 ) & 0xFF );
          }
          pfb_chunk_size = 0;
        }

        *p++ = 0x80;
        if ( code == 5 )
          *p++ = 0x03;  /* the end */
        else if ( code == 2 )
          *p++ = 0x02;  /* binary segment */
        else
          *p++ = 0x01;  /* ASCII segment */

        if ( code != 5 )
        {
          size_p = p;   /* save for later */
          p += 4;       /* make space for size field */
        }
      }

      ft_memcpy( p, *post_data + 2, post_size );
      pfb_chunk_size += post_size;
      p += post_size;
      last_code = code;
    }