don't assert when creating an initially empty wxCB_READONLY combobox
[wxWidgets.git] / src / msw / combobox.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: msw/combobox.cpp
3 // Purpose: wxComboBox class
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 01/02/97
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 "combobox.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_COMBOBOX
32
33 #ifndef WX_PRECOMP
34 #include "wx/settings.h"
35 #include "wx/log.h"
36 // for wxEVT_COMMAND_TEXT_ENTER
37 #include "wx/textctrl.h"
38 #endif
39
40 #include "wx/combobox.h"
41 #include "wx/brush.h"
42 #include "wx/clipbrd.h"
43 #include "wx/msw/private.h"
44
45 #if wxUSE_TOOLTIPS
46 #if !defined(__GNUWIN32_OLD__) || defined(__CYGWIN10__)
47 #include <commctrl.h>
48 #endif
49 #include "wx/tooltip.h"
50 #endif // wxUSE_TOOLTIPS
51
52 // ----------------------------------------------------------------------------
53 // wxWin macros
54 // ----------------------------------------------------------------------------
55
56 #if wxUSE_EXTENDED_RTTI
57 WX_DEFINE_FLAGS( wxComboBoxStyle )
58
59 wxBEGIN_FLAGS( wxComboBoxStyle )
60 // new style border flags, we put them first to
61 // use them for streaming out
62 wxFLAGS_MEMBER(wxBORDER_SIMPLE)
63 wxFLAGS_MEMBER(wxBORDER_SUNKEN)
64 wxFLAGS_MEMBER(wxBORDER_DOUBLE)
65 wxFLAGS_MEMBER(wxBORDER_RAISED)
66 wxFLAGS_MEMBER(wxBORDER_STATIC)
67 wxFLAGS_MEMBER(wxBORDER_NONE)
68
69 // old style border flags
70 wxFLAGS_MEMBER(wxSIMPLE_BORDER)
71 wxFLAGS_MEMBER(wxSUNKEN_BORDER)
72 wxFLAGS_MEMBER(wxDOUBLE_BORDER)
73 wxFLAGS_MEMBER(wxRAISED_BORDER)
74 wxFLAGS_MEMBER(wxSTATIC_BORDER)
75 wxFLAGS_MEMBER(wxBORDER)
76
77 // standard window styles
78 wxFLAGS_MEMBER(wxTAB_TRAVERSAL)
79 wxFLAGS_MEMBER(wxCLIP_CHILDREN)
80 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW)
81 wxFLAGS_MEMBER(wxWANTS_CHARS)
82 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE)
83 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB )
84 wxFLAGS_MEMBER(wxVSCROLL)
85 wxFLAGS_MEMBER(wxHSCROLL)
86
87 wxFLAGS_MEMBER(wxCB_SIMPLE)
88 wxFLAGS_MEMBER(wxCB_SORT)
89 wxFLAGS_MEMBER(wxCB_READONLY)
90 wxFLAGS_MEMBER(wxCB_DROPDOWN)
91
92 wxEND_FLAGS( wxComboBoxStyle )
93
94 IMPLEMENT_DYNAMIC_CLASS_XTI(wxComboBox, wxControl,"wx/combobox.h")
95
96 wxBEGIN_PROPERTIES_TABLE(wxComboBox)
97 wxEVENT_PROPERTY( Select , wxEVT_COMMAND_COMBOBOX_SELECTED , wxCommandEvent )
98 wxEVENT_PROPERTY( TextEnter , wxEVT_COMMAND_TEXT_ENTER , wxCommandEvent )
99
100 // TODO DELEGATES
101 wxPROPERTY( Font , wxFont , SetFont , GetFont , , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
102 wxPROPERTY_COLLECTION( Choices , wxArrayString , wxString , AppendString , GetStrings , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
103 wxPROPERTY( Value ,wxString, SetValue, GetValue, , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
104 wxPROPERTY( Selection ,int, SetSelection, GetSelection, , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
105 wxPROPERTY_FLAGS( WindowStyle , wxComboBoxStyle , long , SetWindowStyleFlag , GetWindowStyleFlag , , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
106 wxEND_PROPERTIES_TABLE()
107
108 wxBEGIN_HANDLERS_TABLE(wxComboBox)
109 wxEND_HANDLERS_TABLE()
110
111 wxCONSTRUCTOR_5( wxComboBox , wxWindow* , Parent , wxWindowID , Id , wxString , Value , wxPoint , Position , wxSize , Size )
112 #else
113 IMPLEMENT_DYNAMIC_CLASS(wxComboBox, wxControl)
114 #endif
115
116 // ----------------------------------------------------------------------------
117 // function prototypes
118 // ----------------------------------------------------------------------------
119
120 LRESULT APIENTRY _EXPORT wxComboEditWndProc(HWND hWnd,
121 UINT message,
122 WPARAM wParam,
123 LPARAM lParam);
124
125 // ---------------------------------------------------------------------------
126 // global vars
127 // ---------------------------------------------------------------------------
128
129 // the pointer to standard radio button wnd proc
130 static WXFARPROC gs_wndprocEdit = (WXFARPROC)NULL;
131
132 // ============================================================================
133 // implementation
134 // ============================================================================
135
136 // ----------------------------------------------------------------------------
137 // wnd proc for subclassed edit control
138 // ----------------------------------------------------------------------------
139
140 LRESULT APIENTRY _EXPORT wxComboEditWndProc(HWND hWnd,
141 UINT message,
142 WPARAM wParam,
143 LPARAM lParam)
144 {
145 HWND hwndCombo = ::GetParent(hWnd);
146 wxWindow *win = wxFindWinFromHandle((WXHWND)hwndCombo);
147
148 switch ( message )
149 {
150 // forward some messages to the combobox to generate the appropriate
151 // wxEvents from them
152 case WM_KEYUP:
153 case WM_KEYDOWN:
154 case WM_CHAR:
155 case WM_SETFOCUS:
156 case WM_KILLFOCUS:
157 {
158 wxComboBox *combo = wxDynamicCast(win, wxComboBox);
159 if ( !combo )
160 {
161 // we can get WM_KILLFOCUS while our parent is already half
162 // destroyed and hence doesn't look like a combobx any
163 // longer, check for it to avoid bogus assert failures
164 if ( !win->IsBeingDeleted() )
165 {
166 wxFAIL_MSG( _T("should have combo as parent") );
167 }
168 }
169 else if ( combo->MSWProcessEditMsg(message, wParam, lParam) )
170 {
171 // handled by parent
172 return 0;
173 }
174 }
175 break;
176
177 case WM_GETDLGCODE:
178 {
179 wxCHECK_MSG( win, 0, _T("should have a parent") );
180
181 if ( win->GetWindowStyle() & wxPROCESS_ENTER )
182 {
183 // need to return a custom dlg code or we'll never get it
184 return DLGC_WANTMESSAGE;
185 }
186 }
187 break;
188
189 // deal with tooltips here
190 #if wxUSE_TOOLTIPS && defined(TTN_NEEDTEXT)
191 case WM_NOTIFY:
192 {
193 wxCHECK_MSG( win, 0, _T("should have a parent") );
194
195 NMHDR* hdr = (NMHDR *)lParam;
196 if ( hdr->code == TTN_NEEDTEXT )
197 {
198 wxToolTip *tooltip = win->GetToolTip();
199 if ( tooltip )
200 {
201 TOOLTIPTEXT *ttt = (TOOLTIPTEXT *)lParam;
202 ttt->lpszText = (wxChar *)tooltip->GetTip().c_str();
203 }
204
205 // processed
206 return 0;
207 }
208 }
209 break;
210 #endif // wxUSE_TOOLTIPS
211 }
212
213 return ::CallWindowProc(CASTWNDPROC gs_wndprocEdit, hWnd, message, wParam, lParam);
214 }
215
216 WXHBRUSH wxComboBox::OnCtlColor(WXHDC pDC,
217 WXHWND WXUNUSED(pWnd),
218 WXUINT WXUNUSED(nCtlColor),
219 WXUINT WXUNUSED(message),
220 WXWPARAM WXUNUSED(wParam),
221 WXLPARAM WXUNUSED(lParam))
222 {
223 HDC hdc = (HDC)pDC;
224 wxColour colBack = GetBackgroundColour();
225
226 if (!IsEnabled())
227 colBack = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE);
228
229 ::SetBkColor(hdc, wxColourToRGB(colBack));
230 ::SetTextColor(hdc, wxColourToRGB(GetForegroundColour()));
231
232 wxBrush *brush = wxTheBrushList->FindOrCreateBrush(colBack, wxSOLID);
233
234 return (WXHBRUSH)brush->GetResourceHandle();
235 }
236
237 // ----------------------------------------------------------------------------
238 // wxComboBox callbacks
239 // ----------------------------------------------------------------------------
240
241 long wxComboBox::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
242 {
243 // handle WM_CTLCOLOR messages from our EDIT control to be able to set its
244 // colour correctly (to be the same as our own one)
245 switch ( nMsg )
246 {
247 // we have to handle both: one for the normal case and the other for
248 // wxCB_READONLY
249 case WM_CTLCOLOREDIT:
250 case WM_CTLCOLORSTATIC:
251 WXWORD nCtlColor;
252 WXHDC hdc;
253 WXHWND hwnd;
254 UnpackCtlColor(wParam, lParam, &nCtlColor, &hdc, &hwnd);
255
256 return OnCtlColor(hdc, hwnd, nCtlColor, nMsg, wParam, lParam);
257 }
258
259 return wxChoice::MSWWindowProc(nMsg, wParam, lParam);
260 }
261
262 bool wxComboBox::MSWProcessEditMsg(WXUINT msg, WXWPARAM wParam, WXLPARAM lParam)
263 {
264 switch ( msg )
265 {
266 case WM_CHAR:
267 // for compatibility with wxTextCtrl, generate a special message
268 // when Enter is pressed
269 if ( wParam == VK_RETURN )
270 {
271 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_windowId);
272 InitCommandEvent(event);
273 event.SetString(GetValue());
274 event.SetInt(GetSelection());
275 ProcessCommand(event);
276 }
277
278 return HandleChar(wParam, lParam, TRUE /* isASCII */);
279
280 case WM_KEYDOWN:
281 return HandleKeyDown(wParam, lParam);
282
283 case WM_KEYUP:
284 return HandleKeyUp(wParam, lParam);
285
286 case WM_SETFOCUS:
287 return HandleSetFocus((WXHWND)wParam);
288
289 case WM_KILLFOCUS:
290 return HandleKillFocus((WXHWND)wParam);
291 }
292
293 return FALSE;
294 }
295
296 bool wxComboBox::MSWCommand(WXUINT param, WXWORD WXUNUSED(id))
297 {
298 wxString value;
299 int sel = -1;
300 switch ( param )
301 {
302 case CBN_SELCHANGE:
303 sel = GetSelection();
304 if ( sel > -1 )
305 {
306 value = GetString(sel);
307
308 wxCommandEvent event(wxEVT_COMMAND_COMBOBOX_SELECTED, GetId());
309 event.SetInt(sel);
310 event.SetEventObject(this);
311 event.SetString(value);
312 ProcessCommand(event);
313 }
314 else
315 {
316 break;
317 }
318
319 // fall through: for compability with wxGTK, also send the text
320 // update event when the selection changes (this also seems more
321 // logical as the text does change)
322
323 case CBN_EDITCHANGE:
324 {
325 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, GetId());
326
327 // if sel != -1, value was initialized above (and we can't use
328 // GetValue() here as it would return the old selection and we
329 // want the new one)
330 if ( sel == -1 )
331 {
332 value = GetValue();
333 }
334 else // we're synthesizing text updated event from sel change
335 {
336 // We need to retrieve the current selection because the user
337 // may have changed it in the previous handler (for CBN_SELCHANGE
338 // above).
339 sel = GetSelection();
340 if ( sel > -1 )
341 {
342 value = GetString(sel);
343 }
344 // we need to do this because the user code expects
345 // wxComboBox::GetValue() to return the new value from
346 // "text updated" handler but it hadn't been updated yet
347 SetValue(value);
348 }
349
350 event.SetString(value);
351 event.SetEventObject(this);
352 ProcessCommand(event);
353 }
354 break;
355 }
356
357 // there is no return value for the CBN_ notifications, so always return
358 // FALSE from here to pass the message to DefWindowProc()
359 return FALSE;
360 }
361
362 WXHWND wxComboBox::GetEditHWND() const
363 {
364 // this function should not be called for wxCB_READONLY controls, it is
365 // the callers responsability to check this
366 wxASSERT_MSG( !(GetWindowStyle() & wxCB_READONLY),
367 _T("read-only combobox doesn't have any edit control") );
368
369 POINT pt;
370 pt.x = pt.y = 4;
371 HWND hwndEdit = ::ChildWindowFromPoint(GetHwnd(), pt);
372 if ( !hwndEdit || hwndEdit == GetHwnd() )
373 {
374 wxFAIL_MSG(_T("not read only combobox without edit control?"));
375 }
376
377 return (WXHWND)hwndEdit;
378 }
379
380 // ----------------------------------------------------------------------------
381 // wxComboBox creation
382 // ----------------------------------------------------------------------------
383
384 bool wxComboBox::Create(wxWindow *parent, wxWindowID id,
385 const wxString& value,
386 const wxPoint& pos,
387 const wxSize& size,
388 int n, const wxString choices[],
389 long style,
390 const wxValidator& validator,
391 const wxString& name)
392 {
393 // pretend that wxComboBox is hidden while it is positioned and resized and
394 // show it only right before leaving this method because otherwise there is
395 // some noticeable flicker while the control rearranges itself
396 m_isShown = FALSE;
397
398 if ( !CreateAndInit(parent, id, pos, size, n, choices, style,
399 validator, name) )
400 return FALSE;
401
402 // we shouldn't call SetValue() for an empty read only combobox as it would
403 // (correctly) thro an assert and is otherwise useless anyhow
404 if ( n || !HasFlag(wxCB_READONLY) )
405 SetValue(value);
406
407 // a (not read only) combobox is, in fact, 2 controls: the combobox itself
408 // and an edit control inside it and if we want to catch events from this
409 // edit control, we must subclass it as well
410 if ( !(style & wxCB_READONLY) )
411 {
412 gs_wndprocEdit = (WXFARPROC)::SetWindowLong
413 (
414 (HWND)GetEditHWND(),
415 GWL_WNDPROC,
416 (LPARAM)wxComboEditWndProc
417 );
418 }
419
420 // and finally, show the control
421 Show(TRUE);
422
423 return TRUE;
424 }
425
426 bool wxComboBox::Create(wxWindow *parent, wxWindowID id,
427 const wxString& value,
428 const wxPoint& pos,
429 const wxSize& size,
430 const wxArrayString& choices,
431 long style,
432 const wxValidator& validator,
433 const wxString& name)
434 {
435 wxCArrayString chs(choices);
436 return Create(parent, id, value, pos, size, chs.GetCount(),
437 chs.GetStrings(), style, validator, name);
438 }
439
440 WXDWORD wxComboBox::MSWGetStyle(long style, WXDWORD *exstyle) const
441 {
442 // we never have an external border
443 WXDWORD msStyle = wxChoice::MSWGetStyle
444 (
445 (style & ~wxBORDER_MASK) | wxBORDER_NONE, exstyle
446 );
447
448 // remove the style always added by wxChoice
449 msStyle &= ~CBS_DROPDOWNLIST;
450
451 if ( style & wxCB_READONLY )
452 msStyle |= CBS_DROPDOWNLIST;
453 #ifndef __WXWINCE__
454 else if ( style & wxCB_SIMPLE )
455 msStyle |= CBS_SIMPLE; // A list (shown always) and edit control
456 #endif
457 else
458 msStyle |= CBS_DROPDOWN;
459
460 // there is no reason to not always use CBS_AUTOHSCROLL, so do use it
461 msStyle |= CBS_AUTOHSCROLL;
462
463 // NB: we used to also add CBS_NOINTEGRALHEIGHT here but why?
464
465 return msStyle;
466 }
467
468 // ----------------------------------------------------------------------------
469 // wxComboBox text control-like methods
470 // ----------------------------------------------------------------------------
471
472 void wxComboBox::SetValue(const wxString& value)
473 {
474 if ( HasFlag(wxCB_READONLY) )
475 SetStringSelection(value);
476 else
477 SetWindowText(GetHwnd(), value.c_str());
478 }
479
480 // Clipboard operations
481 void wxComboBox::Copy()
482 {
483 SendMessage(GetHwnd(), WM_COPY, 0, 0L);
484 }
485
486 void wxComboBox::Cut()
487 {
488 SendMessage(GetHwnd(), WM_CUT, 0, 0L);
489 }
490
491 void wxComboBox::Paste()
492 {
493 SendMessage(GetHwnd(), WM_PASTE, 0, 0L);
494 }
495
496 void wxComboBox::SetEditable(bool WXUNUSED(editable))
497 {
498 // Can't implement in MSW?
499 // HWND hWnd = GetHwnd();
500 // SendMessage(hWnd, EM_SETREADONLY, (WPARAM)!editable, (LPARAM)0L);
501 }
502
503 void wxComboBox::SetInsertionPoint(long pos)
504 {
505 if ( GetWindowStyle() & wxCB_READONLY )
506 return;
507
508 #ifdef __WIN32__
509 HWND hWnd = GetHwnd();
510 ::SendMessage(hWnd, CB_SETEDITSEL, 0, MAKELPARAM(pos, pos));
511 HWND hEditWnd = (HWND) GetEditHWND() ;
512 if ( hEditWnd )
513 {
514 // Scroll insertion point into view
515 SendMessage(hEditWnd, EM_SCROLLCARET, (WPARAM)0, (LPARAM)0);
516 // Why is this necessary? (Copied from wxTextCtrl::SetInsertionPoint)
517 SendMessage(hEditWnd, EM_REPLACESEL, 0, (LPARAM) wxEmptyString);
518 }
519 #endif // __WIN32__
520 }
521
522 void wxComboBox::SetInsertionPointEnd()
523 {
524 // setting insertion point doesn't make sense for read only comboboxes
525 if ( !(GetWindowStyle() & wxCB_READONLY) )
526 {
527 long pos = GetLastPosition();
528 SetInsertionPoint(pos);
529 }
530 }
531
532 long wxComboBox::GetInsertionPoint() const
533 {
534 #ifdef __WIN32__
535 DWORD Pos=(DWORD)SendMessage(GetHwnd(), CB_GETEDITSEL, 0, 0L);
536 return Pos&0xFFFF;
537 #else
538 return 0;
539 #endif
540 }
541
542 long wxComboBox::GetLastPosition() const
543 {
544 HWND hEditWnd = (HWND) GetEditHWND();
545
546 // Get number of characters in the last (only) line. We'll add this to the character
547 // index for the last line, 1st position.
548 int lineLength = (int)SendMessage(hEditWnd, EM_LINELENGTH, (WPARAM) 0, (LPARAM)0L);
549
550 return (long)(lineLength);
551 }
552
553 void wxComboBox::Replace(long from, long to, const wxString& value)
554 {
555 #if wxUSE_CLIPBOARD
556 Remove(from, to);
557
558 // Now replace with 'value', by pasting.
559 wxSetClipboardData(wxDF_TEXT, (wxObject *)(const wxChar *)value, 0, 0);
560
561 // Paste into edit control
562 SendMessage(GetHwnd(), WM_PASTE, (WPARAM)0, (LPARAM)0L);
563 #endif
564 }
565
566 void wxComboBox::Remove(long from, long to)
567 {
568 // Set selection and remove it
569 SetSelection(from, to);
570 SendMessage(GetHwnd(), WM_CUT, (WPARAM)0, (LPARAM)0);
571 }
572
573 void wxComboBox::SetSelection(long from, long to)
574 {
575 HWND hWnd = GetHwnd();
576 long fromChar = from;
577 long toChar = to;
578 // if from and to are both -1, it means
579 // (in wxWindows) that all text should be selected.
580 // This translates into Windows convention
581 if ((from == -1) && (to == -1))
582 {
583 fromChar = 0;
584 toChar = -1;
585 }
586
587 if (
588 #ifdef __WIN32__
589 SendMessage(hWnd, CB_SETEDITSEL, (WPARAM)0, (LPARAM)MAKELONG(fromChar, toChar))
590 #else // Win16
591 SendMessage(hWnd, CB_SETEDITSEL, (WPARAM)fromChar, (LPARAM)toChar)
592 #endif
593 == CB_ERR )
594 {
595 wxLogDebug(_T("CB_SETEDITSEL failed"));
596 }
597 }
598
599 #endif // wxUSE_COMBOBOX
600