guiutils.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. """
  2. @package startup.guiutils
  3. @brief General GUI-dependent utilities for GUI startup of GRASS GIS
  4. (C) 2018 by Vaclav Petras the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. @author Vaclav Petras <wenzeslaus gmail com>
  8. @author Linda Kladivova <l.kladivova@seznam.cz>
  9. This is for code which depend on something from GUI (wx or wxGUI).
  10. """
  11. import os
  12. import sys
  13. import wx
  14. import grass.script as gs
  15. from grass.script import gisenv
  16. from grass.grassdb.checks import mapset_exists, location_exists
  17. from grass.grassdb.create import create_mapset, get_default_mapset_name
  18. from grass.grassdb.manage import (
  19. delete_mapset,
  20. delete_location,
  21. delete_grassdb,
  22. rename_mapset,
  23. rename_location,
  24. )
  25. from core import globalvar
  26. from core.gcmd import GError, GMessage, DecodeString, RunCommand
  27. from gui_core.dialogs import TextEntryDialog
  28. from location_wizard.dialogs import RegionDef
  29. from gui_core.widgets import GenericMultiValidator
  30. def SetSessionMapset(database, location, mapset):
  31. """Sets database, location and mapset for the current session"""
  32. RunCommand("g.gisenv", set="GISDBASE=%s" % database)
  33. RunCommand("g.gisenv", set="LOCATION_NAME=%s" % location)
  34. RunCommand("g.gisenv", set="MAPSET=%s" % mapset)
  35. class MapsetDialog(TextEntryDialog):
  36. def __init__(self, parent=None, default=None, message=None, caption=None,
  37. database=None, location=None):
  38. self.database = database
  39. self.location = location
  40. # list of tuples consisting of conditions and callbacks
  41. checks = [(gs.legal_name, self._nameValidationFailed),
  42. (self._checkMapsetNotExists, self._mapsetAlreadyExists),
  43. (self._checkOGR, self._reservedMapsetName)]
  44. validator = GenericMultiValidator(checks)
  45. TextEntryDialog.__init__(
  46. self, parent=parent,
  47. message=message,
  48. caption=caption,
  49. defaultValue=default,
  50. validator=validator,
  51. )
  52. def _nameValidationFailed(self, ctrl):
  53. message = _(
  54. "Name '{}' is not a valid name for location or mapset. "
  55. "Please use only ASCII characters excluding characters {} "
  56. "and space.").format(ctrl.GetValue(), '/"\'@,=*~')
  57. GError(parent=self, message=message, caption=_("Invalid name"))
  58. def _checkOGR(self, text):
  59. """Check user's input for reserved mapset name."""
  60. if text.lower() == 'ogr':
  61. return False
  62. return True
  63. def _reservedMapsetName(self, ctrl):
  64. message = _(
  65. "Name '{}' is reserved for direct "
  66. "read access to OGR layers. Please use "
  67. "another name for your mapset.").format(ctrl.GetValue())
  68. GError(parent=self, message=message,
  69. caption=_("Reserved mapset name"))
  70. def _checkMapsetNotExists(self, text):
  71. """Check whether user's input mapset exists or not."""
  72. if mapset_exists(self.database, self.location, text):
  73. return False
  74. return True
  75. def _mapsetAlreadyExists(self, ctrl):
  76. message = _(
  77. "Mapset '{}' already exists. Please consider using "
  78. "another name for your mapset.").format(ctrl.GetValue())
  79. GError(parent=self, message=message,
  80. caption=_("Existing mapset path"))
  81. class LocationDialog(TextEntryDialog):
  82. def __init__(self, parent=None, default=None, message=None, caption=None,
  83. database=None):
  84. self.database = database
  85. # list of tuples consisting of conditions and callbacks
  86. checks = [(gs.legal_name, self._nameValidationFailed),
  87. (self._checkLocationNotExists, self._locationAlreadyExists)]
  88. validator = GenericMultiValidator(checks)
  89. TextEntryDialog.__init__(
  90. self, parent=parent,
  91. message=message,
  92. caption=caption,
  93. defaultValue=default,
  94. validator=validator,
  95. )
  96. def _nameValidationFailed(self, ctrl):
  97. message = _(
  98. "Name '{}' is not a valid name for location or mapset. "
  99. "Please use only ASCII characters excluding characters {} "
  100. "and space.").format(ctrl.GetValue(), '/"\'@,=*~')
  101. GError(parent=self, message=message, caption=_("Invalid name"))
  102. def _checkLocationNotExists(self, text):
  103. """Check whether user's input location exists or not."""
  104. if location_exists(self.database, text):
  105. return False
  106. return True
  107. def _locationAlreadyExists(self, ctrl):
  108. message = _(
  109. "Location '{}' already exists. Please consider using "
  110. "another name for your location.").format(ctrl.GetValue())
  111. GError(parent=self, message=message,
  112. caption=_("Existing location path"))
  113. # TODO: similar to (but not the same as) read_gisrc function in grass.py
  114. def read_gisrc():
  115. """Read variables from a current GISRC file
  116. Returns a dictionary representation of the file content.
  117. """
  118. grassrc = {}
  119. gisrc = os.getenv("GISRC")
  120. if gisrc and os.path.isfile(gisrc):
  121. try:
  122. rc = open(gisrc, "r")
  123. for line in rc.readlines():
  124. try:
  125. key, val = line.split(":", 1)
  126. except ValueError as e:
  127. sys.stderr.write(
  128. _('Invalid line in GISRC file (%s):%s\n' % (e, line)))
  129. grassrc[key.strip()] = DecodeString(val.strip())
  130. finally:
  131. rc.close()
  132. return grassrc
  133. def GetVersion():
  134. """Gets version and revision
  135. Returns tuple `(version, revision)`. For standard releases revision
  136. is an empty string.
  137. Revision string is currently wrapped in parentheses with added
  138. leading space. This is an implementation detail and legacy and may
  139. change anytime.
  140. """
  141. versionFile = open(os.path.join(globalvar.ETCDIR, "VERSIONNUMBER"))
  142. versionLine = versionFile.readline().rstrip('\n')
  143. versionFile.close()
  144. try:
  145. grassVersion, grassRevision = versionLine.split(' ', 1)
  146. if grassVersion.endswith('dev'):
  147. grassRevisionStr = ' (%s)' % grassRevision
  148. else:
  149. grassRevisionStr = ''
  150. except ValueError:
  151. grassVersion = versionLine
  152. grassRevisionStr = ''
  153. return (grassVersion, grassRevisionStr)
  154. def create_mapset_interactively(guiparent, grassdb, location):
  155. """
  156. Create new mapset
  157. """
  158. dlg = MapsetDialog(
  159. parent=guiparent,
  160. default=get_default_mapset_name(),
  161. message=_("Name for the new mapset:"),
  162. caption=_("Create new mapset"),
  163. database=grassdb,
  164. location=location,
  165. )
  166. mapset = None
  167. if dlg.ShowModal() == wx.ID_OK:
  168. mapset = dlg.GetValue()
  169. try:
  170. create_mapset(grassdb, location, mapset)
  171. except OSError as err:
  172. mapset = None
  173. GError(
  174. parent=guiparent,
  175. message=_("Unable to create new mapset: {}").format(err),
  176. showTraceback=False,
  177. )
  178. dlg.Destroy()
  179. return mapset
  180. def create_location_interactively(guiparent, grassdb):
  181. """
  182. Create new location using Location Wizard.
  183. Returns tuple (database, location, mapset) where mapset is "PERMANENT"
  184. by default or another mapset a user created and may want to switch to.
  185. """
  186. from location_wizard.wizard import LocationWizard
  187. gWizard = LocationWizard(parent=guiparent,
  188. grassdatabase=grassdb)
  189. if gWizard.location is None:
  190. gWizard_output = (None, None, None)
  191. # Returns Nones after Cancel
  192. return gWizard_output
  193. if gWizard.georeffile:
  194. message = _(
  195. "Do you want to import {}"
  196. "to the newly created location?"
  197. ).format(gWizard.georeffile)
  198. dlg = wx.MessageDialog(parent=guiparent,
  199. message=message,
  200. caption=_("Import data?"),
  201. style=wx.YES_NO | wx.YES_DEFAULT |
  202. wx.ICON_QUESTION)
  203. dlg.CenterOnParent()
  204. if dlg.ShowModal() == wx.ID_YES:
  205. import_file(guiparent, gWizard.georeffile)
  206. dlg.Destroy()
  207. if gWizard.default_region:
  208. defineRegion = RegionDef(guiparent, location=gWizard.location)
  209. defineRegion.CenterOnParent()
  210. defineRegion.ShowModal()
  211. defineRegion.Destroy()
  212. if gWizard.user_mapset:
  213. mapset = create_mapset_interactively(guiparent,
  214. gWizard.grassdatabase,
  215. gWizard.location)
  216. # Returns database and location created by user
  217. # and a mapset user may want to switch to
  218. gWizard_output = (gWizard.grassdatabase, gWizard.location,
  219. mapset)
  220. else:
  221. # Returns PERMANENT mapset when user mapset not defined
  222. gWizard_output = (gWizard.grassdatabase, gWizard.location,
  223. "PERMANENT")
  224. return gWizard_output
  225. def rename_mapset_interactively(guiparent, grassdb, location, mapset):
  226. """Rename mapset with user interaction.
  227. If PERMANENT or current mapset found, rename operation is not performed.
  228. Exceptions during renaming are handled in this function.
  229. Returns newmapset if there was a change or None if the mapset cannot be
  230. renamed (see above the possible reasons) or if another error was encountered.
  231. """
  232. genv = gisenv()
  233. # Check selected mapset and remember issue.
  234. # Each error is reported only once (using elif).
  235. mapset_path = os.path.join(grassdb, location, mapset)
  236. newmapset = None
  237. issue = None
  238. # Check for permanent mapsets
  239. if mapset == "PERMANENT":
  240. issue = _("<{}> is required for a valid location.").format(mapset_path)
  241. # Check for current mapset
  242. elif (
  243. grassdb == genv['GISDBASE'] and
  244. location == genv['LOCATION_NAME'] and
  245. mapset == genv['MAPSET']
  246. ):
  247. issue = _("<{}> is the current mapset.").format(mapset_path)
  248. # If an issue, display the warning message and do not rename mapset
  249. if issue:
  250. dlg = wx.MessageDialog(
  251. parent=guiparent,
  252. message=_(
  253. "Cannot rename selected mapset for the following reason:\n\n"
  254. "{}\n\n"
  255. "No mapset will be renamed."
  256. ).format(issue),
  257. caption=_("Unable to rename selected mapset"),
  258. style=wx.OK | wx.ICON_WARNING
  259. )
  260. dlg.ShowModal()
  261. else:
  262. dlg = MapsetDialog(
  263. parent=guiparent,
  264. default=mapset,
  265. message=_("Current name: {}\n\nEnter new name:").format(mapset),
  266. caption=_("Rename selected mapset"),
  267. database=grassdb,
  268. location=location,
  269. )
  270. if dlg.ShowModal() == wx.ID_OK:
  271. newmapset = dlg.GetValue()
  272. try:
  273. rename_mapset(grassdb, location, mapset, newmapset)
  274. except OSError as err:
  275. newmapset = None
  276. wx.MessageBox(
  277. parent=guiparent,
  278. caption=_("Error"),
  279. message=_("Unable to rename mapset.\n\n{}").format(err),
  280. style=wx.OK | wx.ICON_ERROR | wx.CENTRE,
  281. )
  282. dlg.Destroy()
  283. return newmapset
  284. def rename_location_interactively(guiparent, grassdb, location):
  285. """Rename location with user interaction.
  286. If current location found, rename operation is not performed.
  287. Exceptions during renaming are handled in this function.
  288. Returns newlocation if there was a change or None if the location cannot be
  289. renamed (see above the possible reasons) or if another error was encountered.
  290. """
  291. genv = gisenv()
  292. # Check selected location and remember issue.
  293. # Each error is reported only once (using elif).
  294. location_path = os.path.join(grassdb, location)
  295. newlocation = None
  296. issue = None
  297. # Check for current location
  298. if (
  299. grassdb == genv['GISDBASE'] and
  300. location == genv['LOCATION_NAME']
  301. ):
  302. issue = _("<{}> is the current location.").format(location_path)
  303. # If an issue, display the warning message and do not rename location
  304. if issue:
  305. dlg = wx.MessageDialog(
  306. parent=guiparent,
  307. message=_(
  308. "Cannot rename selected location for the following reason:\n\n"
  309. "{}\n\n"
  310. "No location will be renamed."
  311. ).format(issue),
  312. caption=_("Unable to rename selected location"),
  313. style=wx.OK | wx.ICON_WARNING
  314. )
  315. dlg.ShowModal()
  316. else:
  317. dlg = LocationDialog(
  318. parent=guiparent,
  319. default=location,
  320. message=_("Current name: {}\n\nEnter new name:").format(location),
  321. caption=_("Rename selected location"),
  322. database=grassdb,
  323. )
  324. if dlg.ShowModal() == wx.ID_OK:
  325. newlocation = dlg.GetValue()
  326. try:
  327. rename_location(grassdb, location, newlocation)
  328. except OSError as err:
  329. newlocation = None
  330. wx.MessageBox(
  331. parent=guiparent,
  332. caption=_("Error"),
  333. message=_("Unable to rename location.\n\n{}").format(err),
  334. style=wx.OK | wx.ICON_ERROR | wx.CENTRE,
  335. )
  336. dlg.Destroy()
  337. return newlocation
  338. def download_location_interactively(guiparent, grassdb):
  339. """
  340. Download new location using Location Wizard.
  341. Returns tuple (database, location, mapset) where mapset is "PERMANENT"
  342. by default or in future it could be the mapset the user may want to
  343. switch to.
  344. """
  345. from startup.locdownload import LocationDownloadDialog
  346. result = (None, None, None)
  347. loc_download = LocationDownloadDialog(parent=guiparent,
  348. database=grassdb)
  349. loc_download.Centre()
  350. loc_download.ShowModal()
  351. if loc_download.GetLocation() is not None:
  352. # Returns database and location created by user
  353. # and a mapset user may want to switch to
  354. result = (grassdb, loc_download.GetLocation(), "PERMANENT")
  355. loc_download.Destroy()
  356. return result
  357. def delete_mapset_interactively(guiparent, grassdb, location, mapset):
  358. """Delete one mapset with user interaction.
  359. This is currently just a convenience wrapper for delete_mapsets_interactively().
  360. """
  361. mapsets = [(grassdb, location, mapset)]
  362. return delete_mapsets_interactively(guiparent, mapsets)
  363. def delete_mapsets_interactively(guiparent, mapsets):
  364. """Delete multiple mapsets with user interaction.
  365. Parameter *mapsets* is a list of tuples (database, location, mapset).
  366. If PERMANENT or current mapset found, delete operation is not performed.
  367. Exceptions during deletation are handled in this function.
  368. Returns True if there was a change, i.e., all mapsets were successfuly deleted
  369. or at least one mapset was deleted. Returns False if one or more mapsets cannot be
  370. deleted (see above the possible reasons) or if an error was encountered when
  371. deleting the first mapset in the list.
  372. """
  373. genv = gisenv()
  374. issues = []
  375. deletes = []
  376. # Check selected mapsets and remember issue.
  377. # Each error is reported only once (using elif).
  378. for grassdb, location, mapset in mapsets:
  379. mapset_path = os.path.join(grassdb, location, mapset)
  380. # Check for permanent mapsets
  381. if mapset == "PERMANENT":
  382. issue = _("<{}> is required for a valid location.").format(mapset_path)
  383. issues.append(issue)
  384. # Check for current mapset
  385. elif (
  386. grassdb == genv['GISDBASE'] and
  387. location == genv['LOCATION_NAME'] and
  388. mapset == genv['MAPSET']
  389. ):
  390. issue = _("<{}> is the current mapset.").format(mapset_path)
  391. issues.append(issue)
  392. # No issue detected
  393. else:
  394. deletes.append(mapset_path)
  395. modified = False # True after first successful delete
  396. # If any issues, display the warning message and do not delete anything
  397. if issues:
  398. issues = "\n".join(issues)
  399. dlg = wx.MessageDialog(
  400. parent=guiparent,
  401. message=_(
  402. "Cannot delete one or more mapsets for the following reasons:\n\n"
  403. "{}\n\n"
  404. "No mapsets will be deleted."
  405. ).format(issues),
  406. caption=_("Unable to delete selected mapsets"),
  407. style=wx.OK | wx.ICON_WARNING
  408. )
  409. dlg.ShowModal()
  410. else:
  411. deletes = "\n".join(deletes)
  412. dlg = wx.MessageDialog(
  413. parent=guiparent,
  414. message=_(
  415. "Do you want to continue with deleting"
  416. " one or more of the following mapsets?\n\n"
  417. "{}\n\n"
  418. "All maps included in these mapsets will be permanently deleted!"
  419. ).format(deletes),
  420. caption=_("Delete selected mapsets"),
  421. style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION,
  422. )
  423. if dlg.ShowModal() == wx.ID_YES:
  424. try:
  425. for grassdb, location, mapset in mapsets:
  426. delete_mapset(grassdb, location, mapset)
  427. modified = True
  428. dlg.Destroy()
  429. return modified
  430. except OSError as error:
  431. wx.MessageBox(
  432. parent=guiparent,
  433. caption=_("Error when deleting mapsets"),
  434. message=_(
  435. "The following error occured when deleting mapset <{path}>:"
  436. "\n\n{error}\n\n"
  437. "Deleting of mapsets was interrupted."
  438. ).format(
  439. path=os.path.join(grassdb, location, mapset),
  440. error=error,
  441. ),
  442. style=wx.OK | wx.ICON_ERROR | wx.CENTRE,
  443. )
  444. dlg.Destroy()
  445. return modified
  446. def delete_location_interactively(guiparent, grassdb, location):
  447. """Delete one location with user interaction.
  448. This is currently just a convenience wrapper for delete_locations_interactively().
  449. """
  450. locations = [(grassdb, location)]
  451. return delete_locations_interactively(guiparent, locations)
  452. def delete_locations_interactively(guiparent, locations):
  453. """Delete multiple locations with user interaction.
  454. Parameter *locations* is a list of tuples (database, location).
  455. If current location found, delete operation is not performed.
  456. Exceptions during deletation are handled in this function.
  457. Returns True if there was a change, i.e., all locations were successfuly deleted
  458. or at least one location was deleted. Returns False if one or more locations cannot be
  459. deleted (see above the possible reasons) or if an error was encountered when
  460. deleting the first location in the list.
  461. """
  462. genv = gisenv()
  463. issues = []
  464. deletes = []
  465. # Check selected locations and remember issue.
  466. # Each error is reported only once (using elif).
  467. for grassdb, location in locations:
  468. location_path = os.path.join(grassdb, location)
  469. # Check for current location
  470. if (
  471. grassdb == genv['GISDBASE'] and
  472. location == genv['LOCATION_NAME']
  473. ):
  474. issue = _("<{}> is current location.").format(location_path)
  475. issues.append(issue)
  476. # No issue detected
  477. else:
  478. deletes.append(location_path)
  479. modified = False # True after first successful delete
  480. # If any issues, display the warning message and do not delete anything
  481. if issues:
  482. issues = "\n".join(issues)
  483. dlg = wx.MessageDialog(
  484. parent=guiparent,
  485. message=_(
  486. "Cannot delete one or more locations for the following reasons:\n\n"
  487. "{}\n\n"
  488. "No locations will be deleted."
  489. ).format(issues),
  490. caption=_("Unable to delete selected locations"),
  491. style=wx.OK | wx.ICON_WARNING
  492. )
  493. dlg.ShowModal()
  494. else:
  495. deletes = "\n".join(deletes)
  496. dlg = wx.MessageDialog(
  497. parent=guiparent,
  498. message=_(
  499. "Do you want to continue with deleting"
  500. " one or more of the following locations?\n\n"
  501. "{}\n\n"
  502. "All mapsets included in these locations will be permanently deleted!"
  503. ).format(deletes),
  504. caption=_("Delete selected locations"),
  505. style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION,
  506. )
  507. if dlg.ShowModal() == wx.ID_YES:
  508. try:
  509. for grassdb, location in locations:
  510. delete_location(grassdb, location)
  511. modified = True
  512. dlg.Destroy()
  513. return modified
  514. except OSError as error:
  515. wx.MessageBox(
  516. parent=guiparent,
  517. caption=_("Error when deleting locations"),
  518. message=_(
  519. "The following error occured when deleting location <{path}>:"
  520. "\n\n{error}\n\n"
  521. "Deleting locations was interrupted."
  522. ).format(
  523. path=os.path.join(grassdb, location),
  524. error=error,
  525. ),
  526. style=wx.OK | wx.ICON_ERROR | wx.CENTRE,
  527. )
  528. dlg.Destroy()
  529. return modified
  530. def delete_grassdb_interactively(guiparent, grassdb):
  531. """
  532. Delete grass database if could be deleted.
  533. If current grass database found, desired operation cannot be performed.
  534. Exceptions during deleting are handled in this function.
  535. Returns True if grass database is deleted from the disk. Returns None if
  536. cannot be deleted (see above the possible reasons).
  537. """
  538. genv = gisenv()
  539. issue = None
  540. deleted = False
  541. # Check for current grassdb
  542. if (grassdb == genv['GISDBASE']):
  543. issue = _("<{}> is current GRASS database.").format(grassdb)
  544. if issue:
  545. dlg = wx.MessageDialog(
  546. parent=guiparent,
  547. message=_(
  548. "Cannot delete GRASS database from disk for the following reason:\n\n"
  549. "{}\n\n"
  550. "GRASS database will not be deleted."
  551. ).format(issue),
  552. caption=_("Unable to delete selected GRASS database"),
  553. style=wx.OK | wx.ICON_WARNING
  554. )
  555. dlg.ShowModal()
  556. else:
  557. dlg = wx.MessageDialog(
  558. parent=guiparent,
  559. message=_(
  560. "Do you want to delete"
  561. " the following GRASS database from disk?\n\n"
  562. "{}\n\n"
  563. "The directory will be permanently deleted!"
  564. ).format(grassdb),
  565. caption=_("Delete selected GRASS database"),
  566. style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION,
  567. )
  568. if dlg.ShowModal() == wx.ID_YES:
  569. try:
  570. delete_grassdb(grassdb)
  571. deleted = True
  572. dlg.Destroy()
  573. return deleted
  574. except OSError as error:
  575. wx.MessageBox(
  576. parent=guiparent,
  577. caption=_("Error when deleting GRASS database"),
  578. message=_(
  579. "The following error occured when deleting database <{path}>:"
  580. "\n\n{error}\n\n"
  581. "Deleting of GRASS database was interrupted."
  582. ).format(
  583. path=grassdb,
  584. error=error,
  585. ),
  586. style=wx.OK | wx.ICON_ERROR | wx.CENTRE,
  587. )
  588. dlg.Destroy()
  589. return deleted
  590. def import_file(guiparent, filePath):
  591. """Tries to import file as vector or raster.
  592. If successfull sets default region from imported map.
  593. """
  594. RunCommand('db.connect', flags='c')
  595. mapName = os.path.splitext(os.path.basename(filePath))[0]
  596. vectors = RunCommand('v.in.ogr', input=filePath, flags='l',
  597. read=True)
  598. wx.BeginBusyCursor()
  599. wx.GetApp().Yield()
  600. if vectors:
  601. # vector detected
  602. returncode, error = RunCommand(
  603. 'v.in.ogr', input=filePath, output=mapName, flags='e',
  604. getErrorMsg=True)
  605. else:
  606. returncode, error = RunCommand(
  607. 'r.in.gdal', input=filePath, output=mapName, flags='e',
  608. getErrorMsg=True)
  609. wx.EndBusyCursor()
  610. if returncode != 0:
  611. GError(
  612. parent=guiparent,
  613. message=_(
  614. "Import of <%(name)s> failed.\n"
  615. "Reason: %(msg)s") % ({
  616. 'name': filePath,
  617. 'msg': error}))
  618. else:
  619. GMessage(
  620. message=_(
  621. "Data file <%(name)s> imported successfully. "
  622. "The location's default region was set from "
  623. "this imported map.") % {
  624. 'name': filePath},
  625. parent=guiparent)