dialogs.py 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789
  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-2015 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, GWarning
  40. from gui_core.gselect import LocationSelect, MapsetSelect, Select, \
  41. OgrTypeSelect, GdalSelect, MapsetSelect, \
  42. SubGroupSelect
  43. from gui_core.widgets import SingleSymbolPanel, GListCtrl, SimpleValidator, MapValidator
  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 = MapValidator())
  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('vector')[curMapset]
  329. else:
  330. listOfVectors = RunCommand('v.external',
  331. quiet = True,
  332. parent = parent,
  333. read = True,
  334. flags = 'l',
  335. input = 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. input = 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 = 'raster'
  1204. elif sel == 1:
  1205. ltype = 'raster_3d'
  1206. else:
  1207. ltype = 'vector'
  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.options_par = dict()
  1270. self.commandId = -1 # id of running command
  1271. wx.Dialog.__init__(self, parent, id, title, style = style,
  1272. name = "MultiImportDialog")
  1273. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1274. self.layerBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY)
  1275. if self.importType == 'gdal':
  1276. label = _("List of raster layers")
  1277. elif self.importType == 'ogr':
  1278. label = _("List of vector layers")
  1279. else:
  1280. label = _("List of %s layers") % self.importType.upper()
  1281. self.layerBox.SetLabel(" %s - %s " % (label, _("right click to (un)select all")))
  1282. # list of layers
  1283. columns = [_('Layer id'),
  1284. _('Layer name'),
  1285. _('Name for output GRASS map (editable)')]
  1286. if itype == 'ogr':
  1287. columns.insert(2, _('Feature type'))
  1288. columns.insert(3, _('Projection match'))
  1289. self.list = LayersList(parent = self.panel, columns = columns)
  1290. self.list.LoadData()
  1291. self.optionBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1292. label = "%s" % _("Options"))
  1293. cmd = self._getCommand()
  1294. task = gtask.parse_interface(cmd)
  1295. for f in task.get_options()['flags']:
  1296. name = f.get('name', '')
  1297. desc = f.get('label', '')
  1298. if not desc:
  1299. desc = f.get('description', '')
  1300. if not name and not desc:
  1301. continue
  1302. if cmd == 'r.in.gdal' and name not in ('o', 'e', 'l', 'k'):
  1303. continue
  1304. elif cmd == 'r.external' and name not in ('o', 'e', 'r', 'h', 'v'):
  1305. continue
  1306. elif cmd == 'v.in.ogr' and name not in ('c', 'z', 't', 'o', 'r', 'e', 'w'):
  1307. continue
  1308. elif cmd == 'v.external' and name not in ('b'):
  1309. continue
  1310. elif cmd == 'v.in.dxf' and name not in ('e', 't', 'b', 'f', 'i'):
  1311. continue
  1312. self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1313. label = desc)
  1314. for f in task.get_options()['params']:
  1315. name = f.get('name', '')
  1316. desc = f.get('label', '')
  1317. if not desc:
  1318. desc = f.get('description', '')
  1319. if not name and not desc:
  1320. continue
  1321. if cmd == 'v.in.ogr' and name == 'encoding':
  1322. self.options_par[name] = (_('Encoding'),
  1323. wx.TextCtrl(parent = self.panel, id = wx.ID_ANY))
  1324. self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1325. label = _("Allow output files to overwrite existing files"))
  1326. self.overwrite.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  1327. self.add = wx.CheckBox(parent = self.panel, id = wx.ID_ANY)
  1328. self.closeOnFinish = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1329. label = _("Close dialog on finish"))
  1330. self.closeOnFinish.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  1331. #
  1332. # buttons
  1333. #
  1334. # cancel
  1335. self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  1336. self.btn_close.SetToolTipString(_("Close dialog"))
  1337. self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
  1338. # run
  1339. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Import"))
  1340. self.btn_run.SetToolTipString(_("Import selected layers"))
  1341. self.btn_run.SetDefault()
  1342. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  1343. self.Bind(wx.EVT_CLOSE, lambda evt: self.Destroy())
  1344. def doLayout(self):
  1345. """Do layout"""
  1346. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1347. # dsn input
  1348. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1349. flag = wx.EXPAND)
  1350. #
  1351. # list of DXF layers
  1352. #
  1353. layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)
  1354. layerSizer.Add(item = self.list, proportion = 1,
  1355. flag = wx.ALL | wx.EXPAND, border = 5)
  1356. dialogSizer.Add(item = layerSizer, proportion = 1,
  1357. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1358. # options
  1359. optionSizer = wx.StaticBoxSizer(self.optionBox, wx.VERTICAL)
  1360. for key in self.options.keys():
  1361. optionSizer.Add(item = self.options[key], proportion = 0)
  1362. if self.options_par:
  1363. gridBox = wx.GridBagSizer(vgap = 5, hgap = 5)
  1364. row = 0
  1365. for label, win in self.options_par.itervalues():
  1366. gridBox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1367. label = label + ':'),
  1368. pos = (row, 0), flag = wx.ALIGN_CENTER_VERTICAL)
  1369. gridBox.Add(item = win, pos = (row, 1), flag = wx.EXPAND)
  1370. row += 1
  1371. gridBox.AddGrowableCol(1)
  1372. optionSizer.Add(item = gridBox, proportion = 0,
  1373. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1374. dialogSizer.Add(item = optionSizer, proportion = 0,
  1375. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1376. dialogSizer.Add(item = self.overwrite, proportion = 0,
  1377. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1378. dialogSizer.Add(item = self.add, proportion = 0,
  1379. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1380. dialogSizer.Add(item = self.closeOnFinish, proportion = 0,
  1381. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1382. #
  1383. # buttons
  1384. #
  1385. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1386. btnsizer.Add(item = self.btn_close, proportion = 0,
  1387. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1388. border = 10)
  1389. btnsizer.Add(item = self.btn_run, proportion = 0,
  1390. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1391. border = 10)
  1392. dialogSizer.Add(item = btnsizer, proportion = 0,
  1393. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.ALIGN_RIGHT,
  1394. border = 10)
  1395. # dialogSizer.SetSizeHints(self.panel)
  1396. self.panel.SetAutoLayout(True)
  1397. self.panel.SetSizer(dialogSizer)
  1398. dialogSizer.Fit(self.panel)
  1399. # auto-layout seems not work here - FIXME
  1400. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, 550)
  1401. self.SetMinSize(size)
  1402. self.SetSize((size.width, size.height + 100))
  1403. # width = self.GetSize()[0]
  1404. # self.list.SetColumnWidth(col = 1, width = width / 2 - 50)
  1405. self.Layout()
  1406. def _getCommand(self):
  1407. """Get command"""
  1408. return ''
  1409. def OnClose(self, event = None):
  1410. """Close dialog"""
  1411. self.Close()
  1412. def OnRun(self, event):
  1413. """Import/Link data (each layes as separate vector map)"""
  1414. pass
  1415. def AddLayers(self, returncode, cmd = None, userData = None):
  1416. """Add imported/linked layers into layer tree"""
  1417. if not self.add.IsChecked() or returncode != 0:
  1418. return
  1419. # TODO: if importing map creates more map the folowing does not work
  1420. # * do nothing if map does not exist or
  1421. # * try to determine names using regexp or
  1422. # * persuade import tools to report map names
  1423. self.commandId += 1
  1424. layer, output = self.list.GetLayers()[self.commandId]
  1425. if '@' not in output:
  1426. name = output + '@' + grass.gisenv()['MAPSET']
  1427. else:
  1428. name = output
  1429. # add imported layers into layer tree
  1430. # an alternative would be emit signal (mapCreated) and (optionally)
  1431. # connect to this signal
  1432. llist = self._giface.GetLayerList()
  1433. if self.importType == 'gdal':
  1434. if userData:
  1435. nBands = int(userData.get('nbands', 1))
  1436. else:
  1437. nBands = 1
  1438. if UserSettings.Get(group = 'rasterLayer', key = 'opaque', subkey = 'enabled'):
  1439. nFlag = True
  1440. else:
  1441. nFlag = False
  1442. for i in range(1, nBands+1):
  1443. nameOrig = name
  1444. if nBands > 1:
  1445. mapName, mapsetName = name.split('@')
  1446. mapName += '.%d' % i
  1447. name = mapName + '@' + mapsetName
  1448. cmd = ['d.rast',
  1449. 'map=%s' % name]
  1450. if nFlag:
  1451. cmd.append('-n')
  1452. llist.AddLayer(ltype='raster',
  1453. name=name, checked=True,
  1454. cmd=cmd)
  1455. name = nameOrig
  1456. else:
  1457. llist.AddLayer(ltype='vector',
  1458. name=name, checked=True,
  1459. cmd=['d.vect',
  1460. 'map=%s' % name] + GetDisplayVectSettings())
  1461. self._giface.GetMapWindow().ZoomToMap()
  1462. def OnAbort(self, event):
  1463. """Abort running import
  1464. .. todo::
  1465. not yet implemented
  1466. """
  1467. pass
  1468. def OnCmdDone(self, event):
  1469. """Do what has to be done after importing"""
  1470. pass
  1471. class GdalImportDialog(ImportDialog):
  1472. def __init__(self, parent, giface, ogr = False, link = False):
  1473. """Dialog for bulk import of various raster/vector data
  1474. .. todo::
  1475. Split into GdalImportDialog and OgrImportDialog
  1476. :param parent: parent window
  1477. :param ogr: True for OGR (vector) otherwise GDAL (raster)
  1478. :param link: True for linking data otherwise importing data
  1479. """
  1480. self._giface = giface
  1481. self.link = link
  1482. self.ogr = ogr
  1483. if ogr:
  1484. ImportDialog.__init__(self, parent, giface=giface, itype='ogr')
  1485. if link:
  1486. self.SetTitle(_("Link external vector data"))
  1487. else:
  1488. self.SetTitle(_("Import vector data"))
  1489. else:
  1490. ImportDialog.__init__(self, parent, giface=giface, itype='gdal')
  1491. if link:
  1492. self.SetTitle(_("Link external raster data"))
  1493. else:
  1494. self.SetTitle(_("Import raster data"))
  1495. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1496. ogr = ogr, link = link)
  1497. self.dsnInput.reloadDataRequired.connect(lambda data: self.list.LoadData(data))
  1498. if link:
  1499. self.add.SetLabel(_("Add linked layers into layer tree"))
  1500. else:
  1501. self.add.SetLabel(_("Add imported layers into layer tree"))
  1502. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1503. if link:
  1504. self.btn_run.SetLabel(_("&Link"))
  1505. self.btn_run.SetToolTipString(_("Link selected layers"))
  1506. else:
  1507. self.btn_run.SetLabel(_("&Import"))
  1508. self.btn_run.SetToolTipString(_("Import selected layers"))
  1509. self.doLayout()
  1510. def OnRun(self, event):
  1511. """Import/Link data (each layes as separate vector map)"""
  1512. self.commandId = -1
  1513. data = self.list.GetLayers()
  1514. if not data:
  1515. GMessage(_("No layers selected. Operation canceled."),
  1516. parent = self)
  1517. return
  1518. dsn = self.dsnInput.GetDsn()
  1519. ext = self.dsnInput.GetFormatExt()
  1520. # determine data driver for PostGIS links
  1521. self.popOGR = False
  1522. if self.importType == 'ogr' and \
  1523. self.dsnInput.GetType() == 'db' and \
  1524. self.dsnInput.GetFormat() == 'PostgreSQL' and \
  1525. 'GRASS_VECTOR_OGR' not in os.environ:
  1526. self.popOGR = True
  1527. os.environ['GRASS_VECTOR_OGR'] = '1'
  1528. for layer, output in data:
  1529. userData = {}
  1530. if self.importType == 'ogr':
  1531. if ext and layer.rfind(ext) > -1:
  1532. layer = layer.replace('.' + ext, '')
  1533. if '|' in layer:
  1534. layer, geometry = layer.split('|', 1)
  1535. else:
  1536. geometry = None
  1537. if self.link:
  1538. cmd = ['v.external',
  1539. 'input=%s' % dsn,
  1540. 'output=%s' % output,
  1541. 'layer=%s' % layer]
  1542. else:
  1543. cmd = ['v.in.ogr',
  1544. 'input=%s' % dsn,
  1545. 'layer=%s' % layer,
  1546. 'output=%s' % output]
  1547. if geometry:
  1548. cmd.append('geometry=%s' % geometry)
  1549. else: # gdal
  1550. if self.dsnInput.GetType() == 'dir':
  1551. idsn = os.path.join(dsn, layer)
  1552. else:
  1553. idsn = dsn
  1554. # check number of bands
  1555. nBandsStr = RunCommand('r.in.gdal',
  1556. flags = 'p',
  1557. input = idsn, read = True)
  1558. nBands = -1
  1559. if nBandsStr:
  1560. try:
  1561. nBands = int(nBandsStr.rstrip('\n'))
  1562. except:
  1563. pass
  1564. if nBands < 0:
  1565. GWarning(_("Unable to determine number of raster bands"),
  1566. parent = self)
  1567. nBands = 1
  1568. userData['nbands'] = nBands
  1569. if self.link:
  1570. cmd = ['r.external',
  1571. 'input=%s' % idsn,
  1572. 'output=%s' % output]
  1573. else:
  1574. cmd = ['r.in.gdal',
  1575. 'input=%s' % idsn,
  1576. 'output=%s' % output]
  1577. if nBands > 1:
  1578. cmd.append('-k')
  1579. if self.overwrite.IsChecked():
  1580. cmd.append('--overwrite')
  1581. for key in self.options.keys():
  1582. if self.options[key].IsChecked():
  1583. cmd.append('-%s' % key)
  1584. for key in self.options_par.keys():
  1585. value = self.options_par[key][1].GetValue()
  1586. if value:
  1587. cmd.append('%s=%s' % (key, value))
  1588. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
  1589. '--overwrite' not in cmd:
  1590. cmd.append('--overwrite')
  1591. # run in Layer Manager
  1592. self._giface.RunCmd(cmd, onDone = self.OnCmdDone, userData = userData)
  1593. def OnCmdDone(self, event):
  1594. """Load layers and close if required"""
  1595. if not hasattr(self, 'AddLayers'):
  1596. return
  1597. self.AddLayers(event.returncode, event.cmd, event.userData)
  1598. if self.popOGR:
  1599. os.environ.pop('GRASS_VECTOR_OGR')
  1600. if event.returncode == 0 and self.closeOnFinish.IsChecked():
  1601. self.Close()
  1602. def _getCommand(self):
  1603. """Get command"""
  1604. if self.link:
  1605. if self.ogr:
  1606. return 'v.external'
  1607. else:
  1608. return 'r.external'
  1609. else:
  1610. if self.ogr:
  1611. return 'v.in.ogr'
  1612. else:
  1613. return 'r.in.gdal'
  1614. return ''
  1615. class GdalOutputDialog(wx.Dialog):
  1616. def __init__(self, parent, id = wx.ID_ANY, ogr = False,
  1617. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
  1618. """Dialog for setting output format for rasters/vectors
  1619. .. todo::
  1620. Split into GdalOutputDialog and OgrOutputDialog
  1621. :param parent: parent window
  1622. :param id: window id
  1623. :param ogr: True for OGR (vector) otherwise GDAL (raster)
  1624. :param style: window style
  1625. :param *kwargs: other wx.Dialog's arguments
  1626. """
  1627. self.parent = parent # GMFrame
  1628. self.ogr = ogr
  1629. wx.Dialog.__init__(self, parent, id = id, style = style, *kwargs)
  1630. if self.ogr:
  1631. self.SetTitle(_("Define output format for vector data"))
  1632. else:
  1633. self.SetTitle(_("Define output format for raster data"))
  1634. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1635. # buttons
  1636. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1637. self.btnCancel.SetToolTipString(_("Close dialog"))
  1638. self.btnOk = wx.Button(parent = self.panel, id = wx.ID_OK)
  1639. self.btnOk.SetToolTipString(_("Set external format and close dialog"))
  1640. self.btnOk.SetDefault()
  1641. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1642. ogr = ogr,
  1643. exclude = ['file', 'protocol'], dest = True)
  1644. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  1645. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOk)
  1646. self._layout()
  1647. def _layout(self):
  1648. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1649. dialogSizer.Add(item = self.dsnInput, proportion = 1,
  1650. flag = wx.EXPAND)
  1651. btnSizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1652. btnSizer.Add(item = self.btnCancel, proportion = 0,
  1653. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1654. border = 10)
  1655. btnSizer.Add(item = self.btnOk, proportion = 0,
  1656. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1657. border = 10)
  1658. dialogSizer.Add(item = btnSizer, proportion = 0,
  1659. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.TOP | wx.ALIGN_RIGHT,
  1660. border = 10)
  1661. self.panel.SetAutoLayout(True)
  1662. self.panel.SetSizer(dialogSizer)
  1663. dialogSizer.Fit(self.panel)
  1664. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, self.GetBestSize()[1] + 35)
  1665. self.SetMinSize(size)
  1666. self.SetSize((size.width, size.height))
  1667. self.Layout()
  1668. def OnCancel(self, event):
  1669. self.Destroy()
  1670. def OnOK(self, event):
  1671. if self.dsnInput.GetType() == 'native':
  1672. RunCommand('v.external.out',
  1673. parent = self,
  1674. flags = 'r')
  1675. else:
  1676. dsn = self.dsnInput.GetDsn()
  1677. frmt = self.dsnInput.GetFormat()
  1678. options = self.dsnInput.GetOptions()
  1679. if not dsn:
  1680. GMessage(_("No data source selected."), parent=self)
  1681. return
  1682. RunCommand('v.external.out',
  1683. parent = self,
  1684. output = dsn, format = frmt,
  1685. options = options)
  1686. self.Close()
  1687. class DxfImportDialog(ImportDialog):
  1688. """Dialog for bulk import of DXF layers"""
  1689. def __init__(self, parent, giface):
  1690. ImportDialog.__init__(self, parent, giface=giface, itype='dxf',
  1691. title = _("Import DXF layers"))
  1692. self._giface = giface
  1693. self.dsnInput = filebrowse.FileBrowseButton(parent = self.panel, id = wx.ID_ANY,
  1694. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1695. dialogTitle = _('Choose DXF file to import'),
  1696. buttonText = _('Browse'),
  1697. startDirectory = os.getcwd(), fileMode = 0,
  1698. changeCallback = self.OnSetDsn,
  1699. fileMask = "DXF File (*.dxf)|*.dxf")
  1700. self.add.SetLabel(_("Add imported layers into layer tree"))
  1701. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1702. self.doLayout()
  1703. def _getCommand(self):
  1704. """Get command"""
  1705. return 'v.in.dxf'
  1706. def OnRun(self, event):
  1707. """Import/Link data (each layes as separate vector map)"""
  1708. data = self.list.GetLayers()
  1709. if not data:
  1710. GMessage(_("No layers selected."), parent=self)
  1711. return
  1712. # hide dialog
  1713. self.Hide()
  1714. inputDxf = self.dsnInput.GetValue()
  1715. for layer, output in data:
  1716. cmd = ['v.in.dxf',
  1717. 'input=%s' % inputDxf,
  1718. 'layers=%s' % layer,
  1719. 'output=%s' % output]
  1720. for key in self.options.keys():
  1721. if self.options[key].IsChecked():
  1722. cmd.append('-%s' % key)
  1723. if self.overwrite.IsChecked() or \
  1724. UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  1725. cmd.append('--overwrite')
  1726. # run in Layer Manager
  1727. self._giface.RunCmd(cmd, onDone=self.OnCmdDone)
  1728. def OnCmdDone(self, event):
  1729. """Load layers and close if required"""
  1730. if not hasattr(self, 'AddLayers'):
  1731. return
  1732. self.AddLayers(event.returncode, event.cmd)
  1733. if self.closeOnFinish.IsChecked():
  1734. self.Close()
  1735. def OnSetDsn(self, event):
  1736. """Input DXF file defined, update list of layer widget"""
  1737. path = event.GetString()
  1738. if not path:
  1739. return
  1740. data = list()
  1741. ret = RunCommand('v.in.dxf',
  1742. quiet = True,
  1743. parent = self,
  1744. read = True,
  1745. flags = 'l',
  1746. input = path)
  1747. if not ret:
  1748. self.list.LoadData()
  1749. return
  1750. for line in ret.splitlines():
  1751. layerId = line.split(':')[0].split(' ')[1]
  1752. layerName = line.split(':')[1].strip()
  1753. grassName = GetValidLayerName(layerName)
  1754. data.append((layerId, layerName.strip(), grassName.strip()))
  1755. self.list.LoadData(data)
  1756. class LayersList(GListCtrl, listmix.TextEditMixin):
  1757. """List of layers to be imported (dxf, shp...)"""
  1758. def __init__(self, parent, columns, log = None):
  1759. GListCtrl.__init__(self, parent)
  1760. self.log = log
  1761. # setup mixins
  1762. listmix.TextEditMixin.__init__(self)
  1763. for i in range(len(columns)):
  1764. self.InsertColumn(i, columns[i])
  1765. if len(columns) == 3:
  1766. width = (65, 200)
  1767. else:
  1768. width = (65, 180, 90, 70)
  1769. for i in range(len(width)):
  1770. self.SetColumnWidth(col = i, width = width[i])
  1771. def LoadData(self, data = None):
  1772. """Load data into list"""
  1773. self.DeleteAllItems()
  1774. if data is None:
  1775. return
  1776. for item in data:
  1777. index = self.InsertStringItem(sys.maxint, str(item[0]))
  1778. for i in range(1, len(item)):
  1779. self.SetStringItem(index, i, item[i])
  1780. # check by default only on one item
  1781. if len(data) == 1:
  1782. self.CheckItem(index, True)
  1783. def OnLeftDown(self, event):
  1784. """Allow editing only output name
  1785. Code taken from TextEditMixin class.
  1786. """
  1787. x, y = event.GetPosition()
  1788. colLocs = [0]
  1789. loc = 0
  1790. for n in range(self.GetColumnCount()):
  1791. loc = loc + self.GetColumnWidth(n)
  1792. colLocs.append(loc)
  1793. col = bisect(colLocs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
  1794. if col == self.GetColumnCount() - 1:
  1795. listmix.TextEditMixin.OnLeftDown(self, event)
  1796. else:
  1797. event.Skip()
  1798. def GetLayers(self):
  1799. """Get list of layers (layer name, output name)"""
  1800. data = []
  1801. item = -1
  1802. while True:
  1803. item = self.GetNextItem(item)
  1804. if item == -1:
  1805. break
  1806. if not self.IsChecked(item):
  1807. continue
  1808. # layer / output name
  1809. layer = self.GetItem(item, 1).GetText()
  1810. ftype = self.GetItem(item, 2).GetText()
  1811. if '/' in ftype:
  1812. layer += '|%s' % ftype.split('/', 1)[0]
  1813. output = self.GetItem(item, self.GetColumnCount() - 1).GetText()
  1814. data.append((layer, output))
  1815. return data
  1816. class SetOpacityDialog(wx.Dialog):
  1817. """Set opacity of map layers.
  1818. Dialog expects opacity between 0 and 1 and returns this range, too.
  1819. """
  1820. def __init__(self, parent, id = wx.ID_ANY, title = _("Set Map Layer Opacity"),
  1821. size = wx.DefaultSize, pos = wx.DefaultPosition,
  1822. style = wx.DEFAULT_DIALOG_STYLE, opacity = 1):
  1823. self.parent = parent # GMFrame
  1824. self.opacity = opacity # current opacity
  1825. super(SetOpacityDialog, self).__init__(parent, id = id, pos = pos,
  1826. size = size, style = style, title = title)
  1827. self.applyOpacity = Signal('SetOpacityDialog.applyOpacity')
  1828. panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1829. sizer = wx.BoxSizer(wx.VERTICAL)
  1830. box = wx.GridBagSizer(vgap = 5, hgap = 5)
  1831. self.value = wx.Slider(panel, id = wx.ID_ANY, value = int(self.opacity * 100),
  1832. style = wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | \
  1833. wx.SL_TOP | wx.SL_LABELS,
  1834. minValue = 0, maxValue = 100,
  1835. size = (350, -1))
  1836. box.Add(item = self.value,
  1837. flag = wx.ALIGN_CENTRE, pos = (0, 0), span = (1, 2))
  1838. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1839. label = _("transparent")),
  1840. pos = (1, 0))
  1841. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1842. label = _("opaque")),
  1843. flag = wx.ALIGN_RIGHT,
  1844. pos = (1, 1))
  1845. sizer.Add(item = box, proportion = 0,
  1846. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1847. line = wx.StaticLine(parent = panel, id = wx.ID_ANY,
  1848. style = wx.LI_HORIZONTAL)
  1849. sizer.Add(item = line, proportion = 0,
  1850. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1851. # buttons
  1852. btnsizer = wx.StdDialogButtonSizer()
  1853. btnOK = wx.Button(parent = panel, id = wx.ID_OK)
  1854. btnOK.SetDefault()
  1855. btnsizer.AddButton(btnOK)
  1856. btnCancel = wx.Button(parent = panel, id = wx.ID_CANCEL)
  1857. btnsizer.AddButton(btnCancel)
  1858. btnApply = wx.Button(parent = panel, id = wx.ID_APPLY)
  1859. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1860. btnsizer.AddButton(btnApply)
  1861. btnsizer.Realize()
  1862. sizer.Add(item = btnsizer, proportion = 0,
  1863. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1864. panel.SetSizer(sizer)
  1865. sizer.Fit(panel)
  1866. self.SetSize(self.GetBestSize())
  1867. self.Layout()
  1868. def GetOpacity(self):
  1869. """Button 'OK' pressed"""
  1870. # return opacity value
  1871. opacity = float(self.value.GetValue()) / 100
  1872. return opacity
  1873. def OnApply(self, event):
  1874. self.applyOpacity.emit(value = self.GetOpacity())
  1875. def GetImageHandlers(image):
  1876. """Get list of supported image handlers"""
  1877. lext = list()
  1878. ltype = list()
  1879. for h in image.GetHandlers():
  1880. lext.append(h.GetExtension())
  1881. filetype = ''
  1882. if 'png' in lext:
  1883. filetype += "PNG file (*.png)|*.png|"
  1884. ltype.append({ 'type' : wx.BITMAP_TYPE_PNG,
  1885. 'ext' : 'png' })
  1886. filetype += "BMP file (*.bmp)|*.bmp|"
  1887. ltype.append({ 'type' : wx.BITMAP_TYPE_BMP,
  1888. 'ext' : 'bmp' })
  1889. if 'gif' in lext:
  1890. filetype += "GIF file (*.gif)|*.gif|"
  1891. ltype.append({ 'type' : wx.BITMAP_TYPE_GIF,
  1892. 'ext' : 'gif' })
  1893. if 'jpg' in lext:
  1894. filetype += "JPG file (*.jpg)|*.jpg|"
  1895. ltype.append({ 'type' : wx.BITMAP_TYPE_JPEG,
  1896. 'ext' : 'jpg' })
  1897. if 'pcx' in lext:
  1898. filetype += "PCX file (*.pcx)|*.pcx|"
  1899. ltype.append({ 'type' : wx.BITMAP_TYPE_PCX,
  1900. 'ext' : 'pcx' })
  1901. if 'pnm' in lext:
  1902. filetype += "PNM file (*.pnm)|*.pnm|"
  1903. ltype.append({ 'type' : wx.BITMAP_TYPE_PNM,
  1904. 'ext' : 'pnm' })
  1905. if 'tif' in lext:
  1906. filetype += "TIF file (*.tif)|*.tif|"
  1907. ltype.append({ 'type' : wx.BITMAP_TYPE_TIF,
  1908. 'ext' : 'tif' })
  1909. if 'xpm' in lext:
  1910. filetype += "XPM file (*.xpm)|*.xpm"
  1911. ltype.append({ 'type' : wx.BITMAP_TYPE_XPM,
  1912. 'ext' : 'xpm' })
  1913. return filetype, ltype
  1914. class ImageSizeDialog(wx.Dialog):
  1915. """Set size for saved graphic file"""
  1916. def __init__(self, parent, id = wx.ID_ANY, title = _("Set image size"),
  1917. style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
  1918. self.parent = parent
  1919. wx.Dialog.__init__(self, parent, id = id, style = style, title = title, **kwargs)
  1920. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1921. self.box = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1922. label = ' % s' % _("Image size"))
  1923. size = self.parent.GetWindow().GetClientSize()
  1924. self.width = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1925. style = wx.SP_ARROW_KEYS)
  1926. self.width.SetRange(20, 1e6)
  1927. self.width.SetValue(size.width)
  1928. wx.CallAfter(self.width.SetFocus)
  1929. self.height = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1930. style = wx.SP_ARROW_KEYS)
  1931. self.height.SetRange(20, 1e6)
  1932. self.height.SetValue(size.height)
  1933. self.template = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  1934. size = (125, -1),
  1935. choices = [ "",
  1936. "640x480",
  1937. "800x600",
  1938. "1024x768",
  1939. "1280x960",
  1940. "1600x1200",
  1941. "1920x1440" ])
  1942. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  1943. self.btnOK.SetDefault()
  1944. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1945. self.template.Bind(wx.EVT_CHOICE, self.OnTemplate)
  1946. self._layout()
  1947. self.SetSize(self.GetBestSize())
  1948. def _layout(self):
  1949. """Do layout"""
  1950. sizer = wx.BoxSizer(wx.VERTICAL)
  1951. # body
  1952. box = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
  1953. fbox = wx.FlexGridSizer(cols = 2, vgap = 5, hgap = 5)
  1954. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1955. label = _("Width:")),
  1956. flag = wx.ALIGN_CENTER_VERTICAL)
  1957. fbox.Add(item = self.width)
  1958. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1959. label = _("Height:")),
  1960. flag = wx.ALIGN_CENTER_VERTICAL)
  1961. fbox.Add(item = self.height)
  1962. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1963. label = _("Template:")),
  1964. flag = wx.ALIGN_CENTER_VERTICAL)
  1965. fbox.Add(item = self.template)
  1966. box.Add(item = fbox, proportion = 1,
  1967. flag = wx.EXPAND | wx.ALL, border = 5)
  1968. sizer.Add(item = box, proportion = 1,
  1969. flag=wx.EXPAND | wx.ALL, border = 3)
  1970. # buttons
  1971. btnsizer = wx.StdDialogButtonSizer()
  1972. btnsizer.AddButton(self.btnOK)
  1973. btnsizer.AddButton(self.btnCancel)
  1974. btnsizer.Realize()
  1975. sizer.Add(item = btnsizer, proportion = 0,
  1976. flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
  1977. self.panel.SetSizer(sizer)
  1978. sizer.Fit(self.panel)
  1979. self.Layout()
  1980. def GetValues(self):
  1981. """Get width/height values"""
  1982. return self.width.GetValue(), self.height.GetValue()
  1983. def OnTemplate(self, event):
  1984. """Template selected"""
  1985. sel = event.GetString()
  1986. if not sel:
  1987. width, height = self.parent.GetWindow().GetClientSize()
  1988. else:
  1989. width, height = map(int, sel.split('x'))
  1990. self.width.SetValue(width)
  1991. self.height.SetValue(height)
  1992. class SqlQueryFrame(wx.Frame):
  1993. def __init__(self, parent, id = wx.ID_ANY,
  1994. title = _("GRASS GIS SQL Query Utility"),
  1995. *kwargs):
  1996. """SQL Query Utility window
  1997. """
  1998. self.parent = parent
  1999. wx.Frame.__init__(self, parent = parent, id = id, title = title, *kwargs)
  2000. self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
  2001. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  2002. self.sqlBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  2003. label = _(" SQL statement "))
  2004. self.sql = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  2005. style = wx.TE_MULTILINE)
  2006. self.btnApply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  2007. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  2008. self.Bind(wx.EVT_BUTTON, self.OnCloseWindow, self.btnCancel)
  2009. self._layout()
  2010. self.SetMinSize(wx.Size(300, 150))
  2011. self.SetSize(wx.Size(500, 200))
  2012. def _layout(self):
  2013. """Do layout"""
  2014. sizer = wx.BoxSizer(wx.VERTICAL)
  2015. sqlSizer = wx.StaticBoxSizer(self.sqlBox, wx.HORIZONTAL)
  2016. sqlSizer.Add(item = self.sql, proportion = 1,
  2017. flag = wx.EXPAND)
  2018. btnSizer = wx.StdDialogButtonSizer()
  2019. btnSizer.AddButton(self.btnApply)
  2020. btnSizer.AddButton(self.btnCancel)
  2021. btnSizer.Realize()
  2022. sizer.Add(item = sqlSizer, proportion = 1,
  2023. flag = wx.EXPAND | wx.ALL, border = 5)
  2024. sizer.Add(item = btnSizer, proportion = 0,
  2025. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  2026. self.panel.SetSizer(sizer)
  2027. self.Layout()
  2028. def OnCloseWindow(self, event):
  2029. """Close window
  2030. """
  2031. self.Close()
  2032. class SymbolDialog(wx.Dialog):
  2033. """Dialog for GRASS symbols selection.
  2034. Dialog is called in gui_core::forms module.
  2035. """
  2036. def __init__(self, parent, symbolPath, currentSymbol = None, title = _("Symbols")):
  2037. """Dialog constructor.
  2038. It is assumed that symbolPath contains folders with symbols.
  2039. :param parent: dialog parent
  2040. :param symbolPath: absolute path to symbols
  2041. :param currentSymbol: currently selected symbol (e.g. 'basic/x')
  2042. :param title: dialog title
  2043. """
  2044. wx.Dialog.__init__(self, parent = parent, title = title, id = wx.ID_ANY)
  2045. self.symbolPath = symbolPath
  2046. self.currentSymbol = currentSymbol # default basic/x
  2047. self.selected = None
  2048. self.selectedDir = None
  2049. self._layout()
  2050. def _layout(self):
  2051. mainPanel = wx.Panel(self, id = wx.ID_ANY)
  2052. mainSizer = wx.BoxSizer(wx.VERTICAL)
  2053. vSizer = wx.BoxSizer( wx.VERTICAL)
  2054. fgSizer = wx.FlexGridSizer(rows = 2, vgap = 5, hgap = 5)
  2055. self.folderChoice = wx.Choice(mainPanel, id = wx.ID_ANY, choices = os.listdir(self.symbolPath))
  2056. self.folderChoice.Bind(wx.EVT_CHOICE, self.OnFolderSelect)
  2057. fgSizer.Add(item = wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol directory:")),
  2058. proportion = 0,
  2059. flag = wx.ALIGN_CENTER_VERTICAL)
  2060. fgSizer.Add(item = self.folderChoice, proportion = 0,
  2061. flag = wx.ALIGN_CENTER, border = 0)
  2062. self.infoLabel = wx.StaticText(mainPanel, id = wx.ID_ANY)
  2063. fgSizer.Add(wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol name:")),
  2064. flag = wx.ALIGN_CENTRE_VERTICAL)
  2065. fgSizer.Add(self.infoLabel, proportion = 0,
  2066. flag = wx.ALIGN_CENTRE_VERTICAL)
  2067. vSizer.Add(fgSizer, proportion = 0, flag = wx.ALL, border = 5)
  2068. self.panels = self._createSymbolPanels(mainPanel)
  2069. for panel in self.panels:
  2070. vSizer.Add(panel, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2071. mainSizer.Add(vSizer, proportion = 1, flag = wx.ALL| wx.EXPAND, border = 5)
  2072. self.btnCancel = wx.Button(parent = mainPanel, id = wx.ID_CANCEL)
  2073. self.btnOK = wx.Button(parent = mainPanel, id = wx.ID_OK)
  2074. self.btnOK.SetDefault()
  2075. self.btnOK.Enable(False)
  2076. # buttons
  2077. btnSizer = wx.StdDialogButtonSizer()
  2078. btnSizer.AddButton(self.btnCancel)
  2079. btnSizer.AddButton(self.btnOK)
  2080. btnSizer.Realize()
  2081. mainSizer.Add(item = btnSizer, proportion = 0,
  2082. flag = wx.EXPAND | wx.ALL, border = 5)
  2083. # show panel with the largest number of images and fit size
  2084. count = []
  2085. for folder in os.listdir(self.symbolPath):
  2086. count.append(len(os.listdir(os.path.join(self.symbolPath, folder))))
  2087. index = count.index(max(count))
  2088. self.folderChoice.SetSelection(index)
  2089. self.OnFolderSelect(None)
  2090. self.infoLabel.Show()
  2091. mainPanel.SetSizerAndFit(mainSizer)
  2092. self.SetSize(self.GetBestSize())
  2093. # show currently selected symbol
  2094. if self.currentSymbol:
  2095. # set directory
  2096. self.selectedDir, self.selected = os.path.split(self.currentSymbol)
  2097. self.folderChoice.SetStringSelection(self.selectedDir)
  2098. # select symbol
  2099. panelIdx = self.folderChoice.GetSelection()
  2100. for panel in self.symbolPanels[panelIdx]:
  2101. if panel.GetName() == self.selected:
  2102. panel.Select()
  2103. else:
  2104. self.folderChoice.SetSelection(0)
  2105. self.OnFolderSelect(None)
  2106. def _createSymbolPanels(self, parent):
  2107. """Creates multiple panels with symbols.
  2108. Panels are shown/hidden according to selected folder."""
  2109. folders = os.listdir(self.symbolPath)
  2110. panels = []
  2111. self.symbolPanels = []
  2112. for folder in folders:
  2113. panel = wx.Panel(parent, style = wx.BORDER_RAISED)
  2114. sizer = wx.GridSizer(cols = 6, vgap = 3, hgap = 3)
  2115. images = self._getSymbols(path = os.path.join(self.symbolPath, folder))
  2116. symbolPanels = []
  2117. for img in images:
  2118. iP = SingleSymbolPanel(parent = panel, symbolPath = img)
  2119. iP.symbolSelectionChanged.connect(self.SelectionChanged)
  2120. sizer.Add(item = iP, proportion = 0, flag = wx.ALIGN_CENTER)
  2121. symbolPanels.append(iP)
  2122. panel.SetSizerAndFit(sizer)
  2123. panel.Hide()
  2124. panels.append(panel)
  2125. self.symbolPanels.append(symbolPanels)
  2126. return panels
  2127. def _getSymbols(self, path):
  2128. # we assume that images are in subfolders (1 level only)
  2129. imageList = []
  2130. for image in os.listdir(path):
  2131. imageList.append(os.path.join(path, image))
  2132. return sorted(imageList)
  2133. def OnFolderSelect(self, event):
  2134. """Selected folder with symbols changed."""
  2135. idx = self.folderChoice.GetSelection()
  2136. for i in range(len(self.panels)):
  2137. sizer = self.panels[i].GetContainingSizer()
  2138. sizer.Show(self.panels[i], i == idx, recursive = True)
  2139. sizer.Layout()
  2140. if self.selectedDir == self.folderChoice.GetStringSelection():
  2141. self.btnOK.Enable()
  2142. self.infoLabel.SetLabel(self.selected)
  2143. else:
  2144. self.btnOK.Disable()
  2145. self.infoLabel.SetLabel('')
  2146. def SelectionChanged(self, name, doubleClick):
  2147. """Selected symbol changed."""
  2148. if doubleClick:
  2149. self.EndModal(wx.ID_OK)
  2150. # deselect all
  2151. for i in range(len(self.panels)):
  2152. for panel in self.symbolPanels[i]:
  2153. if panel.GetName() != name:
  2154. panel.Deselect()
  2155. self.btnOK.Enable()
  2156. self.selected = name
  2157. self.selectedDir = self.folderChoice.GetStringSelection()
  2158. self.infoLabel.SetLabel(name)
  2159. def GetSelectedSymbolName(self):
  2160. """Returns currently selected symbol name (e.g. 'basic/x').
  2161. """
  2162. # separator must be '/' and not dependent on OS
  2163. return self.selectedDir + '/' + self.selected
  2164. def GetSelectedSymbolPath(self):
  2165. """Returns currently selected symbol full path.
  2166. """
  2167. return os.path.join(self.symbolPath, self.selectedDir, self.selected)
  2168. class TextEntryDialog(wx.Dialog):
  2169. """Simple dialog with text field.
  2170. It differs from wx.TextEntryDialog because it allows adding validator.
  2171. """
  2172. def __init__(self, parent, message, caption='',
  2173. defaultValue='', validator=wx.DefaultValidator,
  2174. style=wx.OK | wx.CANCEL, **kwargs):
  2175. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=caption, **kwargs)
  2176. vbox = wx.BoxSizer(wx.VERTICAL)
  2177. stline = wx.StaticText(self, id=wx.ID_ANY, label=message)
  2178. vbox.Add(item=stline, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
  2179. self._textCtrl = wx.TextCtrl(self, id=wx.ID_ANY, size = (300, -1),
  2180. value=defaultValue, validator=validator)
  2181. vbox.Add(item=self._textCtrl, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=10)
  2182. self._textCtrl.SetFocus()
  2183. sizer = self.CreateSeparatedButtonSizer(style)
  2184. vbox.Add(item=sizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
  2185. self.SetSizerAndFit(vbox)
  2186. def GetValue(self):
  2187. return self._textCtrl.GetValue()
  2188. def SetValue(self, value):
  2189. self._textCtrl.SetValue(value)
  2190. class HyperlinkDialog(wx.Dialog):
  2191. """Dialog for displaying message with hyperlink."""
  2192. def __init__(self, parent, title, message, hyperlink,
  2193. hyperlinkLabel=None, style=wx.OK):
  2194. """Constructor
  2195. :param parent: gui parent
  2196. :param title: dialog title
  2197. :param message: message
  2198. :param hyperlink: url
  2199. :param hyperlinkLabel: label shown instead of url
  2200. :param style: button style
  2201. """
  2202. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
  2203. style=wx.DEFAULT_DIALOG_STYLE)
  2204. sizer = wx.BoxSizer(wx.VERTICAL)
  2205. label = wx.StaticText(self, label=message)
  2206. sizer.Add(item=label, proportion=0, flag=wx.ALIGN_CENTRE|wx.ALL, border=10)
  2207. hyperlinkLabel = hyperlinkLabel if hyperlinkLabel else hyperlink
  2208. hyperlinkCtrl = wx.HyperlinkCtrl(self, id=wx.ID_ANY,
  2209. label=hyperlinkLabel, url=hyperlink,
  2210. style=wx.HL_ALIGN_LEFT|wx.HL_CONTEXTMENU)
  2211. sizer.Add(item=hyperlinkCtrl, proportion=0, flag=wx.EXPAND|wx.ALL, border=10)
  2212. btnsizer = self.CreateSeparatedButtonSizer(style)
  2213. sizer.Add(item=btnsizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
  2214. self.SetSizer(sizer)
  2215. sizer.Fit(self)