Implement DoGetSizeFromTextSize() for wxMSW wx{Choice,Combobox,TextCtrl}.
[wxWidgets.git] / src / msw / combobox.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/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 // 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_COMBOBOX
28
29 #include "wx/combobox.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
33 #include "wx/settings.h"
34 #include "wx/log.h"
35 // for wxEVT_COMMAND_TEXT_ENTER
36 #include "wx/textctrl.h"
37 #include "wx/app.h"
38 #include "wx/brush.h"
39 #endif
40
41 #include "wx/clipbrd.h"
42 #include "wx/wupdlock.h"
43 #include "wx/msw/private.h"
44
45 #if wxUSE_UXTHEME
46 #include "wx/msw/uxtheme.h"
47 #endif
48
49 #if wxUSE_TOOLTIPS
50 #include "wx/tooltip.h"
51 #endif // wxUSE_TOOLTIPS
52
53 // ----------------------------------------------------------------------------
54 // wxWin macros
55 // ----------------------------------------------------------------------------
56
57 BEGIN_EVENT_TABLE(wxComboBox, wxControl)
58 EVT_MENU(wxID_CUT, wxComboBox::OnCut)
59 EVT_MENU(wxID_COPY, wxComboBox::OnCopy)
60 EVT_MENU(wxID_PASTE, wxComboBox::OnPaste)
61 EVT_MENU(wxID_UNDO, wxComboBox::OnUndo)
62 EVT_MENU(wxID_REDO, wxComboBox::OnRedo)
63 EVT_MENU(wxID_CLEAR, wxComboBox::OnDelete)
64 EVT_MENU(wxID_SELECTALL, wxComboBox::OnSelectAll)
65
66 EVT_UPDATE_UI(wxID_CUT, wxComboBox::OnUpdateCut)
67 EVT_UPDATE_UI(wxID_COPY, wxComboBox::OnUpdateCopy)
68 EVT_UPDATE_UI(wxID_PASTE, wxComboBox::OnUpdatePaste)
69 EVT_UPDATE_UI(wxID_UNDO, wxComboBox::OnUpdateUndo)
70 EVT_UPDATE_UI(wxID_REDO, wxComboBox::OnUpdateRedo)
71 EVT_UPDATE_UI(wxID_CLEAR, wxComboBox::OnUpdateDelete)
72 EVT_UPDATE_UI(wxID_SELECTALL, wxComboBox::OnUpdateSelectAll)
73 END_EVENT_TABLE()
74
75 // ----------------------------------------------------------------------------
76 // function prototypes
77 // ----------------------------------------------------------------------------
78
79 LRESULT APIENTRY _EXPORT wxComboEditWndProc(HWND hWnd,
80 UINT message,
81 WPARAM wParam,
82 LPARAM lParam);
83
84 // ---------------------------------------------------------------------------
85 // global vars
86 // ---------------------------------------------------------------------------
87
88 // the pointer to standard radio button wnd proc
89 static WNDPROC gs_wndprocEdit = (WNDPROC)NULL;
90
91 // ============================================================================
92 // implementation
93 // ============================================================================
94
95 namespace
96 {
97
98 // Check if the given message should be forwarded from the edit control which
99 // is part of the combobox to wxComboBox itself. All messages generating the
100 // events that the code using wxComboBox could be interested in must be
101 // forwarded.
102 bool ShouldForwardFromEditToCombo(UINT message)
103 {
104 switch ( message )
105 {
106 case WM_KEYUP:
107 case WM_KEYDOWN:
108 case WM_CHAR:
109 case WM_SYSCHAR:
110 case WM_SYSKEYDOWN:
111 case WM_SYSKEYUP:
112 case WM_SETFOCUS:
113 case WM_KILLFOCUS:
114 case WM_CUT:
115 case WM_COPY:
116 case WM_PASTE:
117 return true;
118 }
119
120 return false;
121 }
122
123 } // anonymous namespace
124
125 // ----------------------------------------------------------------------------
126 // wnd proc for subclassed edit control
127 // ----------------------------------------------------------------------------
128
129 LRESULT APIENTRY _EXPORT wxComboEditWndProc(HWND hWnd,
130 UINT message,
131 WPARAM wParam,
132 LPARAM lParam)
133 {
134 HWND hwndCombo = ::GetParent(hWnd);
135 wxWindow *win = wxFindWinFromHandle((WXHWND)hwndCombo);
136
137 if ( ShouldForwardFromEditToCombo(message) )
138 {
139 wxComboBox *combo = wxDynamicCast(win, wxComboBox);
140 if ( !combo )
141 {
142 // we can get WM_KILLFOCUS while our parent is already half
143 // destroyed and hence doesn't look like a combobx any
144 // longer, check for it to avoid bogus assert failures
145 if ( !win->IsBeingDeleted() )
146 {
147 wxFAIL_MSG( wxT("should have combo as parent") );
148 }
149 }
150 else if ( combo->MSWProcessEditMsg(message, wParam, lParam) )
151 {
152 // handled by parent
153 return 0;
154 }
155 }
156 else if ( message == WM_GETDLGCODE )
157 {
158 wxCHECK_MSG( win, 0, wxT("should have a parent") );
159
160 if ( win->GetWindowStyle() & wxTE_PROCESS_ENTER )
161 {
162 // need to return a custom dlg code or we'll never get it
163 return DLGC_WANTMESSAGE;
164 }
165 }
166
167 return ::CallWindowProc(CASTWNDPROC gs_wndprocEdit, hWnd, message, wParam, lParam);
168 }
169
170 // ----------------------------------------------------------------------------
171 // wxComboBox callbacks
172 // ----------------------------------------------------------------------------
173
174 WXLRESULT wxComboBox::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
175 {
176 // TODO: handle WM_CTLCOLOR messages from our EDIT control to be able to
177 // set its colour correctly (to be the same as our own one)
178
179 switch ( nMsg )
180 {
181 case WM_SIZE:
182 // wxStaticBox can generate this message, when modifying the control's style.
183 // This causes the content of the combobox to be selected, for some reason.
184 case WM_STYLECHANGED:
185 {
186 // combobox selection sometimes spontaneously changes when its
187 // size changes, restore it to the old value if necessary
188 if ( !GetEditHWNDIfAvailable() )
189 break;
190
191 long fromOld, toOld;
192 GetSelection(&fromOld, &toOld);
193
194 // if an editable combobox has a not empty text not from the
195 // list, it tries to autocomplete it from the list when it is
196 // resized, but we don't want this to happen as it doesn't seem
197 // to make any sense, so we forcefully restore the old text
198 wxString textOld;
199 if ( !HasFlag(wxCB_READONLY) && GetCurrentSelection() == -1 )
200 textOld = GetValue();
201
202 // eliminate flickering during following hacks
203 wxWindowUpdateLocker lock(this);
204
205 WXLRESULT result = wxChoice::MSWWindowProc(nMsg, wParam, lParam);
206
207 if ( !textOld.empty() && GetValue() != textOld )
208 SetLabel(textOld);
209
210 long fromNew, toNew;
211 GetSelection(&fromNew, &toNew);
212
213 if ( fromOld != fromNew || toOld != toNew )
214 {
215 SetSelection(fromOld, toOld);
216 }
217
218 return result;
219 }
220 }
221
222 return wxChoice::MSWWindowProc(nMsg, wParam, lParam);
223 }
224
225 bool wxComboBox::MSWProcessEditMsg(WXUINT msg, WXWPARAM wParam, WXLPARAM lParam)
226 {
227 switch ( msg )
228 {
229 case WM_CHAR:
230 // for compatibility with wxTextCtrl, generate a special message
231 // when Enter is pressed
232 if ( wParam == VK_RETURN )
233 {
234 if (SendMessage(GetHwnd(), CB_GETDROPPEDSTATE, 0, 0))
235 return false;
236
237 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_windowId);
238
239 const int sel = GetSelection();
240 event.SetInt(sel);
241 event.SetString(GetValue());
242 InitCommandEventWithItems(event, sel);
243
244 if ( ProcessCommand(event) )
245 {
246 // don't let the event through to the native control
247 // because it doesn't need it and may generate an annoying
248 // beep if it gets it
249 return true;
250 }
251 }
252 // fall through, WM_CHAR is one of the message we should forward.
253
254 default:
255 if ( ShouldForwardFromEditToCombo(msg) )
256 {
257 // For all the messages forward from the edit control the
258 // result is not used.
259 WXLRESULT result;
260 return MSWHandleMessage(&result, msg, wParam, lParam);
261 }
262 }
263
264 return false;
265 }
266
267 bool wxComboBox::MSWCommand(WXUINT param, WXWORD id)
268 {
269 int sel = -1;
270 wxString value;
271
272 switch ( param )
273 {
274 case CBN_DROPDOWN:
275 // remember the last selection, just as wxChoice does
276 m_lastAcceptedSelection = GetCurrentSelection();
277 if ( m_lastAcceptedSelection == -1 )
278 {
279 // but unlike with wxChoice we may have no selection but still
280 // have some text and we should avoid erasing it if the drop
281 // down is cancelled (see #8474)
282 m_lastAcceptedSelection = wxID_NONE;
283 }
284 {
285 wxCommandEvent event(wxEVT_COMMAND_COMBOBOX_DROPDOWN, GetId());
286 event.SetEventObject(this);
287 ProcessCommand(event);
288 }
289 break;
290 case CBN_CLOSEUP:
291 {
292 wxCommandEvent event(wxEVT_COMMAND_COMBOBOX_CLOSEUP, GetId());
293 event.SetEventObject(this);
294 ProcessCommand(event);
295 }
296 break;
297 case CBN_SELENDOK:
298 #ifndef __SMARTPHONE__
299 // we need to reset this to prevent the selection from being undone
300 // by wxChoice, see wxChoice::MSWCommand() and comments there
301 m_lastAcceptedSelection = wxID_NONE;
302 #endif
303
304 // set these variables so that they could be also fixed in
305 // CBN_EDITCHANGE below
306 sel = GetSelection();
307 value = GetStringSelection();
308
309 // this string is going to become the new combobox value soon but
310 // we need it to be done right now, otherwise the event handler
311 // could get a wrong value when it calls our GetValue()
312 ::SetWindowText(GetHwnd(), value.t_str());
313
314 {
315 wxCommandEvent event(wxEVT_COMMAND_COMBOBOX_SELECTED, GetId());
316 event.SetInt(sel);
317 event.SetString(value);
318 InitCommandEventWithItems(event, sel);
319
320 ProcessCommand(event);
321 }
322
323 // fall through: for compability with wxGTK, also send the text
324 // update event when the selection changes (this also seems more
325 // logical as the text does change)
326
327 case CBN_EDITCHANGE:
328 if ( m_allowTextEvents )
329 {
330 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, GetId());
331
332 // if sel != -1, value was already initialized above
333 if ( sel == -1 )
334 {
335 value = wxGetWindowText(GetHwnd());
336 }
337
338 event.SetString(value);
339 InitCommandEventWithItems(event, sel);
340
341 ProcessCommand(event);
342 }
343 break;
344
345 default:
346 return wxChoice::MSWCommand(param, id);
347 }
348
349 // skip wxChoice version as it would generate its own events for
350 // CBN_SELENDOK and also interfere with our handling of CBN_DROPDOWN
351 return true;
352 }
353
354 bool wxComboBox::MSWShouldPreProcessMessage(WXMSG *pMsg)
355 {
356 // prevent command accelerators from stealing editing
357 // hotkeys when we have the focus
358 if (wxIsCtrlDown())
359 {
360 WPARAM vkey = pMsg->wParam;
361
362 switch (vkey)
363 {
364 case 'C':
365 case 'V':
366 case 'X':
367 case VK_INSERT:
368 case VK_DELETE:
369 case VK_HOME:
370 case VK_END:
371 return false;
372 }
373 }
374
375 return wxChoice::MSWShouldPreProcessMessage(pMsg);
376 }
377
378 WXHWND wxComboBox::GetEditHWNDIfAvailable() const
379 {
380 WinStruct<COMBOBOXINFO> info;
381 if ( MSWGetComboBoxInfo(&info) )
382 return info.hwndItem;
383
384 if (HasFlag(wxCB_SIMPLE))
385 {
386 POINT pt;
387 pt.x = pt.y = 4;
388 return (WXHWND) ::ChildWindowFromPoint(GetHwnd(), pt);
389 }
390
391 // notice that a slightly safer alternative could be to use FindWindowEx()
392 // but it's not available under WinCE so just take the first child for now
393 // to keep one version of the code for all platforms and fix it later if
394 // problems are discovered
395
396 // we assume that the only child of the combobox is the edit window
397 return (WXHWND)::GetWindow(GetHwnd(), GW_CHILD);
398 }
399
400 WXHWND wxComboBox::GetEditHWND() const
401 {
402 // this function should not be called for wxCB_READONLY controls, it is
403 // the callers responsibility to check this
404 wxASSERT_MSG( !HasFlag(wxCB_READONLY),
405 wxT("read-only combobox doesn't have any edit control") );
406
407 WXHWND hWndEdit = GetEditHWNDIfAvailable();
408 wxASSERT_MSG( hWndEdit, wxT("combobox without edit control?") );
409
410 return hWndEdit;
411 }
412
413 wxWindow *wxComboBox::GetEditableWindow()
414 {
415 wxASSERT_MSG( !HasFlag(wxCB_READONLY),
416 wxT("read-only combobox doesn't have any edit control") );
417
418 return this;
419 }
420
421 // ----------------------------------------------------------------------------
422 // wxComboBox creation
423 // ----------------------------------------------------------------------------
424
425 bool wxComboBox::Create(wxWindow *parent, wxWindowID id,
426 const wxString& value,
427 const wxPoint& pos,
428 const wxSize& size,
429 int n, const wxString choices[],
430 long style,
431 const wxValidator& validator,
432 const wxString& name)
433 {
434 // pretend that wxComboBox is hidden while it is positioned and resized and
435 // show it only right before leaving this method because otherwise there is
436 // some noticeable flicker while the control rearranges itself
437 m_isShown = false;
438
439 if ( !CreateAndInit(parent, id, pos, size, n, choices, style,
440 validator, name) )
441 return false;
442
443 // we shouldn't call SetValue() for an empty string because this would
444 // (correctly) result in an assert with a read only combobox and is useless
445 // for the other ones anyhow
446 if ( !value.empty() )
447 SetValue(value);
448
449 // a (not read only) combobox is, in fact, 2 controls: the combobox itself
450 // and an edit control inside it and if we want to catch events from this
451 // edit control, we must subclass it as well
452 if ( !(style & wxCB_READONLY) )
453 {
454 gs_wndprocEdit = wxSetWindowProc((HWND)GetEditHWND(), wxComboEditWndProc);
455 }
456
457 // and finally, show the control
458 Show(true);
459
460 return true;
461 }
462
463 bool wxComboBox::Create(wxWindow *parent, wxWindowID id,
464 const wxString& value,
465 const wxPoint& pos,
466 const wxSize& size,
467 const wxArrayString& choices,
468 long style,
469 const wxValidator& validator,
470 const wxString& name)
471 {
472 wxCArrayString chs(choices);
473 return Create(parent, id, value, pos, size, chs.GetCount(),
474 chs.GetStrings(), style, validator, name);
475 }
476
477 WXDWORD wxComboBox::MSWGetStyle(long style, WXDWORD *exstyle) const
478 {
479 // we never have an external border
480 WXDWORD msStyle = wxChoice::MSWGetStyle
481 (
482 (style & ~wxBORDER_MASK) | wxBORDER_NONE, exstyle
483 );
484
485 // usually WS_TABSTOP is added by wxControl::MSWGetStyle() but as we're
486 // created hidden (see Create() above), it is not done for us but we still
487 // want to have this style
488 msStyle |= WS_TABSTOP;
489
490 // remove the style always added by wxChoice
491 msStyle &= ~CBS_DROPDOWNLIST;
492
493 if ( style & wxCB_READONLY )
494 msStyle |= CBS_DROPDOWNLIST;
495 #ifndef __WXWINCE__
496 else if ( style & wxCB_SIMPLE )
497 msStyle |= CBS_SIMPLE; // A list (shown always) and edit control
498 #endif
499 else
500 msStyle |= CBS_DROPDOWN;
501
502 // there is no reason to not always use CBS_AUTOHSCROLL, so do use it
503 msStyle |= CBS_AUTOHSCROLL;
504
505 // NB: we used to also add CBS_NOINTEGRALHEIGHT here but why?
506
507 return msStyle;
508 }
509
510 // ----------------------------------------------------------------------------
511 // wxComboBox text control-like methods
512 // ----------------------------------------------------------------------------
513
514 wxString wxComboBox::GetValue() const
515 {
516 return HasFlag(wxCB_READONLY) ? GetStringSelection()
517 : wxTextEntry::GetValue();
518 }
519
520 void wxComboBox::SetValue(const wxString& value)
521 {
522 if ( HasFlag(wxCB_READONLY) )
523 SetStringSelection(value);
524 else
525 wxTextEntry::SetValue(value);
526 }
527
528 void wxComboBox::Clear()
529 {
530 wxChoice::Clear();
531 if ( !HasFlag(wxCB_READONLY) )
532 wxTextEntry::Clear();
533 }
534
535 bool wxComboBox::ContainsHWND(WXHWND hWnd) const
536 {
537 return hWnd == GetEditHWNDIfAvailable();
538 }
539
540 void wxComboBox::GetSelection(long *from, long *to) const
541 {
542 if ( !HasFlag(wxCB_READONLY) )
543 {
544 wxTextEntry::GetSelection(from, to);
545 }
546 else // text selection doesn't make sense for read only comboboxes
547 {
548 if ( from )
549 *from = -1;
550 if ( to )
551 *to = -1;
552 }
553 }
554
555 bool wxComboBox::IsEditable() const
556 {
557 return !HasFlag(wxCB_READONLY) && wxTextEntry::IsEditable();
558 }
559
560 // ----------------------------------------------------------------------------
561 // standard event handling
562 // ----------------------------------------------------------------------------
563
564 void wxComboBox::OnCut(wxCommandEvent& WXUNUSED(event))
565 {
566 Cut();
567 }
568
569 void wxComboBox::OnCopy(wxCommandEvent& WXUNUSED(event))
570 {
571 Copy();
572 }
573
574 void wxComboBox::OnPaste(wxCommandEvent& WXUNUSED(event))
575 {
576 Paste();
577 }
578
579 void wxComboBox::OnUndo(wxCommandEvent& WXUNUSED(event))
580 {
581 Undo();
582 }
583
584 void wxComboBox::OnRedo(wxCommandEvent& WXUNUSED(event))
585 {
586 Redo();
587 }
588
589 void wxComboBox::OnDelete(wxCommandEvent& WXUNUSED(event))
590 {
591 RemoveSelection();
592 }
593
594 void wxComboBox::OnSelectAll(wxCommandEvent& WXUNUSED(event))
595 {
596 SelectAll();
597 }
598
599 void wxComboBox::OnUpdateCut(wxUpdateUIEvent& event)
600 {
601 event.Enable( CanCut() );
602 }
603
604 void wxComboBox::OnUpdateCopy(wxUpdateUIEvent& event)
605 {
606 event.Enable( CanCopy() );
607 }
608
609 void wxComboBox::OnUpdatePaste(wxUpdateUIEvent& event)
610 {
611 event.Enable( CanPaste() );
612 }
613
614 void wxComboBox::OnUpdateUndo(wxUpdateUIEvent& event)
615 {
616 event.Enable( IsEditable() && CanUndo() );
617 }
618
619 void wxComboBox::OnUpdateRedo(wxUpdateUIEvent& event)
620 {
621 event.Enable( IsEditable() && CanRedo() );
622 }
623
624 void wxComboBox::OnUpdateDelete(wxUpdateUIEvent& event)
625 {
626 event.Enable(IsEditable() && HasSelection());
627 }
628
629 void wxComboBox::OnUpdateSelectAll(wxUpdateUIEvent& event)
630 {
631 event.Enable(IsEditable() && !wxTextEntry::IsEmpty());
632 }
633
634 #if wxUSE_TOOLTIPS
635
636 void wxComboBox::DoSetToolTip(wxToolTip *tip)
637 {
638 wxChoice::DoSetToolTip(tip);
639
640 if ( tip && !HasFlag(wxCB_READONLY) )
641 tip->AddOtherWindow(GetEditHWND());
642 }
643
644 #endif // wxUSE_TOOLTIPS
645
646 #if wxUSE_UXTHEME
647
648 bool wxComboBox::SetHint(const wxString& hintOrig)
649 {
650 wxString hint(hintOrig);
651 if ( wxUxThemeEngine::GetIfActive() )
652 {
653 // under XP (but not Vista) there is a bug in cue banners
654 // implementation for combobox edit control: the first character is
655 // partially chopped off, so prepend a space to make it fully visible
656 hint.insert(0, " ");
657 }
658
659 return wxTextEntry::SetHint(hint);
660 }
661
662 #endif // wxUSE_UXTHEME
663
664 wxSize wxComboBox::DoGetSizeFromTextSize(int xlen, int ylen) const
665 {
666 wxSize tsize( wxChoice::DoGetSizeFromTextSize(xlen, ylen) );
667
668 if ( !HasFlag(wxCB_READONLY) )
669 {
670 // Add the margins we have previously set
671 wxPoint marg( GetMargins() );
672 marg.x = wxMax(0, marg.x);
673 marg.y = wxMax(0, marg.y);
674 tsize.IncBy( marg );
675 }
676
677 return tsize;
678 }
679
680 #endif // wxUSE_COMBOBOX