widgets.py 55 KB

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