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