]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/wx-console/wxbmainframe.cpp
- Fix ANSI labels to put EOF1 and EOF2 after each file mark.
[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    ct = NULL;
211    
212    promptparser = NULL;
213
214    // set the frame icon
215    SetIcon(wxIcon(wxwin16x16_xpm));
216
217 #if wxUSE_MENUS
218    // create a menu bar
219    menuFile = new wxMenu;
220
221    // the "About" item should be in the help menu
222    wxMenu *helpMenu = new wxMenu;
223    helpMenu->Append(Minimal_About, _T("&About...\tF1"), _T("Show about dialog"));
224
225    menuFile->Append(MenuConnect, _T("Connect"), _T("Connect to the director"));
226    menuFile->Append(MenuDisconnect, _T("Disconnect"), _T("Disconnect of the director"));
227    menuFile->AppendSeparator();
228    menuFile->Append(ChangeConfigFile, _T("Change of configuration file"), _T("Change your default configuration file"));
229    menuFile->Append(EditConfigFile, _T("Edit your configuration file"), _T("Edit your configuration file"));
230    menuFile->AppendSeparator();
231    menuFile->Append(Minimal_Quit, _T("E&xit\tAlt-X"), _T("Quit this program"));
232
233    // now append the freshly created menu to the menu bar...
234    wxMenuBar *menuBar = new wxMenuBar();
235    menuBar->Append(menuFile, _T("&File"));
236    menuBar->Append(helpMenu, _T("&Help"));
237
238    // ... and attach this menu bar to the frame
239    SetMenuBar(menuBar);
240 #endif // wxUSE_MENUS
241
242    CreateStatusBar(1);
243    SetStatusText(wxString("Welcome to bacula wx-console ") << VERSION << " (" << BDATE << ")!\n");
244
245    wxPanel* global = new wxPanel(this, -1);
246
247    notebook = new wxNotebook(global, -1);
248
249    /* Console */
250
251    wxPanel* consolePanel = new wxPanel(notebook, -1);
252    notebook->AddPage(consolePanel, "Console");
253
254    consoleCtrl = new wxTextCtrl(consolePanel,-1,"",wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH);
255    wxFont font(10, wxMODERN, wxNORMAL, wxNORMAL);
256 #if defined __WXGTK12__ && !defined __WXGTK20__ // Fix for "chinese" fonts under gtk+ 1.2
257    font.SetDefaultEncoding(wxFONTENCODING_ISO8859_1);
258    consoleCtrl->SetDefaultStyle(wxTextAttr(*wxBLACK, wxNullColour, font));
259    Print("Warning : Unicode is disabled because you are using wxWidgets for GTK+ 1.2.\n", CS_DEBUG);
260 #else
261    consoleCtrl->SetDefaultStyle(wxTextAttr(*wxBLACK, wxNullColour, font));
262 #endif
263
264    helpCtrl = new wxStaticText(consolePanel, -1, "Type your command below:");
265
266    wxFlexGridSizer *consoleSizer = new wxFlexGridSizer(4, 1, 0, 0);
267    consoleSizer->AddGrowableCol(0);
268    consoleSizer->AddGrowableRow(0);
269
270    typeCtrl = new wxbHistoryTextCtrl(helpCtrl, consolePanel,TypeText,"",wxDefaultPosition,wxSize(200,20));
271    sendButton = new wxButton(consolePanel, SendButton, "Send");
272    
273    wxFlexGridSizer *typeSizer = new wxFlexGridSizer(1, 2, 0, 0);
274    typeSizer->AddGrowableCol(0);
275    typeSizer->AddGrowableRow(0);
276
277    //typeSizer->Add(new wxStaticText(consolePanel, -1, "Command: "), 0, wxALIGN_CENTER | wxALL, 0);
278    typeSizer->Add(typeCtrl, 1, wxEXPAND | wxALL, 0);
279    typeSizer->Add(sendButton, 1, wxEXPAND | wxLEFT, 5);
280
281    consoleSizer->Add(consoleCtrl, 1, wxEXPAND | wxALL, 0);
282    consoleSizer->Add(new wxStaticLine(consolePanel, -1), 0, wxEXPAND | wxALL, 0);
283    consoleSizer->Add(helpCtrl, 1, wxEXPAND | wxALL, 2);
284    consoleSizer->Add(typeSizer, 0, wxEXPAND | wxALL, 2);
285
286    consolePanel->SetAutoLayout( TRUE );
287    consolePanel->SetSizer( consoleSizer );
288    consoleSizer->SetSizeHints( consolePanel );
289
290    // Creates the list of panels which are included in notebook, and that need to receive director information
291
292    panels = new wxbPanel* [2];
293    panels[0] = new wxbRestorePanel(notebook);
294    panels[1] = NULL;
295
296    for (int i = 0; panels[i] != NULL; i++) {
297       notebook->AddPage(panels[i], panels[i]->GetTitle());
298    }
299
300    wxBoxSizer* globalSizer = new wxBoxSizer(wxHORIZONTAL);
301
302    globalSizer->Add(new wxNotebookSizer(notebook), 1, wxEXPAND, 0);
303
304    global->SetSizer( globalSizer );
305    globalSizer->SetSizeHints( global );
306
307    wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);
308
309    sizer->Add(global, 1, wxEXPAND | wxALL, 0);
310    SetAutoLayout(true);
311    SetSizer( sizer );
312    sizer->SetSizeHints( this );
313    this->SetSize(size);
314    EnableConsole(false);
315    
316    lockedbyconsole = false;
317    
318    consoleBuffer = "";
319    
320    configfile = "";
321 }
322
323 /*
324  *  Starts the thread interacting with the director
325  *  If config is not empty, uses this config file.
326  */
327 void wxbMainFrame::StartConsoleThread(const wxString& config) {
328    menuFile->Enable(MenuConnect, false);
329    menuFile->Enable(MenuDisconnect, false);
330    menuFile->Enable(ChangeConfigFile, false);
331    menuFile->Enable(EditConfigFile, false);
332
333    if (ct != NULL) {
334       ct->Delete();
335       ct = NULL;
336       wxTheApp->Yield();
337    }
338    if (promptparser == NULL) {
339       promptparser = new wxbPromptParser();      
340    }
341    
342    if (config == "") {
343       configfile = "";
344       
345       if (((wxTheApp->argc % 2) != 1)) {
346          Print("Error while parsing command line arguments, using defaults.\n", CS_DEBUG);
347          Print("Usage: wx-console [-c configfile] [-w tmp]\n", CS_DEBUG);
348       }
349       else {
350          for (int c = 1; c < wxTheApp->argc; c += 2) {
351             if ((wxTheApp->argc >= c+2) && (wxString(wxTheApp->argv[c]) == "-c")) {
352                configfile = wxTheApp->argv[c+1];
353             }
354             if ((wxTheApp->argc >= c+2) && (wxString(wxTheApp->argv[c]) == "-w")) {
355                console_thread::SetWorkingDirectory(wxTheApp->argv[c+1]);
356             }
357             if (wxTheApp->argv[c][0] != '-') {
358                Print("Error while parsing command line arguments, using defaults.\n", CS_DEBUG);
359                Print("Usage: wx-console [-c configfile] [-w tmp]\n", CS_DEBUG);
360                break;
361             }
362          }
363       }
364       
365       if (configfile == "") {
366          wxConfig::Set(new wxConfig("wx-console", "bacula"));
367          if (!wxConfig::Get()->Read("/ConfigFile", &configfile)) {
368 #ifdef HAVE_MACOSX
369             wxFileName filename(::wxGetHomeDir());
370             filename.MakeAbsolute();
371             configfile = filename.GetLongPath();
372             if (configfile.Last() != '/')
373                configfile += '/';
374             configfile += "Library/Preferences/org.bacula.wxconsole.conf";
375 #else
376             wxFileName filename(::wxGetCwd(), "wx-console.conf");
377             filename.MakeAbsolute();
378             configfile = filename.GetLongPath();
379 #ifdef HAVE_WIN32
380             configfile.Replace("\\", "/");
381 #endif //HAVE_WIN32
382 #endif //HAVE_MACOSX
383             wxConfig::Get()->Write("/ConfigFile", configfile);
384    
385             int answer = wxMessageBox(
386                               wxString("It seems that it is the first time you run wx-console.\n") <<
387                                  "This file (" << configfile << ") has been choosen as default configuration file.\n" << 
388                                  "Do you want to edit it? (if you click No you will have to select another file)",
389                               "First run",
390                               wxYES_NO | wxICON_QUESTION, this);
391             if (answer == wxYES) {
392                wxbConfigFileEditor(this, configfile).ShowModal();
393             }
394          }
395       }
396    }
397    else {
398       configfile = config;
399    }
400    
401    wxString err = console_thread::LoadConfig(configfile);
402    
403    while (err != "") {
404       int answer = wxMessageBox(
405                         wxString("Unable to read ") << configfile << "\n" << 
406                            err << "\nDo you want to choose another one? (Press no to edit this file)",
407                         "Unable to read configuration file",
408                         wxYES_NO | wxCANCEL | wxICON_ERROR, this);
409       if (answer == wxNO) {
410          wxbConfigFileEditor(this, configfile).ShowModal();
411          err = console_thread::LoadConfig(configfile);
412       }
413       else if (answer == wxCANCEL) {
414          frame = NULL;
415          Close(true);
416          return;
417       }
418       else { // (answer == wxYES)
419          configfile = wxFileSelector("Please choose a configuration file to use");
420          if ( !configfile.empty() ) {
421             err = console_thread::LoadConfig(configfile);
422          }
423          else {
424             frame = NULL;
425             Close(true);
426             return;
427          }
428       }
429       
430       if ((err == "") && (config == "")) {
431          answer = wxMessageBox(
432                            "This configuration file has been successfully read, use it as default?",
433                            "Configuration file read successfully",
434                            wxYES_NO | wxICON_QUESTION, this);
435          if (answer == wxYES) {
436               wxConfigBase::Get()->Write("/ConfigFile", configfile);
437          }
438          break;
439       }
440    }
441    
442    csprint(wxString("Using this configuration file: ") << configfile << "\n", CS_DEBUG);
443    
444    ct = new console_thread();
445    ct->Create();
446    ct->Run();
447    SetStatusText("Connecting to the director...");
448 }
449
450 /* Register a new wxbDataParser */
451 void wxbMainFrame::Register(wxbDataParser* dp) {
452    parsers.Add(dp);
453 }
454    
455 /* Unregister a wxbDataParser */
456 void wxbMainFrame::Unregister(wxbDataParser* dp) {
457    int index;
458    if ((index = parsers.Index(dp)) != wxNOT_FOUND) {
459       parsers.RemoveAt(index);
460    }
461    else {
462       Print("Failed to unregister a data parser !", CS_DEBUG);
463    }
464 }
465
466 // event handlers
467
468 void wxbMainFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
469 {
470    Print("Quitting.\n", CS_DEBUG);
471    if (ct != NULL) {
472       ct->Delete();
473       ct = NULL;
474       wxTheApp->Yield();
475    }
476    console_thread::FreeLib();
477    frame = NULL;
478    wxTheApp->Yield();
479    Close(TRUE);
480 }
481
482 void wxbMainFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
483 {
484    wxString msg;
485    msg.Printf( _T("Welcome to Bacula wx-console.\nWritten by Nicolas Boichat <nicolas@boichat.ch>\n(C) 2004 Kern Sibbald and John Walker\n"));
486
487    wxMessageBox(msg, _T("About Bacula wx-console"), wxOK | wxICON_INFORMATION, this);
488 }
489
490 void wxbMainFrame::OnChangeConfig(wxCommandEvent& event) {
491    wxString oriconfigfile;
492    wxConfig::Get()->Read("/ConfigFile", &oriconfigfile);
493    wxString configfile = wxFileSelector("Please choose your default configuration file");
494    if ( !configfile.empty() ) {
495       if (oriconfigfile != configfile) {
496          int answer = wxMessageBox(
497                            "Use this configuration file as default?",
498                            "Configuration file",
499                            wxYES_NO | wxICON_QUESTION, this);
500          if (answer == wxYES) {
501               wxConfigBase::Get()->Write("/ConfigFile", configfile);
502               wxConfigBase::Get()->Flush();
503               StartConsoleThread("");
504               return;
505          }
506       }
507    
508       StartConsoleThread(configfile);
509    }
510 }
511
512 void wxbMainFrame::OnEditConfig(wxCommandEvent& event) {
513    wxString configfile;
514    wxConfig::Get()->Read("/ConfigFile", &configfile);
515    int stat = wxbConfigFileEditor(this, configfile).ShowModal();
516    if (stat == wxOK) {
517       StartConsoleThread(configfile);
518    }
519 }
520
521 void wxbMainFrame::OnConnect(wxCommandEvent& event) {
522    StartConsoleThread(configfile);
523 }
524
525 void wxbMainFrame::OnDisconnect(wxCommandEvent& event) {
526    if (ct != NULL) {
527       ct->Delete();
528       ct = NULL;
529    }
530 }
531
532 void wxbMainFrame::OnEnter(wxCommandEvent& WXUNUSED(event))
533 {
534    lockedbyconsole = true;
535    DisablePanels();
536    typeCtrl->HistoryAdd(typeCtrl->GetValue());
537    wxString str = typeCtrl->GetValue() + "\n";
538    Send(str);
539 }
540
541 /*
542  *  Called when data is arriving from director
543  */
544 void wxbMainFrame::OnPrint(wxbThreadEvent& event) {
545    wxbPrintObject* po = event.GetEventPrintObject();
546
547    Print(po->str, po->status);
548 }
549
550 /*
551  *  Prints data received from director to the console, and forwards it to the panels
552  */
553 void wxbMainFrame::Print(wxString str, int status)
554 {
555    if (lockedbyconsole) {
556       EnableConsole(false);
557    }
558    
559    if (status == CS_TERMINATED) {
560       consoleCtrl->AppendText(consoleBuffer);
561       consoleBuffer = "";
562       SetStatusText("Console thread terminated.");
563       consoleCtrl->ScrollLines(3);
564       ct = NULL;
565       DisablePanels();
566       int answer = wxMessageBox("Connection to the director lost. Quit program?", "Connection lost",
567                         wxYES_NO | wxICON_EXCLAMATION, this);
568       if (answer == wxYES) {
569          frame = NULL;
570          Close(true);
571       }
572       menuFile->Enable(MenuConnect, true);
573       menuFile->SetLabel(MenuConnect, "Connect");
574       menuFile->SetHelpString(MenuConnect, "Connect to the director");
575       menuFile->Enable(MenuDisconnect, false);
576       menuFile->Enable(ChangeConfigFile, true);
577       menuFile->Enable(EditConfigFile, true);
578       return;
579    }
580    
581    if (status == CS_CONNECTED) {
582       SetStatusText("Connected to the director.");
583       typeCtrl->ClearCommandList();
584       wxbDataTokenizer* dt = wxbUtils::WaitForEnd(".help", true);
585       int i, j;
586       wxString str;
587       for (i = 0; i < (int)dt->GetCount(); i++) {
588          str = (*dt)[i];
589          str.RemoveLast();
590          if ((j = str.Find(' ')) > -1) {
591             typeCtrl->AddCommand(str.Mid(0, j), str.Mid(j+1));
592          }
593       }
594       EnablePanels();
595       menuFile->Enable(MenuConnect, true);
596       menuFile->SetLabel(MenuConnect, "Reconnect");
597       menuFile->SetHelpString(MenuConnect, "Reconnect to the director");
598       menuFile->Enable(MenuDisconnect, true);
599       menuFile->Enable(ChangeConfigFile, true);
600       menuFile->Enable(EditConfigFile, true);
601       return;
602    }
603    if (status == CS_DISCONNECTED) {
604       consoleCtrl->AppendText(consoleBuffer);
605       consoleBuffer = "";
606       consoleCtrl->ScrollLines(3);
607       SetStatusText("Disconnected of the director.");
608       DisablePanels();
609       return;
610    }
611       
612    // CS_DEBUG is often sent by panels, 
613    // and resend it to them would sometimes cause infinite loops
614    
615    /* One promptcaught is normal, so we must have two true Print values to be
616     * sure that the prompt has effectively been caught.
617     */
618    int promptcaught = -1;
619    
620    if (status != CS_DEBUG) {
621       for (unsigned int i = 0; i < parsers.GetCount(); i++) {
622          promptcaught += parsers[i]->Print(str, status) ? 1 : 0;
623       }
624          
625       if ((status == CS_PROMPT) && (promptcaught < 1) && (promptparser->isPrompt())) {
626          Print("Unexpected question has been received.\n", CS_DEBUG);
627 //         Print(wxString("(") << promptparser->getIntroString() << "/-/" << promptparser->getQuestionString() << ")\n", CS_DEBUG);
628          
629          wxString message;
630          if (promptparser->getIntroString() != "") {
631             message << promptparser->getIntroString() << "\n";
632          }
633          message << promptparser->getQuestionString();
634          
635          if (promptparser->getChoices()) {
636             wxString *choices = new wxString[promptparser->getChoices()->GetCount()];
637             int *numbers = new int[promptparser->getChoices()->GetCount()];
638             int n = 0;
639             
640             for (unsigned int i = 0; i < promptparser->getChoices()->GetCount(); i++) {
641                if ((*promptparser->getChoices())[i] != "") {
642                   choices[n] = (*promptparser->getChoices())[i];
643                   numbers[n] = i;
644                   n++;
645                }
646             }
647             
648             int res = ::wxGetSingleChoiceIndex(message,
649                "wx-console: unexpected director's question.", n, choices, this);
650             if (res == -1) { //Cancel pressed
651                Send(".\n");
652             }
653             else {
654                if (promptparser->isNumericalChoice()) {
655                   Send(wxString() << numbers[res] << "\n");
656                }
657                else {
658                   Send(wxString() << choices[res] << "\n");
659                }
660             }
661          }
662          else {
663             Send(::wxGetTextFromUser(message,
664                "wx-console: unexpected director's question.", "", this) + "\n");
665          }
666       }
667    }
668       
669    if (status == CS_END) {
670       if (lockedbyconsole) {
671          EnablePanels();
672          lockedbyconsole = false;
673       }
674       str = "#";
675    }
676
677    if (status == CS_DEBUG) {
678       consoleCtrl->AppendText(consoleBuffer);
679       consoleBuffer = "";
680       consoleCtrl->ScrollLines(3);
681       consoleCtrl->SetDefaultStyle(wxTextAttr(wxColour(0, 128, 0)));
682    }
683    else {
684       consoleCtrl->SetDefaultStyle(wxTextAttr(*wxBLACK));
685    }
686    consoleBuffer << str;
687    if (status == CS_PROMPT) {
688       if (lockedbyconsole) {
689          EnableConsole(true);
690       }
691       //consoleBuffer << "<P>";
692    }
693    
694    if ((status == CS_END) || (status == CS_PROMPT) || (str.Find("\n") > -1)) {
695       consoleCtrl->AppendText(consoleBuffer);
696       consoleBuffer = "";
697    
698       consoleCtrl->ScrollLines(3);
699    }
700    
701 //   consoleCtrl->ShowPosition(consoleCtrl->GetLastPosition());
702    
703    /*if (status != CS_DEBUG) {
704       consoleCtrl->AppendText("@");
705    }*/
706    //consoleCtrl->SetInsertionPointEnd();
707    
708 /*   if ((consoleCtrl->GetNumberOfLines()-1) > nlines) {
709       nlines = consoleCtrl->GetNumberOfLines()-1;
710    }
711    
712    if (status == CS_END) {
713       consoleCtrl->ShowPosition(nlines);
714    }*/
715 }
716
717 /*
718  *  Sends data to the director
719  */
720 void wxbMainFrame::Send(wxString str)
721 {
722    if (ct != NULL) {
723       ct->Write((const char*)str);
724       typeCtrl->SetValue("");
725       consoleCtrl->SetDefaultStyle(wxTextAttr(*wxRED));
726       consoleCtrl->AppendText(str);
727       consoleCtrl->ScrollLines(3);
728    }
729    
730 /*   if ((consoleCtrl->GetNumberOfLines()-1) > nlines) {
731       nlines = consoleCtrl->GetNumberOfLines()-1;
732    }
733    
734    consoleCtrl->ShowPosition(nlines);*/
735 }
736
737 /* Enable panels */
738 void wxbMainFrame::EnablePanels() {
739    for (int i = 0; panels[i] != NULL; i++) {
740       panels[i]->EnablePanel(true);
741    }
742    EnableConsole(true);
743 }
744
745 /* Disable panels, except the one passed as parameter */
746 void wxbMainFrame::DisablePanels(void* except) {
747    for (int i = 0; panels[i] != NULL; i++) {
748       if (panels[i] != except) {
749          panels[i]->EnablePanel(false);
750       }
751       else {
752          panels[i]->EnablePanel(true);
753       }
754    }
755    if (this != except) {
756       EnableConsole(false);
757    }
758 }
759
760 /* Enable or disable console typing */
761 void wxbMainFrame::EnableConsole(bool enable) {
762    typeCtrl->Enable(enable);
763    sendButton->Enable(enable);
764    if (enable) {
765       typeCtrl->SetFocus();
766    }
767 }
768
769 /*
770  *  Used by csprint, which is called by console thread.
771  *
772  *  In GTK and perhaps X11, only the main thread is allowed to interact with
773  *  graphical components, so by firing an event, the main loop will call OnPrint.
774  *
775  *  Calling OnPrint directly from console thread produces "unexpected async replies".
776  */
777 void firePrintEvent(wxString str, int status)
778 {
779    wxbPrintObject* po = new wxbPrintObject(str, status);
780
781    wxbThreadEvent evt(Thread);
782    evt.SetEventPrintObject(po);
783    
784    if (wxbMainFrame::GetInstance()) {
785       wxbMainFrame::GetInstance()->AddPendingEvent(evt);
786    }
787 }
788
789 //wxString csBuffer; /* Temporary buffer for receiving data from console thread */
790
791 /*
792  *  Called by console thread, this function forwards data line by line and end
793  *  signals to the GUI.
794  */
795 void csprint(const char* str, int status)
796 {
797    if (str != 0) {
798       firePrintEvent(wxString(str), status);
799    }
800    else {
801       firePrintEvent("", status);
802    }
803 }