Exemplo n.º 1
0
pascal	OSErr	FSpSetFInfoCompat(const FSSpec *spec,
                                  const FInfo *fndrInfo)
{
#if !__MACOSSEVENORLATER
    if ( !FSHasFSSpecCalls() && !QTHasFSSpecCalls() )
    {
        OSErr			result;
        HParamBlockRec	pb;

        pb.fileParam.ioVRefNum = spec->vRefNum;
        pb.fileParam.ioDirID = spec->parID;
        pb.fileParam.ioNamePtr = (StringPtr) &(spec->name);
        pb.fileParam.ioFVersNum = 0;
        pb.fileParam.ioFDirIndex = 0;
        result = PBHGetFInfoSync(&pb);
        if ( result == noErr )
        {
            pb.fileParam.ioFlFndrInfo = *fndrInfo;
            pb.fileParam.ioDirID = spec->parID;
            result = PBHSetFInfoSync(&pb);
        }
        return ( result );
    }
    else
#endif	/* !__MACOSSEVENORLATER */
    {
        return ( FSpSetFInfo(spec, fndrInfo) );
    }
}
Exemplo n.º 2
0
void fixmacfile(char *filename)
{
  FInfo  fndrinfo;
#ifdef OSX_CARBON
  FSSpec fileSpec;
  FSRef fileRef;

  FSPathMakeRef((unsigned char *)filename, &fileRef, NULL);
  FSGetCatalogInfo(&fileRef, kFSCatInfoNone, NULL, NULL, &fileSpec, NULL);
  FSpGetFInfo(&fileSpec, &fndrinfo);
  fndrinfo.fdType='TEXT';
  fndrinfo.fdCreator='MSWD';
  FSpSetFInfo(&fileSpec, &fndrinfo);

#else
  char filename1[FNMLNGTH];
  char filename2[FNMLNGTH];
  strcpy(filename1,filename);
  strcpy(filename2,filename);
  getfinfo(filename1,0,&fndrinfo);
  fndrinfo.fdType='TEXT';
  fndrinfo.fdCreator='MSWD';
  setfinfo(filename2,0,&fndrinfo);
#endif
}
Exemplo n.º 3
0
bool wxFileConfig::Flush(bool /* bCurrentOnly */)
{
  if ( LineListIsEmpty() || !m_pRootGroup->IsDirty() || !m_strLocalFile )
    return TRUE;

#ifdef __UNIX__
  // set the umask if needed
  mode_t umaskOld = 0;
  if ( m_umask != -1 )
  {
      umaskOld = umask((mode_t)m_umask);
  }
#endif // __UNIX__

  wxTempFile file(m_strLocalFile);

  if ( !file.IsOpened() ) {
    wxLogError(_("can't open user configuration file."));
    return FALSE;
  }

  // write all strings to file
  for ( LineList *p = m_linesHead; p != NULL; p = p->Next() ) {
    if ( !file.Write(p->Text() + wxTextFile::GetEOL()) ) {
      wxLogError(_("can't write user configuration file."));
      return FALSE;
    }
  }

  bool ret = file.Commit();

#if defined(__WXMAC__) && !defined(__UNIX__)
  if ( ret )
  {
  	FSSpec spec ;
  	
  	wxMacFilename2FSSpec( m_strLocalFile , &spec ) ;
  	FInfo finfo ;
  	if ( FSpGetFInfo( &spec , &finfo ) == noErr )
  	{
  		finfo.fdType = 'TEXT' ;
  		finfo.fdCreator = 'ttxt' ;
  		FSpSetFInfo( &spec , &finfo ) ;
  	}
  }
#endif // __WXMAC__ && !__UNIX__

#ifdef __UNIX__
  // restore the old umask if we changed it
  if ( m_umask != -1 )
  {
      (void)umask(umaskOld);
  }
#endif // __UNIX__

  return ret;
}
Exemplo n.º 4
0
static CWResult LinkHeaders(CWPluginContext context, XPIDLSettings& settings)
{
	// find out how many files there are to link.
	long fileCount = 0;
	CWResult err = CWGetProjectFileCount(context, &fileCount);
	if (err != cwNoErr || fileCount == 0)
		return err;

	// get the output directory.
	FSSpec outputDir;
	err = CWGetOutputFileDirectory(context, &outputDir);
	if (!CWSUCCESS(err))
		return err;
	
	// enumerate all of the output header files, and make aliases to them in
	// the output directory.
	for (long index = 0; (err == cwNoErr) && (index < fileCount); index++) {
		// get the name of each output file.
		CWFileSpec outputFile;
		err = CWGetStoredObjectFileSpec(context, index, &outputFile);
		if (err == cwNoErr) {
			FInfo info;
			err = FSpGetFInfo(&outputFile, &info);
			
			FSSpec aliasFile = { outputDir.vRefNum, outputDir.parID };
			BlockMoveData(outputFile.name, aliasFile.name, 1 + outputFile.name[0]);
			
			AliasHandle alias = NULL;
			if (NewAliasMinimal(&outputFile, &alias) == noErr) {
				// recreate the alias file from scratch.
				FSpDelete(&aliasFile);
				FSpCreateResFile(&aliasFile, info.fdCreator, info.fdType, smRoman);
				short refNum = FSpOpenResFile(&aliasFile, fsRdWrPerm);
				if (refNum != -1) {
					UseResFile(refNum);
					AddResource(Handle(alias), rAliasType, 0, aliasFile.name);
					ReleaseResource(Handle(alias));
					UpdateResFile(refNum);
					CloseResFile(refNum);
				}
				// finally, mark the newly created file as an alias file.
				FSpGetFInfo(&aliasFile, &info);
				info.fdFlags |= kIsAlias;
				FSpSetFInfo(&aliasFile, &info);
			}
		}
	}
	
	// create the target file in the output directory.
	BlockMoveData(settings.output, outputDir.name, 1 + settings.output[0]);
	FILE* outputFile = FSp_fopen(&outputDir, "w");
	if (outputFile != NULL) fclose(outputFile);

	return err;
}
int dir_SetMacFileTypeAndCreator(char *filename, int filenameSize, char *fType, char *fCreator) {
	/* Set the Macintosh type and creator of the given file. */
	/* Note: On other platforms, this is just a noop. */

    FSSpec spec;
    FInfo   finderInfo;
    
    if (getSpecAndFInfo(filename,filenameSize,&spec,&finderInfo) != noErr)
        return false;
       
	finderInfo.fdType = *((int *) fType);
	finderInfo.fdCreator = *((int *) fCreator);
	
    return FSpSetFInfo(&spec,&finderInfo) == noErr;
}
Exemplo n.º 6
0
/* close the output file, if opened with PDF_open_file();
 * close the output stream if opened 
 */
static void
pdf_close_file(PDF *p)
{
#if defined(MAC) && defined(__MWERKS__)
    FCBPBRec	fcbInfo;
    Str32	name;
    FInfo	fInfo;
    FSSpec	fSpec;
#endif

    if (p->fp == NULL)
	return;

#if defined(MAC) && defined(__MWERKS__)
/*  Contributed by Leonard Rosenthol:
 *  On the MacOS, files are not associated with applications by extensions.
 *  Instead, it uses a pair of values called the type & creator.
 *  This block of code sets those values for PDF files.
 */
    memset(&fcbInfo, 0, sizeof(FCBPBRec));
    fcbInfo.ioRefNum = (short) p->fp->handle;
    fcbInfo.ioNamePtr = name;
    if (!PBGetFCBInfoSync(&fcbInfo) &&
	FSMakeFSSpec(fcbInfo.ioFCBVRefNum, fcbInfo.ioFCBParID, name, &fSpec)
		== noErr) {
	    FSpGetFInfo(&fSpec, &fInfo);
	    fInfo.fdType = 'PDF ';
	    fInfo.fdCreator = 'CARO';
	    FSpSetFInfo(&fSpec, &fInfo);
	}
#endif

    /*
     * If filename is set, we started with PDF_open_file; therefore
     * we also close the file ourselves.
     */
    if (p->filename && p->writeproc) {
	if (strcmp(p->filename, "-"))
	    fclose(p->fp);
	p->free(p, p->filename);
    }

    /* mark fp as dead in case the error handler jumps in later */
    p->fp = NULL;
}
Exemplo n.º 7
0
boolean filesetfinderflag (ptrfilespec pfs, short flagnum, boolean flag) {

	OSErr ec;
	FInfo info;

	ec = FSpGetFInfo (pfs, &info);
	
	if (fileerror (pfs, ec))
		return (false);
	
	if (flag)
		info.fdFlags = setbit (info.fdFlags, flagnum);
	else
		info.fdFlags = clearbit (info.fdFlags, flagnum);
	
	ec = FSpSetFInfo (pfs, &info);	
	
	return (!fileerror (pfs, ec));
	} /*filesetfinderflag*/
Exemplo n.º 8
0
bool ExportPCM(AudacityProject *project,
               wxString format, bool stereo, wxString fName,
               bool selectionOnly, double t0, double t1)
{
    wxMessageBox("In process of being rewritten, sorry...");

#if 0

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

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

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


    // Use snd library to export file

    snd_node sndfile;
    snd_node sndbuffer;

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

    int err;
    long flags = 0;

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

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

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

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

    double t = t0;

    while (t < t1 && !cancelling) {

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

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

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

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

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

        sampleType *mixed = mixer->GetBuffer();

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

        snd_write(&sndfile, buffer, b2);

        t += deltat;

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

            wxString message;

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

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

        delete mixer;
        delete[]buffer;
    }

    snd_close(&sndfile);

#ifdef __WXMAC__

    FSSpec spec;

    wxMacFilename2FSSpec(fName, &spec);

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

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

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

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

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

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

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

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

        finfo.fdCreator = AUDACITY_CREATOR;

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

    if (progress)
        delete progress;

    return true;

#endif

    return false;

}
Exemplo n.º 9
0
/* create file with IPIcon */
OSErr MakeFileWithIPIcon(const FSSpec *theFile,const IPIconRec *ipIcon)
{
	OSErr		err;
	FInfo		fndrInfo;
	short		refNum;
	IconActionUPP	addIconUPP;
	MyIconResRec	newIcon;
	
	/* create a file */
	err=FSpGetFInfo(theFile,&fndrInfo);
	if (err==fnfErr)
		FSpCreateResFile(theFile,kResEditCreator,kResourceFileType,smSystemScript);
	if (err!=fnfErr && err!=noErr) return err;
	
	/* open the file */
	refNum=FSpOpenResFile(theFile,fsWrPerm);
	if (refNum < 0) /* could not open -> the file has no resource fork */
	{
		FSpCreateResFile(theFile,fndrInfo.fdCreator,fndrInfo.fdType,smSystemScript);
		refNum=FSpOpenResFile(theFile,fsWrPerm);
	}
	if (refNum < 0) /* could not open -> error */
		return refNum;
	
	UseResFile(refNum);
	
	/* information for icon */
	newIcon.resID=kCustomIconResource;
	GetIndString(newIcon.resName,141,2);
	newIcon.attrs=0;
	
	/* save icon family(separated icons) */
	if (ipIcon->iconSuite != NULL)
	{
		addIconUPP=NewIconActionUPP(AddIconToFile);
		err=ForEachIconDo(ipIcon->iconSuite,GetMySelector(),addIconUPP,&newIcon);
		DisposeIconActionUPP(addIconUPP);
	}
	
	/* save icns(single icon) */
	if (isIconServicesAvailable)
	{
		IconFamilyHandle	iconFamily;
		
		err=IPIconToIconFamily(ipIcon,&iconFamily);
		if (err==noErr)
		{
			SaveDataToResource(*iconFamily,GetHandleSize((Handle)iconFamily),
				kIconFamilyType,newIcon.resID,newIcon.resName,newIcon.attrs);
			DisposeHandle((Handle)iconFamily);
		}
	}
	else
		/* delete icns resource */
		DeleteIconFamilyResource();
	
	CloseResFile(refNum);
	UseResFile(gApplRefNum);
	
	/* set flag for custom icons */
	err=FSpGetFInfo(theFile,&fndrInfo);
	fndrInfo.fdFlags |= kHasCustomIcon;
	fndrInfo.fdFlags &= ~kHasBeenInited;
	err=FSpSetFInfo(theFile,&fndrInfo);
	
	FlushVol(0L,theFile->vRefNum);
	
	/* update file icon */
	UpdateFinderIcon(theFile);
	
	return err;
}
Exemplo n.º 10
0
void AudacityProject::Save(bool overwrite /* = true */ ,
                           bool fromSaveAs /* = false */ )
{
   if (!fromSaveAs && mDirManager.GetProjectName() == "") {
      SaveAs();
      return;
   }
   //
   // Always save a backup of the original project file
   //

   wxString safetyFileName = "";
   if (wxFileExists(mFileName)) {

#ifdef __WXGTK__
      safetyFileName = mFileName + "~";
#else
      safetyFileName = mFileName + ".bak";
#endif

      if (wxFileExists(safetyFileName))
         wxRemoveFile(safetyFileName);

      wxRename(mFileName, safetyFileName);
   }

   wxString project = mFileName;
   if (project.Len() > 4 && project.Mid(project.Len() - 4) == ".aup")
      project = project.Mid(0, project.Len() - 4);
   wxString projName = wxFileNameFromPath(project) + "_data";
   wxString projPath = wxPathOnly(project);

   // We are about to move files from the current directory to
   // the new directory.  We need to make sure files that belonged
   // to the last saved project don't get erased, so we "lock" them.
   // (Otherwise the new project would be fine, but the old one would
   // be empty of all of its files.)

   // Lock all blocks in all tracks of the last saved version
   if (mLastSavedTracks && !overwrite) {
      TrackListIterator iter(mLastSavedTracks);
      VTrack *t = iter.First();
      while (t) {
         if (t->GetKind() == VTrack::Wave)
            ((WaveTrack *) t)->Lock();
         t = iter.Next();
      }
   }   

   // This renames the project directory, and moves or copies
   // all of our block files over
   bool success = mDirManager.SetProject(projPath, projName, !overwrite);

   // Unlock all blocks in all tracks of the last saved version
   if (mLastSavedTracks && !overwrite) {
      TrackListIterator iter(mLastSavedTracks);
      VTrack *t = iter.First();
      while (t) {
         if (t->GetKind() == VTrack::Wave)
            ((WaveTrack *) t)->Unlock();
         t = iter.Next();
      }
   }   

   if (!success) {
      wxMessageBox(wxString::
                   Format
                   (_("Could not save project.  "
                      "Perhaps %s is not writeable,\n"
                      "or the disk is full."),
                    (const char *) project));

      if (safetyFileName)
         wxRename(safetyFileName, mFileName);

      return;
   }

   wxTextFile f(mFileName);
   f.Create();
   f.Open();
   if (!f.IsOpened()) {
      wxMessageBox(_("Couldn't write to file: ") + mFileName);

      if (safetyFileName)
         wxRename(safetyFileName, mFileName);

      return;
   }

   f.AddLine("AudacityProject");
   f.AddLine("Version");
   f.AddLine(AUDACITY_FILE_FORMAT_VERSION);
   f.AddLine("projName");
   f.AddLine(projName);
   f.AddLine("sel0");
   f.AddLine(wxString::Format("%g", mViewInfo.sel0));
   f.AddLine("sel1");
   f.AddLine(wxString::Format("%g", mViewInfo.sel1));
   f.AddLine("vpos");
   f.AddLine(wxString::Format("%d", mViewInfo.vpos));
   f.AddLine("h");
   f.AddLine(wxString::Format("%g", mViewInfo.h));
   f.AddLine("zoom");
   f.AddLine(wxString::Format("%g", mViewInfo.zoom));
   f.AddLine("rate");
   f.AddLine(wxString::Format("%g", mRate));

   f.AddLine("BeginTracks");

   mTracks->Save(&f, overwrite);

#ifdef __WXMAC__
   f.Write(wxTextFileType_Mac);
#else
   f.Write();
#endif
   f.Close();

#ifdef __WXMAC__
   FSSpec spec;

   wxMacFilename2FSSpec(mFileName, &spec);
   FInfo finfo;
   if (FSpGetFInfo(&spec, &finfo) == noErr) {
      finfo.fdType = AUDACITY_PROJECT_TYPE;
      finfo.fdCreator = AUDACITY_CREATOR;
      FSpSetFInfo(&spec, &finfo);
   }
#endif

   if (mLastSavedTracks) {
      mLastSavedTracks->Clear(true);
      delete mLastSavedTracks;
   }

   mLastSavedTracks = new TrackList();
   TrackListIterator iter(mTracks);
   VTrack *t = iter.First();
   while (t) {
      mLastSavedTracks->Add(t->Duplicate());
      t = iter.Next();
   }

   mStatus->SetField(wxString::Format(_("Saved %s"),
                                      (const char *) mFileName), 0);
}
Exemplo n.º 11
0
void AudacityProject::Save(bool overwrite /* = true */ ,
                           bool fromSaveAs /* = false */ )
{
   if (!fromSaveAs && mDirManager.GetProjectName() == "") {
      SaveAs();
      return;
   }
   //
   // Always save a backup of the original project file
   //

   wxString safetyFileName = "";
   if (wxFileExists(mFileName)) {

#ifdef __WXGTK__
      safetyFileName = mFileName + "~";
#else
      safetyFileName = mFileName + ".bak";
#endif

      if (wxFileExists(safetyFileName))
         wxRemoveFile(safetyFileName);

      wxRename(mFileName, safetyFileName);
   }

   wxString project = mFileName;
   if (project.Len() > 4 && project.Mid(project.Len() - 4) == ".aup")
      project = project.Mid(0, project.Len() - 4);
   wxString projName = wxFileNameFromPath(project) + "_data";
   wxString projPath = wxPathOnly(project);
   bool success = mDirManager.SetProject(projPath, projName, !overwrite);

   if (!success) {
      wxMessageBox(wxString::
                   Format
                   ("Could not save project because the directory %s could not be created.",
                    (const char *) project));

      if (safetyFileName)
         wxRename(safetyFileName, mFileName);

      return;
   }

   wxTextFile f(mFileName);
#ifdef __WXMAC__
   wxFile *temp = new wxFile();
   temp->Create(mFileName);
   delete temp;
#else
   f.Create();
#endif
   f.Open();
   if (!f.IsOpened()) {
      wxMessageBox("Couldn't write to " + mFileName);

      if (safetyFileName)
         wxRename(safetyFileName, mFileName);

      return;
   }

   f.AddLine("AudacityProject");
   f.AddLine("Version");
   f.AddLine(AUDACITY_FILE_FORMAT_VERSION);
   f.AddLine("projName");
   f.AddLine(projName);
   f.AddLine("sel0");
   f.AddLine(wxString::Format("%g", mViewInfo.sel0));
   f.AddLine("sel1");
   f.AddLine(wxString::Format("%g", mViewInfo.sel1));
   f.AddLine("vpos");
   f.AddLine(wxString::Format("%d", mViewInfo.vpos));
   f.AddLine("h");
   f.AddLine(wxString::Format("%g", mViewInfo.h));
   f.AddLine("zoom");
   f.AddLine(wxString::Format("%g", mViewInfo.zoom));
   f.AddLine("rate");
   f.AddLine(wxString::Format("%g", mRate));

   f.AddLine("BeginTracks");

   mTracks->Save(&f, overwrite);

#ifdef __WXMAC__
   f.Write(wxTextFileType_Mac);
#else
   f.Write();
#endif
   f.Close();

#ifdef __WXMAC__
   FSSpec spec;

   wxMacFilename2FSSpec(mFileName, &spec);
   FInfo finfo;
   if (FSpGetFInfo(&spec, &finfo) == noErr) {
      finfo.fdType = AUDACITY_PROJECT_TYPE;
      finfo.fdCreator = AUDACITY_CREATOR;
      FSpSetFInfo(&spec, &finfo);
   }
#endif

   if (mLastSavedTracks) {

      TrackListIterator iter(mLastSavedTracks);
      VTrack *t = iter.First();
      while (t) {
         if (t->GetKind() == VTrack::Wave && !overwrite)
            ((WaveTrack *) t)->DeleteButDontDereference();
         else
            delete t;
         t = iter.Next();
      }

      delete mLastSavedTracks;
   }

   mLastSavedTracks = new TrackList();
   TrackListIterator iter(mTracks);
   VTrack *t = iter.First();
   while (t) {
      mLastSavedTracks->Add(t->Duplicate());
      t = iter.Next();
   }

   mStatus->SetField(wxString::Format("Saved %s",
                                      (const char *) mFileName), 0);
}
Exemplo n.º 12
0
static OSStatus DoFSRefSave(const OurSaveDialogData *dialogDataP, 
                                    NavReplyRecord* reply, AEDesc *actualDescP)
{
    OSStatus 	err = noErr;
    FSRef 	fileRefParent;
	    
    if ((err = AEGetDescData( actualDescP, &fileRefParent, sizeof( FSRef ) )) == noErr )
    {
        // get the name data and its length:	
        HFSUniStr255	nameBuffer;
        UniCharCount 	sourceLength = 0;
        
        sourceLength = (UniCharCount)CFStringGetLength( reply->saveFileName );
        
        CFStringGetCharacters( reply->saveFileName, CFRangeMake( 0, sourceLength ), 
                                                        (UniChar*)&nameBuffer.unicode );
        
        if ( sourceLength > 0 )
        {	
            if ( reply->replacing )
            {
                // delete the file we are replacing:
                FSRef fileToDelete;
                if ((err = FSMakeFSRefUnicode( &fileRefParent, sourceLength, nameBuffer.unicode, 
                                    kTextEncodingUnicodeDefault, &fileToDelete )) == noErr )
                {
                    err = FSDeleteObject( &fileToDelete );
                    if ( err == fBsyErr ){
                        DoErrorAlert(fBsyErr, kMyDeleteErrorFormatStrKey);
                    }
                }
            }
                            
            if ( err == noErr )
            {
                // create the file based on Unicode, but we can write the file's data with an FSSpec:
                FSSpec newFileSpec;

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

  mFileName = filename;
  //Unless it has been changed, use the project rate
  if(!mOutRate) 
    mOutRate = mProject->GetRate();
  
  wxWindow    *parent = mProject;
  TrackList   *tracks = mProject->GetTracks();

  wxString     formatStr;
  SF_INFO      info;
  SNDFILE     *sf = NULL;
  int          err;

   formatStr = sf_header_name(mSoundFileFormat & SF_FORMAT_TYPEMASK);

   // Use libsndfile to export file

   info.samplerate = mOutRate;
   info.frames = (unsigned int)((m_t1 - m_t0)*(double)mOutRate + 0.5);
   info.channels = mChannels;
   info.format = mSoundFileFormat;
   info.sections = 1;
   info.seekable = 0;

   // If we can't export exactly the format they requested,
   // try the default format for that header type...
   if (!sf_format_check(&info))
      info.format = (info.format & SF_FORMAT_TYPEMASK);
   if (!sf_format_check(&info)) {
      wxMessageBox(_("Cannot export audio in this format."));
      return false;
   }

   sf = sf_open((const char *)mFileName, SFM_WRITE, &info);
   if (!sf) {
      wxMessageBox(wxString::Format(_("Cannot export audio to %s"),
                                    (const char *)mFileName));
      return false;
   }

   //Determine what format the track is currently in, to avoid
   //multiple conversions.
   sampleFormat format;
   if (sf_subtype_more_than_16_bits(info.format))
      format = floatSample;
   else
      format = int16Sample;

   int maxBlockLen = 44100 * 5;

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

   int numWaveTracks;
   WaveTrack **waveTracks;
   tracks->GetWaveTracks(mExportSelection, &numWaveTracks, &waveTracks);



  
   Mixer *mixer = new Mixer(numWaveTracks, waveTracks,
                            tracks->GetTimeTrack(),
                            m_t0, m_t1,
                            info.channels, maxBlockLen, true,
                            mInRate, format);

   while(!cancelling) {
      sampleCount numSamples = mixer->Process(maxBlockLen);

      if (numSamples == 0)
         break;
      
      samplePtr mixed = mixer->GetBuffer();

      if (format == int16Sample)
         sf_writef_short(sf, (short *)mixed, numSamples);
      else
         sf_writef_float(sf, (float *)mixed, numSamples);

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

         wxString message;

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

         progress =
             new wxProgressDialog(_("Export"),
                                  message,
                                  1000,
                                  parent,
                                  wxPD_CAN_ABORT |
                                  wxPD_REMAINING_TIME | wxPD_AUTO_HIDE);
      }
      if (progress) {
         int progressvalue = int (1000 * ((mixer->MixGetCurrentTime()-m_t0) /
                                          (m_t1-m_t0)));
         cancelling = !progress->Update(progressvalue);
      }
   }

   delete mixer;

   delete[] waveTracks;                            

   err = sf_close(sf);

   if (err) {
      char buffer[1000];
      sf_error_str(sf, buffer, 1000);
      wxMessageBox(wxString::Format
                   (_("Error (file may not have been written): %s"),
                    buffer));
   }

#ifdef __WXMAC__

   FSSpec spec;

   wxMacFilename2FSSpec(fName, &spec);

   FInfo finfo;
   if (FSpGetFInfo(&spec, &finfo) == noErr) {
      finfo.fdType = sf_header_mactype(mSoundFileFormat & SF_FORMAT_TYPEMASK);
      finfo.fdCreator = AUDACITY_CREATOR;

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

   if (progress)
      delete progress;

   return true;
}
Exemplo n.º 14
0
Arquivo: main.c Projeto: Aeon/osxutils
///////////////////////////////////////////////////////////////////
// Make sure file exists and we have privileges.  Then set the 
// file Finder comment.
///////////////////////////////////////////////////////////////////
static void SetFileLabel (char *path, short labelNum)
{
    OSErr		err = noErr;
    FSRef		fileRef;
    FSSpec		fileSpec;
    short       isFldr;
    short       currentLabel;
    FInfo       finderInfo;
    CInfoPBRec  infoRec;

	//see if the file in question exists and we can write it
	if (access(path, R_OK|W_OK|F_OK) == -1)
	{
		perror(path);
		return;
	}
	
	//get file reference from path
	err = FSPathMakeRef((char *)path, &fileRef, NULL);
	if (err != noErr)
	{
		fprintf(stderr, "FSPathMakeRef: Error %d for file %s\n", err, path);
		return;
	}

	//retrieve filespec from file ref
	err = FSGetCatalogInfo (&fileRef, NULL, NULL, NULL, &fileSpec, NULL);
	if (err != noErr)
	{
		fprintf(stderr, "FSGetCatalogInfo(): Error %d getting file spec for %s\n", err, path);
		return;
	}
        
    /* Check if we're dealing with a folder */
    isFldr = UnixIsFolder(path);
    if (isFldr == -1)/* an error occurred in stat */
    {
            perror(path);
            return;
    }
    
    ///////////////////////// IF SPECIFIED FILE IS A FOLDER /////////////////////////
	
    if (isFldr)
    {
        //Get HFS record
        FSpGetPBRec(&fileSpec, &infoRec);
        
        //get current label
        currentLabel = GetLabelNumber(infoRec.dirInfo.ioDrUsrWds.frFlags);
        
        //set new label into record
        SetLabelInFlags(&infoRec.dirInfo.ioDrUsrWds.frFlags, labelNum);
        
        //fill in the requisite fields
        infoRec.hFileInfo.ioNamePtr = (unsigned char *)fileSpec.name;
		infoRec.hFileInfo.ioVRefNum = fileSpec.vRefNum;
		infoRec.hFileInfo.ioDirID = fileSpec.parID;
        
        //set the record
        PBSetCatInfoSync(&infoRec);
    }
    
    ///////////////////////// IF SPECIFIED FILE IS A REGULAR FILE /////////////////////////
	
    else
    {
        /* get the finder info */
        err = FSpGetFInfo (&fileSpec, &finderInfo);
        if (err != noErr) 
        {
            if (!silentMode)
                fprintf(stderr, "FSpGetFInfo(): Error %d getting file Finder info from file spec for file %s", err, path);
        }
        
        //retrieve the label number of the file
        currentLabel = GetLabelNumber(finderInfo.fdFlags);
        
        //if it's already set with the desired label we return
        if (currentLabel == labelNum)
            return;
        
        //set the appropriate value in the flags field
        SetLabelInFlags(&finderInfo.fdFlags, labelNum);
        
        //apply the settings to the file
        err = FSpSetFInfo (&fileSpec, &finderInfo);
        if (err != noErr)
        {
            if (!silentMode)
                fprintf(stderr, "FSpSetFInfo(): Error %d setting Finder info for %s", err, path);
            return;
        }
    }
    
    //print output reporting the changes made
	if (!silentMode)
		printf("%s:\n\t%s --> %s\n", path, (char *)&labelNames[currentLabel], (char *)&labelNames[labelNum]);
    
    return;
}
Exemplo n.º 15
0
OSErr PAS_decodeMisc(PASEntry *entry, FSSpec *outFile, short inRefNum)
{
	OSErr 		err;	
	short		outRefNum;
	PASMiscInfo	info;
	SInt32		infoSize;
	FInfo		theFInfo;
		
	
	infoSize	=	sizeof(PASMiscInfo);
	
	err = SetFPos(inRefNum, fsFromStart, (*entry).entryOffset );
	if (err != noErr)	return err;

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

	if(infoSize != sizeof(PASMiscInfo))
	{
		return -1;
	}

	err = FSpOpenDF(outFile, fsRdWrPerm, &outRefNum);
	if (err != noErr)	return err;
	
	memset(&theFInfo, 0, sizeof(FInfo));   
		
	theFInfo.fdType		=	info.fileType;
	theFInfo.fdCreator	=	info.fileCreator;	
	theFInfo.fdFlags	=	info.fileFlags;
	
	err = FSpSetFInfo(outFile, &theFInfo);
	if (err != noErr)	return err;
		
	FSClose(outRefNum);
	
	if (info.fileHasResFork)
	{
		outRefNum = FSpOpenResFile(outFile, fsRdWrPerm);
		if (outRefNum < noErr)
		{
			// maybe it does not have one!
			
			FSpCreateResFile(outFile, info.fileCreator, info.fileType, smSystemScript);
			
			outRefNum = FSpOpenResFile(outFile, fsRdWrPerm);	
			if (outRefNum < noErr) 
			{
				return err;
			}
		}
		
		SetResFileAttrs(outRefNum, info.fileResAttrs);
		
		
		CloseResFile(outRefNum);
	}	
	
	return noErr;
	
	

}
Exemplo n.º 16
0
/* create folder with IPIcon */
OSErr MakeFolderWithIPIcon(const FSSpec *theFolder,const IPIconRec *ipIcon)
{
	OSErr		err;
	long		dirID;
	FSSpec		theIconFile;
	Str15		iconFileName;
	#ifdef __MOREFILESX__
	FSRef		fsRef;
	
	#endif
	
	/* create a folder */
	err=FSpDirCreate(theFolder,smSystemScript,&dirID);
	if (err==dupFNErr || err==dirNFErr)
	{
		Boolean	isDirectory;
		
		#ifdef __MOREFILESX__
		err = FSpMakeFSRef(theFolder,&fsRef);
		err = FSGetNodeID(&fsRef,&dirID,&isDirectory);
		#else
		err=FSpGetDirectoryID(theFolder,&dirID,&isDirectory);
		#endif
		if (!isDirectory) return -1;
	}
	if (err!=noErr) return err;
	
	#ifdef __MOREFILESX__
	err = FSpMakeFSRef(theFolder,&fsRef);
	#endif
	
	/* create icon file */
	GetIndString(iconFileName,140,3);
	err=FSMakeFSSpec(theFolder->vRefNum,dirID,iconFileName,&theIconFile);
	if (err==fnfErr)
	{
		FInfo	fndrInfo;
		
		FSpCreateResFile(&theIconFile,kFinderCreator,'icon',smSystemScript);
		err=FSpGetFInfo(&theIconFile,&fndrInfo);
		fndrInfo.fdFlags |= kIsInvisible;
		err=FSpSetFInfo(&theIconFile,&fndrInfo);
	}
	
	/* save icon data */
	if (err==noErr)
	{
		short	refNum;
		IconActionUPP	addIconUPP;
		MyIconResRec	newIcon;
		#ifndef __MOREFILESX__
		DInfo			dInfo;
		#endif
		
		newIcon.resID=kCustomIconResource;
		GetIndString(newIcon.resName,141,2);
		newIcon.attrs=0;
		
		refNum=FSpOpenResFile(&theIconFile,fsWrPerm);
		UseResFile(refNum);
		
		/* save icon family(separated icons) */
		if (ipIcon->iconSuite != NULL)
		{
			addIconUPP = NewIconActionUPP(AddIconToFile);
			err=ForEachIconDo(ipIcon->iconSuite,kSelectorMyData,addIconUPP,&newIcon);
			DisposeIconActionUPP(addIconUPP);
		}
		
		/* save icns(single icon) */
		if (isIconServicesAvailable)
		{
			IconFamilyHandle	iconFamily;
			
			err=IPIconToIconFamily(ipIcon,&iconFamily);
			if (err==noErr)
			{
				SaveDataToResource(*iconFamily,GetHandleSize((Handle)iconFamily),
					kIconFamilyType,newIcon.resID,newIcon.resName,newIcon.attrs);
				DisposeHandle((Handle)iconFamily);
			}
		}
		else
			/* delete icns resource */
			DeleteIconFamilyResource();
		
		CloseResFile(refNum);
		UseResFile(gApplRefNum);
		
		/* set flag for custom icons */
		#ifdef __MOREFILESX__
		err = FSSetHasCustomIcon(&fsRef);
		err = FSClearHasBeenInited(&fsRef);
		#else
		err=FSpGetDInfo(theFolder,&dInfo);
		dInfo.frFlags |= kHasCustomIcon;
		dInfo.frFlags &= ~kHasBeenInited;
		err=FSpSetDInfo(theFolder,&dInfo);
		#endif
		
		gUsedCount.exportNum++;
	}
	
	FlushVol(0L,theFolder->vRefNum);
	
	/* update folder icon */
	UpdateFinderIcon(theFolder);
	
	return err;
}
Exemplo n.º 17
0
static pdc_bool
pdc_init_stream(
    pdc_core *pdc,
    pdc_output *out,
    const char *filename,
    FILE *fp,
    size_t (*writeproc)(pdc_output *out, void *data, size_t size))
{
    static const char fn[] = "pdc_init_stream";

#if (defined(MAC) || defined(MACOSX)) && defined(PDF_FILETYPE_SUPPORTED)
#if !defined(TARGET_API_MAC_CARBON) || defined(__MWERKS__)
    FCBPBRec	fcbInfo;
    Str32	name;
#endif	/* TARGET_API_MAC_CARBON */
    FInfo	fInfo;
    FSSpec	fSpec;
#endif  /* (MAC || MACOSX) && PDF_FILETYPE_SUPPORTED */

    /*
     * This may be left over from the previous run. We deliberately
     * don't reuse the previous buffer in order to avoid potentially
     * unwanted growth of the allocated buffer due to a single large
     * document in a longer series of documents.
     */
    if (out->basepos)
	pdc_free(pdc, (void *) out->basepos);

    out->basepos	= (pdc_byte *) pdc_malloc(pdc, STREAM_BUFSIZE, fn);
    out->curpos		= out->basepos;
    out->maxpos		= out->basepos + STREAM_BUFSIZE;
    out->buf_incr	= STREAM_BUFSIZE;

    out->base_offset	= 0;
    out->compressing	= pdc_false;

#ifdef HAVE_LIBZ
    /* zlib sometimes reads uninitialized memory where it shouldn't... */
    memset(&out->z, 0, sizeof out->z);

    out->z.zalloc	= (alloc_func) pdc_zlib_alloc;
    out->z.zfree	= (free_func) pdc_free;
    out->z.opaque	= (voidpf) pdc;

    if (deflateInit(&out->z, pdc_get_compresslevel(out)) != Z_OK)
	pdc_error(pdc, PDC_E_IO_COMPRESS, "deflateInit", 0, 0, 0);

    out->compr_changed = pdc_false;
#endif

    /* Defaults */
    out->fp		= (FILE *) NULL;
    out->writeproc	= pdc_writeproc_file;

    if (fp)
    {
	out->fp	= fp;
    }
    else if (writeproc)
    {
	out->writeproc	= writeproc;		/* PDF_open_mem */
    }
    else if (filename == NULL || *filename == '\0')
    {
	/* PDF_open_file with in-core output */
	out->writeproc = NULL;
    }
    else
    {
	/* PDF_open_file with file output */
#if !((defined(MAC) || defined (MACOSX)) && defined(__MWERKS__))
	if (filename && !strcmp(filename, "-"))
        {
	    out->fp = stdout;
#if !defined(__MWERKS__) && (defined(WIN32) || defined(OS2))
#if !defined(__BORLANDC__) && !defined(OS2)
	    _setmode(_fileno(stdout), _O_BINARY);
#else
	    setmode(fileno(stdout), O_BINARY);
#endif /* !__BORLANDC__ && !OS2 */
#endif
	}
        else
        {
#endif /* !MAC */
            char fopenparams[200]; /* sufficient */

#if defined(MVS) || defined(MVS_TEST)
            if (out->fopenparams != (char *) 0)
            {
                strcpy(fopenparams, WRITEMODE);
                strcat(fopenparams, ",");
                strcat(fopenparams, out->fopenparams);
            }
            else if (out->recordsize <= 1)
            {
                strcpy(fopenparams, WRITEMODE_V);
            }
            else
            {
                strcpy(fopenparams, WRITEMODE);
            }
#else
            strcpy(fopenparams, WRITEMODE);
#endif

            out->fp = pdc_fopen_logg(out->pdc, filename, fopenparams);
	    if (out->fp == NULL)
		return pdc_false;

#if (defined(MAC) || defined(MACOSX)) && defined(PDF_FILETYPE_SUPPORTED)
            if (!pdc->ptfrun)
            {
                /* set the proper type and creator for the output file */
#if TARGET_API_MAC_CARBON && !defined(__MWERKS__)

                if (FSPathMakeFSSpec((const UInt8 *) filename, &fSpec) == noErr)
                {
                    FSpGetFInfo(&fSpec, &fInfo);
                    fInfo.fdType = 'PDF ';
                    fInfo.fdCreator = 'CARO';
                    FSpSetFInfo(&fSpec, &fInfo);
                }

#else

                memset(&fcbInfo, 0, sizeof(FCBPBRec));
                fcbInfo.ioRefNum = (short) out->fp->handle;
                fcbInfo.ioNamePtr = name;

                if (!PBGetFCBInfoSync(&fcbInfo) &&
                    FSMakeFSSpec(fcbInfo.ioFCBVRefNum, fcbInfo.ioFCBParID,
                    name, &fSpec) == noErr)
                {
                        FSpGetFInfo(&fSpec, &fInfo);
                        fInfo.fdType = 'PDF ';
                        fInfo.fdCreator = 'CARO';
                        FSpSetFInfo(&fSpec, &fInfo);
                }
#endif  /* !defined(TARGET_API_MAC_CARBON) || defined(__MWERKS__) */
            }
#endif	/* (MAC || MACOSX) && PDF_FILETYPE_SUPPORTED */

#if !((defined(MAC) || defined (MACOSX)) && defined(__MWERKS__))
	}
#endif /* !MAC */
    }

    return pdc_true;
}
Exemplo n.º 18
0
OSErr PAS_decodeMisc(PASEntry *entry, FSSpec *outFile, short inRefNum)
{
	OSErr 		err = noErr;	
	short		outRefNum;
	PASMiscInfo	info;
	SInt32		infoSize;
	FInfo		theFInfo;
		
	
	infoSize	=	sizeof(PASMiscInfo);
	
	err = SetFPos(inRefNum, fsFromStart, (*entry).entryOffset );
	if (err != noErr)	return err;

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

	if(infoSize != sizeof(PASMiscInfo))
	{
		return -1;
	}

	err = FSpOpenDF(outFile, fsRdWrPerm, &outRefNum);
	if (err != noErr)	return err;
	
	memset(&theFInfo, 0, sizeof(FInfo));   
		
	theFInfo.fdType		=	info.fileType;
	theFInfo.fdCreator	=	info.fileCreator;	
	theFInfo.fdFlags	=	info.fileFlags;
	
	err = FSpSetFInfo(outFile, &theFInfo);
	if (err != noErr)	return err;
		
	FSClose(outRefNum);
	
	if (info.fileHasResFork)
	{
		outRefNum = FSpOpenResFile(outFile, fsRdWrPerm);
		if (outRefNum < noErr)
		{
			// maybe it does not have one!
			
			FSpCreateResFile(outFile, info.fileCreator, info.fileType, smSystemScript);
			
			outRefNum = FSpOpenResFile(outFile, fsRdWrPerm);	
			if (outRefNum < noErr) 
			{
				return outRefNum;
			}
		}
		
		SetResFileAttrs(outRefNum, info.fileResAttrs);
		
		
		CloseResFile(outRefNum);
	}	
	
	
	if(info.fileType == 'APPL')
	{
		// we need to add applications to the desktop database.
		
/*	FIX :: need to find DTSetAPPL() function	
		err = DTSetAPPL( NULL,
                    	 outFile->vRefNum,
			             info.fileCreator,
			             outFile->parID,
                         outFile->name);
*/	}
	
	
	return err;
	
	

}
static PyObject *
MacOS_SetCreatorAndType(PyObject *self, PyObject *args)
{
    ResType creator, type;
    FSRef ref;
    FileInfo* finfo;
    OSErr err;
    FSCatalogInfo       cataloginfo;

    if (!PyArg_ParseTuple(args, "O&O&O&",
                    PyMac_GetFSRef, &ref, PyMac_GetOSType, &creator, PyMac_GetOSType, &type)) {
#ifndef __LP64__
        /* Try to handle FSSpec arguments, for backward compatibility */
        FSSpec fss;
        FInfo info;

        if (!PyArg_ParseTuple(args, "O&O&O&",
            PyMac_GetFSSpec, &fss, PyMac_GetOSType, &creator, PyMac_GetOSType, &type))
            return NULL;

        if ((err = FSpGetFInfo(&fss, &info)) != noErr)
            return PyErr_Mac(MacOS_Error, err);

        info.fdCreator = creator;
        info.fdType = type;

        if ((err = FSpSetFInfo(&fss, &info)) != noErr)
            return PyErr_Mac(MacOS_Error, err);
        Py_INCREF(Py_None);
        return Py_None;
#else /* __LP64__ */
        return NULL;
#endif /* __LP64__ */
    }

    err = FSGetCatalogInfo(&ref,
                    kFSCatInfoFinderInfo|kFSCatInfoNodeFlags, &cataloginfo,
                    NULL, NULL, NULL);
    if (err != noErr) {
        PyErr_Mac(MacOS_Error, err);
        return NULL;
    }

    if ((cataloginfo.nodeFlags & kFSNodeIsDirectoryMask) != 0) {
        /* Directory: doesn't have type/creator info.
         *
         * The specific error code is for backward compatibility with
         * earlier versions.
         */
        PyErr_Mac(MacOS_Error, fnfErr);
        return NULL;

    }
    finfo = (FileInfo*)&(cataloginfo.finderInfo);
    finfo->fileCreator = creator;
    finfo->fileType = type;

    err = FSSetCatalogInfo(&ref, kFSCatInfoFinderInfo, &cataloginfo);
    if (err != noErr) {
        PyErr_Mac(MacOS_Error, fnfErr);
        return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}
Exemplo n.º 20
0
bool ExportMP3(AudacityProject *project,
               bool stereo, wxString fName,
               bool selectionOnly, double t0, double t1)
{
   double rate = project->GetRate();
   wxWindow *parent = project;
   TrackList *tracks = project->GetTracks();

   wxLogNull logNo;             /* temporarily disable wxWindows error messages */

   bool success = GetMP3Exporter()->FindLibrary(parent);
   
   if (!success)
      return false;

   success = GetMP3Exporter()->LoadLibrary();
   if (!success) {
      wxMessageBox(_("Could not open MP3 encoding library!"));
      gPrefs->Write("/MP3/MP3LibPath", wxString(""));

      return false;
   }

   if(!GetMP3Exporter()->ValidLibraryLoaded()) {
      wxMessageBox(_("Not a valid or supported MP3 encoding library!"));      
      gPrefs->Write("/MP3/MP3LibPath", wxString(""));
      
      return false;
   }
   
   /* Open file for writing */

   wxFFile outFile(fName, "wb");
   if (!outFile.IsOpened()) {
      wxMessageBox(_("Unable to open target file for writing"));
      return false;
   }
   
   /* Put ID3 tags at beginning of file */
   
   Tags *tags = project->GetTags();
   if (!tags->ShowEditDialog(project, _("Edit the ID3 tags for the MP3 file")))
      return false;  // used selected "cancel"

   char *id3buffer;
   int id3len;
   bool endOfFile;
   id3len = tags->ExportID3(&id3buffer, &endOfFile);
   if (!endOfFile)
     outFile.Write(id3buffer, id3len);

   /* Export MP3 using DLL */

   long bitrate = gPrefs->Read("/FileFormats/MP3Bitrate", 128);
   GetMP3Exporter()->SetBitrate(bitrate);

   sampleCount inSamples = GetMP3Exporter()->InitializeStream(stereo ? 2 : 1, int(rate + 0.5));
   double timeStep =  (double)inSamples / rate;
   double t = t0;

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


   int bufferSize = GetMP3Exporter()->GetOutBufferSize();
   unsigned char *buffer = new unsigned char[bufferSize];
   wxASSERT(buffer);

   while (t < t1 && !cancelling) {

      double deltat = timeStep;
      bool lastFrame = false;
      sampleCount numSamples = inSamples;

      if (t + deltat > t1) {
         lastFrame = true;
         deltat = t1 - t;
         numSamples = int(deltat * rate + 0.5);
      }


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


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

      if(lastFrame)
         bytes = GetMP3Exporter()->EncodeRemainder(mixed, numSamples, buffer);
      else
         bytes = GetMP3Exporter()->EncodeBuffer(mixed, buffer);

      outFile.Write(buffer, bytes);

      t += deltat;

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

         wxString message;

         if (selectionOnly)
            message =
                wxString::Format(_("Exporting the selected audio as an mp3"));
         else
            message =
                wxString::Format(_("Exporting the entire project as an mp3"));

         progress =
             new wxProgressDialog(_("Export"),
                                  message,
                                  1000,
                                  parent,
                                  wxPD_CAN_ABORT |
                                  wxPD_REMAINING_TIME | wxPD_AUTO_HIDE);
      }

      if (progress) {
         cancelling =
             !progress->Update(int (((t - t0) * 1000) / (t1 - t0) + 0.5));
      }

      delete mixer;

   }

   bytes = GetMP3Exporter()->FinishStream(buffer);

   if (bytes)
      outFile.Write(buffer, bytes);
   
   /* Write ID3 tag if it was supposed to be at the end of the file */
   
   if (endOfFile)
      outFile.Write(id3buffer, id3len);
   delete[] id3buffer;

   /* Close file */
   
   outFile.Close();
      
   /* MacOS: set the file type/creator so that the OS knows it's an MP3
      file which was created by Audacity */
      
#ifdef __WXMAC__
   FSSpec spec;
   wxMacFilename2FSSpec(fName, &spec);
   FInfo finfo;
   if (FSpGetFInfo(&spec, &finfo) == noErr) {
      finfo.fdType = 'MP3 ';
      finfo.fdCreator = AUDACITY_CREATOR;

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

   if (progress)
      delete progress;

   delete[]buffer;
   
   return true;
}
Exemplo n.º 21
0
int main(int argc, Char *argv[])
{
  boolean canbeplotted;
  boolean wasplotted = false;
#ifdef MAC
  OSErr retcode;
  FInfo  fndrinfo;
#ifdef OSX_CARBON
  FSRef fileRef;
  FSSpec fileSpec;
#endif
#ifdef __MWERKS__
  SIOUXSetTitle("\pPHYLIP:  Drawtree");
#endif
  argv[0] = "Drawgram";
#endif

  grbg = NULL;
  progname = argv[0];

#ifndef X_DISPLAY_MISSING
  nargc=1;
  nargv=argv;
#endif
  
  init(argc, argv);
  emboss_getoptions("fdrawgram",argc,argv);

  setup_environment(argv, &canbeplotted);

  user_loop(&canbeplotted);
  if (!((previewer == winpreview || previewer == xpreview || previewer == mac)
        && (winaction == quitnow))) {
    
    previewing = false;
    initplotter(spp,fontname);
    numlines = dotmatrix ? ((long)floor(yunitspercm * ysize + 0.5)/strpdeep) : 1;
    if (plotter != ibm)
      printf("\nWriting plot file ...\n");
    drawit(fontname,&xoffset,&yoffset,numlines,root);
    finishplotter();
    FClose(plotfile);
    wasplotted = true;
    printf("\nPlot written to file \"%s\"\n\n", pltfilename);
  }
  FClose(intree);
#ifdef MAC
  if (plotter == pict && wasplotted){
#ifdef OSX_CARBON
    FSPathMakeRef((unsigned char *)pltfilename, &fileRef, NULL);
    FSGetCatalogInfo(&fileRef, kFSCatInfoNone, NULL, NULL, &fileSpec, NULL);
    FSpGetFInfo(&fileSpec, &fndrinfo);
    fndrinfo.fdType='PICT';
    fndrinfo.fdCreator='MDRW';
    FSpSetFInfo(&fileSpec, &fndrinfo);
#else
    retcode=GetFInfo(CtoPstr(PLOTFILE),0,&fndrinfo);
    fndrinfo.fdType='PICT';
    fndrinfo.fdCreator='MDRW';
    retcode=SetFInfo(CtoPstr(PLOTFILE),0,&fndrinfo);
#endif
  }
  if (plotter == lw && wasplotted){
#ifdef OSX_CARBON
    FSPathMakeRef((unsigned char *)pltfilename, &fileRef, NULL);
    FSGetCatalogInfo(&fileRef, kFSCatInfoNone, NULL, NULL, &fileSpec, NULL);
    FSpGetFInfo(&fileSpec, &fndrinfo);
    fndrinfo.fdType='TEXT';
    FSpSetFInfo(&fileSpec, &fndrinfo);
#else
    retcode=GetFInfo(CtoPstr(PLOTFILE),0,&fndrinfo);
    fndrinfo.fdType='TEXT';
    retcode=SetFInfo(CtoPstr(PLOTFILE),0,&fndrinfo);
#endif
  }
#endif
  printf("Done.\n\n");

#ifdef WIN32
  phyRestoreConsoleAttributes();
#endif

  embExit();
  return 0;
}
Exemplo n.º 22
0
static int
SetFileFinderAttributes(
    Tcl_Interp *interp,		/* The interp to report errors with. */
    int objIndex,		/* The index of the attribute. */
    char *fileName,		/* The name of the file. */
    Tcl_Obj *attributePtr)	/* The command line object. */
{
    OSErr err;
    FSSpec fileSpec;
    FInfo finfo;
    
    err = FSpLocationFromPath(strlen(fileName), fileName, &fileSpec);
    
    if (err == noErr) {
    	err = FSpGetFInfo(&fileSpec, &finfo);
    }
    
    if (err == noErr) {
    	switch (objIndex) {
    	    case MAC_CREATOR_ATTRIBUTE:
    	    	if (Tcl_GetOSTypeFromObj(interp, attributePtr,
    	    		&finfo.fdCreator) != TCL_OK) {
    	    	    return TCL_ERROR;
    	    	}
    	    	break;
    	    case MAC_HIDDEN_ATTRIBUTE: {
    	    	int hidden;
    	    	
    	    	if (Tcl_GetBooleanFromObj(interp, attributePtr, &hidden)
    	    		!= TCL_OK) {
    	    	    return TCL_ERROR;
    	    	}
    	    	if (hidden) {
    	    	    finfo.fdFlags |= kIsInvisible;
    	    	} else {
    	    	    finfo.fdFlags &= ~kIsInvisible;
    	    	}
    	    	break;
    	    }
    	    case MAC_TYPE_ATTRIBUTE:
    	    	if (Tcl_GetOSTypeFromObj(interp, attributePtr,
    	    		&finfo.fdType) != TCL_OK) {
    	    	    return TCL_ERROR;
    	    	}
    	    	break;
    	}
    	err = FSpSetFInfo(&fileSpec, &finfo);
    } else if (err == fnfErr) {
    	long dirID;
    	Boolean isDirectory = 0;
    	
    	err = FSpGetDirectoryID(&fileSpec, &dirID, &isDirectory);
    	if ((err == noErr) && isDirectory) {
    	    Tcl_Obj *resultPtr = Tcl_GetObjResult(interp);
    	    Tcl_AppendStringsToObj(resultPtr, "cannot set ",
    	    	    tclpFileAttrStrings[objIndex], ": \"",
    	    	    fileName, "\" is a directory", (char *) NULL);
    	    return TCL_ERROR;
    	}
    }
    
    if (err != noErr) {
    	errno = TclMacOSErrorToPosixError(err);
    	Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), 
    		"couldn't set attributes for file \"", fileName, "\": ",
    		Tcl_PosixError(interp), (char *) NULL);
    	return TCL_ERROR;
    }
    return TCL_OK;
}
Exemplo n.º 23
0
bool ExportPCM(AudacityProject *project,
               bool stereo, wxString fName,
               bool selectionOnly, double t0, double t1)
{
   double       rate = project->GetRate();
   wxWindow    *parent = project;
   TrackList   *tracks = project->GetTracks();
   int          format = ReadExportFormatPref();
   int          formatBits = ReadExportFormatBitsPref();
   wxString     formatStr;
   SF_INFO      info;
   SNDFILE     *sf;
   int          err;

   formatStr = sf_header_name(format & SF_FORMAT_TYPEMASK);

   // Use libsndfile to export file

   info.samplerate = (unsigned int)(rate + 0.5);
   info.samples = (unsigned int)((t1 - t0)*rate + 0.5);
   info.channels = stereo? 2: 1;
   info.pcmbitwidth = formatBits;
   info.format = format;
   info.sections = 1;
   info.seekable = 0;

   // If we can't export exactly the format they requested,
   // try the default format for that header type, and try
   // 16-bit samples.
   if (!sf_format_check(&info))
      info.format = (info.format & SF_FORMAT_TYPEMASK);
   if (!sf_format_check(&info))
      info.pcmbitwidth = 16;
   if (!sf_format_check(&info)) {
      wxMessageBox(_("Cannot export audio in this format."));
      return false;
   }

   sf = sf_open_write((const char *)fName, &info);
   if (!sf) {
      wxMessageBox(wxString::Format(_("Cannot export audio to %s"),
                                    (const char *)fName));
      return false;
   }

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

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

   double t = t0;

   while (t < t1 && !cancelling) {

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

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

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

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

      sampleType *mixed = mixer->GetBuffer();

      sf_writef_short(sf, mixed, numSamples);

      t += deltat;

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

         wxString message;

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

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

      delete mixer;
   }

   err = sf_close(sf);

   if (err) {
      char buffer[1000];
      sf_error_str(sf, buffer, 1000);
      wxMessageBox(wxString::Format
                   (_("Error (file may not have been written): %s"),
                    buffer));
   }

#ifdef __WXMAC__

   FSSpec spec;

   wxMacFilename2FSSpec(fName, &spec);

   FInfo finfo;
   if (FSpGetFInfo(&spec, &finfo) == noErr) {
      finfo.fdType = sf_header_mactype(format & SF_FORMAT_TYPEMASK);
      finfo.fdCreator = AUDACITY_CREATOR;

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

   if (progress)
      delete progress;

   return true;
}