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