georect.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  1. """
  2. @package georect.py
  3. @brief Georectification module for GRASS GIS. Includes ground control
  4. point management and interactive point and click GCP creation
  5. Classes:
  6. - GeorectWizard
  7. - LocationPage
  8. - GroupPage
  9. - DispMapPage
  10. - GCP
  11. - GCPList
  12. - VectGroup
  13. - EditGCP
  14. - GrSettingsDialog
  15. (C) 2006-2008 by the GRASS Development Team
  16. This program is free software under the GNU General Public License
  17. (>=v2). Read the file COPYING that comes with GRASS for details.
  18. @author Michael Barton
  19. @author Updated by Martin Landa <landa.martin gmail.com>
  20. """
  21. import os
  22. import sys
  23. import tempfile
  24. import shutil
  25. import time
  26. import wx
  27. from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin, TextEditMixin
  28. import wx.lib.colourselect as csel
  29. import wx.wizard as wiz
  30. import grass.script as grass
  31. import globalvar
  32. import mapdisp
  33. import render
  34. import toolbars
  35. import menuform
  36. import gselect
  37. import gcmd
  38. import utils
  39. from debug import Debug as Debug
  40. from icon import Icons as Icons
  41. from location_wizard import TitledPage as TitledPage
  42. from preferences import globalSettings as UserSettings
  43. try:
  44. import subprocess # Not needed if GRASS commands could actually be quiet
  45. except:
  46. CompatPath = globalvar.ETCWXDIR
  47. sys.path.append(CompatPath)
  48. from compat import subprocess
  49. gmpath = os.path.join(globalvar.ETCWXDIR, "icons")
  50. sys.path.append(gmpath)
  51. #
  52. # global variables
  53. #
  54. global xy_map
  55. global maptype
  56. xy_map = ''
  57. maptype = 'cell'
  58. class GeorectWizard(object):
  59. """
  60. Start wizard here and finish wizard here
  61. """
  62. def __init__(self, parent):
  63. self.parent = parent # GMFrame
  64. #
  65. # get environmental variables
  66. #
  67. self.grassdatabase = grass.gisenv()['GISDBASE']
  68. #
  69. # read original environment settings
  70. #
  71. self.orig_gisrc = os.environ['GISRC']
  72. self.gisrc_dict = {}
  73. try:
  74. f = open(self.orig_gisrc, 'r')
  75. for line in f.readlines():
  76. line = line.replace('\n', '').strip()
  77. if len(line) < 1:
  78. continue
  79. key, value = line.split(':', 1)
  80. self.gisrc_dict[key.strip()] = value.strip()
  81. finally:
  82. f.close()
  83. self.currentlocation = self.gisrc_dict['LOCATION_NAME']
  84. self.currentmapset = self.gisrc_dict['MAPSET']
  85. # location for xy map to georectify
  86. self.newlocation = ''
  87. # mapset for xy map to georectify
  88. self.newmapset = ''
  89. # GISRC file for source location/mapset of map(s) to georectify
  90. self.new_gisrc = ''
  91. #
  92. # define wizard pages
  93. #
  94. self.wizard = wiz.Wizard(parent=parent, id=wx.ID_ANY, title=_("Setup for georectification"))
  95. self.startpage = LocationPage(self.wizard, self)
  96. self.grouppage = GroupPage(self.wizard, self)
  97. self.mappage = DispMapPage(self.wizard, self)
  98. #
  99. # set the initial order of the pages
  100. #
  101. self.startpage.SetNext(self.grouppage)
  102. self.grouppage.SetPrev(self.startpage)
  103. self.grouppage.SetNext(self.mappage)
  104. self.mappage.SetPrev(self.grouppage)
  105. #
  106. # do pages layout
  107. #
  108. self.startpage.DoLayout()
  109. self.grouppage.DoLayout()
  110. self.mappage.DoLayout()
  111. self.wizard.FitToPage(self.startpage)
  112. # self.Bind(wx.EVT_CLOSE, self.Cleanup)
  113. # self.parent.Bind(wx.EVT_ACTIVATE, self.OnGLMFocus)
  114. success = False
  115. #
  116. # run wizard
  117. #
  118. if self.wizard.RunWizard(self.startpage):
  119. success = self.OnWizFinished()
  120. if success == False:
  121. wx.MessageBox(parent=self.parent,
  122. message=_("Georectifying setup canceled."),
  123. caption=_("Georectify"),
  124. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  125. self.Cleanup()
  126. else:
  127. wx.MessageBox(parent=self.parent,
  128. message=_("Georectifying setup canceled."),
  129. caption=_("Georectify"),
  130. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  131. self.Cleanup()
  132. #
  133. # start display showing xymap
  134. #
  135. if success != False:
  136. # instance of render.Map to be associated with display
  137. self.Map = render.Map(gisrc=self.new_gisrc)
  138. global maptype
  139. global xy_map
  140. #
  141. # add layer to map
  142. #
  143. if maptype == 'cell':
  144. rendertype = 'raster'
  145. cmdlist = ['d.rast', 'map=%s' % xy_map]
  146. else: # -> vector layer
  147. rendertype = 'vector'
  148. cmdlist = ['d.vect', 'map=%s' % xy_map]
  149. self.Map.AddLayer(type=rendertype, command=cmdlist, l_active=True,
  150. name=utils.GetLayerNameFromCmd(cmdlist),
  151. l_hidden=False, l_opacity=1.0, l_render=False)
  152. #
  153. # start GCP form
  154. #
  155. self.gcpmgr = GCP(self.parent, grwiz=self)
  156. self.gcpmgr.Show()
  157. #
  158. # start map display
  159. #
  160. self.xy_mapdisp = mapdisp.MapFrame(self.gcpmgr, title=_("Set ground control points (GCPs)"),
  161. size=globalvar.MAP_WINDOW_SIZE,
  162. toolbars=["georect"],
  163. Map=self.Map, lmgr=self.parent)
  164. self.gcpmgr.SetMapDisplay(self.xy_mapdisp)
  165. self.mapwin = self.xy_mapdisp.MapWindow
  166. # set mouse characteristics
  167. self.mapwin.mouse['box'] = 'point'
  168. self.mapwin.mouse["use"] == "pointer"
  169. self.mapwin.zoomtype = 0
  170. self.mapwin.pen = wx.Pen(colour='black', width=2, style=wx.SOLID)
  171. self.mapwin.SetCursor(self.xy_mapdisp.cursors["cross"])
  172. #
  173. # show new display & draw map
  174. #
  175. self.xy_mapdisp.Show()
  176. else:
  177. self.Cleanup()
  178. def SetSrcEnv(self, location, mapset):
  179. """!Create environment to use for location and mapset
  180. that are the source of the file(s) to georectify
  181. @param location source location
  182. @param mapset source mapset
  183. @return False on error
  184. @return True on success
  185. """
  186. self.newlocation = location
  187. self.newmapset = mapset
  188. # check to see if we are georectifying map in current working location/mapset
  189. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  190. return False
  191. self.gisrc_dict['LOCATION_NAME'] = location
  192. self.gisrc_dict['MAPSET'] = mapset
  193. self.new_gisrc = utils.GetTempfile()
  194. try:
  195. f = open(self.new_gisrc, mode='w')
  196. for line in self.gisrc_dict.items():
  197. f.write(line[0] + ": " + line[1] + "\n")
  198. finally:
  199. f.close()
  200. return True
  201. def SwitchEnv(self, grc):
  202. """
  203. Switches between original working location/mapset and
  204. location/mapset that is source of file(s) to georectify
  205. """
  206. # check to see if we are georectifying map in current working location/mapset
  207. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  208. return False
  209. if grc == 'original':
  210. os.environ["GISRC"] = str(self.orig_gisrc)
  211. elif grc == 'new':
  212. os.environ["GISRC"] = str(self.new_gisrc)
  213. return True
  214. def OnWizFinished(self):
  215. # self.Cleanup()
  216. return True
  217. def OnGLMFocus(self, event):
  218. """!Layer Manager focus"""
  219. # self.SwitchEnv('original')
  220. event.Skip()
  221. def Cleanup(self):
  222. """!Return to current location and mapset"""
  223. self.SwitchEnv('original')
  224. self.parent.georectifying = None
  225. if hasattr(self, "xy_mapdisp"):
  226. self.xy_mapdisp.Close()
  227. self.xy_mapdisp = None
  228. self.wizard.Destroy()
  229. class LocationPage(TitledPage):
  230. """
  231. Set map type (raster or vector) to georectify and
  232. select location/mapset of map(s) to georectify.
  233. """
  234. def __init__(self, wizard, parent):
  235. TitledPage.__init__(self, wizard, _("Select map type and location/mapset"))
  236. self.parent = parent
  237. self.grassdatabase = self.parent.grassdatabase
  238. self.xylocation = ''
  239. self.xymapset = ''
  240. #
  241. # layout
  242. #
  243. self.sizer.AddGrowableCol(2)
  244. # map type
  245. self.rb_maptype = wx.RadioBox(parent=self, id=wx.ID_ANY,
  246. label=' %s ' % _("Map type to georectify"),
  247. choices=[_('raster'), _('vector')],
  248. majorDimension=wx.RA_SPECIFY_COLS)
  249. self.sizer.Add(item=self.rb_maptype,
  250. flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, border=5,
  251. pos=(1, 1), span=(1, 2))
  252. # location
  253. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source location:')),
  254. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  255. pos=(2, 1))
  256. self.cb_location = gselect.LocationSelect(parent = self, gisdbase = self.grassdatabase)
  257. self.sizer.Add(item=self.cb_location,
  258. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  259. pos=(2, 2))
  260. # mapset
  261. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source mapset:')),
  262. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  263. pos=(3, 1))
  264. self.cb_mapset = gselect.MapsetSelect(parent = self, gisdbase = self.grassdatabase,
  265. setItems = False)
  266. self.sizer.Add(item=self.cb_mapset,
  267. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  268. pos=(3,2))
  269. #
  270. # bindings
  271. #
  272. self.Bind(wx.EVT_RADIOBOX, self.OnMaptype, self.rb_maptype)
  273. self.Bind(wx.EVT_COMBOBOX, self.OnLocation, self.cb_location)
  274. self.Bind(wx.EVT_COMBOBOX, self.OnMapset, self.cb_mapset)
  275. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  276. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  277. # self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  278. def OnMaptype(self,event):
  279. """!Change map type"""
  280. global maptype
  281. if event.GetInt() == 0:
  282. maptype = 'cell'
  283. else:
  284. maptype = 'vector'
  285. def OnLocation(self, event):
  286. """!Sets source location for map(s) to georectify"""
  287. self.xylocation = event.GetString()
  288. #create a list of valid mapsets
  289. tmplist = os.listdir(os.path.join(self.grassdatabase, self.xylocation))
  290. self.mapsetList = []
  291. for item in tmplist:
  292. if os.path.isdir(os.path.join(self.grassdatabase, self.xylocation, item)) and \
  293. os.path.exists(os.path.join(self.grassdatabase, self.xylocation, item, 'WIND')):
  294. if item != 'PERMANENT':
  295. self.mapsetList.append(item)
  296. self.xymapset = 'PERMANENT'
  297. utils.ListSortLower(self.mapsetList)
  298. self.mapsetList.insert(0, 'PERMANENT')
  299. self.cb_mapset.SetItems(self.mapsetList)
  300. self.cb_mapset.SetStringSelection(self.xymapset)
  301. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  302. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  303. def OnMapset(self, event):
  304. """!Sets source mapset for map(s) to georectify"""
  305. if self.xylocation == '':
  306. wx.MessageBox(_('You must select a valid location before selecting a mapset'))
  307. return
  308. self.xymapset = event.GetString()
  309. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  310. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  311. def OnPageChanging(self, event=None):
  312. if event.GetDirection() and \
  313. (self.xylocation == '' or self.xymapset == ''):
  314. wx.MessageBox(_('You must select a valid location and mapset in order to continue'))
  315. event.Veto()
  316. return
  317. self.parent.SetSrcEnv(self.xylocation, self.xymapset)
  318. def OnEnterPage(self, event=None):
  319. if self.xylocation == '' or self.xymapset == '':
  320. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  321. else:
  322. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  323. class GroupPage(TitledPage):
  324. """
  325. Set group to georectify. Create group if desired.
  326. """
  327. def __init__(self, wizard, parent):
  328. TitledPage.__init__(self, wizard, _("Select image/map group to georectify"))
  329. self.parent = parent
  330. self.grassdatabase = self.parent.grassdatabase
  331. self.groupList = []
  332. self.xylocation = ''
  333. self.xymapset = ''
  334. self.xygroup = ''
  335. # default extension
  336. self.extension = 'georect' + str(os.getpid())
  337. #
  338. # layout
  339. #
  340. self.sizer.AddGrowableCol(2)
  341. # group
  342. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select group:')),
  343. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  344. pos=(1, 1))
  345. self.cb_group = wx.ComboBox(parent=self, id=wx.ID_ANY,
  346. choices=self.groupList, size=(350, -1),
  347. style=wx.CB_DROPDOWN | wx.CB_READONLY)
  348. self.sizer.Add(item=self.cb_group,
  349. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  350. pos=(1, 2))
  351. # create group
  352. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Create group if none exists')),
  353. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  354. pos=(2, 1))
  355. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  356. self.btn_mkgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Create/edit group..."))
  357. self.btn_vgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Add vector map to group..."))
  358. self.btn_vgroup.Hide()
  359. btnSizer.Add(item=self.btn_mkgroup,
  360. flag=wx.RIGHT, border=5)
  361. btnSizer.Add(item=self.btn_vgroup,
  362. flag=wx.LEFT, border=5)
  363. self.sizer.Add(item=btnSizer,
  364. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  365. pos=(2, 2))
  366. # extension
  367. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Extension for output maps:')),
  368. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  369. pos=(3, 1))
  370. self.ext_txt = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(350,-1))
  371. self.ext_txt.SetValue(self.extension)
  372. self.sizer.Add(item=self.ext_txt,
  373. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  374. pos=(3, 2))
  375. #
  376. # bindings
  377. #
  378. self.Bind(wx.EVT_COMBOBOX, self.OnGroup, self.cb_group)
  379. self.Bind(wx.EVT_TEXT, self.OnExtension, self.ext_txt)
  380. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  381. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  382. self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  383. def OnGroup(self, event):
  384. self.xygroup = event.GetString()
  385. def OnMkGroup(self, event):
  386. """!Create new group in source location/mapset"""
  387. menuform.GUI().ParseCommand(['i.group'],
  388. completed=(self.GetOptData, None, ''),
  389. parentframe=self.parent.parent, modal=True)
  390. def OnVGroup(self, event):
  391. """!Add vector maps to group"""
  392. dlg = VectGroup(parent = self,
  393. id = wx.ID_ANY,
  394. grassdb = self.grassdatabase,
  395. location = self.xylocation,
  396. mapset = self.xymapset,
  397. group = self.xygroup)
  398. if dlg.ShowModal() != wx.ID_OK:
  399. return
  400. dlg.MakeVGroup()
  401. self.OnEnterPage()
  402. def GetOptData(self, dcmd, layer, params, propwin):
  403. """!Process i.group"""
  404. # update the page
  405. if dcmd:
  406. gcmd.RunCommand(utils.CmdToTuple(dcmd))
  407. self.OnEnterPage()
  408. self.Update()
  409. def OnExtension(self, event):
  410. self.extension = event.GetString()
  411. def OnPageChanging(self, event=None):
  412. if event.GetDirection() and self.xygroup == '':
  413. wx.MessageBox(_('You must select a valid image/map group in order to continue'))
  414. event.Veto()
  415. return
  416. if event.GetDirection() and self.extension == '':
  417. wx.MessageBox(_('You must enter an map name extension in order to continue'))
  418. event.Veto()
  419. return
  420. def OnEnterPage(self, event=None):
  421. global maptype
  422. self.groupList = []
  423. self.xylocation = self.parent.gisrc_dict['LOCATION_NAME']
  424. self.xymapset = self.parent.gisrc_dict['MAPSET']
  425. # create a list of groups in selected mapset
  426. if os.path.isdir(os.path.join(self.grassdatabase,
  427. self.xylocation,
  428. self.xymapset,
  429. 'group')):
  430. tmplist = os.listdir(os.path.join(self.grassdatabase,
  431. self.xylocation,
  432. self.xymapset,
  433. 'group'))
  434. for item in tmplist:
  435. if os.path.isdir(os.path.join(self.grassdatabase,
  436. self.xylocation,
  437. self.xymapset,
  438. 'group',
  439. item)):
  440. self.groupList.append(item)
  441. if maptype == 'cell':
  442. self.btn_vgroup.Hide()
  443. self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
  444. elif maptype == 'vector':
  445. self.btn_vgroup.Show()
  446. self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
  447. self.Bind(wx.EVT_BUTTON, self.OnVGroup, self.btn_vgroup)
  448. utils.ListSortLower(self.groupList)
  449. self.cb_group.SetItems(self.groupList)
  450. if len(self.groupList) > 0 and \
  451. self.xygroup == '':
  452. self.cb_group.SetSelection(0)
  453. self.xygroup = self.groupList[0]
  454. if self.xygroup == '' or \
  455. self.extension == '':
  456. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  457. else:
  458. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  459. # switch to source
  460. self.parent.SwitchEnv('new')
  461. class DispMapPage(TitledPage):
  462. """
  463. Select ungeoreferenced map to display for interactively
  464. setting ground control points (GCPs).
  465. """
  466. def __init__(self, wizard, parent):
  467. TitledPage.__init__(self, wizard,
  468. _("Select image/map to display for ground control point (GCP) creation"))
  469. self.parent = parent
  470. global maptype
  471. #
  472. # layout
  473. #
  474. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select display image/map:')),
  475. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  476. pos=(1, 1))
  477. self.selection = gselect.Select(self, id=wx.ID_ANY,
  478. size=globalvar.DIALOG_GSELECT_SIZE)
  479. self.sizer.Add(item=self.selection,
  480. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  481. pos=(1, 2))
  482. #
  483. # bindings
  484. #
  485. self.selection.Bind(wx.EVT_TEXT, self.OnSelection)
  486. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  487. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  488. self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  489. def OnSelection(self,event):
  490. """!Map to display selected"""
  491. global xy_map
  492. xy_map = event.GetString()
  493. if xy_map == '':
  494. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  495. else:
  496. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  497. def OnPageChanging(self, event=None):
  498. global xy_map
  499. if event.GetDirection() and xy_map == '':
  500. wx.MessageBox(_('You must select a valid image/map in order to continue'))
  501. event.Veto()
  502. return
  503. self.parent.SwitchEnv('original')
  504. def OnEnterPage(self, event=None):
  505. global maptype
  506. global xy_map
  507. self.selection.SetElementList(maptype,
  508. mapsets = [self.parent.newmapset, ])
  509. if xy_map == '':
  510. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  511. else:
  512. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  513. class GCP(wx.Frame):
  514. """
  515. Manages ground control points for georectifying. Calculates RMS statics.
  516. Calls i.rectify or v.transform to georectify map.
  517. """
  518. def __init__(self, parent, grwiz, mapdisp=None, id=wx.ID_ANY,
  519. title=_("Create & manage ground control points"),
  520. size=wx.DefaultSize):
  521. wx.Frame.__init__(self, parent, id, title, size=(625, 300))
  522. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  523. #
  524. # init variables
  525. #
  526. self.parent = parent # GMFrame
  527. self.parent.georectifying = self
  528. self.mapdisp = mapdisp # XY-location Map Display
  529. self.grwiz = grwiz # GR Wizard
  530. self.grassdatabase = self.grwiz.grassdatabase
  531. self.currentlocation = self.grwiz.currentlocation
  532. self.currentmapset = self.grwiz.currentmapset
  533. self.newlocation = self.grwiz.newlocation
  534. self.newmapset = self.grwiz.newmapset
  535. self.xylocation = self.grwiz.gisrc_dict['LOCATION_NAME']
  536. self.xymapset = self.grwiz.gisrc_dict['MAPSET']
  537. self.xygroup = self.grwiz.grouppage.xygroup
  538. self.extension = self.grwiz.grouppage.extension
  539. self.file = {
  540. 'points' : os.path.join(self.grassdatabase,
  541. self.xylocation,
  542. self.xymapset,
  543. 'group',
  544. self.xygroup,
  545. 'POINTS'),
  546. 'rgrp' : os.path.join(self.grassdatabase,
  547. self.xylocation,
  548. self.xymapset,
  549. 'group',
  550. self.xygroup,
  551. 'REF'),
  552. 'vgrp' : os.path.join(self.grassdatabase,
  553. self.xylocation,
  554. self.xymapset,
  555. 'group',
  556. self.xygroup,
  557. 'VREF'),
  558. 'target' : os.path.join(self.grassdatabase,
  559. self.xylocation,
  560. self.xymapset,
  561. 'group',
  562. self.xygroup,
  563. 'TARGET'),
  564. }
  565. # polynomial order transformation for georectification
  566. self.gr_order = 1
  567. # number of GCPs selected to be used for georectification (checked)
  568. self.GCPcount = 0
  569. # forward RMS error
  570. self.fwd_rmserror = 0.0
  571. # backward RMS error
  572. self.bkw_rmserror = 0.0
  573. # list map coords and ID of map display they came from
  574. self.mapcoordlist = []
  575. self.SetTarget(self.xygroup, self.currentlocation, self.currentmapset)
  576. #
  577. # toolbar and display for xy map
  578. #
  579. self.toolbar = toolbars.GCPToolbar(parent=self, tbframe=self).GetToolbar()
  580. self.SetToolBar(self.toolbar)
  581. self.SetMapDisplay(self.mapdisp)
  582. #
  583. # statusbar
  584. #
  585. self.CreateStatusBar(number=1)
  586. # can put guage into custom statusbar for progress if can figure out how to get progress text from i.rectify
  587. # self.gr_gauge = wx.Gauge(self, -1, 100, (-1,-1), (100, 25))
  588. # self.gr_guage.Pulse()
  589. panel = wx.Panel(parent=self)
  590. #
  591. # do layout
  592. #
  593. sizer = wx.BoxSizer(wx.VERTICAL)
  594. self.rb_grmethod = wx.RadioBox(parent=panel, id=wx.ID_ANY,
  595. label=" %s " % _("Select rectification method for rasters"),
  596. choices=[_('1st order'), _('2nd order'), _('3rd order')],
  597. majorDimension=wx.RA_SPECIFY_COLS)
  598. sizer.Add(item=self.rb_grmethod, proportion=0,
  599. flag=wx.EXPAND | wx.ALL, border=5)
  600. self.clip_to_region = wx.CheckBox(parent=panel, id=wx.ID_ANY,
  601. label=_("clip to computational region in target location"))
  602. sizer.Add(item=self.clip_to_region, proportion=0,
  603. flag=wx.EXPAND | wx.ALL, border=5)
  604. box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
  605. label=" %s " % _("Ground Control Points"))
  606. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  607. # initialize list control for GCP management
  608. self.list = GCPList(parent=panel, gcp=self)
  609. boxSizer.Add(item=self.list, proportion=1,
  610. flag=wx.EXPAND | wx.ALL, border=3)
  611. sizer.Add(item=boxSizer, proportion=1,
  612. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
  613. #
  614. # bindigs
  615. #
  616. self.Bind(wx.EVT_RADIOBOX, self.OnGRMethod, self.rb_grmethod)
  617. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  618. self.Bind(wx.EVT_CLOSE, self.OnQuit)
  619. panel.SetSizer(sizer)
  620. # sizer.Fit(self)
  621. def __del__(self):
  622. """!Disable georectification mode"""
  623. self.parent.georectifying = None
  624. def SetMapDisplay(self, win):
  625. self.mapdisp = win
  626. if self.mapdisp:
  627. self.list.LoadData()
  628. def SetTarget(self, tgroup, tlocation, tmapset):
  629. """
  630. Sets rectification target to current location and mapset
  631. """
  632. # check to see if we are georectifying map in current working location/mapset
  633. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  634. gcmd.RunCommand('i.target',
  635. parent = self,
  636. flags = 'c',
  637. group = tgroup)
  638. else:
  639. self.grwiz.SwitchEnv('new')
  640. gcmd.RunCommand('i.target',
  641. parent = self,
  642. group = tgroup,
  643. location = tlocation,
  644. mapset = tmapset)
  645. self.grwiz.SwitchEnv('original')
  646. def AddGCP(self, event):
  647. """
  648. Appends an item to GCP list
  649. """
  650. self.list.AddGCPItem()
  651. # x, y, MapWindow instance
  652. self.mapcoordlist.append({ 'gcpcoord' : (0.0, 0.0, None),
  653. 'mapcoord' : (0.0, 0.0, None) })
  654. def DeleteGCP(self, event):
  655. """
  656. Deletes selected item in GCP list
  657. """
  658. minNumOfItems = self.OnGRMethod(None)
  659. if self.list.GetItemCount() <= minNumOfItems:
  660. wx.MessageBox(parent=self, message=_("At least %d GCPs required. Operation cancelled.") % minNumOfItems,
  661. caption=_("Delete GCP"), style=wx.OK | wx.ICON_INFORMATION)
  662. return
  663. item = self.list.DeleteGCPItem()
  664. del self.mapcoordlist[item]
  665. def ClearGCP(self, event):
  666. """
  667. Clears all values in selected item of GCP list and unchecks it
  668. """
  669. index = self.list.GetSelected()
  670. for i in range(4):
  671. self.list.SetStringItem(index, i, '0.0')
  672. self.list.SetStringItem(index, 4, '')
  673. self.list.SetStringItem(index, 5, '')
  674. self.list.CheckItem(index, False)
  675. self.mapcoordlist[index] = { 'gcpcoord' : (0.0, 0.0, None),
  676. 'mapcoord' : (0.0, 0.0, None) }
  677. def DrawGCP(self, coordtype):
  678. """
  679. Updates GCP and map coord maps and redraws
  680. active (checked) GCP markers
  681. """
  682. col = UserSettings.Get(group='georect', key='symbol', subkey='color')
  683. wxCol = wx.Colour(col[0], col[1], col[2], 255)
  684. wpx = UserSettings.Get(group='georect', key='symbol', subkey='width')
  685. font = self.GetFont()
  686. idx = 0
  687. for gcp in self.mapcoordlist:
  688. mapWin = gcp[coordtype][2]
  689. if not self.list.IsChecked(idx) or not mapWin:
  690. idx += 1
  691. continue
  692. mapWin.pen = wx.Pen(colour=wxCol, width=wpx, style=wx.SOLID)
  693. mapWin.polypen = wx.Pen(colour=wxCol, width=wpx, style=wx.SOLID) # ?
  694. coord = mapWin.Cell2Pixel((gcp[coordtype][0], gcp[coordtype][1]))
  695. mapWin.DrawCross(pdc=mapWin.pdcTmp, coords=coord,
  696. size=5, text={ 'text' : '%s' % str(idx + 1),
  697. 'active' : True,
  698. 'font' : font,
  699. 'color': wxCol,
  700. 'coords': [coord[0] + 5,
  701. coord[1] + 5,
  702. 5,
  703. 5]})
  704. idx += 1
  705. def SetGCPData(self, coordtype, coord, mapdisp=None, check=True):
  706. """
  707. Inserts coordinates from mouse click on map
  708. into selected item of GCP list and checks it for use
  709. """
  710. index = self.list.GetSelected()
  711. if index == wx.NOT_FOUND:
  712. return
  713. coord0 = str(coord[0])
  714. coord1 = str(coord[1])
  715. if coordtype == 'gcpcoord':
  716. self.list.SetStringItem(index, 0, coord0)
  717. self.list.SetStringItem(index, 1, coord1)
  718. self.mapcoordlist[index]['gcpcoord'] = (coord[0], coord[1], mapdisp)
  719. elif coordtype == 'mapcoord':
  720. self.list.SetStringItem(index, 2, coord0)
  721. self.list.SetStringItem(index, 3, coord1)
  722. self.mapcoordlist[index][coordtype] = (coord[0], coord[1], mapdisp)
  723. self.list.CheckItem(index, check)
  724. # self.list.ResizeColumns()
  725. def SaveGCPs(self, event):
  726. """
  727. Make a POINTS file or save GCP coordinates to existing POINTS file
  728. """
  729. self.GCPcount = 0
  730. try:
  731. f = open(self.file['points'], mode='w')
  732. # use os.linesep or '\n' here ???
  733. f.write('# Ground Control Points File\n')
  734. f.write("# \n")
  735. f.write("# target location: " + self.currentlocation + '\n')
  736. f.write("# target mapset: " + self.currentmapset + '\n')
  737. f.write("#unrectified xy georectified east north 1=use gcp point\n")
  738. f.write("#-------------- ----------------------- ---------------\n")
  739. for index in range(self.list.GetItemCount()):
  740. if self.list.IsChecked(index) == True:
  741. check = "1"
  742. self.GCPcount += 1
  743. else:
  744. check = "0"
  745. coord0 = self.list.GetItem(index, 0).GetText()
  746. coord1 = self.list.GetItem(index, 1).GetText()
  747. coord2 = self.list.GetItem(index, 2).GetText()
  748. coord3 = self.list.GetItem(index, 3).GetText()
  749. f.write(coord0 + ' ' + coord1 + ' ' + coord2 + ' ' + coord3 + ' ' + check + '\n')
  750. self.parent.goutput.WriteLog(_('POINTS file <%s> saved') % self.file['points'])
  751. self.SetStatusText(_('POINTS file saved'))
  752. except IOError, err:
  753. wx.MessageBox(parent=self,
  754. message="%s <%s>. %s%s" % (_("Writing POINTS file failed"),
  755. self.file['points'], os.linesep, err),
  756. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  757. return
  758. f.close()
  759. def ReadGCPs(self):
  760. """
  761. Reads GCPs and georectified coordinates from POINTS file
  762. """
  763. self.GCPcount = 0
  764. sourceMapWin = self.mapdisp.MapWindow
  765. targetMapWin = self.parent.curr_page.maptree.mapdisplay.MapWindow
  766. try:
  767. f = open(self.file['points'], 'r')
  768. GCPcnt = 0
  769. for line in f.readlines():
  770. if line[0] == '#' or line =='':
  771. continue
  772. line = line.replace('\n', '').strip()
  773. coords = map(float, line.split())
  774. if coords[4] == 1:
  775. check = True
  776. self.GCPcount +=1
  777. else:
  778. check = False
  779. index = self.AddGCP(event=None)
  780. self.SetGCPData('gcpcoord', (coords[0], coords[1]), sourceMapWin, check)
  781. self.SetGCPData('mapcoord', (coords[2], coords[3]), targetMapWin, check)
  782. except IOError, err:
  783. wx.MessageBox(parent=self,
  784. message="%s <%s>. %s%s" % (_("Reading POINTS file failed"),
  785. self.file['points'], os.linesep, err),
  786. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  787. return
  788. f.close()
  789. #
  790. # draw GCPs (source and target)
  791. #
  792. sourceMapWin.UpdateMap(render=False, renderVector=False)
  793. if targetMapWin:
  794. targetMapWin.UpdateMap(render=False, renderVector=False)
  795. #
  796. # calculate RMS
  797. #
  798. # FIXME auto calculation on load is not working
  799. #if self.CheckGCPcount():
  800. # self.RMSError(self.xygroup, self.gr_order)
  801. def ReloadGCPs(self, event):
  802. """!Reload data from file"""
  803. self.list.LoadData()
  804. def OnFocus(self, event):
  805. # self.grwiz.SwitchEnv('new')
  806. pass
  807. def OnRMS(self, event):
  808. """
  809. RMS button handler
  810. """
  811. self.RMSError(self.xygroup,self.gr_order)
  812. def CheckGCPcount(self, msg=False):
  813. """
  814. Checks to make sure that the minimum number of GCPs have been defined and
  815. are active for the selected transformation order
  816. """
  817. if (self.GCPcount < 3 and self.gr_order == 1) or \
  818. (self.GCPcount < 6 and self.gr_order == 2) or \
  819. (self.GCPcount < 10 and self.gr_order == 3):
  820. if msg:
  821. wx.MessageBox(parent=self,
  822. caption=_("RMS Error"),
  823. message=_('Insufficient points defined and active (checked) '
  824. 'for selected rectification method.\n'
  825. '3+ points needed for 1st order,\n'
  826. '6+ points for 2nd order, and\n'
  827. '10+ points for 3rd order.'),
  828. style=wx.ICON_INFORMATION | wx.ID_OK | wx.CENTRE)
  829. return False
  830. else:
  831. return True
  832. def OnGeorect(self, event):
  833. """
  834. Georectifies map(s) in group using i.rectify or v.transform
  835. """
  836. global maptype
  837. self.SaveGCPs(None)
  838. if self.CheckGCPcount(msg=True) == False:
  839. return
  840. if maptype == 'cell':
  841. self.grwiz.SwitchEnv('new')
  842. cmdlist = ['i.rectify','-a','group=%s' % self.xygroup,
  843. 'extension=%s' % self.extension,'order=%s' % self.gr_order]
  844. if self.clip_to_region:
  845. cmdlist.append('-c')
  846. self.parent.goutput.RunCmd(cmdlist, compReg=False,
  847. switchPage=True)
  848. time.sleep(.1)
  849. self.grwiz.SwitchEnv('original')
  850. elif maptype == 'vector':
  851. # loop through all vectors in VREF
  852. # and move resulting vector to target location
  853. f = open(self.file['vgrp'])
  854. vectlist = []
  855. try:
  856. for vect in f.readlines():
  857. vect = vect.strip('\n')
  858. if len(vect) < 1:
  859. continue
  860. vectlist.append(vect)
  861. finally:
  862. f.close()
  863. for vect in vectlist:
  864. self.grwiz.SwitchEnv('new')
  865. self.outname = vect + '_' + self.extension
  866. self.parent.goutput.WriteLog(text = _('Transforming <%s>...') % vect,
  867. switchPage = True)
  868. xyLayer = []
  869. for layer in grass.vector_db(map = vect).itervalues():
  870. xyLayer.append((layer['driver'],
  871. layer['database'],
  872. layer['table']))
  873. self.parent.goutput.RunCmd(['v.transform',
  874. '--o',
  875. 'input=%s' % vect,
  876. 'output=%s' % self.outname,
  877. 'pointsfile=%s' % self.file['points']],
  878. switchPage = True,
  879. onDone = self.OnGeorectDone)
  880. dbConnect = grass.db_connection()
  881. for layer in xyLayer:
  882. self.parent.goutput.RunCmd(['db.copy',
  883. '--q',
  884. '--o',
  885. 'from_driver=%s' % layer[0],
  886. 'from_database=%s' % layer[1],
  887. 'from_table=%s' % layer[2],
  888. 'to_driver=%s' % dbConnect['driver'],
  889. 'to_database=%s' % dbConnect['database'],
  890. 'to_table=%s' % layer[2] + '_' + self.extension])
  891. def OnGeorectDone(self, **kargs):
  892. """!Print final message"""
  893. global maptype
  894. if maptype == 'cell':
  895. return
  896. returncode = kargs['returncode']
  897. xyvpath = os.path.join(self.grassdatabase,
  898. self.xylocation,
  899. self.xymapset,
  900. 'vector',
  901. self.outname)
  902. vpath = os.path.join(self.grassdatabase,
  903. self.currentlocation,
  904. self.currentmapset,
  905. 'vector',
  906. self.outname)
  907. if os.path.isdir(vpath):
  908. self.parent.goutput.WriteWarning(_('Vector map <%s> already exists. '
  909. 'Change extension name and '
  910. 'georectify again.') % self.outname)
  911. else:
  912. if returncode == 0:
  913. if not os.path.isdir(os.path.join(self.grassdatabase,
  914. self.currentlocation,
  915. self.currentmapset,
  916. 'vector')):
  917. os.mkdir(os.path.join(self.grassdatabase,
  918. self.currentlocation,
  919. self.currentmapset,
  920. 'vector'))
  921. shutil.move(xyvpath, vpath)
  922. self.parent.goutput.WriteCmdLog(_('Vector map <%s> georectified '
  923. 'successfully') % self.outname)
  924. # copy attributes
  925. self.parent.goutput.WriteLog(_('Copying attributes...'))
  926. else:
  927. self.parent.goutput.WriteError(_('Georectification of vector map <%s> failed') %
  928. self.outname)
  929. del self.outname
  930. self.grwiz.SwitchEnv('original')
  931. def OnSettings(self, event):
  932. """!Georectifier settings"""
  933. dlg = GrSettingsDialog(parent=self, id=wx.ID_ANY, title=_('Georectifier settings'))
  934. if dlg.ShowModal() == wx.ID_OK:
  935. pass
  936. dlg.Destroy()
  937. def OnQuit(self, event):
  938. """!Quit georectifier"""
  939. self.grwiz.Cleanup()
  940. self.Destroy()
  941. event.Skip()
  942. def OnGRMethod(self, event):
  943. """
  944. sets transformation order for georectifying
  945. """
  946. if event:
  947. self.gr_order = event.GetInt() + 1
  948. numOfItems = self.list.GetItemCount()
  949. minNumOfItems = numOfItems
  950. if self.gr_order == 1:
  951. minNumOfItems = 3
  952. # self.SetStatusText(_('Insufficient points, 3+ points needed for 1st order'))
  953. elif self.gr_order == 2:
  954. minNumOfItems = 6
  955. diff = 6 - numOfItems
  956. # self.SetStatusText(_('Insufficient points, 6+ points needed for 2nd order'))
  957. elif self.gr_order == 3:
  958. minNumOfItems = 10
  959. # self.SetStatusText(_('Insufficient points, 10+ points needed for 3rd order'))
  960. for i in range(minNumOfItems - numOfItems):
  961. self.AddGCP(None)
  962. return minNumOfItems
  963. def RMSError(self, xygroup, order):
  964. """
  965. Uses g.transform to calculate forward and backward error for each used GCP
  966. in POINTS file and insert error values into GCP list.
  967. Calculates total forward and backward RMS error for all used points
  968. """
  969. # save GCPs to points file to make sure that all checked GCPs are used
  970. self.SaveGCPs(None)
  971. if self.CheckGCPcount(msg=True) == False:
  972. return
  973. # get list of forward and reverse rms error values for each point
  974. self.grwiz.SwitchEnv('new')
  975. ret = gcmd.RunCommand('g.transform',
  976. parent = self,
  977. read = True,
  978. group = xygroup,
  979. order = order)
  980. self.grwiz.SwitchEnv('original')
  981. if ret:
  982. errlist = ret.splitlines()
  983. if errlist == []:
  984. return
  985. # insert error values into GCP list for checked items
  986. i = 0
  987. sumsq_fwd_err = 0.0
  988. sumsq_bkw_err = 0.0
  989. for index in range(self.list.GetItemCount()):
  990. if self.list.IsChecked(index):
  991. fwd_err, bkw_err = errlist[i].split()
  992. self.list.SetStringItem(index, 4, fwd_err)
  993. self.list.SetStringItem(index, 5, bkw_err)
  994. sumsq_fwd_err += float(fwd_err)**2
  995. sumsq_bkw_err += float(bkw_err)**2
  996. i += 1
  997. else:
  998. self.list.SetStringItem(index, 4, '')
  999. self.list.SetStringItem(index, 5, '')
  1000. # calculate RMS error
  1001. self.fwd_rmserror = round((sumsq_fwd_err/i)**0.5,4)
  1002. self.bkw_rmserror = round((sumsq_bkw_err/i)**0.5,4)
  1003. self.list.ResizeColumns()
  1004. self.SetStatusText(_('RMS error for selected points forward: %(fwd)s backward: %(bkw)s') % \
  1005. { 'fwd' : self.fwd_rmserror, 'bkw' : self.bkw_rmserror })
  1006. class GCPList(wx.ListCtrl,
  1007. CheckListCtrlMixin,
  1008. ListCtrlAutoWidthMixin):
  1009. def __init__(self, parent, gcp, id=wx.ID_ANY,
  1010. pos=wx.DefaultPosition, size=wx.DefaultSize,
  1011. style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_HRULES |
  1012. wx.LC_SINGLE_SEL):
  1013. wx.ListCtrl.__init__(self, parent, id, pos, size, style)
  1014. # Mixin settings
  1015. CheckListCtrlMixin.__init__(self)
  1016. ListCtrlAutoWidthMixin.__init__(self)
  1017. # TextEditMixin.__init__(self)
  1018. self.gcp = gcp # GCP class
  1019. # tracks whether list items are checked or not
  1020. self.CheckList = []
  1021. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
  1022. self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
  1023. self._Create()
  1024. self.selected = wx.NOT_FOUND
  1025. def _Create(self):
  1026. idx_col = 0
  1027. for col in (_('use| X coord'),
  1028. _('Y coord'),
  1029. _('E coord'),
  1030. _('N coord'),
  1031. _('Forward error'),
  1032. _('Backward error')):
  1033. self.InsertColumn(idx_col, col)
  1034. idx_col += 1
  1035. def LoadData(self):
  1036. """!Load data into list"""
  1037. self.DeleteAllItems()
  1038. if os.path.isfile(self.gcp.file['points']):
  1039. self.gcp.ReadGCPs()
  1040. else:
  1041. # 3 gcp is minimum
  1042. for i in range(3):
  1043. self.gcp.AddGCP(None)
  1044. # select first point by default
  1045. self.selected = 0
  1046. self.SetItemState(self.selected,
  1047. wx.LIST_STATE_SELECTED,
  1048. wx.LIST_STATE_SELECTED)
  1049. self.ResizeColumns()
  1050. def OnCheckItem(self, index, flag):
  1051. """!Item is checked/unchecked"""
  1052. pass
  1053. def AddGCPItem(self):
  1054. """
  1055. Appends an item to GCP list
  1056. """
  1057. self.Append(['0.0',
  1058. '0.0',
  1059. '0.0',
  1060. '0.0',
  1061. '',
  1062. ''])
  1063. self.selected = self.GetItemCount() - 1
  1064. self.SetItemState(self.selected,
  1065. wx.LIST_STATE_SELECTED,
  1066. wx.LIST_STATE_SELECTED)
  1067. self.ResizeColumns()
  1068. return self.selected
  1069. def DeleteGCPItem(self):
  1070. """
  1071. Deletes selected item in GCP list
  1072. """
  1073. if self.selected == wx.NOT_FOUND:
  1074. return
  1075. self.DeleteItem(self.selected)
  1076. if self.GetItemCount() > 0:
  1077. self.selected = self.GetItemCount() - 1
  1078. self.SetItemState(self.selected,
  1079. wx.LIST_STATE_SELECTED,
  1080. wx.LIST_STATE_SELECTED)
  1081. else:
  1082. self.selected = wx.NOT_FOUND
  1083. return self.selected
  1084. def ResizeColumns(self):
  1085. """!Resize columns"""
  1086. minWidth = 90
  1087. for i in range(self.GetColumnCount()):
  1088. self.SetColumnWidth(i, wx.LIST_AUTOSIZE)
  1089. if self.GetColumnWidth(i) < minWidth:
  1090. self.SetColumnWidth(i, minWidth)
  1091. self.SendSizeEvent()
  1092. def GetSelected(self):
  1093. """!Get index of selected item"""
  1094. return self.selected
  1095. def OnItemSelected(self, event):
  1096. self.selected = event.GetIndex()
  1097. def OnItemActivated(self, event):
  1098. """
  1099. When item double clicked, open editor to update coordinate values
  1100. """
  1101. coords = []
  1102. index = event.GetIndex()
  1103. for i in range(4):
  1104. coords.append(self.GetItem(index, i).GetText())
  1105. dlg = EditGPC(parent=self, id=wx.ID_ANY, data=coords)
  1106. if dlg.ShowModal() == wx.ID_OK:
  1107. values = dlg.GetValues() # string
  1108. if len(values) == 0:
  1109. wx.MessageBox(parent=self,
  1110. caption=_("Edit GCP"),
  1111. message=_("Invalid coordinate value. Operation cancelled."),
  1112. style=wx.CENTRE | wx.ICON_ERROR | wx.ID_OK)
  1113. else:
  1114. for i in range(len(values)):
  1115. if values[i] != coords[i]:
  1116. self.SetStringItem(index, i, values[i])
  1117. mapdisp = self.gcp.mapcoordlist[index]['gcpcoord'][2]
  1118. self.gcp.mapcoordlist[index]['gcpcoord'] = (float(values[0]), float(values[1]), mapdisp)
  1119. mapdisp = self.gcp.mapcoordlist[index]['mapcoord'][2]
  1120. self.gcp.mapcoordlist[index]['mapcoord'] = (float(values[0]), float(values[1]), mapdisp)
  1121. class VectGroup(wx.Dialog):
  1122. """
  1123. Dialog to create a vector group (VREF file) for georectifying
  1124. @todo Replace by g.group
  1125. """
  1126. def __init__(self, parent, id, grassdb, location, mapset, group,
  1127. style=wx.DEFAULT_DIALOG_STYLE):
  1128. wx.Dialog.__init__(self, parent, id, style=style,
  1129. title = _("Create vector map group"))
  1130. self.grassdatabase = grassdb
  1131. self.xylocation = location
  1132. self.xymapset = mapset
  1133. self.xygroup = group
  1134. #
  1135. # get list of valid vector directories
  1136. #
  1137. vectlist = os.listdir(os.path.join(self.grassdatabase,
  1138. self.xylocation,
  1139. self.xymapset,
  1140. 'vector'))
  1141. for dir in vectlist:
  1142. if not os.path.isfile(os.path.join(self.grassdatabase,
  1143. self.xylocation,
  1144. self.xymapset,
  1145. 'vector',
  1146. dir,
  1147. 'coor')):
  1148. vectlist.remove(dir)
  1149. utils.ListSortLower(vectlist)
  1150. # path to vref file
  1151. self.vgrpfile = os.path.join(self.grassdatabase,
  1152. self.xylocation,
  1153. self.xymapset,
  1154. 'group',
  1155. self.xygroup,
  1156. 'VREF')
  1157. #
  1158. # buttons
  1159. #
  1160. self.btnCancel = wx.Button(parent = self,
  1161. id = wx.ID_CANCEL)
  1162. self.btnOK = wx.Button(parent = self,
  1163. id = wx.ID_OK)
  1164. self.btnOK.SetDefault()
  1165. #
  1166. # list of vector maps
  1167. #
  1168. self.listMap = wx.CheckListBox(parent = self, id = wx.ID_ANY,
  1169. choices = vectlist)
  1170. if os.path.isfile(self.vgrpfile):
  1171. f = open(self.vgrpfile)
  1172. try:
  1173. checked = []
  1174. for line in f.readlines():
  1175. line = line.replace('\n', '')
  1176. if len(line) < 1:
  1177. continue
  1178. checked.append(line)
  1179. self.listMap.SetCheckedStrings(checked)
  1180. finally:
  1181. f.close()
  1182. line = wx.StaticLine(parent = self,
  1183. id = wx.ID_ANY, size = (20, -1),
  1184. style = wx.LI_HORIZONTAL)
  1185. #
  1186. # layout
  1187. #
  1188. sizer = wx.BoxSizer(wx.VERTICAL)
  1189. box = wx.BoxSizer(wx.HORIZONTAL)
  1190. box.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  1191. label = _('Select vector map(s) to add to group:')),
  1192. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
  1193. border = 5)
  1194. box.Add(item = self.listMap,
  1195. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
  1196. border = 5)
  1197. sizer.Add(box, flag = wx.ALIGN_RIGHT | wx.ALL,
  1198. border = 3)
  1199. sizer.Add(item = line, proportion = 0,
  1200. flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  1201. border = 5)
  1202. # buttons
  1203. btnSizer = wx.StdDialogButtonSizer()
  1204. btnSizer.AddButton(self.btnCancel)
  1205. btnSizer.AddButton(self.btnOK)
  1206. btnSizer.Realize()
  1207. sizer.Add(item = btnSizer, proportion = 0,
  1208. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
  1209. border = 5)
  1210. self.SetSizer(sizer)
  1211. sizer.Fit(self)
  1212. self.Layout()
  1213. def MakeVGroup(self):
  1214. """!Create VREF file"""
  1215. vgrouplist = []
  1216. for item in range(self.listMap.GetCount()):
  1217. if not self.listMap.IsChecked(item):
  1218. continue
  1219. vgrouplist.append(self.listMap.GetString(item))
  1220. f = open(self.vgrpfile, mode='w')
  1221. try:
  1222. for vect in vgrouplist:
  1223. f.write(vect + '\n')
  1224. finally:
  1225. f.close()
  1226. class EditGPC(wx.Dialog):
  1227. def __init__(self, parent, data, id=wx.ID_ANY,
  1228. title=_("Edit GCP"),
  1229. style=wx.DEFAULT_DIALOG_STYLE):
  1230. """!Dialog for editing GPC and map coordinates in list control"""
  1231. wx.Dialog.__init__(self, parent, id, title=title, style=style)
  1232. panel = wx.Panel(parent=self)
  1233. sizer = wx.BoxSizer(wx.VERTICAL)
  1234. box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
  1235. label=" %s " % _("Ground Control Point"))
  1236. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1237. # source coordinates
  1238. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1239. self.xcoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1240. self.ycoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1241. self.ncoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1242. self.ecoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1243. row = 0
  1244. col = 0
  1245. idx = 0
  1246. for label, win in ((_("X:"), self.xcoord),
  1247. (_("Y:"), self.ycoord),
  1248. (_("E:"), self.ecoord),
  1249. (_("N:"), self.ncoord)):
  1250. label = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1251. label=label)
  1252. gridSizer.Add(item=label,
  1253. flag=wx.ALIGN_CENTER_VERTICAL,
  1254. pos=(row, col))
  1255. col += 1
  1256. win.SetValue(str(data[idx]))
  1257. gridSizer.Add(item=win,
  1258. pos=(row, col))
  1259. col += 1
  1260. idx += 1
  1261. if col > 3:
  1262. row += 1
  1263. col = 0
  1264. boxSizer.Add(item=gridSizer, proportion=1,
  1265. flag=wx.EXPAND | wx.ALL, border=5)
  1266. sizer.Add(item=boxSizer, proportion=1,
  1267. flag=wx.EXPAND | wx.ALL, border=5)
  1268. #
  1269. # buttons
  1270. #
  1271. self.btnCancel = wx.Button(panel, wx.ID_CANCEL)
  1272. self.btnOk = wx.Button(panel, wx.ID_OK)
  1273. self.btnOk.SetDefault()
  1274. btnSizer = wx.StdDialogButtonSizer()
  1275. btnSizer.AddButton(self.btnCancel)
  1276. btnSizer.AddButton(self.btnOk)
  1277. btnSizer.Realize()
  1278. sizer.Add(item=btnSizer, proportion=0,
  1279. flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  1280. panel.SetSizer(sizer)
  1281. sizer.Fit(self)
  1282. def GetValues(self, columns=None):
  1283. """!Return list of values (as strings).
  1284. """
  1285. valuelist = []
  1286. try:
  1287. float(self.xcoord.GetValue())
  1288. float(self.ycoord.GetValue())
  1289. float(self.ecoord.GetValue())
  1290. float(self.ncoord.GetValue())
  1291. except ValueError:
  1292. return valuelist
  1293. valuelist.append(self.xcoord.GetValue())
  1294. valuelist.append(self.ycoord.GetValue())
  1295. valuelist.append(self.ecoord.GetValue())
  1296. valuelist.append(self.ncoord.GetValue())
  1297. return valuelist
  1298. class GrSettingsDialog(wx.Dialog):
  1299. def __init__(self, parent, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize,
  1300. style=wx.DEFAULT_DIALOG_STYLE):
  1301. wx.Dialog.__init__(self, parent, id, title, pos, size, style)
  1302. """
  1303. Dialog to set profile text options: font, title
  1304. and font size, axis labels and font size
  1305. """
  1306. #
  1307. # initialize variables
  1308. #
  1309. self.parent = parent
  1310. self.symbol = {}
  1311. self._do_layout()
  1312. def _do_layout(self):
  1313. """!Do layout"""
  1314. # dialog layout
  1315. sizer = wx.BoxSizer(wx.VERTICAL)
  1316. box = wx.StaticBox(parent=self, id=wx.ID_ANY,
  1317. label=" %s " % _("Symbol settings"))
  1318. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1319. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1320. gridSizer.AddGrowableCol(1)
  1321. #
  1322. # symbol color
  1323. #
  1324. row = 0
  1325. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Color:"))
  1326. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1327. col = UserSettings.Get(group='georect', key='symbol', subkey='color')
  1328. colWin = csel.ColourSelect(parent=self, id=wx.ID_ANY,
  1329. colour=wx.Colour(col[0],
  1330. col[1],
  1331. col[2],
  1332. 255))
  1333. self.symbol['color'] = colWin.GetId()
  1334. gridSizer.Add(item=colWin,
  1335. flag=wx.ALIGN_RIGHT,
  1336. pos=(row, 1))
  1337. #
  1338. # symbol width
  1339. #
  1340. row += 1
  1341. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Width:"))
  1342. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1343. width = int(UserSettings.Get(group='georect', key='symbol', subkey='width'))
  1344. widWin = wx.SpinCtrl(parent=self, id=wx.ID_ANY,
  1345. min=1, max=10)
  1346. widWin.SetValue(width)
  1347. self.symbol['width'] = widWin.GetId()
  1348. gridSizer.Add(item=widWin,
  1349. flag=wx.ALIGN_RIGHT,
  1350. pos=(row, 1))
  1351. boxSizer.Add(item=gridSizer, flag=wx.EXPAND)
  1352. sizer.Add(item=boxSizer, flag=wx.EXPAND | wx.ALL, border=5)
  1353. line = wx.StaticLine(parent=self, id=wx.ID_ANY, size=(20, -1), style=wx.LI_HORIZONTAL)
  1354. sizer.Add(item=line, proportion=0,
  1355. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border=3)
  1356. #
  1357. # buttons
  1358. #
  1359. btnSave = wx.Button(self, wx.ID_SAVE)
  1360. btnApply = wx.Button(self, wx.ID_APPLY)
  1361. btnCancel = wx.Button(self, wx.ID_CANCEL)
  1362. btnSave.SetDefault()
  1363. # bindigs
  1364. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1365. btnApply.SetToolTipString(_("Apply changes for the current session"))
  1366. btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
  1367. btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
  1368. btnSave.SetDefault()
  1369. btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  1370. btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
  1371. # sizers
  1372. btnStdSizer = wx.StdDialogButtonSizer()
  1373. btnStdSizer.AddButton(btnCancel)
  1374. btnStdSizer.AddButton(btnSave)
  1375. btnStdSizer.AddButton(btnApply)
  1376. btnStdSizer.Realize()
  1377. sizer.Add(item=btnStdSizer, proportion=0, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  1378. self.SetSizer(sizer)
  1379. sizer.Fit(self)
  1380. def UpdateSettings(self):
  1381. UserSettings.Set(group='georect', key='symbol', subkey='color',
  1382. value=wx.FindWindowById(self.symbol['color']).GetColour())
  1383. UserSettings.Set(group='georect', key='symbol', subkey='width',
  1384. value=wx.FindWindowById(self.symbol['width']).GetValue())
  1385. def OnSave(self, event):
  1386. """!Button 'Save' pressed"""
  1387. self.UpdateSettings()
  1388. fileSettings = {}
  1389. UserSettings.ReadSettingsFile(settings=fileSettings)
  1390. fileSettings['georect'] = UserSettings.Get(group='georect')
  1391. file = UserSettings.SaveToFile(fileSettings)
  1392. self.parent.parent.goutput.WriteLog(_('Georectifier settings saved to file \'%s\'.') % file)
  1393. self.Close()
  1394. def OnApply(self, event):
  1395. """!Button 'Apply' pressed"""
  1396. self.UpdateSettings()
  1397. self.Close()
  1398. def OnCancel(self, event):
  1399. """!Button 'Cancel' pressed"""
  1400. self.Close()