1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: exec sample demonstrates wxExecute and related functions
4 // Author: Vadim Zeitlin
8 // Copyright: (c) Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "exec.cpp"
22 #pragma interface "exec.cpp"
25 // For compilers that support precompilation, includes "wx/wx.h".
26 #include "wx/wxprec.h"
32 // for all others, include the necessary headers (this file is usually all you
33 // need because it includes almost all "standard" wxWindows headers
39 #include "wx/msgdlg.h"
40 #include "wx/textdlg.h"
41 #include "wx/listbox.h"
42 #include "wx/filedlg.h"
45 #include "wx/txtstrm.h"
47 #include "wx/process.h"
49 #include "wx/mimetype.h"
55 // ----------------------------------------------------------------------------
57 // ----------------------------------------------------------------------------
59 // Define a new application type, each program should derive a class from wxApp
60 class MyApp
: public wxApp
63 // override base class virtuals
64 // ----------------------------
66 // this one is called on application startup and is a good place for the app
67 // initialization (doing it here and not in the ctor allows to have an error
68 // return: if OnInit() returns false, the application terminates)
69 virtual bool OnInit();
72 // Define an array of process pointers used by MyFrame
74 WX_DEFINE_ARRAY(MyPipedProcess
*, MyProcessesArray
);
76 // Define a new frame type: this is going to be our main frame
77 class MyFrame
: public wxFrame
81 MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
);
83 // event handlers (these functions should _not_ be virtual)
84 void OnQuit(wxCommandEvent
& event
);
86 void OnClear(wxCommandEvent
& event
);
88 void OnSyncExec(wxCommandEvent
& event
);
89 void OnAsyncExec(wxCommandEvent
& event
);
90 void OnShell(wxCommandEvent
& event
);
91 void OnExecWithRedirect(wxCommandEvent
& event
);
92 void OnExecWithPipe(wxCommandEvent
& event
);
94 void OnFileExec(wxCommandEvent
& event
);
96 void OnDDEExec(wxCommandEvent
& event
);
98 void OnAbout(wxCommandEvent
& event
);
100 // polling output of async processes
101 void OnIdle(wxIdleEvent
& event
);
103 // for MyPipedProcess
104 void OnProcessTerminated(MyPipedProcess
*process
);
105 wxListBox
*GetLogListBox() const { return m_lbox
; }
108 void ShowOutput(const wxString
& cmd
,
109 const wxArrayString
& output
,
110 const wxString
& title
);
112 void DoAsyncExec(const wxString
& cmd
);
118 MyProcessesArray m_running
;
120 // any class wishing to process wxWindows events must use this macro
121 DECLARE_EVENT_TABLE()
124 // This is the handler for process termination events
125 class MyProcess
: public wxProcess
128 MyProcess(MyFrame
*parent
, const wxString
& cmd
)
129 : wxProcess(parent
), m_cmd(cmd
)
134 // instead of overriding this virtual function we might as well process the
135 // event from it in the frame class - this might be more convenient in some
137 virtual void OnTerminate(int pid
, int status
);
144 // A specialization of MyProcess for redirecting the output
145 class MyPipedProcess
: public MyProcess
148 MyPipedProcess(MyFrame
*parent
, const wxString
& cmd
)
149 : MyProcess(parent
, cmd
)
154 virtual void OnTerminate(int pid
, int status
);
156 virtual bool HasInput();
159 // A version of MyPipedProcess which also sends input to the stdin of the
161 class MyPipedProcess2
: public MyPipedProcess
164 MyPipedProcess2(MyFrame
*parent
, const wxString
& cmd
, const wxString
& input
)
165 : MyPipedProcess(parent
, cmd
), m_input(input
)
169 virtual bool HasInput();
175 // ----------------------------------------------------------------------------
177 // ----------------------------------------------------------------------------
179 // IDs for the controls and the menu commands
195 static const wxChar
*DIALOG_TITLE
= _T("Exec sample");
197 // ----------------------------------------------------------------------------
198 // event tables and other macros for wxWindows
199 // ----------------------------------------------------------------------------
201 // the event tables connect the wxWindows events with the functions (event
202 // handlers) which process them. It can be also done at run-time, but for the
203 // simple menu events like this the static method is much simpler.
204 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
205 EVT_MENU(Exec_Quit
, MyFrame::OnQuit
)
206 EVT_MENU(Exec_ClearLog
, MyFrame::OnClear
)
208 EVT_MENU(Exec_SyncExec
, MyFrame::OnSyncExec
)
209 EVT_MENU(Exec_AsyncExec
, MyFrame::OnAsyncExec
)
210 EVT_MENU(Exec_Shell
, MyFrame::OnShell
)
211 EVT_MENU(Exec_Redirect
, MyFrame::OnExecWithRedirect
)
212 EVT_MENU(Exec_Pipe
, MyFrame::OnExecWithPipe
)
214 EVT_MENU(Exec_OpenFile
, MyFrame::OnFileExec
)
216 EVT_MENU(Exec_DDEExec
, MyFrame::OnDDEExec
)
218 EVT_MENU(Exec_About
, MyFrame::OnAbout
)
220 EVT_IDLE(MyFrame::OnIdle
)
223 // Create a new application object: this macro will allow wxWindows to create
224 // the application object during program execution (it's better than using a
225 // static object for many reasons) and also declares the accessor function
226 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
230 // ============================================================================
232 // ============================================================================
234 // ----------------------------------------------------------------------------
235 // the application class
236 // ----------------------------------------------------------------------------
238 // `Main program' equivalent: the program execution "starts" here
241 // Create the main application window
242 MyFrame
*frame
= new MyFrame(_T("Exec wxWindows sample"),
243 wxDefaultPosition
, wxSize(500, 140));
245 // Show it and tell the application that it's our main window
249 // success: wxApp::OnRun() will be called which will enter the main message
250 // loop and the application will run. If we returned FALSE here, the
251 // application would exit immediately.
255 // ----------------------------------------------------------------------------
257 // ----------------------------------------------------------------------------
260 MyFrame::MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
)
261 : wxFrame((wxFrame
*)NULL
, -1, title
, pos
, size
)
264 // we need this in order to allow the about menu relocation, since ABOUT is
265 // not the default id of the about menu
266 wxApp::s_macAboutMenuItemId
= Exec_About
;
270 wxMenu
*menuFile
= new wxMenu(_T(""), wxMENU_TEAROFF
);
271 menuFile
->Append(Exec_ClearLog
, _T("&Clear log\tCtrl-C"),
272 _T("Clear the log window"));
273 menuFile
->AppendSeparator();
274 menuFile
->Append(Exec_Quit
, _T("E&xit\tAlt-X"), _T("Quit this program"));
276 wxMenu
*execMenu
= new wxMenu
;
277 execMenu
->Append(Exec_SyncExec
, _T("Sync &execution...\tCtrl-E"),
278 _T("Launch a program and return when it terminates"));
279 execMenu
->Append(Exec_AsyncExec
, _T("&Async execution...\tCtrl-A"),
280 _T("Launch a program and return immediately"));
281 execMenu
->Append(Exec_Shell
, _T("Execute &shell command...\tCtrl-S"),
282 _T("Launch a shell and execute a command in it"));
283 execMenu
->AppendSeparator();
284 execMenu
->Append(Exec_Redirect
, _T("Capture command &output...\tCtrl-O"),
285 _T("Launch a program and capture its output"));
286 execMenu
->Append(Exec_Pipe
, _T("&Pipe through command...\tCtrl-P"),
287 _T("Pipe a string through a filter"));
289 execMenu
->AppendSeparator();
290 execMenu
->Append(Exec_OpenFile
, _T("Open &file...\tCtrl-F"),
291 _T("Launch the command to open this kind of files"));
293 execMenu
->AppendSeparator();
294 execMenu
->Append(Exec_DDEExec
, _T("Execute command via &DDE...\tCtrl-D"));
297 wxMenu
*helpMenu
= new wxMenu(_T(""), wxMENU_TEAROFF
);
298 helpMenu
->Append(Exec_About
, _T("&About...\tF1"), _T("Show about dialog"));
300 // now append the freshly created menu to the menu bar...
301 wxMenuBar
*menuBar
= new wxMenuBar();
302 menuBar
->Append(menuFile
, _T("&File"));
303 menuBar
->Append(execMenu
, _T("&Exec"));
304 menuBar
->Append(helpMenu
, _T("&Help"));
306 // ... and attach this menu bar to the frame
309 // create the listbox in which we will show misc messages as they come
310 m_lbox
= new wxListBox(this, -1);
311 wxFont
font(12, wxFONTFAMILY_TELETYPE
, wxFONTSTYLE_NORMAL
,
312 wxFONTWEIGHT_NORMAL
);
314 m_lbox
->SetFont(font
);
317 // create a status bar just for fun (by default with 1 pane only)
319 SetStatusText(_T("Welcome to wxWindows exec sample!"));
320 #endif // wxUSE_STATUSBAR
326 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
328 // TRUE is to force the frame to close
332 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
337 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
339 wxMessageBox(_T("Exec sample\n© 2000 Vadim Zeitlin"),
340 _T("About Exec"), wxOK
| wxICON_INFORMATION
, this);
343 void MyFrame::DoAsyncExec(const wxString
& cmd
)
345 wxProcess
*process
= new MyProcess(this, cmd
);
346 long pid
= wxExecute(cmd
, FALSE
/* async */, process
);
349 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
355 wxLogStatus(_T("Process %ld (%s) launched."), pid
, cmd
.c_str());
361 void MyFrame::OnSyncExec(wxCommandEvent
& WXUNUSED(event
))
363 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
370 wxLogStatus(_T("'%s' is running please wait..."), cmd
.c_str());
372 int code
= wxExecute(cmd
, TRUE
/* sync */);
374 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
379 void MyFrame::OnAsyncExec(wxCommandEvent
& WXUNUSED(event
))
381 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
391 void MyFrame::OnShell(wxCommandEvent
& WXUNUSED(event
))
393 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
400 int code
= wxShell(cmd
);
401 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
406 void MyFrame::OnExecWithRedirect(wxCommandEvent
& WXUNUSED(event
))
408 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
416 switch ( wxMessageBox(_T("Execute it synchronously?"),
418 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
, this) )
434 wxArrayString output
, errors
;
435 int code
= wxExecute(cmd
, output
, errors
);
436 wxLogStatus(_T("command '%s' terminated with exit code %d."),
441 ShowOutput(cmd
, output
, _T("Output"));
442 ShowOutput(cmd
, errors
, _T("Errors"));
447 MyPipedProcess
*process
= new MyPipedProcess(this, cmd
);
448 if ( !wxExecute(cmd
, FALSE
/* async */, process
) )
450 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
456 m_running
.Add(process
);
463 void MyFrame::OnExecWithPipe(wxCommandEvent
& WXUNUSED(event
))
466 m_cmdLast
= _T("tr [a-z] [A-Z]");
468 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
475 wxString input
= wxGetTextFromUser(_T("Enter the string to send to it: "),
480 // always execute the filter asynchronously
481 MyPipedProcess2
*process
= new MyPipedProcess2(this, cmd
, input
);
482 int pid
= wxExecute(cmd
, FALSE
/* async */, process
);
485 wxLogStatus(_T("Process %ld (%s) launched."), pid
, cmd
.c_str());
487 m_running
.Add(process
);
491 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
499 void MyFrame::OnFileExec(wxCommandEvent
& event
)
501 static wxString s_filename
;
503 wxString filename
= wxLoadFileSelector(_T("file"), _T(""), s_filename
);
507 s_filename
= filename
;
509 wxString ext
= filename
.AfterFirst(_T('.'));
510 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
513 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
519 bool ok
= ft
->GetOpenCommand(&cmd
,
520 wxFileType::MessageParameters(filename
, _T("")));
524 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
532 void MyFrame::OnDDEExec(wxCommandEvent
& WXUNUSED(event
))
535 wxString server
= wxGetTextFromUser(_T("Server to connect to:"),
536 DIALOG_TITLE
, _T("IExplore"));
540 wxString topic
= wxGetTextFromUser(_T("DDE topic:"),
541 DIALOG_TITLE
, _T("WWW_OpenURL"));
545 wxString cmd
= wxGetTextFromUser(_T("DDE command:"),
547 _T("\"file:F:\\wxWindows\\samples\\"
548 "image\\horse.gif\",,-1,,,,,"));
553 wxConnectionBase
*conn
= client
.MakeConnection("", server
, topic
);
556 wxLogError(_T("Failed to connect to the DDE server '%s'."),
561 if ( !conn
->Execute(cmd
) )
563 wxLogError(_T("Failed to execute command '%s' via DDE."),
568 wxLogStatus(_T("Successfully executed DDE command"));
571 #endif // __WINDOWS__
575 void MyFrame::OnIdle(wxIdleEvent
& event
)
577 size_t count
= m_running
.GetCount();
578 for ( size_t n
= 0; n
< count
; n
++ )
580 if ( m_running
[n
]->HasInput() )
587 void MyFrame::OnProcessTerminated(MyPipedProcess
*process
)
589 m_running
.Remove(process
);
593 void MyFrame::ShowOutput(const wxString
& cmd
,
594 const wxArrayString
& output
,
595 const wxString
& title
)
597 size_t count
= output
.GetCount();
601 m_lbox
->Append(wxString::Format(_T("--- %s of '%s' ---"),
602 title
.c_str(), cmd
.c_str()));
604 for ( size_t n
= 0; n
< count
; n
++ )
606 m_lbox
->Append(output
[n
]);
609 m_lbox
->Append(_T("--- End of output ---"));
612 // ----------------------------------------------------------------------------
614 // ----------------------------------------------------------------------------
616 void MyProcess::OnTerminate(int pid
, int status
)
618 wxLogStatus(m_parent
, _T("Process %u ('%s') terminated with exit code %d."),
619 pid
, m_cmd
.c_str(), status
);
621 // we're not needed any more
625 // ----------------------------------------------------------------------------
627 // ----------------------------------------------------------------------------
629 bool MyPipedProcess::HasInput()
631 bool hasInput
= FALSE
;
633 wxInputStream
& is
= *GetInputStream();
636 wxTextInputStream
tis(is
);
638 // this assumes that the output is always line buffered
640 msg
<< m_cmd
<< _T(" (stdout): ") << tis
.ReadLine();
642 m_parent
->GetLogListBox()->Append(msg
);
647 wxInputStream
& es
= *GetErrorStream();
650 wxTextInputStream
tis(es
);
652 // this assumes that the output is always line buffered
654 msg
<< m_cmd
<< _T(" (stderr): ") << tis
.ReadLine();
656 m_parent
->GetLogListBox()->Append(msg
);
664 void MyPipedProcess::OnTerminate(int pid
, int status
)
666 // show the rest of the output
670 m_parent
->OnProcessTerminated(this);
672 MyProcess::OnTerminate(pid
, status
);
675 // ----------------------------------------------------------------------------
677 // ----------------------------------------------------------------------------
679 bool MyPipedProcess2::HasInput()
683 wxTextOutputStream
os(*GetOutputStream());
684 os
.WriteString(m_input
);
689 // call us once again - may be we'll have output
693 return MyPipedProcess::HasInput();