profile.py 54 KB

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