source: git/src/mainfrm.cc @ f302cbaa

RELEASE/1.1RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereostereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since f302cbaa was f302cbaa, checked in by Olly Betts <olly@…>, 15 years ago

src/mainfrm.cc,src/printwx.cc: Use wxFileName::SplitPath?() instead of
baseleaf_from_fnm().

git-svn-id: file:///home/survex-svn/survex/branches/survex-1_1@3395 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

  • Property mode set to 100644
File size: 78.3 KB
Line 
1//
2//  mainfrm.cc
3//
4//  Main frame handling for Aven.
5//
6//  Copyright (C) 2000-2002,2005,2006 Mark R. Shinwell
7//  Copyright (C) 2001-2003,2004,2005,2006 Olly Betts
8//  Copyright (C) 2005 Martin Green
9//
10//  This program is free software; you can redistribute it and/or modify
11//  it under the terms of the GNU General Public License as published by
12//  the Free Software Foundation; either version 2 of the License, or
13//  (at your option) any later version.
14//
15//  This program is distributed in the hope that it will be useful,
16//  but WITHOUT ANY WARRANTY; without even the implied warranty of
17//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18//  GNU General Public License for more details.
19//
20//  You should have received a copy of the GNU General Public License
21//  along with this program; if not, write to the Free Software
22//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
23//
24
25#ifdef HAVE_CONFIG_H
26#include <config.h>
27#endif
28
29#include "cavernlog.h"
30#include "mainfrm.h"
31#include "aven.h"
32#include "aboutdlg.h"
33
34#include "message.h"
35#include "img.h"
36#include "namecmp.h"
37#include "printwx.h"
38#include "filename.h"
39#include "useful.h"
40
41#include <wx/confbase.h>
42#include <wx/filename.h>
43#include <wx/image.h>
44#include <wx/imaglist.h>
45#include <wx/process.h>
46#include <wx/regex.h>
47
48#include <float.h>
49#include <functional>
50#include <stack>
51#include <vector>
52
53using namespace std;
54
55class AvenSplitterWindow : public wxSplitterWindow {
56    MainFrm *parent;
57
58    public:
59        AvenSplitterWindow(MainFrm *parent_)
60            : wxSplitterWindow(parent_, -1, wxDefaultPosition, wxDefaultSize,
61                               wxSP_3D | wxSP_LIVE_UPDATE),
62              parent(parent_)
63        {
64        }
65
66        void OnSplitterDClick(wxSplitterEvent &e) {
67            parent->ToggleSidePanel();
68        }
69
70    private:
71        DECLARE_EVENT_TABLE()
72};
73
74BEGIN_EVENT_TABLE(AvenSplitterWindow, wxSplitterWindow)
75    EVT_SPLITTER_DCLICK(-1, AvenSplitterWindow::OnSplitterDClick)
76END_EVENT_TABLE()
77
78class EditMarkDlg : public wxDialog {
79    wxTextCtrl * easting, * northing, * altitude;
80    wxTextCtrl * angle, * tilt_angle, * scale, * time;
81public:
82    EditMarkDlg(wxWindow* parent, const PresentationMark & p)
83        : wxDialog(parent, 500, wxString(wxT("Edit Waypoint")))
84    {
85        easting = new wxTextCtrl(this, 601, wxString::Format(wxT("%.3f"), p.GetX()));
86        northing = new wxTextCtrl(this, 602, wxString::Format(wxT("%.3f"), p.GetY()));
87        altitude = new wxTextCtrl(this, 603, wxString::Format(wxT("%.3f"), p.GetZ()));
88        angle = new wxTextCtrl(this, 604, wxString::Format(wxT("%.3f"), p.angle));
89        tilt_angle = new wxTextCtrl(this, 605, wxString::Format(wxT("%.3f"), p.tilt_angle));
90        scale = new wxTextCtrl(this, 606, wxString::Format(wxT("%.3f"), p.scale));
91        if (p.time > 0.0) {
92            time = new wxTextCtrl(this, 607, wxString::Format(wxT("%.3f"), p.time));
93        } else if (p.time < 0.0) {
94            time = new wxTextCtrl(this, 607, wxString::Format(wxT("*%.3f"), -p.time));
95        } else {
96            time = new wxTextCtrl(this, 607, wxT("0"));
97        }
98
99        wxBoxSizer * coords = new wxBoxSizer(wxHORIZONTAL);
100        coords->Add(new wxStaticText(this, 610, wxT("(")), 0, wxALIGN_CENTRE_VERTICAL);
101        coords->Add(easting, 1);
102        coords->Add(new wxStaticText(this, 611, wxT(",")), 0, wxALIGN_CENTRE_VERTICAL);
103        coords->Add(northing, 1);
104        coords->Add(new wxStaticText(this, 612, wxT(",")), 0, wxALIGN_CENTRE_VERTICAL);
105        coords->Add(altitude, 1);
106        coords->Add(new wxStaticText(this, 613, wxT(")")), 0, wxALIGN_CENTRE_VERTICAL);
107        wxBoxSizer* vert = new wxBoxSizer(wxVERTICAL);
108        vert->Add(coords, 0, wxALL, 8);
109        wxBoxSizer * r2 = new wxBoxSizer(wxHORIZONTAL);
110        r2->Add(new wxStaticText(this, 614, wxT("Bearing: ")), 0, wxALIGN_CENTRE_VERTICAL);
111        r2->Add(angle);
112        vert->Add(r2, 0, wxALL, 8);
113        wxBoxSizer * r3 = new wxBoxSizer(wxHORIZONTAL);
114        r3->Add(new wxStaticText(this, 615, wxT("Elevation: ")), 0, wxALIGN_CENTRE_VERTICAL);
115        r3->Add(tilt_angle);
116        vert->Add(r3, 0, wxALL, 8);
117        wxBoxSizer * r4 = new wxBoxSizer(wxHORIZONTAL);
118        r4->Add(new wxStaticText(this, 616, wxT("Scale: ")), 0, wxALIGN_CENTRE_VERTICAL);
119        r4->Add(scale);
120        r4->Add(new wxStaticText(this, 617, wxT(" (unused in perspective view)")),
121                0, wxALIGN_CENTRE_VERTICAL);
122        vert->Add(r4, 0, wxALL, 8);
123
124        wxBoxSizer * r5 = new wxBoxSizer(wxHORIZONTAL);
125        r5->Add(new wxStaticText(this, 616, wxT("Time: ")), 0, wxALIGN_CENTRE_VERTICAL);
126        r5->Add(time);
127        r5->Add(new wxStaticText(this, 617, wxT(" secs (0 = auto; *6 = 6 times auto)")),
128                0, wxALIGN_CENTRE_VERTICAL);
129        vert->Add(r5, 0, wxALL, 8);
130
131        wxBoxSizer * buttons = new wxBoxSizer(wxHORIZONTAL);
132        wxButton* cancel = new wxButton(this, wxID_CANCEL, wxT("Cancel"));
133        buttons->Add(cancel, 0, wxALL, 8);
134        wxButton* ok = new wxButton(this, wxID_OK, wxT("OK"));
135        ok->SetDefault();
136        buttons->Add(ok, 0, wxALL, 8);
137        vert->Add(buttons, 0, wxALL|wxALIGN_RIGHT);
138
139        SetAutoLayout(true);
140        SetSizer(vert);
141
142        vert->Fit(this);
143        vert->SetSizeHints(this);
144    }
145    PresentationMark GetMark() const {
146        double a, t, s, T;
147        Vector3 v(atof(easting->GetValue().char_str()),
148                  atof(northing->GetValue().char_str()),
149                  atof(altitude->GetValue().char_str()));
150        a = atof(angle->GetValue().char_str());
151        t = atof(tilt_angle->GetValue().char_str());
152        s = atof(scale->GetValue().char_str());
153        wxString str = time->GetValue();
154        if (str[0u] == '*') str[0u] = '-';
155        T = atof(str.char_str());
156        return PresentationMark(v, a, t, s, T);
157    }
158
159private:
160    DECLARE_EVENT_TABLE()
161};
162
163// Write a value without trailing zeros after the decimal point.
164static void write_double(double d, FILE * fh) {
165    char buf[64];
166    sprintf(buf, "%.21f", d);
167    char * p = strchr(buf, ',');
168    if (p) *p = '.';
169    size_t l = strlen(buf);
170    while (l > 1 && buf[l - 1] == '0') --l;
171    if (l > 1 && buf[l - 1] == '.') --l;
172    fwrite(buf, l, 1, fh);
173}
174
175class AvenPresList : public wxListCtrl {
176    MainFrm * mainfrm;
177    GfxCore * gfx;
178    vector<PresentationMark> entries;
179    long current_item;
180    bool modified;
181    bool force_save_as;
182    wxString filename;
183
184    public:
185        AvenPresList(MainFrm * mainfrm_, wxWindow * parent, GfxCore * gfx_)
186            : wxListCtrl(parent, listctrl_PRES, wxDefaultPosition, wxDefaultSize,
187                         wxLC_REPORT|wxLC_VIRTUAL),
188              mainfrm(mainfrm_), gfx(gfx_), current_item(-1), modified(false),
189              force_save_as(true)
190            {
191                InsertColumn(0, wmsg(/*Easting*/378));
192                InsertColumn(1, wmsg(/*Northing*/379));
193                InsertColumn(2, wmsg(/*Altitude*/335));
194            }
195
196        void OnBeginLabelEdit(wxListEvent& event) {
197            event.Veto(); // No editting allowed
198        }
199        void OnDeleteItem(wxListEvent& event) {
200            long item = event.GetIndex();
201            if (current_item == item) {
202                current_item = -1;
203            } else if (current_item > item) {
204                --current_item;
205            }
206            entries.erase(entries.begin() + item);
207            SetItemCount(entries.size());
208            modified = true;
209        }
210        void OnDeleteAllItems(wxListEvent& event) {
211            entries.clear();
212            SetItemCount(entries.size());
213            filename = wxString();
214            modified = false;
215            force_save_as = true;
216        }
217        void OnListKeyDown(wxListEvent& event) {
218            switch (event.GetKeyCode()) {
219                case WXK_DELETE: {
220                    long item = GetNextItem(-1, wxLIST_NEXT_ALL,
221                                            wxLIST_STATE_SELECTED);
222                    while (item != -1) {
223                        DeleteItem(item);
224                        // - 1 because the indices were shifted by DeleteItem()
225                        item = GetNextItem(item - 1, wxLIST_NEXT_ALL,
226                                           wxLIST_STATE_SELECTED);
227                    }
228                    break;
229                }
230                default:
231                    //printf("event.GetIndex() = %ld %d\n", event.GetIndex(), event.GetKeyCode());
232                    event.Skip();
233            }
234        }
235        void OnActivated(wxListEvent& event) {
236            // Jump to this view.
237            long item = event.GetIndex();
238            gfx->SetView(entries[item]);
239        }
240        void OnFocused(wxListEvent& event) {
241            current_item = event.GetIndex();
242        }
243        void OnRightClick(wxListEvent& event) {
244            long item = event.GetIndex();
245            EditMarkDlg edit(mainfrm, entries[item]);
246            if (edit.ShowModal() == wxID_OK) {
247                entries[item] = edit.GetMark();
248            }
249        }
250        void OnChar(wxKeyEvent& event) {
251            switch (event.GetKeyCode()) {
252                case WXK_INSERT:
253                    if (event.m_controlDown) {
254                        if (current_item != -1 &&
255                            size_t(current_item) < entries.size()) {
256                            AddMark(current_item, entries[current_item]);
257                        }
258                    } else {
259                        AddMark(current_item);
260                    }
261                    break;
262                case WXK_DELETE:
263                    // Already handled in OnListKeyDown.
264                    break;
265                case WXK_UP: case WXK_DOWN:
266                    event.Skip();
267                    break;
268                default:
269                    gfx->OnKeyPress(event);
270            }
271        }
272        void AddMark(long item = -1) {
273            AddMark(item, gfx->GetView());
274        }
275        void AddMark(long item, const PresentationMark & mark) {
276            if (item == -1) item = entries.size();
277            entries.insert(entries.begin() + item, mark);
278            SetItemCount(entries.size());
279            modified = true;
280        }
281        virtual wxString OnGetItemText(long item, long column) const {
282            if (item < 0 || item >= (long)entries.size()) return wxString();
283            const PresentationMark & p = entries[item];
284            double v;
285            switch (column) {
286                case 0: v = p.GetX(); break;
287                case 1: v = p.GetY(); break;
288                case 2: v = p.GetZ(); break;
289#if 0
290                case 3: v = p.angle; break;
291                case 4: v = p.tilt_angle; break;
292                case 5: v = p.scale; break;
293                case 6: v = p.time; break;
294#endif
295                default: return wxString();
296            }
297            return wxString::Format(wxT("%ld"), (long)v);
298        }
299        void Save(bool use_default_name) {
300            wxString fnm = filename;
301            if (!use_default_name || force_save_as) {
302                AvenAllowOnTop ontop(mainfrm);
303#ifdef __WXMOTIF__
304                wxString ext(wxT("*.fly"));
305#else
306                wxString ext = wmsg(/*Aven presentations*/320);
307                ext += wxT("|*.fly|");
308                ext += wmsg(/*All files*/208);
309                ext += wxT("|");
310                ext += wxFileSelectorDefaultWildcardStr;
311#endif
312                wxFileDialog dlg(this, wmsg(/*Select an output filename*/319),
313                                 wxString(), fnm, ext,
314                                 wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
315                if (dlg.ShowModal() != wxID_OK) return;
316                fnm = dlg.GetPath();
317            }
318
319            FILE * fh_pres = fopen(fnm.fn_str(), "w");
320            if (!fh_pres) {
321                wxGetApp().ReportError(wxString::Format(wmsg(/*Error writing to file `%s'*/110), fnm.c_str()));
322                return;
323            }
324            vector<PresentationMark>::const_iterator i;
325            for (i = entries.begin(); i != entries.end(); ++i) {
326                const PresentationMark &p = *i;
327                write_double(p.GetX(), fh_pres);
328                putc(' ', fh_pres);
329                write_double(p.GetY(), fh_pres);
330                putc(' ', fh_pres);
331                write_double(p.GetZ(), fh_pres);
332                putc(' ', fh_pres);
333                write_double(p.angle, fh_pres);
334                putc(' ', fh_pres);
335                write_double(p.tilt_angle, fh_pres);
336                putc(' ', fh_pres);
337                write_double(p.scale, fh_pres);
338                if (p.time != 0.0) {
339                    putc(' ', fh_pres);
340                    write_double(p.time, fh_pres);
341                }
342                putc('\n', fh_pres);
343            }
344            fclose(fh_pres);
345            filename = fnm;
346            modified = false;
347            force_save_as = false;
348        }
349        void New(const wxString &fnm) {
350            DeleteAllItems();
351            char *baseleaf = baseleaf_from_fnm(fnm.fn_str());
352            filename = wxString(baseleaf, wxConvUTF8);
353            free(baseleaf);
354            filename += wxT(".fly");
355            force_save_as = true;
356        }
357        bool Load(const wxString &fnm) {
358            FILE * fh_pres = fopen(fnm.fn_str(), "r");
359            if (!fh_pres) {
360                wxString m;
361                m.Printf(wmsg(/*Couldn't open file `%s'*/93), fnm.c_str());
362                wxGetApp().ReportError(m);
363                return false;
364            }
365            DeleteAllItems();
366            long item = 0;
367            while (!feof(fh_pres)) {
368                char buf[4096];
369                size_t i = 0;
370                while (i < sizeof(buf) - 1) {
371                    int ch = getc(fh_pres);
372                    if (ch == EOF || ch == '\n' || ch == '\r') break;
373                    buf[i++] = ch;
374                }
375                if (i) {
376                    buf[i] = 0;
377                    double x, y, z, a, t, s, T;
378                    int c = sscanf(buf, "%lf %lf %lf %lf %lf %lf %lf", &x, &y, &z, &a, &t, &s, &T);
379                    if (c < 6) {
380                        char *p = buf;
381                        while ((p = strchr(p, '.'))) *p++ = ',';
382                        c = sscanf(buf, "%lf %lf %lf %lf %lf %lf %lf", &x, &y, &z, &a, &t, &s, &T);
383                        if (c < 6) {
384                            DeleteAllItems();
385                            wxGetApp().ReportError(wxString::Format(wmsg(/*Error in format of presentation file `%s'*/323), fnm.c_str()));
386                            return false;
387                        }
388                    }
389                    if (c == 6) T = 0;
390                    AddMark(item, PresentationMark(Vector3(x, y, z), a, t, s, T));
391                    ++item;
392                }
393            }
394            fclose(fh_pres);
395            filename = fnm;
396            modified = false;
397            force_save_as = false;
398            return true;
399        }
400        bool Modified() const { return modified; }
401        bool Empty() const { return entries.empty(); }
402        PresentationMark GetPresMark(int which) {
403            long item = current_item;
404            if (which == MARK_FIRST) {
405                item = 0;
406            } else if (which == MARK_NEXT) {
407                ++item;
408            } else if (which == MARK_PREV) {
409                --item;
410            }
411            if (item == -1 || item == (long)entries.size())
412                return PresentationMark();
413            if (item != current_item) {
414                // Move the focus
415                if (current_item != -1) {
416                    wxListCtrl::SetItemState(current_item, wxLIST_STATE_FOCUSED,
417                                             0);
418                }
419                wxListCtrl::SetItemState(item, wxLIST_STATE_FOCUSED,
420                                         wxLIST_STATE_FOCUSED);
421            }
422            return entries[item];
423        }
424
425    private:
426
427        DECLARE_NO_COPY_CLASS(AvenPresList)
428        DECLARE_EVENT_TABLE()
429};
430
431BEGIN_EVENT_TABLE(EditMarkDlg, wxDialog)
432END_EVENT_TABLE()
433
434BEGIN_EVENT_TABLE(AvenPresList, wxListCtrl)
435    EVT_LIST_BEGIN_LABEL_EDIT(listctrl_PRES, AvenPresList::OnBeginLabelEdit)
436    EVT_LIST_DELETE_ITEM(listctrl_PRES, AvenPresList::OnDeleteItem)
437    EVT_LIST_DELETE_ALL_ITEMS(listctrl_PRES, AvenPresList::OnDeleteAllItems)
438    EVT_LIST_KEY_DOWN(listctrl_PRES, AvenPresList::OnListKeyDown)
439    EVT_LIST_ITEM_ACTIVATED(listctrl_PRES, AvenPresList::OnActivated)
440    EVT_LIST_ITEM_FOCUSED(listctrl_PRES, AvenPresList::OnFocused)
441    EVT_LIST_ITEM_RIGHT_CLICK(listctrl_PRES, AvenPresList::OnRightClick)
442    EVT_CHAR(AvenPresList::OnChar)
443END_EVENT_TABLE()
444
445BEGIN_EVENT_TABLE(MainFrm, wxFrame)
446    EVT_TEXT(textctrl_FIND, MainFrm::OnFind)
447    EVT_TEXT_ENTER(textctrl_FIND, MainFrm::OnGotoFound)
448    EVT_MENU(button_FIND, MainFrm::OnGotoFound)
449    EVT_MENU(button_HIDE, MainFrm::OnHide)
450    EVT_UPDATE_UI(button_HIDE, MainFrm::OnHideUpdate)
451
452    EVT_MENU(menu_FILE_OPEN, MainFrm::OnOpen)
453    EVT_MENU(menu_FILE_PRINT, MainFrm::OnPrint)
454    EVT_MENU(menu_FILE_PAGE_SETUP, MainFrm::OnPageSetup)
455    EVT_MENU(menu_FILE_SCREENSHOT, MainFrm::OnScreenshot)
456//    EVT_MENU(menu_FILE_PREFERENCES, MainFrm::OnFilePreferences)
457    EVT_MENU(menu_FILE_EXPORT, MainFrm::OnExport)
458    EVT_MENU(menu_FILE_QUIT, MainFrm::OnQuit)
459    EVT_MENU_RANGE(wxID_FILE1, wxID_FILE9, MainFrm::OnMRUFile)
460
461    EVT_MENU(menu_PRES_NEW, MainFrm::OnPresNew)
462    EVT_MENU(menu_PRES_OPEN, MainFrm::OnPresOpen)
463    EVT_MENU(menu_PRES_SAVE, MainFrm::OnPresSave)
464    EVT_MENU(menu_PRES_SAVE_AS, MainFrm::OnPresSaveAs)
465    EVT_MENU(menu_PRES_MARK, MainFrm::OnPresMark)
466    EVT_MENU(menu_PRES_FREWIND, MainFrm::OnPresFRewind)
467    EVT_MENU(menu_PRES_REWIND, MainFrm::OnPresRewind)
468    EVT_MENU(menu_PRES_REVERSE, MainFrm::OnPresReverse)
469    EVT_MENU(menu_PRES_PLAY, MainFrm::OnPresPlay)
470    EVT_MENU(menu_PRES_FF, MainFrm::OnPresFF)
471    EVT_MENU(menu_PRES_FFF, MainFrm::OnPresFFF)
472    EVT_MENU(menu_PRES_PAUSE, MainFrm::OnPresPause)
473    EVT_MENU(menu_PRES_STOP, MainFrm::OnPresStop)
474    EVT_MENU(menu_PRES_EXPORT_MOVIE, MainFrm::OnPresExportMovie)
475
476    EVT_UPDATE_UI(menu_PRES_NEW, MainFrm::OnPresNewUpdate)
477    EVT_UPDATE_UI(menu_PRES_OPEN, MainFrm::OnPresOpenUpdate)
478    EVT_UPDATE_UI(menu_PRES_SAVE, MainFrm::OnPresSaveUpdate)
479    EVT_UPDATE_UI(menu_PRES_SAVE_AS, MainFrm::OnPresSaveAsUpdate)
480    EVT_UPDATE_UI(menu_PRES_MARK, MainFrm::OnPresMarkUpdate)
481    EVT_UPDATE_UI(menu_PRES_FREWIND, MainFrm::OnPresFRewindUpdate)
482    EVT_UPDATE_UI(menu_PRES_REWIND, MainFrm::OnPresRewindUpdate)
483    EVT_UPDATE_UI(menu_PRES_REVERSE, MainFrm::OnPresReverseUpdate)
484    EVT_UPDATE_UI(menu_PRES_PLAY, MainFrm::OnPresPlayUpdate)
485    EVT_UPDATE_UI(menu_PRES_FF, MainFrm::OnPresFFUpdate)
486    EVT_UPDATE_UI(menu_PRES_FFF, MainFrm::OnPresFFFUpdate)
487    EVT_UPDATE_UI(menu_PRES_PAUSE, MainFrm::OnPresPauseUpdate)
488    EVT_UPDATE_UI(menu_PRES_STOP, MainFrm::OnPresStopUpdate)
489    EVT_UPDATE_UI(menu_PRES_EXPORT_MOVIE, MainFrm::OnPresExportMovieUpdate)
490
491    EVT_CLOSE(MainFrm::OnClose)
492    EVT_SET_FOCUS(MainFrm::OnSetFocus)
493
494    EVT_MENU(menu_ROTATION_TOGGLE, MainFrm::OnToggleRotation)
495    EVT_MENU(menu_ROTATION_SPEED_UP, MainFrm::OnSpeedUp)
496    EVT_MENU(menu_ROTATION_SLOW_DOWN, MainFrm::OnSlowDown)
497    EVT_MENU(menu_ROTATION_REVERSE, MainFrm::OnReverseDirectionOfRotation)
498    EVT_MENU(menu_ROTATION_STEP_CCW, MainFrm::OnStepOnceAnticlockwise)
499    EVT_MENU(menu_ROTATION_STEP_CW, MainFrm::OnStepOnceClockwise)
500    EVT_MENU(menu_ORIENT_MOVE_NORTH, MainFrm::OnMoveNorth)
501    EVT_MENU(menu_ORIENT_MOVE_EAST, MainFrm::OnMoveEast)
502    EVT_MENU(menu_ORIENT_MOVE_SOUTH, MainFrm::OnMoveSouth)
503    EVT_MENU(menu_ORIENT_MOVE_WEST, MainFrm::OnMoveWest)
504    EVT_MENU(menu_ORIENT_SHIFT_LEFT, MainFrm::OnShiftDisplayLeft)
505    EVT_MENU(menu_ORIENT_SHIFT_RIGHT, MainFrm::OnShiftDisplayRight)
506    EVT_MENU(menu_ORIENT_SHIFT_UP, MainFrm::OnShiftDisplayUp)
507    EVT_MENU(menu_ORIENT_SHIFT_DOWN, MainFrm::OnShiftDisplayDown)
508    EVT_MENU(menu_ORIENT_PLAN, MainFrm::OnPlan)
509    EVT_MENU(menu_ORIENT_ELEVATION, MainFrm::OnElevation)
510    EVT_MENU(menu_ORIENT_HIGHER_VP, MainFrm::OnHigherViewpoint)
511    EVT_MENU(menu_ORIENT_LOWER_VP, MainFrm::OnLowerViewpoint)
512    EVT_MENU(menu_ORIENT_ZOOM_IN, MainFrm::OnZoomIn)
513    EVT_MENU(menu_ORIENT_ZOOM_OUT, MainFrm::OnZoomOut)
514    EVT_MENU(menu_ORIENT_DEFAULTS, MainFrm::OnDefaults)
515    EVT_MENU(menu_VIEW_SHOW_LEGS, MainFrm::OnShowSurveyLegs)
516    EVT_MENU(menu_VIEW_SHOW_CROSSES, MainFrm::OnShowCrosses)
517    EVT_MENU(menu_VIEW_SHOW_ENTRANCES, MainFrm::OnShowEntrances)
518    EVT_MENU(menu_VIEW_SHOW_FIXED_PTS, MainFrm::OnShowFixedPts)
519    EVT_MENU(menu_VIEW_SHOW_EXPORTED_PTS, MainFrm::OnShowExportedPts)
520    EVT_MENU(menu_VIEW_SHOW_NAMES, MainFrm::OnShowStationNames)
521    EVT_MENU(menu_VIEW_SHOW_OVERLAPPING_NAMES, MainFrm::OnDisplayOverlappingNames)
522    EVT_MENU(menu_VIEW_COLOUR_BY_DEPTH, MainFrm::OnColourByDepth)
523    EVT_MENU(menu_VIEW_COLOUR_BY_DATE, MainFrm::OnColourByDate)
524    EVT_MENU(menu_VIEW_COLOUR_BY_ERROR, MainFrm::OnColourByError)
525    EVT_MENU(menu_VIEW_SHOW_SURFACE, MainFrm::OnShowSurface)
526    EVT_MENU(menu_VIEW_GRID, MainFrm::OnViewGrid)
527    EVT_MENU(menu_VIEW_BOUNDING_BOX, MainFrm::OnViewBoundingBox)
528    EVT_MENU(menu_VIEW_PERSPECTIVE, MainFrm::OnViewPerspective)
529    EVT_MENU(menu_VIEW_SMOOTH_SHADING, MainFrm::OnViewSmoothShading)
530    EVT_MENU(menu_VIEW_TEXTURED, MainFrm::OnViewTextured)
531    EVT_MENU(menu_VIEW_FOG, MainFrm::OnViewFog)
532    EVT_MENU(menu_VIEW_SMOOTH_LINES, MainFrm::OnViewSmoothLines)
533    EVT_MENU(menu_VIEW_FULLSCREEN, MainFrm::OnViewFullScreen)
534    EVT_MENU(menu_VIEW_SHOW_TUBES, MainFrm::OnToggleTubes)
535    EVT_MENU(menu_IND_COMPASS, MainFrm::OnViewCompass)
536    EVT_MENU(menu_IND_CLINO, MainFrm::OnViewClino)
537    EVT_MENU(menu_IND_DEPTH_BAR, MainFrm::OnToggleDepthbar)
538    EVT_MENU(menu_IND_SCALE_BAR, MainFrm::OnToggleScalebar)
539    EVT_MENU(menu_CTL_SIDE_PANEL, MainFrm::OnViewSidePanel)
540    EVT_MENU(menu_CTL_METRIC, MainFrm::OnToggleMetric)
541    EVT_MENU(menu_CTL_DEGREES, MainFrm::OnToggleDegrees)
542    EVT_MENU(menu_CTL_REVERSE, MainFrm::OnReverseControls)
543    EVT_MENU(menu_CTL_CANCEL_DIST_LINE, MainFrm::OnCancelDistLine)
544    EVT_MENU(menu_HELP_ABOUT, MainFrm::OnAbout)
545
546    EVT_UPDATE_UI(menu_FILE_PRINT, MainFrm::OnPrintUpdate)
547    EVT_UPDATE_UI(menu_FILE_SCREENSHOT, MainFrm::OnScreenshotUpdate)
548    EVT_UPDATE_UI(menu_FILE_EXPORT, MainFrm::OnExportUpdate)
549    EVT_UPDATE_UI(menu_ROTATION_TOGGLE, MainFrm::OnToggleRotationUpdate)
550    EVT_UPDATE_UI(menu_ROTATION_SPEED_UP, MainFrm::OnSpeedUpUpdate)
551    EVT_UPDATE_UI(menu_ROTATION_SLOW_DOWN, MainFrm::OnSlowDownUpdate)
552    EVT_UPDATE_UI(menu_ROTATION_REVERSE, MainFrm::OnReverseDirectionOfRotationUpdate)
553    EVT_UPDATE_UI(menu_ROTATION_STEP_CCW, MainFrm::OnStepOnceAnticlockwiseUpdate)
554    EVT_UPDATE_UI(menu_ROTATION_STEP_CW, MainFrm::OnStepOnceClockwiseUpdate)
555    EVT_UPDATE_UI(menu_ORIENT_MOVE_NORTH, MainFrm::OnMoveNorthUpdate)
556    EVT_UPDATE_UI(menu_ORIENT_MOVE_EAST, MainFrm::OnMoveEastUpdate)
557    EVT_UPDATE_UI(menu_ORIENT_MOVE_SOUTH, MainFrm::OnMoveSouthUpdate)
558    EVT_UPDATE_UI(menu_ORIENT_MOVE_WEST, MainFrm::OnMoveWestUpdate)
559    EVT_UPDATE_UI(menu_ORIENT_SHIFT_LEFT, MainFrm::OnShiftDisplayLeftUpdate)
560    EVT_UPDATE_UI(menu_ORIENT_SHIFT_RIGHT, MainFrm::OnShiftDisplayRightUpdate)
561    EVT_UPDATE_UI(menu_ORIENT_SHIFT_UP, MainFrm::OnShiftDisplayUpUpdate)
562    EVT_UPDATE_UI(menu_ORIENT_SHIFT_DOWN, MainFrm::OnShiftDisplayDownUpdate)
563    EVT_UPDATE_UI(menu_ORIENT_PLAN, MainFrm::OnPlanUpdate)
564    EVT_UPDATE_UI(menu_ORIENT_ELEVATION, MainFrm::OnElevationUpdate)
565    EVT_UPDATE_UI(menu_ORIENT_HIGHER_VP, MainFrm::OnHigherViewpointUpdate)
566    EVT_UPDATE_UI(menu_ORIENT_LOWER_VP, MainFrm::OnLowerViewpointUpdate)
567    EVT_UPDATE_UI(menu_ORIENT_ZOOM_IN, MainFrm::OnZoomInUpdate)
568    EVT_UPDATE_UI(menu_ORIENT_ZOOM_OUT, MainFrm::OnZoomOutUpdate)
569    EVT_UPDATE_UI(menu_ORIENT_DEFAULTS, MainFrm::OnDefaultsUpdate)
570    EVT_UPDATE_UI(menu_VIEW_SHOW_LEGS, MainFrm::OnShowSurveyLegsUpdate)
571    EVT_UPDATE_UI(menu_VIEW_SHOW_CROSSES, MainFrm::OnShowCrossesUpdate)
572    EVT_UPDATE_UI(menu_VIEW_SHOW_ENTRANCES, MainFrm::OnShowEntrancesUpdate)
573    EVT_UPDATE_UI(menu_VIEW_SHOW_FIXED_PTS, MainFrm::OnShowFixedPtsUpdate)
574    EVT_UPDATE_UI(menu_VIEW_SHOW_EXPORTED_PTS, MainFrm::OnShowExportedPtsUpdate)
575    EVT_UPDATE_UI(menu_VIEW_SHOW_NAMES, MainFrm::OnShowStationNamesUpdate)
576    EVT_UPDATE_UI(menu_VIEW_SHOW_SURFACE, MainFrm::OnShowSurfaceUpdate)
577    EVT_UPDATE_UI(menu_VIEW_SHOW_OVERLAPPING_NAMES, MainFrm::OnDisplayOverlappingNamesUpdate)
578    EVT_UPDATE_UI(menu_VIEW_COLOUR_BY_DEPTH, MainFrm::OnColourByDepthUpdate)
579    EVT_UPDATE_UI(menu_VIEW_COLOUR_BY_DATE, MainFrm::OnColourByDateUpdate)
580    EVT_UPDATE_UI(menu_VIEW_COLOUR_BY_ERROR, MainFrm::OnColourByErrorUpdate)
581    EVT_UPDATE_UI(menu_VIEW_GRID, MainFrm::OnViewGridUpdate)
582    EVT_UPDATE_UI(menu_VIEW_BOUNDING_BOX, MainFrm::OnViewBoundingBoxUpdate)
583    EVT_UPDATE_UI(menu_VIEW_PERSPECTIVE, MainFrm::OnViewPerspectiveUpdate)
584    EVT_UPDATE_UI(menu_VIEW_SMOOTH_SHADING, MainFrm::OnViewSmoothShadingUpdate)
585    EVT_UPDATE_UI(menu_VIEW_TEXTURED, MainFrm::OnViewTexturedUpdate)
586    EVT_UPDATE_UI(menu_VIEW_FOG, MainFrm::OnViewFogUpdate)
587    EVT_UPDATE_UI(menu_VIEW_SMOOTH_LINES, MainFrm::OnViewSmoothLinesUpdate)
588    EVT_UPDATE_UI(menu_VIEW_FULLSCREEN, MainFrm::OnViewFullScreenUpdate)
589    EVT_UPDATE_UI(menu_VIEW_SHOW_TUBES, MainFrm::OnToggleTubesUpdate)
590    EVT_UPDATE_UI(menu_IND_COMPASS, MainFrm::OnViewCompassUpdate)
591    EVT_UPDATE_UI(menu_IND_CLINO, MainFrm::OnViewClinoUpdate)
592    EVT_UPDATE_UI(menu_IND_DEPTH_BAR, MainFrm::OnToggleDepthbarUpdate)
593    EVT_UPDATE_UI(menu_IND_SCALE_BAR, MainFrm::OnToggleScalebarUpdate)
594    EVT_UPDATE_UI(menu_CTL_INDICATORS, MainFrm::OnIndicatorsUpdate)
595    EVT_UPDATE_UI(menu_CTL_SIDE_PANEL, MainFrm::OnViewSidePanelUpdate)
596    EVT_UPDATE_UI(menu_CTL_REVERSE, MainFrm::OnReverseControlsUpdate)
597    EVT_UPDATE_UI(menu_CTL_CANCEL_DIST_LINE, MainFrm::OnCancelDistLineUpdate)
598    EVT_UPDATE_UI(menu_CTL_METRIC, MainFrm::OnToggleMetricUpdate)
599    EVT_UPDATE_UI(menu_CTL_DEGREES, MainFrm::OnToggleDegreesUpdate)
600END_EVENT_TABLE()
601
602class LabelCmp : public greater<const LabelInfo*> {
603    int separator;
604public:
605    LabelCmp(int separator_) : separator(separator_) {}
606    bool operator()(const LabelInfo* pt1, const LabelInfo* pt2) {
607        return name_cmp(pt1->GetText(), pt2->GetText(), separator) < 0;
608    }
609};
610
611class LabelPlotCmp : public greater<const LabelInfo*> {
612    int separator;
613public:
614    LabelPlotCmp(int separator_) : separator(separator_) {}
615    bool operator()(const LabelInfo* pt1, const LabelInfo* pt2) {
616        int n = pt1->get_flags() - pt2->get_flags();
617        if (n) return n > 0;
618        wxString l1 = pt1->GetText().AfterLast(separator);
619        wxString l2 = pt2->GetText().AfterLast(separator);
620        n = name_cmp(l1, l2, separator);
621        if (n) return n < 0;
622        // Prefer non-2-nodes...
623        // FIXME; implement
624        // if leaf names are the same, prefer shorter labels as we can
625        // display more of them
626        n = pt1->GetText().length() - pt2->GetText().length();
627        if (n) return n < 0;
628        // make sure that we don't ever compare different labels as equal
629        return name_cmp(pt1->GetText(), pt2->GetText(), separator) < 0;
630    }
631};
632
633#if wxUSE_DRAG_AND_DROP
634class DnDFile : public wxFileDropTarget {
635    public:
636        DnDFile(MainFrm *parent) : m_Parent(parent) { }
637        virtual bool OnDropFiles(wxCoord, wxCoord,
638                        const wxArrayString &filenames);
639
640    private:
641        MainFrm * m_Parent;
642};
643
644bool
645DnDFile::OnDropFiles(wxCoord, wxCoord, const wxArrayString &filenames)
646{
647    // Load a survey file by drag-and-drop.
648    assert(filenames.GetCount() > 0);
649
650    if (filenames.GetCount() != 1) {
651        wxGetApp().ReportError(wmsg(/*You may only view one 3d file at a time.*/336));
652        return FALSE;
653    }
654
655    m_Parent->OpenFile(filenames[0]);
656    return TRUE;
657}
658#endif
659
660MainFrm::MainFrm(const wxString& title, const wxPoint& pos, const wxSize& size) :
661    wxFrame(NULL, 101, title, pos, size, wxDEFAULT_FRAME_STYLE | wxNO_FULL_REPAINT_ON_RESIZE), // wxNO_FULL_REPAINT_ON_RESIZE is 0 in wx >= 2.6
662    m_Gfx(NULL), m_NumEntrances(0), m_NumFixedPts(0), m_NumExportedPts(0),
663    m_NumHighlighted(0), m_HasUndergroundLegs(false), m_HasSurfaceLegs(false),
664    m_HasErrorInformation(false), m_IsExtendedElevation(false)
665#ifdef PREFDLG
666    , m_PrefsDlg(NULL)
667#endif
668{
669    icon_path = wxString(msg_cfgpth(), wxConvUTF8);
670    icon_path += wxCONFIG_PATH_SEPARATOR;
671    icon_path += wxT("icons");
672    icon_path += wxCONFIG_PATH_SEPARATOR;
673
674#ifdef _WIN32
675    // The peculiar name is so that the icon is the first in the file
676    // (required by Microsoft Windows for this type of icon)
677    SetIcon(wxIcon(wxT("aaaaaAven")));
678#else
679    SetIcon(wxIcon(icon_path + APP_IMAGE, wxBITMAP_TYPE_PNG));
680#endif
681
682    CreateMenuBar();
683    CreateToolBar();
684    CreateStatusBar(2, wxST_SIZEGRIP);
685    CreateSidePanel();
686
687    int widths[2] = { -1 /* variable width */, -1 };
688    GetStatusBar()->SetStatusWidths(2, widths);
689
690#ifdef __X__ // wxMotif or wxX11
691    int x;
692    int y;
693    GetSize(&x, &y);
694    // X seems to require a forced resize.
695    SetSize(-1, -1, x, y);
696#endif
697
698#if wxUSE_DRAG_AND_DROP
699    SetDropTarget(new DnDFile(this));
700#endif
701}
702
703MainFrm::~MainFrm()
704{
705}
706
707void MainFrm::CreateMenuBar()
708{
709    // Create the menus and the menu bar.
710
711    wxMenu* filemenu = new wxMenu;
712    filemenu->Append(menu_FILE_OPEN, GetTabMsg(/*@Open...##Ctrl+O*/220));
713    filemenu->AppendSeparator();
714    filemenu->Append(menu_FILE_PRINT, GetTabMsg(/*@Print...##Ctrl+P*/380));
715    filemenu->Append(menu_FILE_PAGE_SETUP, GetTabMsg(/*P@age Setup...*/381));
716    filemenu->AppendSeparator();
717    filemenu->Append(menu_FILE_SCREENSHOT, GetTabMsg(/*@Screenshot...*/201));
718    filemenu->Append(menu_FILE_EXPORT, GetTabMsg(/*@Export as...*/382));
719#ifndef __WXMAC__
720    // On wxMac the "Quit" menu item will be moved elsewhere, so we suppress
721    // this separator.
722    filemenu->AppendSeparator();
723#endif
724    filemenu->Append(menu_FILE_QUIT, GetTabMsg(/*@Quit##Ctrl+Q*/221));
725
726    m_history.UseMenu(filemenu);
727    m_history.Load(*wxConfigBase::Get());
728
729    wxMenu* rotmenu = new wxMenu;
730    rotmenu->AppendCheckItem(menu_ROTATION_TOGGLE, GetTabMsg(/*@Auto-Rotate##Space*/231));
731    rotmenu->AppendSeparator();
732    rotmenu->Append(menu_ROTATION_SPEED_UP, GetTabMsg(/*Speed @Up*/232));
733    rotmenu->Append(menu_ROTATION_SLOW_DOWN, GetTabMsg(/*Slow @Down*/233));
734    rotmenu->AppendSeparator();
735    rotmenu->Append(menu_ROTATION_REVERSE, GetTabMsg(/*@Reverse Direction*/234));
736    rotmenu->AppendSeparator();
737    rotmenu->Append(menu_ROTATION_STEP_CCW, GetTabMsg(/*Step Once @Anticlockwise*/235));
738    rotmenu->Append(menu_ROTATION_STEP_CW, GetTabMsg(/*Step Once @Clockwise*/236));
739
740    wxMenu* orientmenu = new wxMenu;
741    orientmenu->Append(menu_ORIENT_MOVE_NORTH, GetTabMsg(/*View @North*/240));
742    orientmenu->Append(menu_ORIENT_MOVE_EAST, GetTabMsg(/*View @East*/241));
743    orientmenu->Append(menu_ORIENT_MOVE_SOUTH, GetTabMsg(/*View @South*/242));
744    orientmenu->Append(menu_ORIENT_MOVE_WEST, GetTabMsg(/*View @West*/243));
745    orientmenu->AppendSeparator();
746    orientmenu->Append(menu_ORIENT_SHIFT_LEFT, GetTabMsg(/*Shift Survey @Left*/244));
747    orientmenu->Append(menu_ORIENT_SHIFT_RIGHT, GetTabMsg(/*Shift Survey @Right*/245));
748    orientmenu->Append(menu_ORIENT_SHIFT_UP, GetTabMsg(/*Shift Survey @Up*/246));
749    orientmenu->Append(menu_ORIENT_SHIFT_DOWN, GetTabMsg(/*Shift Survey @Down*/247));
750    orientmenu->AppendSeparator();
751    orientmenu->Append(menu_ORIENT_PLAN, GetTabMsg(/*@Plan View*/248));
752    orientmenu->Append(menu_ORIENT_ELEVATION, GetTabMsg(/*Ele@vation*/249));
753    orientmenu->AppendSeparator();
754    orientmenu->Append(menu_ORIENT_HIGHER_VP, GetTabMsg(/*@Higher Viewpoint*/250));
755    orientmenu->Append(menu_ORIENT_LOWER_VP, GetTabMsg(/*L@ower Viewpoint*/251));
756    orientmenu->AppendSeparator();
757    orientmenu->Append(menu_ORIENT_ZOOM_IN, GetTabMsg(/*@Zoom In##]*/252));
758    orientmenu->Append(menu_ORIENT_ZOOM_OUT, GetTabMsg(/*Zoo@m Out##[*/253));
759    orientmenu->AppendSeparator();
760    orientmenu->Append(menu_ORIENT_DEFAULTS, GetTabMsg(/*Restore De@fault View*/254));
761
762    wxMenu* presmenu = new wxMenu;
763    presmenu->Append(menu_PRES_NEW, GetTabMsg(/*@New Presentation*/311));
764    presmenu->Append(menu_PRES_OPEN, GetTabMsg(/*@Open Presentation...*/312));
765    presmenu->Append(menu_PRES_SAVE, GetTabMsg(/*@Save Presentation*/313));
766    presmenu->Append(menu_PRES_SAVE_AS, GetTabMsg(/*Save Presentation @As...*/314));
767    presmenu->AppendSeparator();
768    presmenu->Append(menu_PRES_MARK, GetTabMsg(/*@Mark*/315));
769    presmenu->Append(menu_PRES_PLAY, GetTabMsg(/*@Play*/316));
770    presmenu->Append(menu_PRES_EXPORT_MOVIE, GetTabMsg(/*@Export as Movie...*/317));
771
772    wxMenu* viewmenu = new wxMenu;
773#ifndef PREFDLG
774    viewmenu->AppendCheckItem(menu_VIEW_SHOW_NAMES, GetTabMsg(/*Station @Names##Ctrl+N*/270));
775    viewmenu->AppendCheckItem(menu_VIEW_SHOW_TUBES, GetTabMsg(/*Passage @Tubes*/346));
776    viewmenu->AppendCheckItem(menu_VIEW_SHOW_CROSSES, GetTabMsg(/*@Crosses##Ctrl+X*/271));
777    viewmenu->AppendCheckItem(menu_VIEW_GRID, GetTabMsg(/*@Grid##Ctrl+G*/297));
778    viewmenu->AppendCheckItem(menu_VIEW_BOUNDING_BOX, GetTabMsg(/*@Bounding Box##Ctrl+B*/318));
779    viewmenu->AppendSeparator();
780    viewmenu->AppendCheckItem(menu_VIEW_SHOW_LEGS, GetTabMsg(/*@Underground Survey Legs##Ctrl+L*/272));
781    viewmenu->AppendCheckItem(menu_VIEW_SHOW_SURFACE, GetTabMsg(/*@Surface Survey Legs##Ctrl+F*/291));
782    viewmenu->AppendSeparator();
783    viewmenu->AppendCheckItem(menu_VIEW_SHOW_OVERLAPPING_NAMES, GetTabMsg(/*@Overlapping Names*/273));
784    viewmenu->AppendCheckItem(menu_VIEW_COLOUR_BY_DEPTH, GetTabMsg(/*Colour by @Depth*/292));
785    viewmenu->AppendCheckItem(menu_VIEW_COLOUR_BY_DATE, GetTabMsg(/*Colour by D@ate*/293));
786    viewmenu->AppendCheckItem(menu_VIEW_COLOUR_BY_ERROR, GetTabMsg(/*Colour by E@rror*/289));
787    viewmenu->AppendSeparator();
788    viewmenu->AppendCheckItem(menu_VIEW_SHOW_ENTRANCES, GetTabMsg(/*Highlight @Entrances*/294));
789    viewmenu->AppendCheckItem(menu_VIEW_SHOW_FIXED_PTS, GetTabMsg(/*Highlight @Fixed Points*/295));
790    viewmenu->AppendCheckItem(menu_VIEW_SHOW_EXPORTED_PTS, GetTabMsg(/*Highlight E@xported Points*/296));
791    viewmenu->AppendSeparator();
792#else
793    viewmenu-> Append(menu_VIEW_CANCEL_DIST_LINE, GetTabMsg(/*@Cancel Measuring Line##Escape*/281));
794#endif
795    viewmenu->AppendCheckItem(menu_VIEW_PERSPECTIVE, GetTabMsg(/*@Perspective*/237));
796// FIXME: enable this    viewmenu->AppendCheckItem(menu_VIEW_SMOOTH_SHADING, GetTabMsg(/*@Smooth Shading*/?!?);
797    viewmenu->AppendCheckItem(menu_VIEW_TEXTURED, GetTabMsg(/*Textured @Walls*/238));
798    viewmenu->AppendCheckItem(menu_VIEW_FOG, GetTabMsg(/*Fade @Distant Objects*/239));
799    viewmenu->AppendCheckItem(menu_VIEW_SMOOTH_LINES, GetTabMsg(/*@Smoothed Survey Legs*/298));
800    viewmenu->AppendSeparator();
801    viewmenu->AppendCheckItem(menu_VIEW_FULLSCREEN, GetTabMsg(/*@Full Screen Mode##F11*/356));
802#ifdef PREFDLG
803    viewmenu->AppendSeparator();
804    viewmenu-> Append(menu_VIEW_PREFERENCES, GetTabMsg(/*@Preferences...*/347));
805#endif
806
807#ifndef PREFDLG
808    wxMenu* ctlmenu = new wxMenu;
809    ctlmenu->AppendCheckItem(menu_CTL_REVERSE, GetTabMsg(/*@Reverse Sense##Ctrl+R*/280));
810    ctlmenu->AppendSeparator();
811    ctlmenu->Append(menu_CTL_CANCEL_DIST_LINE, GetTabMsg(/*@Cancel Measuring Line##Escape*/281));
812    ctlmenu->AppendSeparator();
813    wxMenu* indmenu = new wxMenu;
814    indmenu->AppendCheckItem(menu_IND_COMPASS, GetTabMsg(/*@Compass*/274));
815    indmenu->AppendCheckItem(menu_IND_CLINO, GetTabMsg(/*C@linometer*/275));
816    indmenu->AppendCheckItem(menu_IND_DEPTH_BAR, GetTabMsg(/*@Depth Bar*/276));
817    indmenu->AppendCheckItem(menu_IND_SCALE_BAR, GetTabMsg(/*@Scale Bar*/277));
818    ctlmenu->Append(menu_CTL_INDICATORS, GetTabMsg(/*@Indicators*/299), indmenu);
819    ctlmenu->AppendCheckItem(menu_CTL_SIDE_PANEL, GetTabMsg(/*@Side Panel*/337));
820    ctlmenu->AppendSeparator();
821    ctlmenu->AppendCheckItem(menu_CTL_METRIC, GetTabMsg(/*@Metric*/342));
822    ctlmenu->AppendCheckItem(menu_CTL_DEGREES, GetTabMsg(/*@Degrees*/343));
823#endif
824
825    wxMenu* helpmenu = new wxMenu;
826    helpmenu->Append(menu_HELP_ABOUT, GetTabMsg(/*@About...*/290));
827
828    wxMenuBar* menubar = new wxMenuBar();
829    menubar->Append(filemenu, GetTabMsg(/*@File*/210));
830    menubar->Append(rotmenu, GetTabMsg(/*@Rotation*/211));
831    menubar->Append(orientmenu, GetTabMsg(/*@Orientation*/212));
832    menubar->Append(viewmenu, GetTabMsg(/*@View*/213));
833#ifndef PREFDLG
834    menubar->Append(ctlmenu, GetTabMsg(/*@Controls*/214));
835#endif
836    menubar->Append(presmenu, GetTabMsg(/*@Presentation*/216));
837#ifndef __WXMAC__
838    // On wxMac the "About" menu item will be moved elsewhere, so we suppress
839    // this menu since it will then be empty.
840    menubar->Append(helpmenu, GetTabMsg(/*@Help*/215));
841#endif
842    SetMenuBar(menubar);
843}
844
845// ICON must be a literal string.
846#define TOOLBAR_BITMAP(ICON) wxBitmap(icon_path + wxT(ICON".png"), wxBITMAP_TYPE_PNG)
847
848void MainFrm::CreateToolBar()
849{
850    // Create the toolbar.
851
852    wxToolBar* toolbar = wxFrame::CreateToolBar();
853
854#ifndef __WXGTK20__
855    toolbar->SetMargins(5, 5);
856#endif
857
858    // FIXME: TRANSLATE tooltips
859    toolbar->AddTool(menu_FILE_OPEN, wxT("Open"), TOOLBAR_BITMAP("open"), wxT("Open a 3D file for viewing"));
860    toolbar->AddTool(menu_PRES_OPEN, wxT("Open presentation"), TOOLBAR_BITMAP("open-pres"), wxT("Open a presentation"));
861    toolbar->AddSeparator();
862    toolbar->AddCheckTool(menu_ROTATION_TOGGLE, wxT("Toggle rotation"), TOOLBAR_BITMAP("rotation"), wxNullBitmap, wxT("Toggle rotation"));
863    toolbar->AddTool(menu_ORIENT_PLAN, wxT("Plan"), TOOLBAR_BITMAP("plan"), wxT("Switch to plan view"));
864    toolbar->AddTool(menu_ORIENT_ELEVATION, wxT("Elevation"), TOOLBAR_BITMAP("elevation"), wxT("Switch to elevation view"));
865    toolbar->AddTool(menu_ORIENT_DEFAULTS, wxT("Default view"), TOOLBAR_BITMAP("defaults"), wxT("Restore default view"));
866    toolbar->AddSeparator();
867    toolbar->AddCheckTool(menu_VIEW_SHOW_NAMES, wxT("Names"), TOOLBAR_BITMAP("names"), wxNullBitmap, wxT("Show station names"));
868    toolbar->AddCheckTool(menu_VIEW_SHOW_CROSSES, wxT("Crosses"), TOOLBAR_BITMAP("crosses"), wxNullBitmap, wxT("Show crosses on stations"));
869    toolbar->AddCheckTool(menu_VIEW_SHOW_ENTRANCES, wxT("Entrances"), TOOLBAR_BITMAP("entrances"), wxNullBitmap, wxT("Highlight entrances"));
870    toolbar->AddCheckTool(menu_VIEW_SHOW_FIXED_PTS, wxT("Fixed points"), TOOLBAR_BITMAP("fixed-pts"), wxNullBitmap, wxT("Highlight fixed points"));
871    toolbar->AddCheckTool(menu_VIEW_SHOW_EXPORTED_PTS, wxT("Exported points"), TOOLBAR_BITMAP("exported-pts"), wxNullBitmap, wxT("Highlight exported stations"));
872    toolbar->AddSeparator();
873    toolbar->AddCheckTool(menu_VIEW_SHOW_LEGS, wxT("Underground legs"), TOOLBAR_BITMAP("ug-legs"), wxNullBitmap, wxT("Show underground surveys"));
874    toolbar->AddCheckTool(menu_VIEW_SHOW_SURFACE, wxT("Surface legs"), TOOLBAR_BITMAP("surface-legs"), wxNullBitmap, wxT("Show surface surveys"));
875    toolbar->AddCheckTool(menu_VIEW_SHOW_TUBES, wxT("Tubes"), TOOLBAR_BITMAP("tubes"), wxNullBitmap, wxT("Show passage tubes"));
876    toolbar->AddSeparator();
877    toolbar->AddCheckTool(menu_PRES_FREWIND, wxT("Fast Rewind"), TOOLBAR_BITMAP("pres-frew"), wxNullBitmap, wxT("Very Fast Rewind"));
878    toolbar->AddCheckTool(menu_PRES_REWIND, wxT("Rewind"), TOOLBAR_BITMAP("pres-rew"), wxNullBitmap, wxT("Fast Rewind"));
879    toolbar->AddCheckTool(menu_PRES_REVERSE, wxT("Backwards"), TOOLBAR_BITMAP("pres-go-back"), wxNullBitmap, wxT("Play Backwards"));
880    toolbar->AddCheckTool(menu_PRES_PAUSE, wxT("Pause"), TOOLBAR_BITMAP("pres-pause"), wxNullBitmap, wxT("Pause"));
881    toolbar->AddCheckTool(menu_PRES_PLAY, wxT("Go"), TOOLBAR_BITMAP("pres-go"), wxNullBitmap, wxT("Play"));
882    toolbar->AddCheckTool(menu_PRES_FF, wxT("FF"), TOOLBAR_BITMAP("pres-ff"), wxNullBitmap, wxT("Fast Forward"));
883    toolbar->AddCheckTool(menu_PRES_FFF, wxT("Very FF"), TOOLBAR_BITMAP("pres-fff"), wxNullBitmap, wxT("Very Fast Forward"));
884    toolbar->AddTool(menu_PRES_STOP, wxT("Stop"), TOOLBAR_BITMAP("pres-stop"), wxT("Stop"));
885
886    toolbar->AddSeparator();
887    m_FindBox = new wxTextCtrl(toolbar, textctrl_FIND, wxString(), wxDefaultPosition,
888                               wxDefaultSize, wxTE_PROCESS_ENTER);
889    toolbar->AddControl(m_FindBox);
890    toolbar->AddTool(button_FIND, TOOLBAR_BITMAP("find"),
891                     wmsg(/*Find*/332)/*"Search for station name"*/);
892    toolbar->AddTool(button_HIDE, TOOLBAR_BITMAP("hideresults"),
893                     wmsg(/*Hide*/333)/*"Hide search results"*/);
894
895    toolbar->Realize();
896}
897
898void MainFrm::CreateSidePanel()
899{
900    m_Splitter = new AvenSplitterWindow(this);
901
902    m_Notebook = new wxNotebook(m_Splitter, 400, wxDefaultPosition,
903                                wxDefaultSize,
904                                wxBK_BOTTOM | wxBK_LEFT);
905    m_Notebook->Show(false);
906
907    wxPanel * panel = new wxPanel(m_Notebook);
908    m_Tree = new AvenTreeCtrl(this, panel);
909
910//    m_RegexpCheckBox = new wxCheckBox(find_panel, -1,
911//                                    msg(/*Regular expression*/334));
912
913    wxBoxSizer *panel_sizer = new wxBoxSizer(wxVERTICAL);
914    panel_sizer->Add(m_Tree, 1, wxALL | wxEXPAND, 2);
915    panel->SetAutoLayout(true);
916    panel->SetSizer(panel_sizer);
917//    panel_sizer->Fit(panel);
918//    panel_sizer->SetSizeHints(panel);
919
920    m_Control = new GUIControl();
921    m_Gfx = new GfxCore(this, m_Splitter, m_Control);
922    m_Control->SetView(m_Gfx);
923
924    // Presentation panel:
925    wxPanel * prespanel = new wxPanel(m_Notebook);
926
927    m_PresList = new AvenPresList(this, prespanel, m_Gfx);
928
929    wxBoxSizer *pres_panel_sizer = new wxBoxSizer(wxVERTICAL);
930    pres_panel_sizer->Add(m_PresList, 1, wxALL | wxEXPAND, 2);
931    prespanel->SetAutoLayout(true);
932    prespanel->SetSizer(pres_panel_sizer);
933
934    // Overall tabbed structure:
935    // FIXME: this assumes images are 15x15
936    wxImageList* image_list = new wxImageList(15, 15);
937    wxString path = wxString(msg_cfgpth(), wxConvUTF8);
938    path += wxCONFIG_PATH_SEPARATOR;
939    path += wxT("icons") ;
940    path += wxCONFIG_PATH_SEPARATOR;
941    image_list->Add(wxBitmap(path + wxT("survey-tree.png"), wxBITMAP_TYPE_PNG));
942    image_list->Add(wxBitmap(path + wxT("pres-tree.png"), wxBITMAP_TYPE_PNG));
943    m_Notebook->SetImageList(image_list);
944    m_Notebook->AddPage(panel, wmsg(/*Surveys*/376), true, 0);
945    m_Notebook->AddPage(prespanel, wmsg(/*Presentation*/377), false, 1);
946
947    m_Splitter->Initialize(m_Gfx);
948}
949
950bool
951MainFrm::ProcessSVXFile(const wxString & file)
952{
953    Show(true);
954    m_Splitter->Show(false);
955    CavernLogWindow * log = new CavernLogWindow(this);
956    log->SetSize(GetClientSize());
957
958    int result = log->process(file);
959    if (result == 0) {
960        log->Show(false);
961        m_Splitter->Show();
962    }
963    return result >= 0;
964}
965
966bool MainFrm::LoadData(const wxString& file_, wxString prefix)
967{
968    wxString file(file_);
969    // Load survey data from file, centre the dataset around the origin,
970    // and prepare the data for drawing.
971
972#if 0
973    wxStopWatch timer;
974    timer.Start();
975#endif
976    wxString filename_used;
977
978    // Check if this is an unprocessed survey data file.
979    if (file.length() > 4 && file[file.length() - 4] == '.') {
980        wxString ext = file.substr(file.length() - 3, 3);
981        if (strcasecmp(ext.char_str(), "svx") == 0 ||
982            strcasecmp(ext.char_str(), "dat") == 0 ||
983            strcasecmp(ext.char_str(), "mak") == 0) {
984            if (!ProcessSVXFile(file)) return false;
985            filename_used = file;
986            char * base_fnm = base_from_fnm(file.char_str());
987            char * fnm_3d = add_ext(base_fnm, "3d");
988            file = wxString(fnm_3d, wxConvUTF8);
989            osfree(fnm_3d);
990            osfree(base_fnm);
991        }
992    }
993
994    // Load the survey data.
995    img* survey = img_open_survey(file.char_str(), prefix.char_str());
996    if (!survey) {
997        wxString m = wxString::Format(wmsg(img_error()), file.c_str());
998        wxGetApp().ReportError(m);
999        return false;
1000    }
1001
1002    if (!filename_used.empty()) {
1003        m_File = filename_used;
1004    } else {
1005        m_File = wxString(survey->filename_opened, wxConvUTF8);
1006    }
1007    m_IsExtendedElevation = survey->is_extended_elevation;
1008
1009    m_Tree->DeleteAllItems();
1010
1011    // Create a list of all the leg vertices, counting them and finding the
1012    // extent of the survey at the same time.
1013
1014    m_NumFixedPts = 0;
1015    m_NumExportedPts = 0;
1016    m_NumEntrances = 0;
1017    m_HasUndergroundLegs = false;
1018    m_HasSurfaceLegs = false;
1019    m_HasErrorInformation = false;
1020
1021    // FIXME: discard existing presentation? ask user about saving if we do!
1022
1023    // Delete any existing list entries.
1024    m_Labels.clear();
1025
1026    Double xmin = DBL_MAX;
1027    Double xmax = -DBL_MAX;
1028    Double ymin = DBL_MAX;
1029    Double ymax = -DBL_MAX;
1030    Double zmin = DBL_MAX;
1031    Double zmax = -DBL_MAX;
1032
1033    m_DepthMin = DBL_MAX;
1034    Double depthmax = -DBL_MAX;
1035
1036    m_DateMin = (time_t)-1;
1037    if (m_DateMin < 0) {
1038        // Hmm, signed time_t!
1039        // FIXME: find a cleaner way to do this...
1040        time_t x = time_t(1) << (sizeof(time_t) * 8 - 2);
1041        m_DateMin = x;
1042        while ((x>>=1) != 0) m_DateMin |= x;
1043    }
1044    time_t datemax = 0;
1045    complete_dateinfo = true;
1046
1047    traverses.clear();
1048    surface_traverses.clear();
1049    tubes.clear();
1050
1051    // Ultimately we probably want different types (subclasses perhaps?) for
1052    // underground and surface data, so we don't need to store LRUD for surface
1053    // stuff.
1054    traverse * current_traverse = NULL;
1055    traverse * current_surface_traverse = NULL;
1056    vector<XSect> * current_tube = NULL;
1057
1058    int result;
1059    img_point prev_pt = {0,0,0};
1060    bool current_polyline_is_surface = false;
1061    bool pending_move = false;
1062    // When a traverse is split between surface and underground, we split it
1063    // into contiguous traverses of each, but we need to track these so we can
1064    // assign the error statistics to all of them.  So we keep counts of how
1065    // many surface_traverses and traverses we've generated for the current
1066    // traverse.
1067    size_t n_traverses = 0;
1068    size_t n_surface_traverses = 0;
1069    do {
1070#if 0
1071        if (++items % 200 == 0) {
1072            long pos = ftell(survey->fh);
1073            int progress = int((double(pos) / double(file_size)) * 100.0);
1074            // SetProgress(progress);
1075        }
1076#endif
1077
1078        img_point pt;
1079        result = img_read_item(survey, &pt);
1080        switch (result) {
1081            case img_MOVE:
1082                n_traverses = n_surface_traverses = 0;
1083                pending_move = true;
1084                prev_pt = pt;
1085                break;
1086
1087            case img_LINE: {
1088                // Update survey extents.
1089                if (pt.x < xmin) xmin = pt.x;
1090                if (pt.x > xmax) xmax = pt.x;
1091                if (pt.y < ymin) ymin = pt.y;
1092                if (pt.y > ymax) ymax = pt.y;
1093                if (pt.z < zmin) zmin = pt.z;
1094                if (pt.z > zmax) zmax = pt.z;
1095
1096                time_t date;
1097                date = survey->date1 + (survey->date2 - survey->date1) / 2;
1098                if (date) {
1099                    if (date < m_DateMin) m_DateMin = date;
1100                    if (date > datemax) datemax = date;
1101                } else {
1102                    complete_dateinfo = false;
1103                }
1104
1105                bool is_surface = (survey->flags & img_FLAG_SURFACE);
1106                if (!is_surface) {
1107                    if (pt.z < m_DepthMin) m_DepthMin = pt.z;
1108                    if (pt.z > depthmax) depthmax = pt.z;
1109                }
1110                if (pending_move || current_polyline_is_surface != is_surface) {
1111                    if (!current_polyline_is_surface && current_traverse) {
1112                        //FixLRUD(*current_traverse);
1113                    }
1114                    current_polyline_is_surface = is_surface;
1115                    // Start new traverse (surface or underground).
1116                    if (is_surface) {
1117                        m_HasSurfaceLegs = true;
1118                        surface_traverses.push_back(traverse());
1119                        current_surface_traverse = &surface_traverses.back();
1120                        ++n_surface_traverses;
1121                    } else {
1122                        m_HasUndergroundLegs = true;
1123                        traverses.push_back(traverse());
1124                        current_traverse = &traverses.back();
1125                        ++n_traverses;
1126                        // The previous point was at a surface->ug transition.
1127                        if (prev_pt.z < m_DepthMin) m_DepthMin = prev_pt.z;
1128                        if (prev_pt.z > depthmax) depthmax = prev_pt.z;
1129                    }
1130                    if (pending_move) {
1131                        // Update survey extents.  We only need to do this if
1132                        // there's a pending move, since for a surface <->
1133                        // underground transition, we'll already have handled
1134                        // this point.
1135                        if (prev_pt.x < xmin) xmin = prev_pt.x;
1136                        if (prev_pt.x > xmax) xmax = prev_pt.x;
1137                        if (prev_pt.y < ymin) ymin = prev_pt.y;
1138                        if (prev_pt.y > ymax) ymax = prev_pt.y;
1139                        if (prev_pt.z < zmin) zmin = prev_pt.z;
1140                        if (prev_pt.z > zmax) zmax = prev_pt.z;
1141                    }
1142
1143                    if (is_surface) {
1144                        current_surface_traverse->push_back(PointInfo(prev_pt));
1145                    } else {
1146                        current_traverse->push_back(PointInfo(prev_pt));
1147                    }
1148                }
1149
1150                if (is_surface) {
1151                    current_surface_traverse->push_back(PointInfo(pt, date));
1152                } else {
1153                    current_traverse->push_back(PointInfo(pt, date));
1154                }
1155
1156                prev_pt = pt;
1157                pending_move = false;
1158                break;
1159            }
1160
1161            case img_LABEL: {
1162                int flags = survey->flags;
1163                if (flags & img_SFLAG_ENTRANCE) {
1164                    flags ^= (img_SFLAG_ENTRANCE | LFLAG_ENTRANCE);
1165                }
1166                LabelInfo* label = new LabelInfo(pt, wxString(survey->label, wxConvUTF8), flags);
1167                if (label->IsEntrance()) {
1168                    m_NumEntrances++;
1169                }
1170                if (label->IsFixedPt()) {
1171                    m_NumFixedPts++;
1172                }
1173                if (label->IsExportedPt()) {
1174                    m_NumExportedPts++;
1175                }
1176                m_Labels.push_back(label);
1177                break;
1178            }
1179
1180            case img_XSECT: {
1181                if (!current_tube) {
1182                    // Start new current_tube.
1183                    tubes.push_back(vector<XSect>());
1184                    current_tube = &tubes.back();
1185                }
1186
1187                // FIXME: avoid linear search...
1188                list<LabelInfo*>::const_iterator i = m_Labels.begin();
1189                wxString label(survey->label, wxConvUTF8);
1190                while (i != m_Labels.end() && (*i)->GetText() != label) ++i;
1191
1192                if (i == m_Labels.end()) {
1193                    // Unattached cross-section - ignore for now.
1194                    printf("unattached cross-section\n");
1195                    if (current_tube->size() == 1)
1196                        tubes.resize(tubes.size() - 1);
1197                    current_tube = NULL;
1198                    break;
1199                }
1200
1201                time_t date;
1202                date = survey->date1 + (survey->date2 - survey->date1) / 2;
1203                if (date) {
1204                    if (date < m_DateMin) m_DateMin = date;
1205                    if (date > datemax) datemax = date;
1206                }
1207
1208                current_tube->push_back(XSect(**i, date, survey->l, survey->r, survey->u, survey->d));
1209                break;
1210            }
1211
1212            case img_XSECT_END:
1213                // Finish off current_tube.
1214                // If there's only one cross-section in the tube, just
1215                // discard it for now.  FIXME: we should handle this
1216                // when we come to skinning the tubes.
1217                if (current_tube && current_tube->size() == 1)
1218                    tubes.resize(tubes.size() - 1);
1219                current_tube = NULL;
1220                break;
1221
1222            case img_ERROR_INFO: {
1223                if (survey->E == 0.0) {
1224                    // Currently cavern doesn't spot all articulating traverses
1225                    // so we assume that any traverse with no error isn't part
1226                    // of a loop.  FIXME: fix cavern!
1227                    break;
1228                }
1229                m_HasErrorInformation = true;
1230                list<traverse>::reverse_iterator t;
1231                t = surface_traverses.rbegin();
1232                while (n_surface_traverses) {
1233                    assert(t != surface_traverses.rend());
1234                    t->n_legs = survey->n_legs;
1235                    t->length = survey->length;
1236                    t->E = survey->E;
1237                    t->H = survey->H;
1238                    t->V = survey->V;
1239                    --n_surface_traverses;
1240                    ++t;
1241                }
1242                t = traverses.rbegin();
1243                while (n_traverses) {
1244                    assert(t != traverses.rend());
1245                    t->n_legs = survey->n_legs;
1246                    t->length = survey->length;
1247                    t->E = survey->E;
1248                    t->H = survey->H;
1249                    t->V = survey->V;
1250                    --n_traverses;
1251                    ++t;
1252                }
1253                break;
1254            }
1255
1256            case img_BAD: {
1257                m_Labels.clear();
1258
1259                // FIXME: Do we need to reset all these? - Olly
1260                m_NumFixedPts = 0;
1261                m_NumExportedPts = 0;
1262                m_NumEntrances = 0;
1263                m_HasUndergroundLegs = false;
1264                m_HasSurfaceLegs = false;
1265
1266                img_close(survey);
1267
1268                wxString m = wxString::Format(wmsg(img_error()), file.c_str());
1269                wxGetApp().ReportError(m);
1270
1271                return false;
1272            }
1273
1274            default:
1275                break;
1276        }
1277    } while (result != img_STOP);
1278
1279    if (!current_polyline_is_surface && current_traverse) {
1280        //FixLRUD(*current_traverse);
1281    }
1282
1283    // Finish off current_tube.
1284    // If there's only one cross-section in the tube, just
1285    // discard it for now.  FIXME: we should handle this
1286    // when we come to skinning the tubes.
1287    if (current_tube && current_tube->size() == 1)
1288        tubes.resize(tubes.size() - 1);
1289
1290    separator = survey->separator;
1291    m_Title = wxString(survey->title, wxConvUTF8);
1292    m_DateStamp = wxString(survey->datestamp, wxConvUTF8);
1293    img_close(survey);
1294
1295    // Check we've actually loaded some legs or stations!
1296    if (!m_HasUndergroundLegs && !m_HasSurfaceLegs && m_Labels.empty()) {
1297        wxString m = wxString::Format(wmsg(/*No survey data in 3d file `%s'*/202), file.c_str());
1298        wxGetApp().ReportError(m);
1299        return false;
1300    }
1301
1302    if (traverses.empty() && surface_traverses.empty()) {
1303        // No legs, so get survey extents from stations
1304        list<LabelInfo*>::const_iterator i;
1305        for (i = m_Labels.begin(); i != m_Labels.end(); ++i) {
1306            if ((*i)->GetX() < xmin) xmin = (*i)->GetX();
1307            if ((*i)->GetX() > xmax) xmax = (*i)->GetX();
1308            if ((*i)->GetY() < ymin) ymin = (*i)->GetY();
1309            if ((*i)->GetY() > ymax) ymax = (*i)->GetY();
1310            if ((*i)->GetZ() < zmin) zmin = (*i)->GetZ();
1311            if ((*i)->GetZ() > zmax) zmax = (*i)->GetZ();
1312        }
1313    }
1314
1315    m_Ext.assign(xmax - xmin, ymax - ymin, zmax - zmin);
1316
1317    if (datemax < m_DateMin) m_DateMin = 0;
1318    m_DateExt = datemax - m_DateMin;
1319
1320    // Sort the labels.
1321    m_Labels.sort(LabelCmp(separator));
1322
1323    // Fill the tree of stations and prefixes.
1324    FillTree();
1325
1326    // Sort labels so that entrances are displayed in preference,
1327    // then fixed points, then exported points, then other points.
1328    //
1329    // Also sort by leaf name so that we'll tend to choose labels
1330    // from different surveys, rather than labels from surveys which
1331    // are earlier in the list.
1332    m_Labels.sort(LabelPlotCmp(separator));
1333
1334    // Centre the dataset around the origin.
1335    CentreDataset(Vector3(xmin, ymin, zmin));
1336
1337    if (depthmax < m_DepthMin) {
1338        m_DepthMin = 0;
1339        m_DepthExt = 0;
1340    } else {
1341        m_DepthExt = depthmax - m_DepthMin;
1342        m_DepthMin -= m_Offsets.GetZ();
1343    }
1344
1345#if 0
1346    printf("time to load = %.3f\n", (double)timer.Time());
1347#endif
1348
1349    // Update window title.
1350    SetTitle(m_Title + " - "APP_NAME);
1351
1352    return true;
1353}
1354
1355#if 0
1356// Run along a newly read in traverse and make up plausible LRUD where
1357// it is missing.
1358void
1359MainFrm::FixLRUD(traverse & centreline)
1360{
1361    assert(centreline.size() > 1);
1362
1363    Double last_size = 0;
1364    vector<PointInfo>::iterator i = centreline.begin();
1365    while (i != centreline.end()) {
1366        // Get the coordinates of this vertex.
1367        Point & pt_v = *i++;
1368        Double size;
1369
1370        if (i != centreline.end()) {
1371            Double h = sqrd(i->GetX() - pt_v.GetX()) +
1372                       sqrd(i->GetY() - pt_v.GetY());
1373            Double v = sqrd(i->GetZ() - pt_v.GetZ());
1374            if (h + v > 30.0 * 30.0) {
1375                Double scale = 30.0 / sqrt(h + v);
1376                h *= scale;
1377                v *= scale;
1378            }
1379            size = sqrt(h + v / 9);
1380            size /= 4;
1381            if (i == centreline.begin() + 1) {
1382                // First segment.
1383                last_size = size;
1384            } else {
1385                // Intermediate segment.
1386                swap(size, last_size);
1387                size += last_size;
1388                size /= 2;
1389            }
1390        } else {
1391            // Last segment.
1392            size = last_size;
1393        }
1394
1395        Double & l = pt_v.l;
1396        Double & r = pt_v.r;
1397        Double & u = pt_v.u;
1398        Double & d = pt_v.d;
1399
1400        if (l == 0 && r == 0 && u == 0 && d == 0) {
1401            l = r = u = d = -size;
1402        } else {
1403            if (l < 0 && r < 0) {
1404                l = r = -size;
1405            } else if (l < 0) {
1406                l = -(2 * size - r);
1407                if (l >= 0) l = -0.01;
1408            } else if (r < 0) {
1409                r = -(2 * size - l);
1410                if (r >= 0) r = -0.01;
1411            }
1412            if (u < 0 && d < 0) {
1413                u = d = -size;
1414            } else if (u < 0) {
1415                u = -(2 * size - d);
1416                if (u >= 0) u = -0.01;
1417            } else if (d < 0) {
1418                d = -(2 * size - u);
1419                if (d >= 0) d = -0.01;
1420            }
1421        }
1422    }
1423}
1424#endif
1425
1426void MainFrm::FillTree()
1427{
1428    // Create the root of the tree.
1429    wxTreeItemId treeroot = m_Tree->AddRoot(wxFileNameFromPath(m_File));
1430
1431    // Fill the tree of stations and prefixes.
1432    stack<wxTreeItemId> previous_ids;
1433    wxString current_prefix;
1434    wxTreeItemId current_id = treeroot;
1435
1436    list<LabelInfo*>::iterator pos = m_Labels.begin();
1437    while (pos != m_Labels.end()) {
1438        LabelInfo* label = *pos++;
1439
1440        // Determine the current prefix.
1441        wxString prefix = label->GetText().BeforeLast(separator);
1442
1443        // Determine if we're still on the same prefix.
1444        if (prefix == current_prefix) {
1445            // no need to fiddle with branches...
1446        }
1447        // If not, then see if we've descended to a new prefix.
1448        else if (prefix.length() > current_prefix.length() &&
1449                 prefix.StartsWith(current_prefix) &&
1450                 (prefix[current_prefix.length()] == separator ||
1451                  current_prefix.empty())) {
1452            // We have, so start as many new branches as required.
1453            int current_prefix_length = current_prefix.length();
1454            current_prefix = prefix;
1455            size_t next_dot = current_prefix_length;
1456            if (!next_dot) --next_dot;
1457            do {
1458                size_t prev_dot = next_dot + 1;
1459
1460                // Extract the next bit of prefix.
1461                next_dot = prefix.find(separator, prev_dot + 1);
1462
1463                wxString bit = prefix.substr(prev_dot, next_dot - prev_dot);
1464                assert(!bit.empty());
1465
1466                // Add the current tree ID to the stack.
1467                previous_ids.push(current_id);
1468
1469                // Append the new item to the tree and set this as the current branch.
1470                current_id = m_Tree->AppendItem(current_id, bit);
1471                m_Tree->SetItemData(current_id, new TreeData(prefix.substr(0, next_dot)));
1472            } while (next_dot != wxString::npos);
1473        }
1474        // Otherwise, we must have moved up, and possibly then down again.
1475        else {
1476            size_t count = 0;
1477            bool ascent_only = (prefix.length() < current_prefix.length() &&
1478                                current_prefix.StartsWith(prefix) &&
1479                                (current_prefix[prefix.length()] == separator ||
1480                                 prefix.empty()));
1481            if (!ascent_only) {
1482                // Find out how much of the current prefix and the new prefix
1483                // are the same.
1484                // Note that we require a match of a whole number of parts
1485                // between dots!
1486                for (size_t i = 0; prefix[i] == current_prefix[i]; ++i) {
1487                    if (prefix[i] == separator) count = i + 1;
1488                }
1489            } else {
1490                count = prefix.length() + 1;
1491            }
1492
1493            // Extract the part of the current prefix after the bit (if any)
1494            // which has matched.
1495            // This gives the prefixes to ascend over.
1496            wxString prefixes_ascended = current_prefix.substr(count);
1497
1498            // Count the number of prefixes to ascend over.
1499            int num_prefixes = prefixes_ascended.Freq(separator);
1500
1501            // Reverse up over these prefixes.
1502            for (int i = 1; i <= num_prefixes; i++) {
1503                previous_ids.pop();
1504            }
1505            current_id = previous_ids.top();
1506            previous_ids.pop();
1507
1508            if (!ascent_only) {
1509                // Add branches for this new part.
1510                size_t next_dot = count - 1;
1511                do {
1512                    size_t prev_dot = next_dot + 1;
1513
1514                    // Extract the next bit of prefix.
1515                    next_dot = prefix.find(separator, prev_dot + 1);
1516
1517                    wxString bit = prefix.substr(prev_dot, next_dot - prev_dot);
1518                    assert(!bit.empty());
1519
1520                    // Add the current tree ID to the stack.
1521                    previous_ids.push(current_id);
1522
1523                    // Append the new item to the tree and set this as the current branch.
1524                    current_id = m_Tree->AppendItem(current_id, bit);
1525                    m_Tree->SetItemData(current_id, new TreeData(prefix.substr(0, next_dot)));
1526                } while (next_dot != wxString::npos);
1527            }
1528
1529            current_prefix = prefix;
1530        }
1531
1532        // Now add the leaf.
1533        wxString bit = label->GetText().AfterLast(separator);
1534        assert(!bit.empty());
1535        wxTreeItemId id = m_Tree->AppendItem(current_id, bit);
1536        m_Tree->SetItemData(id, new TreeData(label));
1537        label->tree_id = id;
1538        // Set the colour for an item in the survey tree.
1539        if (label->IsEntrance()) {
1540            // Entrances are green (like entrance blobs).
1541            m_Tree->SetItemTextColour(id, wxColour(0, 255, 0));
1542        } else if (label->IsSurface()) {
1543            // Surface stations are dark green.
1544            m_Tree->SetItemTextColour(id, wxColour(49, 158, 79));
1545        }
1546    }
1547
1548    m_Tree->Expand(treeroot);
1549    m_Tree->SetEnabled();
1550}
1551
1552void MainFrm::SelectTreeItem(LabelInfo* label)
1553{
1554    m_Tree->SelectItem(label->tree_id);
1555}
1556
1557void MainFrm::CentreDataset(const Vector3 & vmin)
1558{
1559    // Centre the dataset around the origin.
1560
1561    m_Offsets = vmin + (m_Ext * 0.5);
1562
1563    list<traverse>::iterator t = traverses.begin();
1564    while (t != traverses.end()) {
1565        assert(t->size() > 1);
1566        vector<PointInfo>::iterator pos = t->begin();
1567        while (pos != t->end()) {
1568            Point & point = *pos++;
1569            point -= m_Offsets;
1570        }
1571        ++t;
1572    }
1573
1574    t = surface_traverses.begin();
1575    while (t != surface_traverses.end()) {
1576        assert(t->size() > 1);
1577        vector<PointInfo>::iterator pos = t->begin();
1578        while (pos != t->end()) {
1579            Point & point = *pos++;
1580            point -= m_Offsets;
1581        }
1582        ++t;
1583    }
1584
1585    list<vector<XSect> >::iterator i = tubes.begin();
1586    while (i != tubes.end()) {
1587        assert(i->size() > 1);
1588        vector<XSect>::iterator pos = i->begin();
1589        while (pos != i->end()) {
1590            Point & point = *pos++;
1591            point -= m_Offsets;
1592        }
1593        ++i;
1594    }
1595
1596    list<LabelInfo*>::iterator lpos = m_Labels.begin();
1597    while (lpos != m_Labels.end()) {
1598        Point & point = **lpos++;
1599        point -= m_Offsets;
1600    }
1601}
1602
1603void MainFrm::OnMRUFile(wxCommandEvent& event)
1604{
1605    wxString f(m_history.GetHistoryFile(event.GetId() - wxID_FILE1));
1606    if (!f.empty()) OpenFile(f);
1607}
1608
1609void MainFrm::OpenFile(const wxString& file, wxString survey)
1610{
1611    wxBusyCursor hourglass;
1612    wxString old_file = m_File;
1613    if (LoadData(file, survey)) {
1614        if (wxIsAbsolutePath(m_File)) {
1615            m_history.AddFileToHistory(m_File);
1616        } else {
1617            wxString abs = wxGetCwd();
1618            abs += wxCONFIG_PATH_SEPARATOR;
1619            abs += m_File;
1620            m_history.AddFileToHistory(abs);
1621        }
1622        wxConfigBase *b = wxConfigBase::Get();
1623        m_history.Save(*b);
1624        b->Flush();
1625
1626        int x;
1627        int y;
1628        GetClientSize(&x, &y);
1629        if (x < 600)
1630            x /= 3;
1631        else if (x < 1000)
1632            x = 200;
1633        else
1634            x /= 5;
1635
1636        m_Splitter->SplitVertically(m_Notebook, m_Gfx, x);
1637        m_SashPosition = x; // Save width of panel.
1638
1639        m_Gfx->Initialise(old_file == m_File);
1640        m_Notebook->Show(true);
1641
1642        m_Gfx->Show(true);
1643        m_Gfx->SetFocus();
1644    }
1645}
1646
1647//
1648//  UI event handlers
1649//
1650
1651// For Unix we want "*.svx;*.SVX" while for Windows we only want "*.svx".
1652#ifdef _WIN32
1653# define CASE(X)
1654#else
1655# define CASE(X) ";"X
1656#endif
1657
1658void MainFrm::OnOpen(wxCommandEvent&)
1659{
1660    AvenAllowOnTop ontop(this);
1661#ifdef __WXMOTIF__
1662    wxString filetypes = wxT("*.3d");
1663#else
1664    wxString filetypes;
1665    filetypes.Printf(wxT("%s|*.3d;*.svx;*.plt;*.plf;*.dat;*.mak;*.xyz"
1666                     CASE("*.3D;*.SVX;*.PLT;*.PLF;*.DAT;*.MAK;*.XYZ")
1667                     "|%s|*.3d"CASE("*.3D")
1668                     "|%s|*.svx"CASE("*.SVX")
1669                     "|%s|*.plt;*.plf"CASE("*.PLT;*.PLF")
1670                     "|%s|*.dat;*.mak"CASE("*.DAT;*.MAK")
1671                     "|%s|*.xyz"CASE("*.XYZ")
1672                     "|%s|%s"),
1673                     wxT("All survey files"),
1674                     wmsg(/*Survex 3d files*/207).c_str(),
1675                     wxT("Survex svx files"),
1676                     wmsg(/*Compass PLT files*/324).c_str(),
1677                     wxT("Compass DAT and MAK files"),
1678                     wmsg(/*CMAP XYZ files*/325).c_str(),
1679                     wmsg(/*All files*/208).c_str(),
1680                     wxFileSelectorDefaultWildcardStr);
1681#endif
1682    // FIXME: drop "3d" from this message?
1683    wxFileDialog dlg(this, wmsg(/*Select a 3d file to view*/206),
1684                     wxString(), wxString(),
1685                     filetypes, wxFD_OPEN|wxFD_FILE_MUST_EXIST);
1686    if (dlg.ShowModal() == wxID_OK) {
1687        OpenFile(dlg.GetPath());
1688    }
1689}
1690
1691void MainFrm::OnScreenshot(wxCommandEvent&)
1692{
1693    AvenAllowOnTop ontop(this);
1694    wxString baseleaf;
1695    wxFileName::SplitPath(m_File, NULL, NULL, &baseleaf, NULL, wxPATH_NATIVE);
1696    wxFileDialog dlg(this, wmsg(/*Save Screenshot*/321), wxString(),
1697                     baseleaf + wxT(".png"),
1698                     wxT("*.png"), wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
1699    if (dlg.ShowModal() == wxID_OK) {
1700        static bool png_handled = false;
1701        if (!png_handled) {
1702#if 0 // FIXME : enable this to allow other export formats...
1703            ::wxInitAllImageHandlers();
1704#else
1705            wxImage::AddHandler(new wxPNGHandler);
1706#endif
1707            png_handled = true;
1708        }
1709        if (!m_Gfx->SaveScreenshot(dlg.GetPath(), wxBITMAP_TYPE_PNG)) {
1710            wxGetApp().ReportError(wxString::Format(wmsg(/*Error writing to file `%s'*/110), dlg.GetPath().c_str()));
1711        }
1712    }
1713}
1714
1715void MainFrm::OnScreenshotUpdate(wxUpdateUIEvent& event)
1716{
1717    event.Enable(!m_File.empty());
1718}
1719
1720void MainFrm::OnFilePreferences(wxCommandEvent&)
1721{
1722#ifdef PREFDLG
1723    m_PrefsDlg = new PrefsDlg(m_Gfx, this);
1724    m_PrefsDlg->Show(true);
1725#endif
1726}
1727
1728void MainFrm::OnPrint(wxCommandEvent&)
1729{
1730    m_Gfx->OnPrint(m_File, m_Title, m_DateStamp);
1731}
1732
1733void MainFrm::OnPageSetup(wxCommandEvent&)
1734{
1735    wxPageSetupDialog dlg(this, wxGetApp().GetPageSetupDialogData());
1736    if (dlg.ShowModal() == wxID_OK) {
1737        wxGetApp().SetPageSetupDialogData(dlg.GetPageSetupData());
1738    }
1739}
1740
1741void MainFrm::OnExport(wxCommandEvent&)
1742{
1743    m_Gfx->OnExport(m_File, m_Title);
1744}
1745
1746void MainFrm::OnQuit(wxCommandEvent&)
1747{
1748    if (m_PresList->Modified()) {
1749        AvenAllowOnTop ontop(this);
1750        // FIXME: better to ask "Do you want to save your changes?" and offer [Save] [Discard] [Cancel]
1751        if (wxMessageBox(wmsg(/*The current presentation has been modified.  Abandon unsaved changes?*/327),
1752                         wmsg(/*Modified Presentation*/326),
1753                         wxOK|wxCANCEL|wxICON_QUESTION) == wxCANCEL) {
1754            return;
1755        }
1756    }
1757    wxConfigBase *b = wxConfigBase::Get();
1758    if (IsFullScreen()) {
1759        b->Write(wxT("width"), -2);
1760        b->DeleteEntry(wxT("height"));
1761    } else if (IsMaximized()) {
1762        b->Write(wxT("width"), -1);
1763        b->DeleteEntry(wxT("height"));
1764    } else {
1765        int width, height;
1766        GetSize(&width, &height);
1767        b->Write(wxT("width"), width);
1768        b->Write(wxT("height"), height);
1769    }
1770    b->Flush();
1771    exit(0);
1772}
1773
1774void MainFrm::OnClose(wxCloseEvent&)
1775{
1776    wxCommandEvent dummy;
1777    OnQuit(dummy);
1778}
1779
1780void MainFrm::OnAbout(wxCommandEvent&)
1781{
1782    AvenAllowOnTop ontop(this);
1783    AboutDlg dlg(this, icon_path);
1784    dlg.Centre();
1785    dlg.ShowModal();
1786}
1787
1788void MainFrm::UpdateStatusBar()
1789{
1790    if (!here_text.empty()) {
1791        GetStatusBar()->SetStatusText(here_text);
1792        GetStatusBar()->SetStatusText(dist_text, 1);
1793    } else if (!coords_text.empty()) {
1794        GetStatusBar()->SetStatusText(coords_text);
1795        GetStatusBar()->SetStatusText(distfree_text, 1);
1796    } else {
1797        GetStatusBar()->SetStatusText(wxString());
1798        GetStatusBar()->SetStatusText(wxString(), 1);
1799    }
1800}
1801
1802void MainFrm::ClearTreeSelection()
1803{
1804    m_Tree->UnselectAll();
1805    if (!dist_text.empty()) {
1806        dist_text = wxString();
1807        UpdateStatusBar();
1808    }
1809    m_Gfx->SetThere();
1810}
1811
1812void MainFrm::ClearCoords()
1813{
1814    if (!coords_text.empty()) {
1815        coords_text = wxString();
1816        UpdateStatusBar();
1817    }
1818}
1819
1820void MainFrm::SetCoords(const Vector3 &v)
1821{
1822    wxString & s = coords_text;
1823    if (m_Gfx->GetMetric()) {
1824        s.Printf(wmsg(/*%.2f E, %.2f N*/338), v.GetX(), v.GetY());
1825        s += wxString::Format(wxT(", %s %.2fm"), wmsg(/*Altitude*/335).c_str(), v.GetZ());
1826    } else {
1827        s.Printf(wmsg(/*%.2f E, %.2f N*/338),
1828                 v.GetX() / METRES_PER_FOOT, v.GetY() / METRES_PER_FOOT);
1829        s += wxString::Format(wxT(", %s %.2fft"), wmsg(/*Altitude*/335).c_str(),
1830                              v.GetZ() / METRES_PER_FOOT);
1831    }
1832    distfree_text = wxString();
1833    UpdateStatusBar();
1834}
1835
1836const LabelInfo * MainFrm::GetTreeSelection() const {
1837    wxTreeItemData* sel_wx;
1838    if (!m_Tree->GetSelectionData(&sel_wx)) return NULL;
1839
1840    const TreeData* data = static_cast<const TreeData*>(sel_wx);
1841    if (!data->IsStation()) return NULL;
1842
1843    return data->GetLabel();
1844}
1845
1846void MainFrm::SetCoords(Double x, Double y)
1847{
1848    wxString & s = coords_text;
1849    if (m_Gfx->GetMetric()) {
1850        s.Printf(wmsg(/*%.2f E, %.2f N*/338), x, y);
1851    } else {
1852        s.Printf(wmsg(/*%.2f E, %.2f N*/338),
1853                 x / METRES_PER_FOOT, y / METRES_PER_FOOT);
1854    }
1855
1856    wxString & t = distfree_text;
1857    t = wxString();
1858    const LabelInfo* label;
1859    if (m_Gfx->ShowingMeasuringLine() && (label = GetTreeSelection())) {
1860        Vector3 delta(x - m_Offsets.GetX() - label->GetX(),
1861                      y - m_Offsets.GetY() - label->GetY(), 0);
1862        Double dh = sqrt(delta.GetX()*delta.GetX() + delta.GetY()*delta.GetY());
1863        Double brg = deg(atan2(delta.GetX(), delta.GetY()));
1864        if (brg < 0) brg += 360;
1865
1866        wxString from_str;
1867        from_str.Printf(wmsg(/*From %s*/339), label->GetText().c_str());
1868
1869        wxString brg_unit;
1870        if (m_Gfx->GetDegrees()) {
1871            brg_unit = wmsg(/*&deg;*/344);
1872        } else {
1873            brg *= 400.0 / 360.0;
1874            brg_unit = wmsg(/*grad*/345);
1875        }
1876
1877        if (m_Gfx->GetMetric()) {
1878            t.Printf(wmsg(/*%s: H %.2f%s, Brg %03d%s*/374),
1879                     from_str.c_str(), dh, wxT("m"), int(brg), brg_unit.c_str());
1880        } else {
1881            t.Printf(wmsg(/*%s: H %.2f%s, Brg %03d%s*/374),
1882                     from_str.c_str(), dh / METRES_PER_FOOT, wxT("ft"), int(brg),
1883                     brg_unit.c_str());
1884        }
1885    }
1886
1887    UpdateStatusBar();
1888}
1889
1890void MainFrm::SetAltitude(Double z)
1891{
1892    wxString & s = coords_text;
1893    if (m_Gfx->GetMetric()) {
1894        s.Printf(wxT("%s %.2fm"), wmsg(/*Altitude*/335).c_str(), double(z));
1895    } else {
1896        s.Printf(wxT("%s %.2fft"), wmsg(/*Altitude*/335).c_str(), double(z / METRES_PER_FOOT));
1897    }
1898
1899    wxString & t = distfree_text;
1900    t = wxString();
1901    const LabelInfo* label;
1902    if (m_Gfx->ShowingMeasuringLine() && (label = GetTreeSelection())) {
1903        Double dz = z - m_Offsets.GetZ() - label->GetZ();
1904
1905        wxString from_str;
1906        from_str.Printf(wmsg(/*From %s*/339), label->GetText().c_str());
1907
1908        if (m_Gfx->GetMetric()) {
1909            t.Printf(wmsg(/*%s: V %.2f%s*/375),
1910                     from_str.c_str(), dz, wxT("m"));
1911        } else {
1912            t.Printf(wmsg(/*%s: V %.2f%s*/375),
1913                     from_str.c_str(), dz / METRES_PER_FOOT, wxT("ft"));
1914        }
1915    }
1916
1917    UpdateStatusBar();
1918}
1919
1920void MainFrm::ShowInfo(const LabelInfo *here)
1921{
1922    assert(m_Gfx);
1923
1924    if (!here) {
1925        m_Gfx->SetHere();
1926        m_Tree->SetHere(wxTreeItemId());
1927        // Don't clear "There" mark here.
1928        if (here_text.empty() && dist_text.empty()) return;
1929        here_text = wxString();
1930        dist_text = wxString();
1931        UpdateStatusBar();
1932        return;
1933    }
1934
1935    Vector3 v = *here + m_Offsets;
1936    wxString & s = here_text;
1937    if (m_Gfx->GetMetric()) {
1938        s.Printf(wmsg(/*%.2f E, %.2f N*/338), v.GetX(), v.GetY());
1939        s += wxString::Format(wxT(", %s %.2fm"), wmsg(/*Altitude*/335).c_str(), v.GetZ());
1940    } else {
1941        s.Printf(wmsg(/*%.2f E, %.2f N*/338),
1942                 v.GetX() / METRES_PER_FOOT, v.GetY() / METRES_PER_FOOT);
1943        s += wxString::Format(wxT(", %s %.2fft"), wmsg(/*Altitude*/335).c_str(),
1944                              v.GetZ() / METRES_PER_FOOT);
1945    }
1946    s += wxT(": ");
1947    s += here->GetText();
1948    m_Gfx->SetHere(*here);
1949    m_Tree->SetHere(here->tree_id);
1950
1951    const LabelInfo* label;
1952    if (m_Gfx->ShowingMeasuringLine() && (label = GetTreeSelection())) {
1953        Vector3 delta = *here - *label;
1954
1955        Double d_horiz = sqrt(delta.GetX()*delta.GetX() + delta.GetY()*delta.GetY());
1956        Double dr = delta.magnitude();
1957
1958        Double brg = deg(atan2(delta.GetX(), delta.GetY()));
1959        if (brg < 0) brg += 360;
1960
1961        wxString from_str;
1962        from_str.Printf(wmsg(/*From %s*/339), label->GetText().c_str());
1963
1964        wxString hv_str;
1965        if (m_Gfx->GetMetric()) {
1966            hv_str.Printf(wmsg(/*H %.2f%s, V %.2f%s*/340),
1967                          d_horiz, wxT("m"), delta.GetZ(), wxT("m"));
1968        } else {
1969            hv_str.Printf(wmsg(/*H %.2f%s, V %.2f%s*/340),
1970                          d_horiz / METRES_PER_FOOT, wxT("ft"),
1971                          delta.GetZ() / METRES_PER_FOOT, wxT("ft"));
1972        }
1973        wxString brg_unit;
1974        if (m_Gfx->GetDegrees()) {
1975            brg_unit = wmsg(/*&deg;*/344);
1976        } else {
1977            brg *= 400.0 / 360.0;
1978            brg_unit = wmsg(/*grad*/345);
1979        }
1980        wxString & d = dist_text;
1981        if (m_Gfx->GetMetric()) {
1982            d.Printf(wmsg(/*%s: %s, Dist %.2f%s, Brg %03d%s*/341),
1983                     from_str.c_str(), hv_str.c_str(),
1984                     dr, wxT("m"), int(brg), brg_unit.c_str());
1985        } else {
1986            d.Printf(wmsg(/*%s: %s, Dist %.2f%s, Brg %03d%s*/341),
1987                     from_str.c_str(), hv_str.c_str(),
1988                     dr / METRES_PER_FOOT, wxT("ft"), int(brg),
1989                     brg_unit.c_str());
1990        }
1991        m_Gfx->SetThere(*label);
1992    } else {
1993        dist_text = wxString();
1994        m_Gfx->SetThere();
1995    }
1996    UpdateStatusBar();
1997}
1998
1999void MainFrm::DisplayTreeInfo(const wxTreeItemData* item)
2000{
2001    const TreeData* data = static_cast<const TreeData*>(item);
2002    if (data && data->IsStation()) {
2003        const LabelInfo * label = data->GetLabel();
2004        ShowInfo(label);
2005        m_Gfx->SetHere(*label);
2006    } else {
2007        ShowInfo(NULL);
2008    }
2009}
2010
2011void MainFrm::TreeItemSelected(const wxTreeItemData* item, bool zoom)
2012{
2013    const TreeData* data = static_cast<const TreeData*>(item);
2014    if (data && data->IsStation()) {
2015        const LabelInfo* label = data->GetLabel();
2016        if (zoom) m_Gfx->CentreOn(*label);
2017        m_Gfx->SetThere(*label);
2018        dist_text = wxString();
2019        // FIXME: Need to update dist_text (From ... etc)
2020        // But we don't currently know where "here" is at this point in the
2021        // code!
2022    } else {
2023        dist_text = wxString();
2024        m_Gfx->SetThere();
2025    }
2026    if (!data) {
2027        // Must be the root.
2028        m_FindBox->SetValue(wxString());
2029        if (zoom) {
2030            wxCommandEvent dummy;
2031            OnDefaults(dummy);
2032        }
2033    } else if (data && !data->IsStation()) {
2034        m_FindBox->SetValue(data->GetSurvey() + wxT(".*"));
2035        if (zoom) {
2036            wxCommandEvent dummy;
2037            OnGotoFound(dummy);
2038        }
2039    }
2040    UpdateStatusBar();
2041}
2042
2043void MainFrm::OnPresNew(wxCommandEvent&)
2044{
2045    if (m_PresList->Modified()) {
2046        AvenAllowOnTop ontop(this);
2047        // FIXME: better to ask "Do you want to save your changes?" and offer [Save] [Discard] [Cancel]
2048        if (wxMessageBox(wmsg(/*The current presentation has been modified.  Abandon unsaved changes?*/327),
2049                         wmsg(/*Modified Presentation*/326),
2050                         wxOK|wxCANCEL|wxICON_QUESTION) == wxCANCEL) {
2051            return;
2052        }
2053    }
2054    m_PresList->New(m_File);
2055    if (!ShowingSidePanel()) ToggleSidePanel();
2056    // Select the presentation page in the notebook.
2057    m_Notebook->SetSelection(1);
2058}
2059
2060void MainFrm::OnPresOpen(wxCommandEvent&)
2061{
2062    AvenAllowOnTop ontop(this);
2063    if (m_PresList->Modified()) {
2064        // FIXME: better to ask "Do you want to save your changes?" and offer [Save] [Discard] [Cancel]
2065        if (wxMessageBox(wmsg(/*The current presentation has been modified.  Abandon unsaved changes?*/327),
2066                         wmsg(/*Modified Presentation*/326),
2067                         wxOK|wxCANCEL|wxICON_QUESTION) == wxCANCEL) {
2068            return;
2069        }
2070    }
2071#ifdef __WXMOTIF__
2072    wxFileDialog dlg(this, wmsg(/*Select a presentation to open*/322), wxString(), wxString(),
2073                     wxT("*.fly"), wxFD_OPEN);
2074#else
2075    wxFileDialog dlg(this, wmsg(/*Select a presentation to open*/322), wxString(), wxString(),
2076                     wxString::Format(wxT("%s|*.fly|%s|%s"),
2077                               wmsg(/*Aven presentations*/320).c_str(),
2078                               wmsg(/*All files*/208).c_str(),
2079                               wxFileSelectorDefaultWildcardStr),
2080                     wxFD_OPEN|wxFD_FILE_MUST_EXIST);
2081#endif
2082    if (dlg.ShowModal() == wxID_OK) {
2083        if (!m_PresList->Load(dlg.GetPath())) {
2084            return;
2085        }
2086        // FIXME : keep a history of loaded/saved presentations, like we do for
2087        // loaded surveys...
2088        // Select the presentation page in the notebook.
2089        m_Notebook->SetSelection(1);
2090    }
2091}
2092
2093void MainFrm::OnPresSave(wxCommandEvent&)
2094{
2095    m_PresList->Save(true);
2096}
2097
2098void MainFrm::OnPresSaveAs(wxCommandEvent&)
2099{
2100    m_PresList->Save(false);
2101}
2102
2103void MainFrm::OnPresMark(wxCommandEvent&)
2104{
2105    m_PresList->AddMark();
2106}
2107
2108void MainFrm::OnPresFRewind(wxCommandEvent&)
2109{
2110    m_Gfx->PlayPres(-100);
2111}
2112
2113void MainFrm::OnPresRewind(wxCommandEvent&)
2114{
2115    m_Gfx->PlayPres(-10);
2116}
2117
2118void MainFrm::OnPresReverse(wxCommandEvent&)
2119{
2120    m_Gfx->PlayPres(-1);
2121}
2122
2123void MainFrm::OnPresPlay(wxCommandEvent&)
2124{
2125    m_Gfx->PlayPres(1);
2126}
2127
2128void MainFrm::OnPresFF(wxCommandEvent&)
2129{
2130    m_Gfx->PlayPres(10);
2131}
2132
2133void MainFrm::OnPresFFF(wxCommandEvent&)
2134{
2135    m_Gfx->PlayPres(100);
2136}
2137
2138void MainFrm::OnPresPause(wxCommandEvent&)
2139{
2140    m_Gfx->PlayPres(0);
2141}
2142
2143void MainFrm::OnPresStop(wxCommandEvent&)
2144{
2145    m_Gfx->PlayPres(0, false);
2146}
2147
2148void MainFrm::OnPresExportMovie(wxCommandEvent&)
2149{
2150    AvenAllowOnTop ontop(this);
2151    // FIXME : Taking the leaf of the currently loaded presentation as the
2152    // default might make more sense?
2153    wxString baseleaf;
2154    wxFileName::SplitPath(m_File, NULL, NULL, &baseleaf, NULL, wxPATH_NATIVE);
2155    wxFileDialog dlg(this, wxT("Export Movie"), wxString(),
2156                     baseleaf + wxT(".mpg"),
2157                     wxT("MPEG|*.mpg|AVI|*.avi|QuickTime|*.mov|WMV|*.wmv;*.asf"),
2158                     wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
2159    if (dlg.ShowModal() == wxID_OK) {
2160        if (!m_Gfx->ExportMovie(dlg.GetPath())) {
2161            wxGetApp().ReportError(wxString::Format(wmsg(/*Error writing to file `%s'*/110), dlg.GetPath().c_str()));
2162        }
2163    }
2164}
2165
2166PresentationMark MainFrm::GetPresMark(int which)
2167{
2168    return m_PresList->GetPresMark(which);
2169}
2170
2171//void MainFrm::OnFileOpenTerrainUpdate(wxUpdateUIEvent& event)
2172//{
2173//    event.Enable(!m_File.empty());
2174//}
2175
2176void MainFrm::OnPresNewUpdate(wxUpdateUIEvent& event)
2177{
2178    event.Enable(!m_File.empty());
2179}
2180
2181void MainFrm::OnPresOpenUpdate(wxUpdateUIEvent& event)
2182{
2183    event.Enable(!m_File.empty());
2184}
2185
2186void MainFrm::OnPresSaveUpdate(wxUpdateUIEvent& event)
2187{
2188    event.Enable(!m_PresList->Empty());
2189}
2190
2191void MainFrm::OnPresSaveAsUpdate(wxUpdateUIEvent& event)
2192{
2193    event.Enable(!m_PresList->Empty());
2194}
2195
2196void MainFrm::OnPresMarkUpdate(wxUpdateUIEvent& event)
2197{
2198    event.Enable(!m_File.empty());
2199}
2200
2201void MainFrm::OnPresFRewindUpdate(wxUpdateUIEvent& event)
2202{
2203    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2204    event.Check(m_Gfx && m_Gfx->GetPresentationSpeed() < -10);
2205}
2206
2207void MainFrm::OnPresRewindUpdate(wxUpdateUIEvent& event)
2208{
2209    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2210    event.Check(m_Gfx && m_Gfx->GetPresentationSpeed() == -10);
2211}
2212
2213void MainFrm::OnPresReverseUpdate(wxUpdateUIEvent& event)
2214{
2215    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2216    event.Check(m_Gfx && m_Gfx->GetPresentationSpeed() == -1);
2217}
2218
2219void MainFrm::OnPresPlayUpdate(wxUpdateUIEvent& event)
2220{
2221    event.Enable(!m_PresList->Empty());
2222    event.Check(m_Gfx && m_Gfx->GetPresentationMode() &&
2223                m_Gfx->GetPresentationSpeed() == 1);
2224}
2225
2226void MainFrm::OnPresFFUpdate(wxUpdateUIEvent& event)
2227{
2228    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2229    event.Check(m_Gfx && m_Gfx->GetPresentationSpeed() == 10);
2230}
2231
2232void MainFrm::OnPresFFFUpdate(wxUpdateUIEvent& event)
2233{
2234    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2235    event.Check(m_Gfx && m_Gfx->GetPresentationSpeed() > 10);
2236}
2237
2238void MainFrm::OnPresPauseUpdate(wxUpdateUIEvent& event)
2239{
2240    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2241    event.Check(m_Gfx && m_Gfx->GetPresentationSpeed() == 0);
2242}
2243
2244void MainFrm::OnPresStopUpdate(wxUpdateUIEvent& event)
2245{
2246    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2247}
2248
2249void MainFrm::OnPresExportMovieUpdate(wxUpdateUIEvent& event)
2250{
2251    event.Enable(!m_PresList->Empty());
2252}
2253
2254void MainFrm::OnFind(wxCommandEvent&)
2255{
2256    wxBusyCursor hourglass;
2257    // Find stations specified by a string or regular expression pattern.
2258
2259    wxString pattern = m_FindBox->GetValue();
2260    if (pattern.empty()) {
2261        // Hide any search result highlights.
2262        list<LabelInfo*>::iterator pos = m_Labels.begin();
2263        while (pos != m_Labels.end()) {
2264            LabelInfo* label = *pos++;
2265            label->clear_flags(LFLAG_HIGHLIGHTED);
2266        }
2267        m_NumHighlighted = 0;
2268    } else {
2269        int re_flags = wxRE_NOSUB;
2270
2271        if (true /* case insensitive */) {
2272            re_flags |= wxRE_ICASE;
2273        }
2274
2275        bool substring = true;
2276        if (false /*m_RegexpCheckBox->GetValue()*/) {
2277            re_flags |= wxRE_EXTENDED;
2278        } else if (true /* simple glob-style */) {
2279            wxString pat;
2280            for (size_t i = 0; i < pattern.size(); i++) {
2281               wxChar ch = pattern[i];
2282               // ^ only special at start; $ at end.  But this is simpler...
2283               switch (ch) {
2284                case '^': case '$': case '.': case '[': case '\\':
2285                  pat += wxT('\\');
2286                  pat += ch;
2287                  break;
2288                case '*':
2289                  pat += wxT(".*");
2290                  substring = false;
2291                  break;
2292                case '?':
2293                  pat += wxT('.');
2294                  substring = false;
2295                  break;
2296                default:
2297                  pat += ch;
2298               }
2299            }
2300            pattern = pat;
2301            re_flags |= wxRE_BASIC;
2302        } else {
2303            wxString pat;
2304            for (size_t i = 0; i < pattern.size(); i++) {
2305               wxChar ch = pattern[i];
2306               // ^ only special at start; $ at end.  But this is simpler...
2307               switch (ch) {
2308                case '^': case '$': case '*': case '.': case '[': case '\\':
2309                  pat += wxT('\\');
2310               }
2311               pat += ch;
2312            }
2313            pattern = pat;
2314            re_flags |= wxRE_BASIC;
2315        }
2316
2317        if (!substring) {
2318            // FIXME "0u" required to avoid compilation error with g++-3.0
2319            if (pattern.empty() || pattern[0u] != '^') pattern = wxT('^') + pattern;
2320            // FIXME: this fails to cope with "\$" at the end of pattern...
2321            if (pattern[pattern.size() - 1] != '$') pattern += wxT('$');
2322        }
2323
2324        wxRegEx regex;
2325        if (!regex.Compile(pattern, re_flags)) {
2326            wxBell();
2327            return;
2328        }
2329
2330        int found = 0;
2331
2332        list<LabelInfo*>::iterator pos = m_Labels.begin();
2333        while (pos != m_Labels.end()) {
2334            LabelInfo* label = *pos++;
2335
2336            if (regex.Matches(label->GetText())) {
2337                label->set_flags(LFLAG_HIGHLIGHTED);
2338                ++found;
2339            } else {
2340                label->clear_flags(LFLAG_HIGHLIGHTED);
2341            }
2342        }
2343
2344        m_NumHighlighted = found;
2345
2346        // Re-sort so highlighted points get names in preference
2347        if (found) m_Labels.sort(LabelPlotCmp(separator));
2348    }
2349
2350    m_Gfx->UpdateBlobs();
2351    m_Gfx->ForceRefresh();
2352
2353    if (!m_NumHighlighted) {
2354        GetToolBar()->SetToolShortHelp(button_HIDE, wmsg(/*No matches were found.*/328));
2355    } else {
2356        GetToolBar()->SetToolShortHelp(button_HIDE, wxString::Format(wxT("Unhilight %d found stations"), m_NumHighlighted));
2357    }
2358}
2359
2360void MainFrm::OnGotoFound(wxCommandEvent&)
2361{
2362    if (!m_NumHighlighted) {
2363        wxGetApp().ReportError(wmsg(/*No matches were found.*/328));
2364        return;
2365    }
2366
2367    Double xmin = DBL_MAX;
2368    Double xmax = -DBL_MAX;
2369    Double ymin = DBL_MAX;
2370    Double ymax = -DBL_MAX;
2371    Double zmin = DBL_MAX;
2372    Double zmax = -DBL_MAX;
2373
2374    list<LabelInfo*>::iterator pos = m_Labels.begin();
2375    while (pos != m_Labels.end()) {
2376        LabelInfo* label = *pos++;
2377
2378        if (label->get_flags() & LFLAG_HIGHLIGHTED) {
2379            if (label->GetX() < xmin) xmin = label->GetX();
2380            if (label->GetX() > xmax) xmax = label->GetX();
2381            if (label->GetY() < ymin) ymin = label->GetY();
2382            if (label->GetY() > ymax) ymax = label->GetY();
2383            if (label->GetZ() < zmin) zmin = label->GetZ();
2384            if (label->GetZ() > zmax) zmax = label->GetZ();
2385        }
2386    }
2387
2388    m_Gfx->SetViewTo(xmin, xmax, ymin, ymax, zmin, zmax);
2389    m_Gfx->SetFocus();
2390}
2391
2392void MainFrm::OnHide(wxCommandEvent&)
2393{
2394    m_FindBox->SetValue(wxString());
2395}
2396
2397void MainFrm::OnHideUpdate(wxUpdateUIEvent& ui)
2398{
2399    ui.Enable(m_NumHighlighted != 0);
2400}
2401
2402void MainFrm::OnViewSidePanel(wxCommandEvent&)
2403{
2404    ToggleSidePanel();
2405}
2406
2407void MainFrm::ToggleSidePanel()
2408{
2409    // Toggle display of the side panel.
2410
2411    assert(m_Gfx);
2412
2413    if (m_Splitter->IsSplit()) {
2414        m_SashPosition = m_Splitter->GetSashPosition(); // save width of panel
2415        m_Splitter->Unsplit(m_Notebook);
2416    } else {
2417        m_Notebook->Show(true);
2418        m_Gfx->Show(true);
2419        m_Splitter->SplitVertically(m_Notebook, m_Gfx, m_SashPosition);
2420    }
2421}
2422
2423void MainFrm::OnViewSidePanelUpdate(wxUpdateUIEvent& ui)
2424{
2425    ui.Enable(!m_File.empty());
2426    ui.Check(ShowingSidePanel());
2427}
2428
2429bool MainFrm::ShowingSidePanel()
2430{
2431    return m_Splitter->IsSplit();
2432}
2433
2434void MainFrm::ViewFullScreen() {
2435    ShowFullScreen(!IsFullScreen());
2436    static bool sidepanel;
2437    if (IsFullScreen()) sidepanel = ShowingSidePanel();
2438    if (sidepanel) ToggleSidePanel();
2439#ifdef __WXGTK__
2440    // wxGTK doesn't currently remove the toolbar, statusbar, or menubar.
2441    // Can't work out how to lose the menubar right now, but this works for
2442    // the other two.  FIXME: tidy this code up and submit a patch for
2443    // wxWidgets.
2444    wxToolBar *tb = GetToolBar();
2445    if (tb) tb->Show(!IsFullScreen());
2446    wxStatusBar *sb = GetStatusBar();
2447    if (sb) sb->Show(!IsFullScreen());
2448#if 0
2449    // FIXME: This sort of works, but we lose the top-level shortcuts
2450    // (e.g. alt-F for File)
2451    wxMenuBar *mb = GetMenuBar();
2452    if (mb) {
2453        static list<wxMenu *> menus;
2454        static list<wxString> labels;
2455        if (IsFullScreen()) {
2456            // remove menus
2457            for (int c = mb->GetMenuCount(); c >= 0; --c) {
2458                labels.push_back(mb->GetLabelTop(c));
2459                menus.push_back(mb->Remove(c));
2460            }
2461        } else {
2462            while (!menus.empty()) {
2463                mb->Append(menus.back(), labels.back());
2464                menus.pop_back();
2465                labels.pop_back();
2466            }
2467        }
2468    }
2469#endif
2470#endif
2471}
Note: See TracBrowser for help on using the repository browser.