wizard.py 97 KB

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