-
Notifications
You must be signed in to change notification settings - Fork 20
/
GpxImport.py
326 lines (269 loc) · 12.1 KB
/
GpxImport.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import os
import sys
import wx
import wx.adv as adv
import wx.lib.filebrowsebutton as filebrowse
import Utils
from Utils import logException
from GeoAnimation import GeoTrack, GpxHasTimes
import HelpSearch
class IntroPage(adv.WizardPageSimple):
def __init__(self, parent, controller):
super().__init__(parent)
self.controller = controller
border = 4
vbs = wx.BoxSizer( wx.VERTICAL )
vbs.Add( wx.StaticText(self, label = _('Import a GPX File containing coordinates for the course.\nContinue if you want to load or change the GPX course file.')),
flag=wx.ALL, border = border )
self.info = wx.TextCtrl(self, value = '\n\n\n\n\n\n', style=wx.TE_READONLY|wx.TE_MULTILINE, size=(-1,180))
vbs.Add( self.info, flag=wx.ALL|wx.EXPAND, border = border )
self.removeButton = wx.Button( self, label = _('Remove GPX Course') )
self.Bind( wx.EVT_BUTTON, self.onRemove, self.removeButton )
vbs.Add( self.removeButton, flag=wx.ALL|wx.ALIGN_RIGHT, border = border )
self.SetSizer( vbs )
def onRemove( self, event ):
if self.geoTrack:
if Utils.MessageOKCancel( self, _('Permanently Remove GPX Course?'), _('Remove GPX Course') ):
self.controller.clearData()
self.setInfo( None, None )
else:
Utils.MessageOK( self, _('No GPX Course'), _('No GPX Course') )
def setInfo( self, geoTrack, geoTrackFName ):
self.geoTrack = geoTrack
if geoTrack:
s = '\n\n'.join( [
_('Existing GPX file:'),
'{}: "{}"'.format(('Imported from'), geoTrackFName),
'{}: {}'.format(_('Number of Coords'), geoTrack.numPoints),
'{}: {:.3f} km, {:.3f} {}'.format(_('Lap Length'), geoTrack.lengthKm, geoTrack.lengthMiles, _('miles')),
'{}: {:.0f} m, {:.0f} ft'.format(_('Total Elevation Gain'), geoTrack.totalElevationGainM, geoTrack.totalElevationGainFt),
'{}: {}'.format(_('Course Type'), _('Point to Point') if getattr(geoTrack, 'isPointToPoint', False) else _('Loop'))
] )
else:
s = ''
self.removeButton.Enable( bool(geoTrack) )
self.info.ChangeValue( s )
self.GetSizer().Layout()
class FileNamePage(adv.WizardPageSimple):
def __init__(self, parent):
super().__init__(parent)
border = 4
vbs = wx.BoxSizer( wx.VERTICAL )
vbs.Add( wx.StaticText(self, label = _('Specify the GPX File containing coordinates for the course.') ),
flag=wx.ALL, border = border )
fileMask = [
'GPX Files (*.gpx)|*.gpx',
]
self.fbb = filebrowse.FileBrowseButton( self, -1, size=(450, -1),
labelText = 'GPX File:',
fileMode=wx.FD_OPEN,
fileMask='|'.join(fileMask),
startDirectory=Utils.getFileDir(),
changeCallback=self.setElevationStatus )
self.courseTypeRadioBox = wx.RadioBox( self, choices=[_('Course is a Loop'), _('Course is Point-to-Point')] )
self.elevationCheckBox = wx.CheckBox( self, label = _('Read "elevation.csv" File (in same folder as GPX file)') )
vbs.Add( self.fbb, flag=wx.ALL, border = border )
vbs.Add( self.courseTypeRadioBox, flag=wx.ALL, border = border )
vbs.Add( self.elevationCheckBox, flag=wx.ALL, border = border )
self.setElevationStatus()
self.SetSizer( vbs )
def setElevationStatus( self, evt = None ):
fileNameElevation = os.path.join( os.path.dirname(self.fbb.GetValue()), 'elevation.csv' )
exists = os.path.isfile(fileNameElevation)
self.elevationCheckBox.Enable( exists )
self.elevationCheckBox.SetValue( exists )
def setInfo( self, geoTrackFName ):
if geoTrackFName:
self.fbb.SetValue( geoTrackFName )
self.setElevationStatus()
else:
self.fbb.SetValue( '' )
self.elevationCheckBox.SetValue( False )
self.GetSizer().Layout()
def getFileName( self ):
return self.fbb.GetValue()
def getUseElevation( self ):
return self.elevationCheckBox.GetValue()
def getIsPointToPoint( self ):
return self.courseTypeRadioBox.GetSelection() == 1
class UseTimesPage(adv.WizardPageSimple):
def __init__(self, parent):
super().__init__(parent)
border = 4
vbs = wx.BoxSizer( wx.VERTICAL )
self.noTimes = wx.StaticText(self, label = _('This GPX file does not contain times.\n\nRace times will be calculated based on distance and elevation.') )
vbs.Add( self.noTimes, flag=wx.ALL, border = border )
self.useTimes = wx.CheckBox(self, label = _('Use times in the GPX file for more realistic animation') )
vbs.Add( self.useTimes, flag=wx.ALL|wx.EXPAND, border = border )
self.SetSizer( vbs )
def setInfo( self, geoTrackFName ):
hasTimes = GpxHasTimes( geoTrackFName )
self.noTimes.Show( not hasTimes )
self.useTimes.Show( hasTimes )
self.useTimes.SetValue( hasTimes )
self.GetSizer().Layout()
def getUseTimes( self ):
return self.useTimes.IsChecked()
class SummaryPage(adv.WizardPageSimple):
def __init__(self, parent):
super().__init__(parent)
self.distanceKm = None
self.distanceMiles = None
border = 4
vbs = wx.BoxSizer( wx.VERTICAL )
vbs.Add( wx.StaticText(self, label = '{}:'.format(_('Summary'))), flag=wx.ALL, border = border )
vbs.Add( wx.StaticText(self, label = ' '), flag=wx.ALL, border = border )
self.fileLabel = wx.StaticText( self, label = '{}:'.format(_('GPX File')) )
self.fileName = wx.StaticText(self )
self.numCoordsLabel = wx.StaticText( self, label = '{}:'.format(_('Number of Coords')) )
self.numCoords = wx.StaticText(self )
self.distanceLabel = wx.StaticText( self, label = '{}:'.format(_('Lap Length')) )
self.distance = wx.TextCtrl(self, style=wx.TE_READONLY)
self.totalElevationGainLabel = wx.StaticText( self, label = '{}:'.format(_('Total Elevation Gain')) )
self.totalElevationGain = wx.TextCtrl(self, style=wx.TE_READONLY)
self.courseTypeLabel = wx.StaticText( self, label = '{}:'.format(_('Course is')) )
self.courseType = wx.TextCtrl(self, style=wx.TE_READONLY)
self.setCategoryDistanceLabel = wx.StaticText( self )
self.setCategoryDistanceCheckbox = wx.CheckBox( self, label = _('Set Category Distances to GPX Lap Length') )
self.setCategoryDistanceCheckbox.SetValue( True )
fbs = wx.FlexGridSizer( rows=0, cols=2, hgap=5, vgap=2 )
fbs.AddGrowableCol( 1 )
labelAlign = wx.ALIGN_RIGHT | wx.ALIGN_CENTRE_VERTICAL
fbs.AddMany( [(self.fileLabel, 0, labelAlign), (self.fileName, 1, wx.EXPAND|wx.GROW),
(self.numCoordsLabel, 0, labelAlign), (self.numCoords, 1, wx.EXPAND|wx.GROW),
(self.distanceLabel, 0, labelAlign), (self.distance, 1, wx.EXPAND|wx.GROW),
(self.totalElevationGainLabel, 0, labelAlign),(self.totalElevationGain, 1, wx.EXPAND|wx.GROW),
(self.courseTypeLabel, 0, labelAlign),(self.courseType, 1, wx.EXPAND|wx.GROW),
(wx.StaticText(self), 0, labelAlign), (wx.StaticText(self), 1, wx.EXPAND|wx.GROW),
(self.setCategoryDistanceLabel, 0, labelAlign), (self.setCategoryDistanceCheckbox, 1, wx.EXPAND|wx.GROW),
] )
vbs.Add( fbs )
self.SetSizer(vbs)
def setInfo( self, fileName, numCoords, distance, totalElevationGain, isPointToPoint ):
self.fileName.SetLabel( fileName )
self.numCoords.SetLabel( '{}'.format(numCoords) )
self.distanceKm = distance
self.distanceMiles = distance*0.621371
self.distance.ChangeValue( '{:.3f} km, {:.3f} miles'.format(self.distanceKm, self.distanceMiles) )
self.totalElevationGainM = totalElevationGain
self.totalElevationGainFt = totalElevationGain*3.28084
self.totalElevationGain.ChangeValue( '{:.0f} m, {:.0f} ft'.format(self.totalElevationGainM, self.totalElevationGainFt) )
self.courseType.ChangeValue( _('Point to Point') if isPointToPoint else _('Loop') )
class GetGeoTrack:
def __init__( self, parent, geoTrack = None, geoTrackFName = None ):
img_filename = os.path.join( Utils.getImageFolder(), 'gps.png' )
bitmap = wx.Bitmap(img_filename) if img_filename and os.path.exists(img_filename) else wx.NullBitmap
self.parent = parent
self.wizard = adv.Wizard()
self.wizard.SetExtraStyle( adv.WIZARD_EX_HELPBUTTON )
self.wizard.Create( parent, title = _('Import GPX Course File'), bitmap = bitmap )
self.introPage = IntroPage( self.wizard, self )
self.fileNamePage = FileNamePage( self.wizard )
self.useTimesPage = UseTimesPage( self.wizard )
self.summaryPage = SummaryPage( self.wizard )
self.wizard.Bind( adv.EVT_WIZARD_PAGE_CHANGING, self.onPageChanging )
self.wizard.Bind( adv.EVT_WIZARD_CANCEL, self.onCancel )
self.wizard.Bind( adv.EVT_WIZARD_HELP,
lambda evt: HelpSearch.showHelp('Menu-DataMgmt.html#import-course-in-gpx-format') )
adv.WizardPageSimple.Chain( self.introPage, self.fileNamePage )
adv.WizardPageSimple.Chain( self.fileNamePage, self.useTimesPage )
adv.WizardPageSimple.Chain( self.useTimesPage, self.summaryPage )
self.wizard.SetPageSize( wx.Size(500,200) )
self.wizard.GetPageAreaSizer().Add( self.introPage )
self.geoTrack = geoTrack
self.geoTrackOriginal = geoTrack
self.geoTrackFName = geoTrackFName
self.geoTrackFNameOriginal = geoTrackFName
self.introPage.setInfo( geoTrack, geoTrackFName )
if geoTrackFName:
self.fileNamePage.setInfo( geoTrackFName )
def show( self ):
if self.wizard.RunWizard(self.introPage):
return (
self.geoTrack,
self.geoTrackFName,
self.summaryPage.distanceKm if self.summaryPage.setCategoryDistanceCheckbox.GetValue() else None
)
else:
return self.geoTrackOriginal, self.geoTrackFNameOriginal, None
def onCancel( self, evt ):
page = evt.GetPage()
if page == self.introPage:
pass
elif page == self.fileNamePage:
pass
elif page == self.summaryPage:
pass
def clearData( self ):
self.geoTrack = None
self.geoTrackFName = None
self.geoTrackOriginal = None
self.geoTrackFNameOriginal = None
def onPageChanging( self, evt ):
isForward = evt.GetDirection()
if not isForward:
return
page = evt.GetPage()
if page == self.introPage:
pass
elif page == self.fileNamePage:
fileName = self.fileNamePage.getFileName()
# Check for a valid file.
try:
open(fileName).close()
except IOError:
if fileName == '':
message = _('Please specify a GPX file.')
else:
message = '{}:\n\n "{}"\n\n{}'.format(
_('Cannot open file'), fileName,
_('Please check the file name and/or its read permissions.'),
)
Utils.MessageOK( self.wizard, message, title=_('File Open Error'), iconMask=wx.ICON_ERROR)
evt.Veto()
return
# Check for valid content.
geoTrack = GeoTrack()
try:
geoTrack.read( fileName, isPointToPoint = self.fileNamePage.getIsPointToPoint() )
except Exception as e:
logException( e, sys.exc_info() )
Utils.MessageOK( self.wizard, '{}: {}\n({})'.format(_('Read Error'), _('Is this GPX file properly formatted?'), e),
title='Read Error', iconMask=wx.ICON_ERROR)
evt.Veto()
return
# Check for too few points.
if geoTrack.numPoints < 2:
Utils.MessageOK( self.wizard,
'{}: {}'.format(_('Import Failed'), _('GPX file contains fewer than two points.')),
title=_('File Format Error'),
iconMask=wx.ICON_ERROR)
evt.Veto()
return
if self.fileNamePage.getUseElevation():
fileNameElevation = os.path.join( os.path.dirname(fileName), 'elevation.csv' )
try:
open(fileNameElevation).close()
except IOError as e:
logException( e, sys.exc_info() )
message = '{}: {}\n\n "{}"\n\n{}'.format(
_('Cannot Open Elevation File'), e, fileNameElevation,
_('Please check the file name and/or its read permissions.'),
)
Utils.MessageOK( self.wizard, message, title=_('File Open Error'), iconMask=wx.ICON_ERROR)
else:
try:
geoTrack.readElevation( fileNameElevation )
except Exception as e:
logException( e, sys.exc_info() )
message = '{}: {}\n\n "{}"'.format(_('Elevation File Error'), e, fileNameElevation )
Utils.MessageOK( self.wizard, message, title=_('File Read Error'), iconMask=wx.ICON_ERROR )
self.geoTrackFName = fileName
self.geoTrack = geoTrack
self.summaryPage.setInfo( self.geoTrackFName, self.geoTrack.numPoints,
self.geoTrack.lengthKm, self.geoTrack.totalElevationGainM,
getattr( self.geoTrack, 'isPointToPoint', False) )
self.useTimesPage.setInfo( self.geoTrackFName )
elif page == self.useTimesPage:
if self.useTimesPage.getUseTimes():
self.geoTrack.read( self.geoTrackFName, True )