widgets.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  1. """
  2. @package gui_core.widgets
  3. @brief Core GUI widgets
  4. Classes:
  5. - widgets::GNotebook
  6. - widgets::ScrolledPanel
  7. - widgets::NumTextCtrl
  8. - widgets::FloatSlider
  9. - widgets::SymbolButton
  10. - widgets::StaticWrapText
  11. - widgets::BaseValidator
  12. - widgets::CoordinatesValidator
  13. - widgets::IntegerValidator
  14. - widgets::FloatValidator
  15. - widgets::EmailValidator
  16. - widgets::TimeISOValidator
  17. - widgets::MapValidator
  18. - widgets::NTCValidator
  19. - widgets::SimpleValidator
  20. - widgets::GenericValidator
  21. - widgets::GListCtrl
  22. - widgets::SearchModuleWidget
  23. - widgets::ManageSettingsWidget
  24. - widgets::PictureComboBox
  25. - widgets::ColorTablesComboBox
  26. - widgets::BarscalesComboBox
  27. - widgets::NArrowsComboBox
  28. - widgets::LayersList
  29. @todo:
  30. - move validators to a separate file gui_core/validators.py
  31. (C) 2008-2014 by the GRASS Development Team
  32. This program is free software under the GNU General Public License
  33. (>=v2). Read the file COPYING that comes with GRASS for details.
  34. @author Martin Landa <landa.martin gmail.com> (Google SoC 2008/2010)
  35. @author Enhancements by Michael Barton <michael.barton asu.edu>
  36. @author Anna Kratochvilova <kratochanna gmail.com> (Google SoC 2011)
  37. @author Stepan Turek <stepan.turek seznam.cz> (ManageSettingsWidget - created from GdalSelect)
  38. @author Matej Krejci <matejkrejci gmail.com> (Google GSoC 2014; EmailValidator, TimeISOValidator)
  39. """
  40. import os
  41. import sys
  42. import string
  43. import re
  44. import six
  45. from bisect import bisect
  46. from datetime import datetime
  47. from core.globalvar import wxPythonPhoenix
  48. import wx
  49. import wx.lib.mixins.listctrl as listmix
  50. import wx.lib.scrolledpanel as SP
  51. from wx.lib.stattext import GenStaticText
  52. from wx.lib.wordwrap import wordwrap
  53. if wxPythonPhoenix:
  54. import wx.adv
  55. from wx.adv import OwnerDrawnComboBox
  56. else:
  57. import wx.combo
  58. from wx.combo import OwnerDrawnComboBox
  59. try:
  60. import wx.lib.agw.flatnotebook as FN
  61. except ImportError:
  62. import wx.lib.flatnotebook as FN
  63. try:
  64. from wx.lib.buttons import ThemedGenBitmapTextButton as BitmapTextButton
  65. except ImportError: # not sure about TGBTButton version
  66. from wx.lib.buttons import GenBitmapTextButton as BitmapTextButton
  67. try:
  68. import wx.lib.agw.customtreectrl as CT
  69. except ImportError:
  70. import wx.lib.customtreectrl as CT
  71. if wxPythonPhoenix:
  72. from wx import Validator as Validator
  73. else:
  74. from wx import PyValidator as Validator
  75. from grass.script import core as grass
  76. from grass.pydispatch.signal import Signal
  77. from core import globalvar
  78. from core.gcmd import GMessage, GError
  79. from core.debug import Debug
  80. from gui_core.wrap import Button, SearchCtrl, StaticText, StaticBox, \
  81. TextCtrl, Menu, Rect, EmptyBitmap, ListCtrl, NewId
  82. class NotebookController:
  83. """Provides handling of notebook page names.
  84. Translates page names to page indices.
  85. Class is aggregated in notebook subclasses.
  86. Notebook subclasses must delegate methods to controller.
  87. Methods inherited from notebook class must be delegated explicitly
  88. and other methods can be delegated by @c __getattr__.
  89. """
  90. def __init__(self, classObject, widget):
  91. """
  92. :param classObject: notebook class name (object, i.e. FlatNotebook)
  93. :param widget: notebook instance
  94. """
  95. self.notebookPages = {}
  96. self.classObject = classObject
  97. self.widget = widget
  98. self.highlightedTextEnd = _(" (...)")
  99. self.BindPageChanged()
  100. def BindPageChanged(self):
  101. """Binds page changed event."""
  102. self.widget.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnRemoveHighlight)
  103. def AddPage(self, **kwargs):
  104. """Add a new page
  105. """
  106. if 'name' in kwargs:
  107. self.notebookPages[kwargs['name']] = kwargs['page']
  108. del kwargs['name']
  109. self.classObject.AddPage(self.widget, **kwargs)
  110. def InsertPage(self, **kwargs):
  111. """Insert a new page
  112. """
  113. if 'name' in kwargs:
  114. self.notebookPages[kwargs['name']] = kwargs['page']
  115. del kwargs['name']
  116. try:
  117. self.classObject.InsertPage(self.widget, **kwargs)
  118. except TypeError as e: # documentation says 'index', but certain versions of wx require 'n'
  119. kwargs['n'] = kwargs['index']
  120. del kwargs['index']
  121. self.classObject.InsertPage(self.widget, **kwargs)
  122. def DeletePage(self, page):
  123. """Delete page
  124. :param page: name
  125. :return: True if page was deleted, False if not exists
  126. """
  127. delPageIndex = self.GetPageIndexByName(page)
  128. if delPageIndex != -1:
  129. ret = self.classObject.DeletePage(self.widget, delPageIndex)
  130. if ret:
  131. del self.notebookPages[page]
  132. return ret
  133. else:
  134. return False
  135. def RemovePage(self, page):
  136. """Delete page without deleting the associated window.
  137. :param page: name
  138. :return: True if page was deleted, False if not exists
  139. """
  140. delPageIndex = self.GetPageIndexByName(page)
  141. if delPageIndex != -1:
  142. ret = self.classObject.RemovePage(self.widget, delPageIndex)
  143. if ret:
  144. del self.notebookPages[page]
  145. return ret
  146. else:
  147. return False
  148. def SetSelectionByName(self, page):
  149. """Set active notebook page.
  150. :param page: name, eg. 'layers', 'output', 'search', 'pyshell', 'nviz'
  151. (depends on concrete notebook instance)
  152. """
  153. idx = self.GetPageIndexByName(page)
  154. if self.classObject.GetSelection(self.widget) != idx:
  155. self.classObject.SetSelection(self.widget, idx)
  156. self.RemoveHighlight(idx)
  157. def OnRemoveHighlight(self, event):
  158. """Highlighted tab name should be removed."""
  159. page = event.GetSelection()
  160. self.RemoveHighlight(page)
  161. event.Skip()
  162. def RemoveHighlight(self, page):
  163. """Removes highlight string from notebook tab name if necessary.
  164. :param page: index
  165. """
  166. text = self.classObject.GetPageText(self.widget, page)
  167. if text.endswith(self.highlightedTextEnd):
  168. text = text.replace(self.highlightedTextEnd, '')
  169. self.classObject.SetPageText(self.widget, page, text)
  170. def GetPageIndexByName(self, page):
  171. """Get notebook page index
  172. :param page: name
  173. """
  174. if page not in self.notebookPages:
  175. return -1
  176. for pageIndex in range(self.classObject.GetPageCount(self.widget)):
  177. if self.notebookPages[page] == self.classObject.GetPage(
  178. self.widget, pageIndex):
  179. break
  180. return pageIndex
  181. def HighlightPageByName(self, page):
  182. pageIndex = self.GetPageIndexByName(page)
  183. self.HighlightPage(pageIndex)
  184. def HighlightPage(self, index):
  185. if self.classObject.GetSelection(self.widget) != index:
  186. text = self.classObject.GetPageText(self.widget, index)
  187. if not text.endswith(self.highlightedTextEnd):
  188. text += self.highlightedTextEnd
  189. self.classObject.SetPageText(self.widget, index, text)
  190. def SetPageImage(self, page, index):
  191. """Sets image index for page
  192. :param page: page name
  193. :param index: image index (in wx.ImageList)
  194. """
  195. pageIndex = self.GetPageIndexByName(page)
  196. self.classObject.SetPageImage(self.widget, pageIndex, index)
  197. class FlatNotebookController(NotebookController):
  198. """Controller specialized for FN.FlatNotebook subclasses"""
  199. def __init__(self, classObject, widget):
  200. NotebookController.__init__(self, classObject, widget)
  201. def BindPageChanged(self):
  202. self.widget.Bind(
  203. FN.EVT_FLATNOTEBOOK_PAGE_CHANGED,
  204. self.OnRemoveHighlight)
  205. def GetPageIndexByName(self, page):
  206. """Get notebook page index
  207. :param page: name
  208. """
  209. if page not in self.notebookPages:
  210. return -1
  211. return self.classObject.GetPageIndex(
  212. self.widget, self.notebookPages[page])
  213. def InsertPage(self, **kwargs):
  214. """Insert a new page
  215. """
  216. if 'name' in kwargs:
  217. self.notebookPages[kwargs['name']] = kwargs['page']
  218. del kwargs['name']
  219. kwargs['indx'] = kwargs['index']
  220. del kwargs['index']
  221. self.classObject.InsertPage(self.widget, **kwargs)
  222. class GNotebook(FN.FlatNotebook):
  223. """Generic notebook widget.
  224. Enables advanced style settings.
  225. Problems with hidden tabs and does not respect system colors (native look).
  226. """
  227. def __init__(self, parent, style, **kwargs):
  228. if globalvar.hasAgw:
  229. FN.FlatNotebook.__init__(self, parent, id=wx.ID_ANY,
  230. agwStyle=style, **kwargs)
  231. else:
  232. FN.FlatNotebook.__init__(self, parent, id=wx.ID_ANY,
  233. style=style, **kwargs)
  234. self.controller = FlatNotebookController(classObject=FN.FlatNotebook,
  235. widget=self)
  236. def AddPage(self, **kwargs):
  237. """@copydoc NotebookController::AddPage()"""
  238. self.controller.AddPage(**kwargs)
  239. def InsertNBPage(self, **kwargs):
  240. """@copydoc NotebookController::InsertPage()"""
  241. self.controller.InsertPage(**kwargs)
  242. def DeleteNBPage(self, page):
  243. """@copydoc NotebookController::DeletePage()"""
  244. return self.controller.DeletePage(page)
  245. def RemoveNBPage(self, page):
  246. """@copydoc NotebookController::RemovePage()"""
  247. return self.controller.RemovePage(page)
  248. def SetPageImage(self, page, index):
  249. """Does nothing because we don't want images for this style"""
  250. pass
  251. def __getattr__(self, name):
  252. return getattr(self.controller, name)
  253. class FormNotebook(wx.Notebook):
  254. """Notebook widget.
  255. Respects native look.
  256. """
  257. def __init__(self, parent, style):
  258. wx.Notebook.__init__(self, parent, id=wx.ID_ANY, style=style)
  259. self.controller = NotebookController(classObject=wx.Notebook,
  260. widget=self)
  261. def AddPage(self, **kwargs):
  262. """@copydoc NotebookController::AddPage()"""
  263. self.controller.AddPage(**kwargs)
  264. def InsertNBPage(self, **kwargs):
  265. """@copydoc NotebookController::InsertPage()"""
  266. self.controller.InsertPage(**kwargs)
  267. def DeleteNBPage(self, page):
  268. """@copydoc NotebookController::DeletePage()"""
  269. return self.controller.DeletePage(page)
  270. def RemoveNBPage(self, page):
  271. """@copydoc NotebookController::RemovePage()"""
  272. return self.controller.RemovePage(page)
  273. def SetPageImage(self, page, index):
  274. """@copydoc NotebookController::SetPageImage()"""
  275. return self.controller.SetPageImage(page, index)
  276. def __getattr__(self, name):
  277. return getattr(self.controller, name)
  278. class FormListbook(wx.Listbook):
  279. """Notebook widget.
  280. Respects native look.
  281. """
  282. def __init__(self, parent, style):
  283. wx.Listbook.__init__(self, parent, id=wx.ID_ANY, style=style)
  284. self.controller = NotebookController(classObject=wx.Listbook,
  285. widget=self)
  286. def AddPage(self, **kwargs):
  287. """@copydoc NotebookController::AddPage()"""
  288. self.controller.AddPage(**kwargs)
  289. def InsertPage_(self, **kwargs):
  290. """@copydoc NotebookController::InsertPage()"""
  291. self.controller.InsertPage(**kwargs)
  292. def DeletePage(self, page):
  293. """@copydoc NotebookController::DeletePage()"""
  294. return self.controller.DeletePage(page)
  295. def RemovePage(self, page):
  296. """@copydoc NotebookController::RemovePage()"""
  297. return self.controller.RemovePage(page)
  298. def SetPageImage(self, page, index):
  299. """@copydoc NotebookController::SetPageImage()"""
  300. return self.controller.SetPageImage(page, index)
  301. def __getattr__(self, name):
  302. return getattr(self.controller, name)
  303. class ScrolledPanel(SP.ScrolledPanel):
  304. """Custom ScrolledPanel to avoid strange behaviour concerning focus"""
  305. def __init__(self, parent, style=wx.TAB_TRAVERSAL):
  306. SP.ScrolledPanel.__init__(self, parent=parent, id=wx.ID_ANY,
  307. style=style)
  308. def OnChildFocus(self, event):
  309. pass
  310. class NumTextCtrl(TextCtrl):
  311. """Class derived from wx.TextCtrl for numerical values only"""
  312. def __init__(self, parent, **kwargs):
  313. ## self.precision = kwargs.pop('prec')
  314. TextCtrl.__init__(self, parent=parent,
  315. validator=NTCValidator(flag='DIGIT_ONLY'),
  316. **kwargs)
  317. def SetValue(self, value):
  318. super(NumTextCtrl, self).SetValue(str(value))
  319. def GetValue(self):
  320. val = super(NumTextCtrl, self).GetValue()
  321. if val == '':
  322. val = '0'
  323. try:
  324. return float(val)
  325. except ValueError:
  326. val = ''.join(''.join(val.split('-')).split('.'))
  327. return float(val)
  328. def SetRange(self, min, max):
  329. pass
  330. class FloatSlider(wx.Slider):
  331. """Class derived from wx.Slider for floats"""
  332. def __init__(self, **kwargs):
  333. Debug.msg(1, "FloatSlider.__init__()")
  334. wx.Slider.__init__(self, **kwargs)
  335. self.coef = 1.
  336. # init range
  337. self.minValueOrig = 0
  338. self.maxValueOrig = 1
  339. def SetValue(self, value):
  340. value *= self.coef
  341. if abs(value) < 1 and value != 0:
  342. while abs(value) < 1:
  343. value *= 100
  344. self.coef *= 100
  345. super(FloatSlider, self).SetRange(self.minValueOrig * self.coef,
  346. self.maxValueOrig * self.coef)
  347. super(FloatSlider, self).SetValue(value)
  348. Debug.msg(4, "FloatSlider.SetValue(): value = %f" % value)
  349. def SetRange(self, minValue, maxValue):
  350. self.coef = 1.
  351. self.minValueOrig = minValue
  352. self.maxValueOrig = maxValue
  353. if abs(minValue) < 1 or abs(maxValue) < 1:
  354. while (abs(minValue) < 1 and minValue != 0) or (
  355. abs(maxValue) < 1 and maxValue != 0):
  356. minValue *= 100
  357. maxValue *= 100
  358. self.coef *= 100
  359. super(
  360. FloatSlider,
  361. self).SetValue(
  362. super(
  363. FloatSlider,
  364. self).GetValue() *
  365. self.coef)
  366. super(FloatSlider, self).SetRange(minValue, maxValue)
  367. Debug.msg(
  368. 4, "FloatSlider.SetRange(): minValue = %f, maxValue = %f" %
  369. (minValue, maxValue))
  370. def GetValue(self):
  371. val = super(FloatSlider, self).GetValue()
  372. Debug.msg(4, "FloatSlider.GetValue(): value = %f" % (val / self.coef))
  373. return val / self.coef
  374. class SymbolButton(BitmapTextButton):
  375. """Button with symbol and label."""
  376. def __init__(self, parent, usage, label, **kwargs):
  377. """Constructor
  378. :param parent: parent (usually wx.Panel)
  379. :param usage: determines usage and picture
  380. :param label: displayed label
  381. """
  382. size = (15, 15)
  383. buffer = EmptyBitmap(*size)
  384. BitmapTextButton.__init__(self, parent=parent, label=" " + label,
  385. bitmap=buffer, **kwargs)
  386. dc = wx.MemoryDC()
  387. dc.SelectObject(buffer)
  388. maskColor = wx.Colour(255, 255, 255)
  389. dc.SetBrush(wx.Brush(maskColor))
  390. dc.Clear()
  391. if usage == 'record':
  392. self.DrawRecord(dc, size)
  393. elif usage == 'stop':
  394. self.DrawStop(dc, size)
  395. elif usage == 'play':
  396. self.DrawPlay(dc, size)
  397. elif usage == 'pause':
  398. self.DrawPause(dc, size)
  399. if sys.platform != "win32":
  400. buffer.SetMaskColour(maskColor)
  401. self.SetBitmapLabel(buffer)
  402. dc.SelectObject(wx.NullBitmap)
  403. def DrawRecord(self, dc, size):
  404. """Draw record symbol"""
  405. dc.SetBrush(wx.Brush(wx.Colour(255, 0, 0)))
  406. dc.DrawCircle(size[0] / 2, size[1] / 2, size[0] / 2)
  407. def DrawStop(self, dc, size):
  408. """Draw stop symbol"""
  409. dc.SetBrush(wx.Brush(wx.Colour(50, 50, 50)))
  410. dc.DrawRectangle(0, 0, size[0], size[1])
  411. def DrawPlay(self, dc, size):
  412. """Draw play symbol"""
  413. dc.SetBrush(wx.Brush(wx.Colour(0, 255, 0)))
  414. points = (wx.Point(0, 0), wx.Point(0, size[1]), wx.Point(size[0],
  415. size[1] / 2))
  416. dc.DrawPolygon(points)
  417. def DrawPause(self, dc, size):
  418. """Draw pause symbol"""
  419. dc.SetBrush(wx.Brush(wx.Colour(50, 50, 50)))
  420. dc.DrawRectangle(0, 0, 2 * size[0] / 5, size[1])
  421. dc.DrawRectangle(3 * size[0] / 5, 0, 2 * size[0] / 5, size[1])
  422. class StaticWrapText(GenStaticText):
  423. """A Static Text widget that wraps its text to fit parents width,
  424. enlarging its height if necessary."""
  425. def __init__(self, parent, id=wx.ID_ANY,
  426. label='', margin=0, *args, **kwds):
  427. self._margin = margin
  428. self._initialLabel = label
  429. self.init = False
  430. GenStaticText.__init__(self, parent, id, label, *args, **kwds)
  431. self.Bind(wx.EVT_SIZE, self.OnSize)
  432. def DoGetBestSize(self):
  433. """Overriden method which reports widget's best size."""
  434. if not self.init:
  435. self.init = True
  436. self._updateLabel()
  437. parent = self.GetParent()
  438. newExtent = wx.ClientDC(parent).GetMultiLineTextExtent(self.GetLabel())
  439. # when starting, width is very small and height is big which creates
  440. # very high windows
  441. if newExtent[0] < newExtent[1]:
  442. return (0, 0)
  443. return newExtent[:2]
  444. def OnSize(self, event):
  445. self._updateLabel()
  446. event.Skip()
  447. def _updateLabel(self):
  448. """Calculates size of wrapped label"""
  449. parent = self.GetParent()
  450. newLabel = wordwrap(text=self._initialLabel, width=parent.GetSize()[0],
  451. dc=wx.ClientDC(parent), breakLongWords=True,
  452. margin=self._margin)
  453. GenStaticText.SetLabel(self, newLabel)
  454. def SetLabel(self, label):
  455. self._initialLabel = label
  456. self._updateLabel()
  457. class BaseValidator(Validator):
  458. def __init__(self):
  459. Validator.__init__(self)
  460. self.Bind(wx.EVT_TEXT, self.OnText)
  461. def OnText(self, event):
  462. """Do validation"""
  463. self.Validate()
  464. event.Skip()
  465. def Validate(self):
  466. """Validate input"""
  467. textCtrl = self.GetWindow()
  468. text = textCtrl.GetValue()
  469. if text:
  470. try:
  471. self.type(text)
  472. except ValueError:
  473. self._notvalid()
  474. return False
  475. self._valid()
  476. return True
  477. def _notvalid(self):
  478. textCtrl = self.GetWindow()
  479. textCtrl.SetBackgroundColour("grey")
  480. textCtrl.SetFocus()
  481. textCtrl.Refresh()
  482. def _valid(self):
  483. textCtrl = self.GetWindow()
  484. sysColor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
  485. textCtrl.SetBackgroundColour(sysColor)
  486. textCtrl.Refresh()
  487. return True
  488. def TransferToWindow(self):
  489. return True # Prevent wxDialog from complaining.
  490. def TransferFromWindow(self):
  491. return True # Prevent wxDialog from complaining.
  492. class CoordinatesValidator(BaseValidator):
  493. """Validator for coordinates input (list of floats separated by comma)"""
  494. def __init__(self):
  495. BaseValidator.__init__(self)
  496. def Validate(self):
  497. """Validate input"""
  498. textCtrl = self.GetWindow()
  499. text = textCtrl.GetValue()
  500. if text:
  501. try:
  502. text = text.split(',')
  503. for t in text:
  504. float(t)
  505. if len(text) % 2 != 0:
  506. return False
  507. except ValueError:
  508. self._notvalid()
  509. return False
  510. self._valid()
  511. return True
  512. def Clone(self):
  513. """Clone validator"""
  514. return CoordinatesValidator()
  515. class IntegerValidator(BaseValidator):
  516. """Validator for floating-point input"""
  517. def __init__(self):
  518. BaseValidator.__init__(self)
  519. self.type = int
  520. def Clone(self):
  521. """Clone validator"""
  522. return IntegerValidator()
  523. class FloatValidator(BaseValidator):
  524. """Validator for floating-point input"""
  525. def __init__(self):
  526. BaseValidator.__init__(self)
  527. self.type = float
  528. def Clone(self):
  529. """Clone validator"""
  530. return FloatValidator()
  531. class EmailValidator(BaseValidator):
  532. """Validator for email input"""
  533. def __init__(self):
  534. BaseValidator.__init__(self)
  535. def Validate(self):
  536. """Validate input"""
  537. textCtrl = self.GetWindow()
  538. text = textCtrl.GetValue()
  539. if text:
  540. if re.match(r'\b[\w.-]+@[\w.-]+.\w{2,4}\b', text) is None:
  541. self._notvalid()
  542. return False
  543. self._valid()
  544. return True
  545. def Clone(self):
  546. """Clone validator"""
  547. return EmailValidator()
  548. class TimeISOValidator(BaseValidator):
  549. """Validator for time ISO format (YYYY-MM-DD) input"""
  550. def __init__(self):
  551. BaseValidator.__init__(self)
  552. def Validate(self):
  553. """Validate input"""
  554. textCtrl = self.GetWindow()
  555. text = textCtrl.GetValue()
  556. if text:
  557. try:
  558. datetime.strptime(text, '%Y-%m-%d')
  559. except:
  560. self._notvalid()
  561. return False
  562. self._valid()
  563. return True
  564. def Clone(self):
  565. """Clone validator"""
  566. return TimeISOValidator()
  567. class NTCValidator(Validator):
  568. """validates input in textctrls, taken from wxpython demo"""
  569. def __init__(self, flag=None):
  570. Validator.__init__(self)
  571. self.flag = flag
  572. self.Bind(wx.EVT_CHAR, self.OnChar)
  573. def Clone(self):
  574. return NTCValidator(self.flag)
  575. def OnChar(self, event):
  576. key = event.GetKeyCode()
  577. if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255:
  578. event.Skip()
  579. return
  580. if self.flag == 'DIGIT_ONLY' and chr(key) in string.digits + '.-':
  581. event.Skip()
  582. return
  583. if not wx.Validator_IsSilent():
  584. wx.Bell()
  585. # Returning without calling even.Skip eats the event before it
  586. # gets to the text control
  587. return
  588. class SimpleValidator(Validator):
  589. """This validator is used to ensure that the user has entered something
  590. into the text object editor dialog's text field.
  591. """
  592. def __init__(self, callback):
  593. """Standard constructor.
  594. """
  595. Validator.__init__(self)
  596. self.callback = callback
  597. def Clone(self):
  598. """Standard cloner.
  599. Note that every validator must implement the Clone() method.
  600. """
  601. return SimpleValidator(self.callback)
  602. def Validate(self, win):
  603. """Validate the contents of the given text control.
  604. """
  605. ctrl = self.GetWindow()
  606. text = ctrl.GetValue()
  607. if len(text) == 0:
  608. self.callback(ctrl)
  609. return False
  610. else:
  611. return True
  612. def TransferToWindow(self):
  613. """Transfer data from validator to window.
  614. The default implementation returns False, indicating that an
  615. error occurred. We simply return True, as we don't do any data
  616. transfer.
  617. """
  618. return True # Prevent wxDialog from complaining.
  619. def TransferFromWindow(self):
  620. """Transfer data from window to validator.
  621. The default implementation returns False, indicating that an
  622. error occurred. We simply return True, as we don't do any data
  623. transfer.
  624. """
  625. return True # Prevent wxDialog from complaining.
  626. class GenericValidator(Validator):
  627. """This validator checks condition and calls callback
  628. in case the condition is not fulfilled.
  629. """
  630. def __init__(self, condition, callback):
  631. """Standard constructor.
  632. :param condition: function which accepts string value and returns T/F
  633. :param callback: function which is called when condition is not fulfilled
  634. """
  635. Validator.__init__(self)
  636. self._condition = condition
  637. self._callback = callback
  638. def Clone(self):
  639. """Standard cloner.
  640. Note that every validator must implement the Clone() method.
  641. """
  642. return GenericValidator(self._condition, self._callback)
  643. def Validate(self, win):
  644. """Validate the contents of the given text control.
  645. """
  646. ctrl = self.GetWindow()
  647. text = ctrl.GetValue()
  648. if not self._condition(text):
  649. self._callback(ctrl)
  650. return False
  651. else:
  652. return True
  653. def TransferToWindow(self):
  654. """Transfer data from validator to window.
  655. """
  656. return True # Prevent wxDialog from complaining.
  657. def TransferFromWindow(self):
  658. """Transfer data from window to validator.
  659. """
  660. return True # Prevent wxDialog from complaining.
  661. class MapValidator(GenericValidator):
  662. """Validator for map name input
  663. See G_legal_filename()
  664. """
  665. def __init__(self):
  666. def _mapNameValidationFailed(ctrl):
  667. message = _(
  668. "Name <%(name)s> is not a valid name for GRASS map. "
  669. "Please use only ASCII characters excluding %(chars)s "
  670. "and space.") % {
  671. 'name': ctrl.GetValue(),
  672. 'chars': '/"\'@,=*~'}
  673. GError(message, caption=_("Invalid name"))
  674. GenericValidator.__init__(self,
  675. grass.legal_name,
  676. _mapNameValidationFailed)
  677. class SingleSymbolPanel(wx.Panel):
  678. """Panel for displaying one symbol.
  679. Changes background when selected. Assumes that parent will catch
  680. events emitted on mouse click. Used in gui_core::dialog::SymbolDialog.
  681. """
  682. def __init__(self, parent, symbolPath):
  683. """Panel constructor
  684. Signal symbolSelectionChanged - symbol selected
  685. - attribute 'name' (symbol name)
  686. - attribute 'doubleClick' (underlying cause)
  687. :param parent: parent (gui_core::dialog::SymbolDialog)
  688. :param symbolPath: absolute path to symbol
  689. """
  690. self.symbolSelectionChanged = Signal(
  691. 'SingleSymbolPanel.symbolSelectionChanged')
  692. wx.Panel.__init__(self, parent, id=wx.ID_ANY, style=wx.BORDER_RAISED)
  693. self.SetName(os.path.splitext(os.path.basename(symbolPath))[0])
  694. self.sBmp = wx.StaticBitmap(self, wx.ID_ANY, wx.Bitmap(symbolPath))
  695. self.selected = False
  696. self.selectColor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
  697. self.deselectColor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
  698. sizer = wx.BoxSizer()
  699. sizer.Add(
  700. self.sBmp,
  701. proportion=0,
  702. flag=wx.ALL | wx.ALIGN_CENTER,
  703. border=5)
  704. self.SetBackgroundColour(self.deselectColor)
  705. self.SetMinSize(self.GetBestSize())
  706. self.SetSizerAndFit(sizer)
  707. # binding to both (staticBitmap, Panel) necessary
  708. self.sBmp.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
  709. self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
  710. self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
  711. self.sBmp.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
  712. def OnLeftDown(self, event):
  713. """Panel selected, background changes"""
  714. self.selected = True
  715. self.SetBackgroundColour(self.selectColor)
  716. self.Refresh()
  717. event.Skip()
  718. self.symbolSelectionChanged.emit(
  719. name=self.GetName(), doubleClick=False)
  720. def OnDoubleClick(self, event):
  721. self.symbolSelectionChanged.emit(name=self.GetName(), doubleClick=True)
  722. def Deselect(self):
  723. """Panel deselected, background changes back to default"""
  724. self.selected = False
  725. self.SetBackgroundColour(self.deselectColor)
  726. self.Refresh()
  727. def Select(self):
  728. """Select panel, no event emitted"""
  729. self.selected = True
  730. self.SetBackgroundColour(self.selectColor)
  731. self.Refresh()
  732. class GListCtrl(ListCtrl, listmix.ListCtrlAutoWidthMixin,
  733. listmix.CheckListCtrlMixin):
  734. """Generic ListCtrl with popup menu to select/deselect all
  735. items"""
  736. def __init__(self, parent):
  737. self.parent = parent
  738. ListCtrl.__init__(self, parent, id=wx.ID_ANY,
  739. style=wx.LC_REPORT)
  740. listmix.CheckListCtrlMixin.__init__(self)
  741. # setup mixins
  742. listmix.ListCtrlAutoWidthMixin.__init__(self)
  743. self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnPopupMenu) # wxMSW
  744. self.Bind(wx.EVT_RIGHT_UP, self.OnPopupMenu) # wxGTK
  745. def OnPopupMenu(self, event):
  746. """Show popup menu"""
  747. if self.GetItemCount() < 1:
  748. return
  749. if not hasattr(self, "popupDataID1"):
  750. self.popupDataID1 = NewId()
  751. self.popupDataID2 = NewId()
  752. self.Bind(wx.EVT_MENU, self.OnSelectAll, id=self.popupDataID1)
  753. self.Bind(wx.EVT_MENU, self.OnSelectNone, id=self.popupDataID2)
  754. # generate popup-menu
  755. menu = Menu()
  756. menu.Append(self.popupDataID1, _("Select all"))
  757. menu.Append(self.popupDataID2, _("Deselect all"))
  758. self.PopupMenu(menu)
  759. menu.Destroy()
  760. def OnSelectAll(self, event):
  761. """Select all items"""
  762. item = -1
  763. while True:
  764. item = self.GetNextItem(item)
  765. if item == -1:
  766. break
  767. self.CheckItem(item, True)
  768. event.Skip()
  769. def OnSelectNone(self, event):
  770. """Deselect items"""
  771. item = -1
  772. while True:
  773. item = self.GetNextItem(item, wx.LIST_STATE_SELECTED)
  774. if item == -1:
  775. break
  776. self.CheckItem(item, False)
  777. event.Skip()
  778. def GetData(self, checked=None):
  779. """Get list data"""
  780. data = []
  781. checkedList = []
  782. item = -1
  783. while True:
  784. row = []
  785. item = self.GetNextItem(item)
  786. if item == -1:
  787. break
  788. isChecked = self.IsChecked(item)
  789. if checked is not None and checked != isChecked:
  790. continue
  791. checkedList.append(isChecked)
  792. for i in range(self.GetColumnCount()):
  793. row.append(self.GetItem(item, i).GetText())
  794. row.append(item)
  795. data.append(tuple(row))
  796. if checked is not None:
  797. return tuple(data)
  798. else:
  799. return (tuple(data), tuple(checkedList))
  800. def LoadData(self, data=None, selectOne=True):
  801. """Load data into list"""
  802. self.DeleteAllItems()
  803. if data is None:
  804. return
  805. idx = 0
  806. for item in data:
  807. index = self.InsertItem(idx, str(item[0]))
  808. for i in range(1, self.GetColumnCount()):
  809. self.SetItem(index, i, item[i])
  810. idx += 1
  811. # check by default only on one item
  812. if len(data) == 1 and selectOne:
  813. self.CheckItem(index, True)
  814. class SearchModuleWidget(wx.Panel):
  815. """Search module widget (used e.g. in SearchModuleWindow)
  816. Signals:
  817. moduleSelected - attribute 'name' is module name
  818. showSearchResult - attribute 'result' is a node (representing module)
  819. showNotification - attribute 'message'
  820. """
  821. def __init__(self, parent, model,
  822. showChoice=True, showTip=False, **kwargs):
  823. self._showTip = showTip
  824. self._showChoice = showChoice
  825. self._model = model
  826. self._results = [] # list of found nodes
  827. self._resultIndex = -1
  828. self._searchKeys = ['description', 'keywords', 'command']
  829. self._oldValue = ''
  830. self.moduleSelected = Signal('SearchModuleWidget.moduleSelected')
  831. self.showSearchResult = Signal('SearchModuleWidget.showSearchResult')
  832. self.showNotification = Signal('SearchModuleWidget.showNotification')
  833. wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY, **kwargs)
  834. # self._box = wx.StaticBox(parent = self, id = wx.ID_ANY,
  835. # label = " %s " % _("Find module - (press Enter for next match)"))
  836. if sys.platform == 'win32':
  837. self._search = TextCtrl(
  838. parent=self, id=wx.ID_ANY, size=(-1, 25),
  839. style=wx.TE_PROCESS_ENTER)
  840. else:
  841. self._search = SearchCtrl(
  842. parent=self, id=wx.ID_ANY, size=(-1, 25),
  843. style=wx.TE_PROCESS_ENTER)
  844. self._search.SetDescriptiveText(_('Fulltext search'))
  845. self._search.SetToolTip(
  846. _("Type to search in all modules. Press Enter for next match."))
  847. self._search.Bind(wx.EVT_TEXT, self.OnSearchModule)
  848. self._search.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)
  849. if self._showTip:
  850. self._searchTip = StaticWrapText(parent=self, id=wx.ID_ANY,
  851. label="Choose a module", size=(-1, 35))
  852. if self._showChoice:
  853. self._searchChoice = wx.Choice(parent=self, id=wx.ID_ANY)
  854. self._searchChoice.SetItems(
  855. self._searchModule(
  856. keys=['command'], value=''))
  857. self._searchChoice.Bind(wx.EVT_CHOICE, self.OnSelectModule)
  858. self._layout()
  859. def _layout(self):
  860. """Do layout"""
  861. sizer = wx.BoxSizer(wx.HORIZONTAL)
  862. boxSizer = wx.BoxSizer(wx.VERTICAL)
  863. boxSizer.Add(self._search,
  864. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND | wx.BOTTOM,
  865. border=5)
  866. if self._showChoice:
  867. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  868. hSizer.Add(self._searchChoice,
  869. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND | wx.BOTTOM,
  870. border=5)
  871. hSizer.AddStretchSpacer()
  872. boxSizer.Add(hSizer, flag=wx.EXPAND)
  873. if self._showTip:
  874. boxSizer.Add(self._searchTip,
  875. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  876. sizer.Add(boxSizer, proportion=1)
  877. self.SetSizer(sizer)
  878. sizer.Fit(self)
  879. def OnEnter(self, event):
  880. """Process EVT_TEXT_ENTER to show search results"""
  881. self._showSearchResult()
  882. event.Skip()
  883. def _showSearchResult(self):
  884. if self._results:
  885. self._resultIndex += 1
  886. if self._resultIndex == len(self._results):
  887. self._resultIndex = 0
  888. self.showSearchResult.emit(result=self._results[self._resultIndex])
  889. def OnSearchModule(self, event):
  890. """Search module by keywords or description"""
  891. value = self._search.GetValue()
  892. if value == self._oldValue:
  893. event.Skip()
  894. return
  895. self._oldValue = value
  896. if len(value) <= 2:
  897. if len(value) == 0: # reset
  898. commands = self._searchModule(keys=['command'], value='')
  899. else:
  900. self.showNotification.emit(
  901. message=_("Searching, please type more characters."))
  902. return
  903. else:
  904. commands = self._searchModule(keys=self._searchKeys, value=value)
  905. if self._showChoice:
  906. self._searchChoice.SetItems(commands)
  907. if commands:
  908. self._searchChoice.SetSelection(0)
  909. label = _("%d modules match") % len(commands)
  910. if self._showTip:
  911. self._searchTip.SetLabel(label)
  912. self.showNotification.emit(message=label)
  913. event.Skip()
  914. def _searchModule(self, keys, value):
  915. """Search modules by keys
  916. :param keys: list of keys
  917. :param value: patter to match
  918. """
  919. nodes = set()
  920. for key in keys:
  921. nodes.update(self._model.SearchNodes(key=key, value=value))
  922. nodes = list(nodes)
  923. nodes.sort(key=lambda node: self._model.GetIndexOfNode(node))
  924. self._results = nodes
  925. self._resultIndex = -1
  926. commands = sorted([node.data['command']
  927. for node in nodes if node.data['command']])
  928. return commands
  929. def OnSelectModule(self, event):
  930. """Module selected from choice, update command prompt"""
  931. cmd = self._searchChoice.GetStringSelection()
  932. self.moduleSelected.emit(name=cmd)
  933. if self._showTip:
  934. for module in self._results:
  935. if cmd == module.data['command']:
  936. self._searchTip.SetLabel(module.data['description'])
  937. break
  938. def Reset(self):
  939. """Reset widget"""
  940. self._search.SetValue('')
  941. if self._showTip:
  942. self._searchTip.SetLabel('Choose a module')
  943. class ManageSettingsWidget(wx.Panel):
  944. """Widget which allows loading and saving settings into file."""
  945. def __init__(self, parent, settingsFile):
  946. """
  947. Signals:
  948. settingsChanged - called when users changes setting
  949. - attribute 'data' with chosen setting data
  950. settingsSaving - called when settings are saving
  951. - attribute 'name' with chosen settings name
  952. settingsLoaded - called when settings are loaded
  953. - attribute 'settings' is dict with loaded settings
  954. {nameofsetting : settingdata, ....}
  955. :param settingsFile: path to file, where settings will be saved and loaded from
  956. """
  957. self.settingsFile = settingsFile
  958. self.settingsChanged = Signal('ManageSettingsWidget.settingsChanged')
  959. self.settingsSaving = Signal('ManageSettingsWidget.settingsSaving')
  960. self.settingsLoaded = Signal('ManageSettingsWidget.settingsLoaded')
  961. wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
  962. self.settingsBox = StaticBox(parent=self, id=wx.ID_ANY,
  963. label=" %s " % _("Profiles"))
  964. self.settingsChoice = wx.Choice(parent=self, id=wx.ID_ANY)
  965. self.settingsChoice.Bind(wx.EVT_CHOICE, self.OnSettingsChanged)
  966. self.btnSettingsSave = Button(parent=self, id=wx.ID_SAVE)
  967. self.btnSettingsSave.Bind(wx.EVT_BUTTON, self.OnSettingsSave)
  968. self.btnSettingsSave.SetToolTip(_("Save current settings"))
  969. self.btnSettingsDel = Button(parent=self, id=wx.ID_REMOVE)
  970. self.btnSettingsDel.Bind(wx.EVT_BUTTON, self.OnSettingsDelete)
  971. self.btnSettingsSave.SetToolTip(
  972. _("Delete currently selected settings"))
  973. # escaping with '$' character - index in self.esc_chars
  974. self.e_char_i = 0
  975. self.esc_chars = ['$', ';']
  976. self._settings = self._loadSettings() # -> self.settingsChoice.SetItems()
  977. self.settingsLoaded.emit(settings=self._settings)
  978. self.data_to_save = []
  979. self._layout()
  980. self.SetSizer(self.settingsSizer)
  981. self.settingsSizer.Fit(self)
  982. def _layout(self):
  983. self.settingsSizer = wx.StaticBoxSizer(self.settingsBox, wx.HORIZONTAL)
  984. self.settingsSizer.Add(
  985. StaticText(
  986. parent=self,
  987. id=wx.ID_ANY,
  988. label=_("Load:")),
  989. flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.LEFT,
  990. border=5)
  991. self.settingsSizer.Add(
  992. self.settingsChoice,
  993. proportion=1,
  994. flag=wx.EXPAND | wx.BOTTOM,
  995. border=3)
  996. self.settingsSizer.Add(self.btnSettingsSave,
  997. flag=wx.LEFT | wx.RIGHT | wx.BOTTOM, border=3)
  998. self.settingsSizer.Add(self.btnSettingsDel,
  999. flag=wx.RIGHT | wx.BOTTOM, border=3)
  1000. def OnSettingsChanged(self, event):
  1001. """Load named settings"""
  1002. name = event.GetString()
  1003. if name not in self._settings:
  1004. GError(parent=self,
  1005. message=_("Settings <%s> not found") % name)
  1006. return
  1007. data = self._settings[name]
  1008. self.settingsChanged.emit(data=data)
  1009. def GetSettings(self):
  1010. """Load named settings"""
  1011. return self._settings.copy()
  1012. def OnSettingsSave(self, event):
  1013. """Save settings"""
  1014. dlg = wx.TextEntryDialog(parent=self,
  1015. message=_("Name:"),
  1016. caption=_("Save settings"))
  1017. if dlg.ShowModal() == wx.ID_OK:
  1018. name = dlg.GetValue()
  1019. if not name:
  1020. GMessage(parent=self,
  1021. message=_("Name not given, settings is not saved."))
  1022. else:
  1023. self.settingsSaving.emit(name=name)
  1024. dlg.Destroy()
  1025. def SaveSettings(self, name):
  1026. # check if settings item already exists
  1027. if name in self._settings:
  1028. dlgOwt = wx.MessageDialog(
  1029. self,
  1030. message=_(
  1031. "Settings <%s> already exists. "
  1032. "Do you want to overwrite the settings?") %
  1033. name,
  1034. caption=_("Save settings"),
  1035. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  1036. if dlgOwt.ShowModal() != wx.ID_YES:
  1037. dlgOwt.Destroy()
  1038. return
  1039. if self.data_to_save:
  1040. self._settings[name] = self.data_to_save
  1041. self._saveSettings()
  1042. self.settingsChoice.SetStringSelection(name)
  1043. self.data_to_save = []
  1044. def _saveSettings(self):
  1045. """Save settings and reload if successful"""
  1046. if self._writeSettings() == 0:
  1047. self._settings = self._loadSettings()
  1048. def SetDataToSave(self, data):
  1049. """Set data for setting, which will be saved.
  1050. :param data: - list of strings, which will be saved
  1051. """
  1052. self.data_to_save = data
  1053. def SetSettings(self, settings):
  1054. """Set settings
  1055. :param settings: - dict with all settigs {nameofsetting : settingdata, ....}
  1056. """
  1057. self._settings = settings
  1058. self._saveSettings()
  1059. def AddSettings(self, settings):
  1060. """Add settings
  1061. :param settings: - dict with all settigs {nameofsetting : settingdata, ....}
  1062. """
  1063. self._settings = dict(self._settings.items() + settings.items())
  1064. self._saveSettings()
  1065. def OnSettingsDelete(self, event):
  1066. """Save settings
  1067. """
  1068. name = self.settingsChoice.GetStringSelection()
  1069. if not name:
  1070. GMessage(parent=self,
  1071. message=_("No settings is defined. Operation canceled."))
  1072. return
  1073. self._settings.pop(name)
  1074. if self._writeSettings() == 0:
  1075. self._settings = self._loadSettings()
  1076. def _writeSettings(self):
  1077. """Save settings into the file
  1078. :return: 0 on success
  1079. :return: -1 on failure
  1080. """
  1081. try:
  1082. fd = open(self.settingsFile, 'w')
  1083. fd.write('format_version=2.0\n')
  1084. for key, values in six.iteritems(self._settings):
  1085. first = True
  1086. for v in values:
  1087. # escaping characters
  1088. for e_ch in self.esc_chars:
  1089. v = v.replace(
  1090. e_ch, self.esc_chars[
  1091. self.e_char_i] + e_ch)
  1092. if first:
  1093. # escaping characters
  1094. for e_ch in self.esc_chars:
  1095. key = key.replace(
  1096. e_ch, self.esc_chars[
  1097. self.e_char_i] + e_ch)
  1098. fd.write('%s;%s;' % (key, v))
  1099. first = False
  1100. else:
  1101. fd.write('%s;' % (v))
  1102. fd.write('\n')
  1103. except IOError:
  1104. GError(parent=self,
  1105. message=_("Unable to save settings"))
  1106. return -1
  1107. fd.close()
  1108. return 0
  1109. def _loadSettings(self):
  1110. """Load settings from the file
  1111. The file is defined by self.SettingsFile.
  1112. :return: parsed dict
  1113. :return: empty dict on error
  1114. """
  1115. data = dict()
  1116. if not os.path.exists(self.settingsFile):
  1117. return data
  1118. try:
  1119. fd = open(self.settingsFile, 'r')
  1120. except IOError:
  1121. return data
  1122. fd_lines = fd.readlines()
  1123. if not fd_lines:
  1124. fd.close()
  1125. return data
  1126. if fd_lines[0].strip() == 'format_version=2.0':
  1127. data = self._loadSettings_v2(fd_lines)
  1128. else:
  1129. data = self._loadSettings_v1(fd_lines)
  1130. self.settingsChoice.SetItems(sorted(data.keys()))
  1131. fd.close()
  1132. self.settingsLoaded.emit(settings=data)
  1133. return data
  1134. def _loadSettings_v2(self, fd_lines):
  1135. """Load settings from the file in format version 2.0
  1136. The file is defined by self.SettingsFile.
  1137. :return: parsed dict
  1138. :return: empty dict on error
  1139. """
  1140. data = dict()
  1141. for line in fd_lines[1:]:
  1142. try:
  1143. lineData = []
  1144. line = line.rstrip('\n')
  1145. i_last_found = i_last = 0
  1146. key = ''
  1147. while True:
  1148. idx = line.find(';', i_last)
  1149. if idx < 0:
  1150. break
  1151. elif idx != 0:
  1152. # find out whether it is separator
  1153. # $$$$; - it is separator
  1154. # $$$$$; - it is not separator
  1155. i_esc_chars = 0
  1156. while True:
  1157. if line[idx - (i_esc_chars + 1)
  1158. ] == self.esc_chars[self.e_char_i]:
  1159. i_esc_chars += 1
  1160. else:
  1161. break
  1162. if i_esc_chars % 2 != 0:
  1163. i_last = idx + 1
  1164. continue
  1165. lineItem = line[i_last_found: idx]
  1166. # unescape characters
  1167. for e_ch in self.esc_chars:
  1168. lineItem = lineItem.replace(
  1169. self.esc_chars[self.e_char_i] + e_ch, e_ch)
  1170. if i_last_found == 0:
  1171. key = lineItem
  1172. else:
  1173. lineData.append(lineItem)
  1174. i_last_found = i_last = idx + 1
  1175. if key and lineData:
  1176. data[key] = lineData
  1177. except ValueError:
  1178. pass
  1179. return data
  1180. def _loadSettings_v1(self, fd_lines):
  1181. """Load settings from the file in format version 1.0 (backward compatibility)
  1182. The file is defined by self.SettingsFile.
  1183. :return: parsed dict
  1184. :return: empty dict on error
  1185. """
  1186. data = dict()
  1187. for line in fd_lines:
  1188. try:
  1189. lineData = line.rstrip('\n').split(';')
  1190. if len(lineData) > 4:
  1191. # type, dsn, format, options
  1192. data[
  1193. lineData[0]] = (
  1194. lineData[1],
  1195. lineData[2],
  1196. lineData[3],
  1197. lineData[4])
  1198. else:
  1199. data[
  1200. lineData[0]] = (
  1201. lineData[1],
  1202. lineData[2],
  1203. lineData[3],
  1204. '')
  1205. except ValueError:
  1206. pass
  1207. return data
  1208. class PictureComboBox(OwnerDrawnComboBox):
  1209. """Abstract class of ComboBox with pictures.
  1210. Derived class has to specify has to specify _getPath method.
  1211. """
  1212. def OnDrawItem(self, dc, rect, item, flags):
  1213. """Overridden from OwnerDrawnComboBox.
  1214. Called to draw each item in the list.
  1215. """
  1216. if item == wx.NOT_FOUND:
  1217. # painting the control, but there is no valid item selected yet
  1218. return
  1219. r = Rect(*rect) # make a copy
  1220. r.Deflate(3, 5)
  1221. # for painting the items in the popup
  1222. bitmap = self.GetPictureBitmap(self.GetString(item))
  1223. if bitmap:
  1224. dc.DrawBitmap(
  1225. bitmap, r.x, r.y + (r.height - bitmap.GetHeight()) / 2)
  1226. width = bitmap.GetWidth() + 10
  1227. else:
  1228. width = 0
  1229. dc.DrawText(self.GetString(item),
  1230. r.x + width,
  1231. (r.y + 0) + (r.height - dc.GetCharHeight()) / 2)
  1232. def OnMeasureItem(self, item):
  1233. """Overridden from OwnerDrawnComboBox, should return the height.
  1234. Needed to display an item in the popup, or -1 for default.
  1235. """
  1236. return 24
  1237. def GetPictureBitmap(self, name):
  1238. """Returns bitmap for given picture name.
  1239. :param str colorTable: name of color table
  1240. """
  1241. if not hasattr(self, 'bitmaps'):
  1242. self.bitmaps = {}
  1243. if name in self.bitmaps:
  1244. return self.bitmaps[name]
  1245. path = self._getPath(name)
  1246. if os.path.exists(path):
  1247. bitmap = wx.Bitmap(path)
  1248. self.bitmaps[name] = bitmap
  1249. return bitmap
  1250. return None
  1251. class ColorTablesComboBox(PictureComboBox):
  1252. """ComboBox with drawn color tables (created by thumbnails.py).
  1253. Used in r(3).colors dialog."""
  1254. def _getPath(self, name):
  1255. return os.path.join(
  1256. os.getenv("GISBASE"),
  1257. "docs", "html", "colortables", "%s.png" % name)
  1258. class BarscalesComboBox(PictureComboBox):
  1259. """ComboBox with barscales for d.barscale."""
  1260. def _getPath(self, name):
  1261. return os.path.join(
  1262. os.getenv("GISBASE"),
  1263. "docs", "html", "barscales", name + '.png')
  1264. class NArrowsComboBox(PictureComboBox):
  1265. """ComboBox with north arrows for d.barscale."""
  1266. def _getPath(self, name):
  1267. return os.path.join(
  1268. os.getenv("GISBASE"),
  1269. "docs", "html", "northarrows", "%s.png" % name)
  1270. class LayersList(GListCtrl, listmix.TextEditMixin):
  1271. """List of layers to be imported (dxf, shp...)"""
  1272. def __init__(self, parent, columns, log=None):
  1273. GListCtrl.__init__(self, parent)
  1274. self.log = log
  1275. # setup mixins
  1276. listmix.TextEditMixin.__init__(self)
  1277. for i in range(len(columns)):
  1278. self.InsertColumn(i, columns[i])
  1279. width = []
  1280. if len(columns) == 3:
  1281. width = (65, 200)
  1282. elif len(columns) == 4:
  1283. width = (65, 200, 90)
  1284. elif len(columns) == 5:
  1285. width = (65, 180, 90, 70)
  1286. for i in range(len(width)):
  1287. self.SetColumnWidth(col=i, width=width[i])
  1288. def OnLeftDown(self, event):
  1289. """Allow editing only output name
  1290. Code taken from TextEditMixin class.
  1291. """
  1292. x, y = event.GetPosition()
  1293. colLocs = [0]
  1294. loc = 0
  1295. for n in range(self.GetColumnCount()):
  1296. loc = loc + self.GetColumnWidth(n)
  1297. colLocs.append(loc)
  1298. col = bisect(colLocs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
  1299. if col == self.GetColumnCount() - 1:
  1300. listmix.TextEditMixin.OnLeftDown(self, event)
  1301. else:
  1302. event.Skip()
  1303. def GetLayers(self):
  1304. """Get list of layers (layer name, output name, list id)"""
  1305. layers = []
  1306. data = self.GetData(checked=True)
  1307. for itm in data:
  1308. layer = itm[1]
  1309. ftype = itm[2]
  1310. if '/' in ftype:
  1311. layer += '|%s' % ftype.split('/', 1)[0]
  1312. output = itm[self.GetColumnCount() - 1]
  1313. layers.append((layer, output, itm[-1]))
  1314. return layers