dialogs.py 98 KB

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