dialogs.py 98 KB

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