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