source: git/src/mainfrm.cc @ 42c7efe

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data
Last change on this file since 42c7efe was 42c7efe, checked in by Olly Betts <olly@…>, 13 years ago

lib/codes.po,src/aven.cc,src/mainfrm.cc,src/mainfrm.h: Use more stock
IDs.

git-svn-id: file:///home/survex-svn/survex/trunk@3610 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

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