void
mux_dialog::on_abort(wxCommandEvent &) {
#if defined(SYS_WINDOWS)
  if (m_abort_button_changed) {
    wxFileName output_file_name(static_cast<mmg_dialog *>(GetParent())->tc_output->GetValue());
    wxExecute(wxString::Format(wxT("explorer \"%s\""), output_file_name.GetPath().c_str()));
    return;
  }

  change_abort_button();
#else
  if (m_abort_button_changed)
    return;

  m_abort_button_changed = true;

  b_abort->Enable(false);
#endif

  b_ok->Enable(true);
  b_ok->SetFocus();

#if defined(SYS_WINDOWS)
  wxKill(m_pid, wxSIGKILL);
#else
  wxKill(m_pid, wxSIGTERM);
#endif
}
Exemple #2
0
void ExecTestCase::TestProcess()
{
    // test wxExecute with wxProcess
    wxProcess *proc = new wxProcess;
    long pid = wxExecute(ASYNC_COMMAND, wxEXEC_ASYNC, proc);
    CPPUNIT_ASSERT( proc->GetPid() == pid && pid != 0 );

    // we're not going to process the wxEVT_END_PROCESS event,
    // so the proc instance will auto-delete itself after we kill
    // the asynch process:
    CPPUNIT_ASSERT( wxKill(pid, wxSIGTERM) == 0 ||
                    wxKill(pid, wxSIGKILL) == 0 );


    // test wxExecute with wxProcess and REDIRECTION
    wxProcess *proc2 = new wxProcess;
    proc2->Redirect();
    CPPUNIT_ASSERT( wxExecute(COMMAND, wxEXEC_SYNC, proc2) == 0 );

    wxStringOutputStream stdout_stream;
    CPPUNIT_ASSERT( proc2->GetInputStream() );
    CPPUNIT_ASSERT_EQUAL( wxSTREAM_EOF,
        proc2->GetInputStream()->Read(stdout_stream).GetLastError() );

    wxString str(stdout_stream.GetString());
    CPPUNIT_ASSERT_EQUAL( "hi", str.Trim() );
}
Exemple #3
0
void
job_run_dialog::on_abort(wxCommandEvent &) {
  abort = true;
#if defined(SYS_WINDOWS)
  wxKill(pid, wxSIGKILL);
  if (m_taskbar_progress)
    m_taskbar_progress->set_state(TBPF_ERROR);
#else
  wxKill(pid, wxSIGTERM);
#endif
}
Exemple #4
0
/* static */
wxKillError wxProcess::Kill(int pid, wxSignal sig, int flags)
{
    wxKillError rc;
    (void)wxKill(pid, sig, &rc, flags);

    return rc;
}
Exemple #5
0
void ConsoleFinder::FreeConsole()
{
	if (m_nConsolePid) {
		wxKill(m_nConsolePid, wxSIGKILL, NULL, wxKILL_CHILDREN);
		m_nConsolePid = 0;
	}
}
void Launcher::OnCIStartButton(wxCommandEvent& WXUNUSED(event)) 
{
	if (ci_started_){
		wxKill (ci_pid_, wxSIGKILL);
		ci_started_= false;
		CIStartBtn -> SetLabel("Start");
		CIStartBtn -> SetBackgroundColour(wxColour(255, 0, 0));
		CIStartBtn -> Refresh();
	} else
	{
		wxProcess *process = new wxProcess (this);
	//	process->Redirect();
		ci_pid_ = wxExecute("qci", wxEXEC_ASYNC, process);
		if ( !ci_pid_ )
		{
			wxLogError( _T("Execution of '%s' failed."), "qci" );

			delete process;
		}
		else
		{
			// change Button
			ci_started_= true;
			CIStartBtn->SetLabel("Stop");
			CIStartBtn -> SetBackgroundColour(wxColour(0, 255, 0));
			CIStartBtn->Refresh();
		}

	}
}
void UnixProcessImpl::Terminate()
{
    wxKill(GetPid(), GetHardKill() ? wxSIGKILL : wxSIGTERM, NULL, wxKILL_CHILDREN);
    int status(0);
    // The real cleanup is done inside ::ChildTerminatedSingalHandler() signal handler (app.cpp)
    waitpid(-1, &status, WNOHANG);
}
void CPyProcess::Cancel(void)
{
	if (m_pid)
	{
		wxKillError kerror;
		wxSignal sig = wxSIGTERM;
		int retcode;

		if ( wxProcess::Exists(m_pid) ) {
			retcode = wxKill(m_pid, sig, &kerror, wxKILL_CHILDREN);
			switch (kerror) {
			case wxKILL_OK:
				wxLogMessage(_T("sent signal %d to process %d"),sig, m_pid);
				break;
			case wxKILL_NO_PROCESS:
				wxLogMessage(_T("process %d already exited"),m_pid);
				break;
			case wxKILL_ACCESS_DENIED:
				wxLogMessage(_T("sending signal %d to process %d - access denied"),sig, m_pid);
				break;
			case wxKILL_BAD_SIGNAL:      // no such signal
				wxLogMessage(_T("no such signal: %d"),sig);
				break;
			case wxKILL_ERROR:            // another, unspecified error
				wxLogMessage(_T("unspecified error sending signal %d to process %d"),sig, m_pid);
				break;
			}
		} else {
			wxLogMessage(_T("process %d has gone away"), m_pid);
		}
		m_pid = 0;
	}
}
Exemple #9
0
void rc_ide2Frame::OnStop(wxCommandEvent& event)
{
    if(pid != -1)
    {
        //wxMessageBox("Kill process");
        wxKill(pid, wxSIGKILL, NULL, wxKILL_CHILDREN);
        //std::cout << "program aborted" << endl;
        pid = -1;
    }
}
Exemple #10
0
void TerminalEmulator::Terminate()
{
    if(IsRunning()) {
        if(m_process) { m_process->Terminate(); }
        if(m_pid != wxNOT_FOUND) {
            wxKill(m_pid, wxSIGKILL, NULL, wxKILL_CHILDREN);
            m_pid = wxNOT_FOUND;
        }
    }
}
int ecKill(long pid, wxSignal sig)
{
#if defined(__UNIX__) && !defined(__CYGWIN__)
    return wxKill(pid, sig);
#elif defined(__WXMSW__)
    return wxNewKill(pid, sig);
#else
    return -1;
#endif
}
Exemple #12
0
void PipedProcess::Terminate()
{
#ifdef __WXGTK__
	wxString cmd;
	wxFileName exePath(wxStandardPaths::Get().GetExecutablePath());
	wxFileName script(exePath.GetPath(), wxT("codelite_kill_children"));
	cmd << wxT("/bin/sh -f ") << script.GetFullPath() << wxT(" ") << GetPid();
	wxExecute(cmd, wxEXEC_ASYNC);
#else
	wxKillError rc;
	wxKill(GetPid(), wxSIGKILL, &rc, wxKILL_CHILDREN);
#endif
}
Exemple #13
0
bool DbgGdb::Stop()
{
    m_goingDown = true;

    if ( !m_attachedMode ) {

        wxKill(m_debuggeePid, wxSIGKILL, NULL, wxKILL_CHILDREN);

    }

    wxCommandEvent event(wxEVT_GDB_STOP_DEBUGGER);
    EventNotifier::Get()->AddPendingEvent(event);
    return true;
}
Exemple #14
0
void ExecTestCase::TestExecute()
{
    // test sync exec (with a command not producing any output to avoid
    // interfering with the test):
    CPPUNIT_ASSERT( wxExecute(COMMAND_NO_OUTPUT, wxEXEC_SYNC) == 0 );

    // test asynch exec
    long pid = wxExecute(ASYNC_COMMAND, wxEXEC_ASYNC);
    CPPUNIT_ASSERT( pid != 0 );

    // NOTE: under Windows the first wxKill() invocation with wxSIGTERM
    //       may fail if the system is fast and the ASYNC_COMMAND app
    //       doesn't manage to create its HWND before our wxKill() is
    //       executed; in that case we "fall back" to the second invocation
    //       with wxSIGKILL (which should always succeed)
    CPPUNIT_ASSERT( wxKill(pid, wxSIGTERM) == 0 ||
                    wxKill(pid, wxSIGKILL) == 0 );

    // test running COMMAND again, but this time with redirection:
    wxArrayString stdout_arr;
    CPPUNIT_ASSERT_EQUAL( 0, wxExecute(COMMAND, stdout_arr, wxEXEC_SYNC) );
    CPPUNIT_ASSERT_EQUAL( "hi", stdout_arr[0] );
}
Exemple #15
0
void wxTerminal::DoCtrlC()
{
    if(!m_process) return;

#ifdef __WXMSW__
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)m_process->GetPid());
    if(hProcess) {
        TerminateProcess(hProcess, 0);
        CloseHandle(hProcess);
    }
#else
    // int status(0); Commented out as 'Unused variable'
    wxKill(m_process->GetPid(), wxSIGKILL, NULL, wxKILL_CHILDREN);
#endif
}
Exemple #16
0
void wxEmulatorFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
{
#ifdef __WXX11__
    if (wxGetApp().m_xnestWindow)
    {
        wxGetApp().m_xnestWindow->SetHandle((WXWindow) NULL);
    }
#endif
    this->Destroy();
    if (wxGetApp().m_xnestPID > 0)
    {
        wxKill(wxGetApp().m_xnestPID);
        wxGetApp().m_xnestPID = 0;
    }
}
void WinProcessImpl::Terminate()
{
    // terminate the process
    if (IsAlive()) {
        std::map<unsigned long, bool> tree;
        ProcUtils::GetProcTree(tree, GetPid());

        std::map<unsigned long, bool>::iterator iter = tree.begin();
        for(; iter != tree.end(); iter++) {
            wxKillError rc;
            wxKill(iter->first, wxSIGKILL, &rc);
        }
        TerminateProcess(piProcInfo.hProcess, 255);
    }
}
Exemple #18
0
// By John Skiff
int wxKillAllChildren(long pid, wxSignal sig, wxKillError *krc)
{
    InitToolHelp32();

    if (krc)
        *krc = wxKILL_OK;

    // If not implemented for this platform (e.g. NT 4.0), silently ignore
    if (!lpfCreateToolhelp32Snapshot || !lpfProcess32First || !lpfProcess32Next)
        return 0;

    // Take a snapshot of all processes in the system.
    HANDLE hProcessSnap = lpfCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hProcessSnap == INVALID_HANDLE_VALUE) {
        if (krc)
            *krc = wxKILL_ERROR;
        return -1;
    }

    //Fill in the size of the structure before using it.
    PROCESSENTRY32 pe;
    wxZeroMemory(pe);
    pe.dwSize = sizeof(PROCESSENTRY32);

    // Walk the snapshot of the processes, and for each process,
    // kill it if its parent is pid.
    if (!lpfProcess32First(hProcessSnap, &pe)) {
        // Can't get first process.
        if (krc)
            *krc = wxKILL_ERROR;
        CloseHandle (hProcessSnap);
        return -1;
    }

    do {
        if (pe.th32ParentProcessID == (DWORD) pid) {
            if (wxKill(pe.th32ProcessID, sig, krc))
                return -1;
        }
    } while (lpfProcess32Next (hProcessSnap, &pe));


    return 0;
}
void UnixProcessImpl::Cleanup()
{
    close(GetReadHandle());
    close(GetWriteHandle());

    if(m_thr) {
        // Stop the reader thread
        m_thr->Stop();
        delete m_thr;
    }
    m_thr = NULL;

    if(GetPid() != wxNOT_FOUND) {
        wxKill(GetPid(), GetHardKill() ? wxSIGKILL : wxSIGTERM, NULL, wxKILL_CHILDREN);
        // The Zombie cleanup is done in app.cpp in ::ChildTerminatedSingalHandler() signal handler
        int status(0);
        waitpid(-1, &status, WNOHANG);
    }
}
void Launcher::OnNSDStartButton(wxCommandEvent& WXUNUSED(event)) 
{
	if (nsd_started_){
		wxKill (nsd_pid_, wxSIGKILL);
		nsd_started_= false;
		NSDStartBtn->SetLabel("Start");
		NSDStartBtn -> SetBackgroundColour(wxColour(255, 0, 0));
		NSDStartBtn->Refresh();
	} else
	{
		wxString port_nr = port_number_->GetValue(); 
		
		wxString host_name = wxGetHostName();
		// get the computers name first 

		wxString cmd = "nsd -ORBIIOPAddr inet:";
		cmd.append(host_name);
		cmd.append(":");
		cmd.append(port_nr);

		wxProcess *process = new wxProcess (this);
	//	process->Redirect();
		nsd_pid_ = wxExecute(cmd, wxEXEC_ASYNC, process);
		if ( !nsd_pid_ )
		{
			wxLogError( _T("Execution of '%s' failed."), cmd.c_str() );

			delete process;
		}
		else
		{
			// change Button
			nsd_started_= true;
			NSDStartBtn->SetLabel("Stop");
			NSDStartBtn -> SetBackgroundColour(wxColour(0, 255, 0));
			NSDStartBtn->Refresh();


		}

	}
}
void WinProcessImpl::Cleanup()
{
    // Under windows, the reader thread is detached
    if ( m_thr ) {
        // Stop the reader thread
        m_thr->Stop();
        delete m_thr;
    }
    m_thr = NULL;

    // terminate the process
    if (IsAlive()) {
        std::map<unsigned long, bool> tree;
        ProcUtils::GetProcTree(tree, GetPid());

        std::map<unsigned long, bool>::iterator iter = tree.begin();
        for(; iter != tree.end(); iter++) {
            wxKillError rc;
            wxKill(iter->first, wxSIGKILL, &rc);
        }
        TerminateProcess(piProcInfo.hProcess, 255);
    }

    CloseHandle( hChildStdinRd);
    CloseHandle( hChildStdinWrDup );
    CloseHandle( hChildStdoutWr);
    CloseHandle( hChildStdoutRdDup );
    CloseHandle( hChildStderrWr);
    CloseHandle( hChildStderrRdDup );
    CloseHandle( piProcInfo.hProcess );
    CloseHandle( piProcInfo.hThread );

    hChildStdinRd       = NULL;
    hChildStdoutWr      = NULL;
    hChildStdinWrDup    = NULL;
    hChildStdoutRdDup   = NULL;
    hChildStderrWr      = NULL;
    hChildStderrRdDup   = NULL;
    piProcInfo.hProcess = NULL;
    piProcInfo.hThread  = NULL;
}
Exemple #22
0
void sysProcess::Abort()
{
	if (pid)
		wxKill(pid, wxSIGTERM);
}
//////////////////////////////////////////////////////////////////////////////
///  public SSHCacheFingerprint
///  Basically, this means that the PlinkConnect will not work until the
///      fingerprint gets cached.  To do so, I run my own, send a "y" to accept
///      the cache then immediately kill the process.
///  I am assuming!!! that the connection should work, and I'm just doing this
///     to accept the cache.
///
///  @return void
///
///  @author David Czechowski @date 04-22-2004
//////////////////////////////////////////////////////////////////////////////
bool Networking::SSHCacheFingerprint()
{
	//Start the program asynchonously, answer "y" to caching, then Kill it:

	wxString cmd = m_options->GetPlinkApp() + " " + m_currHost;
	wxProcess* proc = new wxProcess();
	proc->Redirect();
	long pid = wxExecute(cmd, wxEXEC_ASYNC, proc);
	wxTextOutputStream pout(*proc->GetOutputStream(), wxEOL_UNIX);
	pout << "y\recho \"Successful Login\"\r";

	int i = 0;

	wxProgressDialog* progress = NULL;

	wxString output;

	while(i < 240)
	{
		wxMilliSleep(250);

		if(proc->IsInputAvailable())
		{
			wxInputStream* pStdOut = proc->GetInputStream();
			while(proc->IsInputAvailable()) {
				output += pStdOut->GetC();
			}
			break;
		}

		if(progress != NULL)
		{
			progress->Pulse();
		}

		if(i % 4 == 0)
		{
			wxLogDebug("Synchronous network operation (getting fingerprint): %d", i / 4);

			if(i > 12  && progress == NULL)
			{
				progress = new wxProgressDialog("Network Operation", "This network connection may take a while...");
			}
		}

		i++;
		wxSafeYield();
	}

	if(progress != NULL)
	{
		delete progress;
	}

	wxKill(pid, wxSIGKILL);

	// must have waited for a minute with no result
	if(output.Length() == 0)
	{
		wxMessageBox("Caching the fingerprint timed out.  Try logging in with Putty, then run Chameleon again",
					"Network Error", wxOK | wxCENTRE | wxICON_ERROR);
		return false;
	}
	else
	{
		wxLogDebug("Login presumed successful.  Output: %s", output);
	}

	m_plinks->setLogin("","",""); // terminate all connections, and do a spawn
	m_status = NET_STARTING;

	return true;
}
Exemple #24
0
void ExecTestCase::TestProcess()
{
    AsyncInEventLoop asyncInEventLoop;

    // test wxExecute with wxProcess
    wxProcess *proc = new wxProcess;

    // asyncInEventLoop.DoExecute will perform the
    // call to wxExecute(ASYNC) in an event loop, as required by
    // console test (and this same event loop will also
    // be used in GUI test too, even though not required, just to have
    // common code).
    long pid = asyncInEventLoop.DoExecute(AsyncExec_ExitLoop, // Force exit of event loop right
                                                // after the call to wxExecute()
                                          ASYNC_COMMAND, wxEXEC_ASYNC, proc);
    CPPUNIT_ASSERT( proc->GetPid() == pid && pid != 0 );

    // we're not going to process the wxEVT_END_PROCESS event,
    // so the proc instance will auto-delete itself after we kill
    // the asynch process:
    CPPUNIT_ASSERT( wxKill(pid, wxSIGTERM) == 0 ||
                    wxKill(pid, wxSIGKILL) == 0 );


    // test wxExecute with wxProcess and REDIRECTION

    // Test the sync execution case with/without wxEXEC_NOEVENTS flag
    // because we use either an event loop or wxSelectDispatcher
    // depending on this flag, and we want to test both cases.

    // First the default case, dispatching the events while waiting.
    {
        wxProcess proc2;
        proc2.Redirect();
        CPPUNIT_ASSERT_EQUAL( 0, wxExecute(COMMAND, wxEXEC_SYNC, &proc2) );

        wxStringOutputStream procOutput;
        CPPUNIT_ASSERT( proc2.GetInputStream() );
        CPPUNIT_ASSERT_EQUAL( wxSTREAM_EOF,
            proc2.GetInputStream()->Read(procOutput).GetLastError() );

        wxString output = procOutput.GetString();
        CPPUNIT_ASSERT_EQUAL( "hi", output.Trim() );
    }

    // And now without event dispatching.
    {
        wxProcess proc2;
        proc2.Redirect();
        CPPUNIT_ASSERT_EQUAL( 0,
            wxExecute(COMMAND, wxEXEC_SYNC | wxEXEC_NOEVENTS, &proc2) );

        wxStringOutputStream procOutput;
        CPPUNIT_ASSERT( proc2.GetInputStream() );
        CPPUNIT_ASSERT_EQUAL( wxSTREAM_EOF,
            proc2.GetInputStream()->Read(procOutput).GetLastError() );

        wxString output = procOutput.GetString();
        CPPUNIT_ASSERT_EQUAL( "hi", output.Trim() );
    }
}
Exemple #25
0
void ExecTestCase::TestExecute()
{
    AsyncInEventLoop asyncInEventLoop;

    // test asynch exec
    //
    // asyncInEventLoop.DoExecute will perform the
    // call to wxExecute(ASYNC) in an event loop, as required by
    // console test (and this same event loop will also
    // be used in GUI test too, even though not required, just to have
    // common code).
    long pid = asyncInEventLoop.DoExecute(AsyncExec_ExitLoop, // Force exit of event loop right
                                                // after the call to wxExecute()
                                          ASYNC_COMMAND, wxEXEC_ASYNC);
    CPPUNIT_ASSERT( pid != 0 );

    // NOTE: under Windows the first wxKill() invocation with wxSIGTERM
    //       may fail if the system is fast and the ASYNC_COMMAND app
    //       doesn't manage to create its HWND before our wxKill() is
    //       executed; in that case we "fall back" to the second invocation
    //       with wxSIGKILL (which should always succeed)
    CPPUNIT_ASSERT( wxKill(pid, wxSIGTERM) == 0 ||
                    wxKill(pid, wxSIGKILL) == 0 );

    int useNoeventsFlag;

    // Test the sync execution case with/without wxEXEC_NOEVENTS flag
    // because we use either an event loop or wxSelectDispatcher
    // depending on this flag, and we want to test both cases.
    for (useNoeventsFlag = 0; useNoeventsFlag <=1 ; ++useNoeventsFlag )
    {
        int execFlags = wxEXEC_SYNC;

        if (useNoeventsFlag)
        {
            execFlags |= wxEXEC_NOEVENTS;
        }

        // test sync exec (with a command not producing any output to avoid
        // interfering with the test):
        CPPUNIT_ASSERT( wxExecute(COMMAND_NO_OUTPUT, execFlags) == 0 );

        // test running COMMAND again, but this time with redirection:
        // and the expected data is on stdout.
        wxArrayString stdout_arr;
        CPPUNIT_ASSERT_EQUAL( 0, wxExecute(COMMAND, stdout_arr, execFlags) );
        CPPUNIT_ASSERT_EQUAL( "hi", stdout_arr[0] );

        // test running COMMAND_STDERR with redirection and the expected data
        // is on stderr.
        wxArrayString stderr_arr;
        stdout_arr.Empty();
        CPPUNIT_ASSERT( wxExecute(COMMAND_STDERR, stdout_arr, stderr_arr, execFlags) != 0 );

        // Check that there is something on stderr.
        // In Unix systems, the 'cat' command has the name of the file it could not
        // find in the error output.
        // In Windows, the 'type' command outputs the following when it can't find
        // a file:
        // "The system cannot find the file specified"
        // In both cases, we expect the word 'file' to be in the stderr.
        CPPUNIT_ASSERT( stderr_arr[0].Contains("file") );
    }
}
Exemple #26
0
int bmx_wxkill(int pid, int signal, wxKillError * rc, int flags) {
	return wxKill(pid, static_cast<wxSignal>(signal), rc, flags);
}
Exemple #27
0
int bmx_wxkill(long pid, wxSignal signal, wxKillError * rc, int flags) {
	return wxKill(pid, signal, rc, flags);
}
Exemple #28
0
bool App::OnInit()
{
    _dlgPrefPtr = nullptr;

    //Re direction des logs ver la sorti standard.
    wxLog* logger = new wxLogStream(&std::cout);
    wxLog::SetActiveTarget(logger);

    //Changement du préfixe seulement sous unix
#if defined(__UNIX__)
    wxStandardPaths::Get().SetInstallPrefix("/usr");
#endif

    //Chemin vair le fichier d'instance du programme.
    wxString fileSingleInstance = wxStandardPaths::Get().GetTempDir()+'/'+PROJECT_NAME+'-'+wxGetUserId();
    //Si le fichier existe ceci veux dire qu'il y a une autre instances de ce
    //programme en cour d'exécution.
    if(wxFileExists(fileSingleInstance))
    {
        //On lis le pid de l'autre instances.
        int pid;
        wxFile file(fileSingleInstance);
        file.Read(&pid, sizeof pid);
        file.Close();

        //Et on luis envois le signale USER1.
        if(wxKill(pid, (wxSignal)SIGUSR1) == 0)
        {
            wxLogMessage(PROJECT_NAME" is already running ...");
            return false;
        }
    }

    //Si le fichier n'existe pas, alors on le crée avec le pid de
    //cette instances.
    int pid = getpid();
    wxFile file(fileSingleInstance, wxFile::write);
    file.Write(&pid, sizeof pid);
    file.Close();

    //Installassions du gestionnaire de signale.
    //Pour récupère le signale USER1.
    std::signal(SIGUSR1, signal_user1);
    evtHandlerMain = this;

    //Init général
    wxInitAllImageHandlers();
    SetExitOnFrameDelete(false);

    //Création de tout les managers.
    Manager::createManagers();

    //Chargement de la confige de tous les manager.
    Manager::loadManagers();

    //Bind.
    Bind(wxEVT_COMMAND_MENU_SELECTED, &App::onQuit, this, ID_QUIT);
    Bind(wxEVT_COMMAND_MENU_SELECTED, &App::onAbout, this, ID_ABOUT);
    Bind(wxEVT_COMMAND_MENU_SELECTED, &App::onPreferences, this, ID_PREFERENCES);
    Bind(wxEVT_COMMAND_MENU_SELECTED, &App::onEnableShortcuts, this, ID_ENABLE_SHORTKUT);

#ifdef DEV_RUN_START_PREFERENCES
    //Envoi d'un évènement pour afficher les préférences.
    wxCommandEvent *event =
        new wxCommandEvent(wxEVT_COMMAND_MENU_SELECTED, ID_PREFERENCES);
    wxQueueEvent(this, event);
#endif

    return true;
}
Exemple #29
0
bool RecFile::Decode( wxArrayPtrVoid params, AxProgressDlg *dlg )
{
	wxASSERT_MSG( m_imPagePtr, "ImPage cannot be NULL" );
	wxASSERT_MSG( dlg, "AxProgressDlg cannot be NULL" );
	
    // params 0: RecTypModel: typModelPtr
	// params 1: RecMusModel: musModelPtr
	// params 2: bool: rec_delayed
	// params 3: int: rec_lm_order
	// params 4: double: rec_lm_scaling
	// params 5: wxString: rec_wrdtrns
	
	RecTypModel *typModelPtr = (RecTypModel*)params[0];
	RecMusModel *musModelPtr = (RecMusModel*)params[1];
	bool rec_delayed =  *(bool*)params[2];
	int rec_lm_order =  *(int*)params[3];
	if ( rec_lm_order > MUS_NGRAM_ORDER )
		rec_lm_order = MUS_NGRAM_ORDER;
	double rec_lm_scaling =  *(double*)params[4];
	wxString rec_wrdtrns =  *(wxString*)params[5];
	
	wxString input = m_basename + "mfc.input";
	input.Replace( "\\/", "/" );
	wxString rec_models = typModelPtr->m_basename + "hmm";
	wxString rec_dict = typModelPtr->m_basename + "dic";
	wxString rec_lm = musModelPtr->m_basename + "ngram.gram";
	wxString rec_output = m_basename + "rec.mlf";
	// cannot be changed from interface
	double rec_phone_pen = RecEnv::s_rec_phone_pen;
	double rec_int_prune = RecEnv::s_rec_int_prune;
	double rec_word_pen = RecEnv::s_rec_word_pen;
    
	
#ifdef AX_CMDLINE
    wxString log = AxApp::GetLogDir() + "/decoder.log";
    
    MlDecoder *decoder = new MlDecoder( input, rec_models, rec_dict );
    
    decoder->log_fname = log;
    decoder->am_models_fname = rec_models;
    decoder->am_sil_phone = "{s}";
    decoder->am_phone_del_pen = rec_phone_pen;
     
    decoder->lex_dict_fname = rec_dict;
     
    if ( rec_lm_order && !rec_lm.IsEmpty() )
    {
        decoder->lm_fname = musModelPtr->m_basename + "ngram.gram";
        decoder->lm_ngram_order = rec_lm_order;
        decoder->lm_scaling_factor = rec_lm_scaling;
    }
     
    if ( rec_int_prune != 0.0 )
        decoder->dec_int_prune_window = rec_int_prune;
     
    if ( rec_word_pen != 0.0 )
        decoder->dec_word_entr_pen = rec_word_pen;
     
    if ( rec_delayed )
        decoder->dec_delayed_lm = true;
     
    if ( !rec_output.IsEmpty() )
        decoder->output_fname = rec_output;
     
    if ( !rec_wrdtrns.IsEmpty() )
        decoder->wrdtrns_fname = rec_wrdtrns;

    decoder->Run();

#else
    
#ifdef __WXMSW__
#if defined(_DEBUG)
    wxString cmd = "Decoder.exe";
#else
    wxString cmd = "Decoder.exe";
#endif
#elif __WXGTK__
#if defined(__DEBUG__)
    wxString cmd = "decoderd";
#else
    wxString cmd = "decoder";
#endif
#else
#ifdef __AXDEBUG__
    wxString cmd = "decoder";
#else
    wxString cmd = "decoder";
#endif
#endif
    
	wxString args = " ";
	
	wxString log = AxApp::GetLogDir() + "/decoder.log";
	
	args << " -am_models_fname " << "\"" << rec_models.c_str() << "\"";
	args << " -am_sil_phone \"{s}\" ";
	args << " -am_phone_del_pen " << rec_phone_pen;
    
	args << " -lex_dict_fname " << "\"" << rec_dict.c_str() << "\"";
    
	if ( rec_lm_order && !rec_lm.IsEmpty() )
	{
		args << " -lm_fname " << "\"" << rec_lm << "\"";
		args << " -lm_ngram_order " << rec_lm_order;
		args << " -lm_scaling_factor " << rec_lm_scaling;
	}
	
	if ( rec_int_prune != 0.0 )
		args << " -dec_int_prune_window " << rec_int_prune;
    
	if ( rec_word_pen != 0.0 )
		args << " -dec_word_entr_pen " << rec_word_pen;
    
	if ( rec_delayed )
		args << " -dec_delayed_lm";
    
	args << " -input_fname " << "\"" << input.c_str() << "\"";
	
	if ( !rec_output.IsEmpty() )
		args << " -output_fname " << "\"" << rec_output.c_str() << "\"";
    
	if ( !rec_wrdtrns.IsEmpty() )
		args << " -wrdtrns_fname " << "\"" << rec_wrdtrns.c_str() << "\"";
    
	wxLogDebug( args.c_str() );
    
	if (!dlg->SetOperation( _("Recognition...") ) )
		return this->Terminate( ERR_CANCELED );
    
	dlg->StartTimerOperation( TIMER_DECODING, m_imPagePtr->GetStaffCount() );
	int pid;
	AxProcess *process = new AxProcess( cmd, args, NULL );
	process->SetLog( log );
	if ( process->Start() )
	{
		pid = process->GetPid();
		while  ( !process->HasEnded() )
		{
			if( !dlg->IncTimerOperation( ) )
			{
				wxKill( pid, wxSIGKILL );
				AxYield();
				delete process;
				return this->Terminate( ERR_CANCELED );
			}
			wxMilliSleep( 200 );
		}
		
	}
	AxYield(); // flush termination event before deleting the process.
	if ( process->m_status != 0 )
	{
		delete process;
		return this->Terminate( ERR_UNKNOWN );
	}
	dlg->EndTimerOperation( TIMER_DECODING );
	delete process;
    
#endif // AX_CMDLINE
    
    
	/*Torch::DiskXFile::setBigEndianMode() ;
     
     wxString input = wxGetApp().m_workingDir + "/" + imPage->GetShortName() + ".input";
     input.Replace( "\\/", "/" );
     
     Torch::LexiconInfo lex_info( m_rec_models.c_str() , "{s}" , "" , m_rec_dict.c_str() ,
     "" , "" , "" ) ;
     
     Torch::PhoneModels phone_models ( lex_info.phone_info , (char*) m_rec_models.c_str(),
     true , m_rec_phone_pen ,
     false , "" , "" ,
     9 , "" , false ,
     (real)0.005 , (real)0.005 ) ;
     
     Torch::LinearLexicon lexicon( &lex_info , &phone_models ) ;
     
     Torch::LanguageModel *lang_model;
     if ( m_rec_lm_order <= 0 )
     lang_model = NULL ;
     else
     {
     lang_model = new Torch::LanguageModel( m_rec_lm_order , lex_info.vocabulary ,
     (char*)m_rec_lm.c_str() , m_rec_ls_scaling ) ;
     }
     
     real end_prune = m_rec_end_prune;
     if ( end_prune == 0 )
     end_prune = LOG_ZERO;
     Torch::BeamSearchDecoder bs_decoder( &lexicon , lang_model , m_rec_word_pen ,
     LOG_ZERO, end_prune ,
     m_rec_delayed , false ) ;
     
     
     Torch::DecoderBatchTest batch_tester( (char*)input.c_str() , Torch::DST_FEATS_HTK , (char*)m_rec_wrdtrns.c_str()  , &bs_decoder ,
     true , true , (char*)m_rec_output.c_str() , false , 10.0 ) ;
     
     batch_tester.run() ;
     
     if ( lang_model != NULL )
     delete lang_model ; 
     return(0) ;*/
    
	return true;
}