source: git/src/mainfrm.cc @ 68be120

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

Fix cavern log window to behave if passed a .svx file on the command line.

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

  • Property mode set to 100644
File size: 78.3 KB
Line 
1//
2//  mainfrm.cc
3//
4//  Main frame handling for Aven.
5//
6//  Copyright (C) 2000-2002,2005,2006 Mark R. Shinwell
7//  Copyright (C) 2001-2003,2004,2005,2006 Olly Betts
8//  Copyright (C) 2005 Martin Green
9//
10//  This program is free software; you can redistribute it and/or modify
11//  it under the terms of the GNU General Public License as published by
12//  the Free Software Foundation; either version 2 of the License, or
13//  (at your option) any later version.
14//
15//  This program is distributed in the hope that it will be useful,
16//  but WITHOUT ANY WARRANTY; without even the implied warranty of
17//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18//  GNU General Public License for more details.
19//
20//  You should have received a copy of the GNU General Public License
21//  along with this program; if not, write to the Free Software
22//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
23//
24
25#ifdef HAVE_CONFIG_H
26#include <config.h>
27#endif
28
29#include "cavernlog.h"
30#include "mainfrm.h"
31#include "aven.h"
32#include "aboutdlg.h"
33
34#include "message.h"
35#include "img.h"
36#include "namecmp.h"
37#include "printwx.h"
38#include "filename.h"
39#include "useful.h"
40
41#include <wx/confbase.h>
42#include <wx/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    Show(true);
953    m_Splitter->Show(false);
954    CavernLogWindow * log = new CavernLogWindow(this);
955    log->SetSize(GetClientSize());
956
957    int result = log->process(file);
958    if (result == 0) {
959        log->Show(false);
960        m_Splitter->Show();
961    }
962    return result >= 0;
963}
964
965bool MainFrm::LoadData(const wxString& file_, wxString prefix)
966{
967    wxString file(file_);
968    // Load survey data from file, centre the dataset around the origin,
969    // and prepare the data for drawing.
970
971#if 0
972    wxStopWatch timer;
973    timer.Start();
974#endif
975    wxString filename_used;
976
977    // Check if this is an unprocessed survey data file.
978    if (file.length() > 4 && file[file.length() - 4] == '.') {
979        wxString ext = file.substr(file.length() - 3, 3);
980        if (strcasecmp(ext.char_str(), "svx") == 0 ||
981            strcasecmp(ext.char_str(), "dat") == 0 ||
982            strcasecmp(ext.char_str(), "mak") == 0) {
983            if (!ProcessSVXFile(file)) return false;
984            filename_used = file;
985            char * base_fnm = base_from_fnm(file.char_str());
986            char * fnm_3d = add_ext(base_fnm, "3d");
987            file = wxString(fnm_3d, wxConvUTF8);
988            osfree(fnm_3d);
989            osfree(base_fnm);
990        }
991    }
992
993    // Load the survey data.
994    img* survey = img_open_survey(file.char_str(), prefix.char_str());
995    if (!survey) {
996        wxString m = wxString::Format(wmsg(img_error()), file.c_str());
997        wxGetApp().ReportError(m);
998        return false;
999    }
1000
1001    if (!filename_used.empty()) {
1002        m_File = filename_used;
1003    } else {
1004        m_File = wxString(survey->filename_opened, wxConvUTF8);
1005    }
1006    m_IsExtendedElevation = survey->is_extended_elevation;
1007
1008    m_Tree->DeleteAllItems();
1009
1010    // Create a list of all the leg vertices, counting them and finding the
1011    // extent of the survey at the same time.
1012
1013    m_NumFixedPts = 0;
1014    m_NumExportedPts = 0;
1015    m_NumEntrances = 0;
1016    m_HasUndergroundLegs = false;
1017    m_HasSurfaceLegs = false;
1018    m_HasErrorInformation = false;
1019
1020    // FIXME: discard existing presentation? ask user about saving if we do!
1021
1022    // Delete any existing list entries.
1023    m_Labels.clear();
1024
1025    Double xmin = DBL_MAX;
1026    Double xmax = -DBL_MAX;
1027    Double ymin = DBL_MAX;
1028    Double ymax = -DBL_MAX;
1029    Double zmin = DBL_MAX;
1030    Double zmax = -DBL_MAX;
1031
1032    m_DepthMin = DBL_MAX;
1033    Double depthmax = -DBL_MAX;
1034
1035    m_DateMin = (time_t)-1;
1036    if (m_DateMin < 0) {
1037        // Hmm, signed time_t!
1038        // FIXME: find a cleaner way to do this...
1039        time_t x = time_t(1) << (sizeof(time_t) * 8 - 2);
1040        m_DateMin = x;
1041        while ((x>>=1) != 0) m_DateMin |= x;
1042    }
1043    time_t datemax = 0;
1044    complete_dateinfo = true;
1045
1046    traverses.clear();
1047    surface_traverses.clear();
1048    tubes.clear();
1049
1050    // Ultimately we probably want different types (subclasses perhaps?) for
1051    // underground and surface data, so we don't need to store LRUD for surface
1052    // stuff.
1053    traverse * current_traverse = NULL;
1054    traverse * current_surface_traverse = NULL;
1055    vector<XSect> * current_tube = NULL;
1056
1057    int result;
1058    img_point prev_pt = {0,0,0};
1059    bool current_polyline_is_surface = false;
1060    bool pending_move = false;
1061    // When a traverse is split between surface and underground, we split it
1062    // into contiguous traverses of each, but we need to track these so we can
1063    // assign the error statistics to all of them.  So we keep counts of how
1064    // many surface_traverses and traverses we've generated for the current
1065    // traverse.
1066    size_t n_traverses = 0;
1067    size_t n_surface_traverses = 0;
1068    do {
1069#if 0
1070        if (++items % 200 == 0) {
1071            long pos = ftell(survey->fh);
1072            int progress = int((double(pos) / double(file_size)) * 100.0);
1073            // SetProgress(progress);
1074        }
1075#endif
1076
1077        img_point pt;
1078        result = img_read_item(survey, &pt);
1079        switch (result) {
1080            case img_MOVE:
1081                n_traverses = n_surface_traverses = 0;
1082                pending_move = true;
1083                prev_pt = pt;
1084                break;
1085
1086            case img_LINE: {
1087                // Update survey extents.
1088                if (pt.x < xmin) xmin = pt.x;
1089                if (pt.x > xmax) xmax = pt.x;
1090                if (pt.y < ymin) ymin = pt.y;
1091                if (pt.y > ymax) ymax = pt.y;
1092                if (pt.z < zmin) zmin = pt.z;
1093                if (pt.z > zmax) zmax = pt.z;
1094
1095                time_t date;
1096                date = survey->date1 + (survey->date2 - survey->date1) / 2;
1097                if (date) {
1098                    if (date < m_DateMin) m_DateMin = date;
1099                    if (date > datemax) datemax = date;
1100                } else {
1101                    complete_dateinfo = false;
1102                }
1103
1104                bool is_surface = (survey->flags & img_FLAG_SURFACE);
1105                if (!is_surface) {
1106                    if (pt.z < m_DepthMin) m_DepthMin = pt.z;
1107                    if (pt.z > depthmax) depthmax = pt.z;
1108                }
1109                if (pending_move || current_polyline_is_surface != is_surface) {
1110                    if (!current_polyline_is_surface && current_traverse) {
1111                        //FixLRUD(*current_traverse);
1112                    }
1113                    current_polyline_is_surface = is_surface;
1114                    // Start new traverse (surface or underground).
1115                    if (is_surface) {
1116                        m_HasSurfaceLegs = true;
1117                        surface_traverses.push_back(traverse());
1118                        current_surface_traverse = &surface_traverses.back();
1119                        ++n_surface_traverses;
1120                    } else {
1121                        m_HasUndergroundLegs = true;
1122                        traverses.push_back(traverse());
1123                        current_traverse = &traverses.back();
1124                        ++n_traverses;
1125                        // The previous point was at a surface->ug transition.
1126                        if (prev_pt.z < m_DepthMin) m_DepthMin = prev_pt.z;
1127                        if (prev_pt.z > depthmax) depthmax = prev_pt.z;
1128                    }
1129                    if (pending_move) {
1130                        // Update survey extents.  We only need to do this if
1131                        // there's a pending move, since for a surface <->
1132                        // underground transition, we'll already have handled
1133                        // this point.
1134                        if (prev_pt.x < xmin) xmin = prev_pt.x;
1135                        if (prev_pt.x > xmax) xmax = prev_pt.x;
1136                        if (prev_pt.y < ymin) ymin = prev_pt.y;
1137                        if (prev_pt.y > ymax) ymax = prev_pt.y;
1138                        if (prev_pt.z < zmin) zmin = prev_pt.z;
1139                        if (prev_pt.z > zmax) zmax = prev_pt.z;
1140                    }
1141
1142                    if (is_surface) {
1143                        current_surface_traverse->push_back(PointInfo(prev_pt));
1144                    } else {
1145                        current_traverse->push_back(PointInfo(prev_pt));
1146                    }
1147                }
1148
1149                if (is_surface) {
1150                    current_surface_traverse->push_back(PointInfo(pt, date));
1151                } else {
1152                    current_traverse->push_back(PointInfo(pt, date));
1153                }
1154
1155                prev_pt = pt;
1156                pending_move = false;
1157                break;
1158            }
1159
1160            case img_LABEL: {
1161                int flags = survey->flags;
1162                if (flags & img_SFLAG_ENTRANCE) {
1163                    flags ^= (img_SFLAG_ENTRANCE | LFLAG_ENTRANCE);
1164                }
1165                LabelInfo* label = new LabelInfo(pt, wxString(survey->label, wxConvUTF8), flags);
1166                if (label->IsEntrance()) {
1167                    m_NumEntrances++;
1168                }
1169                if (label->IsFixedPt()) {
1170                    m_NumFixedPts++;
1171                }
1172                if (label->IsExportedPt()) {
1173                    m_NumExportedPts++;
1174                }
1175                m_Labels.push_back(label);
1176                break;
1177            }
1178
1179            case img_XSECT: {
1180                if (!current_tube) {
1181                    // Start new current_tube.
1182                    tubes.push_back(vector<XSect>());
1183                    current_tube = &tubes.back();
1184                }
1185
1186                // FIXME: avoid linear search...
1187                list<LabelInfo*>::const_iterator i = m_Labels.begin();
1188                wxString label(survey->label, wxConvUTF8);
1189                while (i != m_Labels.end() && (*i)->GetText() != label) ++i;
1190
1191                if (i == m_Labels.end()) {
1192                    // Unattached cross-section - ignore for now.
1193                    printf("unattached cross-section\n");
1194                    if (current_tube->size() == 1)
1195                        tubes.resize(tubes.size() - 1);
1196                    current_tube = NULL;
1197                    break;
1198                }
1199
1200                time_t date;
1201                date = survey->date1 + (survey->date2 - survey->date1) / 2;
1202                if (date) {
1203                    if (date < m_DateMin) m_DateMin = date;
1204                    if (date > datemax) datemax = date;
1205                }
1206
1207                current_tube->push_back(XSect(**i, date, survey->l, survey->r, survey->u, survey->d));
1208                break;
1209            }
1210
1211            case img_XSECT_END:
1212                // Finish off current_tube.
1213                // If there's only one cross-section in the tube, just
1214                // discard it for now.  FIXME: we should handle this
1215                // when we come to skinning the tubes.
1216                if (current_tube && current_tube->size() == 1)
1217                    tubes.resize(tubes.size() - 1);
1218                current_tube = NULL;
1219                break;
1220
1221            case img_ERROR_INFO: {
1222                if (survey->E == 0.0) {
1223                    // Currently cavern doesn't spot all articulating traverses
1224                    // so we assume that any traverse with no error isn't part
1225                    // of a loop.  FIXME: fix cavern!
1226                    break;
1227                }
1228                m_HasErrorInformation = true;
1229                list<traverse>::reverse_iterator t;
1230                t = surface_traverses.rbegin();
1231                while (n_surface_traverses) {
1232                    assert(t != surface_traverses.rend());
1233                    t->n_legs = survey->n_legs;
1234                    t->length = survey->length;
1235                    t->E = survey->E;
1236                    t->H = survey->H;
1237                    t->V = survey->V;
1238                    --n_surface_traverses;
1239                    ++t;
1240                }
1241                t = traverses.rbegin();
1242                while (n_traverses) {
1243                    assert(t != traverses.rend());
1244                    t->n_legs = survey->n_legs;
1245                    t->length = survey->length;
1246                    t->E = survey->E;
1247                    t->H = survey->H;
1248                    t->V = survey->V;
1249                    --n_traverses;
1250                    ++t;
1251                }
1252                break;
1253            }
1254
1255            case img_BAD: {
1256                m_Labels.clear();
1257
1258                // FIXME: Do we need to reset all these? - Olly
1259                m_NumFixedPts = 0;
1260                m_NumExportedPts = 0;
1261                m_NumEntrances = 0;
1262                m_HasUndergroundLegs = false;
1263                m_HasSurfaceLegs = false;
1264
1265                img_close(survey);
1266
1267                wxString m = wxString::Format(wmsg(img_error()), file.c_str());
1268                wxGetApp().ReportError(m);
1269
1270                return false;
1271            }
1272
1273            default:
1274                break;
1275        }
1276    } while (result != img_STOP);
1277
1278    if (!current_polyline_is_surface && current_traverse) {
1279        //FixLRUD(*current_traverse);
1280    }
1281
1282    // Finish off current_tube.
1283    // If there's only one cross-section in the tube, just
1284    // discard it for now.  FIXME: we should handle this
1285    // when we come to skinning the tubes.
1286    if (current_tube && current_tube->size() == 1)
1287        tubes.resize(tubes.size() - 1);
1288
1289    separator = survey->separator;
1290    m_Title = wxString(survey->title, wxConvUTF8);
1291    m_DateStamp = wxString(survey->datestamp, wxConvUTF8);
1292    img_close(survey);
1293
1294    // Check we've actually loaded some legs or stations!
1295    if (!m_HasUndergroundLegs && !m_HasSurfaceLegs && m_Labels.empty()) {
1296        wxString m = wxString::Format(wmsg(/*No survey data in 3d file `%s'*/202), file.c_str());
1297        wxGetApp().ReportError(m);
1298        return false;
1299    }
1300
1301    if (traverses.empty() && surface_traverses.empty()) {
1302        // No legs, so get survey extents from stations
1303        list<LabelInfo*>::const_iterator i;
1304        for (i = m_Labels.begin(); i != m_Labels.end(); ++i) {
1305            if ((*i)->GetX() < xmin) xmin = (*i)->GetX();
1306            if ((*i)->GetX() > xmax) xmax = (*i)->GetX();
1307            if ((*i)->GetY() < ymin) ymin = (*i)->GetY();
1308            if ((*i)->GetY() > ymax) ymax = (*i)->GetY();
1309            if ((*i)->GetZ() < zmin) zmin = (*i)->GetZ();
1310            if ((*i)->GetZ() > zmax) zmax = (*i)->GetZ();
1311        }
1312    }
1313
1314    m_Ext.assign(xmax - xmin, ymax - ymin, zmax - zmin);
1315
1316    if (datemax < m_DateMin) m_DateMin = 0;
1317    m_DateExt = datemax - m_DateMin;
1318
1319    // Sort the labels.
1320    m_Labels.sort(LabelCmp(separator));
1321
1322    // Fill the tree of stations and prefixes.
1323    FillTree();
1324
1325    // Sort labels so that entrances are displayed in preference,
1326    // then fixed points, then exported points, then other points.
1327    //
1328    // Also sort by leaf name so that we'll tend to choose labels
1329    // from different surveys, rather than labels from surveys which
1330    // are earlier in the list.
1331    m_Labels.sort(LabelPlotCmp(separator));
1332
1333    // Centre the dataset around the origin.
1334    CentreDataset(Vector3(xmin, ymin, zmin));
1335
1336    if (depthmax < m_DepthMin) {
1337        m_DepthMin = 0;
1338        m_DepthExt = 0;
1339    } else {
1340        m_DepthExt = depthmax - m_DepthMin;
1341        m_DepthMin -= m_Offsets.GetZ();
1342    }
1343
1344#if 0
1345    printf("time to load = %.3f\n", (double)timer.Time());
1346#endif
1347
1348    // Update window title.
1349    SetTitle(m_Title + " - "APP_NAME);
1350
1351    return true;
1352}
1353
1354#if 0
1355// Run along a newly read in traverse and make up plausible LRUD where
1356// it is missing.
1357void
1358MainFrm::FixLRUD(traverse & centreline)
1359{
1360    assert(centreline.size() > 1);
1361
1362    Double last_size = 0;
1363    vector<PointInfo>::iterator i = centreline.begin();
1364    while (i != centreline.end()) {
1365        // Get the coordinates of this vertex.
1366        Point & pt_v = *i++;
1367        Double size;
1368
1369        if (i != centreline.end()) {
1370            Double h = sqrd(i->GetX() - pt_v.GetX()) +
1371                       sqrd(i->GetY() - pt_v.GetY());
1372            Double v = sqrd(i->GetZ() - pt_v.GetZ());
1373            if (h + v > 30.0 * 30.0) {
1374                Double scale = 30.0 / sqrt(h + v);
1375                h *= scale;
1376                v *= scale;
1377            }
1378            size = sqrt(h + v / 9);
1379            size /= 4;
1380            if (i == centreline.begin() + 1) {
1381                // First segment.
1382                last_size = size;
1383            } else {
1384                // Intermediate segment.
1385                swap(size, last_size);
1386                size += last_size;
1387                size /= 2;
1388            }
1389        } else {
1390            // Last segment.
1391            size = last_size;
1392        }
1393
1394        Double & l = pt_v.l;
1395        Double & r = pt_v.r;
1396        Double & u = pt_v.u;
1397        Double & d = pt_v.d;
1398
1399        if (l == 0 && r == 0 && u == 0 && d == 0) {
1400            l = r = u = d = -size;
1401        } else {
1402            if (l < 0 && r < 0) {
1403                l = r = -size;
1404            } else if (l < 0) {
1405                l = -(2 * size - r);
1406                if (l >= 0) l = -0.01;
1407            } else if (r < 0) {
1408                r = -(2 * size - l);
1409                if (r >= 0) r = -0.01;
1410            }
1411            if (u < 0 && d < 0) {
1412                u = d = -size;
1413            } else if (u < 0) {
1414                u = -(2 * size - d);
1415                if (u >= 0) u = -0.01;
1416            } else if (d < 0) {
1417                d = -(2 * size - u);
1418                if (d >= 0) d = -0.01;
1419            }
1420        }
1421    }
1422}
1423#endif
1424
1425void MainFrm::FillTree()
1426{
1427    // Create the root of the tree.
1428    wxTreeItemId treeroot = m_Tree->AddRoot(wxFileNameFromPath(m_File));
1429
1430    // Fill the tree of stations and prefixes.
1431    stack<wxTreeItemId> previous_ids;
1432    wxString current_prefix;
1433    wxTreeItemId current_id = treeroot;
1434
1435    list<LabelInfo*>::iterator pos = m_Labels.begin();
1436    while (pos != m_Labels.end()) {
1437        LabelInfo* label = *pos++;
1438
1439        // Determine the current prefix.
1440        wxString prefix = label->GetText().BeforeLast(separator);
1441
1442        // Determine if we're still on the same prefix.
1443        if (prefix == current_prefix) {
1444            // no need to fiddle with branches...
1445        }
1446        // If not, then see if we've descended to a new prefix.
1447        else if (prefix.length() > current_prefix.length() &&
1448                 prefix.StartsWith(current_prefix) &&
1449                 (prefix[current_prefix.length()] == separator ||
1450                  current_prefix.empty())) {
1451            // We have, so start as many new branches as required.
1452            int current_prefix_length = current_prefix.length();
1453            current_prefix = prefix;
1454            size_t next_dot = current_prefix_length;
1455            if (!next_dot) --next_dot;
1456            do {
1457                size_t prev_dot = next_dot + 1;
1458
1459                // Extract the next bit of prefix.
1460                next_dot = prefix.find(separator, prev_dot + 1);
1461
1462                wxString bit = prefix.substr(prev_dot, next_dot - prev_dot);
1463                assert(!bit.empty());
1464
1465                // Add the current tree ID to the stack.
1466                previous_ids.push(current_id);
1467
1468                // Append the new item to the tree and set this as the current branch.
1469                current_id = m_Tree->AppendItem(current_id, bit);
1470                m_Tree->SetItemData(current_id, new TreeData(prefix.substr(0, next_dot)));
1471            } while (next_dot != wxString::npos);
1472        }
1473        // Otherwise, we must have moved up, and possibly then down again.
1474        else {
1475            size_t count = 0;
1476            bool ascent_only = (prefix.length() < current_prefix.length() &&
1477                                current_prefix.StartsWith(prefix) &&
1478                                (current_prefix[prefix.length()] == separator ||
1479                                 prefix.empty()));
1480            if (!ascent_only) {
1481                // Find out how much of the current prefix and the new prefix
1482                // are the same.
1483                // Note that we require a match of a whole number of parts
1484                // between dots!
1485                for (size_t i = 0; prefix[i] == current_prefix[i]; ++i) {
1486                    if (prefix[i] == separator) count = i + 1;
1487                }
1488            } else {
1489                count = prefix.length() + 1;
1490            }
1491
1492            // Extract the part of the current prefix after the bit (if any)
1493            // which has matched.
1494            // This gives the prefixes to ascend over.
1495            wxString prefixes_ascended = current_prefix.substr(count);
1496
1497            // Count the number of prefixes to ascend over.
1498            int num_prefixes = prefixes_ascended.Freq(separator);
1499
1500            // Reverse up over these prefixes.
1501            for (int i = 1; i <= num_prefixes; i++) {
1502                previous_ids.pop();
1503            }
1504            current_id = previous_ids.top();
1505            previous_ids.pop();
1506
1507            if (!ascent_only) {
1508                // Add branches for this new part.
1509                size_t next_dot = count - 1;
1510                do {
1511                    size_t prev_dot = next_dot + 1;
1512
1513                    // Extract the next bit of prefix.
1514                    next_dot = prefix.find(separator, prev_dot + 1);
1515
1516                    wxString bit = prefix.substr(prev_dot, next_dot - prev_dot);
1517                    assert(!bit.empty());
1518
1519                    // Add the current tree ID to the stack.
1520                    previous_ids.push(current_id);
1521
1522                    // Append the new item to the tree and set this as the current branch.
1523                    current_id = m_Tree->AppendItem(current_id, bit);
1524                    m_Tree->SetItemData(current_id, new TreeData(prefix.substr(0, next_dot)));
1525                } while (next_dot != wxString::npos);
1526            }
1527
1528            current_prefix = prefix;
1529        }
1530
1531        // Now add the leaf.
1532        wxString bit = label->GetText().AfterLast(separator);
1533        assert(!bit.empty());
1534        wxTreeItemId id = m_Tree->AppendItem(current_id, bit);
1535        m_Tree->SetItemData(id, new TreeData(label));
1536        label->tree_id = id;
1537        // Set the colour for an item in the survey tree.
1538        if (label->IsEntrance()) {
1539            // Entrances are green (like entrance blobs).
1540            m_Tree->SetItemTextColour(id, wxColour(0, 255, 0));
1541        } else if (label->IsSurface()) {
1542            // Surface stations are dark green.
1543            m_Tree->SetItemTextColour(id, wxColour(49, 158, 79));
1544        }
1545    }
1546
1547    m_Tree->Expand(treeroot);
1548    m_Tree->SetEnabled();
1549}
1550
1551void MainFrm::SelectTreeItem(LabelInfo* label)
1552{
1553    m_Tree->SelectItem(label->tree_id);
1554}
1555
1556void MainFrm::CentreDataset(const Vector3 & vmin)
1557{
1558    // Centre the dataset around the origin.
1559
1560    m_Offsets = vmin + (m_Ext * 0.5);
1561
1562    list<traverse>::iterator t = traverses.begin();
1563    while (t != traverses.end()) {
1564        assert(t->size() > 1);
1565        vector<PointInfo>::iterator pos = t->begin();
1566        while (pos != t->end()) {
1567            Point & point = *pos++;
1568            point -= m_Offsets;
1569        }
1570        ++t;
1571    }
1572
1573    t = surface_traverses.begin();
1574    while (t != surface_traverses.end()) {
1575        assert(t->size() > 1);
1576        vector<PointInfo>::iterator pos = t->begin();
1577        while (pos != t->end()) {
1578            Point & point = *pos++;
1579            point -= m_Offsets;
1580        }
1581        ++t;
1582    }
1583
1584    list<vector<XSect> >::iterator i = tubes.begin();
1585    while (i != tubes.end()) {
1586        assert(i->size() > 1);
1587        vector<XSect>::iterator pos = i->begin();
1588        while (pos != i->end()) {
1589            Point & point = *pos++;
1590            point -= m_Offsets;
1591        }
1592        ++i;
1593    }
1594
1595    list<LabelInfo*>::iterator lpos = m_Labels.begin();
1596    while (lpos != m_Labels.end()) {
1597        Point & point = **lpos++;
1598        point -= m_Offsets;
1599    }
1600}
1601
1602void MainFrm::OnMRUFile(wxCommandEvent& event)
1603{
1604    wxString f(m_history.GetHistoryFile(event.GetId() - wxID_FILE1));
1605    if (!f.empty()) OpenFile(f);
1606}
1607
1608void MainFrm::OpenFile(const wxString& file, wxString survey)
1609{
1610    wxBusyCursor hourglass;
1611    wxString old_file = m_File;
1612    if (LoadData(file, survey)) {
1613        if (wxIsAbsolutePath(m_File)) {
1614            m_history.AddFileToHistory(m_File);
1615        } else {
1616            wxString abs = wxGetCwd();
1617            abs += wxCONFIG_PATH_SEPARATOR;
1618            abs += m_File;
1619            m_history.AddFileToHistory(abs);
1620        }
1621        wxConfigBase *b = wxConfigBase::Get();
1622        m_history.Save(*b);
1623        b->Flush();
1624
1625        int x;
1626        int y;
1627        GetClientSize(&x, &y);
1628        if (x < 600)
1629            x /= 3;
1630        else if (x < 1000)
1631            x = 200;
1632        else
1633            x /= 5;
1634
1635        m_Splitter->SplitVertically(m_Notebook, m_Gfx, x);
1636        m_SashPosition = x; // Save width of panel.
1637
1638        m_Gfx->Initialise(old_file == m_File);
1639        m_Notebook->Show(true);
1640
1641        m_Gfx->Show(true);
1642        m_Gfx->SetFocus();
1643    }
1644}
1645
1646//
1647//  UI event handlers
1648//
1649
1650// For Unix we want "*.svx;*.SVX" while for Windows we only want "*.svx".
1651#ifdef _WIN32
1652# define CASE(X)
1653#else
1654# define CASE(X) ";"X
1655#endif
1656
1657void MainFrm::OnOpen(wxCommandEvent&)
1658{
1659    AvenAllowOnTop ontop(this);
1660#ifdef __WXMOTIF__
1661    wxString filetypes = wxT("*.3d");
1662#else
1663    wxString filetypes;
1664    filetypes.Printf(wxT("%s|*.3d;*.svx;*.plt;*.plf;*.dat;*.mak;*.xyz"
1665                     CASE("*.3D;*.SVX;*.PLT;*.PLF;*.DAT;*.MAK;*.XYZ")
1666                     "|%s|*.3d"CASE("*.3D")
1667                     "|%s|*.svx"CASE("*.SVX")
1668                     "|%s|*.plt;*.plf"CASE("*.PLT;*.PLF")
1669                     "|%s|*.dat;*.mak"CASE("*.DAT;*.MAK")
1670                     "|%s|*.xyz"CASE("*.XYZ")
1671                     "|%s|%s"),
1672                     wxT("All survey files"),
1673                     wmsg(/*Survex 3d files*/207).c_str(),
1674                     wxT("Survex svx files"),
1675                     wmsg(/*Compass PLT files*/324).c_str(),
1676                     wxT("Compass DAT and MAK files"),
1677                     wmsg(/*CMAP XYZ files*/325).c_str(),
1678                     wmsg(/*All files*/208).c_str(),
1679                     wxFileSelectorDefaultWildcardStr);
1680#endif
1681    // FIXME: drop "3d" from this message?
1682    wxFileDialog dlg(this, wmsg(/*Select a 3d file to view*/206),
1683                     wxString(), wxString(),
1684                     filetypes, wxFD_OPEN|wxFD_FILE_MUST_EXIST);
1685    if (dlg.ShowModal() == wxID_OK) {
1686        OpenFile(dlg.GetPath());
1687    }
1688}
1689
1690void MainFrm::OnScreenshot(wxCommandEvent&)
1691{
1692    AvenAllowOnTop ontop(this);
1693    char *baseleaf = baseleaf_from_fnm(m_File.char_str());
1694    wxFileDialog dlg(this, wmsg(/*Save Screenshot*/321), wxString(),
1695                     wxString(baseleaf, wxConvUTF8) + wxT(".png"),
1696                     wxT("*.png"), wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
1697    free(baseleaf);
1698    if (dlg.ShowModal() == wxID_OK) {
1699        static bool png_handled = false;
1700        if (!png_handled) {
1701#if 0 // FIXME : enable this to allow other export formats...
1702            ::wxInitAllImageHandlers();
1703#else
1704            wxImage::AddHandler(new wxPNGHandler);
1705#endif
1706            png_handled = true;
1707        }
1708        if (!m_Gfx->SaveScreenshot(dlg.GetPath(), wxBITMAP_TYPE_PNG)) {
1709            wxGetApp().ReportError(wxString::Format(wmsg(/*Error writing to file `%s'*/110), dlg.GetPath().c_str()));
1710        }
1711    }
1712}
1713
1714void MainFrm::OnScreenshotUpdate(wxUpdateUIEvent& event)
1715{
1716    event.Enable(!m_File.empty());
1717}
1718
1719void MainFrm::OnFilePreferences(wxCommandEvent&)
1720{
1721#ifdef PREFDLG
1722    m_PrefsDlg = new PrefsDlg(m_Gfx, this);
1723    m_PrefsDlg->Show(true);
1724#endif
1725}
1726
1727void MainFrm::OnPrint(wxCommandEvent&)
1728{
1729    m_Gfx->OnPrint(m_File, m_Title, m_DateStamp);
1730}
1731
1732void MainFrm::OnPageSetup(wxCommandEvent&)
1733{
1734    wxPageSetupDialog dlg(this, wxGetApp().GetPageSetupDialogData());
1735    if (dlg.ShowModal() == wxID_OK) {
1736        wxGetApp().SetPageSetupDialogData(dlg.GetPageSetupData());
1737    }
1738}
1739
1740void MainFrm::OnExport(wxCommandEvent&)
1741{
1742    m_Gfx->OnExport(m_File, m_Title);
1743}
1744
1745void MainFrm::OnQuit(wxCommandEvent&)
1746{
1747    if (m_PresList->Modified()) {
1748        AvenAllowOnTop ontop(this);
1749        // FIXME: better to ask "Do you want to save your changes?" and offer [Save] [Discard] [Cancel]
1750        if (wxMessageBox(wmsg(/*The current presentation has been modified.  Abandon unsaved changes?*/327),
1751                         wmsg(/*Modified Presentation*/326),
1752                         wxOK|wxCANCEL|wxICON_QUESTION) == wxCANCEL) {
1753            return;
1754        }
1755    }
1756    wxConfigBase *b = wxConfigBase::Get();
1757    if (IsFullScreen()) {
1758        b->Write(wxT("width"), -2);
1759        b->DeleteEntry(wxT("height"));
1760    } else if (IsMaximized()) {
1761        b->Write(wxT("width"), -1);
1762        b->DeleteEntry(wxT("height"));
1763    } else {
1764        int width, height;
1765        GetSize(&width, &height);
1766        b->Write(wxT("width"), width);
1767        b->Write(wxT("height"), height);
1768    }
1769    b->Flush();
1770    exit(0);
1771}
1772
1773void MainFrm::OnClose(wxCloseEvent&)
1774{
1775    wxCommandEvent dummy;
1776    OnQuit(dummy);
1777}
1778
1779void MainFrm::OnAbout(wxCommandEvent&)
1780{
1781    AvenAllowOnTop ontop(this);
1782    AboutDlg dlg(this, icon_path);
1783    dlg.Centre();
1784    dlg.ShowModal();
1785}
1786
1787void MainFrm::UpdateStatusBar()
1788{
1789    if (!here_text.empty()) {
1790        GetStatusBar()->SetStatusText(here_text);
1791        GetStatusBar()->SetStatusText(dist_text, 1);
1792    } else if (!coords_text.empty()) {
1793        GetStatusBar()->SetStatusText(coords_text);
1794        GetStatusBar()->SetStatusText(distfree_text, 1);
1795    } else {
1796        GetStatusBar()->SetStatusText(wxString());
1797        GetStatusBar()->SetStatusText(wxString(), 1);
1798    }
1799}
1800
1801void MainFrm::ClearTreeSelection()
1802{
1803    m_Tree->UnselectAll();
1804    if (!dist_text.empty()) {
1805        dist_text = wxString();
1806        UpdateStatusBar();
1807    }
1808    m_Gfx->SetThere();
1809}
1810
1811void MainFrm::ClearCoords()
1812{
1813    if (!coords_text.empty()) {
1814        coords_text = wxString();
1815        UpdateStatusBar();
1816    }
1817}
1818
1819void MainFrm::SetCoords(const Vector3 &v)
1820{
1821    wxString & s = coords_text;
1822    if (m_Gfx->GetMetric()) {
1823        s.Printf(wmsg(/*%.2f E, %.2f N*/338), v.GetX(), v.GetY());
1824        s += wxString::Format(wxT(", %s %.2fm"), wmsg(/*Altitude*/335).c_str(), v.GetZ());
1825    } else {
1826        s.Printf(wmsg(/*%.2f E, %.2f N*/338),
1827                 v.GetX() / METRES_PER_FOOT, v.GetY() / METRES_PER_FOOT);
1828        s += wxString::Format(wxT(", %s %.2fft"), wmsg(/*Altitude*/335).c_str(),
1829                              v.GetZ() / METRES_PER_FOOT);
1830    }
1831    distfree_text = wxString();
1832    UpdateStatusBar();
1833}
1834
1835const LabelInfo * MainFrm::GetTreeSelection() const {
1836    wxTreeItemData* sel_wx;
1837    if (!m_Tree->GetSelectionData(&sel_wx)) return NULL;
1838
1839    const TreeData* data = static_cast<const TreeData*>(sel_wx);
1840    if (!data->IsStation()) return NULL;
1841
1842    return data->GetLabel();
1843}
1844
1845void MainFrm::SetCoords(Double x, Double y)
1846{
1847    wxString & s = coords_text;
1848    if (m_Gfx->GetMetric()) {
1849        s.Printf(wmsg(/*%.2f E, %.2f N*/338), x, y);
1850    } else {
1851        s.Printf(wmsg(/*%.2f E, %.2f N*/338),
1852                 x / METRES_PER_FOOT, y / METRES_PER_FOOT);
1853    }
1854
1855    wxString & t = distfree_text;
1856    t = wxString();
1857    const LabelInfo* label;
1858    if (m_Gfx->ShowingMeasuringLine() && (label = GetTreeSelection())) {
1859        Vector3 delta(x - m_Offsets.GetX() - label->GetX(),
1860                      y - m_Offsets.GetY() - label->GetY(), 0);
1861        Double dh = sqrt(delta.GetX()*delta.GetX() + delta.GetY()*delta.GetY());
1862        Double brg = deg(atan2(delta.GetX(), delta.GetY()));
1863        if (brg < 0) brg += 360;
1864
1865        wxString from_str;
1866        from_str.Printf(wmsg(/*From %s*/339), label->GetText().c_str());
1867
1868        wxString brg_unit;
1869        if (m_Gfx->GetDegrees()) {
1870            brg_unit = wmsg(/*&deg;*/344);
1871        } else {
1872            brg *= 400.0 / 360.0;
1873            brg_unit = wmsg(/*grad*/345);
1874        }
1875
1876        if (m_Gfx->GetMetric()) {
1877            t.Printf(wmsg(/*%s: H %.2f%s, Brg %03d%s*/374),
1878                     from_str.c_str(), dh, wxT("m"), int(brg), brg_unit.c_str());
1879        } else {
1880            t.Printf(wmsg(/*%s: H %.2f%s, Brg %03d%s*/374),
1881                     from_str.c_str(), dh / METRES_PER_FOOT, wxT("ft"), int(brg),
1882                     brg_unit.c_str());
1883        }
1884    }
1885
1886    UpdateStatusBar();
1887}
1888
1889void MainFrm::SetAltitude(Double z)
1890{
1891    wxString & s = coords_text;
1892    if (m_Gfx->GetMetric()) {
1893        s.Printf(wxT("%s %.2fm"), wmsg(/*Altitude*/335).c_str(), double(z));
1894    } else {
1895        s.Printf(wxT("%s %.2fft"), wmsg(/*Altitude*/335).c_str(), double(z / METRES_PER_FOOT));
1896    }
1897
1898    wxString & t = distfree_text;
1899    t = wxString();
1900    const LabelInfo* label;
1901    if (m_Gfx->ShowingMeasuringLine() && (label = GetTreeSelection())) {
1902        Double dz = z - m_Offsets.GetZ() - label->GetZ();
1903
1904        wxString from_str;
1905        from_str.Printf(wmsg(/*From %s*/339), label->GetText().c_str());
1906
1907        if (m_Gfx->GetMetric()) {
1908            t.Printf(wmsg(/*%s: V %.2f%s*/375),
1909                     from_str.c_str(), dz, wxT("m"));
1910        } else {
1911            t.Printf(wmsg(/*%s: V %.2f%s*/375),
1912                     from_str.c_str(), dz / METRES_PER_FOOT, wxT("ft"));
1913        }
1914    }
1915
1916    UpdateStatusBar();
1917}
1918
1919void MainFrm::ShowInfo(const LabelInfo *here)
1920{
1921    assert(m_Gfx);
1922
1923    if (!here) {
1924        m_Gfx->SetHere();
1925        m_Tree->SetHere(wxTreeItemId());
1926        // Don't clear "There" mark here.
1927        if (here_text.empty() && dist_text.empty()) return;
1928        here_text = wxString();
1929        dist_text = wxString();
1930        UpdateStatusBar();
1931        return;
1932    }
1933
1934    Vector3 v = *here + m_Offsets;
1935    wxString & s = here_text;
1936    if (m_Gfx->GetMetric()) {
1937        s.Printf(wmsg(/*%.2f E, %.2f N*/338), v.GetX(), v.GetY());
1938        s += wxString::Format(wxT(", %s %.2fm"), wmsg(/*Altitude*/335).c_str(), v.GetZ());
1939    } else {
1940        s.Printf(wmsg(/*%.2f E, %.2f N*/338),
1941                 v.GetX() / METRES_PER_FOOT, v.GetY() / METRES_PER_FOOT);
1942        s += wxString::Format(wxT(", %s %.2fft"), wmsg(/*Altitude*/335).c_str(),
1943                              v.GetZ() / METRES_PER_FOOT);
1944    }
1945    s += wxT(": ");
1946    s += here->GetText();
1947    m_Gfx->SetHere(*here);
1948    m_Tree->SetHere(here->tree_id);
1949
1950    const LabelInfo* label;
1951    if (m_Gfx->ShowingMeasuringLine() && (label = GetTreeSelection())) {
1952        Vector3 delta = *here - *label;
1953
1954        Double d_horiz = sqrt(delta.GetX()*delta.GetX() + delta.GetY()*delta.GetY());
1955        Double dr = delta.magnitude();
1956
1957        Double brg = deg(atan2(delta.GetX(), delta.GetY()));
1958        if (brg < 0) brg += 360;
1959
1960        wxString from_str;
1961        from_str.Printf(wmsg(/*From %s*/339), label->GetText().c_str());
1962
1963        wxString hv_str;
1964        if (m_Gfx->GetMetric()) {
1965            hv_str.Printf(wmsg(/*H %.2f%s, V %.2f%s*/340),
1966                          d_horiz, wxT("m"), delta.GetZ(), wxT("m"));
1967        } else {
1968            hv_str.Printf(wmsg(/*H %.2f%s, V %.2f%s*/340),
1969                          d_horiz / METRES_PER_FOOT, wxT("ft"),
1970                          delta.GetZ() / METRES_PER_FOOT, wxT("ft"));
1971        }
1972        wxString brg_unit;
1973        if (m_Gfx->GetDegrees()) {
1974            brg_unit = wmsg(/*&deg;*/344);
1975        } else {
1976            brg *= 400.0 / 360.0;
1977            brg_unit = wmsg(/*grad*/345);
1978        }
1979        wxString & d = dist_text;
1980        if (m_Gfx->GetMetric()) {
1981            d.Printf(wmsg(/*%s: %s, Dist %.2f%s, Brg %03d%s*/341),
1982                     from_str.c_str(), hv_str.c_str(),
1983                     dr, wxT("m"), int(brg), brg_unit.c_str());
1984        } else {
1985            d.Printf(wmsg(/*%s: %s, Dist %.2f%s, Brg %03d%s*/341),
1986                     from_str.c_str(), hv_str.c_str(),
1987                     dr / METRES_PER_FOOT, wxT("ft"), int(brg),
1988                     brg_unit.c_str());
1989        }
1990        m_Gfx->SetThere(*label);
1991    } else {
1992        dist_text = wxString();
1993        m_Gfx->SetThere();
1994    }
1995    UpdateStatusBar();
1996}
1997
1998void MainFrm::DisplayTreeInfo(const wxTreeItemData* item)
1999{
2000    const TreeData* data = static_cast<const TreeData*>(item);
2001    if (data && data->IsStation()) {
2002        const LabelInfo * label = data->GetLabel();
2003        ShowInfo(label);
2004        m_Gfx->SetHere(*label);
2005    } else {
2006        ShowInfo(NULL);
2007    }
2008}
2009
2010void MainFrm::TreeItemSelected(const wxTreeItemData* item, bool zoom)
2011{
2012    const TreeData* data = static_cast<const TreeData*>(item);
2013    if (data && data->IsStation()) {
2014        const LabelInfo* label = data->GetLabel();
2015        if (zoom) m_Gfx->CentreOn(*label);
2016        m_Gfx->SetThere(*label);
2017        dist_text = wxString();
2018        // FIXME: Need to update dist_text (From ... etc)
2019        // But we don't currently know where "here" is at this point in the
2020        // code!
2021    } else {
2022        dist_text = wxString();
2023        m_Gfx->SetThere();
2024    }
2025    if (!data) {
2026        // Must be the root.
2027        m_FindBox->SetValue(wxString());
2028        if (zoom) {
2029            wxCommandEvent dummy;
2030            OnDefaults(dummy);
2031        }
2032    } else if (data && !data->IsStation()) {
2033        m_FindBox->SetValue(data->GetSurvey() + wxT(".*"));
2034        if (zoom) {
2035            wxCommandEvent dummy;
2036            OnGotoFound(dummy);
2037        }
2038    }
2039    UpdateStatusBar();
2040}
2041
2042void MainFrm::OnPresNew(wxCommandEvent&)
2043{
2044    if (m_PresList->Modified()) {
2045        AvenAllowOnTop ontop(this);
2046        // FIXME: better to ask "Do you want to save your changes?" and offer [Save] [Discard] [Cancel]
2047        if (wxMessageBox(wmsg(/*The current presentation has been modified.  Abandon unsaved changes?*/327),
2048                         wmsg(/*Modified Presentation*/326),
2049                         wxOK|wxCANCEL|wxICON_QUESTION) == wxCANCEL) {
2050            return;
2051        }
2052    }
2053    m_PresList->New(m_File);
2054    if (!ShowingSidePanel()) ToggleSidePanel();
2055    // Select the presentation page in the notebook.
2056    m_Notebook->SetSelection(1);
2057}
2058
2059void MainFrm::OnPresOpen(wxCommandEvent&)
2060{
2061    AvenAllowOnTop ontop(this);
2062    if (m_PresList->Modified()) {
2063        // FIXME: better to ask "Do you want to save your changes?" and offer [Save] [Discard] [Cancel]
2064        if (wxMessageBox(wmsg(/*The current presentation has been modified.  Abandon unsaved changes?*/327),
2065                         wmsg(/*Modified Presentation*/326),
2066                         wxOK|wxCANCEL|wxICON_QUESTION) == wxCANCEL) {
2067            return;
2068        }
2069    }
2070#ifdef __WXMOTIF__
2071    wxFileDialog dlg(this, wmsg(/*Select a presentation to open*/322), wxString(), wxString(),
2072                     wxT("*.fly"), wxFD_OPEN);
2073#else
2074    wxFileDialog dlg(this, wmsg(/*Select a presentation to open*/322), wxString(), wxString(),
2075                     wxString::Format(wxT("%s|*.fly|%s|%s"),
2076                               wmsg(/*Aven presentations*/320).c_str(),
2077                               wmsg(/*All files*/208).c_str(),
2078                               wxFileSelectorDefaultWildcardStr),
2079                     wxFD_OPEN|wxFD_FILE_MUST_EXIST);
2080#endif
2081    if (dlg.ShowModal() == wxID_OK) {
2082        if (!m_PresList->Load(dlg.GetPath())) {
2083            return;
2084        }
2085        // FIXME : keep a history of loaded/saved presentations, like we do for
2086        // loaded surveys...
2087        // Select the presentation page in the notebook.
2088        m_Notebook->SetSelection(1);
2089    }
2090}
2091
2092void MainFrm::OnPresSave(wxCommandEvent&)
2093{
2094    m_PresList->Save(true);
2095}
2096
2097void MainFrm::OnPresSaveAs(wxCommandEvent&)
2098{
2099    m_PresList->Save(false);
2100}
2101
2102void MainFrm::OnPresMark(wxCommandEvent&)
2103{
2104    m_PresList->AddMark();
2105}
2106
2107void MainFrm::OnPresFRewind(wxCommandEvent&)
2108{
2109    m_Gfx->PlayPres(-100);
2110}
2111
2112void MainFrm::OnPresRewind(wxCommandEvent&)
2113{
2114    m_Gfx->PlayPres(-10);
2115}
2116
2117void MainFrm::OnPresReverse(wxCommandEvent&)
2118{
2119    m_Gfx->PlayPres(-1);
2120}
2121
2122void MainFrm::OnPresPlay(wxCommandEvent&)
2123{
2124    m_Gfx->PlayPres(1);
2125}
2126
2127void MainFrm::OnPresFF(wxCommandEvent&)
2128{
2129    m_Gfx->PlayPres(10);
2130}
2131
2132void MainFrm::OnPresFFF(wxCommandEvent&)
2133{
2134    m_Gfx->PlayPres(100);
2135}
2136
2137void MainFrm::OnPresPause(wxCommandEvent&)
2138{
2139    m_Gfx->PlayPres(0);
2140}
2141
2142void MainFrm::OnPresStop(wxCommandEvent&)
2143{
2144    m_Gfx->PlayPres(0, false);
2145}
2146
2147void MainFrm::OnPresExportMovie(wxCommandEvent&)
2148{
2149    AvenAllowOnTop ontop(this);
2150    // FIXME : Taking the leaf of the currently loaded presentation as the
2151    // default might make more sense?
2152    char *baseleaf = baseleaf_from_fnm(m_File.char_str());
2153    wxFileDialog dlg(this, wxT("Export Movie"), wxString(),
2154                     wxString(baseleaf, wxConvUTF8) + wxT(".mpg"),
2155                     wxT("MPEG|*.mpg|AVI|*.avi|QuickTime|*.mov|WMV|*.wmv;*.asf"),
2156                     wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
2157    free(baseleaf);
2158    if (dlg.ShowModal() == wxID_OK) {
2159        if (!m_Gfx->ExportMovie(dlg.GetPath())) {
2160            wxGetApp().ReportError(wxString::Format(wmsg(/*Error writing to file `%s'*/110), dlg.GetPath().c_str()));
2161        }
2162    }
2163}
2164
2165PresentationMark MainFrm::GetPresMark(int which)
2166{
2167    return m_PresList->GetPresMark(which);
2168}
2169
2170//void MainFrm::OnFileOpenTerrainUpdate(wxUpdateUIEvent& event)
2171//{
2172//    event.Enable(!m_File.empty());
2173//}
2174
2175void MainFrm::OnPresNewUpdate(wxUpdateUIEvent& event)
2176{
2177    event.Enable(!m_File.empty());
2178}
2179
2180void MainFrm::OnPresOpenUpdate(wxUpdateUIEvent& event)
2181{
2182    event.Enable(!m_File.empty());
2183}
2184
2185void MainFrm::OnPresSaveUpdate(wxUpdateUIEvent& event)
2186{
2187    event.Enable(!m_PresList->Empty());
2188}
2189
2190void MainFrm::OnPresSaveAsUpdate(wxUpdateUIEvent& event)
2191{
2192    event.Enable(!m_PresList->Empty());
2193}
2194
2195void MainFrm::OnPresMarkUpdate(wxUpdateUIEvent& event)
2196{
2197    event.Enable(!m_File.empty());
2198}
2199
2200void MainFrm::OnPresFRewindUpdate(wxUpdateUIEvent& event)
2201{
2202    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2203    event.Check(m_Gfx && m_Gfx->GetPresentationSpeed() < -10);
2204}
2205
2206void MainFrm::OnPresRewindUpdate(wxUpdateUIEvent& event)
2207{
2208    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2209    event.Check(m_Gfx && m_Gfx->GetPresentationSpeed() == -10);
2210}
2211
2212void MainFrm::OnPresReverseUpdate(wxUpdateUIEvent& event)
2213{
2214    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2215    event.Check(m_Gfx && m_Gfx->GetPresentationSpeed() == -1);
2216}
2217
2218void MainFrm::OnPresPlayUpdate(wxUpdateUIEvent& event)
2219{
2220    event.Enable(!m_PresList->Empty());
2221    event.Check(m_Gfx && m_Gfx->GetPresentationMode() &&
2222                m_Gfx->GetPresentationSpeed() == 1);
2223}
2224
2225void MainFrm::OnPresFFUpdate(wxUpdateUIEvent& event)
2226{
2227    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2228    event.Check(m_Gfx && m_Gfx->GetPresentationSpeed() == 10);
2229}
2230
2231void MainFrm::OnPresFFFUpdate(wxUpdateUIEvent& event)
2232{
2233    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2234    event.Check(m_Gfx && m_Gfx->GetPresentationSpeed() > 10);
2235}
2236
2237void MainFrm::OnPresPauseUpdate(wxUpdateUIEvent& event)
2238{
2239    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2240    event.Check(m_Gfx && m_Gfx->GetPresentationSpeed() == 0);
2241}
2242
2243void MainFrm::OnPresStopUpdate(wxUpdateUIEvent& event)
2244{
2245    event.Enable(m_Gfx && m_Gfx->GetPresentationMode());
2246}
2247
2248void MainFrm::OnPresExportMovieUpdate(wxUpdateUIEvent& event)
2249{
2250    event.Enable(!m_PresList->Empty());
2251}
2252
2253void MainFrm::OnFind(wxCommandEvent&)
2254{
2255    wxBusyCursor hourglass;
2256    // Find stations specified by a string or regular expression pattern.
2257
2258    wxString pattern = m_FindBox->GetValue();
2259    if (pattern.empty()) {
2260        // Hide any search result highlights.
2261        list<LabelInfo*>::iterator pos = m_Labels.begin();
2262        while (pos != m_Labels.end()) {
2263            LabelInfo* label = *pos++;
2264            label->clear_flags(LFLAG_HIGHLIGHTED);
2265        }
2266        m_NumHighlighted = 0;
2267    } else {
2268        int re_flags = wxRE_NOSUB;
2269
2270        if (true /* case insensitive */) {
2271            re_flags |= wxRE_ICASE;
2272        }
2273
2274        bool substring = true;
2275        if (false /*m_RegexpCheckBox->GetValue()*/) {
2276            re_flags |= wxRE_EXTENDED;
2277        } else if (true /* simple glob-style */) {
2278            wxString pat;
2279            for (size_t i = 0; i < pattern.size(); i++) {
2280               wxChar ch = pattern[i];
2281               // ^ only special at start; $ at end.  But this is simpler...
2282               switch (ch) {
2283                case '^': case '$': case '.': case '[': case '\\':
2284                  pat += wxT('\\');
2285                  pat += ch;
2286                  break;
2287                case '*':
2288                  pat += wxT(".*");
2289                  substring = false;
2290                  break;
2291                case '?':
2292                  pat += wxT('.');
2293                  substring = false;
2294                  break;
2295                default:
2296                  pat += ch;
2297               }
2298            }
2299            pattern = pat;
2300            re_flags |= wxRE_BASIC;
2301        } else {
2302            wxString pat;
2303            for (size_t i = 0; i < pattern.size(); i++) {
2304               wxChar ch = pattern[i];
2305               // ^ only special at start; $ at end.  But this is simpler...
2306               switch (ch) {
2307                case '^': case '$': case '*': case '.': case '[': case '\\':
2308                  pat += wxT('\\');
2309               }
2310               pat += ch;
2311            }
2312            pattern = pat;
2313            re_flags |= wxRE_BASIC;
2314        }
2315
2316        if (!substring) {
2317            // FIXME "0u" required to avoid compilation error with g++-3.0
2318            if (pattern.empty() || pattern[0u] != '^') pattern = wxT('^') + pattern;
2319            // FIXME: this fails to cope with "\$" at the end of pattern...
2320            if (pattern[pattern.size() - 1] != '$') pattern += wxT('$');
2321        }
2322
2323        wxRegEx regex;
2324        if (!regex.Compile(pattern, re_flags)) {
2325            wxBell();
2326            return;
2327        }
2328
2329        int found = 0;
2330
2331        list<LabelInfo*>::iterator pos = m_Labels.begin();
2332        while (pos != m_Labels.end()) {
2333            LabelInfo* label = *pos++;
2334
2335            if (regex.Matches(label->GetText())) {
2336                label->set_flags(LFLAG_HIGHLIGHTED);
2337                ++found;
2338            } else {
2339                label->clear_flags(LFLAG_HIGHLIGHTED);
2340            }
2341        }
2342
2343        m_NumHighlighted = found;
2344
2345        // Re-sort so highlighted points get names in preference
2346        if (found) m_Labels.sort(LabelPlotCmp(separator));
2347    }
2348
2349    m_Gfx->UpdateBlobs();
2350    m_Gfx->ForceRefresh();
2351
2352    if (!m_NumHighlighted) {
2353        GetToolBar()->SetToolShortHelp(button_HIDE, wmsg(/*No matches were found.*/328));
2354    } else {
2355        GetToolBar()->SetToolShortHelp(button_HIDE, wxString::Format(wxT("Unhilight %d found stations"), m_NumHighlighted));
2356    }
2357}
2358
2359void MainFrm::OnGotoFound(wxCommandEvent&)
2360{
2361    if (!m_NumHighlighted) {
2362        wxGetApp().ReportError(wmsg(/*No matches were found.*/328));
2363        return;
2364    }
2365
2366    Double xmin = DBL_MAX;
2367    Double xmax = -DBL_MAX;
2368    Double ymin = DBL_MAX;
2369    Double ymax = -DBL_MAX;
2370    Double zmin = DBL_MAX;
2371    Double zmax = -DBL_MAX;
2372
2373    list<LabelInfo*>::iterator pos = m_Labels.begin();
2374    while (pos != m_Labels.end()) {
2375        LabelInfo* label = *pos++;
2376
2377        if (label->get_flags() & LFLAG_HIGHLIGHTED) {
2378            if (label->GetX() < xmin) xmin = label->GetX();
2379            if (label->GetX() > xmax) xmax = label->GetX();
2380            if (label->GetY() < ymin) ymin = label->GetY();
2381            if (label->GetY() > ymax) ymax = label->GetY();
2382            if (label->GetZ() < zmin) zmin = label->GetZ();
2383            if (label->GetZ() > zmax) zmax = label->GetZ();
2384        }
2385    }
2386
2387    m_Gfx->SetViewTo(xmin, xmax, ymin, ymax, zmin, zmax);
2388    m_Gfx->SetFocus();
2389}
2390
2391void MainFrm::OnHide(wxCommandEvent&)
2392{
2393    m_FindBox->SetValue(wxString());
2394}
2395
2396void MainFrm::OnHideUpdate(wxUpdateUIEvent& ui)
2397{
2398    ui.Enable(m_NumHighlighted != 0);
2399}
2400
2401void MainFrm::OnViewSidePanel(wxCommandEvent&)
2402{
2403    ToggleSidePanel();
2404}
2405
2406void MainFrm::ToggleSidePanel()
2407{
2408    // Toggle display of the side panel.
2409
2410    assert(m_Gfx);
2411
2412    if (m_Splitter->IsSplit()) {
2413        m_SashPosition = m_Splitter->GetSashPosition(); // save width of panel
2414        m_Splitter->Unsplit(m_Notebook);
2415    } else {
2416        m_Notebook->Show(true);
2417        m_Gfx->Show(true);
2418        m_Splitter->SplitVertically(m_Notebook, m_Gfx, m_SashPosition);
2419    }
2420}
2421
2422void MainFrm::OnViewSidePanelUpdate(wxUpdateUIEvent& ui)
2423{
2424    ui.Enable(!m_File.empty());
2425    ui.Check(ShowingSidePanel());
2426}
2427
2428bool MainFrm::ShowingSidePanel()
2429{
2430    return m_Splitter->IsSplit();
2431}
2432
2433void MainFrm::ViewFullScreen() {
2434    ShowFullScreen(!IsFullScreen());
2435    static bool sidepanel;
2436    if (IsFullScreen()) sidepanel = ShowingSidePanel();
2437    if (sidepanel) ToggleSidePanel();
2438#ifdef __WXGTK__
2439    // wxGTK doesn't currently remove the toolbar, statusbar, or menubar.
2440    // Can't work out how to lose the menubar right now, but this works for
2441    // the other two.  FIXME: tidy this code up and submit a patch for
2442    // wxWidgets.
2443    wxToolBar *tb = GetToolBar();
2444    if (tb) tb->Show(!IsFullScreen());
2445    wxStatusBar *sb = GetStatusBar();
2446    if (sb) sb->Show(!IsFullScreen());
2447#if 0
2448    // FIXME: This sort of works, but we lose the top-level shortcuts
2449    // (e.g. alt-F for File)
2450    wxMenuBar *mb = GetMenuBar();
2451    if (mb) {
2452        static list<wxMenu *> menus;
2453        static list<wxString> labels;
2454        if (IsFullScreen()) {
2455            // remove menus
2456            for (int c = mb->GetMenuCount(); c >= 0; --c) {
2457                labels.push_back(mb->GetLabelTop(c));
2458                menus.push_back(mb->Remove(c));
2459            }
2460        } else {
2461            while (!menus.empty()) {
2462                mb->Append(menus.back(), labels.back());
2463                menus.pop_back();
2464                labels.pop_back();
2465            }
2466        }
2467    }
2468#endif
2469#endif
2470}
Note: See TracBrowser for help on using the repository browser.