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"
44 #include "wx/txtstrm.h"
46 #include "wx/process.h"
48 #include "wx/mimetype.h"
54 // ----------------------------------------------------------------------------
56 // ----------------------------------------------------------------------------
58 // Define a new application type, each program should derive a class from wxApp
59 class MyApp
: public wxApp
62 // override base class virtuals
63 // ----------------------------
65 // this one is called on application startup and is a good place for the app
66 // initialization (doing it here and not in the ctor allows to have an error
67 // return: if OnInit() returns false, the application terminates)
68 virtual bool OnInit();
71 // Define an array of process pointers used by MyFrame
73 WX_DEFINE_ARRAY(MyPipedProcess
*, MyProcessesArray
);
75 // Define a new frame type: this is going to be our main frame
76 class MyFrame
: public wxFrame
80 MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
);
82 // event handlers (these functions should _not_ be virtual)
83 void OnQuit(wxCommandEvent
& event
);
85 void OnClear(wxCommandEvent
& event
);
87 void OnSyncExec(wxCommandEvent
& event
);
88 void OnAsyncExec(wxCommandEvent
& event
);
89 void OnShell(wxCommandEvent
& event
);
90 void OnExecWithRedirect(wxCommandEvent
& event
);
91 void OnExecWithPipe(wxCommandEvent
& event
);
93 void OnFileExec(wxCommandEvent
& event
);
95 void OnDDEExec(wxCommandEvent
& event
);
97 void OnAbout(wxCommandEvent
& event
);
99 // polling output of async processes
100 void OnIdle(wxIdleEvent
& event
);
102 // for MyPipedProcess
103 void OnProcessTerminated(MyPipedProcess
*process
);
104 wxListBox
*GetLogListBox() const { return m_lbox
; }
107 void ShowOutput(const wxString
& cmd
,
108 const wxArrayString
& output
,
109 const wxString
& title
);
111 void DoAsyncExec(const wxString
& cmd
);
117 MyProcessesArray m_running
;
119 // any class wishing to process wxWindows events must use this macro
120 DECLARE_EVENT_TABLE()
123 // This is the handler for process termination events
124 class MyProcess
: public wxProcess
127 MyProcess(MyFrame
*parent
, const wxString
& cmd
)
128 : wxProcess(parent
), m_cmd(cmd
)
133 // instead of overriding this virtual function we might as well process the
134 // event from it in the frame class - this might be more convenient in some
136 virtual void OnTerminate(int pid
, int status
);
143 // A specialization of MyProcess for redirecting the output
144 class MyPipedProcess
: public MyProcess
147 MyPipedProcess(MyFrame
*parent
, const wxString
& cmd
)
148 : MyProcess(parent
, cmd
)
153 virtual void OnTerminate(int pid
, int status
);
155 virtual bool HasInput();
158 // A version of MyPipedProcess which also sends input to the stdin of the
160 class MyPipedProcess2
: public MyPipedProcess
163 MyPipedProcess2(MyFrame
*parent
, const wxString
& cmd
, const wxString
& input
)
164 : MyPipedProcess(parent
, cmd
), m_input(input
)
168 virtual bool HasInput();
174 // ----------------------------------------------------------------------------
176 // ----------------------------------------------------------------------------
178 // IDs for the controls and the menu commands
194 static const wxChar
*DIALOG_TITLE
= _T("Exec sample");
196 // ----------------------------------------------------------------------------
197 // event tables and other macros for wxWindows
198 // ----------------------------------------------------------------------------
200 // the event tables connect the wxWindows events with the functions (event
201 // handlers) which process them. It can be also done at run-time, but for the
202 // simple menu events like this the static method is much simpler.
203 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
204 EVT_MENU(Exec_Quit
, MyFrame::OnQuit
)
205 EVT_MENU(Exec_ClearLog
, MyFrame::OnClear
)
207 EVT_MENU(Exec_SyncExec
, MyFrame::OnSyncExec
)
208 EVT_MENU(Exec_AsyncExec
, MyFrame::OnAsyncExec
)
209 EVT_MENU(Exec_Shell
, MyFrame::OnShell
)
210 EVT_MENU(Exec_Redirect
, MyFrame::OnExecWithRedirect
)
211 EVT_MENU(Exec_Pipe
, MyFrame::OnExecWithPipe
)
213 EVT_MENU(Exec_OpenFile
, MyFrame::OnFileExec
)
215 EVT_MENU(Exec_DDEExec
, MyFrame::OnDDEExec
)
217 EVT_MENU(Exec_About
, MyFrame::OnAbout
)
219 EVT_IDLE(MyFrame::OnIdle
)
222 // Create a new application object: this macro will allow wxWindows to create
223 // the application object during program execution (it's better than using a
224 // static object for many reasons) and also declares the accessor function
225 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
229 // ============================================================================
231 // ============================================================================
233 // ----------------------------------------------------------------------------
234 // the application class
235 // ----------------------------------------------------------------------------
237 // `Main program' equivalent: the program execution "starts" here
240 // Create the main application window
241 MyFrame
*frame
= new MyFrame(_T("Exec wxWindows sample"),
242 wxDefaultPosition
, wxSize(500, 140));
244 // Show it and tell the application that it's our main window
248 // success: wxApp::OnRun() will be called which will enter the main message
249 // loop and the application will run. If we returned FALSE here, the
250 // application would exit immediately.
254 // ----------------------------------------------------------------------------
256 // ----------------------------------------------------------------------------
259 MyFrame::MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
)
260 : wxFrame((wxFrame
*)NULL
, -1, title
, pos
, size
)
263 // we need this in order to allow the about menu relocation, since ABOUT is
264 // not the default id of the about menu
265 wxApp::s_macAboutMenuItemId
= Exec_About
;
269 wxMenu
*menuFile
= new wxMenu(_T(""), wxMENU_TEAROFF
);
270 menuFile
->Append(Exec_ClearLog
, _T("&Clear log\tCtrl-C"),
271 _T("Clear the log window"));
272 menuFile
->AppendSeparator();
273 menuFile
->Append(Exec_Quit
, _T("E&xit\tAlt-X"), _T("Quit this program"));
275 wxMenu
*execMenu
= new wxMenu
;
276 execMenu
->Append(Exec_SyncExec
, _T("Sync &execution...\tCtrl-E"),
277 _T("Launch a program and return when it terminates"));
278 execMenu
->Append(Exec_AsyncExec
, _T("&Async execution...\tCtrl-A"),
279 _T("Launch a program and return immediately"));
280 execMenu
->Append(Exec_Shell
, _T("Execute &shell command...\tCtrl-S"),
281 _T("Launch a shell and execute a command in it"));
282 execMenu
->AppendSeparator();
283 execMenu
->Append(Exec_Redirect
, _T("Capture command &output...\tCtrl-O"),
284 _T("Launch a program and capture its output"));
285 execMenu
->Append(Exec_Pipe
, _T("&Pipe through command...\tCtrl-P"),
286 _T("Pipe a string through a filter"));
288 execMenu
->AppendSeparator();
289 execMenu
->Append(Exec_OpenFile
, _T("Open &file...\tCtrl-F"),
290 _T("Launch the command to open this kind of files"));
292 execMenu
->AppendSeparator();
293 execMenu
->Append(Exec_DDEExec
, _T("Execute command via &DDE...\tCtrl-D"));
296 wxMenu
*helpMenu
= new wxMenu(_T(""), wxMENU_TEAROFF
);
297 helpMenu
->Append(Exec_About
, _T("&About...\tF1"), _T("Show about dialog"));
299 // now append the freshly created menu to the menu bar...
300 wxMenuBar
*menuBar
= new wxMenuBar();
301 menuBar
->Append(menuFile
, _T("&File"));
302 menuBar
->Append(execMenu
, _T("&Exec"));
303 menuBar
->Append(helpMenu
, _T("&Help"));
305 // ... and attach this menu bar to the frame
308 // create the listbox in which we will show misc messages as they come
309 m_lbox
= new wxListBox(this, -1);
312 // create a status bar just for fun (by default with 1 pane only)
314 SetStatusText(_T("Welcome to wxWindows exec sample!"));
315 #endif // wxUSE_STATUSBAR
321 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
323 // TRUE is to force the frame to close
327 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
332 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
334 wxMessageBox(_T("Exec sample\n© 2000 Vadim Zeitlin"),
335 _T("About Exec"), wxOK
| wxICON_INFORMATION
, this);
338 void MyFrame::DoAsyncExec(const wxString
& cmd
)
340 wxProcess
*process
= new MyProcess(this, cmd
);
341 long pid
= wxExecute(cmd
, FALSE
/* async */, process
);
344 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
350 wxLogStatus(_T("Process %ld (%s) launched."), pid
, cmd
.c_str());
356 void MyFrame::OnSyncExec(wxCommandEvent
& WXUNUSED(event
))
358 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
365 wxLogStatus(_T("'%s' is running please wait..."), cmd
.c_str());
367 int code
= wxExecute(cmd
, TRUE
/* sync */);
369 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
374 void MyFrame::OnAsyncExec(wxCommandEvent
& WXUNUSED(event
))
376 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
386 void MyFrame::OnShell(wxCommandEvent
& WXUNUSED(event
))
388 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
395 int code
= wxShell(cmd
);
396 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
401 void MyFrame::OnExecWithRedirect(wxCommandEvent
& WXUNUSED(event
))
403 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
411 switch ( wxMessageBox(_T("Execute it synchronously?"),
413 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
, this) )
429 wxArrayString output
, errors
;
430 int code
= wxExecute(cmd
, output
, errors
);
431 wxLogStatus(_T("command '%s' terminated with exit code %d."),
436 ShowOutput(cmd
, output
, _T("Output"));
437 ShowOutput(cmd
, errors
, _T("Errors"));
442 MyPipedProcess
*process
= new MyPipedProcess(this, cmd
);
443 if ( !wxExecute(cmd
, FALSE
/* async */, process
) )
445 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
451 m_running
.Add(process
);
458 void MyFrame::OnExecWithPipe(wxCommandEvent
& WXUNUSED(event
))
461 m_cmdLast
= _T("tr [a-z] [A-Z]");
463 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
470 wxString input
= wxGetTextFromUser(_T("Enter the string to send to it: "),
475 // always execute the filter asynchronously
476 MyPipedProcess2
*process
= new MyPipedProcess2(this, cmd
, input
);
477 int pid
= wxExecute(cmd
, FALSE
/* async */, process
);
480 wxLogStatus(_T("Process %ld (%s) launched."), pid
, cmd
.c_str());
482 m_running
.Add(process
);
486 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
494 void MyFrame::OnFileExec(wxCommandEvent
& event
)
496 static wxString s_filename
;
498 wxString filename
= wxLoadFileSelector(_T("file"), _T(""), s_filename
);
502 s_filename
= filename
;
504 wxString ext
= filename
.AfterFirst(_T('.'));
505 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
508 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
514 bool ok
= ft
->GetOpenCommand(&cmd
,
515 wxFileType::MessageParameters(filename
, _T("")));
519 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
527 void MyFrame::OnDDEExec(wxCommandEvent
& WXUNUSED(event
))
530 wxString server
= wxGetTextFromUser(_T("Server to connect to:"),
531 DIALOG_TITLE
, _T("IExplore"));
535 wxString topic
= wxGetTextFromUser(_T("DDE topic:"),
536 DIALOG_TITLE
, _T("WWW_OpenURL"));
540 wxString cmd
= wxGetTextFromUser(_T("DDE command:"),
542 _T("\"file:F:\\wxWindows\\samples\\"
543 "image\\horse.gif\",,-1,,,,,"));
548 wxConnectionBase
*conn
= client
.MakeConnection("", server
, topic
);
551 wxLogError(_T("Failed to connect to the DDE server '%s'."),
556 if ( !conn
->Execute(cmd
) )
558 wxLogError(_T("Failed to execute command '%s' via DDE."),
563 wxLogStatus(_T("Successfully executed DDE command"));
566 #endif // __WINDOWS__
570 void MyFrame::OnIdle(wxIdleEvent
& event
)
572 size_t count
= m_running
.GetCount();
573 for ( size_t n
= 0; n
< count
; n
++ )
575 if ( m_running
[n
]->HasInput() )
582 void MyFrame::OnProcessTerminated(MyPipedProcess
*process
)
584 m_running
.Remove(process
);
588 void MyFrame::ShowOutput(const wxString
& cmd
,
589 const wxArrayString
& output
,
590 const wxString
& title
)
592 size_t count
= output
.GetCount();
596 m_lbox
->Append(wxString::Format(_T("--- %s of '%s' ---"),
597 title
.c_str(), cmd
.c_str()));
599 for ( size_t n
= 0; n
< count
; n
++ )
601 m_lbox
->Append(output
[n
]);
604 m_lbox
->Append(_T("--- End of output ---"));
607 // ----------------------------------------------------------------------------
609 // ----------------------------------------------------------------------------
611 void MyProcess::OnTerminate(int pid
, int status
)
613 wxLogStatus(m_parent
, _T("Process %u ('%s') terminated with exit code %d."),
614 pid
, m_cmd
.c_str(), status
);
616 // we're not needed any more
620 // ----------------------------------------------------------------------------
622 // ----------------------------------------------------------------------------
624 bool MyPipedProcess::HasInput()
626 bool hasInput
= FALSE
;
628 wxInputStream
& is
= *GetInputStream();
631 wxTextInputStream
tis(is
);
633 // this assumes that the output is always line buffered
635 msg
<< m_cmd
<< _T(" (stdout): ") << tis
.ReadLine();
637 m_parent
->GetLogListBox()->Append(msg
);
642 wxInputStream
& es
= *GetErrorStream();
645 wxTextInputStream
tis(es
);
647 // this assumes that the output is always line buffered
649 msg
<< m_cmd
<< _T(" (stderr): ") << tis
.ReadLine();
651 m_parent
->GetLogListBox()->Append(msg
);
659 void MyPipedProcess::OnTerminate(int pid
, int status
)
661 // show the rest of the output
665 m_parent
->OnProcessTerminated(this);
667 MyProcess::OnTerminate(pid
, status
);
670 // ----------------------------------------------------------------------------
672 // ----------------------------------------------------------------------------
674 bool MyPipedProcess2::HasInput()
678 wxTextOutputStream
os(*GetOutputStream());
679 os
.WriteString(m_input
);
684 // call us once again - may be we'll have output
688 return MyPipedProcess::HasInput();