manager.py 111 KB

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