]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/wx-console/wxbmainframe.cpp
Fix compilation warnings with wxWidgets 2.6.0.
[bacula/bacula] / bacula / src / wx-console / wxbmainframe.cpp
1 /*
2  *
3  *   Main frame
4  *
5  *    Nicolas Boichat, July 2004
6  *
7  *    Version $Id$
8  */
9 /*
10    Copyright (C) 2004 Kern Sibbald and John Walker
11
12    This program is free software; you can redistribute it and/or
13    modify it under the terms of the GNU General Public License
14    as published by the Free Software Foundation; either version 2
15    of the License, or (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with this program; if not, write to the Free Software
24    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25  */
26
27 #include "wxbmainframe.h" // class's header file
28
29 #include "wxbrestorepanel.h"
30
31 #include "wxbconfigfileeditor.h"
32
33 #include "csprint.h"
34
35 #include "wxwin16x16.xpm"
36
37 #include <wx/arrimpl.cpp>
38
39 #include <wx/stattext.h>
40 #include <wx/statline.h>
41 #include <wx/config.h>
42
43 #include <wx/filename.h>
44
45 #undef Yield /* MinGW defines Yield */
46
47 // ----------------------------------------------------------------------------
48 // event tables and other macros for wxWindows
49 // ----------------------------------------------------------------------------
50
51 // ----------------------------------------------------------------------------
52 // constants
53 // ----------------------------------------------------------------------------
54
55 // IDs for the controls and the menu commands
56 enum
57 {
58    // menu items
59    Minimal_Quit = 1,
60
61    // it is important for the id corresponding to the "About" command to have
62    // this standard value as otherwise it won't be handled properly under Mac
63    // (where it is special and put into the "Apple" menu)
64    Minimal_About = wxID_ABOUT,
65    
66    ChangeConfigFile = 2,
67    EditConfigFile = 3,
68    MenuConnect = 4,
69    MenuDisconnect = 5,
70    TypeText = 6,
71    SendButton = 7,
72    Thread = 8
73 };
74
75 /*
76  *   wxbTHREAD_EVENT declaration, used by csprint
77  */
78 BEGIN_DECLARE_EVENT_TYPES()
79    DECLARE_EVENT_TYPE(wxbTHREAD_EVENT,       1)
80 END_DECLARE_EVENT_TYPES()
81
82 DEFINE_EVENT_TYPE(wxbTHREAD_EVENT)
83
84 typedef void (wxEvtHandler::*wxThreadEventFunction)(wxbThreadEvent&);
85
86 #define EVT_THREAD_EVENT(id, fn) \
87     DECLARE_EVENT_TABLE_ENTRY( \
88         wxbTHREAD_EVENT, id, wxID_ANY, \
89         (wxObjectEventFunction)(wxEventFunction)(wxThreadEventFunction)&fn, \
90         (wxObject *) NULL \
91     ),
92
93 // the event tables connect the wxWindows events with the functions (event
94 // handlers) which process them. It can be also done at run-time, but for the
95 // simple menu events like this the static method is much simpler.
96 BEGIN_EVENT_TABLE(wxbMainFrame, wxFrame)
97    EVT_MENU(Minimal_Quit,  wxbMainFrame::OnQuit)
98    EVT_MENU(Minimal_About, wxbMainFrame::OnAbout)
99    EVT_MENU(ChangeConfigFile, wxbMainFrame::OnChangeConfig)
100    EVT_MENU(EditConfigFile, wxbMainFrame::OnEditConfig)
101    EVT_MENU(MenuConnect, wxbMainFrame::OnConnect)
102    EVT_MENU(MenuDisconnect, wxbMainFrame::OnDisconnect)
103    EVT_TEXT_ENTER(TypeText, wxbMainFrame::OnEnter)
104    EVT_THREAD_EVENT(Thread, wxbMainFrame::OnPrint)
105    EVT_BUTTON(SendButton, wxbMainFrame::OnEnter)
106 END_EVENT_TABLE()
107
108 // ----------------------------------------------------------------------------
109 // wxbThreadEvent
110 // ----------------------------------------------------------------------------
111
112 /*
113  *  wxbThreadEvent constructor
114  */
115 wxbThreadEvent::wxbThreadEvent(int id): wxEvent(id, wxbTHREAD_EVENT) {
116    m_eventObject = NULL;
117 }
118
119 /*
120  *  wxbThreadEvent destructor
121  */
122 wxbThreadEvent::~wxbThreadEvent()
123 {
124    if (m_eventObject != NULL) {
125       delete m_eventObject;
126    }
127 }
128
129 /*
130  *  wxbThreadEvent copy constructor
131  */
132 wxbThreadEvent::wxbThreadEvent(const wxbThreadEvent& te)
133 {
134    this->m_eventType = te.m_eventType;
135    this->m_id = te.m_id;
136    if (te.m_eventObject != NULL) {
137       this->m_eventObject = new wxbPrintObject(*((wxbPrintObject*)te.m_eventObject));
138    }
139    else {
140       this->m_eventObject = NULL;
141    }
142    this->m_skipped = te.m_skipped;
143    this->m_timeStamp = te.m_timeStamp;
144 }
145
146 /*
147  *  Must be implemented (abstract in wxEvent)
148  */
149 wxEvent* wxbThreadEvent::Clone() const
150 {
151    return new wxbThreadEvent(*this);
152 }
153
154 /*
155  *  Gets the wxbPrintObject attached to this event, containing data sent by director
156  */
157 wxbPrintObject* wxbThreadEvent::GetEventPrintObject()
158 {
159    return (wxbPrintObject*)m_eventObject;
160 }
161
162 /*
163  *  Sets the wxbPrintObject attached to this event
164  */
165 void wxbThreadEvent::SetEventPrintObject(wxbPrintObject* object)
166 {
167    m_eventObject = (wxObject*)object;
168 }
169
170 // ----------------------------------------------------------------------------
171 // main frame
172 // ----------------------------------------------------------------------------
173
174 wxbMainFrame *wxbMainFrame::frame = NULL;
175
176 /*
177  *  Singleton constructor
178  */
179 wxbMainFrame* wxbMainFrame::CreateInstance(const wxString& title, const wxPoint& pos, const wxSize& size, long style)
180 {
181    frame = new wxbMainFrame(title, pos, size, style);
182    return frame;
183 }
184
185 /*
186  *  Returns singleton instance
187  */
188 wxbMainFrame* wxbMainFrame::GetInstance()
189 {
190    return frame;
191 }
192
193 /*
194  *  Private destructor
195  */
196 wxbMainFrame::~wxbMainFrame()
197 {
198    if (ct != NULL) { // && (!ct->IsRunning())
199       ct->Delete();
200    }
201    frame = NULL;
202 }
203
204 /*
205  *  Private constructor
206  */
207 wxbMainFrame::wxbMainFrame(const wxString& title, const wxPoint& pos, const wxSize& size, long style)
208       : wxFrame(NULL, -1, title, pos, size, style)
209 {
210    lockedbyconsole = false;
211    
212    ct = NULL;
213    
214    promptparser = NULL;
215
216    // set the frame icon
217    SetIcon(wxIcon(wxwin16x16_xpm));
218
219 #if wxUSE_MENUS
220    // create a menu bar
221    menuFile = new wxMenu;
222
223    // the "About" item should be in the help menu
224    wxMenu *helpMenu = new wxMenu;
225    helpMenu->Append(Minimal_About, _T("&About...\tF1"), _T("Show about dialog"));
226
227    menuFile->Append(MenuConnect, _T("Connect"), _T("Connect to the director"));
228    menuFile->Append(MenuDisconnect, _T("Disconnect"), _T("Disconnect of the director"));
229    menuFile->AppendSeparator();
230    menuFile->Append(ChangeConfigFile, _T("Change of configuration file"), _T("Change your default configuration file"));
231    menuFile->Append(EditConfigFile, _T("Edit your configuration file"), _T("Edit your configuration file"));
232    menuFile->AppendSeparator();
233    menuFile->Append(Minimal_Quit, _T("E&xit\tAlt-X"), _T("Quit this program"));
234
235    // now append the freshly created menu to the menu bar...
236    wxMenuBar *menuBar = new wxMenuBar();
237    menuBar->Append(menuFile, _T("&File"));
238    menuBar->Append(helpMenu, _T("&Help"));
239
240    // ... and attach this menu bar to the frame
241    SetMenuBar(menuBar);
242 #endif // wxUSE_MENUS
243
244    CreateStatusBar(1);
245    SetStatusText(wxString("Welcome to bacula wx-console ") << VERSION << " (" << BDATE << ")!\n");
246
247    wxPanel* global = new wxPanel(this, -1);
248
249    notebook = new wxNotebook(global, -1);
250
251    /* Console */
252
253    wxPanel* consolePanel = new wxPanel(notebook, -1);
254    notebook->AddPage(consolePanel, "Console");
255
256    consoleCtrl = new wxTextCtrl(consolePanel,-1,"",wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH);
257    wxFont font(10, wxMODERN, wxNORMAL, wxNORMAL);
258 #if defined __WXGTK12__ && !defined __WXGTK20__ // Fix for "chinese" fonts under gtk+ 1.2
259    font.SetDefaultEncoding(wxFONTENCODING_ISO8859_1);
260    consoleCtrl->SetDefaultStyle(wxTextAttr(*wxBLACK, wxNullColour, font));
261    Print("Warning : Unicode is disabled because you are using wxWidgets for GTK+ 1.2.\n", CS_DEBUG);
262 #else
263    consoleCtrl->SetDefaultStyle(wxTextAttr(*wxBLACK, wxNullColour, font));
264 #endif
265
266    helpCtrl = new wxStaticText(consolePanel, -1, "Type your command below:");
267
268    wxFlexGridSizer *consoleSizer = new wxFlexGridSizer(4, 1, 0, 0);
269    consoleSizer->AddGrowableCol(0);
270    consoleSizer->AddGrowableRow(0);
271
272    typeCtrl = new wxbHistoryTextCtrl(helpCtrl, consolePanel,TypeText,"",wxDefaultPosition,wxSize(200,20));
273    sendButton = new wxButton(consolePanel, SendButton, "Send");
274    
275    wxFlexGridSizer *typeSizer = new wxFlexGridSizer(1, 2, 0, 0);
276    typeSizer->AddGrowableCol(0);
277    typeSizer->AddGrowableRow(0);
278
279    //typeSizer->Add(new wxStaticText(consolePanel, -1, "Command: "), 0, wxALIGN_CENTER | wxALL, 0);
280    typeSizer->Add(typeCtrl, 1, wxEXPAND | wxALL, 0);
281    typeSizer->Add(sendButton, 1, wxEXPAND | wxLEFT, 5);
282
283    consoleSizer->Add(consoleCtrl, 1, wxEXPAND | wxALL, 0);
284    consoleSizer->Add(new wxStaticLine(consolePanel, -1), 0, wxEXPAND | wxALL, 0);
285    consoleSizer->Add(helpCtrl, 1, wxEXPAND | wxALL, 2);
286    consoleSizer->Add(typeSizer, 0, wxEXPAND | wxALL, 2);
287
288    consolePanel->SetAutoLayout( TRUE );
289    consolePanel->SetSizer( consoleSizer );
290    consoleSizer->SetSizeHints( consolePanel );
291
292    // Creates the list of panels which are included in notebook, and that need to receive director information
293
294    panels = new wxbPanel* [2];
295    panels[0] = new wxbRestorePanel(notebook);
296    panels[1] = NULL;
297
298    for (int i = 0; panels[i] != NULL; i++) {
299       notebook->AddPage(panels[i], panels[i]->GetTitle());
300    }
301
302    wxBoxSizer* globalSizer = new wxBoxSizer(wxHORIZONTAL);
303
304 #if wxCHECK_VERSION(2, 6, 0)
305    globalSizer->Add(notebook, 1, wxEXPAND, 0);
306 #else
307    globalSizer->Add(new wxNotebookSizer(notebook), 1, wxEXPAND, 0);
308 #endif
309
310    global->SetSizer( globalSizer );
311    globalSizer->SetSizeHints( global );
312
313    wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);
314
315    sizer->Add(global, 1, wxEXPAND | wxALL, 0);
316    SetAutoLayout(true);
317    SetSizer( sizer );
318    sizer->SetSizeHints( this );
319    this->SetSize(size);
320    EnableConsole(false);
321    
322    consoleBuffer = "";
323    
324    configfile = "";
325 }
326
327 /*
328  *  Starts the thread interacting with the director
329  *  If config is not empty, uses this config file.
330  */
331 void wxbMainFrame::StartConsoleThread(const wxString& config) {
332    menuFile->Enable(MenuConnect, false);
333    menuFile->Enable(MenuDisconnect, false);
334    menuFile->Enable(ChangeConfigFile, false);
335    menuFile->Enable(EditConfigFile, false);
336
337    if (ct != NULL) {
338       ct->Delete();
339       ct = NULL;
340       wxTheApp->Yield();
341    }
342    if (promptparser == NULL) {
343       promptparser = new wxbPromptParser();      
344    }
345    
346    if (config == "") {
347       configfile = "";
348       
349       if (((wxTheApp->argc % 2) != 1)) {
350          Print("Error while parsing command line arguments, using defaults.\n", CS_DEBUG);
351          Print("Usage: wx-console [-c configfile] [-w tmp]\n", CS_DEBUG);
352       }
353       else {
354          for (int c = 1; c < wxTheApp->argc; c += 2) {
355             if ((wxTheApp->argc >= c+2) && (wxString(wxTheApp->argv[c]) == "-c")) {
356                configfile = wxTheApp->argv[c+1];
357             }
358             if ((wxTheApp->argc >= c+2) && (wxString(wxTheApp->argv[c]) == "-w")) {
359                console_thread::SetWorkingDirectory(wxTheApp->argv[c+1]);
360             }
361             if (wxTheApp->argv[c][0] != '-') {
362                Print("Error while parsing command line arguments, using defaults.\n", CS_DEBUG);
363                Print("Usage: wx-console [-c configfile] [-w tmp]\n", CS_DEBUG);
364                break;
365             }
366          }
367       }
368       
369       if (configfile == "") {
370          wxConfig::Set(new wxConfig("wx-console", "bacula"));
371          if (!wxConfig::Get()->Read("/ConfigFile", &configfile)) {
372 #ifdef HAVE_MACOSX
373             wxFileName filename(::wxGetHomeDir());
374             filename.MakeAbsolute();
375             configfile = filename.GetLongPath();
376             if (configfile.Last() != '/')
377                configfile += '/';
378             configfile += "Library/Preferences/org.bacula.wxconsole.conf";
379 #else
380             wxFileName filename(::wxGetCwd(), "wx-console.conf");
381             filename.MakeAbsolute();
382             configfile = filename.GetLongPath();
383 #ifdef HAVE_WIN32
384             configfile.Replace("\\", "/");
385 #endif //HAVE_WIN32
386 #endif //HAVE_MACOSX
387             wxConfig::Get()->Write("/ConfigFile", configfile);
388    
389             int answer = wxMessageBox(
390                               wxString("It seems that it is the first time you run wx-console.\n") <<
391                                  "This file (" << configfile << ") has been choosen as default configuration file.\n" << 
392                                  "Do you want to edit it? (if you click No you will have to select another file)",
393                               "First run",
394                               wxYES_NO | wxICON_QUESTION, this);
395             if (answer == wxYES) {
396                wxbConfigFileEditor(this, configfile).ShowModal();
397             }
398          }
399       }
400    }
401    else {
402       configfile = config;
403    }
404    
405    wxString err = console_thread::LoadConfig(configfile);
406    
407    while (err != "") {
408       int answer = wxMessageBox(
409                         wxString("Unable to read ") << configfile << "\n" << 
410                            err << "\nDo you want to choose another one? (Press no to edit this file)",
411                         "Unable to read configuration file",
412                         wxYES_NO | wxCANCEL | wxICON_ERROR, this);
413       if (answer == wxNO) {
414          wxbConfigFileEditor(this, configfile).ShowModal();
415          err = console_thread::LoadConfig(configfile);
416       }
417       else if (answer == wxCANCEL) {
418          frame = NULL;
419          Close(true);
420          return;
421       }
422       else { // (answer == wxYES)
423          configfile = wxFileSelector("Please choose a configuration file to use");
424          if ( !configfile.empty() ) {
425             err = console_thread::LoadConfig(configfile);
426          }
427          else {
428             frame = NULL;
429             Close(true);
430             return;
431          }
432       }
433       
434       if ((err == "") && (config == "")) {
435          answer = wxMessageBox(
436                            "This configuration file has been successfully read, use it as default?",
437                            "Configuration file read successfully",
438                            wxYES_NO | wxICON_QUESTION, this);
439          if (answer == wxYES) {
440               wxConfigBase::Get()->Write("/ConfigFile", configfile);
441          }
442          break;
443       }
444    }
445    
446    csprint(wxString("Using this configuration file: ") << configfile << "\n", CS_DEBUG);
447    
448    ct = new console_thread();
449    ct->Create();
450    ct->Run();
451    SetStatusText("Connecting to the director...");
452 }
453
454 /* Register a new wxbDataParser */
455 void wxbMainFrame::Register(wxbDataParser* dp) {
456    parsers.Add(dp);
457 }
458    
459 /* Unregister a wxbDataParser */
460 void wxbMainFrame::Unregister(wxbDataParser* dp) {
461    int index;
462    if ((index = parsers.Index(dp)) != wxNOT_FOUND) {
463       parsers.RemoveAt(index);
464    }
465    else {
466       Print("Failed to unregister a data parser !", CS_DEBUG);
467    }
468 }
469
470 // event handlers
471
472 void wxbMainFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
473 {
474    Print("Quitting.\n", CS_DEBUG);
475    if (ct != NULL) {
476       ct->Delete();
477       ct = NULL;
478       wxTheApp->Yield();
479    }
480    console_thread::FreeLib();
481    frame = NULL;
482    wxTheApp->Yield();
483    Close(TRUE);
484 }
485
486 void wxbMainFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
487 {
488    wxString msg;
489    msg.Printf( _T("Welcome to Bacula wx-console.\nWritten by Nicolas Boichat <nicolas@boichat.ch>\n(C) 2004 Kern Sibbald and John Walker\n"));
490
491    wxMessageBox(msg, _T("About Bacula wx-console"), wxOK | wxICON_INFORMATION, this);
492 }
493
494 void wxbMainFrame::OnChangeConfig(wxCommandEvent& event) {
495    wxString oriconfigfile;
496    wxConfig::Get()->Read("/ConfigFile", &oriconfigfile);
497    wxString configfile = wxFileSelector("Please choose your default configuration file");
498    if ( !configfile.empty() ) {
499       if (oriconfigfile != configfile) {
500          int answer = wxMessageBox(
501                            "Use this configuration file as default?",
502                            "Configuration file",
503                            wxYES_NO | wxICON_QUESTION, this);
504          if (answer == wxYES) {
505               wxConfigBase::Get()->Write("/ConfigFile", configfile);
506               wxConfigBase::Get()->Flush();
507               StartConsoleThread("");
508               return;
509          }
510       }
511    
512       StartConsoleThread(configfile);
513    }
514 }
515
516 void wxbMainFrame::OnEditConfig(wxCommandEvent& event) {
517    wxString configfile;
518    wxConfig::Get()->Read("/ConfigFile", &configfile);
519    int stat = wxbConfigFileEditor(this, configfile).ShowModal();
520    if (stat == wxOK) {
521       StartConsoleThread(configfile);
522    }
523 }
524
525 void wxbMainFrame::OnConnect(wxCommandEvent& event) {
526    StartConsoleThread(configfile);
527 }
528
529 void wxbMainFrame::OnDisconnect(wxCommandEvent& event) {
530    if (ct != NULL) {
531       ct->Delete();
532       ct = NULL;
533    }
534 }
535
536 void wxbMainFrame::OnEnter(wxCommandEvent& WXUNUSED(event))
537 {
538    lockedbyconsole = true;
539    DisablePanels();
540    typeCtrl->HistoryAdd(typeCtrl->GetValue());
541    wxString str = typeCtrl->GetValue() + "\n";
542    Send(str);
543 }
544
545 /*
546  *  Called when data is arriving from director
547  */
548 void wxbMainFrame::OnPrint(wxbThreadEvent& event) {
549    wxbPrintObject* po = event.GetEventPrintObject();
550
551    Print(po->str, po->status);
552 }
553
554 /*
555  *  Prints data received from director to the console, and forwards it to the panels
556  */
557 void wxbMainFrame::Print(wxString str, int status)
558 {
559    if (lockedbyconsole) {
560       EnableConsole(false);
561    }
562    
563    if (status == CS_TERMINATED) {
564       consoleCtrl->AppendText(consoleBuffer);
565       consoleBuffer = "";
566       SetStatusText("Console thread terminated.");
567       consoleCtrl->ScrollLines(3);
568       ct = NULL;
569       DisablePanels();
570       int answer = wxMessageBox("Connection to the director lost. Quit program?", "Connection lost",
571                         wxYES_NO | wxICON_EXCLAMATION, this);
572       if (answer == wxYES) {
573          frame = NULL;
574          Close(true);
575       }
576       menuFile->Enable(MenuConnect, true);
577       menuFile->SetLabel(MenuConnect, "Connect");
578       menuFile->SetHelpString(MenuConnect, "Connect to the director");
579       menuFile->Enable(MenuDisconnect, false);
580       menuFile->Enable(ChangeConfigFile, true);
581       menuFile->Enable(EditConfigFile, true);
582       return;
583    }
584    
585    if (status == CS_CONNECTED) {
586       SetStatusText("Connected to the director.");
587       typeCtrl->ClearCommandList();
588       wxbDataTokenizer* dt = wxbUtils::WaitForEnd(".help", true);
589       int i, j;
590       wxString str;
591       for (i = 0; i < (int)dt->GetCount(); i++) {
592          str = (*dt)[i];
593          str.RemoveLast();
594          if ((j = str.Find(' ')) > -1) {
595             typeCtrl->AddCommand(str.Mid(0, j), str.Mid(j+1));
596          }
597       }
598       EnablePanels();
599       menuFile->Enable(MenuConnect, true);
600       menuFile->SetLabel(MenuConnect, "Reconnect");
601       menuFile->SetHelpString(MenuConnect, "Reconnect to the director");
602       menuFile->Enable(MenuDisconnect, true);
603       menuFile->Enable(ChangeConfigFile, true);
604       menuFile->Enable(EditConfigFile, true);
605       return;
606    }
607    if (status == CS_DISCONNECTED) {
608       consoleCtrl->AppendText(consoleBuffer);
609       consoleBuffer = "";
610       consoleCtrl->ScrollLines(3);
611       SetStatusText("Disconnected of the director.");
612       DisablePanels();
613       return;
614    }
615       
616    // CS_DEBUG is often sent by panels, 
617    // and resend it to them would sometimes cause infinite loops
618    
619    /* One promptcaught is normal, so we must have two true Print values to be
620     * sure that the prompt has effectively been caught.
621     */
622    int promptcaught = -1;
623    
624    if (status != CS_DEBUG) {
625       for (unsigned int i = 0; i < parsers.GetCount(); i++) {
626          promptcaught += parsers[i]->Print(str, status) ? 1 : 0;
627       }
628          
629       if ((status == CS_PROMPT) && (promptcaught < 1) && (promptparser->isPrompt())) {
630          Print("Unexpected question has been received.\n", CS_DEBUG);
631 //         Print(wxString("(") << promptparser->getIntroString() << "/-/" << promptparser->getQuestionString() << ")\n", CS_DEBUG);
632          
633          wxString message;
634          if (promptparser->getIntroString() != "") {
635             message << promptparser->getIntroString() << "\n";
636          }
637          message << promptparser->getQuestionString();
638          
639          if (promptparser->getChoices()) {
640             wxString *choices = new wxString[promptparser->getChoices()->GetCount()];
641             int *numbers = new int[promptparser->getChoices()->GetCount()];
642             int n = 0;
643             
644             for (unsigned int i = 0; i < promptparser->getChoices()->GetCount(); i++) {
645                if ((*promptparser->getChoices())[i] != "") {
646                   choices[n] = (*promptparser->getChoices())[i];
647                   numbers[n] = i;
648                   n++;
649                }
650             }
651             
652             int res = ::wxGetSingleChoiceIndex(message,
653                "wx-console: unexpected director's question.", n, choices, this);
654             if (res == -1) { //Cancel pressed
655                Send(".\n");
656             }
657             else {
658                if (promptparser->isNumericalChoice()) {
659                   Send(wxString() << numbers[res] << "\n");
660                }
661                else {
662                   Send(wxString() << choices[res] << "\n");
663                }
664             }
665          }
666          else {
667             Send(::wxGetTextFromUser(message,
668                "wx-console: unexpected director's question.", "", this) + "\n");
669          }
670       }
671    }
672       
673    if (status == CS_END) {
674       if (lockedbyconsole) {
675          EnablePanels();
676          lockedbyconsole = false;
677       }
678       str = "#";
679    }
680
681    if (status == CS_DEBUG) {
682       consoleCtrl->AppendText(consoleBuffer);
683       consoleBuffer = "";
684       consoleCtrl->ScrollLines(3);
685       consoleCtrl->SetDefaultStyle(wxTextAttr(wxColour(0, 128, 0)));
686    }
687    else {
688       consoleCtrl->SetDefaultStyle(wxTextAttr(*wxBLACK));
689    }
690    consoleBuffer << str;
691    if (status == CS_PROMPT) {
692       if (lockedbyconsole) {
693          EnableConsole(true);
694       }
695       //consoleBuffer << "<P>";
696    }
697    
698    if ((status == CS_END) || (status == CS_PROMPT) || (str.Find("\n") > -1)) {
699       consoleCtrl->AppendText(consoleBuffer);
700       consoleBuffer = "";
701    
702       consoleCtrl->ScrollLines(3);
703    }
704    
705 //   consoleCtrl->ShowPosition(consoleCtrl->GetLastPosition());
706    
707    /*if (status != CS_DEBUG) {
708       consoleCtrl->AppendText("@");
709    }*/
710    //consoleCtrl->SetInsertionPointEnd();
711    
712 /*   if ((consoleCtrl->GetNumberOfLines()-1) > nlines) {
713       nlines = consoleCtrl->GetNumberOfLines()-1;
714    }
715    
716    if (status == CS_END) {
717       consoleCtrl->ShowPosition(nlines);
718    }*/
719 }
720
721 /*
722  *  Sends data to the director
723  */
724 void wxbMainFrame::Send(wxString str)
725 {
726    if (ct != NULL) {
727       ct->Write((const char*)str);
728       typeCtrl->SetValue("");
729       consoleCtrl->SetDefaultStyle(wxTextAttr(*wxRED));
730       consoleCtrl->AppendText(str);
731       consoleCtrl->ScrollLines(3);
732    }
733    
734 /*   if ((consoleCtrl->GetNumberOfLines()-1) > nlines) {
735       nlines = consoleCtrl->GetNumberOfLines()-1;
736    }
737    
738    consoleCtrl->ShowPosition(nlines);*/
739 }
740
741 /* Enable panels */
742 void wxbMainFrame::EnablePanels() {
743    for (int i = 0; panels[i] != NULL; i++) {
744       panels[i]->EnablePanel(true);
745    }
746    EnableConsole(true);
747 }
748
749 /* Disable panels, except the one passed as parameter */
750 void wxbMainFrame::DisablePanels(void* except) {
751    for (int i = 0; panels[i] != NULL; i++) {
752       if (panels[i] != except) {
753          panels[i]->EnablePanel(false);
754       }
755       else {
756          panels[i]->EnablePanel(true);
757       }
758    }
759    if (this != except) {
760       EnableConsole(false);
761    }
762 }
763
764 /* Enable or disable console typing */
765 void wxbMainFrame::EnableConsole(bool enable) {
766    typeCtrl->Enable(enable);
767    sendButton->Enable(enable);
768    if (enable) {
769       typeCtrl->SetFocus();
770    }
771 }
772
773 /*
774  *  Used by csprint, which is called by console thread.
775  *
776  *  In GTK and perhaps X11, only the main thread is allowed to interact with
777  *  graphical components, so by firing an event, the main loop will call OnPrint.
778  *
779  *  Calling OnPrint directly from console thread produces "unexpected async replies".
780  */
781 void firePrintEvent(wxString str, int status)
782 {
783    wxbPrintObject* po = new wxbPrintObject(str, status);
784
785    wxbThreadEvent evt(Thread);
786    evt.SetEventPrintObject(po);
787    
788    if (wxbMainFrame::GetInstance()) {
789       wxbMainFrame::GetInstance()->AddPendingEvent(evt);
790    }
791 }
792
793 //wxString csBuffer; /* Temporary buffer for receiving data from console thread */
794
795 /*
796  *  Called by console thread, this function forwards data line by line and end
797  *  signals to the GUI.
798  */
799 void csprint(const char* str, int status)
800 {
801    if (str != 0) {
802       firePrintEvent(wxString(str), status);
803    }
804    else {
805       firePrintEvent("", status);
806    }
807 }