profile.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  1. """
  2. @package profile
  3. Profile analysis of GRASS raster maps and images.
  4. Uses PyPlot (wx.lib.plot.py)
  5. Classes:
  6. - ProfileFrame
  7. - SetRasterDialog
  8. - TextDialog
  9. - OptDialog
  10. COPYRIGHT: (C) 2007-2008 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Michael Barton
  15. Various updates: Martin Landa <landa.martin gmail.com>
  16. """
  17. import os
  18. import sys
  19. import math
  20. import wx
  21. import wx.lib.colourselect as csel
  22. try:
  23. import numpy
  24. import wx.lib.plot as plot
  25. except ImportError:
  26. msg= """
  27. This module requires the NumPy module, which could not be
  28. imported. It probably is not installed (it's not part of the
  29. standard Python distribution). See the Numeric Python site
  30. (http://numpy.scipy.org) for information on downloading source or
  31. binaries."""
  32. print >> sys.stderr, "profile.py: " + msg
  33. import globalvar
  34. try:
  35. import subprocess
  36. except:
  37. CompatPath = os.path.join(globalvar.ETCWXDIR)
  38. sys.path.append(CompatPath)
  39. from compat import subprocess as subprocess
  40. import render
  41. import menuform
  42. import disp_print
  43. import gselect
  44. import gcmd
  45. import toolbars
  46. from debug import Debug as Debug
  47. from icon import Icons as Icons
  48. from preferences import globalSettings as UserSettings
  49. from grass.script import core as grass
  50. class ProfileFrame(wx.Frame):
  51. """
  52. Mainframe for displaying profile of raster map. Uses wx.lib.plot.
  53. """
  54. def __init__(self, parent=None, id=wx.ID_ANY, title=_("Profile Analysis"),
  55. rasterList=[],
  56. pos=wx.DefaultPosition, size=wx.DefaultSize,
  57. style=wx.DEFAULT_FRAME_STYLE):
  58. self.parent = parent # MapFrame
  59. self.mapwin = self.parent.MapWindow
  60. self.Map = render.Map() # instance of render.Map to be associated with display
  61. self.pstyledict = { 'solid' : wx.SOLID,
  62. 'dot' : wx.DOT,
  63. 'long-dash' : wx.LONG_DASH,
  64. 'short-dash' : wx.SHORT_DASH,
  65. 'dot-dash' : wx.DOT_DASH }
  66. self.ptfilldict = { 'transparent' : wx.TRANSPARENT,
  67. 'solid' : wx.SOLID }
  68. wx.Frame.__init__(self, parent, id, title, pos, size, style)
  69. #
  70. # Icon
  71. #
  72. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  73. #
  74. # Add toolbar
  75. #
  76. self.toolbar = toolbars.ProfileToolbar(parent=self, tbframe=self).GetToolbar()
  77. self.SetToolBar(self.toolbar)
  78. #
  79. # Set the size & cursor
  80. #
  81. self.SetClientSize(size)
  82. #
  83. # Add statusbar
  84. #
  85. self.statusbar = self.CreateStatusBar(number=2, style=0)
  86. self.statusbar.SetStatusWidths([-2, -1])
  87. #
  88. # Define canvas
  89. #
  90. # plot canvas settings
  91. self.client = plot.PlotCanvas(self)
  92. #define the function for drawing pointLabels
  93. self.client.SetPointLabelFunc(self.DrawPointLabel)
  94. # Create mouse event for showing cursor coords in status bar
  95. self.client.canvas.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
  96. # Show closest point when enabled
  97. self.client.canvas.Bind(wx.EVT_MOTION, self.OnMotion)
  98. #
  99. # Init variables
  100. #
  101. # 0 -> default raster map to profile
  102. # 1, 2 -> optional raster map to profile
  103. # units -> map data units (used for y axis legend)
  104. self.raster = {}
  105. for idx in (0, 1, 2):
  106. self.raster[idx] = {}
  107. self.raster[idx]['name'] = ''
  108. self.raster[idx]['units'] = ''
  109. self.raster[idx]['plegend'] = ''
  110. # list of distance,value pairs for plotting profile
  111. self.raster[idx]['datalist'] = []
  112. # first (default) profile line
  113. self.raster[idx]['pline'] = None
  114. self.raster[idx]['prop'] = UserSettings.Get(group='profile', key='raster' + str(idx))
  115. # changing color string to tuple
  116. colstr = str(self.raster[idx]['prop']['pcolor'])
  117. self.raster[idx]['prop']['pcolor'] = tuple(int(colval) for colval in colstr.strip('()').split(','))
  118. # set raster map name (if given)
  119. for idx in range(len(rasterList)):
  120. self.raster[idx]['name'] = rasterList[idx]
  121. # string of coordinates for r.profile
  122. self.coordstr = ''
  123. # segment endpoint list
  124. self.seglist = []
  125. # list of things to plot
  126. self.plotlist = []
  127. # segment endpoints data
  128. self.ppoints = ''
  129. # plot draw object
  130. self.profile = None
  131. # total transect length
  132. self.transect_length = 0.0
  133. # title of window
  134. self.ptitle = _('Profile of')
  135. # determine units (axis labels)
  136. if self.parent.Map.projinfo['units'] != '':
  137. self.xlabel = _('Distance (%s)') % self.parent.Map.projinfo['units']
  138. else:
  139. self.xlabel = _("Distance along transect")
  140. self.ylabel = _("Cell values")
  141. self.properties = {}
  142. self.properties['font'] = {}
  143. self.properties['font']['prop'] = UserSettings.Get(group='profile', key='font')
  144. self.properties['font']['wxfont'] = wx.Font(11, wx.FONTFAMILY_SWISS,
  145. wx.FONTSTYLE_NORMAL,
  146. wx.FONTWEIGHT_NORMAL)
  147. self.properties['marker'] = UserSettings.Get(group='profile', key='marker')
  148. # changing color string to tuple
  149. colstr = str(self.properties['marker']['color'])
  150. self.properties['marker']['color'] = tuple(int(colval) for colval in colstr.strip('()').split(','))
  151. self.properties['grid'] = UserSettings.Get(group='profile', key='grid')
  152. # changing color string to tuple
  153. colstr = str(self.properties['grid']['color'])
  154. self.properties['grid']['color'] = tuple(int(colval) for colval in colstr.strip('()').split(','))
  155. self.properties['x-axis'] = {}
  156. self.properties['x-axis']['prop'] = UserSettings.Get(group='profile', key='x-axis')
  157. self.properties['x-axis']['axis'] = None
  158. self.properties['y-axis'] = {}
  159. self.properties['y-axis']['prop'] = UserSettings.Get(group='profile', key='y-axis')
  160. self.properties['y-axis']['axis'] = None
  161. self.properties['legend'] = UserSettings.Get(group='profile', key='legend')
  162. # zooming disabled
  163. self.zoom = False
  164. # draging disabled
  165. self.drag = False
  166. # vertical and horizontal scrollbars
  167. self.client.SetShowScrollbars(True)
  168. # x and y axis set to normal (non-log)
  169. self.client.setLogScale((False, False))
  170. if self.properties['x-axis']['prop']['type']:
  171. self.client.SetXSpec(self.properties['x-axis']['prop']['type'])
  172. else:
  173. self.client.SetXSpec('auto')
  174. if self.properties['y-axis']['prop']['type']:
  175. self.client.SetYSpec(self.properties['y-axis']['prop']['type'])
  176. else:
  177. self.client.SetYSpec('auto')
  178. #
  179. # Bind various events
  180. #
  181. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  182. self.CentreOnScreen()
  183. def OnDrawTransect(self, event):
  184. """
  185. Draws transect to profile in map display
  186. """
  187. self.mapwin.polycoords = []
  188. self.seglist = []
  189. self.mapwin.ClearLines(self.mapwin.pdc)
  190. self.ppoints = ''
  191. self.parent.SetFocus()
  192. self.parent.Raise()
  193. self.mapwin.mouse['use'] = 'profile'
  194. self.mapwin.mouse['box'] = 'line'
  195. self.mapwin.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  196. self.mapwin.polypen = wx.Pen(colour='dark green', width=2, style=wx.SHORT_DASH)
  197. self.mapwin.SetCursor(self.Parent.cursors["cross"])
  198. def OnSelectRaster(self, event):
  199. """
  200. Select raster map(s) to profile
  201. """
  202. dlg = SetRasterDialog(parent=self)
  203. if dlg.ShowModal() == wx.ID_OK:
  204. for r in self.raster.keys():
  205. self.raster[r]['name'] = dlg.raster[r]['name']
  206. # plot profile
  207. if self.raster[0]['name'] and len(self.mapwin.polycoords) > 0:
  208. self.OnCreateProfile(event=None)
  209. dlg.Destroy()
  210. def SetRaster(self):
  211. """
  212. Create coordinate string for profiling. Create segment list for
  213. transect segment markers.
  214. """
  215. #
  216. # create list of coordinate points for r.profile
  217. #
  218. dist = 0
  219. cumdist = 0
  220. self.coordstr = ''
  221. lasteast = lastnorth = None
  222. if len(self.mapwin.polycoords) > 0:
  223. for point in self.mapwin.polycoords:
  224. # build string of coordinate points for r.profile
  225. if self.coordstr == '':
  226. self.coordstr = '%d,%d' % (point[0], point[1])
  227. else:
  228. self.coordstr = '%s,%d,%d' % (self.coordstr, point[0], point[1])
  229. if self.raster[0]['name'] == '':
  230. return
  231. # title of window
  232. self.ptitle = _('Profile of')
  233. #
  234. # create list of coordinates for transect segment markers
  235. #
  236. if len(self.mapwin.polycoords) > 0:
  237. for point in self.mapwin.polycoords:
  238. # get value of raster cell at coordinate point
  239. ret = gcmd.RunCommand('r.what',
  240. parent = self,
  241. read = True,
  242. input = self.raster[0]['name'],
  243. east_north = '%d,%d' % (point[0],point[1]))
  244. val = ret.splitlines()[0].split('|')[3]
  245. # calculate distance between coordinate points
  246. if lasteast and lastnorth:
  247. dist = math.sqrt(math.pow((lasteast-point[0]),2) + math.pow((lastnorth-point[1]),2))
  248. cumdist += dist
  249. #store total transect length
  250. self.transect_length = cumdist
  251. # build a list of distance,value pairs for each segment of transect
  252. self.seglist.append((cumdist,val))
  253. lasteast = point[0]
  254. lastnorth = point[1]
  255. # delete first and last segment point
  256. try:
  257. self.seglist.pop(0)
  258. self.seglist.pop()
  259. except:
  260. pass
  261. #
  262. # create datalist for each raster map
  263. #
  264. for r in self.raster.itervalues():
  265. if r['name'] == '':
  266. continue
  267. r['datalist'] = self.CreateDatalist(r['name'], self.coordstr)
  268. r['plegend'] = _('Profile of %s') % r['name']
  269. ret = gcmd.RunCommand('r.info',
  270. parent = self,
  271. read = True,
  272. quiet = True,
  273. flags = 'u',
  274. map = r['name'])
  275. if ret:
  276. r['units'] = ret.splitlines()[0].split('=')[1]
  277. # update title
  278. self.ptitle += ' %s and' % r['name']
  279. self.ptitle = self.ptitle.rstrip('and')
  280. #
  281. # set ylabel to match units if they exist
  282. #
  283. self.ylabel = ''
  284. i = 0
  285. for r in self.raster.itervalues():
  286. if r['name'] == '':
  287. continue
  288. if r['units'] != '':
  289. self.ylabel = '%s (%d),' % (r['units'], i)
  290. i += 1
  291. if self.ylabel == '':
  292. self.ylabel = _('Raster values')
  293. else:
  294. self.ylabel = self.ylabel.rstrip(',')
  295. def SetGraphStyle(self):
  296. """
  297. Set plot and text options
  298. """
  299. self.client.SetFont(self.properties['font']['wxfont'])
  300. self.client.SetFontSizeTitle(self.properties['font']['prop']['titleSize'])
  301. self.client.SetFontSizeAxis(self.properties['font']['prop']['axisSize'])
  302. self.client.SetEnableZoom(self.zoom)
  303. self.client.SetEnableDrag(self.drag)
  304. #
  305. # axis settings
  306. #
  307. if self.properties['x-axis']['prop']['type'] == 'custom':
  308. self.client.SetXSpec('min')
  309. else:
  310. self.client.SetXSpec(self.properties['x-axis']['prop']['type'])
  311. if self.properties['y-axis']['prop']['type'] == 'custom':
  312. self.client.SetYSpec('min')
  313. else:
  314. self.client.SetYSpec(self.properties['y-axis']['prop']['type'])
  315. if self.properties['x-axis']['prop']['type'] == 'custom' and \
  316. self.properties['x-axis']['prop']['min'] < self.properties['x-axis']['prop']['max']:
  317. self.properties['x-axis']['axis'] = (self.properties['x-axis']['prop']['min'],
  318. self.properties['x-axis']['prop']['max'])
  319. else:
  320. self.properties['x-axis']['axis'] = None
  321. if self.properties['y-axis']['prop']['type'] == 'custom' and \
  322. self.properties['y-axis']['prop']['min'] < self.properties['y-axis']['prop']['max']:
  323. self.properties['y-axis']['axis'] = (self.properties['y-axis']['prop']['min'],
  324. self.properties['y-axis']['prop']['max'])
  325. else:
  326. self.properties['y-axis']['axis'] = None
  327. self.client.SetEnableGrid(self.properties['grid']['enabled'])
  328. self.client.SetGridColour(wx.Color(self.properties['grid']['color'][0],
  329. self.properties['grid']['color'][1],
  330. self.properties['grid']['color'][2],
  331. 255))
  332. self.client.SetFontSizeLegend(self.properties['font']['prop']['legendSize'])
  333. self.client.SetEnableLegend(self.properties['legend']['enabled'])
  334. if self.properties['x-axis']['prop']['log'] == True:
  335. self.properties['x-axis']['axis'] = None
  336. self.client.SetXSpec('min')
  337. if self.properties['y-axis']['prop']['log'] == True:
  338. self.properties['y-axis']['axis'] = None
  339. self.client.SetYSpec('min')
  340. self.client.setLogScale((self.properties['x-axis']['prop']['log'],
  341. self.properties['y-axis']['prop']['log']))
  342. # self.client.SetPointLabelFunc(self.DrawPointLabel())
  343. def CreateDatalist(self, raster, coords):
  344. """
  345. Build a list of distance, value pairs for points along transect
  346. """
  347. datalist = []
  348. import subprocess
  349. # keep total number of transect points to 500 or less to avoid
  350. # freezing with large, high resolution maps
  351. region = grass.region()
  352. curr_res = min(float(region['nsres']),float(region['ewres']))
  353. transect_rec = 0
  354. print "transect length = "+str(self.transect_length)
  355. print "current resolution = "+str(curr_res)
  356. if self.transect_length / curr_res > 500:
  357. transect_res = self.transect_length / 500
  358. else: transect_res = curr_res
  359. print "transect resolution = "+str(transect_res)
  360. try:
  361. ret = gcmd.RunCommand("r.profile",
  362. input=raster,
  363. profile=coords,
  364. res=transect_res,
  365. null="nan",
  366. quiet=True,
  367. read = True)
  368. if not ret:
  369. return dataset
  370. for line in ret.splitlines():
  371. dist, elev = line.split(' ')
  372. if elev != 'nan':
  373. datalist.append((dist,elev))
  374. return datalist
  375. except gcmd.CmdError, e:
  376. print e
  377. return None
  378. def OnCreateProfile(self, event):
  379. """
  380. Main routine for creating a profile. Uses r.profile to create a list
  381. of distance,cell value pairs. This is passed to plot to create a
  382. line graph of the profile. If the profile transect is in multiple
  383. segments, these are drawn as points. Profile transect is drawn, using
  384. methods in mapdisp.py
  385. """
  386. if len(self.mapwin.polycoords) == 0 or self.raster[0]['name'] == '':
  387. dlg = wx.MessageDialog(parent=self,
  388. message=_('You must draw a transect to profile in the map display window.'),
  389. caption=_('Nothing to profile'),
  390. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  391. dlg.ShowModal()
  392. dlg.Destroy()
  393. return
  394. self.mapwin.SetCursor(self.parent.cursors["default"])
  395. self.SetCursor(self.parent.cursors["default"])
  396. self.SetGraphStyle()
  397. self.SetRaster()
  398. self.DrawPlot()
  399. # reset transect
  400. self.mapwin.mouse['begin'] = self.mapwin.mouse['end'] = (0.0,0.0)
  401. self.mapwin.mouse['use'] = 'pointer'
  402. self.mapwin.mouse['box'] = 'point'
  403. def DrawPlot(self):
  404. """
  405. Draw line and point plot from transect datalist and
  406. transect segment endpoint coordinates.
  407. """
  408. # graph the distance, value pairs for the transect
  409. self.plotlist = []
  410. if len(self.seglist) > 0 :
  411. self.ppoints = plot.PolyMarker(self.seglist,
  412. legend=' ' + self.properties['marker']['legend'],
  413. colour=wx.Color(self.properties['marker']['color'][0],
  414. self.properties['marker']['color'][1],
  415. self.properties['marker']['color'][2],
  416. 255),
  417. size=self.properties['marker']['size'],
  418. fillstyle=self.ptfilldict[self.properties['marker']['fill']],
  419. marker=self.properties['marker']['type'])
  420. self.plotlist.append(self.ppoints)
  421. for r in self.raster.itervalues():
  422. if len(r['datalist']) > 0:
  423. col = wx.Color(r['prop']['pcolor'][0],
  424. r['prop']['pcolor'][1],
  425. r['prop']['pcolor'][2],
  426. 255)
  427. r['pline'] = plot.PolyLine(r['datalist'],
  428. colour=col,
  429. width=r['prop']['pwidth'],
  430. style=self.pstyledict[r['prop']['pstyle']],
  431. legend=r['plegend'])
  432. self.plotlist.append(r['pline'])
  433. self.profile = plot.PlotGraphics(self.plotlist,
  434. self.ptitle,
  435. self.xlabel,
  436. self.ylabel)
  437. if self.properties['x-axis']['prop']['type'] == 'custom':
  438. self.client.SetXSpec('min')
  439. else:
  440. self.client.SetXSpec(self.properties['x-axis']['prop']['type'])
  441. if self.properties['y-axis']['prop']['type'] == 'custom':
  442. self.client.SetYSpec('min')
  443. else:
  444. self.client.SetYSpec(self.properties['y-axis']['prop']['type'])
  445. self.client.Draw(self.profile, self.properties['x-axis']['axis'],
  446. self.properties['y-axis']['axis'])
  447. def OnZoom(self, event):
  448. """
  449. Enable zooming and disable dragging
  450. """
  451. self.zoom = True
  452. self.drag = False
  453. self.client.SetEnableZoom(self.zoom)
  454. self.client.SetEnableDrag(self.drag)
  455. def OnDrag(self, event):
  456. """
  457. Enable dragging and disable zooming
  458. """
  459. self.zoom = False
  460. self.drag = True
  461. self.client.SetEnableDrag(self.drag)
  462. self.client.SetEnableZoom(self.zoom)
  463. def OnRedraw(self, event):
  464. """
  465. Redraw the profile window. Unzoom to original size
  466. """
  467. self.client.Reset()
  468. self.client.Redraw()
  469. def Update(self):
  470. """
  471. Update profile after changing options
  472. """
  473. self.SetGraphStyle()
  474. self.DrawPlot()
  475. def OnErase(self, event):
  476. """
  477. Erase the profile window
  478. """
  479. self.client.Clear()
  480. self.mapwin.ClearLines(self.mapwin.pdc)
  481. self.mapwin.ClearLines(self.mapwin.pdcTmp)
  482. self.mapwin.polycoords = []
  483. self.mapwin.Refresh()
  484. # try:
  485. # self.mapwin.pdc.ClearId(self.mapwin.lineid)
  486. # self.mapwin.pdc.ClearId(self.mapwin.plineid)
  487. # self.mapwin.Refresh()
  488. # except:
  489. # pass
  490. def SaveToFile(self, event):
  491. """
  492. Save profile to graphics file
  493. """
  494. self.client.SaveFile()
  495. def DrawPointLabel(self, dc, mDataDict):
  496. """!This is the fuction that defines how the pointLabels are plotted
  497. dc - DC that will be passed
  498. mDataDict - Dictionary of data that you want to use for the pointLabel
  499. As an example I have decided I want a box at the curve point
  500. with some text information about the curve plotted below.
  501. Any wxDC method can be used.
  502. """
  503. # ----------
  504. dc.SetPen(wx.Pen(wx.BLACK))
  505. dc.SetBrush(wx.Brush( wx.BLACK, wx.SOLID ) )
  506. sx, sy = mDataDict["scaledXY"] #scaled x,y of closest point
  507. dc.DrawRectangle( sx-5,sy-5, 10, 10) #10by10 square centered on point
  508. px,py = mDataDict["pointXY"]
  509. cNum = mDataDict["curveNum"]
  510. pntIn = mDataDict["pIndex"]
  511. legend = mDataDict["legend"]
  512. #make a string to display
  513. s = "Crv# %i, '%s', Pt. (%.2f,%.2f), PtInd %i" %(cNum, legend, px, py, pntIn)
  514. dc.DrawText(s, sx , sy+1)
  515. # -----------
  516. def OnMouseLeftDown(self,event):
  517. s= "Left Mouse Down at Point: (%.4f, %.4f)" % self.client._getXY(event)
  518. self.SetStatusText(s)
  519. event.Skip() #allows plotCanvas OnMouseLeftDown to be called
  520. def OnMotion(self, event):
  521. # indicate when mouse is outside the plot area
  522. if self.client.OnLeave(event): print 'out of area'
  523. #show closest point (when enbled)
  524. if self.client.GetEnablePointLabel() == True:
  525. #make up dict with info for the pointLabel
  526. #I've decided to mark the closest point on the closest curve
  527. dlst= self.client.GetClosetPoint( self.client._getXY(event), pointScaled= True)
  528. if dlst != []: #returns [] if none
  529. curveNum, legend, pIndex, pointXY, scaledXY, distance = dlst
  530. #make up dictionary to pass to my user function (see DrawPointLabel)
  531. mDataDict= {"curveNum":curveNum, "legend":legend, "pIndex":pIndex,\
  532. "pointXY":pointXY, "scaledXY":scaledXY}
  533. #pass dict to update the pointLabel
  534. self.client.UpdatePointLabel(mDataDict)
  535. event.Skip() #go to next handler
  536. def ProfileOptionsMenu(self, event):
  537. """
  538. Popup menu for profile and text options
  539. """
  540. point = wx.GetMousePosition()
  541. popt = wx.Menu()
  542. # Add items to the menu
  543. settext = wx.MenuItem(popt, -1, 'Profile text settings')
  544. popt.AppendItem(settext)
  545. self.Bind(wx.EVT_MENU, self.PText, settext)
  546. setgrid = wx.MenuItem(popt, -1, 'Profile plot settings')
  547. popt.AppendItem(setgrid)
  548. self.Bind(wx.EVT_MENU, self.POptions, setgrid)
  549. # Popup the menu. If an item is selected then its handler
  550. # will be called before PopupMenu returns.
  551. self.PopupMenu(popt)
  552. popt.Destroy()
  553. def NotFunctional(self):
  554. """
  555. Creates a 'not functional' message dialog
  556. """
  557. dlg = wx.MessageDialog(self, 'This feature is not yet functional',
  558. 'Under Construction', wx.OK | wx.ICON_INFORMATION)
  559. dlg.ShowModal()
  560. dlg.Destroy()
  561. def PText(self, event):
  562. """
  563. Set custom text values for profile
  564. title and axis labels.
  565. """
  566. dlg = TextDialog(parent=self, id=wx.ID_ANY, title=_('Profile text settings'))
  567. if dlg.ShowModal() == wx.ID_OK:
  568. self.ptitle = dlg.ptitle
  569. self.xlabel = dlg.xlabel
  570. self.ylabel = dlg.ylabel
  571. dlg.UpdateSettings()
  572. self.client.SetFont(self.properties['font']['wxfont'])
  573. self.client.SetFontSizeTitle(self.properties['font']['prop']['titleSize'])
  574. self.client.SetFontSizeAxis(self.properties['font']['prop']['axisSize'])
  575. if self.profile:
  576. self.profile.setTitle(dlg.ptitle)
  577. self.profile.setXLabel(dlg.xlabel)
  578. self.profile.setYLabel(dlg.ylabel)
  579. dlg.Destroy()
  580. self.OnRedraw(event=None)
  581. def POptions(self, event):
  582. """
  583. Set various profile options, including: line width, color, style;
  584. marker size, color, fill, and style; grid and legend options.
  585. Calls OptDialog class.
  586. """
  587. dlg = OptDialog(parent=self, id=wx.ID_ANY, title=_('Profile settings'))
  588. btnval = dlg.ShowModal()
  589. if btnval == wx.ID_SAVE:
  590. dlg.UpdateSettings()
  591. self.SetGraphStyle()
  592. dlg.Destroy()
  593. elif btnval == wx.ID_CANCEL:
  594. dlg.Destroy()
  595. def PrintMenu(self, event):
  596. """
  597. Print options and output menu
  598. """
  599. point = wx.GetMousePosition()
  600. printmenu = wx.Menu()
  601. # Add items to the menu
  602. setup = wx.MenuItem(printmenu, -1,'Page setup')
  603. printmenu.AppendItem(setup)
  604. self.Bind(wx.EVT_MENU, self.OnPageSetup, setup)
  605. preview = wx.MenuItem(printmenu, -1,'Print preview')
  606. printmenu.AppendItem(preview)
  607. self.Bind(wx.EVT_MENU, self.OnPrintPreview, preview)
  608. doprint = wx.MenuItem(printmenu, -1,'Print display')
  609. printmenu.AppendItem(doprint)
  610. self.Bind(wx.EVT_MENU, self.OnDoPrint, doprint)
  611. # Popup the menu. If an item is selected then its handler
  612. # will be called before PopupMenu returns.
  613. self.PopupMenu(printmenu)
  614. printmenu.Destroy()
  615. def OnPageSetup(self, event):
  616. self.client.PageSetup()
  617. def OnPrintPreview(self, event):
  618. self.client.PrintPreview()
  619. def OnDoPrint(self, event):
  620. self.client.Printout()
  621. def OnQuit(self, event):
  622. self.Close(True)
  623. def OnCloseWindow(self, event):
  624. """
  625. Close profile window and clean up
  626. """
  627. self.mapwin.ClearLines()
  628. self.mapwin.mouse['begin'] = self.mapwin.mouse['end'] = (0.0, 0.0)
  629. self.mapwin.mouse['use'] = 'pointer'
  630. self.mapwin.mouse['box'] = 'point'
  631. self.mapwin.polycoords = []
  632. self.mapwin.SetCursor(self.Parent.cursors["default"])
  633. self.mapwin.UpdateMap(render=False, renderVector=False)
  634. self.Destroy()
  635. class SetRasterDialog(wx.Dialog):
  636. def __init__(self, parent, id=wx.ID_ANY, title=_("Select raster map to profile"),
  637. pos=wx.DefaultPosition, size=wx.DefaultSize,
  638. style=wx.DEFAULT_DIALOG_STYLE):
  639. """
  640. Dialog to select raster maps to profile.
  641. """
  642. wx.Dialog.__init__(self, parent, id, title, pos, size, style)
  643. self.parent = parent
  644. self.coordstr = self.parent.coordstr
  645. # if self.coordstr == '':
  646. # dlg = wx.MessageDialog(parent=self,
  647. # message=_('You must draw a transect to profile in the map display window.'),
  648. # caption=_('Nothing to profile'),
  649. # style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  650. # dlg.ShowModal()
  651. # dlg.Destroy()
  652. # self.Close(True)
  653. # return
  654. self.raster = { 0 : { 'name' : self.parent.raster[0]['name'],
  655. 'id' : None },
  656. 1 : { 'name' : self.parent.raster[1]['name'],
  657. 'id' : None },
  658. 2 : { 'name' : self.parent.raster[2]['name'],
  659. 'id' : None }
  660. }
  661. sizer = wx.BoxSizer(wx.VERTICAL)
  662. box = wx.GridBagSizer (hgap=3, vgap=3)
  663. i = 0
  664. for txt in [_("Select raster map 1 (required):"),
  665. _("Select raster map 2 (optional):"),
  666. _("Select raster map 3 (optional):")]:
  667. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=txt)
  668. box.Add(item=label,
  669. flag=wx.ALIGN_CENTER_VERTICAL, pos=(i, 0))
  670. selection = gselect.Select(self, id=wx.ID_ANY,
  671. size=globalvar.DIALOG_GSELECT_SIZE,
  672. type='cell')
  673. selection.SetValue(str(self.raster[i]['name']))
  674. self.raster[i]['id'] = selection.GetChildren()[0].GetId()
  675. selection.Bind(wx.EVT_TEXT, self.OnSelection)
  676. box.Add(item=selection, pos=(i, 1))
  677. i += 1
  678. sizer.Add(item=box, proportion=0,
  679. flag=wx.ALL, border=10)
  680. line = wx.StaticLine(parent=self, id=wx.ID_ANY, size=(20, -1), style=wx.LI_HORIZONTAL)
  681. sizer.Add(item=line, proportion=0,
  682. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border=5)
  683. btnsizer = wx.StdDialogButtonSizer()
  684. btn = wx.Button(self, wx.ID_OK)
  685. btn.SetDefault()
  686. btnsizer.AddButton(btn)
  687. btn = wx.Button(self, wx.ID_CANCEL)
  688. btnsizer.AddButton(btn)
  689. btnsizer.Realize()
  690. sizer.Add(item=btnsizer, proportion=0, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  691. self.SetSizer(sizer)
  692. sizer.Fit(self)
  693. def OnSelection(self, event):
  694. id = event.GetId()
  695. for r in self.raster.itervalues():
  696. if r['id'] == id:
  697. r['name'] = event.GetString()
  698. break
  699. class TextDialog(wx.Dialog):
  700. def __init__(self, parent, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize,
  701. style=wx.DEFAULT_DIALOG_STYLE):
  702. wx.Dialog.__init__(self, parent, id, title, pos, size, style)
  703. """
  704. Dialog to set profile text options: font, title
  705. and font size, axis labels and font size
  706. """
  707. #
  708. # initialize variables
  709. #
  710. # combo box entry lists
  711. self.ffamilydict = { 'default' : wx.FONTFAMILY_DEFAULT,
  712. 'decorative' : wx.FONTFAMILY_DECORATIVE,
  713. 'roman' : wx.FONTFAMILY_ROMAN,
  714. 'script' : wx.FONTFAMILY_SCRIPT,
  715. 'swiss' : wx.FONTFAMILY_SWISS,
  716. 'modern' : wx.FONTFAMILY_MODERN,
  717. 'teletype' : wx.FONTFAMILY_TELETYPE }
  718. self.fstyledict = { 'normal' : wx.FONTSTYLE_NORMAL,
  719. 'slant' : wx.FONTSTYLE_SLANT,
  720. 'italic' : wx.FONTSTYLE_ITALIC }
  721. self.fwtdict = { 'normal' : wx.FONTWEIGHT_NORMAL,
  722. 'light' : wx.FONTWEIGHT_LIGHT,
  723. 'bold' : wx.FONTWEIGHT_BOLD }
  724. self.parent = parent
  725. self.ptitle = self.parent.ptitle
  726. self.xlabel = self.parent.xlabel
  727. self.ylabel = self.parent.ylabel
  728. self.properties = self.parent.properties # read-only
  729. # font size
  730. self.fontfamily = self.properties['font']['wxfont'].GetFamily()
  731. self.fontstyle = self.properties['font']['wxfont'].GetStyle()
  732. self.fontweight = self.properties['font']['wxfont'].GetWeight()
  733. self._do_layout()
  734. def _do_layout(self):
  735. """!Do layout"""
  736. # dialog layout
  737. sizer = wx.BoxSizer(wx.VERTICAL)
  738. box = wx.StaticBox(parent=self, id=wx.ID_ANY,
  739. label=" %s " % _("Text settings"))
  740. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  741. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  742. #
  743. # profile title
  744. #
  745. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Profile title:"))
  746. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
  747. self.ptitleentry = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(200,-1))
  748. # self.ptitleentry.SetFont(self.font)
  749. self.ptitleentry.SetValue(self.ptitle)
  750. gridSizer.Add(item=self.ptitleentry, pos=(0, 1))
  751. #
  752. # title font
  753. #
  754. tlabel = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Title font size (pts):"))
  755. gridSizer.Add(item=tlabel, flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
  756. self.ptitlesize = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="", pos=(30, 50),
  757. size=(50,-1), style=wx.SP_ARROW_KEYS)
  758. self.ptitlesize.SetRange(5,100)
  759. self.ptitlesize.SetValue(int(self.properties['font']['prop']['titleSize']))
  760. gridSizer.Add(item=self.ptitlesize, pos=(1, 1))
  761. #
  762. # x-axis label
  763. #
  764. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=("X-axis label:"))
  765. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(2, 0))
  766. self.xlabelentry = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(200,-1))
  767. # self.xlabelentry.SetFont(self.font)
  768. self.xlabelentry.SetValue(self.xlabel)
  769. gridSizer.Add(item=self.xlabelentry, pos=(2, 1))
  770. #
  771. # y-axis label
  772. #
  773. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Y-axis label:"))
  774. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(3, 0))
  775. self.ylabelentry = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(200,-1))
  776. # self.ylabelentry.SetFont(self.font)
  777. self.ylabelentry.SetValue(self.ylabel)
  778. gridSizer.Add(item=self.ylabelentry, pos=(3, 1))
  779. #
  780. # font size
  781. #
  782. llabel = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Label font size (pts):"))
  783. gridSizer.Add(item=llabel, flag=wx.ALIGN_CENTER_VERTICAL, pos=(4, 0))
  784. self.axislabelsize = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="", pos=(30, 50),
  785. size=(50, -1), style=wx.SP_ARROW_KEYS)
  786. self.axislabelsize.SetRange(5, 100)
  787. self.axislabelsize.SetValue(int(self.properties['font']['prop']['axisSize']))
  788. gridSizer.Add(item=self.axislabelsize, pos=(4,1))
  789. boxSizer.Add(item=gridSizer)
  790. sizer.Add(item=boxSizer, flag=wx.ALL | wx.EXPAND, border=3)
  791. #
  792. # font settings
  793. #
  794. box = wx.StaticBox(parent=self, id=wx.ID_ANY,
  795. label=" %s " % _("Font settings"))
  796. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  797. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  798. gridSizer.AddGrowableCol(1)
  799. #
  800. # font family
  801. #
  802. label1 = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Font family:"))
  803. gridSizer.Add(item=label1, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
  804. self.ffamilycb = wx.ComboBox(parent=self, id=wx.ID_ANY, size=(200, -1),
  805. choices=self.ffamilydict.keys(), style=wx.CB_DROPDOWN)
  806. self.ffamilycb.SetStringSelection('swiss')
  807. for item in self.ffamilydict.items():
  808. if self.fontfamily == item[1]:
  809. self.ffamilycb.SetStringSelection(item[0])
  810. break
  811. gridSizer.Add(item=self.ffamilycb, pos=(0, 1), flag=wx.ALIGN_RIGHT)
  812. #
  813. # font style
  814. #
  815. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Style:"))
  816. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
  817. self.fstylecb = wx.ComboBox(parent=self, id=wx.ID_ANY, size=(200, -1),
  818. choices=self.fstyledict.keys(), style=wx.CB_DROPDOWN)
  819. self.fstylecb.SetStringSelection('normal')
  820. for item in self.fstyledict.items():
  821. if self.fontstyle == item[1]:
  822. self.fstylecb.SetStringSelection(item[0])
  823. break
  824. gridSizer.Add(item=self.fstylecb, pos=(1, 1), flag=wx.ALIGN_RIGHT)
  825. #
  826. # font weight
  827. #
  828. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Weight:"))
  829. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(2, 0))
  830. self.fwtcb = wx.ComboBox(parent=self, size=(200, -1),
  831. choices=self.fwtdict.keys(), style=wx.CB_DROPDOWN)
  832. self.fwtcb.SetStringSelection('normal')
  833. for item in self.fwtdict.items():
  834. if self.fontweight == item[1]:
  835. self.fwtcb.SetStringSelection(item[0])
  836. break
  837. gridSizer.Add(item=self.fwtcb, pos=(2, 1), flag=wx.ALIGN_RIGHT)
  838. boxSizer.Add(item=gridSizer, flag=wx.EXPAND)
  839. sizer.Add(item=boxSizer, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
  840. line = wx.StaticLine(parent=self, id=wx.ID_ANY, size=(20, -1), style=wx.LI_HORIZONTAL)
  841. sizer.Add(item=line, proportion=0,
  842. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border=3)
  843. #
  844. # buttons
  845. #
  846. btnSave = wx.Button(self, wx.ID_SAVE)
  847. btnApply = wx.Button(self, wx.ID_APPLY)
  848. btnCancel = wx.Button(self, wx.ID_CANCEL)
  849. btnSave.SetDefault()
  850. # bindigs
  851. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  852. btnApply.SetToolTipString(_("Apply changes for the current session"))
  853. btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
  854. btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
  855. btnSave.SetDefault()
  856. btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  857. btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
  858. # sizers
  859. btnStdSizer = wx.StdDialogButtonSizer()
  860. btnStdSizer.AddButton(btnCancel)
  861. btnStdSizer.AddButton(btnSave)
  862. btnStdSizer.AddButton(btnApply)
  863. btnStdSizer.Realize()
  864. sizer.Add(item=btnStdSizer, proportion=0, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  865. #
  866. # bindings
  867. #
  868. self.ptitleentry.Bind(wx.EVT_TEXT, self.OnTitle)
  869. self.xlabelentry.Bind(wx.EVT_TEXT, self.OnXLabel)
  870. self.ylabelentry.Bind(wx.EVT_TEXT, self.OnYLabel)
  871. self.SetSizer(sizer)
  872. sizer.Fit(self)
  873. def OnTitle(self, event):
  874. self.ptitle = event.GetString()
  875. def OnXLabel(self, event):
  876. self.xlabel = event.GetString()
  877. def OnYLabel(self, event):
  878. self.ylabel = event.GetString()
  879. def UpdateSettings(self):
  880. self.properties['font']['prop']['titleSize'] = self.ptitlesize.GetValue()
  881. self.properties['font']['prop']['axisSize'] = self.axislabelsize.GetValue()
  882. family = self.ffamilydict[self.ffamilycb.GetStringSelection()]
  883. self.properties['font']['wxfont'].SetFamily(family)
  884. style = self.fstyledict[self.fstylecb.GetStringSelection()]
  885. self.properties['font']['wxfont'].SetStyle(style)
  886. weight = self.fwtdict[self.fwtcb.GetStringSelection()]
  887. self.properties['font']['wxfont'].SetWeight(weight)
  888. def OnSave(self, event):
  889. """!Button 'Save' pressed"""
  890. self.UpdateSettings()
  891. fileSettings = {}
  892. UserSettings.ReadSettingsFile(settings=fileSettings)
  893. fileSettings['profile'] = UserSettings.Get(group='profile')
  894. file = UserSettings.SaveToFile(fileSettings)
  895. self.parent.parent.GetLayerManager().goutput.WriteLog(_('Profile settings saved to file \'%s\'.') % file)
  896. self.Close()
  897. def OnApply(self, event):
  898. """!Button 'Apply' pressed"""
  899. self.UpdateSettings()
  900. self.Close()
  901. def OnCancel(self, event):
  902. """!Button 'Cancel' pressed"""
  903. self.Close()
  904. class OptDialog(wx.Dialog):
  905. def __init__(self, parent, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize,
  906. style=wx.DEFAULT_DIALOG_STYLE):
  907. wx.Dialog.__init__(self, parent, id, title, pos, size, style)
  908. """
  909. Dialog to set various profile options, including: line width, color, style;
  910. marker size, color, fill, and style; grid and legend options.
  911. """
  912. # init variables
  913. self.pstyledict = parent.pstyledict
  914. self.ptfilldict = parent.ptfilldict
  915. self.pttypelist = ['circle',
  916. 'dot',
  917. 'square',
  918. 'triangle',
  919. 'triangle_down',
  920. 'cross',
  921. 'plus']
  922. self.axislist = ['min',
  923. 'auto',
  924. 'custom']
  925. # widgets ids
  926. self.wxId = {}
  927. self.parent = parent
  928. # read-only
  929. self.raster = self.parent.raster
  930. self.properties = self.parent.properties
  931. self._do_layout()
  932. def _do_layout(self):
  933. """!Do layout"""
  934. # dialog layout
  935. sizer = wx.BoxSizer(wx.VERTICAL)
  936. #
  937. # profile line settings
  938. #
  939. box = wx.StaticBox(parent=self, id=wx.ID_ANY,
  940. label=" %s " % _("Profile line settings"))
  941. boxMainSizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  942. idx = 1
  943. self.wxId['pcolor'] = []
  944. self.wxId['pwidth'] = []
  945. self.wxId['pstyle'] = []
  946. self.wxId['plegend'] = []
  947. for r in self.raster.itervalues():
  948. box = wx.StaticBox(parent=self, id=wx.ID_ANY,
  949. label=" %s %d " % (_("Profile"), idx))
  950. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  951. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  952. row = 0
  953. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Line color"))
  954. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  955. pcolor = csel.ColourSelect(parent=self, id=wx.ID_ANY, colour=r['prop']['pcolor'])
  956. self.wxId['pcolor'].append(pcolor.GetId())
  957. gridSizer.Add(item=pcolor, pos=(row, 1))
  958. row += 1
  959. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Line width"))
  960. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  961. pwidth = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="",
  962. size=(50,-1), style=wx.SP_ARROW_KEYS)
  963. pwidth.SetRange(1, 10)
  964. pwidth.SetValue(r['prop']['pwidth'])
  965. self.wxId['pwidth'].append(pwidth.GetId())
  966. gridSizer.Add(item=pwidth, pos=(row, 1))
  967. row +=1
  968. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Line style"))
  969. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  970. pstyle = wx.ComboBox(parent=self, id=wx.ID_ANY,
  971. size=(120, -1), choices=self.pstyledict.keys(), style=wx.CB_DROPDOWN)
  972. pstyle.SetStringSelection(r['prop']['pstyle'])
  973. self.wxId['pstyle'].append(pstyle.GetId())
  974. gridSizer.Add(item=pstyle, pos=(row, 1))
  975. row += 1
  976. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Legend"))
  977. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  978. plegend = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(200,-1))
  979. plegend.SetValue(r['plegend'])
  980. gridSizer.Add(item=plegend, pos=(row, 1))
  981. self.wxId['plegend'].append(plegend.GetId())
  982. boxSizer.Add(item=gridSizer)
  983. if idx == 0:
  984. flag = wx.ALL
  985. else:
  986. flag = wx.TOP | wx.BOTTOM | wx.RIGHT
  987. boxMainSizer.Add(item=boxSizer, flag=flag, border=3)
  988. idx += 1
  989. sizer.Add(item=boxMainSizer, flag=wx.ALL | wx.EXPAND, border=3)
  990. middleSizer = wx.BoxSizer(wx.HORIZONTAL)
  991. #
  992. # segment marker settings
  993. #
  994. box = wx.StaticBox(parent=self, id=wx.ID_ANY,
  995. label=" %s " % _("Transect segment marker settings"))
  996. boxMainSizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  997. self.wxId['marker'] = {}
  998. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  999. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Color"))
  1000. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
  1001. ptcolor = csel.ColourSelect(parent=self, id=wx.ID_ANY, colour=self.properties['marker']['color'])
  1002. self.wxId['marker']['color'] = ptcolor.GetId()
  1003. gridSizer.Add(item=ptcolor, pos=(0, 1))
  1004. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Size"))
  1005. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
  1006. ptsize = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="",
  1007. size=(50, -1), style=wx.SP_ARROW_KEYS)
  1008. ptsize.SetRange(1, 10)
  1009. ptsize.SetValue(self.properties['marker']['size'])
  1010. self.wxId['marker']['size'] = ptsize.GetId()
  1011. gridSizer.Add(item=ptsize, pos=(1, 1))
  1012. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Style"))
  1013. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(2, 0))
  1014. ptfill = wx.ComboBox(parent=self, id=wx.ID_ANY,
  1015. size=(120, -1), choices=self.ptfilldict.keys(), style=wx.CB_DROPDOWN)
  1016. ptfill.SetStringSelection(self.properties['marker']['fill'])
  1017. self.wxId['marker']['fill'] = ptfill.GetId()
  1018. gridSizer.Add(item=ptfill, pos=(2, 1))
  1019. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Legend"))
  1020. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(3, 0))
  1021. ptlegend = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(200,-1))
  1022. ptlegend.SetValue(self.properties['marker']['legend'])
  1023. self.wxId['marker']['legend'] = ptlegend.GetId()
  1024. gridSizer.Add(item=ptlegend, pos=(3, 1))
  1025. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Type"))
  1026. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(4, 0))
  1027. pttype = wx.ComboBox(parent=self,
  1028. size=(200, -1), choices=self.pttypelist, style=wx.CB_DROPDOWN)
  1029. pttype.SetStringSelection(self.properties['marker']['type'])
  1030. self.wxId['marker']['type'] = pttype.GetId()
  1031. gridSizer.Add(item=pttype, pos=(4, 1))
  1032. boxMainSizer.Add(item=gridSizer, flag=wx.ALL, border=3)
  1033. middleSizer.Add(item=boxMainSizer, flag=wx.ALL | wx.EXPAND, border=3)
  1034. #
  1035. # axis options
  1036. #
  1037. box = wx.StaticBox(parent=self, id=wx.ID_ANY,
  1038. label=" %s " % _("Axis settings"))
  1039. boxMainSizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  1040. self.wxId['x-axis'] = {}
  1041. self.wxId['y-axis'] = {}
  1042. idx = 0
  1043. for axis, atype in [(_("X-Axis"), 'x-axis'),
  1044. (_("Y-Axis"), 'y-axis')]:
  1045. box = wx.StaticBox(parent=self, id=wx.ID_ANY,
  1046. label=" %s " % axis)
  1047. boxSizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  1048. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1049. prop = self.properties[atype]['prop']
  1050. row = 0
  1051. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Style"))
  1052. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1053. type = wx.ComboBox(parent=self, id=wx.ID_ANY,
  1054. size=(100, -1), choices=self.axislist, style=wx.CB_DROPDOWN)
  1055. type.SetStringSelection(prop['type'])
  1056. self.wxId[atype]['type'] = type.GetId()
  1057. gridSizer.Add(item=type, pos=(row, 1))
  1058. row += 1
  1059. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Custom min"))
  1060. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1061. min = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(70, -1))
  1062. min.SetValue(str(prop['min']))
  1063. self.wxId[atype]['min'] = min.GetId()
  1064. gridSizer.Add(item=min, pos=(row, 1))
  1065. row += 1
  1066. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Custom max"))
  1067. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1068. max = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(70, -1))
  1069. max.SetValue(str(prop['max']))
  1070. self.wxId[atype]['max'] = max.GetId()
  1071. gridSizer.Add(item=max, pos=(row, 1))
  1072. row += 1
  1073. log = wx.CheckBox(parent=self, id=wx.ID_ANY, label=_("Log scale"))
  1074. log.SetValue(prop['log'])
  1075. self.wxId[atype]['log'] = log.GetId()
  1076. gridSizer.Add(item=log, pos=(row, 0), span=(1, 2))
  1077. if idx == 0:
  1078. flag = wx.ALL | wx.EXPAND
  1079. else:
  1080. flag = wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND
  1081. boxSizer.Add(item=gridSizer, flag=wx.ALL, border=3)
  1082. boxMainSizer.Add(item=boxSizer, flag=flag, border=3)
  1083. idx += 1
  1084. middleSizer.Add(item=boxMainSizer, flag=wx.ALL | wx.EXPAND, border=3)
  1085. #
  1086. # grid & legend options
  1087. #
  1088. self.wxId['grid'] = {}
  1089. self.wxId['legend'] = {}
  1090. self.wxId['font'] = {}
  1091. box = wx.StaticBox(parent=self, id=wx.ID_ANY,
  1092. label=" %s " % _("Grid and Legend settings"))
  1093. boxMainSizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  1094. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1095. row = 0
  1096. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Grid color"))
  1097. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1098. gridcolor = csel.ColourSelect(parent=self, id=wx.ID_ANY, colour=self.properties['grid']['color'])
  1099. self.wxId['grid']['color'] = gridcolor.GetId()
  1100. gridSizer.Add(item=gridcolor, pos=(row, 1))
  1101. row +=1
  1102. gridshow = wx.CheckBox(parent=self, id=wx.ID_ANY, label=_("Show grid"))
  1103. gridshow.SetValue(self.properties['grid']['enabled'])
  1104. self.wxId['grid']['enabled'] = gridshow.GetId()
  1105. gridSizer.Add(item=gridshow, pos=(row, 0), span=(1, 2))
  1106. row +=1
  1107. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Legend font size"))
  1108. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1109. legendfontsize = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="",
  1110. size=(50, -1), style=wx.SP_ARROW_KEYS)
  1111. legendfontsize.SetRange(5,100)
  1112. legendfontsize.SetValue(int(self.properties['font']['prop']['legendSize']))
  1113. self.wxId['font']['legendSize'] = legendfontsize.GetId()
  1114. gridSizer.Add(item=legendfontsize, pos=(row, 1))
  1115. row += 1
  1116. legendshow = wx.CheckBox(parent=self, id=wx.ID_ANY, label=_("Show legend"))
  1117. legendshow.SetValue(self.properties['legend']['enabled'])
  1118. self.wxId['legend']['enabled'] = legendshow.GetId()
  1119. gridSizer.Add(item=legendshow, pos=(row, 0), span=(1, 2))
  1120. boxMainSizer.Add(item=gridSizer, flag=flag, border=3)
  1121. middleSizer.Add(item=boxMainSizer, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
  1122. sizer.Add(item=middleSizer, flag=wx.ALL, border=0)
  1123. #
  1124. # line & buttons
  1125. #
  1126. line = wx.StaticLine(parent=self, id=wx.ID_ANY, size=(20, -1), style=wx.LI_HORIZONTAL)
  1127. sizer.Add(item=line, proportion=0,
  1128. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border=3)
  1129. #
  1130. # buttons
  1131. #
  1132. btnSave = wx.Button(self, wx.ID_SAVE)
  1133. btnApply = wx.Button(self, wx.ID_APPLY)
  1134. btnCancel = wx.Button(self, wx.ID_CANCEL)
  1135. btnSave.SetDefault()
  1136. # bindigs
  1137. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1138. btnApply.SetToolTipString(_("Apply changes for the current session"))
  1139. btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
  1140. btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
  1141. btnSave.SetDefault()
  1142. btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  1143. btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
  1144. # sizers
  1145. btnStdSizer = wx.StdDialogButtonSizer()
  1146. btnStdSizer.AddButton(btnCancel)
  1147. btnStdSizer.AddButton(btnSave)
  1148. btnStdSizer.AddButton(btnApply)
  1149. btnStdSizer.Realize()
  1150. sizer.Add(item=btnStdSizer, proportion=0, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  1151. self.SetSizer(sizer)
  1152. sizer.Fit(self)
  1153. def UpdateSettings(self):
  1154. idx = 0
  1155. for r in self.raster.itervalues():
  1156. r['prop']['pcolor'] = self.FindWindowById(self.wxId['pcolor'][idx]).GetColour()
  1157. r['prop']['pwidth'] = int(self.FindWindowById(self.wxId['pwidth'][idx]).GetValue())
  1158. r['prop']['pstyle'] = self.FindWindowById(self.wxId['pstyle'][idx]).GetStringSelection()
  1159. r['plegend'] = self.FindWindowById(self.wxId['plegend'][idx]).GetValue()
  1160. idx +=1
  1161. self.properties['marker']['color'] = self.FindWindowById(self.wxId['marker']['color']).GetColour()
  1162. self.properties['marker']['fill'] = self.FindWindowById(self.wxId['marker']['fill']).GetStringSelection()
  1163. self.properties['marker']['size'] = self.FindWindowById(self.wxId['marker']['size']).GetValue()
  1164. self.properties['marker']['type'] = self.FindWindowById(self.wxId['marker']['type']).GetValue()
  1165. self.properties['marker']['legend'] = self.FindWindowById(self.wxId['marker']['legend']).GetValue()
  1166. for axis in ('x-axis', 'y-axis'):
  1167. self.properties[axis]['prop']['type'] = self.FindWindowById(self.wxId[axis]['type']).GetValue()
  1168. self.properties[axis]['prop']['min'] = float(self.FindWindowById(self.wxId[axis]['min']).GetValue())
  1169. self.properties[axis]['prop']['max'] = float(self.FindWindowById(self.wxId[axis]['max']).GetValue())
  1170. self.properties[axis]['prop']['log'] = self.FindWindowById(self.wxId[axis]['log']).IsChecked()
  1171. self.properties['grid']['color'] = self.FindWindowById(self.wxId['grid']['color']).GetColour()
  1172. self.properties['grid']['enabled'] = self.FindWindowById(self.wxId['grid']['enabled']).IsChecked()
  1173. self.properties['font']['prop']['legendSize'] = self.FindWindowById(self.wxId['font']['legendSize']).GetValue()
  1174. self.properties['legend']['enabled'] = self.FindWindowById(self.wxId['legend']['enabled']).IsChecked()
  1175. def OnSave(self, event):
  1176. """!Button 'Save' pressed"""
  1177. self.UpdateSettings()
  1178. fileSettings = {}
  1179. UserSettings.ReadSettingsFile(settings=fileSettings)
  1180. fileSettings['profile'] = UserSettings.Get(group='profile')
  1181. file = UserSettings.SaveToFile(fileSettings)
  1182. self.parent.parent.GetLayerManager().goutput.WriteLog(_('Profile settings saved to file \'%s\'.') % file)
  1183. self.parent.SetGraphStyle()
  1184. if self.parent.profile:
  1185. self.parent.DrawPlot()
  1186. self.Close()
  1187. def OnApply(self, event):
  1188. """!Button 'Apply' pressed. Does not close dialog"""
  1189. self.UpdateSettings()
  1190. self.parent.SetGraphStyle()
  1191. if self.parent.profile:
  1192. self.parent.DrawPlot()
  1193. def OnCancel(self, event):
  1194. """!Button 'Cancel' pressed"""
  1195. self.Close()