manager.py 108 KB

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