source: git/src/mainfrm.cc @ 261ab22

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data v1.2.17
Last change on this file since 261ab22 was 261ab22, checked in by Olly Betts <olly@…>, 9 years ago

src/mainfrm.cc: Work around GetIcon?() not working under OS X.

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