dialogs.py 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273
  1. """!
  2. @package gui_core.dialogs
  3. @brief Various dialogs used in wxGUI.
  4. List of classes:
  5. - dialogs::SimpleDialog
  6. - dialogs::LocationDialog
  7. - dialogs::MapsetDialog
  8. - dialogs::NewVectorDialog
  9. - dialogs::SavedRegion
  10. - dialogs::GroupDialog
  11. - dialogs::MapLayersDialog
  12. - dialogs::ImportDialog
  13. - dialogs::GdalImportDialog
  14. - dialogs::GdalOutputDialog
  15. - dialogs::DxfImportDialog
  16. - dialogs::LayersList (used by MultiImport)
  17. - dialogs::SetOpacityDialog
  18. - dialogs::ImageSizeDialog
  19. - dialogs::SqlQueryFrame
  20. - dialogs::SymbolDialog
  21. (C) 2008-2011 by the GRASS Development Team
  22. This program is free software under the GNU General Public License
  23. (>=v2). Read the file COPYING that comes with GRASS for details.
  24. @author Martin Landa <landa.martin gmail.com>
  25. @author Anna Kratochvilova <kratochanna gmail.com> (GroupDialog, SymbolDialog)
  26. """
  27. import os
  28. import sys
  29. import re
  30. from bisect import bisect
  31. import wx
  32. import wx.lib.filebrowsebutton as filebrowse
  33. import wx.lib.mixins.listctrl as listmix
  34. from grass.script import core as grass
  35. from grass.script import task as gtask
  36. from grass.pydispatch.signal import Signal
  37. from core import globalvar
  38. from core.gcmd import GError, RunCommand, GMessage
  39. from gui_core.gselect import LocationSelect, MapsetSelect, Select, OgrTypeSelect, GdalSelect, MapsetSelect
  40. from gui_core.widgets import SingleSymbolPanel, GListCtrl, SimpleValidator
  41. from core.utils import GetValidLayerName, _
  42. from core.settings import UserSettings, GetDisplayVectSettings
  43. from core.debug import Debug
  44. class SimpleDialog(wx.Dialog):
  45. def __init__(self, parent, title, id = wx.ID_ANY,
  46. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  47. **kwargs):
  48. """!General dialog to choose given element (location, mapset, vector map, etc.)
  49. @param parent window
  50. @param title window title
  51. """
  52. wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
  53. self.SetExtraStyle(wx.WS_EX_VALIDATE_RECURSIVELY)
  54. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  55. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  56. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  57. self.btnOK.SetDefault()
  58. self.__layout()
  59. self.warning = _("Required item is not set.")
  60. def __layout(self):
  61. """!Do layout"""
  62. self.sizer = wx.BoxSizer(wx.VERTICAL)
  63. self.dataSizer = wx.BoxSizer(wx.VERTICAL)
  64. # self.informLabel = wx.StaticText(self.panel, id = wx.ID_ANY)
  65. # buttons
  66. btnSizer = wx.StdDialogButtonSizer()
  67. btnSizer.AddButton(self.btnCancel)
  68. btnSizer.AddButton(self.btnOK)
  69. btnSizer.Realize()
  70. self.sizer.Add(item = self.dataSizer, proportion = 1,
  71. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  72. # self.sizer.Add(item = self.informLabel, proportion = 0, flag = wx.ALL, border = 5)
  73. self.sizer.Add(item = btnSizer, proportion = 0,
  74. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  75. def ValidatorCallback(self, win):
  76. GMessage(parent = self, message = self.warning)
  77. # self.informLabel.SetForegroundColour(wx.Colour(255, 0, 0))
  78. # self.informLabel.SetLabel(self.warning)
  79. class LocationDialog(SimpleDialog):
  80. """!Dialog used to select location"""
  81. def __init__(self, parent, title = _("Select GRASS location and mapset")):
  82. SimpleDialog.__init__(self, parent, title)
  83. self.element1 = LocationSelect(parent = self.panel, id = wx.ID_ANY,
  84. size = globalvar.DIALOG_GSELECT_SIZE,
  85. validator = SimpleValidator(callback = self.ValidatorCallback))
  86. self.element1.Bind(wx.EVT_TEXT, self.OnLocation)
  87. self.element2 = MapsetSelect(parent = self.panel, id = wx.ID_ANY,
  88. size = globalvar.DIALOG_GSELECT_SIZE,
  89. setItems = False, skipCurrent = True,
  90. validator = SimpleValidator(callback = self.ValidatorCallback))
  91. self.element1.SetFocus()
  92. self.warning = _("Location or mapset is missing.")
  93. self._layout()
  94. self.SetMinSize(self.GetSize())
  95. def _layout(self):
  96. """!Do layout"""
  97. self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  98. label = _("Name of GRASS location:")),
  99. proportion = 0, flag = wx.ALL, border = 1)
  100. self.dataSizer.Add(self.element1, proportion = 0,
  101. flag = wx.EXPAND | wx.ALL, border = 1)
  102. self.dataSizer.Add(wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  103. label = _("Name of mapset:")), proportion = 0,
  104. flag = wx.EXPAND | wx.ALL, border = 1)
  105. self.dataSizer.Add(self.element2, proportion = 0,
  106. flag = wx.EXPAND | wx.ALL, border = 1)
  107. self.panel.SetSizer(self.sizer)
  108. self.sizer.Fit(self)
  109. def OnLocation(self, event):
  110. """!Select mapset given location name"""
  111. location = event.GetString()
  112. if location:
  113. dbase = grass.gisenv()['GISDBASE']
  114. self.element2.UpdateItems(dbase = dbase, location = location)
  115. self.element2.SetSelection(0)
  116. mapset = self.element2.GetStringSelection()
  117. def GetValues(self):
  118. """!Get location, mapset"""
  119. return (self.element1.GetValue(), self.element2.GetValue())
  120. class MapsetDialog(SimpleDialog):
  121. """!Dialog used to select mapset"""
  122. def __init__(self, parent, title = _("Select mapset in GRASS location"),
  123. location = None):
  124. SimpleDialog.__init__(self, parent, title)
  125. if location:
  126. self.SetTitle(self.GetTitle() + ' <%s>' % location)
  127. else:
  128. self.SetTitle(self.GetTitle() + ' <%s>' % grass.gisenv()['LOCATION_NAME'])
  129. self.element = MapsetSelect(parent = self.panel, id = wx.ID_ANY, skipCurrent = True,
  130. size = globalvar.DIALOG_GSELECT_SIZE,
  131. validator = SimpleValidator(callback = self.ValidatorCallback))
  132. self.element.SetFocus()
  133. self.warning = _("Name of mapset is missing.")
  134. self._layout()
  135. self.SetMinSize(self.GetSize())
  136. def _layout(self):
  137. """!Do layout"""
  138. self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  139. label = _("Name of mapset:")),
  140. proportion = 0, flag = wx.ALL, border = 1)
  141. self.dataSizer.Add(self.element, proportion = 0,
  142. flag = wx.EXPAND | wx.ALL, border = 1)
  143. self.panel.SetSizer(self.sizer)
  144. self.sizer.Fit(self)
  145. def GetMapset(self):
  146. return self.element.GetValue()
  147. class NewVectorDialog(SimpleDialog):
  148. def __init__(self, parent, title = _("Create new vector map"),
  149. disableAdd = False, disableTable = False, showType = False):
  150. """!Dialog for creating new vector map
  151. @param parent parent window
  152. @param title window title
  153. @param disableAdd disable 'add layer' checkbox
  154. @param disableTable disable 'create table' checkbox
  155. @param showType True to show feature type selector (used for creating new empty OGR layers)
  156. @return dialog instance
  157. """
  158. SimpleDialog.__init__(self, parent, title)
  159. self.element = Select(parent = self.panel, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  160. type = 'vector', mapsets = [grass.gisenv()['MAPSET'],],
  161. validator = SimpleValidator(callback = self.ValidatorCallback))
  162. self.element.SetFocus()
  163. # determine output format
  164. if showType:
  165. self.ftype = OgrTypeSelect(parent = self, panel = self.panel)
  166. else:
  167. self.ftype = None
  168. self.table = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  169. label = _("Create attribute table"))
  170. self.table.SetValue(True)
  171. if disableTable:
  172. self.table.Enable(False)
  173. if showType:
  174. self.keycol = None
  175. else:
  176. self.keycol = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  177. size = globalvar.DIALOG_SPIN_SIZE)
  178. self.keycol.SetValue(UserSettings.Get(group = 'atm', key = 'keycolumn', subkey = 'value'))
  179. if disableTable:
  180. self.keycol.Enable(False)
  181. self.addbox = wx.CheckBox(parent = self.panel,
  182. label = _('Add created map into layer tree'), style = wx.NO_BORDER)
  183. if disableAdd:
  184. self.addbox.SetValue(True)
  185. self.addbox.Enable(False)
  186. else:
  187. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  188. self.table.Bind(wx.EVT_CHECKBOX, self.OnTable)
  189. self.warning = _("Name of new vector map is missing.")
  190. self._layout()
  191. self.SetMinSize(self.GetSize())
  192. def OnTable(self, event):
  193. if self.keycol:
  194. self.keycol.Enable(event.IsChecked())
  195. def _layout(self):
  196. """!Do layout"""
  197. self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  198. label = _("Name for new vector map:")),
  199. proportion = 0, flag = wx.ALL, border = 1)
  200. self.dataSizer.Add(item = self.element, proportion = 0,
  201. flag = wx.EXPAND | wx.ALL, border = 1)
  202. if self.ftype:
  203. self.dataSizer.AddSpacer(1)
  204. self.dataSizer.Add(item = self.ftype, proportion = 0,
  205. flag = wx.EXPAND | wx.ALL, border = 1)
  206. self.dataSizer.Add(item = self.table, proportion = 0,
  207. flag = wx.EXPAND | wx.ALL, border = 1)
  208. if self.keycol:
  209. keySizer = wx.BoxSizer(wx.HORIZONTAL)
  210. keySizer.Add(item = wx.StaticText(parent = self.panel, label = _("Key column:")),
  211. proportion = 0,
  212. flag = wx.ALIGN_CENTER_VERTICAL)
  213. keySizer.AddSpacer(10)
  214. keySizer.Add(item = self.keycol, proportion = 0,
  215. flag = wx.ALIGN_RIGHT)
  216. self.dataSizer.Add(item = keySizer, proportion = 1,
  217. flag = wx.EXPAND | wx.ALL, border = 1)
  218. self.dataSizer.AddSpacer(5)
  219. self.dataSizer.Add(item = self.addbox, proportion = 0,
  220. flag = wx.EXPAND | wx.ALL, border = 1)
  221. self.panel.SetSizer(self.sizer)
  222. self.sizer.Fit(self)
  223. def GetName(self, full = False):
  224. """!Get name of vector map to be created
  225. @param full True to get fully qualified name
  226. """
  227. name = self.element.GetValue()
  228. if full:
  229. if '@' in name:
  230. return name
  231. else:
  232. return name + '@' + grass.gisenv()['MAPSET']
  233. return name.split('@', 1)[0]
  234. def GetKey(self):
  235. """!Get key column name"""
  236. if self.keycol:
  237. return self.keycol.GetValue()
  238. return UserSettings.Get(group = 'atm', key = 'keycolumn', subkey = 'value')
  239. def IsChecked(self, key):
  240. """!Get dialog properties
  241. @param key window key ('add', 'table')
  242. @return True/False
  243. @return None on error
  244. """
  245. if key == 'add':
  246. return self.addbox.IsChecked()
  247. elif key == 'table':
  248. return self.table.IsChecked()
  249. return None
  250. def GetFeatureType(self):
  251. """!Get feature type for OGR
  252. @return feature type as string
  253. @return None for native format
  254. """
  255. if self.ftype:
  256. return self.ftype.GetType()
  257. return None
  258. def CreateNewVector(parent, cmd, title = _('Create new vector map'),
  259. exceptMap=None, giface=None,
  260. disableAdd = False, disableTable = False):
  261. """!Create new vector map layer
  262. @param cmd (prog, **kwargs)
  263. @param title window title
  264. @param exceptMap list of maps to be excepted
  265. @param log
  266. @param disableAdd disable 'add layer' checkbox
  267. @param disableTable disable 'create table' checkbox
  268. @return dialog instance
  269. @return None on error
  270. """
  271. vExternalOut = grass.parse_command('v.external.out', flags = 'g')
  272. isNative = vExternalOut['format'] == 'native'
  273. if cmd[0] == 'v.edit' and not isNative:
  274. showType = True
  275. else:
  276. showType = False
  277. dlg = NewVectorDialog(parent, title = title,
  278. disableAdd = disableAdd, disableTable = disableTable,
  279. showType = showType)
  280. if dlg.ShowModal() != wx.ID_OK:
  281. dlg.Destroy()
  282. return None
  283. outmap = dlg.GetName()
  284. key = dlg.GetKey()
  285. if outmap == exceptMap:
  286. GError(parent = parent,
  287. message = _("Unable to create vector map <%s>.") % outmap)
  288. dlg.Destroy()
  289. return None
  290. if dlg.table.IsEnabled() and not key:
  291. GError(parent = parent,
  292. message = _("Invalid or empty key column.\n"
  293. "Unable to create vector map <%s>.") % outmap)
  294. dlg.Destroy()
  295. return
  296. if outmap == '': # should not happen
  297. dlg.Destroy()
  298. return None
  299. # update cmd -> output name defined
  300. cmd[1][cmd[2]] = outmap
  301. if showType:
  302. cmd[1]['type'] = dlg.GetFeatureType()
  303. if isNative:
  304. listOfVectors = grass.list_grouped('vect')[grass.gisenv()['MAPSET']]
  305. else:
  306. listOfVectors = RunCommand('v.external',
  307. quiet = True,
  308. parent = parent,
  309. read = True,
  310. flags = 'l',
  311. dsn = vExternalOut['dsn']).splitlines()
  312. overwrite = False
  313. if not UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
  314. outmap in listOfVectors:
  315. dlgOw = wx.MessageDialog(parent, message = _("Vector map <%s> already exists "
  316. "in the current mapset. "
  317. "Do you want to overwrite it?") % outmap,
  318. caption = _("Overwrite?"),
  319. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  320. if dlgOw.ShowModal() == wx.ID_YES:
  321. overwrite = True
  322. else:
  323. dlgOw.Destroy()
  324. dlg.Destroy()
  325. return None
  326. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  327. overwrite = True
  328. ret = RunCommand(prog = cmd[0],
  329. parent = parent,
  330. overwrite = overwrite,
  331. **cmd[1])
  332. if ret != 0:
  333. dlg.Destroy()
  334. return None
  335. if not isNative:
  336. # create link for OGR layers
  337. RunCommand('v.external',
  338. overwrite = overwrite,
  339. parent = parent,
  340. dsn = vExternalOut['dsn'],
  341. layer = outmap)
  342. # create attribute table
  343. if dlg.table.IsEnabled() and dlg.table.IsChecked():
  344. if isNative:
  345. sql = 'CREATE TABLE %s (%s INTEGER)' % (outmap, key)
  346. RunCommand('db.connect',
  347. flags = 'c')
  348. Debug.msg(1, "SQL: %s" % sql)
  349. RunCommand('db.execute',
  350. quiet = True,
  351. parent = parent,
  352. input = '-',
  353. stdin = sql)
  354. RunCommand('v.db.connect',
  355. quiet = True,
  356. parent = parent,
  357. map = outmap,
  358. table = outmap,
  359. key = key,
  360. layer = '1')
  361. # TODO: how to deal with attribute tables for OGR layers?
  362. # return fully qualified map name
  363. if '@' not in outmap:
  364. outmap += '@' + grass.gisenv()['MAPSET']
  365. if giface:
  366. giface.WriteLog(_("New vector map <%s> created") % outmap)
  367. return dlg
  368. class SavedRegion(wx.Dialog):
  369. def __init__(self, parent, title, id = wx.ID_ANY, loadsave = 'load',
  370. **kwargs):
  371. """!Loading or saving of display extents to saved region file
  372. @param loadsave load or save region?
  373. """
  374. wx.Dialog.__init__(self, parent, id, title, **kwargs)
  375. self.loadsave = loadsave
  376. self.wind = ''
  377. sizer = wx.BoxSizer(wx.VERTICAL)
  378. box = wx.BoxSizer(wx.HORIZONTAL)
  379. label = wx.StaticText(parent = self, id = wx.ID_ANY)
  380. box.Add(item = label, proportion = 0, flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  381. if loadsave == 'load':
  382. label.SetLabel(_("Load region:"))
  383. selection = Select(parent = self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  384. type = 'windows')
  385. elif loadsave == 'save':
  386. label.SetLabel(_("Save region:"))
  387. selection = Select(parent = self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  388. type = 'windows', mapsets = [grass.gisenv()['MAPSET']], fullyQualified = False)
  389. box.Add(item = selection, proportion = 0, flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  390. selection.SetFocus()
  391. selection.Bind(wx.EVT_TEXT, self.OnRegion)
  392. sizer.Add(item = box, proportion = 0, flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  393. border = 5)
  394. line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL)
  395. sizer.Add(item = line, proportion = 0,
  396. flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border = 5)
  397. btnsizer = wx.StdDialogButtonSizer()
  398. btn = wx.Button(parent = self, id = wx.ID_OK)
  399. btn.SetDefault()
  400. btnsizer.AddButton(btn)
  401. btn = wx.Button(parent = self, id = wx.ID_CANCEL)
  402. btnsizer.AddButton(btn)
  403. btnsizer.Realize()
  404. sizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
  405. self.SetSizer(sizer)
  406. sizer.Fit(self)
  407. self.Layout()
  408. def OnRegion(self, event):
  409. self.wind = event.GetString()
  410. def GetName(self):
  411. """!Return region name"""
  412. return self.wind
  413. class GroupDialog(wx.Dialog):
  414. """!Dialog for creating/editing groups"""
  415. def __init__(self, parent = None, defaultGroup = None,
  416. title = _("Create or edit imagery groups"),
  417. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  418. wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
  419. style = style, **kwargs)
  420. self.parent = parent
  421. self.defaultGroup = defaultGroup
  422. self.currentGroup = self.defaultGroup
  423. self.groupChanged = False
  424. self.bodySizer = self._createDialogBody()
  425. # buttons
  426. btnOk = wx.Button(parent = self, id = wx.ID_OK)
  427. btnApply = wx.Button(parent = self, id = wx.ID_APPLY)
  428. btnClose = wx.Button(parent = self, id = wx.ID_CANCEL)
  429. btnOk.SetToolTipString(_("Apply changes to selected group and close dialog"))
  430. btnApply.SetToolTipString(_("Apply changes to selected group"))
  431. btnClose.SetToolTipString(_("Close dialog, changes are not applied"))
  432. btnOk.SetDefault()
  433. # sizers & do layout
  434. # btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  435. # btnSizer.Add(item = btnClose, proportion = 0,
  436. # flag = wx.RIGHT | wx.ALIGN_RIGHT | wx.EXPAND, border = 5)
  437. # btnSizer.Add(item = btnApply, proportion = 0,
  438. # flag = wx.LEFT, border = 5)
  439. btnSizer = wx.StdDialogButtonSizer()
  440. btnSizer.AddButton(btnOk)
  441. btnSizer.AddButton(btnApply)
  442. btnSizer.AddButton(btnClose)
  443. btnSizer.Realize()
  444. mainSizer = wx.BoxSizer(wx.VERTICAL)
  445. mainSizer.Add(item = self.bodySizer, proportion = 1,
  446. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 10)
  447. mainSizer.Add(item = wx.StaticLine(parent = self, id = wx.ID_ANY,
  448. style = wx.LI_HORIZONTAL), proportion = 0,
  449. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 10)
  450. mainSizer.Add(item = btnSizer, proportion = 0,
  451. flag = wx.ALL | wx.ALIGN_RIGHT, border = 10)
  452. self.SetSizer(mainSizer)
  453. mainSizer.Fit(self)
  454. btnOk.Bind(wx.EVT_BUTTON, self.OnOk)
  455. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  456. btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
  457. # set dialog min size
  458. self.SetMinSize(self.GetSize())
  459. def _createDialogBody(self):
  460. bodySizer = wx.BoxSizer(wx.VERTICAL)
  461. # group selection
  462. bodySizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  463. label = _("Select the group you want to edit or "
  464. "enter name of new group:")),
  465. flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP, border = 10)
  466. self.groupSelect = Select(parent = self, type = 'group',
  467. mapsets = [grass.gisenv()['MAPSET']],
  468. size = globalvar.DIALOG_GSELECT_SIZE,
  469. fullyQualified = False) # searchpath?
  470. bodySizer.Add(item = self.groupSelect, flag = wx.TOP | wx.EXPAND, border = 5)
  471. bodySizer.AddSpacer(10)
  472. # layers in group
  473. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Raster maps in selected group:")),
  474. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM, border = 5)
  475. buttonSizer = wx.BoxSizer(wx.VERTICAL)
  476. listSizer = wx.BoxSizer(wx.HORIZONTAL)
  477. self.layerBox = wx.ListBox(parent = self, id = wx.ID_ANY, size = (-1, 150),
  478. style = wx.LB_MULTIPLE | wx.LB_NEEDED_SB)
  479. listSizer.Add(item = self.layerBox, proportion = 1, flag = wx.EXPAND)
  480. self.addLayer = wx.Button(self, id = wx.ID_ADD)
  481. self.addLayer.SetToolTipString(_("Select map layers and add them to the list."))
  482. buttonSizer.Add(item = self.addLayer, flag = wx.BOTTOM, border = 10)
  483. self.removeLayer = wx.Button(self, id = wx.ID_REMOVE)
  484. self.removeLayer.SetToolTipString(_("Remove selected layer(s) from list."))
  485. buttonSizer.Add(item = self.removeLayer)
  486. listSizer.Add(item = buttonSizer, flag = wx.LEFT, border = 5)
  487. bodySizer.Add(item = listSizer, proportion = 1, flag = wx.EXPAND)
  488. self.infoLabel = wx.StaticText(parent = self, id = wx.ID_ANY)
  489. bodySizer.Add(item = self.infoLabel,
  490. flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.BOTTOM, border = 5)
  491. # TODO: subgroup can have a different name than the group
  492. # self.subGroup must be a text field, not a checkbox
  493. #self.subGroup = wx.CheckBox(parent = self, id = wx.ID_ANY,
  494. # label = _("Define also sub-group (same name as group)"))
  495. #self.subGroup.SetValue(True) # most of imagery modules requires also subgroup
  496. #bodySizer.Add(item = self.subGroup, flag = wx.BOTTOM | wx.EXPAND, border = 5)
  497. # bindings
  498. self.groupSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnGroupSelected)
  499. self.addLayer.Bind(wx.EVT_BUTTON, self.OnAddLayer)
  500. self.removeLayer.Bind(wx.EVT_BUTTON, self.OnRemoveLayer)
  501. if self.defaultGroup:
  502. self.groupSelect.SetValue(self.defaultGroup)
  503. return bodySizer
  504. def OnAddLayer(self, event):
  505. """!Add new layer to listbox"""
  506. dlg = MapLayersDialogForGroups(parent = self, title = _("Add selected map layers into group"))
  507. if dlg.ShowModal() != wx.ID_OK:
  508. dlg.Destroy()
  509. return
  510. layers = dlg.GetMapLayers()
  511. for layer in layers:
  512. if layer not in self.GetLayers():
  513. self.layerBox.Append(layer)
  514. self.groupChanged = True
  515. def OnRemoveLayer(self, event):
  516. """!Remove layer from listbox"""
  517. while self.layerBox.GetSelections():
  518. sel = self.layerBox.GetSelections()[0]
  519. self.layerBox.Delete(sel)
  520. self.groupChanged = True
  521. def GetLayers(self):
  522. """!Get layers"""
  523. return self.layerBox.GetItems()
  524. def OnGroupSelected(self, event):
  525. """!Text changed in group selector"""
  526. # callAfter must be called to close popup before other actions
  527. wx.CallAfter(self.GroupSelected)
  528. def GroupSelected(self):
  529. """!Group was selected, check if changes were apllied"""
  530. group = self.GetSelectedGroup()
  531. if self.currentGroup and self.groupChanged:
  532. dlg = wx.MessageDialog(self, message = _("Group <%s> was changed, "
  533. "do you want to apply changes?") % self.currentGroup,
  534. caption = _("Unapplied changes"),
  535. style = wx.YES_NO | wx.ICON_QUESTION | wx.YES_DEFAULT)
  536. if dlg.ShowModal() == wx.ID_YES:
  537. self.ApplyChanges()
  538. dlg.Destroy()
  539. maps = list()
  540. groups = self.GetExistGroups()
  541. if group in groups:
  542. maps = self.GetGroupLayers(group)
  543. self.ShowGroupLayers(maps)
  544. self.currentGroup = group
  545. self.groupChanged = False
  546. self.ClearNotification()
  547. def ShowGroupLayers(self, mapList):
  548. """!Show map layers in currently selected group"""
  549. self.layerBox.Set(mapList)
  550. def EditGroup(self, group):
  551. """!Edit selected group"""
  552. layersNew = self.GetLayers()
  553. layersOld = self.GetGroupLayers(group)
  554. add = []
  555. remove = []
  556. for layerNew in layersNew:
  557. if layerNew not in layersOld:
  558. add.append(layerNew)
  559. for layerOld in layersOld:
  560. if layerOld not in layersNew:
  561. remove.append(layerOld)
  562. kwargs = {}
  563. # TODO: self.subGroup must be a text field
  564. #if self.subGroup.IsChecked():
  565. # kwargs['subgroup'] = group
  566. ret = None
  567. if remove:
  568. ret = RunCommand('i.group',
  569. parent = self,
  570. group = group,
  571. flags = 'r',
  572. input = ','.join(remove),
  573. **kwargs)
  574. if add:
  575. ret = RunCommand('i.group',
  576. parent = self,
  577. group = group,
  578. input = ','.join(add),
  579. **kwargs)
  580. return ret
  581. def CreateNewGroup(self, group):
  582. """!Create new group"""
  583. layers = self.GetLayers()
  584. if not layers:
  585. GMessage(parent = self,
  586. message = _("No raster maps selected."))
  587. return 1
  588. kwargs = {}
  589. # TODO: self.subGroup must be a text field
  590. #if self.subGroup.IsChecked():
  591. # kwargs['subgroup'] = group
  592. return RunCommand('i.group',
  593. parent = self,
  594. group = group,
  595. input = layers,
  596. **kwargs)
  597. def GetExistGroups(self):
  598. """!Returns existing groups in current mapset"""
  599. return grass.list_grouped('group')[grass.gisenv()['MAPSET']]
  600. def ShowResult(self, group, returnCode, create):
  601. """!Show if operation was successfull."""
  602. group += '@' + grass.gisenv()['MAPSET']
  603. if returnCode is None:
  604. label = _("No changes to apply in group <%s>.") % group
  605. elif returnCode == 0:
  606. if create:
  607. label = _("Group <%s> was successfully created.") % group
  608. else:
  609. label = _("Group <%s> was successfully changed.") % group
  610. else:
  611. if create:
  612. label = _("Creating of new group <%s> failed.") % group
  613. else:
  614. label = _("Changing of group <%s> failed.") % group
  615. self.infoLabel.SetLabel(label)
  616. wx.FutureCall(4000, self.ClearNotification)
  617. def GetSelectedGroup(self):
  618. """!Return currently selected group (without mapset)"""
  619. return self.groupSelect.GetValue().split('@')[0]
  620. def GetGroupLayers(self, group):
  621. """!Get layers in group"""
  622. kwargs = dict()
  623. kwargs['group'] = group
  624. # TODO: self.subGroup must be a text field
  625. #if self.subGroup.IsChecked():
  626. # kwargs['subgroup'] = group
  627. res = RunCommand('i.group',
  628. parent = self,
  629. flags = 'g',
  630. read = True, **kwargs)
  631. if not res:
  632. return []
  633. return res.splitlines()
  634. def ClearNotification(self):
  635. """!Clear notification string"""
  636. self.infoLabel.SetLabel("")
  637. def ApplyChanges(self):
  638. """!Create or edit group"""
  639. group = self.currentGroup
  640. if not group:
  641. GMessage(parent = self,
  642. message = _("No group selected."))
  643. return False
  644. groups = self.GetExistGroups()
  645. if group in groups:
  646. ret = self.EditGroup(group)
  647. self.ShowResult(group = group, returnCode = ret, create = False)
  648. else:
  649. ret = self.CreateNewGroup(group)
  650. self.ShowResult(group = group, returnCode = ret, create = True)
  651. self.groupChanged = False
  652. return True
  653. def OnApply(self, event):
  654. """!Apply changes"""
  655. self.ApplyChanges()
  656. def OnOk(self, event):
  657. """!Apply changes and close dialog"""
  658. if self.ApplyChanges():
  659. self.OnClose(event)
  660. def OnClose(self, event):
  661. """!Close dialog"""
  662. if not self.IsModal():
  663. self.Destroy()
  664. event.Skip()
  665. class MapLayersDialogBase(wx.Dialog):
  666. """!Base dialog for selecting map layers (raster, vector).
  667. There are 3 subclasses: MapLayersDialogForGroups, MapLayersDialogForModeler,
  668. MapLayersDialog. Base class contains core functionality.
  669. """
  670. def __init__(self, parent, title,
  671. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  672. wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
  673. style = style, **kwargs)
  674. self.parent = parent # GMFrame or ?
  675. self.applyAddingMapLayers = Signal('MapLayersDialogBase.applyAddingMapLayers')
  676. self.mainSizer = wx.BoxSizer(wx.VERTICAL)
  677. # dialog body
  678. self.bodySizer = self._createDialogBody()
  679. self.mainSizer.Add(item = self.bodySizer, proportion = 1,
  680. flag = wx.EXPAND | wx.ALL, border = 5)
  681. # update list of layer to be loaded
  682. self.map_layers = [] # list of map layers (full list type/mapset)
  683. self.LoadMapLayers(self.GetLayerType(cmd = True),
  684. self.mapset.GetStringSelection())
  685. self._fullyQualifiedNames()
  686. self._modelerDSeries()
  687. # buttons
  688. btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  689. btnOk = wx.Button(parent = self, id = wx.ID_OK)
  690. btnOk.SetDefault()
  691. # sizers & do layout
  692. self.btnSizer = wx.StdDialogButtonSizer()
  693. self.btnSizer.AddButton(btnCancel)
  694. self.btnSizer.AddButton(btnOk)
  695. self._addApplyButton()
  696. self.btnSizer.Realize()
  697. self.mainSizer.Add(item = self.btnSizer, proportion = 0,
  698. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  699. self.SetSizer(self.mainSizer)
  700. self.mainSizer.Fit(self)
  701. # set dialog min size
  702. self.SetMinSize(self.GetSize())
  703. def _modelerDSeries(self):
  704. """!Method used only by MapLayersDialogForModeler,
  705. for other subclasses does nothing.
  706. """
  707. pass
  708. def _addApplyButton(self):
  709. """!Method used only by MapLayersDialog,
  710. for other subclasses does nothing.
  711. """
  712. pass
  713. def _fullyQualifiedNames(self):
  714. """!Adds CheckBox which determines is fully qualified names are retuned.
  715. """
  716. self.fullyQualified = wx.CheckBox(parent = self, id = wx.ID_ANY,
  717. label = _("Use fully-qualified map names"))
  718. self.fullyQualified.SetValue(True)
  719. self.mainSizer.Add(item = self.fullyQualified, proportion = 0,
  720. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  721. def _useFullyQualifiedNames(self):
  722. return self.fullyQualified.IsChecked()
  723. def _layerTypes(self):
  724. """!Determines which layer types can be chosen.
  725. Valid values:
  726. - raster
  727. - raster3d
  728. - vector
  729. """
  730. return [_('raster'), _('3D raster'), _('vector')]
  731. def _selectAll(self):
  732. """!Check all layers by default"""
  733. return True
  734. def _createDialogBody(self):
  735. bodySizer = wx.GridBagSizer(vgap = 3, hgap = 3)
  736. # layer type
  737. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Map type:")),
  738. flag = wx.ALIGN_CENTER_VERTICAL,
  739. pos = (0,0))
  740. self.layerType = wx.Choice(parent = self, id = wx.ID_ANY,
  741. choices = self._layerTypes(), size = (100,-1))
  742. self.layerType.SetSelection(0)
  743. bodySizer.Add(item = self.layerType,
  744. pos = (0,1))
  745. self.layerType.Bind(wx.EVT_CHOICE, self.OnChangeParams)
  746. # select toggle
  747. self.toggle = wx.CheckBox(parent = self, id = wx.ID_ANY,
  748. label = _("Select toggle"))
  749. self.toggle.SetValue(self._selectAll())
  750. bodySizer.Add(item = self.toggle,
  751. flag = wx.ALIGN_CENTER_VERTICAL,
  752. pos = (0,2))
  753. # mapset filter
  754. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Mapset:")),
  755. flag = wx.ALIGN_CENTER_VERTICAL,
  756. pos = (1,0))
  757. self.mapset = MapsetSelect(parent = self, searchPath = True)
  758. self.mapset.SetStringSelection(grass.gisenv()['MAPSET'])
  759. bodySizer.Add(item = self.mapset,
  760. pos = (1,1), span = (1, 2))
  761. # map name filter
  762. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Pattern:")),
  763. flag = wx.ALIGN_CENTER_VERTICAL,
  764. pos = (2,0))
  765. self.filter = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  766. value = "",
  767. size = (250,-1))
  768. bodySizer.Add(item = self.filter,
  769. flag = wx.EXPAND,
  770. pos = (2,1), span = (1, 2))
  771. self.filter.SetFocus()
  772. self.filter.SetToolTipString(_("Put here a regular expression."
  773. " Characters '.*' stand for anything,"
  774. " character '^' stands for the beginning"
  775. " and '$' for the end."))
  776. # layer list
  777. bodySizer.Add(item = wx.StaticText(parent = self, label = _("List of maps:")),
  778. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_TOP,
  779. pos = (3,0))
  780. self.layers = wx.CheckListBox(parent = self, id = wx.ID_ANY,
  781. size = (250, 100),
  782. choices = [])
  783. bodySizer.Add(item = self.layers,
  784. flag = wx.EXPAND,
  785. pos = (3,1), span = (1, 2))
  786. bodySizer.AddGrowableCol(1)
  787. bodySizer.AddGrowableRow(3)
  788. # bindings
  789. self.mapset.Bind(wx.EVT_COMBOBOX, self.OnChangeParams)
  790. self.layers.Bind(wx.EVT_RIGHT_DOWN, self.OnMenu)
  791. self.filter.Bind(wx.EVT_TEXT, self.OnFilter)
  792. self.toggle.Bind(wx.EVT_CHECKBOX, self.OnToggle)
  793. return bodySizer
  794. def LoadMapLayers(self, type, mapset):
  795. """!Load list of map layers
  796. @param type layer type ('raster' or 'vector')
  797. @param mapset mapset name
  798. """
  799. self.map_layers = grass.mlist_grouped(type = type)[mapset]
  800. self.layers.Set(self.map_layers)
  801. # check all items by default
  802. for item in range(self.layers.GetCount()):
  803. self.layers.Check(item, check = self._selectAll())
  804. def OnChangeParams(self, event):
  805. """!Filter parameters changed by user"""
  806. # update list of layer to be loaded
  807. self.LoadMapLayers(self.GetLayerType(cmd = True),
  808. self.mapset.GetStringSelection())
  809. event.Skip()
  810. def OnMenu(self, event):
  811. """!Table description area, context menu"""
  812. if not hasattr(self, "popupID1"):
  813. self.popupDataID1 = wx.NewId()
  814. self.popupDataID2 = wx.NewId()
  815. self.popupDataID3 = wx.NewId()
  816. self.Bind(wx.EVT_MENU, self.OnSelectAll, id = self.popupDataID1)
  817. self.Bind(wx.EVT_MENU, self.OnSelectInvert, id = self.popupDataID2)
  818. self.Bind(wx.EVT_MENU, self.OnDeselectAll, id = self.popupDataID3)
  819. # generate popup-menu
  820. menu = wx.Menu()
  821. menu.Append(self.popupDataID1, _("Select all"))
  822. menu.Append(self.popupDataID2, _("Invert selection"))
  823. menu.Append(self.popupDataID3, _("Deselect all"))
  824. self.PopupMenu(menu)
  825. menu.Destroy()
  826. def OnSelectAll(self, event):
  827. """!Select all map layer from list"""
  828. for item in range(self.layers.GetCount()):
  829. self.layers.Check(item, True)
  830. def OnSelectInvert(self, event):
  831. """!Invert current selection"""
  832. for item in range(self.layers.GetCount()):
  833. if self.layers.IsChecked(item):
  834. self.layers.Check(item, False)
  835. else:
  836. self.layers.Check(item, True)
  837. def OnDeselectAll(self, event):
  838. """!Select all map layer from list"""
  839. for item in range(self.layers.GetCount()):
  840. self.layers.Check(item, False)
  841. def OnFilter(self, event):
  842. """!Apply filter for map names"""
  843. if len(event.GetString()) == 0:
  844. self.layers.Set(self.map_layers)
  845. return
  846. list = []
  847. for layer in self.map_layers:
  848. try:
  849. if re.compile(event.GetString()).search(layer):
  850. list.append(layer)
  851. except:
  852. pass
  853. self.layers.Set(list)
  854. self.OnSelectAll(None)
  855. event.Skip()
  856. def OnToggle(self, event):
  857. """!Select toggle (check or uncheck all layers)"""
  858. check = event.Checked()
  859. for item in range(self.layers.GetCount()):
  860. self.layers.Check(item, check)
  861. event.Skip()
  862. def GetMapLayers(self):
  863. """!Return list of checked map layers"""
  864. layerNames = []
  865. for indx in self.layers.GetSelections():
  866. # layers.append(self.layers.GetStringSelec(indx))
  867. pass
  868. mapset = self.mapset.GetStringSelection()
  869. for item in range(self.layers.GetCount()):
  870. if not self.layers.IsChecked(item):
  871. continue
  872. if self._useFullyQualifiedNames():
  873. layerNames.append(self.layers.GetString(item) + '@' + mapset)
  874. else:
  875. layerNames.append(self.layers.GetString(item))
  876. return layerNames
  877. def GetLayerType(self, cmd = False):
  878. """!Get selected layer type
  879. @param cmd True for g.mlist
  880. """
  881. if not cmd:
  882. return self.layerType.GetStringSelection()
  883. sel = self.layerType.GetSelection()
  884. if sel == 0:
  885. ltype = 'rast'
  886. elif sel == 1:
  887. ltype = 'rast3d'
  888. else:
  889. ltype = 'vect'
  890. return ltype
  891. class MapLayersDialog(MapLayersDialogBase):
  892. """!Subclass of MapLayersDialogBase used in Layer Manager.
  893. Contains apply button, which sends wxApplyMapLayers event.
  894. """
  895. def __init__(self, parent, title, **kwargs):
  896. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  897. def _addApplyButton(self):
  898. btnApply = wx.Button(parent = self, id = wx.ID_APPLY)
  899. self.btnSizer.AddButton(btnApply)
  900. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  901. def OnApply(self, event):
  902. self.applyAddingMapLayers.emit(mapLayers = self.GetMapLayers(),
  903. ltype = self.GetLayerType(cmd = True))
  904. class MapLayersDialogForGroups(MapLayersDialogBase):
  905. """!Subclass of MapLayersDialogBase used for specyfying maps in an imagery group.
  906. Shows only raster maps.
  907. """
  908. def __init__(self, parent, title, **kwargs):
  909. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  910. def _layerTypes(self):
  911. return [_('raster'),]
  912. def _selectAll(self):
  913. """!Could be overriden"""
  914. return False
  915. def _fullyQualifiedNames(self):
  916. pass
  917. def _useFullyQualifiedNames(self):
  918. return True
  919. class MapLayersDialogForModeler(MapLayersDialogBase):
  920. """!Subclass of MapLayersDialogBase used in Modeler.
  921. """
  922. def __init__(self, parent, title, **kwargs):
  923. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  924. def _modelerDSeries(self):
  925. self.dseries = wx.CheckBox(parent = self, id = wx.ID_ANY,
  926. label = _("Dynamic series (%s)") % 'g.mlist')
  927. self.dseries.SetValue(False)
  928. self.mainSizer.Add(item = self.dseries, proportion = 0,
  929. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  930. def GetDSeries(self):
  931. """!Used by modeler only
  932. @return g.mlist command
  933. """
  934. if not self.dseries or not self.dseries.IsChecked():
  935. return ''
  936. cond = 'map in `g.mlist type=%s ' % self.GetLayerType(cmd = True)
  937. patt = self.filter.GetValue()
  938. if patt:
  939. cond += 'pattern=%s ' % patt
  940. cond += 'mapset=%s`' % self.mapset.GetStringSelection()
  941. return cond
  942. class ImportDialog(wx.Dialog):
  943. """!Dialog for bulk import of various data (base class)"""
  944. def __init__(self, parent, giface, itype,
  945. id = wx.ID_ANY, title = _("Multiple import"),
  946. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  947. self.parent = parent # GMFrame
  948. self._giface = giface # used to add layers
  949. self.importType = itype
  950. self.options = dict() # list of options
  951. self.commandId = -1 # id of running command
  952. wx.Dialog.__init__(self, parent, id, title, style = style,
  953. name = "MultiImportDialog")
  954. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  955. self.layerBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY)
  956. if self.importType == 'gdal':
  957. label = _("List of raster layers")
  958. elif self.importType == 'ogr':
  959. label = _("List of vector layers")
  960. else:
  961. label = _("List of %s layers") % self.importType.upper()
  962. self.layerBox.SetLabel(" %s - %s " % (label, _("right click to (un)select all")))
  963. # list of layers
  964. columns = [_('Layer id'),
  965. _('Layer name'),
  966. _('Name for output GRASS map (editable)')]
  967. if itype == 'ogr':
  968. columns.insert(2, _('Feature type'))
  969. columns.insert(3, _('Projection match'))
  970. self.list = LayersList(parent = self.panel, columns = columns)
  971. self.list.LoadData()
  972. self.optionBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  973. label = "%s" % _("Options"))
  974. cmd = self._getCommand()
  975. task = gtask.parse_interface(cmd)
  976. for f in task.get_options()['flags']:
  977. name = f.get('name', '')
  978. desc = f.get('label', '')
  979. if not desc:
  980. desc = f.get('description', '')
  981. if not name and not desc:
  982. continue
  983. if cmd == 'r.in.gdal' and name not in ('o', 'e', 'l', 'k'):
  984. continue
  985. elif cmd == 'r.external' and name not in ('o', 'e', 'r', 'h', 'v'):
  986. continue
  987. elif cmd == 'v.in.ogr' and name not in ('c', 'z', 't', 'o', 'r', 'e', 'w'):
  988. continue
  989. elif cmd == 'v.external' and name not in ('b'):
  990. continue
  991. elif cmd == 'v.in.dxf' and name not in ('e', 't', 'b', 'f', 'i'):
  992. continue
  993. self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  994. label = desc)
  995. self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  996. label = _("Allow output files to overwrite existing files"))
  997. self.overwrite.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  998. self.add = wx.CheckBox(parent = self.panel, id = wx.ID_ANY)
  999. self.closeOnFinish = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1000. label = _("Close dialog on finish"))
  1001. self.closeOnFinish.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  1002. #
  1003. # buttons
  1004. #
  1005. # cancel
  1006. self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  1007. self.btn_close.SetToolTipString(_("Close dialog"))
  1008. self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
  1009. # run
  1010. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Import"))
  1011. self.btn_run.SetToolTipString(_("Import selected layers"))
  1012. self.btn_run.SetDefault()
  1013. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  1014. def doLayout(self):
  1015. """!Do layout"""
  1016. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1017. # dsn input
  1018. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1019. flag = wx.EXPAND)
  1020. #
  1021. # list of DXF layers
  1022. #
  1023. layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)
  1024. layerSizer.Add(item = self.list, proportion = 1,
  1025. flag = wx.ALL | wx.EXPAND, border = 5)
  1026. dialogSizer.Add(item = layerSizer, proportion = 1,
  1027. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1028. # options
  1029. optionSizer = wx.StaticBoxSizer(self.optionBox, wx.VERTICAL)
  1030. for key in self.options.keys():
  1031. optionSizer.Add(item = self.options[key], proportion = 0)
  1032. dialogSizer.Add(item = optionSizer, proportion = 0,
  1033. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1034. dialogSizer.Add(item = self.overwrite, proportion = 0,
  1035. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1036. dialogSizer.Add(item = self.add, proportion = 0,
  1037. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1038. dialogSizer.Add(item = self.closeOnFinish, proportion = 0,
  1039. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1040. #
  1041. # buttons
  1042. #
  1043. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1044. btnsizer.Add(item = self.btn_close, proportion = 0,
  1045. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1046. border = 10)
  1047. btnsizer.Add(item = self.btn_run, proportion = 0,
  1048. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1049. border = 10)
  1050. dialogSizer.Add(item = btnsizer, proportion = 0,
  1051. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.ALIGN_RIGHT,
  1052. border = 10)
  1053. # dialogSizer.SetSizeHints(self.panel)
  1054. self.panel.SetAutoLayout(True)
  1055. self.panel.SetSizer(dialogSizer)
  1056. dialogSizer.Fit(self.panel)
  1057. # auto-layout seems not work here - FIXME
  1058. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, 550)
  1059. self.SetMinSize(size)
  1060. self.SetSize((size.width, size.height + 100))
  1061. # width = self.GetSize()[0]
  1062. # self.list.SetColumnWidth(col = 1, width = width / 2 - 50)
  1063. self.Layout()
  1064. def _getCommand(self):
  1065. """!Get command"""
  1066. return ''
  1067. def OnClose(self, event = None):
  1068. """!Close dialog"""
  1069. self.Close()
  1070. def OnRun(self, event):
  1071. """!Import/Link data (each layes as separate vector map)"""
  1072. pass
  1073. def AddLayers(self, returncode, cmd = None):
  1074. """!Add imported/linked layers into layer tree"""
  1075. if not self.add.IsChecked() or returncode != 0:
  1076. return
  1077. # TODO: if importing map creates more map the folowing does not work
  1078. # * do nothing if map does not exist or
  1079. # * try to determine names using regexp or
  1080. # * persuade import tools to report map names
  1081. self.commandId += 1
  1082. layer, output = self.list.GetLayers()[self.commandId]
  1083. if '@' not in output:
  1084. name = output + '@' + grass.gisenv()['MAPSET']
  1085. else:
  1086. name = output
  1087. # add imported layers into layer tree
  1088. # an alternative would be emit signal (mapCreated) and (optionally)
  1089. # connect to this signal
  1090. llist = self._giface.GetLayerList()
  1091. if self.importType == 'gdal':
  1092. cmd = ['d.rast',
  1093. 'map=%s' % name]
  1094. if UserSettings.Get(group = 'rasterLayer', key = 'opaque', subkey = 'enabled'):
  1095. cmd.append('-n')
  1096. llist.AddLayer(ltype='raster',
  1097. name=name, checked=False,
  1098. cmd=cmd)
  1099. else:
  1100. llist.AddLayer(ltype='vector',
  1101. name=name, checked=False,
  1102. cmd=['d.vect',
  1103. 'map=%s' % name] + GetDisplayVectSettings())
  1104. self._giface.GetMapWindow().ZoomToMap()
  1105. def OnAbort(self, event):
  1106. """!Abort running import
  1107. @todo not yet implemented
  1108. """
  1109. pass
  1110. class GdalImportDialog(ImportDialog):
  1111. def __init__(self, parent, giface, ogr = False, link = False):
  1112. """!Dialog for bulk import of various raster/vector data
  1113. @todo Split into GdalImportDialog and OgrImportDialog
  1114. @param parent parent window
  1115. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1116. @param link True for linking data otherwise importing data
  1117. """
  1118. self._giface = giface
  1119. self.link = link
  1120. self.ogr = ogr
  1121. if ogr:
  1122. ImportDialog.__init__(self, parent, giface=giface, itype='ogr')
  1123. if link:
  1124. self.SetTitle(_("Link external vector data"))
  1125. else:
  1126. self.SetTitle(_("Import vector data"))
  1127. else:
  1128. ImportDialog.__init__(self, parent, giface=giface, itype='gdal')
  1129. if link:
  1130. self.SetTitle(_("Link external raster data"))
  1131. else:
  1132. self.SetTitle(_("Import raster data"))
  1133. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1134. ogr = ogr, link = link)
  1135. self.dsnInput.reloadDataRequired.connect(lambda data: self.list.LoadData(data))
  1136. mightNotWork = _("this might not work for multiple bands")
  1137. if link:
  1138. self.add.SetLabel(_("Add linked layers into layer tree"
  1139. " ({mightNotWork})".format(mightNotWork=mightNotWork)))
  1140. else:
  1141. self.add.SetLabel(_("Add imported layers into layer tree"
  1142. " ({mightNotWork})".format(mightNotWork=mightNotWork)))
  1143. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1144. if link:
  1145. self.btn_run.SetLabel(_("&Link"))
  1146. self.btn_run.SetToolTipString(_("Link selected layers"))
  1147. else:
  1148. self.btn_run.SetLabel(_("&Import"))
  1149. self.btn_run.SetToolTipString(_("Import selected layers"))
  1150. self.doLayout()
  1151. def OnRun(self, event):
  1152. """!Import/Link data (each layes as separate vector map)"""
  1153. self.commandId = -1
  1154. data = self.list.GetLayers()
  1155. if not data:
  1156. GMessage(_("No layers selected. Operation canceled."),
  1157. parent = self)
  1158. return
  1159. dsn = self.dsnInput.GetDsn()
  1160. ext = self.dsnInput.GetFormatExt()
  1161. # determine data driver for PostGIS links
  1162. popOGR = False
  1163. if self.importType == 'ogr' and \
  1164. self.dsnInput.GetType() == 'db' and \
  1165. self.dsnInput.GetFormat() == 'PostgreSQL' and \
  1166. 'GRASS_VECTOR_OGR' not in os.environ:
  1167. popOGR = True
  1168. os.environ['GRASS_VECTOR_OGR'] = '1'
  1169. for layer, output in data:
  1170. if self.importType == 'ogr':
  1171. if ext and layer.rfind(ext) > -1:
  1172. layer = layer.replace('.' + ext, '')
  1173. if self.link:
  1174. cmd = ['v.external',
  1175. 'dsn=%s' % dsn,
  1176. 'output=%s' % output,
  1177. 'layer=%s' % layer]
  1178. else:
  1179. cmd = ['v.in.ogr',
  1180. 'dsn=%s' % dsn,
  1181. 'layer=%s' % layer,
  1182. 'output=%s' % output]
  1183. else: # gdal
  1184. if self.dsnInput.GetType() == 'dir':
  1185. idsn = os.path.join(dsn, layer)
  1186. else:
  1187. idsn = dsn
  1188. if self.link:
  1189. cmd = ['r.external',
  1190. 'input=%s' % idsn,
  1191. 'output=%s' % output]
  1192. else:
  1193. cmd = ['r.in.gdal',
  1194. 'input=%s' % idsn,
  1195. 'output=%s' % output]
  1196. if self.overwrite.IsChecked():
  1197. cmd.append('--overwrite')
  1198. for key in self.options.keys():
  1199. if self.options[key].IsChecked():
  1200. cmd.append('-%s' % key)
  1201. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
  1202. '--overwrite' not in cmd:
  1203. cmd.append('--overwrite')
  1204. # run in Layer Manager
  1205. self._giface.RunCmd(cmd, switchPage = True, onDone = self.AddLayers)
  1206. if popOGR:
  1207. os.environ.pop('GRASS_VECTOR_OGR')
  1208. if self.closeOnFinish.IsChecked():
  1209. self.Close()
  1210. def _getCommand(self):
  1211. """!Get command"""
  1212. if self.link:
  1213. if self.ogr:
  1214. return 'v.external'
  1215. else:
  1216. return 'r.external'
  1217. else:
  1218. if self.ogr:
  1219. return 'v.in.ogr'
  1220. else:
  1221. return 'r.in.gdal'
  1222. return ''
  1223. class GdalOutputDialog(wx.Dialog):
  1224. def __init__(self, parent, id = wx.ID_ANY, ogr = False,
  1225. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
  1226. """!Dialog for setting output format for rasters/vectors
  1227. @todo Split into GdalOutputDialog and OgrOutputDialog
  1228. @param parent parent window
  1229. @param id window id
  1230. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1231. @param style window style
  1232. @param *kwargs other wx.Dialog's arguments
  1233. """
  1234. self.parent = parent # GMFrame
  1235. self.ogr = ogr
  1236. wx.Dialog.__init__(self, parent, id = id, style = style, *kwargs)
  1237. if self.ogr:
  1238. self.SetTitle(_("Define output format for vector data"))
  1239. else:
  1240. self.SetTitle(_("Define output format for raster data"))
  1241. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1242. # buttons
  1243. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1244. self.btnCancel.SetToolTipString(_("Close dialog"))
  1245. self.btnOk = wx.Button(parent = self.panel, id = wx.ID_OK)
  1246. self.btnOk.SetToolTipString(_("Set external format and close dialog"))
  1247. self.btnOk.SetDefault()
  1248. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1249. ogr = ogr,
  1250. exclude = ['file', 'protocol'], dest = True)
  1251. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  1252. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOk)
  1253. self._layout()
  1254. def _layout(self):
  1255. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1256. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1257. flag = wx.EXPAND)
  1258. btnSizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1259. btnSizer.Add(item = self.btnCancel, proportion = 0,
  1260. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1261. border = 10)
  1262. btnSizer.Add(item = self.btnOk, proportion = 0,
  1263. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1264. border = 10)
  1265. dialogSizer.Add(item = btnSizer, proportion = 0,
  1266. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.TOP | wx.ALIGN_RIGHT,
  1267. border = 10)
  1268. self.panel.SetAutoLayout(True)
  1269. self.panel.SetSizer(dialogSizer)
  1270. dialogSizer.Fit(self.panel)
  1271. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, self.GetBestSize()[1])
  1272. self.SetMinSize(size)
  1273. self.SetSize((size.width, size.height))
  1274. self.Layout()
  1275. def OnCancel(self, event):
  1276. self.Destroy()
  1277. def OnOK(self, event):
  1278. if self.dsnInput.GetType() == 'native':
  1279. RunCommand('v.external.out',
  1280. parent = self,
  1281. flags = 'r')
  1282. else:
  1283. dsn = self.dsnInput.GetDsn()
  1284. frmt = self.dsnInput.GetFormat()
  1285. options = self.dsnInput.GetOptions()
  1286. if not dsn:
  1287. GMessage(_("No data source selected."), parent=self)
  1288. return
  1289. RunCommand('v.external.out',
  1290. parent = self,
  1291. dsn = dsn, format = frmt,
  1292. options = options)
  1293. self.Close()
  1294. class DxfImportDialog(ImportDialog):
  1295. """!Dialog for bulk import of DXF layers"""
  1296. def __init__(self, parent, giface):
  1297. ImportDialog.__init__(self, parent, giface=giface, itype='dxf',
  1298. title = _("Import DXF layers"))
  1299. self._giface = giface
  1300. self.dsnInput = filebrowse.FileBrowseButton(parent = self.panel, id = wx.ID_ANY,
  1301. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1302. dialogTitle = _('Choose DXF file to import'),
  1303. buttonText = _('Browse'),
  1304. startDirectory = os.getcwd(), fileMode = 0,
  1305. changeCallback = self.OnSetDsn,
  1306. fileMask = "DXF File (*.dxf)|*.dxf")
  1307. self.add.SetLabel(_("Add imported layers into layer tree"))
  1308. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1309. self.doLayout()
  1310. def _getCommand(self):
  1311. """!Get command"""
  1312. return 'v.in.dxf'
  1313. def OnRun(self, event):
  1314. """!Import/Link data (each layes as separate vector map)"""
  1315. data = self.list.GetLayers()
  1316. if not data:
  1317. GMessage(_("No layers selected."), parent=self)
  1318. return
  1319. # hide dialog
  1320. self.Hide()
  1321. inputDxf = self.dsnInput.GetValue()
  1322. for layer, output in data:
  1323. cmd = ['v.in.dxf',
  1324. 'input=%s' % inputDxf,
  1325. 'layers=%s' % layer,
  1326. 'output=%s' % output]
  1327. for key in self.options.keys():
  1328. if self.options[key].IsChecked():
  1329. cmd.append('-%s' % key)
  1330. if self.overwrite.IsChecked() or \
  1331. UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  1332. cmd.append('--overwrite')
  1333. # run in Layer Manager
  1334. self._giface.RunCmd(cmd, switchPage = True, onDone = self.AddLayers)
  1335. self.Close()
  1336. def OnSetDsn(self, event):
  1337. """!Input DXF file defined, update list of layer widget"""
  1338. path = event.GetString()
  1339. if not path:
  1340. return
  1341. data = list()
  1342. ret = RunCommand('v.in.dxf',
  1343. quiet = True,
  1344. parent = self,
  1345. read = True,
  1346. flags = 'l',
  1347. input = path)
  1348. if not ret:
  1349. self.list.LoadData()
  1350. return
  1351. for line in ret.splitlines():
  1352. layerId = line.split(':')[0].split(' ')[1]
  1353. layerName = line.split(':')[1].strip()
  1354. grassName = GetValidLayerName(layerName)
  1355. data.append((layerId, layerName.strip(), grassName.strip()))
  1356. self.list.LoadData(data)
  1357. class LayersList(GListCtrl, listmix.TextEditMixin):
  1358. """!List of layers to be imported (dxf, shp...)"""
  1359. def __init__(self, parent, columns, log = None):
  1360. GListCtrl.__init__(self, parent)
  1361. self.log = log
  1362. # setup mixins
  1363. listmix.TextEditMixin.__init__(self)
  1364. for i in range(len(columns)):
  1365. self.InsertColumn(i, columns[i])
  1366. if len(columns) == 3:
  1367. width = (65, 200)
  1368. else:
  1369. width = (65, 180, 90, 70)
  1370. for i in range(len(width)):
  1371. self.SetColumnWidth(col = i, width = width[i])
  1372. def LoadData(self, data = None):
  1373. """!Load data into list"""
  1374. self.DeleteAllItems()
  1375. if data is None:
  1376. return
  1377. for item in data:
  1378. index = self.InsertStringItem(sys.maxint, str(item[0]))
  1379. for i in range(1, len(item)):
  1380. self.SetStringItem(index, i, "%s" % str(item[i]))
  1381. # check by default only on one item
  1382. if len(data) == 1:
  1383. self.CheckItem(index, True)
  1384. def OnLeftDown(self, event):
  1385. """!Allow editing only output name
  1386. Code taken from TextEditMixin class.
  1387. """
  1388. x, y = event.GetPosition()
  1389. colLocs = [0]
  1390. loc = 0
  1391. for n in range(self.GetColumnCount()):
  1392. loc = loc + self.GetColumnWidth(n)
  1393. colLocs.append(loc)
  1394. col = bisect(colLocs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
  1395. if col == self.GetColumnCount() - 1:
  1396. listmix.TextEditMixin.OnLeftDown(self, event)
  1397. else:
  1398. event.Skip()
  1399. def GetLayers(self):
  1400. """!Get list of layers (layer name, output name)"""
  1401. data = []
  1402. item = -1
  1403. while True:
  1404. item = self.GetNextItem(item)
  1405. if item == -1:
  1406. break
  1407. if not self.IsChecked(item):
  1408. continue
  1409. # layer / output name
  1410. data.append((self.GetItem(item, 1).GetText(),
  1411. self.GetItem(item, self.GetColumnCount() - 1).GetText()))
  1412. return data
  1413. class SetOpacityDialog(wx.Dialog):
  1414. """!Set opacity of map layers"""
  1415. def __init__(self, parent, id = wx.ID_ANY, title = _("Set Map Layer Opacity"),
  1416. size = wx.DefaultSize, pos = wx.DefaultPosition,
  1417. style = wx.DEFAULT_DIALOG_STYLE, opacity = 100):
  1418. self.parent = parent # GMFrame
  1419. self.opacity = opacity # current opacity
  1420. super(SetOpacityDialog, self).__init__(parent, id = id, pos = pos,
  1421. size = size, style = style, title = title)
  1422. self.applyOpacity = Signal('SetOpacityDialog.applyOpacity')
  1423. panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1424. sizer = wx.BoxSizer(wx.VERTICAL)
  1425. box = wx.GridBagSizer(vgap = 5, hgap = 5)
  1426. self.value = wx.Slider(panel, id = wx.ID_ANY, value = self.opacity,
  1427. style = wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | \
  1428. wx.SL_TOP | wx.SL_LABELS,
  1429. minValue = 0, maxValue = 100,
  1430. size = (350, -1))
  1431. box.Add(item = self.value,
  1432. flag = wx.ALIGN_CENTRE, pos = (0, 0), span = (1, 2))
  1433. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1434. label = _("transparent")),
  1435. pos = (1, 0))
  1436. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1437. label = _("opaque")),
  1438. flag = wx.ALIGN_RIGHT,
  1439. pos = (1, 1))
  1440. sizer.Add(item = box, proportion = 0,
  1441. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1442. line = wx.StaticLine(parent = panel, id = wx.ID_ANY,
  1443. style = wx.LI_HORIZONTAL)
  1444. sizer.Add(item = line, proportion = 0,
  1445. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1446. # buttons
  1447. btnsizer = wx.StdDialogButtonSizer()
  1448. btnOK = wx.Button(parent = panel, id = wx.ID_OK)
  1449. btnOK.SetDefault()
  1450. btnsizer.AddButton(btnOK)
  1451. btnCancel = wx.Button(parent = panel, id = wx.ID_CANCEL)
  1452. btnsizer.AddButton(btnCancel)
  1453. btnApply = wx.Button(parent = panel, id = wx.ID_APPLY)
  1454. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1455. btnsizer.AddButton(btnApply)
  1456. btnsizer.Realize()
  1457. sizer.Add(item = btnsizer, proportion = 0,
  1458. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1459. panel.SetSizer(sizer)
  1460. sizer.Fit(panel)
  1461. self.SetSize(self.GetBestSize())
  1462. self.Layout()
  1463. def GetOpacity(self):
  1464. """!Button 'OK' pressed"""
  1465. # return opacity value
  1466. opacity = float(self.value.GetValue()) / 100
  1467. return opacity
  1468. def OnApply(self, event):
  1469. self.applyOpacity.emit(value = self.GetOpacity())
  1470. def GetImageHandlers(image):
  1471. """!Get list of supported image handlers"""
  1472. lext = list()
  1473. ltype = list()
  1474. for h in image.GetHandlers():
  1475. lext.append(h.GetExtension())
  1476. filetype = ''
  1477. if 'png' in lext:
  1478. filetype += "PNG file (*.png)|*.png|"
  1479. ltype.append({ 'type' : wx.BITMAP_TYPE_PNG,
  1480. 'ext' : 'png' })
  1481. filetype += "BMP file (*.bmp)|*.bmp|"
  1482. ltype.append({ 'type' : wx.BITMAP_TYPE_BMP,
  1483. 'ext' : 'bmp' })
  1484. if 'gif' in lext:
  1485. filetype += "GIF file (*.gif)|*.gif|"
  1486. ltype.append({ 'type' : wx.BITMAP_TYPE_GIF,
  1487. 'ext' : 'gif' })
  1488. if 'jpg' in lext:
  1489. filetype += "JPG file (*.jpg)|*.jpg|"
  1490. ltype.append({ 'type' : wx.BITMAP_TYPE_JPEG,
  1491. 'ext' : 'jpg' })
  1492. if 'pcx' in lext:
  1493. filetype += "PCX file (*.pcx)|*.pcx|"
  1494. ltype.append({ 'type' : wx.BITMAP_TYPE_PCX,
  1495. 'ext' : 'pcx' })
  1496. if 'pnm' in lext:
  1497. filetype += "PNM file (*.pnm)|*.pnm|"
  1498. ltype.append({ 'type' : wx.BITMAP_TYPE_PNM,
  1499. 'ext' : 'pnm' })
  1500. if 'tif' in lext:
  1501. filetype += "TIF file (*.tif)|*.tif|"
  1502. ltype.append({ 'type' : wx.BITMAP_TYPE_TIF,
  1503. 'ext' : 'tif' })
  1504. if 'xpm' in lext:
  1505. filetype += "XPM file (*.xpm)|*.xpm"
  1506. ltype.append({ 'type' : wx.BITMAP_TYPE_XPM,
  1507. 'ext' : 'xpm' })
  1508. return filetype, ltype
  1509. class ImageSizeDialog(wx.Dialog):
  1510. """!Set size for saved graphic file"""
  1511. def __init__(self, parent, id = wx.ID_ANY, title = _("Set image size"),
  1512. style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
  1513. self.parent = parent
  1514. wx.Dialog.__init__(self, parent, id = id, style = style, title = title, **kwargs)
  1515. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1516. self.box = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1517. label = ' % s' % _("Image size"))
  1518. size = self.parent.GetWindow().GetClientSize()
  1519. self.width = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1520. style = wx.SP_ARROW_KEYS)
  1521. self.width.SetRange(20, 1e6)
  1522. self.width.SetValue(size.width)
  1523. wx.CallAfter(self.width.SetFocus)
  1524. self.height = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1525. style = wx.SP_ARROW_KEYS)
  1526. self.height.SetRange(20, 1e6)
  1527. self.height.SetValue(size.height)
  1528. self.template = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  1529. size = (125, -1),
  1530. choices = [ "",
  1531. "640x480",
  1532. "800x600",
  1533. "1024x768",
  1534. "1280x960",
  1535. "1600x1200",
  1536. "1920x1440" ])
  1537. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  1538. self.btnOK.SetDefault()
  1539. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1540. self.template.Bind(wx.EVT_CHOICE, self.OnTemplate)
  1541. self._layout()
  1542. self.SetSize(self.GetBestSize())
  1543. def _layout(self):
  1544. """!Do layout"""
  1545. sizer = wx.BoxSizer(wx.VERTICAL)
  1546. # body
  1547. box = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
  1548. fbox = wx.FlexGridSizer(cols = 2, vgap = 5, hgap = 5)
  1549. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1550. label = _("Width:")),
  1551. flag = wx.ALIGN_CENTER_VERTICAL)
  1552. fbox.Add(item = self.width)
  1553. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1554. label = _("Height:")),
  1555. flag = wx.ALIGN_CENTER_VERTICAL)
  1556. fbox.Add(item = self.height)
  1557. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1558. label = _("Template:")),
  1559. flag = wx.ALIGN_CENTER_VERTICAL)
  1560. fbox.Add(item = self.template)
  1561. box.Add(item = fbox, proportion = 1,
  1562. flag = wx.EXPAND | wx.ALL, border = 5)
  1563. sizer.Add(item = box, proportion = 1,
  1564. flag=wx.EXPAND | wx.ALL, border = 3)
  1565. # buttons
  1566. btnsizer = wx.StdDialogButtonSizer()
  1567. btnsizer.AddButton(self.btnOK)
  1568. btnsizer.AddButton(self.btnCancel)
  1569. btnsizer.Realize()
  1570. sizer.Add(item = btnsizer, proportion = 0,
  1571. flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
  1572. self.panel.SetSizer(sizer)
  1573. sizer.Fit(self.panel)
  1574. self.Layout()
  1575. def GetValues(self):
  1576. """!Get width/height values"""
  1577. return self.width.GetValue(), self.height.GetValue()
  1578. def OnTemplate(self, event):
  1579. """!Template selected"""
  1580. sel = event.GetString()
  1581. if not sel:
  1582. width, height = self.parent.GetWindow().GetClientSize()
  1583. else:
  1584. width, height = map(int, sel.split('x'))
  1585. self.width.SetValue(width)
  1586. self.height.SetValue(height)
  1587. class SqlQueryFrame(wx.Frame):
  1588. def __init__(self, parent, id = wx.ID_ANY,
  1589. title = _("GRASS GIS SQL Query Utility"),
  1590. *kwargs):
  1591. """!SQL Query Utility window
  1592. """
  1593. self.parent = parent
  1594. wx.Frame.__init__(self, parent = parent, id = id, title = title, *kwargs)
  1595. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
  1596. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1597. self.sqlBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1598. label = _(" SQL statement "))
  1599. self.sql = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  1600. style = wx.TE_MULTILINE)
  1601. self.btnApply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  1602. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1603. self.Bind(wx.EVT_BUTTON, self.OnCloseWindow, self.btnCancel)
  1604. self._layout()
  1605. self.SetMinSize(wx.Size(300, 150))
  1606. self.SetSize(wx.Size(500, 200))
  1607. def _layout(self):
  1608. """!Do layout"""
  1609. sizer = wx.BoxSizer(wx.VERTICAL)
  1610. sqlSizer = wx.StaticBoxSizer(self.sqlBox, wx.HORIZONTAL)
  1611. sqlSizer.Add(item = self.sql, proportion = 1,
  1612. flag = wx.EXPAND)
  1613. btnSizer = wx.StdDialogButtonSizer()
  1614. btnSizer.AddButton(self.btnApply)
  1615. btnSizer.AddButton(self.btnCancel)
  1616. btnSizer.Realize()
  1617. sizer.Add(item = sqlSizer, proportion = 1,
  1618. flag = wx.EXPAND | wx.ALL, border = 5)
  1619. sizer.Add(item = btnSizer, proportion = 0,
  1620. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1621. self.panel.SetSizer(sizer)
  1622. self.Layout()
  1623. def OnCloseWindow(self, event):
  1624. """!Close window
  1625. """
  1626. self.Close()
  1627. class SymbolDialog(wx.Dialog):
  1628. """!Dialog for GRASS symbols selection.
  1629. Dialog is called in gui_core::forms module.
  1630. """
  1631. def __init__(self, parent, symbolPath, currentSymbol = None, title = _("Symbols")):
  1632. """!Dialog constructor.
  1633. It is assumed that symbolPath contains folders with symbols.
  1634. @param parent dialog parent
  1635. @param symbolPath absolute path to symbols
  1636. @param currentSymbol currently selected symbol (e.g. 'basic/x')
  1637. @param title dialog title
  1638. """
  1639. wx.Dialog.__init__(self, parent = parent, title = title, id = wx.ID_ANY)
  1640. self.symbolPath = symbolPath
  1641. self.currentSymbol = currentSymbol # default basic/x
  1642. self.selected = None
  1643. self.selectedDir = None
  1644. self._layout()
  1645. def _layout(self):
  1646. mainPanel = wx.Panel(self, id = wx.ID_ANY)
  1647. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1648. vSizer = wx.BoxSizer( wx.VERTICAL)
  1649. fgSizer = wx.FlexGridSizer(rows = 2, vgap = 5, hgap = 5)
  1650. self.folderChoice = wx.Choice(mainPanel, id = wx.ID_ANY, choices = os.listdir(self.symbolPath))
  1651. self.folderChoice.Bind(wx.EVT_CHOICE, self.OnFolderSelect)
  1652. fgSizer.Add(item = wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol directory:")),
  1653. proportion = 0,
  1654. flag = wx.ALIGN_CENTER_VERTICAL)
  1655. fgSizer.Add(item = self.folderChoice, proportion = 0,
  1656. flag = wx.ALIGN_CENTER, border = 0)
  1657. self.infoLabel = wx.StaticText(mainPanel, id = wx.ID_ANY)
  1658. fgSizer.Add(wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol name:")),
  1659. flag = wx.ALIGN_CENTRE_VERTICAL)
  1660. fgSizer.Add(self.infoLabel, proportion = 0,
  1661. flag = wx.ALIGN_CENTRE_VERTICAL)
  1662. vSizer.Add(fgSizer, proportion = 0, flag = wx.ALL, border = 5)
  1663. self.panels = self._createSymbolPanels(mainPanel)
  1664. for panel in self.panels:
  1665. vSizer.Add(panel, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  1666. mainSizer.Add(vSizer, proportion = 1, flag = wx.ALL| wx.EXPAND, border = 5)
  1667. self.btnCancel = wx.Button(parent = mainPanel, id = wx.ID_CANCEL)
  1668. self.btnOK = wx.Button(parent = mainPanel, id = wx.ID_OK)
  1669. self.btnOK.SetDefault()
  1670. self.btnOK.Enable(False)
  1671. # buttons
  1672. btnSizer = wx.StdDialogButtonSizer()
  1673. btnSizer.AddButton(self.btnCancel)
  1674. btnSizer.AddButton(self.btnOK)
  1675. btnSizer.Realize()
  1676. mainSizer.Add(item = btnSizer, proportion = 0,
  1677. flag = wx.EXPAND | wx.ALL, border = 5)
  1678. # show panel with the largest number of images and fit size
  1679. count = []
  1680. for folder in os.listdir(self.symbolPath):
  1681. count.append(len(os.listdir(os.path.join(self.symbolPath, folder))))
  1682. index = count.index(max(count))
  1683. self.folderChoice.SetSelection(index)
  1684. self.OnFolderSelect(None)
  1685. self.infoLabel.Show()
  1686. mainPanel.SetSizerAndFit(mainSizer)
  1687. self.SetSize(self.GetBestSize())
  1688. # show currently selected symbol
  1689. if self.currentSymbol:
  1690. # set directory
  1691. self.selectedDir, self.selected = os.path.split(self.currentSymbol)
  1692. self.folderChoice.SetStringSelection(self.selectedDir)
  1693. # select symbol
  1694. panelIdx = self.folderChoice.GetSelection()
  1695. for panel in self.symbolPanels[panelIdx]:
  1696. if panel.GetName() == self.selected:
  1697. panel.Select()
  1698. else:
  1699. self.folderChoice.SetSelection(0)
  1700. self.OnFolderSelect(None)
  1701. def _createSymbolPanels(self, parent):
  1702. """!Creates multiple panels with symbols.
  1703. Panels are shown/hidden according to selected folder."""
  1704. folders = os.listdir(self.symbolPath)
  1705. panels = []
  1706. self.symbolPanels = []
  1707. for folder in folders:
  1708. panel = wx.Panel(parent, style = wx.BORDER_RAISED)
  1709. sizer = wx.GridSizer(cols = 6, vgap = 3, hgap = 3)
  1710. images = self._getSymbols(path = os.path.join(self.symbolPath, folder))
  1711. symbolPanels = []
  1712. for img in images:
  1713. iP = SingleSymbolPanel(parent = panel, symbolPath = img)
  1714. iP.symbolSelectionChanged.connect(self.SelectionChanged)
  1715. sizer.Add(item = iP, proportion = 0, flag = wx.ALIGN_CENTER)
  1716. symbolPanels.append(iP)
  1717. panel.SetSizerAndFit(sizer)
  1718. panel.Hide()
  1719. panels.append(panel)
  1720. self.symbolPanels.append(symbolPanels)
  1721. return panels
  1722. def _getSymbols(self, path):
  1723. # we assume that images are in subfolders (1 level only)
  1724. imageList = []
  1725. for image in os.listdir(path):
  1726. imageList.append(os.path.join(path, image))
  1727. return sorted(imageList)
  1728. def OnFolderSelect(self, event):
  1729. """!Selected folder with symbols changed."""
  1730. idx = self.folderChoice.GetSelection()
  1731. for i in range(len(self.panels)):
  1732. sizer = self.panels[i].GetContainingSizer()
  1733. sizer.Show(self.panels[i], i == idx, recursive = True)
  1734. sizer.Layout()
  1735. if self.selectedDir == self.folderChoice.GetStringSelection():
  1736. self.btnOK.Enable()
  1737. self.infoLabel.SetLabel(self.selected)
  1738. else:
  1739. self.btnOK.Disable()
  1740. self.infoLabel.SetLabel('')
  1741. def SelectionChanged(self, name, doubleClick):
  1742. """!Selected symbol changed."""
  1743. if doubleClick:
  1744. self.EndModal(wx.ID_OK)
  1745. # deselect all
  1746. for i in range(len(self.panels)):
  1747. for panel in self.symbolPanels[i]:
  1748. if panel.GetName() != name:
  1749. panel.Deselect()
  1750. self.btnOK.Enable()
  1751. self.selected = name
  1752. self.selectedDir = self.folderChoice.GetStringSelection()
  1753. self.infoLabel.SetLabel(name)
  1754. def GetSelectedSymbolName(self):
  1755. """!Returns currently selected symbol name (e.g. 'basic/x').
  1756. """
  1757. # separator must be '/' and not dependent on OS
  1758. return self.selectedDir + '/' + self.selected
  1759. def GetSelectedSymbolPath(self):
  1760. """!Returns currently selected symbol full path.
  1761. """
  1762. return os.path.join(self.symbolPath, self.selectedDir, self.selected)
  1763. class TextEntryDialog(wx.Dialog):
  1764. """!Simple dialog with text field.
  1765. It differs from wx.TextEntryDialog because it allows adding validator.
  1766. """
  1767. def __init__(self, parent, message, caption='',
  1768. defaultValue='', pos=wx.DefaultPosition, validator=wx.DefaultValidator,
  1769. style=wx.OK | wx.CANCEL):
  1770. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=caption, pos=pos)
  1771. vbox = wx.BoxSizer(wx.VERTICAL)
  1772. stline = wx.StaticText(self, id=wx.ID_ANY, label=message)
  1773. vbox.Add(item=stline, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
  1774. self._textCtrl = wx.TextCtrl(self, id=wx.ID_ANY, size = (300, -1),
  1775. value=defaultValue, validator=validator)
  1776. vbox.Add(item=self._textCtrl, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=10)
  1777. self._textCtrl.SetFocus()
  1778. sizer = self.CreateSeparatedButtonSizer(style)
  1779. vbox.Add(item=sizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
  1780. self.SetSizerAndFit(vbox)
  1781. def GetValue(self):
  1782. return self._textCtrl.GetValue()
  1783. def SetValue(self, value):
  1784. self._textCtrl.SetValue(value)
  1785. class HyperlinkDialog(wx.Dialog):
  1786. """!Dialog for displaying message with hyperlink."""
  1787. def __init__(self, parent, title, message, hyperlink,
  1788. hyperlinkLabel=None, style=wx.OK):
  1789. """!Constructor
  1790. @param parent gui parent
  1791. @param title dialog title
  1792. @param message message
  1793. @param hyperlink url
  1794. @param hyperlinkLabel label shown instead of url
  1795. @param style button style
  1796. """
  1797. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
  1798. style=wx.DEFAULT_DIALOG_STYLE)
  1799. sizer = wx.BoxSizer(wx.VERTICAL)
  1800. label = wx.StaticText(self, label=message)
  1801. sizer.Add(item=label, proportion=0, flag=wx.ALIGN_CENTRE|wx.ALL, border=10)
  1802. hyperlinkLabel = hyperlinkLabel if hyperlinkLabel else hyperlink
  1803. hyperlinkCtrl = wx.HyperlinkCtrl(self, id=wx.ID_ANY,
  1804. label=hyperlinkLabel, url=hyperlink,
  1805. style=wx.HL_ALIGN_LEFT|wx.HL_CONTEXTMENU)
  1806. sizer.Add(item=hyperlinkCtrl, proportion=0, flag=wx.EXPAND|wx.ALL, border=10)
  1807. btnsizer = self.CreateSeparatedButtonSizer(style)
  1808. sizer.Add(item=btnsizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
  1809. self.SetSizer(sizer)
  1810. sizer.Fit(self)