widgets.py 55 KB

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