]> git.saurik.com Git - wxWidgets.git/blame - samples/exec/exec.cpp
1. don't assert if we're passed an empty defaultDir and full path in
[wxWidgets.git] / samples / exec / exec.cpp
CommitLineData
69c33c6c
VZ
1/////////////////////////////////////////////////////////////////////////////
2// Name: exec.cpp
3// Purpose: exec sample demonstrates wxExecute and related functions
4// Author: Vadim Zeitlin
5// Modified by:
6// Created: 15.01.00
7// RCS-ID: $Id$
8// Copyright: (c) Vadim Zeitlin
9// Licence: wxWindows licence
10/////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
69c33c6c
VZ
20// For compilers that support precompilation, includes "wx/wx.h".
21#include "wx/wxprec.h"
22
23#ifdef __BORLANDC__
24 #pragma hdrstop
25#endif
26
27// for all others, include the necessary headers (this file is usually all you
be5a51fb 28// need because it includes almost all "standard" wxWidgets headers
69c33c6c
VZ
29#ifndef WX_PRECOMP
30 #include "wx/app.h"
788233da 31 #include "wx/log.h"
69c33c6c 32 #include "wx/frame.h"
92a2a7eb
VZ
33 #include "wx/panel.h"
34
35 #include "wx/timer.h"
eb671557 36
69c33c6c 37 #include "wx/utils.h"
a8f0faf3 38 #include "wx/menu.h"
eb671557 39
a8f0faf3
GRG
40 #include "wx/msgdlg.h"
41 #include "wx/textdlg.h"
8ce88dfa 42 #include "wx/filedlg.h"
50567b69 43 #include "wx/choicdlg.h"
eb671557
VZ
44
45 #include "wx/button.h"
46 #include "wx/textctrl.h"
47 #include "wx/listbox.h"
48
49 #include "wx/sizer.h"
69c33c6c
VZ
50#endif
51
d8e41d42 52#include "wx/txtstrm.h"
e4f3eb42 53#include "wx/numdlg.h"
ba59de5d 54#include "wx/textdlg.h"
1a278e7b 55#include "wx/ffile.h"
d8e41d42 56
69c33c6c
VZ
57#include "wx/process.h"
58
6ba63600
VZ
59#include "wx/mimetype.h"
60
d93c719a
VZ
61#ifdef __WINDOWS__
62 #include "wx/dde.h"
63#endif // __WINDOWS__
64
69c33c6c 65// ----------------------------------------------------------------------------
eb671557 66// the usual application and main frame classes
69c33c6c
VZ
67// ----------------------------------------------------------------------------
68
69// Define a new application type, each program should derive a class from wxApp
70class MyApp : public wxApp
71{
72public:
73 // override base class virtuals
74 // ----------------------------
75
76 // this one is called on application startup and is a good place for the app
77 // initialization (doing it here and not in the ctor allows to have an error
78 // return: if OnInit() returns false, the application terminates)
79 virtual bool OnInit();
80};
81
cd6ce4a9
VZ
82// Define an array of process pointers used by MyFrame
83class MyPipedProcess;
33eab530 84WX_DEFINE_ARRAY_PTR(MyPipedProcess *, MyProcessesArray);
cd6ce4a9 85
69c33c6c
VZ
86// Define a new frame type: this is going to be our main frame
87class MyFrame : public wxFrame
88{
89public:
90 // ctor(s)
91 MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
92
93 // event handlers (these functions should _not_ be virtual)
94 void OnQuit(wxCommandEvent& event);
95
50567b69
VZ
96 void OnKill(wxCommandEvent& event);
97
d8e41d42
VZ
98 void OnClear(wxCommandEvent& event);
99
69c33c6c
VZ
100 void OnSyncExec(wxCommandEvent& event);
101 void OnAsyncExec(wxCommandEvent& event);
102 void OnShell(wxCommandEvent& event);
d8e41d42 103 void OnExecWithRedirect(wxCommandEvent& event);
f6bcfd97
BP
104 void OnExecWithPipe(wxCommandEvent& event);
105
eb671557
VZ
106 void OnPOpen(wxCommandEvent& event);
107
6ba63600 108 void OnFileExec(wxCommandEvent& event);
ba59de5d 109 void OnOpenURL(wxCommandEvent& event);
6ba63600 110
69c33c6c
VZ
111 void OnAbout(wxCommandEvent& event);
112
cd6ce4a9 113 // polling output of async processes
92a2a7eb 114 void OnTimer(wxTimerEvent& event);
cd6ce4a9
VZ
115 void OnIdle(wxIdleEvent& event);
116
d8e41d42 117 // for MyPipedProcess
f6bcfd97 118 void OnProcessTerminated(MyPipedProcess *process);
d8e41d42
VZ
119 wxListBox *GetLogListBox() const { return m_lbox; }
120
69c33c6c 121private:
f6bcfd97
BP
122 void ShowOutput(const wxString& cmd,
123 const wxArrayString& output,
124 const wxString& title);
125
6ba63600
VZ
126 void DoAsyncExec(const wxString& cmd);
127
92a2a7eb
VZ
128 void AddAsyncProcess(MyPipedProcess *process)
129 {
130 if ( m_running.IsEmpty() )
131 {
132 // we want to start getting the timer events to ensure that a
133 // steady stream of idle events comes in -- otherwise we
134 // wouldn't be able to poll the child process input
135 m_timerIdleWakeUp.Start(100);
136 }
137 //else: the timer is already running
138
139 m_running.Add(process);
140 }
141
142 void RemoveAsyncProcess(MyPipedProcess *process)
143 {
144 m_running.Remove(process);
145
146 if ( m_running.IsEmpty() )
147 {
148 // we don't need to get idle events all the time any more
149 m_timerIdleWakeUp.Stop();
150 }
151 }
152
50567b69 153 // the PID of the last process we launched asynchronously
aec18ff7 154 long m_pidLast;
50567b69 155
ca289436 156 // last command we executed
69c33c6c
VZ
157 wxString m_cmdLast;
158
ca289436
VZ
159#ifdef __WINDOWS__
160 void OnDDEExec(wxCommandEvent& event);
161 void OnDDERequest(wxCommandEvent& event);
162
163 bool GetDDEServer();
164
165 // last params of a DDE transaction
166 wxString m_server,
167 m_topic,
168 m_cmdDde;
169#endif // __WINDOWS__
170
d8e41d42
VZ
171 wxListBox *m_lbox;
172
cd6ce4a9
VZ
173 MyProcessesArray m_running;
174
92a2a7eb
VZ
175 // the idle event wake up timer
176 wxTimer m_timerIdleWakeUp;
177
be5a51fb 178 // any class wishing to process wxWidgets events must use this macro
69c33c6c
VZ
179 DECLARE_EVENT_TABLE()
180};
181
eb671557
VZ
182// ----------------------------------------------------------------------------
183// MyPipeFrame: allows the user to communicate with the child process
184// ----------------------------------------------------------------------------
185
186class MyPipeFrame : public wxFrame
187{
188public:
189 MyPipeFrame(wxFrame *parent,
190 const wxString& cmd,
191 wxProcess *process);
192
193protected:
a0b08655
VZ
194 void OnTextEnter(wxCommandEvent& WXUNUSED(event)) { DoSend(); }
195 void OnBtnSend(wxCommandEvent& WXUNUSED(event)) { DoSend(); }
1a278e7b 196 void OnBtnSendFile(wxCommandEvent& WXUNUSED(event));
a0b08655 197 void OnBtnGet(wxCommandEvent& WXUNUSED(event)) { DoGet(); }
1a278e7b 198 void OnBtnClose(wxCommandEvent& WXUNUSED(event)) { DoClose(); }
eb671557
VZ
199
200 void OnClose(wxCloseEvent& event);
201
7ca528cb
VZ
202 void OnProcessTerm(wxProcessEvent& event);
203
204 void DoSend()
205 {
1a278e7b
VZ
206 wxString s(m_textOut->GetValue());
207 s += _T('\n');
208 m_out.Write(s.c_str(), s.length());
209 m_textOut->Clear();
7ca528cb
VZ
210
211 DoGet();
212 }
213
eb671557 214 void DoGet();
1a278e7b 215 void DoClose();
eb671557
VZ
216
217private:
1a278e7b
VZ
218 void DoGetFromStream(wxTextCtrl *text, wxInputStream& in);
219 void DisableInput();
220 void DisableOutput();
221
222
eb671557
VZ
223 wxProcess *m_process;
224
1a278e7b
VZ
225 wxOutputStream &m_out;
226 wxInputStream &m_in,
227 &m_err;
eb671557 228
1a278e7b
VZ
229 wxTextCtrl *m_textOut,
230 *m_textIn,
231 *m_textErr;
eb671557
VZ
232
233 DECLARE_EVENT_TABLE()
234};
235
236// ----------------------------------------------------------------------------
237// wxProcess-derived classes
238// ----------------------------------------------------------------------------
239
69c33c6c
VZ
240// This is the handler for process termination events
241class MyProcess : public wxProcess
242{
243public:
d8e41d42 244 MyProcess(MyFrame *parent, const wxString& cmd)
69c33c6c
VZ
245 : wxProcess(parent), m_cmd(cmd)
246 {
247 m_parent = parent;
248 }
249
250 // instead of overriding this virtual function we might as well process the
251 // event from it in the frame class - this might be more convenient in some
252 // cases
253 virtual void OnTerminate(int pid, int status);
254
d8e41d42
VZ
255protected:
256 MyFrame *m_parent;
69c33c6c
VZ
257 wxString m_cmd;
258};
259
d8e41d42
VZ
260// A specialization of MyProcess for redirecting the output
261class MyPipedProcess : public MyProcess
262{
263public:
264 MyPipedProcess(MyFrame *parent, const wxString& cmd)
265 : MyProcess(parent, cmd)
266 {
cd6ce4a9 267 Redirect();
d8e41d42
VZ
268 }
269
270 virtual void OnTerminate(int pid, int status);
cd6ce4a9 271
f6bcfd97
BP
272 virtual bool HasInput();
273};
274
275// A version of MyPipedProcess which also sends input to the stdin of the
276// child process
277class MyPipedProcess2 : public MyPipedProcess
278{
279public:
280 MyPipedProcess2(MyFrame *parent, const wxString& cmd, const wxString& input)
281 : MyPipedProcess(parent, cmd), m_input(input)
282 {
283 }
284
285 virtual bool HasInput();
286
287private:
288 wxString m_input;
d8e41d42
VZ
289};
290
69c33c6c
VZ
291// ----------------------------------------------------------------------------
292// constants
293// ----------------------------------------------------------------------------
294
295// IDs for the controls and the menu commands
296enum
297{
298 // menu items
299 Exec_Quit = 100,
50567b69 300 Exec_Kill,
d8e41d42 301 Exec_ClearLog,
69c33c6c
VZ
302 Exec_SyncExec = 200,
303 Exec_AsyncExec,
304 Exec_Shell,
eb671557 305 Exec_POpen,
6ba63600 306 Exec_OpenFile,
ba59de5d 307 Exec_OpenURL,
d93c719a 308 Exec_DDEExec,
ca289436 309 Exec_DDERequest,
d8e41d42 310 Exec_Redirect,
f6bcfd97 311 Exec_Pipe,
eb671557
VZ
312 Exec_About = 300,
313
314 // control ids
315 Exec_Btn_Send = 1000,
1a278e7b
VZ
316 Exec_Btn_SendFile,
317 Exec_Btn_Get,
318 Exec_Btn_Close
69c33c6c
VZ
319};
320
d93c719a
VZ
321static const wxChar *DIALOG_TITLE = _T("Exec sample");
322
69c33c6c 323// ----------------------------------------------------------------------------
be5a51fb 324// event tables and other macros for wxWidgets
69c33c6c
VZ
325// ----------------------------------------------------------------------------
326
be5a51fb 327// the event tables connect the wxWidgets events with the functions (event
69c33c6c
VZ
328// handlers) which process them. It can be also done at run-time, but for the
329// simple menu events like this the static method is much simpler.
330BEGIN_EVENT_TABLE(MyFrame, wxFrame)
331 EVT_MENU(Exec_Quit, MyFrame::OnQuit)
50567b69 332 EVT_MENU(Exec_Kill, MyFrame::OnKill)
d8e41d42 333 EVT_MENU(Exec_ClearLog, MyFrame::OnClear)
69c33c6c
VZ
334
335 EVT_MENU(Exec_SyncExec, MyFrame::OnSyncExec)
336 EVT_MENU(Exec_AsyncExec, MyFrame::OnAsyncExec)
337 EVT_MENU(Exec_Shell, MyFrame::OnShell)
d8e41d42 338 EVT_MENU(Exec_Redirect, MyFrame::OnExecWithRedirect)
f6bcfd97
BP
339 EVT_MENU(Exec_Pipe, MyFrame::OnExecWithPipe)
340
eb671557
VZ
341 EVT_MENU(Exec_POpen, MyFrame::OnPOpen)
342
6ba63600 343 EVT_MENU(Exec_OpenFile, MyFrame::OnFileExec)
ba59de5d 344 EVT_MENU(Exec_OpenURL, MyFrame::OnOpenURL)
6ba63600 345
5af4b77f 346#ifdef __WINDOWS__
d93c719a 347 EVT_MENU(Exec_DDEExec, MyFrame::OnDDEExec)
ca289436 348 EVT_MENU(Exec_DDERequest, MyFrame::OnDDERequest)
5af4b77f 349#endif // __WINDOWS__
eb671557 350
69c33c6c 351 EVT_MENU(Exec_About, MyFrame::OnAbout)
cd6ce4a9
VZ
352
353 EVT_IDLE(MyFrame::OnIdle)
92a2a7eb 354
07850a49 355 EVT_TIMER(wxID_ANY, MyFrame::OnTimer)
69c33c6c
VZ
356END_EVENT_TABLE()
357
eb671557
VZ
358BEGIN_EVENT_TABLE(MyPipeFrame, wxFrame)
359 EVT_BUTTON(Exec_Btn_Send, MyPipeFrame::OnBtnSend)
1a278e7b 360 EVT_BUTTON(Exec_Btn_SendFile, MyPipeFrame::OnBtnSendFile)
eb671557 361 EVT_BUTTON(Exec_Btn_Get, MyPipeFrame::OnBtnGet)
1a278e7b 362 EVT_BUTTON(Exec_Btn_Close, MyPipeFrame::OnBtnClose)
eb671557 363
07850a49 364 EVT_TEXT_ENTER(wxID_ANY, MyPipeFrame::OnTextEnter)
eb671557
VZ
365
366 EVT_CLOSE(MyPipeFrame::OnClose)
7ca528cb 367
07850a49 368 EVT_END_PROCESS(wxID_ANY, MyPipeFrame::OnProcessTerm)
eb671557
VZ
369END_EVENT_TABLE()
370
be5a51fb 371// Create a new application object: this macro will allow wxWidgets to create
69c33c6c
VZ
372// the application object during program execution (it's better than using a
373// static object for many reasons) and also declares the accessor function
374// wxGetApp() which will return the reference of the right type (i.e. MyApp and
375// not wxApp)
376IMPLEMENT_APP(MyApp)
377
378// ============================================================================
379// implementation
380// ============================================================================
381
382// ----------------------------------------------------------------------------
383// the application class
384// ----------------------------------------------------------------------------
385
386// `Main program' equivalent: the program execution "starts" here
387bool MyApp::OnInit()
388{
389 // Create the main application window
be5a51fb 390 MyFrame *frame = new MyFrame(_T("Exec wxWidgets sample"),
69c33c6c
VZ
391 wxDefaultPosition, wxSize(500, 140));
392
393 // Show it and tell the application that it's our main window
07850a49 394 frame->Show(true);
69c33c6c
VZ
395 SetTopWindow(frame);
396
397 // success: wxApp::OnRun() will be called which will enter the main message
07850a49 398 // loop and the application will run. If we returned false here, the
69c33c6c 399 // application would exit immediately.
07850a49 400 return true;
69c33c6c
VZ
401}
402
403// ----------------------------------------------------------------------------
404// main frame
405// ----------------------------------------------------------------------------
406
2b5f62a0
VZ
407#ifdef __VISUALC__
408#pragma warning(disable: 4355) // this used in base member initializer list
409#endif
410
69c33c6c
VZ
411// frame constructor
412MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
07850a49 413 : wxFrame((wxFrame *)NULL, wxID_ANY, title, pos, size),
92a2a7eb 414 m_timerIdleWakeUp(this)
69c33c6c 415{
50567b69
VZ
416 m_pidLast = 0;
417
69c33c6c
VZ
418#ifdef __WXMAC__
419 // we need this in order to allow the about menu relocation, since ABOUT is
420 // not the default id of the about menu
421 wxApp::s_macAboutMenuItemId = Exec_About;
422#endif
423
69c33c6c 424 // create a menu bar
71307412 425 wxMenu *menuFile = new wxMenu(wxEmptyString, wxMENU_TEAROFF);
50567b69
VZ
426 menuFile->Append(Exec_Kill, _T("&Kill process...\tCtrl-K"),
427 _T("Kill a process by PID"));
428 menuFile->AppendSeparator();
d8e41d42
VZ
429 menuFile->Append(Exec_ClearLog, _T("&Clear log\tCtrl-C"),
430 _T("Clear the log window"));
431 menuFile->AppendSeparator();
69c33c6c
VZ
432 menuFile->Append(Exec_Quit, _T("E&xit\tAlt-X"), _T("Quit this program"));
433
434 wxMenu *execMenu = new wxMenu;
435 execMenu->Append(Exec_SyncExec, _T("Sync &execution...\tCtrl-E"),
436 _T("Launch a program and return when it terminates"));
437 execMenu->Append(Exec_AsyncExec, _T("&Async execution...\tCtrl-A"),
438 _T("Launch a program and return immediately"));
439 execMenu->Append(Exec_Shell, _T("Execute &shell command...\tCtrl-S"),
440 _T("Launch a shell and execute a command in it"));
f6bcfd97 441 execMenu->AppendSeparator();
d8e41d42
VZ
442 execMenu->Append(Exec_Redirect, _T("Capture command &output...\tCtrl-O"),
443 _T("Launch a program and capture its output"));
eb671557 444 execMenu->Append(Exec_Pipe, _T("&Pipe through command..."),
f6bcfd97 445 _T("Pipe a string through a filter"));
eb671557
VZ
446 execMenu->Append(Exec_POpen, _T("&Open a pipe to a command...\tCtrl-P"),
447 _T("Open a pipe to and from another program"));
69c33c6c 448
6ba63600
VZ
449 execMenu->AppendSeparator();
450 execMenu->Append(Exec_OpenFile, _T("Open &file...\tCtrl-F"),
451 _T("Launch the command to open this kind of files"));
ba59de5d
VZ
452 execMenu->Append(Exec_OpenURL, _T("Open &URL...\tCtrl-U"),
453 _T("Launch the default browser with the given URL"));
d93c719a
VZ
454#ifdef __WINDOWS__
455 execMenu->AppendSeparator();
456 execMenu->Append(Exec_DDEExec, _T("Execute command via &DDE...\tCtrl-D"));
ca289436 457 execMenu->Append(Exec_DDERequest, _T("Send DDE &request...\tCtrl-R"));
d93c719a
VZ
458#endif
459
71307412 460 wxMenu *helpMenu = new wxMenu(wxEmptyString, wxMENU_TEAROFF);
69c33c6c
VZ
461 helpMenu->Append(Exec_About, _T("&About...\tF1"), _T("Show about dialog"));
462
463 // now append the freshly created menu to the menu bar...
464 wxMenuBar *menuBar = new wxMenuBar();
465 menuBar->Append(menuFile, _T("&File"));
466 menuBar->Append(execMenu, _T("&Exec"));
467 menuBar->Append(helpMenu, _T("&Help"));
468
469 // ... and attach this menu bar to the frame
470 SetMenuBar(menuBar);
471
9121bed2 472 // create the listbox in which we will show misc messages as they come
07850a49 473 m_lbox = new wxListBox(this, wxID_ANY);
8ce88dfa
VZ
474 wxFont font(12, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL,
475 wxFONTWEIGHT_NORMAL);
476 if ( font.Ok() )
477 m_lbox->SetFont(font);
9121bed2 478
69c33c6c
VZ
479#if wxUSE_STATUSBAR
480 // create a status bar just for fun (by default with 1 pane only)
e680a378 481 CreateStatusBar();
be5a51fb 482 SetStatusText(_T("Welcome to wxWidgets exec sample!"));
69c33c6c
VZ
483#endif // wxUSE_STATUSBAR
484}
485
50567b69
VZ
486// ----------------------------------------------------------------------------
487// event handlers: file and help menu
488// ----------------------------------------------------------------------------
69c33c6c
VZ
489
490void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
491{
07850a49
WS
492 // true is to force the frame to close
493 Close(true);
69c33c6c
VZ
494}
495
d8e41d42
VZ
496void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
497{
498 m_lbox->Clear();
499}
500
69c33c6c
VZ
501void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
502{
749bfe9a 503 wxMessageBox(_T("Exec wxWidgets Sample\n(c) 2000-2002 Vadim Zeitlin"),
69c33c6c
VZ
504 _T("About Exec"), wxOK | wxICON_INFORMATION, this);
505}
506
50567b69
VZ
507void MyFrame::OnKill(wxCommandEvent& WXUNUSED(event))
508{
509 long pid = wxGetNumberFromUser(_T("Please specify the process to kill"),
510 _T("Enter PID:"),
511 _T("Exec question"),
512 m_pidLast,
9c05a3ca
VZ
513 // we need the full unsigned int range
514 -INT_MAX, INT_MAX,
50567b69
VZ
515 this);
516 if ( pid == -1 )
517 {
518 // cancelled
519 return;
520 }
521
522 static const wxString signalNames[] =
523 {
524 _T("Just test (SIGNONE)"),
525 _T("Hangup (SIGHUP)"),
526 _T("Interrupt (SIGINT)"),
527 _T("Quit (SIGQUIT)"),
528 _T("Illegal instruction (SIGILL)"),
529 _T("Trap (SIGTRAP)"),
530 _T("Abort (SIGABRT)"),
531 _T("Emulated trap (SIGEMT)"),
532 _T("FP exception (SIGFPE)"),
533 _T("Kill (SIGKILL)"),
534 _T("Bus (SIGBUS)"),
535 _T("Segment violation (SIGSEGV)"),
536 _T("System (SIGSYS)"),
537 _T("Broken pipe (SIGPIPE)"),
538 _T("Alarm (SIGALRM)"),
539 _T("Terminate (SIGTERM)"),
540 };
541
542 int sig = wxGetSingleChoiceIndex(_T("How to kill the process?"),
543 _T("Exec question"),
544 WXSIZEOF(signalNames), signalNames,
545 this);
546 switch ( sig )
547 {
548 default:
549 wxFAIL_MSG( _T("unexpected return value") );
550 // fall through
551
552 case -1:
553 // cancelled
554 return;
555
556 case wxSIGNONE:
557 case wxSIGHUP:
558 case wxSIGINT:
559 case wxSIGQUIT:
560 case wxSIGILL:
561 case wxSIGTRAP:
562 case wxSIGABRT:
563 case wxSIGEMT:
564 case wxSIGFPE:
565 case wxSIGKILL:
566 case wxSIGBUS:
567 case wxSIGSEGV:
568 case wxSIGSYS:
569 case wxSIGPIPE:
570 case wxSIGALRM:
571 case wxSIGTERM:
572 break;
573 }
574
575 if ( sig == 0 )
576 {
577 if ( wxProcess::Exists(pid) )
aec18ff7 578 wxLogStatus(_T("Process %ld is running."), pid);
50567b69 579 else
aec18ff7 580 wxLogStatus(_T("No process with pid = %ld."), pid);
50567b69
VZ
581 }
582 else // not SIGNONE
583 {
584 wxKillError rc = wxProcess::Kill(pid, (wxSignal)sig);
585 if ( rc == wxKILL_OK )
586 {
aec18ff7 587 wxLogStatus(_T("Process %ld killed with signal %d."), pid, sig);
50567b69
VZ
588 }
589 else
590 {
591 static const wxChar *errorText[] =
592 {
593 _T(""), // no error
594 _T("signal not supported"),
595 _T("permission denied"),
596 _T("no such process"),
597 _T("unspecified error"),
598 };
599
aec18ff7 600 wxLogStatus(_T("Failed to kill process %ld with signal %d: %s"),
50567b69
VZ
601 pid, sig, errorText[rc]);
602 }
603 }
604}
605
606// ----------------------------------------------------------------------------
607// event handlers: exec menu
608// ----------------------------------------------------------------------------
609
6ba63600
VZ
610void MyFrame::DoAsyncExec(const wxString& cmd)
611{
612 wxProcess *process = new MyProcess(this, cmd);
4c1ef422 613 m_pidLast = wxExecute(cmd, wxEXEC_ASYNC, process);
50567b69 614 if ( !m_pidLast )
6ba63600 615 {
aec18ff7 616 wxLogError( _T("Execution of '%s' failed."), cmd.c_str() );
6ba63600
VZ
617
618 delete process;
619 }
620 else
621 {
aec18ff7
MB
622 wxLogStatus( _T("Process %ld (%s) launched."),
623 m_pidLast, cmd.c_str() );
6ba63600
VZ
624
625 m_cmdLast = cmd;
626 }
627}
628
69c33c6c
VZ
629void MyFrame::OnSyncExec(wxCommandEvent& WXUNUSED(event))
630{
631 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
d93c719a 632 DIALOG_TITLE,
69c33c6c
VZ
633 m_cmdLast);
634
635 if ( !cmd )
636 return;
637
aec18ff7 638 wxLogStatus( _T("'%s' is running please wait..."), cmd.c_str() );
d31b7b68 639
4c1ef422 640 int code = wxExecute(cmd, wxEXEC_SYNC);
d31b7b68 641
69c33c6c 642 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
aec18ff7
MB
643 cmd.c_str(), code);
644
69c33c6c
VZ
645 m_cmdLast = cmd;
646}
647
648void MyFrame::OnAsyncExec(wxCommandEvent& WXUNUSED(event))
649{
650 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
d93c719a 651 DIALOG_TITLE,
69c33c6c
VZ
652 m_cmdLast);
653
654 if ( !cmd )
655 return;
656
6ba63600 657 DoAsyncExec(cmd);
69c33c6c
VZ
658}
659
660void MyFrame::OnShell(wxCommandEvent& WXUNUSED(event))
661{
662 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
d93c719a 663 DIALOG_TITLE,
69c33c6c
VZ
664 m_cmdLast);
665
666 if ( !cmd )
667 return;
668
669 int code = wxShell(cmd);
670 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
671 cmd.c_str(), code);
672 m_cmdLast = cmd;
673}
674
d8e41d42
VZ
675void MyFrame::OnExecWithRedirect(wxCommandEvent& WXUNUSED(event))
676{
677 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
678 DIALOG_TITLE,
679 m_cmdLast);
680
681 if ( !cmd )
682 return;
683
cd6ce4a9
VZ
684 bool sync;
685 switch ( wxMessageBox(_T("Execute it synchronously?"),
686 _T("Exec question"),
687 wxYES_NO | wxCANCEL | wxICON_QUESTION, this) )
d8e41d42 688 {
cd6ce4a9 689 case wxYES:
07850a49 690 sync = true;
cd6ce4a9 691 break;
d8e41d42 692
cd6ce4a9 693 case wxNO:
07850a49 694 sync = false;
cd6ce4a9
VZ
695 break;
696
697 default:
698 return;
d8e41d42 699 }
cd6ce4a9
VZ
700
701 if ( sync )
d8e41d42 702 {
f6bcfd97
BP
703 wxArrayString output, errors;
704 int code = wxExecute(cmd, output, errors);
cd6ce4a9
VZ
705 wxLogStatus(_T("command '%s' terminated with exit code %d."),
706 cmd.c_str(), code);
707
708 if ( code != -1 )
709 {
f6bcfd97
BP
710 ShowOutput(cmd, output, _T("Output"));
711 ShowOutput(cmd, errors, _T("Errors"));
cd6ce4a9
VZ
712 }
713 }
714 else // async exec
715 {
716 MyPipedProcess *process = new MyPipedProcess(this, cmd);
4c1ef422 717 if ( !wxExecute(cmd, wxEXEC_ASYNC, process) )
cd6ce4a9
VZ
718 {
719 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
720
721 delete process;
722 }
723 else
724 {
92a2a7eb 725 AddAsyncProcess(process);
cd6ce4a9 726 }
d8e41d42 727 }
cd6ce4a9
VZ
728
729 m_cmdLast = cmd;
d8e41d42
VZ
730}
731
f6bcfd97
BP
732void MyFrame::OnExecWithPipe(wxCommandEvent& WXUNUSED(event))
733{
734 if ( !m_cmdLast )
735 m_cmdLast = _T("tr [a-z] [A-Z]");
736
737 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
738 DIALOG_TITLE,
739 m_cmdLast);
740
741 if ( !cmd )
742 return;
743
744 wxString input = wxGetTextFromUser(_T("Enter the string to send to it: "),
745 DIALOG_TITLE);
746 if ( !input )
747 return;
748
749 // always execute the filter asynchronously
750 MyPipedProcess2 *process = new MyPipedProcess2(this, cmd, input);
aec18ff7 751 long pid = wxExecute(cmd, wxEXEC_ASYNC, process);
f6bcfd97
BP
752 if ( pid )
753 {
aec18ff7 754 wxLogStatus( _T("Process %ld (%s) launched."), pid, cmd.c_str() );
f6bcfd97 755
92a2a7eb 756 AddAsyncProcess(process);
f6bcfd97
BP
757 }
758 else
759 {
760 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
761
762 delete process;
763 }
764
765 m_cmdLast = cmd;
766}
767
87728739 768void MyFrame::OnPOpen(wxCommandEvent& WXUNUSED(event))
eb671557
VZ
769{
770 wxString cmd = wxGetTextFromUser(_T("Enter the command to launch: "),
771 DIALOG_TITLE,
772 m_cmdLast);
773 if ( cmd.empty() )
774 return;
775
776 wxProcess *process = wxProcess::Open(cmd);
777 if ( !process )
778 {
779 wxLogError(_T("Failed to launch the command."));
780 return;
781 }
782
a387938f
JS
783 wxLogVerbose(_T("PID of the new process: %ld"), process->GetPid());
784
eb671557
VZ
785 wxOutputStream *out = process->GetOutputStream();
786 if ( !out )
787 {
788 wxLogError(_T("Failed to connect to child stdin"));
789 return;
790 }
791
792 wxInputStream *in = process->GetInputStream();
793 if ( !in )
794 {
795 wxLogError(_T("Failed to connect to child stdout"));
796 return;
797 }
798
799 new MyPipeFrame(this, cmd, process);
800}
801
87728739 802void MyFrame::OnFileExec(wxCommandEvent& WXUNUSED(event))
6ba63600
VZ
803{
804 static wxString s_filename;
805
71307412
WS
806 wxString filename;
807
808#if wxUSE_FILEDLG
ba59de5d
VZ
809 filename = wxLoadFileSelector(_T("any file"), NULL, s_filename, this);
810#else // !wxUSE_FILEDLG
811 filename = wxGetTextFromUser(_T("Enter the file name"), _T("exec sample"),
812 s_filename, this);
813#endif // wxUSE_FILEDLG/!wxUSE_FILEDLG
71307412
WS
814
815 if ( filename.empty() )
6ba63600
VZ
816 return;
817
818 s_filename = filename;
819
820 wxString ext = filename.AfterFirst(_T('.'));
821 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
822 if ( !ft )
823 {
824 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
825 ext.c_str());
826 return;
827 }
828
829 wxString cmd;
830 bool ok = ft->GetOpenCommand(&cmd,
71307412 831 wxFileType::MessageParameters(filename));
6ba63600
VZ
832 delete ft;
833 if ( !ok )
834 {
835 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
836 ext.c_str());
837 return;
838 }
839
840 DoAsyncExec(cmd);
841}
842
ba59de5d
VZ
843void MyFrame::OnOpenURL(wxCommandEvent& WXUNUSED(event))
844{
845 static wxString s_filename;
846
847 wxString filename = wxGetTextFromUser
848 (
849 _T("Enter the URL"),
850 _T("exec sample"),
851 s_filename,
852 this
853 );
854
855 if ( filename.empty() )
856 return;
857
858 s_filename = filename;
859
860 if ( !wxLaunchDefaultBrowser(s_filename) )
861 wxLogError(_T("Failed to open URL \"%s\""), s_filename.c_str());
862}
863
50567b69
VZ
864// ----------------------------------------------------------------------------
865// DDE stuff
866// ----------------------------------------------------------------------------
867
d93c719a 868#ifdef __WINDOWS__
ca289436
VZ
869
870bool MyFrame::GetDDEServer()
871{
d93c719a 872 wxString server = wxGetTextFromUser(_T("Server to connect to:"),
ca289436 873 DIALOG_TITLE, m_server);
d93c719a 874 if ( !server )
07850a49 875 return false;
ca289436
VZ
876
877 m_server = server;
d93c719a 878
ca289436 879 wxString topic = wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE, m_topic);
d93c719a 880 if ( !topic )
07850a49 881 return false;
d93c719a 882
ca289436
VZ
883 m_topic = topic;
884
885 wxString cmd = wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE, m_cmdDde);
d93c719a 886 if ( !cmd )
07850a49 887 return false;
ca289436
VZ
888
889 m_cmdDde = cmd;
890
07850a49 891 return true;
ca289436
VZ
892}
893
894void MyFrame::OnDDEExec(wxCommandEvent& WXUNUSED(event))
895{
896 if ( !GetDDEServer() )
d93c719a
VZ
897 return;
898
899 wxDDEClient client;
71307412 900 wxConnectionBase *conn = client.MakeConnection(wxEmptyString, m_server, m_topic);
d93c719a
VZ
901 if ( !conn )
902 {
903 wxLogError(_T("Failed to connect to the DDE server '%s'."),
ca289436 904 m_server.c_str());
d93c719a
VZ
905 }
906 else
907 {
ca289436 908 if ( !conn->Execute(m_cmdDde) )
d93c719a
VZ
909 {
910 wxLogError(_T("Failed to execute command '%s' via DDE."),
ca289436 911 m_cmdDde.c_str());
d93c719a
VZ
912 }
913 else
914 {
915 wxLogStatus(_T("Successfully executed DDE command"));
916 }
917 }
d93c719a
VZ
918}
919
ca289436
VZ
920void MyFrame::OnDDERequest(wxCommandEvent& WXUNUSED(event))
921{
922 if ( !GetDDEServer() )
923 return;
924
925 wxDDEClient client;
71307412 926 wxConnectionBase *conn = client.MakeConnection(wxEmptyString, m_server, m_topic);
ca289436
VZ
927 if ( !conn )
928 {
929 wxLogError(_T("Failed to connect to the DDE server '%s'."),
930 m_server.c_str());
931 }
932 else
933 {
934 if ( !conn->Request(m_cmdDde) )
935 {
936 wxLogError(_T("Failed to send request '%s' via DDE."),
937 m_cmdDde.c_str());
938 }
939 else
940 {
941 wxLogStatus(_T("Successfully sent DDE request."));
942 }
943 }
944}
945
946#endif // __WINDOWS__
947
50567b69
VZ
948// ----------------------------------------------------------------------------
949// various helpers
950// ----------------------------------------------------------------------------
951
cd6ce4a9
VZ
952// input polling
953void MyFrame::OnIdle(wxIdleEvent& event)
954{
955 size_t count = m_running.GetCount();
956 for ( size_t n = 0; n < count; n++ )
957 {
958 if ( m_running[n]->HasInput() )
959 {
960 event.RequestMore();
961 }
962 }
963}
964
92a2a7eb
VZ
965void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event))
966{
967 wxWakeUpIdle();
968}
969
f6bcfd97
BP
970void MyFrame::OnProcessTerminated(MyPipedProcess *process)
971{
92a2a7eb 972 RemoveAsyncProcess(process);
f6bcfd97
BP
973}
974
975
976void MyFrame::ShowOutput(const wxString& cmd,
977 const wxArrayString& output,
978 const wxString& title)
979{
980 size_t count = output.GetCount();
981 if ( !count )
982 return;
983
984 m_lbox->Append(wxString::Format(_T("--- %s of '%s' ---"),
985 title.c_str(), cmd.c_str()));
986
987 for ( size_t n = 0; n < count; n++ )
988 {
989 m_lbox->Append(output[n]);
990 }
991
eb671557
VZ
992 m_lbox->Append(wxString::Format(_T("--- End of %s ---"),
993 title.Lower().c_str()));
f6bcfd97
BP
994}
995
69c33c6c
VZ
996// ----------------------------------------------------------------------------
997// MyProcess
998// ----------------------------------------------------------------------------
999
1000void MyProcess::OnTerminate(int pid, int status)
1001{
1002 wxLogStatus(m_parent, _T("Process %u ('%s') terminated with exit code %d."),
1003 pid, m_cmd.c_str(), status);
1004
1005 // we're not needed any more
1006 delete this;
1007}
d8e41d42 1008
cd6ce4a9
VZ
1009// ----------------------------------------------------------------------------
1010// MyPipedProcess
1011// ----------------------------------------------------------------------------
1012
1013bool MyPipedProcess::HasInput()
d8e41d42 1014{
07850a49 1015 bool hasInput = false;
f6bcfd97 1016
92a2a7eb 1017 if ( IsInputAvailable() )
cd6ce4a9 1018 {
92a2a7eb 1019 wxTextInputStream tis(*GetInputStream());
cd6ce4a9
VZ
1020
1021 // this assumes that the output is always line buffered
1022 wxString msg;
f6bcfd97 1023 msg << m_cmd << _T(" (stdout): ") << tis.ReadLine();
d8e41d42 1024
cd6ce4a9
VZ
1025 m_parent->GetLogListBox()->Append(msg);
1026
07850a49 1027 hasInput = true;
cd6ce4a9 1028 }
f6bcfd97 1029
92a2a7eb 1030 if ( IsErrorAvailable() )
d8e41d42 1031 {
92a2a7eb 1032 wxTextInputStream tis(*GetErrorStream());
f6bcfd97
BP
1033
1034 // this assumes that the output is always line buffered
1035 wxString msg;
1036 msg << m_cmd << _T(" (stderr): ") << tis.ReadLine();
1037
1038 m_parent->GetLogListBox()->Append(msg);
1039
07850a49 1040 hasInput = true;
d8e41d42 1041 }
f6bcfd97
BP
1042
1043 return hasInput;
cd6ce4a9
VZ
1044}
1045
1046void MyPipedProcess::OnTerminate(int pid, int status)
1047{
1048 // show the rest of the output
1049 while ( HasInput() )
1050 ;
1051
1052 m_parent->OnProcessTerminated(this);
d8e41d42
VZ
1053
1054 MyProcess::OnTerminate(pid, status);
1055}
f6bcfd97
BP
1056
1057// ----------------------------------------------------------------------------
1058// MyPipedProcess2
1059// ----------------------------------------------------------------------------
1060
1061bool MyPipedProcess2::HasInput()
1062{
11fdee42 1063 if ( !m_input.empty() )
f6bcfd97
BP
1064 {
1065 wxTextOutputStream os(*GetOutputStream());
1066 os.WriteString(m_input);
1067
1068 CloseOutput();
1069 m_input.clear();
1070
1071 // call us once again - may be we'll have output
07850a49 1072 return true;
f6bcfd97
BP
1073 }
1074
1075 return MyPipedProcess::HasInput();
1076}
eb671557
VZ
1077
1078// ============================================================================
1079// MyPipeFrame implementation
1080// ============================================================================
1081
1082MyPipeFrame::MyPipeFrame(wxFrame *parent,
1083 const wxString& cmd,
1084 wxProcess *process)
07850a49 1085 : wxFrame(parent, wxID_ANY, cmd),
eb671557
VZ
1086 m_process(process),
1087 // in a real program we'd check that the streams are !NULL here
f6def1fa 1088 m_out(*process->GetOutputStream()),
eb671557 1089 m_in(*process->GetInputStream()),
f6def1fa 1090 m_err(*process->GetErrorStream())
eb671557 1091{
7ca528cb
VZ
1092 m_process->SetNextHandler(this);
1093
07850a49 1094 wxPanel *panel = new wxPanel(this, wxID_ANY);
7ca528cb 1095
71307412 1096 m_textOut = new wxTextCtrl(panel, wxID_ANY, wxEmptyString,
eb671557
VZ
1097 wxDefaultPosition, wxDefaultSize,
1098 wxTE_PROCESS_ENTER);
71307412 1099 m_textIn = new wxTextCtrl(panel, wxID_ANY, wxEmptyString,
1a278e7b
VZ
1100 wxDefaultPosition, wxDefaultSize,
1101 wxTE_MULTILINE | wxTE_RICH);
1102 m_textIn->SetEditable(false);
71307412 1103 m_textErr = new wxTextCtrl(panel, wxID_ANY, wxEmptyString,
1a278e7b
VZ
1104 wxDefaultPosition, wxDefaultSize,
1105 wxTE_MULTILINE | wxTE_RICH);
1106 m_textErr->SetEditable(false);
eb671557
VZ
1107
1108 wxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
1a278e7b 1109 sizerTop->Add(m_textOut, 0, wxGROW | wxALL, 5);
eb671557
VZ
1110
1111 wxSizer *sizerBtns = new wxBoxSizer(wxHORIZONTAL);
1a278e7b
VZ
1112 sizerBtns->
1113 Add(new wxButton(panel, Exec_Btn_Send, _T("&Send")), 0, wxALL, 5);
1114 sizerBtns->
1115 Add(new wxButton(panel, Exec_Btn_SendFile, _T("&File...")), 0, wxALL, 5);
1116 sizerBtns->
1117 Add(new wxButton(panel, Exec_Btn_Get, _T("&Get")), 0, wxALL, 5);
1118 sizerBtns->
1119 Add(new wxButton(panel, Exec_Btn_Close, _T("&Close")), 0, wxALL, 5);
eb671557
VZ
1120
1121 sizerTop->Add(sizerBtns, 0, wxCENTRE | wxALL, 5);
1a278e7b
VZ
1122 sizerTop->Add(m_textIn, 1, wxGROW | wxALL, 5);
1123 sizerTop->Add(m_textErr, 1, wxGROW | wxALL, 5);
eb671557 1124
7ca528cb 1125 panel->SetSizer(sizerTop);
eb671557
VZ
1126 sizerTop->Fit(this);
1127
1128 Show();
1129}
1130
1a278e7b
VZ
1131void MyPipeFrame::OnBtnSendFile(wxCommandEvent& WXUNUSED(event))
1132{
71307412 1133#if wxUSE_FILEDLG
1a278e7b
VZ
1134 wxFileDialog filedlg(this, _T("Select file to send"));
1135 if ( filedlg.ShowModal() != wxID_OK )
1136 return;
1137
1138 wxFFile file(filedlg.GetFilename(), _T("r"));
1139 wxString data;
1140 if ( !file.IsOpened() || !file.ReadAll(&data) )
1141 return;
1142
1143 // can't write the entire string at once, this risk overflowing the pipe
1144 // and we would dead lock
1145 size_t len = data.length();
1146 const wxChar *pc = data.c_str();
1147 while ( len )
1148 {
1149 const size_t CHUNK_SIZE = 4096;
42d0aa30 1150 m_out.Write(pc, len > CHUNK_SIZE ? CHUNK_SIZE : len);
1a278e7b 1151
42d0aa30
VZ
1152 // note that not all data could have been written as we don't block on
1153 // the write end of the pipe
1154 const size_t lenChunk = m_out.LastWrite();
1a278e7b
VZ
1155
1156 pc += lenChunk;
1157 len -= lenChunk;
1158
1159 DoGet();
1160 }
71307412 1161#endif // wxUSE_FILEDLG
1a278e7b
VZ
1162}
1163
eb671557
VZ
1164void MyPipeFrame::DoGet()
1165{
7ca528cb
VZ
1166 // we don't have any way to be notified when any input appears on the
1167 // stream so we have to poll it :-(
1a278e7b
VZ
1168 DoGetFromStream(m_textIn, m_in);
1169 DoGetFromStream(m_textErr, m_err);
1170}
1171
1172void MyPipeFrame::DoGetFromStream(wxTextCtrl *text, wxInputStream& in)
1173{
1174 while ( in.CanRead() )
1175 {
1176 wxChar buffer[4096];
1177 buffer[in.Read(buffer, WXSIZEOF(buffer) - 1).LastRead()] = _T('\0');
7ca528cb 1178
1a278e7b
VZ
1179 text->AppendText(buffer);
1180 }
1181}
1182
1183void MyPipeFrame::DoClose()
1184{
1185 m_process->CloseOutput();
1186
1187 DisableInput();
1188}
1189
1190void MyPipeFrame::DisableInput()
1191{
1192 m_textOut->SetEditable(false);
1193 FindWindow(Exec_Btn_Send)->Disable();
1194 FindWindow(Exec_Btn_SendFile)->Disable();
1195 FindWindow(Exec_Btn_Close)->Disable();
1196}
1197
1198void MyPipeFrame::DisableOutput()
1199{
1200 FindWindow(Exec_Btn_Get)->Disable();
eb671557
VZ
1201}
1202
1203void MyPipeFrame::OnClose(wxCloseEvent& event)
1204{
7ca528cb
VZ
1205 if ( m_process )
1206 {
1207 // we're not interested in getting the process termination notification
1208 // if we are closing it ourselves
1209 wxProcess *process = m_process;
1210 m_process = NULL;
1211 process->SetNextHandler(NULL);
1212
1213 process->CloseOutput();
1214 }
eb671557
VZ
1215
1216 event.Skip();
1217}
1218
87728739 1219void MyPipeFrame::OnProcessTerm(wxProcessEvent& WXUNUSED(event))
7ca528cb 1220{
1a278e7b
VZ
1221 DoGet();
1222
7ca528cb
VZ
1223 delete m_process;
1224 m_process = NULL;
1225
1226 wxLogWarning(_T("The other process has terminated, closing"));
1227
1a278e7b
VZ
1228 DisableInput();
1229 DisableOutput();
7ca528cb 1230}