]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wx/lib/mixins/listctrl.py
Play nice with sizers
[wxWidgets.git] / wxPython / wx / 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 # 12/14/2003 - Jeff Grimmett (grimmtooth@softhome.net)
13 #
14 # o 2.5 compatability update.
15 # o ListCtrlSelectionManagerMix untested.
16 #
17 # 12/21/2003 - Jeff Grimmett (grimmtooth@softhome.net)
18 #
19 # o wxColumnSorterMixin -> ColumnSorterMixin
20 # o wxListCtrlAutoWidthMixin -> ListCtrlAutoWidthMixin
21 # ...
22 # 13/10/2004 - Pim Van Heuven (pim@think-wize.com)
23 # o wxTextEditMixin: Support Horizontal scrolling when TAB is pressed on long
24 # ListCtrls, support for WXK_DOWN, WXK_UP, performance improvements on
25 # very long ListCtrls, Support for virtual ListCtrls
26 #
27 # 15-Oct-2004 - Robin Dunn
28 # o wxTextEditMixin: Added Shift-TAB support
29 #
30
31 import locale
32 import wx
33
34 #----------------------------------------------------------------------------
35
36 class ColumnSorterMixin:
37 """
38 A mixin class that handles sorting of a wx.ListCtrl in REPORT mode when
39 the column header is clicked on.
40
41 There are a few requirments needed in order for this to work genericly:
42
43 1. The combined class must have a GetListCtrl method that
44 returns the wx.ListCtrl to be sorted, and the list control
45 must exist at the time the wx.ColumnSorterMixin.__init__
46 method is called because it uses GetListCtrl.
47
48 2. Items in the list control must have a unique data value set
49 with list.SetItemData.
50
51 3. The combined class must have an attribute named itemDataMap
52 that is a dictionary mapping the data values to a sequence of
53 objects representing the values in each column. These values
54 are compared in the column sorter to determine sort order.
55
56 Interesting methods to override are GetColumnSorter,
57 GetSecondarySortValues, and GetSortImages. See below for details.
58 """
59
60 def __init__(self, numColumns):
61 self.SetColumnCount(numColumns)
62 list = self.GetListCtrl()
63 if not list:
64 raise ValueError, "No wx.ListCtrl available"
65 self.Bind(wx.EVT_LIST_COL_CLICK, self.__OnColClick, list)
66
67
68 def SetColumnCount(self, newNumColumns):
69 self._colSortFlag = [0] * newNumColumns
70 self._col = -1
71
72
73 def SortListItems(self, col=-1, ascending=1):
74 """Sort the list on demand. Can also be used to set the sort column and order."""
75 oldCol = self._col
76 if col != -1:
77 self._col = col
78 self._colSortFlag[col] = ascending
79 self.GetListCtrl().SortItems(self.GetColumnSorter())
80 self.__updateImages(oldCol)
81
82
83 def GetColumnWidths(self):
84 """
85 Returns a list of column widths. Can be used to help restore the current
86 view later.
87 """
88 list = self.GetListCtrl()
89 rv = []
90 for x in range(len(self._colSortFlag)):
91 rv.append(list.GetColumnWidth(x))
92 return rv
93
94
95 def GetSortImages(self):
96 """
97 Returns a tuple of image list indexesthe indexes in the image list for an image to be put on the column
98 header when sorting in descending order.
99 """
100 return (-1, -1) # (decending, ascending) image IDs
101
102
103 def GetColumnSorter(self):
104 """Returns a callable object to be used for comparing column values when sorting."""
105 return self.__ColumnSorter
106
107
108 def GetSecondarySortValues(self, col, key1, key2):
109 """Returns a tuple of 2 values to use for secondary sort values when the
110 items in the selected column match equal. The default just returns the
111 item data values."""
112 return (key1, key2)
113
114
115 def __OnColClick(self, evt):
116 oldCol = self._col
117 self._col = col = evt.GetColumn()
118 self._colSortFlag[col] = not self._colSortFlag[col]
119 self.GetListCtrl().SortItems(self.GetColumnSorter())
120 self.__updateImages(oldCol)
121 evt.Skip()
122
123
124 def __ColumnSorter(self, key1, key2):
125 col = self._col
126 ascending = self._colSortFlag[col]
127 item1 = self.itemDataMap[key1][col]
128 item2 = self.itemDataMap[key2][col]
129
130 #--- Internationalization of string sorting with locale module
131 if type(item1) == type('') or type(item2) == type(''):
132 cmpVal = locale.strcoll(str(item1), str(item2))
133 else:
134 cmpVal = cmp(item1, item2)
135 #---
136
137 # If the items are equal then pick something else to make the sort value unique
138 if cmpVal == 0:
139 cmpVal = apply(cmp, self.GetSecondarySortValues(col, key1, key2))
140
141 if ascending:
142 return cmpVal
143 else:
144 return -cmpVal
145
146
147 def __updateImages(self, oldCol):
148 sortImages = self.GetSortImages()
149 if self._col != -1 and sortImages[0] != -1:
150 img = sortImages[self._colSortFlag[self._col]]
151 list = self.GetListCtrl()
152 if oldCol != -1:
153 list.ClearColumnImage(oldCol)
154 list.SetColumnImage(self._col, img)
155
156
157 #----------------------------------------------------------------------------
158 #----------------------------------------------------------------------------
159
160 class ListCtrlAutoWidthMixin:
161 """ A mix-in class that automatically resizes the last column to take up
162 the remaining width of the wx.ListCtrl.
163
164 This causes the wx.ListCtrl to automatically take up the full width of
165 the list, without either a horizontal scroll bar (unless absolutely
166 necessary) or empty space to the right of the last column.
167
168 NOTE: This only works for report-style lists.
169
170 WARNING: If you override the EVT_SIZE event in your wx.ListCtrl, make
171 sure you call event.Skip() to ensure that the mixin's
172 _OnResize method is called.
173
174 This mix-in class was written by Erik Westra <ewestra@wave.co.nz>
175 """
176 def __init__(self):
177 """ Standard initialiser.
178 """
179 self._lastColMinWidth = None
180
181 self.Bind(wx.EVT_SIZE, self._onResize)
182 self.Bind(wx.EVT_LIST_COL_END_DRAG, self._onResize, self)
183
184
185 def resizeLastColumn(self, minWidth):
186 """ Resize the last column appropriately.
187
188 If the list's columns are too wide to fit within the window, we use
189 a horizontal scrollbar. Otherwise, we expand the right-most column
190 to take up the remaining free space in the list.
191
192 This method is called automatically when the wx.ListCtrl is resized;
193 you can also call it yourself whenever you want the last column to
194 be resized appropriately (eg, when adding, removing or resizing
195 columns).
196
197 'minWidth' is the preferred minimum width for the last column.
198 """
199 self._lastColMinWidth = minWidth
200 self._doResize()
201
202 # =====================
203 # == Private Methods ==
204 # =====================
205
206 def _onResize(self, event):
207 """ Respond to the wx.ListCtrl being resized.
208
209 We automatically resize the last column in the list.
210 """
211 wx.CallAfter(self._doResize)
212 event.Skip()
213
214
215 def _doResize(self):
216 """ Resize the last column as appropriate.
217
218 If the list's columns are too wide to fit within the window, we use
219 a horizontal scrollbar. Otherwise, we expand the right-most column
220 to take up the remaining free space in the list.
221
222 We remember the current size of the last column, before resizing,
223 as the preferred minimum width if we haven't previously been given
224 or calculated a minimum width. This ensure that repeated calls to
225 _doResize() don't cause the last column to size itself too large.
226 """
227
228 if not self: # avoid a PyDeadObject error
229 return
230
231 numCols = self.GetColumnCount()
232 if numCols == 0: return # Nothing to resize.
233
234 if self._lastColMinWidth == None:
235 self._lastColMinWidth = self.GetColumnWidth(numCols - 1)
236
237 # We're showing the vertical scrollbar -> allow for scrollbar width
238 # NOTE: on GTK, the scrollbar is included in the client size, but on
239 # Windows it is not included
240 listWidth = self.GetClientSize().width
241 if wx.Platform != '__WXMSW__':
242 if self.GetItemCount() > self.GetCountPerPage():
243 scrollWidth = wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X)
244 listWidth = listWidth - scrollWidth
245
246 totColWidth = 0 # Width of all columns except last one.
247 for col in range(numCols-1):
248 totColWidth = totColWidth + self.GetColumnWidth(col)
249
250 lastColWidth = self.GetColumnWidth(numCols - 1)
251
252 if totColWidth + self._lastColMinWidth > listWidth:
253 # We haven't got the width to show the last column at its minimum
254 # width -> set it to its minimum width and allow the horizontal
255 # scrollbar to show.
256 self.SetColumnWidth(numCols-1, self._lastColMinWidth)
257 return
258
259 # Resize the last column to take up the remaining available space.
260
261 self.SetColumnWidth(numCols-1, listWidth - totColWidth)
262
263
264
265 #----------------------------------------------------------------------------
266
267 SEL_FOC = wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED
268 def selectBeforePopup(event):
269 """Ensures the item the mouse is pointing at is selected before a popup.
270
271 Works with both single-select and multi-select lists."""
272 ctrl = event.GetEventObject()
273 if isinstance(ctrl, wx.ListCtrl):
274 n, flags = ctrl.HitTest(event.GetPosition())
275 if n >= 0:
276 if not ctrl.GetItemState(n, wx.LIST_STATE_SELECTED):
277 for i in range(ctrl.GetItemCount()):
278 ctrl.SetItemState(i, 0, SEL_FOC)
279 #for i in getListCtrlSelection(ctrl, SEL_FOC):
280 # ctrl.SetItemState(i, 0, SEL_FOC)
281 ctrl.SetItemState(n, SEL_FOC, SEL_FOC)
282
283
284 def getListCtrlSelection(listctrl, state=wx.LIST_STATE_SELECTED):
285 """ Returns list of item indexes of given state (selected by defaults) """
286 res = []
287 idx = -1
288 while 1:
289 idx = listctrl.GetNextItem(idx, wx.LIST_NEXT_ALL, state)
290 if idx == -1:
291 break
292 res.append(idx)
293 return res
294
295 wxEVT_DOPOPUPMENU = wx.NewEventType()
296 EVT_DOPOPUPMENU = wx.PyEventBinder(wxEVT_DOPOPUPMENU, 0)
297
298
299 class ListCtrlSelectionManagerMix:
300 """Mixin that defines a platform independent selection policy
301
302 As selection single and multi-select list return the item index or a
303 list of item indexes respectively.
304 """
305 _menu = None
306
307 def __init__(self):
308 self.Bind(wx.EVT_RIGHT_DOWN, self.OnLCSMRightDown)
309 self.Bind(EVT_DOPOPUPMENU, self.OnLCSMDoPopup)
310 # self.Connect(-1, -1, self.wxEVT_DOPOPUPMENU, self.OnLCSMDoPopup)
311
312
313 def getPopupMenu(self):
314 """ Override to implement dynamic menus (create) """
315 return self._menu
316
317
318 def setPopupMenu(self, menu):
319 """ Must be set for default behaviour """
320 self._menu = menu
321
322
323 def afterPopupMenu(self, menu):
324 """ Override to implement dynamic menus (destroy) """
325 pass
326
327
328 def getSelection(self):
329 res = getListCtrlSelection(self)
330 if self.GetWindowStyleFlag() & wx.LC_SINGLE_SEL:
331 if res:
332 return res[0]
333 else:
334 return -1
335 else:
336 return res
337
338
339 def OnLCSMRightDown(self, event):
340 selectBeforePopup(event)
341 event.Skip()
342 menu = self.getPopupMenu()
343 if menu:
344 evt = wx.PyEvent()
345 evt.SetEventType(wxEVT_DOPOPUPMENU)
346 evt.menu = menu
347 evt.pos = event.GetPosition()
348 wx.PostEvent(self, evt)
349
350
351 def OnLCSMDoPopup(self, event):
352 self.PopupMenu(event.menu, event.pos)
353 self.afterPopupMenu(event.menu)
354
355
356 #----------------------------------------------------------------------------
357 from bisect import bisect
358
359
360 class TextEditMixin:
361 """
362 A mixin class that handles enables any text in any column of a
363 multi-column listctrl to be edited by clicking on the given row
364 and column. You close the text editor by hitting the ENTER key or
365 clicking somewhere else on the listctrl. You switch to the next
366 column by hiting TAB.
367
368 To use the mixin you have to include it in the class definition
369 and call the __init__ function::
370
371 class TestListCtrl(wx.ListCtrl, TextEdit):
372 def __init__(self, parent, ID, pos=wx.DefaultPosition,
373 size=wx.DefaultSize, style=0):
374 wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
375 TextEdit.__init__(self)
376
377
378 Authors: Steve Zatz, Pim Van Heuven (pim@think-wize.com)
379 """
380
381 def __init__(self):
382 #editor = wx.TextCtrl(self, -1, pos=(-1,-1), size=(-1,-1),
383 # style=wx.TE_PROCESS_ENTER|wx.TE_PROCESS_TAB \
384 # |wx.TE_RICH2)
385
386 self.make_editor()
387 self.Bind(wx.EVT_TEXT_ENTER, self.CloseEditor)
388 self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
389 self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)
390 self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
391
392
393 def make_editor(self, col_style=wx.LIST_FORMAT_LEFT):
394 editor = wx.PreTextCtrl()
395
396 style =wx.TE_PROCESS_ENTER|wx.TE_PROCESS_TAB|wx.TE_RICH2
397 style |= {wx.LIST_FORMAT_LEFT: wx.TE_LEFT, wx.LIST_FORMAT_RIGHT: wx.TE_RIGHT, wx.LIST_FORMAT_CENTRE : wx.TE_CENTRE}[col_style]
398
399 editor.Create(self, -1, style=style)
400 editor.SetBackgroundColour(wx.Colour(red=255,green=255,blue=175)) #Yellow
401 font = self.GetFont()
402 editor.SetFont(font)
403
404 self.curRow = 0
405 self.curCol = 0
406
407 editor.Hide()
408 self.editor = editor
409
410 self.col_style = col_style
411 self.editor.Bind(wx.EVT_CHAR, self.OnChar)
412 self.editor.Bind(wx.EVT_KILL_FOCUS, self.CloseEditor)
413
414
415 def OnItemSelected(self, evt):
416 self.curRow = evt.GetIndex()
417 evt.Skip()
418
419
420 def OnChar(self, event):
421 ''' Catch the TAB, Shift-TAB, cursor DOWN/UP key code
422 so we can open the editor at the next column (if any).'''
423
424 keycode = event.GetKeyCode()
425 if keycode == wx.WXK_TAB and event.ShiftDown():
426 self.CloseEditor()
427 if self.curCol-1 >= 0:
428 self.OpenEditor(self.curCol-1, self.curRow)
429
430 elif keycode == wx.WXK_TAB:
431 self.CloseEditor()
432 if self.curCol+1 < self.GetColumnCount():
433 self.OpenEditor(self.curCol+1, self.curRow)
434
435 elif keycode == wx.WXK_ESCAPE:
436 self.CloseEditor()
437
438 elif keycode == wx.WXK_DOWN:
439 self.CloseEditor()
440 if self.curRow+1 < self.GetItemCount():
441 self._SelectIndex(self.curRow+1)
442 self.OpenEditor(self.curCol, self.curRow)
443
444 elif keycode == wx.WXK_UP:
445 self.CloseEditor()
446 if self.curRow > 0:
447 self._SelectIndex(self.curRow-1)
448 self.OpenEditor(self.curCol, self.curRow)
449
450 else:
451 event.Skip()
452
453
454 def OnLeftDown(self, evt=None):
455 ''' Examine the click and double
456 click events to see if a row has been click on twice. If so,
457 determine the current row and columnn and open the editor.'''
458
459 if self.editor.IsShown():
460 self.CloseEditor()
461
462 x,y = evt.GetPosition()
463 row,flags = self.HitTest((x,y))
464
465 if row != self.curRow: # self.curRow keeps track of the current row
466 evt.Skip()
467 return
468
469 # the following should really be done in the mixin's init but
470 # the wx.ListCtrl demo creates the columns after creating the
471 # ListCtrl (generally not a good idea) on the other hand,
472 # doing this here handles adjustable column widths
473
474 self.col_locs = [0]
475 loc = 0
476 for n in range(self.GetColumnCount()):
477 loc = loc + self.GetColumnWidth(n)
478 self.col_locs.append(loc)
479
480
481 col = bisect(self.col_locs, x+self.GetScrollPos(wx.HORIZONTAL)) - 1
482 self.OpenEditor(col, row)
483
484
485 def OpenEditor(self, col, row):
486 ''' Opens an editor at the current position. '''
487
488 if self.GetColumn(col).m_format != self.col_style:
489 self.make_editor(self.GetColumn(col).m_format)
490
491 x0 = self.col_locs[col]
492 x1 = self.col_locs[col+1] - x0
493
494 scrolloffset = self.GetScrollPos(wx.HORIZONTAL)
495
496 # scroll foreward
497 if x0+x1-scrolloffset > self.GetSize()[0]:
498 if wx.Platform == "__WXMSW__":
499 # don't start scrolling unless we really need to
500 offset = x0+x1-self.GetSize()[0]-scrolloffset
501 # scroll a bit more than what is minimum required
502 # so we don't have to scroll everytime the user presses TAB
503 # which is very tireing to the eye
504 addoffset = self.GetSize()[0]/4
505 # but be careful at the end of the list
506 if addoffset + scrolloffset < self.GetSize()[0]:
507 offset += addoffset
508
509 self.ScrollList(offset, 0)
510 scrolloffset = self.GetScrollPos(wx.HORIZONTAL)
511 else:
512 # Since we can not programmatically scroll the ListCtrl
513 # close the editor so the user can scroll and open the editor
514 # again
515 self.CloseEditor()
516 return
517
518 y0 = self.GetItemRect(row)[1]
519
520 editor = self.editor
521 editor.SetDimensions(x0-scrolloffset,y0, x1,-1)
522
523 editor.SetValue(self.GetItem(row, col).GetText())
524 editor.Show()
525 editor.Raise()
526 editor.SetSelection(-1,-1)
527 editor.SetFocus()
528
529 self.curRow = row
530 self.curCol = col
531
532
533 def CloseEditor(self, evt=None):
534 ''' Close the editor and save the new value to the ListCtrl. '''
535 text = self.editor.GetValue()
536 self.editor.Hide()
537 if self.IsVirtual():
538 # replace by whather you use to populate the virtual ListCtrl
539 # data source
540 self.SetVirtualData(self.curRow, self.curCol, text)
541 else:
542 self.SetStringItem(self.curRow, self.curCol, text)
543 self.RefreshItem(self.curRow)
544
545 def _SelectIndex(self, row):
546 listlen = self.GetItemCount()
547 if row < 0 and not listlen:
548 return
549 if row > (listlen-1):
550 row = listlen -1
551
552 self.SetItemState(self.curRow, ~wx.LIST_STATE_SELECTED,
553 wx.LIST_STATE_SELECTED)
554 self.EnsureVisible(row)
555 self.SetItemState(row, wx.LIST_STATE_SELECTED,
556 wx.LIST_STATE_SELECTED)
557
558
559
560 #----------------------------------------------------------------------------