[GRASS-SVN] r53948 - in grass/trunk/gui/wxpython: . gui_core
svn_grass at osgeo.org
svn_grass at osgeo.org
Wed Nov 21 01:37:56 PST 2012
Author: annakrat
Date: 2012-11-21 01:37:55 -0800 (Wed, 21 Nov 2012)
New Revision: 53948
Modified:
grass/trunk/gui/wxpython/gui_core/prompt.py
grass/trunk/gui/wxpython/wxpythonlib.dox
Log:
wxGUI/prompt: remove unused and not maintained classes - PromptListCtrl, TextCtrlAutoComplete, GPromptPopUp
Modified: grass/trunk/gui/wxpython/gui_core/prompt.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/prompt.py 2012-11-21 09:37:46 UTC (rev 53947)
+++ grass/trunk/gui/wxpython/gui_core/prompt.py 2012-11-21 09:37:55 UTC (rev 53948)
@@ -4,10 +4,7 @@
@brief wxGUI command prompt
Classes:
- - prompt::PromptListCtrl
- - prompt::TextCtrlAutoComplete
- prompt::GPrompt
- - prompt::GPromptPopUp
- prompt::GPromptSTC
(C) 2009-2011 by the GRASS Development Team
@@ -21,13 +18,11 @@
"""
import os
-import sys
import difflib
import codecs
import wx
import wx.stc
-import wx.lib.mixins.listctrl as listmix
from wx.lib.newevent import NewEvent
@@ -39,435 +34,6 @@
from core.gcmd import EncodeString, DecodeString, GetRealCmd
from core.events import gShowNotification
-class PromptListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
- """!PopUp window used by GPromptPopUp"""
- def __init__(self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition,
- size = wx.DefaultSize, style = 0):
- wx.ListCtrl.__init__(self, parent, id, pos, size, style)
- listmix.ListCtrlAutoWidthMixin.__init__(self)
-
-class TextCtrlAutoComplete(wx.ComboBox, listmix.ColumnSorterMixin):
- """!Auto complete text area used by GPromptPopUp"""
- def __init__ (self, parent, statusbar,
- id = wx.ID_ANY, choices = [], **kwargs):
- """!Constructor works just like wx.TextCtrl except you can pass in a
- list of choices. You can also change the choice list at any time
- by calling setChoices.
-
- Inspired by http://wiki.wxpython.org/TextCtrlAutoComplete
- """
- self.statusbar = statusbar
-
- if 'style' in kwargs:
- kwargs['style'] = wx.TE_PROCESS_ENTER | kwargs['style']
- else:
- kwargs['style'] = wx.TE_PROCESS_ENTER
-
- wx.ComboBox.__init__(self, parent, id, **kwargs)
-
- # some variables
- self._choices = choices
- self._hideOnNoMatch = True
- self._module = None # currently selected module
- self._choiceType = None # type of choice (module, params, flags, raster, vector ...)
- self._screenheight = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)
- self._historyItem = 0 # last item
-
- # sort variable needed by listmix
- self.itemDataMap = dict()
-
- # widgets
- try:
- self.dropdown = wx.PopupWindow(self)
- except NotImplementedError:
- self.Destroy()
- raise NotImplementedError
-
- # create the list and bind the events
- self.dropdownlistbox = PromptListCtrl(parent = self.dropdown,
- style = wx.LC_REPORT | wx.LC_SINGLE_SEL | \
- wx.LC_SORT_ASCENDING | wx.LC_NO_HEADER,
- pos = wx.Point(0, 0))
-
- listmix.ColumnSorterMixin.__init__(self, 1)
-
- # set choices (list of GRASS modules)
- self._choicesCmd = globalvar.grassCmd
- self._choicesMap = dict()
- for type in ('raster', 'vector'):
- self._choicesMap[type] = grass.list_strings(type = type[:4])
- # first search for GRASS module
- self.SetChoices(self._choicesCmd)
-
- self.SetMinSize(self.GetSize())
-
- # bindings...
- self.Bind(wx.EVT_KILL_FOCUS, self.OnControlChanged)
- self.Bind(wx.EVT_TEXT, self.OnEnteredText)
- self.Bind(wx.EVT_TEXT_ENTER, self.OnRunCmd)
- self.Bind(wx.EVT_KEY_DOWN , self.OnKeyDown)
- ### self.Bind(wx.EVT_LEFT_DOWN, self.OnClick)
-
- # if need drop down on left click
- self.dropdown.Bind(wx.EVT_LISTBOX , self.OnListItemSelected, self.dropdownlistbox)
- self.dropdownlistbox.Bind(wx.EVT_LEFT_DOWN, self.OnListClick)
- self.dropdownlistbox.Bind(wx.EVT_LEFT_DCLICK, self.OnListDClick)
- self.dropdownlistbox.Bind(wx.EVT_LIST_COL_CLICK, self.OnListColClick)
-
- self.Bind(wx.EVT_COMBOBOX, self.OnCommandSelect)
-
- def _updateDataList(self, choices):
- """!Update data list"""
- # delete, if need, all the previous data
- if self.dropdownlistbox.GetColumnCount() != 0:
- self.dropdownlistbox.DeleteAllColumns()
- self.dropdownlistbox.DeleteAllItems()
- # and update the dict
- if choices:
- for numVal, data in enumerate(choices):
- self.itemDataMap[numVal] = data
- else:
- numVal = 0
- self.SetColumnCount(numVal)
-
- def _setListSize(self):
- """!Set list size"""
- choices = self._choices
- longest = 0
- for choice in choices:
- longest = max(len(choice), longest)
- longest += 3
- itemcount = min(len( choices ), 7) + 2
- charheight = self.dropdownlistbox.GetCharHeight()
- charwidth = self.dropdownlistbox.GetCharWidth()
- self.popupsize = wx.Size(charwidth*longest, charheight*itemcount)
- self.dropdownlistbox.SetSize(self.popupsize)
- self.dropdown.SetClientSize(self.popupsize)
-
- def _showDropDown(self, show = True):
- """!Either display the drop down list (show = True) or hide it
- (show = False).
- """
- if show:
- size = self.dropdown.GetSize()
- width, height = self.GetSizeTuple()
- x, y = self.ClientToScreenXY(0, height)
- if size.GetWidth() != width:
- size.SetWidth(width)
- self.dropdown.SetSize(size)
- self.dropdownlistbox.SetSize(self.dropdown.GetClientSize())
- if (y + size.GetHeight()) < self._screenheight:
- self.dropdown.SetPosition(wx.Point(x, y))
- else:
- self.dropdown.SetPosition(wx.Point(x, y - height - size.GetHeight()))
-
- self.dropdown.Show(show)
-
- def _listItemVisible(self):
- """!Moves the selected item to the top of the list ensuring it is
- always visible.
- """
- toSel = self.dropdownlistbox.GetFirstSelected()
- if toSel == -1:
- return
- self.dropdownlistbox.EnsureVisible(toSel)
-
- def _setModule(self, name):
- """!Set module's choices (flags, parameters)"""
- # get module's description
- if name in self._choicesCmd and not self._module:
- try:
- self._module = gtask.parse_interface(name)
- except IOError:
- self._module = None
-
- # set choices (flags)
- self._choicesMap['flag'] = self._module.get_list_flags()
- for idx in range(len(self._choicesMap['flag'])):
- item = self._choicesMap['flag'][idx]
- desc = self._module.get_flag(item)['label']
- if not desc:
- desc = self._module.get_flag(item)['description']
-
- self._choicesMap['flag'][idx] = '%s (%s)' % (item, desc)
-
- # set choices (parameters)
- self._choicesMap['param'] = self._module.get_list_params()
- for idx in range(len(self._choicesMap['param'])):
- item = self._choicesMap['param'][idx]
- desc = self._module.get_param(item)['label']
- if not desc:
- desc = self._module.get_param(item)['description']
-
- self._choicesMap['param'][idx] = '%s (%s)' % (item, desc)
-
- def _setValueFromSelected(self):
- """!Sets the wx.TextCtrl value from the selected wx.ListCtrl item.
- Will do nothing if no item is selected in the wx.ListCtrl.
- """
- sel = self.dropdownlistbox.GetFirstSelected()
- if sel < 0:
- return
-
- if self._colFetch != -1:
- col = self._colFetch
- else:
- col = self._colSearch
- itemtext = self.dropdownlistbox.GetItem(sel, col).GetText()
-
- cmd = utils.split(str(self.GetValue()))
- if len(cmd) > 0 and cmd[0] in self._choicesCmd:
- # -> append text (skip last item)
- if self._choiceType == 'param':
- itemtext = itemtext.split(' ')[0]
- self.SetValue(' '.join(cmd) + ' ' + itemtext + '=')
- optType = self._module.get_param(itemtext)['prompt']
- if optType in ('raster', 'vector'):
- # -> raster/vector map
- self.SetChoices(self._choicesMap[optType], optType)
- elif self._choiceType == 'flag':
- itemtext = itemtext.split(' ')[0]
- if len(itemtext) > 1:
- prefix = '--'
- else:
- prefix = '-'
- self.SetValue(' '.join(cmd[:-1]) + ' ' + prefix + itemtext)
- elif self._choiceType in ('raster', 'vector'):
- self.SetValue(' '.join(cmd[:-1]) + ' ' + cmd[-1].split('=', 1)[0] + '=' + itemtext)
- else:
- # -> reset text
- self.SetValue(itemtext + ' ')
-
- # define module
- self._setModule(itemtext)
-
- # use parameters as default choices
- self._choiceType = 'param'
- self.SetChoices(self._choicesMap['param'], type = 'param')
-
- self.SetInsertionPointEnd()
-
- self._showDropDown(False)
-
- def GetListCtrl(self):
- """!Method required by listmix.ColumnSorterMixin"""
- return self.dropdownlistbox
-
- def SetChoices(self, choices, type = 'module'):
- """!Sets the choices available in the popup wx.ListBox.
- The items will be sorted case insensitively.
-
- @param choices list of choices
- @param type type of choices (module, param, flag, raster, vector)
- """
- self._choices = choices
- self._choiceType = type
-
- self.dropdownlistbox.SetWindowStyleFlag(wx.LC_REPORT | wx.LC_SINGLE_SEL |
- wx.LC_SORT_ASCENDING | wx.LC_NO_HEADER)
- if not isinstance(choices, list):
- self._choices = [ x for x in choices ]
- if self._choiceType not in ('raster', 'vector'):
- # do not sort raster/vector maps
- utils.ListSortLower(self._choices)
-
- self._updateDataList(self._choices)
-
- self.dropdownlistbox.InsertColumn(0, "")
- for num, colVal in enumerate(self._choices):
- index = self.dropdownlistbox.InsertImageStringItem(sys.maxint, colVal, -1)
- self.dropdownlistbox.SetStringItem(index, 0, colVal)
- self.dropdownlistbox.SetItemData(index, num)
- self._setListSize()
-
- # there is only one choice for both search and fetch if setting a single column:
- self._colSearch = 0
- self._colFetch = -1
-
- def OnClick(self, event):
- """Left mouse button pressed"""
- sel = self.dropdownlistbox.GetFirstSelected()
- if not self.dropdown.IsShown():
- if sel > -1:
- self.dropdownlistbox.Select(sel)
- else:
- self.dropdownlistbox.Select(0)
- self._listItemVisible()
- self._showDropDown()
- else:
- self.dropdown.Hide()
-
- def OnCommandSelect(self, event):
- """!Command selected from history"""
- self._historyItem = event.GetSelection() - len(self.GetItems())
- self.SetFocus()
-
- def OnListClick(self, evt):
- """!Left mouse button pressed"""
- toSel, flag = self.dropdownlistbox.HitTest( evt.GetPosition() )
- #no values on poition, return
- if toSel == -1: return
- self.dropdownlistbox.Select(toSel)
-
- def OnListDClick(self, evt):
- """!Mouse button double click"""
- self._setValueFromSelected()
-
- def OnListColClick(self, evt):
- """!Left mouse button pressed on column"""
- col = evt.GetColumn()
- # reverse the sort
- if col == self._colSearch:
- self._ascending = not self._ascending
- self.SortListItems( evt.GetColumn(), ascending=self._ascending )
- self._colSearch = evt.GetColumn()
- evt.Skip()
-
- def OnListItemSelected(self, event):
- """!Item selected"""
- self._setValueFromSelected()
- event.Skip()
-
- def OnEnteredText(self, event):
- """!Text entered"""
- text = event.GetString()
-
- if not text:
- # control is empty; hide dropdown if shown:
- if self.dropdown.IsShown():
- self._showDropDown(False)
- event.Skip()
- return
-
- try:
- cmd = utils.split(str(text))
- except ValueError, e:
- self.statusbar.SetStatusText(str(e))
- cmd = text.split(' ')
- pattern = str(text)
-
- if len(cmd) > 0 and cmd[0] in self._choicesCmd and not self._module:
- self._setModule(cmd[0])
- elif len(cmd) > 1 and cmd[0] in self._choicesCmd:
- if self._module:
- if len(cmd[-1].split('=', 1)) == 1:
- # new option
- if cmd[-1][0] == '-':
- # -> flags
- self.SetChoices(self._choicesMap['flag'], type = 'flag')
- pattern = cmd[-1].lstrip('-')
- else:
- # -> options
- self.SetChoices(self._choicesMap['param'], type = 'param')
- pattern = cmd[-1]
- else:
- # value
- pattern = cmd[-1].split('=', 1)[1]
- else:
- # search for GRASS modules
- if self._module:
- # -> switch back to GRASS modules list
- self.SetChoices(self._choicesCmd)
- self._module = None
- self._choiceType = None
-
- self._choiceType
- self._choicesMap
- found = False
- choices = self._choices
- for numCh, choice in enumerate(choices):
- if choice.lower().startswith(pattern):
- found = True
- if found:
- self._showDropDown(True)
- item = self.dropdownlistbox.GetItem(numCh)
- toSel = item.GetId()
- self.dropdownlistbox.Select(toSel)
- break
-
- if not found:
- self.dropdownlistbox.Select(self.dropdownlistbox.GetFirstSelected(), False)
- if self._hideOnNoMatch:
- self._showDropDown(False)
- if self._module and '=' not in cmd[-1]:
- message = ''
- if cmd[-1][0] == '-': # flag
- message = _("Warning: flag <%(flag)s> not found in '%(module)s'") % \
- { 'flag' : cmd[-1][1:], 'module' : self._module.name }
- else: # option
- message = _("Warning: option <%(param)s> not found in '%(module)s'") % \
- { 'param' : cmd[-1], 'module' : self._module.name }
- self.statusbar.SetStatusText(message)
-
- if self._module and len(cmd[-1]) == 2 and cmd[-1][-2] == '=':
- optType = self._module.get_param(cmd[-1][:-2])['prompt']
- if optType in ('raster', 'vector'):
- # -> raster/vector map
- self.SetChoices(self._choicesMap[optType], optType)
-
- self._listItemVisible()
-
- event.Skip()
-
- def OnKeyDown (self, event):
- """!Do some work when the user press on the keys: up and down:
- move the cursor left and right: move the search
- """
- skip = True
- sel = self.dropdownlistbox.GetFirstSelected()
- visible = self.dropdown.IsShown()
- KC = event.GetKeyCode()
-
- if KC == wx.WXK_RIGHT:
- # right -> show choices
- if sel < (self.dropdownlistbox.GetItemCount() - 1):
- self.dropdownlistbox.Select(sel + 1)
- self._listItemVisible()
- self._showDropDown()
- skip = False
- elif KC == wx.WXK_UP:
- if visible:
- if sel > 0:
- self.dropdownlistbox.Select(sel - 1)
- self._listItemVisible()
- self._showDropDown()
- skip = False
- else:
- self._historyItem -= 1
- try:
- self.SetValue(self.GetItems()[self._historyItem])
- except IndexError:
- self._historyItem += 1
- elif KC == wx.WXK_DOWN:
- if visible:
- if sel < (self.dropdownlistbox.GetItemCount() - 1):
- self.dropdownlistbox.Select(sel + 1)
- self._listItemVisible()
- self._showDropDown()
- skip = False
- else:
- if self._historyItem < -1:
- self._historyItem += 1
- self.SetValue(self.GetItems()[self._historyItem])
-
- if visible:
- if event.GetKeyCode() == wx.WXK_RETURN:
- self._setValueFromSelected()
- skip = False
- if event.GetKeyCode() == wx.WXK_ESCAPE:
- self._showDropDown(False)
- skip = False
- if skip:
- event.Skip()
-
- def OnControlChanged(self, event):
- """!Control changed"""
- if self.IsShown():
- self._showDropDown(False)
-
- event.Skip()
-
-
gPromptRunCmd, EVT_GPROMPT_RUN_CMD = NewEvent()
class GPrompt(object):
@@ -582,46 +148,8 @@
def ClearCommands(self):
"""!Clear list of commands"""
del self.commands[:]
-
-class GPromptPopUp(GPrompt, TextCtrlAutoComplete):
- """!Interactive wxGUI prompt - popup version"""
- def __init__(self, parent):
- GPrompt.__init__(self, parent)
-
- ### todo: fix TextCtrlAutoComplete to work also on Macs
- ### reason: missing wx.PopupWindow()
- try:
- TextCtrlAutoComplete.__init__(self, parent = self.panel, id = wx.ID_ANY,
- value = "",
- style = wx.TE_LINEWRAP | wx.TE_PROCESS_ENTER,
- statusbar = self.parent.parent.statusbar)
- self.SetItems(self._readHistory())
- except NotImplementedError:
- # wx.PopupWindow may be not available in wxMac
- # see http://trac.wxwidgets.org/ticket/9377
- wx.TextCtrl.__init__(parent = self.panel, id = wx.ID_ANY,
- value = "",
- style=wx.TE_LINEWRAP | wx.TE_PROCESS_ENTER,
- size = (-1, 25))
- self.searchBy.Enable(False)
- self.search.Enable(False)
-
- self.SetFont(wx.Font(10, wx.FONTFAMILY_MODERN, wx.NORMAL, wx.NORMAL, 0, ''))
-
- wx.CallAfter(self.SetInsertionPoint, 0)
-
- # bidnings
- self.Bind(wx.EVT_TEXT_ENTER, self.OnRunCmd)
- self.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
-
- def OnCmdErase(self, event):
- """!Erase command prompt"""
- self.input.SetValue('')
- def OnRunCmd(self, event):
- """!Run command"""
- self._runCmd(event.GetString())
-
+
class GPromptSTC(GPrompt, wx.stc.StyledTextCtrl):
"""!Styled wxGUI prompt with autocomplete and calltips"""
def __init__(self, parent, modulesData, updateCmdHistory = True, margin = False):
Modified: grass/trunk/gui/wxpython/wxpythonlib.dox
===================================================================
--- grass/trunk/gui/wxpython/wxpythonlib.dox 2012-11-21 09:37:46 UTC (rev 53947)
+++ grass/trunk/gui/wxpython/wxpythonlib.dox 2012-11-21 09:37:55 UTC (rev 53948)
@@ -157,10 +157,7 @@
- preferences::DefaultFontDialog
- preferences::MapsetAccess
- gui_core::prompt
- - prompt::PromptListCtrl
- - prompt::TextCtrlAutoComplete
- prompt::GPrompt
- - prompt::GPromptPopUp
- prompt::GPromptSTC
- gui_core::toolbars
- toolbars::BaseToolbar
More information about the grass-commit
mailing list