widgets.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  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::LayersListValidator
  23. - widgets::PlacementValidator
  24. - widgets::GListCtrl
  25. - widgets::SearchModuleWidget
  26. - widgets::ManageSettingsWidget
  27. - widgets::PictureComboBox
  28. - widgets::ColorTablesComboBox
  29. - widgets::BarscalesComboBox
  30. - widgets::NArrowsComboBox
  31. - widgets::LayersList
  32. @todo:
  33. - move validators to a separate file gui_core/validators.py
  34. (C) 2008-2014 by the GRASS Development Team
  35. This program is free software under the GNU General Public License
  36. (>=v2). Read the file COPYING that comes with GRASS for details.
  37. @author Martin Landa <landa.martin gmail.com> (Google SoC 2008/2010)
  38. @author Enhancements by Michael Barton <michael.barton asu.edu>
  39. @author Anna Kratochvilova <kratochanna gmail.com> (Google SoC 2011)
  40. @author Stepan Turek <stepan.turek seznam.cz> (ManageSettingsWidget - created from GdalSelect)
  41. @author Matej Krejci <matejkrejci gmail.com> (Google GSoC 2014; EmailValidator, TimeISOValidator)
  42. @author Tomas Zigo <tomas.zigo slovanet.sk> (LayersListValidator,
  43. PlacementValidator)
  44. """
  45. import os
  46. import sys
  47. import string
  48. import re
  49. import six
  50. from bisect import bisect
  51. from datetime import datetime
  52. from core.globalvar import wxPythonPhoenix
  53. import wx
  54. import wx.lib.mixins.listctrl as listmix
  55. import wx.lib.scrolledpanel as SP
  56. from wx.lib.stattext import GenStaticText
  57. from wx.lib.wordwrap import wordwrap
  58. if wxPythonPhoenix:
  59. import wx.adv
  60. from wx.adv import OwnerDrawnComboBox
  61. else:
  62. import wx.combo
  63. from wx.combo import OwnerDrawnComboBox
  64. try:
  65. import wx.lib.agw.flatnotebook as FN
  66. except ImportError:
  67. import wx.lib.flatnotebook as FN
  68. try:
  69. from wx.lib.buttons import ThemedGenBitmapTextButton as BitmapTextButton
  70. except ImportError: # not sure about TGBTButton version
  71. from wx.lib.buttons import GenBitmapTextButton as BitmapTextButton
  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 not in ("win32", "darwin"):
  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. """Overridden 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(win=event.GetEventObject())
  465. event.Skip()
  466. def Validate(self, parent):
  467. """Is called upon closing wx.Dialog"""
  468. win = self.GetWindow()
  469. return self._validate(win)
  470. def _validate(self, win):
  471. """Validate input"""
  472. text = win.GetValue()
  473. if text:
  474. try:
  475. self.type(text)
  476. except ValueError:
  477. self._notvalid()
  478. return False
  479. self._valid()
  480. return True
  481. def _notvalid(self):
  482. textCtrl = self.GetWindow()
  483. textCtrl.SetBackgroundColour("grey")
  484. textCtrl.Refresh()
  485. def _valid(self):
  486. textCtrl = self.GetWindow()
  487. sysColor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
  488. textCtrl.SetBackgroundColour(sysColor)
  489. textCtrl.Refresh()
  490. return True
  491. def TransferToWindow(self):
  492. return True # Prevent wxDialog from complaining.
  493. def TransferFromWindow(self):
  494. return True # Prevent wxDialog from complaining.
  495. class CoordinatesValidator(BaseValidator):
  496. """Validator for coordinates input (list of floats separated by comma)"""
  497. def __init__(self):
  498. BaseValidator.__init__(self)
  499. def _validate(self, win):
  500. """Validate input"""
  501. text = win.GetValue()
  502. if text:
  503. try:
  504. text = text.split(',')
  505. for t in text:
  506. float(t)
  507. if len(text) % 2 != 0:
  508. return False
  509. except ValueError:
  510. self._notvalid()
  511. return False
  512. self._valid()
  513. return True
  514. def Clone(self):
  515. """Clone validator"""
  516. return CoordinatesValidator()
  517. class IntegerValidator(BaseValidator):
  518. """Validator for floating-point input"""
  519. def __init__(self):
  520. BaseValidator.__init__(self)
  521. self.type = int
  522. def Clone(self):
  523. """Clone validator"""
  524. return IntegerValidator()
  525. class FloatValidator(BaseValidator):
  526. """Validator for floating-point input"""
  527. def __init__(self):
  528. BaseValidator.__init__(self)
  529. self.type = float
  530. def Clone(self):
  531. """Clone validator"""
  532. return FloatValidator()
  533. class EmailValidator(BaseValidator):
  534. """Validator for email input"""
  535. def __init__(self):
  536. BaseValidator.__init__(self)
  537. def _validate(self, win):
  538. """Validate input"""
  539. text = win.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, win):
  554. """Validate input"""
  555. text = win.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 GenericMultiValidator(Validator):
  678. """This validator checks conditions and calls callbacks
  679. in case the condition is not fulfilled.
  680. """
  681. def __init__(self, checks):
  682. """Standard constructor.
  683. :param checks: list of tuples consisting of conditions (list of
  684. functions which accepts string value and returns T/F) and callbacks (
  685. list of functions which is called when condition is not fulfilled)
  686. """
  687. Validator.__init__(self)
  688. self._checks = checks
  689. def Clone(self):
  690. """Standard cloner.
  691. Note that every validator must implement the Clone() method.
  692. """
  693. return GenericMultiValidator(self._checks)
  694. def Validate(self, win):
  695. """Validate the contents of the given text control.
  696. """
  697. ctrl = self.GetWindow()
  698. text = ctrl.GetValue()
  699. for condition, callback in self._checks:
  700. if not condition(text):
  701. callback(ctrl)
  702. return False
  703. return True
  704. def TransferToWindow(self):
  705. """Transfer data from validator to window.
  706. """
  707. return True # Prevent wxDialog from complaining.
  708. def TransferFromWindow(self):
  709. """Transfer data from window to validator.
  710. """
  711. return True # Prevent wxDialog from complaining.
  712. class SingleSymbolPanel(wx.Panel):
  713. """Panel for displaying one symbol.
  714. Changes background when selected. Assumes that parent will catch
  715. events emitted on mouse click. Used in gui_core::dialog::SymbolDialog.
  716. """
  717. def __init__(self, parent, symbolPath):
  718. """Panel constructor
  719. Signal symbolSelectionChanged - symbol selected
  720. - attribute 'name' (symbol name)
  721. - attribute 'doubleClick' (underlying cause)
  722. :param parent: parent (gui_core::dialog::SymbolDialog)
  723. :param symbolPath: absolute path to symbol
  724. """
  725. self.symbolSelectionChanged = Signal(
  726. 'SingleSymbolPanel.symbolSelectionChanged')
  727. wx.Panel.__init__(self, parent, id=wx.ID_ANY, style=wx.BORDER_RAISED)
  728. self.SetName(os.path.splitext(os.path.basename(symbolPath))[0])
  729. self.sBmp = wx.StaticBitmap(self, wx.ID_ANY, wx.Bitmap(symbolPath))
  730. self.selected = False
  731. self.selectColor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
  732. self.deselectColor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
  733. sizer = wx.BoxSizer()
  734. sizer.Add(
  735. self.sBmp,
  736. proportion=0,
  737. flag=wx.ALL | wx.ALIGN_CENTER,
  738. border=5)
  739. self.SetBackgroundColour(self.deselectColor)
  740. self.SetMinSize(self.GetBestSize())
  741. self.SetSizerAndFit(sizer)
  742. # binding to both (staticBitmap, Panel) necessary
  743. self.sBmp.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
  744. self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
  745. self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
  746. self.sBmp.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
  747. def OnLeftDown(self, event):
  748. """Panel selected, background changes"""
  749. self.selected = True
  750. self.SetBackgroundColour(self.selectColor)
  751. self.Refresh()
  752. event.Skip()
  753. self.symbolSelectionChanged.emit(
  754. name=self.GetName(), doubleClick=False)
  755. def OnDoubleClick(self, event):
  756. self.symbolSelectionChanged.emit(name=self.GetName(), doubleClick=True)
  757. def Deselect(self):
  758. """Panel deselected, background changes back to default"""
  759. self.selected = False
  760. self.SetBackgroundColour(self.deselectColor)
  761. self.Refresh()
  762. def Select(self):
  763. """Select panel, no event emitted"""
  764. self.selected = True
  765. self.SetBackgroundColour(self.selectColor)
  766. self.Refresh()
  767. class LayersListValidator(GenericValidator):
  768. """This validator check output map existence"""
  769. def __init__(self, condition, callback):
  770. """Standard constructor.
  771. :param condition: function which accepts string value and returns T/F
  772. :param callback: function which is called when condition is not fulfilled
  773. """
  774. GenericValidator.__init__(self, condition, callback)
  775. def Clone(self):
  776. """Standard cloner.
  777. Note that every validator must implement the Clone() method.
  778. """
  779. return LayersListValidator(self._condition, self._callback)
  780. def Validate(self, win, validate_all=False):
  781. """Validate output map existence"""
  782. mapset = grass.gisenv()['MAPSET']
  783. maps = grass.list_grouped(type=self._condition)[mapset]
  784. # Check all selected layers
  785. if validate_all:
  786. outputs = []
  787. data = win.GetLayers()
  788. if data is None:
  789. return False
  790. for layer, output, list_id in data:
  791. if output in maps:
  792. outputs.append(output)
  793. if outputs:
  794. win.output_map = outputs
  795. self._callback(layers_list=win)
  796. return False
  797. else:
  798. output_map = win.GetItemText(
  799. win.col, win.row)
  800. if output_map in maps:
  801. win.output_map = output_map
  802. self._callback(layers_list=win)
  803. return False
  804. return True
  805. class PlacementValidator(BaseValidator):
  806. """Validator for placement input (list of floats separated by comma)"""
  807. def __init__(self, num_of_params):
  808. self._num_of_params = num_of_params
  809. super().__init__()
  810. def _enableDisableBtn(self, enable):
  811. """Enable/Disable buttomn
  812. :param bool enable: Enable/Disable btn
  813. """
  814. win = self.GetWindow().GetTopLevelParent()
  815. for btn_id in (wx.ID_OK, wx.ID_APPLY):
  816. btn = win.FindWindow(id=btn_id)
  817. if btn:
  818. btn.Enable(enable)
  819. def _valid(self):
  820. super()._valid()
  821. self._enableDisableBtn(enable=True)
  822. def _notvalid(self):
  823. super()._notvalid()
  824. self._enableDisableBtn(enable=False)
  825. def _validate(self, win):
  826. """Validate input"""
  827. text = win.GetValue()
  828. if text:
  829. try:
  830. text = text.split(',')
  831. for t in text:
  832. float(t)
  833. if len(text) % self._num_of_params != 0:
  834. self._notvalid()
  835. return False
  836. except ValueError:
  837. self._notvalid()
  838. return False
  839. self._valid()
  840. return True
  841. def Clone(self):
  842. """Clone validator"""
  843. return PlacementValidator(num_of_params=self._num_of_params)
  844. class GListCtrl(ListCtrl, listmix.ListCtrlAutoWidthMixin,
  845. CheckListCtrlMixin):
  846. """Generic ListCtrl with popup menu to select/deselect all
  847. items"""
  848. def __init__(self, parent):
  849. self.parent = parent
  850. ListCtrl.__init__(self, parent, id=wx.ID_ANY,
  851. style=wx.LC_REPORT)
  852. CheckListCtrlMixin.__init__(self)
  853. # setup mixins
  854. listmix.ListCtrlAutoWidthMixin.__init__(self)
  855. self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnPopupMenu) # wxMSW
  856. self.Bind(wx.EVT_RIGHT_UP, self.OnPopupMenu) # wxGTK
  857. def OnPopupMenu(self, event):
  858. """Show popup menu"""
  859. if self.GetItemCount() < 1:
  860. return
  861. if not hasattr(self, "popupDataID1"):
  862. self.popupDataID1 = NewId()
  863. self.popupDataID2 = NewId()
  864. self.Bind(wx.EVT_MENU, self.OnSelectAll, id=self.popupDataID1)
  865. self.Bind(wx.EVT_MENU, self.OnSelectNone, id=self.popupDataID2)
  866. # generate popup-menu
  867. menu = Menu()
  868. menu.Append(self.popupDataID1, _("Select all"))
  869. menu.Append(self.popupDataID2, _("Deselect all"))
  870. self.PopupMenu(menu)
  871. menu.Destroy()
  872. def SelectAll(self, select=True):
  873. """Check or uncheck all items"""
  874. item = -1
  875. while True:
  876. item = self.GetNextItem(item)
  877. if item == -1:
  878. break
  879. self.CheckItem(item, select)
  880. def OnSelectAll(self, event):
  881. """Check all items"""
  882. self.SelectAll(select=True)
  883. event.Skip()
  884. def OnSelectNone(self, event):
  885. """Uncheck items"""
  886. self.SelectAll(select=False)
  887. event.Skip()
  888. def GetData(self, checked=None):
  889. """Get list data"""
  890. data = []
  891. checkedList = []
  892. item = -1
  893. while True:
  894. row = []
  895. item = self.GetNextItem(item)
  896. if item == -1:
  897. break
  898. isChecked = self.IsItemChecked(item)
  899. if checked is not None and checked != isChecked:
  900. continue
  901. checkedList.append(isChecked)
  902. for i in range(self.GetColumnCount()):
  903. row.append(self.GetItem(item, i).GetText())
  904. row.append(item)
  905. data.append(tuple(row))
  906. if checked is not None:
  907. return tuple(data)
  908. else:
  909. return (tuple(data), tuple(checkedList))
  910. def LoadData(self, data=None, selectOne=True):
  911. """Load data into list"""
  912. self.DeleteAllItems()
  913. if data is None:
  914. return
  915. idx = 0
  916. for item in data:
  917. index = self.InsertItem(idx, str(item[0]))
  918. for i in range(1, self.GetColumnCount()):
  919. self.SetItem(index, i, item[i])
  920. idx += 1
  921. # check by default only on one item
  922. if len(data) == 1 and selectOne:
  923. self.CheckItem(index, True)
  924. class SearchModuleWidget(wx.Panel):
  925. """Search module widget (used e.g. in SearchModuleWindow)
  926. Signals:
  927. moduleSelected - attribute 'name' is module name
  928. showSearchResult - attribute 'result' is a node (representing module)
  929. showNotification - attribute 'message'
  930. """
  931. def __init__(self, parent, model,
  932. showChoice=True, showTip=False, **kwargs):
  933. self._showTip = showTip
  934. self._showChoice = showChoice
  935. self._model = model
  936. self._results = [] # list of found nodes
  937. self._resultIndex = -1
  938. self._searchKeys = ['description', 'keywords', 'command']
  939. self._oldValue = ''
  940. self.moduleSelected = Signal('SearchModuleWidget.moduleSelected')
  941. self.showSearchResult = Signal('SearchModuleWidget.showSearchResult')
  942. self.showNotification = Signal('SearchModuleWidget.showNotification')
  943. wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY, **kwargs)
  944. # self._box = wx.StaticBox(parent = self, id = wx.ID_ANY,
  945. # label = " %s " % _("Find module - (press Enter for next match)"))
  946. if sys.platform == 'win32':
  947. self._search = TextCtrl(
  948. parent=self, id=wx.ID_ANY, size=(-1, 25),
  949. style=wx.TE_PROCESS_ENTER)
  950. else:
  951. self._search = SearchCtrl(
  952. parent=self, id=wx.ID_ANY, size=(-1, 25),
  953. style=wx.TE_PROCESS_ENTER)
  954. self._search.SetDescriptiveText(_('Fulltext search'))
  955. self._search.SetToolTip(
  956. _("Type to search in all modules. Press Enter for next match."))
  957. self._search.Bind(wx.EVT_TEXT, self.OnSearchModule)
  958. self._search.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)
  959. if self._showTip:
  960. self._searchTip = StaticWrapText(parent=self, id=wx.ID_ANY,
  961. label="Choose a module", size=(-1, 35))
  962. if self._showChoice:
  963. self._searchChoice = wx.Choice(parent=self, id=wx.ID_ANY)
  964. self._searchChoice.SetItems(
  965. self._searchModule(
  966. keys=['command'], value=''))
  967. self._searchChoice.Bind(wx.EVT_CHOICE, self.OnSelectModule)
  968. self._layout()
  969. def _layout(self):
  970. """Do layout"""
  971. sizer = wx.BoxSizer(wx.HORIZONTAL)
  972. boxSizer = wx.BoxSizer(wx.VERTICAL)
  973. boxSizer.Add(self._search,
  974. flag=wx.EXPAND | wx.BOTTOM,
  975. border=5)
  976. if self._showChoice:
  977. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  978. hSizer.Add(self._searchChoice,
  979. flag=wx.EXPAND | wx.BOTTOM,
  980. border=5)
  981. hSizer.AddStretchSpacer()
  982. boxSizer.Add(hSizer, flag=wx.EXPAND)
  983. if self._showTip:
  984. boxSizer.Add(self._searchTip,
  985. flag=wx.EXPAND)
  986. sizer.Add(boxSizer, proportion=1)
  987. self.SetSizer(sizer)
  988. sizer.Fit(self)
  989. def OnEnter(self, event):
  990. """Process EVT_TEXT_ENTER to show search results"""
  991. self._showSearchResult()
  992. event.Skip()
  993. def _showSearchResult(self):
  994. if self._results:
  995. self._resultIndex += 1
  996. if self._resultIndex == len(self._results):
  997. self._resultIndex = 0
  998. self.showSearchResult.emit(result=self._results[self._resultIndex])
  999. def OnSearchModule(self, event):
  1000. """Search module by keywords or description"""
  1001. value = self._search.GetValue()
  1002. if value == self._oldValue:
  1003. event.Skip()
  1004. return
  1005. self._oldValue = value
  1006. if len(value) <= 2:
  1007. if len(value) == 0: # reset
  1008. commands = self._searchModule(keys=['command'], value='')
  1009. else:
  1010. self.showNotification.emit(
  1011. message=_("Searching, please type more characters."))
  1012. return
  1013. else:
  1014. commands = self._searchModule(keys=self._searchKeys, value=value)
  1015. if self._showChoice:
  1016. self._searchChoice.SetItems(commands)
  1017. if commands:
  1018. self._searchChoice.SetSelection(0)
  1019. label = _("%d modules match") % len(commands)
  1020. if self._showTip:
  1021. self._searchTip.SetLabel(label)
  1022. self.showNotification.emit(message=label)
  1023. event.Skip()
  1024. def _searchModule(self, keys, value):
  1025. """Search modules by keys
  1026. :param keys: list of keys
  1027. :param value: patter to match
  1028. """
  1029. nodes = set()
  1030. for key in keys:
  1031. nodes.update(self._model.SearchNodes(key=key, value=value))
  1032. nodes = list(nodes)
  1033. nodes.sort(key=lambda node: self._model.GetIndexOfNode(node))
  1034. self._results = nodes
  1035. self._resultIndex = -1
  1036. commands = sorted([node.data['command']
  1037. for node in nodes if node.data['command']])
  1038. return commands
  1039. def OnSelectModule(self, event):
  1040. """Module selected from choice, update command prompt"""
  1041. cmd = self._searchChoice.GetStringSelection()
  1042. self.moduleSelected.emit(name=cmd)
  1043. if self._showTip:
  1044. for module in self._results:
  1045. if cmd == module.data['command']:
  1046. self._searchTip.SetLabel(module.data['description'])
  1047. break
  1048. def Reset(self):
  1049. """Reset widget"""
  1050. self._search.SetValue('')
  1051. if self._showTip:
  1052. self._searchTip.SetLabel('Choose a module')
  1053. class ManageSettingsWidget(wx.Panel):
  1054. """Widget which allows loading and saving settings into file."""
  1055. def __init__(self, parent, settingsFile):
  1056. """
  1057. Signals:
  1058. settingsChanged - called when users changes setting
  1059. - attribute 'data' with chosen setting data
  1060. settingsSaving - called when settings are saving
  1061. - attribute 'name' with chosen settings name
  1062. settingsLoaded - called when settings are loaded
  1063. - attribute 'settings' is dict with loaded settings
  1064. {nameofsetting : settingdata, ....}
  1065. :param settingsFile: path to file, where settings will be saved and loaded from
  1066. """
  1067. self.settingsFile = settingsFile
  1068. self.settingsChanged = Signal('ManageSettingsWidget.settingsChanged')
  1069. self.settingsSaving = Signal('ManageSettingsWidget.settingsSaving')
  1070. self.settingsLoaded = Signal('ManageSettingsWidget.settingsLoaded')
  1071. wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
  1072. self.settingsBox = StaticBox(parent=self, id=wx.ID_ANY,
  1073. label=" %s " % _("Profiles"))
  1074. self.settingsChoice = wx.Choice(parent=self, id=wx.ID_ANY)
  1075. self.settingsChoice.Bind(wx.EVT_CHOICE, self.OnSettingsChanged)
  1076. self.btnSettingsSave = Button(parent=self, id=wx.ID_SAVE)
  1077. self.btnSettingsSave.Bind(wx.EVT_BUTTON, self.OnSettingsSave)
  1078. self.btnSettingsSave.SetToolTip(_("Save current settings"))
  1079. self.btnSettingsDel = Button(parent=self, id=wx.ID_REMOVE)
  1080. self.btnSettingsDel.Bind(wx.EVT_BUTTON, self.OnSettingsDelete)
  1081. self.btnSettingsSave.SetToolTip(
  1082. _("Delete currently selected settings"))
  1083. # escaping with '$' character - index in self.esc_chars
  1084. self.e_char_i = 0
  1085. self.esc_chars = ['$', ';']
  1086. self._settings = self._loadSettings() # -> self.settingsChoice.SetItems()
  1087. self.settingsLoaded.emit(settings=self._settings)
  1088. self.data_to_save = []
  1089. self._layout()
  1090. self.SetSizer(self.settingsSizer)
  1091. self.settingsSizer.Fit(self)
  1092. def _layout(self):
  1093. self.settingsSizer = wx.StaticBoxSizer(self.settingsBox, wx.HORIZONTAL)
  1094. self.settingsSizer.Add(
  1095. StaticText(
  1096. parent=self,
  1097. id=wx.ID_ANY,
  1098. label=_("Load:")),
  1099. flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.LEFT,
  1100. border=5)
  1101. self.settingsSizer.Add(
  1102. self.settingsChoice,
  1103. proportion=1,
  1104. flag=wx.EXPAND | wx.BOTTOM,
  1105. border=3)
  1106. self.settingsSizer.Add(self.btnSettingsSave,
  1107. flag=wx.LEFT | wx.RIGHT | wx.BOTTOM, border=3)
  1108. self.settingsSizer.Add(self.btnSettingsDel,
  1109. flag=wx.RIGHT | wx.BOTTOM, border=3)
  1110. def OnSettingsChanged(self, event):
  1111. """Load named settings"""
  1112. name = event.GetString()
  1113. if name not in self._settings:
  1114. GError(parent=self,
  1115. message=_("Settings <%s> not found") % name)
  1116. return
  1117. data = self._settings[name]
  1118. self.settingsChanged.emit(data=data)
  1119. def GetSettings(self):
  1120. """Load named settings"""
  1121. return self._settings.copy()
  1122. def OnSettingsSave(self, event):
  1123. """Save settings"""
  1124. dlg = wx.TextEntryDialog(parent=self,
  1125. message=_("Name:"),
  1126. caption=_("Save settings"))
  1127. if dlg.ShowModal() == wx.ID_OK:
  1128. name = dlg.GetValue()
  1129. if not name:
  1130. GMessage(parent=self,
  1131. message=_("Name not given, settings is not saved."))
  1132. else:
  1133. self.settingsSaving.emit(name=name)
  1134. dlg.Destroy()
  1135. def SaveSettings(self, name):
  1136. # check if settings item already exists
  1137. if name in self._settings:
  1138. dlgOwt = wx.MessageDialog(
  1139. self,
  1140. message=_(
  1141. "Settings <%s> already exists. "
  1142. "Do you want to overwrite the settings?") %
  1143. name,
  1144. caption=_("Save settings"),
  1145. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  1146. if dlgOwt.ShowModal() != wx.ID_YES:
  1147. dlgOwt.Destroy()
  1148. return
  1149. if self.data_to_save:
  1150. self._settings[name] = self.data_to_save
  1151. self._saveSettings()
  1152. self.settingsChoice.SetStringSelection(name)
  1153. self.data_to_save = []
  1154. def _saveSettings(self):
  1155. """Save settings and reload if successful"""
  1156. if self._writeSettings() == 0:
  1157. self._settings = self._loadSettings()
  1158. def SetDataToSave(self, data):
  1159. """Set data for setting, which will be saved.
  1160. :param data: - list of strings, which will be saved
  1161. """
  1162. self.data_to_save = data
  1163. def SetSettings(self, settings):
  1164. """Set settings
  1165. :param settings: - dict with all settigs {nameofsetting : settingdata, ....}
  1166. """
  1167. self._settings = settings
  1168. self._saveSettings()
  1169. def AddSettings(self, settings):
  1170. """Add settings
  1171. :param settings: - dict with all settigs {nameofsetting : settingdata, ....}
  1172. """
  1173. self._settings.update(settings)
  1174. self._saveSettings()
  1175. def OnSettingsDelete(self, event):
  1176. """Save settings
  1177. """
  1178. name = self.settingsChoice.GetStringSelection()
  1179. if not name:
  1180. GMessage(parent=self,
  1181. message=_("No settings is defined. Operation canceled."))
  1182. return
  1183. self._settings.pop(name)
  1184. if self._writeSettings() == 0:
  1185. self._settings = self._loadSettings()
  1186. def _writeSettings(self):
  1187. """Save settings into the file
  1188. :return: 0 on success
  1189. :return: -1 on failure
  1190. """
  1191. try:
  1192. fd = open(self.settingsFile, 'w')
  1193. fd.write('format_version=2.0\n')
  1194. for key, values in six.iteritems(self._settings):
  1195. first = True
  1196. for v in values:
  1197. # escaping characters
  1198. for e_ch in self.esc_chars:
  1199. v = v.replace(
  1200. e_ch, self.esc_chars[
  1201. self.e_char_i] + e_ch)
  1202. if first:
  1203. # escaping characters
  1204. for e_ch in self.esc_chars:
  1205. key = key.replace(
  1206. e_ch, self.esc_chars[
  1207. self.e_char_i] + e_ch)
  1208. fd.write('%s;%s;' % (key, v))
  1209. first = False
  1210. else:
  1211. fd.write('%s;' % (v))
  1212. fd.write('\n')
  1213. except IOError:
  1214. GError(parent=self,
  1215. message=_("Unable to save settings"))
  1216. return -1
  1217. fd.close()
  1218. return 0
  1219. def _loadSettings(self):
  1220. """Load settings from the file
  1221. The file is defined by self.SettingsFile.
  1222. :return: parsed dict
  1223. :return: empty dict on error
  1224. """
  1225. data = dict()
  1226. if not os.path.exists(self.settingsFile):
  1227. return data
  1228. try:
  1229. fd = open(self.settingsFile, 'r')
  1230. except IOError:
  1231. return data
  1232. fd_lines = fd.readlines()
  1233. if not fd_lines:
  1234. fd.close()
  1235. return data
  1236. if fd_lines[0].strip() == 'format_version=2.0':
  1237. data = self._loadSettings_v2(fd_lines)
  1238. else:
  1239. data = self._loadSettings_v1(fd_lines)
  1240. self.settingsChoice.SetItems(sorted(data.keys()))
  1241. fd.close()
  1242. self.settingsLoaded.emit(settings=data)
  1243. return data
  1244. def _loadSettings_v2(self, fd_lines):
  1245. """Load settings from the file in format version 2.0
  1246. The file is defined by self.SettingsFile.
  1247. :return: parsed dict
  1248. :return: empty dict on error
  1249. """
  1250. data = dict()
  1251. for line in fd_lines[1:]:
  1252. try:
  1253. lineData = []
  1254. line = line.rstrip('\n')
  1255. i_last_found = i_last = 0
  1256. key = ''
  1257. while True:
  1258. idx = line.find(';', i_last)
  1259. if idx < 0:
  1260. break
  1261. elif idx != 0:
  1262. # find out whether it is separator
  1263. # $$$$; - it is separator
  1264. # $$$$$; - it is not separator
  1265. i_esc_chars = 0
  1266. while True:
  1267. if line[idx - (i_esc_chars + 1)
  1268. ] == self.esc_chars[self.e_char_i]:
  1269. i_esc_chars += 1
  1270. else:
  1271. break
  1272. if i_esc_chars % 2 != 0:
  1273. i_last = idx + 1
  1274. continue
  1275. lineItem = line[i_last_found: idx]
  1276. # unescape characters
  1277. for e_ch in self.esc_chars:
  1278. lineItem = lineItem.replace(
  1279. self.esc_chars[self.e_char_i] + e_ch, e_ch)
  1280. if i_last_found == 0:
  1281. key = lineItem
  1282. else:
  1283. lineData.append(lineItem)
  1284. i_last_found = i_last = idx + 1
  1285. if key and lineData:
  1286. data[key] = lineData
  1287. except ValueError:
  1288. pass
  1289. return data
  1290. def _loadSettings_v1(self, fd_lines):
  1291. """Load settings from the file in format version 1.0 (backward compatibility)
  1292. The file is defined by self.SettingsFile.
  1293. :return: parsed dict
  1294. :return: empty dict on error
  1295. """
  1296. data = dict()
  1297. for line in fd_lines:
  1298. try:
  1299. lineData = line.rstrip('\n').split(';')
  1300. if len(lineData) > 4:
  1301. # type, dsn, format, options
  1302. data[
  1303. lineData[0]] = (
  1304. lineData[1],
  1305. lineData[2],
  1306. lineData[3],
  1307. lineData[4])
  1308. else:
  1309. data[
  1310. lineData[0]] = (
  1311. lineData[1],
  1312. lineData[2],
  1313. lineData[3],
  1314. '')
  1315. except ValueError:
  1316. pass
  1317. return data
  1318. class PictureComboBox(OwnerDrawnComboBox):
  1319. """Abstract class of ComboBox with pictures.
  1320. Derived class has to specify has to specify _getPath method.
  1321. """
  1322. def OnDrawItem(self, dc, rect, item, flags):
  1323. """Overridden from OwnerDrawnComboBox.
  1324. Called to draw each item in the list.
  1325. """
  1326. if item == wx.NOT_FOUND:
  1327. # painting the control, but there is no valid item selected yet
  1328. return
  1329. r = Rect(*rect) # make a copy
  1330. r.Deflate(3, 5)
  1331. # for painting the items in the popup
  1332. bitmap = self.GetPictureBitmap(self.GetString(item))
  1333. if bitmap:
  1334. dc.DrawBitmap(
  1335. bitmap, r.x, r.y + (r.height - bitmap.GetHeight()) / 2)
  1336. width = bitmap.GetWidth() + 10
  1337. else:
  1338. width = 0
  1339. dc.DrawText(self.GetString(item),
  1340. r.x + width,
  1341. (r.y + 0) + (r.height - dc.GetCharHeight()) / 2)
  1342. def OnMeasureItem(self, item):
  1343. """Overridden from OwnerDrawnComboBox, should return the height.
  1344. Needed to display an item in the popup, or -1 for default.
  1345. """
  1346. return 24
  1347. def GetPictureBitmap(self, name):
  1348. """Returns bitmap for given picture name.
  1349. :param str colorTable: name of color table
  1350. """
  1351. if not hasattr(self, 'bitmaps'):
  1352. self.bitmaps = {}
  1353. if name in self.bitmaps:
  1354. return self.bitmaps[name]
  1355. path = self._getPath(name)
  1356. if os.path.exists(path):
  1357. bitmap = wx.Bitmap(path)
  1358. self.bitmaps[name] = bitmap
  1359. return bitmap
  1360. return None
  1361. class ColorTablesComboBox(PictureComboBox):
  1362. """ComboBox with drawn color tables (created by thumbnails.py).
  1363. Used in r(3).colors dialog."""
  1364. def _getPath(self, name):
  1365. return os.path.join(
  1366. os.getenv("GISBASE"),
  1367. "docs", "html", "colortables", "%s.png" % name)
  1368. class BarscalesComboBox(PictureComboBox):
  1369. """ComboBox with barscales for d.barscale."""
  1370. def _getPath(self, name):
  1371. return os.path.join(
  1372. os.getenv("GISBASE"),
  1373. "docs", "html", "barscales", name + '.png')
  1374. class NArrowsComboBox(PictureComboBox):
  1375. """ComboBox with north arrows for d.barscale."""
  1376. def _getPath(self, name):
  1377. return os.path.join(
  1378. os.getenv("GISBASE"),
  1379. "docs", "html", "northarrows", "%s.png" % name)
  1380. class LayersList(GListCtrl, listmix.TextEditMixin):
  1381. """List of layers to be imported (dxf, shp...)"""
  1382. def __init__(self, parent, columns, log=None):
  1383. GListCtrl.__init__(self, parent)
  1384. self.log = log
  1385. self.row = None
  1386. self.col = None
  1387. self.output_map = None
  1388. self.validate = True
  1389. # setup mixins
  1390. listmix.TextEditMixin.__init__(self)
  1391. for i in range(len(columns)):
  1392. self.InsertColumn(i, columns[i])
  1393. width = []
  1394. if len(columns) == 3:
  1395. width = (65, 200)
  1396. elif len(columns) == 4:
  1397. width = (65, 200, 90)
  1398. elif len(columns) == 5:
  1399. width = (65, 180, 90, 70)
  1400. for i in range(len(width)):
  1401. self.SetColumnWidth(col=i, width=width[i])
  1402. def OnLeftDown(self, event):
  1403. """Allow editing only output name
  1404. Code taken from TextEditMixin class.
  1405. """
  1406. x, y = event.GetPosition()
  1407. colLocs = [0]
  1408. loc = 0
  1409. for n in range(self.GetColumnCount()):
  1410. loc = loc + self.GetColumnWidth(n)
  1411. colLocs.append(loc)
  1412. col = bisect(colLocs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
  1413. if col == self.GetColumnCount() - 1:
  1414. listmix.TextEditMixin.OnLeftDown(self, event)
  1415. else:
  1416. event.Skip()
  1417. def GetLayers(self):
  1418. """Get list of layers (layer name, output name, list id)"""
  1419. layers = []
  1420. data = self.GetData(checked=True)
  1421. for itm in data:
  1422. layer = itm[1]
  1423. ftype = itm[2]
  1424. if '/' in ftype:
  1425. layer += '|%s' % ftype.split('/', 1)[0]
  1426. output = itm[self.GetColumnCount() - 1]
  1427. layers.append((layer, output, itm[-1]))
  1428. return layers
  1429. def ValidateOutputMapName(self):
  1430. """Validate output map name"""
  1431. wx.CallAfter(self.GetValidator().Validate, self)
  1432. def OpenEditor(self, row, col):
  1433. """Open editor"""
  1434. self.col = col
  1435. self.row = row
  1436. super().OpenEditor(row, col)
  1437. def CloseEditor(self, event=None):
  1438. """Close editor"""
  1439. if event:
  1440. if event.IsCommandEvent():
  1441. listmix.TextEditMixin.CloseEditor(self, event)
  1442. if self.validate:
  1443. self.ValidateOutputMapName()
  1444. event.Skip()