source: git/src/mainfrm.cc @ 419952a

RELEASE/1.1RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernlogstereowalls-datawalls-data-hanging-as-warning
Last change on this file since 419952a was 5627cbb, checked in by Olly Betts <olly@…>, 14 years ago
  • Fix to build with a "unicode" build of wx.
  • Add "Copy" button to the About dialog to copy the system info to the clipboard.
  • List OpenGL extensions last, since there are usually lots of them with a modern gfx card.
  • When processing survey data, auto-scroll the log window until we've reported a warning or error.
  • Put the survey data log window in a splitter in the standard frame rather than having a separate frame for it.

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

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