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