manager.py 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237
  1. """
  2. @package gcp.manager
  3. @brief Georectification module for GRASS GIS. Includes ground control
  4. point management and interactive point and click GCP creation
  5. Classes:
  6. - manager::GCPWizard
  7. - manager::LocationPage
  8. - manager::GroupPage
  9. - manager::DispMapPage
  10. - manager::GCP
  11. - manager::GCPList
  12. - manager::VectGroup
  13. - manager::EditGCP
  14. - manager::GrSettingsDialog
  15. (C) 2006-2014 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 Original author Michael Barton
  19. @author Original version improved by Martin Landa <landa.martin gmail.com>
  20. @author Rewritten by Markus Metz redesign georectfier -> GCP Manage
  21. @author Support for GraphicsSet added by Stepan Turek <stepan.turek seznam.cz> (2012)
  22. """
  23. from __future__ import print_function
  24. import os
  25. import sys
  26. import shutil
  27. import six
  28. from copy import copy
  29. import wx
  30. from wx.lib.mixins.listctrl import ColumnSorterMixin, ListCtrlAutoWidthMixin
  31. import wx.lib.colourselect as csel
  32. from core import globalvar
  33. if globalvar.wxPythonPhoenix:
  34. from wx import adv as wiz
  35. from wx.adv import Wizard
  36. else:
  37. from wx import wizard as wiz
  38. from wx.wizard import Wizard
  39. import grass.script as grass
  40. from core import utils
  41. from core.render import Map
  42. from gui_core.gselect import Select, LocationSelect, MapsetSelect
  43. from gui_core.dialogs import GroupDialog
  44. from core.gcmd import RunCommand, GMessage, GError, GWarning
  45. from core.settings import UserSettings
  46. from gcp.mapdisplay import MapFrame
  47. from core.giface import Notification
  48. from gui_core.wrap import SpinCtrl, Button, StaticText, StaticBox, \
  49. CheckListBox, TextCtrl, Menu, ListCtrl, BitmapFromImage, CheckListCtrlMixin
  50. from location_wizard.wizard import TitledPage as TitledPage
  51. #
  52. # global variables
  53. #
  54. global src_map
  55. global tgt_map
  56. global maptype
  57. src_map = ''
  58. tgt_map = {'raster': '',
  59. 'vector': ''}
  60. maptype = 'raster'
  61. def getSmallUpArrowImage():
  62. stream = open(os.path.join(globalvar.IMGDIR, 'small_up_arrow.png'), 'rb')
  63. try:
  64. img = wx.Image(stream)
  65. finally:
  66. stream.close()
  67. return img
  68. def getSmallDnArrowImage():
  69. stream = open(os.path.join(globalvar.IMGDIR, 'small_down_arrow.png'), 'rb')
  70. try:
  71. img = wx.Image(stream)
  72. finally:
  73. stream.close()
  74. stream.close()
  75. return img
  76. class GCPWizard(object):
  77. """
  78. Start wizard here and finish wizard here
  79. """
  80. def __init__(self, parent, giface):
  81. self.parent = parent # GMFrame
  82. self._giface = giface
  83. #
  84. # get environmental variables
  85. #
  86. self.grassdatabase = grass.gisenv()['GISDBASE']
  87. #
  88. # read original environment settings
  89. #
  90. self.target_gisrc = os.environ['GISRC']
  91. self.gisrc_dict = {}
  92. try:
  93. f = open(self.target_gisrc, 'r')
  94. for line in f.readlines():
  95. line = line.replace('\n', '').strip()
  96. if len(line) < 1:
  97. continue
  98. key, value = line.split(':', 1)
  99. self.gisrc_dict[key.strip()] = value.strip()
  100. finally:
  101. f.close()
  102. self.currentlocation = self.gisrc_dict['LOCATION_NAME']
  103. self.currentmapset = self.gisrc_dict['MAPSET']
  104. # location for xy map to georectify
  105. self.newlocation = ''
  106. # mapset for xy map to georectify
  107. self.newmapset = ''
  108. global maptype
  109. global src_map
  110. global tgt_map
  111. #src_map = ''
  112. #tgt_map = ''
  113. maptype = 'raster'
  114. # GISRC file for source location/mapset of map(s) to georectify
  115. self.source_gisrc = ''
  116. self.src_maps = []
  117. #
  118. # define wizard pages
  119. #
  120. self.wizard = wiz.Wizard(
  121. parent=parent,
  122. id=wx.ID_ANY,
  123. title=_("Setup for georectification"))
  124. self.startpage = LocationPage(self.wizard, self)
  125. self.grouppage = GroupPage(self.wizard, self)
  126. self.mappage = DispMapPage(self.wizard, self)
  127. #
  128. # set the initial order of the pages
  129. #
  130. self.startpage.SetNext(self.grouppage)
  131. self.grouppage.SetPrev(self.startpage)
  132. self.grouppage.SetNext(self.mappage)
  133. self.mappage.SetPrev(self.grouppage)
  134. #
  135. # do pages layout
  136. #
  137. self.startpage.DoLayout()
  138. self.grouppage.DoLayout()
  139. self.mappage.DoLayout()
  140. self.wizard.FitToPage(self.startpage)
  141. # self.Bind(wx.EVT_CLOSE, self.Cleanup)
  142. # self.parent.Bind(wx.EVT_ACTIVATE, self.OnGLMFocus)
  143. success = False
  144. #
  145. # run wizard
  146. #
  147. if self.wizard.RunWizard(self.startpage):
  148. success = self.OnWizFinished()
  149. if not success:
  150. GMessage(parent=self.parent,
  151. message=_("Georectifying setup canceled."))
  152. self.Cleanup()
  153. else:
  154. GMessage(parent=self.parent,
  155. message=_("Georectifying setup canceled."))
  156. self.Cleanup()
  157. #
  158. # start GCP display
  159. #
  160. if success:
  161. # instance of render.Map to be associated with display
  162. self.SwitchEnv('source')
  163. self.SrcMap = Map(gisrc=self.source_gisrc)
  164. self.SwitchEnv('target')
  165. self.TgtMap = Map(gisrc=self.target_gisrc)
  166. self.Map = self.SrcMap
  167. #
  168. # add layer to source map
  169. #
  170. if maptype == 'raster':
  171. rendertype = 'raster'
  172. cmdlist = ['d.rast', 'map=%s' % src_map]
  173. else: # -> vector layer
  174. rendertype = 'vector'
  175. cmdlist = ['d.vect', 'map=%s' % src_map]
  176. self.SwitchEnv('source')
  177. name, found = utils.GetLayerNameFromCmd(cmdlist)
  178. self.SrcMap.AddLayer(
  179. ltype=rendertype,
  180. command=cmdlist,
  181. active=True,
  182. name=name,
  183. hidden=False,
  184. opacity=1.0,
  185. render=False)
  186. self.SwitchEnv('target')
  187. if tgt_map['raster']:
  188. #
  189. # add raster layer to target map
  190. #
  191. rendertype = 'raster'
  192. cmdlist = ['d.rast', 'map=%s' % tgt_map['raster']]
  193. name, found = utils.GetLayerNameFromCmd(cmdlist)
  194. self.TgtMap.AddLayer(
  195. ltype=rendertype,
  196. command=cmdlist,
  197. active=True,
  198. name=name,
  199. hidden=False,
  200. opacity=1.0,
  201. render=False)
  202. if tgt_map['vector']:
  203. #
  204. # add raster layer to target map
  205. #
  206. rendertype = 'vector'
  207. cmdlist = ['d.vect', 'map=%s' % tgt_map['vector']]
  208. name, found = utils.GetLayerNameFromCmd(cmdlist)
  209. self.TgtMap.AddLayer(
  210. ltype=rendertype,
  211. command=cmdlist,
  212. active=True,
  213. name=name,
  214. hidden=False,
  215. opacity=1.0,
  216. render=False)
  217. #
  218. # start GCP Manager
  219. #
  220. self.gcpmgr = GCP(self.parent, giface=self._giface,
  221. grwiz=self, size=globalvar.MAP_WINDOW_SIZE,
  222. toolbars=["gcpdisp"],
  223. Map=self.SrcMap, lmgr=self.parent)
  224. # load GCPs
  225. self.gcpmgr.InitMapDisplay()
  226. self.gcpmgr.CenterOnScreen()
  227. self.gcpmgr.Show()
  228. # need to update AUI here for wingrass
  229. self.gcpmgr._mgr.Update()
  230. else:
  231. self.Cleanup()
  232. def SetSrcEnv(self, location, mapset):
  233. """Create environment to use for location and mapset
  234. that are the source of the file(s) to georectify
  235. :param location: source location
  236. :param mapset: source mapset
  237. :return: False on error
  238. :return: True on success
  239. """
  240. self.newlocation = location
  241. self.newmapset = mapset
  242. # check to see if we are georectifying map in current working
  243. # location/mapset
  244. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  245. return False
  246. self.gisrc_dict['LOCATION_NAME'] = location
  247. self.gisrc_dict['MAPSET'] = mapset
  248. self.source_gisrc = utils.GetTempfile()
  249. try:
  250. f = open(self.source_gisrc, mode='w')
  251. for line in self.gisrc_dict.items():
  252. f.write(line[0] + ": " + line[1] + "\n")
  253. finally:
  254. f.close()
  255. return True
  256. def SwitchEnv(self, grc):
  257. """
  258. Switches between original working location/mapset and
  259. location/mapset that is source of file(s) to georectify
  260. """
  261. # check to see if we are georectifying map in current working
  262. # location/mapset
  263. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  264. return False
  265. if grc == 'target':
  266. os.environ['GISRC'] = str(self.target_gisrc)
  267. elif grc == 'source':
  268. os.environ['GISRC'] = str(self.source_gisrc)
  269. return True
  270. def OnWizFinished(self):
  271. # self.Cleanup()
  272. return True
  273. def OnGLMFocus(self, event):
  274. """Layer Manager focus"""
  275. # self.SwitchEnv('target')
  276. event.Skip()
  277. def Cleanup(self):
  278. """Return to current location and mapset"""
  279. # here was also the cleaning of gcpmanagement from layer manager
  280. # which is no longer needed
  281. self.SwitchEnv('target')
  282. self.wizard.Destroy()
  283. class LocationPage(TitledPage):
  284. """
  285. Set map type (raster or vector) to georectify and
  286. select location/mapset of map(s) to georectify.
  287. """
  288. def __init__(self, wizard, parent):
  289. TitledPage.__init__(self, wizard, _(
  290. "Select map type and location/mapset"))
  291. self.parent = parent
  292. self.grassdatabase = self.parent.grassdatabase
  293. self.xylocation = ''
  294. self.xymapset = ''
  295. #
  296. # layout
  297. #
  298. # map type
  299. self.rb_maptype = wx.RadioBox(
  300. parent=self, id=wx.ID_ANY, label=' %s ' %
  301. _("Map type to georectify"), choices=[
  302. _('raster'), _('vector')], majorDimension=wx.RA_SPECIFY_COLS)
  303. self.sizer.Add(self.rb_maptype,
  304. flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, border=5,
  305. pos=(1, 1), span=(1, 2))
  306. # location
  307. self.sizer.Add(
  308. StaticText(
  309. parent=self,
  310. id=wx.ID_ANY,
  311. label=_('Select source location:')),
  312. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  313. border=5,
  314. pos=(
  315. 2,
  316. 1))
  317. self.cb_location = LocationSelect(
  318. parent=self, gisdbase=self.grassdatabase)
  319. self.sizer.Add(
  320. self.cb_location,
  321. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  322. border=5,
  323. pos=(
  324. 2,
  325. 2))
  326. # mapset
  327. self.sizer.Add(
  328. StaticText(
  329. parent=self,
  330. id=wx.ID_ANY,
  331. label=_('Select source mapset:')),
  332. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  333. border=5,
  334. pos=(
  335. 3,
  336. 1))
  337. self.cb_mapset = MapsetSelect(parent=self, gisdbase=self.grassdatabase,
  338. setItems=False)
  339. self.sizer.Add(self.cb_mapset, flag=wx.ALIGN_LEFT |
  340. wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(3, 2))
  341. self.sizer.AddGrowableCol(2)
  342. #
  343. # bindings
  344. #
  345. self.Bind(wx.EVT_RADIOBOX, self.OnMaptype, self.rb_maptype)
  346. self.Bind(wx.EVT_COMBOBOX, self.OnLocation, self.cb_location)
  347. self.cb_mapset.Bind(wx.EVT_TEXT, self.OnMapset)
  348. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  349. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  350. # self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  351. def OnMaptype(self, event):
  352. """Change map type"""
  353. global maptype
  354. if event.GetInt() == 0:
  355. maptype = 'raster'
  356. else:
  357. maptype = 'vector'
  358. def OnLocation(self, event):
  359. """Sets source location for map(s) to georectify"""
  360. self.xylocation = event.GetString()
  361. # create a list of valid mapsets
  362. tmplist = os.listdir(os.path.join(self.grassdatabase, self.xylocation))
  363. self.mapsetList = []
  364. for item in tmplist:
  365. if os.path.isdir(os.path.join(self.grassdatabase, self.xylocation, item)) and \
  366. os.path.exists(os.path.join(self.grassdatabase, self.xylocation, item, 'WIND')):
  367. if item != 'PERMANENT':
  368. self.mapsetList.append(item)
  369. self.xymapset = 'PERMANENT'
  370. utils.ListSortLower(self.mapsetList)
  371. self.mapsetList.insert(0, 'PERMANENT')
  372. self.cb_mapset.SetItems(self.mapsetList)
  373. self.cb_mapset.SetStringSelection(self.xymapset)
  374. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  375. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  376. def OnMapset(self, event):
  377. """Sets source mapset for map(s) to georectify"""
  378. if self.xylocation == '':
  379. GMessage(_('You must select a valid location '
  380. 'before selecting a mapset'),
  381. parent=self)
  382. return
  383. self.xymapset = event.GetString()
  384. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  385. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  386. def OnPageChanging(self, event=None):
  387. if event.GetDirection() and \
  388. (self.xylocation == '' or self.xymapset == ''):
  389. GMessage(_('You must select a valid location '
  390. 'and mapset in order to continue'),
  391. parent=self)
  392. event.Veto()
  393. return
  394. self.parent.SetSrcEnv(self.xylocation, self.xymapset)
  395. def OnEnterPage(self, event=None):
  396. if self.xylocation == '' or self.xymapset == '':
  397. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  398. else:
  399. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  400. class GroupPage(TitledPage):
  401. """
  402. Set group to georectify. Create group if desired.
  403. """
  404. def __init__(self, wizard, parent):
  405. TitledPage.__init__(self, wizard, _(
  406. "Select image/map group to georectify"))
  407. self.parent = parent
  408. self.grassdatabase = self.parent.grassdatabase
  409. self.groupList = []
  410. self.xylocation = ''
  411. self.xymapset = ''
  412. self.xygroup = ''
  413. # default extension
  414. self.extension = '_georect' + str(os.getpid())
  415. #
  416. # layout
  417. #
  418. # group
  419. self.sizer.Add(
  420. StaticText(
  421. parent=self,
  422. id=wx.ID_ANY,
  423. label=_('Select/create group:')),
  424. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  425. border=5,
  426. pos=(
  427. 1,
  428. 1))
  429. self.cb_group = wx.ComboBox(parent=self, id=wx.ID_ANY,
  430. choices=self.groupList, size=(350, -1),
  431. style=wx.CB_DROPDOWN)
  432. self.sizer.Add(self.cb_group, flag=wx.ALIGN_LEFT |
  433. wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(1, 2))
  434. # create group
  435. self.sizer.Add(
  436. StaticText(
  437. parent=self,
  438. id=wx.ID_ANY,
  439. label=_('Create group if none exists')),
  440. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  441. border=5,
  442. pos=(
  443. 2,
  444. 1))
  445. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  446. self.btn_mkgroup = Button(
  447. parent=self,
  448. id=wx.ID_ANY,
  449. label=_("Create/edit group..."))
  450. self.btn_vgroup = Button(
  451. parent=self,
  452. id=wx.ID_ANY,
  453. label=_("Add vector map to group..."))
  454. btnSizer.Add(self.btn_mkgroup,
  455. flag=wx.RIGHT, border=5)
  456. btnSizer.Add(self.btn_vgroup,
  457. flag=wx.LEFT, border=5)
  458. self.sizer.Add(
  459. btnSizer,
  460. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  461. border=5,
  462. pos=(
  463. 2,
  464. 2))
  465. # extension
  466. self.sizer.Add(
  467. StaticText(
  468. parent=self,
  469. id=wx.ID_ANY,
  470. label=_('Extension for output maps:')),
  471. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  472. border=5,
  473. pos=(
  474. 3,
  475. 1))
  476. self.ext_txt = TextCtrl(
  477. parent=self, id=wx.ID_ANY, value="", size=(
  478. 350, -1))
  479. self.ext_txt.SetValue(self.extension)
  480. self.sizer.Add(self.ext_txt, flag=wx.ALIGN_LEFT |
  481. wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(3, 2))
  482. self.sizer.AddGrowableCol(2)
  483. #
  484. # bindings
  485. #
  486. self.Bind(wx.EVT_COMBOBOX, self.OnGroup, self.cb_group)
  487. self.Bind(wx.EVT_TEXT, self.OnExtension, self.ext_txt)
  488. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  489. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  490. self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  491. # hide vector group button by default
  492. self.btn_vgroup.Hide()
  493. def OnGroup(self, event):
  494. self.xygroup = event.GetString()
  495. def OnMkGroup(self, event):
  496. """Create new group in source location/mapset"""
  497. if self.xygroup == '':
  498. self.xygroup = self.cb_group.GetValue()
  499. dlg = GroupDialog(parent=self, defaultGroup=self.xygroup)
  500. dlg.DisableSubgroupEdit()
  501. dlg.ShowModal()
  502. gr, s = dlg.GetSelectedGroup()
  503. if gr in dlg.GetExistGroups():
  504. self.xygroup = gr
  505. else:
  506. gr = ''
  507. dlg.Destroy()
  508. self.OnEnterPage()
  509. self.Update()
  510. def OnVGroup(self, event):
  511. """Add vector maps to group"""
  512. if self.xygroup == '':
  513. self.xygroup = self.cb_group.GetValue()
  514. vector_dir = os.path.join(self.grassdatabase,
  515. self.xylocation,
  516. self.xymapset,
  517. 'vector')
  518. if os.path.exists(vector_dir):
  519. dlg = VectGroup(parent=self,
  520. id=wx.ID_ANY,
  521. grassdb=self.grassdatabase,
  522. location=self.xylocation,
  523. mapset=self.xymapset,
  524. group=self.xygroup)
  525. if dlg.ShowModal() != wx.ID_OK:
  526. return
  527. dlg.MakeVGroup()
  528. self.OnEnterPage()
  529. else:
  530. GError(parent=self, message=_('No vector maps.'))
  531. def OnExtension(self, event):
  532. self.extension = self.ext_txt.GetValue()
  533. def OnPageChanging(self, event=None):
  534. if event.GetDirection() and self.xygroup == '':
  535. GMessage(_('You must select a valid image/map '
  536. 'group in order to continue'),
  537. parent=self)
  538. event.Veto()
  539. return
  540. if event.GetDirection() and self.extension == '':
  541. GMessage(_('You must enter an map name '
  542. 'extension in order to continue'),
  543. parent=self)
  544. event.Veto()
  545. return
  546. def OnEnterPage(self, event=None):
  547. global maptype
  548. self.groupList = []
  549. self.xylocation = self.parent.gisrc_dict['LOCATION_NAME']
  550. self.xymapset = self.parent.gisrc_dict['MAPSET']
  551. # create a list of groups in selected mapset
  552. if os.path.isdir(os.path.join(self.grassdatabase,
  553. self.xylocation,
  554. self.xymapset,
  555. 'group')):
  556. tmplist = os.listdir(os.path.join(self.grassdatabase,
  557. self.xylocation,
  558. self.xymapset,
  559. 'group'))
  560. for item in tmplist:
  561. if os.path.isdir(os.path.join(self.grassdatabase,
  562. self.xylocation,
  563. self.xymapset,
  564. 'group',
  565. item)):
  566. self.groupList.append(item)
  567. if maptype == 'raster':
  568. self.btn_vgroup.Hide()
  569. self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
  570. elif maptype == 'vector':
  571. self.btn_vgroup.Show()
  572. self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
  573. self.Bind(wx.EVT_BUTTON, self.OnVGroup, self.btn_vgroup)
  574. utils.ListSortLower(self.groupList)
  575. self.cb_group.SetItems(self.groupList)
  576. if len(self.groupList) > 0:
  577. if self.xygroup and self.xygroup in self.groupList:
  578. self.cb_group.SetStringSelection(self.xygroup)
  579. else:
  580. self.cb_group.SetSelection(0)
  581. self.xygroup = self.groupList[0]
  582. if self.xygroup == '' or \
  583. self.extension == '':
  584. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  585. else:
  586. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  587. # switch to source
  588. self.parent.SwitchEnv('source')
  589. class DispMapPage(TitledPage):
  590. """
  591. Select ungeoreferenced map to display for interactively
  592. setting ground control points (GCPs).
  593. """
  594. def __init__(self, wizard, parent):
  595. TitledPage.__init__(
  596. self, wizard,
  597. _("Select maps to display for ground control point (GCP) creation"))
  598. self.parent = parent
  599. global maptype
  600. #
  601. # layout
  602. #
  603. self.sizer.Add(
  604. StaticText(
  605. parent=self,
  606. id=wx.ID_ANY,
  607. label=_('Select source map to display:')),
  608. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  609. border=5,
  610. pos=(
  611. 1,
  612. 1))
  613. self.srcselection = Select(
  614. self,
  615. id=wx.ID_ANY,
  616. size=globalvar.DIALOG_GSELECT_SIZE,
  617. type=maptype,
  618. updateOnPopup=False)
  619. self.sizer.Add(
  620. self.srcselection,
  621. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  622. border=5,
  623. pos=(
  624. 1,
  625. 2))
  626. self.sizer.Add(
  627. StaticText(
  628. parent=self,
  629. id=wx.ID_ANY,
  630. label=_('Select target raster map to display:')),
  631. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  632. border=5,
  633. pos=(
  634. 2,
  635. 1))
  636. self.tgtrastselection = Select(
  637. self, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  638. type='raster', updateOnPopup=False)
  639. self.sizer.Add(
  640. self.tgtrastselection,
  641. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  642. border=5,
  643. pos=(
  644. 2,
  645. 2))
  646. self.sizer.Add(
  647. StaticText(
  648. parent=self,
  649. id=wx.ID_ANY,
  650. label=_('Select target vector map to display:')),
  651. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  652. border=5,
  653. pos=(
  654. 3,
  655. 1))
  656. self.tgtvectselection = Select(
  657. self, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  658. type='vector', updateOnPopup=False)
  659. self.sizer.Add(
  660. self.tgtvectselection,
  661. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  662. border=5,
  663. pos=(
  664. 3,
  665. 2))
  666. #
  667. # bindings
  668. #
  669. self.srcselection.Bind(wx.EVT_TEXT, self.OnSrcSelection)
  670. self.tgtrastselection.Bind(wx.EVT_TEXT, self.OnTgtRastSelection)
  671. self.tgtvectselection.Bind(wx.EVT_TEXT, self.OnTgtVectSelection)
  672. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  673. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  674. self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  675. def OnSrcSelection(self, event):
  676. """Source map to display selected"""
  677. global src_map
  678. global maptype
  679. src_map = self.srcselection.GetValue()
  680. if src_map == '':
  681. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  682. else:
  683. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  684. try:
  685. # set computational region to match selected map and zoom display
  686. # to region
  687. if maptype == 'raster':
  688. p = RunCommand('g.region', 'raster=src_map')
  689. elif maptype == 'vector':
  690. p = RunCommand('g.region', 'vector=src_map')
  691. if p.returncode == 0:
  692. print('returncode = ', str(p.returncode))
  693. self.parent.Map.region = self.parent.Map.GetRegion()
  694. except:
  695. pass
  696. def OnTgtRastSelection(self, event):
  697. """Source map to display selected"""
  698. global tgt_map
  699. tgt_map['raster'] = self.tgtrastselection.GetValue()
  700. def OnTgtVectSelection(self, event):
  701. """Source map to display selected"""
  702. global tgt_map
  703. tgt_map['vector'] = self.tgtvectselection.GetValue()
  704. def OnPageChanging(self, event=None):
  705. global src_map
  706. global tgt_map
  707. if event.GetDirection() and (src_map == ''):
  708. GMessage(_('You must select a source map '
  709. 'in order to continue'),
  710. parent=self)
  711. event.Veto()
  712. return
  713. self.parent.SwitchEnv('target')
  714. def OnEnterPage(self, event=None):
  715. global maptype
  716. global src_map
  717. global tgt_map
  718. self.srcselection.SetElementList(maptype)
  719. if maptype == 'raster':
  720. ret = RunCommand('i.group',
  721. parent=self,
  722. read=True,
  723. group=self.parent.grouppage.xygroup,
  724. flags='g')
  725. if ret:
  726. self.parent.src_maps = ret.splitlines()
  727. else:
  728. GError(
  729. parent=self, message=_(
  730. 'No maps in selected group <%s>.\n'
  731. 'Please edit group or select another group.') %
  732. self.parent.grouppage.xygroup)
  733. return
  734. elif maptype == 'vector':
  735. grassdatabase = self.parent.grassdatabase
  736. xylocation = self.parent.gisrc_dict['LOCATION_NAME']
  737. xymapset = self.parent.gisrc_dict['MAPSET']
  738. # make list of vectors to georectify from VREF
  739. vgrpfile = os.path.join(grassdatabase,
  740. xylocation,
  741. xymapset,
  742. 'group',
  743. self.parent.grouppage.xygroup,
  744. 'VREF')
  745. f = open(vgrpfile)
  746. try:
  747. for vect in f.readlines():
  748. vect = vect.strip('\n')
  749. if len(vect) < 1:
  750. continue
  751. self.parent.src_maps.append(vect)
  752. finally:
  753. f.close()
  754. if len(self.parent.src_maps) < 1:
  755. GError(
  756. parent=self, message=_(
  757. 'No maps in selected group <%s>.\n'
  758. 'Please edit group or select another group.') %
  759. self.parent.grouppage.xygroup)
  760. return
  761. # filter out all maps not in group
  762. self.srcselection.tcp.GetElementList(elements=self.parent.src_maps)
  763. src_map = self.parent.src_maps[0]
  764. self.srcselection.SetValue(src_map)
  765. self.parent.SwitchEnv('target')
  766. self.tgtrastselection.SetElementList('raster')
  767. self.tgtrastselection.GetElementList()
  768. self.tgtvectselection.SetElementList('vector')
  769. self.tgtvectselection.GetElementList()
  770. self.parent.SwitchEnv('source')
  771. if src_map == '':
  772. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  773. else:
  774. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  775. class GCP(MapFrame, ColumnSorterMixin):
  776. """
  777. Manages ground control points for georectifying. Calculates RMS statistics.
  778. Calls i.rectify or v.rectify to georectify map.
  779. """
  780. def __init__(self, parent, giface, grwiz=None, id=wx.ID_ANY,
  781. title=_("Manage Ground Control Points"),
  782. size=(700, 300), toolbars=["gcpdisp"], Map=None, lmgr=None):
  783. self.grwiz = grwiz # GR Wizard
  784. self._giface = giface
  785. if tgt_map['raster'] == '' and tgt_map['vector'] == '':
  786. self.show_target = False
  787. else:
  788. self.show_target = True
  789. #wx.Frame.__init__(self, parent, id, title, size = size, name = "GCPFrame")
  790. MapFrame.__init__(
  791. self,
  792. parent=parent,
  793. giface=self._giface,
  794. title=title,
  795. size=size,
  796. Map=Map,
  797. toolbars=toolbars,
  798. name='GCPMapWindow')
  799. # init variables
  800. self.parent = parent
  801. #
  802. # register data structures for drawing GCP's
  803. #
  804. self.pointsToDrawTgt = self.TgtMapWindow.RegisterGraphicsToDraw(
  805. graphicsType="point", setStatusFunc=self.SetGCPSatus)
  806. self.pointsToDrawSrc = self.SrcMapWindow.RegisterGraphicsToDraw(
  807. graphicsType="point", setStatusFunc=self.SetGCPSatus)
  808. # connect to the map windows signals
  809. # used to add or edit GCP
  810. self.SrcMapWindow.mouseLeftUpPointer.connect(
  811. lambda x, y:
  812. self._onMouseLeftUpPointer(self.SrcMapWindow, x, y))
  813. self.TgtMapWindow.mouseLeftUpPointer.connect(
  814. lambda x, y:
  815. self._onMouseLeftUpPointer(self.TgtMapWindow, x, y))
  816. # window resized
  817. self.resize = False
  818. self.grassdatabase = self.grwiz.grassdatabase
  819. self.currentlocation = self.grwiz.currentlocation
  820. self.currentmapset = self.grwiz.currentmapset
  821. self.newlocation = self.grwiz.newlocation
  822. self.newmapset = self.grwiz.newmapset
  823. self.xylocation = self.grwiz.gisrc_dict['LOCATION_NAME']
  824. self.xymapset = self.grwiz.gisrc_dict['MAPSET']
  825. self.xygroup = self.grwiz.grouppage.xygroup
  826. self.src_maps = self.grwiz.src_maps
  827. self.extension = self.grwiz.grouppage.extension
  828. self.outname = ''
  829. self.VectGRList = []
  830. self.file = {
  831. 'points': os.path.join(self.grassdatabase,
  832. self.xylocation,
  833. self.xymapset,
  834. 'group',
  835. self.xygroup,
  836. 'POINTS'),
  837. 'points_bak': os.path.join(self.grassdatabase,
  838. self.xylocation,
  839. self.xymapset,
  840. 'group',
  841. self.xygroup,
  842. 'POINTS_BAK'),
  843. 'rgrp': os.path.join(self.grassdatabase,
  844. self.xylocation,
  845. self.xymapset,
  846. 'group',
  847. self.xygroup,
  848. 'REF'),
  849. 'vgrp': os.path.join(self.grassdatabase,
  850. self.xylocation,
  851. self.xymapset,
  852. 'group',
  853. self.xygroup,
  854. 'VREF'),
  855. 'target': os.path.join(self.grassdatabase,
  856. self.xylocation,
  857. self.xymapset,
  858. 'group',
  859. self.xygroup,
  860. 'TARGET'),
  861. }
  862. # make a backup of the current points file
  863. if os.path.exists(self.file['points']):
  864. shutil.copy(self.file['points'], self.file['points_bak'])
  865. # polynomial order transformation for georectification
  866. self.gr_order = 1
  867. # interpolation method for georectification
  868. self.gr_method = 'nearest'
  869. # region clipping for georectified map
  870. self.clip_to_region = False
  871. # number of GCPs selected to be used for georectification (checked)
  872. self.GCPcount = 0
  873. # forward RMS error
  874. self.fwd_rmserror = 0.0
  875. # backward RMS error
  876. self.bkw_rmserror = 0.0
  877. # list map coords and ID of map display they came from
  878. self.mapcoordlist = []
  879. self.mapcoordlist.append([0, # GCP number
  880. 0.0, # source east
  881. 0.0, # source north
  882. 0.0, # target east
  883. 0.0, # target north
  884. 0.0, # forward error
  885. 0.0]) # backward error
  886. # init vars to highlight high RMS errors
  887. self.highest_only = True
  888. self.show_unused = True
  889. self.highest_key = -1
  890. self.rmsthresh = 0
  891. self.rmsmean = 0
  892. self.rmssd = 0
  893. self.SetTarget(self.xygroup, self.currentlocation, self.currentmapset)
  894. self.itemDataMap = None
  895. # images for column sorting
  896. # CheckListCtrlMixin must set an ImageList first
  897. self.il = self.list.GetImageList(wx.IMAGE_LIST_SMALL)
  898. SmallUpArrow = BitmapFromImage(getSmallUpArrowImage())
  899. SmallDnArrow = BitmapFromImage(getSmallDnArrowImage())
  900. self.sm_dn = self.il.Add(SmallDnArrow)
  901. self.sm_up = self.il.Add(SmallUpArrow)
  902. # set mouse characteristics
  903. self.mapwin = self.SrcMapWindow
  904. self.mapwin.mouse['box'] = 'point'
  905. self.mapwin.mouse["use"] == "pointer"
  906. self.mapwin.zoomtype = 0
  907. self.mapwin.pen = wx.Pen(colour='black', width=2, style=wx.SOLID)
  908. self.mapwin.SetNamedCursor('cross')
  909. self.mapwin = self.TgtMapWindow
  910. # set mouse characteristics
  911. self.mapwin.mouse['box'] = 'point'
  912. self.mapwin.mouse["use"] == "pointer"
  913. self.mapwin.zoomtype = 0
  914. self.mapwin.pen = wx.Pen(colour='black', width=2, style=wx.SOLID)
  915. self.mapwin.SetNamedCursor('cross')
  916. #
  917. # show new display & draw map
  918. #
  919. if self.show_target:
  920. self.MapWindow = self.TgtMapWindow
  921. self.Map = self.TgtMap
  922. self.OnZoomToMap(None)
  923. self.MapWindow = self.SrcMapWindow
  924. self.Map = self.SrcMap
  925. self.OnZoomToMap(None)
  926. #
  927. # bindings
  928. #
  929. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  930. self.Bind(wx.EVT_SIZE, self.OnSize)
  931. self.Bind(wx.EVT_IDLE, self.OnIdle)
  932. self.Bind(wx.EVT_CLOSE, self.OnQuit)
  933. self.SetSettings()
  934. def __del__(self):
  935. """Disable GCP manager mode"""
  936. # leaving the method here but was used only to delete gcpmanagement
  937. # from layer manager which is now not needed
  938. pass
  939. def CreateGCPList(self):
  940. """Create GCP List Control"""
  941. return GCPList(parent=self, gcp=self)
  942. # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
  943. def GetListCtrl(self):
  944. return self.list
  945. def GetMapCoordList(self):
  946. return self.mapcoordlist
  947. # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
  948. def GetSortImages(self):
  949. return (self.sm_dn, self.sm_up)
  950. def GetFwdError(self):
  951. return self.fwd_rmserror
  952. def GetBkwError(self):
  953. return self.bkw_rmserror
  954. def InitMapDisplay(self):
  955. self.list.LoadData()
  956. # initialize column sorter
  957. self.itemDataMap = self.mapcoordlist
  958. ncols = self.list.GetColumnCount()
  959. ColumnSorterMixin.__init__(self, ncols)
  960. # init to ascending sort on first click
  961. self._colSortFlag = [1] * ncols
  962. def SetTarget(self, tgroup, tlocation, tmapset):
  963. """
  964. Sets rectification target to current location and mapset
  965. """
  966. # check to see if we are georectifying map in current working
  967. # location/mapset
  968. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  969. RunCommand('i.target',
  970. parent=self,
  971. flags='c',
  972. group=tgroup)
  973. else:
  974. self.grwiz.SwitchEnv('source')
  975. RunCommand('i.target',
  976. parent=self,
  977. group=tgroup,
  978. location=tlocation,
  979. mapset=tmapset)
  980. self.grwiz.SwitchEnv('target')
  981. def AddGCP(self, event):
  982. """
  983. Appends an item to GCP list
  984. """
  985. keyval = self.list.AddGCPItem() + 1
  986. # source east, source north, target east, target north, forward error,
  987. # backward error
  988. self.mapcoordlist.append([keyval, # GCP number
  989. 0.0, # source east
  990. 0.0, # source north
  991. 0.0, # target east
  992. 0.0, # target north
  993. 0.0, # forward error
  994. 0.0]) # backward error
  995. if self.statusbarManager.GetMode() == 8: # go to
  996. self.StatusbarUpdate()
  997. def DeleteGCP(self, event):
  998. """
  999. Deletes selected item in GCP list
  1000. """
  1001. minNumOfItems = self.OnGROrder(None)
  1002. if self.list.GetItemCount() <= minNumOfItems:
  1003. GMessage(
  1004. parent=self,
  1005. message=_("At least %d GCPs required. Operation canceled.") %
  1006. minNumOfItems)
  1007. return
  1008. key = self.list.DeleteGCPItem()
  1009. del self.mapcoordlist[key]
  1010. # update key and GCP number
  1011. for newkey in range(key, len(self.mapcoordlist)):
  1012. index = self.list.FindItemData(-1, newkey + 1)
  1013. self.mapcoordlist[newkey][0] = newkey
  1014. self.list.SetItem(index, 0, str(newkey))
  1015. self.list.SetItemData(index, newkey)
  1016. # update selected
  1017. if self.list.GetItemCount() > 0:
  1018. if self.list.selected < self.list.GetItemCount():
  1019. self.list.selectedkey = self.list.GetItemData(
  1020. self.list.selected)
  1021. else:
  1022. self.list.selected = self.list.GetItemCount() - 1
  1023. self.list.selectedkey = self.list.GetItemData(
  1024. self.list.selected)
  1025. self.list.SetItemState(self.list.selected,
  1026. wx.LIST_STATE_SELECTED,
  1027. wx.LIST_STATE_SELECTED)
  1028. else:
  1029. self.list.selected = wx.NOT_FOUND
  1030. self.list.selectedkey = -1
  1031. self.UpdateColours()
  1032. if self.statusbarManager.GetMode() == 8: # go to
  1033. self.StatusbarUpdate()
  1034. if self.list.selectedkey > 0:
  1035. self.statusbarManager.SetProperty(
  1036. 'gotoGCP', self.list.selectedkey)
  1037. def ClearGCP(self, event):
  1038. """
  1039. Clears all values in selected item of GCP list and unchecks it
  1040. """
  1041. index = self.list.GetSelected()
  1042. key = self.list.GetItemData(index)
  1043. for i in range(1, 5):
  1044. self.list.SetItem(index, i, '0.0')
  1045. self.list.SetItem(index, 5, '')
  1046. self.list.SetItem(index, 6, '')
  1047. self.list.CheckItem(index, False)
  1048. # GCP number, source E, source N, target E, target N, fwd error, bkwd
  1049. # error
  1050. self.mapcoordlist[key] = [key, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
  1051. def SetSettings(self):
  1052. """Sets settings for drawing of GCP's.
  1053. """
  1054. self.highest_only = UserSettings.Get(
  1055. group='gcpman', key='rms', subkey='highestonly')
  1056. self.show_unused = UserSettings.Get(
  1057. group='gcpman', key='symbol', subkey='unused')
  1058. colours = {"color": "default",
  1059. "hcolor": "highest",
  1060. "scolor": "selected",
  1061. "ucolor": "unused"}
  1062. wpx = UserSettings.Get(group='gcpman', key='symbol', subkey='width')
  1063. for k, v in six.iteritems(colours):
  1064. col = UserSettings.Get(group='gcpman', key='symbol', subkey=k)
  1065. self.pointsToDrawSrc.GetPen(v).SetColour(wx.Colour(
  1066. col[0], col[1], col[2], 255)) # TODO GetPen neni to spatne?
  1067. self.pointsToDrawTgt.GetPen(v).SetColour(
  1068. wx.Colour(col[0], col[1], col[2], 255))
  1069. self.pointsToDrawSrc.GetPen(v).SetWidth(wpx)
  1070. self.pointsToDrawTgt.GetPen(v).SetWidth(wpx)
  1071. spx = UserSettings.Get(group='gcpman', key='symbol', subkey='size')
  1072. self.pointsToDrawSrc.SetPropertyVal("size", int(spx))
  1073. self.pointsToDrawTgt.SetPropertyVal("size", int(spx))
  1074. font = self.GetFont()
  1075. font.SetPointSize(int(spx) + 2)
  1076. textProp = {}
  1077. textProp['active'] = True
  1078. textProp['font'] = font
  1079. self.pointsToDrawSrc.SetPropertyVal("text", textProp)
  1080. self.pointsToDrawTgt.SetPropertyVal("text", copy(textProp))
  1081. def SetGCPSatus(self, item, itemIndex):
  1082. """Before GCP is drawn, decides it's colour and whether it
  1083. will be drawed.
  1084. """
  1085. key = self.list.GetItemData(itemIndex)
  1086. # incremented because of itemDataMap (has one more item) - will be
  1087. # changed
  1088. itemIndex += 1
  1089. if not self.list.IsItemChecked(key - 1):
  1090. wxPen = "unused"
  1091. if not self.show_unused:
  1092. item.SetPropertyVal('hide', True)
  1093. else:
  1094. item.SetPropertyVal('hide', False)
  1095. else:
  1096. item.SetPropertyVal('hide', False)
  1097. if self.highest_only:
  1098. if itemIndex == self.highest_key:
  1099. wxPen = "highest"
  1100. else:
  1101. wxPen = "default"
  1102. else:
  1103. if (self.mapcoordlist[key][5] > self.rmsthresh):
  1104. wxPen = "highest"
  1105. else:
  1106. wxPen = "default"
  1107. if itemIndex == self.list.selectedkey:
  1108. wxPen = "selected"
  1109. item.SetPropertyVal('label', str(itemIndex))
  1110. item.SetPropertyVal('penName', wxPen)
  1111. def SetGCPData(self, coordtype, coord, mapdisp=None, confirm=False):
  1112. """Inserts coordinates from file, mouse click on map, or
  1113. after editing into selected item of GCP list and checks it for
  1114. use.
  1115. """
  1116. index = self.list.GetSelected()
  1117. if index == wx.NOT_FOUND:
  1118. return
  1119. coord0 = coord[0]
  1120. coord1 = coord[1]
  1121. key = self.list.GetItemData(index)
  1122. if confirm:
  1123. if self.MapWindow == self.SrcMapWindow:
  1124. currloc = _("source")
  1125. else:
  1126. currloc = _("target")
  1127. ret = wx.MessageBox(
  1128. parent=self, caption=_("Set GCP coordinates"),
  1129. message=_(
  1130. 'Set %(coor)s coordinates for GCP No. %(key)s? \n\n'
  1131. 'East: %(coor0)s \n'
  1132. 'North: %(coor1)s') %
  1133. {'coor': currloc, 'key': str(key),
  1134. 'coor0': str(coord0),
  1135. 'coor1': str(coord1)},
  1136. style=wx.ICON_QUESTION | wx.YES_NO | wx.CENTRE)
  1137. # for wingrass
  1138. if os.name == 'nt':
  1139. self.MapWindow.SetFocus()
  1140. if ret == wx.NO:
  1141. return
  1142. if coordtype == 'source':
  1143. self.list.SetItem(index, 1, str(coord0))
  1144. self.list.SetItem(index, 2, str(coord1))
  1145. self.mapcoordlist[key][1] = coord[0]
  1146. self.mapcoordlist[key][2] = coord[1]
  1147. self.pointsToDrawSrc.GetItem(key - 1).SetCoords([coord0, coord1])
  1148. elif coordtype == 'target':
  1149. self.list.SetItem(index, 3, str(coord0))
  1150. self.list.SetItem(index, 4, str(coord1))
  1151. self.mapcoordlist[key][3] = coord[0]
  1152. self.mapcoordlist[key][4] = coord[1]
  1153. self.pointsToDrawTgt.GetItem(key - 1).SetCoords([coord0, coord1])
  1154. self.list.SetItem(index, 5, '0')
  1155. self.list.SetItem(index, 6, '0')
  1156. self.mapcoordlist[key][5] = 0.0
  1157. self.mapcoordlist[key][6] = 0.0
  1158. # self.list.ResizeColumns()
  1159. def SaveGCPs(self, event):
  1160. """Make a POINTS file or save GCP coordinates to existing
  1161. POINTS file
  1162. """
  1163. self.GCPcount = 0
  1164. try:
  1165. f = open(self.file['points'], mode='w')
  1166. # use os.linesep or '\n' here ???
  1167. f.write('# Ground Control Points File\n')
  1168. f.write("# \n")
  1169. f.write("# target location: " + self.currentlocation + '\n')
  1170. f.write("# target mapset: " + self.currentmapset + '\n')
  1171. f.write("#\tsource\t\ttarget\t\tstatus\n")
  1172. f.write("#\teast\tnorth\teast\tnorth\t(1=ok, 0=ignore)\n")
  1173. f.write(
  1174. "#----------------------- ----------------------- ---------------\n")
  1175. for index in range(self.list.GetItemCount()):
  1176. if self.list.IsItemChecked(index):
  1177. check = "1"
  1178. self.GCPcount += 1
  1179. else:
  1180. check = "0"
  1181. coord0 = self.list.GetItem(index, 1).GetText()
  1182. coord1 = self.list.GetItem(index, 2).GetText()
  1183. coord2 = self.list.GetItem(index, 3).GetText()
  1184. coord3 = self.list.GetItem(index, 4).GetText()
  1185. f.write(
  1186. coord0 +
  1187. ' ' +
  1188. coord1 +
  1189. ' ' +
  1190. coord2 +
  1191. ' ' +
  1192. coord3 +
  1193. ' ' +
  1194. check +
  1195. '\n')
  1196. except IOError as err:
  1197. GError(
  1198. parent=self,
  1199. message="%s <%s>. %s%s" %
  1200. (_("Writing POINTS file failed"),
  1201. self.file['points'],
  1202. os.linesep,
  1203. err))
  1204. return
  1205. f.close()
  1206. # if event != None save also to backup file
  1207. if event:
  1208. shutil.copy(self.file['points'], self.file['points_bak'])
  1209. self._giface.WriteLog(
  1210. _('POINTS file saved for group <%s>') %
  1211. self.xygroup)
  1212. #self.SetStatusText(_('POINTS file saved'))
  1213. def ReadGCPs(self):
  1214. """
  1215. Reads GCPs and georectified coordinates from POINTS file
  1216. """
  1217. self.GCPcount = 0
  1218. sourceMapWin = self.SrcMapWindow
  1219. targetMapWin = self.TgtMapWindow
  1220. if not sourceMapWin:
  1221. GError(parent=self,
  1222. message="%s. %s%s" % (_("source mapwin not defined"),
  1223. os.linesep, err))
  1224. if not targetMapWin:
  1225. GError(parent=self,
  1226. message="%s. %s%s" % (_("target mapwin not defined"),
  1227. os.linesep, err))
  1228. try:
  1229. f = open(self.file['points'], 'r')
  1230. GCPcnt = 0
  1231. for line in f.readlines():
  1232. if line[0] == '#' or line == '':
  1233. continue
  1234. line = line.replace('\n', '').strip()
  1235. coords = list(map(float, line.split()))
  1236. if coords[4] == 1:
  1237. check = True
  1238. self.GCPcount += 1
  1239. else:
  1240. check = False
  1241. self.AddGCP(event=None)
  1242. self.SetGCPData('source', (coords[0], coords[1]), sourceMapWin)
  1243. self.SetGCPData('target', (coords[2], coords[3]), targetMapWin)
  1244. index = self.list.GetSelected()
  1245. if index != wx.NOT_FOUND:
  1246. self.list.CheckItem(index, check)
  1247. GCPcnt += 1
  1248. except IOError as err:
  1249. GError(
  1250. parent=self,
  1251. message="%s <%s>. %s%s" %
  1252. (_("Reading POINTS file failed"),
  1253. self.file['points'],
  1254. os.linesep,
  1255. err))
  1256. return
  1257. f.close()
  1258. if GCPcnt == 0:
  1259. # 3 gcp is minimum
  1260. for i in range(3):
  1261. self.AddGCP(None)
  1262. if self.CheckGCPcount():
  1263. # calculate RMS
  1264. self.RMSError(self.xygroup, self.gr_order)
  1265. def ReloadGCPs(self, event):
  1266. """Reload data from file"""
  1267. # use backup
  1268. shutil.copy(self.file['points_bak'], self.file['points'])
  1269. # delete all items in mapcoordlist
  1270. self.mapcoordlist = []
  1271. self.mapcoordlist.append([0, # GCP number
  1272. 0.0, # source east
  1273. 0.0, # source north
  1274. 0.0, # target east
  1275. 0.0, # target north
  1276. 0.0, # forward error
  1277. 0.0]) # backward error
  1278. self.list.LoadData()
  1279. self.itemDataMap = self.mapcoordlist
  1280. if self._col != -1:
  1281. self.list.ClearColumnImage(self._col)
  1282. self._colSortFlag = [1] * self.list.GetColumnCount()
  1283. # draw GCPs (source and target)
  1284. sourceMapWin = self.SrcMapWindow
  1285. sourceMapWin.UpdateMap(render=False, renderVector=False)
  1286. if self.show_target:
  1287. targetMapWin = self.TgtMapWindow
  1288. targetMapWin.UpdateMap(render=False, renderVector=False)
  1289. def OnFocus(self, event):
  1290. # TODO: it is here just to remove old or obsolate beavior of base class gcp/MapFrame?
  1291. # self.grwiz.SwitchEnv('source')
  1292. pass
  1293. def _onMouseLeftUpPointer(self, mapWindow, x, y):
  1294. if mapWindow == self.SrcMapWindow:
  1295. coordtype = 'source'
  1296. else:
  1297. coordtype = 'target'
  1298. coord = (x, y)
  1299. self.SetGCPData(coordtype, coord, self, confirm=True)
  1300. mapWindow.UpdateMap(render=False, renderVector=False)
  1301. def OnRMS(self, event):
  1302. """
  1303. RMS button handler
  1304. """
  1305. self.RMSError(self.xygroup, self.gr_order)
  1306. sourceMapWin = self.SrcMapWindow
  1307. sourceMapWin.UpdateMap(render=False, renderVector=False)
  1308. if self.show_target:
  1309. targetMapWin = self.TgtMapWindow
  1310. targetMapWin.UpdateMap(render=False, renderVector=False)
  1311. def CheckGCPcount(self, msg=False):
  1312. """
  1313. Checks to make sure that the minimum number of GCPs have been defined and
  1314. are active for the selected transformation order
  1315. """
  1316. if (self.GCPcount < 3 and self.gr_order == 1) or \
  1317. (self.GCPcount < 6 and self.gr_order == 2) or \
  1318. (self.GCPcount < 10 and self.gr_order == 3):
  1319. if msg:
  1320. GWarning(
  1321. parent=self, message=_(
  1322. 'Insufficient points defined and active (checked) '
  1323. 'for selected rectification method (order: %d).\n'
  1324. '3+ points needed for 1st order,\n'
  1325. '6+ points for 2nd order, and\n'
  1326. '10+ points for 3rd order.') %
  1327. self.gr_order)
  1328. return False
  1329. else:
  1330. return True
  1331. def OnGeorect(self, event):
  1332. """
  1333. Georectifies map(s) in group using i.rectify or v.transform
  1334. """
  1335. global maptype
  1336. self.SaveGCPs(None)
  1337. if not self.CheckGCPcount(msg=True):
  1338. return
  1339. if maptype == 'raster':
  1340. self.grwiz.SwitchEnv('source')
  1341. if self.clip_to_region:
  1342. flags = "ac"
  1343. else:
  1344. flags = "a"
  1345. busy = wx.BusyInfo(_("Rectifying images, please wait..."),
  1346. parent=self)
  1347. wx.GetApp().Yield()
  1348. ret, msg = RunCommand('i.rectify',
  1349. parent=self,
  1350. getErrorMsg=True,
  1351. quiet=True,
  1352. group=self.xygroup,
  1353. extension=self.extension,
  1354. order=self.gr_order,
  1355. method=self.gr_method,
  1356. flags=flags)
  1357. del busy
  1358. # provide feedback on failure
  1359. if ret != 0:
  1360. print(msg, file=sys.stderr)
  1361. elif maptype == 'vector':
  1362. # loop through all vectors in VREF
  1363. self.grwiz.SwitchEnv('source')
  1364. # make list of vectors to georectify from VREF
  1365. f = open(self.file['vgrp'])
  1366. vectlist = []
  1367. try:
  1368. for vect in f.readlines():
  1369. vect = vect.strip('\n')
  1370. if len(vect) < 1:
  1371. continue
  1372. vectlist.append(vect)
  1373. finally:
  1374. f.close()
  1375. # georectify each vector in VREF using v.rectify
  1376. for vect in vectlist:
  1377. self.outname = str(vect.split('@')[0]) + self.extension
  1378. self._giface.WriteLog(text=_('Transforming <%s>...') % vect,
  1379. notification=Notification.MAKE_VISIBLE)
  1380. ret = msg = ''
  1381. busy = wx.BusyInfo(
  1382. _("Rectifying vector map <%s>, please wait...") %
  1383. vect, parent=self)
  1384. wx.GetApp().Yield()
  1385. ret, msg = RunCommand('v.rectify',
  1386. parent=self,
  1387. getErrorMsg=True,
  1388. quiet=True,
  1389. input=vect,
  1390. output=self.outname,
  1391. group=self.xygroup,
  1392. order=self.gr_order)
  1393. del busy
  1394. # provide feedback on failure
  1395. if ret != 0:
  1396. print(msg, file=sys.stderr)
  1397. self.grwiz.SwitchEnv('target')
  1398. def OnGeorectDone(self, **kargs):
  1399. """Print final message"""
  1400. global maptype
  1401. if maptype == 'raster':
  1402. return
  1403. returncode = kargs['returncode']
  1404. if returncode == 0:
  1405. self.VectGRList.append(self.outname)
  1406. print('*****vector list = ' + str(self.VectGRList))
  1407. else:
  1408. self._giface.WriteError(
  1409. _('Georectification of vector map <%s> failed') %
  1410. self.outname)
  1411. def OnSettings(self, event):
  1412. """GCP Manager settings"""
  1413. dlg = GrSettingsDialog(parent=self, giface=self._giface,
  1414. id=wx.ID_ANY, title=_('GCP Manager settings'))
  1415. if dlg.ShowModal() == wx.ID_OK:
  1416. pass
  1417. dlg.Destroy()
  1418. def UpdateColours(self, srcrender=False, srcrenderVector=False,
  1419. tgtrender=False, tgtrenderVector=False):
  1420. """update colours"""
  1421. highest_fwd_err = 0.0
  1422. self.highest_key = 0
  1423. highest_idx = 0
  1424. for index in range(self.list.GetItemCount()):
  1425. if self.list.IsItemChecked(index):
  1426. key = self.list.GetItemData(index)
  1427. fwd_err = self.mapcoordlist[key][5]
  1428. if self.highest_only:
  1429. self.list.SetItemTextColour(index, wx.BLACK)
  1430. if highest_fwd_err < fwd_err:
  1431. highest_fwd_err = fwd_err
  1432. self.highest_key = key
  1433. highest_idx = index
  1434. elif self.rmsthresh > 0:
  1435. if (fwd_err > self.rmsthresh):
  1436. self.list.SetItemTextColour(index, wx.RED)
  1437. else:
  1438. self.list.SetItemTextColour(index, wx.BLACK)
  1439. else:
  1440. self.list.SetItemTextColour(index, wx.BLACK)
  1441. if self.highest_only and highest_fwd_err > 0.0:
  1442. self.list.SetItemTextColour(highest_idx, wx.RED)
  1443. sourceMapWin = self.SrcMapWindow
  1444. sourceMapWin.UpdateMap(render=srcrender, renderVector=srcrenderVector)
  1445. if self.show_target:
  1446. targetMapWin = self.TgtMapWindow
  1447. targetMapWin.UpdateMap(
  1448. render=tgtrender,
  1449. renderVector=tgtrenderVector)
  1450. def OnQuit(self, event):
  1451. """Quit georectifier"""
  1452. ret = wx.MessageBox(
  1453. parent=self, caption=_("Quit GCP Manager"),
  1454. message=_('Save ground control points?'),
  1455. style=wx.ICON_QUESTION | wx.YES_NO | wx.CANCEL | wx.CENTRE)
  1456. if ret != wx.CANCEL:
  1457. if ret == wx.YES:
  1458. self.SaveGCPs(None)
  1459. elif ret == wx.NO:
  1460. # restore POINTS file from backup
  1461. if os.path.exists(self.file['points_bak']):
  1462. shutil.copy(self.file['points_bak'], self.file['points'])
  1463. if os.path.exists(self.file['points_bak']):
  1464. os.unlink(self.file['points_bak'])
  1465. self.SrcMap.Clean()
  1466. self.TgtMap.Clean()
  1467. self.grwiz.Cleanup()
  1468. self._mgr.UnInit()
  1469. self.Destroy()
  1470. # event.Skip()
  1471. def OnGROrder(self, event):
  1472. """
  1473. sets transformation order for georectifying
  1474. """
  1475. if event:
  1476. self.gr_order = event.GetInt() + 1
  1477. numOfItems = self.list.GetItemCount()
  1478. minNumOfItems = numOfItems
  1479. if self.gr_order == 1:
  1480. minNumOfItems = 3
  1481. # self.SetStatusText(_('Insufficient points, 3+ points needed for 1st order'))
  1482. elif self.gr_order == 2:
  1483. minNumOfItems = 6
  1484. diff = 6 - numOfItems
  1485. # self.SetStatusText(_('Insufficient points, 6+ points needed for 2nd order'))
  1486. elif self.gr_order == 3:
  1487. minNumOfItems = 10
  1488. # self.SetStatusText(_('Insufficient points, 10+ points needed for 3rd order'))
  1489. for i in range(minNumOfItems - numOfItems):
  1490. self.AddGCP(None)
  1491. return minNumOfItems
  1492. def RMSError(self, xygroup, order):
  1493. """
  1494. Uses m.transform to calculate forward and backward error for each used GCP
  1495. in POINTS file and insert error values into GCP list.
  1496. Calculates total forward and backward RMS error for all used points
  1497. """
  1498. # save GCPs to points file to make sure that all checked GCPs are used
  1499. self.SaveGCPs(None)
  1500. # self.SetStatusText('')
  1501. if not self.CheckGCPcount(msg=True):
  1502. return
  1503. # get list of forward and reverse rms error values for each point
  1504. self.grwiz.SwitchEnv('source')
  1505. ret = RunCommand('m.transform',
  1506. parent=self,
  1507. read=True,
  1508. group=xygroup,
  1509. order=order)
  1510. self.grwiz.SwitchEnv('target')
  1511. if ret:
  1512. errlist = ret.splitlines()
  1513. else:
  1514. GError(parent=self,
  1515. message=_('Could not calculate RMS Error.\n'
  1516. 'Possible error with m.transform.'))
  1517. return
  1518. # insert error values into GCP list for checked items
  1519. sdfactor = float(
  1520. UserSettings.Get(
  1521. group='gcpman',
  1522. key='rms',
  1523. subkey='sdfactor'))
  1524. GCPcount = 0
  1525. sumsq_fwd_err = 0.0
  1526. sumsq_bkw_err = 0.0
  1527. sum_fwd_err = 0.0
  1528. highest_fwd_err = 0.0
  1529. self.highest_key = 0
  1530. highest_idx = 0
  1531. for index in range(self.list.GetItemCount()):
  1532. key = self.list.GetItemData(index)
  1533. if self.list.IsItemChecked(index):
  1534. fwd_err, bkw_err = errlist[GCPcount].split()
  1535. self.list.SetItem(index, 5, fwd_err)
  1536. self.list.SetItem(index, 6, bkw_err)
  1537. self.mapcoordlist[key][5] = float(fwd_err)
  1538. self.mapcoordlist[key][6] = float(bkw_err)
  1539. self.list.SetItemTextColour(index, wx.BLACK)
  1540. if self.highest_only:
  1541. if highest_fwd_err < float(fwd_err):
  1542. highest_fwd_err = float(fwd_err)
  1543. self.highest_key = key
  1544. highest_idx = index
  1545. sumsq_fwd_err += float(fwd_err)**2
  1546. sumsq_bkw_err += float(bkw_err)**2
  1547. sum_fwd_err += float(fwd_err)
  1548. GCPcount += 1
  1549. else:
  1550. self.list.SetItem(index, 5, '')
  1551. self.list.SetItem(index, 6, '')
  1552. self.mapcoordlist[key][5] = 0.0
  1553. self.mapcoordlist[key][6] = 0.0
  1554. self.list.SetItemTextColour(index, wx.BLACK)
  1555. # SD
  1556. if GCPcount > 0:
  1557. self.rmsmean = sum_fwd_err / GCPcount
  1558. self.rmssd = ((sumsq_fwd_err - self.rmsmean**2)**0.5)
  1559. self.rmsthresh = self.rmsmean + sdfactor * self.rmssd
  1560. else:
  1561. self.rmsthresh = 0
  1562. self.rmsmean = 0
  1563. self.rmssd = 0
  1564. if self.highest_only and highest_fwd_err > 0.0:
  1565. self.list.SetItemTextColour(highest_idx, wx.RED)
  1566. elif GCPcount > 0 and self.rmsthresh > 0 and not self.highest_only:
  1567. for index in range(self.list.GetItemCount()):
  1568. if self.list.IsItemChecked(index):
  1569. key = self.list.GetItemData(index)
  1570. if (self.mapcoordlist[key][5] > self.rmsthresh):
  1571. self.list.SetItemTextColour(index, wx.RED)
  1572. # calculate global RMS error (geometric mean)
  1573. self.fwd_rmserror = round((sumsq_fwd_err / GCPcount)**0.5, 4)
  1574. self.bkw_rmserror = round((sumsq_bkw_err / GCPcount)**0.5, 4)
  1575. self.list.ResizeColumns()
  1576. def GetNewExtent(self, region, map=None):
  1577. coord_file = utils.GetTempfile()
  1578. newreg = {'n': 0.0, 's': 0.0, 'e': 0.0, 'w': 0.0, }
  1579. try:
  1580. f = open(coord_file, mode='w')
  1581. # NW corner
  1582. f.write(str(region['e']) + " " + str(region['n']) + "\n")
  1583. # NE corner
  1584. f.write(str(region['e']) + " " + str(region['s']) + "\n")
  1585. # SW corner
  1586. f.write(str(region['w']) + " " + str(region['n']) + "\n")
  1587. # SE corner
  1588. f.write(str(region['w']) + " " + str(region['s']) + "\n")
  1589. finally:
  1590. f.close()
  1591. # save GCPs to points file to make sure that all checked GCPs are used
  1592. self.SaveGCPs(None)
  1593. order = self.gr_order
  1594. self.gr_order = 1
  1595. if not self.CheckGCPcount(msg=True):
  1596. self.gr_order = order
  1597. return
  1598. self.gr_order = order
  1599. # get list of forward and reverse rms error values for each point
  1600. self.grwiz.SwitchEnv('source')
  1601. if map == 'source':
  1602. ret = RunCommand('m.transform',
  1603. parent=self,
  1604. read=True,
  1605. group=self.xygroup,
  1606. order=1,
  1607. format='dst',
  1608. coords=coord_file)
  1609. elif map == 'target':
  1610. ret = RunCommand('m.transform',
  1611. parent=self,
  1612. read=True,
  1613. group=self.xygroup,
  1614. order=1,
  1615. flags='r',
  1616. format='src',
  1617. coords=coord_file)
  1618. os.unlink(coord_file)
  1619. self.grwiz.SwitchEnv('target')
  1620. if ret:
  1621. errlist = ret.splitlines()
  1622. else:
  1623. GError(parent=self,
  1624. message=_('Could not calculate new extends.\n'
  1625. 'Possible error with m.transform.'))
  1626. return
  1627. # fist corner
  1628. e, n = errlist[0].split()
  1629. fe = float(e)
  1630. fn = float(n)
  1631. newreg['n'] = fn
  1632. newreg['s'] = fn
  1633. newreg['e'] = fe
  1634. newreg['w'] = fe
  1635. # other three corners
  1636. for i in range(1, 4):
  1637. e, n = errlist[i].split()
  1638. fe = float(e)
  1639. fn = float(n)
  1640. if fe < newreg['w']:
  1641. newreg['w'] = fe
  1642. if fe > newreg['e']:
  1643. newreg['e'] = fe
  1644. if fn < newreg['s']:
  1645. newreg['s'] = fn
  1646. if fn > newreg['n']:
  1647. newreg['n'] = fn
  1648. return newreg
  1649. def OnHelp(self, event):
  1650. """Show GCP Manager manual page"""
  1651. self._giface.Help(entry='wxGUI.gcp')
  1652. def OnUpdateActive(self, event):
  1653. if self.activemap.GetSelection() == 0:
  1654. self.MapWindow = self.SrcMapWindow
  1655. self.Map = self.SrcMap
  1656. else:
  1657. self.MapWindow = self.TgtMapWindow
  1658. self.Map = self.TgtMap
  1659. self.UpdateActive(self.MapWindow)
  1660. # for wingrass
  1661. if os.name == 'nt':
  1662. self.MapWindow.SetFocus()
  1663. def UpdateActive(self, win):
  1664. # optionally disable tool zoomback tool
  1665. self.GetMapToolbar().Enable('zoomback',
  1666. enable=(len(self.MapWindow.zoomhistory) > 1))
  1667. if self.activemap.GetSelection() != (win == self.TgtMapWindow):
  1668. self.activemap.SetSelection(win == self.TgtMapWindow)
  1669. self.StatusbarUpdate()
  1670. def AdjustMap(self, newreg):
  1671. """Adjust map window to new extents
  1672. """
  1673. # adjust map window
  1674. self.Map.region['n'] = newreg['n']
  1675. self.Map.region['s'] = newreg['s']
  1676. self.Map.region['e'] = newreg['e']
  1677. self.Map.region['w'] = newreg['w']
  1678. self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1679. self.Map.region['e'], self.Map.region['w'])
  1680. # LL locations
  1681. if self.Map.projinfo['proj'] == 'll':
  1682. if newreg['n'] > 90.0:
  1683. newreg['n'] = 90.0
  1684. if newreg['s'] < -90.0:
  1685. newreg['s'] = -90.0
  1686. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  1687. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  1688. # calculate new center point and display resolution
  1689. self.Map.region['center_easting'] = ce
  1690. self.Map.region['center_northing'] = cn
  1691. self.Map.region["ewres"] = (newreg['e'] - newreg['w']) / self.Map.width
  1692. self.Map.region["nsres"] = (
  1693. newreg['n'] - newreg['s']) / self.Map.height
  1694. self.Map.AlignExtentFromDisplay()
  1695. self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1696. self.Map.region['e'], self.Map.region['w'])
  1697. if self.MapWindow.redrawAll is False:
  1698. self.MapWindow.redrawAll = True
  1699. self.MapWindow.UpdateMap()
  1700. self.StatusbarUpdate()
  1701. def OnZoomToSource(self, event):
  1702. """Set target map window to match extents of source map window
  1703. """
  1704. if not self.MapWindow == self.TgtMapWindow:
  1705. self.MapWindow = self.TgtMapWindow
  1706. self.Map = self.TgtMap
  1707. self.UpdateActive(self.TgtMapWindow)
  1708. # get new N, S, E, W for target
  1709. newreg = self.GetNewExtent(self.SrcMap.region, 'source')
  1710. if newreg:
  1711. self.AdjustMap(newreg)
  1712. def OnZoomToTarget(self, event):
  1713. """Set source map window to match extents of target map window
  1714. """
  1715. if not self.MapWindow == self.SrcMapWindow:
  1716. self.MapWindow = self.SrcMapWindow
  1717. self.Map = self.SrcMap
  1718. self.UpdateActive(self.SrcMapWindow)
  1719. # get new N, S, E, W for target
  1720. newreg = self.GetNewExtent(self.TgtMap.region, 'target')
  1721. if newreg:
  1722. self.AdjustMap(newreg)
  1723. def OnZoomMenuGCP(self, event):
  1724. """Popup Zoom menu
  1725. """
  1726. point = wx.GetMousePosition()
  1727. zoommenu = Menu()
  1728. # Add items to the menu
  1729. zoomsource = wx.MenuItem(zoommenu, wx.ID_ANY, _(
  1730. 'Adjust source display to target display'))
  1731. zoommenu.AppendItem(zoomsource)
  1732. self.Bind(wx.EVT_MENU, self.OnZoomToTarget, zoomsource)
  1733. zoomtarget = wx.MenuItem(zoommenu, wx.ID_ANY, _(
  1734. 'Adjust target display to source display'))
  1735. zoommenu.AppendItem(zoomtarget)
  1736. self.Bind(wx.EVT_MENU, self.OnZoomToSource, zoomtarget)
  1737. # Popup the menu. If an item is selected then its handler
  1738. # will be called before PopupMenu returns.
  1739. self.PopupMenu(zoommenu)
  1740. zoommenu.Destroy()
  1741. def OnSize(self, event):
  1742. """Adjust Map Windows after GCP Map Display has been resized
  1743. """
  1744. # re-render image on idle
  1745. self.resize = grass.clock()
  1746. super(MapFrame, self).OnSize(event)
  1747. def OnIdle(self, event):
  1748. """GCP Map Display resized, adjust Map Windows
  1749. """
  1750. if self.GetMapToolbar():
  1751. if self.resize and self.resize + 0.2 < grass.clock():
  1752. srcwidth, srcheight = self.SrcMapWindow.GetSize()
  1753. tgtwidth, tgtheight = self.TgtMapWindow.GetSize()
  1754. srcwidth = (srcwidth + tgtwidth) / 2
  1755. if self.show_target:
  1756. self._mgr.GetPane("target").Hide()
  1757. self._mgr.Update()
  1758. self._mgr.GetPane("source").BestSize((srcwidth, srcheight))
  1759. self._mgr.GetPane("target").BestSize((srcwidth, tgtheight))
  1760. if self.show_target:
  1761. self._mgr.GetPane("target").Show()
  1762. self._mgr.Update()
  1763. self.resize = False
  1764. elif self.resize:
  1765. event.RequestMore()
  1766. pass
  1767. class GCPList(ListCtrl,
  1768. CheckListCtrlMixin,
  1769. ListCtrlAutoWidthMixin):
  1770. def __init__(self, parent, gcp, id=wx.ID_ANY,
  1771. pos=wx.DefaultPosition, size=wx.DefaultSize,
  1772. style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_HRULES |
  1773. wx.LC_SINGLE_SEL):
  1774. ListCtrl.__init__(self, parent, id, pos, size, style)
  1775. self.gcp = gcp # GCP class
  1776. self.render = True
  1777. # Mixin settings
  1778. CheckListCtrlMixin.__init__(self)
  1779. ListCtrlAutoWidthMixin.__init__(self)
  1780. # TextEditMixin.__init__(self)
  1781. # tracks whether list items are checked or not
  1782. self.CheckList = []
  1783. self._Create()
  1784. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
  1785. self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
  1786. self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)
  1787. self.selected = wx.NOT_FOUND
  1788. self.selectedkey = -1
  1789. def _Create(self):
  1790. if 0:
  1791. # normal, simple columns
  1792. idx_col = 0
  1793. for col in (_('use'),
  1794. _('source E'),
  1795. _('source N'),
  1796. _('target E'),
  1797. _('target N'),
  1798. _('Forward error'),
  1799. _('Backward error')):
  1800. self.InsertColumn(idx_col, col)
  1801. idx_col += 1
  1802. else:
  1803. # the hard way: we want images on the column header
  1804. info = wx.ListItem()
  1805. info.SetMask(
  1806. wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT)
  1807. info.SetImage(-1)
  1808. info.m_format = wx.LIST_FORMAT_LEFT
  1809. idx_col = 0
  1810. for lbl in (_('use'),
  1811. _('source E'),
  1812. _('source N'),
  1813. _('target E'),
  1814. _('target N'),
  1815. _('Forward error'),
  1816. _('Backward error')):
  1817. info.SetText(lbl)
  1818. self.InsertColumn(idx_col, info)
  1819. idx_col += 1
  1820. def LoadData(self):
  1821. """Load data into list"""
  1822. self.DeleteAllItems()
  1823. self.render = False
  1824. if os.path.isfile(self.gcp.file['points']):
  1825. self.gcp.ReadGCPs()
  1826. else:
  1827. # 3 gcp is minimum
  1828. for i in range(3):
  1829. self.gcp.AddGCP(None)
  1830. # select first point by default
  1831. self.selected = 0
  1832. self.selectedkey = self.GetItemData(self.selected)
  1833. self.SetItemState(self.selected,
  1834. wx.LIST_STATE_SELECTED,
  1835. wx.LIST_STATE_SELECTED)
  1836. self.ResizeColumns()
  1837. self.render = True
  1838. self.EnsureVisible(self.selected)
  1839. def OnCheckItem(self, index, flag):
  1840. """Item is checked/unchecked"""
  1841. if self.render:
  1842. # redraw points
  1843. sourceMapWin = self.gcp.SrcMapWindow
  1844. sourceMapWin.UpdateMap(render=False, renderVector=False)
  1845. if self.gcp.show_target:
  1846. targetMapWin = self.gcp.TgtMapWindow
  1847. targetMapWin.UpdateMap(render=False, renderVector=False)
  1848. def AddGCPItem(self):
  1849. """
  1850. Appends an item to GCP list
  1851. """
  1852. self.selectedkey = self.GetItemCount() + 1
  1853. self.Append([str(self.selectedkey), # GCP number
  1854. '0.0', # source E
  1855. '0.0', # source N
  1856. '0.0', # target E
  1857. '0.0', # target N
  1858. '', # forward error
  1859. '']) # backward error
  1860. self.selected = self.GetItemCount() - 1
  1861. self.SetItemData(self.selected, self.selectedkey)
  1862. self.SetItemState(self.selected,
  1863. wx.LIST_STATE_SELECTED,
  1864. wx.LIST_STATE_SELECTED)
  1865. self.ResizeColumns()
  1866. self.gcp.pointsToDrawSrc.AddItem(
  1867. coords=[0, 0], label=str(self.selectedkey))
  1868. self.gcp.pointsToDrawTgt.AddItem(
  1869. coords=[0, 0], label=str(self.selectedkey))
  1870. self.EnsureVisible(self.selected)
  1871. return self.selected
  1872. def DeleteGCPItem(self):
  1873. """Deletes selected item in GCP list.
  1874. """
  1875. if self.selected == wx.NOT_FOUND:
  1876. return
  1877. key = self.GetItemData(self.selected)
  1878. self.DeleteItem(self.selected)
  1879. if self.selected != wx.NOT_FOUND:
  1880. item = self.gcp.pointsToDrawSrc.GetItem(key - 1)
  1881. self.gcp.pointsToDrawSrc.DeleteItem(item)
  1882. item = self.gcp.pointsToDrawTgt.GetItem(key - 1)
  1883. self.gcp.pointsToDrawTgt.DeleteItem(item)
  1884. return key
  1885. def ResizeColumns(self):
  1886. """Resize columns"""
  1887. minWidth = [90, 120]
  1888. for i in range(self.GetColumnCount()):
  1889. self.SetColumnWidth(i, wx.LIST_AUTOSIZE)
  1890. # first column is checkbox, don't set to minWidth
  1891. if i > 0 and self.GetColumnWidth(i) < minWidth[i > 4]:
  1892. self.SetColumnWidth(i, minWidth[i > 4])
  1893. self.SendSizeEvent()
  1894. def GetSelected(self):
  1895. """Get index of selected item"""
  1896. return self.selected
  1897. def OnItemSelected(self, event):
  1898. """Item selected
  1899. """
  1900. if self.render and self.selected != event.GetIndex():
  1901. self.selected = event.GetIndex()
  1902. self.selectedkey = self.GetItemData(self.selected)
  1903. sourceMapWin = self.gcp.SrcMapWindow
  1904. sourceMapWin.UpdateMap(render=False, renderVector=False)
  1905. if self.gcp.show_target:
  1906. targetMapWin = self.gcp.TgtMapWindow
  1907. targetMapWin.UpdateMap(render=False, renderVector=False)
  1908. event.Skip()
  1909. def OnItemActivated(self, event):
  1910. """
  1911. When item double clicked, open editor to update coordinate values
  1912. """
  1913. coords = []
  1914. index = event.GetIndex()
  1915. key = self.GetItemData(index)
  1916. changed = False
  1917. for i in range(1, 5):
  1918. coords.append(self.GetItem(index, i).GetText())
  1919. dlg = EditGCP(parent=self, id=wx.ID_ANY, data=coords, gcpno=key)
  1920. if dlg.ShowModal() == wx.ID_OK:
  1921. values = dlg.GetValues() # string
  1922. if len(values) == 0:
  1923. GError(parent=self, message=_(
  1924. "Invalid coordinate value. Operation canceled."))
  1925. else:
  1926. for i in range(len(values)):
  1927. if values[i] != coords[i]:
  1928. self.SetItem(index, i + 1, values[i])
  1929. changed = True
  1930. if changed:
  1931. # reset RMS and update mapcoordlist
  1932. self.SetItem(index, 5, '')
  1933. self.SetItem(index, 6, '')
  1934. key = self.GetItemData(index)
  1935. self.gcp.mapcoordlist[key] = [key,
  1936. float(values[0]),
  1937. float(values[1]),
  1938. float(values[2]),
  1939. float(values[3]),
  1940. 0.0,
  1941. 0.0]
  1942. self.gcp.pointsToDrawSrc.GetItem(
  1943. key - 1).SetCoords([float(values[0]), float(values[1])])
  1944. self.gcp.pointsToDrawTgt.GetItem(
  1945. key - 1).SetCoords([float(values[2]), float(values[3])])
  1946. self.gcp.UpdateColours()
  1947. def OnColClick(self, event):
  1948. """ListCtrl forgets selected item..."""
  1949. self.selected = self.FindItemData(-1, self.selectedkey)
  1950. self.SetItemState(self.selected,
  1951. wx.LIST_STATE_SELECTED,
  1952. wx.LIST_STATE_SELECTED)
  1953. event.Skip()
  1954. class VectGroup(wx.Dialog):
  1955. """Dialog to create a vector group (VREF file) for georectifying
  1956. .. todo::
  1957. Replace by g.group
  1958. """
  1959. def __init__(self, parent, id, grassdb, location, mapset, group,
  1960. style=wx.DEFAULT_DIALOG_STYLE):
  1961. wx.Dialog.__init__(self, parent, id, style=style,
  1962. title=_("Create vector map group"))
  1963. self.grassdatabase = grassdb
  1964. self.xylocation = location
  1965. self.xymapset = mapset
  1966. self.xygroup = group
  1967. #
  1968. # get list of valid vector directories
  1969. #
  1970. vectlist = os.listdir(os.path.join(self.grassdatabase,
  1971. self.xylocation,
  1972. self.xymapset,
  1973. 'vector'))
  1974. for dir in vectlist:
  1975. if not os.path.isfile(os.path.join(self.grassdatabase,
  1976. self.xylocation,
  1977. self.xymapset,
  1978. 'vector',
  1979. dir,
  1980. 'coor')):
  1981. vectlist.remove(dir)
  1982. utils.ListSortLower(vectlist)
  1983. # path to vref file
  1984. self.vgrpfile = os.path.join(self.grassdatabase,
  1985. self.xylocation,
  1986. self.xymapset,
  1987. 'group',
  1988. self.xygroup,
  1989. 'VREF')
  1990. #
  1991. # buttons
  1992. #
  1993. self.btnCancel = Button(parent=self,
  1994. id=wx.ID_CANCEL)
  1995. self.btnOK = Button(parent=self,
  1996. id=wx.ID_OK)
  1997. self.btnOK.SetDefault()
  1998. #
  1999. # list of vector maps
  2000. #
  2001. self.listMap = CheckListBox(parent=self, id=wx.ID_ANY,
  2002. choices=vectlist)
  2003. if os.path.isfile(self.vgrpfile):
  2004. f = open(self.vgrpfile)
  2005. try:
  2006. checked = []
  2007. for line in f.readlines():
  2008. line = line.replace('\n', '')
  2009. if len(line) < 1:
  2010. continue
  2011. checked.append(line)
  2012. self.listMap.SetCheckedStrings(checked)
  2013. finally:
  2014. f.close()
  2015. line = wx.StaticLine(parent=self,
  2016. id=wx.ID_ANY, size=(20, -1),
  2017. style=wx.LI_HORIZONTAL)
  2018. #
  2019. # layout
  2020. #
  2021. sizer = wx.BoxSizer(wx.VERTICAL)
  2022. box = wx.BoxSizer(wx.HORIZONTAL)
  2023. box.Add(
  2024. StaticText(
  2025. parent=self,
  2026. id=wx.ID_ANY,
  2027. label=_('Select vector map(s) to add to group:')),
  2028. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
  2029. border=5)
  2030. box.Add(self.listMap,
  2031. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
  2032. border=5)
  2033. sizer.Add(box, flag=wx.ALIGN_RIGHT | wx.ALL,
  2034. border=3)
  2035. sizer.Add(line, proportion=0,
  2036. flag=wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  2037. border=5)
  2038. # buttons
  2039. btnSizer = wx.StdDialogButtonSizer()
  2040. btnSizer.AddButton(self.btnCancel)
  2041. btnSizer.AddButton(self.btnOK)
  2042. btnSizer.Realize()
  2043. sizer.Add(btnSizer, proportion=0,
  2044. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
  2045. border=5)
  2046. self.SetSizer(sizer)
  2047. sizer.Fit(self)
  2048. self.Layout()
  2049. def MakeVGroup(self):
  2050. """Create VREF file"""
  2051. vgrouplist = []
  2052. for item in range(self.listMap.GetCount()):
  2053. if not self.listMap.IsChecked(item):
  2054. continue
  2055. vgrouplist.append(
  2056. self.listMap.GetString(item) +
  2057. '@' +
  2058. self.xymapset)
  2059. dirname = os.path.dirname(self.vgrpfile)
  2060. if not os.path.exists(dirname):
  2061. os.makedirs(dirname)
  2062. f = open(self.vgrpfile, mode='w')
  2063. try:
  2064. for vect in vgrouplist:
  2065. f.write(vect + '\n')
  2066. finally:
  2067. f.close()
  2068. class EditGCP(wx.Dialog):
  2069. def __init__(self, parent, data, gcpno, id=wx.ID_ANY,
  2070. title=_("Edit GCP"),
  2071. style=wx.DEFAULT_DIALOG_STYLE):
  2072. """Dialog for editing GPC and map coordinates in list control"""
  2073. wx.Dialog.__init__(self, parent, id, title=title, style=style)
  2074. panel = wx.Panel(parent=self)
  2075. sizer = wx.BoxSizer(wx.VERTICAL)
  2076. box = StaticBox(
  2077. parent=panel, id=wx.ID_ANY, label=" %s %s " %
  2078. (_("Ground Control Point No."), str(gcpno)))
  2079. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2080. # source coordinates
  2081. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  2082. self.xcoord = TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  2083. self.ycoord = TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  2084. self.ecoord = TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  2085. self.ncoord = TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  2086. # swap source N, target E
  2087. tmp_coord = data[1]
  2088. data[1] = data[2]
  2089. data[2] = tmp_coord
  2090. row = 0
  2091. col = 0
  2092. idx = 0
  2093. for label, win in ((_("source E:"), self.xcoord),
  2094. (_("target E:"), self.ecoord),
  2095. (_("source N:"), self.ycoord),
  2096. (_("target N:"), self.ncoord)):
  2097. label = StaticText(parent=panel, id=wx.ID_ANY,
  2098. label=label)
  2099. gridSizer.Add(label,
  2100. flag=wx.ALIGN_CENTER_VERTICAL,
  2101. pos=(row, col))
  2102. col += 1
  2103. win.SetValue(str(data[idx]))
  2104. gridSizer.Add(win,
  2105. pos=(row, col))
  2106. col += 1
  2107. idx += 1
  2108. if col > 3:
  2109. row += 1
  2110. col = 0
  2111. boxSizer.Add(gridSizer, proportion=1,
  2112. flag=wx.EXPAND | wx.ALL, border=5)
  2113. sizer.Add(boxSizer, proportion=1,
  2114. flag=wx.EXPAND | wx.ALL, border=5)
  2115. #
  2116. # buttons
  2117. #
  2118. self.btnCancel = Button(panel, wx.ID_CANCEL)
  2119. self.btnOk = Button(panel, wx.ID_OK)
  2120. self.btnOk.SetDefault()
  2121. btnSizer = wx.StdDialogButtonSizer()
  2122. btnSizer.AddButton(self.btnCancel)
  2123. btnSizer.AddButton(self.btnOk)
  2124. btnSizer.Realize()
  2125. sizer.Add(btnSizer, proportion=0,
  2126. flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  2127. panel.SetSizer(sizer)
  2128. sizer.Fit(self)
  2129. def GetValues(self, columns=None):
  2130. """Return list of values (as strings).
  2131. """
  2132. valuelist = []
  2133. try:
  2134. float(self.xcoord.GetValue())
  2135. float(self.ycoord.GetValue())
  2136. float(self.ecoord.GetValue())
  2137. float(self.ncoord.GetValue())
  2138. except ValueError:
  2139. return valuelist
  2140. valuelist.append(self.xcoord.GetValue())
  2141. valuelist.append(self.ycoord.GetValue())
  2142. valuelist.append(self.ecoord.GetValue())
  2143. valuelist.append(self.ncoord.GetValue())
  2144. return valuelist
  2145. class GrSettingsDialog(wx.Dialog):
  2146. def __init__(
  2147. self, parent, id, giface, title, pos=wx.DefaultPosition,
  2148. size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE):
  2149. wx.Dialog.__init__(self, parent, id, title, pos, size, style)
  2150. """
  2151. Dialog to set profile text options: font, title
  2152. and font size, axis labels and font size
  2153. """
  2154. #
  2155. # initialize variables
  2156. #
  2157. self.parent = parent
  2158. self.new_src_map = src_map
  2159. self.new_tgt_map = {'raster': tgt_map['raster'],
  2160. 'vector': tgt_map['vector']}
  2161. self.sdfactor = 0
  2162. self.symbol = {}
  2163. self.methods = ["nearest",
  2164. "linear",
  2165. "linear_f",
  2166. "cubic",
  2167. "cubic_f",
  2168. "lanczos",
  2169. "lanczos_f"]
  2170. # notebook
  2171. notebook = wx.Notebook(parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
  2172. self.__CreateSymbologyPage(notebook)
  2173. self.__CreateRectificationPage(notebook)
  2174. # buttons
  2175. btnSave = Button(self, wx.ID_SAVE)
  2176. btnApply = Button(self, wx.ID_APPLY)
  2177. btnClose = Button(self, wx.ID_CLOSE)
  2178. btnApply.SetDefault()
  2179. # bindings
  2180. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  2181. btnApply.SetToolTip(_("Apply changes for the current session"))
  2182. btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
  2183. btnSave.SetToolTip(
  2184. _("Apply and save changes to user settings file (default for next sessions)"))
  2185. btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
  2186. btnClose.SetToolTip(_("Close dialog"))
  2187. # sizers
  2188. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  2189. btnSizer.Add(btnApply, flag=wx.LEFT | wx.RIGHT, border=5)
  2190. btnSizer.Add(btnSave, flag=wx.LEFT | wx.RIGHT, border=5)
  2191. btnSizer.Add(btnClose, flag=wx.LEFT | wx.RIGHT, border=5)
  2192. # sizers
  2193. mainSizer = wx.BoxSizer(wx.VERTICAL)
  2194. mainSizer.Add(
  2195. notebook,
  2196. proportion=1,
  2197. flag=wx.EXPAND | wx.ALL,
  2198. border=5)
  2199. mainSizer.Add(btnSizer, proportion=0,
  2200. flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  2201. # flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  2202. self.SetSizer(mainSizer)
  2203. mainSizer.Fit(self)
  2204. def __CreateSymbologyPage(self, notebook):
  2205. """Create notebook page with symbology settings"""
  2206. panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
  2207. notebook.AddPage(page=panel, text=_("Symbology"))
  2208. sizer = wx.BoxSizer(wx.VERTICAL)
  2209. rmsgridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  2210. # highlight only highest forward RMS error
  2211. self.highlighthighest = wx.CheckBox(
  2212. parent=panel, id=wx.ID_ANY,
  2213. label=_("Highlight highest RMS error only"))
  2214. hh = UserSettings.Get(group='gcpman', key='rms', subkey='highestonly')
  2215. self.highlighthighest.SetValue(hh)
  2216. rmsgridSizer.Add(
  2217. self.highlighthighest,
  2218. flag=wx.ALIGN_CENTER_VERTICAL,
  2219. pos=(
  2220. 0,
  2221. 0))
  2222. # RMS forward error threshold
  2223. rmslabel = StaticText(
  2224. parent=panel, id=wx.ID_ANY,
  2225. label=_("Highlight RMS error > M + SD * factor:"))
  2226. rmslabel.SetToolTip(
  2227. _(
  2228. "Highlight GCPs with an RMS error larger than \n"
  2229. "mean + standard deviation * given factor. \n"
  2230. "Recommended values for this factor are between 1 and 2."))
  2231. rmsgridSizer.Add(
  2232. rmslabel,
  2233. flag=wx.ALIGN_CENTER_VERTICAL,
  2234. pos=(
  2235. 1,
  2236. 0))
  2237. sdfactor = UserSettings.Get(
  2238. group='gcpman', key='rms', subkey='sdfactor')
  2239. self.rmsWin = TextCtrl(parent=panel, id=wx.ID_ANY,
  2240. size=(70, -1), style=wx.TE_NOHIDESEL)
  2241. self.rmsWin.SetValue("%s" % str(sdfactor))
  2242. if (self.parent.highest_only):
  2243. self.rmsWin.Disable()
  2244. self.symbol['sdfactor'] = self.rmsWin.GetId()
  2245. rmsgridSizer.Add(self.rmsWin, flag=wx.ALIGN_RIGHT, pos=(1, 1))
  2246. rmsgridSizer.AddGrowableCol(1)
  2247. sizer.Add(rmsgridSizer, flag=wx.EXPAND | wx.ALL, border=5)
  2248. box = StaticBox(parent=panel, id=wx.ID_ANY,
  2249. label=" %s " % _("Symbol settings"))
  2250. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2251. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  2252. #
  2253. # general symbol color
  2254. #
  2255. row = 0
  2256. label = StaticText(parent=panel, id=wx.ID_ANY, label=_("Color:"))
  2257. gridSizer.Add(label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2258. col = UserSettings.Get(group='gcpman', key='symbol', subkey='color')
  2259. colWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
  2260. colour=wx.Colour(col[0],
  2261. col[1],
  2262. col[2],
  2263. 255))
  2264. self.symbol['color'] = colWin.GetId()
  2265. gridSizer.Add(colWin,
  2266. flag=wx.ALIGN_RIGHT,
  2267. pos=(row, 1))
  2268. #
  2269. # symbol color for high forward RMS error
  2270. #
  2271. row += 1
  2272. label = StaticText(
  2273. parent=panel,
  2274. id=wx.ID_ANY,
  2275. label=_("Color for high RMS error:"))
  2276. gridSizer.Add(label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2277. hcol = UserSettings.Get(group='gcpman', key='symbol', subkey='hcolor')
  2278. hcolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
  2279. colour=wx.Colour(hcol[0],
  2280. hcol[1],
  2281. hcol[2],
  2282. 255))
  2283. self.symbol['hcolor'] = hcolWin.GetId()
  2284. gridSizer.Add(hcolWin,
  2285. flag=wx.ALIGN_RIGHT,
  2286. pos=(row, 1))
  2287. #
  2288. # symbol color for selected GCP
  2289. #
  2290. row += 1
  2291. label = StaticText(
  2292. parent=panel,
  2293. id=wx.ID_ANY,
  2294. label=_("Color for selected GCP:"))
  2295. gridSizer.Add(label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2296. scol = UserSettings.Get(group='gcpman', key='symbol', subkey='scolor')
  2297. scolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
  2298. colour=wx.Colour(scol[0],
  2299. scol[1],
  2300. scol[2],
  2301. 255))
  2302. self.symbol['scolor'] = scolWin.GetId()
  2303. gridSizer.Add(scolWin,
  2304. flag=wx.ALIGN_RIGHT,
  2305. pos=(row, 1))
  2306. #
  2307. # symbol color for unused GCP
  2308. #
  2309. row += 1
  2310. label = StaticText(
  2311. parent=panel,
  2312. id=wx.ID_ANY,
  2313. label=_("Color for unused GCPs:"))
  2314. gridSizer.Add(label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2315. ucol = UserSettings.Get(group='gcpman', key='symbol', subkey='ucolor')
  2316. ucolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
  2317. colour=wx.Colour(ucol[0],
  2318. ucol[1],
  2319. ucol[2],
  2320. 255))
  2321. self.symbol['ucolor'] = ucolWin.GetId()
  2322. gridSizer.Add(ucolWin,
  2323. flag=wx.ALIGN_RIGHT,
  2324. pos=(row, 1))
  2325. # show unused GCPs
  2326. row += 1
  2327. self.showunused = wx.CheckBox(parent=panel, id=wx.ID_ANY,
  2328. label=_("Show unused GCPs"))
  2329. shuu = UserSettings.Get(group='gcpman', key='symbol', subkey='unused')
  2330. self.showunused.SetValue(shuu)
  2331. gridSizer.Add(
  2332. self.showunused,
  2333. flag=wx.ALIGN_CENTER_VERTICAL,
  2334. pos=(
  2335. row,
  2336. 0))
  2337. #
  2338. # symbol size
  2339. #
  2340. row += 1
  2341. label = StaticText(
  2342. parent=panel,
  2343. id=wx.ID_ANY,
  2344. label=_("Symbol size:"))
  2345. gridSizer.Add(label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2346. symsize = int(
  2347. UserSettings.Get(
  2348. group='gcpman',
  2349. key='symbol',
  2350. subkey='size'))
  2351. sizeWin = SpinCtrl(parent=panel, id=wx.ID_ANY,
  2352. min=1, max=20)
  2353. sizeWin.SetValue(symsize)
  2354. self.symbol['size'] = sizeWin.GetId()
  2355. gridSizer.Add(sizeWin,
  2356. flag=wx.ALIGN_RIGHT,
  2357. pos=(row, 1))
  2358. #
  2359. # symbol width
  2360. #
  2361. row += 1
  2362. label = StaticText(
  2363. parent=panel,
  2364. id=wx.ID_ANY,
  2365. label=_("Line width:"))
  2366. gridSizer.Add(label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2367. width = int(
  2368. UserSettings.Get(
  2369. group='gcpman',
  2370. key='symbol',
  2371. subkey='width'))
  2372. widWin = SpinCtrl(parent=panel, id=wx.ID_ANY,
  2373. min=1, max=10)
  2374. widWin.SetValue(width)
  2375. self.symbol['width'] = widWin.GetId()
  2376. gridSizer.Add(widWin,
  2377. flag=wx.ALIGN_RIGHT,
  2378. pos=(row, 1))
  2379. gridSizer.AddGrowableCol(1)
  2380. boxSizer.Add(gridSizer, flag=wx.EXPAND)
  2381. sizer.Add(boxSizer, flag=wx.EXPAND | wx.ALL, border=5)
  2382. #
  2383. # maps to display
  2384. #
  2385. # source map to display
  2386. self.srcselection = Select(
  2387. panel,
  2388. id=wx.ID_ANY,
  2389. size=globalvar.DIALOG_GSELECT_SIZE,
  2390. type='maptype',
  2391. updateOnPopup=False)
  2392. self.parent.grwiz.SwitchEnv('source')
  2393. self.srcselection.SetElementList(maptype)
  2394. # filter out all maps not in group
  2395. self.srcselection.tcp.GetElementList(elements=self.parent.src_maps)
  2396. # target map(s) to display
  2397. self.parent.grwiz.SwitchEnv('target')
  2398. self.tgtrastselection = Select(
  2399. panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  2400. type='raster', updateOnPopup=False)
  2401. self.tgtrastselection.SetElementList('cell')
  2402. self.tgtrastselection.GetElementList()
  2403. self.tgtvectselection = Select(
  2404. panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  2405. type='vector', updateOnPopup=False)
  2406. self.tgtvectselection.SetElementList('vector')
  2407. self.tgtvectselection.GetElementList()
  2408. sizer.Add(
  2409. StaticText(
  2410. parent=panel,
  2411. id=wx.ID_ANY,
  2412. label=_('Select source map to display:')),
  2413. proportion=0,
  2414. flag=wx.ALIGN_LEFT | wx.ALL,
  2415. border=5)
  2416. sizer.Add(
  2417. self.srcselection,
  2418. proportion=0,
  2419. flag=wx.ALIGN_LEFT | wx.ALL,
  2420. border=5)
  2421. self.srcselection.SetValue(src_map)
  2422. sizer.Add(
  2423. StaticText(
  2424. parent=panel,
  2425. id=wx.ID_ANY,
  2426. label=_('Select target raster map to display:')),
  2427. proportion=0,
  2428. flag=wx.ALIGN_LEFT | wx.ALL,
  2429. border=5)
  2430. sizer.Add(
  2431. self.tgtrastselection,
  2432. proportion=0,
  2433. flag=wx.ALIGN_LEFT | wx.ALL,
  2434. border=5)
  2435. self.tgtrastselection.SetValue(tgt_map['raster'])
  2436. sizer.Add(
  2437. StaticText(
  2438. parent=panel,
  2439. id=wx.ID_ANY,
  2440. label=_('Select target vector map to display:')),
  2441. proportion=0,
  2442. flag=wx.ALIGN_LEFT | wx.ALL,
  2443. border=5)
  2444. sizer.Add(
  2445. self.tgtvectselection,
  2446. proportion=0,
  2447. flag=wx.ALIGN_LEFT | wx.ALL,
  2448. border=5)
  2449. self.tgtvectselection.SetValue(tgt_map['vector'])
  2450. # bindings
  2451. self.highlighthighest.Bind(wx.EVT_CHECKBOX, self.OnHighlight)
  2452. self.rmsWin.Bind(wx.EVT_TEXT, self.OnSDFactor)
  2453. self.srcselection.Bind(wx.EVT_TEXT, self.OnSrcSelection)
  2454. self.tgtrastselection.Bind(wx.EVT_TEXT, self.OnTgtRastSelection)
  2455. self.tgtvectselection.Bind(wx.EVT_TEXT, self.OnTgtVectSelection)
  2456. panel.SetSizer(sizer)
  2457. return panel
  2458. def __CreateRectificationPage(self, notebook):
  2459. """Create notebook page with symbology settings"""
  2460. panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
  2461. notebook.AddPage(page=panel, text=_("Rectification"))
  2462. sizer = wx.BoxSizer(wx.VERTICAL)
  2463. # transformation order
  2464. self.rb_grorder = wx.RadioBox(
  2465. parent=panel,
  2466. id=wx.ID_ANY,
  2467. label=" %s " %
  2468. _("Select rectification order"),
  2469. choices=[
  2470. _('1st order'),
  2471. _('2nd order'),
  2472. _('3rd order')],
  2473. majorDimension=wx.RA_SPECIFY_COLS)
  2474. sizer.Add(self.rb_grorder, proportion=0,
  2475. flag=wx.EXPAND | wx.ALL, border=5)
  2476. self.rb_grorder.SetSelection(self.parent.gr_order - 1)
  2477. # interpolation method
  2478. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  2479. gridSizer.Add(
  2480. StaticText(
  2481. parent=panel,
  2482. id=wx.ID_ANY,
  2483. label=_('Select interpolation method:')),
  2484. pos=(
  2485. 0,
  2486. 0),
  2487. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  2488. border=5)
  2489. self.grmethod = wx.Choice(parent=panel, id=wx.ID_ANY,
  2490. choices=self.methods)
  2491. gridSizer.Add(self.grmethod, pos=(0, 1),
  2492. flag=wx.ALIGN_RIGHT, border=5)
  2493. self.grmethod.SetStringSelection(self.parent.gr_method)
  2494. gridSizer.AddGrowableCol(1)
  2495. sizer.Add(gridSizer, flag=wx.EXPAND | wx.ALL, border=5)
  2496. # clip to region
  2497. self.check = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
  2498. "clip to computational region in target location"))
  2499. sizer.Add(self.check, proportion=0,
  2500. flag=wx.EXPAND | wx.ALL, border=5)
  2501. self.check.SetValue(self.parent.clip_to_region)
  2502. # extension
  2503. sizer.Add(
  2504. StaticText(
  2505. parent=panel,
  2506. id=wx.ID_ANY,
  2507. label=_('Extension for output maps:')),
  2508. proportion=0,
  2509. flag=wx.ALIGN_LEFT | wx.ALL,
  2510. border=5)
  2511. self.ext_txt = TextCtrl(
  2512. parent=panel, id=wx.ID_ANY, value="", size=(
  2513. 350, -1))
  2514. self.ext_txt.SetValue(self.parent.extension)
  2515. sizer.Add(
  2516. self.ext_txt,
  2517. proportion=0,
  2518. flag=wx.ALIGN_LEFT | wx.ALL,
  2519. border=5)
  2520. # bindings
  2521. self.ext_txt.Bind(wx.EVT_TEXT, self.OnExtension)
  2522. self.Bind(wx.EVT_RADIOBOX, self.parent.OnGROrder, self.rb_grorder)
  2523. self.Bind(wx.EVT_CHOICE, self.OnMethod, self.grmethod)
  2524. self.Bind(wx.EVT_CHECKBOX, self.OnClipRegion, self.check)
  2525. panel.SetSizer(sizer)
  2526. return panel
  2527. def OnHighlight(self, event):
  2528. """Checkbox 'highlighthighest' checked/unchecked"""
  2529. if self.highlighthighest.IsChecked():
  2530. self.parent.highest_only = True
  2531. self.rmsWin.Disable()
  2532. else:
  2533. self.parent.highest_only = False
  2534. self.rmsWin.Enable()
  2535. def OnSDFactor(self, event):
  2536. """New factor for RMS threshold = M + SD * factor"""
  2537. try:
  2538. self.sdfactor = float(self.rmsWin.GetValue())
  2539. except ValueError:
  2540. return
  2541. if self.sdfactor <= 0:
  2542. GError(parent=self,
  2543. message=_('RMS threshold factor must be > 0'))
  2544. elif self.sdfactor < 1:
  2545. GError(parent=self,
  2546. message=_('RMS threshold factor is < 1\n'
  2547. 'Too many points might be highlighted'))
  2548. def OnSrcSelection(self, event):
  2549. """Source map to display selected"""
  2550. global src_map
  2551. tmp_map = self.srcselection.GetValue()
  2552. if not tmp_map == '' and not tmp_map == src_map:
  2553. self.new_src_map = tmp_map
  2554. def OnTgtRastSelection(self, event):
  2555. """Target map to display selected"""
  2556. global tgt_map
  2557. self.new_tgt_map['raster'] = self.tgtrastselection.GetValue()
  2558. def OnTgtVectSelection(self, event):
  2559. """Target map to display selected"""
  2560. global tgt_map
  2561. self.new_tgt_map['vector'] = self.tgtvectselection.GetValue()
  2562. def OnMethod(self, event):
  2563. self.parent.gr_method = self.methods[event.GetSelection()]
  2564. def OnClipRegion(self, event):
  2565. self.parent.clip_to_region = event.IsChecked()
  2566. def OnExtension(self, event):
  2567. self.parent.extension = self.ext_txt.GetValue()
  2568. def UpdateSettings(self):
  2569. global src_map
  2570. global tgt_map
  2571. global maptype
  2572. layers = None
  2573. UserSettings.Set(group='gcpman', key='rms', subkey='highestonly',
  2574. value=self.highlighthighest.GetValue())
  2575. if self.sdfactor > 0:
  2576. UserSettings.Set(group='gcpman', key='rms', subkey='sdfactor',
  2577. value=self.sdfactor)
  2578. self.parent.sdfactor = self.sdfactor
  2579. if self.parent.rmsthresh > 0:
  2580. self.parent.rmsthresh = self.parent.rmsmean + self.parent.sdfactor * self.parent.rmssd
  2581. UserSettings.Set(
  2582. group='gcpman',
  2583. key='symbol',
  2584. subkey='color',
  2585. value=tuple(
  2586. wx.FindWindowById(
  2587. self.symbol['color']).GetColour()))
  2588. UserSettings.Set(
  2589. group='gcpman',
  2590. key='symbol',
  2591. subkey='hcolor',
  2592. value=tuple(
  2593. wx.FindWindowById(
  2594. self.symbol['hcolor']).GetColour()))
  2595. UserSettings.Set(
  2596. group='gcpman',
  2597. key='symbol',
  2598. subkey='scolor',
  2599. value=tuple(
  2600. wx.FindWindowById(
  2601. self.symbol['scolor']).GetColour()))
  2602. UserSettings.Set(
  2603. group='gcpman',
  2604. key='symbol',
  2605. subkey='ucolor',
  2606. value=tuple(
  2607. wx.FindWindowById(
  2608. self.symbol['ucolor']).GetColour()))
  2609. UserSettings.Set(group='gcpman', key='symbol', subkey='unused',
  2610. value=self.showunused.GetValue())
  2611. UserSettings.Set(
  2612. group='gcpman',
  2613. key='symbol',
  2614. subkey='size',
  2615. value=wx.FindWindowById(
  2616. self.symbol['size']).GetValue())
  2617. UserSettings.Set(
  2618. group='gcpman',
  2619. key='symbol',
  2620. subkey='width',
  2621. value=wx.FindWindowById(
  2622. self.symbol['width']).GetValue())
  2623. srcrender = False
  2624. srcrenderVector = False
  2625. tgtrender = False
  2626. tgtrenderVector = False
  2627. reload_target = False
  2628. if self.new_src_map != src_map:
  2629. # remove old layer
  2630. layers = self.parent.grwiz.SrcMap.GetListOfLayers()
  2631. self.parent.grwiz.SrcMap.DeleteLayer(layers[0])
  2632. src_map = self.new_src_map
  2633. if maptype == 'raster':
  2634. cmdlist = ['d.rast', 'map=%s' % src_map]
  2635. srcrender = True
  2636. else:
  2637. cmdlist = ['d.vect', 'map=%s' % src_map]
  2638. srcrenderVector = True
  2639. self.parent.grwiz.SwitchEnv('source')
  2640. name, found = utils.GetLayerNameFromCmd(cmdlist)
  2641. self.parent.grwiz.SrcMap.AddLayer(
  2642. ltype=maptype, command=cmdlist, active=True, name=name,
  2643. hidden=False, opacity=1.0, render=False)
  2644. self.parent.grwiz.SwitchEnv('target')
  2645. if self.new_tgt_map['raster'] != tgt_map['raster'] or \
  2646. self.new_tgt_map['vector'] != tgt_map['vector']:
  2647. # remove all layers
  2648. layers = self.parent.grwiz.TgtMap.GetListOfLayers()
  2649. while layers:
  2650. self.parent.grwiz.TgtMap.DeleteLayer(layers[0])
  2651. del layers[0]
  2652. layers = self.parent.grwiz.TgtMap.GetListOfLayers()
  2653. # self.parent.grwiz.TgtMap.DeleteAllLayers()
  2654. reload_target = True
  2655. tgt_map['raster'] = self.new_tgt_map['raster']
  2656. tgt_map['vector'] = self.new_tgt_map['vector']
  2657. if tgt_map['raster'] != '':
  2658. cmdlist = ['d.rast', 'map=%s' % tgt_map['raster']]
  2659. name, found = utils.GetLayerNameFromCmd(cmdlist)
  2660. self.parent.grwiz.TgtMap.AddLayer(
  2661. ltype='raster', command=cmdlist, active=True, name=name,
  2662. hidden=False, opacity=1.0, render=False)
  2663. tgtrender = True
  2664. if tgt_map['vector'] != '':
  2665. cmdlist = ['d.vect', 'map=%s' % tgt_map['vector']]
  2666. name, found = utils.GetLayerNameFromCmd(cmdlist)
  2667. self.parent.grwiz.TgtMap.AddLayer(
  2668. ltype='vector', command=cmdlist, active=True, name=name,
  2669. hidden=False, opacity=1.0, render=False)
  2670. tgtrenderVector = True
  2671. if tgt_map['raster'] == '' and tgt_map['vector'] == '':
  2672. if self.parent.show_target:
  2673. self.parent.show_target = False
  2674. self.parent._mgr.GetPane("target").Hide()
  2675. self.parent._mgr.Update()
  2676. self.parent.activemap.SetSelection(0)
  2677. self.parent.activemap.Enable(False)
  2678. self.parent.GetMapToolbar().Enable('zoommenu', enable=False)
  2679. else:
  2680. if not self.parent.show_target:
  2681. self.parent.show_target = True
  2682. self.parent._mgr.GetPane("target").Show()
  2683. self.parent._mgr.Update()
  2684. self.parent.activemap.SetSelection(0)
  2685. self.parent.activemap.Enable(True)
  2686. self.parent.GetMapToolbar().Enable('zoommenu', enable=True)
  2687. self.parent.TgtMapWindow.ZoomToMap(
  2688. layers=self.parent.TgtMap.GetListOfLayers())
  2689. self.parent.UpdateColours(
  2690. srcrender,
  2691. srcrenderVector,
  2692. tgtrender,
  2693. tgtrenderVector)
  2694. self.parent.SetSettings()
  2695. def OnSave(self, event):
  2696. """Button 'Save' pressed"""
  2697. self.UpdateSettings()
  2698. fileSettings = {}
  2699. UserSettings.ReadSettingsFile(settings=fileSettings)
  2700. fileSettings['gcpman'] = UserSettings.Get(group='gcpman')
  2701. file = UserSettings.SaveToFile(fileSettings)
  2702. self.parent._giface.WriteLog(
  2703. _('GCP Manager settings saved to file \'%s\'.') %
  2704. file)
  2705. # self.Close()
  2706. def OnApply(self, event):
  2707. """Button 'Apply' pressed"""
  2708. self.UpdateSettings()
  2709. # self.Close()
  2710. def OnClose(self, event):
  2711. """Button 'Cancel' pressed"""
  2712. self.Close()