示例#1
0
void LoadLadspaEffect(wxString fname)
{
   wxLogNull logNo;
   LADSPA_Descriptor_Function mainFn = NULL;

   // As a courtesy to some plug-ins that might be bridges to
   // open other plug-ins, we set the current working
   // directory to be the plug-in's directory.

   wxString saveOldCWD = FROMFILENAME(::wxGetCwd());
   wxString prefix = ::wxPathOnly(fname);
   ::wxSetWorkingDirectory(FILENAME(prefix));

#if defined(__WXGTK__) || defined(__WXMAC__)

   void *libHandle = NULL;

   libHandle = dlopen(FILENAME(fname), RTLD_LAZY);
   
   mainFn = (LADSPA_Descriptor_Function)
      dlsym(libHandle, descriptorFnName);

#else
   // The following code uses the wxWindows DLL class, which does
   // not allow us to control the flags passed to dlopen().  This
   // leads to potential segfault bugs when plugins have conflicting
   // symbols, so until wxWindows adds this capability we are calling
   // dlopen() by hand under WXGTK, above...

   wxDllType libHandle = NULL;
     
   libHandle = wxDllLoader::LoadLibrary(FILENAME(fname));
   mainFn = (LADSPA_Descriptor_Function)
      wxDllLoader::GetSymbol(libHandle, descriptorFnName);
#endif

   if (mainFn) {
      int index = 0;
      const LADSPA_Descriptor *data;

      data = mainFn(index);
      while(data) {
         LadspaEffect *effect = new LadspaEffect(data);
         Effect::RegisterEffect(effect);
         
         // Get next plugin
         index++;
         data = mainFn(index);            
      }
   }

   ::wxSetWorkingDirectory(saveOldCWD);
}
示例#2
0
bool AudacityApp::InitCleanSpeech()
{
   wxString cwd = FROMFILENAME(::wxGetCwd());
   wxString presetsFromPrefs = gPrefs->Read(wxT("/Directories/PresetsDir"), wxT(""));
   wxString presets = wxT("");

   #ifdef __WXGTK__
   if (presetsFromPrefs.GetChar(0) != wxT('/'))
      presetsFromPrefs = wxT("");
   #endif

   #ifdef __WXMSW__
   wxString presetsDefaultLoc = cwd + wxT("\\presets");
   #else
   wxString presetsDefaultLoc = cwd + wxT("/presets");
   #endif

   // Stop wxWindows from printing its own error messages (not used ... does this really do anything?)
   wxLogNull logNo;

   // Try temp dir that was stored in prefs first
   if (presetsFromPrefs != wxT("")) {
      if (wxDirExists(FILENAME(presetsFromPrefs)))
         presets = presetsFromPrefs;
      else if (wxMkdir(FILENAME(presetsFromPrefs)))
         presets = presetsFromPrefs;
   }

   // If that didn't work, try the default location
   if ((presets == wxT("")) && (presetsDefaultLoc != wxT(""))) {
      if (wxDirExists(FILENAME(presetsDefaultLoc)))
         presets = presetsDefaultLoc;
      else if (wxMkdir(FILENAME(presetsDefaultLoc)))
         presets = presetsDefaultLoc;
   }

   if (presets == wxT("")) {
      // Failed
      wxMessageBox(_("Audacity could not find a place to store\n.csp CleanSpeech preset files\nAudacity is now going to exit. \nInstallation may be corrupt."));
      return false;
   }

   // The permissions don't always seem to be set on
   // some platforms.  Hopefully this fixes it...
   #ifdef __UNIX__
   chmod(FILENAME(presets).fn_str(), 0755);
   #endif

   gPrefs->Write(wxT("/Directories/PresetsDir"), presets);
   return true;
}
示例#3
0
void InitPreferences()
{
#if (AUDACITY_BRANDING == BRAND_UMIXIT)
   wxString vendorName = "Audacity";
   wxString appName = "UmixIt, powered by Audacity";
#elif (AUDACITY_BRANDING == BRAND_THINKLABS)
   wxString vendorName = "Audacity";
   wxString appName = "Thinklabs Phonocardiography, powered by Audacity";
#elif (AUDACITY_BRANDING == BRAND_AUDIOTOUCH)
   wxString vendorName = "Audacity";
   wxString appName = "Audacity_Voice";
#elif AUDACITY_NAME
   wxString appName = AUDACITY_NAME;
   wxString vendorName = AUDACITY_NAME;
#else
   wxString vendorName = "Audacity";
   wxString appName = "Audacity";
#endif

   wxTheApp->SetVendorName(vendorName);
   wxTheApp->SetAppName(appName);

   gPrefs = new wxConfig(appName);
   wxConfigBase::Set(gPrefs);

#ifdef __WXMAC__
#ifndef __UNIX__
   // This fixes changes in Mac filenames under wxWindows between versions
   // 0.95 and 0.96 of Audacity.
   wxString path;
   bool fix = false;   
   path = gPrefs->Read("/DefaultOpenPath", "");
   if (path.Length() > 0 && path.Left(1)=="/")
      fix = true;
   path = gPrefs->Read("/DefaultExportPath", "");
   if (path.Length() > 0 && path.Left(1)=="/")
      fix = true;
   path = gPrefs->Read("/Directories/TempDir", "");
   if (path.Length() > 0 && path.Left(1)=="/")
      fix = true;
   if (fix) {
      gPrefs->Write("/DefaultOpenPath", FROMFILENAME(::wxGetCwd()));
      gPrefs->Write("/DefaultExportPath", FROMFILENAME(::wxGetCwd()));
      gPrefs->Write("/Directories/TempDir", "");
      wxMessageBox(_("Some of your preferences were from an earlier version "
                     "of Audacity and have been reset."));
   }
#endif
#endif

   gPrefs->Write("/Version", (wxString)AUDACITY_VERSION_STRING);

   // BG: Make sure the users prefs are up to date
   // BG: Otherwise reset some of them to their defaults
   wxString prefsversion;
   prefsversion = gPrefs->Read("/PrefsVersion", "");

   if(prefsversion.CmpNoCase((wxString)AUDACITY_PREFS_VERSION_STRING))
   {
      // BG: Reset the prefs by removing them
      if(gPrefs->Exists("/Keyboard"))
         gPrefs->DeleteGroup("/Keyboard");
      if(gPrefs->Exists("/Locale"))
         gPrefs->DeleteGroup("/Locale");
      gPrefs->Write("/PrefsVersion", (wxString)AUDACITY_PREFS_VERSION_STRING);
   }
}
示例#4
0
void InitPreferences()
{
//MERGE:
//Everything now uses Audacity name for preferences.
//(Audacity and CleanSpeech the same program and use
//the same preferences file).
#ifdef AUDACITY_NAME
   wxString appName = wxT(AUDACITY_NAME);
   wxString vendorName = wxT(AUDACITY_NAME);
#else
   wxString vendorName = wxT("Audacity");
   wxString appName = wxT("Audacity");
#endif

   wxTheApp->SetVendorName(vendorName);
   wxTheApp->SetAppName(appName);

   gPrefs = new wxConfig(appName);
   wxConfigBase::Set(gPrefs);

#ifdef __WXMAC__
#ifndef __UNIX__
   // This fixes changes in Mac filenames under wxWindows between versions
   // 0.95 and 0.96 of Audacity.
   wxString path;
   bool fix = false;   
   path = gPrefs->Read(wxT("/DefaultOpenPath"), wxT(""));
   if (path.Length() > 0 && path.Left(1)==wxT("/"))
      fix = true;
   path = gPrefs->Read(wxT("/DefaultExportPath"), wxT(""));
   if (path.Length() > 0 && path.Left(1)==wxT("/"))
      fix = true;
   path = gPrefs->Read(wxT("/Directories/TempDir"), wxT(""));
   if (path.Length() > 0 && path.Left(1)==wxT("/"))
      fix = true;
   if (fix) {
      gPrefs->Write(wxT("/DefaultOpenPath"), FROMFILENAME(::wxGetCwd()));
      gPrefs->Write(wxT("/DefaultExportPath"), FROMFILENAME(::wxGetCwd()));
      gPrefs->Write(wxT("/Directories/TempDir"), wxT(""));
      wxMessageBox(_("Some of your preferences were from an earlier version "
                     "of Audacity and have been reset."));
   }
#endif
#endif

   gPrefs->Write(wxT("/Version"), wxString(wxT(AUDACITY_VERSION_STRING)));

   // BG: Make sure the users prefs are up to date
   // BG: Otherwise reset some of them to their defaults
   wxString prefsversion;
   prefsversion = gPrefs->Read(wxT("/PrefsVersion"), wxT(""));

   if(prefsversion.CmpNoCase(wxString(wxT(AUDACITY_PREFS_VERSION_STRING))))
   {
      // BG: Reset the prefs by removing them
      if(gPrefs->Exists(wxT("/Keyboard")))
         gPrefs->DeleteGroup(wxT("/Keyboard"));
      if(gPrefs->Exists(wxT("/Locale")))
         gPrefs->DeleteGroup(wxT("/Locale"));
      gPrefs->Write(wxT("/PrefsVersion"), wxString(wxT(AUDACITY_PREFS_VERSION_STRING)));
   }
}
示例#5
0
// The `main program' equivalent, creating the windows and returning the
// main frame
bool AudacityApp::OnInit()
{
   // Unused strings that we want to be translated, even though
   // we're not using them yet...
   wxString future1 = _("Master Gain Control");
   wxString future2 = _("Input Meter");
   wxString future3 = _("Output Meter");

   ::wxInitAllImageHandlers();

   wxFileSystem::AddHandler(new wxZipFSHandler);

   InitPreferences();

	#if defined(__WXMSW__) && !defined(__WXUNIVERSAL__) && !defined(__CYGWIN__)
		this->AssociateFileTypes(); 
	#endif

   //
   // Paths: set search path and temp dir path
   //

   wxString home = wxGetHomeDir();
   mAppHomeDir = home;

   // On Unix systems, the default temp dir is in /tmp.
   // Search path (in this order):
   // * The AUDACITY_PATH environment variable
   // * The current directory
   // * The user's .audacity-files directory in their home directory
   // * The "share" and "share/doc" directories in their install path
   #ifdef __WXGTK__
   defaultTempDir.Printf(wxT("/tmp/audacity1.2-%s"), wxGetUserId().c_str());
   wxString pathVar = wxGetenv(wxT("AUDACITY_PATH"));
   if (pathVar != wxT(""))
      AddMultiPathsToPathList(pathVar, audacityPathList);
   AddUniquePathToPathList(FROMFILENAME(::wxGetCwd()), audacityPathList);
   AddUniquePathToPathList(wxString::Format(wxT("%s/.audacity-files"),
                                            home.c_str()),
                           audacityPathList);
   #ifdef AUDACITY_NAME
      AddUniquePathToPathList(wxString::Format(wxT("%s/share/%s"),
                                               wxT(INSTALL_PREFIX), wxT(AUDACITY_NAME)),
                              audacityPathList);
      AddUniquePathToPathList(wxString::Format(wxT("%s/share/doc/%s"),
                                               wxT(INSTALL_PREFIX), wxT(AUDACITY_NAME)),
                              audacityPathList);
   #else
      AddUniquePathToPathList(wxString::Format(wxT("%s/share/audacity"),
                                               wxT(INSTALL_PREFIX)),
                              audacityPathList);
      AddUniquePathToPathList(wxString::Format(wxT("%s/share/doc/audacity"),
                                               wxT(INSTALL_PREFIX)),
                              audacityPathList);
   #endif

   AddUniquePathToPathList(wxString::Format(wxT("%s/share/locale"),
                                            wxT(INSTALL_PREFIX)),
                           audacityPathList);

   #endif

   wxFileName tmpFile;
   tmpFile.AssignTempFileName(wxT("nn"));
   wxString tmpDirLoc = tmpFile.GetPath(wxPATH_GET_VOLUME);
   ::wxRemoveFile(FILENAME(tmpFile.GetFullPath()));

   // On Mac and Windows systems, use the directory which contains Audacity.
   #ifdef __WXMSW__
   // On Windows, the path to the Audacity program is in argv[0]
   wxString progPath = wxPathOnly(argv[0]);
   AddUniquePathToPathList(progPath, audacityPathList);
   AddUniquePathToPathList(progPath+wxT("\\Languages"), audacityPathList);
   defaultTempDir.Printf(wxT("%s\\audacity_1_2_temp"), tmpDirLoc.c_str());
   #endif
   #ifdef __MACOSX__
   // On Mac OS X, the path to the Audacity program is in argv[0]
   wxString progPath = wxPathOnly(argv[0]);

   AddUniquePathToPathList(progPath, audacityPathList);
   // If Audacity is a "bundle" package, then the root directory is
   // the great-great-grandparent of the directory containing the executable.
   AddUniquePathToPathList(progPath+wxT("/../../../"), audacityPathList);

   AddUniquePathToPathList(progPath+wxT("/Languages"), audacityPathList);
   AddUniquePathToPathList(progPath+wxT("/../../../Languages"), audacityPathList);
   defaultTempDir.Printf(wxT("%s/audacity1.2-%s"),
                         tmpDirLoc.c_str(),
                         wxGetUserId().c_str());
   #endif
   #ifdef __MACOS9__
   // On Mac OS 9, the initial working directory is the one that
   // contains the program.
   wxString progPath = wxGetCwd();
   AddUniquePathToPathList(progPath, audacityPathList);
   AddUniquePathToPathList(progPath+wxT(":Languages"), audacityPathList);
   defaultTempDir.Printf(wxT("%s/audacity_1_2_temp"), tmpDirLoc.c_str());
   #endif

   // BG: Create a temporary window to set as the top window
   wxFrame *temporarywindow = new wxFrame(NULL, -1, wxT("temporarytopwindow"));
   SetTopWindow(temporarywindow);

   // Locale
   // wxWindows 2.3 has a much nicer wxLocale API.  We can make this code much
   // better once we move to wx 2.3/2.4.

   wxString lang = gPrefs->Read(wxT("/Locale/Language"), wxT(""));

   // Pop up a dialog the first time the program is run
   if (lang == wxT(""))
      lang = ChooseLanguage(NULL);

#ifdef NOT_RQD
//TIDY-ME: (CleanSpeech) Language prompt??
// The prompt for language only happens ONCE on a system.
// I don't think we should disable it JKC
   wxString lang = gPrefs->Read(wxT("/Locale/Language"), "en");  //lda

// Pop up a dialog the first time the program is run
//lda   if (lang == "")
//lda      lang = ChooseLanguage(NULL);
#endif
   gPrefs->Write(wxT("/Locale/Language"), lang);

   if (lang != wxT("en")) {
      wxLogNull nolog;
      mLocale = new wxLocale(wxT(""), lang, wxT(""), true, true);

      for(unsigned int i=0; i<audacityPathList.GetCount(); i++)
         mLocale->AddCatalogLookupPathPrefix(audacityPathList[i]);

#ifdef AUDACITY_NAME
      mLocale->AddCatalog(wxT(AUDACITY_NAME));
#else
      mLocale->AddCatalog(wxT("audacity"));
#endif
   } else
      mLocale = NULL;

   // Initialize internationalisation (number formats etc.)
   //
   // This must go _after_ creating the wxLocale instance because
   // creating the wxLocale instance sets the application-wide locale.
   Internat::Init();

   // Init DirManager, which initializes the temp directory
   // If this fails, we must exit the program.

   if (!InitTempDir()) {
      FinishPreferences();
      return false;
   }

   // More initialization
   InitCleanSpeech();

   InitDitherers();
   InitAudioIO();

   LoadEffects();

#ifdef __WXMAC__

   // On the Mac, users don't expect a program to quit when you close the last window.
   // Create an offscreen frame with a menu bar.  The frame should never
   // be visible, but when all other windows are closed, this menu bar should
   // become visible.

   gParentFrame = new wxFrame(NULL, -1, wxT("invisible"), wxPoint(5000, 5000), wxSize(100, 100));

   wxMenu *fileMenu = new wxMenu();
   fileMenu->Append(wxID_NEW, wxT("&New\tCtrl+N"));
   fileMenu->Append(wxID_OPEN, wxT("&Open...\tCtrl+O"));
   /* i18n-hint: Mac OS X shortcut should be Ctrl+, */
   fileMenu->Append(wxID_PREFERENCES, _("&Preferences...\tCtrl+,"));

   wxMenuBar *menuBar = new wxMenuBar();
   menuBar->Append(fileMenu, wxT("&File"));

   gParentFrame->SetMenuBar(menuBar);

   gParentFrame->Show();

   SetTopWindow(gParentFrame);

#endif

   SetExitOnFrameDelete(true);


   ///////////////////////////////////////////////////////////////////
   //////////////////////////////////////////////////////////////////
   //Initiate pointers to toolbars here, and create 
   //the toolbars that should be loaded at startup.

   gControlToolBarStub = 
      LoadToolBar( wxT(""),true,
      gParentWindow,ControlToolBarID);
   gMixerToolBarStub = 
      LoadToolBar( wxT("/GUI/EnableMixerToolBar"),true,
      gParentWindow,MixerToolBarID);
   gMeterToolBarStub = 
      LoadToolBar( wxT("/GUI/EnableMeterToolBar"),true,
      gParentWindow,MeterToolBarID);
   gEditToolBarStub = 
      LoadToolBar( wxT("/GUI/EnableEditToolBar"),true,
      gParentWindow,EditToolBarID);
   gTranscriptionToolBarStub = 
      LoadToolBar( wxT("/GUI/EnableTranscriptionToolBar"),false,
      gParentWindow,TranscriptionToolBarID);

   /// ToolBar Initiation Complete.
   ////////////////////////////////////////////////////////////////
   ////////////////////////////////////////////////////////////////

   AudacityProject *project = CreateNewAudacityProject(gParentWindow);
   SetTopWindow(project);

   delete temporarywindow;

   // Can't handle command-line args on Mac OS X yet...
   // Cygwin command-line parser below...
   #if !defined(__MACOSX__) && !defined(__CYGWIN__)
   // Parse command-line arguments
   if (argc > 1) {
      for (int option = 1; option < argc; option++) {
         if (!argv[option])
            continue;
         bool handled = false;

         if (!wxString(wxT("-help")).CmpNoCase(argv[option])) {
            wxPrintf(/* i18n-hint: '-help', '-test' and
                      '-blocksize' need to stay in English. */
                   _("Command-line options supported:\n  -help (this message)\n  -test (run self diagnostics)\n  -blocksize ### (set max disk block size in bytes)\n\nIn addition, specify the name of an audio file or Audacity project\nto open it.\n\n"));
            exit(0);
         }

         if (option < argc - 1 &&
             argv[option + 1] &&
             !wxString(wxT("-blocksize")).CmpNoCase(argv[option])) {
            long theBlockSize;
            if (wxString(argv[option + 1]).ToLong(&theBlockSize)) {
               if (theBlockSize >= 256 && theBlockSize < 100000000) {
                  wxFprintf(stderr, _("Using block size of %ld\n"),
                          theBlockSize);
                  Sequence::SetMaxDiskBlockSize(theBlockSize);
               }
            }
            option++;
            handled = true;
         }

         if (!handled && !wxString(wxT("-test")).CmpNoCase(argv[option])) {
            RunBenchmark(NULL);
            exit(0);
         }

         if (argv[option][0] == wxT('-') && !handled) {
            wxPrintf(_("Unknown command line option: %s\n"), argv[option]);
            exit(0);
         }

         if (!handled)
            project->OpenFile(argv[option]);

      }                         // for option...
   }                            // if (argc>1)
   #endif // not Mac OS X
	
   // Cygwin command line parser (by Dave Fancella)
   #if defined(__CYGWIN__)
   if (argc > 1) {
      int optionstart = 1;
      bool startAtOffset = false;
		
      // Scan command line arguments looking for trouble
      for (int option = 1; option < argc; option++) {
         if (!argv[option])
            continue;
         // Check to see if argv[0] is copied across other arguments.
         // This is the reason Cygwin gets its own command line parser.
         if (wxString(argv[option]).Lower().Contains(wxString(wxT("audacity.exe")))) {
            startAtOffset = true;
            optionstart = option + 1;
         }
      }
		
      for (int option = optionstart; option < argc; option++) {
         if (!argv[option])
            continue;
         bool handled = false;
         bool openThisFile = false;
         wxString fileToOpen;
			
         if (!wxString(wxT("-help")).CmpNoCase(argv[option])) {
            wxPrintf(/* i18n-hint: '-help', '-test' and
                      '-blocksize' need to stay in English. */
                   _("Command-line options supported:\n"
                     "  -help (this message)\n"
                     "  -test (run self diagnostics)\n"
                     "  -blocksize ### (set max disk block size in bytes)\n"
                     "\n"
                     "In addition, specify the name of an audio file or "
                     "Audacity project\n" "to open it.\n" "\n"));
            exit(0);
         }

         if (option < argc - 1 &&
             argv[option + 1] &&
             !wxString(wxT("-blocksize")).CmpNoCase(argv[option])) {
            long theBlockSize;
            if (wxString(argv[option + 1]).ToLong(&theBlockSize)) {
               if (theBlockSize >= 256 && theBlockSize < 100000000) {
                  wxFprintf(stderr, _("Using block size of %ld\n"),
                          theBlockSize);
                  Sequence::SetMaxDiskBlockSize(theBlockSize);
               }
            }
            option++;
            handled = true;
         }

         if (!handled && !wxString(wxT("-test")).CmpNoCase(argv[option])) {
            RunBenchmark(NULL);
            exit(0);
         }

         if (argv[option][0] == wxT('-') && !handled) {
            wxPrintf(_("Unknown command line option: %s\n"), argv[option]);
            exit(0);
         }
			
         if(handled)
            fileToOpen.Clear();
			
         if (!handled)
            fileToOpen = fileToOpen + wxT(" ") + argv[option];
         if(wxString(argv[option]).Lower().Contains(wxT(".aup")))
            openThisFile = true;
         if(openThisFile) {
            openThisFile = false;
            project->OpenFile(fileToOpen);
         }

      }                         // for option...
   }                            // if (argc>1)
   #endif // Cygwin command-line parser

   gInited = true;

   return TRUE;
}
示例#6
0
/*
 * This first function contains the code common to both
 * Export() and ExportLossy()
 *
 * For safety, if the file already exists it stores the filename
 * the user wants in actualName, and returns a temporary file name.
 * The calling function should rename the file when it's successfully
 * exported.
 */
wxString ExportCommon(AudacityProject *project,
                      wxString format, wxString defaultExtension,
                      bool selectionOnly, double *t0, double *t1,
                      bool *isStereo,
                      wxString &actualName)
{
   TrackList *tracks = project->GetTracks();

   /* First analyze the selected audio, perform sanity checks, and provide
    * information as appropriate. */

   /* Tally how many are right, left, mono, and make sure at
      least one track is selected (if selectionOnly==true) */

   int numSelected = 0, numLeft = 0, numRight = 0, numMono = 0;
   float earliestBegin = *t1;
   float latestEnd = *t0;

   TrackListIterator iter1(tracks);
   Track *tr = iter1.First();

   while (tr) {
      if (tr->GetKind() == Track::Wave) {
         if (tr->GetSelected() || !selectionOnly) {

            numSelected++;

            if (tr->GetChannel() == Track::LeftChannel)
               numLeft++;
            else if (tr->GetChannel() == Track::RightChannel)
               numRight++;
            else if (tr->GetChannel() == Track::MonoChannel)
            {
               // It's a mono channel, but it may be panned
               float pan = ((WaveTrack*)tr)->GetPan();
               
               if (pan == -1.0)
                  numLeft++;
               else if (pan == 1.0)
                  numRight++;
               else if (pan == 0)
                  numMono++;
               else {
                  numLeft++;
                  numRight++;
               }
            }
            
            if(tr->GetOffset() < earliestBegin)
               earliestBegin = tr->GetOffset();

            if(tr->GetEndTime() > latestEnd)
               latestEnd = tr->GetEndTime();

         }
      }

      tr = iter1.Next();
   }

   if(*t0 < earliestBegin)
      *t0 = earliestBegin;
   
   if(*t1 > latestEnd)
      *t1 = latestEnd;

   if (numSelected == 0 && selectionOnly) {
      wxMessageBox(_("No tracks are selected!\n"
                     "Choose Export... to export all tracks."));
      return "";
   }
   
   /* Detemine if exported file will be stereo or mono,
      and if mixing will occur */

   bool stereo = false;
   if (numRight > 0 || numLeft > 0)
      stereo = true;

   numRight += numMono;
   numLeft += numMono;
   
   if (numLeft > 1 || numRight > 1)
      if (stereo) {
         ShowWarningDialog(project, "MixStereo",
                           _("Your tracks will be mixed down to two "
                             "stereo channels in the exported file."));
      }
      else {
         ShowWarningDialog(project, "MixMono",
                           _("Your tracks will be mixed down to a "
                             "single mono channel in the exported file."));
      }

   /* Prepare and display the filename selection dialog */

   wxString path = gPrefs->Read("/DefaultExportPath",
                                FROMFILENAME(::wxGetCwd()));
   wxString nameOnly;
   wxString extension;
   wxString defaultName = project->GetName();
   wxString fName;
   wxString maskString;
   wxString endOfPathSep;

   if (defaultExtension.Left(1) == ".")
      defaultExtension =
         defaultExtension.Right(defaultExtension.Length()-1);

   maskString.Printf("%s files (*.%s)|*.%s|All files (*.*)|*.*", (const char *)format,
                     (const char *)defaultExtension, (const char *)defaultExtension);

   bool fileOkay;

   do {
      fileOkay = true;

      fName = defaultName + "." + defaultExtension;
      fName = wxFileSelector(wxString::Format(_("Save %s File As:"),
                                              (const char *) format),
                             path,
                             fName,       // default file name
                             defaultExtension,
                             maskString,
                             wxSAVE | wxOVERWRITE_PROMPT);
      
      if (fName.Length() >= 256) {
         wxMessageBox
            (_("Sorry, pathnames longer than 256 characters not supported."));
         return "";
      }
      
      if (fName == "")
         return "";

      ::wxSplitPath(fName, &path, &nameOnly, &extension);

      //
      // Make sure the user doesn't accidentally save the file
      // as an extension with no name, like just plain ".wav".
      //

      if ((nameOnly.Left(1)=="." && extension=="") ||
          (nameOnly=="" && extension!="")) {
         wxString prompt =
            _("Are you sure you want to save the file as \"")+
            ::wxFileNameFromPath(fName)+"\"?\n";
         
         int action = wxMessageBox(prompt,
                                   "Warning",
                                   wxYES_NO | wxICON_EXCLAMATION,
                                   project);
         
         fileOkay = (action == wxYES);
         continue;
      }

      //
      // Check the extension - add the default if it's not there,
      // and warn user if it's abnormal.
      //

      wxString defaultExtension3 = defaultExtension;
      if (defaultExtension.Length() > 3)
         defaultExtension = defaultExtension.Left(3);
      
      if (extension == "") {
         #ifdef __WXMSW__
         // Windows prefers 3-char uppercase extensions
         extension = defaultExtension;
         #else
         // Linux and Mac prefer lowercase extensions
         extension = defaultExtension.Lower();
         #endif
      }
      else if (extension.Upper() != defaultExtension.Upper() &&
               extension.Upper() != defaultExtension3.Upper()) {
         #ifdef __WXMSW__
         // Windows prefers 3-char extensions
         defaultExtension3 = defaultExtension3;
         #endif

         wxString prompt;
         prompt.Printf(_("You are about to save a %s file with the name %s.\n"
                       "Normally these files end in %s, and some programs "
                       "will not open files with nonstandard extensions.\n"
                       "Are you sure you want to save the file "
                       "under this name?"),
                       (const char *)format,
                       (const char *)("\""+nameOnly+"."+extension+"\""),
                       (const char *)("\"."+defaultExtension+"\""));

         int action = wxMessageBox(prompt,
                                   "Warning",
                                   wxYES_NO | wxICON_EXCLAMATION,
                                   project);

         if (action == wxYES)
            fileOkay = true;
         else {
            fileOkay = false;
            defaultName = nameOnly + "." + extension;
         }
      }

      if (path.Length() > 0 && path.Last() == wxFILE_SEP_PATH)
         endOfPathSep = "";
      else
         endOfPathSep = wxFILE_SEP_PATH;

      fName = path + endOfPathSep + 
         nameOnly + "." + extension;
   } while(!fileOkay);

   /*
    * Ensure that exporting a file by this name doesn't overwrite
    * one of the existing files in the project.  (If it would
    * overwrite an existing file, DirManager tries to rename the
    * existing file.)
    */

   if (!project->GetDirManager()->EnsureSafeFilename(wxFileName(fName)))
      return "";

   gPrefs->Write("/DefaultExportPath", path);

   *isStereo = stereo;

   /*
    * To be even MORE safe, return a temporary file name based
    * on this one...
    */

   actualName = fName;

   int suffix = 0;
   while(::wxFileExists(FILENAME(fName))) {
      fName = path + endOfPathSep + 
         nameOnly + wxString::Format("%d", suffix) + "." + extension;
      suffix++;
   }

   return fName;
}
示例#7
0
bool DirManager::SetProject(wxString & projPath, wxString & projName,
                            bool create)
{
    wxString oldPath = this->projPath;
    wxString oldName = this->projName;
    wxString oldFull = this->projFull;
    wxString oldLoc = this->projFull;
    if (oldLoc == "")
        oldLoc = temp;

    if (projPath == "")
        projPath = FROMFILENAME(::wxGetCwd());

    this->projPath = projPath;
    this->projName = projName;
    this->projFull = projPath + wxFILE_SEP_PATH + projName;

    if (create) {
        if (!wxPathExists(FILENAME(projFull)))
            if (!wxMkdir(FILENAME(projFull)))
                return false;

#ifdef __UNIX__
        chmod(FILENAME(projFull), 0775);
#endif

    } else {
#ifndef __WXMAC__
        if (!wxPathExists(FILENAME(projFull)))
            return false;
#endif
    }

    /* Move all files into this new directory.  Files which are
       "locked" get copied instead of moved.  (This happens when
       we perform a Save As - the files which belonged to the last
       saved version of the old project must not be moved,
       otherwise the old project would not be safe. */

    blockFileHash->BeginFind();
    wxNode *n = blockFileHash->Next();
    bool success = true;
    while(n && success) {
        BlockFile *b = (BlockFile *)n->GetData();

        if (b->IsLocked())
            success = CopyToNewProjectDirectory(b);
        else
            success = MoveToNewProjectDirectory(b);

        n = blockFileHash->Next();
    }

    if (!success) {
        // If the move failed, we try to move/copy as many files
        // back as possible so that no damage was done.  (No sense
        // in checking for errors this time around - there's nothing
        // that could be done about it.)
        // Likely causes: directory was not writeable, disk was full

        projFull = oldLoc;

        blockFileHash->BeginFind();
        wxNode *n = blockFileHash->Next();
        while(n) {
            BlockFile *b = (BlockFile *)n->GetData();
            MoveToNewProjectDirectory(b);
            n = blockFileHash->Next();
        }

        projFull = oldFull;
        projPath = oldPath;
        projName = oldName;

        return false;
    }

    return true;
}