]>
git.saurik.com Git - wxWidgets.git/blob - src/msw/listbox.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/listbox.cpp
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin (owner drawn stuff)
7 // Copyright: (c) Julian Smart
8 // Licence: wxWindows licence
9 ///////////////////////////////////////////////////////////////////////////////
11 // For compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
20 #include "wx/listbox.h"
23 #include "wx/dynarray.h"
24 #include "wx/settings.h"
30 #include "wx/window.h"
33 #include "wx/msw/private.h"
34 #include "wx/msw/dc.h"
39 #include "wx/ownerdrw.h"
42 // ============================================================================
43 // list box item declaration and implementation
44 // ============================================================================
48 class wxListBoxItem
: public wxOwnerDrawn
51 wxListBoxItem(wxListBox
*parent
)
52 { m_parent
= parent
; }
54 wxListBox
*GetParent() const
58 { return m_parent
->GetItemIndex(const_cast<wxListBoxItem
*>(this)); }
60 wxString
GetName() const
61 { return m_parent
->GetString(GetIndex()); }
67 wxOwnerDrawn
*wxListBox::CreateLboxItem(size_t WXUNUSED(n
))
69 return new wxListBoxItem(this);
72 #endif //USE_OWNER_DRAWN
74 // ============================================================================
75 // list box control implementation
76 // ============================================================================
78 // ----------------------------------------------------------------------------
80 // ----------------------------------------------------------------------------
82 void wxListBox::Init()
85 m_updateHorizontalExtent
= false;
88 bool wxListBox::Create(wxWindow
*parent
,
92 int n
, const wxString choices
[],
94 const wxValidator
& validator
,
97 // initialize base class fields
98 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
101 // create the native control
102 if ( !MSWCreateControl(wxT("LISTBOX"), wxEmptyString
, pos
, size
) )
104 // control creation failed
108 // initialize the contents
109 for ( int i
= 0; i
< n
; i
++ )
114 // now we can compute our best size correctly, so do it again
115 SetInitialSize(size
);
120 bool wxListBox::Create(wxWindow
*parent
,
124 const wxArrayString
& choices
,
126 const wxValidator
& validator
,
127 const wxString
& name
)
129 wxCArrayString
chs(choices
);
130 return Create(parent
, id
, pos
, size
, chs
.GetCount(), chs
.GetStrings(),
131 style
, validator
, name
);
134 wxListBox::~wxListBox()
139 WXDWORD
wxListBox::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
141 WXDWORD msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
143 // we always want to get the notifications
144 msStyle
|= LBS_NOTIFY
;
146 // without this style, you get unexpected heights, so e.g. constraint
147 // layout doesn't work properly
148 msStyle
|= LBS_NOINTEGRALHEIGHT
;
150 wxASSERT_MSG( !(style
& wxLB_MULTIPLE
) || !(style
& wxLB_EXTENDED
),
151 wxT("only one of listbox selection modes can be specified") );
153 if ( style
& wxLB_MULTIPLE
)
154 msStyle
|= LBS_MULTIPLESEL
;
155 else if ( style
& wxLB_EXTENDED
)
156 msStyle
|= LBS_EXTENDEDSEL
;
158 wxASSERT_MSG( !(style
& wxLB_ALWAYS_SB
) || !(style
& wxLB_NO_SB
),
159 wxT( "Conflicting styles wxLB_ALWAYS_SB and wxLB_NO_SB." ) );
161 if ( !(style
& wxLB_NO_SB
) )
163 msStyle
|= WS_VSCROLL
;
164 if ( style
& wxLB_ALWAYS_SB
)
165 msStyle
|= LBS_DISABLENOSCROLL
;
168 if ( m_windowStyle
& wxLB_HSCROLL
)
169 msStyle
|= WS_HSCROLL
;
170 if ( m_windowStyle
& wxLB_SORT
)
173 #if wxUSE_OWNER_DRAWN && !defined(__WXWINCE__)
174 if ( m_windowStyle
& wxLB_OWNERDRAW
)
176 // we don't support LBS_OWNERDRAWVARIABLE yet and we also always put
177 // the strings in the listbox for simplicity even though we could have
178 // avoided it in this case
179 msStyle
|= LBS_OWNERDRAWFIXED
| LBS_HASSTRINGS
;
181 #endif // wxUSE_OWNER_DRAWN
186 void wxListBox::OnInternalIdle()
188 wxWindow::OnInternalIdle();
190 if (m_updateHorizontalExtent
)
192 SetHorizontalExtent(wxEmptyString
);
193 m_updateHorizontalExtent
= false;
197 void wxListBox::MSWOnItemsChanged()
199 // we need to do two things when items change: update their max horizontal
200 // extent so that horizontal scrollbar could be shown or hidden as
201 // appropriate and also invlaidate the best size
203 // updating the max extent is slow (it's an O(N) operation) and so we defer
204 // it until the idle time but the best size should be invalidated
205 // immediately doing it in idle time is too late -- layout using incorrect
206 // old best size will have been already done by then
208 m_updateHorizontalExtent
= true;
210 InvalidateBestSize();
213 // ----------------------------------------------------------------------------
214 // implementation of wxListBoxBase methods
215 // ----------------------------------------------------------------------------
217 void wxListBox::DoSetFirstItem(int N
)
219 wxCHECK_RET( IsValid(N
),
220 wxT("invalid index in wxListBox::SetFirstItem") );
222 SendMessage(GetHwnd(), LB_SETTOPINDEX
, (WPARAM
)N
, (LPARAM
)0);
225 void wxListBox::DoDeleteOneItem(unsigned int n
)
227 wxCHECK_RET( IsValid(n
),
228 wxT("invalid index in wxListBox::Delete") );
230 #if wxUSE_OWNER_DRAWN
231 if ( HasFlag(wxLB_OWNERDRAW
) )
234 m_aItems
.RemoveAt(n
);
236 #endif // wxUSE_OWNER_DRAWN
238 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
243 UpdateOldSelections();
246 int wxListBox::FindString(const wxString
& s
, bool bCase
) const
248 // back to base class search for not native search type
250 return wxItemContainerImmutable::FindString( s
, bCase
);
252 int pos
= ListBox_FindStringExact(GetHwnd(), -1, s
.t_str());
259 void wxListBox::DoClear()
261 #if wxUSE_OWNER_DRAWN
262 if ( HasFlag(wxLB_OWNERDRAW
) )
264 WX_CLEAR_ARRAY(m_aItems
);
266 #endif // wxUSE_OWNER_DRAWN
268 ListBox_ResetContent(GetHwnd());
273 UpdateOldSelections();
276 void wxListBox::DoSetSelection(int N
, bool select
)
278 wxCHECK_RET( N
== wxNOT_FOUND
|| IsValid(N
),
279 wxT("invalid index in wxListBox::SetSelection") );
281 if ( HasMultipleSelection() )
283 // Setting selection to -1 should deselect everything.
284 const bool deselectAll
= N
== wxNOT_FOUND
;
285 SendMessage(GetHwnd(), LB_SETSEL
,
286 deselectAll
? FALSE
: select
,
287 deselectAll
? -1 : N
);
291 SendMessage(GetHwnd(), LB_SETCURSEL
, select
? N
: -1, 0);
294 UpdateOldSelections();
297 bool wxListBox::IsSelected(int N
) const
299 wxCHECK_MSG( IsValid(N
), false,
300 wxT("invalid index in wxListBox::Selected") );
302 return SendMessage(GetHwnd(), LB_GETSEL
, N
, 0) == 0 ? false : true;
305 void *wxListBox::DoGetItemClientData(unsigned int n
) const
307 LPARAM rc
= SendMessage(GetHwnd(), LB_GETITEMDATA
, n
, 0);
308 if ( rc
== LB_ERR
&& GetLastError() != ERROR_SUCCESS
)
310 wxLogLastError(wxT("LB_GETITEMDATA"));
318 void wxListBox::DoSetItemClientData(unsigned int n
, void *clientData
)
320 if ( ListBox_SetItemData(GetHwnd(), n
, clientData
) == LB_ERR
)
322 wxLogDebug(wxT("LB_SETITEMDATA failed"));
326 // Return number of selections and an array of selected integers
327 int wxListBox::GetSelections(wxArrayInt
& aSelections
) const
331 if ( HasMultipleSelection() )
333 int countSel
= ListBox_GetSelCount(GetHwnd());
334 if ( countSel
== LB_ERR
)
336 wxLogDebug(wxT("ListBox_GetSelCount failed"));
338 else if ( countSel
!= 0 )
340 int *selections
= new int[countSel
];
342 if ( ListBox_GetSelItems(GetHwnd(),
343 countSel
, selections
) == LB_ERR
)
345 wxLogDebug(wxT("ListBox_GetSelItems failed"));
350 aSelections
.Alloc(countSel
);
351 for ( int n
= 0; n
< countSel
; n
++ )
352 aSelections
.Add(selections
[n
]);
355 delete [] selections
;
360 else // single-selection listbox
362 if (ListBox_GetCurSel(GetHwnd()) > -1)
363 aSelections
.Add(ListBox_GetCurSel(GetHwnd()));
365 return aSelections
.Count();
369 // Get single selection, for single choice list items
370 int wxListBox::GetSelection() const
372 wxCHECK_MSG( !HasMultipleSelection(),
374 wxT("GetSelection() can't be used with multiple-selection listboxes, use GetSelections() instead.") );
376 return ListBox_GetCurSel(GetHwnd());
379 // Find string for position
380 wxString
wxListBox::GetString(unsigned int n
) const
382 wxCHECK_MSG( IsValid(n
), wxEmptyString
,
383 wxT("invalid index in wxListBox::GetString") );
385 int len
= ListBox_GetTextLen(GetHwnd(), n
);
387 // +1 for terminating NUL
389 ListBox_GetText(GetHwnd(), n
, (wxChar
*)wxStringBuffer(result
, len
+ 1));
394 int wxListBox::DoInsertItems(const wxArrayStringsAdapter
& items
,
397 wxClientDataType type
)
399 MSWAllocStorage(items
, LB_INITSTORAGE
);
401 const bool append
= pos
== GetCount();
403 // we must use CB_ADDSTRING when appending as only it works correctly for
404 // the sorted controls
405 const unsigned msg
= append
? LB_ADDSTRING
: LB_INSERTSTRING
;
412 const unsigned int numItems
= items
.GetCount();
413 for ( unsigned int i
= 0; i
< numItems
; i
++ )
415 n
= MSWInsertOrAppendItem(pos
, items
[i
], msg
);
416 if ( n
== wxNOT_FOUND
)
424 #if wxUSE_OWNER_DRAWN
425 if ( HasFlag(wxLB_OWNERDRAW
) )
427 wxOwnerDrawn
*pNewItem
= CreateLboxItem(n
);
428 pNewItem
->SetFont(GetFont());
429 m_aItems
.Insert(pNewItem
, n
);
431 #endif // wxUSE_OWNER_DRAWN
432 AssignNewItemClientData(n
, clientData
, i
, type
);
437 UpdateOldSelections();
442 int wxListBox::DoHitTestList(const wxPoint
& point
) const
444 LRESULT lRes
= ::SendMessage(GetHwnd(), LB_ITEMFROMPOINT
,
445 0, MAKELPARAM(point
.x
, point
.y
));
447 // non zero high-order word means that this item is outside of the client
448 // area, IOW the point is outside of the listbox
449 return HIWORD(lRes
) ? wxNOT_FOUND
: LOWORD(lRes
);
452 void wxListBox::SetString(unsigned int n
, const wxString
& s
)
454 wxCHECK_RET( IsValid(n
),
455 wxT("invalid index in wxListBox::SetString") );
457 // remember the state of the item
458 bool wasSelected
= IsSelected(n
);
460 void *oldData
= NULL
;
461 wxClientData
*oldObjData
= NULL
;
462 if ( HasClientUntypedData() )
463 oldData
= GetClientData(n
);
464 else if ( HasClientObjectData() )
465 oldObjData
= GetClientObject(n
);
467 // delete and recreate it
468 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
471 if ( n
== (m_noItems
- 1) )
474 ListBox_InsertString(GetHwnd(), newN
, s
.t_str());
476 // restore the client data
478 SetClientData(n
, oldData
);
479 else if ( oldObjData
)
480 SetClientObject(n
, oldObjData
);
482 // we may have lost the selection
489 unsigned int wxListBox::GetCount() const
494 // ----------------------------------------------------------------------------
495 // size-related stuff
496 // ----------------------------------------------------------------------------
498 void wxListBox::SetHorizontalExtent(const wxString
& s
)
500 // the rest is only necessary if we want a horizontal scrollbar
501 if ( !HasFlag(wxHSCROLL
) )
505 WindowHDC
dc(GetHwnd());
506 SelectInHDC
selFont(dc
, GetHfontOf(GetFont()));
508 TEXTMETRIC lpTextMetric
;
509 ::GetTextMetrics(dc
, &lpTextMetric
);
511 int largestExtent
= 0;
516 // set extent to the max length of all strings
517 for ( unsigned int i
= 0; i
< m_noItems
; i
++ )
519 const wxString str
= GetString(i
);
520 ::GetTextExtentPoint32(dc
, str
.c_str(), str
.length(), &extentXY
);
522 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
523 if ( extentX
> largestExtent
)
524 largestExtent
= extentX
;
527 else // just increase the extent to the length of this string
529 int existingExtent
= (int)SendMessage(GetHwnd(),
530 LB_GETHORIZONTALEXTENT
, 0, 0L);
532 ::GetTextExtentPoint32(dc
, s
.c_str(), s
.length(), &extentXY
);
534 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
535 if ( extentX
> existingExtent
)
536 largestExtent
= extentX
;
540 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT
, LOWORD(largestExtent
), 0L);
541 //else: it shouldn't change
544 wxSize
wxListBox::DoGetBestClientSize() const
546 // find the widest string
549 for (unsigned int i
= 0; i
< m_noItems
; i
++)
551 wxString
str(GetString(i
));
552 GetTextExtent(str
, &wLine
, NULL
);
553 if ( wLine
> wListbox
)
557 // give it some reasonable default value if there are no strings in the
562 // the listbox should be slightly larger than the widest string
563 wListbox
+= 3*GetCharWidth();
565 // add room for the scrollbar
566 wListbox
+= wxSystemSettings::GetMetric(wxSYS_VSCROLL_X
);
568 // don't make the listbox too tall (limit height to 10 items) but don't
569 // make it too small neither
570 int hListbox
= SendMessage(GetHwnd(), LB_GETITEMHEIGHT
, 0, 0)*
571 wxMin(wxMax(m_noItems
, 3), 10);
573 return wxSize(wListbox
, hListbox
);
576 // ----------------------------------------------------------------------------
578 // ----------------------------------------------------------------------------
580 bool wxListBox::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
583 if ( param
== LBN_SELCHANGE
)
585 if ( HasMultipleSelection() )
586 return CalcAndSendEvent();
588 evtType
= wxEVT_LISTBOX
;
590 else if ( param
== LBN_DBLCLK
)
592 // Clicking under the last item in the listbox generates double click
593 // event for the currently selected item which is rather surprising.
594 // Avoid the surprise by checking that we do have an item under mouse.
595 const DWORD pos
= ::GetMessagePos();
596 const wxPoint
pt(GET_X_LPARAM(pos
), GET_Y_LPARAM(pos
));
597 if ( HitTest(ScreenToClient(pt
)) == wxNOT_FOUND
)
600 evtType
= wxEVT_LISTBOX_DCLICK
;
604 // some event we're not interested in
608 const int n
= ListBox_GetCurSel(GetHwnd());
610 // We get events even when mouse is clicked outside of any valid item from
611 // Windows, just ignore them.
612 if ( n
== wxNOT_FOUND
)
615 if ( param
== LBN_SELCHANGE
)
617 if ( !DoChangeSingleSelection(n
) )
621 // Do generate an event otherwise.
622 return SendEvent(evtType
, n
, true /* selection */);
625 // ----------------------------------------------------------------------------
626 // owner-drawn list boxes support
627 // ----------------------------------------------------------------------------
629 #if wxUSE_OWNER_DRAWN
631 // misc overloaded methods
632 // -----------------------
634 bool wxListBox::SetFont(const wxFont
&font
)
636 if ( HasFlag(wxLB_OWNERDRAW
) )
638 const unsigned count
= m_aItems
.GetCount();
639 for ( unsigned i
= 0; i
< count
; i
++ )
640 m_aItems
[i
]->SetFont(font
);
643 wxListBoxBase::SetFont(font
);
648 bool wxListBox::GetItemRect(size_t n
, wxRect
& rect
) const
650 wxCHECK_MSG( IsValid(n
), false,
651 wxT("invalid index in wxListBox::GetItemRect") );
655 if ( ListBox_GetItemRect(GetHwnd(), n
, &rc
) != LB_ERR
)
657 rect
= wxRectFromRECT(rc
);
662 // couldn't retrieve rect: for example, item isn't visible
667 bool wxListBox::RefreshItem(size_t n
)
670 if ( !GetItemRect(n
, rect
) )
674 wxCopyRectToRECT(rect
, rc
);
676 return ::InvalidateRect((HWND
)GetHWND(), &rc
, FALSE
) == TRUE
;
685 // space beneath/above each row in pixels
686 static const int LISTBOX_EXTRA_SPACE
= 1;
688 } // anonymous namespace
690 // the height is the same for all items
691 // TODO should be changed for LBS_OWNERDRAWVARIABLE style listboxes
693 // NB: can't forward this to wxListBoxItem because LB_SETITEMDATA
694 // message is not yet sent when we get here!
695 bool wxListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT
*item
)
697 // only owner-drawn control should receive this message
698 wxCHECK( HasFlag(wxLB_OWNERDRAW
), false );
700 MEASUREITEMSTRUCT
*pStruct
= (MEASUREITEMSTRUCT
*)item
;
703 HDC hdc
= GetDC(NULL
);
705 HDC hdc
= CreateIC(wxT("DISPLAY"), NULL
, NULL
, 0);
709 wxDCTemp
dc((WXHDC
)hdc
);
710 dc
.SetFont(GetFont());
712 pStruct
->itemHeight
= dc
.GetCharHeight() + 2 * LISTBOX_EXTRA_SPACE
;
713 pStruct
->itemWidth
= dc
.GetCharWidth();
717 ReleaseDC(NULL
, hdc
);
725 // forward the message to the appropriate item
726 bool wxListBox::MSWOnDraw(WXDRAWITEMSTRUCT
*item
)
728 // only owner-drawn control should receive this message
729 wxCHECK( HasFlag(wxLB_OWNERDRAW
), false );
731 DRAWITEMSTRUCT
*pStruct
= (DRAWITEMSTRUCT
*)item
;
733 // the item may be -1 for an empty listbox
734 if ( pStruct
->itemID
== (UINT
)-1 )
737 wxListBoxItem
*pItem
= (wxListBoxItem
*)m_aItems
[pStruct
->itemID
];
739 wxDCTemp
dc((WXHDC
)pStruct
->hDC
);
741 return pItem
->OnDrawItem(dc
, wxRectFromRECT(pStruct
->rcItem
),
742 (wxOwnerDrawn::wxODAction
)pStruct
->itemAction
,
743 (wxOwnerDrawn::wxODStatus
)(pStruct
->itemState
| wxOwnerDrawn::wxODHidePrefix
));
746 #endif // wxUSE_OWNER_DRAWN
748 #endif // wxUSE_LISTBOX