dialogs.py 87 KB

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