dialogs.py 103 KB

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