Exemplo n.º 1
0
static void HandleStartEvent(NavCBRecPtr callBackParms, CustomData *data)
{
   data->context = callBackParms->context;

   CreateUserPaneControl(callBackParms->window, &data->bounds, kControlSupportsEmbedding, &data->userpane);

   InstallControlEventHandler(data->userpane,
                              GetHandlePaneEventsUPP(),
                              GetEventTypeCount(namedAttrsList),
                              namedAttrsList,
                              data,
                              NULL);

   EmbedControl(data->choice, data->userpane);
   EmbedControl(data->button, data->userpane);
   
   NavCustomControl(callBackParms->context, kNavCtlAddControl, data->userpane);
   
   HandleAdjustRect(callBackParms, data);
   
   if (data && !(data->defaultLocation).IsEmpty())
   {
      // Set default location for the modern Navigation APIs
      // Apple Technical Q&A 1151
      FSSpec theFSSpec;
      wxMacFilename2FSSpec(data->defaultLocation, &theFSSpec);
      AEDesc theLocation = {typeNull, NULL};
      if (noErr == ::AECreateDesc(typeFSS, &theFSSpec, sizeof(FSSpec), &theLocation))
         ::NavCustomControl(callBackParms->context, kNavCtlSetLocation, (void *) &theLocation);
   }
}
Exemplo n.º 2
0
bool wxDynamicLibrary::Load(const wxString& libnameOrig, int flags)
{
    wxASSERT_MSG(m_handle == 0, _T("Library already loaded."));

    // add the proper extension for the DLL ourselves unless told not to
    wxString libname = libnameOrig;
    if ( !(flags & wxDL_VERBATIM) )
    {
        // and also check that the libname doesn't already have it
        wxString ext;
        wxFileName::SplitPath(libname, NULL, NULL, &ext);
        if ( ext.empty() )
        {
            libname += GetDllExt();
        }
    }

    // different ways to load a shared library
    //
    // FIXME: should go to the platform-specific files!
#if defined(__WXMAC__) && !defined(__DARWIN__)
    FSSpec      myFSSpec;
    Ptr         myMainAddr;
    Str255      myErrName;

    wxMacFilename2FSSpec( libname , &myFSSpec );

    if( GetDiskFragment( &myFSSpec,
                         0,
                         kCFragGoesToEOF,
                         "\p",
                         kPrivateCFragCopy,
                         &m_handle,
                         &myMainAddr,
                         myErrName ) != noErr )
    {
        wxLogSysError( _("Failed to load shared library '%s' Error '%s'"),
                       libname.c_str(),
                       wxMacMakeStringFromPascal( myErrName ).c_str() );
        m_handle = 0;
    }

#elif defined(__WXPM__) || defined(__EMX__)
    char    err[256] = "";
    DosLoadModule(err, sizeof(err), (PSZ)libname.c_str(), &m_handle);
#else
    m_handle = RawLoad(libname, flags);
#endif

    if ( m_handle == 0 )
    {
#ifdef wxHAVE_DYNLIB_ERROR
        Error();
#else
        wxLogSysError(_("Failed to load shared library '%s'"), libname.c_str());
#endif
    }

    return IsLoaded();
}
Exemplo n.º 3
0
static pascal void
NavEventProc(
    NavEventCallbackMessage        inSelector,
    NavCBRecPtr                    ioParams,
    NavCallBackUserData    ioUserData    )
{
    OpenUserDataRec * data = ( OpenUserDataRec *) ioUserData ;
    if (inSelector == kNavCBEvent) {
    }
    else if ( inSelector == kNavCBStart )
    {
        if (data && !(data->defaultLocation).IsEmpty())
        {
            // Set default location for the modern Navigation APIs
            // Apple Technical Q&A 1151
            FSSpec theFSSpec;
            wxMacFilename2FSSpec(data->defaultLocation, &theFSSpec);
            AEDesc theLocation = {typeNull, NULL};
            if (noErr == ::AECreateDesc(typeFSS, &theFSSpec, sizeof(FSSpec), &theLocation))
                ::NavCustomControl(ioParams->context, kNavCtlSetLocation, (void *) &theLocation);
        }

        NavMenuItemSpec  menuItem;
        menuItem.version = kNavMenuItemSpecVersion;
        menuItem.menuCreator = 'WXNG';
        menuItem.menuType = data->currentfilter;
        wxMacStringToPascal( data->name[data->currentfilter] , (StringPtr)(menuItem.menuItemName) ) ;
        ::NavCustomControl(ioParams->context, kNavCtlSelectCustomType, &menuItem);
    }
    else if ( inSelector == kNavCBPopupMenuSelect )
    {
        NavMenuItemSpec * menu = (NavMenuItemSpec *) ioParams->eventData.eventDataParms.param ;
        const size_t numFilters = data->extensions.GetCount();

        if ( menu->menuType < numFilters )
        {
            data->currentfilter = menu->menuType ;
            if ( data->saveMode )
            {
                int i = menu->menuType ;
                wxString extension =  data->extensions[i].AfterLast('.') ;
                extension.MakeLower() ;
                wxString sfilename ;

                wxMacCFStringHolder cfString( NavDialogGetSaveFileName( ioParams->context ) , false  );
                sfilename = cfString.AsString() ;

                int pos = sfilename.Find('.', true) ;
                if ( pos != wxNOT_FOUND )
                {
                    sfilename = sfilename.Left(pos+1)+extension ;
                    cfString.Assign( sfilename , wxFONTENCODING_DEFAULT ) ;
                    NavDialogSetSaveFileName( ioParams->context , cfString ) ;
                }
            }
        }
    }
}
Exemplo n.º 4
0
ImportFileHandle *QTImportPlugin::Open(wxString Filename)
{
   FSSpec inFile;
   FInfo fileInfo;
   Movie theMovie = 0;
   Media theMedia;

   // Make sure QuickTime is initialized
   //::EnterMovies();

#ifdef WIN32
   char* specFilename = strdup(Filename.GetData());
   if (FSMakeFSSpec(0,0,c2pstr(specFilename), &inFile) != noErr)
   {
       free(specFilename);
       return false;
   }
   free(specFilename);
#else
   wxMacFilename2FSSpec(Filename, &inFile);
#endif

   OSErr err = FSpGetFInfo(&inFile, &fileInfo);

   if(err != noErr)
      return NULL;

   if (kQTFileTypeSystemSevenSound == fileInfo.fdType)
   {
      // TODO: handle this case.  it is special because system seven sounds cannot
      // be opened in place
   }
   else
   {
      short theRefNum;
      short theResID = 0;  // we want the first movie
      Boolean wasChanged;

      // open the movie file
      err = OpenMovieFile(&inFile, &theRefNum, fsRdPerm);
      if(err != noErr)
         return NULL;

      // instantiate the movie
      err = NewMovieFromFile(&theMovie, theRefNum, &theResID, NULL, newMovieActive, &wasChanged);
      CloseMovieFile(theRefNum);
      if(err != noErr)
         return NULL;
   }


   // get and return the sound track media
   theMedia = GetMediaFromMovie(theMovie);
   if(theMedia == NULL)
      return NULL;

   return new QTImportFileHandle(theMovie, theMedia);
}
Exemplo n.º 5
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.º 6
0
wxDirData::wxDirData(const wxString& dirname)
         : m_dirname(dirname)
{
    m_ok = false;

    OSErr err;

    // throw away the trailing slashes
    size_t n = m_dirname.length();
    wxCHECK_RET( n, _T("empty dir name in wxDir") );

    while ( n > 0 && wxIsPathSeparator(m_dirname[--n]) )
        ;

    m_dirname.Truncate(n + 1);

#ifdef __DARWIN__
    FSRef theRef;

    // get the FSRef associated with the POSIX path
    err = FSPathMakeRef((const UInt8 *) m_dirname.c_str(), &theRef, NULL);
    FSGetVRefNum(&theRef, &(m_CPB.hFileInfo.ioVRefNum));

    err = FSGetNodeID( &theRef , &m_dirId , &m_isDir ) ;
#else
    FSSpec fsspec ;

    wxMacFilename2FSSpec( m_dirname , &fsspec ) ;
    m_CPB.hFileInfo.ioVRefNum = fsspec.vRefNum ;

    err = FSpGetDirectoryID( &fsspec , &m_dirId , &m_isDir ) ;
#endif
    //wxASSERT_MSG( (err == noErr) || (err == nsvErr) , wxT("Error accessing directory " + m_dirname)) ;
    if ( (err == noErr) || (err == nsvErr))
        m_ok = true;
    else
        wxLogError(wxString(wxT("Error accessing directory ")) + m_dirname);

    m_CPB.hFileInfo.ioNamePtr = m_name ;
    m_index = 0 ;
}
Exemplo n.º 7
0
void MolDisplayWin::WriteQTMovie(wxString & filepath) {
	//Create a QuickTime movie using the standard animation codecs with normal quality, and 
	//temporal compression. The final file is flattened for cross platform compatability
	
	QTExport * QTOptions = new QTExport(this);
	//setup controls for the current data
	if (MainData->GetNumFrames() > 1) { //default to frame animation
		QTOptions->SetMovieChoice(0);
	} else {
		QTOptions->EnableFrameMovie(false);
	}
	if (MainData->cFrame->GetNumberNormalModes() <= 0) {
		QTOptions->EnableModeMovie(false);
	}
	
	if (QTOptions->ShowModal() != wxID_OK) {
		//user cancelled the operation
		QTOptions->Destroy();
		return;
	}
	//retrieve the value of each option
	int MovieType = QTOptions->GetMovieChoice();
	bool IncludeEPlot = QTOptions->AddEnergyPlot();
	int compressorChoice = QTOptions->GetCompressorChoice();
	int keyFrameRate = QTOptions->GetKeyFrameRate();
	if (keyFrameRate < 0) keyFrameRate = 0;
	
	QTOptions->Destroy();
	
	CodecType mCodec;
	switch (compressorChoice) {
		case 0:
			mCodec = kCinepakCodecType;
			break;
		case 1:
			mCodec = kGraphicsCodecType;
			break;
		case 2:
			mCodec = kAnimationCodecType;
			break;
		case 3:
		default:
			mCodec = kMPEG4VisualCodecType;
	}

	OSStatus s;
	OSErr myErr = myErr;
	FSSpec targetSpec;
	//ugh I need to get an FSSpec to hand to quicktime, but these calls only seem to work if
	//the file already exists...
	const char * t = filepath.mb_str(wxConvUTF8);
	FILE * temp = fopen(t, "wb");
	fclose(temp);

#ifdef __WXOSX_COCOA__
	//This function is not found in the wxCocoa implementation, it is probably possible to work around it
	//Otherwise the code appears to link and run currently. However, it is probably better to redue the
	//code to use the Cocoa qtKit framework rather than the old Carbon QT library.
	
	//This path is not tested as the current Cocoa code does not properly support the extended save dialog.
	//	void wxMacFilename2FSSpec( const wxString& path , FSSpec *spec )
	{
		OSStatus err = noErr;
		FSRef fsRef;
		wxMacPathToFSRef( filepath , &fsRef );
		err = FSGetCatalogInfo(&fsRef, kFSCatInfoNone, NULL, NULL, &targetSpec, NULL);
		verify_noerr( err );
	}
#else
	wxMacFilename2FSSpec(filepath, &targetSpec);
#endif
	
	Movie	theMovie = NULL;
		
	FSSpec tempSpec = targetSpec;
	strcpy((char *) &(tempSpec.name[1]), "MacMolPlt8933tempMovie");
	tempSpec.name[0] = 22;

	BeginOperation();
	ProgressInd->ChangeText("Creating movie...");
		
	myErr = EnterMovies();	//initialize the quicktime manager
	if (myErr != noErr) {
		FinishOperation();
		MessageAlert("Error initializing QuickTime!");
		return;
	}
		//Create the movie file and initialize file data
		//Use Quicktime creator code 'TVOD' instead of simpletext 'ttxt'
	short	resRefNum = 0;
	short	resId = 0;
	myErr = CreateMovieFile(&tempSpec, 'TVOD', smCurrentScript, createMovieFileDeleteCurFile,
							&resRefNum, &theMovie);
	if (myErr != noErr) {
		MessageAlert("Error creating movie file!");
	} else {
		bool KillEPlot = false;
		int width, height, savedEPlotWidth, savedEPlotHeight;
		glCanvas->GetClientSize(&width, &height);
		Rect lDisplayRect={0,0,0,0};
		lDisplayRect.right = width;
		lDisplayRect.bottom = height;
		Rect		gRect = lDisplayRect;

		Rect EPlotRect = lDisplayRect;
		//If we are including an energy plot add space for it here
		if (IncludeEPlot && (MovieType == 0)) {
			EPlotRect.left = EPlotRect.right;
			EPlotRect.right = EPlotRect.left + height;
			if (!energyPlotWindow) {
				energyPlotWindow = new EnergyPlotDialog(this);
				KillEPlot = true;
			} else {
				energyPlotWindow->GetSize(&savedEPlotWidth, &savedEPlotHeight);
			}
			gRect.right += height;
			width += height;
			energyPlotWindow->Show(false);
			energyPlotWindow->SetSize(height, height);
			energyPlotWindow->Update();	//This is needed to initialise the window if we just created it
		}

		LocalToGlobal ((Point *) &(gRect.top));
		LocalToGlobal ((Point *) &(gRect.bottom));
		WindowRef TempWindow;
		s = CreateNewWindow(kDocumentWindowClass, kWindowNoAttributes, &gRect, &TempWindow);
		if (s == noErr) {
													//Create the video track
			Track theTrack = NewMovieTrack (theMovie, FixRatio(width,1),
											FixRatio(height,1), kNoVolume);
			if ((noErr == GetMoviesError())&&theTrack) {
				Media theMedia = NewTrackMedia (theTrack, VideoMediaType,
												60, // Video Time Scale
												NULL, 0);
				if ((noErr == GetMoviesError())&&theMedia) {
					myErr = BeginMediaEdits (theMedia);
					if (myErr == noErr) {
						//create the actual movie frames
						GWorldPtr	lgWorld=NULL;
						
						if (! NewGWorld (&lgWorld, 0, &gRect, (CTabHandle) NULL, (GDHandle) NULL,
										 (GWorldFlags) (pixPurge + useTempMem))) {
							long MaxCompressedSize;
							ImageSequence seqID;
							ImageDescriptionHandle imageDesc = (ImageDescriptionHandle)NewHandle(4);
							PixMapHandle myPixMap = GetPortPixMap(lgWorld);
							LockPixels (myPixMap);
							myErr = CompressSequenceBegin(&seqID, myPixMap, NULL, &gRect, &gRect, 0,
														  mCodec, bestCompressionCodec, codecNormalQuality, codecNormalQuality, keyFrameRate, NULL,
														  codecFlagUpdatePreviousComp, imageDesc);
							GetMaxCompressionSize (myPixMap, &gRect,
												   0, codecNormalQuality, mCodec, (CompressorComponent) anyCodec, &MaxCompressedSize);
							Handle Buffer = TempNewHandle(MaxCompressedSize, &myErr);
							if (!Buffer)
								Buffer = NewHandle(MaxCompressedSize);
							if (Buffer) {
								qtData myqtData = {theMedia, imageDesc, seqID, lDisplayRect, gRect};
								if (MovieType == 0) {
									CreateFrameMovie(lgWorld, Buffer, myqtData, IncludeEPlot);
								} else {
									CreateModeMovie(lgWorld, Buffer, myqtData);
								}
								DisposeHandle(Buffer);
							}
							myErr = CDSequenceEnd(seqID);
							if (lgWorld != NULL) DisposeGWorld (lgWorld);
							if (imageDesc) DisposeHandle((Handle) imageDesc);
						}
						
						myErr = EndMediaEdits (theMedia);
					}
					myErr = InsertMediaIntoTrack (theTrack, 0,/* track start time */
						0,        /* media start time */
						GetMediaDuration (theMedia),
						FixRatio(1,1));
				}
				myErr = AddMovieResource (theMovie, resRefNum, &resId, NULL);
			}
			if (resRefNum) {
						//Create the actual file as a flat data fork so it can be placed on the www
				ProgressInd->ChangeText("Flattening movieÉ");
				FlattenMovie(theMovie, flattenAddMovieToDataFork, &targetSpec, 'TVOD', smCurrentScript, 
							 createMovieFileDeleteCurFile, &resId, NULL);
				CloseMovieFile (resRefNum);
			}
			DisposeWindow(TempWindow);
		}
		DisposeMovie (theMovie);
		DeleteMovieFile (&tempSpec);	//delete the temp file after disposing of the movie

		if (energyPlotWindow) {
			if (KillEPlot) {
				delete energyPlotWindow;
				energyPlotWindow = NULL;
			} else {
				energyPlotWindow->SetSize(savedEPlotWidth, savedEPlotHeight);
				energyPlotWindow->FrameChanged();
				energyPlotWindow->Show(true);
			}
		}
	}
	ExitMovies();	//Close out quicktime as we are done with it for now
	FinishOperation();
}
Exemplo n.º 8
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.º 9
0
wxDragResult wxDropSource::DoDragDrop(int flags)
{
    wxASSERT_MSG( m_data, wxT("Drop source: no data") );

    if ((m_data == NULL) || (m_data->GetFormatCount() == 0))
        return (wxDragResult)wxDragNone;

    DragReference theDrag;
    RgnHandle dragRegion;

    if (NewDrag( &theDrag ) != noErr)
        return wxDragNone;

    // add data to drag
    size_t formatCount = m_data->GetFormatCount();
    wxDataFormat *formats = new wxDataFormat[formatCount];
    m_data->GetAllFormats( formats );
    ItemReference theItem = (ItemReference) 1;

    for ( size_t i = 0; i < formatCount; ++i )
    {
        size_t dataSize = m_data->GetDataSize( formats[i] );
        Ptr dataPtr = new char[dataSize];
        m_data->GetDataHere( formats[i], dataPtr );
        OSType type = formats[i].GetFormatId();
        if ( type == 'TEXT' || type == 'utxt' )
        {
            if ( dataSize > 0 )
                dataSize--;
            dataPtr[ dataSize ] = 0;
            if ( type == 'utxt' )
            {
                if ( dataSize > 0 )
                    dataSize--;
                dataPtr[ dataSize ] = 0;
            }

            AddDragItemFlavor( theDrag, theItem, type, dataPtr, dataSize, 0 );
        }
        else if (type == kDragFlavorTypeHFS )
        {
            HFSFlavor  theFlavor;
            OSErr err = noErr;
#ifndef __LP64__
            CInfoPBRec cat;

            wxMacFilename2FSSpec( wxString( dataPtr, *wxConvCurrent ), &theFlavor.fileSpec );

            memset( &cat, 0, sizeof(cat) );
            cat.hFileInfo.ioNamePtr = theFlavor.fileSpec.name;
            cat.hFileInfo.ioVRefNum = theFlavor.fileSpec.vRefNum;
            cat.hFileInfo.ioDirID = theFlavor.fileSpec.parID;
            cat.hFileInfo.ioFDirIndex = 0;
            err = PBGetCatInfoSync( &cat );
#endif
          if (err == noErr)
            {
#ifndef __LP64__
                theFlavor.fdFlags = cat.hFileInfo.ioFlFndrInfo.fdFlags;
                if (theFlavor.fileSpec.parID == fsRtParID)
                {
                    theFlavor.fileCreator = 'MACS';
                    theFlavor.fileType = 'disk';
                }
                else if ((cat.hFileInfo.ioFlAttrib & ioDirMask) != 0)
                {
                    theFlavor.fileCreator = 'MACS';
                    theFlavor.fileType = 'fold';
                }
                else
                {
                    theFlavor.fileCreator = cat.hFileInfo.ioFlFndrInfo.fdCreator;
                    theFlavor.fileType = cat.hFileInfo.ioFlFndrInfo.fdType;
                }
#endif
                AddDragItemFlavor( theDrag, theItem, type, &theFlavor, sizeof(theFlavor), 0 );
            }
        }
        else
        {
            AddDragItemFlavor( theDrag, theItem, type, dataPtr, dataSize, 0 );
        }

        delete [] dataPtr;
    }

    delete [] formats;

    dragRegion = NewRgn();
    RgnHandle tempRgn = NewRgn();

    EventRecord* ev = NULL;

#if !TARGET_CARBON // TODO
    ev = (EventRecord*) wxTheApp->MacGetCurrentEvent();
#else
    EventRecord rec;
    ev = &rec;
    wxMacConvertEventToRecord( (EventRef) wxTheApp->MacGetCurrentEvent(), &rec );
#endif

    const short dragRegionOuterBoundary = 10;
    const short dragRegionInnerBoundary = 9;

    SetRectRgn(
        dragRegion,
        ev->where.h - dragRegionOuterBoundary,
        ev->where.v  - dragRegionOuterBoundary,
        ev->where.h + dragRegionOuterBoundary,
        ev->where.v + dragRegionOuterBoundary );

    SetRectRgn(
        tempRgn,
        ev->where.h - dragRegionInnerBoundary,
        ev->where.v - dragRegionInnerBoundary,
        ev->where.h + dragRegionInnerBoundary,
        ev->where.v + dragRegionInnerBoundary );

    DiffRgn( dragRegion, tempRgn, dragRegion );
    DisposeRgn( tempRgn );

    // TODO: work with promises in order to return data
    // only when drag was successfully completed

    gTrackingGlobals.m_currentSource = this;
    TrackDrag( theDrag, ev, dragRegion );
    DisposeRgn( dragRegion );
    DisposeDrag( theDrag );
    gTrackingGlobals.m_currentSource = NULL;

    bool optionDown = GetCurrentKeyModifiers() & optionKey;
    wxDragResult dndresult = wxDragCopy;
    if ( flags != wxDrag_CopyOnly )
        // on mac the option key is always the indication for copy
        dndresult = optionDown ? wxDragCopy : wxDragMove;

    return dndresult;
}
Exemplo n.º 10
0
static pascal void
NavEventProc(
    NavEventCallbackMessage        inSelector,
    NavCBRecPtr                    ioParams,
    NavCallBackUserData    ioUserData    )
{
    OpenUserDataRec * data = ( OpenUserDataRec *) ioUserData ;
    if (inSelector == kNavCBEvent) {
#if TARGET_CARBON
#else
        wxTheApp->MacHandleOneEvent(ioParams->eventData.eventDataParms.event);
#endif
    }
    else if ( inSelector == kNavCBStart )
    {
#if TARGET_CARBON
        if (data && !(data->defaultLocation).IsEmpty())
        {
            // Set default location for the modern Navigation APIs
            // Apple Technical Q&A 1151
            FSSpec theFSSpec;
            wxMacFilename2FSSpec(data->defaultLocation, &theFSSpec);
            AEDesc theLocation = {typeNull, NULL};
            if (noErr == ::AECreateDesc(typeFSS, &theFSSpec, sizeof(FSSpec), &theLocation))
                ::NavCustomControl(ioParams->context, kNavCtlSetLocation, (void *) &theLocation);
        }
#else
        if ( data->menuitems )
            NavCustomControl(ioParams->context, kNavCtlSelectCustomType, &(*data->menuitems)[data->currentfilter]);
#endif
    }
    else if ( inSelector == kNavCBPopupMenuSelect )
    {
        NavMenuItemSpec * menu = (NavMenuItemSpec *) ioParams->eventData.eventDataParms.param ;
#if TARGET_CARBON
#else
        if ( menu->menuCreator == 'WXNG' )
#endif
        {
            data->currentfilter = menu->menuType ;
            if ( data->saveMode )
            {
                int i = menu->menuType ;
                wxString extension =  data->extensions[i].AfterLast('.') ;
                extension.MakeLower() ;
                wxString sfilename ;

#if TARGET_CARBON
                wxMacCFStringHolder cfString( NavDialogGetSaveFileName( ioParams->context ) , false  );
                sfilename = cfString.AsString() ;
#else
                Str255 filename ;
                // get the current filename
                NavCustomControl(ioParams->context, kNavCtlGetEditFileName, &filename);
                sfilename = wxMacMakeStringFromPascal( filename ) ;
#endif

                int pos = sfilename.Find('.', true) ;
                if ( pos != wxNOT_FOUND )
                {
                    sfilename = sfilename.Left(pos+1)+extension ;
#if TARGET_CARBON
                    cfString.Assign( sfilename , wxFONTENCODING_DEFAULT ) ;
                    NavDialogSetSaveFileName( ioParams->context , cfString ) ;
#else
                    wxMacStringToPascal( sfilename , filename ) ;
                    NavCustomControl(ioParams->context, kNavCtlSetEditFileName, &filename);
#endif
                }
            }
        }
    }
}
Exemplo n.º 11
0
   void LoadVSTPlugins()
   {
#ifdef __MACOSX__
      audioMasterCallback audioMasterFPtr =
         (audioMasterCallback)NewCFMFromMachO(audioMaster);
#else
      // What is the corrct way of creating an audioMasterCallback
      // in OS 9/Carbon???
      // audioMasterCallback audioMasterFPtr = NULL; 
      audioMasterCallback audioMasterFPtr = audioMaster;
#endif      

      wxArrayString audacityPathList = wxGetApp().audacityPathList;
      wxArrayString pathList;
      wxArrayString files;
      unsigned int i;
      
      for(i=0; i<audacityPathList.GetCount(); i++) {
         wxString prefix = audacityPathList[i] + wxFILE_SEP_PATH;
         wxGetApp().AddUniquePathToPathList(prefix + "VST",
                                            pathList);
         wxGetApp().AddUniquePathToPathList(prefix + "Plugins",
                                            pathList);
         wxGetApp().AddUniquePathToPathList(prefix + "Plug-Ins",
                                            pathList);
      }

      #ifdef __MACOSX__
      wxGetApp().AddUniquePathToPathList("/Library/Audio/Plug-Ins/VST",
                              pathList);
      wxString vstPath;
      vstPath.Printf("/Users/%s/Library/Audio/Plug-Ins/VST",
                     wxGetenv("USER"));
      wxGetApp().AddUniquePathToPathList(vstPath,
                                         pathList);
      #endif

      wxGetApp().FindFilesInPathList("*", pathList, wxFILE, files);
      
      for(i=0; i<files.GetCount(); i++) {
         short   resFileID;
         FSSpec  spec;
         
         wxMacFilename2FSSpec(FILENAME(files[i]), &spec);
         resFileID = FSpOpenResFile(&spec, fsRdPerm);
         short cResCB = Count1Resources('aEff');

         for (int i = 0; i < cResCB; i++) {
            Handle             codeH;
            CFragConnectionID  connID;
            Ptr                mainAddr;
            Str255             errName;
            Str255             fragName;
            char               fragNameCStr[256];
            short              resID;
            OSType             resType;
            OSErr              err;

            codeH = Get1IndResource('aEff', short(i+1));
            if (!codeH)
               continue;

            GetResInfo(codeH, &resID, &resType, fragName);
            DetachResource(codeH);
            HLock(codeH);

            err = GetMemFragment(*codeH,
                                 GetHandleSize(codeH),
                                 fragName,
                                 kPrivateCFragCopy,
                                 &connID, (Ptr *) & mainAddr, errName);

            if (!err) {
               vstPluginMain   pluginMain;
               AEffect        *theEffect;

               #ifdef __MACOSX__
               pluginMain = (vstPluginMain)NewMachOFromCFM(mainAddr);
               #else
               pluginMain = (vstPluginMain)mainAddr;
               #endif

               theEffect = pluginMain(audioMasterFPtr);

               if (theEffect->magic == kEffectMagic) {
                  
                  memcpy(fragNameCStr, &fragName[1], fragName[0]);
                  fragNameCStr[fragName[0]] = 0;
                  
                  VSTEffect *vst =
                     new VSTEffect(wxString(fragNameCStr), theEffect);
                  Effect::RegisterEffect(vst);
               }

               #ifdef __MACOSX__
               DisposeMachOFromCFM(pluginMain);
               #endif
               
               audacityVSTID++;
            }
         }
         
         CloseResFile(resFileID);

      }
         
#ifdef __MACOSX__
      DisposeCFMFromMachO(audioMasterFPtr);
#endif  //   __MACOSX__
   }
Exemplo n.º 12
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.º 13
0
int wxFileDialog::ShowModal()
{
#if TARGET_CARBON
    OSErr err;
    NavDialogCreationOptions dialogCreateOptions;
    // set default options
    ::NavGetDefaultDialogCreationOptions(&dialogCreateOptions);

    // this was always unset in the old code
    dialogCreateOptions.optionFlags &= ~kNavSelectDefaultLocation;

    wxMacCFStringHolder message(m_message, m_font.GetEncoding());
    dialogCreateOptions.windowTitle = message;

    wxMacCFStringHolder defaultFileName(m_fileName, m_font.GetEncoding());
    dialogCreateOptions.saveFileName = defaultFileName;


    NavDialogRef dialog;
    NavObjectFilterUPP navFilterUPP = NULL;
    CFArrayRef cfArray = NULL; // for popupExtension
    OpenUserDataRec myData;
    myData.defaultLocation = m_dir;

    if (m_dialogStyle & wxSAVE)
    {
        dialogCreateOptions.optionFlags |= kNavNoTypePopup;
        dialogCreateOptions.optionFlags |= kNavDontAutoTranslate;
        dialogCreateOptions.optionFlags |= kNavDontAddTranslateItems;

        // The extension is important
        dialogCreateOptions.optionFlags |= kNavPreserveSaveFileExtension;

        err = ::NavCreatePutFileDialog(&dialogCreateOptions,
                                       'TEXT',
                                       'TEXT',
                                       sStandardNavEventFilter,
                                       &myData, // for defaultLocation
                                       &dialog);
    }
    else
    {
        MakeUserDataRec(&myData , m_wildCard);
        size_t numfilters = myData.extensions.GetCount();
        if (numfilters > 0)
        {
            CFMutableArrayRef popup = CFArrayCreateMutable( kCFAllocatorDefault ,
                                      numfilters , &kCFTypeArrayCallBacks ) ;
            dialogCreateOptions.popupExtension = popup ;
            myData.menuitems = dialogCreateOptions.popupExtension ;
            for ( size_t i = 0 ; i < numfilters ; ++i )
            {
                CFArrayAppendValue( popup , (CFStringRef) wxMacCFStringHolder( myData.name[i] , m_font.GetEncoding() ) ) ;
            }
        }

        navFilterUPP = NewNavObjectFilterUPP(CrossPlatformFilterCallback);
        err = ::NavCreateGetFileDialog(&dialogCreateOptions,
                                       NULL, // NavTypeListHandle
                                       sStandardNavEventFilter,
                                       NULL, // NavPreviewUPP
                                       navFilterUPP,
                                       (void *) &myData, // inClientData
                                       &dialog);
    }

    if (err == noErr)
        err = ::NavDialogRun(dialog);

    // clean up filter related data, etc.
    if (navFilterUPP)
        ::DisposeNavObjectFilterUPP(navFilterUPP);
    if (cfArray)
        ::CFRelease(cfArray);

    if (err != noErr)
        return wxID_CANCEL;

    NavReplyRecord navReply;
    err = ::NavDialogGetReply(dialog, &navReply);
    if (err == noErr && navReply.validRecord)
    {
        AEKeyword   theKeyword;
        DescType    actualType;
        Size        actualSize;
        FSRef       theFSRef;
        wxString thePath ;
        long count;
        ::AECountItems(&navReply.selection , &count);
        for (long i = 1; i <= count; ++i)
        {
            err = ::AEGetNthPtr(&(navReply.selection), i, typeFSRef, &theKeyword, &actualType,
                                &theFSRef, sizeof(theFSRef), &actualSize);
            if (err != noErr)
                break;

            CFURLRef fullURLRef;
            if (m_dialogStyle & wxSAVE)
            {
                CFURLRef parentURLRef = ::CFURLCreateFromFSRef(NULL, &theFSRef);

                if (parentURLRef)
                {
                    fullURLRef =
                        ::CFURLCreateCopyAppendingPathComponent(NULL,
                                parentURLRef,
                                navReply.saveFileName,
                                false);
                    ::CFRelease(parentURLRef);
                }
            }
            else
            {
                fullURLRef = ::CFURLCreateFromFSRef(NULL, &theFSRef);
            }
#ifdef __UNIX__
            CFURLPathStyle pathstyle = kCFURLPOSIXPathStyle;
#else
            CFURLPathStyle pathstyle = kCFURLHFSPathStyle;
#endif
            CFStringRef cfString = CFURLCopyFileSystemPath(fullURLRef, pathstyle);
            thePath = wxMacCFStringHolder(cfString).AsString(m_font.GetEncoding());
            if (!thePath)
            {
                ::NavDisposeReply(&navReply);
                return wxID_CANCEL;
            }
            m_path = thePath;
            m_paths.Add(m_path);
            m_fileName = wxFileNameFromPath(m_path);
            m_fileNames.Add(m_fileName);
        }
        // set these to the first hit
        m_path = m_paths[0];
        m_fileName = wxFileNameFromPath(m_path);
        m_dir = wxPathOnly(m_path);
    }
    ::NavDisposeReply(&navReply);

    return (err == noErr) ? wxID_OK : wxID_CANCEL;
#else // TARGET_CARBON

    NavDialogOptions           mNavOptions;
    NavObjectFilterUPP           mNavFilterUPP = NULL;
    NavPreviewUPP           mNavPreviewUPP = NULL ;
    NavReplyRecord           mNavReply;
    AEDesc               mDefaultLocation ;
    bool               mSelectDefault = false ;
    OSStatus            err = noErr ;
    // setup dialog

    mNavFilterUPP    = nil;
    mNavPreviewUPP    = nil;
    mSelectDefault    = false;
    mDefaultLocation.descriptorType = typeNull;
    mDefaultLocation.dataHandle     = nil;

    NavGetDefaultDialogOptions(&mNavOptions);
    wxMacStringToPascal( m_message , (StringPtr)mNavOptions.message ) ;
    wxMacStringToPascal( m_fileName , (StringPtr)mNavOptions.savedFileName ) ;

    // Set default location, the location
    //   that's displayed when the dialog
    //   first appears

    FSSpec location ;
    wxMacFilename2FSSpec( m_dir , &location ) ;

    err = ::AECreateDesc(typeFSS, &location, sizeof(FSSpec), &mDefaultLocation );

    if ( mDefaultLocation.dataHandle )
    {
        if (mSelectDefault)
        {
            mNavOptions.dialogOptionFlags |= kNavSelectDefaultLocation;
        } else {
            mNavOptions.dialogOptionFlags &= ~kNavSelectDefaultLocation;
        }
    }

    memset( &mNavReply , 0 , sizeof( mNavReply ) ) ;
    mNavReply.validRecord = false;
    mNavReply.replacing = false;
    mNavReply.isStationery = false;
    mNavReply.translationNeeded = false;
    mNavReply.selection.descriptorType = typeNull;
    mNavReply.selection.dataHandle = nil;
    mNavReply.keyScript = smSystemScript;
    mNavReply.fileTranslation = nil;
    mNavReply.version = kNavReplyRecordVersion ;

    // zero all data

    m_path = wxEmptyString ;
    m_fileName = wxEmptyString ;
    m_paths.Empty();
    m_fileNames.Empty();

    OpenUserDataRec            myData;
    MakeUserDataRec( &myData , m_wildCard ) ;
    myData.currentfilter = m_filterIndex ;
    if ( myData.extensions.GetCount() > 0 )
    {
        mNavOptions.popupExtension = (NavMenuItemSpecArrayHandle) NewHandle( sizeof( NavMenuItemSpec ) * myData.extensions.GetCount() ) ;
        myData.menuitems = mNavOptions.popupExtension ;
        for ( size_t i = 0 ; i < myData.extensions.GetCount() ; ++i )
        {
            (*mNavOptions.popupExtension)[i].version     = kNavMenuItemSpecVersion ;
            (*mNavOptions.popupExtension)[i].menuCreator = 'WXNG' ;
            // TODO : according to the new docs  -1 to 10 are reserved for the OS
            (*mNavOptions.popupExtension)[i].menuType    = i ;
            wxMacStringToPascal( myData.name[i] , (StringPtr)(*mNavOptions.popupExtension)[i].menuItemName ) ;
        }
    }
    if ( m_dialogStyle & wxSAVE )
    {
        myData.saveMode = true ;

        mNavOptions.dialogOptionFlags |= kNavDontAutoTranslate ;
        mNavOptions.dialogOptionFlags |= kNavDontAddTranslateItems ;

        err = ::NavPutFile(
                  &mDefaultLocation,
                  &mNavReply,
                  &mNavOptions,
                  sStandardNavEventFilter ,
                  NULL,
                  kNavGenericSignature,
                  &myData);                    // User Data
        m_filterIndex = myData.currentfilter ;
    }
    else
    {
        myData.saveMode = false ;

        mNavFilterUPP = NewNavObjectFilterUPP( CrossPlatformFilterCallback ) ;
        if ( m_dialogStyle & wxMULTIPLE )
            mNavOptions.dialogOptionFlags |= kNavAllowMultipleFiles ;
        else
            mNavOptions.dialogOptionFlags &= ~kNavAllowMultipleFiles ;

        err = ::NavGetFile(
                  &mDefaultLocation,
                  &mNavReply,
                  &mNavOptions,
                  sStandardNavEventFilter ,
                  mNavPreviewUPP,
                  mNavFilterUPP,
                  NULL ,
                  &myData);
        m_filterIndex = myData.currentfilter ;
    }

    DisposeNavObjectFilterUPP(mNavFilterUPP);
    if ( mDefaultLocation.dataHandle != nil )
    {
        ::AEDisposeDesc(&mDefaultLocation);
    }

    if ( (err != noErr) && (err != userCanceledErr) ) {
        return wxID_CANCEL ;
    }

    if (mNavReply.validRecord)
    {
        FSSpec  outFileSpec ;
        AEDesc specDesc ;
        AEKeyword keyWord ;

        long count ;
        ::AECountItems( &mNavReply.selection , &count ) ;
        for ( long i = 1 ; i <= count ; ++i )
        {
            OSErr err = ::AEGetNthDesc( &mNavReply.selection , i , typeFSS, &keyWord , &specDesc);
            if ( err != noErr )
            {
                m_path = wxT("") ;
                return wxID_CANCEL ;
            }
            outFileSpec = **(FSSpec**) specDesc.dataHandle;
            if (specDesc.dataHandle != nil) {
                ::AEDisposeDesc(&specDesc);
            }
            m_path = wxMacFSSpec2MacFilename( &outFileSpec ) ;

            m_paths.Add( m_path ) ;
            m_fileName = wxFileNameFromPath(m_path);
            m_fileNames.Add(m_fileName);
        }
        // set these to the first hit
        m_path = m_paths[ 0 ] ;
        m_fileName = wxFileNameFromPath(m_path);
        m_dir = wxPathOnly(m_path);
        NavDisposeReply( &mNavReply ) ;
        return wxID_OK ;
    }
    return wxID_CANCEL;
#endif // TARGET_CARBON
}
Exemplo n.º 14
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.º 15
0
// returns number of tracks imported
int Import(AudacityProject *project,
           wxString fName,
           WaveTrack *** tracks)
{
   bool success;
   int numTracks = 0;
   DirManager *dirManager = project->GetDirManager();
   wxWindow *parent = project;

   if (!fName.Right(3).CmpNoCase("aup")) {
      wxMessageBox("Audacity does not support importing Audacity Projects.\n"
                   "Please use the Open command instead of Import.",
                   "Import audio file", wxOK | wxCENTRE, parent);
      return 0;
   }

   if (!fName.Right(3).CmpNoCase("mid") ||
       !fName.Right(3).CmpNoCase("midi")) {
      wxMessageBox("Please use the Import MIDI command instead.",
                   "Import audio file", wxOK | wxCENTRE, parent);
      return 0;
   }
   
   bool isMP3 = false;

   if (!fName.Right(3).CmpNoCase("mp3") ||
       !fName.Right(3).CmpNoCase("mp2") ||
       !fName.Right(3).CmpNoCase("mpg") ||
       !fName.Right(4).CmpNoCase("mpeg"))
      isMP3 = true;
   
#ifdef __WXMAC__
   FSSpec spec;
   FInfo finfo;
   wxMacFilename2FSSpec(fName, &spec);
   if (FSpGetFInfo(&spec, &finfo) == noErr) {
      if (finfo.fdType == 'MP3 ' ||
          finfo.fdType == 'mp3 ' ||
          finfo.fdType == 'MPG ' ||
          finfo.fdType == 'MPG3' ||
          finfo.fdType == 'MPEG')
         isMP3 = true;
   }
#endif

   if (isMP3) {

     #ifdef MP3SUPPORT
      *tracks = new WaveTrack *[2];
      success =::ImportMP3(project, fName,
                           &(*tracks)[0], &(*tracks)[1]);
      if (!success)
         return 0;

      numTracks = 1;
      if ((*tracks)[1] != NULL)
         numTracks = 2;

      return numTracks;
     #else
   
      wxMessageBox("This version of Audacity was not compiled "
                   "with MP3 support.");
      return 0;
     #endif
   }

   if (!fName.Right(3).CmpNoCase("ogg")) {
     #ifdef USE_LIBVORBIS
      success =::ImportOGG(parent, fName, tracks, &numTracks, dirManager);
      if (!success)
         return 0;

      return numTracks;
     #else
      wxMessageBox("This version of Audacity was not compiled "
                   "with Ogg Vorbis support.", "Import Ogg Vorbis",
                   wxOK | wxCENTRE, parent);
      return 0;
     #endif
   }

   if (::IsPCM(fName)) {
      *tracks = new WaveTrack *[2];
      success =::ImportPCM(parent, fName,
                           &(*tracks)[0], &(*tracks)[1], dirManager);
      if (!success)
         return 0;

      numTracks = 1;
      if ((*tracks)[1] != NULL)
         numTracks = 2;

      return numTracks;
   }

   int action = wxMessageBox("Audacity did not recognize the type "
                             "of this file.\n"
                             "Would you like to try to import it as "
                             "raw PCM audio data?",
                             "Unknown file type",
                             wxYES_NO | wxICON_EXCLAMATION,
                             parent);

   if (action == wxYES) {
      *tracks = new WaveTrack *[2];
      success =::ImportRaw(parent, fName,
                           &(*tracks)[0], &(*tracks)[1], dirManager);
      if (!success)
         return 0;

      numTracks = 1;
      if ((*tracks)[1] != NULL)
         numTracks = 2;

      return numTracks;
   }

   return 0;
}
Exemplo n.º 16
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.º 17
0
   void LoadVSTPlugins() {
      wxString home = DirManager::GetHomeDir();
      wxString pathChar = DirManager::GetPathChar();
      wxString vstDirPath = home + pathChar + "vst";
      wxString fname;

      fname =
          wxFindFirstFile((const char *) (vstDirPath + pathChar + "*"));

      while (fname != "") {
         short resID;
         FSSpec spec;

         wxMacFilename2FSSpec(fname, &spec);
         resID = FSpOpenResFile(&spec, fsRdPerm);
         Handle codeH;

         int count = Count1Resources('aEff');
         for (int i = 0; i < count; i++) {
            CFragConnectionID connID;
            Ptr mainAddr;
            Str255 errName;
            Str255 fragName;
            char fragNameCStr[256];
            short resID;
            OSType resType;
            OSErr err;

            codeH = Get1IndResource('aEff', count);
            GetResInfo(codeH, &resID, &resType, fragName);
            DetachResource(codeH);
            HLock(codeH);

            err = GetMemFragment(*codeH,
                                 GetHandleSize(codeH),
                                 fragName,
                                 kPrivateCFragCopy,
                                 &connID, (Ptr *) & mainAddr, errName);

            if (err >= 0) {

               Ptr symbolAddress;
               CFragSymbolClass symbolClass;

               err =
                   FindSymbol(connID, "\pmain", &symbolAddress,
                              &symbolClass);
               if (!err) {
                  vstPluginMain pluginMain = (vstPluginMain) symbolAddress;

                  AEffect *theEffect;

                  theEffect = pluginMain(audioMaster);

                  if (theEffect->magic == kEffectMagic) {

                     memcpy(fragNameCStr, &fragName[1], fragName[0]);
                     fragNameCStr[fragName[0]] = 0;

                     VSTEffect *vst =
                         new VSTEffect(wxString(fragNameCStr), theEffect);
                     Effect::RegisterEffect(vst);
                  }
               }
            } else {
               HUnlock(codeH);
            }

            audacityVSTID++;

            // Don't HUnlock unless you don't want to keep it in memory
         }

         CloseResFile(resID);
         fname = wxFindNextFile();
      }
   }
Exemplo n.º 18
0
wxDragResult wxDropSource::DoDragDrop(int WXUNUSED(flags))
{
    wxASSERT_MSG( m_data, wxT("Drop source: no data") );
    
    if (!m_data)
        return (wxDragResult) wxDragNone;
    
    if (m_data->GetFormatCount() == 0)
        return (wxDragResult) wxDragNone;
    
    OSErr result;
    DragReference theDrag;
    RgnHandle dragRegion;
    if ((result = NewDrag(&theDrag)))
    {
        return wxDragNone ;
    }
    // add data to drag
    size_t formatCount = m_data->GetFormatCount() ;
    wxDataFormat *formats = new wxDataFormat[formatCount] ;
    m_data->GetAllFormats( formats ) ;
    ItemReference theItem = 1 ;
    for ( size_t i = 0 ; i < formatCount ; ++i )
    {
        size_t dataSize = m_data->GetDataSize( formats[i] ) ;
        Ptr dataPtr = new char[dataSize] ;
        m_data->GetDataHere( formats[i] , dataPtr ) ;
        OSType type = formats[i].GetFormatId() ;
        if ( type == 'TEXT' )
        {
            dataSize-- ;
            dataPtr[ dataSize ] = 0 ;
            wxString st( (wxChar*) dataPtr ) ;
            wxCharBuffer buf = st.mb_str( wxConvLocal) ;
            AddDragItemFlavor(theDrag, theItem, type , buf.data(), strlen(buf), 0);
        }
        else if (type == kDragFlavorTypeHFS )
        {
            HFSFlavor  theFlavor ;
            OSErr err = noErr;
            CInfoPBRec cat;
            
            wxMacFilename2FSSpec( dataPtr , &theFlavor.fileSpec ) ;
            
            cat.hFileInfo.ioNamePtr = theFlavor.fileSpec.name;
            cat.hFileInfo.ioVRefNum = theFlavor.fileSpec.vRefNum;
            cat.hFileInfo.ioDirID = theFlavor.fileSpec.parID;
            cat.hFileInfo.ioFDirIndex = 0;
            err = PBGetCatInfoSync(&cat);
            if (err == noErr )
            {
                theFlavor.fdFlags = cat.hFileInfo.ioFlFndrInfo.fdFlags;
                if (theFlavor.fileSpec.parID == fsRtParID) {
                    theFlavor.fileCreator = 'MACS';
                    theFlavor.fileType = 'disk';
                } else if ((cat.hFileInfo.ioFlAttrib & ioDirMask) != 0) {
                    theFlavor.fileCreator = 'MACS';
                    theFlavor.fileType = 'fold';
                } else {
                    theFlavor.fileCreator = cat.hFileInfo.ioFlFndrInfo.fdCreator;
                    theFlavor.fileType = cat.hFileInfo.ioFlFndrInfo.fdType;
                }
                AddDragItemFlavor(theDrag, theItem, type , &theFlavor, sizeof(theFlavor), 0);  
            }    
        }
        else
        {
            AddDragItemFlavor(theDrag, theItem, type , dataPtr, dataSize, 0);      
        }
        delete[] dataPtr ;
    }
    delete[] formats ;
    
    dragRegion = NewRgn();
    RgnHandle tempRgn = NewRgn() ;
    
    EventRecord* ev = NULL ;
#if !TARGET_CARBON // TODO
    ev = (EventRecord*) wxTheApp->MacGetCurrentEvent() ;
#else
    EventRecord rec ;
    ev = &rec ;
    wxMacConvertEventToRecord( (EventRef) wxTheApp->MacGetCurrentEvent() , &rec ) ;
#endif
    const short dragRegionOuterBoundary = 10 ;
    const short dragRegionInnerBoundary = 9 ;
    
    SetRectRgn( dragRegion , ev->where.h - dragRegionOuterBoundary , 
        ev->where.v  - dragRegionOuterBoundary ,
        ev->where.h + dragRegionOuterBoundary , 
        ev->where.v + dragRegionOuterBoundary ) ;
    
    SetRectRgn( tempRgn , ev->where.h - dragRegionInnerBoundary , 
        ev->where.v  - dragRegionInnerBoundary ,
        ev->where.h + dragRegionInnerBoundary , 
        ev->where.v + dragRegionInnerBoundary ) ;
    
    DiffRgn( dragRegion , tempRgn , dragRegion ) ;
    DisposeRgn( tempRgn ) ;    
    
    // TODO:work with promises in order to return data only when drag
    // was successfully completed
    
    gTrackingGlobals.m_currentSource = this ;
    result = TrackDrag(theDrag, ev , dragRegion);
    DisposeRgn(dragRegion);
    DisposeDrag(theDrag);
    gTrackingGlobals.m_currentSource = NULL ;
    
    KeyMap keymap;
    GetKeys(keymap);
    bool optionDown = keymap[1] & 4;
    wxDragResult dndresult = optionDown ? wxDragCopy : wxDragMove;
    return dndresult;
}
Exemplo n.º 19
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.º 20
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;
}