]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/wx-console/wxbmainframe.cpp
- wxbMainFrame : Corrected incorrect casting of thread event functions (reported...
[bacula/bacula] / bacula / src / wx-console / wxbmainframe.cpp
1 /*
2  *
3  *   Main frame
4  *
5  *    Nicolas Boichat, April 2004
6  *
7  */
8 /*
9    Copyright (C) 2004 Kern Sibbald and John Walker
10
11    This program is free software; you can redistribute it and/or
12    modify it under the terms of the GNU General Public License
13    as published by the Free Software Foundation; either version 2
14    of the License, or (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program; if not, write to the Free Software
23    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
24  */
25
26 #include "wxbmainframe.h" // class's header file
27
28 #include "wxbrestorepanel.h"
29
30 #include "csprint.h"
31
32 #include "wxwin16x16.xpm"
33
34 #include <wx/arrimpl.cpp>
35
36 #include <wx/stattext.h>
37
38 // ----------------------------------------------------------------------------
39 // event tables and other macros for wxWindows
40 // ----------------------------------------------------------------------------
41
42 // ----------------------------------------------------------------------------
43 // constants
44 // ----------------------------------------------------------------------------
45
46 // IDs for the controls and the menu commands
47 enum
48 {
49    // menu items
50    Minimal_Quit = 1,
51
52    // it is important for the id corresponding to the "About" command to have
53    // this standard value as otherwise it won't be handled properly under Mac
54    // (where it is special and put into the "Apple" menu)
55    Minimal_About = wxID_ABOUT,
56    TypeText = 2,
57    SendButton = 3,
58    Thread = 4
59 };
60
61 /*
62  *   wxbTHREAD_EVENT declaration, used by csprint
63  */
64 BEGIN_DECLARE_EVENT_TYPES()
65    DECLARE_EVENT_TYPE(wxbTHREAD_EVENT,       1)
66 END_DECLARE_EVENT_TYPES()
67
68 DEFINE_EVENT_TYPE(wxbTHREAD_EVENT)
69
70 typedef void (wxEvtHandler::*wxThreadEventFunction)(wxbThreadEvent&);
71
72 #define EVT_THREAD_EVENT(id, fn) \
73     DECLARE_EVENT_TABLE_ENTRY( \
74         wxbTHREAD_EVENT, id, wxID_ANY, \
75         (wxObjectEventFunction)(wxEventFunction)(wxThreadEventFunction)&fn, \
76         (wxObject *) NULL \
77     ),
78
79 // the event tables connect the wxWindows events with the functions (event
80 // handlers) which process them. It can be also done at run-time, but for the
81 // simple menu events like this the static method is much simpler.
82 BEGIN_EVENT_TABLE(wxbMainFrame, wxFrame)
83    EVT_MENU(Minimal_Quit,  wxbMainFrame::OnQuit)
84    EVT_MENU(Minimal_About, wxbMainFrame::OnAbout)
85    EVT_TEXT_ENTER(TypeText, wxbMainFrame::OnEnter)
86    EVT_THREAD_EVENT(Thread, wxbMainFrame::OnPrint)
87    EVT_BUTTON(SendButton, wxbMainFrame::OnEnter)
88 END_EVENT_TABLE()
89
90 // ----------------------------------------------------------------------------
91 // wxbThreadEvent
92 // ----------------------------------------------------------------------------
93
94 /*
95  *  wxbThreadEvent constructor
96  */
97 wxbThreadEvent::wxbThreadEvent(int id): wxEvent(id, wxbTHREAD_EVENT) {
98    m_eventObject = NULL;
99 }
100
101 /*
102  *  wxbThreadEvent destructor
103  */
104 wxbThreadEvent::~wxbThreadEvent()
105 {
106    if (m_eventObject != NULL) {
107       delete m_eventObject;
108    }
109 }
110
111 /*
112  *  wxbThreadEvent copy constructor
113  */
114 wxbThreadEvent::wxbThreadEvent(const wxbThreadEvent& te)
115 {
116    this->m_eventType = te.m_eventType;
117    this->m_id = te.m_id;
118    if (te.m_eventObject != NULL) {
119       this->m_eventObject = new wxbPrintObject(*((wxbPrintObject*)te.m_eventObject));
120    }
121    else {
122       this->m_eventObject = NULL;
123    }
124    this->m_skipped = te.m_skipped;
125    this->m_timeStamp = te.m_timeStamp;
126 }
127
128 /*
129  *  Must be implemented (abstract in wxEvent)
130  */
131 wxEvent* wxbThreadEvent::Clone() const
132 {
133    return new wxbThreadEvent(*this);
134 }
135
136 /*
137  *  Gets the wxbPrintObject attached to this event, containing data sent by director
138  */
139 wxbPrintObject* wxbThreadEvent::GetEventPrintObject()
140 {
141    return (wxbPrintObject*)m_eventObject;
142 }
143
144 /*
145  *  Sets the wxbPrintObject attached to this event
146  */
147 void wxbThreadEvent::SetEventPrintObject(wxbPrintObject* object)
148 {
149    m_eventObject = (wxObject*)object;
150 }
151
152 // ----------------------------------------------------------------------------
153 // main frame
154 // ----------------------------------------------------------------------------
155
156 wxbMainFrame *wxbMainFrame::frame = NULL;
157
158 /*
159  *  Singleton constructor
160  */
161 wxbMainFrame* wxbMainFrame::CreateInstance(const wxString& title, const wxPoint& pos, const wxSize& size, long style)
162 {
163    frame = new wxbMainFrame(title, pos, size, style);
164    return frame;
165 }
166
167 /*
168  *  Returns singleton instance
169  */
170 wxbMainFrame* wxbMainFrame::GetInstance()
171 {
172    return frame;
173 }
174
175 /*
176  *  Private destructor
177  */
178 wxbMainFrame::~wxbMainFrame()
179 {
180    if (ct != NULL) { // && (!ct->IsRunning())
181       ct->Delete();
182    }
183    frame = NULL;
184 }
185
186 /*
187  *  Private constructor
188  */
189 wxbMainFrame::wxbMainFrame(const wxString& title, const wxPoint& pos, const wxSize& size, long style)
190       : wxFrame(NULL, -1, title, pos, size, style)
191 {
192    ct = NULL;
193
194    // set the frame icon
195    SetIcon(wxIcon(wxwin16x16_xpm));
196
197 #if wxUSE_MENUS
198    // create a menu bar
199    wxMenu *menuFile = new wxMenu;
200
201    // the "About" item should be in the help menu
202    wxMenu *helpMenu = new wxMenu;
203    helpMenu->Append(Minimal_About, _T("&About...\tF1"), _T("Show about dialog"));
204
205    menuFile->Append(Minimal_Quit, _T("E&xit\tAlt-X"), _T("Quit this program"));
206
207    // now append the freshly created menu to the menu bar...
208    wxMenuBar *menuBar = new wxMenuBar();
209    menuBar->Append(menuFile, _T("&File"));
210    menuBar->Append(helpMenu, _T("&Help"));
211
212    // ... and attach this menu bar to the frame
213    SetMenuBar(menuBar);
214 #endif // wxUSE_MENUS
215
216    CreateStatusBar(1);
217    SetStatusText(wxString("Welcome to bacula wx-console ") << VERSION << " (" << BDATE << ")!\n");
218
219    wxPanel* global = new wxPanel(this, -1);
220
221    notebook = new wxNotebook(global, -1);
222
223    /* Console */
224
225    wxPanel* consolePanel = new wxPanel(notebook, -1);
226    notebook->AddPage(consolePanel, "Console");
227
228    consoleCtrl = new wxTextCtrl(consolePanel,-1,"",wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH);
229    consoleCtrl->SetDefaultStyle(wxTextAttr(*wxBLACK, wxNullColour, wxFont(10, wxMODERN, wxNORMAL, wxNORMAL)));
230
231    wxFlexGridSizer *consoleSizer = new wxFlexGridSizer(2, 1, 0, 0);
232    consoleSizer->AddGrowableCol(0);
233    consoleSizer->AddGrowableRow(0);
234
235    typeCtrl = new wxTextCtrl(consolePanel,TypeText,"",wxDefaultPosition,wxSize(200,20), wxTE_PROCESS_ENTER);
236    sendButton = new wxButton(consolePanel, SendButton, "Send");
237    
238    wxFlexGridSizer *typeSizer = new wxFlexGridSizer(1, 3, 0, 0);
239    typeSizer->AddGrowableCol(1);
240    typeSizer->AddGrowableRow(0);
241
242    typeSizer->Add(new wxStaticText(consolePanel, -1, "Command: "), 0, wxALIGN_CENTER | wxALL, 0);
243    typeSizer->Add(typeCtrl, 1, wxEXPAND | wxALL, 0);
244    typeSizer->Add(sendButton, 1, wxEXPAND | wxLEFT, 5);
245
246    consoleSizer->Add(consoleCtrl, 1, wxEXPAND | wxALL, 0);
247    consoleSizer->Add(typeSizer, 0, wxEXPAND | wxALL, 0);
248
249    consolePanel->SetAutoLayout( TRUE );
250    consolePanel->SetSizer( consoleSizer );
251    consoleSizer->SetSizeHints( consolePanel );
252
253    // Creates the list of panels which are included in notebook, and that need to receive director information
254
255    panels = new wxbPanel* [2];
256    panels[0] = new wxbRestorePanel(notebook);
257    panels[1] = NULL;
258
259    for (int i = 0; panels[i] != NULL; i++) {
260       notebook->AddPage(panels[i], panels[i]->GetTitle());
261    }
262
263    wxBoxSizer* globalSizer = new wxBoxSizer(wxHORIZONTAL);
264
265    globalSizer->Add(new wxNotebookSizer(notebook), 1, wxEXPAND, 0);
266
267    global->SetSizer( globalSizer );
268    globalSizer->SetSizeHints( global );
269
270    wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);
271
272    sizer->Add(global, 1, wxEXPAND | wxALL, 0);
273    SetAutoLayout(true);
274    SetSizer( sizer );
275    sizer->SetSizeHints( this );
276    this->SetSize(size);
277    EnableConsole(false);
278    
279    lockedbyconsole = false;
280    
281    consoleBuffer = "";
282 }
283
284 /*
285  *  Starts the thread interacting with the director
286  */
287 void wxbMainFrame::StartConsoleThread()
288 {
289    if (ct != NULL) {
290       ct->Delete();
291    }
292    else {
293       promptparser = new wxbPromptParser();      
294    }
295    ct = new console_thread();
296    ct->Create();
297    ct->Run();
298    SetStatusText("Connecting to the director...");
299 }
300
301 /* Register a new wxbDataParser */
302 void wxbMainFrame::Register(wxbDataParser* dp) {
303    parsers.Add(dp);
304 }
305    
306 /* Unregister a wxbDataParser */
307 void wxbMainFrame::Unregister(wxbDataParser* dp) {
308    int index;
309    if ((index = parsers.Index(dp)) != wxNOT_FOUND) {
310       parsers.RemoveAt(index);
311    }
312    else {
313       Print("Failed to unregister a data parser !", CS_DEBUG);
314    }
315 }
316
317 // event handlers
318
319 void wxbMainFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
320 {
321    Print("Quitting.\n", CS_DEBUG);
322    if (ct != NULL) {
323       ct->Delete();
324       ct = NULL;
325    }
326    frame = NULL;
327    Close(TRUE);
328 }
329
330 void wxbMainFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
331 {
332    wxString msg;
333    msg.Printf( _T("Welcome to Bacula wx-console.\nWritten by Nicolas Boichat <nicolas@boichat.ch>\n(C) 2004 Kern Sibbald and John Walker\n"));
334
335    wxMessageBox(msg, _T("About Bacula wx-console"), wxOK | wxICON_INFORMATION, this);
336 }
337
338 void wxbMainFrame::OnEnter(wxCommandEvent& WXUNUSED(event))
339 {
340    lockedbyconsole = true;
341    DisablePanels();
342    wxString str = typeCtrl->GetValue() + "\n";
343    Send(str);
344 }
345
346 /*
347  *  Called when data is arriving from director
348  */
349 void wxbMainFrame::OnPrint(wxbThreadEvent& event) {
350    wxbPrintObject* po = event.GetEventPrintObject();
351
352    Print(po->str, po->status);
353 }
354
355 /*
356  *  Prints data received from director to the console, and forwards it to the panels
357  */
358 void wxbMainFrame::Print(wxString str, int status)
359 {
360    if (lockedbyconsole) {
361       EnableConsole(false);
362    }
363    
364    if (status == CS_TERMINATED) {
365       consoleCtrl->AppendText(consoleBuffer);
366       consoleBuffer = "";
367       SetStatusText("Console thread terminated.");
368       ct = NULL;
369       DisablePanels();
370       int answer = wxMessageBox("Connection to the director lost. Quit program?", "Connection lost",
371                         wxYES_NO | wxICON_EXCLAMATION, this);
372       if (answer == wxYES) {
373          frame = NULL;
374          Close(true);
375       }
376       return;
377    }
378    
379    if (status == CS_CONNECTED) {
380       SetStatusText("Connected to the director.");
381       EnablePanels();
382       return;
383    }
384    if (status == CS_DISCONNECTED) {
385       consoleCtrl->AppendText(consoleBuffer);
386       consoleBuffer = "";
387       SetStatusText("Disconnected of the director.");
388       DisablePanels();
389       return;
390    }
391       
392    // CS_DEBUG is often sent by panels, 
393    // and resend it to them would sometimes cause infinite loops
394    
395    /* One promptcaught is normal, so we must have two true Print values to be
396     * sure that the prompt has effectively been caught.
397     */
398    int promptcaught = -1;
399    
400    if (status != CS_DEBUG) {
401       for (unsigned int i = 0; i < parsers.GetCount(); i++) {
402          promptcaught += parsers[i]->Print(str, status) ? 1 : 0;
403       }
404          
405       if ((status == CS_PROMPT) && (promptcaught < 1) && (promptparser->isPrompt())) {
406          Print("Unexpected question has been received.\n", CS_DEBUG);
407 //         Print(wxString("(") << promptparser->getIntroString() << "/-/" << promptparser->getQuestionString() << ")\n", CS_DEBUG);
408          
409          wxString message;
410          if (promptparser->getIntroString() != "") {
411             message << promptparser->getIntroString() << "\n";
412          }
413          message << promptparser->getQuestionString();
414          
415          if (promptparser->getChoices()) {
416             wxString *choices = new wxString[promptparser->getChoices()->GetCount()];
417             int *numbers = new int[promptparser->getChoices()->GetCount()];
418             int n = 0;
419             
420             for (unsigned int i = 0; i < promptparser->getChoices()->GetCount(); i++) {
421                if ((*promptparser->getChoices())[i] != "") {
422                   choices[n] = (*promptparser->getChoices())[i];
423                   numbers[n] = i;
424                   n++;
425                }
426             }
427             
428             int res = ::wxGetSingleChoiceIndex(message,
429                "wx-console: unexpected director's question.", n, choices, this);
430             if (res == -1) {
431                Send("\n");
432             }
433             else {
434                Send(wxString() << numbers[res] << "\n");
435             }
436          }
437          else {
438             Send(::wxGetTextFromUser(message,
439                "wx-console: unexpected director's question.", "", this) + "\n");
440          }
441       }
442    }
443       
444    if (status == CS_END) {
445       if (lockedbyconsole) {
446          EnablePanels();
447          lockedbyconsole = false;
448       }
449       str = "#";
450    }
451
452    if (status == CS_DEBUG) {
453       consoleCtrl->AppendText(consoleBuffer);
454       consoleBuffer = "";
455       consoleCtrl->SetDefaultStyle(wxTextAttr(wxColour(0, 128, 0)));
456    }
457    else {
458       consoleCtrl->SetDefaultStyle(wxTextAttr(*wxBLACK));
459    }
460    consoleBuffer << str;
461    if (status == CS_PROMPT) {
462       if (lockedbyconsole) {
463          EnableConsole(true);
464       }
465       consoleBuffer << "<P>";
466    }
467    
468    if ((status == CS_END) || (status == CS_PROMPT) || (str.Find("\n") > -1)) {
469       consoleCtrl->AppendText(consoleBuffer);
470       consoleBuffer = "";
471    
472       consoleCtrl->ScrollLines(3);
473    }
474    
475 //   consoleCtrl->ShowPosition(consoleCtrl->GetLastPosition());
476    
477    /*if (status != CS_DEBUG) {
478       consoleCtrl->AppendText("@");
479    }*/
480    //consoleCtrl->SetInsertionPointEnd();
481    
482 /*   if ((consoleCtrl->GetNumberOfLines()-1) > nlines) {
483       nlines = consoleCtrl->GetNumberOfLines()-1;
484    }
485    
486    if (status == CS_END) {
487       consoleCtrl->ShowPosition(nlines);
488    }*/
489 }
490
491 /*
492  *  Sends data to the director
493  */
494 void wxbMainFrame::Send(wxString str)
495 {
496    if (ct != NULL) {
497       ct->Write((const char*)str);
498       typeCtrl->SetValue("");
499       consoleCtrl->SetDefaultStyle(wxTextAttr(*wxRED));
500       consoleCtrl->AppendText(str);
501       consoleCtrl->ScrollLines(3);
502    }
503    
504 /*   if ((consoleCtrl->GetNumberOfLines()-1) > nlines) {
505       nlines = consoleCtrl->GetNumberOfLines()-1;
506    }
507    
508    consoleCtrl->ShowPosition(nlines);*/
509 }
510
511 /* Enable panels */
512 void wxbMainFrame::EnablePanels() {
513    for (int i = 0; panels[i] != NULL; i++) {
514       panels[i]->EnablePanel(true);
515    }
516    EnableConsole(true);
517 }
518
519 /* Disable panels, except the one passed as parameter */
520 void wxbMainFrame::DisablePanels(void* except) {
521    for (int i = 0; panels[i] != NULL; i++) {
522       if (panels[i] != except) {
523          panels[i]->EnablePanel(false);
524       }
525       else {
526          panels[i]->EnablePanel(true);
527       }
528    }
529    if (this != except) {
530       EnableConsole(false);
531    }
532 }
533
534 /* Enable or disable console typing */
535 void wxbMainFrame::EnableConsole(bool enable) {
536    typeCtrl->Enable(enable);
537    sendButton->Enable(enable);
538    if (enable) {
539       typeCtrl->SetFocus();
540    }
541 }
542
543 /*
544  *  Used by csprint, which is called by console thread.
545  *
546  *  In GTK and perhaps X11, only the main thread is allowed to interact with
547  *  graphical components, so by firing an event, the main loop will call OnPrint.
548  *
549  *  Calling OnPrint directly from console thread produces "unexpected async replies".
550  */
551 void firePrintEvent(wxString str, int status)
552 {
553    wxbPrintObject* po = new wxbPrintObject(str, status);
554
555    wxbThreadEvent evt(Thread);
556    evt.SetEventPrintObject(po);
557    
558    if (wxbMainFrame::GetInstance()) {
559       wxbMainFrame::GetInstance()->AddPendingEvent(evt);
560    }
561 }
562
563 //wxString csBuffer; /* Temporary buffer for receiving data from console thread */
564
565 /*
566  *  Called by console thread, this function forwards data line by line and end
567  *  signals to the GUI.
568  */
569 void csprint(const char* str, int status)
570 {
571    if (str != 0) {
572       firePrintEvent(wxString(str), status);
573    }
574    else {
575       firePrintEvent("", status);
576    }
577 }
578