wizard.py 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722
  1. """
  2. @package location_wizard.wizard
  3. @brief Location wizard - creates a new GRASS Location. User can choose
  4. from multiple methods.
  5. Classes:
  6. - wizard::TitledPage
  7. - wizard::DatabasePage
  8. - wizard::CoordinateSystemPage
  9. - wizard::ProjectionsPage
  10. - wizard::ItemList
  11. - wizard::ProjParamsPage
  12. - wizard::DatumPage
  13. - wizard::EllipsePage
  14. - wizard::GeoreferencedFilePage
  15. - wizard::WKTPage
  16. - wizard::EPSGPage
  17. - wizard::IAUPage
  18. - wizard::CustomPage
  19. - wizard::SummaryPage
  20. - wizard::LocationWizard
  21. - wizard::WizardWithHelpButton
  22. (C) 2007-2016 by the GRASS Development Team
  23. This program is free software under the GNU General Public License
  24. (>=v2). Read the file COPYING that comes with GRASS for details.
  25. @author Michael Barton
  26. @author Jachym Cepicky
  27. @author Martin Landa <landa.martin gmail.com>
  28. @author Hamish Bowman (planetary ellipsoids)
  29. """
  30. import os
  31. import sys
  32. import locale
  33. import six
  34. import wx
  35. import wx.lib.mixins.listctrl as listmix
  36. from core import globalvar
  37. if globalvar.wxPythonPhoenix:
  38. from wx import adv as wiz
  39. from wx.adv import Wizard
  40. from wx.adv import WizardPageSimple
  41. else:
  42. from wx import wizard as wiz
  43. from wx.wizard import Wizard
  44. from wx.wizard import WizardPageSimple
  45. import wx.lib.scrolledpanel as scrolled
  46. from core import utils
  47. from core.utils import cmp
  48. from core.gcmd import RunCommand, GError, GMessage, GWarning
  49. from gui_core.widgets import GenericValidator
  50. from gui_core.wrap import SpinCtrl, SearchCtrl, StaticText, \
  51. TextCtrl, Button, CheckBox, StaticBox, NewId, ListCtrl
  52. from location_wizard.base import BaseClass
  53. from location_wizard.dialogs import SelectTransformDialog
  54. from grass.script import decode
  55. from grass.script import core as grass
  56. from grass.exceptions import OpenError
  57. global coordsys
  58. global north
  59. global south
  60. global east
  61. global west
  62. global resolution
  63. global wizerror
  64. global translist
  65. class TitledPage(WizardPageSimple):
  66. """Class to make wizard pages. Generic methods to make labels,
  67. text entries, and buttons.
  68. """
  69. def __init__(self, parent, title):
  70. self.page = WizardPageSimple.__init__(self, parent)
  71. # page title
  72. self.title = StaticText(parent=self, id=wx.ID_ANY, label=title)
  73. self.title.SetFont(wx.Font(13, wx.SWISS, wx.NORMAL, wx.BOLD))
  74. # main sizers
  75. self.pagesizer = wx.BoxSizer(wx.VERTICAL)
  76. self.sizer = wx.GridBagSizer(vgap=0, hgap=0)
  77. self.sizer.SetCols(5)
  78. self.sizer.SetRows(6)
  79. def DoLayout(self):
  80. """Do page layout"""
  81. self.pagesizer.Add(self.title, proportion=0,
  82. flag=wx.ALIGN_CENTRE | wx.ALL,
  83. border=5)
  84. self.pagesizer.Add(wx.StaticLine(self, -1), proportion=0,
  85. flag=wx.EXPAND | wx.ALL,
  86. border=0)
  87. self.pagesizer.Add(self.sizer, proportion=1,
  88. flag=wx.EXPAND)
  89. self.SetAutoLayout(True)
  90. self.SetSizer(self.pagesizer)
  91. self.Layout()
  92. def MakeLabel(self, text="", style=wx.ALIGN_LEFT,
  93. parent=None, tooltip=None):
  94. """Make aligned label"""
  95. if not parent:
  96. parent = self
  97. label = StaticText(parent=parent, id=wx.ID_ANY, label=text,
  98. style=style)
  99. if tooltip:
  100. label.SetToolTip(tooltip)
  101. return label
  102. def MakeTextCtrl(self, text='', size=(100, -1),
  103. style=0, parent=None, tooltip=None):
  104. """Generic text control"""
  105. if not parent:
  106. parent = self
  107. textCtrl = TextCtrl(parent=parent, id=wx.ID_ANY, value=text,
  108. size=size, style=style)
  109. if tooltip:
  110. textCtrl.SetToolTip(tooltip)
  111. return textCtrl
  112. def MakeStaticText(self, text='', size=(100, -1),
  113. style=0, parent=None):
  114. """Generic static text control"""
  115. if not parent:
  116. parent = self
  117. staticText = StaticText(parent=parent, id=wx.ID_ANY, label=text,
  118. size=size, style=style)
  119. return staticText
  120. def MakeButton(self, text, id=wx.ID_ANY, size=(-1, -1),
  121. parent=None, tooltip=None):
  122. """Generic button"""
  123. if not parent:
  124. parent = self
  125. button = Button(parent=parent, id=id, label=text,
  126. size=size)
  127. if tooltip:
  128. button.SetToolTip(tooltip)
  129. return button
  130. def MakeCheckBox(self, text, id=wx.ID_ANY, size=(-1, -1),
  131. parent=None, tooltip=None):
  132. """Generic checkbox"""
  133. if not parent:
  134. parent = self
  135. chbox = CheckBox(parent=parent, id=id, label=text,
  136. size=size)
  137. if tooltip:
  138. chbox.SetToolTip(tooltip)
  139. return chbox
  140. class DatabasePage(TitledPage):
  141. """Wizard page for setting GIS data directory and location name"""
  142. def __init__(self, wizard, parent, grassdatabase):
  143. TitledPage.__init__(self, wizard, _(
  144. "Define GRASS Database and Location Name"))
  145. self.grassdatabase = grassdatabase
  146. self.location = ''
  147. self.locTitle = ''
  148. # text controls
  149. self.tgisdbase = self.MakeStaticText(grassdatabase, size=(-1, -1))
  150. self.tlocation = self.MakeTextCtrl("newLocation", size=(300, -1))
  151. self.tlocation.SetFocus()
  152. self.tlocation.SetValidator(
  153. GenericValidator(
  154. grass.legal_name,
  155. self._nameValidationFailed))
  156. self.tlocTitle = self.MakeTextCtrl(size=(400, -1))
  157. # checkbox
  158. self.tlocRegion = self.MakeCheckBox(_("Set default region extent and resolution"),
  159. tooltip=_("This option allows setting default "
  160. "computation region immediately after "
  161. "new location is created. Default "
  162. "computation region can be defined later "
  163. "using g.region based on imported data."))
  164. self.tlocUserMapset = self.MakeCheckBox(_("Create user mapset"),
  165. tooltip=_("This option allows creating user "
  166. "mapset immediately after new location "
  167. "is created. Note that GRASS always creates "
  168. "PERMANENT mapset."))
  169. # layout
  170. self.sizer.Add(self.MakeLabel(_("GIS Data Directory:")),
  171. flag=wx.ALIGN_RIGHT |
  172. wx.ALIGN_CENTER_VERTICAL |
  173. wx.ALL, border=5,
  174. pos=(1, 1))
  175. self.sizer.Add(self.tgisdbase,
  176. flag=wx.ALIGN_LEFT |
  177. wx.ALIGN_CENTER_VERTICAL |
  178. wx.ALL, border=5,
  179. pos=(1, 2))
  180. self.sizer.Add(
  181. self.MakeLabel(
  182. "%s:" %
  183. _("Project Location"),
  184. tooltip=_("Name of location directory in GIS Data Directory")),
  185. flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  186. border=5,
  187. pos=(2, 1)
  188. )
  189. self.sizer.Add(self.tlocation,
  190. flag=wx.ALIGN_LEFT |
  191. wx.ALIGN_CENTER_VERTICAL |
  192. wx.ALL, border=5,
  193. pos=(2, 2))
  194. self.sizer.Add(
  195. self.MakeLabel(
  196. "%s:" %
  197. _("Location Title"),
  198. tooltip=_(
  199. "Optional location title, "
  200. "you can leave this field blank.")),
  201. flag=wx.ALIGN_RIGHT | wx.ALIGN_TOP | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  202. border=5,
  203. pos=(3, 1)
  204. )
  205. self.sizer.Add(self.tlocTitle,
  206. flag=wx.ALIGN_LEFT |
  207. wx.ALIGN_CENTER_VERTICAL |
  208. wx.ALL, border=5,
  209. pos=(3, 2), span=(1, 2))
  210. self.sizer.Add(self.tlocRegion,
  211. flag=wx.ALIGN_LEFT |
  212. wx.ALIGN_CENTER_VERTICAL |
  213. wx.ALL, border=5,
  214. pos=(4, 2), span=(1, 2))
  215. self.sizer.Add(self.tlocUserMapset,
  216. flag=wx.ALIGN_LEFT |
  217. wx.ALIGN_CENTER_VERTICAL |
  218. wx.ALL, border=5,
  219. pos=(5, 2), span=(1, 2))
  220. self.sizer.AddGrowableCol(3)
  221. # bindings
  222. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  223. self.tgisdbase.Bind(wx.EVT_TEXT, self.OnChangeName)
  224. self.tlocation.Bind(wx.EVT_TEXT, self.OnChangeName)
  225. def _nameValidationFailed(self, ctrl):
  226. message = _(
  227. "Name <%(name)s> is not a valid name for location. "
  228. "Please use only ASCII characters excluding %(chars)s "
  229. "and space.") % {
  230. 'name': ctrl.GetValue(),
  231. 'chars': '/"\'@,=*~'}
  232. GError(
  233. parent=self,
  234. message=message,
  235. caption=_("Invalid location name"))
  236. def OnChangeName(self, event):
  237. """Name for new location was changed"""
  238. nextButton = wx.FindWindowById(wx.ID_FORWARD)
  239. if len(event.GetString()) > 0:
  240. if not nextButton.IsEnabled():
  241. nextButton.Enable()
  242. else:
  243. nextButton.Disable()
  244. event.Skip()
  245. def OnPageChanging(self, event=None):
  246. error = None
  247. if os.path.isdir(
  248. os.path.join(
  249. self.tgisdbase.GetLabel(),
  250. self.tlocation.GetValue())):
  251. error = _("Location already exists in GRASS Database.")
  252. if error:
  253. GError(parent=self,
  254. message="%s <%s>.%s%s" % (_("Unable to create location"),
  255. str(self.tlocation.GetValue()),
  256. os.linesep,
  257. error))
  258. event.Veto()
  259. return
  260. self.location = self.tlocation.GetValue()
  261. self.grassdatabase = self.tgisdbase.GetLabel()
  262. self.locTitle = self.tlocTitle.GetValue()
  263. if os.linesep in self.locTitle or \
  264. len(self.locTitle) > 255:
  265. GWarning(
  266. parent=self, message=_(
  267. "Title of the location is limited only to one line and "
  268. "256 characters. The rest of the text will be ignored."))
  269. self.locTitle = self.locTitle.split(os.linesep)[0][:255]
  270. class CoordinateSystemPage(TitledPage):
  271. """Wizard page for choosing method for location creation"""
  272. def __init__(self, wizard, parent):
  273. TitledPage.__init__(self, wizard, _(
  274. "Choose method for creating a new location"))
  275. self.parent = parent
  276. global coordsys
  277. # toggles
  278. self.radioEpsg = wx.RadioButton(parent=self, id=wx.ID_ANY, label=_(
  279. "Select EPSG code of spatial reference system"), style=wx.RB_GROUP)
  280. #self.radioIau = wx.RadioButton(
  281. # parent=self, id=wx.ID_ANY,
  282. # label=_("Select IAU code of spatial reference system"))
  283. self.radioFile = wx.RadioButton(
  284. parent=self, id=wx.ID_ANY, label=_(
  285. "Read projection and datum terms from a "
  286. "georeferenced data file"))
  287. self.radioWkt = wx.RadioButton(
  288. parent=self, id=wx.ID_ANY, label=_(
  289. "Read projection and datum terms from a "
  290. "Well Known Text (WKT) .prj file"))
  291. self.radioSrs = wx.RadioButton(parent=self, id=wx.ID_ANY, label=_(
  292. "Select coordinate system parameters from a list"))
  293. self.radioProj = wx.RadioButton(
  294. parent=self, id=wx.ID_ANY, label=_(
  295. "Specify projection and datum terms using custom "
  296. "PROJ.4 parameters"))
  297. self.radioXy = wx.RadioButton(parent=self, id=wx.ID_ANY, label=_(
  298. "Create a generic Cartesian coordinate system (XY)"))
  299. # layout
  300. self.sizer.SetVGap(10)
  301. self.sizer.Add(StaticText(parent=self, label=_("Simple methods:")),
  302. flag=wx.ALIGN_LEFT, pos=(1, 1))
  303. self.sizer.Add(self.radioEpsg,
  304. flag=wx.ALIGN_LEFT, pos=(2, 1))
  305. #self.sizer.Add(self.radioIau,
  306. # flag=wx.ALIGN_LEFT, pos=(1, 1))
  307. self.sizer.Add(self.radioFile,
  308. flag=wx.ALIGN_LEFT, pos=(3, 1))
  309. self.sizer.Add(self.radioWkt,
  310. flag=wx.ALIGN_LEFT, pos=(4, 1))
  311. self.sizer.Add(self.radioXy,
  312. flag=wx.ALIGN_LEFT, pos=(5, 1))
  313. self.sizer.Add(StaticText(parent=self, label=_("Advanced methods:")),
  314. flag=wx.ALIGN_LEFT, pos=(6, 1))
  315. self.sizer.Add(self.radioSrs,
  316. flag=wx.ALIGN_LEFT, pos=(7, 1))
  317. self.sizer.Add(self.radioProj,
  318. flag=wx.ALIGN_LEFT, pos=(8, 1))
  319. self.sizer.AddGrowableCol(1)
  320. # bindings
  321. self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioEpsg.GetId())
  322. #self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioIau.GetId())
  323. self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioFile.GetId())
  324. self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioWkt.GetId())
  325. self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioSrs.GetId())
  326. self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioProj.GetId())
  327. self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioXy.GetId())
  328. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  329. def OnEnterPage(self, event):
  330. global coordsys
  331. if not coordsys:
  332. coordsys = "epsg"
  333. self.radioEpsg.SetValue(True)
  334. else:
  335. if coordsys == 'proj':
  336. self.radioSrs.SetValue(True)
  337. if coordsys == "epsg":
  338. self.radioEpsg.SetValue(True)
  339. #if coordsys == "iau":
  340. # self.radioIau.SetValue(True)
  341. if coordsys == "file":
  342. self.radioFile.SetValue(True)
  343. if coordsys == "wkt":
  344. self.radioWkt.SetValue(True)
  345. if coordsys == "custom":
  346. self.radioProj.SetValue(True)
  347. if coordsys == "xy":
  348. self.radioXy.SetValue(True)
  349. if event.GetDirection():
  350. if coordsys == 'proj':
  351. self.SetNext(self.parent.projpage)
  352. self.parent.sumpage.SetPrev(self.parent.datumpage)
  353. if coordsys == "epsg":
  354. self.SetNext(self.parent.epsgpage)
  355. self.parent.sumpage.SetPrev(self.parent.epsgpage)
  356. #if coordsys == "iau":
  357. # self.SetNext(self.parent.iaupage)
  358. # self.parent.sumpage.SetPrev(self.parent.iaupage)
  359. if coordsys == "file":
  360. self.SetNext(self.parent.filepage)
  361. self.parent.sumpage.SetPrev(self.parent.filepage)
  362. if coordsys == "wkt":
  363. self.SetNext(self.parent.wktpage)
  364. self.parent.sumpage.SetPrev(self.parent.wktpage)
  365. if coordsys == "custom":
  366. self.SetNext(self.parent.custompage)
  367. self.parent.sumpage.SetPrev(self.parent.custompage)
  368. if coordsys == "xy":
  369. self.SetNext(self.parent.sumpage)
  370. self.parent.sumpage.SetPrev(self.parent.csystemspage)
  371. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  372. wx.FindWindowById(wx.ID_FORWARD).Enable()
  373. def SetVal(self, event):
  374. """Choose method"""
  375. global coordsys
  376. if event.GetId() == self.radioSrs.GetId():
  377. coordsys = "proj"
  378. self.SetNext(self.parent.projpage)
  379. self.parent.sumpage.SetPrev(self.parent.datumpage)
  380. #elif event.GetId() == self.radioIau.GetId():
  381. # coordsys = "iau"
  382. # self.SetNext(self.parent.iaupage)
  383. # self.parent.sumpage.SetPrev(self.parent.iaupage)
  384. elif event.GetId() == self.radioEpsg.GetId():
  385. coordsys = "epsg"
  386. self.SetNext(self.parent.epsgpage)
  387. self.parent.sumpage.SetPrev(self.parent.epsgpage)
  388. elif event.GetId() == self.radioFile.GetId():
  389. coordsys = "file"
  390. self.SetNext(self.parent.filepage)
  391. self.parent.sumpage.SetPrev(self.parent.filepage)
  392. elif event.GetId() == self.radioWkt.GetId():
  393. coordsys = "wkt"
  394. self.SetNext(self.parent.wktpage)
  395. self.parent.sumpage.SetPrev(self.parent.wktpage)
  396. elif event.GetId() == self.radioProj.GetId():
  397. coordsys = "custom"
  398. self.SetNext(self.parent.custompage)
  399. self.parent.sumpage.SetPrev(self.parent.custompage)
  400. elif event.GetId() == self.radioXy.GetId():
  401. coordsys = "xy"
  402. self.SetNext(self.parent.sumpage)
  403. self.parent.sumpage.SetPrev(self.parent.csystemspage)
  404. class ProjectionsPage(TitledPage):
  405. """Wizard page for selecting projection (select coordinate system option)"""
  406. def __init__(self, wizard, parent):
  407. TitledPage.__init__(self, wizard, _("Choose projection"))
  408. self.parent = parent
  409. self.proj = ''
  410. self.projdesc = ''
  411. self.p4proj = ''
  412. # text input
  413. self.tproj = self.MakeTextCtrl("", size=(200, -1))
  414. # search box
  415. self.searchb = SearchCtrl(self, size=(200, -1),
  416. style=wx.TE_PROCESS_ENTER)
  417. # projection list
  418. self.projlist = ItemList(self, data=self.parent.projdesc.items(),
  419. columns=[_('Code'), _('Description')])
  420. self.projlist.resizeLastColumn(30)
  421. # layout
  422. self.sizer.Add(self.MakeLabel(_("Projection code:")),
  423. flag=wx.ALIGN_LEFT |
  424. wx.ALIGN_CENTER_VERTICAL |
  425. wx.ALL, border=5, pos=(1, 1))
  426. self.sizer.Add(self.tproj,
  427. flag=wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL,
  428. border=5, pos=(1, 2))
  429. self.sizer.Add(self.MakeLabel(_("Search in description:")),
  430. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  431. border=5, pos=(2, 1))
  432. self.sizer.Add(self.searchb,
  433. flag=wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL,
  434. border=5, pos=(2, 2))
  435. self.sizer.Add(self.projlist,
  436. flag=wx.EXPAND |
  437. wx.ALIGN_LEFT |
  438. wx.ALL, border=5, pos=(3, 1), span=(1, 3))
  439. self.sizer.AddGrowableCol(3)
  440. self.sizer.AddGrowableRow(3)
  441. # events
  442. self.tproj.Bind(wx.EVT_TEXT, self.OnText)
  443. self.tproj.Bind(wx.EVT_TEXT_ENTER, self.OnText)
  444. self.searchb.Bind(wx.EVT_TEXT_ENTER, self.OnSearch)
  445. self.projlist.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
  446. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  447. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  448. def OnPageChanging(self, event):
  449. if event.GetDirection() and self.proj not in self.parent.projections.keys():
  450. event.Veto()
  451. def OnText(self, event):
  452. """Projection name changed"""
  453. self.proj = event.GetString().lower()
  454. self.p4proj = ''
  455. nextButton = wx.FindWindowById(wx.ID_FORWARD)
  456. if self.proj not in self.parent.projections.keys() and nextButton.IsEnabled():
  457. nextButton.Enable(False)
  458. if self.proj in self.parent.projections.keys():
  459. if self.proj == 'stp':
  460. wx.MessageBox(
  461. 'Currently State Plane projections must be selected using the '
  462. 'text-based setup (g.setproj), or entered by EPSG code or '
  463. 'custom PROJ.4 terms.', 'Warning', wx.ICON_WARNING)
  464. self.proj = ''
  465. self.tproj.SetValue(self.proj)
  466. nextButton.Enable(False)
  467. return
  468. elif self.proj.lower() == 'll':
  469. self.p4proj = '+proj=longlat'
  470. else:
  471. self.p4proj = '+proj=' + self.proj.lower()
  472. self.projdesc = self.parent.projections[self.proj][0]
  473. nextButton.Enable()
  474. def OnEnterPage(self, event):
  475. if len(self.proj) == 0:
  476. # disable 'next' button by default
  477. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  478. else:
  479. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  480. event.Skip()
  481. def OnSearch(self, event):
  482. """Search projection by desc"""
  483. str = event.GetString()
  484. try:
  485. self.proj, self.projdesc = self.projlist.Search(
  486. index=[0, 1], pattern=event.GetString())
  487. except:
  488. self.proj = self.projdesc = ''
  489. event.Skip()
  490. def OnItemSelected(self, event):
  491. """Projection selected"""
  492. index = event.GetIndex()
  493. # set values
  494. self.proj = self.projlist.GetItem(index, 0).GetText().lower()
  495. self.tproj.SetValue(self.proj)
  496. event.Skip()
  497. class ItemList(ListCtrl,
  498. listmix.ListCtrlAutoWidthMixin,
  499. listmix.ColumnSorterMixin):
  500. """Generic list (for projections, ellipsoids, etc.)"""
  501. def __init__(self, parent, columns, data=None):
  502. ListCtrl.__init__(self, parent=parent, id=wx.ID_ANY,
  503. style=wx.LC_REPORT |
  504. wx.LC_VIRTUAL |
  505. wx.LC_HRULES |
  506. wx.LC_VRULES |
  507. wx.LC_SINGLE_SEL |
  508. wx.LC_SORT_ASCENDING, size=(550, 125))
  509. # original data or None
  510. self.sourceData = data
  511. #
  512. # insert columns
  513. #
  514. i = 0
  515. for column in columns:
  516. self.InsertColumn(i, column)
  517. i += 1
  518. #
  519. # add some attributes
  520. #
  521. self.attr1 = wx.ListItemAttr()
  522. self.attr1.SetBackgroundColour(wx.Colour(238, 238, 238))
  523. self.attr2 = wx.ListItemAttr()
  524. self.attr2.SetBackgroundColour("white")
  525. if self.sourceData:
  526. self.Populate()
  527. for i in range(self.GetColumnCount()):
  528. self.SetColumnWidth(i, wx.LIST_AUTOSIZE_USEHEADER)
  529. if self.GetColumnWidth(i) < 80:
  530. self.SetColumnWidth(i, 80)
  531. #
  532. # listmix
  533. #
  534. listmix.ListCtrlAutoWidthMixin.__init__(self)
  535. listmix.ColumnSorterMixin.__init__(self, self.GetColumnCount())
  536. self.il = wx.ImageList(16, 16)
  537. self.sm_up = self.il.Add(
  538. wx.ArtProvider.GetBitmap(
  539. wx.ART_GO_UP, wx.ART_TOOLBAR, (16, 16)))
  540. self.sm_dn = self.il.Add(
  541. wx.ArtProvider.GetBitmap(
  542. wx.ART_GO_DOWN, wx.ART_TOOLBAR, (16, 16)))
  543. self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
  544. #
  545. # sort by first column
  546. #
  547. if self.sourceData:
  548. self.SortListItems(col=0, ascending=True)
  549. #
  550. # bindings
  551. #
  552. self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColumnClick)
  553. def Populate(self, data=None, update=False):
  554. """Populate list"""
  555. self.itemDataMap = {}
  556. self.itemIndexMap = []
  557. if data is None:
  558. data = self.sourceData
  559. elif update:
  560. self.sourceData = data
  561. try:
  562. data = sorted(data)
  563. self.DeleteAllItems()
  564. row = 0
  565. for value in data:
  566. self.itemDataMap[row] = [value[0]]
  567. for i in range(1, len(value)):
  568. self.itemDataMap[row].append(value[i])
  569. self.itemIndexMap.append(row)
  570. row += 1
  571. self.SetItemCount(row)
  572. # set column width
  573. self.SetColumnWidth(0, 80)
  574. self.SetColumnWidth(1, 300)
  575. self.SendSizeEvent()
  576. except Exception as e:
  577. wx.MessageBox(parent=self,
  578. message=_("Unable to read list: %s") % e,
  579. caption=_("Error"), style=wx.OK | wx.ICON_ERROR)
  580. def OnColumnClick(self, event):
  581. """Sort by column"""
  582. self._col = event.GetColumn()
  583. # remove duplicated arrow symbol from column header
  584. # FIXME: should be done automatically
  585. info = wx.ListItem()
  586. info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE
  587. info.m_image = -1
  588. for column in range(self.GetColumnCount()):
  589. info.m_text = self.GetColumn(column).GetText()
  590. self.SetColumn(column, info)
  591. event.Skip()
  592. def GetSortImages(self):
  593. """Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py"""
  594. return (self.sm_dn, self.sm_up)
  595. def OnGetItemText(self, item, col):
  596. """Get item text"""
  597. index = self.itemIndexMap[item]
  598. s = str(self.itemDataMap[index][col])
  599. return s
  600. def OnGetItemImage(self, item):
  601. return -1
  602. def OnGetItemAttr(self, item):
  603. """Get item attributes"""
  604. index = self.itemIndexMap[item]
  605. if (index % 2) == 0:
  606. return self.attr2
  607. else:
  608. return self.attr1
  609. def SortItems(self, sorter=cmp):
  610. """Sort items"""
  611. items = list(self.itemDataMap.keys())
  612. if sys.version_info[0] >= 3:
  613. # not sure what Sorter is needed for
  614. items.sort()
  615. else:
  616. items.sort(self.Sorter)
  617. self.itemIndexMap = items
  618. # redraw the list
  619. self.Refresh()
  620. def Sorter(self, key1, key2):
  621. colName = self.GetColumn(self._col).GetText()
  622. ascending = self._colSortFlag[self._col]
  623. # convert always string
  624. item1 = self.itemDataMap[key1][self._col]
  625. item2 = self.itemDataMap[key2][self._col]
  626. if isinstance(item1, type('')) or isinstance(item2, type('')):
  627. cmpVal = locale.strcoll(str(item1), str(item2))
  628. else:
  629. cmpVal = cmp(item1, item2)
  630. # If the items are equal then pick something else to make the sort
  631. # value unique
  632. if cmpVal == 0:
  633. cmpVal = cmp(*self.GetSecondarySortValues(self._col, key1, key2))
  634. if ascending:
  635. return cmpVal
  636. else:
  637. return -cmpVal
  638. def GetListCtrl(self):
  639. """Used by listmix.ColumnSorterMixin"""
  640. return self
  641. def Search(self, index, pattern):
  642. """Search projection by description
  643. Return first found item or None
  644. """
  645. if pattern == '':
  646. self.Populate(self.sourceData)
  647. return []
  648. data = []
  649. pattern = pattern.lower()
  650. for i in range(len(self.sourceData)):
  651. for idx in index:
  652. try:
  653. value = str(self.sourceData[i][idx]).lower()
  654. if pattern in value:
  655. data.append(self.sourceData[i])
  656. break
  657. except UnicodeDecodeError:
  658. # osgeo4w problem (should be fixed)
  659. pass
  660. self.Populate(data)
  661. if len(data) > 0:
  662. return data[0]
  663. else:
  664. return []
  665. class ProjParamsPage(TitledPage):
  666. """Wizard page for selecting method of setting coordinate system
  667. parameters (select coordinate system option)
  668. """
  669. def __init__(self, wizard, parent):
  670. TitledPage.__init__(self, wizard, _("Choose projection parameters"))
  671. global coordsys
  672. self.parent = parent
  673. self.panel = None
  674. self.prjParamSizer = None
  675. self.pparam = dict()
  676. self.p4projparams = ''
  677. self.projdesc = ''
  678. radioSBox = StaticBox(
  679. parent=self, id=wx.ID_ANY, label=" %s " %
  680. _("Select datum or ellipsoid (next page)"))
  681. radioSBSizer = wx.StaticBoxSizer(radioSBox)
  682. self.sizer.Add(radioSBSizer, pos=(0, 1),
  683. flag=wx.EXPAND | wx.ALIGN_TOP | wx.TOP, border=10)
  684. self.sizer.AddGrowableCol(1)
  685. self.radio1 = wx.RadioButton(
  686. parent=self, id=wx.ID_ANY,
  687. label=_("Datum with associated ellipsoid"),
  688. style=wx.RB_GROUP)
  689. self.radioEpsg = wx.RadioButton(parent=self, id=wx.ID_ANY,
  690. label=_("Ellipsoid only"))
  691. # default button setting
  692. if self.radio1.GetValue() is False and self.radioEpsg.GetValue() is False:
  693. self.radio1.SetValue(True)
  694. self.SetNext(self.parent.datumpage)
  695. # self.parent.sumpage.SetPrev(self.parent.datumpage)
  696. radioSBSizer.Add(self.radio1,
  697. flag=wx.ALIGN_LEFT | wx.RIGHT, border=20)
  698. radioSBSizer.Add(self.radioEpsg,
  699. flag=wx.ALIGN_LEFT)
  700. # bindings
  701. self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radio1.GetId())
  702. self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioEpsg.GetId())
  703. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChange)
  704. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  705. def OnParamEntry(self, event):
  706. """Parameter value changed"""
  707. id = event.GetId()
  708. val = event.GetString()
  709. if id not in self.pparam:
  710. event.Skip()
  711. return
  712. param = self.pparam[id]
  713. win = self.FindWindowById(id)
  714. if param['type'] == 'zone':
  715. val = self.FindWindowById(id).GetValue()
  716. if val < 1:
  717. win.SetValue(1)
  718. elif val > 60:
  719. win.SetValue(60)
  720. if param['type'] == 'bool':
  721. param['value'] = event.GetSelection()
  722. else:
  723. param['value'] = val
  724. event.Skip()
  725. def OnPageChange(self, event=None):
  726. """Go to next page"""
  727. if event.GetDirection():
  728. self.p4projparams = ''
  729. for id, param in six.iteritems(self.pparam):
  730. if param['type'] == 'bool':
  731. if param['value'] is False:
  732. continue
  733. else:
  734. self.p4projparams += (' +' + param['proj4'])
  735. else:
  736. if param['value'] is None:
  737. wx.MessageBox(
  738. parent=self,
  739. message=_('You must enter a value for %s') %
  740. param['desc'],
  741. caption=_('Error'),
  742. style=wx.ICON_ERROR | wx.CENTRE)
  743. event.Veto()
  744. else:
  745. self.p4projparams += (' +' +
  746. param['proj4'] +
  747. '=' +
  748. str(param['value']))
  749. def OnEnterPage(self, event):
  750. """Page entered"""
  751. self.projdesc = self.parent.projections[self.parent.projpage.proj][0]
  752. if self.prjParamSizer is None:
  753. # entering page for the first time
  754. self.paramSBox = StaticBox(
  755. parent=self,
  756. id=wx.ID_ANY,
  757. label=_(" Enter parameters for %s projection ") %
  758. self.projdesc)
  759. paramSBSizer = wx.StaticBoxSizer(self.paramSBox)
  760. self.panel = scrolled.ScrolledPanel(parent=self, id=wx.ID_ANY)
  761. self.panel.SetupScrolling()
  762. self.prjParamSizer = wx.GridBagSizer(vgap=0, hgap=0)
  763. self.sizer.Add(paramSBSizer, pos=(1, 1),
  764. flag=wx.EXPAND)
  765. self.sizer.AddGrowableRow(1)
  766. paramSBSizer.Add(self.panel, proportion=1,
  767. flag=wx.ALIGN_CENTER | wx.EXPAND)
  768. paramSBSizer.Fit(self.panel)
  769. self.panel.SetSizer(self.prjParamSizer)
  770. if event.GetDirection():
  771. self.prjParamSizer.Clear(True)
  772. self.paramSBox.SetLabel(
  773. _(" Enter parameters for %s projection ") %
  774. self.projdesc)
  775. self.pparam = dict()
  776. row = 0
  777. for paramgrp in self.parent.projections[
  778. self.parent.projpage.proj][1]:
  779. # get parameters
  780. id = NewId()
  781. param = self.pparam[id] = {
  782. 'type': self.parent.paramdesc[
  783. paramgrp[0]][0], 'proj4': self.parent.paramdesc[
  784. paramgrp[0]][1], 'desc': self.parent.paramdesc[
  785. paramgrp[0]][2]}
  786. # default values
  787. if param['type'] == 'bool':
  788. param['value'] = 0
  789. elif param['type'] == 'zone':
  790. param['value'] = 30
  791. param['desc'] += ' (1-60)'
  792. else:
  793. param['value'] = paramgrp[2]
  794. label = StaticText(
  795. parent=self.panel,
  796. id=wx.ID_ANY,
  797. label=param['desc'],
  798. style=wx.ALIGN_RIGHT | wx.ST_NO_AUTORESIZE)
  799. if param['type'] == 'bool':
  800. win = wx.Choice(parent=self.panel, id=id, size=(100, -1),
  801. choices=[_('No'), _('Yes')])
  802. win.SetSelection(param['value'])
  803. win.Bind(wx.EVT_CHOICE, self.OnParamEntry)
  804. elif param['type'] == 'zone':
  805. win = SpinCtrl(parent=self.panel, id=id,
  806. size=(100, -1),
  807. style=wx.SP_ARROW_KEYS | wx.SP_WRAP,
  808. min=1, max=60)
  809. win.SetValue(param['value'])
  810. win.Bind(wx.EVT_SPINCTRL, self.OnParamEntry)
  811. win.Bind(wx.EVT_TEXT, self.OnParamEntry)
  812. else:
  813. win = TextCtrl(parent=self.panel, id=id,
  814. value=param['value'],
  815. size=(100, -1))
  816. win.Bind(wx.EVT_TEXT, self.OnParamEntry)
  817. if paramgrp[1] == 'noask':
  818. win.Enable(False)
  819. self.prjParamSizer.Add(label, pos=(row, 1),
  820. flag=wx.ALIGN_RIGHT |
  821. wx.ALIGN_CENTER_VERTICAL |
  822. wx.RIGHT, border=5)
  823. self.prjParamSizer.Add(win, pos=(row, 2),
  824. flag=wx.ALIGN_LEFT |
  825. wx.ALIGN_CENTER_VERTICAL |
  826. wx.LEFT, border=5)
  827. row += 1
  828. self.panel.SetSize(self.panel.GetBestSize())
  829. self.panel.Layout()
  830. self.Layout()
  831. self.Update()
  832. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  833. wx.FindWindowById(wx.ID_FORWARD).Enable()
  834. event.Skip()
  835. def SetVal(self, event):
  836. """Set value"""
  837. if event.GetId() == self.radio1.GetId():
  838. self.SetNext(self.parent.datumpage)
  839. self.parent.sumpage.SetPrev(self.parent.datumpage)
  840. elif event.GetId() == self.radioEpsg.GetId():
  841. self.SetNext(self.parent.ellipsepage)
  842. self.parent.sumpage.SetPrev(self.parent.ellipsepage)
  843. class DatumPage(TitledPage):
  844. """Wizard page for selecting datum (with associated ellipsoid)
  845. and datum transformation parameters (select coordinate system option)
  846. """
  847. def __init__(self, wizard, parent):
  848. TitledPage.__init__(self, wizard, _("Specify geodetic datum"))
  849. self.parent = parent
  850. self.datum = ''
  851. self.datumdesc = ''
  852. self.ellipse = ''
  853. self.datumparams = ''
  854. self.proj4params = ''
  855. # text input
  856. self.tdatum = self.MakeTextCtrl("", size=(200, -1))
  857. # search box
  858. self.searchb = SearchCtrl(self, size=(200, -1),
  859. style=wx.TE_PROCESS_ENTER)
  860. # create list control for datum/elipsoid list
  861. data = []
  862. for key in self.parent.datums.keys():
  863. data.append([key, self.parent.datums[key][
  864. 0], self.parent.datums[key][1]])
  865. self.datumlist = ItemList(
  866. self, data=data, columns=[
  867. _('Code'), _('Ellipsoid'), _('Description')])
  868. self.datumlist.resizeLastColumn(10)
  869. # layout
  870. self.sizer.Add(self.MakeLabel(_("Datum code:")),
  871. flag=wx.ALIGN_LEFT |
  872. wx.ALIGN_CENTER_VERTICAL |
  873. wx.ALL, border=5, pos=(1, 1))
  874. self.sizer.Add(self.tdatum,
  875. flag=wx.ALIGN_LEFT |
  876. wx.ALIGN_CENTER_VERTICAL |
  877. wx.ALL, border=5, pos=(1, 2))
  878. self.sizer.Add(self.MakeLabel(_("Search in description:")),
  879. flag=wx.ALIGN_LEFT |
  880. wx.ALIGN_CENTER_VERTICAL |
  881. wx.ALL, border=5, pos=(2, 1))
  882. self.sizer.Add(self.searchb,
  883. flag=wx.ALIGN_LEFT |
  884. wx.ALIGN_CENTER_VERTICAL |
  885. wx.ALL, border=5, pos=(2, 2))
  886. self.sizer.Add(self.datumlist,
  887. flag=wx.EXPAND |
  888. wx.ALIGN_LEFT |
  889. wx.ALL, border=5, pos=(3, 1), span=(1, 4))
  890. self.sizer.AddGrowableCol(4)
  891. self.sizer.AddGrowableRow(3)
  892. # events
  893. self.datumlist.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnDatumSelected)
  894. self.searchb.Bind(wx.EVT_TEXT_ENTER, self.OnDSearch)
  895. self.tdatum.Bind(wx.EVT_TEXT, self.OnDText)
  896. self.tdatum.Bind(wx.EVT_TEXT_ENTER, self.OnDText)
  897. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  898. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  899. # do page layout
  900. # self.DoLayout()
  901. def OnPageChanging(self, event):
  902. self.proj4params = ''
  903. proj = self.parent.projpage.p4proj
  904. if event.GetDirection():
  905. if self.datum not in self.parent.datums:
  906. event.Veto()
  907. else:
  908. # check for datum tranforms
  909. # proj4string = self.parent.CreateProj4String() + ' +datum=%s' % self.datum
  910. ret = RunCommand('g.proj',
  911. read=True,
  912. proj4='%s' % proj,
  913. datum='%s' % self.datum,
  914. datum_trans='-1',
  915. flags='t')
  916. # wx.Messagebox('here')
  917. if ret != '':
  918. dtrans = ''
  919. # open a dialog to select datum transform number
  920. dlg = SelectTransformDialog(
  921. self.parent.parent, transforms=ret)
  922. if dlg.ShowModal() == wx.ID_OK:
  923. dtrans = dlg.GetTransform()
  924. if dtrans == '':
  925. dlg.Destroy()
  926. event.Veto()
  927. return 'Datum transform is required.'
  928. else:
  929. dlg.Destroy()
  930. event.Veto()
  931. return 'Datum transform is required.'
  932. self.parent.datum_trans = dtrans
  933. self.GetNext().SetPrev(self)
  934. self.parent.ellipsepage.ellipse = self.ellipse
  935. self.parent.ellipsepage.ellipseparams = self.parent.ellipsoids[
  936. self.ellipse][1]
  937. def OnEnterPage(self, event):
  938. self.parent.datum_trans = None
  939. if event.GetDirection():
  940. if len(self.datum) == 0:
  941. # disable 'next' button by default when entering from previous
  942. # page
  943. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  944. else:
  945. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  946. event.Skip()
  947. def OnDText(self, event):
  948. """Datum code changed"""
  949. self.datum = event.GetString()
  950. nextButton = wx.FindWindowById(wx.ID_FORWARD)
  951. if len(self.datum) == 0 or self.datum not in self.parent.datums:
  952. nextButton.Enable(False)
  953. else:
  954. self.ellipse = self.parent.datums[self.datum][0]
  955. self.datumdesc = self.parent.datums[self.datum][1]
  956. self.datumparams = self.parent.datums[self.datum][2]
  957. try:
  958. self.datumparams.remove('dx=0.0')
  959. except:
  960. pass
  961. try:
  962. self.datumparams.remove('dy=0.0')
  963. except:
  964. pass
  965. try:
  966. self.datumparams.remove('dz=0.0')
  967. except:
  968. pass
  969. nextButton.Enable(True)
  970. self.Update()
  971. event.Skip()
  972. def OnDSearch(self, event):
  973. """Search geodetic datum by desc"""
  974. str = self.searchb.GetValue()
  975. try:
  976. self.datum, self.ellipsoid, self.datumdesc = self.datumlist.Search(
  977. index=[
  978. 0,
  979. 1,
  980. 2],
  981. pattern=str)
  982. except:
  983. self.datum = self.datumdesc = self.ellipsoid = ''
  984. event.Skip()
  985. def OnDatumSelected(self, event):
  986. """Datum selected"""
  987. index = event.GetIndex()
  988. item = event.GetItem()
  989. self.datum = self.datumlist.GetItem(index, 0).GetText()
  990. self.tdatum.SetValue(self.datum)
  991. event.Skip()
  992. class EllipsePage(TitledPage):
  993. """Wizard page for selecting ellipsoid (select coordinate system option)"""
  994. def __init__(self, wizard, parent):
  995. TitledPage.__init__(self, wizard, _("Specify ellipsoid"))
  996. self.parent = parent
  997. self.ellipse = ''
  998. self.ellipsedesc = ''
  999. self.ellipseparams = ''
  1000. self.proj4params = ''
  1001. # text input
  1002. self.tellipse = self.MakeTextCtrl("", size=(200, -1))
  1003. # search box
  1004. self.searchb = SearchCtrl(self, size=(200, -1),
  1005. style=wx.TE_PROCESS_ENTER)
  1006. # radio buttons
  1007. self.radio1 = wx.RadioButton(parent=self, id=wx.ID_ANY,
  1008. label=_("Earth based"),
  1009. style=wx.RB_GROUP)
  1010. self.radioEpsg = wx.RadioButton(parent=self, id=wx.ID_ANY,
  1011. label=_("Planetary bodies"))
  1012. # create list control for ellipse list
  1013. data = []
  1014. # extract code, desc
  1015. for key in self.parent.ellipsoids.keys():
  1016. data.append([key, self.parent.ellipsoids[key][0]])
  1017. self.ellipselist = ItemList(self, data=data,
  1018. columns=[_('Code'), _('Description')])
  1019. self.ellipselist.resizeLastColumn(30)
  1020. # layout
  1021. self.sizer.Add(self.MakeLabel(_("Ellipsoid code:")),
  1022. flag=wx.ALIGN_RIGHT |
  1023. wx.ALIGN_CENTER_VERTICAL |
  1024. wx.ALL, border=5, pos=(1, 1))
  1025. self.sizer.Add(self.tellipse,
  1026. flag=wx.ALIGN_LEFT |
  1027. wx.ALIGN_CENTER_VERTICAL |
  1028. wx.ALL, border=5, pos=(1, 2))
  1029. self.sizer.Add(self.radio1,
  1030. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
  1031. border=25, pos=(1, 3))
  1032. self.sizer.Add(self.MakeLabel(_("Search in description:")),
  1033. flag=wx.ALIGN_RIGHT |
  1034. wx.ALIGN_CENTER_VERTICAL |
  1035. wx.ALL, border=5, pos=(2, 1))
  1036. self.sizer.Add(self.searchb,
  1037. flag=wx.ALIGN_LEFT |
  1038. wx.ALIGN_CENTER_VERTICAL |
  1039. wx.ALL, border=5, pos=(2, 2))
  1040. self.sizer.Add(self.radioEpsg,
  1041. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
  1042. border=25, pos=(2, 3))
  1043. self.sizer.Add(self.ellipselist,
  1044. flag=wx.EXPAND |
  1045. wx.ALIGN_LEFT |
  1046. wx.ALL, border=5, pos=(3, 1), span=(1, 4))
  1047. self.sizer.AddGrowableCol(4)
  1048. self.sizer.AddGrowableRow(3)
  1049. # events
  1050. self.ellipselist.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
  1051. self.tellipse.Bind(wx.EVT_TEXT, self.OnText)
  1052. self.tellipse.Bind(wx.EVT_TEXT_ENTER, self.OnText)
  1053. self.searchb.Bind(wx.EVT_TEXT_ENTER, self.OnSearch)
  1054. self.radio1.Bind(
  1055. wx.EVT_RADIOBUTTON,
  1056. self.SetVal,
  1057. id=self.radio1.GetId())
  1058. self.radioEpsg.Bind(
  1059. wx.EVT_RADIOBUTTON,
  1060. self.SetVal,
  1061. id=self.radioEpsg.GetId())
  1062. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  1063. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  1064. def OnEnterPage(self, event):
  1065. if len(self.ellipse) == 0:
  1066. # disable 'next' button by default
  1067. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  1068. else:
  1069. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  1070. self.scope = 'earth'
  1071. event.Skip()
  1072. def OnPageChanging(self, event):
  1073. if event.GetDirection() \
  1074. and self.ellipse not in self.parent.ellipsoids \
  1075. and self.ellipse not in self.parent.planetary_ellipsoids:
  1076. event.Veto()
  1077. # print self.ellipse, self.ellipsedesc, self.ellipseparams
  1078. self.proj4params = ''
  1079. self.GetNext().SetPrev(self)
  1080. self.parent.datumpage.datumparams = ''
  1081. # self.GetNext().SetPrev(self) (???)
  1082. # FIXME: index number doesn't translate when you've given a valid name
  1083. # from the other list
  1084. def OnText(self, event):
  1085. """Ellipspoid code changed"""
  1086. self.ellipse = event.GetString()
  1087. nextButton = wx.FindWindowById(wx.ID_FORWARD)
  1088. if len(self.ellipse) == 0 or \
  1089. (self.ellipse not in self.parent.ellipsoids and
  1090. self.ellipse not in self.parent.planetary_ellipsoids):
  1091. nextButton.Enable(False)
  1092. self.ellipsedesc = ''
  1093. self.ellipseparams = ''
  1094. self.proj4params = ''
  1095. elif self.ellipse in self.parent.ellipsoids:
  1096. self.ellipsedesc = self.parent.ellipsoids[self.ellipse][0]
  1097. self.ellipseparams = self.parent.ellipsoids[self.ellipse][1]
  1098. nextButton.Enable(True)
  1099. elif self.ellipse in self.parent.planetary_ellipsoids:
  1100. self.ellipsedesc = self.parent.planetary_ellipsoids[
  1101. self.ellipse][0]
  1102. self.ellipseparams = self.parent.planetary_ellipsoids[
  1103. self.ellipse][1]
  1104. nextButton.Enable(True)
  1105. # print self.ellipse, self.ellipsedesc, self.ellipseparams
  1106. def OnSearch(self, event):
  1107. """Search ellipsoid by desc"""
  1108. try:
  1109. self.ellipse, self.ellipsedesc = self.ellipselist.Search(
  1110. index=[0, 1], pattern=event.GetString())
  1111. if self.scope == 'earth':
  1112. self.ellipseparams = self.parent.ellipsoids[self.ellipse][1]
  1113. else:
  1114. self.ellipseparams = self.parent.planetary_ellipsoids[
  1115. self.ellipse][1]
  1116. except:
  1117. self.ellipse = self.ellipsedesc = self.ellipseparams = ''
  1118. event.Skip()
  1119. def OnItemSelected(self, event):
  1120. """Ellipsoid selected"""
  1121. index = event.GetIndex()
  1122. item = event.GetItem()
  1123. self.ellipse = self.ellipselist.GetItem(index, 0).GetText()
  1124. self.tellipse.SetValue(self.ellipse)
  1125. event.Skip()
  1126. def SetVal(self, event):
  1127. """Choose table to use"""
  1128. self.ellipselist.DeleteAllItems()
  1129. data = []
  1130. if event.GetId() == self.radio1.GetId():
  1131. self.scope = 'earth'
  1132. for key in self.parent.ellipsoids.keys():
  1133. data.append([key, self.parent.ellipsoids[key][0]])
  1134. elif event.GetId() == self.radioEpsg.GetId():
  1135. self.scope = 'planetary'
  1136. for key in self.parent.planetary_ellipsoids.keys():
  1137. data.append([key, self.parent.planetary_ellipsoids[key][0]])
  1138. self.ellipselist.Populate(data=data, update=True)
  1139. class GeoreferencedFilePage(TitledPage):
  1140. """Wizard page for selecting georeferenced file to use
  1141. for setting coordinate system parameters"""
  1142. def __init__(self, wizard, parent):
  1143. TitledPage.__init__(self, wizard, _("Select georeferenced file"))
  1144. self.georeffile = ''
  1145. # create controls
  1146. self.lfile = self.MakeLabel(_("Georeferenced file:"))
  1147. self.tfile = self.MakeTextCtrl(size=(300, -1))
  1148. self.bbrowse = self.MakeButton(_("Browse"))
  1149. # do layout
  1150. self.sizer.Add(self.lfile, flag=wx.ALIGN_LEFT |
  1151. wx.ALIGN_CENTRE_VERTICAL |
  1152. wx.ALL, border=5, pos=(1, 1))
  1153. self.sizer.Add(self.tfile, flag=wx.ALIGN_LEFT |
  1154. wx.ALIGN_CENTRE_VERTICAL |
  1155. wx.ALL, border=5, pos=(1, 2))
  1156. self.sizer.Add(self.bbrowse, flag=wx.ALIGN_LEFT |
  1157. wx.ALL, border=5, pos=(1, 3))
  1158. self.sizer.AddGrowableCol(3)
  1159. self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
  1160. self.tfile.Bind(wx.EVT_TEXT, self.OnText)
  1161. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  1162. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  1163. # do page layout
  1164. # self.DoLayout()
  1165. def OnEnterPage(self, event):
  1166. if len(self.georeffile) == 0:
  1167. # disable 'next' button by default
  1168. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  1169. else:
  1170. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  1171. event.Skip()
  1172. def OnPageChanging(self, event):
  1173. if event.GetDirection() and not os.path.isfile(self.georeffile):
  1174. event.Veto()
  1175. self.GetNext().SetPrev(self)
  1176. event.Skip()
  1177. def OnText(self, event):
  1178. """File changed"""
  1179. self.georeffile = event.GetString()
  1180. nextButton = wx.FindWindowById(wx.ID_FORWARD)
  1181. if len(self.georeffile) > 0 and os.path.isfile(self.georeffile):
  1182. if not nextButton.IsEnabled():
  1183. nextButton.Enable(True)
  1184. else:
  1185. if nextButton.IsEnabled():
  1186. nextButton.Enable(False)
  1187. event.Skip()
  1188. def OnBrowse(self, event):
  1189. """Choose file"""
  1190. dlg = wx.FileDialog(self,
  1191. _("Select georeferenced file"),
  1192. os.getcwd(), "", "*.*", wx.FD_OPEN)
  1193. if dlg.ShowModal() == wx.ID_OK:
  1194. path = dlg.GetPath()
  1195. self.tfile.SetValue(path)
  1196. dlg.Destroy()
  1197. event.Skip()
  1198. class WKTPage(TitledPage):
  1199. """Wizard page for selecting WKT file to use
  1200. for setting coordinate system parameters"""
  1201. def __init__(self, wizard, parent):
  1202. TitledPage.__init__(self, wizard, _(
  1203. "Select Well Known Text (WKT) .prj file"))
  1204. self.wktfile = ''
  1205. # create controls
  1206. self.lfile = self.MakeLabel(_("WKT .prj file:"))
  1207. self.tfile = self.MakeTextCtrl(size=(300, -1))
  1208. self.bbrowse = self.MakeButton(_("Browse"))
  1209. # do layout
  1210. self.sizer.Add(self.lfile, flag=wx.ALIGN_LEFT |
  1211. wx.ALIGN_CENTRE_VERTICAL |
  1212. wx.ALL, border=5, pos=(1, 1))
  1213. self.sizer.Add(self.tfile, flag=wx.ALIGN_LEFT |
  1214. wx.ALIGN_CENTRE_VERTICAL |
  1215. wx.ALL, border=5, pos=(1, 2))
  1216. self.sizer.Add(self.bbrowse, flag=wx.ALIGN_LEFT |
  1217. wx.ALL, border=5, pos=(1, 3))
  1218. self.sizer.AddGrowableCol(3)
  1219. self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
  1220. self.tfile.Bind(wx.EVT_TEXT, self.OnText)
  1221. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  1222. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  1223. def OnEnterPage(self, event):
  1224. if len(self.wktfile) == 0:
  1225. # disable 'next' button by default
  1226. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  1227. else:
  1228. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  1229. event.Skip()
  1230. def OnPageChanging(self, event):
  1231. if event.GetDirection() and not os.path.isfile(self.wktfile):
  1232. event.Veto()
  1233. self.GetNext().SetPrev(self)
  1234. event.Skip()
  1235. def OnText(self, event):
  1236. """File changed"""
  1237. self.wktfile = event.GetString()
  1238. nextButton = wx.FindWindowById(wx.ID_FORWARD)
  1239. if len(self.wktfile) > 0 and os.path.isfile(self.wktfile):
  1240. if not nextButton.IsEnabled():
  1241. nextButton.Enable(True)
  1242. else:
  1243. if nextButton.IsEnabled():
  1244. nextButton.Enable(False)
  1245. event.Skip()
  1246. def OnBrowse(self, event):
  1247. """Choose file"""
  1248. dlg = wx.FileDialog(
  1249. parent=self,
  1250. message=_("Select Well Known Text (WKT) .prj file"),
  1251. defaultDir=os.getcwd(),
  1252. wildcard="PRJ files (*.prj)|*.prj|Files (*.*)|*.*",
  1253. style=wx.FD_OPEN)
  1254. if dlg.ShowModal() == wx.ID_OK:
  1255. path = dlg.GetPath()
  1256. self.tfile.SetValue(path)
  1257. dlg.Destroy()
  1258. event.Skip()
  1259. class EPSGPage(TitledPage):
  1260. """Wizard page for selecting EPSG code for
  1261. setting coordinate system parameters"""
  1262. def __init__(self, wizard, parent):
  1263. TitledPage.__init__(self, wizard, _("Choose EPSG Code"))
  1264. self.parent = parent
  1265. self.epsgCodeDict = {}
  1266. self.epsgcode = None
  1267. self.epsgdesc = ''
  1268. self.epsgparams = ''
  1269. # labels
  1270. self.lfile = self.MakeLabel(
  1271. _("Path to the EPSG-codes file:"),
  1272. style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
  1273. self.lcode = self.MakeLabel(
  1274. _("EPSG code:"),
  1275. style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
  1276. # text input
  1277. epsgdir = utils.PathJoin(os.environ["GRASS_PROJSHARE"], 'epsg')
  1278. self.tfile = self.MakeTextCtrl(text=epsgdir, size=(200, -1),
  1279. style=wx.TE_PROCESS_ENTER)
  1280. self.tcode = self.MakeTextCtrl(size=(200, -1))
  1281. # buttons
  1282. self.bbrowse = self.MakeButton(_("Browse"))
  1283. # search box
  1284. self.searchb = SearchCtrl(self, size=(200, -1),
  1285. style=wx.TE_PROCESS_ENTER)
  1286. self.epsglist = ItemList(
  1287. self,
  1288. data=None,
  1289. columns=[
  1290. _('Code'),
  1291. _('Description'),
  1292. _('Parameters')])
  1293. # layout
  1294. self.sizer.Add(self.lfile,
  1295. flag=wx.ALIGN_LEFT |
  1296. wx.ALIGN_CENTER_VERTICAL |
  1297. wx.ALL, border=5, pos=(1, 1), span=(1, 2))
  1298. self.sizer.Add(self.tfile,
  1299. flag=wx.ALIGN_LEFT |
  1300. wx.ALIGN_CENTER_VERTICAL |
  1301. wx.ALL, border=5, pos=(1, 3))
  1302. self.sizer.Add(self.bbrowse,
  1303. flag=wx.ALIGN_LEFT |
  1304. wx.ALIGN_CENTER_VERTICAL |
  1305. wx.ALL, border=5, pos=(1, 4))
  1306. self.sizer.Add(self.lcode,
  1307. flag=wx.ALIGN_LEFT |
  1308. wx.ALIGN_CENTER_VERTICAL |
  1309. wx.ALL, border=5, pos=(2, 1), span=(1, 2))
  1310. self.sizer.Add(self.tcode,
  1311. flag=wx.ALIGN_LEFT |
  1312. wx.ALIGN_CENTER_VERTICAL |
  1313. wx.ALL, border=5, pos=(2, 3))
  1314. self.sizer.Add(self.searchb,
  1315. flag=wx.ALIGN_LEFT |
  1316. wx.ALIGN_CENTER_VERTICAL |
  1317. wx.ALL, border=5, pos=(3, 3))
  1318. self.sizer.Add(self.epsglist,
  1319. flag=wx.ALIGN_LEFT | wx.EXPAND, pos=(4, 1),
  1320. span=(1, 4))
  1321. self.sizer.AddGrowableCol(3)
  1322. self.sizer.AddGrowableRow(4)
  1323. # events
  1324. self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
  1325. self.tfile.Bind(wx.EVT_TEXT_ENTER, self.OnBrowseCodes)
  1326. self.tcode.Bind(wx.EVT_TEXT, self.OnText)
  1327. self.tcode.Bind(wx.EVT_TEXT_ENTER, self.OnText)
  1328. self.epsglist.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
  1329. self.searchb.Bind(wx.EVT_TEXT_ENTER, self.OnSearch)
  1330. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  1331. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  1332. def OnEnterPage(self, event):
  1333. self.parent.datum_trans = None
  1334. if event.GetDirection():
  1335. if not self.epsgcode:
  1336. # disable 'next' button by default
  1337. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  1338. else:
  1339. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  1340. # load default epsg database file
  1341. self.OnBrowseCodes(None)
  1342. event.Skip()
  1343. def OnPageChanging(self, event):
  1344. if event.GetDirection():
  1345. if not self.epsgcode:
  1346. event.Veto()
  1347. return
  1348. else:
  1349. # check for datum transforms
  1350. ret = RunCommand('g.proj',
  1351. read=True,
  1352. epsg=self.epsgcode,
  1353. datum_trans='-1',
  1354. flags='t')
  1355. if ret != '':
  1356. dtrans = ''
  1357. # open a dialog to select datum transform number
  1358. dlg = SelectTransformDialog(
  1359. self.parent.parent, transforms=ret)
  1360. if dlg.ShowModal() == wx.ID_OK:
  1361. dtrans = dlg.GetTransform()
  1362. if dtrans == '':
  1363. dlg.Destroy()
  1364. event.Veto()
  1365. return 'Datum transform is required.'
  1366. else:
  1367. dlg.Destroy()
  1368. event.Veto()
  1369. return 'Datum transform is required.'
  1370. self.parent.datum_trans = dtrans
  1371. self.GetNext().SetPrev(self)
  1372. def OnText(self, event):
  1373. self.epsgcode = event.GetString()
  1374. try:
  1375. self.epsgcode = int(self.epsgcode)
  1376. except:
  1377. self.epsgcode = None
  1378. nextButton = wx.FindWindowById(wx.ID_FORWARD)
  1379. if self.epsgcode and self.epsgCodeDict and \
  1380. self.epsgcode in self.epsgCodeDict.keys():
  1381. self.epsgdesc = self.epsgCodeDict[self.epsgcode][0]
  1382. self.epsgparams = self.epsgCodeDict[self.epsgcode][1]
  1383. if not nextButton.IsEnabled():
  1384. nextButton.Enable(True)
  1385. else:
  1386. self.epsgcode = None # not found
  1387. if nextButton.IsEnabled():
  1388. nextButton.Enable(False)
  1389. self.epsgdesc = self.epsgparams = ''
  1390. def OnSearch(self, event):
  1391. value = self.searchb.GetValue()
  1392. if value == '':
  1393. self.epsgcode = None
  1394. self.epsgdesc = self.epsgparams = ''
  1395. self.tcode.SetValue('')
  1396. self.searchb.SetValue('')
  1397. self.OnBrowseCodes(None)
  1398. else:
  1399. try:
  1400. self.epsgcode, self.epsgdesc, self.epsgparams = \
  1401. self.epsglist.Search(index=[0, 1, 2], pattern=value)
  1402. except (IndexError, ValueError): # -> no item found
  1403. self.epsgcode = None
  1404. self.epsgdesc = self.epsgparams = ''
  1405. self.tcode.SetValue('')
  1406. event.Skip()
  1407. def OnBrowse(self, event):
  1408. """Define path for EPSG code file"""
  1409. path = os.path.dirname(self.tfile.GetValue())
  1410. if not path:
  1411. path = os.getcwd()
  1412. dlg = wx.FileDialog(
  1413. parent=self,
  1414. message=_("Choose EPSG codes file"),
  1415. defaultDir=path,
  1416. defaultFile="",
  1417. wildcard="*",
  1418. style=wx.FD_OPEN)
  1419. if dlg.ShowModal() == wx.ID_OK:
  1420. path = dlg.GetPath()
  1421. self.tfile.SetValue(path)
  1422. self.OnBrowseCodes(None)
  1423. dlg.Destroy()
  1424. event.Skip()
  1425. def OnItemSelected(self, event):
  1426. """EPSG code selected from the list"""
  1427. index = event.GetIndex()
  1428. item = event.GetItem()
  1429. self.epsgcode = int(self.epsglist.GetItem(index, 0).GetText())
  1430. self.epsgdesc = self.epsglist.GetItem(index, 1).GetText()
  1431. self.tcode.SetValue(str(self.epsgcode))
  1432. event.Skip()
  1433. def OnBrowseCodes(self, event, search=None):
  1434. """Browse EPSG codes"""
  1435. try:
  1436. self.epsgCodeDict = utils.ReadEpsgCodes()
  1437. except OpenError as e:
  1438. GError(
  1439. parent=self,
  1440. message=_("Unable to read EPGS codes: {0}").format(e),
  1441. showTraceback=False)
  1442. self.epsglist.Populate(list(), update=True)
  1443. return
  1444. data = list()
  1445. for code, val in six.iteritems(self.epsgCodeDict):
  1446. if code is not None:
  1447. data.append((code, val[0], val[1]))
  1448. self.epsglist.Populate(data, update=True)
  1449. class IAUPage(TitledPage):
  1450. """Wizard page for selecting IAU code/WKT for
  1451. setting coordinate system parameters"""
  1452. def __init__(self, wizard, parent):
  1453. TitledPage.__init__(self, wizard, _("Choose IAU Code"))
  1454. self.parent = parent
  1455. self.epsgCodeDict = {}
  1456. self.epsgcode = None
  1457. self.epsgdesc = ''
  1458. self.epsgparams = ''
  1459. # labels
  1460. self.lfile = self.MakeLabel(
  1461. _("Path to the IAU-codes file:"),
  1462. style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
  1463. self.lcode = self.MakeLabel(
  1464. _("IAU code:"),
  1465. style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
  1466. # text input
  1467. epsgdir = utils.PathJoin(
  1468. globalvar.ETCDIR,
  1469. "proj",
  1470. "ogr_csv",
  1471. 'iau2009.csv')
  1472. self.tfile = self.MakeTextCtrl(text=epsgdir, size=(200, -1),
  1473. style=wx.TE_PROCESS_ENTER)
  1474. self.tcode = self.MakeTextCtrl(size=(200, -1))
  1475. # buttons
  1476. self.bbrowse = self.MakeButton(_("Browse"))
  1477. # search box
  1478. self.searchb = SearchCtrl(self, size=(200, -1),
  1479. style=wx.TE_PROCESS_ENTER)
  1480. self.epsglist = ItemList(
  1481. self,
  1482. data=None,
  1483. columns=[
  1484. _('Code'),
  1485. _('Description'),
  1486. _('Parameters')])
  1487. # layout
  1488. self.sizer.Add(self.lfile,
  1489. flag=wx.ALIGN_LEFT |
  1490. wx.ALIGN_CENTER_VERTICAL |
  1491. wx.ALL, border=5, pos=(1, 1), span=(1, 2))
  1492. self.sizer.Add(self.tfile,
  1493. flag=wx.ALIGN_LEFT |
  1494. wx.ALIGN_CENTER_VERTICAL |
  1495. wx.ALL, border=5, pos=(1, 3))
  1496. self.sizer.Add(self.bbrowse,
  1497. flag=wx.ALIGN_LEFT |
  1498. wx.ALIGN_CENTER_VERTICAL |
  1499. wx.ALL, border=5, pos=(1, 4))
  1500. self.sizer.Add(self.lcode,
  1501. flag=wx.ALIGN_LEFT |
  1502. wx.ALIGN_CENTER_VERTICAL |
  1503. wx.ALL, border=5, pos=(2, 1), span=(1, 2))
  1504. self.sizer.Add(self.tcode,
  1505. flag=wx.ALIGN_LEFT |
  1506. wx.ALIGN_CENTER_VERTICAL |
  1507. wx.ALL, border=5, pos=(2, 3))
  1508. self.sizer.Add(self.searchb,
  1509. flag=wx.ALIGN_LEFT |
  1510. wx.ALIGN_CENTER_VERTICAL |
  1511. wx.ALL, border=5, pos=(3, 3))
  1512. self.sizer.Add(self.epsglist,
  1513. flag=wx.ALIGN_LEFT | wx.EXPAND, pos=(4, 1),
  1514. span=(1, 4))
  1515. self.sizer.AddGrowableCol(3)
  1516. self.sizer.AddGrowableRow(4)
  1517. # events
  1518. self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
  1519. self.tfile.Bind(wx.EVT_TEXT_ENTER, self.OnBrowseCodes)
  1520. self.tcode.Bind(wx.EVT_TEXT, self.OnText)
  1521. self.tcode.Bind(wx.EVT_TEXT_ENTER, self.OnText)
  1522. self.epsglist.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
  1523. self.searchb.Bind(wx.EVT_TEXT_ENTER, self.OnSearch)
  1524. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  1525. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  1526. def OnEnterPage(self, event):
  1527. self.parent.datum_trans = None
  1528. if event.GetDirection():
  1529. if not self.epsgcode:
  1530. # disable 'next' button by default
  1531. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  1532. else:
  1533. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  1534. # load default epsg database file
  1535. self.OnBrowseCodes(None)
  1536. event.Skip()
  1537. def OnPageChanging(self, event):
  1538. if event.GetDirection():
  1539. if not self.epsgcode:
  1540. event.Veto()
  1541. return
  1542. else:
  1543. # check for datum transforms
  1544. ret = RunCommand('g.proj',
  1545. read=True,
  1546. proj4=self.epsgparams,
  1547. datum_trans='-1',
  1548. flags='t')
  1549. if ret != '':
  1550. dtrans = ''
  1551. # open a dialog to select datum transform number
  1552. dlg = SelectTransformDialog(
  1553. self.parent.parent, transforms=ret)
  1554. if dlg.ShowModal() == wx.ID_OK:
  1555. dtrans = dlg.GetTransform()
  1556. if dtrans == '':
  1557. dlg.Destroy()
  1558. event.Veto()
  1559. return 'Datum transform is required.'
  1560. else:
  1561. dlg.Destroy()
  1562. event.Veto()
  1563. return 'Datum transform is required.'
  1564. self.parent.datum_trans = dtrans
  1565. self.parent.epsgcode = self.epsgcode
  1566. self.parent.epsgdesc = self.epsgdesc
  1567. # prepare +nadgrids or +towgs84 terms for Summary page. first
  1568. # convert them:
  1569. ret, projlabel, err = RunCommand(
  1570. 'g.proj', flags='jft', proj4=self.epsgparams,
  1571. datum_trans=self.parent.datum_trans, getErrorMsg=True,
  1572. read=True)
  1573. # splitting on space alone would break for grid files with
  1574. # space in pathname
  1575. for projterm in projlabel.split(' +'):
  1576. if projterm.find(
  1577. "towgs84=") != -1 or projterm.find("nadgrids=") != -1:
  1578. self.custom_dtrans_string = ' +%s' % projterm
  1579. break
  1580. self.GetNext().SetPrev(self)
  1581. def OnText(self, event):
  1582. self.epsgcode = event.GetString()
  1583. try:
  1584. self.epsgcode = int(self.epsgcode)
  1585. except:
  1586. self.epsgcode = None
  1587. nextButton = wx.FindWindowById(wx.ID_FORWARD)
  1588. # if self.epsgcode and self.epsgcode in self.epsgCodeDict.keys():
  1589. if self.epsgcode:
  1590. self.epsgdesc = self.epsgCodeDict[self.epsgcode][0]
  1591. self.epsgparams = self.epsgCodeDict[self.epsgcode][1]
  1592. if not nextButton.IsEnabled():
  1593. nextButton.Enable(True)
  1594. else:
  1595. self.epsgcode = None # not found
  1596. if nextButton.IsEnabled():
  1597. nextButton.Enable(False)
  1598. self.epsgdesc = self.epsgparams = ''
  1599. def OnSearch(self, event):
  1600. value = self.searchb.GetValue()
  1601. if value == '':
  1602. self.epsgcode = None
  1603. self.epsgdesc = self.epsgparams = ''
  1604. self.tcode.SetValue('')
  1605. self.searchb.SetValue('')
  1606. self.OnBrowseCodes(None)
  1607. else:
  1608. try:
  1609. self.epsgcode, self.epsgdesc, self.epsgparams = \
  1610. self.epsglist.Search(index=[0, 1, 2], pattern=value)
  1611. except (IndexError, ValueError): # -> no item found
  1612. self.epsgcode = None
  1613. self.epsgdesc = self.epsgparams = ''
  1614. self.tcode.SetValue('')
  1615. event.Skip()
  1616. def OnBrowse(self, event):
  1617. """Define path for IAU code file"""
  1618. path = os.path.dirname(self.tfile.GetValue())
  1619. if not path:
  1620. path = os.getcwd()
  1621. dlg = wx.FileDialog(
  1622. parent=self,
  1623. message=_("Choose IAU codes file"),
  1624. defaultDir=path,
  1625. defaultFile="",
  1626. wildcard="*",
  1627. style=wx.FD_OPEN)
  1628. if dlg.ShowModal() == wx.ID_OK:
  1629. path = dlg.GetPath()
  1630. self.tfile.SetValue(path)
  1631. self.OnBrowseCodes(None)
  1632. dlg.Destroy()
  1633. event.Skip()
  1634. def OnItemSelected(self, event):
  1635. """IAU code selected from the list"""
  1636. index = event.GetIndex()
  1637. item = event.GetItem()
  1638. self.epsgcode = int(self.epsglist.GetItem(index, 0).GetText())
  1639. # This is here that the index 2 (aka WKT) should be loaded in a
  1640. # variable
  1641. self.epsgdesc = self.epsglist.GetItem(index, 1).GetText()
  1642. self.tcode.SetValue(str(self.epsgcode))
  1643. event.Skip()
  1644. def OnBrowseCodes(self, event, search=None):
  1645. """Browse IAU codes"""
  1646. try:
  1647. self.epsgCodeDict = utils.ReadEpsgCodes()
  1648. except OpenError as e:
  1649. GError(
  1650. parent=self,
  1651. message=_("Unable to read IAU codes: {0}").format(e),
  1652. showTraceback=False)
  1653. self.epsglist.Populate(list(), update=True)
  1654. return
  1655. data = list()
  1656. for code, val in six.iteritems(self.epsgCodeDict):
  1657. if code is not None:
  1658. data.append((code, val[0], val[1]))
  1659. self.epsglist.Populate(data, update=True)
  1660. class CustomPage(TitledPage):
  1661. """Wizard page for entering custom PROJ.4 string
  1662. for setting coordinate system parameters"""
  1663. def __init__(self, wizard, parent):
  1664. TitledPage.__init__(
  1665. self, wizard,
  1666. _("Choose method of specifying georeferencing parameters"))
  1667. global coordsys
  1668. self.customstring = ''
  1669. self.parent = parent
  1670. # widgets
  1671. self.text_proj4string = self.MakeTextCtrl(size=(400, 200),
  1672. style=wx.TE_MULTILINE)
  1673. self.label_proj4string = self.MakeLabel(
  1674. _("Enter PROJ.4 parameters string:"))
  1675. # layout
  1676. self.sizer.Add(self.label_proj4string,
  1677. flag=wx.ALIGN_LEFT | wx.ALL,
  1678. border=5, pos=(1, 1))
  1679. self.sizer.Add(self.text_proj4string,
  1680. flag=wx.ALIGN_LEFT | wx.ALL | wx.EXPAND,
  1681. border=5, pos=(2, 1), span=(1, 2))
  1682. self.sizer.AddGrowableRow(2)
  1683. self.sizer.AddGrowableCol(2)
  1684. self.text_proj4string.Bind(wx.EVT_TEXT, self.GetProjstring)
  1685. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  1686. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  1687. def OnEnterPage(self, event):
  1688. if len(self.customstring) == 0:
  1689. # disable 'next' button by default
  1690. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  1691. else:
  1692. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  1693. def OnPageChanging(self, event):
  1694. if event.GetDirection():
  1695. self.custom_dtrans_string = ''
  1696. if self.customstring.find('+datum=') < 0:
  1697. self.GetNext().SetPrev(self)
  1698. return
  1699. # check for datum tranforms
  1700. # FIXME: -t flag is a hack-around for trac bug #1849
  1701. ret, out, err = RunCommand('g.proj',
  1702. read=True, getErrorMsg=True,
  1703. proj4=self.customstring,
  1704. datum_trans='-1',
  1705. flags='t')
  1706. if ret != 0:
  1707. wx.MessageBox(parent=self,
  1708. message=err,
  1709. caption=_("Error"),
  1710. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1711. event.Veto()
  1712. return
  1713. if out:
  1714. dtrans = ''
  1715. # open a dialog to select datum transform number
  1716. dlg = SelectTransformDialog(self.parent.parent, transforms=out)
  1717. if dlg.ShowModal() == wx.ID_OK:
  1718. dtrans = dlg.GetTransform()
  1719. if dtrans == '':
  1720. dlg.Destroy()
  1721. event.Veto()
  1722. return _('Datum transform is required.')
  1723. else:
  1724. dlg.Destroy()
  1725. event.Veto()
  1726. return _('Datum transform is required.')
  1727. self.parent.datum_trans = dtrans
  1728. # prepare +nadgrids or +towgs84 terms for Summary page. first
  1729. # convert them:
  1730. ret, projlabel, err = RunCommand('g.proj',
  1731. flags='jft',
  1732. proj4=self.customstring,
  1733. datum_trans=dtrans,
  1734. getErrorMsg=True,
  1735. read=True)
  1736. # splitting on space alone would break for grid files with
  1737. # space in pathname
  1738. for projterm in projlabel.split(' +'):
  1739. if projterm.find(
  1740. "towgs84=") != -1 or projterm.find("nadgrids=") != -1:
  1741. self.custom_dtrans_string = ' +%s' % projterm
  1742. break
  1743. self.GetNext().SetPrev(self)
  1744. def GetProjstring(self, event):
  1745. """Change proj string"""
  1746. # TODO: check PROJ.4 syntax
  1747. self.customstring = event.GetString()
  1748. nextButton = wx.FindWindowById(wx.ID_FORWARD)
  1749. if len(self.customstring) == 0:
  1750. if nextButton.IsEnabled():
  1751. nextButton.Enable(False)
  1752. else:
  1753. if not nextButton.IsEnabled():
  1754. nextButton.Enable()
  1755. class SummaryPage(TitledPage):
  1756. """Shows summary result of choosing coordinate system parameters
  1757. prior to creating location"""
  1758. def __init__(self, wizard, parent):
  1759. TitledPage.__init__(self, wizard, _("Summary"))
  1760. self.parent = parent
  1761. self.panelTitle = scrolled.ScrolledPanel(parent=self, id=wx.ID_ANY)
  1762. self.panelProj4string = scrolled.ScrolledPanel(
  1763. parent=self, id=wx.ID_ANY)
  1764. self.panelProj = scrolled.ScrolledPanel(parent=self, id=wx.ID_ANY)
  1765. # labels
  1766. self.ldatabase = self.MakeLabel()
  1767. self.llocation = self.MakeLabel()
  1768. self.llocTitle = self.MakeLabel(parent=self.panelTitle)
  1769. self.lprojection = self.MakeLabel(parent=self.panelProj)
  1770. self.lproj4string = self.MakeLabel(parent=self.panelProj4string)
  1771. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  1772. # do sub-page layout
  1773. self._doLayout()
  1774. def _doLayout(self):
  1775. """Do page layout"""
  1776. titleSizer = wx.BoxSizer(wx.VERTICAL)
  1777. titleSizer.Add(self.llocTitle, proportion=1,
  1778. flag=wx.EXPAND | wx.ALL, border=5)
  1779. self.panelTitle.SetSizer(titleSizer)
  1780. projSizer = wx.BoxSizer(wx.VERTICAL)
  1781. projSizer.Add(self.lprojection, proportion=1,
  1782. flag=wx.EXPAND | wx.ALL, border=5)
  1783. self.panelProj.SetSizer(projSizer)
  1784. proj4stringSizer = wx.BoxSizer(wx.VERTICAL)
  1785. proj4stringSizer.Add(self.lproj4string, proportion=1,
  1786. flag=wx.EXPAND | wx.ALL, border=5)
  1787. self.panelProj4string.SetSizer(proj4stringSizer)
  1788. self.panelProj4string.SetupScrolling()
  1789. self.panelProj.SetupScrolling(scroll_y=False)
  1790. self.panelTitle.SetupScrolling(scroll_y=False)
  1791. self.sizer.Add(self.MakeLabel(_("GRASS Database:")),
  1792. flag=wx.ALIGN_LEFT | wx.ALL,
  1793. border=5, pos=(1, 0))
  1794. self.sizer.Add(self.ldatabase,
  1795. flag=wx.ALIGN_LEFT | wx.ALL,
  1796. border=5, pos=(1, 1))
  1797. self.sizer.Add(self.MakeLabel(_("Location Name:")),
  1798. flag=wx.ALIGN_LEFT | wx.ALL,
  1799. border=5, pos=(2, 0))
  1800. self.sizer.Add(self.llocation,
  1801. flag=wx.ALIGN_LEFT | wx.ALL,
  1802. border=5, pos=(2, 1))
  1803. self.sizer.Add(self.MakeLabel(_("Location Title:")),
  1804. flag=wx.ALIGN_LEFT | wx.ALL,
  1805. border=5, pos=(3, 0))
  1806. self.sizer.Add(self.panelTitle,
  1807. flag=wx.ALIGN_LEFT | wx.ALL | wx.EXPAND,
  1808. border=0, pos=(3, 1))
  1809. self.sizer.Add(self.MakeLabel(_("Projection:")),
  1810. flag=wx.ALIGN_LEFT | wx.ALL,
  1811. border=5, pos=(4, 0))
  1812. self.sizer.Add(self.panelProj,
  1813. flag=wx.ALIGN_LEFT | wx.ALL | wx.EXPAND,
  1814. border=0, pos=(4, 1))
  1815. self.sizer.Add(
  1816. self.MakeLabel(
  1817. _("PROJ.4 definition:\n (non-definitive)")),
  1818. flag=wx.ALIGN_LEFT | wx.ALL,
  1819. border=5,
  1820. pos=(
  1821. 5,
  1822. 0))
  1823. self.sizer.Add(self.panelProj4string,
  1824. flag=wx.ALIGN_LEFT | wx.ALL | wx.EXPAND,
  1825. border=0, pos=(5, 1))
  1826. self.sizer.AddGrowableCol(1)
  1827. self.sizer.AddGrowableRow(3, 1)
  1828. self.sizer.AddGrowableRow(4, 1)
  1829. self.sizer.AddGrowableRow(5, 5)
  1830. def OnEnterPage(self, event):
  1831. """Insert values into text controls for summary of location
  1832. creation options
  1833. """
  1834. database = self.parent.startpage.grassdatabase
  1835. location = self.parent.startpage.location
  1836. proj4string = self.parent.CreateProj4String()
  1837. iauproj4string = self.parent.iaupage.epsgparams
  1838. epsgcode = self.parent.epsgpage.epsgcode
  1839. datum = self.parent.datumpage.datum
  1840. dtrans = self.parent.datum_trans
  1841. global coordsys
  1842. # print coordsys,proj4string
  1843. if coordsys in ('proj', 'epsg', 'iau', 'wkt', 'file'):
  1844. extra_opts = {}
  1845. extra_opts['location'] = 'location'
  1846. extra_opts['getErrorMsg'] = True
  1847. extra_opts['read'] = True
  1848. if coordsys == 'proj':
  1849. addl_opts = {}
  1850. if len(datum) > 0:
  1851. extra_opts['datum'] = '%s' % datum
  1852. extra_opts['datum_trans'] = dtrans
  1853. ret, projlabel, err = RunCommand('g.proj',
  1854. flags='jf',
  1855. proj4=proj4string,
  1856. **extra_opts)
  1857. elif coordsys == 'iau':
  1858. addl_opts = {}
  1859. if len(datum) > 0:
  1860. extra_opts['datum'] = '%s' % datum
  1861. extra_opts['datum_trans'] = dtrans
  1862. ret, projlabel, err = RunCommand('g.proj',
  1863. flags='jf',
  1864. proj4=iauproj4string,
  1865. **extra_opts)
  1866. elif coordsys == 'epsg':
  1867. ret, projlabel, err = RunCommand('g.proj',
  1868. flags='jft',
  1869. epsg=epsgcode,
  1870. datum_trans=dtrans,
  1871. **extra_opts)
  1872. elif coordsys == 'file':
  1873. ret, projlabel, err = RunCommand(
  1874. 'g.proj', flags='jft',
  1875. georef=self.parent.filepage.georeffile, **extra_opts)
  1876. elif coordsys == 'wkt':
  1877. ret, projlabel, err = RunCommand(
  1878. 'g.proj', flags='jft', wkt=self.parent.wktpage.wktfile, **extra_opts)
  1879. finishButton = wx.FindWindowById(wx.ID_FORWARD)
  1880. if ret == 0:
  1881. if datum != '':
  1882. projlabel = projlabel + '+datum=%s' % datum
  1883. self.lproj4string.SetLabel(
  1884. projlabel.replace(' +', os.linesep + '+'))
  1885. finishButton.Enable(True)
  1886. else:
  1887. GError(err, parent=self)
  1888. self.lproj4string.SetLabel('')
  1889. finishButton.Enable(False)
  1890. projdesc = self.parent.projpage.projdesc
  1891. ellipsedesc = self.parent.ellipsepage.ellipsedesc
  1892. datumdesc = self.parent.datumpage.datumdesc
  1893. # print projdesc,ellipsedesc,datumdesc
  1894. self.ldatabase.SetLabel(database)
  1895. self.llocation.SetLabel(location)
  1896. self.llocTitle.SetLabel(self.parent.startpage.locTitle)
  1897. label = ''
  1898. if coordsys == 'epsg':
  1899. label = 'EPSG code %s (%s)' % (self.parent.epsgpage.epsgcode,
  1900. self.parent.epsgpage.epsgdesc)
  1901. elif coordsys == 'iau':
  1902. label = 'IAU code %s (%s)' % (self.parent.iaupage.epsgcode,
  1903. self.parent.iaupage.epsgdesc)
  1904. elif coordsys == 'file':
  1905. label = 'matches file %s' % self.parent.filepage.georeffile
  1906. elif coordsys == 'wkt':
  1907. label = 'matches file %s' % self.parent.wktpage.wktfile
  1908. elif coordsys == 'proj':
  1909. label = ('%s, %s %s' % (projdesc, datumdesc, ellipsedesc))
  1910. elif coordsys == 'xy':
  1911. label = ('XY coordinate system (not projected).')
  1912. self.lproj4string.SetLabel("")
  1913. elif coordsys == 'custom':
  1914. label = _("custom")
  1915. combo_str = self.parent.custompage.customstring + \
  1916. self.parent.custompage.custom_dtrans_string
  1917. self.lproj4string.SetLabel(
  1918. ('%s' %
  1919. combo_str.replace(
  1920. ' +',
  1921. os.linesep +
  1922. '+')))
  1923. self.lprojection.SetLabel(label)
  1924. def OnFinish(self, event):
  1925. dlg = wx.MessageDialog(
  1926. parent=self.wizard,
  1927. message=_("Do you want to create GRASS location <%s>?") %
  1928. location,
  1929. caption=_("Create new location?"),
  1930. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  1931. if dlg.ShowModal() == wx.ID_NO:
  1932. dlg.Destroy()
  1933. event.Veto()
  1934. else:
  1935. dlg.Destroy()
  1936. event.Skip()
  1937. class LocationWizard(wx.Object):
  1938. """Start wizard here and finish wizard here
  1939. """
  1940. def __init__(self, parent, grassdatabase):
  1941. self.__cleanUp()
  1942. global coordsys
  1943. self.parent = parent
  1944. #
  1945. # define wizard image
  1946. #
  1947. imagePath = os.path.join(globalvar.IMGDIR, "loc_wizard_qgis.png")
  1948. wizbmp = wx.Image(imagePath, wx.BITMAP_TYPE_PNG)
  1949. wizbmp = wizbmp.ConvertToBitmap()
  1950. #
  1951. # get georeferencing information from tables in $GISBASE/etc
  1952. #
  1953. self.__readData()
  1954. #
  1955. # datum transform number and list of datum transforms
  1956. #
  1957. self.datum_trans = None
  1958. self.proj4string = ''
  1959. # file from which new location is created
  1960. self.georeffile = None
  1961. # additional settings
  1962. self.default_region = False
  1963. self.user_mapset = False
  1964. #
  1965. # define wizard pages
  1966. #
  1967. self.wizard = WizardWithHelpButton(
  1968. parent,
  1969. id=wx.ID_ANY,
  1970. title=_("Define new GRASS Location"),
  1971. bitmap=wizbmp)
  1972. self.wizard.Bind(wiz.EVT_WIZARD_HELP, self.OnHelp)
  1973. self.startpage = DatabasePage(self.wizard, self, grassdatabase)
  1974. self.csystemspage = CoordinateSystemPage(self.wizard, self)
  1975. self.projpage = ProjectionsPage(self.wizard, self)
  1976. self.datumpage = DatumPage(self.wizard, self)
  1977. self.paramspage = ProjParamsPage(self.wizard, self)
  1978. self.epsgpage = EPSGPage(self.wizard, self)
  1979. self.iaupage = IAUPage(self.wizard, self)
  1980. self.filepage = GeoreferencedFilePage(self.wizard, self)
  1981. self.wktpage = WKTPage(self.wizard, self)
  1982. self.ellipsepage = EllipsePage(self.wizard, self)
  1983. self.custompage = CustomPage(self.wizard, self)
  1984. self.sumpage = SummaryPage(self.wizard, self)
  1985. #
  1986. # set the initial order of the pages
  1987. # (should follow the epsg line)
  1988. #
  1989. self.startpage.SetNext(self.csystemspage)
  1990. self.csystemspage.SetPrev(self.startpage)
  1991. self.csystemspage.SetNext(self.sumpage)
  1992. self.projpage.SetPrev(self.csystemspage)
  1993. self.projpage.SetNext(self.paramspage)
  1994. self.paramspage.SetPrev(self.projpage)
  1995. self.paramspage.SetNext(self.datumpage)
  1996. self.datumpage.SetPrev(self.paramspage)
  1997. self.datumpage.SetNext(self.sumpage)
  1998. self.ellipsepage.SetPrev(self.paramspage)
  1999. self.ellipsepage.SetNext(self.sumpage)
  2000. self.epsgpage.SetPrev(self.csystemspage)
  2001. self.epsgpage.SetNext(self.sumpage)
  2002. self.iaupage.SetPrev(self.csystemspage)
  2003. self.iaupage.SetNext(self.sumpage)
  2004. self.filepage.SetPrev(self.csystemspage)
  2005. self.filepage.SetNext(self.sumpage)
  2006. self.wktpage.SetPrev(self.csystemspage)
  2007. self.wktpage.SetNext(self.sumpage)
  2008. self.custompage.SetPrev(self.csystemspage)
  2009. self.custompage.SetNext(self.sumpage)
  2010. self.sumpage.SetPrev(self.csystemspage)
  2011. #
  2012. # do pages layout
  2013. #
  2014. self.startpage.DoLayout()
  2015. self.csystemspage.DoLayout()
  2016. self.projpage.DoLayout()
  2017. self.datumpage.DoLayout()
  2018. self.paramspage.DoLayout()
  2019. self.epsgpage.DoLayout()
  2020. self.iaupage.DoLayout()
  2021. self.filepage.DoLayout()
  2022. self.wktpage.DoLayout()
  2023. self.ellipsepage.DoLayout()
  2024. self.custompage.DoLayout()
  2025. self.sumpage.DoLayout()
  2026. self.wizard.FitToPage(self.datumpage)
  2027. size = self.wizard.GetPageSize()
  2028. self.wizard.SetPageSize((size[0], size[1] + 75))
  2029. # new location created?
  2030. self.location = None
  2031. success = False
  2032. # location created in different GIS database?
  2033. self.altdb = False
  2034. #
  2035. # run wizard...
  2036. #
  2037. if self.wizard.RunWizard(self.startpage):
  2038. msg = self.OnWizFinished()
  2039. if not msg:
  2040. self.wizard.Destroy()
  2041. self.location = self.startpage.location
  2042. self.grassdatabase = self.startpage.grassdatabase
  2043. self.georeffile = self.filepage.georeffile
  2044. self.default_region = self.startpage.tlocRegion.IsChecked()
  2045. self.user_mapset = self.startpage.tlocUserMapset.IsChecked()
  2046. # FIXME here was code for setting default region, what for is this if:
  2047. # if self.altdb == False:
  2048. else: # -> error
  2049. self.wizard.Destroy()
  2050. GError(parent=self.parent,
  2051. message="%s" % _("Unable to create new location. "
  2052. "Location <%(loc)s> not created.\n\n"
  2053. "Details: %(err)s") %
  2054. {'loc': self.startpage.location,
  2055. 'err': msg})
  2056. else: # -> canceled
  2057. self.wizard.Destroy()
  2058. GMessage(parent=self.parent,
  2059. message=_("Location wizard canceled. "
  2060. "Location not created."))
  2061. self.__cleanUp()
  2062. def __cleanUp(self):
  2063. global coordsys
  2064. global north
  2065. global south
  2066. global east
  2067. global west
  2068. global resolution
  2069. global wizerror
  2070. global translist
  2071. coordsys = None
  2072. north = None
  2073. south = None
  2074. east = None
  2075. west = None
  2076. resolution = None
  2077. transformlist = list()
  2078. def __readData(self):
  2079. """Get georeferencing information from tables in $GISBASE/etc/proj"""
  2080. # read projection and parameters
  2081. f = open(os.path.join(globalvar.ETCDIR, "proj", "parms.table"), "r")
  2082. self.projections = {}
  2083. self.projdesc = {}
  2084. for line in f.readlines():
  2085. line = line.strip()
  2086. try:
  2087. proj, projdesc, params = line.split(':')
  2088. paramslist = params.split(';')
  2089. plist = []
  2090. for p in paramslist:
  2091. if p == '':
  2092. continue
  2093. p1, pdefault = p.split(',')
  2094. pterm, pask = p1.split('=')
  2095. p = [pterm.strip(), pask.strip(), pdefault.strip()]
  2096. plist.append(p)
  2097. self.projections[
  2098. proj.lower().strip()] = (
  2099. projdesc.strip(), plist)
  2100. self.projdesc[proj.lower().strip()] = projdesc.strip()
  2101. except:
  2102. continue
  2103. f.close()
  2104. # read datum definitions
  2105. f = open(os.path.join(globalvar.ETCDIR, "proj", "datum.table"), "r")
  2106. self.datums = {}
  2107. paramslist = []
  2108. for line in f.readlines():
  2109. line = line.expandtabs(1)
  2110. line = line.strip()
  2111. if line == '' or line[0] == "#":
  2112. continue
  2113. datum, info = line.split(" ", 1)
  2114. info = info.strip()
  2115. datumdesc, params = info.split(" ", 1)
  2116. datumdesc = datumdesc.strip('"')
  2117. paramlist = params.split()
  2118. ellipsoid = paramlist.pop(0)
  2119. self.datums[datum] = (
  2120. ellipsoid, datumdesc.replace(
  2121. '_', ' '), paramlist)
  2122. f.close()
  2123. # read Earth-based ellipsiod definitions
  2124. f = open(os.path.join(globalvar.ETCDIR, "proj", "ellipse.table"), "r")
  2125. self.ellipsoids = {}
  2126. for line in f.readlines():
  2127. line = line.expandtabs(1)
  2128. line = line.strip()
  2129. if line == '' or line[0] == "#":
  2130. continue
  2131. ellipse, rest = line.split(" ", 1)
  2132. rest = rest.strip('" ')
  2133. desc, params = rest.split('"', 1)
  2134. desc = desc.strip('" ')
  2135. paramslist = params.split()
  2136. self.ellipsoids[ellipse] = (desc, paramslist)
  2137. f.close()
  2138. # read Planetary ellipsiod definitions
  2139. f = open(
  2140. os.path.join(
  2141. globalvar.ETCDIR,
  2142. "proj",
  2143. "ellipse.table.solar.system"),
  2144. "r")
  2145. self.planetary_ellipsoids = {}
  2146. for line in f.readlines():
  2147. line = line.expandtabs(1)
  2148. line = line.strip()
  2149. if line == '' or line[0] == "#":
  2150. continue
  2151. ellipse, rest = line.split(" ", 1)
  2152. rest = rest.strip('" ')
  2153. desc, params = rest.split('"', 1)
  2154. desc = desc.strip('" ')
  2155. paramslist = params.split()
  2156. self.planetary_ellipsoids[ellipse] = (desc, paramslist)
  2157. f.close()
  2158. # read projection parameter description and parsing table
  2159. f = open(os.path.join(globalvar.ETCDIR, "proj", "desc.table"), "r")
  2160. self.paramdesc = {}
  2161. for line in f.readlines():
  2162. line = line.strip()
  2163. try:
  2164. pparam, datatype, proj4term, desc = line.split(':')
  2165. self.paramdesc[pparam] = (datatype, proj4term, desc)
  2166. except:
  2167. continue
  2168. f.close()
  2169. def OnWizFinished(self):
  2170. """Wizard finished, create new location
  2171. :return: error message on error
  2172. :return: None on success
  2173. """
  2174. database = self.startpage.grassdatabase
  2175. location = self.startpage.location
  2176. # location already exists?
  2177. if os.path.isdir(os.path.join(database, location)):
  2178. GError(parent=self.wizard,
  2179. message="%s <%s>: %s" %
  2180. (_("Unable to create new location"),
  2181. os.path.join(database, location),
  2182. _("Location already exists in GRASS Database.")))
  2183. return None
  2184. # current GISDbase or a new one?
  2185. current_gdb = decode(grass.gisenv()['GISDBASE'])
  2186. if current_gdb != database:
  2187. # change to new GISDbase or create new one
  2188. if not os.path.isdir(database):
  2189. # create new directory
  2190. try:
  2191. os.mkdir(database)
  2192. except OSError as error:
  2193. GError(parent=self.wizard, message="%s <%s>" %
  2194. (_("Unable to create new GRASS Database"),
  2195. database))
  2196. return None
  2197. # change to new GISDbase directory
  2198. RunCommand('g.gisenv',
  2199. parent=self.wizard,
  2200. set='GISDBASE=%s' % database)
  2201. wx.MessageBox(
  2202. parent=self.wizard,
  2203. message=_(
  2204. "Location <%(loc)s> will be created "
  2205. "in GIS data directory <%(dir)s>. "
  2206. "You will need to change the default GIS "
  2207. "data directory in the GRASS startup screen.") %
  2208. {'loc': location, 'dir': database},
  2209. caption=_("New GIS data directory"),
  2210. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  2211. # location created in alternate GISDbase
  2212. self.altdb = True
  2213. global coordsys
  2214. try:
  2215. if coordsys == "xy":
  2216. grass.create_location(dbase=self.startpage.grassdatabase,
  2217. location=self.startpage.location,
  2218. desc=self.startpage.locTitle)
  2219. elif coordsys == "proj":
  2220. grass.create_location(dbase=self.startpage.grassdatabase,
  2221. location=self.startpage.location,
  2222. proj4=self.CreateProj4String(),
  2223. datum=self.datumpage.datum,
  2224. datum_trans=self.datum_trans,
  2225. desc=self.startpage.locTitle)
  2226. elif coordsys == 'custom':
  2227. addl_opts = {}
  2228. if self.datum_trans is not None:
  2229. addl_opts['datum_trans'] = self.datum_trans
  2230. grass.create_location(dbase=self.startpage.grassdatabase,
  2231. location=self.startpage.location,
  2232. proj4=self.custompage.customstring,
  2233. desc=self.startpage.locTitle,
  2234. **addl_opts)
  2235. elif coordsys == "epsg":
  2236. if not self.epsgpage.epsgcode:
  2237. return _('EPSG code missing.')
  2238. grass.create_location(dbase=self.startpage.grassdatabase,
  2239. location=self.startpage.location,
  2240. epsg=self.epsgpage.epsgcode,
  2241. datum=self.datumpage.datum,
  2242. datum_trans=self.datum_trans,
  2243. desc=self.startpage.locTitle)
  2244. elif coordsys == "iau":
  2245. if not self.iaupage.epsgcode:
  2246. return _('IAU code missing.')
  2247. grass.create_location(dbase=self.startpage.grassdatabase,
  2248. location=self.startpage.location,
  2249. proj4=self.iaupage.epsgparams,
  2250. datum=self.datumpage.datum,
  2251. datum_trans=self.datum_trans,
  2252. desc=self.startpage.locTitle)
  2253. elif coordsys == "file":
  2254. if not self.filepage.georeffile or \
  2255. not os.path.isfile(self.filepage.georeffile):
  2256. return _("File <%s> not found." % self.filepage.georeffile)
  2257. grass.create_location(dbase=self.startpage.grassdatabase,
  2258. location=self.startpage.location,
  2259. filename=self.filepage.georeffile,
  2260. desc=self.startpage.locTitle)
  2261. elif coordsys == "wkt":
  2262. if not self.wktpage.wktfile or \
  2263. not os.path.isfile(self.wktpage.wktfile):
  2264. return _("File <%s> not found." % self.wktpage.wktfile)
  2265. grass.create_location(dbase=self.startpage.grassdatabase,
  2266. location=self.startpage.location,
  2267. wkt=self.wktpage.wktfile,
  2268. desc=self.startpage.locTitle)
  2269. except grass.ScriptError as e:
  2270. return e.value
  2271. return None
  2272. def CreateProj4String(self):
  2273. """Constract PROJ.4 string"""
  2274. location = self.startpage.location
  2275. proj = self.projpage.p4proj
  2276. projdesc = self.projpage.projdesc
  2277. proj4params = self.paramspage.p4projparams
  2278. # datum = self.datumpage.datum
  2279. if self.datumpage.datumdesc:
  2280. datumdesc = self.datumpage.datumdesc + ' - ' + self.datumpage.ellipse
  2281. else:
  2282. datumdesc = ''
  2283. datumparams = self.datumpage.datumparams
  2284. ellipse = self.ellipsepage.ellipse
  2285. ellipsedesc = self.ellipsepage.ellipsedesc
  2286. ellipseparams = self.ellipsepage.ellipseparams
  2287. #
  2288. # creating PROJ.4 string
  2289. #
  2290. proj4string = '%s %s' % (proj, proj4params)
  2291. # set ellipsoid parameters
  2292. if ellipse != '':
  2293. proj4string = '%s +ellps=%s' % (proj4string, ellipse)
  2294. for item in ellipseparams:
  2295. if item[:4] == 'f=1/':
  2296. item = ' +rf=' + item[4:]
  2297. else:
  2298. item = ' +' + item
  2299. proj4string = '%s %s' % (proj4string, item)
  2300. # set datum transform parameters if relevant
  2301. if datumparams:
  2302. for item in datumparams:
  2303. proj4string = '%s +%s' % (proj4string, item)
  2304. proj4string = '%s +no_defs' % proj4string
  2305. return proj4string
  2306. def OnHelp(self, event):
  2307. """'Help' button clicked"""
  2308. # help text in lib/init/helptext.html
  2309. RunCommand('g.manual', entry='helptext')
  2310. class WizardWithHelpButton(Wizard):
  2311. def __init__(self, parent, id, title, bitmap):
  2312. if globalvar.wxPythonPhoenix:
  2313. Wizard.__init__(self)
  2314. self.SetExtraStyle(wx.adv.WIZARD_EX_HELPBUTTON)
  2315. self.Create(parent=parent, id=id, title=title, bitmap=bitmap)
  2316. else:
  2317. pre = wiz.PreWizard()
  2318. pre.SetExtraStyle(wx.wizard.WIZARD_EX_HELPBUTTON)
  2319. pre.Create(parent=parent, id=id, title=title, bitmap=bitmap)
  2320. self.PostCreate(pre)