Exemplo n.º 1
0
bool ImportPCM(wxWindow * parent,
               wxString fName, 
               WaveTrack ** channels[],
               int *numChannels,
               DirManager * dirManager)
{
   SF_INFO    info;
   SNDFILE   *fp;

   fp = sf_open_read(fName, &info);

   if (!fp) {
      char str[1000];
      sf_error_str((SNDFILE *)NULL, str, 1000);
      wxMessageBox(str);

      return false;
   }

   wxString progressStr;
   wxString formatName;
   for(int z=0; z<gNumPCMFormats; z++)
      if ((info.format & SF_FORMAT_TYPEMASK) == gPCMFormats[z].id)
         formatName = gPCMFormats[z].name;
   progressStr.Printf("Importing %s file...",
                      formatName);

   *numChannels = info.channels;
   *channels = new WaveTrack*[*numChannels];

   int c;
   for(c=0; c<*numChannels; c++) {
      (*channels)[c] = new WaveTrack(dirManager);
      (*channels)[c]->rate = info.samplerate;
      (*channels)[c]->name = TrackNameFromFileName(fName);
      (*channels)[c]->channel = VTrack::MonoChannel;
   }

   if (*numChannels == 2) {
      (*channels)[0]->channel = VTrack::LeftChannel;
      (*channels)[1]->channel = VTrack::RightChannel;
      (*channels)[0]->linked = true;
   }

   sampleCount fileTotalFrames = (sampleCount)info.samples;
   sampleCount maxBlockSize = (sampleCount)WaveTrack::GetIdealBlockSize();

   wxString copyEdit =
       gPrefs->Read("/FileFormats/CopyOrEditUncompressedData", "edit");

   // Fall back to "edit" if it doesn't match anything else
   bool doEdit = true;          
   if (copyEdit.IsSameAs("copy", false))
      doEdit = false;

   if (doEdit) {

      // If this mode has been selected, we form the tracks as
      // aliases to the files we're editing, i.e. ("foo.wav", 12000-18000)
      // instead of actually making fresh copies of the samples.

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

      bool cancelling = false;

      for (sampleCount i = 0; i < fileTotalFrames; i += maxBlockSize) {
         sampleCount blockLen = maxBlockSize;
         if (i + blockLen > fileTotalFrames)
            blockLen = fileTotalFrames - i;

         for(c=0; c<*numChannels; c++)
            (*channels)[c]->AppendAlias(fName, i, blockLen, c);

         if (!progress && wxGetElapsedTime(false) > 500) {
            progress =
                new wxProgressDialog("Import", progressStr,
                                     1000,
                                     parent,
                                     wxPD_CAN_ABORT |
                                     wxPD_REMAINING_TIME | wxPD_AUTO_HIDE);
         }
         if (progress) {
            cancelling = !progress->Update((int)((i*1000.0)/fileTotalFrames));

            if (cancelling)
               i = fileTotalFrames;
         }
      }

      //printf("Time elapsed: %d\n", wxGetElapsedTime());

      if (progress)
         delete progress;

      if (cancelling) {
         for(c=0; c<*numChannels; c++)
            delete (*channels)[c];
         delete[] (*channels);
         *channels = NULL;

         return false;
      }

      return true;
   }

   // Otherwise, we're in the "copy" mode, where we read in the actual
   // samples from the file and store our own local copy of the
   // samples in the tracks.

   sampleType *srcbuffer = new short[maxBlockSize * (*numChannels)];
   sampleType *buffer = new short[maxBlockSize];

   unsigned long framescompleted = 0;

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

   bool cancelling = false;

   long block;
   do {
      block = maxBlockSize;
      block = sf_readf_short(fp, srcbuffer, block);

      if (block) {
         for(c=0; c<(*numChannels); c++) {
            for(int j=0; j<block; j++)
               buffer[j] = srcbuffer[(*numChannels)*j+c];
            (*channels)[c]->Append(buffer, block);
         }

         framescompleted += block;
      }

      if (!progress && wxGetElapsedTime(false) > 500) {
         progress =
            new wxProgressDialog("Import", progressStr,
                                  1000,
                                  parent,
                                  wxPD_CAN_ABORT |
                                  wxPD_REMAINING_TIME | wxPD_AUTO_HIDE);
      }
      if (progress) {
         int progressvalue = (framescompleted > fileTotalFrames) ?
             fileTotalFrames : framescompleted;

         cancelling =
            !progress->Update((int)((progressvalue*1000.0)/fileTotalFrames));

         if (cancelling)
            block = 0;
      }
   } while (block > 0);

   sf_close(fp);

   //printf("Time elapsed: %d\n", wxGetElapsedTime());

   if (progress)
      delete progress;

   delete[] srcbuffer;
   delete[] buffer;

   if (cancelling) {
      for(c=0; c<*numChannels; c++)
         delete (*channels)[c];
      delete[] (*channels);
      *channels = NULL;

      return false;
   }

   return true;
}
Exemplo n.º 2
0
//------------------------------------------------------------------------------
// void MakeScriptActive(wxCommandEvent &event, bool isScriptModified)
//------------------------------------------------------------------------------
void GmatSavePanel::MakeScriptActive(wxCommandEvent &event, bool isScriptModified)
{
   #ifdef DEBUG_ACTIVE_SCRIPT
   MessageInterface::ShowMessage
      ("GmatSavePanel::MakeScriptActive() entered, isScriptModified=%d\n",
       isScriptModified);
   #endif
   
   bool saveScript = true;
   mSyncGui = false;
   mDelayBuild = false;
   GmatAppData *gmatAppData = GmatAppData::Instance();
   
   if (event.GetEventObject() == mSaveSyncButton ||
       event.GetEventObject() == mSaveSyncRunButton)
   {
      #ifdef DEBUG_ACTIVE_SCRIPT
      MessageInterface::ShowMessage("   Event is SaveSyncButton or SaveSyncRunButton\n");
      #endif
      if (gmatAppData->GetMainFrame()->IsAnimationRunning())
      {
         #ifdef DEBUG_ACTIVE_SCRIPT
         MessageInterface::ShowMessage("   Animation is running\n");
         #endif
         // @todo - Figure out why following happens. (LOJ: 2012.07.18)
         // It always runs mission before updating the resource tree.
         // It sometimes crashes when I tried SaveSyncRun again.
         // @note - Prompt user to stop animation first until issue is resolved.
         // Is there a timing issue? wxYield() didn't seem to solve the problem.
         // Use wxTimer?
         //===========================================================
         #if 0
         //===========================================================
         wxString action = "reload the GUI with the saved script?";
         if (event.GetEventObject() == mSaveSyncRunButton)
            action = "reload the GUI with the saved script and run?";
         
         int answer =
            wxMessageBox(wxT("GMAT is running the animation.\n"
                             "Are you sure you want to stop the animation and " + action),
                         wxT("Please confirm"), wxYES_NO);
         
         if (answer == wxYES)
         {
            // Stop animation
            gmatAppData->GetMainFrame()->StopAnimation();
         }
         else
            return;
         
         //===========================================================
         #else
         //===========================================================
        
         wxMessageBox(wxT("GMAT is running the animation.\n"
                          "Please stop the animation first."),
                      wxT("Warning"), wxOK);
         return;
         
         //===========================================================
         #endif
         //===========================================================
      }
      else
      {
         #ifdef DEBUG_ACTIVE_SCRIPT
         MessageInterface::ShowMessage("   Animation is not running\n");
         #endif
      }
      mSyncGui = true;
      mDelayBuild = true;
   }
   
   wxYield();
   
   #ifdef DEBUG_ACTIVE_SCRIPT
   MessageInterface::ShowMessage("   mIsScriptActive=%d\n", mIsScriptActive);
   #endif
   
   // If this is not an active script, prompt the user for setting active
   if (!mIsScriptActive)
   {
      #ifdef DEBUG_ACTIVE_SCRIPT
      MessageInterface::ShowMessage("   ==> Showing active script confirm message\n");
      #endif
      wxString makeActiveMsg = "The script file \"" + mFilename + "\" is not the active script.  "
         "Would you like to save, make it the active script, and load it into the GUI";
      if (event.GetEventObject() == mSaveSyncButton)
         makeActiveMsg = makeActiveMsg + "?";
      else if (event.GetEventObject() == mSaveSyncRunButton)
         makeActiveMsg = makeActiveMsg + " and run?";
      
      wxMessageDialog *msgDlg = new wxMessageDialog
         (this, makeActiveMsg, "Save active...", wxYES_NO | wxICON_QUESTION, wxDefaultPosition);
      int result = msgDlg->ShowModal();
      
      if (result == wxID_YES)
      {
         mSyncGui = true;
         saveScript = true;
         // If inactive script is modified, set it dirty so that change can be saved
         // before build (Fix for GMT-2843, LOJ: 2012.08.22)
         if (isScriptModified)
            theGuiManager->SetActiveScriptStatus(2);
      }
      else
      {
         mSyncGui = false;
         saveScript = false;
      }
   }
   
   #ifdef DEBUG_ACTIVE_SCRIPT
   MessageInterface::ShowMessage
      ("   mSyncGui=%d, saveScript=%d, mScriptFilename='%s'\n", mSyncGui, saveScript,
       mScriptFilename.c_str());
   #endif
   
   // No action is performed if user said no to sync GUI
   // See GMAT Software Specification, Script Editor section (LOJ: 2012.02.22)
   if (saveScript)
   {
      OnSave(event);
      if (mSaveCanceled)
      {
         #ifdef DEBUG_SAVE
         MessageInterface::ShowMessage
            ("GmatSavePanel::OnSave() leaving, user canceled SaveAs, mFilename='%s'\n", mFilename.c_str());
         #endif
         return;
      }
   }
   
   wxYield();
   
   // If continue building, set script file name and build script
   if (mSyncGui)
   {
      if (event.GetEventObject() == mSaveSyncButton)
      {
         if (gmatAppData->GetMainFrame()->SetScriptFileName(mScriptFilename.c_str()))
         {
            #ifdef DEBUG_ACTIVE_SCRIPT
            MessageInterface::ShowMessage
               ("   ==> Calling GmatMainFrame::OnScriptBuildObject()\n");
            #endif
            gmatAppData->GetMainFrame()->OnScriptBuildObject(event);
         }
      }
      else if (event.GetEventObject() == mSaveSyncRunButton)
      {
         if (gmatAppData->GetMainFrame()->SetScriptFileName(mScriptFilename.c_str()))
         {
            #ifdef DEBUG_ACTIVE_SCRIPT
            MessageInterface::ShowMessage
               ("   ==> Calling GmatMainFrame::OnScriptBuildAndRun()\n");
            #endif
            gmatAppData->GetMainFrame()->OnScriptBuildAndRun(event);
         }
      }
      // Make current script active script (Fix for GMT-206, LOJ: 2012.02.09)
      UpdateScriptActiveStatus(true);
      mSyncGui = false;
   }
   
   #ifdef DEBUG_ACTIVE_SCRIPT
   MessageInterface::ShowMessage("GmatSavePanel::MakeScriptActive() leaving\n");
   #endif
}
Exemplo n.º 3
0
EWXWEXPORT(int,ELJApp_Yield)()
{
        return (int)wxYield();
}
Exemplo n.º 4
0
void wxCYield()
{
    wxYield() ;
}
Exemplo n.º 5
0
bool CodeLiteApp::OnInit()
{
#if defined(__WXMSW__) && !defined(NDEBUG)
    SetAppName(wxT("codelite-dbg"));
#else
    SetAppName(wxT("codelite"));
#endif

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

    // block signal pipe
    sigset_t mask_set;
    sigemptyset(&mask_set);
    sigaddset(&mask_set, SIGPIPE);
    sigprocmask(SIG_SETMASK, &mask_set, NULL);

    // Handle sigchld
    CodeLiteBlockSigChild();

#ifdef __WXGTK__
    // Insall signal handlers
    signal(SIGSEGV, WaitForDebugger);
    signal(SIGABRT, WaitForDebugger);
#endif

#endif
    wxSocketBase::Initialize();

#if wxUSE_ON_FATAL_EXCEPTION
    // trun on fatal exceptions handler
    wxHandleFatalExceptions(true);
#endif

#ifdef __WXMSW__
    // as described in http://jrfonseca.dyndns.org/projects/gnu-win32/software/drmingw/
    // load the exception handler dll so we will get Dr MinGW at runtime
    m_handler = LoadLibrary(wxT("exchndl.dll"));

// Enable this process debugging priviliges
// EnableDebugPriv();
#endif

#ifdef USE_POSIX_LAYOUT
    clStandardPaths::Get().IgnoreAppSubDir("bin");
#endif

    // Init resources and add the PNG handler
    wxSystemOptions::SetOption(_T("msw.remap"), 0);
    wxSystemOptions::SetOption("msw.notebook.themed-background", 1);
    wxXmlResource::Get()->InitAllHandlers();
    wxImage::AddHandler(new wxPNGHandler);
    wxImage::AddHandler(new wxCURHandler);
    wxImage::AddHandler(new wxICOHandler);
    wxImage::AddHandler(new wxXPMHandler);
    wxImage::AddHandler(new wxGIFHandler);
    wxImage::AddHandler(new wxJPEGHandler);
    InitXmlResource();

    wxLog::EnableLogging(false);
    wxString homeDir(wxEmptyString);

    // parse command line
    wxCmdLineParser parser;
    parser.SetDesc(cmdLineDesc);
    parser.SetCmdLine(wxAppBase::argc, wxAppBase::argv);
    if(parser.Parse() != 0) {
        return false;
    }

    wxString newDataDir(wxEmptyString);
    if(parser.Found(wxT("d"), &newDataDir)) {
        clStandardPaths::Get().SetUserDataDir(newDataDir);
    }

    // check for single instance
    if(!IsSingleInstance(parser)) {
        return false;
    }

    if(parser.Found(wxT("h"))) {
        // print usage
        parser.Usage();
        return false;
    }

    if(parser.Found(wxT("v"))) {
// print version
#ifdef __WXMSW__
        ::wxMessageBox(wxString() << "CodeLite IDE v" << CODELITE_VERSION_STRING, "CodeLite");
#else
        wxPrintf("CodeLite IDE v%s\n", CODELITE_VERSION_STRING);
#endif
        return false;
    }

    if(parser.Found(wxT("n"))) {
        // Load codelite without plugins
        SetPluginLoadPolicy(PP_None);
    }

    wxString plugins;
    if(parser.Found(wxT("p"), &plugins)) {
        wxArrayString pluginsArr = ::wxStringTokenize(plugins, wxT(","));
        // Trim and make lower case
        for(size_t i = 0; i < pluginsArr.GetCount(); i++) {
            pluginsArr.Item(i).Trim().Trim(false).MakeLower();
        }

        // Load codelite without plugins
        SetAllowedPlugins(pluginsArr);
        SetPluginLoadPolicy(PP_FromList);
    }

    wxString newBaseDir(wxEmptyString);
    if(parser.Found(wxT("b"), &newBaseDir)) {
#if defined(__WXMSW__)
        homeDir = newBaseDir;
#else
        wxLogDebug("Ignoring the Windows-only --basedir option as not running Windows");
#endif
    }

    // Set the log file verbosity. NB Doing this earlier seems to break wxGTK debug output when debugging CodeLite
    // itself :/
    FileLogger::OpenLog("codelite.log", clConfig::Get().Read(kConfigLogVerbosity, FileLogger::Error));
    CL_DEBUG(wxT("Starting codelite..."));

    // Copy gdb pretty printers from the installation folder to a writeable location
    // this is  needed because python complies the files and in most cases the user
    // running codelite has no write permissions to /usr/share/codelite/...
    DoCopyGdbPrinters();

    // Since GCC 4.8.2 gcc has a default colored output
    // which breaks codelite output parsing
    // to disable this, we need to set GCC_COLORS to an empty
    // string.
    // https://sourceforge.net/p/codelite/bugs/946/
    // http://gcc.gnu.org/onlinedocs/gcc/Language-Independent-Options.html
    ::wxSetEnv("GCC_COLORS", "");

#if defined(__WXGTK__)
    if(homeDir.IsEmpty()) {
        homeDir = clStandardPaths::Get()
                      .GetUserDataDir(); // By default, ~/Library/Application Support/codelite or ~/.codelite
        if(!wxFileName::Exists(homeDir)) {
            wxLogNull noLog;
            wxFileName::Mkdir(homeDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
            wxCHECK_MSG(wxFileName::DirExists(homeDir), false, "Failed to create the requested data dir");
        }

        // Create the directory structure
        wxLogNull noLog;
        wxMkdir(homeDir);
        wxMkdir(homeDir + wxT("/lexers/"));
        wxMkdir(homeDir + wxT("/rc/"));
        wxMkdir(homeDir + wxT("/images/"));
        wxMkdir(homeDir + wxT("/templates/"));
        wxMkdir(homeDir + wxT("/config/"));
        wxMkdir(homeDir + wxT("/tabgroups/"));

        // copy the settings from the global location if needed
        wxString installPath(INSTALL_DIR, wxConvUTF8);
        if(!CopySettings(homeDir, installPath)) return false;
        ManagerST::Get()->SetInstallDir(installPath);

    } else {
        wxFileName fn(homeDir);
        fn.MakeAbsolute();
        ManagerST::Get()->SetInstallDir(fn.GetFullPath());
    }

#elif defined(__WXMAC__)
    homeDir = clStandardPaths::Get().GetUserDataDir();
    if(!wxFileName::Exists(homeDir)) {
        wxLogNull noLog;
        wxFileName::Mkdir(homeDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
        wxCHECK_MSG(wxFileName::DirExists(homeDir), false, "Failed to create the requested data dir");
    }

    {
        wxLogNull noLog;

        // Create the directory structure
        wxMkdir(homeDir);
        wxMkdir(homeDir + wxT("/lexers/"));
        wxMkdir(homeDir + wxT("/rc/"));
        wxMkdir(homeDir + wxT("/images/"));
        wxMkdir(homeDir + wxT("/templates/"));
        wxMkdir(homeDir + wxT("/config/"));
        wxMkdir(homeDir + wxT("/tabgroups/"));
    }

    wxString installPath(MacGetBasePath());
    ManagerST::Get()->SetInstallDir(installPath);
    // copy the settings from the global location if needed
    CopySettings(homeDir, installPath);

#else //__WXMSW__
    if(homeDir.IsEmpty()) { // did we got a basedir from user?
#ifdef USE_POSIX_LAYOUT
        homeDir = clStandardPaths::Get().GetDataDir() + wxT(INSTALL_DIR);
#else
        homeDir = ::wxGetCwd();
#endif
    }
    wxFileName fnHomdDir(homeDir + wxT("/"));

    // try to locate the menu/rc.xrc file
    wxFileName fn(homeDir + wxT("/rc"), wxT("menu.xrc"));
    if(!fn.FileExists()) {
        // we got wrong home directory
        wxFileName appFn(wxAppBase::argv[0]);
        homeDir = appFn.GetPath();
    }

    if(fnHomdDir.IsRelative()) {
        fnHomdDir.MakeAbsolute();
        homeDir = fnHomdDir.GetPath();
    }

    ManagerST::Get()->SetInstallDir(homeDir);
#endif

    // Use our persistence manager (which uses wxFileConfig instead of the registry...)
    m_persistencManager = new clPersistenceManager();
    wxPersistenceManager::Set(*m_persistencManager);

    // Make sure we have an instance if the keyboard manager allocated before we create the main frame class
    // (the keyboard manager needs to connect to the main frame events)
    clKeyboardManager::Get();

    ManagerST::Get()->SetOriginalCwd(wxGetCwd());
    ::wxSetWorkingDirectory(homeDir);
    // Load all of the XRC files that will be used. You can put everything
    // into one giant XRC file if you wanted, but then they become more
    // diffcult to manage, and harder to reuse in later projects.
    // The menubar
    if(!wxXmlResource::Get()->Load(DoFindMenuFile(ManagerST::Get()->GetInstallDir(), wxT("2.0")))) return false;

    // keep the startup directory
    ManagerST::Get()->SetStartupDirectory(::wxGetCwd());

    // set the performance output file name
    PERF_OUTPUT(wxString::Format(wxT("%s/codelite.perf"), wxGetCwd().c_str()).mb_str(wxConvUTF8));

    // Initialize the configuration file locater
    ConfFileLocator::Instance()->Initialize(ManagerST::Get()->GetInstallDir(), ManagerST::Get()->GetStartupDirectory());

    // set the CTAGS_REPLACEMENT environment variable
    wxSetEnv(wxT("CTAGS_REPLACEMENTS"), ManagerST::Get()->GetStartupDirectory() + wxT("/ctags.replacements"));

    long style = wxSIMPLE_BORDER;
#if defined(__WXMSW__) || defined(__WXGTK__)
    style |= wxFRAME_NO_TASKBAR;

#else // Mac
    wxUnusedVar(style);

#endif

// read the last frame size from the configuration file
// Initialise editor configuration files
#ifdef __WXMSW__
    {
        wxLogNull noLog;
        wxFileName::Mkdir(clStandardPaths::Get().GetUserDataDir(), wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
    }
#endif

    Manager* mgr = ManagerST::Get();
    EditorConfig* cfg = EditorConfigST::Get();
    cfg->SetInstallDir(mgr->GetInstallDir());

    // Update codelite revision and Version
    wxString strVersion = CODELITE_VERSION_STRING;
    cfg->Init(strVersion, wxT("2.0.2"));
    if(!cfg->Load()) {
        CL_ERROR(wxT("Failed to load configuration file: %s/config/codelite.xml"), wxGetCwd().c_str());
        return false;
    }

#if !defined(__WXMAC__) && defined(NDEBUG)
    // Now all image handlers have been added, show splash screen; but only when using Release builds of codelite
    GeneralInfo inf;
    cfg->ReadObject(wxT("GeneralInfo"), &inf);
    if(inf.GetFlags() & CL_SHOW_SPLASH) {
        wxBitmap bitmap;
        wxString splashName(clStandardPaths::Get().GetDataDir() + wxT("/images/splashscreen.png"));
        if(bitmap.LoadFile(splashName, wxBITMAP_TYPE_PNG)) {
            wxString mainTitle = CODELITE_VERSION_STRING;
            clSplashScreen::g_splashScreen = new clSplashScreen(clSplashScreen::CreateSplashScreenBitmap(bitmap),
                                                                wxSPLASH_CENTRE_ON_SCREEN | wxSPLASH_NO_TIMEOUT,
                                                                -1,
                                                                NULL,
                                                                wxID_ANY);
            wxYield();
        }
    }
#endif

#ifdef __WXGTK__
    bool redirect = clConfig::Get().Read(kConfigRedirectLogOutput, true);
    if(redirect) {
        // Redirect stdout/error to a file
        wxFileName stdout_err(clStandardPaths::Get().GetUserDataDir(), "codelite-stdout-stderr.log");
        FILE* new_stdout = ::freopen(stdout_err.GetFullPath().mb_str(wxConvISO8859_1).data(), "a+b", stdout);
        FILE* new_stderr = ::freopen(stdout_err.GetFullPath().mb_str(wxConvISO8859_1).data(), "a+b", stderr);
        wxUnusedVar(new_stderr);
        wxUnusedVar(new_stdout);
    }
#endif

    //---------------------------------------------------------
    // Set environment variable for CodeLiteDir (make it first
    // on the list so it can be used by other variables)
    //---------------------------------------------------------
    EvnVarList vars;
    EnvironmentConfig::Instance()->Load();
    EnvironmentConfig::Instance()->ReadObject(wxT("Variables"), &vars);

    vars.InsertVariable(wxT("Default"), wxT("CodeLiteDir"), ManagerST::Get()->GetInstallDir());
    EnvironmentConfig::Instance()->WriteObject(wxT("Variables"), &vars);

//---------------------------------------------------------

#ifdef __WXMSW__

    // Read registry values
    MSWReadRegistry();

#endif

    // Set up the locale if appropriate
    if(EditorConfigST::Get()->GetOptions()->GetUseLocale()) {
        int preferredLocale = wxLANGUAGE_ENGLISH;
        // The locale had to be saved as the canonical locale name, as the wxLanguage enum wasn't consistent between wx
        // versions
        wxString preferredLocalename = EditorConfigST::Get()->GetOptions()->GetPreferredLocale();
        if(!preferredLocalename.IsEmpty()) {
            const wxLanguageInfo* info = wxLocale::FindLanguageInfo(preferredLocalename);
            if(info) {
                preferredLocale = info->Language;
                if(preferredLocale == wxLANGUAGE_UNKNOWN) {
                    preferredLocale = wxLANGUAGE_ENGLISH;
                }
            }
        }

#if defined(__WXGTK__)
        // Cater for a --prefix= build. This gets added automatically to the search path for catalogues.
        // So hack in the standard ones too, otherwise wxstd.mo will be missed
        wxLocale::AddCatalogLookupPathPrefix(wxT("/usr/share/locale"));
        wxLocale::AddCatalogLookupPathPrefix(wxT("/usr/local/share/locale"));

#elif defined(__WXMSW__)
#ifdef USE_POSIX_LAYOUT
        wxLocale::AddCatalogLookupPathPrefix(clStandardPaths::Get().GetDataDir() + wxT("/share/locale"));
#else
        wxLocale::AddCatalogLookupPathPrefix(ManagerST::Get()->GetInstallDir() + wxT("\\locale"));
#endif
#endif

        // This has to be done before the catalogues are added, as otherwise the wrong one (or none) will be found
        m_locale.Init(preferredLocale);

        bool codelitemo_found = m_locale.AddCatalog(wxT("codelite"));
        if(!codelitemo_found) {
            m_locale.AddCatalog(wxT("CodeLite")); // Hedge bets re our spelling
        }

        if(!codelitemo_found) {
            // I wanted to 'un-init' the locale if no translations were found
            // as otherwise, in a RTL locale, menus, dialogs etc will be displayed RTL, in English...
            // However I couldn't find a way to do this
        }
    } else {
        // For proper encoding handling by system libraries it's needed to inialize locale even if UI translation is
        // turned off
        m_locale.Init(wxLANGUAGE_ENGLISH, wxLOCALE_DONT_LOAD_DEFAULT);
    }

// Append the binary's dir to $PATH. This makes codelite-cc available even for a --prefix= installation
#if defined(__WXMSW__)
    wxChar pathsep(wxT(';'));
#else
    wxChar pathsep(wxT(':'));
#endif
    wxString oldpath;
    wxGetEnv(wxT("PATH"), &oldpath);
    wxFileName execfpath(clStandardPaths::Get().GetExecutablePath());
    wxSetEnv(wxT("PATH"), oldpath + pathsep + execfpath.GetPath());
    wxString newpath;
    wxGetEnv(wxT("PATH"), &newpath);

    // If running under Cygwin terminal, adjust the environment variables
    AdjustPathForCygwinIfNeeded();

    // If running under Cygwin terminal, adjust the environment variables
    AdjustPathForMSYSIfNeeded();

    // Make sure that the colours and fonts manager is instantiated
    ColoursAndFontsManager::Get().Load();

    // Create the main application window
    clMainFrame::Initialize(parser.GetParamCount() == 0);
    m_pMainFrame = clMainFrame::Get();
    m_pMainFrame->Show(TRUE);
    SetTopWindow(m_pMainFrame);

    long lineNumber(0);
    parser.Found(wxT("l"), &lineNumber);
    if(lineNumber > 0) {
        lineNumber--;
    } else {
        lineNumber = 0;
    }

    for(size_t i = 0; i < parser.GetParamCount(); i++) {
        wxString argument = parser.GetParam(i);

        // convert to full path and open it
        wxFileName fn(argument);
        fn.MakeAbsolute(ManagerST::Get()->GetOriginalCwd());

        if(fn.GetExt() == wxT("workspace")) {
            ManagerST::Get()->OpenWorkspace(fn.GetFullPath());
        } else {
            clMainFrame::Get()->GetMainBook()->OpenFile(fn.GetFullPath(), wxEmptyString, lineNumber);
        }
    }

    wxLogMessage(wxString::Format(wxT("Install path: %s"), ManagerST::Get()->GetInstallDir().c_str()));
    wxLogMessage(wxString::Format(wxT("Startup Path: %s"), ManagerST::Get()->GetStartupDirectory().c_str()));

#ifdef __WXGTK__
    // Needed on GTK
    if(clMainFrame::Get()->GetMainBook()->GetActiveEditor() == NULL) {
        clMainFrame::Get()->GetOutputPane()->GetBuildTab()->SetFocus();
    }
#endif

    // Especially with the OutputView open, CodeLite was consuming 50% of a cpu, mostly in updateui
    // The next line limits the frequency of UpdateUI events to every 100ms
    wxUpdateUIEvent::SetUpdateInterval(100);

    return TRUE;
}
Exemplo n.º 6
0
void TextEntryTestCase::Editable()
{

#ifdef __WXGTK__
    // FIXME: For some reason this test regularly (although not always) fails
    //        in wxGTK build bot builds when testing wxBitmapComboBox, but I
    //        can't reproduce the failure locally. For now, disable this check
    //        to let the entire test suite pass in automatic tests instead of
    //        failing sporadically.
    if ( wxStrcmp(GetTestWindow()->GetClassInfo()->GetClassName(),
                  "wxBitmapComboBox") == 0 &&
           IsAutomaticTest() )
    {
        return;
    }
#endif // __WGTK__

    wxTextEntry * const entry = GetTestEntry();
    wxWindow * const window = GetTestWindow();

    EventCounter updated(window, wxEVT_TEXT);

    window->SetFocus();
    wxYield();

    // Check that we get the expected number of events.
    wxUIActionSimulator sim;
    sim.Text("abcdef");
    wxYield();

    CPPUNIT_ASSERT_EQUAL("abcdef", entry->GetValue());
    CPPUNIT_ASSERT_EQUAL(6, updated.GetCount());


    // And that the event carries the right value.
    TextEventHandler handler(window);

    sim.Text("g");
    wxYield();

    CPPUNIT_ASSERT_EQUAL("abcdefg", handler.GetLastString());

    // ... even if we generate the event programmatically and whether it uses
    // the same value as the control has right now
    entry->SetValue("abcdefg");
    CPPUNIT_ASSERT_EQUAL("abcdefg", handler.GetLastString());

    // ... or not
    entry->SetValue("abcdef");
    CPPUNIT_ASSERT_EQUAL("abcdef", handler.GetLastString());

    // Check that making the control not editable does indeed prevent it from
    // being edited.
    updated.Clear();

    entry->SetEditable(false);
    sim.Text("gh");
    wxYield();

    CPPUNIT_ASSERT_EQUAL("abcdef", entry->GetValue());
    CPPUNIT_ASSERT_EQUAL(0, updated.GetCount());
}
void LIB_EDIT_FRAME::OnPlotCurrentComponent( wxCommandEvent& event )
{
    wxString   fullFileName;
    wxString   file_ext;
    wxString   mask;

    LIB_PART*      part = GetCurPart();

    if( !part )
    {
        wxMessageBox( _( "No component" ) );
        return;
    }

    switch( event.GetId() )
    {
    case ID_LIBEDIT_GEN_PNG_FILE:
        {
            bool       fmt_is_jpeg = false; // could be selectable later. so keep this option.

            file_ext = fmt_is_jpeg ? wxT( "jpg" ) : wxT( "png" );
            mask     = wxT( "*." ) + file_ext;
            wxFileName fn( part->GetName() );
            fn.SetExt( file_ext );

            wxString pro_dir = wxPathOnly( Prj().GetProjectFullName() );

            fullFileName = EDA_FILE_SELECTOR( _( "Filename:" ), pro_dir,
                                             fn.GetFullName(), file_ext, mask, this,
                                             wxFD_SAVE, true );

            if( fullFileName.IsEmpty() )
                return;

            // calling wxYield is mandatory under Linux, after closing the file selector dialog
            // to refresh the screen before creating the PNG or JPEG image from screen
            wxYield();
            CreatePNGorJPEGFile( fullFileName, fmt_is_jpeg );
        }
        break;

    case ID_LIBEDIT_GEN_SVG_FILE:
        {
            file_ext = wxT( "svg" );
            mask     = wxT( "*." ) + file_ext;
            wxFileName fn( part->GetName() );
            fn.SetExt( file_ext );

            wxString pro_dir = wxPathOnly( Prj().GetProjectFullName() );

            fullFileName = EDA_FILE_SELECTOR( _( "Filename:" ), pro_dir,
                                              fn.GetFullName(), file_ext, mask, this,
                                              wxFD_SAVE, true );

            if( fullFileName.IsEmpty() )
                return;

            PAGE_INFO pageSave = GetScreen()->GetPageSettings();
            PAGE_INFO pageTemp = pageSave;

            wxSize componentSize = part->GetBoundingBox( m_unit, m_convert ).GetSize();

            // Add a small margin to the plot bounding box
            pageTemp.SetWidthMils(  int( componentSize.x * 1.2 ) );
            pageTemp.SetHeightMils( int( componentSize.y * 1.2 ) );

            GetScreen()->SetPageSettings( pageTemp );
            SVG_PlotComponent( fullFileName );
            GetScreen()->SetPageSettings( pageSave );
        }
        break;
    }
}
Exemplo n.º 8
0
        bool OnInit()
        {

#if DEBUG
            wxLogWarning("MODO DEBUG");
#else
            wxSetAssertHandler(NULL);
#endif

            //i18n/l10n:
            //20120603: Change suggested by Juan Pizarro to solve the i18n bug in some Windows and Linux machines:
            //if ( !locale.Init(wxLANGUAGE_DEFAULT, wxLOCALE_CONV_ENCODING) )

#if !defined(linux)
            wxLogWarning("Esta version esta desarrollada exclusivamente para Linux");
            return true;
#endif


/*
#if defined (linux)
            wxLogNull logNo;
#endif
*/
            /*
            if ( !locale.Init(wxLANGUAGE_ENGLISH, wxLOCALE_CONV_ENCODING) )
                wxLogWarning(_("Error #1: This language is not supported by the system."));
            */

            /*
            wxString lanPath(wxStandardPaths::Get().GetExecutablePath().BeforeLast(wxFileName::GetPathSeparator()) +
                             wxFileName::GetPathSeparator() + wxString("GUI") +
                             wxFileName::GetPathSeparator() + wxString("Texts") //##Unhardcode this in the future? I'm not sure...
                            );
            */


            //wxString lanPath = wxStandardPaths::Get().GetExecutablePath().BeforeLast(wxFileName::GetPathSeparator()) + "/../../GUI/Texts/";
            //wxLocale::AddCatalogLookupPathPrefix(lanPath);

	    wxString lanPath = "/usr/share";
	    locale.AddCatalogLookupPathPrefix(lanPath);


            //Por defecto debe levantar en Castellano
            //wxString initialCatalogName("es.mo");

	    wxString initialCatalogName = "Minibloq.mo";

            //wxString initialCatalogName("es.mo"); //##Debug...
            if (!locale.AddCatalog(initialCatalogName))
            {
                //##Future: See if future wxLocale implementations solve this problem:
                wxLogWarning(   _("Error #1: The installation path\n\n\"") + wxStandardPaths::Get().GetExecutablePath() +
                                _("\"\n\ncontains non-English chars.\n") +
                                _("Please try to install Minibloq on a location without this kind of chars. ") +
                                _("Otherwise, the program will run, but the translation system will not work properly.")
                            );
                //wxLogWarning(_("Error #2: Can't load ") + initialCatalogName);
                printf("NO ENCUENTRO EL CATALOGO\n");
            }

            MainFrame* frame = NULL;

            wxString caption = wxString(wxString("miniBloq ") + MINIBLOQ_VERSION);
            wxPoint framePosition = wxDefaultPosition;
            wxSize frameSize = wxDefaultSize;
            long style = wxDEFAULT_FRAME_STYLE;

            //Default values:
            initialFrameX = 0;
            initialFrameY = 0;
            initialFrameHeight = 600;
            initialFrameWidth = 800;
            maximized = true;
            centered = true;
            strBoard = wxString("");

            //Try to read the configuration file:
            readConfig();

            //Priorities:
            //  maximized has priority over all the other pos and size settings.
            //  centered has priority over x and y settings.
            if (maximized)
                style = style | wxMAXIMIZE;
            if ( (initialFrameWidth > 0) && (initialFrameHeight > 0) )
            {
                framePosition = wxPoint(initialFrameX, initialFrameY);
                frameSize = wxSize(initialFrameWidth, initialFrameHeight);
            }

            //TODO: Chequeo de errores
	    wxString execPath = wxStandardPaths::Get().GetExecutablePath().BeforeLast(wxFileName::GetPathSeparator()); 
	    wxString splashImg = execPath + "/../../GUI/Images/minibloqSplash.png";

            wxBitmap splashPng;
            splashPng.LoadFile(splashImg);
            wxSplashScreen* splash = new wxSplashScreen(splashPng,
                                                        wxSPLASH_CENTRE_ON_SCREEN|wxSPLASH_TIMEOUT,
                                                        3000,
                                                        NULL,
                                                        -1,
                                                        wxDefaultPosition,
                                                        wxDefaultSize,
                                                        wxBORDER_SIMPLE|wxSTAY_ON_TOP);

            wxYield();


            frame = new MainFrame(  NULL,
                                    wxID_ANY,
                                    locale,
                                    lanPath,
                                    initialCatalogName,
                                    caption,
                                    strBoard,
                                    framePosition,
                                    frameSize,
                                    style
                                  );
            /*## Future: Full screen:
            wxFrame* frame = new MainFrame(NULL,
                                         wxID_ANY,
                                         wxString("Minibloq v1.0"),
                                         wxDefaultPosition,
                                         wxSize(1280, 800),
                                         wxCLIP_CHILDREN);
            */
            if (frame)
            {
                if (centered)
                    frame->Centre();
                frame->setCentered(centered);

                SetTopWindow(frame);
                frame->Show();
                if (maximized)
                {
                    frame->Maximize();
                }
                if (argc > 0)
                {
                    wxString fileName = argv[1];
                    if (wxFile::Exists(fileName))
                    {
                        frame->loadFileComponent(fileName);
                    }
                }
            }

            return true;
        }
Exemplo n.º 9
0
TEST_F(GuiTest,ClockTest) {

	wxDateTime d = wxDateTime::Now();
	wxUIActionSimulator act;

	app->frame->m_choice1->SetFocus();
	wxYield();
	act.Select(app->frame->m_choice1->GetString(1));
	wxYield();
	ASSERT_EQ(app->frame->Slot1->GetLabel(), d.Format(wxT("%H:%M"))); // Time Only

	app->frame->m_choice1->SetFocus();
	wxYield();
	act.Select(app->frame->m_choice1->GetString(2));
	wxYield();
	ASSERT_EQ(app->frame->Slot1->GetLabel(), d.Format(wxT("%a %d %b %Y"))); // date only

	app->frame->m_choice1->SetFocus();
	wxYield();
	act.Select(app->frame->m_choice1->GetString(3));
	wxYield();
	ASSERT_EQ(app->frame->Slot1->GetLabel(), d.Format(wxT("%a %d %b %Y")));
	ASSERT_EQ(app->frame->Slot2->GetLabel(), d.Format(wxT("%H:%M"))); // date and time

	app->frame->m_choice1->SetFocus();
	wxYield();
	act.Select(app->frame->m_choice1->GetString(4));
	wxYield();
	ASSERT_EQ(app->frame->Slot1->GetLabel(), d.Format(wxT("%H:%M")));
	ASSERT_EQ(app->frame->Slot2->GetLabel(), d.Format(wxT("%a %d %b %Y"))); // time and date

	app->frame->amPm->SetFocus();
	wxYield();
	act.Char(WXK_SPACE);
	wxYield();

	if (d.GetHour() > 12)
		ASSERT_EQ(app->frame->Slot1->GetLabel(), d.Format(wxT("%I:%M PM")));

	else{
		ASSERT_EQ(app->frame->Slot1->GetLabel(), d.Format(wxT("%I:%M AM")));
	}// per AM/PM

	app->frame->DateCheck->SetFocus();
	wxYield();
	act.Char(WXK_SPACE);
	wxYield();
	ASSERT_EQ(app->frame->Slot2->GetLabel(),d.Format(wxT("%x"))); // per date checkbox

}
Exemplo n.º 10
0
void EDA_3D_CANVAS::TakeScreenshot( wxCommandEvent& event )
{
    static wxFileName fn;                 // Remember path between saves during this session only.
    wxString          FullFileName;
    wxString          file_ext, mask;
    bool              fmt_is_jpeg = false;

    // First time path is set to the project path.
    if( !fn.IsOk() )
        fn = Parent()->Prj().GetProjectFullName();

    if( event.GetId() == ID_MENU_SCREENCOPY_JPEG )
        fmt_is_jpeg = true;

    if( event.GetId() != ID_TOOL_SCREENCOPY_TOCLIBBOARD )
    {
        file_ext     = fmt_is_jpeg ? wxT( "jpg" ) : wxT( "png" );
        mask         = wxT( "*." ) + file_ext;
        fn.SetExt( file_ext );

        FullFileName = EDA_FILE_SELECTOR( _( "3D Image File Name:" ), fn.GetPath(),
                                          fn.GetFullName(), file_ext, mask, this,
                                          wxFD_SAVE | wxFD_OVERWRITE_PROMPT, true );

        if( FullFileName.IsEmpty() )
            return;

        fn = FullFileName;

        // Be sure the screen area destroyed by the file dialog is redrawn before making
        // a screen copy.
        // Without this call, under Linux the screen refresh is made to late.
        wxYield();
    }

    struct viewport_params
    {
        GLint originx;
        GLint originy;
        GLint x;
        GLint y;
    } viewport;

    // Be sure we have the latest 3D view (remember 3D view is buffered)
    Refresh();
    wxYield();

    // Build image from the 3D buffer
    wxWindowUpdateLocker noUpdates( this );
    glGetIntegerv( GL_VIEWPORT, (GLint*) &viewport );

    unsigned char*       pixelbuffer = (unsigned char*) malloc( viewport.x * viewport.y * 3 );
    unsigned char*       alphabuffer = (unsigned char*) malloc( viewport.x * viewport.y );
    wxImage image( viewport.x, viewport.y );

    glPixelStorei( GL_PACK_ALIGNMENT, 1 );
    glReadBuffer( GL_BACK_LEFT );
    glReadPixels( viewport.originx, viewport.originy,
                  viewport.x, viewport.y,
                  GL_RGB, GL_UNSIGNED_BYTE, pixelbuffer );
    glReadPixels( viewport.originx, viewport.originy,
                  viewport.x, viewport.y,
                  GL_ALPHA, GL_UNSIGNED_BYTE, alphabuffer );

    image.SetData( pixelbuffer );
    image.SetAlpha( alphabuffer );
    image = image.Mirror( false );
    wxBitmap bitmap( image );

    if( event.GetId() == ID_TOOL_SCREENCOPY_TOCLIBBOARD )
    {
        if( wxTheClipboard->Open() )
        {
            wxBitmapDataObject* dobjBmp = new wxBitmapDataObject( bitmap );

            if( !wxTheClipboard->SetData( dobjBmp ) )
                wxMessageBox( _( "Failed to copy image to clipboard" ) );

            wxTheClipboard->Flush();    /* the data in clipboard will stay
                                         * available after the application exits */
            wxTheClipboard->Close();
        }
    }
    else
    {
        wxImage image = bitmap.ConvertToImage();

        if( !image.SaveFile( FullFileName,
                             fmt_is_jpeg ? wxBITMAP_TYPE_JPEG : wxBITMAP_TYPE_PNG ) )
            wxMessageBox( _( "Can't save file" ) );

        image.Destroy();
    }
}
Exemplo n.º 11
0
bool SimpleFTP::UploadFile(std::string file, std::string folder, std::string newfilename, bool backup, bool binary, wxWindow* parent)
{
    static log4cpp::Category &logger_base = log4cpp::Category::getInstance(std::string("log_base"));
    if (!IsConnected()) return false;

    if (newfilename == "") newfilename = file;

    ftp.ChDir(folder);

    if (binary)
    {
        ftp.SetBinary();
    }
    else
    {
        ftp.SetAscii();
    }

    wxProgressDialog progress("FTP Upload", wxString(file.c_str()), 100, parent, wxPD_CAN_ABORT | wxPD_APP_MODAL | wxPD_AUTO_HIDE);
    progress.Show();

    bool cancelled = false;

    progress.Update(0, wxEmptyString, &cancelled);

    wxFileName fn(wxString(file.c_str()));
    wxString ext = fn.GetExt();
    if (ext != "") ext = "." + ext;
    wxString basefile = fn.GetName() + ext;
    wxFileName fnnew(wxString(newfilename.c_str()));
    wxString extnew = fnnew.GetExt();
    if (extnew != "") extnew = "." + extnew;
    wxString basefilenew = fnnew.GetName() + extnew;

    wxLogNull logNo; //kludge: avoid "error 0" message from wxWidgets

    //logger_base.info("FTP current directory %s.", (const char *)ftp.Pwd().c_str());

    if (backup)
    {
        int size = ftp.GetFileSize((folder + "/" + basefile).c_str());
        if (size == -1)
        {
            // file not there so no need to backup
        }
        else
        {
            wxDateTime dt = wxDateTime::Now();
            wxString tgtfile = wxString((folder + "/" + basefilenew).c_str()) + "_" + dt.Format("%Y%m%d_%H%M%S");
            logger_base.info("FTP Backing up file %s to %s.", (const char *)(folder + "/" + basefilenew).c_str(), (const char *)tgtfile.c_str());
            ftp.Rename((folder + "/" + basefilenew).c_str(), tgtfile);
            if (!cancelled)
            {
                cancelled = progress.WasCancelled();
            }
        }
    }

    wxFile in;
    in.Open(wxString(file.c_str()));
    if (in.IsOpened())
    {
        logger_base.info("FTP Uploading file %s to %s.", (const char *)file.c_str(), (const char *)(folder + "/" + basefilenew).c_str());
        wxFileOffset length = in.Length();
        wxFileOffset done = 0;
        wxSocketOutputStream *out = dynamic_cast<wxSocketOutputStream*>(ftp.GetOutputStream((folder + "/" + basefilenew).c_str()));
        wxSocketBase sock;
        MySocketOutputStream sout(sock, (MySocketOutputStream*)out);
        if (out)
        {
            uint8_t buffer[8192]; // 8KB at a time
            int lastDone = 0;
            while (!in.Eof() && !cancelled)
            {
                ssize_t read = in.Read(&buffer[0], sizeof(buffer));
                done += read;

                int bufPos = 0;
                while (read) {
                    out->Write(&buffer[bufPos], read);
                    ssize_t written = out->LastWrite();
                    bufPos += written;
                    read -= written;
                }
                ssize_t donePct = done * 100;
                donePct = donePct / length;
                if (donePct != lastDone) {
                    lastDone = donePct;
                    cancelled = !progress.Update(donePct, wxEmptyString, &cancelled);
                    wxYield();
                }
            }
            if (in.Eof())
            {
                progress.Update(100, wxEmptyString, &cancelled);
                logger_base.info("   FTP Upload of file %s done.", (const char *)file.c_str());
            }
            else
            {
                progress.Update(100, wxEmptyString, &cancelled);
                logger_base.warn("   FTP Upload of file %s cancelled.", (const char *)file.c_str());
            }
            in.Close();
            out->Close();
            delete out;
            if (ftp.GetFileSize((folder + "/" + basefilenew).c_str()) != length)
            {
                logger_base.warn("   FTP Upload of file %s failed. Source size (%d) != Destination Size (%d)", (const char *)file.c_str(), length, ftp.GetFileSize((folder + "/" + basefile).c_str()));
            }
        }
        else
        {
            wxMessageBox("FTP Upload of file failed to create the target file.");
            progress.Update(100, wxEmptyString, &cancelled);
            logger_base.error("   FTP Upload of file %s failed as file %s could not be created on FPP.", (const char *)file.c_str(), (const char *)(folder + "/" + basefilenew).c_str());
        }
    }
    else
    {
        wxMessageBox("FTP Upload of file failed to open the file.");
        progress.Update(100, wxEmptyString, &cancelled);
        logger_base.error("   FTP Upload of file %s failed as file could not be opened.", (const char *)file.c_str());
    }

    if (!cancelled)
    {
        cancelled = progress.WasCancelled();
    }

    return cancelled;
}
Exemplo n.º 12
0
void MiscGUIFuncsTestCase::FindWindowAtPoint()
{
    wxWindow* const parent = wxTheApp->GetTopWindow();
    CPPUNIT_ASSERT( parent );

    // Set a label to allow distinguishing it from the other windows in the
    // assertion messages.
    parent->SetLabel("parent");

    wxWindow* btn1 = new TestButton(parent, "1", wxPoint(10, 10));
    wxWindow* btn2 = new TestButton(parent, "2", wxPoint(10, 90));
    wxWindow* btn3 = new TestButton(btn2, "3", wxPoint(20, 20));

    // We need this to realize the windows created above under wxGTK.
    wxYield();

    CPPUNIT_ASSERT_EQUAL_MESSAGE
    (
        "No window for a point outside of the window",
        "NONE",
        GetLabelOfWindowAtPoint(parent, 900, 900)
    );

    CPPUNIT_ASSERT_EQUAL_MESSAGE
    (
        "Point over a child control corresponds to it",
        btn1->GetLabel(),
        GetLabelOfWindowAtPoint(parent, 11, 11)
    );

    CPPUNIT_ASSERT_EQUAL_MESSAGE
    (
        "Point outside of any child control returns the TLW itself",
        parent->GetLabel(),
        GetLabelOfWindowAtPoint(parent, 5, 5)
    );

    btn2->Disable();
    CPPUNIT_ASSERT_EQUAL_MESSAGE
    (
        "Point over a disabled child control still corresponds to it",
        btn2->GetLabel(),
        GetLabelOfWindowAtPoint(parent, 11, 91)
    );

    btn2->Hide();
    CPPUNIT_ASSERT_EQUAL_MESSAGE
    (
        "Point over a hidden child control doesn't take it into account",
        parent->GetLabel(),
        GetLabelOfWindowAtPoint(parent, 11, 91)
    );

    btn2->Show();
    CPPUNIT_ASSERT_EQUAL_MESSAGE
    (
        "Point over child control corresponds to the child",
        btn3->GetLabel(),
        GetLabelOfWindowAtPoint(parent, 31, 111)
    );

    btn3->Disable();
    CPPUNIT_ASSERT_EQUAL_MESSAGE
    (
        "Point over disabled child controls still corresponds to this child",
        btn3->GetLabel(),
        GetLabelOfWindowAtPoint(parent, 31, 111)
    );

    btn1->Destroy();
    btn2->Destroy();
    // btn3 was already deleted when its parent was
}
Exemplo n.º 13
0
/**
 * @function OnToolMovie
 * @brief
 * @date 2011-10-13
 */
void GRIPFrame::OnToolMovie(wxCommandEvent& event){
    wxString dirname = wxDirSelector(wxT("Choose output directory for movie pictures:")); // , "", wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST

    if ( dirname.empty() ){ // filename
        std::cout << "No Directory Selected" << std::endl;
	return;
    }

    string path = string(dirname.mb_str());

    char *buf = new char[1000];

	//Create a new Viewer Window
	wxFrame *movieFrame = new wxFrame(NULL,wxID_ANY, wxT("MovieWindow"),wxPoint(0, 0), wxSize(renderW,renderH),wxDEFAULT_FRAME_STYLE & ~ (wxRESIZE_BORDER | wxMAXIMIZE_BOX));
	//#ifndef WIN32 // Weird hack to make wxWidgets work in Linux
	movieFrame->Show();
	//#endif

	int attrib[] = {WX_GL_DOUBLEBUFFER,WX_GL_RGBA,	WX_GL_DEPTH_SIZE, 16,0};
	Viewer *movieViewer = new Viewer(movieFrame, viewer, wxID_ANY, wxPoint(0, 0), wxSize(renderW, renderH), 0, _T("MovieWindow"), attrib);
	movieViewer->backColor = viewer->backColor;
	movieViewer->gridColor = viewer->gridColor;	

	//movieFrame.AddChild(
	#ifdef WIN32  // Weird hack to make wxWidgets work with VC++ debug
	movieViewer->MSWSetOldWndProc((WXFARPROC)DefWindowProc);
	#endif

	int w,h;

	movieViewer->Show(true);
    movieViewer->Freeze();
    wxClientDC dc2(movieViewer);
    dc2.GetSize(&w, &h);
    movieViewer->InitGL();
    movieViewer->Thaw();
	movieViewer->handleEvents = false;
	movieViewer->Show(true);

	movieViewer->camT = viewer->camT;
	movieViewer->camRotT = viewer->camRotT;
	movieViewer->camRadius = viewer->camRadius;
	movieViewer->worldV = viewer->worldV;

    double curTargetTime = 0.0;
    std::vector<GRIPTimeSlice>::iterator it = timeVector.begin();
    int framesWritten = 0;

    double framerate = 30.0;

    do {
        if (it == timeVector.end()) break; // call it done
        while((*it).time < curTargetTime) it++;

		// Issue 122 from DART
        //mWorld->setState((*it).state);
		Eigen::VectorXd newState = (*it).state;   
    	setState_Issue122( newState );

        movieViewer->DrawGLScene();
        wxYield();

        unsigned char* imageData = (unsigned char*) malloc(w * h * 3);
        glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, imageData);
        wxImage img_ud(w,h,imageData);
        wxImage img = img_ud.Mirror(false);

        sprintf(buf, "%s/%06d.png",path.c_str(), framesWritten);

        wxString fname = wxString(buf,wxConvUTF8);
        cout << "Saving frame at t = " << (*it).time << " (targeting " << curTargetTime << ") into " << buf << "" << endl;
        img.SaveFile(fname, wxBITMAP_TYPE_PNG);

        framesWritten++;

        curTargetTime += 1.0 / framerate;
    } while (curTargetTime < timeVector.back().time);


	delete movieViewer;
	delete movieFrame;
	viewer->InitGL();

    delete buf;
    event.Skip();
}
Exemplo n.º 14
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;
}
Exemplo n.º 15
0
void TextCtrlTestCase::DoPositionToCoordsTestWithStyle(long style)
{
    delete m_text;
    CreateText(style);

    // Asking for invalid index should fail.
    WX_ASSERT_FAILS_WITH_ASSERT( m_text->PositionToCoords(1) );

    // Getting position shouldn't return wxDefaultPosition except if the method
    // is not implemented at all in the current port.
    const wxPoint pos0 = m_text->PositionToCoords(0);
    if ( pos0 == wxDefaultPosition )
    {
#if defined(__WXMSW__) || defined(__WXGTK20__)
        CPPUNIT_FAIL( "PositionToCoords() unexpectedly failed." );
#endif
        return;
    }

    CPPUNIT_ASSERT(pos0.x >= 0);
    CPPUNIT_ASSERT(pos0.y >= 0);


    m_text->SetValue("Hello");
    wxYield(); // Let GTK layout the control correctly.

    // Position of non-first character should be positive.
    const long posHello4 = m_text->PositionToCoords(4).x;
    CPPUNIT_ASSERT( posHello4 > 0 );

    // Asking for position beyond the last character should succeed and return
    // reasonable result.
    CPPUNIT_ASSERT( m_text->PositionToCoords(5).x > posHello4 );

    // But asking for the next position should fail.
    WX_ASSERT_FAILS_WITH_ASSERT( m_text->PositionToCoords(6) );

    // Test getting the coordinates of the last character when it is in the
    // beginning of a new line to exercise MSW code which has specific logic
    // for it.
    m_text->AppendText("\n");
    const wxPoint posLast = m_text->PositionToCoords(m_text->GetLastPosition());
    CPPUNIT_ASSERT_EQUAL( pos0.x, posLast.x );
    CPPUNIT_ASSERT( posLast.y > 0 );


    // Add enough contents to the control to make sure it has a scrollbar.
    m_text->SetValue("First line" + wxString(50, '\n') + "Last line");
    m_text->SetInsertionPoint(0);
    wxYield(); // Let GTK layout the control correctly.

    // This shouldn't change anything for the first position coordinates.
    CPPUNIT_ASSERT_EQUAL( pos0, m_text->PositionToCoords(0) );

    // And the last one must be beyond the window boundary and so not be
    // visible -- but getting its coordinate should still work.
    CPPUNIT_ASSERT
    (
        m_text->PositionToCoords(m_text->GetLastPosition()).y > TEXT_HEIGHT
    );


    // Now make it scroll to the end and check that the first position now has
    // negative offset as its above the visible part of the window while the
    // last position is in its bounds.
    m_text->SetInsertionPointEnd();

    CPPUNIT_ASSERT( m_text->PositionToCoords(0).y < 0 );
    CPPUNIT_ASSERT
    (
        m_text->PositionToCoords(m_text->GetInsertionPoint()).y <= TEXT_HEIGHT
    );
}
Exemplo n.º 16
0
/* Route all traces
 * Return:
 *  1 if OK
 * -1 if escape (stop being routed) request
 * -2 if default memory allocation
 */
int PCB_EDIT_FRAME::Solve( wxDC* DC, int aLayersCount )
{
    int           current_net_code;
    int           row_source, col_source, row_target, col_target;
    int           success, nbsucces = 0, nbunsucces = 0;
    NETINFO_ITEM* net;
    bool          stop = false;
    wxString      msg;
    int           routedCount = 0;      // routed ratsnest count
    bool          two_sides = aLayersCount == 2;

    m_canvas->SetAbortRequest( false );

    s_Clearance = GetBoard()->m_NetClasses.GetDefault()->GetClearance();

    // Prepare the undo command info
    s_ItemsListPicker.ClearListAndDeleteItems();  // Should not be necessary, but...

    /* go until no more work to do */
    GetWork( &row_source, &col_source, &current_net_code,
             &row_target, &col_target, &pt_cur_ch ); // First net to route.

    for( ; row_source != ILLEGAL; GetWork( &row_source, &col_source,
                                           &current_net_code, &row_target,
                                           &col_target,
                                           &pt_cur_ch ) )
    {
        /* Test to stop routing ( escape key pressed ) */
        wxYield();

        if( m_canvas->GetAbortRequest() )
        {
            if( IsOK( this, _( "Abort routing?" ) ) )
            {
                success = STOP_FROM_ESC;
                stop    = true;
                break;
            }
            else
            {
                m_canvas->SetAbortRequest( false );
            }
        }

        EraseMsgBox();

        routedCount++;
        net = GetBoard()->FindNet( current_net_code );

        if( net )
        {
            msg.Printf( wxT( "[%8.8s]" ), GetChars( net->GetNetname() ) );
            AppendMsgPanel( wxT( "Net route" ), msg, BROWN );
            msg.Printf( wxT( "%d / %d" ), routedCount, RoutingMatrix.m_RouteCount );
            AppendMsgPanel( wxT( "Activity" ), msg, BROWN );
        }

        segm_oX = GetBoard()->GetBoundingBox().GetX() + (RoutingMatrix.m_GridRouting * col_source);
        segm_oY = GetBoard()->GetBoundingBox().GetY() + (RoutingMatrix.m_GridRouting * row_source);
        segm_fX = GetBoard()->GetBoundingBox().GetX() + (RoutingMatrix.m_GridRouting * col_target);
        segm_fY = GetBoard()->GetBoundingBox().GetY() + (RoutingMatrix.m_GridRouting * row_target);

        /* Draw segment. */
        GRLine( m_canvas->GetClipBox(), DC,
                segm_oX, segm_oY, segm_fX, segm_fY,
                0, WHITE );
        pt_cur_ch->m_PadStart->Draw( m_canvas, DC, GR_OR | GR_HIGHLIGHT );
        pt_cur_ch->m_PadEnd->Draw( m_canvas, DC, GR_OR | GR_HIGHLIGHT );

        success = Autoroute_One_Track( this, DC,
                                       two_sides, row_source, col_source,
                                       row_target, col_target, pt_cur_ch );

        switch( success )
        {
        case NOSUCCESS:
            pt_cur_ch->m_Status |= CH_UNROUTABLE;
            nbunsucces++;
            break;

        case STOP_FROM_ESC:
            stop = true;
            break;

        case ERR_MEMORY:
            stop = true;
            break;

        default:
            nbsucces++;
            break;
        }

        msg.Printf( wxT( "%d" ), nbsucces );
        AppendMsgPanel( wxT( "OK" ), msg, GREEN );
        msg.Printf( wxT( "%d" ), nbunsucces );
        AppendMsgPanel( wxT( "Fail" ), msg, RED );
        msg.Printf( wxT( "  %d" ), GetBoard()->GetUnconnectedNetCount() );
        AppendMsgPanel( wxT( "Not Connected" ), msg, CYAN );

        /* Delete routing from display. */
        pt_cur_ch->m_PadStart->Draw( m_canvas, DC, GR_AND );
        pt_cur_ch->m_PadEnd->Draw( m_canvas, DC, GR_AND );

        if( stop )
            break;
    }

    SaveCopyInUndoList( s_ItemsListPicker, UR_UNSPECIFIED );
    s_ItemsListPicker.ClearItemsList(); // s_ItemsListPicker is no more owner of picked items

    return SUCCESS;
}
Exemplo n.º 17
0
bool mainApp::OnInit()
{
  if(g_pThis != NULL) return false;
	if(!wxApp::OnInit()) return false;
  g_pThis = this;
  // Set up splash screen
#ifndef _DEBUG
  wxBitmap bitmap;
  if(CImageAbout::LoadBitmap(&bitmap))
  {
      new wxSplashScreen(bitmap,
      wxSPLASH_CENTRE_ON_SCREEN | wxSPLASH_TIMEOUT,
      2000, NULL, -1, wxDefaultPosition, wxDefaultSize,
          wxSIMPLE_BORDER|wxSTAY_ON_TOP|wxFRAME_NO_TASKBAR);
    wxYield();
  }
#endif
  GetConfig();
  // set up log file if Debug directory exists
  _OpenMessageStream();

  // set up window

  m_pFrame = new mainFrame();
  bool bHasArgs = (argc > 1) && (argv[1] != (wxChar *)NULL);
#ifdef __WXMAC__
  if(m_asFiles.Count() > 0)
  {
    bHasArgs = true;
  }
#endif
  
  m_pFrame->Startup(bHasArgs);
  const wxChar *psFormat(wxS("argv[%d] = %ls"));
  LogMessageV(psFormat,0,argv[0].wc_str());
  for(int i = 1; i < argc; ++i)
  {
    LogMessageV(psFormat,i,argv[i].wc_str());
    m_pFrame->OpenFile(argv[i]);
  }
//  time_t t;
//  time(&t);
  wxString sPID = wxString::Format(wxS("PID: %d"),(int)getpid());
//  wxLog::OnLog(wxLOG_Message,(const wxChar *)sPID,t);
  LogMessage(sPID);
#if defined(__WXDEBUG__)
  const wxPlatformInfo &plat(wxPlatformInfo::Get());
  wxString sOS = wxString::Format(
    wxT("Platform:\n  OS: %s; %s\n  Version: %d.%d\n  Arch: %s\n  Toolkit: %d.%d\n  Port: %s"),
    (const char *) plat.GetOperatingSystemFamilyName().ToAscii(),
    (const char *) plat.GetOperatingSystemDescription().ToAscii(),
    plat.GetOSMajorVersion(),
    plat.GetOSMinorVersion(),
    (const char *)plat.GetArchName().ToAscii(),
    plat.GetToolkitMajorVersion(),
    plat.GetToolkitMinorVersion(),
    (const char *) plat.GetPortIdName().ToAscii());

  sOS += wxString::Format(wxS("\n  sizeof(char):        %d"),(int)(sizeof(char)));
  sOS += wxString::Format(wxS("\n  sizeof(wxChar):      %d"),(int)(sizeof(wxChar)));
  sOS += wxString::Format(wxS("\n  sizeof(wchar_t):     %d"),(int)(sizeof(wchar_t)));
  sOS += wxString::Format(wxS("\n  sizeof(short):       %d"),(int)(sizeof(short)));
  sOS += wxString::Format(wxS("\n  sizeof(int):         %d"),(int)(sizeof(int)));
  sOS += wxString::Format(wxS("\n  sizeof(long):        %d"),(int)(sizeof(long)));
  sOS += wxString::Format(wxS("\n  sizeof(longlong):    %d"),(int)(sizeof(long long)));
  sOS += wxString::Format(wxS("\n  sizeof(size_t):      %d"),(int)(sizeof(size_t)));
  sOS += wxString::Format(wxS("\n  sizeof(time_t):      %d"),(int)(sizeof(time_t)));
  sOS += wxString::Format(wxS("\n  sizeof(float):       %d"),(int)(sizeof(float)));
  sOS += wxString::Format(wxS("\n  sizeof(double):      %d"),(int)(sizeof(double)));
  sOS += wxString::Format(wxS("\n  sizeof(long double): %d"),(int)(sizeof(long double )));

  LogMessage(sOS);
#endif

#ifdef __WXDEBUG__

    
  m_pConfig->Log();

#endif
#ifdef __WXMAC__
  if(bHasArgs)
  {
    _MacOpenFiles();
  }
#endif
  return true;
}
Exemplo n.º 18
0
void WebTestCase::setUp()
{
    m_browser = wxWebView::New(wxTheApp->GetTopWindow(), wxID_ANY);
    //We yield to let the initial page load
    wxYield();
}
Exemplo n.º 19
0
bool wxPostScriptPrinter::Print(wxWindow *parent, wxPrintout *printout, bool prompt)
{
    sm_abortIt = false;
    sm_abortWindow = NULL;

    if (!printout)
    {
        sm_lastError = wxPRINTER_ERROR;
        return false;
    }

    if (m_printDialogData.GetMinPage() < 1)
        m_printDialogData.SetMinPage(1);
    if (m_printDialogData.GetMaxPage() < 1)
        m_printDialogData.SetMaxPage(9999);

    // Create a suitable device context
    wxDC *dc;
    if (prompt)
    {
        dc = PrintDialog(parent);
        if (!dc)
            return false;
    }
    else
    {
        dc = new wxPostScriptDC(GetPrintDialogData().GetPrintData());
    }

    // May have pressed cancel.
    if (!dc || !dc->IsOk())
    {
        if (dc) delete dc;
        sm_lastError = wxPRINTER_ERROR;
        return false;
    }

    wxSize ScreenPixels = wxGetDisplaySize();
    wxSize ScreenMM = wxGetDisplaySizeMM();

    printout->SetPPIScreen( (int) ((ScreenPixels.GetWidth() * 25.4) / ScreenMM.GetWidth()),
                            (int) ((ScreenPixels.GetHeight() * 25.4) / ScreenMM.GetHeight()) );
    printout->SetPPIPrinter( dc->GetResolution(),
                             dc->GetResolution() );

    // Set printout parameters
    printout->SetDC(dc);

    int w, h;
    dc->GetSize(&w, &h);
    printout->SetPageSizePixels((int)w, (int)h);
    printout->SetPaperRectPixels(wxRect(0, 0, w, h));
    int mw, mh;
    dc->GetSizeMM(&mw, &mh);
    printout->SetPageSizeMM((int)mw, (int)mh);

    // Create an abort window
    wxBeginBusyCursor();

    printout->OnPreparePrinting();

    // Get some parameters from the printout, if defined
    int fromPage, toPage;
    int minPage, maxPage;
    printout->GetPageInfo(&minPage, &maxPage, &fromPage, &toPage);

    if (maxPage == 0)
    {
        sm_lastError = wxPRINTER_ERROR;
        wxEndBusyCursor();
        return false;
    }

    // Only set min and max, because from and to have been
    // set by the user
    m_printDialogData.SetMinPage(minPage);
    m_printDialogData.SetMaxPage(maxPage);

    if (m_printDialogData.GetFromPage() < minPage)
        m_printDialogData.SetFromPage( minPage );
    if (m_printDialogData.GetToPage() > maxPage)
        m_printDialogData.SetToPage( maxPage );

    int
       pagesPerCopy = m_printDialogData.GetToPage()-m_printDialogData.GetFromPage()+1,
       totalPages = pagesPerCopy * m_printDialogData.GetNoCopies(),
       printedPages = 0;
    // Open the progress bar dialog
    wxProgressDialog *progressDialog = new wxProgressDialog (
       printout->GetTitle(),
       _("Printing..."),
       totalPages,
       parent,
       wxPD_CAN_ABORT|wxPD_AUTO_HIDE|wxPD_APP_MODAL);

    printout->OnBeginPrinting();

    sm_lastError = wxPRINTER_NO_ERROR;

    bool keepGoing = true;

    int copyCount;
    for (copyCount = 1; copyCount <= m_printDialogData.GetNoCopies(); copyCount ++)
    {
        if (!printout->OnBeginDocument(m_printDialogData.GetFromPage(), m_printDialogData.GetToPage()))
        {
            wxEndBusyCursor();
            wxLogError(_("Could not start printing."));
            sm_lastError = wxPRINTER_ERROR;
            break;
        }
        if (sm_abortIt)
        {
            sm_lastError = wxPRINTER_CANCELLED;
            break;
        }

        int pn;
        for (pn = m_printDialogData.GetFromPage(); keepGoing && (pn <= m_printDialogData.GetToPage()) && printout->HasPage(pn);
        pn++)
        {
            if (sm_abortIt)
            {
                keepGoing = false;
                sm_lastError = wxPRINTER_CANCELLED;
                break;
            }
            else
            {
               wxString msg;
               msg.Printf(_("Printing page %d..."), printedPages+1);
               if(progressDialog->Update(printedPages++, msg))
               {
                  dc->StartPage();
                  printout->OnPrintPage(pn);
                  dc->EndPage();
               }
               else
               {
                  sm_abortIt = true;
                  sm_lastError = wxPRINTER_CANCELLED;
                  keepGoing = false;
               }
            }
            wxYield();
        }
        printout->OnEndDocument();
    }

    printout->OnEndPrinting();
    delete progressDialog;

    wxEndBusyCursor();

    delete dc;

    return (sm_lastError == wxPRINTER_NO_ERROR);
}
Exemplo n.º 20
0
bool ExportCL(AudacityProject *project, bool stereo, wxString fName,
              bool selectionOnly, double t0, double t1)
{
   int rate = int(project->GetRate() + 0.5);
   wxWindow *parent = project;
   TrackList *tracks = project->GetTracks();
   
   wxString command = gPrefs->Read("/FileFormats/ExternalProgramExportCommand", "lame - '%f'");
   command.Replace("%f", fName);

   /* establish parameters */
   int channels = stereo ? 2 : 1;
   unsigned long totalSamples = (unsigned long)((t1 - t0) * rate + 0.5);
   unsigned long sampleBytes = totalSamples * channels * SAMPLE_SIZE(int16Sample);
   double timeStep = 10.0;      // write in blocks of 10 secs

   /* fill up the wav header */
   wav_header header;
   header.riffID[0] = 'R';
   header.riffID[1] = 'I';
   header.riffID[2] = 'F';
   header.riffID[3] = 'F';
   header.riffType[0] = 'W';
   header.riffType[1] = 'A';
   header.riffType[2] = 'V';
   header.riffType[3] = 'E';
   header.lenAfterRiff = sampleBytes + 32;

   header.fmtID[0]  = 'f';
   header.fmtID[1]  = 'm';
   header.fmtID[2]  = 't';
   header.fmtID[3]  = ' ';
   header.formatChunkLen = 16;
   header.formatTag      = 1;
   header.channels       = channels;
   header.sampleRate     = rate;
   header.bitsPerSample  = SAMPLE_SIZE(int16Sample) * 8;
   header.blockAlign     = header.bitsPerSample * header.channels;
   header.avgBytesPerSec = header.sampleRate * header.blockAlign;

   header.dataID[0] = 'd';
   header.dataID[1] = 'a';
   header.dataID[2] = 't';
   header.dataID[3] = 'a';
   header.dataLen   = sampleBytes;

   FILE *pipe = popen(command.c_str(), "w");

   /* write the header */

   fwrite( &header, sizeof(wav_header), 1, pipe );

   //sampleCount maxSamples = int (timeStep * rate + 0.5);

   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(channels, numSamples, true, rate, int16Sample);
      wxASSERT(mixer);
      mixer->Clear();

      char *buffer = new char[numSamples * SAMPLE_SIZE(int16Sample) * channels];
      wxASSERT(buffer);

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

      samplePtr mixed = mixer->GetBuffer();

      // Byte-swapping is neccesary on big-endian machines, since
      // WAV files are little-endian
#if wxBYTE_ORDER == wxBIG_ENDIAN
      {
         short *buffer = (short*)mixed;
         for( int i = 0; i < numSamples; i++ )
            buffer[i] = wxINT16_SWAP_ON_BE(buffer[i]);
      }
#endif

      fwrite( mixed, numSamples * channels * SAMPLE_SIZE(int16Sample), 1, pipe );

      t += deltat;

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

         wxString message;

         if (selectionOnly)
            message = "Exporting the selected audio using command-line encoder";
         else
            message = "Exporting the entire project using command-line encoder";

         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;
   }

   pclose( pipe );

   if(progress)
      delete progress;
   return true;
}
Exemplo n.º 21
0
// OnMenu handles all events which don't have their own event handler
void LifeFrame::OnMenu(wxCommandEvent& event)
{
    switch (event.GetId())
    {
        case wxID_NEW:
        {
            // stop if it was running
            OnStop();
            m_life->Clear();
            m_canvas->Recenter(0, 0);
            m_tics = 0;
            UpdateInfoText();
            break;
        }
        case wxID_ABOUT:
        {
            LifeAboutDialog dialog(this);
            dialog.ShowModal();
            break;
        }
        case wxID_EXIT:
        {
            // true is to force the frame to close
            Close(true);
            break;
        }
        case ID_SHOWNAV:
        {
            bool checked = GetMenuBar()->GetMenu(1)->IsChecked(ID_SHOWNAV);
            if (m_navigator)
                m_navigator->Show(checked);
            break;
        }
        case ID_INFO:
        {
            wxString desc = m_life->GetDescription();

            if ( desc.empty() )
                desc = _("Not available");

            // should we make the description editable here?
            wxMessageBox(desc, _("Description"), wxOK | wxICON_INFORMATION);

            break;
        }
        case ID_START   : OnStart(); break;
        case ID_STEP    : OnStep(); break;
        case wxID_STOP  : OnStop(); break;
        case ID_TOPSPEED:
        {
            m_running = true;
            m_topspeed = true;
            UpdateUI();
            while (m_running && m_topspeed)
            {
                OnStep();
                wxYield();
            }
            break;
        }
    }
}
Exemplo n.º 22
0
bool wxWindowsPrinter::Print(wxWindow *parent, wxPrintout *printout, bool prompt)
{
    sm_abortIt = false;
    sm_abortWindow = NULL;

    if (!printout)
    {
        sm_lastError = wxPRINTER_ERROR;
        return false;
    }

    printout->SetIsPreview(false);

    if (m_printDialogData.GetMinPage() < 1)
        m_printDialogData.SetMinPage(1);
    if (m_printDialogData.GetMaxPage() < 1)
        m_printDialogData.SetMaxPage(9999);

    // Create a suitable device context
    wxDC *dc wxDUMMY_INITIALIZE(NULL);
    if (prompt)
    {
        dc = PrintDialog(parent);
        if (!dc)
            return false;
    }
    else
    {
        dc = new wxPrinterDC(m_printDialogData.GetPrintData());
    }

    // May have pressed cancel.
    if (!dc || !dc->Ok())
    {
        if (dc) delete dc;
        return false;
    }

    HDC hdc = ::GetDC(NULL);
    int logPPIScreenX = ::GetDeviceCaps(hdc, LOGPIXELSX);
    int logPPIScreenY = ::GetDeviceCaps(hdc, LOGPIXELSY);
    ::ReleaseDC(NULL, hdc);

    int logPPIPrinterX = ::GetDeviceCaps((HDC) dc->GetHDC(), LOGPIXELSX);
    int logPPIPrinterY = ::GetDeviceCaps((HDC) dc->GetHDC(), LOGPIXELSY);
    if (logPPIPrinterX == 0 || logPPIPrinterY == 0)
    {
        delete dc;
        sm_lastError = wxPRINTER_ERROR;
        return false;
    }

    printout->SetPPIScreen(logPPIScreenX, logPPIScreenY);
    printout->SetPPIPrinter(logPPIPrinterX, logPPIPrinterY);

    // Set printout parameters
    printout->SetDC(dc);

    int w, h;
    dc->GetSize(&w, &h);
    printout->SetPageSizePixels((int)w, (int)h);

    dc->GetSizeMM(&w, &h);
    printout->SetPageSizeMM((int)w, (int)h);

    // Create an abort window
    wxBusyCursor busyCursor;

    printout->OnPreparePrinting();

    // Get some parameters from the printout, if defined
    int fromPage, toPage;
    int minPage, maxPage;
    printout->GetPageInfo(&minPage, &maxPage, &fromPage, &toPage);

    if (maxPage == 0)
    {
        sm_lastError = wxPRINTER_ERROR;
        return false;
    }

    // Only set min and max, because from and to have been
    // set by the user
    m_printDialogData.SetMinPage(minPage);
    m_printDialogData.SetMaxPage(maxPage);

    wxWindow *win = CreateAbortWindow(parent, printout);
    wxYield();

#if defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__GNUWIN32__) || defined(__SALFORDC__) || !defined(__WIN32__)
#ifdef STRICT
    ::SetAbortProc((HDC) dc->GetHDC(), (ABORTPROC) m_lpAbortProc);
#else
    ::SetAbortProc((HDC) dc->GetHDC(), (FARPROC) m_lpAbortProc);
#endif
#else
    ::SetAbortProc((HDC) dc->GetHDC(), (int (_stdcall *)
        // cast it to right type only if required
        // FIXME it's really cdecl and we're casting it to stdcall - either there is
        //       something I don't understand or it will crash at first usage
#ifdef STRICT
        (HDC, int)
#else
        ()
#endif
        )m_lpAbortProc);
#endif

    if (!win)
    {
        wxLogDebug(wxT("Could not create an abort dialog."));
        sm_lastError = wxPRINTER_ERROR;

        delete dc;
        return false;
    }
    sm_abortWindow = win;
    sm_abortWindow->Show();
    wxSafeYield();

    printout->OnBeginPrinting();

    sm_lastError = wxPRINTER_NO_ERROR;

    int minPageNum = minPage, maxPageNum = maxPage;

    if ( !m_printDialogData.GetAllPages() )
    {
        minPageNum = m_printDialogData.GetFromPage();
        maxPageNum = m_printDialogData.GetToPage();
    }

    int copyCount;
    for ( copyCount = 1;
          copyCount <= m_printDialogData.GetNoCopies();
          copyCount++ )
    {
        if ( !printout->OnBeginDocument(minPageNum, maxPageNum) )
        {
            wxLogError(_("Could not start printing."));
            sm_lastError = wxPRINTER_ERROR;
            break;
        }
        if (sm_abortIt)
        {
            sm_lastError = wxPRINTER_CANCELLED;
            break;
        }

        int pn;

        for ( pn = minPageNum;
              pn <= maxPageNum && printout->HasPage(pn);
              pn++ )
        {
            if ( sm_abortIt )
            {
                sm_lastError = wxPRINTER_CANCELLED;
                break;
            }

            dc->StartPage();
            bool cont = printout->OnPrintPage(pn);
            dc->EndPage();

            if ( !cont )
            {
                sm_lastError = wxPRINTER_CANCELLED;
                break;
            }
        }

        printout->OnEndDocument();
    }

    printout->OnEndPrinting();

    if (sm_abortWindow)
    {
        sm_abortWindow->Show(false);
        delete sm_abortWindow;
        sm_abortWindow = NULL;
    }

    delete dc;

    return sm_lastError == wxPRINTER_NO_ERROR;
}
Exemplo n.º 23
0
void wxGUIAppTraits::AlwaysYield()
{
    wxYield();
}
Exemplo n.º 24
0
bool wxHtmlHelpController::KeywordSearch(const wxString& keyword)
{
    int foundcnt = 0;
    CreateHelpWindow();
    // if these are not set, we can't continue
    if (! (m_SearchList && m_HtmlWin))
       return FALSE;
    m_Frame -> Raise();
    if (m_Splitter && m_NavigPan && m_SearchButton) {
       if (!m_Splitter -> IsSplit()) {
          m_NavigPan -> Show(TRUE);
          m_HtmlWin -> Show(TRUE);
          m_Splitter -> SplitVertically(m_NavigPan, m_HtmlWin, m_Cfg.sashpos);
       }
       m_NavigPan -> SetSelection(2);
       m_SearchList -> Clear();
       m_SearchText -> SetValue(keyword);
       m_SearchButton -> Enable(FALSE);
    }
    {
        int cnt = m_ContentsCnt;
        wxSearchEngine engine;
        wxFileSystem fsys;
        wxFSFile *file;
        wxString lastpage = wxEmptyString;
        wxString foundstr;

#if (wxVERSION_NUMBER < 2100) || ((wxVERSION_NUMBER == 2100) && (wxBETA_NUMBER < 7))
        MyProgressDlg progress(m_Frame);

        wxStaticText *prompt = new wxStaticText(&progress, -1, "", wxPoint(20, 50), wxSize(260, 25), wxALIGN_CENTER);
        wxGauge *gauge = new wxGauge(&progress, -1, cnt, wxPoint(20, 20), wxSize(260, 25));
        wxButton *btn = new wxButton(&progress, wxID_CANCEL, _("Cancel"), wxPoint(110, 70), wxSize(80, 25));
        btn = btn; /* fool compiler :-) */
        prompt -> SetLabel(_("No matching page found yet"));

	progress.Centre(wxBOTH);
        progress.Show(TRUE);
#else
	wxProgressDialog progress(_("Searching..."), _("No matching page found yet"), cnt, m_Frame, wxPD_APP_MODAL | wxPD_CAN_ABORT | wxPD_AUTO_HIDE);
#endif

        engine.LookFor(keyword);

        for (int i = 0; i < cnt; i++) {
#if (wxVERSION_NUMBER < 2100) || ((wxVERSION_NUMBER == 2100) && (wxBETA_NUMBER < 7))
            gauge -> SetValue(i);
            if (progress.m_Canceled) break;
#else
    	    if (progress.Update(i) == FALSE) break;
#endif
	    wxYield();

            file = fsys.OpenFile(m_Contents[i].m_Book -> GetBasePath() + m_Contents[i].m_Page);
            if (file) {
                if (lastpage != file -> GetLocation()) {
                    lastpage = file -> GetLocation();
                    if (engine.Scan(file -> GetStream())) {
                        foundstr.Printf(_("Found %i matches"), ++foundcnt);
#if (wxVERSION_NUMBER < 2100) || ((wxVERSION_NUMBER == 2100) && (wxBETA_NUMBER < 7))
                        prompt -> SetLabel(foundstr);
#else
    	    	    	progress.Update(i, foundstr);
#endif
                        wxYield();
                        m_SearchList -> Append(m_Contents[i].m_Name, (char*)(m_Contents + i));
                    }
                }
                delete file;
            }
        }

#if (wxVERSION_NUMBER < 2100) || ((wxVERSION_NUMBER == 2100) && (wxBETA_NUMBER < 7))
        progress.Close(TRUE);
#endif
    }
    if (m_SearchButton)
	m_SearchButton -> Enable(TRUE);
    if (m_SearchText) {
	m_SearchText -> SetSelection(0, keyword.Length());
	m_SearchText -> SetFocus();
    }
    if (foundcnt) {
        HtmlContentsItem *it = (HtmlContentsItem*) m_SearchList -> GetClientData(0);
        if (it) m_HtmlWin -> LoadPage(it -> m_Book -> GetBasePath() + it -> m_Page);
    }
    return (foundcnt > 0);
}
Exemplo n.º 25
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.º 26
0
void wxHtmlHelpController::CreateHelpWindow()
{
    wxBusyCursor cur;
    wxString oldpath;
    wxStatusBar *sbar;

    if (m_Frame) {
        m_Frame -> Raise();
    	m_Frame -> Show(TRUE);
        return;
    }

#if wxUSE_BUSYINFO
    wxBusyInfo busyinfo(_("Preparing help window..."));
#endif

    if (m_Config) ReadCustomization(m_Config, m_ConfigRoot);

    m_Frame = new wxFrame(NULL, -1, "", wxPoint(m_Cfg.x, m_Cfg.y), wxSize(m_Cfg.w, m_Cfg.h));
    m_Frame -> PushEventHandler(this);
    sbar = m_Frame -> CreateStatusBar();

    {
        wxToolBar *toolBar;
        toolBar = m_Frame -> CreateToolBar(wxNO_BORDER | wxTB_HORIZONTAL | wxTB_FLAT | wxTB_DOCKABLE);
        toolBar -> SetMargins(2, 2);
        wxBitmap* toolBarBitmaps[3];

#ifdef __WXMSW__
        toolBarBitmaps[0] = new wxBitmap("panel");
        toolBarBitmaps[1] = new wxBitmap("back");
        toolBarBitmaps[2] = new wxBitmap("forward");
        int width = 24;
#else
        toolBarBitmaps[0] = new wxBitmap(panel_xpm);
        toolBarBitmaps[1] = new wxBitmap(back_xpm);
        toolBarBitmaps[2] = new wxBitmap(forward_xpm);
        int width = 16;
#endif

        int currentX = 5;

        toolBar -> AddTool(wxID_HTML_PANEL, *(toolBarBitmaps[0]), wxNullBitmap, FALSE, currentX, -1, (wxObject *) NULL, _("Show/hide navigation panel"));
        currentX += width + 5;
        toolBar -> AddSeparator();
        toolBar -> AddTool(wxID_HTML_BACK, *(toolBarBitmaps[1]), wxNullBitmap, FALSE, currentX, -1, (wxObject *) NULL, _("Go back to the previous HTML page"));
        currentX += width + 5;
        toolBar -> AddTool(wxID_HTML_FORWARD, *(toolBarBitmaps[2]), wxNullBitmap, FALSE, currentX, -1, (wxObject *) NULL, _("Go forward to the next HTML page"));
        currentX += width + 5;

        toolBar -> Realize();

        // Can delete the bitmaps since they're reference counted
        for (int i = 0; i < 3; i++) delete toolBarBitmaps[i];
    }


    {
        m_Splitter = new wxSplitterWindow(m_Frame);

        m_HtmlWin = new wxHtmlWindow(m_Splitter);
        m_HtmlWin -> SetRelatedFrame(m_Frame, m_TitleFormat);
        m_HtmlWin -> SetRelatedStatusBar(0);
        if (m_Config) m_HtmlWin -> ReadCustomization(m_Config, m_ConfigRoot);

        m_NavigPan = new wxNotebook(m_Splitter, wxID_HTML_NOTEBOOK, wxDefaultPosition, wxDefaultSize);
        {
            m_ContentsBox = new wxTreeCtrl(m_NavigPan, wxID_HTML_TREECTRL, wxDefaultPosition, wxDefaultSize, wxTR_HAS_BUTTONS | wxSUNKEN_BORDER);
            m_ContentsBox -> SetImageList(m_ContentsImageList);
            m_NavigPan -> AddPage(m_ContentsBox, _("Contents"));
        }

        {
            wxWindow *dummy = new wxPanel(m_NavigPan, wxID_HTML_INDEXPAGE);
            wxLayoutConstraints *b1 = new wxLayoutConstraints;
            b1 -> top.SameAs        (dummy, wxTop, 0);
            b1 -> left.SameAs       (dummy, wxLeft, 0);
            b1 -> width.PercentOf   (dummy, wxWidth, 100);
            b1 -> bottom.SameAs     (dummy, wxBottom, 0);
            m_IndexBox = new wxListBox(dummy, wxID_HTML_INDEXLIST, wxDefaultPosition, wxDefaultSize, 0);
            m_IndexBox -> SetConstraints(b1);
            dummy -> SetAutoLayout(TRUE);
            m_NavigPan -> AddPage(dummy, _("Index"));
        }

        {
            wxWindow *dummy = new wxPanel(m_NavigPan, wxID_HTML_SEARCHPAGE);

            wxLayoutConstraints *b1 = new wxLayoutConstraints;
            m_SearchText = new wxTextCtrl(dummy, wxID_HTML_SEARCHTEXT);
            b1 -> top.SameAs        (dummy, wxTop, 0);
            b1 -> left.SameAs       (dummy, wxLeft, 0);
            b1 -> right.SameAs      (dummy, wxRight, 0);
            b1 -> height.AsIs();
            m_SearchText -> SetConstraints(b1);

            wxLayoutConstraints *b2 = new wxLayoutConstraints;
            m_SearchButton = new wxButton(dummy, wxID_HTML_SEARCHBUTTON, _("Search!"));
            b2 -> top.Below         (m_SearchText, 10);
            b2 -> right.SameAs      (dummy, wxRight, 10);
            b2 -> width.AsIs();
            b2 -> height.AsIs();
            m_SearchButton -> SetConstraints(b2);

            wxLayoutConstraints *b3 = new wxLayoutConstraints;
            m_SearchList = new wxListBox(dummy, wxID_HTML_SEARCHLIST, wxDefaultPosition, wxDefaultSize, 0);
            b3 -> top.Below         (m_SearchButton, 10);
            b3 -> left.SameAs       (dummy, wxLeft, 0);
            b3 -> right.SameAs      (dummy, wxRight, 0);
            b3 -> bottom.SameAs     (dummy, wxBottom, 0);
            m_SearchList -> SetConstraints(b3);

            dummy -> SetAutoLayout(TRUE);
            dummy -> Layout();
            m_NavigPan -> AddPage(dummy, _("Search"));
        }

        RefreshLists();
        m_NavigPan -> Show(TRUE);
        m_HtmlWin -> Show(TRUE);
        m_Splitter -> SetMinimumPaneSize(20);
        m_Splitter -> SplitVertically(m_NavigPan, m_HtmlWin, m_Cfg.sashpos);
        if (!m_Cfg.navig_on) m_Splitter -> Unsplit(m_NavigPan);
        wxYield();
    }

    m_Frame -> Show(TRUE);
    wxYield();
}
Exemplo n.º 27
0
void ListBaseTestCase::ItemClick()
{
#if wxUSE_UIACTIONSIMULATOR 

#ifdef __WXMSW__
    // FIXME: This test fails on MSW buildbot slaves although works fine on
    //        development machine, no idea why. It seems to be a problem with
    //        wxUIActionSimulator rather the wxListCtrl control itself however.
    if ( IsAutomaticTest() )
        return;
#endif // __WXMSW__

    wxListCtrl* const list = GetList();

    list->InsertColumn(0, "Column 0", wxLIST_FORMAT_LEFT, 60);
    list->InsertColumn(1, "Column 1", wxLIST_FORMAT_LEFT, 50);
    list->InsertColumn(2, "Column 2", wxLIST_FORMAT_LEFT, 40);

    list->InsertItem(0, "Item 0");
    list->SetItem(0, 1, "first column");
    list->SetItem(0, 2, "second column");

    EventCounter selected(list, wxEVT_LIST_ITEM_SELECTED);
    EventCounter focused(list, wxEVT_LIST_ITEM_FOCUSED);
    EventCounter activated(list, wxEVT_LIST_ITEM_ACTIVATED);
    EventCounter rclick(list, wxEVT_LIST_ITEM_RIGHT_CLICK);

    wxUIActionSimulator sim;

    wxRect pos;
    list->GetItemRect(0, pos);

    //We move in slightly so we are not on the edge
    wxPoint point = list->ClientToScreen(pos.GetPosition()) + wxPoint(10, 5);

    sim.MouseMove(point);
    wxYield();

    sim.MouseClick();
    wxYield();

    sim.MouseDblClick();
    wxYield();

    sim.MouseClick(wxMOUSE_BTN_RIGHT);
    wxYield();

    // when the first item was selected the focus changes to it, but not
    // on subsequent clicks
    
    // FIXME: This test fail under wxGTK & wxOSX because we get 3 FOCUSED events and
    //        2 SELECTED ones instead of the one of each we expect for some
    //        reason, this needs to be debugged as it may indicate a bug in the
    //        generic wxListCtrl implementation.
#ifndef _WX_GENERIC_LISTCTRL_H_
    CPPUNIT_ASSERT_EQUAL(1, focused.GetCount());
    CPPUNIT_ASSERT_EQUAL(1, selected.GetCount());
#endif
    CPPUNIT_ASSERT_EQUAL(1, activated.GetCount());
    CPPUNIT_ASSERT_EQUAL(1, rclick.GetCount());

    //tidy up when we are finished
    list->ClearAll();
#endif // wxUSE_UIACTIONSIMULATOR
}
Exemplo n.º 28
0
int MyApp::OnRun()
{
    // Using a space so the initial 'w' will not be capitalized in wxLogGUI dialogs
    wxApp::SetAppName( wxT( " wxFormBuilder" ) );

    // Creating the wxConfig manually so there will be no space
    // The old config (if any) is returned, delete it
    delete wxConfigBase::Set( new wxConfig( wxT("wxFormBuilder") ) );

    // Get the data directory
    wxStandardPathsBase& stdPaths = wxStandardPaths::Get();
    wxString dataDir = stdPaths.GetDataDir();
    dataDir.Replace( GetAppName().c_str(), wxT("wxformbuilder") );

    // Log to stderr while working on the command line
    delete wxLog::SetActiveTarget( new wxLogStderr );

    // Message output to the same as the log target
    delete wxMessageOutput::Set( new wxMessageOutputLog );

    // Parse command line
    wxCmdLineParser parser( s_cmdLineDesc, argc, argv );
    if ( 0 != parser.Parse() )
    {
        return 1;
    }

    // Get project to load
    wxString projectToLoad = wxEmptyString;
    if ( parser.GetParamCount() > 0 )
    {
        projectToLoad = parser.GetParam();
    }

    bool justGenerate = false;
    wxString language;
    bool hasLanguage = parser.Found( wxT("l"), &language );
    if ( parser.Found( wxT("g") ) )
    {
        if ( projectToLoad.empty() )
        {
            wxLogError( _("You must pass a path to a project file. Nothing to generate.") );
            return 2;
        }

        if ( hasLanguage )
        {
            if ( language.empty() )
            {
                wxLogError( _("Empty language option. Nothing generated.") );
                return 3;
            }
            language.Replace( wxT(","), wxT("|"), true );
        }

        // generate code
        justGenerate = true;
    }
    else
    {
        delete wxLog::SetActiveTarget( new wxLogGui );
    }

    // Create singleton AppData - wait to initialize until sure that this is not the second
    // instance of a project file.
    AppDataCreate( dataDir );

    // Make passed project name absolute
    try
    {
        if ( !projectToLoad.empty() )
        {
            wxFileName projectPath( projectToLoad );
            if ( !projectPath.IsOk() )
            {
                THROW_WXFBEX( wxT("This path is invalid: ") << projectToLoad );
            }

            if ( !projectPath.IsAbsolute() )
            {
                if ( !projectPath.MakeAbsolute() )
                {
                    THROW_WXFBEX( wxT("Could not make path absolute: ") << projectToLoad );
                }
            }
            projectToLoad = projectPath.GetFullPath();
        }
    }
    catch ( wxFBException& ex )
    {
        wxLogError( ex.what() );
    }

    // If the project is already loaded in another instance, switch to that instance and quit
    if ( !projectToLoad.empty() && !justGenerate )
    {
        if ( ::wxFileExists( projectToLoad ) )
        {
            if ( !AppData()->VerifySingleInstance( projectToLoad ) )
            {
                return 4;
            }
        }
    }

    // Init handlers
    wxInitAllImageHandlers();
    wxXmlResource::Get()->InitAllHandlers();
#if wxVERSION_NUMBER >= 2905
    wxXmlResource::Get()->AddHandler(new wxAuiNotebookXmlHandler);
#endif

    // Init AppData
    try
    {
        AppDataInit();
    }
    catch( wxFBException& ex )
    {
        wxLogError( _("Error loading application: %s\nwxFormBuilder cannot continue."),	ex.what() );
        wxLog::FlushActive();
        return 5;
    }

    wxSystemOptions::SetOption( wxT( "msw.remap" ), 0 );
    wxSystemOptions::SetOption( wxT( "msw.staticbox.optimized-paint" ), 0 );

    m_frame = NULL;

#ifndef __WXFB_DEBUG__
    wxBitmap bitmap;
    std::unique_ptr< cbSplashScreen > splash;
    if ( !justGenerate )
    {
        if ( bitmap.LoadFile( dataDir + wxFILE_SEP_PATH + wxT( "resources" ) + wxFILE_SEP_PATH + wxT( "splash.png" ), wxBITMAP_TYPE_PNG ) )
        {
            splash = std::unique_ptr< cbSplashScreen >( new cbSplashScreen( bitmap, -1, 0, wxNewId() ) );
        }
    }
#endif

    wxYield();

    // Read size and position from config file
    wxConfigBase *config = wxConfigBase::Get();
    config->SetPath( wxT("/mainframe") );
    int x, y, w, h;
    x = y = w = h = -1;
    config->Read( wxT( "PosX" ), &x );
    config->Read( wxT( "PosY" ), &y );
    config->Read( wxT( "SizeW" ), &w );
    config->Read( wxT( "SizeH" ), &h );

    long style = config->Read( wxT("style"), wxFB_WIDE_GUI );
    if ( style != wxFB_CLASSIC_GUI )
    {
        style = wxFB_WIDE_GUI;
    }

    config->SetPath( wxT("/") );

    m_frame = new MainFrame( NULL ,-1, (int)style, wxPoint( x, y ), wxSize( w, h ) );
    if ( !justGenerate )
    {
        m_frame->Show( TRUE );
        SetTopWindow( m_frame );

#ifndef __WXFB_DEBUG__
        // turn off the splash screen
        delete splash.release();
#endif

#ifdef __WXFB_DEBUG__
        wxLogWindow* log = dynamic_cast< wxLogWindow* >( AppData()->GetDebugLogTarget() );
        if ( log )
        {
            m_frame->AddChild( log->GetFrame() );
        }
#endif //__WXFB_DEBUG__
    }

    // This is not necessary for wxFB to work. However, Windows sets the Current Working Directory
    // to the directory from which a .fbp file was opened, if opened from Windows Explorer.
    // This puts an unneccessary lock on the directory.
    // This changes the CWD to the already locked app directory as a workaround
#ifdef __WXMSW__
    ::wxSetWorkingDirectory( dataDir );
#endif

    if ( !projectToLoad.empty() )
    {
        if ( AppData()->LoadProject( projectToLoad, justGenerate ) )
        {
            if ( justGenerate )
            {
                if ( hasLanguage )
                {
                    PObjectBase project = AppData()->GetProjectData();
                    PProperty codeGen = project->GetProperty( _("code_generation") );
                    if ( codeGen )
                    {
                        codeGen->SetValue( language );
                    }
                }
                AppData()->GenerateCode( false, true );
                return 0;
            }
            else
            {
                m_frame->InsertRecentProject( projectToLoad );
                return wxApp::OnRun();
            }
        }
        else
        {
            wxLogError( wxT("Unable to load project: %s"), projectToLoad.c_str() );
        }
    }

    if ( justGenerate )
    {
        return 6;
    }

    AppData()->NewProject();

#ifdef __WXMAC__
    // document to open on startup
    if(!m_mac_file_name.IsEmpty())
    {
        if ( AppData()->LoadProject( m_mac_file_name ) )
            m_frame->InsertRecentProject( m_mac_file_name );
    }
#endif

    return wxApp::OnRun();
}
Exemplo n.º 29
0
void NumValidatorTestCase::Interactive()
{
    // FIXME: This test fails on MSW buildbot slaves although works fine on
    //        development machine, no idea why. It seems to be a problem with
    //        wxUIActionSimulator rather the wxListCtrl control itself however.
    if ( wxGetUserId().Lower().Matches("buildslave*") )
        return;

    // Set a locale using comma as thousands separator character.
    wxLocale loc(wxLANGUAGE_ENGLISH_UK, wxLOCALE_DONT_LOAD_DEFAULT);

    m_text->SetValidator(
        wxIntegerValidator<unsigned>(NULL, wxNUM_VAL_THOUSANDS_SEPARATOR));

    // Create a sibling text control to be able to switch focus and thus
    // trigger the control validation/normalization.
    wxTextCtrl * const text2 = new wxTextCtrl(m_text->GetParent(), wxID_ANY);
    text2->Move(10, 80); // Just to see it better while debugging...
    wxFloatingPointValidator<float> valFloat(3);
    valFloat.SetRange(-10., 10.);
    text2->SetValidator(valFloat);

    wxUIActionSimulator sim;

    // Entering '-' in a control with positive range is not allowed.
    m_text->SetFocus();
    sim.Char('-');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "", m_text->GetValue() );

    // Neither is entering '.' or any non-digit character.
    sim.Text(".a+/");
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "", m_text->GetValue() );

    // Entering digits should work though and after leaving the control the
    // contents should be normalized.
    sim.Text("1234567");
    wxYield();
    text2->SetFocus();
    wxYield();
    if ( loc.IsOk() )
        CPPUNIT_ASSERT_EQUAL( "1,234,567", m_text->GetValue() );
    else
        CPPUNIT_ASSERT_EQUAL( "1234567", m_text->GetValue() );


    // Entering both '-' and '.' in this control should work but only in the
    // correct order.
    sim.Char('-');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "-", text2->GetValue() );

    text2->SetInsertionPoint(0);
    sim.Char('.');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "-", text2->GetValue() );

    text2->SetInsertionPointEnd();
    sim.Char('.');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "-.", text2->GetValue() );

    // Adding up to three digits after the point should work.
    sim.Text("987");
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "-.987", text2->GetValue() );

    // But no more.
    sim.Text("654");
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "-.987", text2->GetValue() );

    // We can remove one digit and another one though.
    sim.Char(WXK_BACK);
    sim.Char(WXK_BACK);
    sim.Char('6');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "-.96", text2->GetValue() );


    // Also test the range constraint.
    text2->Clear();

    sim.Char('9');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "9", text2->GetValue() );

    sim.Char('9');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "9", text2->GetValue() );
}
Exemplo n.º 30
0
void MainWND::OnEnter(wxCommandEvent &event)
{
//    bool loop_check;
    if(Commandline->GetValue()== wxT("read")) {
			Clear_terminal(); SOFT_TRIG(); wxYield(); Read(true); wxYield();
    } else if(Commandline->GetValue() == wxT("write0")) {
        Clear_terminal(); LOAD_RAM_DATA(0); LOAD_PATTERN(); SOFT_TRIG(); wxYield();
    } else if(Commandline->GetValue() == wxT("write1")) {
        Clear_terminal(); LOAD_RAM_DATA(1); LOAD_PATTERN(); SOFT_TRIG(); wxYield();
    } else if(Commandline->GetValue() == wxT("write2")) {
        Clear_terminal(); LOAD_RAM_DATA(2); LOAD_PATTERN(); SOFT_TRIG(); wxYield();
    } else if(Commandline->GetValue() == wxT("write3")) {
        Clear_terminal(); LOAD_RAM_DATA(3); LOAD_PATTERN(); SOFT_TRIG(); wxYield();
    } else if(Commandline->GetValue() == wxT("write4")) {
        Clear_terminal(); LOAD_RAM_DATA(4); LOAD_PATTERN(); SOFT_TRIG(); wxYield();
    } else if(Commandline->GetValue() == wxT("write5")) {
        Clear_terminal(); LOAD_RAM_DATA(5); LOAD_PATTERN(); SOFT_TRIG(); wxYield();
    } else if(Commandline->GetValue() == wxT("write6")) {
        Clear_terminal(); LOAD_RAM_DATA(6); LOAD_PATTERN(); SOFT_TRIG(); wxYield();
    } else if(Commandline->GetValue() == wxT("write7")) {
        Clear_terminal(); LOAD_RAM_DATA(7); LOAD_PATTERN(); SOFT_TRIG(); wxYield();
    } else if(Commandline->GetValue() == wxT("write8")) {
        Clear_terminal(); LOAD_RAM_DATA(8); LOAD_PATTERN(); SOFT_TRIG(); wxYield();
    } else if(Commandline->GetValue() == wxT("write9")) {
        Clear_terminal(); LOAD_RAM_DATA(9); LOAD_PATTERN(); SOFT_TRIG(); wxYield();
    } else if(Commandline->GetValue() == wxT("trig")) {
		SOFT_TRIG(); TextFrame->AppendText(wxString::Format(wxT("sending software trigger...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("bank0")) {
		set_register_bank_address(0); TextFrame->AppendText(wxString::Format(wxT("setting register bank address to 0...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("bank1")) {
		set_register_bank_address(1); TextFrame->AppendText(wxString::Format(wxT("setting register bank address to 1...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("bank2")) {
		set_register_bank_address(2); TextFrame->AppendText(wxString::Format(wxT("setting register bank address to 2...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("bank3")) {
		set_register_bank_address(3); TextFrame->AppendText(wxString::Format(wxT("setting register bank address to 3...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("writemode0")) {
		set_ram_write_mode(0); TextFrame->AppendText(wxString::Format(wxT("setting ram write mode to 0...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("writemode1")) {
		set_ram_write_mode(1); TextFrame->AppendText(wxString::Format(wxT("setting ram write mode to 1...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("writemode2")) {
		set_ram_write_mode(2); TextFrame->AppendText(wxString::Format(wxT("setting ram write mode to 2...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("writemode3")) {
		set_ram_write_mode(3); TextFrame->AppendText(wxString::Format(wxT("setting ram write mode to 3...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("readmode0")) {
		set_ram_read_mode(0); TextFrame->AppendText(wxString::Format(wxT("setting ram read mode to 0...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("readmode1")) {
		set_ram_read_mode(1); TextFrame->AppendText(wxString::Format(wxT("setting ram read mode to 1...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("readmode2")) {
		set_ram_read_mode(2); TextFrame->AppendText(wxString::Format(wxT("setting ram read mode to 2...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("readmode3")) {
		set_ram_read_mode(3); TextFrame->AppendText(wxString::Format(wxT("setting ram read mode to 3...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("trigger0")) {
		trigger_fiber_transfer(1); TextFrame->AppendText(wxString::Format(wxT("triggering fiber channel 0...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("trigger1")) {
		trigger_fiber_transfer(2); TextFrame->AppendText(wxString::Format(wxT("triggering fiber channel 1...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("trigger2")) {
		trigger_fiber_transfer(4); TextFrame->AppendText(wxString::Format(wxT("triggering fiber channel 2...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("trigger3")) {
		trigger_fiber_transfer(8); TextFrame->AppendText(wxString::Format(wxT("triggering fiber channel 3...\n"))); wxYield();
    } else if(Commandline->GetValue() == wxT("run")) {
		TextFrame->AppendText(wxString::Format(wxT("running...\n"))); wxYield();
		set_ram_read_mode(2);
		set_ram_write_mode(2);
		wxYield();
		LOAD_RAM_DATA(6); LOAD_PATTERN(); SOFT_TRIG();
		trigger_chipscope();
		wxYield();
		set_ram_read_mode(1);
		set_ram_write_mode(0);
		wxYield();
//		trigger_fiber_transfer(8);
//		trigger_fiber_transfer(1);
		trigger_fiber_transfer(4);
//		trigger_fiber_transfer(0); // turn it back off
		wxYield();
		set_ram_read_mode(2);
		set_ram_write_mode(2);
		wxYield();
		SOFT_TRIG(); wxYield(); Read(true);
		wxYield();
		TextFrame->AppendText(wxString::Format(wxT("done\n"))); wxYield();
    } else {
        Send();
	}
}