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