widgets.py 55 KB

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