static PyObject* loadfont(PyObject* self, PyObject* args) { PyObject* result = Py_False; const char* path = NULL; int ok = PyArg_ParseTuple(args, "s", &path); if (ok) { CFStringRef componentPath = CFStringCreateWithCString(kCFAllocatorDefault, path, kCFStringEncodingUTF8); CFURLRef componentURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, componentPath, kCFURLPOSIXPathStyle, false); FSRef fsref; if (CFURLGetFSRef(componentURL, &fsref)) { OSStatus err = noErr; ATSFontContainerRef fontContainerRef; // we don't deactivate the font #if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4) err = ATSFontActivateFromFileReference(&fsref, kATSFontContextLocal, kATSFontFormatUnspecified, NULL, kATSOptionFlagsDefault, &fontContainerRef); #else FSSpec fsSpec; FSRef fsRef; if ((err = FSGetCatalogInfo( &fsRef, kFSCatInfoNone, NULL, NULL, &fsSpec, NULL)) == noErr) { err = ATSFontActivateFromFileSpecification(&fsSpec, kATSFontContextLocal, kATSFontFormatUnspecified, NULL, kATSOptionFlagsDefault, &fontContainerRef); } #endif if (err == noErr) { result = Py_True; } } CFRelease(componentURL); CFRelease(componentPath); } return result; }
OSStatus FindPIDForWoW(pid_t *pid) { CFURLRef outAppURL; OSErr err; err = LSFindApplicationForInfo(NULL, (CFStringRef)@"com.blizzard.worldofwarcraft", NULL, NULL, &outAppURL); err = 0; FSRef desired, found; ProcessSerialNumber psn = {0, kNoProcess}; if (!CFURLGetFSRef(outAppURL, &desired)) return errFSBadFSRef; do { err = GetNextProcess(&psn); if (err) return err; // -600 = process not found err = GetProcessBundleLocation(&psn, &found); } while (err || FSCompareFSRefs(&desired, &found)); err = GetProcessPID(&psn, pid); if (err) return err; return noErr; }
static OSErr FindSNESFolder(FSRef *folderRef, char *folderPath, const char *folderName) { OSStatus err; CFURLRef burl, purl; CFStringRef fstr; FSRef pref; UniChar buffer[PATH_MAX + 1]; Boolean r; fstr = CFStringCreateWithCString(kCFAllocatorDefault, folderName, CFStringGetSystemEncoding()); CFStringGetCharacters(fstr, CFRangeMake(0, CFStringGetLength(fstr)), buffer); burl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); purl = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, burl); r = CFURLGetFSRef(purl, &pref); err = FSMakeFSRefUnicode(&pref, CFStringGetLength(fstr), buffer, kTextEncodingUnicodeDefault, folderRef); if (err == dirNFErr || err == fnfErr) { err = FSCreateDirectoryUnicode(&pref, CFStringGetLength(fstr), buffer, kFSCatInfoNone, nil, folderRef, nil, nil); if (err == noErr) AddFolderIcon(folderRef, folderName); } if (err != noErr && !folderWarning) { AppearanceAlert(kAlertCautionAlert, kFolderFail, kFolderHint); folderWarning = true; } else err = FSRefMakePath(folderRef, (unsigned char *) folderPath, PATH_MAX); CFRelease(purl); CFRelease(burl); CFRelease(fstr); return err; }
int __open_file(const char * name, __file_modes mode, __file_handle * handle) { FSSpec spec; OSErr ioResult; HParamBlockRec pb; ioResult = __path2fss(name, &spec); if (ioResult) gSqueakFileLastError = ioResult; if (__system7present()) /* mm 980424 */ { /* mm 980424 */ Boolean targetIsFolder, wasAliased; /* mm 980424 */ ResolveAliasFile(&spec, true, &targetIsFolder, &wasAliased); /* mm 980424 */ } /* mm 980424 */ if (ioResult && (ioResult != fnfErr || mode.open_mode == __must_exist)) return(__io_error); #if TARGET_API_MAC_CARBON if (ioResult) { CFStringRef filePath; CFURLRef sillyThing, sillyThing2; FSRef parentFSRef; short int fileRefNum; OSErr err; UniChar buffer[1024]; long tokenLength; filePath = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)name,strlen(name),gCurrentVMEncoding,false); if (filePath == nil) return __io_error; sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLHFSPathStyle,false); CFRelease(filePath); sillyThing2 = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault,sillyThing); err = CFURLGetFSRef(sillyThing2,&parentFSRef); if (err == 0) { CFRelease(sillyThing); CFRelease(sillyThing2); return fnfErr; } filePath = CFURLCopyLastPathComponent(sillyThing); tokenLength = CFStringGetLength(filePath); if (tokenLength > 1024) { CFRelease(filePath); CFRelease(sillyThing); CFRelease(sillyThing2); return(__io_error); } CFStringGetCharacters(filePath,CFRangeMake(0,tokenLength),buffer); CFRelease(filePath); CFRelease(sillyThing); CFRelease(sillyThing2); ioResult = FSCreateFileUnicode(&parentFSRef,tokenLength,buffer,kFSCatInfoNone,NULL,NULL,&spec); if (ioResult) gSqueakFileLastError = ioResult; if (ioResult) return(__io_error); pb.ioParam.ioNamePtr = spec.name; pb.ioParam.ioVRefNum = spec.vRefNum; pb.ioParam.ioPermssn = (mode.io_mode == __read) ? fsRdPerm : fsRdWrPerm; pb.ioParam.ioMisc = 0; pb.fileParam.ioFVersNum = 0; pb.fileParam.ioDirID = spec.parID; set_file_type(&spec, mode.binary_io); ioResult = PBHOpenDFSync(&pb); /* HH 10/25/97 was PBHOpenSync */ if (ioResult) return(__io_error); *handle = pb.ioParam.ioRefNum; return(__no_io_error); } #endif pb.ioParam.ioNamePtr = spec.name; pb.ioParam.ioVRefNum = spec.vRefNum; pb.ioParam.ioPermssn = (mode.io_mode == __read) ? fsRdPerm : fsRdWrPerm; pb.ioParam.ioMisc = 0; pb.fileParam.ioFVersNum = 0; pb.fileParam.ioDirID = spec.parID; if (ioResult) { if (!(ioResult = PBHCreateSync(&pb))) { if (ioResult) gSqueakFileLastError = ioResult; set_file_type(&spec, mode.binary_io); ioResult = PBHOpenDFSync(&pb); /* HH 10/25/97 was PBHOpenSync */ if (ioResult) gSqueakFileLastError = ioResult; } } else { if (!(ioResult = PBHOpenDFSync(&pb)) && mode.open_mode == __create_or_truncate) /* HH 10/25/97 was PBHOpenSync */ { pb.ioParam.ioMisc = 0; ioResult = PBSetEOFSync((ParmBlkPtr) &pb); if (ioResult) gSqueakFileLastError = ioResult; if (ioResult) PBCloseSync((ParmBlkPtr) &pb); } else { if (ioResult) gSqueakFileLastError = ioResult; } } if (ioResult) return(__io_error); *handle = pb.ioParam.ioRefNum; return(__no_io_error); }
prMALError SDKOpenFile8( imStdParms *stdParms, imFileRef *SDKfileRef, imFileOpenRec8 *SDKfileOpenRec8) { prMALError result = malNoError; ImporterLocalRec8H localRecH = NULL; ImporterLocalRec8Ptr localRecP = NULL; if(SDKfileOpenRec8->privatedata) { localRecH = (ImporterLocalRec8H)SDKfileOpenRec8->privatedata; stdParms->piSuites->memFuncs->lockHandle(reinterpret_cast<char**>(localRecH)); localRecP = reinterpret_cast<ImporterLocalRec8Ptr>( *localRecH ); } else { localRecH = (ImporterLocalRec8H)stdParms->piSuites->memFuncs->newHandle(sizeof(ImporterLocalRec8)); SDKfileOpenRec8->privatedata = (PrivateDataPtr)localRecH; stdParms->piSuites->memFuncs->lockHandle(reinterpret_cast<char**>(localRecH)); localRecP = reinterpret_cast<ImporterLocalRec8Ptr>( *localRecH ); localRecP->vf = NULL; localRecP->opus = NULL; localRecP->flac = NULL; localRecP->importerID = SDKfileOpenRec8->inImporterID; localRecP->fileType = SDKfileOpenRec8->fileinfo.filetype; } SDKfileOpenRec8->fileinfo.fileref = *SDKfileRef = reinterpret_cast<imFileRef>(imInvalidHandleValue); if(localRecP) { const prUTF16Char *path = SDKfileOpenRec8->fileinfo.filepath; #ifdef PRWIN_ENV HANDLE fileH = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(fileH != imInvalidHandleValue) { SDKfileOpenRec8->fileinfo.fileref = *SDKfileRef = fileH; } else result = imFileOpenFailed; #else FSIORefNum refNum = CAST_REFNUM(imInvalidHandleValue); CFStringRef filePathCFSR = CFStringCreateWithCharacters(NULL, path, prUTF16CharLength(path)); CFURLRef filePathURL = CFURLCreateWithFileSystemPath(NULL, filePathCFSR, kCFURLPOSIXPathStyle, false); if(filePathURL != NULL) { FSRef fileRef; Boolean success = CFURLGetFSRef(filePathURL, &fileRef); if(success) { HFSUniStr255 dataForkName; FSGetDataForkName(&dataForkName); OSErr err = FSOpenFork( &fileRef, dataForkName.length, dataForkName.unicode, fsRdWrPerm, &refNum); } CFRelease(filePathURL); } CFRelease(filePathCFSR); if(CAST_FILEREF(refNum) != imInvalidHandleValue) { SDKfileOpenRec8->fileinfo.fileref = *SDKfileRef = CAST_FILEREF(refNum); } else result = imFileOpenFailed; #endif } if(result == malNoError) { localRecP->fileType = SDKfileOpenRec8->fileinfo.filetype; assert(0 == ogg_tell_func(static_cast<void *>(*SDKfileRef))); if(localRecP->fileType == Ogg_filetype) { localRecP->vf = new OggVorbis_File; OggVorbis_File &vf = *localRecP->vf; int ogg_err = ov_open_callbacks(static_cast<void *>(*SDKfileRef), &vf, NULL, 0, g_ov_callbacks); if(ogg_err == OV_OK) { if( ov_streams(&vf) == 0 ) { result = imFileHasNoImportableStreams; ov_clear(&vf); } else if( !ov_seekable(&vf) ) { result = imBadFile; } } else result = imBadHeader; } else if(localRecP->fileType == Opus_filetype) { int _error = 0; localRecP->opus = op_open_callbacks(static_cast<void *>(*SDKfileRef), &g_opusfile_callbacks, NULL, 0, &_error); if(localRecP->opus != NULL && _error == 0) { assert(op_link_count(localRecP->opus) == 1); // we're not really handling multi-link scenarios } else result = imBadHeader; } else if(localRecP->fileType == FLAC_filetype) { try { localRecP->flac = new OurDecoder(*SDKfileRef); localRecP->flac->set_md5_checking(true); FLAC__StreamDecoderInitStatus init_status = localRecP->flac->init(); assert(init_status == FLAC__STREAM_DECODER_INIT_STATUS_OK && localRecP->flac->is_valid()); bool ok = localRecP->flac->process_until_end_of_metadata(); assert(ok); } catch(...) { result = imBadHeader; } } } // close file and delete private data if we got a bad file if(result != malNoError) { if(SDKfileOpenRec8->privatedata) { stdParms->piSuites->memFuncs->disposeHandle(reinterpret_cast<PrMemoryHandle>(SDKfileOpenRec8->privatedata)); SDKfileOpenRec8->privatedata = NULL; } } else { stdParms->piSuites->memFuncs->unlockHandle(reinterpret_cast<char**>(SDKfileOpenRec8->privatedata)); } return result; }
static int quicklyMakePath(char *pathString, int pathStringLength,char *dst, Boolean resolveAlias) { CFStringRef filePath; CFURLRef sillyThing,firstPartOfPath; FSRef theFSRef; Boolean isFolder,isAlias; OSErr err; filePath = CFStringCreateWithBytes(kCFAllocatorDefault, (UInt8 *)pathString,pathStringLength,gCurrentVMEncoding,false); if (filePath == nil) return -1; CFMutableStringRef str= CFStringCreateMutableCopy(NULL, 0, filePath); // HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements if (gCurrentVMEncoding == kCFStringEncodingUTF8) CFStringNormalize(str, kCFStringNormalizationFormKC); // canonical decomposition sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault, str, kCFURLHFSPathStyle,false); if (sillyThing == NULL) { CFRelease(filePath); return -2; } CFRelease(str); if (!CFURLGetFSRef(sillyThing,&theFSRef)) { firstPartOfPath = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault,sillyThing); if (!CFURLGetFSRef(firstPartOfPath,&theFSRef)) { CFRelease(firstPartOfPath); CFRelease(filePath); CFRelease(sillyThing); return -1; } else { CFStringRef lastPathPart; char lastpart[256]; CFRelease(filePath); CFRelease(firstPartOfPath); lastPathPart = CFURLCopyLastPathComponent(sillyThing); CFRelease(sillyThing); err = noErr; if (resolveAlias) err = FSResolveAliasFile (&theFSRef,true,&isFolder,&isAlias); if (err) return 2; err = FSRefMakePath(&theFSRef,(UInt8 *)dst,1000); CFStringGetCString(lastPathPart,lastpart,256, kCFStringEncodingUTF8); CFRelease(lastPathPart); if (strlen(dst)+1+strlen(lastpart) < 1000) { strcat(dst,"/"); strcat(dst,lastpart); #if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__) filePath = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)dst,strlen(dst),gCurrentVMEncoding,false); if (filePath == nil) return 2; sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLPOSIXPathStyle,true); CFRelease(filePath); filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle); CFStringGetCString (filePath,dst,1000, gCurrentVMEncoding); CFRelease(sillyThing); CFRelease(filePath); #endif return 0; } else return 2; } } CFRelease(filePath); CFRelease(sillyThing); if (resolveAlias) err = FSResolveAliasFile (&theFSRef,true,&isFolder,&isAlias); #if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__) sillyThing = CFURLCreateFromFSRef(kCFAllocatorDefault,&theFSRef); filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle); CFStringGetCString (filePath,dst,1000, gCurrentVMEncoding); CFRelease(sillyThing); CFRelease(filePath); return 0; #else err = FSRefMakePath(&theFSRef,(UInt8 *)dst,1000); return err; #endif }
void MusicBoxDialog(void) { OSStatus err; IBNibRef nibRef; if (!cartOpen) return; err = CreateNibReference(kMacS9XCFString, &nibRef); if (err == noErr) { CFURLRef iconURL; FSRef iconFSRef; IconRef actIcon; WindowRef tWindowRef; actIcon = nil; if (musicboxmode == kMBXSoundEmulation) iconURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("musicbox_ledoff"), CFSTR("icns"), nil); else iconURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("musicbox_ledon" ), CFSTR("icns"), nil); if (iconURL) { if (CFURLGetFSRef(iconURL, &iconFSRef)) err = RegisterIconRefFromFSRef('~9X~', 'micn', &iconFSRef, &actIcon); CFRelease(iconURL); } err = CreateWindowFromNib(nibRef, CFSTR("MusicBox"), &tWindowRef); if (err == noErr) { EventHandlerRef mboxRef, paneRef; EventHandlerUPP mboxUPP, paneUPP; EventLoopTimerRef timeRef; EventLoopTimerUPP timeUPP; EventTypeSpec mboxEvents[] = { { kEventClassCommand, kEventCommandProcess }, { kEventClassCommand, kEventCommandUpdateStatus } }, paneEvents[] = { { kEventClassControl, kEventControlDraw } }; CFStringRef sref; CGDataProviderRef prov; CGImageRef ipng; CFURLRef iurl; HIViewRef ctl, root, paneView, imageView, contentView; HIViewID cid; HIRect bounds; Rect windowRect, barRect; char drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME], ext[_MAX_EXT]; mboxPause = false; mbxFinished = false; showIndicator = false; so.stereo_switch = ~0; for (int i = 0; i < MAC_MAX_PLAYERS; i++) controlPad[i] = 0; switch (drawingMethod) { case kDrawingOpenGL: Settings.OpenGLEnable = true; break; case kDrawingDirect: case kDrawingBlitGL: Settings.OpenGLEnable = false; } // 107's enhanced SPC player root = HIViewGetRoot(tWindowRef); cid.id = 0; if (musicboxmode == kMBXSoundEmulation) { cid.signature = 'HEAD'; HIViewFindByID(root, cid, &ctl); EnableControl(ctl); StoredAPU = new SAPU; StoredAPURegisters = new SAPURegisters; StoredSoundData = new SSoundData; StoredIAPURAM = new uint8 [0x10000]; SPCPlayFreeze(); } else MusicBoxForceFreeze(); cid.signature = 'Kart'; HIViewFindByID(root, cid, &ctl); SetStaticTextTrunc(ctl, truncEnd, false); _splitpath(Memory.ROMFilename, drive, dir, fname, ext); sref = CFStringCreateWithCString(kCFAllocatorDefault, fname, MAC_PATH_ENCODING); if (sref) { SetStaticTextCFString(ctl, sref, false); CFRelease(sref); } ipng = nil; iurl = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("musicbox_indicator"), CFSTR("png"), nil); if (iurl) { prov = CGDataProviderCreateWithURL(iurl); if (prov) { ipng = CGImageCreateWithPNGDataProvider(prov, nil, false, kCGRenderingIntentDefault); CGDataProviderRelease(prov); } CFRelease(iurl); } imageView = nil; if (ipng) { HIViewFindByID(root, kHIViewWindowContentID, &contentView); err = HIImageViewCreate(ipng, &imageView); if (err == noErr) { bounds = CGRectMake(30, 64, CGImageGetWidth(ipng), CGImageGetHeight(ipng)); HIViewSetFrame(imageView, &bounds); HIImageViewSetOpaque(imageView, false); HIViewSetVisible(imageView, true); HIViewAddSubview(contentView, imageView); cid.signature = 'iMaG'; SetControlID(imageView, &cid); } CGImageRelease(ipng); } cid.signature = 'Pane'; HIViewFindByID(root, cid, &paneView); HIViewGetBounds(paneView, &bounds); mbxViewWidth = bounds.size.width; mbxViewHeight = bounds.size.height; mbxMarginY = (mbxViewHeight - mbxBarHeight) / 2.0; mbxMarginX = (mbxViewWidth - ((mbxBarWidth * 8.0 + mbxBarSpace * 7.0) * 2.0 + mbxLRSpace)) / 2.0; if (imageView) { HIViewSetZOrder(imageView, kHIViewZOrderBelow, paneView); HIViewAddSubview(imageView, paneView); } cid.signature = 'Tr_i'; HIViewFindByID(root, cid, &ctl); HIViewGetFrame(ctl, &bounds); GetWindowBounds(tWindowRef, kWindowTitleBarRgn, &barRect); mbxClosedHeight = (short) (bounds.origin.y + bounds.size.height + 7.0) + (barRect.bottom - barRect.top); GetWindowBounds(tWindowRef, kWindowStructureRgn, &windowRect); mbxOpenedHeight = windowRect.bottom - windowRect.top; windowRect.bottom = windowRect.top + mbxClosedHeight; SetWindowBounds(tWindowRef, kWindowStructureRgn, &windowRect); paneUPP = NewEventHandlerUPP(IndicatorEventHandler); err = InstallControlEventHandler(paneView, paneUPP, GetEventTypeCount(paneEvents), paneEvents, (void *) paneView, &paneRef); mboxUPP = NewEventHandlerUPP(MusicBoxEventHandler); err = InstallWindowEventHandler(tWindowRef, mboxUPP, GetEventTypeCount(mboxEvents), mboxEvents, (void *) tWindowRef, &mboxRef); timeUPP = NewEventLoopTimerUPP(MusicBoxTimerHandler); err = InstallEventLoopTimer(GetCurrentEventLoop(), kEventDurationNoWait, kEventDurationSecond * 2.0 / (double) Memory.ROMFramesPerSecond, timeUPP, (void *) paneView, &timeRef); MusicBoxInitIndicator(); stopNow = false; MacStartSound(); pthread_create(&mbxThread, nil, SoundTask, nil); MoveWindowPosition(tWindowRef, kWindowMusicBox, true); GetWindowBounds(tWindowRef, kWindowStructureRgn, &windowRect); if (windowRect.bottom - windowRect.top > mbxClosedHeight) { showIndicator = true; SetControl32BitValue(ctl, 1); // Tr_i } ShowWindow(tWindowRef); err = RunAppModalLoopForWindow(tWindowRef); HideWindow(tWindowRef); SaveWindowPosition(tWindowRef, kWindowMusicBox); stopNow = true; pthread_join(mbxThread, nil); MacStopSound(); err = RemoveEventLoopTimer(timeRef); DisposeEventLoopTimerUPP(timeUPP); err = RemoveEventHandler(mboxRef); DisposeEventHandlerUPP(mboxUPP); err = RemoveEventHandler(paneRef); DisposeEventHandlerUPP(paneUPP); ReleaseWindow(tWindowRef); so.stereo_switch = ~0; mbxFinished = true; if (musicboxmode == kMBXSoundEmulation) { SPCPlayDefrost(); delete StoredAPU; delete StoredAPURegisters; delete StoredSoundData; delete [] StoredIAPURAM; } else MusicBoxForceDefrost(); Settings.OpenGLEnable = false; } if (actIcon) err = UnregisterIconRef('~9X~', 'micn'); DisposeNibReference(nibRef); } }
// -------------------------------------------------------------------------------------- static DataBrowserItemID addItemsToIconDB(ControlRef iconDataBrowser, ControlRef *userPanes) { IconDBItemDataRec *itemsData, *rowItemData; CFBundleRef mainBundle; CFIndex rowNumber; DataBrowserItemID items[kNumberOfRows]; CFStringRef catNameKeys[kNumberOfRows]; itemsData = CFAllocatorAllocate(kCFAllocatorDefault, kNumberOfRows * sizeof(IconDBItemDataRec), 0); mainBundle = CFBundleGetMainBundle(); if (!gIconsRegistered) // if we didn't register our icons already, we need to { CFArrayRef iconURLs; FSRef iconFile; FSSpec iconSpec; iconURLs = CFBundleCopyResourceURLsOfType(mainBundle, CFSTR("icns"), CFSTR("PrefCategories")); for (rowNumber = 0; rowNumber < kNumberOfRows; rowNumber++) { CFURLGetFSRef(CFArrayGetValueAtIndex(iconURLs, rowNumber), &iconFile); #if TARGET_API_MAC_OSX #pragma unused (iconSpec) RegisterIconRefFromFSRef(kAppSignature, 'Cat0' + rowNumber, &iconFile, &((itemsData + rowNumber)->icon)); #else FSGetCatalogInfo(&iconFile, kFSCatInfoNone, NULL, NULL, &iconSpec, NULL); RegisterIconRefFromIconFile(kAppSignature, 'Cat0' + rowNumber, &iconSpec, &((itemsData + rowNumber)->icon)); #endif } CFRelease(iconURLs); gIconsRegistered = true; } else // the icons are already registered so we just have to get them { for (rowNumber = 0; rowNumber < kNumberOfRows; rowNumber++) { GetIconRef(kOnSystemDisk, kAppSignature, 'Cat0' + rowNumber, &((itemsData + rowNumber)->icon)); } } catNameKeys[0] = CFSTR("Panel 1"); // this is necessary because you have to use catNameKeys[1] = CFSTR("Panel 2"); // constant strings with CFSTR catNameKeys[2] = CFSTR("Panel 3"); // if we didn't do this then we couldn't get catNameKeys[3] = CFSTR("Panel 4"); // the strings in a loop catNameKeys[4] = CFSTR("Panel 5"); catNameKeys[5] = CFSTR("Panel 6"); catNameKeys[6] = CFSTR("Panel 7"); catNameKeys[7] = CFSTR("Panel 8"); catNameKeys[8] = CFSTR("Panel 9"); catNameKeys[9] = CFSTR("Panel 10"); for (rowNumber = 0; rowNumber < kNumberOfRows; rowNumber++) // now get the names { // and set the user panes rowItemData = itemsData + rowNumber; items[rowNumber] = (DataBrowserItemID)rowItemData; /* We use CFCopyLocalilzedStringFromTableInBundle here instead of CFCopyLocalizedString to avoid a call to CFBundleGetMainBundle every trip around the loop. */ rowItemData->name = CFCopyLocalizedStringFromTableInBundle(catNameKeys[rowNumber], NULL, mainBundle, NULL); rowItemData->userPane = *(userPanes + rowNumber); } AddDataBrowserItems(iconDataBrowser, kDataBrowserNoItem, kNumberOfRows, items, kDataBrowserItemNoProperty); return *items; }
prMALError SDKOpenFile8( imStdParms *stdParms, imFileRef *SDKfileRef, imFileOpenRec8 *SDKfileOpenRec8) { prMALError result = malNoError; ImporterLocalRec8H localRecH = NULL; ImporterLocalRec8Ptr localRecP = NULL; if(SDKfileOpenRec8->privatedata) { localRecH = (ImporterLocalRec8H)SDKfileOpenRec8->privatedata; stdParms->piSuites->memFuncs->lockHandle(reinterpret_cast<char**>(localRecH)); localRecP = reinterpret_cast<ImporterLocalRec8Ptr>( *localRecH ); } else { localRecH = (ImporterLocalRec8H)stdParms->piSuites->memFuncs->newHandle(sizeof(ImporterLocalRec8)); SDKfileOpenRec8->privatedata = (PrivateDataPtr)localRecH; stdParms->piSuites->memFuncs->lockHandle(reinterpret_cast<char**>(localRecH)); localRecP = reinterpret_cast<ImporterLocalRec8Ptr>( *localRecH ); localRecP->reader = NULL; localRecP->file = NULL; localRecP->audio_track = NULL; localRecP->alac = NULL; localRecP->importerID = SDKfileOpenRec8->inImporterID; localRecP->fileType = SDKfileOpenRec8->fileinfo.filetype; } SDKfileOpenRec8->fileinfo.fileref = *SDKfileRef = reinterpret_cast<imFileRef>(imInvalidHandleValue); if(localRecP) { const prUTF16Char *path = SDKfileOpenRec8->fileinfo.filepath; #ifdef PRWIN_ENV HANDLE fileH = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(fileH != imInvalidHandleValue) { SDKfileOpenRec8->fileinfo.fileref = *SDKfileRef = fileH; } else result = imFileOpenFailed; #else FSIORefNum refNum = CAST_REFNUM(imInvalidHandleValue); CFStringRef filePathCFSR = CFStringCreateWithCharacters(NULL, path, prUTF16CharLength(path)); CFURLRef filePathURL = CFURLCreateWithFileSystemPath(NULL, filePathCFSR, kCFURLPOSIXPathStyle, false); if(filePathURL != NULL) { FSRef fileRef; Boolean success = CFURLGetFSRef(filePathURL, &fileRef); if(success) { HFSUniStr255 dataForkName; FSGetDataForkName(&dataForkName); OSErr err = FSOpenFork( &fileRef, dataForkName.length, dataForkName.unicode, fsRdPerm, &refNum); } CFRelease(filePathURL); } CFRelease(filePathCFSR); if(CAST_FILEREF(refNum) != imInvalidHandleValue) { SDKfileOpenRec8->fileinfo.fileref = *SDKfileRef = CAST_FILEREF(refNum); } else result = imFileOpenFailed; #endif } if(result == malNoError) { localRecP->fileType = SDKfileOpenRec8->fileinfo.filetype; try { localRecP->reader = new My_ByteStream(*SDKfileRef); localRecP->file = new AP4_File(*localRecP->reader); AP4_Track *audio_track = localRecP->file->GetMovie()->GetTrack(AP4_Track::TYPE_AUDIO); if(audio_track != NULL) { assert(audio_track->GetSampleDescriptionCount() == 1); AP4_SampleDescription *desc = audio_track->GetSampleDescription(0); AP4_AudioSampleDescription *audio_desc = AP4_DYNAMIC_CAST(AP4_AudioSampleDescription, desc); if(desc != NULL && desc->GetFormat() == AP4_SAMPLE_FORMAT_ALAC) { localRecP->audio_track = audio_track; ALAC_Atom *alac_atom = AP4_DYNAMIC_CAST(ALAC_Atom, desc->GetDetails().GetChild(AP4_SAMPLE_FORMAT_ALAC)); if(alac_atom != NULL) { size_t magic_cookie_size = 0; void *magic_cookie = alac_atom->GetMagicCookie(magic_cookie_size); if(magic_cookie != NULL && magic_cookie_size > 0) { localRecP->alac = new ALACDecoder(); int32_t alac_result = localRecP->alac->Init(magic_cookie, magic_cookie_size); if(alac_result != 0) { result = imBadHeader; } } else result = imBadHeader; } else result = imBadHeader; } else result = imUnsupportedCompression; } else result = imFileHasNoImportableStreams; } catch(...) { result = imBadFile; } } // close file and delete private data if we got a bad file if(result != malNoError) { if(SDKfileOpenRec8->privatedata) { stdParms->piSuites->memFuncs->disposeHandle(reinterpret_cast<PrMemoryHandle>(SDKfileOpenRec8->privatedata)); SDKfileOpenRec8->privatedata = NULL; } } else { stdParms->piSuites->memFuncs->unlockHandle(reinterpret_cast<char**>(SDKfileOpenRec8->privatedata)); } return result; }
/* main: * Guess what this function does. */ int main(int argc, char *argv[]) { PACKFILE *f; CFURLRef cf_url_ref; FSRef fs_ref; FSSpec fs_spec; IconFamilyHandle icon_family; Handle raw_data; char datafile[MAX_STRING_SIZE]; char bundle[MAX_STRING_SIZE]; char bundle_dir[MAX_STRING_SIZE]; char bundle_contents_dir[MAX_STRING_SIZE]; char bundle_contents_resources_dir[MAX_STRING_SIZE]; char bundle_contents_macos_dir[MAX_STRING_SIZE]; char bundle_contents_frameworks_dir[MAX_STRING_SIZE]; char *bundle_exe = NULL; char bundle_plist[MAX_STRING_SIZE]; char bundle_pkginfo[MAX_STRING_SIZE]; char bundle_icns[MAX_STRING_SIZE]; char bundle_version[MAX_STRING_SIZE]; char bundle_long_version[MAX_STRING_SIZE]; char *buffer = NULL; int arg, type = 0, result = 0; int i, size, x, y, mask_bit, mask_byte; unsigned char *data; install_allegro(SYSTEM_NONE, &errno, &atexit); set_color_depth(32); set_color_conversion(COLORCONV_TOTAL | COLORCONV_KEEP_TRANS); if (argc < 2) usage(); datafile[0] = '\0'; bundle[0] = '\0'; select_palette(black_palette); /* Parse command line and load any given resource */ for (arg = 2; arg < argc; arg++) { if (!strcmp(argv[arg], "-m")) flags |= F_MOVE; else if (!strcmp(argv[arg], "-e")) flags |= F_EMBED_FRAMEWORK; else if (!strcmp(argv[arg], "-o")) { if ((argc < arg + 2) || (bundle[0] != '\0')) usage(); strcpy(bundle, argv[++arg]); } else if (!strcmp(argv[arg], "-v")) { if (argc < arg + 2) usage(); flags |= F_GOT_VERSION; strcpy(bundle_version, argv[++arg]); } else if (!strcmp(argv[arg], "-V")) { if (argc < arg + 2) usage(); flags |= F_GOT_LONG_VERSION; strcpy(bundle_long_version, argv[++arg]); } else if (!strcmp(argv[arg], "-d")) { if (argc < arg + 2) usage(); strcpy(datafile, argv[++arg]); } else if ((!strcmp(argv[arg], "-16")) || (!strcmp(argv[arg], "-32")) || (!strcmp(argv[arg], "-48")) || (!strcmp(argv[arg], "-128"))) { if (argc < arg + 2) usage(); switch (atoi(&argv[arg][1])) { case 16: type = 0; break; case 32: type = 1; break; case 48: type = 2; break; case 128: type = 3; break; } if (load_resource(datafile, argv[++arg], &icon_data[type])) { result = -1; goto exit_error; } } else { if (load_resource(datafile, argv[arg], NULL)) { result = -1; goto exit_error; } } } buffer = malloc(4096); if (!buffer) { result = -1; goto exit_error_bundle; } bundle_exe = argv[1]; if (!exists(bundle_exe)) { fprintf(stderr, "Cannot locate executable file '%s'\n", bundle_exe); result = -1; goto exit_error; } if (bundle[0] == '\0') strcpy(bundle, bundle_exe); replace_extension(bundle_dir, bundle, "app", MAX_STRING_SIZE); strcpy(bundle_contents_dir, bundle_dir); strcat(bundle_contents_dir, "/Contents"); strcpy(bundle_contents_resources_dir, bundle_contents_dir); strcat(bundle_contents_resources_dir, "/Resources"); strcpy(bundle_contents_macos_dir, bundle_contents_dir); strcat(bundle_contents_macos_dir, "/MacOS"); strcpy(bundle_contents_frameworks_dir, bundle_contents_dir); strcat(bundle_contents_frameworks_dir, "/Frameworks"); bundle_icns[0] = '\0'; bundle_plist[0] = '\0'; bundle_pkginfo[0] = '\0'; /* Create bundle structure */ if ((mkdir(bundle_dir, 0777) && (errno != EEXIST)) || (mkdir(bundle_contents_dir, 0777) && (errno != EEXIST)) || (mkdir(bundle_contents_resources_dir, 0777) && (errno != EEXIST)) || (mkdir(bundle_contents_macos_dir, 0777) && (errno != EEXIST))) { fprintf(stderr, "Cannot create %s\n", bundle_dir); result = -1; goto exit_error_bundle; } /* Copy/move executable into the bundle */ if (copy_file(bundle_exe, bundle_contents_macos_dir)) { fprintf(stderr, "Cannot create %s\n", bundle_contents_macos_dir); result = -1; goto exit_error_bundle; } strcat(bundle_contents_macos_dir, "/"); strcat(bundle_contents_macos_dir, get_filename(bundle_exe)); chmod(bundle_contents_macos_dir, 0755); if (flags & F_MOVE) unlink(bundle_exe); /* Embed Allegro framework if requested */ if (flags & F_EMBED_FRAMEWORK) { if (!file_exists("/Library/Frameworks/Allegro.framework", FA_RDONLY | FA_DIREC, NULL)) { fprintf(stderr, "Cannot find Allegro framework\n"); result = -1; goto exit_error_bundle; } if (!exists("/Library/Frameworks/Allegro.framework/Resources/Embeddable")) { fprintf(stderr, "Cannot embed system wide Allegro framework; install embeddable version first!\n"); result = -1; goto exit_error_bundle; } sprintf(buffer, "/Developer/Tools/pbxcp -exclude .DS_Store -exclude CVS -resolve-src-symlinks /Library/Frameworks/Allegro.framework %s", bundle_contents_frameworks_dir); if ((mkdir(bundle_contents_frameworks_dir, 0777) && (errno != EEXIST)) || (system(buffer))) { fprintf(stderr, "Cannot create %s\n", bundle_contents_frameworks_dir); result = -1; goto exit_error_bundle; } } /* Setup the .icns resource */ if (flags & F_ICONS_DEFINED) { strcat(bundle_contents_resources_dir, "/"); strcat(bundle_contents_resources_dir, get_filename(bundle)); replace_extension(bundle_icns, bundle_contents_resources_dir, "icns", MAX_STRING_SIZE); icon_family = (IconFamilyHandle)NewHandle(0); for (i = 0; i < 4; i++) { if (flags & icon_data[i].defined) { /* Set 32bit RGBA data */ raw_data = NewHandle(icon_data[i].size * icon_data[i].size * 4); data = *(unsigned char **)raw_data; for (y = 0; y < icon_data[i].size; y++) { for (x = 0; x < icon_data[i].size; x++) { *data++ = geta32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); *data++ = getr32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); *data++ = getg32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); *data++ = getb32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); } } if (SetIconFamilyData(icon_family, icon_data[i].data, raw_data) != noErr) { DisposeHandle(raw_data); fprintf(stderr, "Error setting %dx%d icon resource RGBA data\n", icon_data[i].size, icon_data[i].size); result = -1; goto exit_error_bundle; } DisposeHandle(raw_data); /* Set 8bit mask */ raw_data = NewHandle(icon_data[i].size * icon_data[i].size); data = *(unsigned char **)raw_data; for (y = 0; y < icon_data[i].size; y++) { for (x = 0; x < icon_data[i].size; x++) { *data++ = geta32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); } } if (SetIconFamilyData(icon_family, icon_data[i].mask8, raw_data) != noErr) { DisposeHandle(raw_data); fprintf(stderr, "Error setting %dx%d icon resource 8bit mask\n", icon_data[i].size, icon_data[i].size); result = -1; goto exit_error_bundle; } DisposeHandle(raw_data); /* Set 1bit mask */ if (icon_data[i].mask1) { size = ((icon_data[i].size * icon_data[i].size) + 7) / 8; raw_data = NewHandle(size * 2); data = *(unsigned char **)raw_data; mask_byte = 0; mask_bit = 7; for (y = 0; y < icon_data[i].size; y++) { for (x = 0; x < icon_data[i].size; x++) { if (geta32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]) >= 0xfd) mask_byte |= (1 << mask_bit); mask_bit--; if (mask_bit < 0) { *data++ = mask_byte; mask_byte = 0; mask_bit = 7; } } } memcpy(*raw_data + size, *raw_data, size); if (SetIconFamilyData(icon_family, icon_data[i].mask1, raw_data) != noErr) { DisposeHandle(raw_data); fprintf(stderr, "Error setting %dx%d icon resource 1bit mask\n", icon_data[i].size, icon_data[i].size); result = -1; goto exit_error_bundle; } DisposeHandle(raw_data); } } } f = pack_fopen(bundle_icns, F_WRITE); if (!f) { fprintf(stderr, "Cannot create %s\n", bundle_icns); result = -1; goto exit_error_bundle; } pack_fclose(f); cf_url_ref = CFURLCreateWithBytes(kCFAllocatorDefault, (unsigned char *)bundle_icns, strlen(bundle_icns), 0, NULL); if (!cf_url_ref) { fprintf(stderr, "Cannot create %s\n", bundle_icns); result = -1; goto exit_error_bundle; } CFURLGetFSRef(cf_url_ref, &fs_ref); CFRelease(cf_url_ref); if ((FSGetCatalogInfo(&fs_ref, kFSCatInfoNone, NULL, NULL, &fs_spec, NULL)) || (WriteIconFile(icon_family, &fs_spec) != noErr)) { fprintf(stderr, "Cannot create %s\n", bundle_icns); result = -1; goto exit_error_bundle; } DisposeHandle((Handle)icon_family); } /* Setup Info.plist */ sprintf(bundle_plist, "%s/Info.plist", bundle_contents_dir); f = pack_fopen(bundle_plist, F_WRITE); if (!f) { fprintf(stderr, "Cannot create %s\n", bundle_plist); result = -1; goto exit_error_bundle; } sprintf(buffer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" "<plist version=\"1.0\">\n" "<dict>\n" "\t<key>CFBundleExecutable</key>\n" "\t<string>%s</string>\n" "\t<key>CFBundleInfoDictionaryVersion</key>\n" "\t<string>6.0</string>\n" "\t<key>CFBundlePackageType</key>\n" "\t<string>APPL</string>\n" "\t<key>CFBundleSignature</key>\n" "\t<string>%s</string>\n" "\t<key>CFBundleVersion</key>\n" "\t<string>%s</string>\n" "\t<key>CFBundleDocumentTypes</key>\n" "\t<array>\n" "\t\t<dict>\n" "\t\t\t<key>CFBundleTypeExtensions</key>\n" "\t\t\t<array>\n" "\t\t\t\t<string>*</string>\n" "\t\t\t</array>\n" "\t\t\t<key>CFBundleTypeName</key>\n" "\t\t\t<string>NSStringPboardType</string>\n" "\t\t\t<key>CFBundleTypeOSTypes</key>\n" "\t\t\t<array>\n" "\t\t\t\t<string>****</string>\n" "\t\t\t</array>\n" "\t\t\t<key>CFBundleTypeRole</key>\n" "\t\t\t<string>Viewer</string>\n" "\t\t</dict>\n" "\t</array>\n", get_filename(bundle_exe), "????", (flags & F_GOT_VERSION) ? bundle_version : "1.0"); pack_fputs(buffer, f); if (flags & F_GOT_LONG_VERSION) { sprintf(buffer, "\t<key>CFBundleGetInfoString</key>\n" "\t<string>%s</string>\n", bundle_long_version); pack_fputs(buffer, f); } if (flags & F_ICONS_DEFINED) { sprintf(buffer, "\t<key>CFBundleIconFile</key>\n" "\t<string>%s</string>\n", get_filename(bundle_icns)); pack_fputs(buffer, f); } pack_fputs("</dict>\n</plist>\n", f); pack_fclose(f); /* Setup PkgInfo */ sprintf(bundle_pkginfo, "%s/PkgInfo", bundle_contents_dir); f = pack_fopen(bundle_pkginfo, F_WRITE); if (!f) { fprintf(stderr, "Cannot create %s\n", bundle_pkginfo); result = -1; goto exit_error_bundle; } pack_fputs("APPL????", f); pack_fclose(f); exit_error: if (buffer) free(buffer); for (i = 0; i < 4; i++) { if (icon_data[i].original) destroy_bitmap(icon_data[i].original); if (icon_data[i].workspace) destroy_bitmap(icon_data[i].workspace); if (icon_data[i].scaled) destroy_bitmap(icon_data[i].scaled); } return result; exit_error_bundle: sprintf(buffer, "%s/%s", bundle_contents_macos_dir, get_filename(bundle_exe)); unlink(buffer); unlink(bundle_plist); unlink(bundle_pkginfo); unlink(bundle_icns); rmdir(bundle_dir); rmdir(bundle_contents_dir); rmdir(bundle_contents_resources_dir); rmdir(bundle_contents_macos_dir); goto exit_error; }
URL_TYPE createURLByMakingDirectoryAtURLWithName(URL_TYPE parent, STRING_TYPE name) { CFURLRef newDirectory = NULL; CFAllocatorRef allocator = parent ? CFGetAllocator(parent) : name ? CFGetAllocator(name) : kCFAllocatorDefault; if (parent) parent = CFRetain(parent); else { char *cwdBytes = alloca(PATH_MAX); getcwd(cwdBytes, PATH_MAX); parent = CFURLCreateFromFileSystemRepresentation(allocator, (const unsigned char *)cwdBytes, strlen(cwdBytes), /*isDirectory*/ true); if (!name) { newDirectory = parent; goto end; } } if (!parent) NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: parent directory URL is NULL (please tell the Growl developers)\n"), parent); else { if (name) name = CFRetain(name); else { name = CFURLCopyLastPathComponent(parent); CFURLRef newParent = CFURLCreateCopyDeletingLastPathComponent(allocator, parent); CFRelease(parent); parent = newParent; } if (!name) NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: name of directory to create is NULL (please tell the Growl developers)\n"), parent); else { FSRef parentRef; if (!CFURLGetFSRef(parent, &parentRef)) NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: could not create FSRef for parent directory at %@ (please tell the Growl developers)\n"), parent); else { FSRef newDirectoryRef; struct HFSUniStr255 nameUnicode; CFRange range = { 0, MIN(CFStringGetLength(name), USHRT_MAX) }; CFStringGetCharacters(name, range, nameUnicode.unicode); nameUnicode.length = range.length; struct FSRefParam refPB = { .ref = &parentRef, .nameLength = nameUnicode.length, .name = nameUnicode.unicode, .whichInfo = kFSCatInfoNone, .catInfo = NULL, .textEncodingHint = kTextEncodingUnknown, .newRef = &newDirectoryRef, }; OSStatus err = PBCreateDirectoryUnicodeSync(&refPB); if (err == dupFNErr) { //dupFNErr == file (or folder) exists already. this is fine. err = PBMakeFSRefUnicodeSync(&refPB); } if (err == noErr) { NSLog(CFSTR("PBCreateDirectoryUnicodeSync or PBMakeFSRefUnicodeSync returned %li; calling CFURLCreateFromFSRef"), (long)err); //XXX newDirectory = CFURLCreateFromFSRef(allocator, &newDirectoryRef); NSLog(CFSTR("CFURLCreateFromFSRef returned %@"), newDirectory); //XXX } else NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: could not create directory '%@' in parent directory at %@: FSCreateDirectoryUnicode returned %li (please tell the Growl developers)"), name, parent, (long)err); } CFRelease(parent); } //if (name) CFRelease(name); } //if (parent) end: return newDirectory; } #ifndef COPYFORK_BUFSIZE # define COPYFORK_BUFSIZE 5242880U /*5 MiB*/ #endif static OSStatus copyFork(const struct HFSUniStr255 *forkName, const FSRef *srcFile, const FSRef *destDir, const struct HFSUniStr255 *destName, FSRef *outDestFile) { OSStatus err, closeErr; struct FSForkIOParam srcPB = { .ref = srcFile, .forkNameLength = forkName->length, .forkName = forkName->unicode, .permissions = fsRdPerm, }; unsigned char debuggingPathBuf[PATH_MAX] = ""; OSStatus debuggingPathErr; err = PBOpenForkSync(&srcPB); if (err != noErr) { debuggingPathErr = FSRefMakePath(srcFile, debuggingPathBuf, PATH_MAX); if (debuggingPathErr != noErr) snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr); NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBOpenForkSync (source: %s) returned %li"), debuggingPathBuf, (long)err); } else { FSRef destFile; /*the first thing to do is get the name of the destination file, if one * wasn't provided. *and while we're at it, we get the catalogue info as well. */ struct FSCatalogInfo catInfo; struct FSRefParam refPB = { .ref = srcFile, .whichInfo = kFSCatInfoGettableInfo & kFSCatInfoSettableInfo, .catInfo = &catInfo, .spec = NULL, .parentRef = NULL, .outName = destName ? NULL : (struct HFSUniStr255 *)(destName = alloca(sizeof(struct HFSUniStr255))), }; err = PBGetCatalogInfoSync(&refPB); if (err != noErr) { debuggingPathErr = FSRefMakePath(srcFile, debuggingPathBuf, PATH_MAX); if (debuggingPathErr != noErr) snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr); NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBGetCatalogInfoSync (source: %s) returned %li"), debuggingPathBuf, (long)err); } else { refPB.ref = destDir; refPB.nameLength = destName->length; refPB.name = destName->unicode; refPB.textEncodingHint = kTextEncodingUnknown; refPB.newRef = &destFile; const char *functionName = "PBMakeFSRefUnicodeSync"; //for error-reporting message err = PBMakeFSRefUnicodeSync(&refPB); if ((err != noErr) && (err != fnfErr)) { handleMakeFSRefError: debuggingPathErr = FSRefMakePath(destDir, debuggingPathBuf, PATH_MAX); if (debuggingPathErr != noErr) snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for destination directory: FSRefMakePath returned %li)", (long)debuggingPathErr); //get filename too CFStringRef debuggingFilename = CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, destName->unicode, destName->length, /*contentsDeallocator*/ kCFAllocatorNull); if (!debuggingFilename) debuggingFilename = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, "(could not get filename for destination file: CFStringCreateWithCharactersNoCopy returned NULL)", kCFStringEncodingASCII, /*contentsDeallocator*/ kCFAllocatorNull); NSLog(CFSTR("in copyFork in CFGrowlAdditions: %s (destination: %s/%@) returned %li"), functionName, debuggingPathBuf, debuggingFilename, (long)err); if (debuggingFilename) CFRelease(debuggingFilename); } else { //that file doesn't exist in that folder; create it. err = PBCreateFileUnicodeSync(&refPB); if (err == noErr) { /*make sure the Finder knows about the new file. *FNNotify returns a status code too, but this isn't an * essential step, so we just ignore it. */ FNNotify(destDir, kFNDirectoryModifiedMessage, kNilOptions); } else if (err == dupFNErr) { /*dupFNErr: the file already exists. *we can safely ignore this error. */ err = noErr; } else { functionName = "PBCreateFileUnicodeSync"; goto handleMakeFSRefError; } } } if (err == noErr) { if (outDestFile) memcpy(outDestFile, &destFile, sizeof(destFile)); struct FSForkIOParam destPB = { .ref = &destFile, .forkNameLength = forkName->length, .forkName = forkName->unicode, .permissions = fsWrPerm, }; err = PBOpenForkSync(&destPB); NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBOpenForkSync (dest) returned %li"), (long)err); if (err != noErr) { debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX); if (debuggingPathErr != noErr) snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for dest file: FSRefMakePath returned %li)", (long)debuggingPathErr); NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBOpenForkSync (destination: %s) returned %li"), debuggingPathBuf, (long)err); } else { void *buf = malloc(COPYFORK_BUFSIZE); if (buf) { srcPB.buffer = destPB.buffer = buf; srcPB.requestCount = COPYFORK_BUFSIZE; while (err == noErr) { err = PBReadForkSync(&srcPB); if (err == eofErr) { err = noErr; if (srcPB.actualCount == 0) break; } if (err != noErr) { debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX); if (debuggingPathErr != noErr) snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr); NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBReadForkSync (source: %s) returned %li"), debuggingPathBuf, (long)err); } else { destPB.requestCount = srcPB.actualCount; err = PBWriteForkSync(&destPB); if (err != noErr) { debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX); if (debuggingPathErr != noErr) snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for dest file: FSRefMakePath returned %li)", (long)debuggingPathErr); NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBWriteForkSync (destination: %s) returned %li"), debuggingPathBuf, (long)err); } } } free(buf); } closeErr = PBCloseForkSync(&destPB); if (closeErr != noErr) { debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX); if (debuggingPathErr != noErr) snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for dest file: FSRefMakePath returned %li)", (long)debuggingPathErr); NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBCloseForkSync (destination: %s) returned %li"), debuggingPathBuf, (long)err); } if (err == noErr) err = closeErr; } } closeErr = PBCloseForkSync(&srcPB); if (closeErr != noErr) { debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX); if (debuggingPathErr != noErr) snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr); NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBCloseForkSync (source: %s) returned %li"), debuggingPathBuf, (long)err); } if (err == noErr) err = closeErr; } return err; } static OSStatus GrowlCopyObjectSync(const FSRef *fileRef, const FSRef *destRef, FSRef *destFileRef) { OSStatus err; struct HFSUniStr255 forkName; struct FSForkIOParam forkPB = { .ref = fileRef, .forkIterator = { .initialize = 0L }, .outForkName = &forkName, }; do { err = PBIterateForksSync(&forkPB); NSLog(CFSTR("PBIterateForksSync returned %li"), (long)err); if (err != noErr) { if (err != errFSNoMoreItems) NSLog(CFSTR("in GrowlCopyObjectSync in CFGrowlAdditions: PBIterateForksSync returned %li"), (long)err); } else { err = copyFork(&forkName, fileRef, destRef, /*destName*/ NULL, /*outDestFile*/ destFileRef); //copyFork prints its own error messages } } while (err == noErr); if (err == errFSNoMoreItems) err = noErr; return err; } CFURLRef createURLByCopyingFileFromURLToDirectoryURL(CFURLRef file, CFURLRef dest) { CFURLRef destFileURL = NULL; FSRef fileRef, destRef, destFileRef; Boolean gotFileRef = CFURLGetFSRef(file, &fileRef); Boolean gotDestRef = CFURLGetFSRef(dest, &destRef); if (!gotFileRef) NSLog(CFSTR("in createURLByCopyingFileFromURLToDirectoryURL in CFGrowlAdditions: CFURLGetFSRef failed with source URL %@"), file); else if (!gotDestRef) NSLog(CFSTR("in createURLByCopyingFileFromURLToDirectoryURL in CFGrowlAdditions: CFURLGetFSRef failed with destination URL %@"), dest); else { OSStatus err; /* * 10.2 has a problem with weak symbols in frameworks so we use * MAC_OS_X_VERSION_MIN_REQUIRED >= 10.3. */ #if defined(NSAppKitVersionNumber10_3) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3 if (FSCopyObjectSync) { err = FSCopyObjectSync(&fileRef, &destRef, /*destName*/ NULL, &destFileRef, kFSFileOperationOverwrite); } else { #endif err = GrowlCopyObjectSync(&fileRef, &destRef, &destFileRef); #if defined(NSAppKitVersionNumber10_3) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3 } #endif if (err == noErr) destFileURL = CFURLCreateFromFSRef(kCFAllocatorDefault, &destFileRef); else NSLog(CFSTR("in createURLByCopyingFileFromURLToDirectoryURL in CFGrowlAdditions: CopyObjectSync returned %li for source URL %@"), (long)err, file); } return destFileURL; }
void osx_launch_special_handling(MCAP_CMD_S *mc_cmd, char *image_file) { CFStringRef str_ref = NULL; CFURLRef url_ref = NULL; LSLaunchFSRefSpec launch_spec; FSRef app_ref, file_ref; static EXEC_EVENT_DATA_S event_data; install_app_launch_cb((void *)&event_data); if((str_ref = CFStringCreateWithCString(NULL, mc_cmd->command, kCFStringEncodingASCII)) == NULL) return; if((url_ref = CFURLCreateWithString(NULL, str_ref, NULL)) == NULL) return; if(CFURLGetFSRef(url_ref, &app_ref) == false) return; if(FSPathMakeRef((unsigned char *)image_file, &file_ref, NULL) != noErr) return; launch_spec.appRef = &app_ref; launch_spec.numDocs = 1; launch_spec.itemRefs = &file_ref; launch_spec.passThruParams = NULL; launch_spec.launchFlags = kLSLaunchDontAddToRecents | kLSLaunchNoParams | kLSLaunchAsync | kLSLaunchNewInstance; /* would want to use this if we ever did true event handling */ launch_spec.asyncRefCon = 0; if(LSOpenFromRefSpec( &launch_spec, NULL) == noErr){ /* * Here's the strategy: we want to be able to just launch * the app and then just delete the temp file, but that * doesn't work because the called app needs the temp file * at least until it's finished loading. Being that there's * no way to tell when the app has finished loading, we wait * until the program has exited, which is the safest thing to * do and is what we do for windows. Since we haven't totally * embraced event handling at this point, we must do the waiting * synchronously. We allow for a keystroke to stop waiting, and * just delete the temp file. * Ideally, we would launch the app, and keep running, checking * the events until the process terminates, and then delete the * temp file. In this method, we would delete the temp file * at close time if the app was still running. */ int ch; OSStatus rne_rv; EventTargetRef target; EventRef out_event; EventTypeSpec event_types[2] = { {kEventClassApplication, kEventAppTerminated}, {kEventClassApplication, kEventAppLaunchNotification}}; q_status_message(SM_ORDER, 0, 4, "Waiting for program to finish, or press a key to stop waiting..."); flush_status_messages(1); target = GetEventDispatcherTarget(); event_data.done = 0; event_data.set_pid = 0; while(!event_data.done){ if((rne_rv = ReceiveNextEvent(2, event_types, 1, true, &out_event)) == noErr){ SendEventToEventTarget(out_event, target); ReleaseEvent(out_event); } else if(rne_rv == eventLoopTimedOutErr){ ch = read_char(1); if(ch) event_data.done = 1; } else if(rne_rv == eventLoopQuitErr) event_data.done = 1; } our_unlink(image_file); } q_status_message(SM_ORDER, 0, 4, "VIEWER command completed"); }
/***************************************************** * * MPWindowEventHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData ) * * Purpose: Window event handling routine * * Returns: OSStatus - eventNotHandledErr to allow other EventHandlers to run */ static pascal OSStatus MPWindowEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData ) { #pragma unused ( inCallRef, inUserData ) LongDateRec lDate; LongDateTime lSecs; unsigned long secs; ControlRef dateControl; WindowRef window; struct kevent kev; HICommand command; FSRef fsRef; CFURLRef urlRef = NULL; CFURLRef fullUrlRef = NULL; OSStatus err = eventNotHandledErr; UInt32 eventKind = GetEventKind( inEvent ); UInt32 eventClass = GetEventClass( inEvent ); switch ( eventClass ) { case kEventClassMP: if ( eventKind == kEventKQueue ) { // When we receive the kEventKQueue event, we update the date control associated with the path we are watching. GetEventParameter( inEvent, kEventParamDirectObject, typeKEvent, NULL, sizeof(struct kevent), NULL, &kev ); GetEventParameter( inEvent, kEventParamControlRef, typeControlRef, NULL, sizeof(ControlRef), NULL, &dateControl ); GetDateTime( &secs ); lSecs = secs; LongSecondsToDate( &lSecs, &lDate ); (void) SetControlData( dateControl, 0, kControlClockLongDateTag, sizeof(lDate), &lDate ); Draw1Control( dateControl ); PrintKEvent( GetControlOwner( dateControl ) , &kev ); // Display the kevent information } break; case kEventClassWindow: if ( eventKind == kEventWindowClose ) { GetEventParameter( inEvent, kEventParamDirectObject, typeWindowRef, NULL, sizeof(WindowRef), NULL, &window ); ((MyMPTaskInfo*)GetWRefCon( window ))->done = true; // Flag the thread to terminate (thread checks at least every 30 seconds in this sample) } break; case kEventClassCommand: GetEventParameter( inEvent, kEventParamDirectObject, typeHICommand, NULL, sizeof(HICommand), NULL, &command ); if ( eventKind == kEventCommandProcess ) { if ( command.commandID == 'Help' ) // Our 'Help' command, just have LaunchServices open the "kqueue.pdf" file within our bundle. { urlRef = CFBundleCopyResourcesDirectoryURL( CFBundleGetMainBundle() ); fullUrlRef = CFURLCreateCopyAppendingPathComponent( NULL, urlRef, CFSTR("kqueue.pdf"), false ); CFURLGetFSRef( fullUrlRef, &fsRef ); (void) LSOpenFSRef( &fsRef, NULL ); // Open the file if ( urlRef != NULL ) CFRelease( urlRef ); if ( urlRef != NULL ) CFRelease( fullUrlRef ); } } break; } return( err ); }
static void AddFolderIcon (FSRef *fref, const char *folderName) { OSStatus err; FSCatalogInfo fcat, icat; FSRef bref, iref; CFStringRef str; CFURLRef url; IconFamilyHandle family; IconRef icon; HFSUniStr255 fork; Boolean r; SInt16 resf; char name[64]; UniChar iconName[5] = { 'I', 'c', 'o', 'n', '\r' }; strcpy(name, "folder_"); strcat(name, folderName); str = CFStringCreateWithCString(kCFAllocatorDefault, name, CFStringGetSystemEncoding()); if (str) { url = CFBundleCopyResourceURL(CFBundleGetMainBundle(), str, CFSTR("icns"), NULL); if (url) { r = CFURLGetFSRef(url, &bref); if (r) { err = RegisterIconRefFromFSRef('~9X~', 'TEMP', &bref, &icon); if (err == noErr) { err = FSGetResourceForkName(&fork); if (err == noErr) { err = FSCreateResourceFile(fref, 5, iconName, kFSCatInfoNone, NULL, fork.length, fork.unicode, &iref, NULL); if (err == noErr) { err = FSOpenResourceFile(&iref, fork.length, fork.unicode, fsWrPerm, &resf); if (err == noErr) { err = IconRefToIconFamily(icon, kSelectorAllAvailableData, &family); if (err == noErr) { AddResource((Handle) family, 'icns', -16455, "\p"); WriteResource((Handle) family); ReleaseResource((Handle) family); err = FSGetCatalogInfo(&iref, kFSCatInfoFinderInfo, &icat, NULL, NULL, NULL); ((FileInfo *) &icat.finderInfo)->finderFlags |= kIsInvisible; ((FileInfo *) &icat.finderInfo)->fileCreator = 'MACS'; ((FileInfo *) &icat.finderInfo)->fileType = 'icon'; err = FSSetCatalogInfo(&iref, kFSCatInfoFinderInfo, &icat); err = FSGetCatalogInfo(fref, kFSCatInfoFinderInfo, &fcat, NULL, NULL, NULL); ((FolderInfo *) &fcat.finderInfo)->finderFlags |= kHasCustomIcon; ((FolderInfo *) &fcat.finderInfo)->finderFlags &= ~kHasBeenInited; err = FSSetCatalogInfo(fref, kFSCatInfoFinderInfo, &fcat); } CloseResFile(resf); } } }
void CheckSaveFolder (FSRef *cartRef) { OSStatus err; Boolean r; FSCatalogInfo finfo; FSVolumeInfo vinfo; FSRef ref; CFURLRef burl, purl; char s[PATH_MAX + 1]; switch (saveInROMFolder) { case 0: // Snes9x folder burl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); purl = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, burl); r = CFURLGetFSRef(purl, &ref); CFRelease(purl); CFRelease(burl); break; case 1: // ROM folder err = FSGetCatalogInfo(cartRef, kFSCatInfoNone, NULL, NULL, NULL, &ref); break; case 2: // Application Support folder return; case 4: // Custom folder if (saveFolderPath == NULL) { saveInROMFolder = 2; return; } r = CFStringGetCString(saveFolderPath, s, PATH_MAX, kCFStringEncodingUTF8); err = FSPathMakeRef((unsigned char *) s, &ref, NULL); if (err) { AppearanceAlert(kAlertCautionAlert, kS9xMacAlertFolderNotFound, kS9xMacAlertFolderNotFoundHint); saveInROMFolder = 2; return; } break; } err = FSGetCatalogInfo(&ref, kFSCatInfoUserPrivs | kFSCatInfoVolume, &finfo, NULL, NULL, NULL); if (err == noErr) { if (finfo.userPrivileges & kioACUserNoMakeChangesMask) { AppearanceAlert(kAlertCautionAlert, kS9xMacAlertFolderFailToCreate, kS9xMacAlertFolderFailToCreateHint); saveInROMFolder = 2; return; } err = FSGetVolumeInfo(finfo.volume, 0, NULL, kFSVolInfoFlags, &vinfo, NULL, NULL); if (err == noErr) { if ((vinfo.flags & kFSVolFlagHardwareLockedMask) || (vinfo.flags & kFSVolFlagSoftwareLockedMask)) { AppearanceAlert(kAlertCautionAlert, kS9xMacAlertFolderFailToCreate, kS9xMacAlertFolderFailToCreateHint); saveInROMFolder = 2; return; } } } if (err) saveInROMFolder = 2; }
//Taken from OS X's Kerberos source code file FSpUtils.c, as found ot: // http://www.opensource.apple.com/source/Kerberos/Kerberos-47/KerberosFramework/Common/Sources/FSpUtils.c //Note that the URL might change. static OSStatus CFURLToFSSpec (CFURLRef pathURL, FSSpec *outSpec) { OSStatus err = noErr; FSRef ref; FSCatalogInfo info; CFStringRef pathString = NULL; CFURLRef parentURL = NULL; CFStringRef nameString = NULL; // First, try to create an FSRef for the full path if (err == noErr) { if (CFURLGetFSRef(pathURL, &ref)) { err = FSIsFSRefValid(&ref) ? noErr : fnfErr; } else { err = fnfErr; } } if (err == noErr) { // It's a directory or a file that exists; convert directly into an FSSpec: err = FSGetCatalogInfo(&ref, kFSCatInfoNone, NULL, NULL, outSpec, NULL); } else { Str255 fileName; // The suck case. The file doesn't exist. err = noErr; // Get a CFString for the path if (err == noErr) { pathString = CFURLCopyFileSystemPath(pathURL, kCFURLPOSIXPathStyle); if (pathString == NULL) err = memFullErr; } // Get a CFURL for the parent if (err == noErr) { parentURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, pathURL); if (parentURL == NULL) err = memFullErr; } // Build an FSRef for the parent directory, which must be valid to make an FSSpec if (err == noErr) { Boolean converted = CFURLGetFSRef(parentURL, &ref); if (!converted) err = fnfErr; } // Get the node ID of the parent directory if (err == noErr) err = FSGetCatalogInfo(&ref, kFSCatInfoNodeFlags|kFSCatInfoNodeID|kFSCatInfoVolume, &info, NULL, outSpec, NULL); // Get a CFString for the file name if (err == noErr) { nameString = CFURLCopyLastPathComponent(pathURL); if (nameString == NULL) err = memFullErr; } // Copy the string into the FSSpec if (err == noErr) { Boolean converted = CFStringGetPascalString(pathString, fileName, sizeof(fileName), kCFStringEncodingMacRoman); if (!converted) converted = CFStringGetPascalString(pathString, fileName, sizeof(fileName), CFStringGetSystemEncoding()); if (!converted) err = fnfErr; } // Set the node ID in the FSSpec if (err == noErr) err = FSMakeFSSpec(info.volume, info.nodeID, fileName, outSpec); } // Free allocated memory if (pathString != NULL) CFRelease(pathString); if (parentURL != NULL) CFRelease(parentURL); if (nameString != NULL) CFRelease(nameString); return err; }
/** * Starts playing a new song. * * @param filename Path to a MIDI file. */ void MusicDriver_Cocoa::PlaySong(const char *filename) { DEBUG(driver, 2, "cocoa_m: trying to play '%s'", filename); this->StopSong(); if (_sequence != NULL) { DisposeMusicSequence(_sequence); _sequence = NULL; } if (NewMusicSequence(&_sequence) != noErr) { DEBUG(driver, 0, "cocoa_m: Failed to create music sequence"); return; } const char *os_file = OTTD2FS(filename); CFURLRef url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8*)os_file, strlen(os_file), false); #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5) if (MacOSVersionIsAtLeast(10, 5, 0)) { if (MusicSequenceFileLoad(_sequence, url, 0, 0) != noErr) { DEBUG(driver, 0, "cocoa_m: Failed to load MIDI file"); CFRelease(url); return; } } else #endif { #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) FSRef ref_file; if (!CFURLGetFSRef(url, &ref_file)) { DEBUG(driver, 0, "cocoa_m: Failed to make FSRef"); CFRelease(url); return; } if (MusicSequenceLoadSMFWithFlags(_sequence, &ref_file, 0) != noErr) { DEBUG(driver, 0, "cocoa_m: Failed to load MIDI file old style"); CFRelease(url); return; } #endif } CFRelease(url); /* Construct audio graph */ AUGraph graph = NULL; MusicSequenceGetAUGraph(_sequence, &graph); AUGraphOpen(graph); if (AUGraphInitialize(graph) != noErr) { DEBUG(driver, 0, "cocoa_m: Failed to initialize AU graph"); return; } /* Figure out sequence length */ UInt32 num_tracks; MusicSequenceGetTrackCount(_sequence, &num_tracks); _seq_length = 0; for (UInt32 i = 0; i < num_tracks; i++) { MusicTrack track = NULL; MusicTimeStamp track_length = 0; UInt32 prop_size = sizeof(MusicTimeStamp); MusicSequenceGetIndTrack(_sequence, i, &track); MusicTrackGetProperty(track, kSequenceTrackProperty_TrackLength, &track_length, &prop_size); if (track_length > _seq_length) _seq_length = track_length; } /* Add 8 beats for reverb/long note release */ _seq_length += 8; DoSetVolume(); MusicPlayerSetSequence(_player, _sequence); MusicPlayerPreroll(_player); if (MusicPlayerStart(_player) != noErr) return; _playing = true; DEBUG(driver, 3, "cocoa_m: playing '%s'", filename); }
long platformLoadSoundFile (string theFilename) { #ifdef QuickTimeInstalled short myRefNum; OSStatus err = noErr; Movie theMovie; FSSpec theSoundFile; #ifdef __APPLE__ CFURLRef musicURL; FSRef musicfsRef; #endif // get the full path to the sound file string fileLocation; fileLocation = pathToResourceDirectory() + theFilename; #ifdef __APPLE__ // create a URL to the file from the C string musicURL = CFURLCreateWithBytes (kCFAllocatorDefault, (UInt8 *)fileLocation.c_str(), fileLocation.length(), kCFStringEncodingASCII, NULL); if (musicURL == NULL) { cout << "error getting URL for sound file " << fileLocation << " (sound file may not exist)"; return 0L; } // get a FSRef from the URL if (!CFURLGetFSRef(musicURL, &musicfsRef)) { cout << "error getting FSRef for sound file " << fileLocation << " (sound file may not exist)"; CFRelease(musicURL); return 0L; } // get the FSSpec from the FSRef if (FSGetCatalogInfo (&musicfsRef, kFSCatInfoNone, NULL, NULL, &theSoundFile, NULL)) { cout << "error getting FSSpec for sound file " << fileLocation << " (sound file may not exist)"; CFRelease(musicURL); return 0L; } // release the URL (not needed any more) CFRelease(musicURL); #endif #ifdef _WIN32 // get an FSSpec from the pathname if (NativePathNameToFSSpec ((char *)fileLocation.c_str(), &theSoundFile, 0)) { cout << "error getting FSSpec for sound file " << fileLocation << " (sound file may not exist)" << endl; return 0L; } #endif // tell QuickTime to open the sound file err = OpenMovieFile(&theSoundFile, &myRefNum, fsRdPerm); if (err) { cout << "OpenMovieFile returned " << (long)err << endl; return 0L; } else { // tell QuickTime to imagine that this is a movie NewMovieFromFile(&theMovie, myRefNum, NULL, (StringPtr)NULL, newMovieActive, NULL); if (myRefNum != 0) CloseMovieFile(myRefNum); } // return the reference to the sound return (long)theMovie; #endif // QuickTimeInstalled }
CoreAudioReadStream::CoreAudioReadStream(string path) : m_path(path), m_d(new D) { m_channelCount = 0; m_sampleRate = 0; if (!QFile(m_path).exists()) { throw FileNotFound(m_path); } QByteArray ba = m_path.toLocal8Bit(); CFURLRef url = CFURLCreateFromFileSystemRepresentation (kCFAllocatorDefault, (const UInt8 *)ba.data(), (CFIndex)ba.length(), false); //!!! how do we find out if the file open fails because of DRM protection? #if (MACOSX_DEPLOYMENT_TARGET <= 1040 && MAC_OS_X_VERSION_MIN_REQUIRED <= 1040) FSRef fsref; if (!CFURLGetFSRef(url, &fsref)) { // returns Boolean, not error code m_error = "CoreAudioReadStream: Error looking up FS ref (file not found?)"; throw FileReadFailed(m_path); } m_d->err = ExtAudioFileOpen(&fsref, &m_d->file); #else m_d->err = ExtAudioFileOpenURL(url, &m_d->file); #endif CFRelease(url); if (m_d->err) { m_error = "CoreAudioReadStream: Error opening file: code " + codestr(m_d->err); throw InvalidFileFormat(path, "failed to open audio file"); } if (!m_d->file) { m_error = "CoreAudioReadStream: Failed to open file, but no error reported!"; throw InvalidFileFormat(path, "failed to open audio file"); } UInt32 propsize = sizeof(AudioStreamBasicDescription); m_d->err = ExtAudioFileGetProperty (m_d->file, kExtAudioFileProperty_FileDataFormat, &propsize, &m_d->asbd); if (m_d->err) { m_error = "CoreAudioReadStream: Error in getting basic description: code " + codestr(m_d->err); ExtAudioFileDispose(m_d->file); throw FileOperationFailed(m_path, "get basic description", codestr(m_d->err)); } m_channelCount = m_d->asbd.mChannelsPerFrame; m_sampleRate = m_d->asbd.mSampleRate; cerr << "CoreAudioReadStream: " << m_channelCount << " channels, " << m_sampleRate << " Hz" << std::endl; m_d->asbd.mSampleRate = getSampleRate(); m_d->asbd.mFormatID = kAudioFormatLinearPCM; m_d->asbd.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked | kAudioFormatFlagsNativeEndian; m_d->asbd.mBitsPerChannel = sizeof(float) * 8; m_d->asbd.mBytesPerFrame = sizeof(float) * m_channelCount; m_d->asbd.mBytesPerPacket = sizeof(float) * m_channelCount; m_d->asbd.mFramesPerPacket = 1; m_d->asbd.mReserved = 0; m_d->err = ExtAudioFileSetProperty (m_d->file, kExtAudioFileProperty_ClientDataFormat, propsize, &m_d->asbd); if (m_d->err) { m_error = "CoreAudioReadStream: Error in setting client format: code " + codestr(m_d->err); throw FileOperationFailed(m_path, "set client format", codestr(m_d->err)); } m_d->buffer.mNumberBuffers = 1; m_d->buffer.mBuffers[0].mNumberChannels = m_channelCount; m_d->buffer.mBuffers[0].mDataByteSize = 0; m_d->buffer.mBuffers[0].mData = 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; }
GLuint platformLoadTextureFile(string theFilename, bool generateMipmaps, int *width, int *height) { #ifdef QuickTimeInstalled GLuint textureName; // the "name" by which OpenGL knows the texture unsigned char *pImageBuffer; // the buffer that contains the image data GWorldPtr pGWorld; // a gworld to load the image into int imageDepth; FSSpec fsspecImage; // FSSpec of the image to load #ifdef __APPLE__ CFURLRef imageURL; FSRef imagefsRef; #endif OSStatus err = noErr; // err return value long rowStride; // length, in bytes, of a pixel row in the image GraphicsImportComponent giComp; // component for importing image MatrixRecord matrix; Rect rectImage; // rectangle of source image PixMapHandle hPixMap; // handle to image pix map ImageDescriptionHandle hImageDesc; // handle to image description used to get image depth long imageWidth; long imageHeight; float imageAspect; long textureWidth; long textureHeight; // get the full path to the texture file string fileLocation; fileLocation = pathToResourceDirectory() + theFilename; #ifdef __APPLE__ // create a URL to the file from the C string imageURL = CFURLCreateWithBytes (kCFAllocatorDefault, (UInt8 *)fileLocation.c_str(), fileLocation.length(), kCFStringEncodingASCII, NULL); if (imageURL == NULL) { cout << "error getting URL for image file (image file may not exist): " << theFilename << endl; return 0; } // get a FSRef from the URL if (!CFURLGetFSRef(imageURL, &imagefsRef)) { cout << "error getting FSRef for image file:: " << theFilename << endl; CFRelease(imageURL); return 0; } // get the FSSpec from the FSRef if (FSGetCatalogInfo (&imagefsRef, kFSCatInfoNone, NULL, NULL, &fsspecImage, NULL)) { cout << "error getting FSSpec for image file: " << theFilename << endl; CFRelease(imageURL); return 0; } // release the URL (not needed any more) CFRelease(imageURL); #endif #ifdef _WIN32 // get an FSSpec from the pathname if (NativePathNameToFSSpec ((char *)fileLocation.c_str(), &fsspecImage, kErrorIfFileNotFound)) { cout << "error getting FSSpec for image file: " << fileLocation << endl; return 0; } #endif // save the onscreen graphics port GDHandle origDevice; CGrafPtr origPort; GetGWorld (&origPort, &origDevice); // get an importer for the file err = GetGraphicsImporterForFileWithFlags (&fsspecImage, &giComp, kDontUseValidateToFindGraphicsImporter); if (err != noErr) return 0; // get the image bounds err = GraphicsImportGetNaturalBounds (giComp, &rectImage); if (err != noErr) return 0; // create a handle for the image description and lock it hImageDesc = (ImageDescriptionHandle) NewHandle (sizeof (ImageDescriptionHandle)); HLock ((Handle) hImageDesc); // retrieve the image description err = GraphicsImportGetImageDescription (giComp, &hImageDesc); if (err != noErr) return 0; // find width and height imageWidth = (int) (rectImage.right - rectImage.left); imageHeight = (int) (rectImage.bottom - rectImage.top); // now calculate the aspect ratio (width/height), used to restore image correctly imageAspect = ((float) imageWidth) / ((float) imageHeight); // get the image's pixel depth imageDepth = (**hImageDesc).depth; // find nearest acceptable texture size (width and height) for the image textureWidth = GetTextureDimFromImageDim (imageWidth); textureHeight = GetTextureDimFromImageDim (imageHeight); // pass the optimised (and scaled) size back out to the caller *width = textureWidth; *height = textureHeight; // set texture rectangle for creation of GWorld #ifdef __APPLE__ SetRect (&rectImage, 0, 0, (int) textureWidth, (int) textureHeight); #endif #ifdef _WIN32 MacSetRect (&rectImage, 0, 0, (int) textureWidth, (int) textureHeight); #endif // set stride in bytes width of image * 4 bytes per pixel rowStride = textureWidth * 4; // build new buffer exact size of image (stride * height) pImageBuffer = (unsigned char *) NewPtr (rowStride * textureHeight); // check we got the buffer we wanted if (pImageBuffer == NULL) { // failed - release the component and return an error CloseComponent(giComp); return 0; } // create a new gworld using our unpadded buffer, setting the pixel type correctly for the expected image depth #ifdef __BIG_ENDIAN__ QTNewGWorldFromPtr (&(pGWorld), k32ARGBPixelFormat, &rectImage, NULL, NULL, 0, pImageBuffer, rowStride); #else QTNewGWorldFromPtr (&(pGWorld), k32RGBAPixelFormat, &rectImage, NULL, NULL, 0, pImageBuffer, rowStride); #endif // could we allocate the GWorld? if (pGWorld == NULL) { // failed - release the buffer, component and return an error DisposePtr ((Ptr) pImageBuffer); CloseComponent(giComp); return 0; } // build a transformation matrix to scale the image to the texture size // this also flips the image horizontally, so that texture coordinates map correctly float horizontalScale = (float) textureWidth / (float) imageWidth; float verticalScale = (float) textureHeight / (float) imageHeight; SetIdentityMatrix (&matrix); ScaleMatrix (&matrix, X2Fix(horizontalScale), X2Fix(-verticalScale), 0, 0); TranslateMatrix (&matrix, 0, X2Fix((float)textureHeight)); // set the matrix as the importer matrix err = GraphicsImportSetMatrix(giComp, &matrix); // set the destination of the importer component if (err == noErr) err = GraphicsImportSetGWorld (giComp, pGWorld, NULL); // ensure lossless decompression (if the CODEC supports this) if (err == noErr) err = GraphicsImportSetQuality(giComp, codecLosslessQuality); if (err != noErr) { // failed - release the GWorld, buffer, component and return an error DisposeGWorld (pGWorld); DisposePtr ((Ptr) pImageBuffer); CloseComponent(giComp); return 0; } // get the address of the GWorld's pixmap hPixMap = GetGWorldPixMap (pGWorld); // if everything looks good draw the image to the locked pixmap if ((hPixMap) && (LockPixels (hPixMap))) GraphicsImportDraw (giComp); else { // the pixmap doesn't exist, or we couldn't lock it // release the GWorld, buffer, component and return an error DisposeGWorld (pGWorld); DisposePtr ((Ptr) pImageBuffer); CloseComponent(giComp); return 0; } // for images without an alpha channel, initialise the alpha bytes since QuickTime won't if (imageDepth < 32) { #ifdef __BIG_ENDIAN__ for( unsigned char *p = pImageBuffer; p < pImageBuffer + (rowStride * textureHeight); p+=4) *p = 0xFF; #else for( unsigned char *p = pImageBuffer+3; p < pImageBuffer + (rowStride * textureHeight) +3; p+=4) *p = 0xFF; #endif } // unlock the pixmap UnlockPixels (hPixMap); // dump the component CloseComponent(giComp); // set image width in groups (pixels), accounts for border this ensures proper image alignment row to row glPixelStorei (GL_UNPACK_ROW_LENGTH, textureWidth); // generate a "name" for the texture glGenTextures (1, &textureName); // create the texture in OpenGL glBindTexture(GL_TEXTURE_2D, textureName); // tell OpenGL about the texture and have GLU build mipmaps #ifdef __BIG_ENDIAN__ glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, pImageBuffer); #else glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, pImageBuffer); #endif if (generateMipmaps) #ifdef __BIG_ENDIAN__ if (gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, textureWidth, textureHeight, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, pImageBuffer) != 0) #else if (gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, textureWidth, textureHeight, GL_RGBA, GL_UNSIGNED_BYTE, pImageBuffer) != 0) #endif // good time to check for errors? openGLCheckError(); // finished with the GWorld but not the image buffer (it's used by OpenGL as the "live" image buffer) DisposeGWorld (pGWorld); // restore the current graphics port we saved earlier SetGWorld(origPort, origDevice); // all done - return the texture name return textureName; #endif // QuickTimeInstalled }