]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wxPython/lib/mixins/listctrl.py
c422c17cadba908fa8c31d7db5761e351eaa0ff8
[wxWidgets.git] / wxPython / wxPython / lib / mixins / listctrl.py
1 #----------------------------------------------------------------------------
2 # Name: wxPython.lib.mixins.listctrl
3 # Purpose: Helpful mix-in classes for wxListCtrl
4 #
5 # Author: Robin Dunn
6 #
7 # Created: 15-May-2001
8 # RCS-ID: $Id$
9 # Copyright: (c) 2001 by Total Control Software
10 # Licence: wxWindows license
11 #----------------------------------------------------------------------------
12
13 from wxPython.wx import *
14 import locale
15
16 #----------------------------------------------------------------------------
17
18 class wxColumnSorterMixin:
19 """
20 A mixin class that handles sorting of a wxListCtrl in REPORT mode when
21 the column header is clicked on.
22
23 There are a few requirments needed in order for this to work genericly:
24
25 1. The combined class must have a GetListCtrl method that
26 returns the wxListCtrl to be sorted, and the list control
27 must exist at the time the wxColumnSorterMixin.__init__
28 method is called because it uses GetListCtrl.
29
30 2. Items in the list control must have a unique data value set
31 with list.SetItemData.
32
33 3. The combined class must have an attribute named itemDataMap
34 that is a dictionary mapping the data values to a sequence of
35 objects representing the values in each column. These values
36 are compared in the column sorter to determine sort order.
37
38 Interesting methods to override are GetColumnSorter,
39 GetSecondarySortValues, and GetSortImages. See below for details.
40 """
41
42 def __init__(self, numColumns):
43 self._colSortFlag = [0] * numColumns
44 self._col = -1
45
46 list = self.GetListCtrl()
47 if not list:
48 raise ValueError, "No wxListCtrl available"
49 EVT_LIST_COL_CLICK(list, list.GetId(), self.__OnColClick)
50
51
52 def SortListItems(self, col=-1, ascending=1):
53 """Sort the list on demand. Can also be used to set the sort column and order."""
54 oldCol = self._col
55 if col != -1:
56 self._col = col
57 self._colSortFlag[col] = ascending
58 self.GetListCtrl().SortItems(self.GetColumnSorter())
59 self.__updateImages(oldCol)
60
61
62 def GetColumnWidths(self):
63 """
64 Returns a list of column widths. Can be used to help restore the current
65 view later.
66 """
67 list = self.GetListCtrl()
68 rv = []
69 for x in range(len(self._colSortFlag)):
70 rv.append(list.GetColumnWidth(x))
71 return rv
72
73
74 def GetSortImages(self):
75 """
76 Returns a tuple of image list indexesthe indexes in the image list for an image to be put on the column
77 header when sorting in descending order.
78 """
79 return (-1, -1) # (decending, ascending) image IDs
80
81
82 def GetColumnSorter(self):
83 """Returns a callable object to be used for comparing column values when sorting."""
84 return self.__ColumnSorter
85
86
87 def GetSecondarySortValues(self, col, key1, key2):
88 """Returns a tuple of 2 values to use for secondary sort values when the
89 items in the selected column match equal. The default just returns the
90 item data values."""
91 return (key1, key2)
92
93
94 def __OnColClick(self, evt):
95 oldCol = self._col
96 self._col = col = evt.GetColumn()
97 self._colSortFlag[col] = not self._colSortFlag[col]
98 self.GetListCtrl().SortItems(self.GetColumnSorter())
99 self.__updateImages(oldCol)
100 evt.Skip()
101
102
103 def __ColumnSorter(self, key1, key2):
104 col = self._col
105 ascending = self._colSortFlag[col]
106 item1 = self.itemDataMap[key1][col]
107 item2 = self.itemDataMap[key2][col]
108
109 #--- Internationalization of string sorting with locale module
110 if type(item1) == type('') or type(item2) == type(''):
111 cmpVal = locale.strcoll(str(item1), str(item2))
112 else:
113 cmpVal = cmp(item1, item2)
114 #---
115
116 # If the items are equal then pick something else to make the sort value unique
117 if cmpVal == 0:
118 cmpVal = apply(cmp, self.GetSecondarySortValues(col, key1, key2))
119
120 if ascending:
121 return cmpVal
122 else:
123 return -cmpVal
124
125
126 def __updateImages(self, oldCol):
127 sortImages = self.GetSortImages()
128 if self._col != -1 and sortImages[0] != -1:
129 img = sortImages[self._colSortFlag[self._col]]
130 list = self.GetListCtrl()
131 if oldCol != -1:
132 list.ClearColumnImage(oldCol)
133 list.SetColumnImage(self._col, img)
134
135
136 #----------------------------------------------------------------------------
137 #----------------------------------------------------------------------------
138
139 class wxListCtrlAutoWidthMixin:
140 """ A mix-in class that automatically resizes the last column to take up
141 the remaining width of the wxListCtrl.
142
143 This causes the wxListCtrl to automatically take up the full width of
144 the list, without either a horizontal scroll bar (unless absolutely
145 necessary) or empty space to the right of the last column.
146
147 NOTE: This only works for report-style lists.
148
149 WARNING: If you override the EVT_SIZE event in your wxListCtrl, make
150 sure you call event.Skip() to ensure that the mixin's
151 _OnResize method is called.
152
153 This mix-in class was written by Erik Westra <ewestra@wave.co.nz>
154 """
155 def __init__(self):
156 """ Standard initialiser.
157 """
158 self._lastColMinWidth = None
159
160 EVT_SIZE(self, self._onResize)
161 EVT_LIST_COL_END_DRAG(self, self.GetId(), self._onResize)
162
163
164 def resizeLastColumn(self, minWidth):
165 """ Resize the last column appropriately.
166
167 If the list's columns are too wide to fit within the window, we use
168 a horizontal scrollbar. Otherwise, we expand the right-most column
169 to take up the remaining free space in the list.
170
171 This method is called automatically when the wxListCtrl is resized;
172 you can also call it yourself whenever you want the last column to
173 be resized appropriately (eg, when adding, removing or resizing
174 columns).
175
176 'minWidth' is the preferred minimum width for the last column.
177 """
178 self._lastColMinWidth = minWidth
179 self._doResize()
180
181 # =====================
182 # == Private Methods ==
183 # =====================
184
185 def _onResize(self, event):
186 """ Respond to the wxListCtrl being resized.
187
188 We automatically resize the last column in the list.
189 """
190 wxCallAfter(self._doResize)
191 event.Skip()
192
193
194 def _doResize(self):
195 """ Resize the last column as appropriate.
196
197 If the list's columns are too wide to fit within the window, we use
198 a horizontal scrollbar. Otherwise, we expand the right-most column
199 to take up the remaining free space in the list.
200
201 We remember the current size of the last column, before resizing,
202 as the preferred minimum width if we haven't previously been given
203 or calculated a minimum width. This ensure that repeated calls to
204 _doResize() don't cause the last column to size itself too large.
205 """
206 numCols = self.GetColumnCount()
207 if numCols == 0: return # Nothing to resize.
208
209 if self._lastColMinWidth == None:
210 self._lastColMinWidth = self.GetColumnWidth(numCols - 1)
211
212 # We're showing the vertical scrollbar -> allow for scrollbar width
213 # NOTE: on GTK, the scrollbar is included in the client size, but on
214 # Windows it is not included
215 listWidth = self.GetClientSize().width
216 if wxPlatform != '__WXMSW__':
217 if self.GetItemCount() > self.GetCountPerPage():
218 scrollWidth = wxSystemSettings_GetSystemMetric(wxSYS_VSCROLL_X)
219 listWidth = listWidth - scrollWidth
220
221 totColWidth = 0 # Width of all columns except last one.
222 for col in range(numCols-1):
223 totColWidth = totColWidth + self.GetColumnWidth(col)
224
225 lastColWidth = self.GetColumnWidth(numCols - 1)
226
227 if totColWidth + self._lastColMinWidth > listWidth:
228 # We haven't got the width to show the last column at its minimum
229 # width -> set it to its minimum width and allow the horizontal
230 # scrollbar to show.
231 self.SetColumnWidth(numCols-1, self._lastColMinWidth)
232 return
233
234 # Resize the last column to take up the remaining available space.
235
236 self.SetColumnWidth(numCols-1, listWidth - totColWidth)
237
238
239
240 #----------------------------------------------------------------------------
241
242 SEL_FOC = wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED
243 def selectBeforePopup(event):
244 """Ensures the item the mouse is pointing at is selected before a popup.
245
246 Works with both single-select and multi-select lists."""
247 ctrl = event.GetEventObject()
248 if isinstance(ctrl, wxListCtrl):
249 n, flags = ctrl.HitTest(event.GetPosition())
250 if n >= 0:
251 if not ctrl.GetItemState(n, wxLIST_STATE_SELECTED):
252 for i in range(ctrl.GetItemCount()):
253 ctrl.SetItemState(i, 0, SEL_FOC)
254 #for i in getListCtrlSelection(ctrl, SEL_FOC):
255 # ctrl.SetItemState(i, 0, SEL_FOC)
256 ctrl.SetItemState(n, SEL_FOC, SEL_FOC)
257
258 def getListCtrlSelection(listctrl, state=wxLIST_STATE_SELECTED):
259 """ Returns list of item indexes of given state (selected by defaults) """
260 res = []
261 idx = -1
262 while 1:
263 idx = listctrl.GetNextItem(idx, wxLIST_NEXT_ALL, state)
264 if idx == -1:
265 break
266 res.append(idx)
267 return res
268
269 class ListCtrlSelectionManagerMix:
270 """Mixin that defines a platform independent selection policy
271
272 As selection single and multi-select list return the item index or a
273 list of item indexes respectively.
274 """
275 wxEVT_DOPOPUPMENU = wxNewId()
276 _menu = None
277
278 def __init__(self):
279 EVT_RIGHT_DOWN(self, self.OnLCSMRightDown)
280 self.Connect(-1, -1, self.wxEVT_DOPOPUPMENU, self.OnLCSMDoPopup)
281
282 def getPopupMenu(self):
283 """ Override to implement dynamic menus (create) """
284 return self._menu
285
286 def setPopupMenu(self, menu):
287 """ Must be set for default behaviour """
288 self._menu = menu
289
290 def afterPopupMenu(self, menu):
291 """ Override to implement dynamic menus (destroy) """
292 pass
293
294 def getSelection(self):
295 res = getListCtrlSelection(self)
296 if self.GetWindowStyleFlag() & wxLC_SINGLE_SEL:
297 if res:
298 return res[0]
299 else:
300 return -1
301 else:
302 return res
303
304 def OnLCSMRightDown(self, event):
305 selectBeforePopup(event)
306 event.Skip()
307 menu = self.getPopupMenu()
308 if menu:
309 evt = wxPyEvent()
310 evt.SetEventType(self.wxEVT_DOPOPUPMENU)
311 evt.menu = menu
312 evt.pos = event.GetPosition()
313 wxPostEvent(self, evt)
314
315 def OnLCSMDoPopup(self, event):
316 self.PopupMenu(event.menu, event.pos)
317 self.afterPopupMenu(event.menu)
318
319 #----------------------------------------------------------------------