source: git/src/mainfrm.cc @ e1d6f8b

RELEASE/1.0
Last change on this file since e1d6f8b was e1d6f8b, checked in by Olly Betts <olly@…>, 13 years ago

Backport changes from 1.2.0:
src/printwx.cc: Use stock wx button IDs wxID_PRINT and
wxID_PREVIEW where appropriate.
src/aven.cc,src/mainfrm.cc,src/mainfrm.h: Use more stock IDs.

git-svn-id: file:///home/survex-svn/survex/branches/1.0@3688 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

  • Property mode set to 100644
File size: 47.0 KB
Line 
1//
2//  mainfrm.cc
3//
4//  Main frame handling for Aven.
5//
6//  Copyright (C) 2000-2002 Mark R. Shinwell
7//  Copyright (C) 2001-2003,2004,2005,2010 Olly Betts
8//  Copyright (C) 2004 Philip Underwood
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 "mainfrm.h"
30#include "aven.h"
31#include "aboutdlg.h"
32
33#include "message.h"
34#include "img.h"
35#include "namecmp.h"
36#include "printwx.h"
37#include "filename.h"
38
39#include <wx/confbase.h>
40#include <wx/regex.h>
41
42#include <float.h>
43#include <functional>
44#include <stack>
45
46using namespace std;
47
48const int NUM_DEPTH_COLOURS = 13; // up to 13
49
50#include "avenpal.h"
51
52class AvenSplitterWindow : public wxSplitterWindow {
53    MainFrm *parent;
54
55    public:
56        AvenSplitterWindow(MainFrm *parent_)
57            : wxSplitterWindow(parent_, -1, wxDefaultPosition, wxDefaultSize,
58                               wxSP_3D | wxSP_LIVE_UPDATE),
59              parent(parent_)
60        {
61        }
62
63        void OnSplitterDClick(wxSplitterEvent &e) {
64#if wxCHECK_VERSION(2,3,0)
65            e.Veto();
66#endif
67#if defined(__UNIX__) && !wxCHECK_VERSION(2,3,5)
68            parent->m_SashPosition = GetSashPosition(); // save width of panel
69            // Calling Unsplit from OnSplitterDClick() doesn't work in debian
70            // wxGtk 2.3.3.2 (which calls itself 2.3.4) - it does work from CVS
71            // prior to the actual 2.3.4 though - FIXME: monitor this
72            // situation...
73            SetSashPosition(0);
74#else
75            parent->ToggleSidePanel();
76#endif
77        }
78
79    private:
80        DECLARE_EVENT_TABLE()
81};
82
83BEGIN_EVENT_TABLE(AvenSplitterWindow, wxSplitterWindow)
84    // The wx docs say "EVT_SPLITTER_DOUBLECLICKED" but the wx headers say
85    // "EVT_SPLITTER_DCLICK" (wx docs corrected to agree with headers in 2.3)
86#ifdef EVT_SPLITTER_DOUBLECLICKED
87    EVT_SPLITTER_DOUBLECLICKED(-1, AvenSplitterWindow::OnSplitterDClick)
88#else
89    EVT_SPLITTER_DCLICK(-1, AvenSplitterWindow::OnSplitterDClick)
90#endif
91END_EVENT_TABLE()
92
93BEGIN_EVENT_TABLE(MainFrm, wxFrame)
94    EVT_BUTTON(wxID_FIND, MainFrm::OnFind)
95    EVT_BUTTON(button_HIDE, MainFrm::OnHide)
96
97    EVT_MENU(wxID_OPEN, MainFrm::OnOpen)
98    EVT_MENU(wxID_PRINT, MainFrm::OnPrint)
99    EVT_MENU(menu_FILE_PAGE_SETUP, MainFrm::OnPageSetup)
100    EVT_MENU(menu_FILE_EXPORT, MainFrm::OnExport)
101    EVT_MENU(wxID_EXIT, MainFrm::OnQuit)
102    EVT_MENU_RANGE(wxID_FILE1, wxID_FILE9, MainFrm::OnMRUFile)
103
104    EVT_CLOSE(MainFrm::OnClose)
105    EVT_SET_FOCUS(MainFrm::OnSetFocus)
106
107    EVT_MENU(menu_ROTATION_START, MainFrm::OnStartRotation)
108    EVT_MENU(menu_ROTATION_TOGGLE, MainFrm::OnToggleRotation)
109    EVT_MENU(menu_ROTATION_STOP, MainFrm::OnStopRotation)
110    EVT_MENU(menu_ROTATION_SPEED_UP, MainFrm::OnSpeedUp)
111    EVT_MENU(menu_ROTATION_SLOW_DOWN, MainFrm::OnSlowDown)
112    EVT_MENU(menu_ROTATION_REVERSE, MainFrm::OnReverseDirectionOfRotation)
113    EVT_MENU(menu_ROTATION_STEP_CCW, MainFrm::OnStepOnceAnticlockwise)
114    EVT_MENU(menu_ROTATION_STEP_CW, MainFrm::OnStepOnceClockwise)
115    EVT_MENU(menu_ORIENT_MOVE_NORTH, MainFrm::OnMoveNorth)
116    EVT_MENU(menu_ORIENT_MOVE_EAST, MainFrm::OnMoveEast)
117    EVT_MENU(menu_ORIENT_MOVE_SOUTH, MainFrm::OnMoveSouth)
118    EVT_MENU(menu_ORIENT_MOVE_WEST, MainFrm::OnMoveWest)
119    EVT_MENU(menu_ORIENT_SHIFT_LEFT, MainFrm::OnShiftDisplayLeft)
120    EVT_MENU(menu_ORIENT_SHIFT_RIGHT, MainFrm::OnShiftDisplayRight)
121    EVT_MENU(menu_ORIENT_SHIFT_UP, MainFrm::OnShiftDisplayUp)
122    EVT_MENU(menu_ORIENT_SHIFT_DOWN, MainFrm::OnShiftDisplayDown)
123    EVT_MENU(menu_ORIENT_PLAN, MainFrm::OnPlan)
124    EVT_MENU(menu_ORIENT_ELEVATION, MainFrm::OnElevation)
125    EVT_MENU(menu_ORIENT_HIGHER_VP, MainFrm::OnHigherViewpoint)
126    EVT_MENU(menu_ORIENT_LOWER_VP, MainFrm::OnLowerViewpoint)
127    EVT_MENU(wxID_ZOOM_IN, MainFrm::OnZoomIn)
128    EVT_MENU(wxID_ZOOM_OUT, MainFrm::OnZoomOut)
129    EVT_MENU(menu_ORIENT_DEFAULTS, MainFrm::OnDefaults)
130    EVT_MENU(menu_VIEW_SHOW_LEGS, MainFrm::OnShowSurveyLegs)
131    EVT_MENU(menu_VIEW_SHOW_CROSSES, MainFrm::OnShowCrosses)
132    EVT_MENU(menu_VIEW_SHOW_ENTRANCES, MainFrm::OnShowEntrances)
133    EVT_MENU(menu_VIEW_SHOW_FIXED_PTS, MainFrm::OnShowFixedPts)
134    EVT_MENU(menu_VIEW_SHOW_EXPORTED_PTS, MainFrm::OnShowExportedPts)
135    EVT_MENU(menu_VIEW_SHOW_NAMES, MainFrm::OnShowStationNames)
136    EVT_MENU(menu_VIEW_SHOW_OVERLAPPING_NAMES, MainFrm::OnDisplayOverlappingNames)
137    EVT_MENU(menu_VIEW_SHOW_SURFACE, MainFrm::OnShowSurface)
138    EVT_MENU(menu_VIEW_SURFACE_DEPTH, MainFrm::OnShowSurfaceDepth)
139    EVT_MENU(menu_VIEW_SURFACE_DASHED, MainFrm::OnShowSurfaceDashed)
140    EVT_MENU(menu_VIEW_COMPASS, MainFrm::OnViewCompass)
141    EVT_MENU(menu_VIEW_CLINO, MainFrm::OnViewClino)
142    EVT_MENU(menu_VIEW_GRID, MainFrm::OnViewGrid)
143    EVT_MENU(menu_VIEW_DEPTH_BAR, MainFrm::OnToggleDepthbar)
144    EVT_MENU(menu_VIEW_SCALE_BAR, MainFrm::OnToggleScalebar)
145    EVT_MENU(menu_VIEW_SIDE_PANEL, MainFrm::OnViewSidePanel)
146    EVT_MENU(menu_VIEW_METRIC, MainFrm::OnToggleMetric)
147    EVT_MENU(menu_VIEW_DEGREES, MainFrm::OnToggleDegrees)
148    EVT_MENU(menu_CTL_REVERSE, MainFrm::OnReverseControls)
149    EVT_MENU(menu_CTL_CANCEL_DIST_LINE, MainFrm::OnCancelDistLine)
150    EVT_MENU(wxID_ABOUT, MainFrm::OnAbout)
151
152    EVT_UPDATE_UI(wxID_PRINT, MainFrm::OnPrintUpdate)
153    EVT_UPDATE_UI(menu_FILE_EXPORT, MainFrm::OnExportUpdate)
154    EVT_UPDATE_UI(menu_ROTATION_START, MainFrm::OnStartRotationUpdate)
155    EVT_UPDATE_UI(menu_ROTATION_TOGGLE, MainFrm::OnToggleRotationUpdate)
156    EVT_UPDATE_UI(menu_ROTATION_STOP, MainFrm::OnStopRotationUpdate)
157    EVT_UPDATE_UI(menu_ROTATION_SPEED_UP, MainFrm::OnSpeedUpUpdate)
158    EVT_UPDATE_UI(menu_ROTATION_SLOW_DOWN, MainFrm::OnSlowDownUpdate)
159    EVT_UPDATE_UI(menu_ROTATION_REVERSE, MainFrm::OnReverseDirectionOfRotationUpdate)
160    EVT_UPDATE_UI(menu_ROTATION_STEP_CCW, MainFrm::OnStepOnceAnticlockwiseUpdate)
161    EVT_UPDATE_UI(menu_ROTATION_STEP_CW, MainFrm::OnStepOnceClockwiseUpdate)
162    EVT_UPDATE_UI(menu_ORIENT_MOVE_NORTH, MainFrm::OnMoveNorthUpdate)
163    EVT_UPDATE_UI(menu_ORIENT_MOVE_EAST, MainFrm::OnMoveEastUpdate)
164    EVT_UPDATE_UI(menu_ORIENT_MOVE_SOUTH, MainFrm::OnMoveSouthUpdate)
165    EVT_UPDATE_UI(menu_ORIENT_MOVE_WEST, MainFrm::OnMoveWestUpdate)
166    EVT_UPDATE_UI(menu_ORIENT_SHIFT_LEFT, MainFrm::OnShiftDisplayLeftUpdate)
167    EVT_UPDATE_UI(menu_ORIENT_SHIFT_RIGHT, MainFrm::OnShiftDisplayRightUpdate)
168    EVT_UPDATE_UI(menu_ORIENT_SHIFT_UP, MainFrm::OnShiftDisplayUpUpdate)
169    EVT_UPDATE_UI(menu_ORIENT_SHIFT_DOWN, MainFrm::OnShiftDisplayDownUpdate)
170    EVT_UPDATE_UI(menu_ORIENT_PLAN, MainFrm::OnPlanUpdate)
171    EVT_UPDATE_UI(menu_ORIENT_ELEVATION, MainFrm::OnElevationUpdate)
172    EVT_UPDATE_UI(menu_ORIENT_HIGHER_VP, MainFrm::OnHigherViewpointUpdate)
173    EVT_UPDATE_UI(menu_ORIENT_LOWER_VP, MainFrm::OnLowerViewpointUpdate)
174    EVT_UPDATE_UI(wxID_ZOOM_IN, MainFrm::OnZoomInUpdate)
175    EVT_UPDATE_UI(wxID_ZOOM_OUT, MainFrm::OnZoomOutUpdate)
176    EVT_UPDATE_UI(menu_ORIENT_DEFAULTS, MainFrm::OnDefaultsUpdate)
177    EVT_UPDATE_UI(menu_VIEW_SHOW_LEGS, MainFrm::OnShowSurveyLegsUpdate)
178    EVT_UPDATE_UI(menu_VIEW_SHOW_CROSSES, MainFrm::OnShowCrossesUpdate)
179    EVT_UPDATE_UI(menu_VIEW_SHOW_ENTRANCES, MainFrm::OnShowEntrancesUpdate)
180    EVT_UPDATE_UI(menu_VIEW_SHOW_FIXED_PTS, MainFrm::OnShowFixedPtsUpdate)
181    EVT_UPDATE_UI(menu_VIEW_SHOW_EXPORTED_PTS, MainFrm::OnShowExportedPtsUpdate)
182    EVT_UPDATE_UI(menu_VIEW_SHOW_NAMES, MainFrm::OnShowStationNamesUpdate)
183    EVT_UPDATE_UI(menu_VIEW_SHOW_SURFACE, MainFrm::OnShowSurfaceUpdate)
184    EVT_UPDATE_UI(menu_VIEW_SURFACE_DEPTH, MainFrm::OnShowSurfaceDepthUpdate)
185    EVT_UPDATE_UI(menu_VIEW_SURFACE_DASHED, MainFrm::OnShowSurfaceDashedUpdate)
186    EVT_UPDATE_UI(menu_VIEW_SHOW_OVERLAPPING_NAMES, MainFrm::OnDisplayOverlappingNamesUpdate)
187    EVT_UPDATE_UI(menu_VIEW_COMPASS, MainFrm::OnViewCompassUpdate)
188    EVT_UPDATE_UI(menu_VIEW_CLINO, MainFrm::OnViewClinoUpdate)
189    EVT_UPDATE_UI(menu_VIEW_DEPTH_BAR, MainFrm::OnToggleDepthbarUpdate)
190    EVT_UPDATE_UI(menu_VIEW_SCALE_BAR, MainFrm::OnToggleScalebarUpdate)
191    EVT_UPDATE_UI(menu_VIEW_GRID, MainFrm::OnViewGridUpdate)
192    EVT_UPDATE_UI(menu_VIEW_INDICATORS, MainFrm::OnIndicatorsUpdate)
193    EVT_UPDATE_UI(menu_VIEW_SIDE_PANEL, MainFrm::OnViewSidePanelUpdate)
194    EVT_UPDATE_UI(menu_CTL_REVERSE, MainFrm::OnReverseControlsUpdate)
195    EVT_UPDATE_UI(menu_CTL_CANCEL_DIST_LINE, MainFrm::OnCancelDistLineUpdate)
196    EVT_UPDATE_UI(menu_VIEW_METRIC, MainFrm::OnToggleMetricUpdate)
197    EVT_UPDATE_UI(menu_VIEW_DEGREES, MainFrm::OnToggleDegreesUpdate)
198END_EVENT_TABLE()
199
200class LabelCmp : public greater<const LabelInfo*> {
201    int separator;
202public:
203    LabelCmp(int separator_) : separator(separator_) {}
204    bool operator()(const LabelInfo* pt1, const LabelInfo* pt2) {
205        return name_cmp(pt1->GetText(), pt2->GetText(), separator) < 0;
206    }
207};
208
209class LabelPlotCmp : public greater<const LabelInfo*> {
210    int separator;
211public:
212    LabelPlotCmp(int separator_) : separator(separator_) {}
213    bool operator()(const LabelInfo* pt1, const LabelInfo* pt2) {
214        int n = pt1->flags - pt2->flags;
215        if (n) return n > 0;
216        wxString l1 = pt1->text.AfterLast(separator);
217        wxString l2 = pt2->text.AfterLast(separator);
218        n = name_cmp(l1, l2, separator);
219        if (n) return n < 0;
220        // Prefer non-2-nodes...
221        // FIXME; implement
222        // if leaf names are the same, prefer shorter labels as we can
223        // display more of them
224        n = pt1->text.length() - pt2->text.length();
225        if (n) return n < 0;
226        // make sure that we don't ever compare different labels as equal
227        return name_cmp(pt1->text, pt2->text, separator) < 0;
228    }
229};
230
231#if wxUSE_DRAG_AND_DROP
232class DnDFile : public wxFileDropTarget {
233    public:
234        DnDFile(MainFrm *parent) : m_Parent(parent) { }
235        virtual bool OnDropFiles(wxCoord, wxCoord,
236                        const wxArrayString &filenames);
237
238    private:
239        MainFrm * m_Parent;
240};
241
242bool
243DnDFile::OnDropFiles(wxCoord, wxCoord, const wxArrayString &filenames)
244{
245    // Load a survey file by drag-and-drop.
246    assert(filenames.GetCount() > 0);
247
248    if (filenames.GetCount() != 1) {
249        wxGetApp().ReportError(msg(/*You may only view one 3d file at a time.*/336));
250        return FALSE;
251    }
252
253    m_Parent->OpenFile(filenames[0]);
254    return TRUE;
255}
256#endif
257
258MainFrm::MainFrm(const wxString& title, const wxPoint& pos, const wxSize& size) :
259    wxFrame(NULL, 101, title, pos, size, wxDEFAULT_FRAME_STYLE | wxNO_FULL_REPAINT_ON_RESIZE),
260    m_Gfx(NULL), m_NumEntrances(0), m_NumFixedPts(0), m_NumExportedPts(0)
261{
262    icon_path = msg_cfgpth();
263    icon_path += wxCONFIG_PATH_SEPARATOR;
264    icon_path += "icons";
265    icon_path += wxCONFIG_PATH_SEPARATOR;
266
267#ifdef _WIN32
268    // The peculiar name is so that the icon is the first in the file
269    // (required by Microsoft Windows for this type of icon)
270    SetIcon(wxIcon("aaaaaAven"));
271#else
272    SetIcon(wxIcon(icon_path + "aven.png", wxBITMAP_TYPE_PNG));
273#endif
274
275    InitialisePensAndBrushes();
276    CreateMenuBar();
277    CreateToolBar();
278    CreateSidePanel();
279
280#ifdef __X__ // wxMotif or wxX11
281    int x;
282    int y;
283    GetSize(&x, &y);
284    // X seems to require a forced resize.
285    SetSize(-1, -1, x, y);
286#endif
287
288#if wxUSE_DRAG_AND_DROP
289    SetDropTarget(new DnDFile(this));
290#endif
291}
292
293MainFrm::~MainFrm()
294{
295    ClearPointLists();
296    delete[] m_Points;
297    delete[] m_Pens;
298    delete[] m_Brushes;
299}
300
301void MainFrm::InitialisePensAndBrushes()
302{
303    m_Points = new list<PointInfo*>[NUM_DEPTH_COLOURS + 1];
304    m_Pens = new wxPen[NUM_DEPTH_COLOURS + 1];
305    m_Brushes = new wxBrush[NUM_DEPTH_COLOURS + 1];
306    for (int pen = 0; pen < NUM_DEPTH_COLOURS + 1; ++pen) {
307        m_Pens[pen].SetColour(REDS[pen], GREENS[pen], BLUES[pen]);
308        m_Brushes[pen].SetColour(REDS[pen], GREENS[pen], BLUES[pen]);
309    }
310}
311
312void MainFrm::CreateMenuBar()
313{
314    // Create the menus and the menu bar.
315
316    wxMenu* filemenu = new wxMenu;
317    // wxID_OPEN stock label lacks the ellipses
318    filemenu->Append(wxID_OPEN, GetTabMsg(/*@Open...##Ctrl+O*/220));
319    filemenu->AppendSeparator();
320    // wxID_PRINT stock label lacks the ellipses
321    filemenu->Append(wxID_PRINT, GetTabMsg(/*@Print...##Ctrl+P*/380));
322    filemenu->Append(menu_FILE_PAGE_SETUP, GetTabMsg(/*P@age Setup...*/381));
323    filemenu->AppendSeparator();
324    filemenu->Append(menu_FILE_EXPORT, GetTabMsg(/*@Export as...*/382));
325    filemenu->AppendSeparator();
326    filemenu->Append(wxID_EXIT);
327
328    m_history.UseMenu(filemenu);
329    m_history.Load(*wxConfigBase::Get());
330
331    wxMenu* rotmenu = new wxMenu;
332    rotmenu->Append(menu_ROTATION_START, GetTabMsg(/*@Start Rotation##Return*/230));
333    rotmenu->Append(menu_ROTATION_STOP, GetTabMsg(/*S@top Rotation##Space*/231));
334    rotmenu->AppendSeparator();
335    rotmenu->Append(menu_ROTATION_SPEED_UP, GetTabMsg(/*Speed @Up*/232));
336    rotmenu->Append(menu_ROTATION_SLOW_DOWN, GetTabMsg(/*Slow @Down*/233));
337    rotmenu->AppendSeparator();
338    rotmenu->Append(menu_ROTATION_REVERSE, GetTabMsg(/*@Reverse Direction*/234));
339    rotmenu->AppendSeparator();
340    rotmenu->Append(menu_ROTATION_STEP_CCW, GetTabMsg(/*Step Once @Anticlockwise*/235));
341    rotmenu->Append(menu_ROTATION_STEP_CW, GetTabMsg(/*Step Once @Clockwise*/236));
342
343    wxMenu* orientmenu = new wxMenu;
344    orientmenu->Append(menu_ORIENT_MOVE_NORTH, GetTabMsg(/*View @North*/240));
345    orientmenu->Append(menu_ORIENT_MOVE_EAST, GetTabMsg(/*View @East*/241));
346    orientmenu->Append(menu_ORIENT_MOVE_SOUTH, GetTabMsg(/*View @South*/242));
347    orientmenu->Append(menu_ORIENT_MOVE_WEST, GetTabMsg(/*View @West*/243));
348    orientmenu->AppendSeparator();
349    orientmenu->Append(menu_ORIENT_SHIFT_LEFT, GetTabMsg(/*Shift Survey @Left*/244));
350    orientmenu->Append(menu_ORIENT_SHIFT_RIGHT, GetTabMsg(/*Shift Survey @Right*/245));
351    orientmenu->Append(menu_ORIENT_SHIFT_UP, GetTabMsg(/*Shift Survey @Up*/246));
352    orientmenu->Append(menu_ORIENT_SHIFT_DOWN, GetTabMsg(/*Shift Survey @Down*/247));
353    orientmenu->AppendSeparator();
354    orientmenu->Append(menu_ORIENT_PLAN, GetTabMsg(/*@Plan View*/248));
355    orientmenu->Append(menu_ORIENT_ELEVATION, GetTabMsg(/*Ele@vation*/249));
356    orientmenu->AppendSeparator();
357    orientmenu->Append(menu_ORIENT_HIGHER_VP, GetTabMsg(/*@Higher Viewpoint*/250));
358    orientmenu->Append(menu_ORIENT_LOWER_VP, GetTabMsg(/*L@ower Viewpoint*/251));
359    orientmenu->AppendSeparator();
360    // Default labels for wxID_ZOOM_IN and wxID_ZOOM_OUT don't have accels.
361    orientmenu->Append(wxID_ZOOM_IN, GetTabMsg(/*@Zoom In##]*/252));
362    orientmenu->Append(wxID_ZOOM_OUT, GetTabMsg(/*Zoo@m Out##[*/253));
363    orientmenu->AppendSeparator();
364    orientmenu->Append(menu_ORIENT_DEFAULTS, GetTabMsg(/*Restore De@fault Settings*/254));
365
366    wxMenu* viewmenu = new wxMenu;
367    viewmenu->Append(menu_VIEW_SHOW_NAMES, GetTabMsg(/*Station @Names##Ctrl+N*/270), "", true);
368    viewmenu->Append(menu_VIEW_SHOW_CROSSES, GetTabMsg(/*@Crosses##Ctrl+X*/271), "", true);
369    viewmenu->Append(menu_VIEW_GRID, GetTabMsg(/*@Grid##Ctrl+G*/297), "", true);
370    viewmenu->AppendSeparator();
371    viewmenu->Append(menu_VIEW_SHOW_LEGS, GetTabMsg(/*@Underground Survey Legs##Ctrl+L*/272), "", true);
372    viewmenu->Append(menu_VIEW_SHOW_SURFACE, GetTabMsg(/*@Surface Survey Legs##Ctrl+F*/291), "", true);
373    viewmenu->AppendSeparator();
374    viewmenu->Append(menu_VIEW_SURFACE_DEPTH, GetTabMsg(/*@Altitude Colouring on Surface Surveys*/292), "", true);
375    viewmenu->Append(menu_VIEW_SURFACE_DASHED, GetTabMsg(/*@Dashed Surface Surveys*/293), "", true);
376    viewmenu->AppendSeparator();
377    viewmenu->Append(menu_VIEW_SHOW_OVERLAPPING_NAMES, GetTabMsg(/*@Overlapping Names*/273), "", true);
378    viewmenu->AppendSeparator();
379    viewmenu->Append(menu_VIEW_SHOW_ENTRANCES, GetTabMsg(/*Highlight @Entrances*/294), "", true);
380    viewmenu->Append(menu_VIEW_SHOW_FIXED_PTS, GetTabMsg(/*Highlight @Fixed Points*/295), "", true);
381    viewmenu->Append(menu_VIEW_SHOW_EXPORTED_PTS, GetTabMsg(/*Highlight E@xported Points*/296), "", true);
382
383    wxMenu* ctlmenu = new wxMenu;
384    ctlmenu->Append(menu_CTL_REVERSE, GetTabMsg(/*@Reverse Sense##Ctrl+R*/280), "", true);
385    ctlmenu->AppendSeparator();
386    ctlmenu->Append(menu_CTL_CANCEL_DIST_LINE, GetTabMsg(/*@Cancel Measuring Line##Escape*/281));
387    ctlmenu->AppendSeparator();
388    wxMenu* indmenu = new wxMenu;
389    indmenu->Append(menu_VIEW_COMPASS, GetTabMsg(/*@Compass*/274), "", true);
390    indmenu->Append(menu_VIEW_CLINO, GetTabMsg(/*C@linometer*/275), "", true);
391    indmenu->Append(menu_VIEW_DEPTH_BAR, GetTabMsg(/*@Depth Bar*/276), "", true);
392    indmenu->Append(menu_VIEW_SCALE_BAR, GetTabMsg(/*@Scale Bar*/277), "", true);
393    ctlmenu->Append(menu_VIEW_INDICATORS, GetTabMsg(/*@Indicators*/299), indmenu);
394    ctlmenu->Append(menu_VIEW_SIDE_PANEL, GetTabMsg(/*@Side Panel*/337), "", true);
395    ctlmenu->AppendSeparator();
396    ctlmenu->Append(menu_VIEW_METRIC, GetTabMsg(/*@Metric*/342), "", true);
397    ctlmenu->Append(menu_VIEW_DEGREES, GetTabMsg(/*@Degrees*/343), "", true);
398
399    wxMenu* helpmenu = new wxMenu;
400    helpmenu->Append(wxID_ABOUT);
401
402    wxMenuBar* menubar = new wxMenuBar(wxMB_DOCKABLE);
403    menubar->Append(filemenu, GetTabMsg(/*@File*/210));
404    menubar->Append(rotmenu, GetTabMsg(/*@Rotation*/211));
405    menubar->Append(orientmenu, GetTabMsg(/*@Orientation*/212));
406    menubar->Append(viewmenu, GetTabMsg(/*@View*/213));
407    menubar->Append(ctlmenu, GetTabMsg(/*@Controls*/214));
408    menubar->Append(helpmenu, GetTabMsg(/*@Help*/215));
409    SetMenuBar(menubar);
410}
411
412// ICON must be a literal string.
413#define TOOLBAR_BITMAP(ICON) wxBitmap(icon_path + ICON".png", wxBITMAP_TYPE_PNG)
414
415void MainFrm::CreateToolBar()
416{
417    // Create the toolbar.
418
419    wxToolBar* toolbar = wxFrame::CreateToolBar();
420
421#ifndef __WXGTK20__
422    toolbar->SetMargins(5, 5);
423#endif
424
425    toolbar->AddTool(wxID_OPEN, TOOLBAR_BITMAP("open"), "Open a 3D file for viewing");
426    toolbar->AddSeparator();
427    toolbar->AddTool(menu_ROTATION_TOGGLE, TOOLBAR_BITMAP("rotation"),
428                     wxNullBitmap, true, -1, -1, NULL, "Toggle rotation");
429    toolbar->AddSeparator();
430    toolbar->AddTool(menu_ORIENT_PLAN, TOOLBAR_BITMAP("plan"), "Switch to plan view");
431    toolbar->AddTool(menu_ORIENT_ELEVATION, TOOLBAR_BITMAP("elevation"), "Switch to elevation view");
432    toolbar->AddSeparator();
433    toolbar->AddTool(menu_ORIENT_DEFAULTS, TOOLBAR_BITMAP("defaults"), "Restore default view");
434    toolbar->AddSeparator();
435    toolbar->AddTool(menu_VIEW_SHOW_NAMES, TOOLBAR_BITMAP("names"), wxNullBitmap, true,
436                     -1, -1, NULL, "Show station names");
437    toolbar->AddTool(menu_VIEW_SHOW_CROSSES, TOOLBAR_BITMAP("crosses"), wxNullBitmap, true,
438                     -1, -1, NULL, "Show crosses on stations");
439    toolbar->AddTool(menu_VIEW_SHOW_ENTRANCES, TOOLBAR_BITMAP("entrances"), wxNullBitmap, true,
440                     -1, -1, NULL, "Highlight entrances");
441    toolbar->AddTool(menu_VIEW_SHOW_FIXED_PTS, TOOLBAR_BITMAP("fixed-pts"), wxNullBitmap, true,
442                     -1, -1, NULL, "Highlight fixed points");
443    toolbar->AddTool(menu_VIEW_SHOW_EXPORTED_PTS, TOOLBAR_BITMAP("exported-pts"), wxNullBitmap, true,
444                     -1, -1, NULL, "Highlight exported stations");
445    toolbar->AddSeparator();
446    toolbar->AddTool(menu_VIEW_SHOW_LEGS, TOOLBAR_BITMAP("ug-legs"), wxNullBitmap, true,
447                     -1, -1, NULL, "Show underground surveys");
448    toolbar->AddTool(menu_VIEW_SHOW_SURFACE, TOOLBAR_BITMAP("surface-legs"), wxNullBitmap, true,
449                     -1, -1, NULL, "Show surface surveys");
450    toolbar->AddSeparator();
451
452    toolbar->Realize();
453}
454
455void MainFrm::CreateSidePanel()
456{
457    m_Splitter = new AvenSplitterWindow(this);
458
459    m_Panel = new wxPanel(m_Splitter);
460    m_Tree = new AvenTreeCtrl(this, m_Panel);
461    wxPanel *find_panel = new wxPanel(m_Panel);
462    m_Panel->Show(false);
463
464    m_FindBox = new wxTextCtrl(find_panel, -1, "");
465    wxButton *find_button, *hide_button;
466    find_button = new wxButton(find_panel, wxID_FIND, msg(/*Find*/332));
467    find_button->SetDefault();
468    // SetDefaultItem() was moved from wxPanel to wxTopLevelWindow in wx2.8.
469    // No idea how to work around that, but it doesn't seem to be needed with
470    // wx2.8 (at least with wxGTK - perhaps the SetDefault() call above does
471    // the trick.  Seems safest to still call this for older version in case
472    // they need it.
473#if !wxCHECK_VERSION(2,8,0)
474    find_panel->SetDefaultItem(find_button);
475#endif
476    hide_button = new wxButton(find_panel, button_HIDE, msg(/*Hide*/333));
477    m_RegexpCheckBox = new wxCheckBox(find_panel, -1,
478                                      msg(/*Regular expression*/334));
479    m_Coords = new wxStaticText(find_panel, -1, "");
480    m_StnCoords = new wxStaticText(find_panel, -1, "");
481    //  m_MousePtr = new wxStaticText(find_panel, -1, "Mouse coordinates");
482    m_StnName = new wxStaticText(find_panel, -1, "");
483    m_StnAlt = new wxStaticText(find_panel, -1, "");
484    m_Dist1 = new wxStaticText(find_panel, -1, "");
485    m_Dist2 = new wxStaticText(find_panel, -1, "");
486    m_Dist3 = new wxStaticText(find_panel, -1, "");
487    m_Found = new wxStaticText(find_panel, -1, "");
488
489    wxBoxSizer *find_button_sizer = new wxBoxSizer(wxHORIZONTAL);
490    find_button_sizer->Add(m_FindBox, 1, wxALL, 2);
491#ifdef _WIN32
492    find_button_sizer->Add(find_button, 0, wxALL, 2);
493#else
494    // GTK+ (and probably Motif) default buttons have a thick external
495    // border we need to allow for
496    find_button_sizer->Add(find_button, 0, wxALL, 4);
497#endif
498
499    wxBoxSizer *hide_button_sizer = new wxBoxSizer(wxHORIZONTAL);
500    hide_button_sizer->Add(m_Found, 1, wxALL, 2);
501#ifdef _WIN32
502    hide_button_sizer->Add(hide_button, 0, wxALL, 2);
503#else
504    hide_button_sizer->Add(hide_button, 0, wxALL, 4);
505#endif
506
507    wxBoxSizer *find_sizer = new wxBoxSizer(wxVERTICAL);
508    find_sizer->Add(find_button_sizer, 0, wxALL | wxEXPAND, 2);
509    find_sizer->Add(hide_button_sizer, 0, wxALL | wxEXPAND, 2);
510    find_sizer->Add(m_RegexpCheckBox, 0, wxALL | wxEXPAND, 2);
511    find_sizer->Add(10, 5, 0, wxALL | wxEXPAND, 2);
512    //   find_sizer->Add(m_MousePtr, 0, wxALL | wxEXPAND, 2);
513    find_sizer->Add(m_Coords, 0, wxALL | wxEXPAND, 2);
514    find_sizer->Add(10, 5, 0, wxALL | wxEXPAND, 2);
515    find_sizer->Add(m_StnName, 0, wxALL | wxEXPAND, 2);
516    find_sizer->Add(m_StnCoords, 0, wxALL | wxEXPAND, 2);
517    find_sizer->Add(m_StnAlt, 0, wxALL | wxEXPAND, 2);
518    find_sizer->Add(10, 5, 0, wxALL | wxEXPAND, 2);
519    find_sizer->Add(m_Dist1, 0, wxALL | wxEXPAND, 2);
520    find_sizer->Add(m_Dist2, 0, wxALL | wxEXPAND, 2);
521    find_sizer->Add(m_Dist3, 0, wxALL | wxEXPAND, 2);
522
523    find_panel->SetAutoLayout(true);
524    find_panel->SetSizer(find_sizer);
525    find_sizer->Fit(find_panel);
526    find_sizer->SetSizeHints(find_panel);
527
528    wxBoxSizer *panel_sizer = new wxBoxSizer(wxVERTICAL);
529    panel_sizer->Add(m_Tree, 1, wxALL | wxEXPAND, 2);
530    panel_sizer->Add(find_panel, 0, wxALL | wxEXPAND, 2);
531    m_Panel->SetAutoLayout(true);
532    m_Panel->SetSizer(panel_sizer);
533//    panel_sizer->Fit(m_Panel);
534//    panel_sizer->SetSizeHints(m_Panel);
535
536    m_Gfx = new GfxCore(this, m_Splitter);
537
538    m_Splitter->Initialize(m_Gfx);
539}
540
541void MainFrm::ClearPointLists()
542{
543    // Free memory occupied by the contents of the point and label lists.
544
545    for (int band = 0; band < NUM_DEPTH_COLOURS + 1; band++) {
546        list<PointInfo*>::iterator pos = m_Points[band].begin();
547        list<PointInfo*>::iterator end = m_Points[band].end();
548        while (pos != end) {
549            PointInfo* point = *pos++;
550            delete point;
551        }
552        m_Points[band].clear();
553    }
554
555    list<LabelInfo*>::iterator pos = m_Labels.begin();
556    while (pos != m_Labels.end()) {
557        LabelInfo* label = *pos++;
558        delete label;
559    }
560    m_Labels.clear();
561}
562
563bool MainFrm::LoadData(const wxString& file, wxString prefix)
564{
565    // Load survey data from file, centre the dataset around the origin,
566    // chop legs such that no legs cross depth colour boundaries and prepare
567    // the data for drawing.
568
569#if 0
570    wxStopWatch timer;
571    timer.Start();
572#endif
573
574    // Load the survey data.
575
576    img* survey = img_open_survey(file, prefix.c_str());
577    if (!survey) {
578        wxString m = wxString::Format(msg(img_error()), file.c_str());
579        wxGetApp().ReportError(m);
580        return false;
581    }
582
583    m_File = survey->filename_opened;
584
585    m_Tree->DeleteAllItems();
586
587    // Create a list of all the leg vertices, counting them and finding the
588    // extent of the survey at the same time.
589
590    m_NumLegs = 0;
591    m_NumPoints = 0;
592    m_NumExtraLegs = 0;
593    m_NumCrosses = 0;
594    m_NumFixedPts = 0;
595    m_NumExportedPts = 0;
596    m_NumEntrances = 0;
597
598    // Delete any existing list entries.
599    ClearPointLists();
600
601    Double xmin = DBL_MAX;
602    Double xmax = -DBL_MAX;
603    Double ymin = DBL_MAX;
604    Double ymax = -DBL_MAX;
605    m_ZMin = DBL_MAX;
606    Double zmax = -DBL_MAX;
607
608    list<PointInfo*> points;
609
610    int result;
611    do {
612        img_point pt;
613        result = img_read_item(survey, &pt);
614        switch (result) {
615            case img_MOVE:
616            case img_LINE:
617            {
618                m_NumPoints++;
619
620                // Update survey extents.
621                if (pt.x < xmin) xmin = pt.x;
622                if (pt.x > xmax) xmax = pt.x;
623                if (pt.y < ymin) ymin = pt.y;
624                if (pt.y > ymax) ymax = pt.y;
625                if (pt.z < m_ZMin) m_ZMin = pt.z;
626                if (pt.z > zmax) zmax = pt.z;
627
628                PointInfo* info = new PointInfo;
629                info->x = pt.x;
630                info->y = pt.y;
631                info->z = pt.z;
632
633                if (result == img_LINE) {
634                    // Set flags to say this is a line rather than a move
635                    m_NumLegs++;
636                    info->isLine = true;
637                    info->isSurface = (survey->flags & img_FLAG_SURFACE);
638                } else {
639                    info->isLine = false;
640                }
641
642                // Add this point to the list.
643                points.push_back(info);
644                break;
645            }
646
647            case img_LABEL: {
648                LabelInfo* label = new LabelInfo;
649                label->text = survey->label;
650                label->x = pt.x;
651                label->y = pt.y;
652                label->z = pt.z;
653                if (survey->flags & img_SFLAG_ENTRANCE) {
654                    survey->flags ^= (img_SFLAG_ENTRANCE | LFLAG_ENTRANCE);
655                }
656                label->flags = survey->flags;
657                if (label->IsEntrance()) {
658                    m_NumEntrances++;
659                }
660                if (label->IsFixedPt()) {
661                    m_NumFixedPts++;
662                }
663                if (label->IsExportedPt()) {
664                    m_NumExportedPts++;
665                }
666                m_Labels.push_back(label);
667                m_NumCrosses++;
668
669                break;
670            }
671
672            case img_BAD: {
673                m_Labels.clear();
674
675                // FIXME: Do we need to reset all these? - Olly
676                m_NumLegs = 0;
677                m_NumPoints = 0;
678                m_NumExtraLegs = 0;
679                m_NumCrosses = 0;
680                m_NumFixedPts = 0;
681                m_NumExportedPts = 0;
682                m_NumEntrances = 0;
683
684                m_ZMin = DBL_MAX;
685
686                img_close(survey);
687
688                wxString m = wxString::Format(msg(img_error()), file.c_str());
689                wxGetApp().ReportError(m);
690
691                return false;
692            }
693
694            default:
695                break;
696        }
697    } while (result != img_STOP);
698
699    separator = survey->separator;
700    m_Title = survey->title;
701    m_DateStamp = survey->datestamp;
702    img_close(survey);
703
704    // Check we've actually loaded some legs or stations!
705    if (m_NumLegs == 0 && m_Labels.empty()) {
706        wxString m = wxString::Format(msg(/*No survey data in 3d file `%s'*/202), file.c_str());
707        wxGetApp().ReportError(m);
708        return false;
709    }
710
711    if (points.empty()) {
712        // No legs, so get survey extents from stations
713        list<LabelInfo*>::const_iterator i;
714        for (i = m_Labels.begin(); i != m_Labels.end(); ++i) {
715            if ((*i)->x < xmin) xmin = (*i)->x;
716            if ((*i)->x > xmax) xmax = (*i)->x;
717            if ((*i)->y < ymin) ymin = (*i)->y;
718            if ((*i)->y > ymax) ymax = (*i)->y;
719            if ((*i)->z < m_ZMin) m_ZMin = (*i)->z;
720            if ((*i)->z > zmax) zmax = (*i)->z;
721        }
722    } else {
723        // Delete any trailing move.
724        PointInfo* pt = points.back();
725        if (!pt->isLine) {
726            m_NumPoints--;
727            points.pop_back();
728            delete pt;
729        }
730    }
731
732    m_XExt = xmax - xmin;
733    m_YExt = ymax - ymin;
734    m_ZExt = zmax - m_ZMin;
735
736    // FIXME -- temporary bodge
737    m_XMin = xmin;
738    m_YMin = ymin;
739
740    // Sort the labels.
741    m_Labels.sort(LabelCmp(separator));
742
743    // Fill the tree of stations and prefixes.
744    FillTree();
745
746    // Sort labels so that entrances are displayed in preference,
747    // then fixed points, then exported points, then other points.
748    //
749    // Also sort by leaf name so that we'll tend to choose labels
750    // from different surveys, rather than labels from surveys which
751    // are earlier in the list.
752    m_Labels.sort(LabelPlotCmp(separator));
753
754    // Sort out depth colouring boundaries (before centering dataset!)
755    SortIntoDepthBands(points);
756
757    // Centre the dataset around the origin.
758    CentreDataset(xmin, ymin, m_ZMin);
759
760#if 0
761    printf("time to load = %.3f\n", (double)timer.Time());
762#endif
763
764    // Update window title.
765    SetTitle(wxString(APP_NAME" - [") + m_File + wxString("]"));
766
767    return true;
768}
769
770void MainFrm::FillTree()
771{
772    // Create the root of the tree.
773    wxTreeItemId treeroot = m_Tree->AddRoot(wxFileNameFromPath(m_File));
774
775    // Fill the tree of stations and prefixes.
776    stack<wxTreeItemId> previous_ids;
777    wxString current_prefix = "";
778    wxTreeItemId current_id = treeroot;
779
780    list<LabelInfo*>::iterator pos = m_Labels.begin();
781    while (pos != m_Labels.end()) {
782        LabelInfo* label = *pos++;
783
784        // Determine the current prefix.
785        wxString prefix = label->GetText().BeforeLast(separator);
786
787        // Determine if we're still on the same prefix.
788        if (prefix == current_prefix) {
789            // no need to fiddle with branches...
790        }
791        // If not, then see if we've descended to a new prefix.
792        else if (prefix.length() > current_prefix.length() &&
793                 prefix.StartsWith(current_prefix) &&
794                 (prefix[current_prefix.length()] == separator ||
795                  current_prefix == "")) {
796            // We have, so start as many new branches as required.
797            int current_prefix_length = current_prefix.length();
798            current_prefix = prefix;
799            if (current_prefix_length != 0) {
800                prefix = prefix.Mid(current_prefix_length + 1);
801            }
802            int next_dot;
803            do {
804                // Extract the next bit of prefix.
805                next_dot = prefix.Find(separator);
806
807                wxString bit = next_dot == -1 ? prefix : prefix.Left(next_dot);
808                assert(bit != "");
809
810                // Add the current tree ID to the stack.
811                previous_ids.push(current_id);
812
813                // Append the new item to the tree and set this as the current branch.
814                current_id = m_Tree->AppendItem(current_id, bit);
815                m_Tree->SetItemData(current_id, new TreeData(NULL));
816                prefix = prefix.Mid(next_dot + 1);
817            } while (next_dot != -1);
818        }
819        // Otherwise, we must have moved up, and possibly then down again.
820        else {
821            size_t count = 0;
822            bool ascent_only = (prefix.length() < current_prefix.length() &&
823                                current_prefix.StartsWith(prefix) &&
824                                (current_prefix[prefix.length()] == separator ||
825                                 prefix == ""));
826            if (!ascent_only) {
827                // Find out how much of the current prefix and the new prefix
828                // are the same.
829                // Note that we require a match of a whole number of parts
830                // between dots!
831                for (size_t i = 0; prefix[i] == current_prefix[i]; ++i) {
832                    if (prefix[i] == separator) count = i + 1;
833                }
834            } else {
835                count = prefix.length() + 1;
836            }
837
838            // Extract the part of the current prefix after the bit (if any)
839            // which has matched.
840            // This gives the prefixes to ascend over.
841            wxString prefixes_ascended = current_prefix.Mid(count);
842
843            // Count the number of prefixes to ascend over.
844            int num_prefixes = prefixes_ascended.Freq(separator);
845
846            // Reverse up over these prefixes.
847            for (int i = 1; i <= num_prefixes; i++) {
848                previous_ids.pop();
849            }
850            current_id = previous_ids.top();
851            previous_ids.pop();
852
853            if (!ascent_only) {
854                // Now extract the bit of new prefix.
855                wxString new_prefix = prefix.Mid(count);
856
857                // Add branches for this new part.
858                while (true) {
859                    // Extract the next bit of prefix.
860                    int next_dot = new_prefix.Find(separator);
861
862                    wxString bit;
863                    if (next_dot == -1) {
864                        bit = new_prefix;
865                    } else {
866                        bit = new_prefix.Left(next_dot);
867                    }
868
869                    // Add the current tree ID to the stack.
870                    previous_ids.push(current_id);
871
872                    // Append the new item to the tree and set this as the
873                    // current branch.
874                    current_id = m_Tree->AppendItem(current_id, bit);
875                    m_Tree->SetItemData(current_id, new TreeData(NULL));
876
877                    if (next_dot == -1) break;
878
879                    new_prefix = new_prefix.Mid(next_dot + 1);
880                }
881            }
882
883            current_prefix = prefix;
884        }
885
886        // Now add the leaf.
887        wxString bit = label->GetText().AfterLast(separator);
888        assert(bit != "");
889        wxTreeItemId id = m_Tree->AppendItem(current_id, bit);
890        m_Tree->SetItemData(id, new TreeData(label));
891        label->tree_id = id;
892        // Set the colour for an item in the survey tree.
893        if (label->IsEntrance()) {
894            // Entrances are green (like entrance blobs).
895            m_Tree->SetItemTextColour(id, wxColour(0, 255, 0));
896        } else if (label->IsSurface()) {
897            // Surface stations are dark green.
898            m_Tree->SetItemTextColour(id, wxColour(49, 158, 79));
899        }
900    }
901
902    m_Tree->Expand(treeroot);
903    m_Tree->SetEnabled();
904}
905
906void MainFrm::SelectTreeItem(LabelInfo* label)
907{
908    m_Tree->SelectItem(label->tree_id);
909}
910
911void MainFrm::CentreDataset(Double xmin, Double ymin, Double zmin)
912{
913    // Centre the dataset around the origin.
914
915    Double xoff = xmin + (m_XExt / 2.0);
916    Double yoff = ymin + (m_YExt / 2.0);
917    Double zoff = zmin + (m_ZExt / 2.0);
918    m_Offsets.set(xoff, yoff, zoff);
919
920    for (int band = 0; band < NUM_DEPTH_COLOURS + 1; band++) {
921        list<PointInfo*>::iterator pos = m_Points[band].begin();
922        list<PointInfo*>::iterator end = m_Points[band].end();
923        while (pos != end) {
924            PointInfo* point = *pos++;
925            point->x -= xoff;
926            point->y -= yoff;
927            point->z -= zoff;
928        }
929    }
930
931    list<LabelInfo*>::iterator lpos = m_Labels.begin();
932    while (lpos != m_Labels.end()) {
933        LabelInfo* label = *lpos++;
934        label->x -= xoff;
935        label->y -= yoff;
936        label->z -= zoff;
937    }
938}
939
940int MainFrm::GetDepthColour(Double z)
941{
942    // Return the (0-based) depth colour band index for a z-coordinate.
943    return int(((z - m_ZMin) / (m_ZExt == 0.0 ? 1.0 : m_ZExt)) * (NUM_DEPTH_COLOURS - 1));
944}
945
946Double MainFrm::GetDepthBoundaryBetweenBands(int a, int b)
947{
948    // Return the z-coordinate of the depth colour boundary between
949    // two adjacent depth colour bands (specified by 0-based indices).
950
951    assert((a == b - 1) || (a == b + 1));
952
953    int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
954    return m_ZMin + (m_ZExt * band / (NUM_DEPTH_COLOURS - 1));
955}
956
957void MainFrm::IntersectLineWithPlane(Double x0, Double y0, Double z0,
958                                     Double x1, Double y1, Double z1,
959                                     Double z, Double& x, Double& y)
960{
961    // Find the intersection point of the line (x0, y0, z0) -> (x1, y1, z1)
962    // with the plane parallel to the xy-plane with z-axis intersection z.
963    assert(z1 - z0 != 0.0);
964
965    Double t = (z - z0) / (z1 - z0);
966    // FIXME: this assertion fails on Windows - haven't investigated but I
967    // suspect it'll be crap rounding:
968    // assert(0.0 <= t && t <= 1.0);
969
970    x = x0 + t * (x1 - x0);
971    y = y0 + t * (y1 - y0);
972}
973
974void MainFrm::SortIntoDepthBands(list<PointInfo*>& points)
975{
976    // Split legs which cross depth colouring boundaries and classify all
977    // points into the correct depth bands.
978
979    list<PointInfo*>::iterator pos = points.begin();
980    PointInfo* prev_point = NULL;
981    while (pos != points.end()) {
982        PointInfo* point = *pos++;
983        assert(point);
984
985        // If this is a leg, then check if it intersects a depth
986        // colour boundary.
987        if (point->isLine) {
988            assert(prev_point);
989            int col1 = GetDepthColour(prev_point->z);
990            int col2 = GetDepthColour(point->z);
991            if (col1 != col2) {
992                // The leg does cross at least one boundary, so split it as
993                // many times as required...
994                int inc = (col1 > col2) ? -1 : 1;
995                for (int band = col1; band != col2; band += inc) {
996                    int next_band = band + inc;
997
998                    // Determine the z-coordinate of the boundary being
999                    // intersected.
1000                    Double split_at_z = GetDepthBoundaryBetweenBands(band, next_band);
1001                    Double split_at_x, split_at_y;
1002
1003                    // Find the coordinates of the intersection point.
1004                    IntersectLineWithPlane(prev_point->x, prev_point->y, prev_point->z,
1005                                           point->x, point->y, point->z,
1006                                           split_at_z, split_at_x, split_at_y);
1007
1008                    // Create a new leg only as far as this point.
1009                    PointInfo* info = new PointInfo;
1010                    info->x = split_at_x;
1011                    info->y = split_at_y;
1012                    info->z = split_at_z;
1013                    info->isLine = true;
1014                    info->isSurface = point->isSurface;
1015                    m_Points[band].push_back(info);
1016
1017                    // Create a move to this point in the next band.
1018                    info = new PointInfo;
1019                    info->x = split_at_x;
1020                    info->y = split_at_y;
1021                    info->z = split_at_z;
1022                    info->isLine = false;
1023                    info->isSurface = point->isSurface;
1024                    m_Points[next_band].push_back(info);
1025
1026                    m_NumExtraLegs++;
1027                    m_NumPoints += 2;
1028                }
1029            }
1030
1031            // Add the last point of the (possibly split) leg.
1032            m_Points[col2].push_back(point);
1033        }
1034        else {
1035            // The first point, a surface point, or another move: put it in the
1036            // correct list according to depth.
1037            int band = GetDepthColour(point->z);
1038            m_Points[band].push_back(point);
1039        }
1040
1041        prev_point = point;
1042    }
1043}
1044
1045void MainFrm::OnMRUFile(wxCommandEvent& event)
1046{
1047    wxString f(m_history.GetHistoryFile(event.GetId() - wxID_FILE1));
1048    if (!f.empty()) OpenFile(f);
1049}
1050
1051void MainFrm::OpenFile(const wxString& file, wxString survey, bool delay)
1052{
1053    wxBusyCursor hourglass;
1054    if (LoadData(file, survey)) {
1055        if (wxIsAbsolutePath(m_File)) {
1056            m_history.AddFileToHistory(m_File);
1057        } else {
1058            wxString abs = wxGetCwd() + wxString(FNM_SEP_LEV) + m_File;
1059            m_history.AddFileToHistory(abs);
1060        }
1061        wxConfigBase *b = wxConfigBase::Get();
1062        m_history.Save(*b);
1063        b->Flush();
1064
1065        int x;
1066        int y;
1067        GetClientSize(&x, &y);
1068        if (x < 600)
1069            x /= 3;
1070        else if (x < 1000)
1071            x = 200;
1072        else
1073            x /= 5;
1074
1075        m_Splitter->SplitVertically(m_Panel, m_Gfx, x);
1076        m_SashPosition = x; // Save width of panel.
1077
1078        if (delay) {
1079            m_Gfx->InitialiseOnNextResize();
1080        } else {
1081            m_Gfx->Initialise();
1082        }
1083        m_Panel->Show(true);
1084
1085        m_Gfx->SetFocus();
1086    }
1087}
1088
1089//
1090//  UI event handlers
1091//
1092
1093#undef FILEDIALOG_MULTIGLOBS
1094// MS Windows supports "*.abc;*.def" natively; wxGtk supports them as of 2.3
1095#if defined(_WIN32) || wxCHECK_VERSION(2,3,0)
1096# define FILEDIALOG_MULTIGLOBS
1097#endif
1098
1099void MainFrm::OnOpen(wxCommandEvent&)
1100{
1101#ifdef __WXMOTIF__
1102    wxFileDialog dlg (this, wxString(msg(/*Select a 3d file to view*/206)), "", "",
1103                      "*.3d", wxOPEN);
1104#else
1105    wxFileDialog dlg(this, wxString(msg(/*Select a 3d file to view*/206)), "", "",
1106                     wxString::Format("%s|*.3d"
1107#ifdef FILEDIALOG_MULTIGLOBS
1108                                      ";*.3D"
1109#endif
1110#ifdef FILEDIALOG_MULTIGLOBS
1111                                      "|%s|*.plt;*.plf"
1112#ifndef _WIN32
1113                                      ";*.PLT;*.PLF"
1114#endif
1115#else
1116                                      "|%s|*.pl?" // not ideal...
1117#endif
1118                                      "|%s|*.xyz"
1119#ifdef FILEDIALOG_MULTIGLOBS
1120#ifndef _WIN32
1121                                      ";*.XYZ"
1122#endif
1123#endif
1124                                      "|%s|%s",
1125                                      msg(/*Survex 3d files*/207),
1126                                      msg(/*Compass PLT files*/324),
1127                                      msg(/*CMAP XYZ files*/325),
1128                                      msg(/*All files*/208),
1129                                      wxFileSelectorDefaultWildcardStr),
1130                     wxFD_OPEN);
1131#endif
1132    if (dlg.ShowModal() == wxID_OK) {
1133        OpenFile(dlg.GetPath());
1134    }
1135}
1136
1137void MainFrm::OnPrint(wxCommandEvent&)
1138{
1139    m_Gfx->OnPrint(m_File, m_Title, m_DateStamp);
1140}
1141
1142void MainFrm::OnPageSetup(wxCommandEvent&)
1143{
1144    wxPageSetupDialog dlg(this, wxGetApp().GetPageSetupDialogData());
1145    if (dlg.ShowModal() == wxID_OK) {
1146        wxGetApp().SetPageSetupDialogData(dlg.GetPageSetupData());
1147    }
1148}
1149
1150void MainFrm::OnExport(wxCommandEvent&)
1151{
1152    char *baseleaf = baseleaf_from_fnm(m_File.c_str());
1153    wxFileDialog dlg(this, wxString("Export as:"), "",
1154                     wxString(baseleaf),
1155                     "DXF files|*.dxf|SVG files|*.svg|Sketch files|*.sk|EPS files|*.eps|Compass PLT for use with Carto|*.plt",
1156                     wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
1157    free(baseleaf);
1158    if (dlg.ShowModal() == wxID_OK) {
1159        wxString fnm = dlg.GetPath();
1160        if (!m_Gfx->OnExport(fnm, m_Title)) {
1161            wxGetApp().ReportError(wxString::Format("Couldn't write file `%s'", fnm.c_str()));
1162        }
1163    }
1164}
1165
1166void MainFrm::OnQuit(wxCommandEvent&)
1167{
1168    exit(0);
1169}
1170
1171void MainFrm::OnClose(wxCloseEvent&)
1172{
1173    exit(0);
1174}
1175
1176void MainFrm::OnAbout(wxCommandEvent&)
1177{
1178    AboutDlg dlg(this, icon_path);
1179    dlg.Centre();
1180    dlg.ShowModal();
1181}
1182
1183void MainFrm::GetColour(int band, Double& r, Double& g, Double& b) const
1184{
1185    assert(band >= 0 && band < NUM_DEPTH_COLOURS);
1186    r = Double(REDS[band]) / 255.0;
1187    g = Double(GREENS[band]) / 255.0;
1188    b = Double(BLUES[band]) / 255.0;
1189}
1190
1191void MainFrm::ClearTreeSelection()
1192{
1193    m_Tree->UnselectAll();
1194    m_Gfx->SetThere();
1195}
1196
1197void MainFrm::ClearCoords()
1198{
1199    m_Coords->SetLabel("");
1200}
1201
1202void MainFrm::SetCoords(Double x, Double y)
1203{
1204    wxString s;
1205    if (m_Gfx->m_Metric) {
1206        s.Printf(msg(/*  %d E, %d N*/338), int(x), int(y));
1207    } else {
1208        s.Printf(msg(/*  %d E, %d N*/338),
1209                 int(x / METRES_PER_FOOT), int(y / METRES_PER_FOOT));
1210    }
1211    m_Coords->SetLabel(s);
1212}
1213
1214void MainFrm::SetAltitude(Double z)
1215{
1216    wxString s;
1217    if (m_Gfx->m_Metric) {
1218        s.Printf("  %s %dm", msg(/*Altitude*/335), int(z));
1219    } else {
1220        s.Printf("  %s %dft", msg(/*Altitude*/335), int(z / METRES_PER_FOOT));
1221    }
1222    m_Coords->SetLabel(s);
1223}
1224
1225void MainFrm::ShowInfo(const LabelInfo *label)
1226{
1227    assert(m_Gfx);
1228
1229    wxString str;
1230    if (m_Gfx->m_Metric) {
1231        str.Printf(msg(/*  %d E, %d N*/338),
1232                   int(label->x + m_Offsets.getX()),
1233                   int(label->y + m_Offsets.getY()));
1234    } else {
1235        str.Printf(msg(/*  %d E, %d N*/338),
1236                   int((label->x + m_Offsets.getX()) / METRES_PER_FOOT),
1237                   int((label->y + m_Offsets.getY()) / METRES_PER_FOOT));
1238    }
1239    m_StnCoords->SetLabel(str);
1240    m_StnName->SetLabel(label->text);
1241
1242    if (m_Gfx->m_Metric) {
1243        str.Printf("  %s %dm", msg(/*Altitude*/335),
1244                   int(label->z + m_Offsets.getZ()));
1245    } else {
1246        str.Printf("  %s %dft", msg(/*Altitude*/335),
1247                   int((label->z + m_Offsets.getZ()) / METRES_PER_FOOT));
1248    }
1249    m_StnAlt->SetLabel(str);
1250    m_Gfx->SetHere(label->x, label->y, label->z);
1251
1252    wxTreeItemData* sel_wx;
1253    bool sel = m_Tree->GetSelectionData(&sel_wx);
1254    if (sel) {
1255        TreeData *data = (TreeData*) sel_wx;
1256
1257        if (data->IsStation()) {
1258            const LabelInfo* label2 = data->GetLabel();
1259            assert(label2);
1260
1261            Double x0 = label2->x;
1262            Double x1 = label->x;
1263            Double dx = x1 - x0;
1264            Double y0 = label2->y;
1265            Double y1 = label->y;
1266            Double dy = y1 - y0;
1267            Double z0 = label2->z;
1268            Double z1 = label->z;
1269            Double dz = z1 - z0;
1270
1271            Double d_horiz = sqrt(dx*dx + dy*dy);
1272            Double dr = sqrt(dx*dx + dy*dy + dz*dz);
1273
1274            Double brg = deg(atan2(dx, dy));
1275            if (brg < 0) brg += 360;
1276
1277            str.Printf(msg(/*From %s*/339), label2->text.c_str());
1278            m_Dist1->SetLabel(str);
1279            if (m_Gfx->m_Metric) {
1280                str.Printf(msg(/*  H %d%s, V %d%s*/340),
1281                           int(d_horiz), "m",
1282                           int(dz), "m");
1283            } else {
1284                str.Printf(msg(/*  H %d%s, V %d%s*/340),
1285                           int(d_horiz / METRES_PER_FOOT), "ft",
1286                           int(dz / METRES_PER_FOOT), "ft");
1287            }
1288            m_Dist2->SetLabel(str);
1289            wxString brg_unit;
1290            if (m_Gfx->m_Degrees) {
1291                brg_unit = msg(/*&deg;*/344);
1292            } else {
1293                brg *= 400.0 / 360.0;
1294                brg_unit = msg(/*grad*/345);
1295            }
1296            if (m_Gfx->m_Metric) {
1297                str.Printf(msg(/*  Dist %d%s, Brg %03d%s*/341),
1298                           int(dr), "m", int(brg), brg_unit.c_str());
1299            } else {
1300                str.Printf(msg(/*  Dist %d%s, Brg %03d%s*/341),
1301                           int(dr / METRES_PER_FOOT), "ft", int(brg),
1302                           brg_unit.c_str());
1303            }
1304            m_Dist3->SetLabel(str);
1305            m_Gfx->SetThere(x0, y0, z0);
1306        } else {
1307            m_Gfx->SetThere(); // FIXME: not in SetMouseOverStation version?
1308        }
1309    }
1310}
1311
1312void MainFrm::DisplayTreeInfo(const wxTreeItemData* item)
1313{
1314    const TreeData* data = static_cast<const TreeData*>(item);
1315    if (data && data->IsStation()) {
1316        const LabelInfo * l = data->GetLabel();
1317        ShowInfo(l);
1318        m_Gfx->SetHere(l->x, l->y, l->z);
1319    } else {
1320        m_StnName->SetLabel("");
1321        m_StnCoords->SetLabel("");
1322        m_StnAlt->SetLabel("");
1323        m_Gfx->SetHere();
1324        m_Dist1->SetLabel("");
1325        m_Dist2->SetLabel("");
1326        m_Dist3->SetLabel("");
1327        m_Gfx->SetHere();
1328    }
1329}
1330
1331void MainFrm::TreeItemSelected(wxTreeItemData* item)
1332{
1333    TreeData* data = (TreeData*) item;
1334
1335    if (data && data->IsStation()) {
1336        const LabelInfo* label = data->GetLabel();
1337        m_Gfx->CentreOn(label->x, label->y, label->z);
1338        m_Gfx->SetThere(label->x, label->y, label->z);
1339    } else {
1340        m_Gfx->SetThere();
1341    }
1342
1343    m_Dist1->SetLabel("");
1344    m_Dist2->SetLabel("");
1345    m_Dist3->SetLabel("");
1346}
1347
1348void MainFrm::OnFind(wxCommandEvent&)
1349{
1350    wxBusyCursor hourglass;
1351    // Find stations specified by a string or regular expression.
1352
1353    wxString pattern = m_FindBox->GetValue();
1354    int re_flags = wxRE_NOSUB;
1355
1356    if (true /* case insensitive */) {
1357        re_flags |= wxRE_ICASE;
1358    }
1359
1360    bool substring = true;
1361    if (m_RegexpCheckBox->GetValue()) {
1362        re_flags |= wxRE_EXTENDED;
1363    } else if (false /* simple glob-style */) {
1364        wxString pat;
1365        for (size_t i = 0; i < pattern.size(); i++) {
1366           char ch = pattern[i];
1367           // ^ only special at start; $ at end.  But this is simpler...
1368           switch (ch) {
1369            case '^': case '$': case '.': case '[': case '\\':
1370              pat += '\\';
1371              pat += ch;
1372              break;
1373            case '*':
1374              pat += ".*";
1375              substring = false;
1376              break;
1377            case '?':
1378              pat += '.';
1379              substring = false;
1380              break;
1381            default:
1382              pat += ch;
1383           }
1384        }
1385        pattern = pat;
1386        re_flags |= wxRE_BASIC;
1387    } else {
1388        wxString pat;
1389        for (size_t i = 0; i < pattern.size(); i++) {
1390           char ch = pattern[i];
1391           // ^ only special at start; $ at end.  But this is simpler...
1392           switch (ch) {
1393            case '^': case '$': case '*': case '.': case '[': case '\\':
1394              pat += '\\';
1395           }
1396           pat += ch;
1397        }
1398        pattern = pat;
1399        re_flags |= wxRE_BASIC;
1400    }
1401
1402    if (!substring) {
1403        // FIXME "0u" required to avoid compilation error with g++-3.0
1404        if (pattern.empty() || pattern[0u] != '^') pattern = '^' + pattern;
1405        // FIXME: this fails to cope with "\$" at the end of pattern...
1406        if (pattern[pattern.size() - 1] != '$') pattern += '$';
1407    }
1408
1409    wxRegEx regex;
1410    if (!regex.Compile(pattern, re_flags)) {
1411        wxString m;
1412        m.Printf(msg(/*Invalid regular expression: %s*/404), pattern.c_str());
1413        wxGetApp().ReportError(m);
1414        return;
1415    }
1416
1417    list<LabelInfo*>::iterator pos = m_Labels.begin();
1418
1419    int found = 0;
1420    while (pos != m_Labels.end()) {
1421        LabelInfo* label = *pos++;
1422
1423        if (regex.Matches(label->text)) {
1424            label->flags |= LFLAG_HIGHLIGHTED;
1425            found++;
1426        } else {
1427            label->flags &= ~LFLAG_HIGHLIGHTED;
1428        }
1429    }
1430
1431    m_Found->SetLabel(wxString::Format(msg(/*%d found*/331), found));
1432#ifdef _WIN32
1433    m_Found->Refresh(); // FIXME
1434#endif
1435    // Re-sort so highlighted points get names in preference
1436    if (found) m_Labels.sort(LabelPlotCmp(separator));
1437    m_Gfx->ForceRefresh();
1438
1439#if 0
1440    if (!found) {
1441        wxGetApp().ReportError(msg(/*No matches were found.*/328));
1442    }
1443#endif
1444
1445    m_Gfx->SetFocus();
1446}
1447
1448void MainFrm::OnHide(wxCommandEvent&)
1449{
1450    // Hide any search result highlights.
1451    m_Found->SetLabel("");
1452    list<LabelInfo*>::iterator pos = m_Labels.begin();
1453    while (pos != m_Labels.end()) {
1454        LabelInfo* label = *pos++;
1455        label->flags &= ~LFLAG_HIGHLIGHTED;
1456    }
1457    m_Gfx->ForceRefresh();
1458}
1459
1460void MainFrm::SetMouseOverStation(LabelInfo* label)
1461{
1462    if (label) {
1463        ShowInfo(label);
1464    } else {
1465        m_StnName->SetLabel("");
1466        m_StnCoords->SetLabel("");
1467        m_StnAlt->SetLabel("");
1468        m_Gfx->SetHere();
1469        m_Dist1->SetLabel("");
1470        m_Dist2->SetLabel("");
1471        m_Dist3->SetLabel("");
1472    }
1473}
1474
1475void MainFrm::OnViewSidePanel(wxCommandEvent&)
1476{
1477    ToggleSidePanel();
1478}
1479
1480void MainFrm::ToggleSidePanel()
1481{
1482    // Toggle display of the side panel.
1483
1484    assert(m_Gfx);
1485
1486    if (m_Splitter->IsSplit()) {
1487        m_SashPosition = m_Splitter->GetSashPosition(); // save width of panel
1488        m_Splitter->Unsplit(m_Panel);
1489    } else {
1490        m_Panel->Show(true);
1491        m_Gfx->Show(true);
1492        m_Splitter->SplitVertically(m_Panel, m_Gfx, m_SashPosition);
1493    }
1494}
1495
1496void MainFrm::OnViewSidePanelUpdate(wxUpdateUIEvent& ui)
1497{
1498    ui.Enable(!m_File.empty());
1499    ui.Check(m_Splitter->IsSplit());
1500}
Note: See TracBrowser for help on using the repository browser.