profile.py 55 KB

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