source: git/src/mainfrm.cc @ 72f1bb2

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

src/mainfrm.cc: Highlight stations matching any current search when a
file is loaded. (ticket#9)

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

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