widgets.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795
  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 OnSelectAll(self, event):
  836. """Select all items"""
  837. item = -1
  838. while True:
  839. item = self.GetNextItem(item)
  840. if item == -1:
  841. break
  842. self.CheckItem(item, True)
  843. event.Skip()
  844. def OnSelectNone(self, event):
  845. """Deselect items"""
  846. item = -1
  847. while True:
  848. item = self.GetNextItem(item, wx.LIST_STATE_SELECTED)
  849. if item == -1:
  850. break
  851. self.CheckItem(item, False)
  852. event.Skip()
  853. def GetData(self, checked=None):
  854. """Get list data"""
  855. data = []
  856. checkedList = []
  857. item = -1
  858. while True:
  859. row = []
  860. item = self.GetNextItem(item)
  861. if item == -1:
  862. break
  863. isChecked = self.IsItemChecked(item)
  864. if checked is not None and checked != isChecked:
  865. continue
  866. checkedList.append(isChecked)
  867. for i in range(self.GetColumnCount()):
  868. row.append(self.GetItem(item, i).GetText())
  869. row.append(item)
  870. data.append(tuple(row))
  871. if checked is not None:
  872. return tuple(data)
  873. else:
  874. return (tuple(data), tuple(checkedList))
  875. def LoadData(self, data=None, selectOne=True):
  876. """Load data into list"""
  877. self.DeleteAllItems()
  878. if data is None:
  879. return
  880. idx = 0
  881. for item in data:
  882. index = self.InsertItem(idx, str(item[0]))
  883. for i in range(1, self.GetColumnCount()):
  884. self.SetItem(index, i, item[i])
  885. idx += 1
  886. # check by default only on one item
  887. if len(data) == 1 and selectOne:
  888. self.CheckItem(index, True)
  889. class SearchModuleWidget(wx.Panel):
  890. """Search module widget (used e.g. in SearchModuleWindow)
  891. Signals:
  892. moduleSelected - attribute 'name' is module name
  893. showSearchResult - attribute 'result' is a node (representing module)
  894. showNotification - attribute 'message'
  895. """
  896. def __init__(self, parent, model,
  897. showChoice=True, showTip=False, **kwargs):
  898. self._showTip = showTip
  899. self._showChoice = showChoice
  900. self._model = model
  901. self._results = [] # list of found nodes
  902. self._resultIndex = -1
  903. self._searchKeys = ['description', 'keywords', 'command']
  904. self._oldValue = ''
  905. self.moduleSelected = Signal('SearchModuleWidget.moduleSelected')
  906. self.showSearchResult = Signal('SearchModuleWidget.showSearchResult')
  907. self.showNotification = Signal('SearchModuleWidget.showNotification')
  908. wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY, **kwargs)
  909. # self._box = wx.StaticBox(parent = self, id = wx.ID_ANY,
  910. # label = " %s " % _("Find module - (press Enter for next match)"))
  911. if sys.platform == 'win32':
  912. self._search = TextCtrl(
  913. parent=self, id=wx.ID_ANY, size=(-1, 25),
  914. style=wx.TE_PROCESS_ENTER)
  915. else:
  916. self._search = SearchCtrl(
  917. parent=self, id=wx.ID_ANY, size=(-1, 25),
  918. style=wx.TE_PROCESS_ENTER)
  919. self._search.SetDescriptiveText(_('Fulltext search'))
  920. self._search.SetToolTip(
  921. _("Type to search in all modules. Press Enter for next match."))
  922. self._search.Bind(wx.EVT_TEXT, self.OnSearchModule)
  923. self._search.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)
  924. if self._showTip:
  925. self._searchTip = StaticWrapText(parent=self, id=wx.ID_ANY,
  926. label="Choose a module", size=(-1, 35))
  927. if self._showChoice:
  928. self._searchChoice = wx.Choice(parent=self, id=wx.ID_ANY)
  929. self._searchChoice.SetItems(
  930. self._searchModule(
  931. keys=['command'], value=''))
  932. self._searchChoice.Bind(wx.EVT_CHOICE, self.OnSelectModule)
  933. self._layout()
  934. def _layout(self):
  935. """Do layout"""
  936. sizer = wx.BoxSizer(wx.HORIZONTAL)
  937. boxSizer = wx.BoxSizer(wx.VERTICAL)
  938. boxSizer.Add(self._search,
  939. flag=wx.EXPAND | wx.BOTTOM,
  940. border=5)
  941. if self._showChoice:
  942. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  943. hSizer.Add(self._searchChoice,
  944. flag=wx.EXPAND | wx.BOTTOM,
  945. border=5)
  946. hSizer.AddStretchSpacer()
  947. boxSizer.Add(hSizer, flag=wx.EXPAND)
  948. if self._showTip:
  949. boxSizer.Add(self._searchTip,
  950. flag=wx.EXPAND)
  951. sizer.Add(boxSizer, proportion=1)
  952. self.SetSizer(sizer)
  953. sizer.Fit(self)
  954. def OnEnter(self, event):
  955. """Process EVT_TEXT_ENTER to show search results"""
  956. self._showSearchResult()
  957. event.Skip()
  958. def _showSearchResult(self):
  959. if self._results:
  960. self._resultIndex += 1
  961. if self._resultIndex == len(self._results):
  962. self._resultIndex = 0
  963. self.showSearchResult.emit(result=self._results[self._resultIndex])
  964. def OnSearchModule(self, event):
  965. """Search module by keywords or description"""
  966. value = self._search.GetValue()
  967. if value == self._oldValue:
  968. event.Skip()
  969. return
  970. self._oldValue = value
  971. if len(value) <= 2:
  972. if len(value) == 0: # reset
  973. commands = self._searchModule(keys=['command'], value='')
  974. else:
  975. self.showNotification.emit(
  976. message=_("Searching, please type more characters."))
  977. return
  978. else:
  979. commands = self._searchModule(keys=self._searchKeys, value=value)
  980. if self._showChoice:
  981. self._searchChoice.SetItems(commands)
  982. if commands:
  983. self._searchChoice.SetSelection(0)
  984. label = _("%d modules match") % len(commands)
  985. if self._showTip:
  986. self._searchTip.SetLabel(label)
  987. self.showNotification.emit(message=label)
  988. event.Skip()
  989. def _searchModule(self, keys, value):
  990. """Search modules by keys
  991. :param keys: list of keys
  992. :param value: patter to match
  993. """
  994. nodes = set()
  995. for key in keys:
  996. nodes.update(self._model.SearchNodes(key=key, value=value))
  997. nodes = list(nodes)
  998. nodes.sort(key=lambda node: self._model.GetIndexOfNode(node))
  999. self._results = nodes
  1000. self._resultIndex = -1
  1001. commands = sorted([node.data['command']
  1002. for node in nodes if node.data['command']])
  1003. return commands
  1004. def OnSelectModule(self, event):
  1005. """Module selected from choice, update command prompt"""
  1006. cmd = self._searchChoice.GetStringSelection()
  1007. self.moduleSelected.emit(name=cmd)
  1008. if self._showTip:
  1009. for module in self._results:
  1010. if cmd == module.data['command']:
  1011. self._searchTip.SetLabel(module.data['description'])
  1012. break
  1013. def Reset(self):
  1014. """Reset widget"""
  1015. self._search.SetValue('')
  1016. if self._showTip:
  1017. self._searchTip.SetLabel('Choose a module')
  1018. class ManageSettingsWidget(wx.Panel):
  1019. """Widget which allows loading and saving settings into file."""
  1020. def __init__(self, parent, settingsFile):
  1021. """
  1022. Signals:
  1023. settingsChanged - called when users changes setting
  1024. - attribute 'data' with chosen setting data
  1025. settingsSaving - called when settings are saving
  1026. - attribute 'name' with chosen settings name
  1027. settingsLoaded - called when settings are loaded
  1028. - attribute 'settings' is dict with loaded settings
  1029. {nameofsetting : settingdata, ....}
  1030. :param settingsFile: path to file, where settings will be saved and loaded from
  1031. """
  1032. self.settingsFile = settingsFile
  1033. self.settingsChanged = Signal('ManageSettingsWidget.settingsChanged')
  1034. self.settingsSaving = Signal('ManageSettingsWidget.settingsSaving')
  1035. self.settingsLoaded = Signal('ManageSettingsWidget.settingsLoaded')
  1036. wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
  1037. self.settingsBox = StaticBox(parent=self, id=wx.ID_ANY,
  1038. label=" %s " % _("Profiles"))
  1039. self.settingsChoice = wx.Choice(parent=self, id=wx.ID_ANY)
  1040. self.settingsChoice.Bind(wx.EVT_CHOICE, self.OnSettingsChanged)
  1041. self.btnSettingsSave = Button(parent=self, id=wx.ID_SAVE)
  1042. self.btnSettingsSave.Bind(wx.EVT_BUTTON, self.OnSettingsSave)
  1043. self.btnSettingsSave.SetToolTip(_("Save current settings"))
  1044. self.btnSettingsDel = Button(parent=self, id=wx.ID_REMOVE)
  1045. self.btnSettingsDel.Bind(wx.EVT_BUTTON, self.OnSettingsDelete)
  1046. self.btnSettingsSave.SetToolTip(
  1047. _("Delete currently selected settings"))
  1048. # escaping with '$' character - index in self.esc_chars
  1049. self.e_char_i = 0
  1050. self.esc_chars = ['$', ';']
  1051. self._settings = self._loadSettings() # -> self.settingsChoice.SetItems()
  1052. self.settingsLoaded.emit(settings=self._settings)
  1053. self.data_to_save = []
  1054. self._layout()
  1055. self.SetSizer(self.settingsSizer)
  1056. self.settingsSizer.Fit(self)
  1057. def _layout(self):
  1058. self.settingsSizer = wx.StaticBoxSizer(self.settingsBox, wx.HORIZONTAL)
  1059. self.settingsSizer.Add(
  1060. StaticText(
  1061. parent=self,
  1062. id=wx.ID_ANY,
  1063. label=_("Load:")),
  1064. flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.LEFT,
  1065. border=5)
  1066. self.settingsSizer.Add(
  1067. self.settingsChoice,
  1068. proportion=1,
  1069. flag=wx.EXPAND | wx.BOTTOM,
  1070. border=3)
  1071. self.settingsSizer.Add(self.btnSettingsSave,
  1072. flag=wx.LEFT | wx.RIGHT | wx.BOTTOM, border=3)
  1073. self.settingsSizer.Add(self.btnSettingsDel,
  1074. flag=wx.RIGHT | wx.BOTTOM, border=3)
  1075. def OnSettingsChanged(self, event):
  1076. """Load named settings"""
  1077. name = event.GetString()
  1078. if name not in self._settings:
  1079. GError(parent=self,
  1080. message=_("Settings <%s> not found") % name)
  1081. return
  1082. data = self._settings[name]
  1083. self.settingsChanged.emit(data=data)
  1084. def GetSettings(self):
  1085. """Load named settings"""
  1086. return self._settings.copy()
  1087. def OnSettingsSave(self, event):
  1088. """Save settings"""
  1089. dlg = wx.TextEntryDialog(parent=self,
  1090. message=_("Name:"),
  1091. caption=_("Save settings"))
  1092. if dlg.ShowModal() == wx.ID_OK:
  1093. name = dlg.GetValue()
  1094. if not name:
  1095. GMessage(parent=self,
  1096. message=_("Name not given, settings is not saved."))
  1097. else:
  1098. self.settingsSaving.emit(name=name)
  1099. dlg.Destroy()
  1100. def SaveSettings(self, name):
  1101. # check if settings item already exists
  1102. if name in self._settings:
  1103. dlgOwt = wx.MessageDialog(
  1104. self,
  1105. message=_(
  1106. "Settings <%s> already exists. "
  1107. "Do you want to overwrite the settings?") %
  1108. name,
  1109. caption=_("Save settings"),
  1110. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  1111. if dlgOwt.ShowModal() != wx.ID_YES:
  1112. dlgOwt.Destroy()
  1113. return
  1114. if self.data_to_save:
  1115. self._settings[name] = self.data_to_save
  1116. self._saveSettings()
  1117. self.settingsChoice.SetStringSelection(name)
  1118. self.data_to_save = []
  1119. def _saveSettings(self):
  1120. """Save settings and reload if successful"""
  1121. if self._writeSettings() == 0:
  1122. self._settings = self._loadSettings()
  1123. def SetDataToSave(self, data):
  1124. """Set data for setting, which will be saved.
  1125. :param data: - list of strings, which will be saved
  1126. """
  1127. self.data_to_save = data
  1128. def SetSettings(self, settings):
  1129. """Set settings
  1130. :param settings: - dict with all settigs {nameofsetting : settingdata, ....}
  1131. """
  1132. self._settings = settings
  1133. self._saveSettings()
  1134. def AddSettings(self, settings):
  1135. """Add settings
  1136. :param settings: - dict with all settigs {nameofsetting : settingdata, ....}
  1137. """
  1138. self._settings.update(settings)
  1139. self._saveSettings()
  1140. def OnSettingsDelete(self, event):
  1141. """Save settings
  1142. """
  1143. name = self.settingsChoice.GetStringSelection()
  1144. if not name:
  1145. GMessage(parent=self,
  1146. message=_("No settings is defined. Operation canceled."))
  1147. return
  1148. self._settings.pop(name)
  1149. if self._writeSettings() == 0:
  1150. self._settings = self._loadSettings()
  1151. def _writeSettings(self):
  1152. """Save settings into the file
  1153. :return: 0 on success
  1154. :return: -1 on failure
  1155. """
  1156. try:
  1157. fd = open(self.settingsFile, 'w')
  1158. fd.write('format_version=2.0\n')
  1159. for key, values in six.iteritems(self._settings):
  1160. first = True
  1161. for v in values:
  1162. # escaping characters
  1163. for e_ch in self.esc_chars:
  1164. v = v.replace(
  1165. e_ch, self.esc_chars[
  1166. self.e_char_i] + e_ch)
  1167. if first:
  1168. # escaping characters
  1169. for e_ch in self.esc_chars:
  1170. key = key.replace(
  1171. e_ch, self.esc_chars[
  1172. self.e_char_i] + e_ch)
  1173. fd.write('%s;%s;' % (key, v))
  1174. first = False
  1175. else:
  1176. fd.write('%s;' % (v))
  1177. fd.write('\n')
  1178. except IOError:
  1179. GError(parent=self,
  1180. message=_("Unable to save settings"))
  1181. return -1
  1182. fd.close()
  1183. return 0
  1184. def _loadSettings(self):
  1185. """Load settings from the file
  1186. The file is defined by self.SettingsFile.
  1187. :return: parsed dict
  1188. :return: empty dict on error
  1189. """
  1190. data = dict()
  1191. if not os.path.exists(self.settingsFile):
  1192. return data
  1193. try:
  1194. fd = open(self.settingsFile, 'r')
  1195. except IOError:
  1196. return data
  1197. fd_lines = fd.readlines()
  1198. if not fd_lines:
  1199. fd.close()
  1200. return data
  1201. if fd_lines[0].strip() == 'format_version=2.0':
  1202. data = self._loadSettings_v2(fd_lines)
  1203. else:
  1204. data = self._loadSettings_v1(fd_lines)
  1205. self.settingsChoice.SetItems(sorted(data.keys()))
  1206. fd.close()
  1207. self.settingsLoaded.emit(settings=data)
  1208. return data
  1209. def _loadSettings_v2(self, fd_lines):
  1210. """Load settings from the file in format version 2.0
  1211. The file is defined by self.SettingsFile.
  1212. :return: parsed dict
  1213. :return: empty dict on error
  1214. """
  1215. data = dict()
  1216. for line in fd_lines[1:]:
  1217. try:
  1218. lineData = []
  1219. line = line.rstrip('\n')
  1220. i_last_found = i_last = 0
  1221. key = ''
  1222. while True:
  1223. idx = line.find(';', i_last)
  1224. if idx < 0:
  1225. break
  1226. elif idx != 0:
  1227. # find out whether it is separator
  1228. # $$$$; - it is separator
  1229. # $$$$$; - it is not separator
  1230. i_esc_chars = 0
  1231. while True:
  1232. if line[idx - (i_esc_chars + 1)
  1233. ] == self.esc_chars[self.e_char_i]:
  1234. i_esc_chars += 1
  1235. else:
  1236. break
  1237. if i_esc_chars % 2 != 0:
  1238. i_last = idx + 1
  1239. continue
  1240. lineItem = line[i_last_found: idx]
  1241. # unescape characters
  1242. for e_ch in self.esc_chars:
  1243. lineItem = lineItem.replace(
  1244. self.esc_chars[self.e_char_i] + e_ch, e_ch)
  1245. if i_last_found == 0:
  1246. key = lineItem
  1247. else:
  1248. lineData.append(lineItem)
  1249. i_last_found = i_last = idx + 1
  1250. if key and lineData:
  1251. data[key] = lineData
  1252. except ValueError:
  1253. pass
  1254. return data
  1255. def _loadSettings_v1(self, fd_lines):
  1256. """Load settings from the file in format version 1.0 (backward compatibility)
  1257. The file is defined by self.SettingsFile.
  1258. :return: parsed dict
  1259. :return: empty dict on error
  1260. """
  1261. data = dict()
  1262. for line in fd_lines:
  1263. try:
  1264. lineData = line.rstrip('\n').split(';')
  1265. if len(lineData) > 4:
  1266. # type, dsn, format, options
  1267. data[
  1268. lineData[0]] = (
  1269. lineData[1],
  1270. lineData[2],
  1271. lineData[3],
  1272. lineData[4])
  1273. else:
  1274. data[
  1275. lineData[0]] = (
  1276. lineData[1],
  1277. lineData[2],
  1278. lineData[3],
  1279. '')
  1280. except ValueError:
  1281. pass
  1282. return data
  1283. class PictureComboBox(OwnerDrawnComboBox):
  1284. """Abstract class of ComboBox with pictures.
  1285. Derived class has to specify has to specify _getPath method.
  1286. """
  1287. def OnDrawItem(self, dc, rect, item, flags):
  1288. """Overridden from OwnerDrawnComboBox.
  1289. Called to draw each item in the list.
  1290. """
  1291. if item == wx.NOT_FOUND:
  1292. # painting the control, but there is no valid item selected yet
  1293. return
  1294. r = Rect(*rect) # make a copy
  1295. r.Deflate(3, 5)
  1296. # for painting the items in the popup
  1297. bitmap = self.GetPictureBitmap(self.GetString(item))
  1298. if bitmap:
  1299. dc.DrawBitmap(
  1300. bitmap, r.x, r.y + (r.height - bitmap.GetHeight()) / 2)
  1301. width = bitmap.GetWidth() + 10
  1302. else:
  1303. width = 0
  1304. dc.DrawText(self.GetString(item),
  1305. r.x + width,
  1306. (r.y + 0) + (r.height - dc.GetCharHeight()) / 2)
  1307. def OnMeasureItem(self, item):
  1308. """Overridden from OwnerDrawnComboBox, should return the height.
  1309. Needed to display an item in the popup, or -1 for default.
  1310. """
  1311. return 24
  1312. def GetPictureBitmap(self, name):
  1313. """Returns bitmap for given picture name.
  1314. :param str colorTable: name of color table
  1315. """
  1316. if not hasattr(self, 'bitmaps'):
  1317. self.bitmaps = {}
  1318. if name in self.bitmaps:
  1319. return self.bitmaps[name]
  1320. path = self._getPath(name)
  1321. if os.path.exists(path):
  1322. bitmap = wx.Bitmap(path)
  1323. self.bitmaps[name] = bitmap
  1324. return bitmap
  1325. return None
  1326. class ColorTablesComboBox(PictureComboBox):
  1327. """ComboBox with drawn color tables (created by thumbnails.py).
  1328. Used in r(3).colors dialog."""
  1329. def _getPath(self, name):
  1330. return os.path.join(
  1331. os.getenv("GISBASE"),
  1332. "docs", "html", "colortables", "%s.png" % name)
  1333. class BarscalesComboBox(PictureComboBox):
  1334. """ComboBox with barscales for d.barscale."""
  1335. def _getPath(self, name):
  1336. return os.path.join(
  1337. os.getenv("GISBASE"),
  1338. "docs", "html", "barscales", name + '.png')
  1339. class NArrowsComboBox(PictureComboBox):
  1340. """ComboBox with north arrows for d.barscale."""
  1341. def _getPath(self, name):
  1342. return os.path.join(
  1343. os.getenv("GISBASE"),
  1344. "docs", "html", "northarrows", "%s.png" % name)
  1345. class LayersList(GListCtrl, listmix.TextEditMixin):
  1346. """List of layers to be imported (dxf, shp...)"""
  1347. def __init__(self, parent, columns, log=None):
  1348. GListCtrl.__init__(self, parent)
  1349. self.log = log
  1350. self.row = None
  1351. self.col = None
  1352. self.output_map = None
  1353. self.validate = True
  1354. # setup mixins
  1355. listmix.TextEditMixin.__init__(self)
  1356. for i in range(len(columns)):
  1357. self.InsertColumn(i, columns[i])
  1358. width = []
  1359. if len(columns) == 3:
  1360. width = (65, 200)
  1361. elif len(columns) == 4:
  1362. width = (65, 200, 90)
  1363. elif len(columns) == 5:
  1364. width = (65, 180, 90, 70)
  1365. for i in range(len(width)):
  1366. self.SetColumnWidth(col=i, width=width[i])
  1367. def OnLeftDown(self, event):
  1368. """Allow editing only output name
  1369. Code taken from TextEditMixin class.
  1370. """
  1371. x, y = event.GetPosition()
  1372. colLocs = [0]
  1373. loc = 0
  1374. for n in range(self.GetColumnCount()):
  1375. loc = loc + self.GetColumnWidth(n)
  1376. colLocs.append(loc)
  1377. col = bisect(colLocs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
  1378. if col == self.GetColumnCount() - 1:
  1379. listmix.TextEditMixin.OnLeftDown(self, event)
  1380. else:
  1381. event.Skip()
  1382. def GetLayers(self):
  1383. """Get list of layers (layer name, output name, list id)"""
  1384. layers = []
  1385. data = self.GetData(checked=True)
  1386. for itm in data:
  1387. layer = itm[1]
  1388. ftype = itm[2]
  1389. if '/' in ftype:
  1390. layer += '|%s' % ftype.split('/', 1)[0]
  1391. output = itm[self.GetColumnCount() - 1]
  1392. layers.append((layer, output, itm[-1]))
  1393. return layers
  1394. def ValidateOutputMapName(self):
  1395. """Validate output map name"""
  1396. wx.CallAfter(self.GetValidator().Validate, self)
  1397. def OpenEditor(self, row, col):
  1398. """Open editor"""
  1399. self.col = col
  1400. self.row = row
  1401. super().OpenEditor(row, col)
  1402. def CloseEditor(self, event=None):
  1403. """Close editor"""
  1404. if event:
  1405. if event.IsCommandEvent():
  1406. listmix.TextEditMixin.CloseEditor(self, event)
  1407. if self.validate:
  1408. self.ValidateOutputMapName()
  1409. event.Skip()