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