widgets.py 52 KB

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