5 * Nicolas Boichat, July 2004
9 Copyright (C) 2004 Kern Sibbald and John Walker
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.
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.
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.
26 #include "wxbmainframe.h" // class's header file
28 #include "wxbrestorepanel.h"
30 #include "wxbconfigfileeditor.h"
34 #include "wxwin16x16.xpm"
36 #include <wx/arrimpl.cpp>
38 #include <wx/stattext.h>
40 #include <wx/config.h>
42 #include <wx/filename.h>
44 #undef Yield /* MinGW defines Yield */
46 // ----------------------------------------------------------------------------
47 // event tables and other macros for wxWindows
48 // ----------------------------------------------------------------------------
50 // ----------------------------------------------------------------------------
52 // ----------------------------------------------------------------------------
54 // IDs for the controls and the menu commands
60 // it is important for the id corresponding to the "About" command to have
61 // this standard value as otherwise it won't be handled properly under Mac
62 // (where it is special and put into the "Apple" menu)
63 Minimal_About = wxID_ABOUT,
75 * wxbTHREAD_EVENT declaration, used by csprint
77 BEGIN_DECLARE_EVENT_TYPES()
78 DECLARE_EVENT_TYPE(wxbTHREAD_EVENT, 1)
79 END_DECLARE_EVENT_TYPES()
81 DEFINE_EVENT_TYPE(wxbTHREAD_EVENT)
83 typedef void (wxEvtHandler::*wxThreadEventFunction)(wxbThreadEvent&);
85 #define EVT_THREAD_EVENT(id, fn) \
86 DECLARE_EVENT_TABLE_ENTRY( \
87 wxbTHREAD_EVENT, id, wxID_ANY, \
88 (wxObjectEventFunction)(wxEventFunction)(wxThreadEventFunction)&fn, \
92 // the event tables connect the wxWindows events with the functions (event
93 // handlers) which process them. It can be also done at run-time, but for the
94 // simple menu events like this the static method is much simpler.
95 BEGIN_EVENT_TABLE(wxbMainFrame, wxFrame)
96 EVT_MENU(Minimal_Quit, wxbMainFrame::OnQuit)
97 EVT_MENU(Minimal_About, wxbMainFrame::OnAbout)
98 EVT_MENU(ChangeConfigFile, wxbMainFrame::OnChangeConfig)
99 EVT_MENU(EditConfigFile, wxbMainFrame::OnEditConfig)
100 EVT_MENU(MenuConnect, wxbMainFrame::OnConnect)
101 EVT_MENU(MenuDisconnect, wxbMainFrame::OnDisconnect)
102 EVT_TEXT_ENTER(TypeText, wxbMainFrame::OnEnter)
103 EVT_THREAD_EVENT(Thread, wxbMainFrame::OnPrint)
104 EVT_BUTTON(SendButton, wxbMainFrame::OnEnter)
107 // ----------------------------------------------------------------------------
109 // ----------------------------------------------------------------------------
112 * wxbThreadEvent constructor
114 wxbThreadEvent::wxbThreadEvent(int id): wxEvent(id, wxbTHREAD_EVENT) {
115 m_eventObject = NULL;
119 * wxbThreadEvent destructor
121 wxbThreadEvent::~wxbThreadEvent()
123 if (m_eventObject != NULL) {
124 delete m_eventObject;
129 * wxbThreadEvent copy constructor
131 wxbThreadEvent::wxbThreadEvent(const wxbThreadEvent& te)
133 this->m_eventType = te.m_eventType;
134 this->m_id = te.m_id;
135 if (te.m_eventObject != NULL) {
136 this->m_eventObject = new wxbPrintObject(*((wxbPrintObject*)te.m_eventObject));
139 this->m_eventObject = NULL;
141 this->m_skipped = te.m_skipped;
142 this->m_timeStamp = te.m_timeStamp;
146 * Must be implemented (abstract in wxEvent)
148 wxEvent* wxbThreadEvent::Clone() const
150 return new wxbThreadEvent(*this);
154 * Gets the wxbPrintObject attached to this event, containing data sent by director
156 wxbPrintObject* wxbThreadEvent::GetEventPrintObject()
158 return (wxbPrintObject*)m_eventObject;
162 * Sets the wxbPrintObject attached to this event
164 void wxbThreadEvent::SetEventPrintObject(wxbPrintObject* object)
166 m_eventObject = (wxObject*)object;
169 // ----------------------------------------------------------------------------
171 // ----------------------------------------------------------------------------
173 wxbMainFrame *wxbMainFrame::frame = NULL;
176 * Singleton constructor
178 wxbMainFrame* wxbMainFrame::CreateInstance(const wxString& title, const wxPoint& pos, const wxSize& size, long style)
180 frame = new wxbMainFrame(title, pos, size, style);
185 * Returns singleton instance
187 wxbMainFrame* wxbMainFrame::GetInstance()
195 wxbMainFrame::~wxbMainFrame()
197 if (ct != NULL) { // && (!ct->IsRunning())
204 * Private constructor
206 wxbMainFrame::wxbMainFrame(const wxString& title, const wxPoint& pos, const wxSize& size, long style)
207 : wxFrame(NULL, -1, title, pos, size, style)
213 // set the frame icon
214 SetIcon(wxIcon(wxwin16x16_xpm));
218 menuFile = new wxMenu;
220 // the "About" item should be in the help menu
221 wxMenu *helpMenu = new wxMenu;
222 helpMenu->Append(Minimal_About, _T("&About...\tF1"), _T("Show about dialog"));
224 menuFile->Append(MenuConnect, _T("Connect"), _T("Connect to the director"));
225 menuFile->Append(MenuDisconnect, _T("Disconnect"), _T("Disconnect of the director"));
226 menuFile->AppendSeparator();
227 menuFile->Append(ChangeConfigFile, _T("Change of configuration file"), _T("Change your default configuration file"));
228 menuFile->Append(EditConfigFile, _T("Edit your configuration file"), _T("Edit your configuration file"));
229 menuFile->AppendSeparator();
230 menuFile->Append(Minimal_Quit, _T("E&xit\tAlt-X"), _T("Quit this program"));
232 // now append the freshly created menu to the menu bar...
233 wxMenuBar *menuBar = new wxMenuBar();
234 menuBar->Append(menuFile, _T("&File"));
235 menuBar->Append(helpMenu, _T("&Help"));
237 // ... and attach this menu bar to the frame
239 #endif // wxUSE_MENUS
242 SetStatusText(wxString("Welcome to bacula wx-console ") << VERSION << " (" << BDATE << ")!\n");
244 wxPanel* global = new wxPanel(this, -1);
246 notebook = new wxNotebook(global, -1);
250 wxPanel* consolePanel = new wxPanel(notebook, -1);
251 notebook->AddPage(consolePanel, "Console");
253 consoleCtrl = new wxTextCtrl(consolePanel,-1,"",wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH);
254 wxFont font(10, wxMODERN, wxNORMAL, wxNORMAL);
255 #if defined __WXGTK12__ && !defined __WXGTK20__ // Fix for "chinese" fonts under gtk+ 1.2
256 font.SetDefaultEncoding(wxFONTENCODING_ISO8859_1);
257 consoleCtrl->SetDefaultStyle(wxTextAttr(*wxBLACK, wxNullColour, font));
258 Print("Warning : Unicode is disabled because you are using wxWidgets for GTK+ 1.2.\n", CS_DEBUG);
260 consoleCtrl->SetDefaultStyle(wxTextAttr(*wxBLACK, wxNullColour, font));
263 wxFlexGridSizer *consoleSizer = new wxFlexGridSizer(2, 1, 0, 0);
264 consoleSizer->AddGrowableCol(0);
265 consoleSizer->AddGrowableRow(0);
267 typeCtrl = new wxbHistoryTextCtrl(consolePanel,TypeText,"",wxDefaultPosition,wxSize(200,20));
268 sendButton = new wxButton(consolePanel, SendButton, "Send");
270 wxFlexGridSizer *typeSizer = new wxFlexGridSizer(1, 3, 0, 0);
271 typeSizer->AddGrowableCol(1);
272 typeSizer->AddGrowableRow(0);
274 typeSizer->Add(new wxStaticText(consolePanel, -1, "Command: "), 0, wxALIGN_CENTER | wxALL, 0);
275 typeSizer->Add(typeCtrl, 1, wxEXPAND | wxALL, 0);
276 typeSizer->Add(sendButton, 1, wxEXPAND | wxLEFT, 5);
278 consoleSizer->Add(consoleCtrl, 1, wxEXPAND | wxALL, 0);
279 consoleSizer->Add(typeSizer, 0, wxEXPAND | wxALL, 0);
281 consolePanel->SetAutoLayout( TRUE );
282 consolePanel->SetSizer( consoleSizer );
283 consoleSizer->SetSizeHints( consolePanel );
285 // Creates the list of panels which are included in notebook, and that need to receive director information
287 panels = new wxbPanel* [2];
288 panels[0] = new wxbRestorePanel(notebook);
291 for (int i = 0; panels[i] != NULL; i++) {
292 notebook->AddPage(panels[i], panels[i]->GetTitle());
295 wxBoxSizer* globalSizer = new wxBoxSizer(wxHORIZONTAL);
297 globalSizer->Add(new wxNotebookSizer(notebook), 1, wxEXPAND, 0);
299 global->SetSizer( globalSizer );
300 globalSizer->SetSizeHints( global );
302 wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);
304 sizer->Add(global, 1, wxEXPAND | wxALL, 0);
307 sizer->SetSizeHints( this );
309 EnableConsole(false);
311 lockedbyconsole = false;
319 * Starts the thread interacting with the director
320 * If config is not empty, uses this config file.
322 void wxbMainFrame::StartConsoleThread(const wxString& config) {
323 menuFile->Enable(MenuConnect, false);
324 menuFile->Enable(MenuDisconnect, false);
325 menuFile->Enable(ChangeConfigFile, false);
326 menuFile->Enable(EditConfigFile, false);
333 if (promptparser == NULL) {
334 promptparser = new wxbPromptParser();
338 if ((wxTheApp->argc == 3) && (wxString(wxTheApp->argv[1]) == "-c")) {
339 configfile = wxTheApp->argv[2];
342 wxConfig::Set(new wxConfig("wx-console", "bacula"));
343 if (!wxConfig::Get()->Read("/ConfigFile", &configfile)) {
345 wxFileName filename(::wxGetHomeDir());
346 filename.MakeAbsolute();
347 configfile = filename.GetLongPath();
348 if (configfile.Last() != '/')
350 configfile += "Library/Preferences/org.bacula.wxconsole.conf";
352 wxFileName filename(::wxGetCwd(), "wx-console.conf");
353 filename.MakeAbsolute();
354 configfile = filename.GetLongPath();
356 configfile.Replace("\\", "/");
359 wxConfig::Get()->Write("/ConfigFile", configfile);
360 if (wxTheApp->argc > 1) {
361 Print("Error while parsing command line arguments, using defaults.\n", CS_DEBUG);
362 Print("Usage: wx-console [-c configfile]\n", CS_DEBUG);
365 int answer = wxMessageBox(
366 wxString("It seems that it is the first time you run wx-console.\n") <<
367 "This file (" << configfile << ") has been choosen as default configuration file.\n" <<
368 "Do you want to edit it? (if you click No you will have to select another file)",
370 wxYES_NO | wxICON_QUESTION, this);
371 if (answer == wxYES) {
372 wxbConfigFileEditor(this, configfile).ShowModal();
381 wxString err = console_thread::LoadConfig(configfile);
384 int answer = wxMessageBox(
385 wxString("Unable to read ") << configfile << "\n" <<
386 err << "\nDo you want to choose another one? (Press no to edit this file)",
387 "Unable to read configuration file",
388 wxYES_NO | wxCANCEL | wxICON_ERROR, this);
389 if (answer == wxNO) {
390 wxbConfigFileEditor(this, configfile).ShowModal();
391 err = console_thread::LoadConfig(configfile);
393 else if (answer == wxCANCEL) {
398 else { // (answer == wxYES)
399 configfile = wxFileSelector("Please choose a configuration file to use");
400 if ( !configfile.empty() ) {
401 err = console_thread::LoadConfig(configfile);
410 if ((err == "") && (config == "")) {
411 answer = wxMessageBox(
412 "This configuration file has been successfully read, use it as default?",
413 "Configuration file read successfully",
414 wxYES_NO | wxICON_QUESTION, this);
415 if (answer == wxYES) {
416 wxConfigBase::Get()->Write("/ConfigFile", configfile);
422 csprint(wxString("Using this configuration file: ") << configfile << "\n", CS_DEBUG);
424 ct = new console_thread();
427 SetStatusText("Connecting to the director...");
430 /* Register a new wxbDataParser */
431 void wxbMainFrame::Register(wxbDataParser* dp) {
435 /* Unregister a wxbDataParser */
436 void wxbMainFrame::Unregister(wxbDataParser* dp) {
438 if ((index = parsers.Index(dp)) != wxNOT_FOUND) {
439 parsers.RemoveAt(index);
442 Print("Failed to unregister a data parser !", CS_DEBUG);
448 void wxbMainFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
450 Print("Quitting.\n", CS_DEBUG);
456 console_thread::FreeLib();
462 void wxbMainFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
465 msg.Printf( _T("Welcome to Bacula wx-console.\nWritten by Nicolas Boichat <nicolas@boichat.ch>\n(C) 2004 Kern Sibbald and John Walker\n"));
467 wxMessageBox(msg, _T("About Bacula wx-console"), wxOK | wxICON_INFORMATION, this);
470 void wxbMainFrame::OnChangeConfig(wxCommandEvent& event) {
471 wxString oriconfigfile;
472 wxConfig::Get()->Read("/ConfigFile", &oriconfigfile);
473 wxString configfile = wxFileSelector("Please choose your default configuration file");
474 if ( !configfile.empty() ) {
475 if (oriconfigfile != configfile) {
476 int answer = wxMessageBox(
477 "Use this configuration file as default?",
478 "Configuration file",
479 wxYES_NO | wxICON_QUESTION, this);
480 if (answer == wxYES) {
481 wxConfigBase::Get()->Write("/ConfigFile", configfile);
482 wxConfigBase::Get()->Flush();
483 StartConsoleThread("");
488 StartConsoleThread(configfile);
492 void wxbMainFrame::OnEditConfig(wxCommandEvent& event) {
494 wxConfig::Get()->Read("/ConfigFile", &configfile);
495 int stat = wxbConfigFileEditor(this, configfile).ShowModal();
497 StartConsoleThread(configfile);
501 void wxbMainFrame::OnConnect(wxCommandEvent& event) {
502 StartConsoleThread(configfile);
505 void wxbMainFrame::OnDisconnect(wxCommandEvent& event) {
512 void wxbMainFrame::OnEnter(wxCommandEvent& WXUNUSED(event))
514 lockedbyconsole = true;
516 typeCtrl->HistoryAdd(typeCtrl->GetValue());
517 wxString str = typeCtrl->GetValue() + "\n";
522 * Called when data is arriving from director
524 void wxbMainFrame::OnPrint(wxbThreadEvent& event) {
525 wxbPrintObject* po = event.GetEventPrintObject();
527 Print(po->str, po->status);
531 * Prints data received from director to the console, and forwards it to the panels
533 void wxbMainFrame::Print(wxString str, int status)
535 if (lockedbyconsole) {
536 EnableConsole(false);
539 if (status == CS_TERMINATED) {
540 consoleCtrl->AppendText(consoleBuffer);
542 SetStatusText("Console thread terminated.");
543 consoleCtrl->ScrollLines(3);
546 int answer = wxMessageBox("Connection to the director lost. Quit program?", "Connection lost",
547 wxYES_NO | wxICON_EXCLAMATION, this);
548 if (answer == wxYES) {
552 menuFile->Enable(MenuConnect, true);
553 menuFile->SetLabel(MenuConnect, "Connect");
554 menuFile->SetHelpString(MenuConnect, "Connect to the director");
555 menuFile->Enable(MenuDisconnect, false);
556 menuFile->Enable(ChangeConfigFile, true);
557 menuFile->Enable(EditConfigFile, true);
561 if (status == CS_CONNECTED) {
562 SetStatusText("Connected to the director.");
564 menuFile->Enable(MenuConnect, true);
565 menuFile->SetLabel(MenuConnect, "Reconnect");
566 menuFile->SetHelpString(MenuConnect, "Reconnect to the director");
567 menuFile->Enable(MenuDisconnect, true);
568 menuFile->Enable(ChangeConfigFile, true);
569 menuFile->Enable(EditConfigFile, true);
572 if (status == CS_DISCONNECTED) {
573 consoleCtrl->AppendText(consoleBuffer);
575 consoleCtrl->ScrollLines(3);
576 SetStatusText("Disconnected of the director.");
581 // CS_DEBUG is often sent by panels,
582 // and resend it to them would sometimes cause infinite loops
584 /* One promptcaught is normal, so we must have two true Print values to be
585 * sure that the prompt has effectively been caught.
587 int promptcaught = -1;
589 if (status != CS_DEBUG) {
590 for (unsigned int i = 0; i < parsers.GetCount(); i++) {
591 promptcaught += parsers[i]->Print(str, status) ? 1 : 0;
594 if ((status == CS_PROMPT) && (promptcaught < 1) && (promptparser->isPrompt())) {
595 Print("Unexpected question has been received.\n", CS_DEBUG);
596 // Print(wxString("(") << promptparser->getIntroString() << "/-/" << promptparser->getQuestionString() << ")\n", CS_DEBUG);
599 if (promptparser->getIntroString() != "") {
600 message << promptparser->getIntroString() << "\n";
602 message << promptparser->getQuestionString();
604 if (promptparser->getChoices()) {
605 wxString *choices = new wxString[promptparser->getChoices()->GetCount()];
606 int *numbers = new int[promptparser->getChoices()->GetCount()];
609 for (unsigned int i = 0; i < promptparser->getChoices()->GetCount(); i++) {
610 if ((*promptparser->getChoices())[i] != "") {
611 choices[n] = (*promptparser->getChoices())[i];
617 int res = ::wxGetSingleChoiceIndex(message,
618 "wx-console: unexpected director's question.", n, choices, this);
623 Send(wxString() << numbers[res] << "\n");
627 Send(::wxGetTextFromUser(message,
628 "wx-console: unexpected director's question.", "", this) + "\n");
633 if (status == CS_END) {
634 if (lockedbyconsole) {
636 lockedbyconsole = false;
641 if (status == CS_DEBUG) {
642 consoleCtrl->AppendText(consoleBuffer);
644 consoleCtrl->ScrollLines(3);
645 consoleCtrl->SetDefaultStyle(wxTextAttr(wxColour(0, 128, 0)));
648 consoleCtrl->SetDefaultStyle(wxTextAttr(*wxBLACK));
650 consoleBuffer << str;
651 if (status == CS_PROMPT) {
652 if (lockedbyconsole) {
655 //consoleBuffer << "<P>";
658 if ((status == CS_END) || (status == CS_PROMPT) || (str.Find("\n") > -1)) {
659 consoleCtrl->AppendText(consoleBuffer);
662 consoleCtrl->ScrollLines(3);
665 // consoleCtrl->ShowPosition(consoleCtrl->GetLastPosition());
667 /*if (status != CS_DEBUG) {
668 consoleCtrl->AppendText("@");
670 //consoleCtrl->SetInsertionPointEnd();
672 /* if ((consoleCtrl->GetNumberOfLines()-1) > nlines) {
673 nlines = consoleCtrl->GetNumberOfLines()-1;
676 if (status == CS_END) {
677 consoleCtrl->ShowPosition(nlines);
682 * Sends data to the director
684 void wxbMainFrame::Send(wxString str)
687 ct->Write((const char*)str);
688 typeCtrl->SetValue("");
689 consoleCtrl->SetDefaultStyle(wxTextAttr(*wxRED));
690 consoleCtrl->AppendText(str);
691 consoleCtrl->ScrollLines(3);
694 /* if ((consoleCtrl->GetNumberOfLines()-1) > nlines) {
695 nlines = consoleCtrl->GetNumberOfLines()-1;
698 consoleCtrl->ShowPosition(nlines);*/
702 void wxbMainFrame::EnablePanels() {
703 for (int i = 0; panels[i] != NULL; i++) {
704 panels[i]->EnablePanel(true);
709 /* Disable panels, except the one passed as parameter */
710 void wxbMainFrame::DisablePanels(void* except) {
711 for (int i = 0; panels[i] != NULL; i++) {
712 if (panels[i] != except) {
713 panels[i]->EnablePanel(false);
716 panels[i]->EnablePanel(true);
719 if (this != except) {
720 EnableConsole(false);
724 /* Enable or disable console typing */
725 void wxbMainFrame::EnableConsole(bool enable) {
726 typeCtrl->Enable(enable);
727 sendButton->Enable(enable);
729 typeCtrl->SetFocus();
734 * Used by csprint, which is called by console thread.
736 * In GTK and perhaps X11, only the main thread is allowed to interact with
737 * graphical components, so by firing an event, the main loop will call OnPrint.
739 * Calling OnPrint directly from console thread produces "unexpected async replies".
741 void firePrintEvent(wxString str, int status)
743 wxbPrintObject* po = new wxbPrintObject(str, status);
745 wxbThreadEvent evt(Thread);
746 evt.SetEventPrintObject(po);
748 if (wxbMainFrame::GetInstance()) {
749 wxbMainFrame::GetInstance()->AddPendingEvent(evt);
753 //wxString csBuffer; /* Temporary buffer for receiving data from console thread */
756 * Called by console thread, this function forwards data line by line and end
757 * signals to the GUI.
759 void csprint(const char* str, int status)
762 firePrintEvent(wxString(str), status);
765 firePrintEvent("", status);