Refactor owner-drawing code.
[wxWidgets.git] / src / msw / checklst.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/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 licence
10 ///////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_CHECKLISTBOX && wxUSE_OWNER_DRAWN
28
29 #include "wx/checklst.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/msw/wrapcctl.h"
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/dcmemory.h"
40 #include "wx/settings.h"
41 #include "wx/log.h"
42 #endif
43
44 #include "wx/ownerdrw.h"
45
46 #include <windowsx.h>
47
48 #include "wx/renderer.h"
49 #include "wx/msw/private.h"
50 #include "wx/msw/dc.h"
51
52 // ----------------------------------------------------------------------------
53 // private functions
54 // ----------------------------------------------------------------------------
55
56 // get item (converted to right type)
57 #define GetItem(n) ((wxCheckListBoxItem *)(GetItem(n)))
58
59 // ============================================================================
60 // implementation
61 // ============================================================================
62
63
64 #if wxUSE_EXTENDED_RTTI
65 WX_DEFINE_FLAGS( wxCheckListBoxStyle )
66
67 wxBEGIN_FLAGS( wxCheckListBoxStyle )
68 // new style border flags, we put them first to
69 // use them for streaming out
70 wxFLAGS_MEMBER(wxBORDER_SIMPLE)
71 wxFLAGS_MEMBER(wxBORDER_SUNKEN)
72 wxFLAGS_MEMBER(wxBORDER_DOUBLE)
73 wxFLAGS_MEMBER(wxBORDER_RAISED)
74 wxFLAGS_MEMBER(wxBORDER_STATIC)
75 wxFLAGS_MEMBER(wxBORDER_NONE)
76
77 // old style border flags
78 wxFLAGS_MEMBER(wxSIMPLE_BORDER)
79 wxFLAGS_MEMBER(wxSUNKEN_BORDER)
80 wxFLAGS_MEMBER(wxDOUBLE_BORDER)
81 wxFLAGS_MEMBER(wxRAISED_BORDER)
82 wxFLAGS_MEMBER(wxSTATIC_BORDER)
83 wxFLAGS_MEMBER(wxBORDER)
84
85 // standard window styles
86 wxFLAGS_MEMBER(wxTAB_TRAVERSAL)
87 wxFLAGS_MEMBER(wxCLIP_CHILDREN)
88 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW)
89 wxFLAGS_MEMBER(wxWANTS_CHARS)
90 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE)
91 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB )
92 wxFLAGS_MEMBER(wxVSCROLL)
93 wxFLAGS_MEMBER(wxHSCROLL)
94
95 wxFLAGS_MEMBER(wxLB_SINGLE)
96 wxFLAGS_MEMBER(wxLB_MULTIPLE)
97 wxFLAGS_MEMBER(wxLB_EXTENDED)
98 wxFLAGS_MEMBER(wxLB_HSCROLL)
99 wxFLAGS_MEMBER(wxLB_ALWAYS_SB)
100 wxFLAGS_MEMBER(wxLB_NEEDED_SB)
101 wxFLAGS_MEMBER(wxLB_SORT)
102 wxFLAGS_MEMBER(wxLB_OWNERDRAW)
103
104 wxEND_FLAGS( wxCheckListBoxStyle )
105
106 IMPLEMENT_DYNAMIC_CLASS_XTI(wxCheckListBox, wxListBox,"wx/checklst.h")
107
108 wxBEGIN_PROPERTIES_TABLE(wxCheckListBox)
109 wxEVENT_PROPERTY( Toggle , wxEVT_COMMAND_CHECKLISTBOX_TOGGLED , wxCommandEvent )
110 wxPROPERTY_FLAGS( WindowStyle , wxCheckListBoxStyle , long , SetWindowStyleFlag , GetWindowStyleFlag , EMPTY_MACROVALUE , wxLB_OWNERDRAW /*flags*/ , wxT("Helpstring") , wxT("group")) // style
111 wxEND_PROPERTIES_TABLE()
112
113 wxBEGIN_HANDLERS_TABLE(wxCheckListBox)
114 wxEND_HANDLERS_TABLE()
115
116 wxCONSTRUCTOR_4( wxCheckListBox , wxWindow* , Parent , wxWindowID , Id , wxPoint , Position , wxSize , Size )
117
118 #else
119 IMPLEMENT_DYNAMIC_CLASS(wxCheckListBox, wxListBox)
120 #endif
121
122 // ----------------------------------------------------------------------------
123 // declaration and implementation of wxCheckListBoxItem class
124 // ----------------------------------------------------------------------------
125
126 class wxCheckListBoxItem : public wxOwnerDrawn
127 {
128 friend class WXDLLIMPEXP_FWD_CORE wxCheckListBox;
129 public:
130 // ctor
131 wxCheckListBoxItem(wxCheckListBox *pParent, size_t nIndex);
132
133 // drawing functions
134 virtual bool OnDrawItem(wxDC& dc, const wxRect& rc, wxODAction act, wxODStatus stat);
135
136 // simple accessors and operations
137 bool IsChecked() const { return m_bChecked; }
138
139 void Check(bool bCheck);
140 void Toggle() { Check(!IsChecked()); }
141
142 void SendEvent();
143
144 virtual wxString GetName() const { return m_pParent->GetString(m_nIndex); }
145
146 private:
147 bool m_bChecked;
148 wxCheckListBox *m_pParent;
149 size_t m_nIndex;
150
151 wxDECLARE_NO_COPY_CLASS(wxCheckListBoxItem);
152 };
153
154 wxCheckListBoxItem::wxCheckListBoxItem(wxCheckListBox *pParent, size_t nIndex)
155 {
156 m_bChecked = false;
157 m_pParent = pParent;
158 m_nIndex = nIndex;
159
160 // we don't initialize m_nCheckHeight/Width vars because it's
161 // done in OnMeasure while they are used only in OnDraw and we
162 // know that there will always be OnMeasure before OnDraw
163
164 SetMarginWidth(::GetSystemMetrics(SM_CXMENUCHECK));
165
166 SetBackgroundColour(pParent->GetBackgroundColour());
167 }
168
169 bool wxCheckListBoxItem::OnDrawItem(wxDC& dc, const wxRect& rc,
170 wxODAction act, wxODStatus stat)
171 {
172 // first draw the label
173 if ( IsChecked() )
174 stat = (wxOwnerDrawn::wxODStatus)(stat | wxOwnerDrawn::wxODChecked);
175
176 if ( !wxOwnerDrawn::OnDrawItem(dc, rc, act, stat) )
177 return false;
178
179 wxMSWDCImpl *impl = (wxMSWDCImpl*) dc.GetImpl();
180 // now draw the check mark part
181 HDC hdc = GetHdcOf(*impl);
182
183 int nBmpWidth = ::GetSystemMetrics(SM_CXMENUCHECK),
184 nBmpHeight = ::GetSystemMetrics(SM_CYMENUCHECK);
185
186
187 // first create bitmap in a memory DC
188 MemoryHDC hdcMem(hdc);
189 CompatibleBitmap hBmpCheck(hdc, nBmpWidth, nBmpHeight);
190
191 // then draw a check mark into it
192 {
193 SelectInHDC selBmp(hdcMem, hBmpCheck);
194
195 int flags = wxCONTROL_FLAT;
196 if ( IsChecked() )
197 flags |= wxCONTROL_CHECKED;
198
199 wxDCTemp dcMem(hdcMem);
200 wxRendererNative::Get().DrawCheckBox(
201 m_pParent, dcMem, wxRect(0, 0, nBmpWidth, nBmpHeight), flags);
202 } // select hBmpCheck out of hdcMem
203
204 // shift check mark 2 pixel to the right and bottom, looks better like this
205 int x = rc.GetX() + 2,
206 y = rc.GetY() + 2;
207
208 // finally draw bitmap to screen: uses image list functions to blend
209 // the bitmap with the background colour (better for the selected items)
210 HIMAGELIST himl = ImageList_Create(nBmpWidth, nBmpHeight,
211 ILC_COLOR32 | ILC_MASK, 1, 1);
212 ImageList_Add(himl, hBmpCheck, NULL);
213
214 UINT fStyle = stat & wxOwnerDrawn::wxODSelected ? ILD_SELECTED : ILD_NORMAL;
215 ImageList_Draw(himl, 0, hdc, x, y, fStyle);
216
217 ImageList_Destroy(himl);
218
219 if (stat & wxODHasFocus)
220 wxRendererNative::Get().DrawFocusRect(m_pParent, dc, rc);
221
222 return true;
223 }
224
225 // change the state of the item and redraw it
226 void wxCheckListBoxItem::Check(bool check)
227 {
228 m_bChecked = check;
229
230 // index may be changed because new items were added/deleted
231 if ( m_pParent->GetItemIndex(this) != (int)m_nIndex )
232 {
233 // update it
234 int index = m_pParent->GetItemIndex(this);
235
236 wxASSERT_MSG( index != wxNOT_FOUND, wxT("what does this item do here?") );
237
238 m_nIndex = (size_t)index;
239 }
240
241 HWND hwndListbox = (HWND)m_pParent->GetHWND();
242
243 RECT rcUpdate;
244
245 if ( ::SendMessage(hwndListbox, LB_GETITEMRECT,
246 m_nIndex, (LPARAM)&rcUpdate) == LB_ERR )
247 {
248 wxLogDebug(wxT("LB_GETITEMRECT failed"));
249 }
250
251 ::InvalidateRect(hwndListbox, &rcUpdate, FALSE);
252 }
253
254 // send an "item checked" event
255 void wxCheckListBoxItem::SendEvent()
256 {
257 wxCommandEvent event(wxEVT_COMMAND_CHECKLISTBOX_TOGGLED, m_pParent->GetId());
258 event.SetInt(m_nIndex);
259 event.SetEventObject(m_pParent);
260 event.SetString(m_pParent->GetString(m_nIndex));
261 m_pParent->ProcessCommand(event);
262 }
263
264 // ----------------------------------------------------------------------------
265 // implementation of wxCheckListBox class
266 // ----------------------------------------------------------------------------
267
268 // define event table
269 // ------------------
270 BEGIN_EVENT_TABLE(wxCheckListBox, wxListBox)
271 EVT_KEY_DOWN(wxCheckListBox::OnKeyDown)
272 EVT_LEFT_DOWN(wxCheckListBox::OnLeftClick)
273 END_EVENT_TABLE()
274
275 // control creation
276 // ----------------
277
278 // def ctor: use Create() to really create the control
279 wxCheckListBox::wxCheckListBox()
280 {
281 }
282
283 // ctor which creates the associated control
284 wxCheckListBox::wxCheckListBox(wxWindow *parent, wxWindowID id,
285 const wxPoint& pos, const wxSize& size,
286 int nStrings, const wxString choices[],
287 long style, const wxValidator& val,
288 const wxString& name)
289 {
290 Create(parent, id, pos, size, nStrings, choices, style, val, name);
291 }
292
293 wxCheckListBox::wxCheckListBox(wxWindow *parent, wxWindowID id,
294 const wxPoint& pos, const wxSize& size,
295 const wxArrayString& choices,
296 long style, const wxValidator& val,
297 const wxString& name)
298 {
299 Create(parent, id, pos, size, choices, style, val, name);
300 }
301
302 bool wxCheckListBox::Create(wxWindow *parent, wxWindowID id,
303 const wxPoint& pos, const wxSize& size,
304 int n, const wxString choices[],
305 long style,
306 const wxValidator& validator, const wxString& name)
307 {
308 return wxListBox::Create(parent, id, pos, size, n, choices,
309 style | wxLB_OWNERDRAW, validator, name);
310 }
311
312 bool wxCheckListBox::Create(wxWindow *parent, wxWindowID id,
313 const wxPoint& pos, const wxSize& size,
314 const wxArrayString& choices,
315 long style,
316 const wxValidator& validator, const wxString& name)
317 {
318 return wxListBox::Create(parent, id, pos, size, choices,
319 style | wxLB_OWNERDRAW, validator, name);
320 }
321
322 // misc overloaded methods
323 // -----------------------
324
325 void wxCheckListBox::Delete(unsigned int n)
326 {
327 wxCHECK_RET( IsValid(n),
328 wxT("invalid index in wxListBox::Delete") );
329
330 wxListBox::Delete(n);
331
332 // free memory
333 delete m_aItems[n];
334
335 m_aItems.RemoveAt(n);
336 }
337
338 bool wxCheckListBox::SetFont( const wxFont &font )
339 {
340 unsigned int i;
341 for ( i = 0; i < m_aItems.GetCount(); i++ )
342 m_aItems[i]->SetFont(font);
343
344 wxListBox::SetFont(font);
345
346 return true;
347 }
348
349 // create/retrieve item
350 // --------------------
351
352 // create a check list box item
353 wxOwnerDrawn *wxCheckListBox::CreateLboxItem(size_t nIndex)
354 {
355 wxCheckListBoxItem *pItem = new wxCheckListBoxItem(this, nIndex);
356 return pItem;
357 }
358
359 // return item size
360 // ----------------
361 bool wxCheckListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT *item)
362 {
363 if ( wxListBox::MSWOnMeasure(item) ) {
364 MEASUREITEMSTRUCT *pStruct = (MEASUREITEMSTRUCT *)item;
365
366 // add place for the check mark
367 pStruct->itemWidth += wxOwnerDrawn::GetDefaultMarginWidth();
368 pStruct->itemHeight += 1;
369
370 // save item height
371 m_nItemHeight = pStruct->itemHeight;
372
373 return true;
374 }
375
376 return false;
377 }
378
379 // check items
380 // -----------
381
382 bool wxCheckListBox::IsChecked(unsigned int uiIndex) const
383 {
384 wxCHECK_MSG( IsValid(uiIndex), false, wxT("bad wxCheckListBox index") );
385
386 return GetItem(uiIndex)->IsChecked();
387 }
388
389 void wxCheckListBox::Check(unsigned int uiIndex, bool bCheck)
390 {
391 wxCHECK_RET( IsValid(uiIndex), wxT("bad wxCheckListBox index") );
392
393 GetItem(uiIndex)->Check(bCheck);
394 }
395
396 // process events
397 // --------------
398
399 void wxCheckListBox::OnKeyDown(wxKeyEvent& event)
400 {
401 // what do we do?
402 enum
403 {
404 None,
405 Toggle,
406 Set,
407 Clear
408 } oper;
409
410 switch ( event.GetKeyCode() )
411 {
412 case WXK_SPACE:
413 oper = Toggle;
414 break;
415
416 case WXK_NUMPAD_ADD:
417 case '+':
418 oper = Set;
419 break;
420
421 case WXK_NUMPAD_SUBTRACT:
422 case '-':
423 oper = Clear;
424 break;
425
426 default:
427 oper = None;
428 }
429
430 if ( oper != None )
431 {
432 wxArrayInt selections;
433 int count = 0;
434 if ( HasMultipleSelection() )
435 {
436 count = GetSelections(selections);
437 }
438 else
439 {
440 int sel = GetSelection();
441 if (sel != -1)
442 {
443 count = 1;
444 selections.Add(sel);
445 }
446 }
447
448 for ( int i = 0; i < count; i++ )
449 {
450 wxCheckListBoxItem *item = GetItem(selections[i]);
451 if ( !item )
452 {
453 wxFAIL_MSG( wxT("no wxCheckListBoxItem?") );
454 continue;
455 }
456
457 switch ( oper )
458 {
459 case Toggle:
460 item->Toggle();
461 break;
462
463 case Set:
464 case Clear:
465 item->Check( oper == Set );
466 break;
467
468 default:
469 wxFAIL_MSG( wxT("what should this key do?") );
470 }
471
472 // we should send an event as this has been done by the user and
473 // not by the program
474 item->SendEvent();
475 }
476 }
477 else // nothing to do
478 {
479 event.Skip();
480 }
481 }
482
483 void wxCheckListBox::OnLeftClick(wxMouseEvent& event)
484 {
485 // clicking on the item selects it, clicking on the checkmark toggles
486 if ( event.GetX() <= wxOwnerDrawn::GetDefaultMarginWidth() )
487 {
488 int nItem = HitTest(event.GetX(), event.GetY());
489
490 if ( nItem != wxNOT_FOUND )
491 {
492 // people expect to get "kill focus" event for the currently
493 // focused control before getting events from the other controls
494 // and, equally importantly, they may prevent the focus change from
495 // taking place at all (e.g. because the old control contents is
496 // invalid and needs to be corrected) in which case we shouldn't
497 // generate this event at all
498 SetFocus();
499 if ( FindFocus() == this )
500 {
501 wxCheckListBoxItem *item = GetItem(nItem);
502 item->Toggle();
503 item->SendEvent();
504 }
505 }
506 //else: it's not an error, just click outside of client zone
507 }
508 else
509 {
510 // implement default behaviour: clicking on the item selects it
511 event.Skip();
512 }
513 }
514
515 wxSize wxCheckListBox::DoGetBestSize() const
516 {
517 wxSize best = wxListBox::DoGetBestSize();
518 best.x += wxOwnerDrawn::GetDefaultMarginWidth(); // add room for the checkbox
519 CacheBestSize(best);
520 return best;
521 }
522
523 #endif // wxUSE_CHECKLISTBOX