wxCheckListBox fixes: crash/memory leak when items are dynamically
[wxWidgets.git] / src / msw / checklst.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: msw/checklst.cpp
3 // Purpose: implementation of wxCheckListBox class
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 16.11.97
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 ///////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation "checklst.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #if wxUSE_OWNER_DRAWN
32
33 #include "wx/object.h"
34 #include "wx/colour.h"
35 #include "wx/font.h"
36 #include "wx/bitmap.h"
37 #include "wx/window.h"
38 #include "wx/listbox.h"
39 #include "wx/ownerdrw.h"
40 #include "wx/settings.h"
41 #include "wx/dcmemory.h"
42 #include "wx/msw/checklst.h"
43
44 #include <windows.h>
45 #include <windowsx.h>
46
47 // ----------------------------------------------------------------------------
48 // private functions
49 // ----------------------------------------------------------------------------
50
51 // get item (converted to right type)
52 #define GetItem(n) ((wxCheckListBoxItem *)(GetItem(n)))
53
54 // ============================================================================
55 // implementation
56 // ============================================================================
57
58 #if !USE_SHARED_LIBRARY
59 IMPLEMENT_DYNAMIC_CLASS(wxCheckListBox, wxListBox)
60 #endif
61
62 // ----------------------------------------------------------------------------
63 // declaration and implementation of wxCheckListBoxItem class
64 // ----------------------------------------------------------------------------
65
66 class wxCheckListBoxItem : public wxOwnerDrawn
67 {
68 friend class wxCheckListBox;
69 public:
70 // ctor
71 wxCheckListBoxItem(wxCheckListBox *pParent, size_t nIndex);
72
73 // drawing functions
74 virtual bool OnDrawItem(wxDC& dc, const wxRect& rc, wxODAction act, wxODStatus stat);
75
76 // simple accessors
77 bool IsChecked() const { return m_bChecked; }
78 void Check(bool bCheck);
79 void Toggle() { Check(!IsChecked()); }
80
81 private:
82 bool m_bChecked;
83 wxCheckListBox *m_pParent;
84 size_t m_nIndex;
85 };
86
87 wxCheckListBoxItem::wxCheckListBoxItem(wxCheckListBox *pParent, size_t nIndex)
88 : wxOwnerDrawn("", TRUE) // checkable
89 {
90 m_bChecked = FALSE;
91 m_pParent = pParent;
92 m_nIndex = nIndex;
93
94 // we don't initialize m_nCheckHeight/Width vars because it's
95 // done in OnMeasure while they are used only in OnDraw and we
96 // know that there will always be OnMeasure before OnDraw
97
98 // fix appearance
99 SetFont(wxSystemSettings::GetSystemFont(wxSYS_ANSI_VAR_FONT));
100 SetMarginWidth(GetDefaultMarginWidth());
101 }
102
103 /*
104 * JACS - I've got the owner-draw stuff partially working with WIN16,
105 * with a really horrible-looking cross for wxCheckListBox instead of a
106 * check - could use a bitmap check-mark instead, defined in wx.rc.
107 * Also there's a refresh problem whereby it doesn't always draw the
108 * check until you click to the right of it, which is OK for WIN32.
109 */
110
111 bool wxCheckListBoxItem::OnDrawItem(wxDC& dc, const wxRect& rc,
112 wxODAction act, wxODStatus stat)
113 {
114 if ( IsChecked() )
115 stat = (wxOwnerDrawn::wxODStatus)(stat | wxOwnerDrawn::wxODChecked);
116
117 if ( wxOwnerDrawn::OnDrawItem(dc, rc, act, stat) ) {
118 // ## using native API for performance and precision
119 size_t nCheckWidth = GetDefaultMarginWidth(),
120 nCheckHeight = m_pParent->GetItemHeight();
121
122 int x = rc.GetX(),
123 y = rc.GetY();
124
125 HDC hdc = (HDC)dc.GetHDC();
126
127 // create pens
128 HPEN hpenBack = CreatePen(PS_SOLID, 0, GetSysColor(COLOR_WINDOW)),
129 hpenGray = CreatePen(PS_SOLID, 0, RGB(128, 128, 128)),
130 hpenPrev = (HPEN)SelectObject(hdc, hpenBack);
131
132 // we erase the 1-pixel border
133 Rectangle(hdc, x, y, x + nCheckWidth, y + nCheckHeight);
134
135 // shift check mark 1 pixel to the right (it looks better like this)
136 x++;
137
138 if ( IsChecked() ) {
139 // first create a monochrome bitmap in a memory DC
140 HDC hdcMem = CreateCompatibleDC(hdc);
141 HBITMAP hbmpCheck = CreateBitmap(nCheckWidth, nCheckHeight, 1, 1, 0);
142 HBITMAP hbmpOld = (HBITMAP)SelectObject(hdcMem, hbmpCheck);
143
144 // then draw a check mark into it
145 RECT rect = { 0, 0, nCheckWidth, nCheckHeight };
146
147 #ifdef __WIN32__
148 #ifndef __SC__
149 DrawFrameControl(hdcMem, &rect, DFC_MENU, DFCS_MENUCHECK);
150 #endif
151 #else
152 // In WIN16, draw a cross
153 HPEN blackPen = CreatePen(PS_SOLID, 1, RGB(0, 0, 0));
154 HPEN whiteBrush = GetStockObject(WHITE_BRUSH);
155 HPEN hPenOld = ::SelectObject(hdcMem, blackPen);
156 HPEN hBrushOld = ::SelectObject(hdcMem, whiteBrush);
157 ::SetROP2(hdcMem, R2_COPYPEN);
158 Rectangle(hdcMem, 0, 0, nCheckWidth, nCheckHeight);
159 MoveTo(hdcMem, 0, 0);
160 LineTo(hdcMem, nCheckWidth, nCheckHeight);
161 MoveTo(hdcMem, nCheckWidth, 0);
162 LineTo(hdcMem, 0, nCheckHeight);
163 ::SelectObject(hdcMem, hPenOld);
164 ::SelectObject(hdcMem, hBrushOld);
165 ::DeleteObject(blackPen);
166 #endif
167
168 // finally copy it to screen DC and clean up
169 BitBlt(hdc, x, y, nCheckWidth - 1, nCheckHeight,
170 hdcMem, 0, 0, SRCCOPY);
171
172 SelectObject(hdcMem, hbmpOld);
173 DeleteObject(hbmpCheck);
174 DeleteDC(hdcMem);
175 }
176
177 // now we draw the smaller rectangle
178 y++;
179 nCheckWidth -= 2;
180 nCheckHeight -= 2;
181
182 // draw hollow gray rectangle
183 (void)SelectObject(hdc, hpenGray);
184 HBRUSH hbrPrev = (HBRUSH)SelectObject(hdc, GetStockObject(NULL_BRUSH));
185 Rectangle(hdc, x, y, x + nCheckWidth, y + nCheckHeight);
186
187 // clean up
188 (void)SelectObject(hdc, hpenPrev);
189 (void)SelectObject(hdc, hbrPrev);
190
191 DeleteObject(hpenBack);
192 DeleteObject(hpenGray);
193
194 /*
195 dc.DrawRectangle(x, y, nCheckWidth, nCheckHeight);
196
197 if ( IsChecked() ) {
198 dc.DrawLine(x, y, x + nCheckWidth, y + nCheckHeight);
199 dc.DrawLine(x, y + nCheckHeight, x + nCheckWidth, y);
200 }
201 */
202
203 return TRUE;
204 }
205
206 return FALSE;
207 }
208
209 // change the state of the item and redraw it
210 void wxCheckListBoxItem::Check(bool check)
211 {
212 m_bChecked = check;
213
214 // index may be chanegd because new items were added/deleted
215 if ( m_pParent->GetItemIndex(this) != (int)m_nIndex )
216 {
217 // update it
218 int index = m_pParent->GetItemIndex(this);
219
220 wxASSERT_MSG( index != wxNOT_FOUND, "what does this item do here?" );
221
222 m_nIndex = (size_t)index;
223 }
224
225 size_t nHeight = m_pParent->GetItemHeight();
226 size_t y = m_nIndex * nHeight;
227 RECT rcUpdate = { 0, y, GetDefaultMarginWidth(), y + nHeight};
228 InvalidateRect((HWND)m_pParent->GetHWND(), &rcUpdate, FALSE);
229
230 wxCommandEvent event(wxEVT_COMMAND_CHECKLISTBOX_TOGGLED, m_pParent->GetId());
231 event.SetInt(m_nIndex);
232 event.SetEventObject(m_pParent);
233 m_pParent->ProcessCommand(event);
234 }
235
236 // ----------------------------------------------------------------------------
237 // implementation of wxCheckListBox class
238 // ----------------------------------------------------------------------------
239
240 // define event table
241 // ------------------
242 BEGIN_EVENT_TABLE(wxCheckListBox, wxListBox)
243 EVT_CHAR(wxCheckListBox::OnChar)
244 EVT_LEFT_DOWN(wxCheckListBox::OnLeftClick)
245 END_EVENT_TABLE()
246
247 // control creation
248 // ----------------
249
250 // def ctor: use Create() to really create the control
251 wxCheckListBox::wxCheckListBox() : wxListBox()
252 {
253 }
254
255 // ctor which creates the associated control
256 wxCheckListBox::wxCheckListBox(wxWindow *parent, wxWindowID id,
257 const wxPoint& pos, const wxSize& size,
258 int nStrings, const wxString choices[],
259 long style, const wxValidator& val,
260 const wxString& name)
261 : wxListBox()
262 {
263 Create(parent, id, pos, size, nStrings, choices,
264 style | wxLB_OWNERDRAW, val, name);
265 }
266
267 void wxCheckListBox::Delete(int N)
268 {
269 wxCHECK_RET( N >= 0 && N < m_noItems,
270 "invalid index in wxListBox::Delete" );
271
272 wxListBox::Delete(N);
273
274 // free memory
275 delete m_aItems[N];
276
277 m_aItems.Remove(N);
278 }
279
280 void wxCheckListBox::InsertItems(int nItems, const wxString items[], int pos)
281 {
282 wxCHECK_RET( pos >= 0 && pos <= m_noItems,
283 "invalid index in wxCheckListBox::InsertItems" );
284
285 wxListBox::InsertItems(nItems, items, pos);
286
287 int i;
288 for ( i = 0; i < nItems; i++ ) {
289 wxOwnerDrawn *pNewItem = CreateItem((size_t)(pos + i));
290 pNewItem->SetName(items[i]);
291 m_aItems.Insert(pNewItem, (size_t)(pos + i));
292 ListBox_SetItemData((HWND)GetHWND(), i + pos, pNewItem);
293 }
294 }
295
296 // create/retrieve item
297 // --------------------
298
299 // create a check list box item
300 wxOwnerDrawn *wxCheckListBox::CreateItem(size_t nIndex)
301 {
302 wxCheckListBoxItem *pItem = new wxCheckListBoxItem(this, nIndex);
303 if ( m_windowFont.Ok() )
304 pItem->SetFont(m_windowFont);
305
306 return pItem;
307 }
308
309 // return item size
310 // ----------------
311 bool wxCheckListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT *item)
312 {
313 if ( wxListBox::MSWOnMeasure(item) ) {
314 MEASUREITEMSTRUCT *pStruct = (MEASUREITEMSTRUCT *)item;
315
316 // save item height
317 m_nItemHeight = pStruct->itemHeight;
318
319 // add place for the check mark
320 pStruct->itemWidth += wxOwnerDrawn::GetDefaultMarginWidth();
321
322 return TRUE;
323 }
324
325 return FALSE;
326 }
327
328 // check items
329 // -----------
330
331 bool wxCheckListBox::IsChecked(size_t uiIndex) const
332 {
333 return GetItem(uiIndex)->IsChecked();
334 }
335
336 void wxCheckListBox::Check(size_t uiIndex, bool bCheck)
337 {
338 GetItem(uiIndex)->Check(bCheck);
339 }
340
341 // process events
342 // --------------
343
344 void wxCheckListBox::OnChar(wxKeyEvent& event)
345 {
346 if ( event.KeyCode() == WXK_SPACE )
347 GetItem(GetSelection())->Toggle();
348 else
349 wxListBox::OnChar(event);
350 }
351
352 void wxCheckListBox::OnLeftClick(wxMouseEvent& event)
353 {
354 // clicking on the item selects it, clicking on the checkmark toggles
355 if ( event.GetX() <= wxOwnerDrawn::GetDefaultMarginWidth() ) {
356 // FIXME better use LB_ITEMFROMPOINT perhaps?
357 size_t nItem = ((size_t)event.GetY()) / m_nItemHeight;
358 if ( nItem < (size_t)m_noItems )
359 GetItem(nItem)->Toggle();
360 //else: it's not an error, just click outside of client zone
361 }
362 else {
363 // implement default behaviour: clicking on the item selects it
364 event.Skip();
365 }
366 }
367
368 #endif
369