]> git.saurik.com Git - wxWidgets.git/blob - src/msw/listbox.cpp
Improve inotify()-based wxFileSystemWatcher to handle creation/deletion.
[wxWidgets.git] / src / msw / listbox.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/listbox.cpp
3 // Purpose: wxListBox
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin (owner drawn stuff)
6 // Created:
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
11
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
14
15 #ifdef __BORLANDC__
16 #pragma hdrstop
17 #endif
18
19 #if wxUSE_LISTBOX
20
21 #include "wx/listbox.h"
22
23 #ifndef WX_PRECOMP
24 #include "wx/dynarray.h"
25 #include "wx/settings.h"
26 #include "wx/brush.h"
27 #include "wx/font.h"
28 #include "wx/dc.h"
29 #include "wx/utils.h"
30 #include "wx/log.h"
31 #include "wx/window.h"
32 #endif
33
34 #include "wx/msw/private.h"
35 #include "wx/msw/dc.h"
36
37 #include <windowsx.h>
38
39 #if wxUSE_OWNER_DRAWN
40 #include "wx/ownerdrw.h"
41 #endif
42
43 // ============================================================================
44 // list box item declaration and implementation
45 // ============================================================================
46
47 #if wxUSE_OWNER_DRAWN
48
49 class wxListBoxItem : public wxOwnerDrawn
50 {
51 public:
52 wxListBoxItem(wxListBox *parent)
53 { m_parent = parent; }
54
55 wxListBox *GetParent() const
56 { return m_parent; }
57
58 int GetIndex() const
59 { return m_parent->GetItemIndex(const_cast<wxListBoxItem*>(this)); }
60
61 wxString GetName() const
62 { return m_parent->GetString(GetIndex()); }
63
64 private:
65 wxListBox *m_parent;
66 };
67
68 wxOwnerDrawn *wxListBox::CreateLboxItem(size_t WXUNUSED(n))
69 {
70 return new wxListBoxItem(this);
71 }
72
73 #endif //USE_OWNER_DRAWN
74
75 // ============================================================================
76 // list box control implementation
77 // ============================================================================
78
79 // ----------------------------------------------------------------------------
80 // creation
81 // ----------------------------------------------------------------------------
82
83 void wxListBox::Init()
84 {
85 m_noItems = 0;
86 m_updateHorizontalExtent = false;
87 }
88
89 bool wxListBox::Create(wxWindow *parent,
90 wxWindowID id,
91 const wxPoint& pos,
92 const wxSize& size,
93 int n, const wxString choices[],
94 long style,
95 const wxValidator& validator,
96 const wxString& name)
97 {
98 // initialize base class fields
99 if ( !CreateControl(parent, id, pos, size, style, validator, name) )
100 return false;
101
102 // create the native control
103 if ( !MSWCreateControl(wxT("LISTBOX"), wxEmptyString, pos, size) )
104 {
105 // control creation failed
106 return false;
107 }
108
109 // initialize the contents
110 for ( int i = 0; i < n; i++ )
111 {
112 Append(choices[i]);
113 }
114
115 // now we can compute our best size correctly, so do it again
116 SetInitialSize(size);
117
118 return true;
119 }
120
121 bool wxListBox::Create(wxWindow *parent,
122 wxWindowID id,
123 const wxPoint& pos,
124 const wxSize& size,
125 const wxArrayString& choices,
126 long style,
127 const wxValidator& validator,
128 const wxString& name)
129 {
130 wxCArrayString chs(choices);
131 return Create(parent, id, pos, size, chs.GetCount(), chs.GetStrings(),
132 style, validator, name);
133 }
134
135 wxListBox::~wxListBox()
136 {
137 Clear();
138 }
139
140 WXDWORD wxListBox::MSWGetStyle(long style, WXDWORD *exstyle) const
141 {
142 WXDWORD msStyle = wxControl::MSWGetStyle(style, exstyle);
143
144 // we always want to get the notifications
145 msStyle |= LBS_NOTIFY;
146
147 // without this style, you get unexpected heights, so e.g. constraint
148 // layout doesn't work properly
149 msStyle |= LBS_NOINTEGRALHEIGHT;
150
151 wxASSERT_MSG( !(style & wxLB_MULTIPLE) || !(style & wxLB_EXTENDED),
152 wxT("only one of listbox selection modes can be specified") );
153
154 if ( style & wxLB_MULTIPLE )
155 msStyle |= LBS_MULTIPLESEL;
156 else if ( style & wxLB_EXTENDED )
157 msStyle |= LBS_EXTENDEDSEL;
158
159 wxASSERT_MSG( !(style & wxLB_ALWAYS_SB) || !(style & wxLB_NO_SB),
160 wxT( "Conflicting styles wxLB_ALWAYS_SB and wxLB_NO_SB." ) );
161
162 if ( !(style & wxLB_NO_SB) )
163 {
164 msStyle |= WS_VSCROLL;
165 if ( style & wxLB_ALWAYS_SB )
166 msStyle |= LBS_DISABLENOSCROLL;
167 }
168
169 if ( m_windowStyle & wxLB_HSCROLL )
170 msStyle |= WS_HSCROLL;
171 if ( m_windowStyle & wxLB_SORT )
172 msStyle |= LBS_SORT;
173
174 #if wxUSE_OWNER_DRAWN && !defined(__WXWINCE__)
175 if ( m_windowStyle & wxLB_OWNERDRAW )
176 {
177 // we don't support LBS_OWNERDRAWVARIABLE yet and we also always put
178 // the strings in the listbox for simplicity even though we could have
179 // avoided it in this case
180 msStyle |= LBS_OWNERDRAWFIXED | LBS_HASSTRINGS;
181 }
182 #endif // wxUSE_OWNER_DRAWN
183
184 return msStyle;
185 }
186
187 void wxListBox::OnInternalIdle()
188 {
189 wxWindow::OnInternalIdle();
190
191 if (m_updateHorizontalExtent)
192 {
193 SetHorizontalExtent(wxEmptyString);
194 m_updateHorizontalExtent = false;
195 }
196 }
197
198 void wxListBox::MSWOnItemsChanged()
199 {
200 // we need to do two things when items change: update their max horizontal
201 // extent so that horizontal scrollbar could be shown or hidden as
202 // appropriate and also invlaidate the best size
203 //
204 // updating the max extent is slow (it's an O(N) operation) and so we defer
205 // it until the idle time but the best size should be invalidated
206 // immediately doing it in idle time is too late -- layout using incorrect
207 // old best size will have been already done by then
208
209 m_updateHorizontalExtent = true;
210
211 InvalidateBestSize();
212 }
213
214 // ----------------------------------------------------------------------------
215 // implementation of wxListBoxBase methods
216 // ----------------------------------------------------------------------------
217
218 void wxListBox::DoSetFirstItem(int N)
219 {
220 wxCHECK_RET( IsValid(N),
221 wxT("invalid index in wxListBox::SetFirstItem") );
222
223 SendMessage(GetHwnd(), LB_SETTOPINDEX, (WPARAM)N, (LPARAM)0);
224 }
225
226 void wxListBox::DoDeleteOneItem(unsigned int n)
227 {
228 wxCHECK_RET( IsValid(n),
229 wxT("invalid index in wxListBox::Delete") );
230
231 #if wxUSE_OWNER_DRAWN
232 if ( HasFlag(wxLB_OWNERDRAW) )
233 {
234 delete m_aItems[n];
235 m_aItems.RemoveAt(n);
236 }
237 #endif // wxUSE_OWNER_DRAWN
238
239 SendMessage(GetHwnd(), LB_DELETESTRING, n, 0);
240 m_noItems--;
241
242 MSWOnItemsChanged();
243
244 UpdateOldSelections();
245 }
246
247 int wxListBox::FindString(const wxString& s, bool bCase) const
248 {
249 // back to base class search for not native search type
250 if (bCase)
251 return wxItemContainerImmutable::FindString( s, bCase );
252
253 int pos = ListBox_FindStringExact(GetHwnd(), -1, s.t_str());
254 if (pos == LB_ERR)
255 return wxNOT_FOUND;
256 else
257 return pos;
258 }
259
260 void wxListBox::DoClear()
261 {
262 #if wxUSE_OWNER_DRAWN
263 if ( HasFlag(wxLB_OWNERDRAW) )
264 {
265 WX_CLEAR_ARRAY(m_aItems);
266 }
267 #endif // wxUSE_OWNER_DRAWN
268
269 ListBox_ResetContent(GetHwnd());
270
271 m_noItems = 0;
272 MSWOnItemsChanged();
273
274 UpdateOldSelections();
275 }
276
277 void wxListBox::DoSetSelection(int N, bool select)
278 {
279 wxCHECK_RET( N == wxNOT_FOUND || IsValid(N),
280 wxT("invalid index in wxListBox::SetSelection") );
281
282 if ( HasMultipleSelection() )
283 {
284 // Setting selection to -1 should deselect everything.
285 const bool deselectAll = N == wxNOT_FOUND;
286 SendMessage(GetHwnd(), LB_SETSEL,
287 deselectAll ? FALSE : select,
288 deselectAll ? -1 : N);
289 }
290 else
291 {
292 SendMessage(GetHwnd(), LB_SETCURSEL, select ? N : -1, 0);
293 }
294
295 UpdateOldSelections();
296 }
297
298 bool wxListBox::IsSelected(int N) const
299 {
300 wxCHECK_MSG( IsValid(N), false,
301 wxT("invalid index in wxListBox::Selected") );
302
303 return SendMessage(GetHwnd(), LB_GETSEL, N, 0) == 0 ? false : true;
304 }
305
306 void *wxListBox::DoGetItemClientData(unsigned int n) const
307 {
308 LPARAM rc = SendMessage(GetHwnd(), LB_GETITEMDATA, n, 0);
309 if ( rc == LB_ERR && GetLastError() != ERROR_SUCCESS )
310 {
311 wxLogLastError(wxT("LB_GETITEMDATA"));
312
313 return NULL;
314 }
315
316 return (void *)rc;
317 }
318
319 void wxListBox::DoSetItemClientData(unsigned int n, void *clientData)
320 {
321 if ( ListBox_SetItemData(GetHwnd(), n, clientData) == LB_ERR )
322 {
323 wxLogDebug(wxT("LB_SETITEMDATA failed"));
324 }
325 }
326
327 // Return number of selections and an array of selected integers
328 int wxListBox::GetSelections(wxArrayInt& aSelections) const
329 {
330 aSelections.Empty();
331
332 if ( HasMultipleSelection() )
333 {
334 int countSel = ListBox_GetSelCount(GetHwnd());
335 if ( countSel == LB_ERR )
336 {
337 wxLogDebug(wxT("ListBox_GetSelCount failed"));
338 }
339 else if ( countSel != 0 )
340 {
341 int *selections = new int[countSel];
342
343 if ( ListBox_GetSelItems(GetHwnd(),
344 countSel, selections) == LB_ERR )
345 {
346 wxLogDebug(wxT("ListBox_GetSelItems failed"));
347 countSel = -1;
348 }
349 else
350 {
351 aSelections.Alloc(countSel);
352 for ( int n = 0; n < countSel; n++ )
353 aSelections.Add(selections[n]);
354 }
355
356 delete [] selections;
357 }
358
359 return countSel;
360 }
361 else // single-selection listbox
362 {
363 if (ListBox_GetCurSel(GetHwnd()) > -1)
364 aSelections.Add(ListBox_GetCurSel(GetHwnd()));
365
366 return aSelections.Count();
367 }
368 }
369
370 // Get single selection, for single choice list items
371 int wxListBox::GetSelection() const
372 {
373 wxCHECK_MSG( !HasMultipleSelection(),
374 -1,
375 wxT("GetSelection() can't be used with multiple-selection listboxes, use GetSelections() instead.") );
376
377 return ListBox_GetCurSel(GetHwnd());
378 }
379
380 // Find string for position
381 wxString wxListBox::GetString(unsigned int n) const
382 {
383 wxCHECK_MSG( IsValid(n), wxEmptyString,
384 wxT("invalid index in wxListBox::GetString") );
385
386 int len = ListBox_GetTextLen(GetHwnd(), n);
387
388 // +1 for terminating NUL
389 wxString result;
390 ListBox_GetText(GetHwnd(), n, (wxChar*)wxStringBuffer(result, len + 1));
391
392 return result;
393 }
394
395 int wxListBox::DoInsertItems(const wxArrayStringsAdapter & items,
396 unsigned int pos,
397 void **clientData,
398 wxClientDataType type)
399 {
400 MSWAllocStorage(items, LB_INITSTORAGE);
401
402 const bool append = pos == GetCount();
403
404 // we must use CB_ADDSTRING when appending as only it works correctly for
405 // the sorted controls
406 const unsigned msg = append ? LB_ADDSTRING : LB_INSERTSTRING;
407
408 if ( append )
409 pos = 0;
410
411 int n = wxNOT_FOUND;
412
413 const unsigned int numItems = items.GetCount();
414 for ( unsigned int i = 0; i < numItems; i++ )
415 {
416 n = MSWInsertOrAppendItem(pos, items[i], msg);
417 if ( n == wxNOT_FOUND )
418 return n;
419
420 if ( !append )
421 pos++;
422
423 ++m_noItems;
424
425 #if wxUSE_OWNER_DRAWN
426 if ( HasFlag(wxLB_OWNERDRAW) )
427 {
428 wxOwnerDrawn *pNewItem = CreateLboxItem(n);
429 pNewItem->SetFont(GetFont());
430 m_aItems.Insert(pNewItem, n);
431 }
432 #endif // wxUSE_OWNER_DRAWN
433 AssignNewItemClientData(n, clientData, i, type);
434 }
435
436 MSWOnItemsChanged();
437
438 UpdateOldSelections();
439
440 return n;
441 }
442
443 int wxListBox::DoHitTestList(const wxPoint& point) const
444 {
445 LRESULT lRes = ::SendMessage(GetHwnd(), LB_ITEMFROMPOINT,
446 0, MAKELPARAM(point.x, point.y));
447
448 // non zero high-order word means that this item is outside of the client
449 // area, IOW the point is outside of the listbox
450 return HIWORD(lRes) ? wxNOT_FOUND : LOWORD(lRes);
451 }
452
453 void wxListBox::SetString(unsigned int n, const wxString& s)
454 {
455 wxCHECK_RET( IsValid(n),
456 wxT("invalid index in wxListBox::SetString") );
457
458 // remember the state of the item
459 bool wasSelected = IsSelected(n);
460
461 void *oldData = NULL;
462 wxClientData *oldObjData = NULL;
463 if ( HasClientUntypedData() )
464 oldData = GetClientData(n);
465 else if ( HasClientObjectData() )
466 oldObjData = GetClientObject(n);
467
468 // delete and recreate it
469 SendMessage(GetHwnd(), LB_DELETESTRING, n, 0);
470
471 int newN = n;
472 if ( n == (m_noItems - 1) )
473 newN = -1;
474
475 ListBox_InsertString(GetHwnd(), newN, s.t_str());
476
477 // restore the client data
478 if ( oldData )
479 SetClientData(n, oldData);
480 else if ( oldObjData )
481 SetClientObject(n, oldObjData);
482
483 // we may have lost the selection
484 if ( wasSelected )
485 Select(n);
486
487 MSWOnItemsChanged();
488 }
489
490 unsigned int wxListBox::GetCount() const
491 {
492 return m_noItems;
493 }
494
495 // ----------------------------------------------------------------------------
496 // size-related stuff
497 // ----------------------------------------------------------------------------
498
499 void wxListBox::SetHorizontalExtent(const wxString& s)
500 {
501 // the rest is only necessary if we want a horizontal scrollbar
502 if ( !HasFlag(wxHSCROLL) )
503 return;
504
505
506 WindowHDC dc(GetHwnd());
507 SelectInHDC selFont(dc, GetHfontOf(GetFont()));
508
509 TEXTMETRIC lpTextMetric;
510 ::GetTextMetrics(dc, &lpTextMetric);
511
512 int largestExtent = 0;
513 SIZE extentXY;
514
515 if ( s.empty() )
516 {
517 // set extent to the max length of all strings
518 for ( unsigned int i = 0; i < m_noItems; i++ )
519 {
520 const wxString str = GetString(i);
521 ::GetTextExtentPoint32(dc, str.c_str(), str.length(), &extentXY);
522
523 int extentX = (int)(extentXY.cx + lpTextMetric.tmAveCharWidth);
524 if ( extentX > largestExtent )
525 largestExtent = extentX;
526 }
527 }
528 else // just increase the extent to the length of this string
529 {
530 int existingExtent = (int)SendMessage(GetHwnd(),
531 LB_GETHORIZONTALEXTENT, 0, 0L);
532
533 ::GetTextExtentPoint32(dc, s.c_str(), s.length(), &extentXY);
534
535 int extentX = (int)(extentXY.cx + lpTextMetric.tmAveCharWidth);
536 if ( extentX > existingExtent )
537 largestExtent = extentX;
538 }
539
540 if ( largestExtent )
541 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT, LOWORD(largestExtent), 0L);
542 //else: it shouldn't change
543 }
544
545 wxSize wxListBox::DoGetBestClientSize() const
546 {
547 // find the widest string
548 int wLine;
549 int wListbox = 0;
550 for (unsigned int i = 0; i < m_noItems; i++)
551 {
552 wxString str(GetString(i));
553 GetTextExtent(str, &wLine, NULL);
554 if ( wLine > wListbox )
555 wListbox = wLine;
556 }
557
558 // give it some reasonable default value if there are no strings in the
559 // list
560 if ( wListbox == 0 )
561 wListbox = 100;
562
563 // the listbox should be slightly larger than the widest string
564 wListbox += 3*GetCharWidth();
565
566 // add room for the scrollbar
567 wListbox += wxSystemSettings::GetMetric(wxSYS_VSCROLL_X);
568
569 // don't make the listbox too tall (limit height to 10 items) but don't
570 // make it too small neither
571 int hListbox = SendMessage(GetHwnd(), LB_GETITEMHEIGHT, 0, 0)*
572 wxMin(wxMax(m_noItems, 3), 10);
573
574 return wxSize(wListbox, hListbox);
575 }
576
577 // ----------------------------------------------------------------------------
578 // callbacks
579 // ----------------------------------------------------------------------------
580
581 bool wxListBox::MSWCommand(WXUINT param, WXWORD WXUNUSED(id))
582 {
583 wxEventType evtType;
584 if ( param == LBN_SELCHANGE )
585 {
586 if ( HasMultipleSelection() )
587 return CalcAndSendEvent();
588
589 evtType = wxEVT_COMMAND_LISTBOX_SELECTED;
590 }
591 else if ( param == LBN_DBLCLK )
592 {
593 // Clicking under the last item in the listbox generates double click
594 // event for the currently selected item which is rather surprising.
595 // Avoid the surprise by checking that we do have an item under mouse.
596 const DWORD pos = ::GetMessagePos();
597 const wxPoint pt(GET_X_LPARAM(pos), GET_Y_LPARAM(pos));
598 if ( HitTest(ScreenToClient(pt)) == wxNOT_FOUND )
599 return false;
600
601 evtType = wxEVT_COMMAND_LISTBOX_DOUBLECLICKED;
602 }
603 else
604 {
605 // some event we're not interested in
606 return false;
607 }
608
609 const int n = ListBox_GetCurSel(GetHwnd());
610
611 // We get events even when mouse is clicked outside of any valid item from
612 // Windows, just ignore them.
613 if ( n == wxNOT_FOUND )
614 return false;
615
616 if ( param == LBN_SELCHANGE )
617 {
618 if ( !DoChangeSingleSelection(n) )
619 return false;
620 }
621
622 // Do generate an event otherwise.
623 return SendEvent(evtType, n, true /* selection */);
624 }
625
626 // ----------------------------------------------------------------------------
627 // owner-drawn list boxes support
628 // ----------------------------------------------------------------------------
629
630 #if wxUSE_OWNER_DRAWN
631
632 // misc overloaded methods
633 // -----------------------
634
635 bool wxListBox::SetFont(const wxFont &font)
636 {
637 if ( HasFlag(wxLB_OWNERDRAW) )
638 {
639 const unsigned count = m_aItems.GetCount();
640 for ( unsigned i = 0; i < count; i++ )
641 m_aItems[i]->SetFont(font);
642 }
643
644 wxListBoxBase::SetFont(font);
645
646 return true;
647 }
648
649 bool wxListBox::GetItemRect(size_t n, wxRect& rect) const
650 {
651 wxCHECK_MSG( IsValid(n), false,
652 wxT("invalid index in wxListBox::GetItemRect") );
653
654 RECT rc;
655
656 if ( ListBox_GetItemRect(GetHwnd(), n, &rc) != LB_ERR )
657 {
658 rect = wxRectFromRECT(rc);
659 return true;
660 }
661 else
662 {
663 // couldn't retrieve rect: for example, item isn't visible
664 return false;
665 }
666 }
667
668 bool wxListBox::RefreshItem(size_t n)
669 {
670 wxRect rect;
671 if ( !GetItemRect(n, rect) )
672 return false;
673
674 RECT rc;
675 wxCopyRectToRECT(rect, rc);
676
677 return ::InvalidateRect((HWND)GetHWND(), &rc, FALSE) == TRUE;
678 }
679
680
681 // drawing
682 // -------
683
684 namespace
685 {
686 // space beneath/above each row in pixels
687 static const int LISTBOX_EXTRA_SPACE = 1;
688
689 } // anonymous namespace
690
691 // the height is the same for all items
692 // TODO should be changed for LBS_OWNERDRAWVARIABLE style listboxes
693
694 // NB: can't forward this to wxListBoxItem because LB_SETITEMDATA
695 // message is not yet sent when we get here!
696 bool wxListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT *item)
697 {
698 // only owner-drawn control should receive this message
699 wxCHECK( HasFlag(wxLB_OWNERDRAW), false );
700
701 MEASUREITEMSTRUCT *pStruct = (MEASUREITEMSTRUCT *)item;
702
703 #ifdef __WXWINCE__
704 HDC hdc = GetDC(NULL);
705 #else
706 HDC hdc = CreateIC(wxT("DISPLAY"), NULL, NULL, 0);
707 #endif
708
709 {
710 wxDCTemp dc((WXHDC)hdc);
711 dc.SetFont(GetFont());
712
713 pStruct->itemHeight = dc.GetCharHeight() + 2 * LISTBOX_EXTRA_SPACE;
714 pStruct->itemWidth = dc.GetCharWidth();
715 }
716
717 #ifdef __WXWINCE__
718 ReleaseDC(NULL, hdc);
719 #else
720 DeleteDC(hdc);
721 #endif
722
723 return true;
724 }
725
726 // forward the message to the appropriate item
727 bool wxListBox::MSWOnDraw(WXDRAWITEMSTRUCT *item)
728 {
729 // only owner-drawn control should receive this message
730 wxCHECK( HasFlag(wxLB_OWNERDRAW), false );
731
732 DRAWITEMSTRUCT *pStruct = (DRAWITEMSTRUCT *)item;
733
734 // the item may be -1 for an empty listbox
735 if ( pStruct->itemID == (UINT)-1 )
736 return false;
737
738 wxListBoxItem *pItem = (wxListBoxItem *)m_aItems[pStruct->itemID];
739
740 wxDCTemp dc((WXHDC)pStruct->hDC);
741
742 return pItem->OnDrawItem(dc, wxRectFromRECT(pStruct->rcItem),
743 (wxOwnerDrawn::wxODAction)pStruct->itemAction,
744 (wxOwnerDrawn::wxODStatus)(pStruct->itemState | wxOwnerDrawn::wxODHidePrefix));
745 }
746
747 #endif // wxUSE_OWNER_DRAWN
748
749 #endif // wxUSE_LISTBOX