widgets.py 56 KB

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