コード例 #1
0
void DrawImage( void )
{
    OSErr  err = noErr;
    Handle hOpenTypeList = NewHandle(0);
    long   numTypes = 0;
    FSSpec theFSSpec;
    Rect   bounds;
    GraphicsImportComponent importer = 0;

    BuildGraphicsImporterValidFileTypes( hOpenTypeList, &numTypes );
    HLock( hOpenTypeList );

    err = GetOneFileWithPreview(numTypes, (OSTypePtr)*hOpenTypeList, &theFSSpec, NULL);
    DisposeHandle( hOpenTypeList );
    if ( err ) return;

    // locate and open a graphics importer component which can be used to draw the
    // selected file. If a suitable importer is not found the ComponentInstance
    // is set to NULL.
    err = GetGraphicsImporterForFile( &theFSSpec,	// specifies the file to be drawn
                                      &importer );	// pointer to the returned GraphicsImporterComponent

    // get the native size of the image associated with the importer
    err = GraphicsImportGetNaturalBounds( importer, 	// importer instance
                                          &bounds );	// returned bounds

    OffsetRect( &bounds, 10, 45 );
    window = NewCWindow( NULL, &bounds, "\pDraw Image", true, documentProc, (WindowPtr)-1, true, 0);

    // set the graphics port for drawing
    err = GraphicsImportSetGWorld( importer,				// importer instance
                                   GetWindowPort( window ),	// destination graphics port or GWorld
                                   NULL );					// destination GDevice, set to NULL uses GWorlds device

    // draw the image
    err = GraphicsImportDraw( importer );

    // close the importer instance
    CloseComponent( importer );
}
コード例 #2
0
ファイル: scrap.c プロジェクト: LarBob/executor
P0(PUBLIC pascal trap, LONGINT, UnloadScrap)
{
    OSErr retval;
    INTEGER f;
    LONGINT l = Cx(ScrapSize);
    
    if (Cx(ScrapState) > 0) {
        retval = cropen(&f);
        if (retval != noErr)
/*-->*/     return(retval);
        HLock(MR(ScrapHandle));
        retval = FSWriteAll(f, &l, STARH(MR(ScrapHandle)));
        HUnlock(MR(ScrapHandle));
        if (retval != noErr)
/*-->*/     return(retval);
        retval = FSClose(f);
        if (retval != noErr)
/*-->*/     return(retval);
        ScrapState = 0;
    }
    return noErr;
}
コード例 #3
0
ファイル: msRsrc.c プロジェクト: AntonLanghoff/whitecatlib
//_______________________________________________________________________________
OSErr WriteRsrc	(Handle rsrc, ResType type, short ID, short	resFile)
{
	OSErr err; Handle h;
	short saved;
	
	saved = CurResFile();
	UseResFile( resFile);
	if ((err= ResError())!=noErr)	return err;
	
	h= GetResource (type, ID);
	if (h) RemoveResource (h);
	HLock (rsrc);
	AddResource( rsrc, type, ID, "\p");
	err= ResError();
	if( err== noErr) {
		UpdateResFile( resFile);
		err= ResError();
	}
	HUnlock( rsrc);
	UseResFile( saved);
	return err;
}
コード例 #4
0
ファイル: AppleEvents.cpp プロジェクト: MaddTheSane/tntbasic
// ÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑ
//		¥ GetAEDataHandle										/*e*/
// ÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑ
// Returns the AE data handle from the desc. You have to dispose of this handle.
Handle GetAEDataHandle(
	const AEDesc	&inDesc)
{
	Size		size;

	size=::AEGetDescDataSize(&inDesc);
	
	Handle		h=::NewHandle(size);
	ThrowIfMemFull_(h);
	
	HLock(h);
	OSErr	err=::AEGetDescData(&inDesc,*h,size);
	HUnlock(h);
	
	if (err)
	{
		DisposeHandle(h);
		Throw_(err);
	}

	return h;
}
コード例 #5
0
ファイル: tclMacEnv.c プロジェクト: durandj/devkitadv
static char *
GetUserName()
{
    static char buf[33];
    short refnum;
    Handle h;

    refnum = CurResFile();
    UseResFile(0);
    h = GetResource('STR ', -16096);
    UseResFile(refnum);
    if (h == NULL) {
        return NULL;
    }

    HLock(h);
    strncpy(buf, (*h)+1, **h);
    buf[**h] = '\0';
    HUnlock(h);
    ReleaseResource(h);
    return(buf[0] ? buf : NULL);
}
コード例 #6
0
OSErr SpriteUtils_AddPICTImageToKeyFrameSample (QTAtomContainer theKeySample, short thePictID, RGBColor *theKeyColor, QTAtomID theID, FixedPoint *theRegistrationPoint, StringPtr theImageName)
{
	PicHandle				myPicture = NULL;
	Handle					myCompressedPicture = NULL;
	ImageDescriptionHandle	myImageDesc = NULL;
	OSErr					myErr = noErr;
	
	// get picture from resource
	myPicture = (PicHandle)GetPicture(thePictID);
	if (myPicture == NULL)
		myErr = resNotFound;

	if (myErr != noErr)
		goto bail;
	
	DetachResource((Handle)myPicture);
	
	// convert it to image data compressed by the animation compressor
	myErr = ICUtils_RecompressPictureWithTransparency(myPicture, theKeyColor, NULL, &myImageDesc, &myCompressedPicture);
	if (myErr != noErr)
		goto bail;

	// add it to the key sample
	HLock(myCompressedPicture);
	myErr = SpriteUtils_AddCompressedImageToKeyFrameSample(theKeySample, myImageDesc, GetHandleSize(myCompressedPicture), *myCompressedPicture, theID, theRegistrationPoint, theImageName);
	
bail:
	if (myPicture != NULL)
		KillPicture(myPicture);
		
	if (myCompressedPicture != NULL)
		DisposeHandle(myCompressedPicture);
		
	if (myImageDesc != NULL)
		DisposeHandle((Handle)myImageDesc);
		
	return(myErr);
}
コード例 #7
0
ファイル: Printer.cpp プロジェクト: ffostertw/praat
	int Printer_postScript_printf (void *stream, const char *format, ... ) {
		#if defined (_WIN32)
			static union { char chars [3002]; short shorts [1501]; } theLine;
		#elif cocoa
		#elif defined (macintosh)
			static Handle theLine;
		#endif
		int length;
		va_list args;
		va_start (args, format);
		(void) stream;
		#if cocoa
		#elif defined (_WIN32)
			vsprintf (theLine.chars + 2, format, args);
			length = strlen (theLine.chars + 2);
			theLine.shorts [0] = length;
			if (length > 0 && theLine.chars [length + 1] == '\n') {
				theLine.chars [length + 1] = '\r';
				theLine.chars [length + 2] = '\n';
				theLine.chars [length + 3] = '\0';
				length ++;
			}
			Escape (theWinDC, POSTSCRIPT_PASSTHROUGH, length + 2, theLine.chars, nullptr);
		#elif defined (macintosh)
			if (! theLine) {
				theLine = NewHandle (3000);
				HLock (theLine);
			}
			vsprintf (*theLine, format, args);
			length = strlen (*theLine);
			if (length > 0 && (*theLine) [length - 1] == '\n')
				(*theLine) [length - 1] = '\r';
			SetPort (theMacPort);
			PMSessionPostScriptData (theMacPrintSession, *theLine, strlen (*theLine));
		#endif
		va_end (args);
		return 1;
	}
コード例 #8
0
ファイル: macros.c プロジェクト: macssh/macssh
void setupNewMacros(NewMacroInfo *macrost) // RAB BetterTelnet 2.0b5
{
	Handle macroHandle;
	Ptr pos;
	long len;
	short i;

	len = NUM_MACROS;
	macrost->handle = macroHandle = myNewHandle(len);
	HLock(macroHandle);
	pos = *macroHandle;

	while (len) {
		*pos = 0;
		pos++;
		len--;
	}

	for (i = 0; i < NUM_MACROS; i++)
		macrost->index[i] = i;

	HUnlock(macroHandle);
}
コード例 #9
0
void debug_freehand(void *ptr)
{
long i;
Handle h;

if (current_level < 0) return;

if (!ptr) McoErrorAlert(MCO_INVALID_PTR);
if (!dbg_hand_ptrs) return;
for (i=0; i<max_hand; i++) if (dbg_hand_ptrs[i] == ptr)
	{
	h = (Handle)ptr;
	HLock((Handle)h);
	fill_mem(dbg_hand_sizes[i],*h,HAND_FILL_D);
	HUnlock((Handle)h);
	dbg_hand_ptrs[i] = 0L;
	dbg_hand_sizes[i] = 0;
	dbg_hand_counts[i] = 0;
	dbg_hand_levels[i] = 0;
	break;
	}
if (i == max_hand) McoErrorAlert(MCO_INVALID_PTR);
}
コード例 #10
0
ファイル: XPInstallGlue.c プロジェクト: rn10950/RetroZilla
void 		
ProgressMsgInit()
{
	Rect	r;
	
	if (gControls->tw->allProgressMsg)
	{
		HLock((Handle)gControls->tw->allProgressMsg);
		SetRect(&r, (*gControls->tw->allProgressMsg)->viewRect.left,
				(*gControls->tw->allProgressMsg)->viewRect.top,
				(*gControls->tw->allProgressMsg)->viewRect.right,
				(*gControls->tw->allProgressMsg)->viewRect.bottom );
		HUnlock((Handle)gControls->tw->allProgressMsg);
		
		TESetText("", 0, gControls->tw->allProgressMsg);
		
		EraseRect(&r);
	}
	
	bProgMsgInit = true;
	
	return;
}
コード例 #11
0
ファイル: IPIconSupport.c プロジェクト: amatubu/iconparty
/* create icns(icon for MacOS X) with IPIcon */
OSErr MakeXIconWithIPIcon(const FSSpec *theFile,const IPIconRec *ipIcon)
{
	OSErr	err;
	FInfo	fndrInfo;
	short	refNum;
	IconFamilyHandle	iconFamily;
	long	count;
	
	if (!isIconServicesAvailable) return -1;
	
	/* convert IPIcon to icns */
	err=IPIconToIconFamily(ipIcon,&iconFamily);
	if (err!=noErr) return err;
	
	/* create a file */
	err=FSpGetFInfo(theFile,&fndrInfo);
	if (err==fnfErr)
		err=FSpCreate(theFile,kIconPartyCreator,kXIconFileType,smSystemScript);
	if (err!=noErr) return err;
	
	/* open the file */
	err=FSpOpenDF(theFile,fsWrPerm,&refNum);
	if (err!=noErr) return err;
	
	/* save icns */
	HLock((Handle)iconFamily);
	count=GetHandleSize((Handle)iconFamily);
	err=FSWrite(refNum,&count,*iconFamily);
	err=SetEOF(refNum,count);
	HUnlock((Handle)iconFamily);
	DisposeHandle((Handle)iconFamily);
	
	/* close the file */
	err=FSClose(refNum);
	
	return noErr;
}
コード例 #12
0
ファイル: Deflation.c プロジェクト: rn10950/RetroZilla
OSErr
CleanupExtractedFiles(short tgtVRefNum, long tgtDirID)
{
	OSErr		err = noErr;
	FSSpec		coreDirFSp;
	StringPtr	pcoreDir = nil;
	short		i = 0;
	
	HLock(gControls->cfg->coreDir);
	if (*gControls->cfg->coreDir != NULL && **gControls->cfg->coreDir != NULL)		
	{
		// just need to delete the core dir and its contents
		
		pcoreDir = CToPascal(*gControls->cfg->coreDir);
		err = FSMakeFSSpec(tgtVRefNum, tgtDirID, pcoreDir, &coreDirFSp);
		if (err == noErr)
		{
			err = FSpDelete( &coreDirFSp );
		}
	
		HUnlock(gControls->cfg->coreDir);
		goto aurevoir;
	}	
		
	HUnlock(gControls->cfg->coreDir);
	
	// otherwise iterate through coreFileList deleteing each individually
	for (i=0; i<currCoreFile+1; i++)
	{
		FSpDelete( &coreFileList[i] );
	}

aurevoir:
	if (pcoreDir)
		DisposePtr((Ptr) pcoreDir);	
	return err;
}
コード例 #13
0
ファイル: ftmac.c プロジェクト: Joincheng/lithtech
  /* Create a new FT_Face from an SFNT resource, specified by res ID. */
  static
  FT_Error  FT_New_Face_From_SFNT( FT_Library  library,
                                   short       sfnt_id,
                                   FT_Long     face_index,
                                   FT_Face*    aface )
  {
    Handle     sfnt = NULL;
    FT_Byte*   sfnt_data;
    size_t     sfnt_size;
    FT_Stream  stream = NULL;
    FT_Error   error = 0;
    FT_Memory  memory = library->memory;


    sfnt = GetResource( 'sfnt', sfnt_id );
    if ( ResError() )
      return FT_Err_Invalid_Handle;

    sfnt_size = (FT_ULong)GetHandleSize( sfnt );
    if ( ALLOC( sfnt_data, (FT_Long)sfnt_size ) )
    {
      ReleaseResource( sfnt );
      return error;
    }

    HLock( sfnt );
    memcpy( sfnt_data, *sfnt, sfnt_size );
    HUnlock( sfnt );
    ReleaseResource( sfnt );

    return open_face_from_buffer( library,
                                  sfnt_data,
                                  sfnt_size,
                                  face_index,
                                  "truetype",
                                  aface );
  }
コード例 #14
0
ファイル: BLAST Tint.c プロジェクト: MaddTheSane/tntbasic
// This routine takes a CTab and generates a mapping array which will map one colour onto the best
// tinted colour in the palette. It makes no attempt to change the colours in the palette, they
// are mapped to the closest match.
void MakeTintMapShifted(CTabHandle theClut,TintPtr theTint,long rShift,long gShift,long bShift)
{
	char		origState=HGetState((Handle)theClut);
	RGBColor	theCol;
	short		count,index;
	Boolean		openedWorld=false;
	
	HLock((Handle)theClut);

	CTabChanged(theClut);		// important, otherwise the remapping goes : "fsd;jhgflkasrhgflkdsavbn.asdkjrhvliuabhdv.kjhopsd; jrg;osnalkgvsa;rlfjhlkhbeoirlh"

	if (!gBL_TintWorld)
	{
		OpenTintWorld(theClut);
		openedWorld=true;
	}
	
	if (gBL_TintWorld)
	{
		for(count=0; count<=(**theClut).ctSize; count++)
		{
			theCol=(**theClut).ctTable[count].rgb;
			ShiftColour(&theCol,rShift,gShift,bShift);
			index=RGB2IndexGW(theClut,&theCol);
			if (index!=-1) // if a match could not be found then put the original colour in
				theTint[count]=index;
			else
				theTint[count]=count;
		}
		
		if (openedWorld)
			CloseTintWorld();
	}

	HSetState((Handle)theClut,origState);
}
コード例 #15
0
ファイル: _Resmodule.c プロジェクト: 0xcc/python-read
static int ResObj_set_data(ResourceObject *self, PyObject *v, void *closure)
{

                    char *data;
                    long size;

                    if ( v == NULL )
                            return -1;
                    if ( !PyString_Check(v) )
                            return -1;
                    size = PyString_Size(v);
                    data = PyString_AsString(v);
                    /* XXXX Do I need the GetState/SetState calls? */
            SetHandleSize(self->ob_itself, size);
            if ( MemError())
                return -1;
            HLock(self->ob_itself);
            memcpy((char *)*self->ob_itself, data, size);
            HUnlock(self->ob_itself);
            /* XXXX Should I do the Changed call immedeately? */
            return 0;

    return 0;
}
コード例 #16
0
ファイル: su_pas.c プロジェクト: binoc-software/mozilla-cvs
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;
}
コード例 #17
0
ファイル: su_pas.c プロジェクト: binoc-software/mozilla-cvs
OSErr PAS_flattenResource(ResType type, short *ids, long count, short source, short dest)
{
	long 			idIndex;
	
	
	Handle			resToCopy;
	long			handleLength;
	
	PASResource		pasResource;
	long			pasResLen;
	
	OSErr			err;
	
	for (idIndex=0; idIndex < count; idIndex++)
	{
		if( (type == 'SIZE') && ( ids[idIndex] == 1 || ids[idIndex] == 0  ) )
		{
			/* 	
				We do not want to encode/flatten SIZE 0 or 1 because this
				is the resource that the user can modify.  Most applications
				will not be affected if we remove these resources
			*/
		}
		else
		{	
			resToCopy=Get1Resource(type,ids[idIndex]);
					
			if(!resToCopy)	
			{
				return resNotFound;
			}	
				
			memset(&pasResource, 0, sizeof(PASResource));	
				
			GetResInfo(	resToCopy, 	
						&pasResource.attrID, 
						&pasResource.attrType, 
						pasResource.attrName);	
			
			pasResource.attr = GetResAttrs(resToCopy);
			
			DetachResource(resToCopy);	
			HLock(resToCopy);
			
			pasResource.length 	= GetHandleSize(resToCopy);
			handleLength 		= pasResource.length;
			
			pasResLen			=	sizeof(PASResource);
			
			err = FSWrite(dest, &pasResLen, &pasResource);
			
			if(err != noErr) 
			{
				return err;
			}
			
			err = FSWrite(dest, &handleLength, &(**resToCopy));

			if(err != noErr) 
			{
				return err;
			}
			
			HUnlock(resToCopy);
			DisposeHandle(resToCopy);		
		}
	}
	
	
	return noErr;
}
コード例 #18
0
ファイル: macros.c プロジェクト: macssh/macssh
void	oldsetmacro(short n, char *s)			/* Set macro number <n> to the value of s */
{
	unsigned char	*p;
	short	num, pos, escape;
	short	len;
	OSErr 	memError;
	
	if (n<0  || n>9)
		return;

	// Restrict the maximum length of macros to MACRO_MAX_LEN bytes
	len = strlen(s)+1;
	if (len > (MACRO_MAX_LEN - 1)) {
		len = MACRO_MAX_LEN;
		s[MACRO_MAX_LEN - 1] = 0;
		}
	
	// If this is an empty string, remove whatever storage might have been used previously
	// by this macro.
	if (len == 1) {
		if (gMacros[n] != nil) {
			DisposeHandle(gMacros[n]);
			gMacros[n] = nil;
			}
		return;
		}
		
	// If neccessary, create storage for the macro
	if (gMacros[n] == nil) {
		gMacros[n] = myNewHandle(len);
		if (gMacros[n] == nil) {		// Memory error
			return;
			}
		}

	// Adjust the handle to the proper size (may be making an existing macro longer)
	memError = mySetHandleSize(gMacros[n], len);
	if (memError != noErr) {
		return;
		}
	
	HLock(gMacros[n]);
	p = (unsigned char *)*gMacros[n];

	num = 0;
	pos = 0;
	escape = 0;
	
	while ( *s) {
		if (escape) {
			escape = 0;
			switch (*s) {
				case 'i':
					if ( pos >0) {
						*p++=num;
						*p++=*s;
						pos=0;
						}
					*p++=MACRO_IP;
					break;
				case '#':
					if ( pos >0) {
						*p++=num;
						*p++=*s;
						pos=0;
						}
					*p++=MACRO_LINES;
					break;
				case 'n':
					if ( pos >0) {
						*p++=num;
						*p++=*s;
						pos=0;
						}
					*p++='\012';
					break;
				case 'r':
					if ( pos >0) {
						*p++=num;
						*p++=*s;
						pos=0;
						}
					*p++='\015';
					break;
				case 't':
					if ( pos >0) {
						*p++=num;
						*p++=*s;
						pos=0;
						}
					*p++='\t';
					break;
				case '"':
					if ( pos >0) {
						*p++=num;
						*p++=*s;
						pos=0;
						}
					*p++='\"';
					break;

						
				case '\\':
					if ( pos >0) {
						*p++=num;
						escape=1;
						pos=0;
						num=0;
						}
					else
						*p++='\\';
					break;
				default:
					if (*s <='9' && *s >='0' && pos <3) {
						num= num*8+( *s -'0');
						pos++;
						escape=1;
						}
					else {
						if (pos ==0 && num==0) {
							*p++='\\';
							*p++=*s;
							}
						else {
							*p++=num;
							pos= 0;
							s--;			/* back up the buffer. */
							}
						}
					break;
				}
			}
		else {
			if (*s=='\\') {
				num=0;
				pos=0;
				escape=1;
				}
			else
				*p++=*s;
			}
		s++;
		}

	if (pos >0) *p++=num;
	
	*p=0;
	
	// The resultant macro may be shorter than the input string due to escaped characters.
	// So, recalculate the length of the macro and resize than handle if neccessary.
	len = strlen(*gMacros[n])+1;
	
	HUnlock(gMacros[n]);
	mySetHandleSize(gMacros[n], len);
} /* setmacro */
コード例 #19
0
ファイル: QTImportExport.cpp プロジェクト: aalex/osg
osg::Image* QuicktimeImportExport::doImport(unsigned char* data, unsigned int sizeData, const std::string& fileTypeHint)
{
    GWorldPtr gworld = 0;
    OSType pixelFormat;
    int rowStride;
    GraphicsImportComponent gicomp = 0;
    Rect rectImage;
    GDHandle origDevice = 0;
    CGrafPtr origPort = 0;
    ImageDescriptionHandle desc = 0;
    int depth = 32;
    unsigned int xsize, ysize;
    unsigned char* imageData = 0;
    
    // Data Handle for file data ( & load data from file )
    Handle dataRef = getPtrDataRef(data, sizeData, fileTypeHint);
    
    try {
        OSErr err = noErr;
        
        // GraphicsImporter - Get Importer for our filetype
        GetGraphicsImporterForDataRef(dataRef, 'ptr ', &gicomp);

        // GWorld - Get Texture Info
        err = GraphicsImportGetNaturalBounds(gicomp, &rectImage);
        if (err != noErr) {
            throw QTImportExportException(err, "GraphicsImportGetNaturalBounds failed");
            
        }
        xsize = (unsigned int)(rectImage.right - rectImage.left);
        ysize = (unsigned int)(rectImage.bottom - rectImage.top);

        // ImageDescription - Get Image Description
        err = GraphicsImportGetImageDescription(gicomp, &desc);
        if (err != noErr) {
            throw QTImportExportException(err, "GraphicsImportGetImageDescription failed");
        }

        // ImageDescription - Get Bit Depth
        HLock(reinterpret_cast<char **>(desc));
        

        // GWorld - Pixel Format stuff
        pixelFormat = k32ARGBPixelFormat; // Make sure its forced...NOTE: i'm pretty sure this cannot be RGBA!

        // GWorld - Row stride
        rowStride = xsize * 4; // (width * depth_bpp / 8)

        // GWorld - Allocate output buffer
        imageData = new unsigned char[rowStride * ysize];

        // GWorld - Actually Create IT!
        QTNewGWorldFromPtr(&gworld, pixelFormat, &rectImage, 0, 0, 0, imageData, rowStride);
        if (!gworld) {
            throw QTImportExportException(-1, "QTNewGWorldFromPtr failed");
        }

        // Save old Graphics Device and Graphics Port to reset to later
        GetGWorld (&origPort, &origDevice);

        // GraphicsImporter - Set Destination GWorld (our buffer)
        err = GraphicsImportSetGWorld(gicomp, gworld, 0);
        if (err != noErr) {
            throw QTImportExportException(err, "GraphicsImportSetGWorld failed");
        }

        // GraphicsImporter - Set Quality Level
        err = GraphicsImportSetQuality(gicomp, codecLosslessQuality);
        if (err != noErr) {
            throw QTImportExportException(err, "GraphicsImportSetQuality failed");
        }

        // Lock pixels so that we can draw to our memory texture
        if (!GetGWorldPixMap(gworld) || !LockPixels(GetGWorldPixMap(gworld))) {
            throw QTImportExportException(0, "GetGWorldPixMap failed");
        }
        
           
        //*** Draw GWorld into our Memory Texture!
        GraphicsImportDraw(gicomp);
 
        // Clean up
        UnlockPixels(GetGWorldPixMap(gworld));
        SetGWorld(origPort, origDevice); // set graphics port to offscreen (we don't need it now)
        DisposeGWorld(gworld);
        CloseComponent(gicomp);
        DisposeHandle(reinterpret_cast<char **>(desc));
        DisposeHandle(dataRef);
    } 
    catch (QTImportExportException& e) 
    {
        setError(e.what());
        
        if (gworld) {
            UnlockPixels(GetGWorldPixMap(gworld));
            SetGWorld(origPort, origDevice); // set graphics port to offscreen (we don't need it now)
            DisposeGWorld(gworld);
        }
        if (gicomp)
            CloseComponent(gicomp);
        if (desc) 
            DisposeHandle(reinterpret_cast<char **>(desc));
        
        if (imageData) 
            delete[] imageData;
        if (dataRef)
            DisposeHandle(dataRef);
            
        return NULL;
    }
    

    
    unsigned int bytesPerPixel = depth / 8;
    unsigned int glpixelFormat;
    switch(bytesPerPixel) {
        case 3 :
            glpixelFormat = GL_RGB;
            break;
        case 4 :
            glpixelFormat = GL_RGBA;
            break;
        default :
            delete[] imageData;
            setError("unknown pixelformat");
            return NULL;
            break;
    }
    
    unsigned char* swizzled = pepareBufferForOSG(imageData, bytesPerPixel, xsize, ysize);
    
    delete[] imageData;
 
    osg::Image* image = new osg::Image();
    image->setFileName(fileTypeHint.c_str());
    image->setImage(xsize,ysize,1,
        bytesPerPixel,
        glpixelFormat,
        GL_UNSIGNED_BYTE,
        swizzled,
        osg::Image::USE_NEW_DELETE );
    
 
    return image;
}
コード例 #20
0
ファイル: nsMacUtils.cpp プロジェクト: fortunto2/celtx
void MyHLock(Handle theHandle)
{
  HLock(theHandle);
}
コード例 #21
0
ファイル: ftmac.c プロジェクト: Wafflespeanut/gecko-dev
  FT_New_Face_From_FOND( FT_Library  library,
                         Handle      fond,
                         FT_Long     face_index,
                         FT_Face*    aface )
  {
    short     have_sfnt, have_lwfn = 0;
    ResID     sfnt_id, fond_id;
    OSType    fond_type;
    Str255    fond_name;
    Str255    lwfn_file_name;
    UInt8     path_lwfn[PATH_MAX];
    OSErr     err;
    FT_Error  error = FT_Err_Ok;


    /* test for valid `aface' and `library' delayed to */
    /* `FT_New_Face_From_XXX'                          */

    GetResInfo( fond, &fond_id, &fond_type, fond_name );
    if ( ResError() != noErr || fond_type != TTAG_FOND )
      return FT_THROW( Invalid_File_Format );

    HLock( fond );
    parse_fond( *fond, &have_sfnt, &sfnt_id, lwfn_file_name, face_index );
    HUnlock( fond );

    if ( lwfn_file_name[0] )
    {
      ResFileRefNum  res;


      res = HomeResFile( fond );
      if ( noErr != ResError() )
        goto found_no_lwfn_file;

#if HAVE_FSREF

      {
        UInt8  path_fond[PATH_MAX];
        FSRef  ref;


        err = FSGetForkCBInfo( res, kFSInvalidVolumeRefNum,
                               NULL, NULL, NULL, &ref, NULL );
        if ( noErr != err )
          goto found_no_lwfn_file;

        err = FSRefMakePath( &ref, path_fond, sizeof ( path_fond ) );
        if ( noErr != err )
          goto found_no_lwfn_file;

        error = lookup_lwfn_by_fond( path_fond, lwfn_file_name,
                                     path_lwfn, sizeof ( path_lwfn ) );
        if ( !error )
          have_lwfn = 1;
      }

#elif HAVE_FSSPEC

      {
        UInt8     path_fond[PATH_MAX];
        FCBPBRec  pb;
        Str255    fond_file_name;
        FSSpec    spec;


        FT_MEM_SET( &spec, 0, sizeof ( FSSpec ) );
        FT_MEM_SET( &pb,   0, sizeof ( FCBPBRec ) );

        pb.ioNamePtr = fond_file_name;
        pb.ioVRefNum = 0;
        pb.ioRefNum  = res;
        pb.ioFCBIndx = 0;

        err = PBGetFCBInfoSync( &pb );
        if ( noErr != err )
          goto found_no_lwfn_file;

        err = FSMakeFSSpec( pb.ioFCBVRefNum, pb.ioFCBParID,
                            fond_file_name, &spec );
        if ( noErr != err )
          goto found_no_lwfn_file;

        err = FT_FSpMakePath( &spec, path_fond, sizeof ( path_fond ) );
        if ( noErr != err )
          goto found_no_lwfn_file;

        error = lookup_lwfn_by_fond( path_fond, lwfn_file_name,
                                     path_lwfn, sizeof ( path_lwfn ) );
        if ( !error )
          have_lwfn = 1;
      }

#endif /* HAVE_FSREF, HAVE_FSSPEC */

    }

    if ( have_lwfn && ( !have_sfnt || PREFER_LWFN ) )
      error = FT_New_Face_From_LWFN( library,
                                     path_lwfn,
                                     face_index,
                                     aface );
    else
      error = FT_ERR( Unknown_File_Format );

  found_no_lwfn_file:
    if ( have_sfnt && error )
      error = FT_New_Face_From_SFNT( library,
                                     sfnt_id,
                                     face_index,
                                     aface );

    return error;
  }
コード例 #22
0
ファイル: ftmac.c プロジェクト: Wafflespeanut/gecko-dev
  /* Create a new FT_Face from an SFNT resource, specified by res ID. */
  static FT_Error
  FT_New_Face_From_SFNT( FT_Library  library,
                         ResID       sfnt_id,
                         FT_Long     face_index,
                         FT_Face*    aface )
  {
    Handle     sfnt = NULL;
    FT_Byte*   sfnt_data;
    size_t     sfnt_size;
    FT_Error   error  = FT_Err_Ok;
    FT_Memory  memory = library->memory;
    int        is_cff, is_sfnt_ps;


    sfnt = GetResource( TTAG_sfnt, sfnt_id );
    if ( sfnt == NULL )
      return FT_THROW( Invalid_Handle );

    sfnt_size = (FT_ULong)GetHandleSize( sfnt );
    if ( FT_ALLOC( sfnt_data, (FT_Long)sfnt_size ) )
    {
      ReleaseResource( sfnt );
      return error;
    }

    HLock( sfnt );
    ft_memcpy( sfnt_data, *sfnt, sfnt_size );
    HUnlock( sfnt );
    ReleaseResource( sfnt );

    is_cff     = sfnt_size > 4 && !ft_memcmp( sfnt_data, "OTTO", 4 );
    is_sfnt_ps = sfnt_size > 4 && !ft_memcmp( sfnt_data, "typ1", 4 );

    if ( is_sfnt_ps )
    {
      FT_Stream  stream;


      if ( FT_NEW( stream ) )
        goto Try_OpenType;

      FT_Stream_OpenMemory( stream, sfnt_data, sfnt_size );
      if ( !open_face_PS_from_sfnt_stream( library,
                                           stream,
                                           face_index,
                                           0, NULL,
                                           aface ) )
      {
        FT_Stream_Close( stream );
        FT_FREE( stream );
        FT_FREE( sfnt_data );
        goto Exit;
      }

      FT_FREE( stream );
    }
  Try_OpenType:
    error = open_face_from_buffer( library,
                                   sfnt_data,
                                   sfnt_size,
                                   face_index,
                                   is_cff ? "cff" : "truetype",
                                   aface );
  Exit:
    return error;
  }
コード例 #23
0
const StringPtr kApplicationName = "\pYourAppNameHere";

//////////
//
// GetOneFileWithPreview
// Display the appropriate file-opening dialog box, with an optional QuickTime preview pane. If the user
// selects a file, return information about it using the theFSSpecPtr parameter.
//
// Note that both StandardGetFilePreview and NavGetFile use the function specified by theFilterProc as a
// file filter. This framework always passes NULL in the theFilterProc parameter. If you use this function
// in your own code, keep in mind that on Windows the function specifier must be of type FileFilterUPP and
// on Macintosh it must be of type NavObjectFilterUPP. (You can use the QTFrame_GetFileFilterUPP to create
// a function specifier of the appropriate type.) Also keep in mind that Navigation Services expects a file
// filter function to return true if a file is to be displayed, while the Standard File Package expects the
// filter to return false if a file is to be displayed.
//
//////////

OSErr GetOneFileWithPreview (short theNumTypes, TypeListPtr theTypeList, FSSpecPtr theFSSpecPtr, void *theFilterProc)
{

#if TARGET_OS_WIN32
	StandardFileReply	myReply;
#endif
#if TARGET_OS_MAC
	NavReplyRecord		myReply;
	NavDialogOptions		myDialogOptions;
	NavTypeListHandle	myOpenList = NULL;
	NavEventUPP		myEventUPP = NewNavEventUPP(HandleNavEvent);
#endif
	OSErr				myErr = noErr;

	if (theFSSpecPtr == NULL)
		return(paramErr);

#if TARGET_OS_WIN32
	// prompt the user for a file
	StandardGetFilePreview((FileFilterUPP)theFilterProc, theNumTypes, (ConstSFTypeListPtr)theTypeList, &myReply);
	if (!myReply.sfGood)
		return(userCanceledErr);

	// make an FSSpec record
	myErr = FSMakeFSSpec(myReply.sfFile.vRefNum, myReply.sfFile.parID, myReply.sfFile.name, theFSSpecPtr);
#endif

#if TARGET_OS_MAC
	// specify the options for the dialog box
	NavGetDefaultDialogOptions(&myDialogOptions);
	myDialogOptions.dialogOptionFlags -= kNavNoTypePopup;
	myDialogOptions.dialogOptionFlags -= kNavAllowMultipleFiles;
	BlockMoveData(kApplicationName, myDialogOptions.clientName, kApplicationName[0] + 1);

	// create a handle to an 'open' resource
	myOpenList = (NavTypeListHandle)CreateOpenHandle(kApplicationSignature, theNumTypes, theTypeList);
	if (myOpenList != NULL)
		HLock((Handle)myOpenList);

	// prompt the user for a file
	myErr = NavGetFile(NULL, &myReply, &myDialogOptions, myEventUPP, NULL, (NavObjectFilterUPP)theFilterProc, myOpenList, NULL);
	if ((myErr == noErr) && myReply.validRecord) {
		AEKeyword		myKeyword;
		DescType		myActualType;
		Size			myActualSize = 0;

		// get the FSSpec for the selected file
		if (theFSSpecPtr != NULL)
			myErr = AEGetNthPtr(&(myReply.selection), 1, typeFSS, &myKeyword, &myActualType, theFSSpecPtr, sizeof(FSSpec), &myActualSize);

		NavDisposeReply(&myReply);
	}

	if (myOpenList != NULL) {
		HUnlock((Handle)myOpenList);
		DisposeHandle((Handle)myOpenList);
	}

	DisposeNavEventUPP(myEventUPP);
#endif

	return(myErr);
}
コード例 #24
0
CFDictionaryRef createDockDescriptionForURL(CFURLRef url) {
	if (!url) {
		NSLog(CFSTR("%@"), CFSTR("in copyDockDescriptionForURL in CFGrowlAdditions: Cannot copy Dock description for a NULL URL"));
		return NULL;
	}

	//return NULL for non-file: URLs.
	CFStringRef scheme = CFURLCopyScheme(url);
	Boolean isFileURL = (CFStringCompare(scheme, CFSTR("file"), kCFCompareCaseInsensitive) == kCFCompareEqualTo);
	CFRelease(scheme);
	if (!isFileURL)
		return NULL;

	CFDictionaryRef dict = NULL;
	CFStringRef path     = NULL;
	CFDataRef aliasData  = NULL;

	FSRef    fsref;
	if (CFURLGetFSRef(url, &fsref)) {
		AliasHandle alias = NULL;
		OSStatus    err   = FSNewAlias(/*fromFile*/ NULL, &fsref, &alias);
		if (err != noErr) {
			NSLog(CFSTR("in copyDockDescriptionForURL in CFGrowlAdditions: FSNewAlias for %@ returned %li"), url, (long)err);
		} else {
			HLock((Handle)alias);

			err = FSCopyAliasInfo(alias, /*targetName*/ NULL, /*volumeName*/ NULL, (CFStringRef *)&path, /*whichInfo*/ NULL, /*info*/ NULL);
			if (err != noErr) {
				NSLog(CFSTR("in copyDockDescriptionForURL in CFGrowlAdditions: FSCopyAliasInfo for %@ returned %li"), url, (long)err);
			}

			aliasData = CFDataCreate(kCFAllocatorDefault, (UInt8 *)*alias, GetHandleSize((Handle)alias));

			HUnlock((Handle)alias);
			DisposeHandle((Handle)alias);
		}
	}

	if (!path) {
		path = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
	}

	if (path || aliasData) {
		CFMutableDictionaryRef temp = CFDictionaryCreateMutable(kCFAllocatorDefault, /*capacity*/ 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

		if (path) {
			CFDictionarySetValue(temp, _CFURLStringKey, path);
			CFRelease(path);

			int pathStyle = kCFURLPOSIXPathStyle;
			CFNumberRef pathStyleNum = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &pathStyle);
			CFDictionarySetValue(temp, _CFURLStringTypeKey, pathStyleNum);
			CFRelease(pathStyleNum);
		}

		if (aliasData) {
			CFDictionarySetValue(temp, _CFURLAliasDataKey, aliasData);
			CFRelease(aliasData);
		}

		dict = temp;
	}

	return dict;
}
コード例 #25
0
ファイル: macros.c プロジェクト: macssh/macssh
short	sendmacro(struct WindRec *tw, short n)				/* send macro number n */
// RAB BetterTelnet 2.0b5 - changed to support new macro system
{
	char			temp[20];
	unsigned char	*s, *first, *p;
	unsigned char	myipnum[4];
	Handle			mh, ph;
	short			i, num, pos, escape, length;
	char			*plabel;
	Str255			password;
	unsigned long	startTicks;
	
	// Invalid number
	if (n < 0 || n >= NUM_MACROS) {
		return -1;
	}

	// first we actually have to GET the macro (2.0b5)
	// we use getmacrointohandle for this
	i = -1;
	if (tw->sessmacros.handle)
		i = getmacrointohandle(&tw->sessmacros, n, &mh);
	if (i == -1)
		i = getmacrointohandle(&TelInfo->newMacros, n, &mh);
	if (i == -1)
		return 0;

// Empty macro, so do nothing
//	if (gMacros[n] == nil) {
//		return 0;
//		}

//	HLock(gMacros[n]);
//	mp = (unsigned char *)*gMacros[n];

	s = (unsigned char *)*mh;

	ph = myNewHandle(GetHandleSize(mh) + 256);
	if (!ph) return 0; // ouch
	HLock(ph);
	first = p = (unsigned char *)*ph;

	netgetip(myipnum);

// totally revised - we parse as we go (RAB BetterTelnet 2.0b5)
// this has the pleasant side effect of getting rid of the use of 254 and 255 as special
// characters, so we can use them in macros now - you can now send telnet options from a macro!
	num = 0;
	pos = 0;
	escape = 0;

	while ( *s) {
		if (escape == 1 && (((*s < '0' || *s > '9') && pos) || pos >= 3)) {
												  // do this ONCE -
												  // it's a kludge to do this in each case
			*p++=num;
			pos = 0;
			escape = 0;
			// now the rest of the code will take care of whatever char this was
		}
		if (escape == 1) {
			escape = 0;
			switch (*s) {
				case 'i':
					SendStringAsIfTyped(tw, (char *)first, p-first);
					sprintf(temp,"%d.%d.%d.%d", myipnum[0], myipnum[1], myipnum[2], myipnum[3]);
					SendStringAsIfTyped(tw, temp, strlen(temp));
					first = p = (unsigned char *)*ph;
					break;
				case '#':
					SendStringAsIfTyped(tw, (char *)first, p-first);
					sprintf(temp,"%d", VSgetlines(tw->vs));
					SendStringAsIfTyped(tw, temp, strlen(temp));
					first = p = (unsigned char *)*ph;
					break;
				case 'n':
					*p++='\012';
					break;
				case 'r':
					*p++='\015';
					break;
				case 't':
					*p++='\t';
					break;
				case '"':
					*p++='\"';
					break;
				case '\\':
					*p++='\\';
					break;
				case 'k':
					escape = 2;
					break;
				case 'w':
					// switch to window num
					if ( s[1] >= '1' && s[1] <= '9') {
						HandleMenuCommand( (connMenu << 16 | FIRST_CNXN_ITEM) + s[1] - '1', 0 );
						++s;
					}
					break;
				default:
					if (*s <='9' && *s >='0' && pos <3) {
						num= num*8+( *s -'0');
						pos++;
						escape=1;
						}
					else {
//						if (pos ==0 && num==0) {
							*p++='\\';
							*p++=*s;
//							}
//						else {
//							*p++=num;
//							pos= 0;
//							s--;			/* back up the buffer. */
//							}
						}
					break;
				}
		} else if (escape == 2) {
			if (*s == '{') {
				escape = 3;
				plabel = NULL;
			} else {
				escape = 0;
			}
		} else if (escape == 3) {
			if (*s != '}') {
				if ( plabel == NULL )
					plabel = s;
			} else {
				*s = 0;
				if (plabel && SSH2PasswordDialog(plabel, password, NULL)) {
					SendStringAsIfTyped(tw, (char *)first, p-first);
					// better wait for echo off...
					startTicks = TickCount();
					while (TickCount() - startTicks < 30) {
						ssh2_sched();
						DoNetEvents();
					}
					first = p = (unsigned char *)*ph;
					SendStringAsIfTyped(tw, (char *)password + 1, password[0]);
				} else {
					// malformed macro, or pasword cancel
					first = p = (unsigned char *)*ph;
					break;
				}
				escape = 0;
			}
		} else {
			if (*s=='\\') {
				num=0;
				pos=0;
				escape=1;
				}
			else
				*p++=*s;
			}
		s++;
		}

	if (pos >0) *p++=num;

	SendStringAsIfTyped(tw, (char *)first, p-first);

	DisposeHandle(mh);
	DisposeHandle(ph);
	return 0;
}
コード例 #26
0
ファイル: dataobj.cpp プロジェクト: Bluehorn/wxPython
bool wxBitmapDataObject::SetData( const wxDataFormat& format, size_t nSize, const void *pBuf )
{
    Clear();

    if ((pBuf == NULL) || (nSize == 0))
        return false;

#if wxMAC_USE_CORE_GRAPHICS
    Handle picHandle = NULL ;
    m_pictHandle = NewHandle( nSize );
    memcpy( *(Handle) m_pictHandle, pBuf, nSize );
    
    if ( format == s_pict )
    {
        // pict for IO expects a 512 byte header
        picHandle = NewHandle( nSize + 512 );
        memset( *picHandle , 0 , 512 );
        memcpy( *picHandle+512, pBuf, nSize );
    }
    else
    {
        picHandle = (Handle) m_pictHandle;
    }

    CGImageRef cgImageRef = 0;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
    if ( UMAGetSystemVersion() >= 0x1040 )
    {
        CFDataRef data = NULL; 
        
        HLock( picHandle );
        data = CFDataCreateWithBytesNoCopy( kCFAllocatorDefault, (const UInt8*) *picHandle, GetHandleSize(picHandle), kCFAllocatorNull);
        CGImageSourceRef source = CGImageSourceCreateWithData( data, NULL );
        if ( source )
        {
            cgImageRef = CGImageSourceCreateImageAtIndex(source, 0, NULL);
        }
        CFRelease( source );
        CFRelease( data );
        HUnlock( picHandle );
    }
    else
#endif
#ifndef __LP64__
    {
        // import from TIFF
        GraphicsImportComponent importer = 0;
        OSStatus err = OpenADefaultComponent(GraphicsImporterComponentType, s_pict == format ? kQTFileTypePicture : kQTFileTypeTIFF, &importer);
        if (noErr == err)
        {
            if ( picHandle )
            {
                ComponentResult result = GraphicsImportSetDataHandle(importer, picHandle);
                if ( result == noErr )
                {
                    Rect frame;
                    GraphicsImportGetNaturalBounds( importer, &frame );
                    GraphicsImportCreateCGImage( importer, &cgImageRef, kGraphicsImportCreateCGImageUsingCurrentSettings );
                }
            }
            CloseComponent( importer );
        }
    }
#endif
    if ( format == s_pict )
    {
        DisposeHandle( picHandle );
    }
    if ( cgImageRef )
    {
        m_bitmap.Create( CGImageGetWidth(cgImageRef)  , CGImageGetHeight(cgImageRef) );
        CGRect r = CGRectMake( 0 , 0 , CGImageGetWidth(cgImageRef)  , CGImageGetHeight(cgImageRef) );
        // since our context is upside down we dont use CGContextDrawImage
        HIViewDrawCGImage( (CGContextRef) m_bitmap.GetHBITMAP() , &r, cgImageRef ) ;
        CGImageRelease(cgImageRef);
        cgImageRef = NULL;
    }
#else
    PicHandle picHandle = (PicHandle)NewHandle( nSize );
    memcpy( *picHandle, pBuf, nSize );
    m_pictHandle = picHandle;
    // ownership is transferred to the bitmap
    m_pictCreated = false;
#ifndef __LP64__
    Rect frame;
    wxMacGetPictureBounds( picHandle, &frame );
#if wxUSE_METAFILE
    wxMetafile mf;
    mf.SetHMETAFILE( (WXHMETAFILE)m_pictHandle );
#endif
    wxMemoryDC mdc;
    m_bitmap.Create( frame.right - frame.left, frame.bottom - frame.top );
    mdc.SelectObject( m_bitmap );
#if wxUSE_METAFILE  
    mf.Play( &mdc );
#endif
    mdc.SelectObject( wxNullBitmap );
#endif
#endif

    return m_bitmap.Ok();
}
コード例 #27
0
ファイル: macros.c プロジェクト: macssh/macssh
void saveMacros(NewMacroInfo *macrost, FSSpec *theFile)
{
	SFReply		whereReply;
	short 		refNum,exist;
	FSSpec		macroFile;
	long		junk, len, len2;
	short 		i;
	Point		where;
	OSErr		err;
	Str255		tempString,tempString2;
	Handle		macroHandle;
	Ptr			pos;

	if (!macrost->handle) return; // sanity check

	where.h = 100; where.v = 100;

	GetIndString(tempString,MISC_STRINGS,SAVE_MACROS_STRING);
	GetIndString(tempString2,MISC_STRINGS,DEFAULT_MACRO_SET_NAME);

	if (theFile == 0) {
		SFPutFile( where, tempString, tempString2, 0L, &whereReply);

		if (!whereReply.good)
			return;

		BlockMoveData(&whereReply.fName, macroFile.name, (*whereReply.fName)+1); 
		GetWDInfo(whereReply.vRefNum, &macroFile.vRefNum, &macroFile.parID, &junk);
	}
	else
		macroFile = *theFile;

	if ((err = HCreate(macroFile.vRefNum, macroFile.parID, 
			macroFile.name, kNCSACreatorSignature, 'TEXT')) == dupFNErr)
		exist = 1;
	
	err = HOpenDF(macroFile.vRefNum, macroFile.parID, macroFile.name, fsWrPerm, &refNum);

	if (exist) 
		SetEOF(refNum, 0L);

// the new code - RAB BetterTelnet 2.0b5
	macroHandle = macrost->handle;
	HandToHand(&macroHandle);
	HLock(macroHandle);
	pos = *macroHandle;
	len = len2 = GetHandleSize(macroHandle);
	while (len) {
		if (*pos == 0) *pos = 13;
		pos++;
		len--;
	}

	pos = *macroHandle;
	junk = 2;
	FSWrite(refNum, &junk, "!\015");
	FSWrite(refNum, &len2, pos);
	DisposeHandle(macroHandle); // it's a copy anyway, get rid of it!

	FSClose(refNum);
}
コード例 #28
0
ファイル: pm.c プロジェクト: Room1337/projectM-update
int main( int argc, char **argv ) {

    Movie movie;
    Track track;
    Media media;
    short refNum;
    short resID = 0;
    Boolean wasChanged;
    OSErr err = noErr;
    FSSpec fsspec;
    AudioFormatAtomPtr outAudioAtom;
    CmpSoundHeader outSoundInfo;
    SoundComponentData theInputFormat,
                       theOutputFormat;
    SoundConverter mySoundConverter = NULL;
//    SCFillBufferData scFillBufferData = { NULL };
    Ptr pDecomBuffer0 = NULL,
        pDecomBuffer1 = NULL;
    long kMaxOutputBuffer = 64 * 1024;
    long noFrames = 0,
                  niFrames = 0,
                  noBytes = 0,
                  noSamples = 0;
#define MAX_BUFFER_SIZE 256 * 1024 * 1024


    /** Initialise MovieToolbox */
    EnterMovies();

    /** Open the movie file from the first argument */
    printf( "opening audio file: '%s'\n", argv[1] );
    path2fss( &fsspec, argv[1] );
    err = OpenMovieFile( &fsspec, &refNum, fsRdPerm );
    if ( err != noErr ) {
        printf( "failed to open audio: %d\n", GetMoviesError() );
        exit( -1 );
      }

    /** Instantiate the movie */
    err = NewMovieFromFile( &movie, refNum, &resID, NULL,
                            newMovieActive, &wasChanged );
    if ( err ) {
        printf( "failed to instantiate movie\n" );
        exit( -1 );
      }

    CloseMovieFile( refNum );
    refNum = 0;

    /** Get the first sound track */
    track = GetMovieIndTrackType( movie, 1, SoundMediaType,
                                  movieTrackMediaType );
    if ( track == NULL ) {
        printf( "failed to get sound track\n" );
        exit( -1 );
      }

    /** Get the sound track media */
    media = GetTrackMedia( track );
    if ( media == NULL ) {
        printf( "failed to get media from audio track\n" );
        exit( -1 );
      }

    Size size;
    Handle extension;
    SoundDescriptionHandle sourceSoundDescription;

    sourceSoundDescription = (SoundDescriptionHandle)NewHandle(0);

    /** Get the description of the sample data */
    GetMediaSampleDescription( media, 1,
                               (SampleDescriptionHandle)sourceSoundDescription );
    err = GetMoviesError();
    if ( err ) {
        printf( "failed to get description of sample data\n" );
        exit( -1 );
      }

    extension = NewHandle( 0 );

    // get the "magic" decompression atom
    // This extension to the SoundDescription information stores
    // data specific to a given audio decompressor. Some audio
    // decompression algorithms require a set of out-of-stream
    // values to configure the decompressor.
    err = 
        GetSoundDescriptionExtension( (SoundDescriptionHandle)sourceSoundDescription,
                                      &extension, siDecompressionParams );
    if ( noErr == err ) {
        size = GetHandleSize( extension );
        printf( "transferring data to audio buffer: %d bytes\n", size );
        HLock( extension );
        outAudioAtom = (AudioFormatAtom*)NewPtr( size );
        err = MemError();
        // copy the atom data to our buffer...
        BlockMoveData( *extension, outAudioAtom, size );
        HUnlock( extension );
      } else {
        // if it doesn't have an atom, that's ok
        outAudioAtom = NULL;
        err = noErr;
      }

    /** Setup our sound header */
    outSoundInfo.format = (*sourceSoundDescription)->dataFormat;
    outSoundInfo.numChannels = (*sourceSoundDescription)->numChannels;
    outSoundInfo.sampleSize = (*sourceSoundDescription)->sampleSize;
    outSoundInfo.sampleRate = (*sourceSoundDescription)->sampleRate;
    outSoundInfo.compressionID = (*sourceSoundDescription)->compressionID;

    float db = ((float)outSoundInfo.sampleRate)/(1<<16);

    printf( "sample: %d\tchannels: %d\tsample size: %d\tsample rate: %f\tcompressionID: %d\n",
            outSoundInfo.format, outSoundInfo.numChannels, outSoundInfo.sampleSize,
            db, outSoundInfo.compressionID );

    DisposeHandle( extension );
    DisposeHandle( (Handle)sourceSoundDescription );

    /** 
     * Now that we've figured out what the audio file is, allocate buffers
     * and so on for conversion and playback
     */

    printf( "initialising input/output conversion buffers\n" );

    /** setup input/output format for sound converter */
    theInputFormat.flags = 0;
    theInputFormat.format = outSoundInfo.format;
    theInputFormat.numChannels = outSoundInfo.numChannels;
    theInputFormat.sampleSize = outSoundInfo.sampleSize;
    theInputFormat.sampleRate = outSoundInfo. sampleRate;
    theInputFormat.sampleCount = 0;
    theInputFormat.buffer = NULL;
    theInputFormat.reserved = 0;

    theOutputFormat.flags = 0;
    theOutputFormat.format = kSoundNotCompressed;
    theOutputFormat.numChannels = theInputFormat.numChannels;
    theOutputFormat.sampleSize = theInputFormat.sampleSize;
    theOutputFormat.sampleRate = theInputFormat.sampleRate;
    theOutputFormat.sampleCount = 0;
    theOutputFormat.buffer = NULL;
    theOutputFormat.reserved = 0;

    // variableCompression means we're going to use the commonFrameSize field and the kExtendedSoundCommonFrameSizeValid flag
//    scFillBufferData.isSourceVBR = (outSoundInfo.compressionID == variableCompression );

    err = SoundConverterOpen( &theInputFormat, &theOutputFormat, 
                              &mySoundConverter );
    if ( err != noErr ) {
        printf( "failed to open sound converter\n" );
        exit( -1 );
      } else {
        printf( "opened sound converter ok\n" );
      }

    // this isn't crucial or even required for decompression only, but it does tell
    // the sound converter that we're cool with VBR audio
    Ptr tptr = NewPtr( 1 );
    tptr[0] = 1;
    SoundConverterSetInfo( mySoundConverter, siClientAcceptsVBR, tptr );
    free( tptr );

    /**
     * Set up the sound converters decompresson 'environment' by passing
     * in the 'magic' decompression atom
     */
    err = 
        SoundConverterSetInfo( mySoundConverter, siDecompressionParams,
                               outAudioAtom );
    if ( err != noErr ) {
        printf( "failed to set sound converter info\n" );
        exit( -1 );
      } else {
        printf( "set sound converter info ok\n" );
      }

    if ( outAudioAtom ) {
        DisposePtr( (Ptr)outAudioAtom );
      }

    if ( siUnknownInfoType == err ) {
        // clear this error, the decompressor didn't
        // need the decompression atom and that's OK
        err = noErr;
      } else {
//        BailErr(err);
      }

    /** 
     * The input buffer has to be large enough so GetMediaSample isn't
     * going to fail, your mileage may vary
     */
    Handle inputBuffer = NewHandle( MAX_BUFFER_SIZE );
//    HLock( inputBuffer );

    /** Start the sound conversion */
    err = SoundConverterBeginConversion(mySoundConverter);
//    BailErr(err);

    /** Extract compressed audio from media track */
    TimeValue tperSample = 0;
    err = 
        GetMediaSample( media, inputBuffer, 0, 
                        &noBytes, 0, NULL, &tperSample, NULL, NULL, 0, &noSamples, NULL );
    if ( err != noErr ) {
        printf( "failed to fetch media sample data: %d\n", GetMoviesError() );
        exit( -1 );
      } else {
        printf( "media sample: %d (%d) bytes / %ld samples / %d per sample\n", 
                noBytes, GetHandleSize( inputBuffer ), noSamples, tperSample );
      }

    unsigned long niBytes = 0;
    SoundConverterGetBufferSizes( mySoundConverter, noBytes * noSamples,
                                  &niFrames, &niBytes, &noBytes );

    printf( "buffer sizes: frames: %d\tibytes: %d\tobytes: %d\n",
            niFrames, niBytes, noBytes );

    /** Convert into uncompressed audio */
    Ptr outputBuffer = NewPtr( noBytes * 1.2 );
    SoundConverterConvertBuffer( mySoundConverter, inputBuffer, noSamples /* niFrames */, 
                                 outputBuffer, &noFrames, &noBytes );

    printf( "converted: %d frames / %d bytes\n", noFrames, noBytes );

    /** Shutdown the sound converter */
    err = SoundConverterEndConversion( mySoundConverter, outputBuffer, &noFrames, &noBytes );

    printf( "converted final: %d frames / %d bytes\n", noFrames, noBytes );

//    HUnlock( inputBuffer );

    /** We now should have decompressed audio for the input file */
    /** 
     * So, generate visuals using a sliding sample grid at the
     * given framerate
     */

    /** Create a new movie clip with audio and video tracks */

    /** PROJECTM CRAP HERE -- stuff frames into QuickTime */

    /** Close movie file */

    /** Shutdown MovieToolbox */
    ExitMovies();

    return 0;
  }
コード例 #29
0
void	AUControlGroup::AddAUInfo (		AUCarbonViewBase *			auView,
										const Point &				inLocation,
										const SInt16 				inRightOffset,
										const SInt16				inTotalWidth)
{
#if !__LP64__
   // get component info
	ComponentDescription desc;
    Handle h1 = NewHandleClear(4);
	OSStatus err = GetComponentInfo ((Component)auView->GetEditAudioUnit(), &desc, h1, 0, 0);

    if (err == noErr) {
        // Get the manufacturer's name... look for the ':' character convention
        HLock(h1);
        char* ptr1 = *h1;
        int len = *ptr1++;
        char* displayStr = 0;

        for (int i = 0; i < len; ++i) {
            if (ptr1[i] == ':') { // found the name
                ptr1[i++] = 0;
                displayStr = ptr1;
                break;
            }
        }

        // localize as necessary:
        if (!sLocalized) {
            CFBundleRef mainBundle = CFBundleGetBundleWithIdentifier(kLocalizedStringBundle_AUView);
            if (mainBundle) {
                kStringManufacturer = CFCopyLocalizedStringFromTableInBundle(
                                            kAUViewLocalizedStringKey_Manufacturer, kLocalizedStringTable_AUView,
                                            mainBundle, CFSTR("Manufacturer title string"));
                sLocalized = true;
            }
        }

        // display strings
        ControlRef newControl;
        Rect r;
        r.top = SInt16(inLocation.v);		r.bottom = SInt16(inLocation.v) + 16;
        ControlFontStyleRec fontStyle;
        fontStyle.flags = kControlUseFontMask | kControlUseJustMask;
        fontStyle.font = kControlFontSmallBoldSystemFont;

        // display manufacturer string
        if (displayStr) {
            CFMutableStringRef mfrstring = CFStringCreateMutable(NULL, 0);
            CFStringAppend(mfrstring, kStringManufacturer);		// "Manufacturer"
            CFStringAppend(mfrstring, kAUViewUnlocalizedString_TitleSeparator);
                                                                // "Manufacturer: "
            CFStringRef mfrname = CFStringCreateWithCString(NULL, displayStr, kCFStringEncodingUTF8);
            if (mfrname) {
                CFStringAppend(mfrstring, mfrname);	// "Manufacturer: MFRName"
                CFRelease (mfrname);
            }

            r.left = inLocation.h + inRightOffset;
			r.right = inLocation.h + inTotalWidth - 28;
			fontStyle.just = teFlushRight;

            verify_noerr(CreateStaticTextControl(auView->GetCarbonWindow(), &r, mfrstring, &fontStyle, &newControl));
            verify_noerr(auView->EmbedControl(newControl));
            CFRelease (mfrstring);

            //move displayStr ptr past the manu, to the name
            // we move the characters down an index, because the handle doesn't have any room
            // at the end for the \0
			int i = strlen(displayStr), j = 0;
			while (displayStr[++i] == ' ' && i < len)
				;
			while (i < len)
				displayStr[j++] = displayStr[i++];
			displayStr[j] = 0;
        } else {
			displayStr = ptr1;
			int i = 0, j = 0;
			do {
				displayStr[j] = displayStr[i];
				++j; ++i;
			} while (i < len);

			displayStr[j] = 0;
        }

        // display AudioUnit string
        r.left = inLocation.h;	r.right = r.left + inRightOffset;
        fontStyle.just = 0;

        CFMutableStringRef cfstr = CFStringCreateMutable(NULL, 0);
        CFStringAppend(cfstr, kAUViewLocalizedStringKey_AudioUnit);		// "Audio Unit"
        CFStringAppend(cfstr, kAUViewUnlocalizedString_TitleSeparator);
                                                        // "Audio Unit: "

		CFStringRef auname = CFStringCreateWithCString(NULL, displayStr, kCFStringEncodingUTF8);
		CFStringAppend(cfstr, auname);				// "Audio Unit: AUName"
		CFRelease (auname);

        verify_noerr(CreateStaticTextControl(auView->GetCarbonWindow(), &r, cfstr, &fontStyle, &newControl));

		// size text control correctly
		Boolean bValue = false;
		SetControlData(newControl, kControlEntireControl, 'stim' /* kControlStaticTextIsMultilineTag */, sizeof(Boolean), &bValue);
		SInt16 baseLineOffset;
		Rect bestRect;
		err = GetBestControlRect(newControl, &bestRect, &baseLineOffset);
		if (err == noErr)
		{
			int width = (bestRect.right - bestRect.left) + 1;
			int height = (bestRect.bottom - bestRect.top) + 1;
			SizeControl (newControl, width, height);
		}

        verify_noerr(auView->EmbedControl(newControl));
        CFRelease (cfstr);
    }

	DisposeHandle (h1);
#endif
}
コード例 #30
0
ファイル: tkMacInit.c プロジェクト: martym/Lens
int
TkpInit(
    Tcl_Interp *interp)		/* Interp to initialize. */
{
    char *libDir, *tempPath;
    Tcl_DString path;
    int result;

    /*
     * The following does not work with
     * safe interps because file exists is restricted.
     * to be fixed using [interp issafe] like in Unix & Windows.
     */
    static char initCmd[] = "\
proc sourcePath {file} {\n\
  global tk_library\n\
  if {[catch {uplevel #0 [list source $tk_library:$file.tcl]}] == 0} {\n\
    return\n\
  }\n\
  if {[catch {uplevel #0 [list source -rsrc $file]}] == 0} {\n\
    return\n\
  }\n\
  rename sourcePath {}\n\
  set msg \"can't find $file resource or a usable $file.tcl file\"\n\
  append msg \" perhaps you need to install Tk or set your \"\n\
  append msg \"TK_LIBRARY environment variable?\"\n\
  error $msg\n\
}\n\
sourcePath tk\n\
sourcePath button\n\
sourcePath dialog\n\
sourcePath entry\n\
sourcePath focus\n\
sourcePath listbox\n\
sourcePath menu\n\
sourcePath optMenu\n\
sourcePath palette\n\
sourcePath scale\n\
sourcePath scrlbar\n\
sourcePath tearoff\n\
sourcePath text\n\
sourcePath bgerror\n\
sourcePath msgbox\n\
sourcePath comdlg\n\
rename sourcePath {}";

    Tcl_DStringInit(&path);

    /*
     * The tk_library path can be found in several places.  Here is the order
     * in which the are searched.
     *		1) the variable may already exist
     *		2) env array
     *		3) System Folder:Extensions:Tool Command Language:
     */
     
    libDir = Tcl_GetVar(interp, "tk_library", TCL_GLOBAL_ONLY);
    if (libDir == NULL) {
	libDir = Tcl_GetVar2(interp, "env", "TK_LIBRARY", TCL_GLOBAL_ONLY);
    }
    if (libDir == NULL) {
	tempPath = Tcl_GetVar2(interp, "env", "EXT_FOLDER", TCL_GLOBAL_ONLY);
	if (tempPath != NULL) {
	    Tcl_DString libPath;
	    char *argv[3];
	    
	    argv[0] = tempPath;
	    argv[1] = "Tool Command Language";	    
	    Tcl_DStringInit(&libPath);
	    Tcl_DStringAppend(&libPath, "tk", -1);
	    Tcl_DStringAppend(&libPath, TK_VERSION, -1);
	    argv[2] = libPath.string;
	    Tcl_JoinPath(3, argv, &path);
	    Tcl_DStringFree(&libPath);
	    libDir = path.string;
	}
    }
    if (libDir == NULL) {
	libDir = "no library";
    }

    /*
     * Assign path to the global Tcl variable tcl_library.
     */
    Tcl_SetVar(interp, "tk_library", libDir, TCL_GLOBAL_ONLY);
    Tcl_DStringFree(&path);

	result = Tcl_Eval(interp, initCmd);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * TkpGetAppName --
 *
 *	Retrieves the name of the current application from a platform
 *	specific location.  On the Macintosh we look to see if the
 *	App Name is specified in a resource.  If not, the application 
 *	name is the root of the tail of the path contained in the tcl
 *	variable argv0.
 *
 * Results:
 *	Returns the application name in the given Tcl_DString.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkpGetAppName(
    Tcl_Interp *interp,		/* The main interpreter. */
    Tcl_DString *namePtr)	/* A previously initialized Tcl_DString. */
{
    int argc;
    char **argv = NULL, *name, *p;
    Handle h = NULL;

    h = GetNamedResource('STR ', "\pTk App Name");
    if (h != NULL) {
	HLock(h);
	Tcl_DStringAppend(namePtr, (*h)+1, **h);
	HUnlock(h);
	ReleaseResource(h);
	return;
    }
    
    name = Tcl_GetVar(interp, "argv0", TCL_GLOBAL_ONLY);
    if (name != NULL) {
	Tcl_SplitPath(name, &argc, &argv);
	if (argc > 0) {
	    name = argv[argc-1];
	    p = strrchr(name, '.');
	    if (p != NULL) {
		*p = '\0';
	    }
	} else {
	    name = NULL;
	}
    }
    if ((name == NULL) || (*name == 0)) {
	name = "tk";
    }
    Tcl_DStringAppend(namePtr, name, -1);
    if (argv != NULL) {
	ckfree((char *)argv);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkpDisplayWarning --
 *
 *	This routines is called from Tk_Main to display warning
 *	messages that occur during startup.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Displays a message box.
 *
 *----------------------------------------------------------------------
 */

void
TkpDisplayWarning(
    char *msg,			/* Message to be displayed. */
    char *title)		/* Title of warning. */
{
    Tcl_DString ds;
    Tcl_DStringInit(&ds);
    Tcl_DStringAppend(&ds, title, -1);
    Tcl_DStringAppend(&ds, ": ", -1);
    Tcl_DStringAppend(&ds, msg, -1);
    panic(Tcl_DStringValue(&ds));
    Tcl_DStringFree(&ds);
}