manager.py 108 KB

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