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

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

lib/survex.pot,src/mainfrm.cc: Allow "m" and "ft" suffixes to be
translated.

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