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