widgets.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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::IntegerValidator
  13. - widgets::FloatValidator
  14. - widgets::ItemTree
  15. (C) 2008-2011 by the GRASS Development Team
  16. This program is free software under the GNU General Public License
  17. (>=v2). Read the file COPYING that comes with GRASS for details.
  18. @author Martin Landa <landa.martin gmail.com> (Google SoC 2008/2010)
  19. @author Enhancements by Michael Barton <michael.barton asu.edu>
  20. @author Anna Kratochvilova <kratochanna gmail.com> (Google SoC 2011)
  21. """
  22. import os
  23. import sys
  24. import string
  25. import wx
  26. import wx.lib.scrolledpanel as SP
  27. try:
  28. import wx.lib.agw.flatnotebook as FN
  29. except ImportError:
  30. import wx.lib.flatnotebook as FN
  31. try:
  32. from wx.lib.buttons import ThemedGenBitmapTextButton as BitmapTextButton
  33. except ImportError: # not sure about TGBTButton version
  34. from wx.lib.buttons import GenBitmapTextButton as BitmapTextButton
  35. try:
  36. import wx.lib.agw.customtreectrl as CT
  37. except ImportError:
  38. import wx.lib.customtreectrl as CT
  39. from core import globalvar
  40. from core.debug import Debug
  41. from wx.lib.newevent import NewEvent
  42. wxSymbolSelectionChanged, EVT_SYMBOL_SELECTION_CHANGED = NewEvent()
  43. class GNotebook(FN.FlatNotebook):
  44. """!Generic notebook widget
  45. """
  46. def __init__(self, parent, style, **kwargs):
  47. if globalvar.hasAgw:
  48. FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, agwStyle = style, **kwargs)
  49. else:
  50. FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, style = style, **kwargs)
  51. self.notebookPages = {}
  52. def AddPage(self, **kwargs):
  53. """!Add a new page
  54. """
  55. if 'name' in kwargs:
  56. self.notebookPages[kwargs['name']] = kwargs['page']
  57. del kwargs['name']
  58. super(GNotebook, self).AddPage(**kwargs)
  59. def InsertPage(self, **kwargs):
  60. """!Insert a new page
  61. """
  62. if 'name' in kwargs:
  63. self.notebookPages[kwargs['name']] = kwargs['page']
  64. del kwargs['name']
  65. super(GNotebook, self).InsertPage(**kwargs)
  66. def SetSelectionByName(self, page):
  67. """!Set notebook
  68. @param page names, eg. 'layers', 'output', 'search', 'pyshell', 'nviz'
  69. """
  70. idx = self.GetPageIndexByName(page)
  71. if self.GetSelection() != idx:
  72. self.SetSelection(idx)
  73. def GetPageIndexByName(self, page):
  74. """!Get notebook page index
  75. @param page name
  76. """
  77. if page not in self.notebookPages:
  78. return -1
  79. return self.GetPageIndex(self.notebookPages[page])
  80. class ScrolledPanel(SP.ScrolledPanel):
  81. """!Custom ScrolledPanel to avoid strange behaviour concerning focus"""
  82. def __init__(self, parent, style = wx.TAB_TRAVERSAL):
  83. SP.ScrolledPanel.__init__(self, parent = parent, id = wx.ID_ANY, style = style)
  84. def OnChildFocus(self, event):
  85. pass
  86. class NumTextCtrl(wx.TextCtrl):
  87. """!Class derived from wx.TextCtrl for numerical values only"""
  88. def __init__(self, parent, **kwargs):
  89. ## self.precision = kwargs.pop('prec')
  90. wx.TextCtrl.__init__(self, parent = parent,
  91. validator = NTCValidator(flag = 'DIGIT_ONLY'), **kwargs)
  92. def SetValue(self, value):
  93. super(NumTextCtrl, self).SetValue( str(value))
  94. def GetValue(self):
  95. val = super(NumTextCtrl, self).GetValue()
  96. if val == '':
  97. val = '0'
  98. try:
  99. return float(val)
  100. except ValueError:
  101. val = ''.join(''.join(val.split('-')).split('.'))
  102. return float(val)
  103. def SetRange(self, min, max):
  104. pass
  105. class FloatSlider(wx.Slider):
  106. """!Class derived from wx.Slider for floats"""
  107. def __init__(self, **kwargs):
  108. Debug.msg(1, "FloatSlider.__init__()")
  109. wx.Slider.__init__(self, **kwargs)
  110. self.coef = 1.
  111. #init range
  112. self.minValueOrig = 0
  113. self.maxValueOrig = 1
  114. def SetValue(self, value):
  115. value *= self.coef
  116. if abs(value) < 1 and value != 0:
  117. while abs(value) < 1:
  118. value *= 100
  119. self.coef *= 100
  120. super(FloatSlider, self).SetRange(self.minValueOrig * self.coef, self.maxValueOrig * self.coef)
  121. super(FloatSlider, self).SetValue(value)
  122. Debug.msg(4, "FloatSlider.SetValue(): value = %f" % value)
  123. def SetRange(self, minValue, maxValue):
  124. self.coef = 1.
  125. self.minValueOrig = minValue
  126. self.maxValueOrig = maxValue
  127. if abs(minValue) < 1 or abs(maxValue) < 1:
  128. while (abs(minValue) < 1 and minValue != 0) or (abs(maxValue) < 1 and maxValue != 0):
  129. minValue *= 100
  130. maxValue *= 100
  131. self.coef *= 100
  132. super(FloatSlider, self).SetValue(super(FloatSlider, self).GetValue() * self.coef)
  133. super(FloatSlider, self).SetRange(minValue, maxValue)
  134. Debug.msg(4, "FloatSlider.SetRange(): minValue = %f, maxValue = %f" % (minValue, maxValue))
  135. def GetValue(self):
  136. val = super(FloatSlider, self).GetValue()
  137. Debug.msg(4, "FloatSlider.GetValue(): value = %f" % (val/self.coef))
  138. return val/self.coef
  139. class SymbolButton(BitmapTextButton):
  140. """!Button with symbol and label."""
  141. def __init__(self, parent, usage, label, **kwargs):
  142. """!Constructor
  143. @param parent parent (usually wx.Panel)
  144. @param usage determines usage and picture
  145. @param label displayed label
  146. """
  147. size = (15, 15)
  148. buffer = wx.EmptyBitmap(*size)
  149. BitmapTextButton.__init__(self, parent = parent, label = " " + label, bitmap = buffer, **kwargs)
  150. dc = wx.MemoryDC()
  151. dc.SelectObject(buffer)
  152. maskColor = wx.Color(255, 255, 255)
  153. dc.SetBrush(wx.Brush(maskColor))
  154. dc.Clear()
  155. if usage == 'record':
  156. self.DrawRecord(dc, size)
  157. elif usage == 'stop':
  158. self.DrawStop(dc, size)
  159. elif usage == 'play':
  160. self.DrawPlay(dc, size)
  161. elif usage == 'pause':
  162. self.DrawPause(dc, size)
  163. if sys.platform != "win32":
  164. buffer.SetMaskColour(maskColor)
  165. self.SetBitmapLabel(buffer)
  166. dc.SelectObject(wx.NullBitmap)
  167. def DrawRecord(self, dc, size):
  168. """!Draw record symbol"""
  169. dc.SetBrush(wx.Brush(wx.Color(255, 0, 0)))
  170. dc.DrawCircle(size[0]/2, size[1] / 2, size[0] / 2)
  171. def DrawStop(self, dc, size):
  172. """!Draw stop symbol"""
  173. dc.SetBrush(wx.Brush(wx.Color(50, 50, 50)))
  174. dc.DrawRectangle(0, 0, size[0], size[1])
  175. def DrawPlay(self, dc, size):
  176. """!Draw play symbol"""
  177. dc.SetBrush(wx.Brush(wx.Color(0, 255, 0)))
  178. points = (wx.Point(0, 0), wx.Point(0, size[1]), wx.Point(size[0], size[1] / 2))
  179. dc.DrawPolygon(points)
  180. def DrawPause(self, dc, size):
  181. """!Draw pause symbol"""
  182. dc.SetBrush(wx.Brush(wx.Color(50, 50, 50)))
  183. dc.DrawRectangle(0, 0, 2 * size[0] / 5, size[1])
  184. dc.DrawRectangle(3 * size[0] / 5, 0, 2 * size[0] / 5, size[1])
  185. class StaticWrapText(wx.StaticText):
  186. """!A Static Text field that wraps its text to fit its width,
  187. enlarging its height if necessary.
  188. """
  189. def __init__(self, parent, id = wx.ID_ANY, label = '', *args, **kwds):
  190. self.parent = parent
  191. self.originalLabel = label
  192. wx.StaticText.__init__(self, parent, id, label = '', *args, **kwds)
  193. self.SetLabel(label)
  194. self.Bind(wx.EVT_SIZE, self.OnResize)
  195. def SetLabel(self, label):
  196. self.originalLabel = label
  197. self.wrappedSize = None
  198. self.OnResize(None)
  199. def OnResize(self, event):
  200. if not getattr(self, "resizing", False):
  201. self.resizing = True
  202. newSize = wx.Size(self.parent.GetSize().width - 50,
  203. self.GetSize().height)
  204. if self.wrappedSize != newSize:
  205. wx.StaticText.SetLabel(self, self.originalLabel)
  206. self.Wrap(newSize.width)
  207. self.wrappedSize = newSize
  208. self.SetSize(self.wrappedSize)
  209. del self.resizing
  210. class BaseValidator(wx.PyValidator):
  211. def __init__(self):
  212. wx.PyValidator.__init__(self)
  213. self.Bind(wx.EVT_TEXT, self.OnText)
  214. def OnText(self, event):
  215. """!Do validation"""
  216. self.Validate()
  217. event.Skip()
  218. def Validate(self):
  219. """Validate input"""
  220. textCtrl = self.GetWindow()
  221. text = textCtrl.GetValue()
  222. if text:
  223. try:
  224. self.type(text)
  225. except ValueError:
  226. textCtrl.SetBackgroundColour("grey")
  227. textCtrl.SetFocus()
  228. textCtrl.Refresh()
  229. return False
  230. sysColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)
  231. textCtrl.SetBackgroundColour(sysColor)
  232. textCtrl.Refresh()
  233. return True
  234. def TransferToWindow(self):
  235. return True # Prevent wxDialog from complaining.
  236. def TransferFromWindow(self):
  237. return True # Prevent wxDialog from complaining.
  238. class IntegerValidator(BaseValidator):
  239. """!Validator for floating-point input"""
  240. def __init__(self):
  241. BaseValidator.__init__(self)
  242. self.type = int
  243. def Clone(self):
  244. """!Clone validator"""
  245. return IntegerValidator()
  246. class FloatValidator(BaseValidator):
  247. """!Validator for floating-point input"""
  248. def __init__(self):
  249. BaseValidator.__init__(self)
  250. self.type = float
  251. def Clone(self):
  252. """!Clone validator"""
  253. return FloatValidator()
  254. class NTCValidator(wx.PyValidator):
  255. """!validates input in textctrls, taken from wxpython demo"""
  256. def __init__(self, flag = None):
  257. wx.PyValidator.__init__(self)
  258. self.flag = flag
  259. self.Bind(wx.EVT_CHAR, self.OnChar)
  260. def Clone(self):
  261. return NTCValidator(self.flag)
  262. def OnChar(self, event):
  263. key = event.GetKeyCode()
  264. if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255:
  265. event.Skip()
  266. return
  267. if self.flag == 'DIGIT_ONLY' and chr(key) in string.digits + '.-':
  268. event.Skip()
  269. return
  270. if not wx.Validator_IsSilent():
  271. wx.Bell()
  272. # Returning without calling even.Skip eats the event before it
  273. # gets to the text control
  274. return
  275. class ItemTree(CT.CustomTreeCtrl):
  276. def __init__(self, parent, id = wx.ID_ANY,
  277. ctstyle = CT.TR_HIDE_ROOT | CT.TR_FULL_ROW_HIGHLIGHT | CT.TR_HAS_BUTTONS |
  278. CT.TR_LINES_AT_ROOT | CT.TR_SINGLE, **kwargs):
  279. if globalvar.hasAgw:
  280. super(ItemTree, self).__init__(parent, id, agwStyle = ctstyle, **kwargs)
  281. else:
  282. super(ItemTree, self).__init__(parent, id, style = ctstyle, **kwargs)
  283. self.root = self.AddRoot(_("Menu tree"))
  284. self.itemsMarked = [] # list of marked items
  285. self.itemSelected = None
  286. def SearchItems(self, element, value):
  287. """!Search item
  288. @param element element index (see self.searchBy)
  289. @param value
  290. @return list of found tree items
  291. """
  292. items = list()
  293. if not value:
  294. return items
  295. item = self.GetFirstChild(self.root)[0]
  296. self._processItem(item, element, value, items)
  297. self.itemsMarked = items
  298. self.itemSelected = None
  299. return items
  300. def _processItem(self, item, element, value, listOfItems):
  301. """!Search items (used by SearchItems)
  302. @param item reference item
  303. @param listOfItems list of found items
  304. """
  305. while item and item.IsOk():
  306. subItem = self.GetFirstChild(item)[0]
  307. if subItem:
  308. self._processItem(subItem, element, value, listOfItems)
  309. data = self.GetPyData(item)
  310. if data and element in data and \
  311. value.lower() in data[element].lower():
  312. listOfItems.append(item)
  313. item = self.GetNextSibling(item)
  314. def GetSelected(self):
  315. """!Get selected item"""
  316. return self.itemSelected
  317. def OnShowItem(self, event):
  318. """!Highlight first found item in menu tree"""
  319. if len(self.itemsMarked) > 0:
  320. if self.GetSelected():
  321. self.ToggleItemSelection(self.GetSelected())
  322. idx = self.itemsMarked.index(self.GetSelected()) + 1
  323. else:
  324. idx = 0
  325. try:
  326. self.ToggleItemSelection(self.itemsMarked[idx])
  327. self.itemSelected = self.itemsMarked[idx]
  328. self.EnsureVisible(self.itemsMarked[idx])
  329. except IndexError:
  330. self.ToggleItemSelection(self.itemsMarked[0]) # reselect first item
  331. self.EnsureVisible(self.itemsMarked[0])
  332. self.itemSelected = self.itemsMarked[0]
  333. else:
  334. for item in self.root.GetChildren():
  335. self.Collapse(item)
  336. itemSelected = self.GetSelection()
  337. if itemSelected:
  338. self.ToggleItemSelection(itemSelected)
  339. self.itemSelected = None
  340. class SingleSymbolPanel(wx.Panel):
  341. """!Panel for displaying one symbol.
  342. Changes background when selected. Assumes that parent will catch
  343. events emitted on mouse click. Used in gui_core::dialog::SymbolDialog.
  344. """
  345. def __init__(self, parent, symbolPath):
  346. """!Panel constructor
  347. @param parent parent (gui_core::dialog::SymbolDialog)
  348. @param symbolPath absolute path to symbol
  349. """
  350. wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.BORDER_RAISED)
  351. self.SetName(os.path.splitext(os.path.basename(symbolPath))[0])
  352. self.sBmp = wx.StaticBitmap(self, wx.ID_ANY, wx.Bitmap(symbolPath))
  353. self.selected = False
  354. self.selectColor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
  355. self.deselectColor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
  356. sizer = wx.BoxSizer()
  357. sizer.Add(item = self.sBmp, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 5)
  358. self.SetBackgroundColour(self.deselectColor)
  359. self.SetMinSize(self.GetBestSize())
  360. self.SetSizerAndFit(sizer)
  361. # binding to both (staticBitmap, Panel) necessary
  362. self.sBmp.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
  363. self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
  364. self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
  365. self.sBmp.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
  366. def OnLeftDown(self, event):
  367. """!Panel selected, background changes"""
  368. self.selected = True
  369. self.SetBackgroundColour(self.selectColor)
  370. event.Skip()
  371. event = wxSymbolSelectionChanged(name = self.GetName(), doubleClick = False)
  372. wx.PostEvent(self.GetParent(), event)
  373. def OnDoubleClick(self, event):
  374. event = wxSymbolSelectionChanged(name = self.GetName(), doubleClick = True)
  375. wx.PostEvent(self.GetParent(), event)
  376. def Deselect(self):
  377. """!Panel deselected, background changes back to default"""
  378. self.selected = False
  379. self.SetBackgroundColour(self.deselectColor)
  380. def Select(self):
  381. """!Select panel, no event emitted"""
  382. self.selected = True
  383. self.SetBackgroundColour(self.selectColor)