size combobox/choices properly initially by considering the length of the strings...
[wxWidgets.git] / src / msw / choice.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: choice.cpp
3 // Purpose: wxChoice
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin to derive from wxChoiceBase
6 // Created: 04/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
21 #pragma implementation "choice.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_CHOICE
32
33 #ifndef WX_PRECOMP
34 #include "wx/choice.h"
35 #include "wx/utils.h"
36 #include "wx/log.h"
37 #include "wx/brush.h"
38 #include "wx/settings.h"
39 #endif
40
41 #include "wx/msw/private.h"
42
43 #if wxUSE_EXTENDED_RTTI
44 WX_DEFINE_FLAGS( wxChoiceStyle )
45
46 wxBEGIN_FLAGS( wxChoiceStyle )
47 // new style border flags, we put them first to
48 // use them for streaming out
49 wxFLAGS_MEMBER(wxBORDER_SIMPLE)
50 wxFLAGS_MEMBER(wxBORDER_SUNKEN)
51 wxFLAGS_MEMBER(wxBORDER_DOUBLE)
52 wxFLAGS_MEMBER(wxBORDER_RAISED)
53 wxFLAGS_MEMBER(wxBORDER_STATIC)
54 wxFLAGS_MEMBER(wxBORDER_NONE)
55
56 // old style border flags
57 wxFLAGS_MEMBER(wxSIMPLE_BORDER)
58 wxFLAGS_MEMBER(wxSUNKEN_BORDER)
59 wxFLAGS_MEMBER(wxDOUBLE_BORDER)
60 wxFLAGS_MEMBER(wxRAISED_BORDER)
61 wxFLAGS_MEMBER(wxSTATIC_BORDER)
62 wxFLAGS_MEMBER(wxBORDER)
63
64 // standard window styles
65 wxFLAGS_MEMBER(wxTAB_TRAVERSAL)
66 wxFLAGS_MEMBER(wxCLIP_CHILDREN)
67 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW)
68 wxFLAGS_MEMBER(wxWANTS_CHARS)
69 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE)
70 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB )
71 wxFLAGS_MEMBER(wxVSCROLL)
72 wxFLAGS_MEMBER(wxHSCROLL)
73
74 wxEND_FLAGS( wxChoiceStyle )
75
76 IMPLEMENT_DYNAMIC_CLASS_XTI(wxChoice, wxControl,"wx/choice.h")
77
78 wxBEGIN_PROPERTIES_TABLE(wxChoice)
79 wxEVENT_PROPERTY( Select , wxEVT_COMMAND_CHOICE_SELECTED , wxCommandEvent )
80
81 wxPROPERTY( Font , wxFont , SetFont , GetFont , , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
82 wxPROPERTY_COLLECTION( Choices , wxArrayString , wxString , AppendString , GetStrings , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
83 wxPROPERTY( Selection ,int, SetSelection, GetSelection, , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
84 wxPROPERTY_FLAGS( WindowStyle , wxChoiceStyle , long , SetWindowStyleFlag , GetWindowStyleFlag , , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
85 wxEND_PROPERTIES_TABLE()
86
87 wxBEGIN_HANDLERS_TABLE(wxChoice)
88 wxEND_HANDLERS_TABLE()
89
90 wxCONSTRUCTOR_4( wxChoice , wxWindow* , Parent , wxWindowID , Id , wxPoint , Position , wxSize , Size )
91 #else
92 IMPLEMENT_DYNAMIC_CLASS(wxChoice, wxControl)
93 #endif
94 /*
95 TODO PROPERTIES
96 selection (long)
97 content (list)
98 item
99 */
100
101 // ============================================================================
102 // implementation
103 // ============================================================================
104
105 // ----------------------------------------------------------------------------
106 // creation
107 // ----------------------------------------------------------------------------
108
109 bool wxChoice::Create(wxWindow *parent,
110 wxWindowID id,
111 const wxPoint& pos,
112 const wxSize& size,
113 int n, const wxString choices[],
114 long style,
115 const wxValidator& validator,
116 const wxString& name)
117 {
118 // Experience shows that wxChoice vs. wxComboBox distinction confuses
119 // quite a few people - try to help them
120 wxASSERT_MSG( !(style & wxCB_DROPDOWN) &&
121 !(style & wxCB_READONLY) &&
122 !(style & wxCB_SIMPLE),
123 _T("this style flag is ignored by wxChoice, you ")
124 _T("probably want to use a wxComboBox") );
125
126 return CreateAndInit(parent, id, pos, size, n, choices, style,
127 validator, name);
128 }
129
130 bool wxChoice::CreateAndInit(wxWindow *parent,
131 wxWindowID id,
132 const wxPoint& pos,
133 const wxSize& sizeOrig,
134 int n, const wxString choices[],
135 long style,
136 const wxValidator& validator,
137 const wxString& name)
138 {
139 // this is a bit hackish but we want to prevent MSWCreateControl() from
140 // calling SetBestSize() (which it would do if any of the size components
141 // is not given) because it wouldn't calculate it correctly if we have any
142 // strings as they're not yet added to the control when it is called
143 //
144 // so: if we have any strings, we fudge the size parameter so that
145 // SetBestSize() is not called by MSWCreateControl() but then we do call it
146 // manually below
147 bool autoSize = false;
148 wxSize size = sizeOrig;
149 if ( n )
150 {
151 if ( size.x < 0 )
152 {
153 size.x = 1;
154 autoSize = true;
155 }
156 if ( size.y < 0 )
157 {
158 size.y = 1;
159 autoSize = true;
160 }
161 }
162
163 // initialize wxControl
164 if ( !CreateControl(parent, id, pos, size, style, validator, name) )
165 return FALSE;
166
167 // now create the real HWND
168 if ( !MSWCreateControl(wxT("COMBOBOX"), _T(""), pos, size) )
169 return FALSE;
170
171
172 // choice/combobox normally has "white" (depends on colour scheme, of
173 // course) background rather than inheriting the parent's background
174 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
175
176 // initialize the controls contents
177 for ( int i = 0; i < n; i++ )
178 {
179 Append(choices[i]);
180 }
181
182 // and now we may finally size the control properly (if needed)
183 if ( autoSize )
184 {
185 SetBestSize(sizeOrig);
186 }
187
188 return TRUE;
189 }
190
191 bool wxChoice::Create(wxWindow *parent,
192 wxWindowID id,
193 const wxPoint& pos,
194 const wxSize& size,
195 const wxArrayString& choices,
196 long style,
197 const wxValidator& validator,
198 const wxString& name)
199 {
200 wxCArrayString chs(choices);
201 return Create(parent, id, pos, size, chs.GetCount(), chs.GetStrings(),
202 style, validator, name);
203 }
204
205 WXDWORD wxChoice::MSWGetStyle(long style, WXDWORD *exstyle) const
206 {
207 // we never have an external border
208 WXDWORD msStyle = wxControl::MSWGetStyle
209 (
210 (style & ~wxBORDER_MASK) | wxBORDER_NONE, exstyle
211 );
212
213 // WS_CLIPSIBLINGS is useful with wxChoice and doesn't seem to result in
214 // any problems
215 msStyle |= WS_CLIPSIBLINGS;
216
217 // wxChoice-specific styles
218 msStyle |= CBS_DROPDOWNLIST | WS_HSCROLL | WS_VSCROLL;
219 if ( style & wxCB_SORT )
220 msStyle |= CBS_SORT;
221
222 return msStyle;
223 }
224
225 wxChoice::~wxChoice()
226 {
227 Free();
228 }
229
230 // ----------------------------------------------------------------------------
231 // adding/deleting items to/from the list
232 // ----------------------------------------------------------------------------
233
234 int wxChoice::DoAppend(const wxString& item)
235 {
236 int n = (int)SendMessage(GetHwnd(), CB_ADDSTRING, 0, (LONG)item.c_str());
237 if ( n == CB_ERR )
238 {
239 wxLogLastError(wxT("SendMessage(CB_ADDSTRING)"));
240 }
241 else // ok
242 {
243 // we need to refresh our size in order to have enough space for the
244 // newly added items
245 UpdateVisibleHeight();
246 }
247
248 return n;
249 }
250
251 int wxChoice::DoInsert(const wxString& item, int pos)
252 {
253 wxCHECK_MSG(!(GetWindowStyle() & wxCB_SORT), -1, wxT("can't insert into sorted list"));
254 wxCHECK_MSG((pos>=0) && (pos<=GetCount()), -1, wxT("invalid index"));
255
256 int n = (int)SendMessage(GetHwnd(), CB_INSERTSTRING, pos, (LONG)item.c_str());
257 if ( n == CB_ERR )
258 {
259 wxLogLastError(wxT("SendMessage(CB_INSERTSTRING)"));
260 }
261 else // ok
262 {
263 UpdateVisibleHeight();
264 }
265
266 return n;
267 }
268
269 void wxChoice::Delete(int n)
270 {
271 wxCHECK_RET( n < GetCount(), wxT("invalid item index in wxChoice::Delete") );
272
273 if ( HasClientObjectData() )
274 {
275 delete GetClientObject(n);
276 }
277
278 SendMessage(GetHwnd(), CB_DELETESTRING, n, 0);
279
280 UpdateVisibleHeight();
281 }
282
283 void wxChoice::Clear()
284 {
285 Free();
286
287 SendMessage(GetHwnd(), CB_RESETCONTENT, 0, 0);
288
289 UpdateVisibleHeight();
290 }
291
292 void wxChoice::Free()
293 {
294 if ( HasClientObjectData() )
295 {
296 size_t count = GetCount();
297 for ( size_t n = 0; n < count; n++ )
298 {
299 delete GetClientObject(n);
300 }
301 }
302 }
303
304 // ----------------------------------------------------------------------------
305 // selection
306 // ----------------------------------------------------------------------------
307
308 int wxChoice::GetSelection() const
309 {
310 return (int)SendMessage(GetHwnd(), CB_GETCURSEL, 0, 0);
311 }
312
313 void wxChoice::SetSelection(int n)
314 {
315 SendMessage(GetHwnd(), CB_SETCURSEL, n, 0);
316 }
317
318 // ----------------------------------------------------------------------------
319 // string list functions
320 // ----------------------------------------------------------------------------
321
322 int wxChoice::GetCount() const
323 {
324 return (int)SendMessage(GetHwnd(), CB_GETCOUNT, 0, 0);
325 }
326
327 int wxChoice::FindString(const wxString& s) const
328 {
329 #if defined(__WATCOMC__) && defined(__WIN386__)
330 // For some reason, Watcom in WIN386 mode crashes in the CB_FINDSTRINGEXACT message.
331 // wxChoice::Do it the long way instead.
332 int count = GetCount();
333 for ( int i = 0; i < count; i++ )
334 {
335 // as CB_FINDSTRINGEXACT is case insensitive, be case insensitive too
336 if ( GetString(i).IsSameAs(s, FALSE) )
337 return i;
338 }
339
340 return wxNOT_FOUND;
341 #else // !Watcom
342 int pos = (int)SendMessage(GetHwnd(), CB_FINDSTRINGEXACT,
343 (WPARAM)-1, (LPARAM)s.c_str());
344
345 return pos == LB_ERR ? wxNOT_FOUND : pos;
346 #endif // Watcom/!Watcom
347 }
348
349 void wxChoice::SetString(int n, const wxString& s)
350 {
351 wxCHECK_RET( n >= 0 && n < GetCount(),
352 wxT("invalid item index in wxChoice::SetString") );
353
354 // we have to delete and add back the string as there is no way to change a
355 // string in place
356
357 // we need to preserve the client data
358 void *data;
359 if ( m_clientDataItemsType != wxClientData_None )
360 {
361 data = DoGetItemClientData(n);
362 }
363 else // no client data
364 {
365 data = NULL;
366 }
367
368 ::SendMessage(GetHwnd(), CB_DELETESTRING, n, 0);
369 ::SendMessage(GetHwnd(), CB_INSERTSTRING, n, (LPARAM)s.c_str() );
370
371 if ( data )
372 {
373 DoSetItemClientData(n, data);
374 }
375 //else: it's already NULL by default
376 }
377
378 wxString wxChoice::GetString(int n) const
379 {
380 int len = (int)::SendMessage(GetHwnd(), CB_GETLBTEXTLEN, n, 0);
381
382 wxString str;
383 if ( len != CB_ERR && len > 0 )
384 {
385 if ( ::SendMessage
386 (
387 GetHwnd(),
388 CB_GETLBTEXT,
389 n,
390 (LPARAM)(wxChar *)wxStringBuffer(str, len)
391 ) == CB_ERR )
392 {
393 wxLogLastError(wxT("SendMessage(CB_GETLBTEXT)"));
394 }
395 }
396
397 return str;
398 }
399
400 // ----------------------------------------------------------------------------
401 // client data
402 // ----------------------------------------------------------------------------
403
404 void wxChoice::DoSetItemClientData( int n, void* clientData )
405 {
406 if ( ::SendMessage(GetHwnd(), CB_SETITEMDATA,
407 n, (LPARAM)clientData) == CB_ERR )
408 {
409 wxLogLastError(wxT("CB_SETITEMDATA"));
410 }
411 }
412
413 void* wxChoice::DoGetItemClientData( int n ) const
414 {
415 LPARAM rc = SendMessage(GetHwnd(), CB_GETITEMDATA, n, 0);
416 if ( rc == CB_ERR )
417 {
418 wxLogLastError(wxT("CB_GETITEMDATA"));
419
420 // unfortunately, there is no way to return an error code to the user
421 rc = (LPARAM) NULL;
422 }
423
424 return (void *)rc;
425 }
426
427 void wxChoice::DoSetItemClientObject( int n, wxClientData* clientData )
428 {
429 DoSetItemClientData(n, clientData);
430 }
431
432 wxClientData* wxChoice::DoGetItemClientObject( int n ) const
433 {
434 return (wxClientData *)DoGetItemClientData(n);
435 }
436
437 // ----------------------------------------------------------------------------
438 // wxMSW specific helpers
439 // ----------------------------------------------------------------------------
440
441 int wxChoice::GetVisibleHeight() const
442 {
443 return ::SendMessage(GetHwnd(), CB_GETITEMHEIGHT, (WPARAM)-1, 0);
444 }
445
446 void wxChoice::UpdateVisibleHeight()
447 {
448 // be careful to not change the width here
449 DoSetSize(-1, -1, -1, GetVisibleHeight(), wxSIZE_USE_EXISTING);
450 }
451
452 void wxChoice::DoMoveWindow(int x, int y, int width, int height)
453 {
454 // here is why this is necessary: if the width is negative, the combobox
455 // window proc makes the window of the size width*height instead of
456 // interpreting height in the usual manner (meaning the height of the drop
457 // down list - usually the height specified in the call to MoveWindow()
458 // will not change the height of combo box per se)
459 //
460 // this behaviour is not documented anywhere, but this is just how it is
461 // here (NT 4.4) and, anyhow, the check shouldn't hurt - however without
462 // the check, constraints/sizers using combos may break the height
463 // constraint will have not at all the same value as expected
464 if ( width < 0 )
465 return;
466
467 wxControl::DoMoveWindow(x, y, width, height);
468 }
469
470 void wxChoice::DoGetSize(int *w, int *h) const
471 {
472 wxControl::DoGetSize(w, h);
473
474 // we need to return only the height of the visible part, not the entire
475 // height in the Windows sense which includes the height of the drop down
476 // list as well
477 if ( h )
478 *h = GetVisibleHeight();
479 }
480
481 void wxChoice::DoSetSize(int x, int y,
482 int width, int height,
483 int sizeFlags)
484 {
485 int heightOrig = height;
486
487 // the height which we must pass to Windows should be the total height of
488 // the control including the drop down list while the height given to us
489 // is, of course, just the height of the permanently visible part of it
490 if ( height != -1 )
491 {
492 // don't make the drop down list too tall, arbitrarily limit it to 40
493 // items max and also don't leave it empty
494 size_t nItems = GetCount();
495 if ( !nItems )
496 nItems = 9;
497 else if ( nItems > 39 )
498 nItems = 39;
499
500 // add space for the drop down list
501 const int hItem = SendMessage(GetHwnd(), CB_GETITEMHEIGHT, 0, 0);
502 height += hItem*(nItems + 1);
503 }
504
505 wxControl::DoSetSize(x, y, width, height, sizeFlags);
506
507 // if the height specified for the visible part of the control is
508 // different from the current one, we need to change it separately
509 // as it is not affected by normal WM_SETSIZE
510 if ( height != -1 )
511 {
512 const int hVisibleCurrent = GetVisibleHeight();
513 if ( hVisibleCurrent != heightOrig )
514 {
515 SendMessage(GetHwnd(), CB_SETITEMHEIGHT, (WPARAM)-1, heightOrig);
516 }
517 }
518 }
519
520 wxSize wxChoice::DoGetBestSize() const
521 {
522 // find the widest string
523 int wChoice = 0;
524 const size_t nItems = GetCount();
525 for ( size_t i = 0; i < nItems; i++ )
526 {
527 int wLine;
528 GetTextExtent(GetString(i), &wLine, NULL);
529 if ( wLine > wChoice )
530 wChoice = wLine;
531 }
532
533 // give it some reasonable default value if there are no strings in the
534 // list
535 if ( wChoice == 0 )
536 wChoice = 100;
537
538 // the combobox should be slightly larger than the widest string
539 wChoice += 5*GetCharWidth();
540
541 return wxSize(wChoice, GetVisibleHeight());
542 }
543
544 long wxChoice::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
545 {
546 if ( nMsg == WM_LBUTTONUP )
547 {
548 int x = (int)LOWORD(lParam);
549 int y = (int)HIWORD(lParam);
550
551 // Ok, this is truly weird, but if a panel with a wxChoice loses the
552 // focus, then you get a *fake* WM_LBUTTONUP message with x = 65535 and
553 // y = 65535. Filter out this nonsense.
554 //
555 // VZ: I'd like to know how to reproduce this please...
556 if ( x == 65535 && y == 65535 )
557 return 0;
558 }
559
560 return wxWindow::MSWWindowProc(nMsg, wParam, lParam);
561 }
562
563 bool wxChoice::MSWCommand(WXUINT param, WXWORD WXUNUSED(id))
564 {
565 if ( param != CBN_SELCHANGE)
566 {
567 // "selection changed" is the only event we're after
568 return FALSE;
569 }
570
571 int n = GetSelection();
572 if (n > -1)
573 {
574 wxCommandEvent event(wxEVT_COMMAND_CHOICE_SELECTED, m_windowId);
575 event.SetInt(n);
576 event.SetEventObject(this);
577 event.SetString(GetStringSelection());
578 if ( HasClientObjectData() )
579 event.SetClientObject( GetClientObject(n) );
580 else if ( HasClientUntypedData() )
581 event.SetClientData( GetClientData(n) );
582 ProcessCommand(event);
583 }
584
585 return TRUE;
586 }
587
588 WXHBRUSH wxChoice::OnCtlColor(WXHDC pDC, WXHWND WXUNUSED(pWnd), WXUINT WXUNUSED(nCtlColor),
589 WXUINT WXUNUSED(message),
590 WXWPARAM WXUNUSED(wParam),
591 WXLPARAM WXUNUSED(lParam)
592 )
593 {
594 HDC hdc = (HDC)pDC;
595 wxColour colBack = GetBackgroundColour();
596
597 if (!IsEnabled())
598 colBack = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE);
599
600 ::SetBkColor(hdc, wxColourToRGB(colBack));
601 ::SetTextColor(hdc, wxColourToRGB(GetForegroundColour()));
602
603 wxBrush *brush = wxTheBrushList->FindOrCreateBrush(colBack, wxSOLID);
604
605 return (WXHBRUSH)brush->GetResourceHandle();
606 }
607
608 #endif // wxUSE_CHOICE