]> git.saurik.com Git - wxWidgets.git/blame - samples/exec/exec.cpp
use wxFD_XXX instead of deprecated wxXXX in the documentation
[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{
45e6e6f8
VZ
389 if ( !wxApp::OnInit() )
390 return false;
391
69c33c6c 392 // Create the main application window
be5a51fb 393 MyFrame *frame = new MyFrame(_T("Exec wxWidgets sample"),
69c33c6c
VZ
394 wxDefaultPosition, wxSize(500, 140));
395
396 // Show it and tell the application that it's our main window
07850a49 397 frame->Show(true);
69c33c6c
VZ
398 SetTopWindow(frame);
399
400 // success: wxApp::OnRun() will be called which will enter the main message
07850a49 401 // loop and the application will run. If we returned false here, the
69c33c6c 402 // application would exit immediately.
07850a49 403 return true;
69c33c6c
VZ
404}
405
406// ----------------------------------------------------------------------------
407// main frame
408// ----------------------------------------------------------------------------
409
2b5f62a0
VZ
410#ifdef __VISUALC__
411#pragma warning(disable: 4355) // this used in base member initializer list
412#endif
413
69c33c6c
VZ
414// frame constructor
415MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
07850a49 416 : wxFrame((wxFrame *)NULL, wxID_ANY, title, pos, size),
92a2a7eb 417 m_timerIdleWakeUp(this)
69c33c6c 418{
50567b69
VZ
419 m_pidLast = 0;
420
69c33c6c
VZ
421#ifdef __WXMAC__
422 // we need this in order to allow the about menu relocation, since ABOUT is
423 // not the default id of the about menu
424 wxApp::s_macAboutMenuItemId = Exec_About;
425#endif
426
69c33c6c 427 // create a menu bar
71307412 428 wxMenu *menuFile = new wxMenu(wxEmptyString, wxMENU_TEAROFF);
50567b69
VZ
429 menuFile->Append(Exec_Kill, _T("&Kill process...\tCtrl-K"),
430 _T("Kill a process by PID"));
431 menuFile->AppendSeparator();
d8e41d42
VZ
432 menuFile->Append(Exec_ClearLog, _T("&Clear log\tCtrl-C"),
433 _T("Clear the log window"));
434 menuFile->AppendSeparator();
69c33c6c
VZ
435 menuFile->Append(Exec_Quit, _T("E&xit\tAlt-X"), _T("Quit this program"));
436
437 wxMenu *execMenu = new wxMenu;
438 execMenu->Append(Exec_SyncExec, _T("Sync &execution...\tCtrl-E"),
439 _T("Launch a program and return when it terminates"));
440 execMenu->Append(Exec_AsyncExec, _T("&Async execution...\tCtrl-A"),
441 _T("Launch a program and return immediately"));
442 execMenu->Append(Exec_Shell, _T("Execute &shell command...\tCtrl-S"),
443 _T("Launch a shell and execute a command in it"));
f6bcfd97 444 execMenu->AppendSeparator();
d8e41d42
VZ
445 execMenu->Append(Exec_Redirect, _T("Capture command &output...\tCtrl-O"),
446 _T("Launch a program and capture its output"));
eb671557 447 execMenu->Append(Exec_Pipe, _T("&Pipe through command..."),
f6bcfd97 448 _T("Pipe a string through a filter"));
eb671557
VZ
449 execMenu->Append(Exec_POpen, _T("&Open a pipe to a command...\tCtrl-P"),
450 _T("Open a pipe to and from another program"));
69c33c6c 451
6ba63600
VZ
452 execMenu->AppendSeparator();
453 execMenu->Append(Exec_OpenFile, _T("Open &file...\tCtrl-F"),
454 _T("Launch the command to open this kind of files"));
ba59de5d
VZ
455 execMenu->Append(Exec_OpenURL, _T("Open &URL...\tCtrl-U"),
456 _T("Launch the default browser with the given URL"));
d93c719a
VZ
457#ifdef __WINDOWS__
458 execMenu->AppendSeparator();
459 execMenu->Append(Exec_DDEExec, _T("Execute command via &DDE...\tCtrl-D"));
ca289436 460 execMenu->Append(Exec_DDERequest, _T("Send DDE &request...\tCtrl-R"));
d93c719a
VZ
461#endif
462
71307412 463 wxMenu *helpMenu = new wxMenu(wxEmptyString, wxMENU_TEAROFF);
69c33c6c
VZ
464 helpMenu->Append(Exec_About, _T("&About...\tF1"), _T("Show about dialog"));
465
466 // now append the freshly created menu to the menu bar...
467 wxMenuBar *menuBar = new wxMenuBar();
468 menuBar->Append(menuFile, _T("&File"));
469 menuBar->Append(execMenu, _T("&Exec"));
470 menuBar->Append(helpMenu, _T("&Help"));
471
472 // ... and attach this menu bar to the frame
473 SetMenuBar(menuBar);
474
9121bed2 475 // create the listbox in which we will show misc messages as they come
07850a49 476 m_lbox = new wxListBox(this, wxID_ANY);
8ce88dfa
VZ
477 wxFont font(12, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL,
478 wxFONTWEIGHT_NORMAL);
479 if ( font.Ok() )
480 m_lbox->SetFont(font);
9121bed2 481
69c33c6c
VZ
482#if wxUSE_STATUSBAR
483 // create a status bar just for fun (by default with 1 pane only)
e680a378 484 CreateStatusBar();
be5a51fb 485 SetStatusText(_T("Welcome to wxWidgets exec sample!"));
69c33c6c
VZ
486#endif // wxUSE_STATUSBAR
487}
488
50567b69
VZ
489// ----------------------------------------------------------------------------
490// event handlers: file and help menu
491// ----------------------------------------------------------------------------
69c33c6c
VZ
492
493void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
494{
07850a49
WS
495 // true is to force the frame to close
496 Close(true);
69c33c6c
VZ
497}
498
d8e41d42
VZ
499void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
500{
501 m_lbox->Clear();
502}
503
69c33c6c
VZ
504void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
505{
749bfe9a 506 wxMessageBox(_T("Exec wxWidgets Sample\n(c) 2000-2002 Vadim Zeitlin"),
69c33c6c
VZ
507 _T("About Exec"), wxOK | wxICON_INFORMATION, this);
508}
509
50567b69
VZ
510void MyFrame::OnKill(wxCommandEvent& WXUNUSED(event))
511{
512 long pid = wxGetNumberFromUser(_T("Please specify the process to kill"),
513 _T("Enter PID:"),
514 _T("Exec question"),
515 m_pidLast,
9c05a3ca
VZ
516 // we need the full unsigned int range
517 -INT_MAX, INT_MAX,
50567b69
VZ
518 this);
519 if ( pid == -1 )
520 {
521 // cancelled
522 return;
523 }
524
525 static const wxString signalNames[] =
526 {
527 _T("Just test (SIGNONE)"),
528 _T("Hangup (SIGHUP)"),
529 _T("Interrupt (SIGINT)"),
530 _T("Quit (SIGQUIT)"),
531 _T("Illegal instruction (SIGILL)"),
532 _T("Trap (SIGTRAP)"),
533 _T("Abort (SIGABRT)"),
534 _T("Emulated trap (SIGEMT)"),
535 _T("FP exception (SIGFPE)"),
536 _T("Kill (SIGKILL)"),
537 _T("Bus (SIGBUS)"),
538 _T("Segment violation (SIGSEGV)"),
539 _T("System (SIGSYS)"),
540 _T("Broken pipe (SIGPIPE)"),
541 _T("Alarm (SIGALRM)"),
542 _T("Terminate (SIGTERM)"),
543 };
544
545 int sig = wxGetSingleChoiceIndex(_T("How to kill the process?"),
546 _T("Exec question"),
547 WXSIZEOF(signalNames), signalNames,
548 this);
549 switch ( sig )
550 {
551 default:
552 wxFAIL_MSG( _T("unexpected return value") );
553 // fall through
554
555 case -1:
556 // cancelled
557 return;
558
559 case wxSIGNONE:
560 case wxSIGHUP:
561 case wxSIGINT:
562 case wxSIGQUIT:
563 case wxSIGILL:
564 case wxSIGTRAP:
565 case wxSIGABRT:
566 case wxSIGEMT:
567 case wxSIGFPE:
568 case wxSIGKILL:
569 case wxSIGBUS:
570 case wxSIGSEGV:
571 case wxSIGSYS:
572 case wxSIGPIPE:
573 case wxSIGALRM:
574 case wxSIGTERM:
575 break;
576 }
577
578 if ( sig == 0 )
579 {
580 if ( wxProcess::Exists(pid) )
aec18ff7 581 wxLogStatus(_T("Process %ld is running."), pid);
50567b69 582 else
aec18ff7 583 wxLogStatus(_T("No process with pid = %ld."), pid);
50567b69
VZ
584 }
585 else // not SIGNONE
586 {
587 wxKillError rc = wxProcess::Kill(pid, (wxSignal)sig);
588 if ( rc == wxKILL_OK )
589 {
aec18ff7 590 wxLogStatus(_T("Process %ld killed with signal %d."), pid, sig);
50567b69
VZ
591 }
592 else
593 {
594 static const wxChar *errorText[] =
595 {
596 _T(""), // no error
597 _T("signal not supported"),
598 _T("permission denied"),
599 _T("no such process"),
600 _T("unspecified error"),
601 };
602
aec18ff7 603 wxLogStatus(_T("Failed to kill process %ld with signal %d: %s"),
50567b69
VZ
604 pid, sig, errorText[rc]);
605 }
606 }
607}
608
609// ----------------------------------------------------------------------------
610// event handlers: exec menu
611// ----------------------------------------------------------------------------
612
6ba63600
VZ
613void MyFrame::DoAsyncExec(const wxString& cmd)
614{
615 wxProcess *process = new MyProcess(this, cmd);
4c1ef422 616 m_pidLast = wxExecute(cmd, wxEXEC_ASYNC, process);
50567b69 617 if ( !m_pidLast )
6ba63600 618 {
aec18ff7 619 wxLogError( _T("Execution of '%s' failed."), cmd.c_str() );
6ba63600
VZ
620
621 delete process;
622 }
623 else
624 {
aec18ff7
MB
625 wxLogStatus( _T("Process %ld (%s) launched."),
626 m_pidLast, cmd.c_str() );
6ba63600
VZ
627
628 m_cmdLast = cmd;
629 }
630}
631
69c33c6c
VZ
632void MyFrame::OnSyncExec(wxCommandEvent& WXUNUSED(event))
633{
634 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
d93c719a 635 DIALOG_TITLE,
69c33c6c
VZ
636 m_cmdLast);
637
638 if ( !cmd )
639 return;
640
aec18ff7 641 wxLogStatus( _T("'%s' is running please wait..."), cmd.c_str() );
d31b7b68 642
4c1ef422 643 int code = wxExecute(cmd, wxEXEC_SYNC);
d31b7b68 644
69c33c6c 645 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
aec18ff7
MB
646 cmd.c_str(), code);
647
69c33c6c
VZ
648 m_cmdLast = cmd;
649}
650
651void MyFrame::OnAsyncExec(wxCommandEvent& WXUNUSED(event))
652{
653 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
d93c719a 654 DIALOG_TITLE,
69c33c6c
VZ
655 m_cmdLast);
656
657 if ( !cmd )
658 return;
659
6ba63600 660 DoAsyncExec(cmd);
69c33c6c
VZ
661}
662
663void MyFrame::OnShell(wxCommandEvent& WXUNUSED(event))
664{
665 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
d93c719a 666 DIALOG_TITLE,
69c33c6c
VZ
667 m_cmdLast);
668
669 if ( !cmd )
670 return;
671
672 int code = wxShell(cmd);
673 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
674 cmd.c_str(), code);
675 m_cmdLast = cmd;
676}
677
d8e41d42
VZ
678void MyFrame::OnExecWithRedirect(wxCommandEvent& WXUNUSED(event))
679{
680 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
681 DIALOG_TITLE,
682 m_cmdLast);
683
684 if ( !cmd )
685 return;
686
cd6ce4a9
VZ
687 bool sync;
688 switch ( wxMessageBox(_T("Execute it synchronously?"),
689 _T("Exec question"),
690 wxYES_NO | wxCANCEL | wxICON_QUESTION, this) )
d8e41d42 691 {
cd6ce4a9 692 case wxYES:
07850a49 693 sync = true;
cd6ce4a9 694 break;
d8e41d42 695
cd6ce4a9 696 case wxNO:
07850a49 697 sync = false;
cd6ce4a9
VZ
698 break;
699
700 default:
701 return;
d8e41d42 702 }
cd6ce4a9
VZ
703
704 if ( sync )
d8e41d42 705 {
f6bcfd97
BP
706 wxArrayString output, errors;
707 int code = wxExecute(cmd, output, errors);
cd6ce4a9
VZ
708 wxLogStatus(_T("command '%s' terminated with exit code %d."),
709 cmd.c_str(), code);
710
711 if ( code != -1 )
712 {
f6bcfd97
BP
713 ShowOutput(cmd, output, _T("Output"));
714 ShowOutput(cmd, errors, _T("Errors"));
cd6ce4a9
VZ
715 }
716 }
717 else // async exec
718 {
719 MyPipedProcess *process = new MyPipedProcess(this, cmd);
4c1ef422 720 if ( !wxExecute(cmd, wxEXEC_ASYNC, process) )
cd6ce4a9
VZ
721 {
722 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
723
724 delete process;
725 }
726 else
727 {
92a2a7eb 728 AddAsyncProcess(process);
cd6ce4a9 729 }
d8e41d42 730 }
cd6ce4a9
VZ
731
732 m_cmdLast = cmd;
d8e41d42
VZ
733}
734
f6bcfd97
BP
735void MyFrame::OnExecWithPipe(wxCommandEvent& WXUNUSED(event))
736{
737 if ( !m_cmdLast )
738 m_cmdLast = _T("tr [a-z] [A-Z]");
739
740 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
741 DIALOG_TITLE,
742 m_cmdLast);
743
744 if ( !cmd )
745 return;
746
747 wxString input = wxGetTextFromUser(_T("Enter the string to send to it: "),
748 DIALOG_TITLE);
749 if ( !input )
750 return;
751
752 // always execute the filter asynchronously
753 MyPipedProcess2 *process = new MyPipedProcess2(this, cmd, input);
aec18ff7 754 long pid = wxExecute(cmd, wxEXEC_ASYNC, process);
f6bcfd97
BP
755 if ( pid )
756 {
aec18ff7 757 wxLogStatus( _T("Process %ld (%s) launched."), pid, cmd.c_str() );
f6bcfd97 758
92a2a7eb 759 AddAsyncProcess(process);
f6bcfd97
BP
760 }
761 else
762 {
763 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
764
765 delete process;
766 }
767
768 m_cmdLast = cmd;
769}
770
87728739 771void MyFrame::OnPOpen(wxCommandEvent& WXUNUSED(event))
eb671557
VZ
772{
773 wxString cmd = wxGetTextFromUser(_T("Enter the command to launch: "),
774 DIALOG_TITLE,
775 m_cmdLast);
776 if ( cmd.empty() )
777 return;
778
779 wxProcess *process = wxProcess::Open(cmd);
780 if ( !process )
781 {
782 wxLogError(_T("Failed to launch the command."));
783 return;
784 }
785
a387938f
JS
786 wxLogVerbose(_T("PID of the new process: %ld"), process->GetPid());
787
eb671557
VZ
788 wxOutputStream *out = process->GetOutputStream();
789 if ( !out )
790 {
791 wxLogError(_T("Failed to connect to child stdin"));
792 return;
793 }
794
795 wxInputStream *in = process->GetInputStream();
796 if ( !in )
797 {
798 wxLogError(_T("Failed to connect to child stdout"));
799 return;
800 }
801
802 new MyPipeFrame(this, cmd, process);
803}
804
87728739 805void MyFrame::OnFileExec(wxCommandEvent& WXUNUSED(event))
6ba63600
VZ
806{
807 static wxString s_filename;
808
71307412
WS
809 wxString filename;
810
811#if wxUSE_FILEDLG
ba59de5d
VZ
812 filename = wxLoadFileSelector(_T("any file"), NULL, s_filename, this);
813#else // !wxUSE_FILEDLG
814 filename = wxGetTextFromUser(_T("Enter the file name"), _T("exec sample"),
815 s_filename, this);
816#endif // wxUSE_FILEDLG/!wxUSE_FILEDLG
71307412
WS
817
818 if ( filename.empty() )
6ba63600
VZ
819 return;
820
821 s_filename = filename;
822
823 wxString ext = filename.AfterFirst(_T('.'));
824 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
825 if ( !ft )
826 {
827 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
828 ext.c_str());
829 return;
830 }
831
832 wxString cmd;
833 bool ok = ft->GetOpenCommand(&cmd,
71307412 834 wxFileType::MessageParameters(filename));
6ba63600
VZ
835 delete ft;
836 if ( !ok )
837 {
838 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
839 ext.c_str());
840 return;
841 }
842
843 DoAsyncExec(cmd);
844}
845
ba59de5d
VZ
846void MyFrame::OnOpenURL(wxCommandEvent& WXUNUSED(event))
847{
848 static wxString s_filename;
849
850 wxString filename = wxGetTextFromUser
851 (
852 _T("Enter the URL"),
853 _T("exec sample"),
854 s_filename,
855 this
856 );
857
858 if ( filename.empty() )
859 return;
860
861 s_filename = filename;
862
863 if ( !wxLaunchDefaultBrowser(s_filename) )
864 wxLogError(_T("Failed to open URL \"%s\""), s_filename.c_str());
865}
866
50567b69
VZ
867// ----------------------------------------------------------------------------
868// DDE stuff
869// ----------------------------------------------------------------------------
870
d93c719a 871#ifdef __WINDOWS__
ca289436
VZ
872
873bool MyFrame::GetDDEServer()
874{
d93c719a 875 wxString server = wxGetTextFromUser(_T("Server to connect to:"),
ca289436 876 DIALOG_TITLE, m_server);
d93c719a 877 if ( !server )
07850a49 878 return false;
ca289436
VZ
879
880 m_server = server;
d93c719a 881
ca289436 882 wxString topic = wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE, m_topic);
d93c719a 883 if ( !topic )
07850a49 884 return false;
d93c719a 885
ca289436
VZ
886 m_topic = topic;
887
888 wxString cmd = wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE, m_cmdDde);
d93c719a 889 if ( !cmd )
07850a49 890 return false;
ca289436
VZ
891
892 m_cmdDde = cmd;
893
07850a49 894 return true;
ca289436
VZ
895}
896
897void MyFrame::OnDDEExec(wxCommandEvent& WXUNUSED(event))
898{
899 if ( !GetDDEServer() )
d93c719a
VZ
900 return;
901
902 wxDDEClient client;
71307412 903 wxConnectionBase *conn = client.MakeConnection(wxEmptyString, m_server, m_topic);
d93c719a
VZ
904 if ( !conn )
905 {
906 wxLogError(_T("Failed to connect to the DDE server '%s'."),
ca289436 907 m_server.c_str());
d93c719a
VZ
908 }
909 else
910 {
ca289436 911 if ( !conn->Execute(m_cmdDde) )
d93c719a
VZ
912 {
913 wxLogError(_T("Failed to execute command '%s' via DDE."),
ca289436 914 m_cmdDde.c_str());
d93c719a
VZ
915 }
916 else
917 {
918 wxLogStatus(_T("Successfully executed DDE command"));
919 }
920 }
d93c719a
VZ
921}
922
ca289436
VZ
923void MyFrame::OnDDERequest(wxCommandEvent& WXUNUSED(event))
924{
925 if ( !GetDDEServer() )
926 return;
927
928 wxDDEClient client;
71307412 929 wxConnectionBase *conn = client.MakeConnection(wxEmptyString, m_server, m_topic);
ca289436
VZ
930 if ( !conn )
931 {
932 wxLogError(_T("Failed to connect to the DDE server '%s'."),
933 m_server.c_str());
934 }
935 else
936 {
937 if ( !conn->Request(m_cmdDde) )
938 {
939 wxLogError(_T("Failed to send request '%s' via DDE."),
940 m_cmdDde.c_str());
941 }
942 else
943 {
944 wxLogStatus(_T("Successfully sent DDE request."));
945 }
946 }
947}
948
949#endif // __WINDOWS__
950
50567b69
VZ
951// ----------------------------------------------------------------------------
952// various helpers
953// ----------------------------------------------------------------------------
954
cd6ce4a9
VZ
955// input polling
956void MyFrame::OnIdle(wxIdleEvent& event)
957{
958 size_t count = m_running.GetCount();
959 for ( size_t n = 0; n < count; n++ )
960 {
961 if ( m_running[n]->HasInput() )
962 {
963 event.RequestMore();
964 }
965 }
966}
967
92a2a7eb
VZ
968void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event))
969{
970 wxWakeUpIdle();
971}
972
f6bcfd97
BP
973void MyFrame::OnProcessTerminated(MyPipedProcess *process)
974{
92a2a7eb 975 RemoveAsyncProcess(process);
f6bcfd97
BP
976}
977
978
979void MyFrame::ShowOutput(const wxString& cmd,
980 const wxArrayString& output,
981 const wxString& title)
982{
983 size_t count = output.GetCount();
984 if ( !count )
985 return;
986
987 m_lbox->Append(wxString::Format(_T("--- %s of '%s' ---"),
988 title.c_str(), cmd.c_str()));
989
990 for ( size_t n = 0; n < count; n++ )
991 {
992 m_lbox->Append(output[n]);
993 }
994
eb671557
VZ
995 m_lbox->Append(wxString::Format(_T("--- End of %s ---"),
996 title.Lower().c_str()));
f6bcfd97
BP
997}
998
69c33c6c
VZ
999// ----------------------------------------------------------------------------
1000// MyProcess
1001// ----------------------------------------------------------------------------
1002
1003void MyProcess::OnTerminate(int pid, int status)
1004{
1005 wxLogStatus(m_parent, _T("Process %u ('%s') terminated with exit code %d."),
1006 pid, m_cmd.c_str(), status);
1007
1008 // we're not needed any more
1009 delete this;
1010}
d8e41d42 1011
cd6ce4a9
VZ
1012// ----------------------------------------------------------------------------
1013// MyPipedProcess
1014// ----------------------------------------------------------------------------
1015
1016bool MyPipedProcess::HasInput()
d8e41d42 1017{
07850a49 1018 bool hasInput = false;
f6bcfd97 1019
92a2a7eb 1020 if ( IsInputAvailable() )
cd6ce4a9 1021 {
92a2a7eb 1022 wxTextInputStream tis(*GetInputStream());
cd6ce4a9
VZ
1023
1024 // this assumes that the output is always line buffered
1025 wxString msg;
f6bcfd97 1026 msg << m_cmd << _T(" (stdout): ") << tis.ReadLine();
d8e41d42 1027
cd6ce4a9
VZ
1028 m_parent->GetLogListBox()->Append(msg);
1029
07850a49 1030 hasInput = true;
cd6ce4a9 1031 }
f6bcfd97 1032
92a2a7eb 1033 if ( IsErrorAvailable() )
d8e41d42 1034 {
92a2a7eb 1035 wxTextInputStream tis(*GetErrorStream());
f6bcfd97
BP
1036
1037 // this assumes that the output is always line buffered
1038 wxString msg;
1039 msg << m_cmd << _T(" (stderr): ") << tis.ReadLine();
1040
1041 m_parent->GetLogListBox()->Append(msg);
1042
07850a49 1043 hasInput = true;
d8e41d42 1044 }
f6bcfd97
BP
1045
1046 return hasInput;
cd6ce4a9
VZ
1047}
1048
1049void MyPipedProcess::OnTerminate(int pid, int status)
1050{
1051 // show the rest of the output
1052 while ( HasInput() )
1053 ;
1054
1055 m_parent->OnProcessTerminated(this);
d8e41d42
VZ
1056
1057 MyProcess::OnTerminate(pid, status);
1058}
f6bcfd97
BP
1059
1060// ----------------------------------------------------------------------------
1061// MyPipedProcess2
1062// ----------------------------------------------------------------------------
1063
1064bool MyPipedProcess2::HasInput()
1065{
11fdee42 1066 if ( !m_input.empty() )
f6bcfd97
BP
1067 {
1068 wxTextOutputStream os(*GetOutputStream());
1069 os.WriteString(m_input);
1070
1071 CloseOutput();
1072 m_input.clear();
1073
1074 // call us once again - may be we'll have output
07850a49 1075 return true;
f6bcfd97
BP
1076 }
1077
1078 return MyPipedProcess::HasInput();
1079}
eb671557
VZ
1080
1081// ============================================================================
1082// MyPipeFrame implementation
1083// ============================================================================
1084
1085MyPipeFrame::MyPipeFrame(wxFrame *parent,
1086 const wxString& cmd,
1087 wxProcess *process)
07850a49 1088 : wxFrame(parent, wxID_ANY, cmd),
eb671557
VZ
1089 m_process(process),
1090 // in a real program we'd check that the streams are !NULL here
f6def1fa 1091 m_out(*process->GetOutputStream()),
eb671557 1092 m_in(*process->GetInputStream()),
f6def1fa 1093 m_err(*process->GetErrorStream())
eb671557 1094{
7ca528cb
VZ
1095 m_process->SetNextHandler(this);
1096
07850a49 1097 wxPanel *panel = new wxPanel(this, wxID_ANY);
7ca528cb 1098
71307412 1099 m_textOut = new wxTextCtrl(panel, wxID_ANY, wxEmptyString,
eb671557
VZ
1100 wxDefaultPosition, wxDefaultSize,
1101 wxTE_PROCESS_ENTER);
71307412 1102 m_textIn = new wxTextCtrl(panel, wxID_ANY, wxEmptyString,
1a278e7b
VZ
1103 wxDefaultPosition, wxDefaultSize,
1104 wxTE_MULTILINE | wxTE_RICH);
1105 m_textIn->SetEditable(false);
71307412 1106 m_textErr = new wxTextCtrl(panel, wxID_ANY, wxEmptyString,
1a278e7b
VZ
1107 wxDefaultPosition, wxDefaultSize,
1108 wxTE_MULTILINE | wxTE_RICH);
1109 m_textErr->SetEditable(false);
eb671557
VZ
1110
1111 wxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
1a278e7b 1112 sizerTop->Add(m_textOut, 0, wxGROW | wxALL, 5);
eb671557
VZ
1113
1114 wxSizer *sizerBtns = new wxBoxSizer(wxHORIZONTAL);
1a278e7b
VZ
1115 sizerBtns->
1116 Add(new wxButton(panel, Exec_Btn_Send, _T("&Send")), 0, wxALL, 5);
1117 sizerBtns->
1118 Add(new wxButton(panel, Exec_Btn_SendFile, _T("&File...")), 0, wxALL, 5);
1119 sizerBtns->
1120 Add(new wxButton(panel, Exec_Btn_Get, _T("&Get")), 0, wxALL, 5);
1121 sizerBtns->
1122 Add(new wxButton(panel, Exec_Btn_Close, _T("&Close")), 0, wxALL, 5);
eb671557
VZ
1123
1124 sizerTop->Add(sizerBtns, 0, wxCENTRE | wxALL, 5);
1a278e7b
VZ
1125 sizerTop->Add(m_textIn, 1, wxGROW | wxALL, 5);
1126 sizerTop->Add(m_textErr, 1, wxGROW | wxALL, 5);
eb671557 1127
7ca528cb 1128 panel->SetSizer(sizerTop);
eb671557
VZ
1129 sizerTop->Fit(this);
1130
1131 Show();
1132}
1133
1a278e7b
VZ
1134void MyPipeFrame::OnBtnSendFile(wxCommandEvent& WXUNUSED(event))
1135{
71307412 1136#if wxUSE_FILEDLG
1a278e7b
VZ
1137 wxFileDialog filedlg(this, _T("Select file to send"));
1138 if ( filedlg.ShowModal() != wxID_OK )
1139 return;
1140
1141 wxFFile file(filedlg.GetFilename(), _T("r"));
1142 wxString data;
1143 if ( !file.IsOpened() || !file.ReadAll(&data) )
1144 return;
1145
1146 // can't write the entire string at once, this risk overflowing the pipe
1147 // and we would dead lock
1148 size_t len = data.length();
1149 const wxChar *pc = data.c_str();
1150 while ( len )
1151 {
1152 const size_t CHUNK_SIZE = 4096;
42d0aa30 1153 m_out.Write(pc, len > CHUNK_SIZE ? CHUNK_SIZE : len);
1a278e7b 1154
42d0aa30
VZ
1155 // note that not all data could have been written as we don't block on
1156 // the write end of the pipe
1157 const size_t lenChunk = m_out.LastWrite();
1a278e7b
VZ
1158
1159 pc += lenChunk;
1160 len -= lenChunk;
1161
1162 DoGet();
1163 }
71307412 1164#endif // wxUSE_FILEDLG
1a278e7b
VZ
1165}
1166
eb671557
VZ
1167void MyPipeFrame::DoGet()
1168{
7ca528cb
VZ
1169 // we don't have any way to be notified when any input appears on the
1170 // stream so we have to poll it :-(
1a278e7b
VZ
1171 DoGetFromStream(m_textIn, m_in);
1172 DoGetFromStream(m_textErr, m_err);
1173}
1174
1175void MyPipeFrame::DoGetFromStream(wxTextCtrl *text, wxInputStream& in)
1176{
1177 while ( in.CanRead() )
1178 {
1179 wxChar buffer[4096];
1180 buffer[in.Read(buffer, WXSIZEOF(buffer) - 1).LastRead()] = _T('\0');
7ca528cb 1181
1a278e7b
VZ
1182 text->AppendText(buffer);
1183 }
1184}
1185
1186void MyPipeFrame::DoClose()
1187{
1188 m_process->CloseOutput();
1189
1190 DisableInput();
1191}
1192
1193void MyPipeFrame::DisableInput()
1194{
1195 m_textOut->SetEditable(false);
1196 FindWindow(Exec_Btn_Send)->Disable();
1197 FindWindow(Exec_Btn_SendFile)->Disable();
1198 FindWindow(Exec_Btn_Close)->Disable();
1199}
1200
1201void MyPipeFrame::DisableOutput()
1202{
1203 FindWindow(Exec_Btn_Get)->Disable();
eb671557
VZ
1204}
1205
1206void MyPipeFrame::OnClose(wxCloseEvent& event)
1207{
7ca528cb
VZ
1208 if ( m_process )
1209 {
1210 // we're not interested in getting the process termination notification
1211 // if we are closing it ourselves
1212 wxProcess *process = m_process;
1213 m_process = NULL;
1214 process->SetNextHandler(NULL);
1215
1216 process->CloseOutput();
1217 }
eb671557
VZ
1218
1219 event.Skip();
1220}
1221
87728739 1222void MyPipeFrame::OnProcessTerm(wxProcessEvent& WXUNUSED(event))
7ca528cb 1223{
1a278e7b
VZ
1224 DoGet();
1225
7ca528cb
VZ
1226 delete m_process;
1227 m_process = NULL;
1228
1229 wxLogWarning(_T("The other process has terminated, closing"));
1230
1a278e7b
VZ
1231 DisableInput();
1232 DisableOutput();
7ca528cb 1233}