]> git.saurik.com Git - wxWidgets.git/blob - samples/exec/exec.cpp
added commands to test how busy cursor behaves during wxExecute()
[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 wxArrayString output, errors;
751 int code = wxExecute(cmd, output, errors);
752 wxLogStatus(_T("command '%s' terminated with exit code %d."),
753 cmd.c_str(), code);
754
755 if ( code != -1 )
756 {
757 ShowOutput(cmd, output, _T("Output"));
758 ShowOutput(cmd, errors, _T("Errors"));
759 }
760 }
761 else // async exec
762 {
763 MyPipedProcess *process = new MyPipedProcess(this, cmd);
764 if ( !wxExecute(cmd, wxEXEC_ASYNC, process) )
765 {
766 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
767
768 delete process;
769 }
770 else
771 {
772 AddAsyncProcess(process);
773 }
774 }
775
776 m_cmdLast = cmd;
777 }
778
779 void MyFrame::OnExecWithPipe(wxCommandEvent& WXUNUSED(event))
780 {
781 if ( !m_cmdLast )
782 m_cmdLast = _T("tr [a-z] [A-Z]");
783
784 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
785 DIALOG_TITLE,
786 m_cmdLast);
787
788 if ( !cmd )
789 return;
790
791 wxString input = wxGetTextFromUser(_T("Enter the string to send to it: "),
792 DIALOG_TITLE);
793 if ( !input )
794 return;
795
796 // always execute the filter asynchronously
797 MyPipedProcess2 *process = new MyPipedProcess2(this, cmd, input);
798 long pid = wxExecute(cmd, wxEXEC_ASYNC, process);
799 if ( pid )
800 {
801 wxLogStatus( _T("Process %ld (%s) launched."), pid, cmd.c_str() );
802
803 AddAsyncProcess(process);
804 }
805 else
806 {
807 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
808
809 delete process;
810 }
811
812 m_cmdLast = cmd;
813 }
814
815 void MyFrame::OnPOpen(wxCommandEvent& WXUNUSED(event))
816 {
817 wxString cmd = wxGetTextFromUser(_T("Enter the command to launch: "),
818 DIALOG_TITLE,
819 m_cmdLast);
820 if ( cmd.empty() )
821 return;
822
823 wxProcess *process = wxProcess::Open(cmd);
824 if ( !process )
825 {
826 wxLogError(_T("Failed to launch the command."));
827 return;
828 }
829
830 wxLogVerbose(_T("PID of the new process: %ld"), process->GetPid());
831
832 wxOutputStream *out = process->GetOutputStream();
833 if ( !out )
834 {
835 wxLogError(_T("Failed to connect to child stdin"));
836 return;
837 }
838
839 wxInputStream *in = process->GetInputStream();
840 if ( !in )
841 {
842 wxLogError(_T("Failed to connect to child stdout"));
843 return;
844 }
845
846 new MyPipeFrame(this, cmd, process);
847 }
848
849 void MyFrame::OnFileExec(wxCommandEvent& WXUNUSED(event))
850 {
851 static wxString s_filename;
852
853 wxString filename;
854
855 #if wxUSE_FILEDLG
856 filename = wxLoadFileSelector(_T("any file"), wxEmptyString, s_filename, this);
857 #else // !wxUSE_FILEDLG
858 filename = wxGetTextFromUser(_T("Enter the file name"), _T("exec sample"),
859 s_filename, this);
860 #endif // wxUSE_FILEDLG/!wxUSE_FILEDLG
861
862 if ( filename.empty() )
863 return;
864
865 s_filename = filename;
866
867 wxString ext = filename.AfterFirst(_T('.'));
868 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
869 if ( !ft )
870 {
871 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
872 ext.c_str());
873 return;
874 }
875
876 wxString cmd;
877 bool ok = ft->GetOpenCommand(&cmd,
878 wxFileType::MessageParameters(filename));
879 delete ft;
880 if ( !ok )
881 {
882 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
883 ext.c_str());
884 return;
885 }
886
887 DoAsyncExec(cmd);
888 }
889
890 void MyFrame::OnOpenURL(wxCommandEvent& WXUNUSED(event))
891 {
892 static wxString s_filename(_T("http://www.wxwidgets.org/"));
893
894 wxString filename = wxGetTextFromUser
895 (
896 _T("Enter the URL"),
897 _T("exec sample"),
898 s_filename,
899 this
900 );
901
902 if ( filename.empty() )
903 return;
904
905 s_filename = filename;
906
907 if ( !wxLaunchDefaultBrowser(s_filename) )
908 wxLogError(_T("Failed to open URL \"%s\""), s_filename.c_str());
909 }
910
911 // ----------------------------------------------------------------------------
912 // DDE stuff
913 // ----------------------------------------------------------------------------
914
915 #ifdef __WINDOWS__
916
917 bool MyFrame::GetDDEServer()
918 {
919 wxString server = wxGetTextFromUser(_T("Server to connect to:"),
920 DIALOG_TITLE, m_server);
921 if ( !server )
922 return false;
923
924 m_server = server;
925
926 wxString topic = wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE, m_topic);
927 if ( !topic )
928 return false;
929
930 m_topic = topic;
931
932 wxString cmd = wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE, m_cmdDde);
933 if ( !cmd )
934 return false;
935
936 m_cmdDde = cmd;
937
938 return true;
939 }
940
941 void MyFrame::OnDDEExec(wxCommandEvent& WXUNUSED(event))
942 {
943 if ( !GetDDEServer() )
944 return;
945
946 wxDDEClient client;
947 wxConnectionBase *conn = client.MakeConnection(wxEmptyString, m_server, m_topic);
948 if ( !conn )
949 {
950 wxLogError(_T("Failed to connect to the DDE server '%s'."),
951 m_server.c_str());
952 }
953 else
954 {
955 if ( !conn->Execute(m_cmdDde) )
956 {
957 wxLogError(_T("Failed to execute command '%s' via DDE."),
958 m_cmdDde.c_str());
959 }
960 else
961 {
962 wxLogStatus(_T("Successfully executed DDE command"));
963 }
964 }
965 }
966
967 void MyFrame::OnDDERequest(wxCommandEvent& WXUNUSED(event))
968 {
969 if ( !GetDDEServer() )
970 return;
971
972 wxDDEClient client;
973 wxConnectionBase *conn = client.MakeConnection(wxEmptyString, m_server, m_topic);
974 if ( !conn )
975 {
976 wxLogError(_T("Failed to connect to the DDE server '%s'."),
977 m_server.c_str());
978 }
979 else
980 {
981 if ( !conn->Request(m_cmdDde) )
982 {
983 wxLogError(_T("Failed to send request '%s' via DDE."),
984 m_cmdDde.c_str());
985 }
986 else
987 {
988 wxLogStatus(_T("Successfully sent DDE request."));
989 }
990 }
991 }
992
993 #endif // __WINDOWS__
994
995 // ----------------------------------------------------------------------------
996 // various helpers
997 // ----------------------------------------------------------------------------
998
999 // input polling
1000 void MyFrame::OnIdle(wxIdleEvent& event)
1001 {
1002 size_t count = m_running.GetCount();
1003 for ( size_t n = 0; n < count; n++ )
1004 {
1005 if ( m_running[n]->HasInput() )
1006 {
1007 event.RequestMore();
1008 }
1009 }
1010 }
1011
1012 void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event))
1013 {
1014 wxWakeUpIdle();
1015 }
1016
1017 void MyFrame::OnProcessTerminated(MyPipedProcess *process)
1018 {
1019 RemoveAsyncProcess(process);
1020 }
1021
1022
1023 void MyFrame::ShowOutput(const wxString& cmd,
1024 const wxArrayString& output,
1025 const wxString& title)
1026 {
1027 size_t count = output.GetCount();
1028 if ( !count )
1029 return;
1030
1031 m_lbox->Append(wxString::Format(_T("--- %s of '%s' ---"),
1032 title.c_str(), cmd.c_str()));
1033
1034 for ( size_t n = 0; n < count; n++ )
1035 {
1036 m_lbox->Append(output[n]);
1037 }
1038
1039 m_lbox->Append(wxString::Format(_T("--- End of %s ---"),
1040 title.Lower().c_str()));
1041 }
1042
1043 // ----------------------------------------------------------------------------
1044 // MyProcess
1045 // ----------------------------------------------------------------------------
1046
1047 void MyProcess::OnTerminate(int pid, int status)
1048 {
1049 wxLogStatus(m_parent, _T("Process %u ('%s') terminated with exit code %d."),
1050 pid, m_cmd.c_str(), status);
1051
1052 // we're not needed any more
1053 delete this;
1054 }
1055
1056 // ----------------------------------------------------------------------------
1057 // MyPipedProcess
1058 // ----------------------------------------------------------------------------
1059
1060 bool MyPipedProcess::HasInput()
1061 {
1062 bool hasInput = false;
1063
1064 if ( IsInputAvailable() )
1065 {
1066 wxTextInputStream tis(*GetInputStream());
1067
1068 // this assumes that the output is always line buffered
1069 wxString msg;
1070 msg << m_cmd << _T(" (stdout): ") << tis.ReadLine();
1071
1072 m_parent->GetLogListBox()->Append(msg);
1073
1074 hasInput = true;
1075 }
1076
1077 if ( IsErrorAvailable() )
1078 {
1079 wxTextInputStream tis(*GetErrorStream());
1080
1081 // this assumes that the output is always line buffered
1082 wxString msg;
1083 msg << m_cmd << _T(" (stderr): ") << tis.ReadLine();
1084
1085 m_parent->GetLogListBox()->Append(msg);
1086
1087 hasInput = true;
1088 }
1089
1090 return hasInput;
1091 }
1092
1093 void MyPipedProcess::OnTerminate(int pid, int status)
1094 {
1095 // show the rest of the output
1096 while ( HasInput() )
1097 ;
1098
1099 m_parent->OnProcessTerminated(this);
1100
1101 MyProcess::OnTerminate(pid, status);
1102 }
1103
1104 // ----------------------------------------------------------------------------
1105 // MyPipedProcess2
1106 // ----------------------------------------------------------------------------
1107
1108 bool MyPipedProcess2::HasInput()
1109 {
1110 if ( !m_input.empty() )
1111 {
1112 wxTextOutputStream os(*GetOutputStream());
1113 os.WriteString(m_input);
1114
1115 CloseOutput();
1116 m_input.clear();
1117
1118 // call us once again - may be we'll have output
1119 return true;
1120 }
1121
1122 return MyPipedProcess::HasInput();
1123 }
1124
1125 // ============================================================================
1126 // MyPipeFrame implementation
1127 // ============================================================================
1128
1129 MyPipeFrame::MyPipeFrame(wxFrame *parent,
1130 const wxString& cmd,
1131 wxProcess *process)
1132 : wxFrame(parent, wxID_ANY, cmd),
1133 m_process(process),
1134 // in a real program we'd check that the streams are !NULL here
1135 m_out(*process->GetOutputStream()),
1136 m_in(*process->GetInputStream()),
1137 m_err(*process->GetErrorStream())
1138 {
1139 m_process->SetNextHandler(this);
1140
1141 wxPanel *panel = new wxPanel(this, wxID_ANY);
1142
1143 m_textOut = new wxTextCtrl(panel, wxID_ANY, wxEmptyString,
1144 wxDefaultPosition, wxDefaultSize,
1145 wxTE_PROCESS_ENTER);
1146 m_textIn = new wxTextCtrl(panel, wxID_ANY, wxEmptyString,
1147 wxDefaultPosition, wxDefaultSize,
1148 wxTE_MULTILINE | wxTE_RICH);
1149 m_textIn->SetEditable(false);
1150 m_textErr = new wxTextCtrl(panel, wxID_ANY, wxEmptyString,
1151 wxDefaultPosition, wxDefaultSize,
1152 wxTE_MULTILINE | wxTE_RICH);
1153 m_textErr->SetEditable(false);
1154
1155 wxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
1156 sizerTop->Add(m_textOut, 0, wxGROW | wxALL, 5);
1157
1158 wxSizer *sizerBtns = new wxBoxSizer(wxHORIZONTAL);
1159 sizerBtns->
1160 Add(new wxButton(panel, Exec_Btn_Send, _T("&Send")), 0, wxALL, 5);
1161 sizerBtns->
1162 Add(new wxButton(panel, Exec_Btn_SendFile, _T("&File...")), 0, wxALL, 5);
1163 sizerBtns->
1164 Add(new wxButton(panel, Exec_Btn_Get, _T("&Get")), 0, wxALL, 5);
1165 sizerBtns->
1166 Add(new wxButton(panel, Exec_Btn_Close, _T("&Close")), 0, wxALL, 5);
1167
1168 sizerTop->Add(sizerBtns, 0, wxCENTRE | wxALL, 5);
1169 sizerTop->Add(m_textIn, 1, wxGROW | wxALL, 5);
1170 sizerTop->Add(m_textErr, 1, wxGROW | wxALL, 5);
1171
1172 panel->SetSizer(sizerTop);
1173 sizerTop->Fit(this);
1174
1175 Show();
1176 }
1177
1178 void MyPipeFrame::OnBtnSendFile(wxCommandEvent& WXUNUSED(event))
1179 {
1180 #if wxUSE_FILEDLG
1181 wxFileDialog filedlg(this, _T("Select file to send"));
1182 if ( filedlg.ShowModal() != wxID_OK )
1183 return;
1184
1185 wxFFile file(filedlg.GetFilename(), _T("r"));
1186 wxString data;
1187 if ( !file.IsOpened() || !file.ReadAll(&data) )
1188 return;
1189
1190 // can't write the entire string at once, this risk overflowing the pipe
1191 // and we would dead lock
1192 size_t len = data.length();
1193 const wxChar *pc = data.c_str();
1194 while ( len )
1195 {
1196 const size_t CHUNK_SIZE = 4096;
1197 m_out.Write(pc, len > CHUNK_SIZE ? CHUNK_SIZE : len);
1198
1199 // note that not all data could have been written as we don't block on
1200 // the write end of the pipe
1201 const size_t lenChunk = m_out.LastWrite();
1202
1203 pc += lenChunk;
1204 len -= lenChunk;
1205
1206 DoGet();
1207 }
1208 #endif // wxUSE_FILEDLG
1209 }
1210
1211 void MyPipeFrame::DoGet()
1212 {
1213 // we don't have any way to be notified when any input appears on the
1214 // stream so we have to poll it :-(
1215 DoGetFromStream(m_textIn, m_in);
1216 DoGetFromStream(m_textErr, m_err);
1217 }
1218
1219 void MyPipeFrame::DoGetFromStream(wxTextCtrl *text, wxInputStream& in)
1220 {
1221 while ( in.CanRead() )
1222 {
1223 wxChar buffer[4096];
1224 buffer[in.Read(buffer, WXSIZEOF(buffer) - 1).LastRead()] = _T('\0');
1225
1226 text->AppendText(buffer);
1227 }
1228 }
1229
1230 void MyPipeFrame::DoClose()
1231 {
1232 m_process->CloseOutput();
1233
1234 DisableInput();
1235 }
1236
1237 void MyPipeFrame::DisableInput()
1238 {
1239 m_textOut->SetEditable(false);
1240 FindWindow(Exec_Btn_Send)->Disable();
1241 FindWindow(Exec_Btn_SendFile)->Disable();
1242 FindWindow(Exec_Btn_Close)->Disable();
1243 }
1244
1245 void MyPipeFrame::DisableOutput()
1246 {
1247 FindWindow(Exec_Btn_Get)->Disable();
1248 }
1249
1250 void MyPipeFrame::OnClose(wxCloseEvent& event)
1251 {
1252 if ( m_process )
1253 {
1254 // we're not interested in getting the process termination notification
1255 // if we are closing it ourselves
1256 wxProcess *process = m_process;
1257 m_process = NULL;
1258 process->SetNextHandler(NULL);
1259
1260 process->CloseOutput();
1261 }
1262
1263 event.Skip();
1264 }
1265
1266 void MyPipeFrame::OnProcessTerm(wxProcessEvent& WXUNUSED(event))
1267 {
1268 DoGet();
1269
1270 delete m_process;
1271 m_process = NULL;
1272
1273 wxLogWarning(_T("The other process has terminated, closing"));
1274
1275 DisableInput();
1276 DisableOutput();
1277 }