manager.py 108 KB

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