guiutils.py 26 KB

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